1/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
57/* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
70 * distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 * acknowledgment:
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com). */
108
109#include <openssl/ssl.h>
110
111#include <assert.h>
112#include <limits.h>
113#include <stdlib.h>
114#include <string.h>
115
116#include <algorithm>
117#include <utility>
118
119#include <openssl/aead.h>
120#include <openssl/bytestring.h>
121#include <openssl/chacha.h>
122#include <openssl/curve25519.h>
123#include <openssl/digest.h>
124#include <openssl/err.h>
125#include <openssl/evp.h>
126#include <openssl/hmac.h>
127#include <openssl/hpke.h>
128#include <openssl/mem.h>
129#include <openssl/nid.h>
130#include <openssl/rand.h>
131
132#include "../crypto/internal.h"
133#include "internal.h"
134
135
136BSSL_NAMESPACE_BEGIN
137
138static bool ssl_check_clienthello_tlsext(SSL_HANDSHAKE *hs);
139static bool ssl_check_serverhello_tlsext(SSL_HANDSHAKE *hs);
140
141static int compare_uint16_t(const void *p1, const void *p2) {
142 uint16_t u1 = *((const uint16_t *)p1);
143 uint16_t u2 = *((const uint16_t *)p2);
144 if (u1 < u2) {
145 return -1;
146 } else if (u1 > u2) {
147 return 1;
148 } else {
149 return 0;
150 }
151}
152
153// Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
154// more than one extension of the same type in a ClientHello or ServerHello.
155// This function does an initial scan over the extensions block to filter those
156// out.
157static bool tls1_check_duplicate_extensions(const CBS *cbs) {
158 // First pass: count the extensions.
159 size_t num_extensions = 0;
160 CBS extensions = *cbs;
161 while (CBS_len(cbs: &extensions) > 0) {
162 uint16_t type;
163 CBS extension;
164
165 if (!CBS_get_u16(cbs: &extensions, out: &type) ||
166 !CBS_get_u16_length_prefixed(cbs: &extensions, out: &extension)) {
167 return false;
168 }
169
170 num_extensions++;
171 }
172
173 if (num_extensions == 0) {
174 return true;
175 }
176
177 Array<uint16_t> extension_types;
178 if (!extension_types.Init(new_size: num_extensions)) {
179 return false;
180 }
181
182 // Second pass: gather the extension types.
183 extensions = *cbs;
184 for (size_t i = 0; i < extension_types.size(); i++) {
185 CBS extension;
186
187 if (!CBS_get_u16(cbs: &extensions, out: &extension_types[i]) ||
188 !CBS_get_u16_length_prefixed(cbs: &extensions, out: &extension)) {
189 // This should not happen.
190 return false;
191 }
192 }
193 assert(CBS_len(&extensions) == 0);
194
195 // Sort the extensions and make sure there are no duplicates.
196 qsort(base: extension_types.data(), nmemb: extension_types.size(), size: sizeof(uint16_t),
197 compar: compare_uint16_t);
198 for (size_t i = 1; i < num_extensions; i++) {
199 if (extension_types[i - 1] == extension_types[i]) {
200 return false;
201 }
202 }
203
204 return true;
205}
206
207static bool is_post_quantum_group(uint16_t id) {
208 switch (id) {
209 case SSL_CURVE_CECPQ2:
210 case SSL_CURVE_X25519KYBER768:
211 case SSL_CURVE_P256KYBER768:
212 return true;
213 default:
214 return false;
215 }
216}
217
218bool ssl_client_hello_init(const SSL *ssl, SSL_CLIENT_HELLO *out,
219 Span<const uint8_t> body) {
220 CBS cbs = body;
221 if (!ssl_parse_client_hello_with_trailing_data(ssl, cbs: &cbs, out) ||
222 CBS_len(cbs: &cbs) != 0) {
223 return false;
224 }
225 return true;
226}
227
228bool ssl_parse_client_hello_with_trailing_data(const SSL *ssl, CBS *cbs,
229 SSL_CLIENT_HELLO *out) {
230 OPENSSL_memset(dst: out, c: 0, n: sizeof(*out));
231 out->ssl = const_cast<SSL *>(ssl);
232
233 CBS copy = *cbs;
234 CBS random, session_id;
235 if (!CBS_get_u16(cbs, out: &out->version) ||
236 !CBS_get_bytes(cbs, out: &random, SSL3_RANDOM_SIZE) ||
237 !CBS_get_u8_length_prefixed(cbs, out: &session_id) ||
238 CBS_len(cbs: &session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
239 return false;
240 }
241
242 out->random = CBS_data(cbs: &random);
243 out->random_len = CBS_len(cbs: &random);
244 out->session_id = CBS_data(cbs: &session_id);
245 out->session_id_len = CBS_len(cbs: &session_id);
246
247 // Skip past DTLS cookie
248 if (SSL_is_dtls(ssl: out->ssl)) {
249 CBS cookie;
250 if (!CBS_get_u8_length_prefixed(cbs, out: &cookie)) {
251 return false;
252 }
253 }
254
255 CBS cipher_suites, compression_methods;
256 if (!CBS_get_u16_length_prefixed(cbs, out: &cipher_suites) ||
257 CBS_len(cbs: &cipher_suites) < 2 || (CBS_len(cbs: &cipher_suites) & 1) != 0 ||
258 !CBS_get_u8_length_prefixed(cbs, out: &compression_methods) ||
259 CBS_len(cbs: &compression_methods) < 1) {
260 return false;
261 }
262
263 out->cipher_suites = CBS_data(cbs: &cipher_suites);
264 out->cipher_suites_len = CBS_len(cbs: &cipher_suites);
265 out->compression_methods = CBS_data(cbs: &compression_methods);
266 out->compression_methods_len = CBS_len(cbs: &compression_methods);
267
268 // If the ClientHello ends here then it's valid, but doesn't have any
269 // extensions.
270 if (CBS_len(cbs) == 0) {
271 out->extensions = nullptr;
272 out->extensions_len = 0;
273 } else {
274 // Extract extensions and check it is valid.
275 CBS extensions;
276 if (!CBS_get_u16_length_prefixed(cbs, out: &extensions) ||
277 !tls1_check_duplicate_extensions(cbs: &extensions)) {
278 return false;
279 }
280 out->extensions = CBS_data(cbs: &extensions);
281 out->extensions_len = CBS_len(cbs: &extensions);
282 }
283
284 out->client_hello = CBS_data(cbs: &copy);
285 out->client_hello_len = CBS_len(cbs: &copy) - CBS_len(cbs);
286 return true;
287}
288
289bool ssl_client_hello_get_extension(const SSL_CLIENT_HELLO *client_hello,
290 CBS *out, uint16_t extension_type) {
291 CBS extensions;
292 CBS_init(cbs: &extensions, data: client_hello->extensions, len: client_hello->extensions_len);
293 while (CBS_len(cbs: &extensions) != 0) {
294 // Decode the next extension.
295 uint16_t type;
296 CBS extension;
297 if (!CBS_get_u16(cbs: &extensions, out: &type) ||
298 !CBS_get_u16_length_prefixed(cbs: &extensions, out: &extension)) {
299 return false;
300 }
301
302 if (type == extension_type) {
303 *out = extension;
304 return true;
305 }
306 }
307
308 return false;
309}
310
311static const uint16_t kDefaultGroups[] = {
312 SSL_CURVE_X25519,
313 SSL_CURVE_SECP256R1,
314 SSL_CURVE_SECP384R1,
315};
316
317Span<const uint16_t> tls1_get_grouplist(const SSL_HANDSHAKE *hs) {
318 if (!hs->config->supported_group_list.empty()) {
319 return hs->config->supported_group_list;
320 }
321 return Span<const uint16_t>(kDefaultGroups);
322}
323
324bool tls1_get_shared_group(SSL_HANDSHAKE *hs, uint16_t *out_group_id) {
325 SSL *const ssl = hs->ssl;
326 assert(ssl->server);
327
328 // Clients are not required to send a supported_groups extension. In this
329 // case, the server is free to pick any group it likes. See RFC 4492,
330 // section 4, paragraph 3.
331 //
332 // However, in the interests of compatibility, we will skip ECDH if the
333 // client didn't send an extension because we can't be sure that they'll
334 // support our favoured group. Thus we do not special-case an emtpy
335 // |peer_supported_group_list|.
336
337 Span<const uint16_t> groups = tls1_get_grouplist(hs);
338 Span<const uint16_t> pref, supp;
339 if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
340 pref = groups;
341 supp = hs->peer_supported_group_list;
342 } else {
343 pref = hs->peer_supported_group_list;
344 supp = groups;
345 }
346
347 for (uint16_t pref_group : pref) {
348 for (uint16_t supp_group : supp) {
349 if (pref_group == supp_group &&
350 // Post-quantum key agreements don't fit in the u8-length-prefixed
351 // ECPoint field in TLS 1.2 and below.
352 (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
353 !is_post_quantum_group(id: pref_group))) {
354 *out_group_id = pref_group;
355 return true;
356 }
357 }
358 }
359
360 return false;
361}
362
363bool tls1_set_curves(Array<uint16_t> *out_group_ids, Span<const int> curves) {
364 Array<uint16_t> group_ids;
365 if (!group_ids.Init(new_size: curves.size())) {
366 return false;
367 }
368
369 for (size_t i = 0; i < curves.size(); i++) {
370 if (!ssl_nid_to_group_id(out_group_id: &group_ids[i], nid: curves[i])) {
371 return false;
372 }
373 }
374
375 *out_group_ids = std::move(group_ids);
376 return true;
377}
378
379bool tls1_set_curves_list(Array<uint16_t> *out_group_ids, const char *curves) {
380 // Count the number of curves in the list.
381 size_t count = 0;
382 const char *ptr = curves, *col;
383 do {
384 col = strchr(s: ptr, c: ':');
385 count++;
386 if (col) {
387 ptr = col + 1;
388 }
389 } while (col);
390
391 Array<uint16_t> group_ids;
392 if (!group_ids.Init(new_size: count)) {
393 return false;
394 }
395
396 size_t i = 0;
397 ptr = curves;
398 do {
399 col = strchr(s: ptr, c: ':');
400 if (!ssl_name_to_group_id(out_group_id: &group_ids[i++], name: ptr,
401 len: col ? (size_t)(col - ptr) : strlen(s: ptr))) {
402 return false;
403 }
404 if (col) {
405 ptr = col + 1;
406 }
407 } while (col);
408
409 assert(i == count);
410 *out_group_ids = std::move(group_ids);
411 return true;
412}
413
414bool tls1_check_group_id(const SSL_HANDSHAKE *hs, uint16_t group_id) {
415 if (is_post_quantum_group(id: group_id) &&
416 ssl_protocol_version(ssl: hs->ssl) < TLS1_3_VERSION) {
417 // CECPQ2(b) requires TLS 1.3.
418 return false;
419 }
420
421 // We internally assume zero is never allocated as a group ID.
422 if (group_id == 0) {
423 return false;
424 }
425
426 for (uint16_t supported : tls1_get_grouplist(hs)) {
427 if (supported == group_id) {
428 return true;
429 }
430 }
431
432 return false;
433}
434
435// kVerifySignatureAlgorithms is the default list of accepted signature
436// algorithms for verifying.
437static const uint16_t kVerifySignatureAlgorithms[] = {
438 // List our preferred algorithms first.
439 SSL_SIGN_ECDSA_SECP256R1_SHA256,
440 SSL_SIGN_RSA_PSS_RSAE_SHA256,
441 SSL_SIGN_RSA_PKCS1_SHA256,
442
443 // Larger hashes are acceptable.
444 SSL_SIGN_ECDSA_SECP384R1_SHA384,
445 SSL_SIGN_RSA_PSS_RSAE_SHA384,
446 SSL_SIGN_RSA_PKCS1_SHA384,
447
448 SSL_SIGN_RSA_PSS_RSAE_SHA512,
449 SSL_SIGN_RSA_PKCS1_SHA512,
450
451 // For now, SHA-1 is still accepted but least preferable.
452 SSL_SIGN_RSA_PKCS1_SHA1,
453};
454
455// kSignSignatureAlgorithms is the default list of supported signature
456// algorithms for signing.
457static const uint16_t kSignSignatureAlgorithms[] = {
458 // List our preferred algorithms first.
459 SSL_SIGN_ED25519,
460 SSL_SIGN_ECDSA_SECP256R1_SHA256,
461 SSL_SIGN_RSA_PSS_RSAE_SHA256,
462 SSL_SIGN_RSA_PKCS1_SHA256,
463
464 // If needed, sign larger hashes.
465 //
466 // TODO(davidben): Determine which of these may be pruned.
467 SSL_SIGN_ECDSA_SECP384R1_SHA384,
468 SSL_SIGN_RSA_PSS_RSAE_SHA384,
469 SSL_SIGN_RSA_PKCS1_SHA384,
470
471 SSL_SIGN_ECDSA_SECP521R1_SHA512,
472 SSL_SIGN_RSA_PSS_RSAE_SHA512,
473 SSL_SIGN_RSA_PKCS1_SHA512,
474
475 // If the peer supports nothing else, sign with SHA-1.
476 SSL_SIGN_ECDSA_SHA1,
477 SSL_SIGN_RSA_PKCS1_SHA1,
478};
479
480static Span<const uint16_t> tls12_get_verify_sigalgs(const SSL_HANDSHAKE *hs) {
481 if (hs->config->verify_sigalgs.empty()) {
482 return Span<const uint16_t>(kVerifySignatureAlgorithms);
483 }
484 return hs->config->verify_sigalgs;
485}
486
487bool tls12_add_verify_sigalgs(const SSL_HANDSHAKE *hs, CBB *out) {
488 for (uint16_t sigalg : tls12_get_verify_sigalgs(hs)) {
489 if (!CBB_add_u16(cbb: out, value: sigalg)) {
490 return false;
491 }
492 }
493 return true;
494}
495
496bool tls12_check_peer_sigalg(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
497 uint16_t sigalg) {
498 for (uint16_t verify_sigalg : tls12_get_verify_sigalgs(hs)) {
499 if (verify_sigalg == sigalg) {
500 return true;
501 }
502 }
503
504 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SIGNATURE_TYPE);
505 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
506 return false;
507}
508
509// tls_extension represents a TLS extension that is handled internally.
510//
511// The parse callbacks receive a |CBS| that contains the contents of the
512// extension (i.e. not including the type and length bytes). If an extension is
513// not received then the parse callbacks will be called with a NULL CBS so that
514// they can do any processing needed to handle the absence of an extension.
515//
516// The add callbacks receive a |CBB| to which the extension can be appended but
517// the function is responsible for appending the type and length bytes too.
518//
519// |add_clienthello| may be called multiple times and must not mutate |hs|. It
520// is additionally passed two output |CBB|s. If the extension is the same
521// independent of the value of |type|, the callback may write to
522// |out_compressible| instead of |out|. When serializing the ClientHelloInner,
523// all compressible extensions will be made continguous and replaced with
524// ech_outer_extensions when encrypted. When serializing the ClientHelloOuter
525// or not offering ECH, |out| will be equal to |out_compressible|, so writing to
526// |out_compressible| still works.
527//
528// Note the |parse_serverhello| and |add_serverhello| callbacks refer to the
529// TLS 1.2 ServerHello. In TLS 1.3, these callbacks act on EncryptedExtensions,
530// with ServerHello extensions handled elsewhere in the handshake.
531//
532// All callbacks return true for success and false for error. If a parse
533// function returns zero then a fatal alert with value |*out_alert| will be
534// sent. If |*out_alert| isn't set, then a |decode_error| alert will be sent.
535struct tls_extension {
536 uint16_t value;
537
538 bool (*add_clienthello)(const SSL_HANDSHAKE *hs, CBB *out,
539 CBB *out_compressible, ssl_client_hello_type_t type);
540 bool (*parse_serverhello)(SSL_HANDSHAKE *hs, uint8_t *out_alert,
541 CBS *contents);
542
543 bool (*parse_clienthello)(SSL_HANDSHAKE *hs, uint8_t *out_alert,
544 CBS *contents);
545 bool (*add_serverhello)(SSL_HANDSHAKE *hs, CBB *out);
546};
547
548static bool forbid_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
549 CBS *contents) {
550 if (contents != NULL) {
551 // Servers MUST NOT send this extension.
552 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
553 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
554 return false;
555 }
556
557 return true;
558}
559
560static bool ignore_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
561 CBS *contents) {
562 // This extension from the client is handled elsewhere.
563 return true;
564}
565
566static bool dont_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
567 return true;
568}
569
570// Server name indication (SNI).
571//
572// https://tools.ietf.org/html/rfc6066#section-3.
573
574static bool ext_sni_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
575 CBB *out_compressible,
576 ssl_client_hello_type_t type) {
577 const SSL *const ssl = hs->ssl;
578 // If offering ECH, send the public name instead of the configured name.
579 Span<const uint8_t> hostname;
580 if (type == ssl_client_hello_outer) {
581 hostname = hs->selected_ech_config->public_name;
582 } else {
583 if (ssl->hostname == nullptr) {
584 return true;
585 }
586 hostname =
587 MakeConstSpan(ptr: reinterpret_cast<const uint8_t *>(ssl->hostname.get()),
588 size: strlen(s: ssl->hostname.get()));
589 }
590
591 CBB contents, server_name_list, name;
592 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_server_name) ||
593 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
594 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &server_name_list) ||
595 !CBB_add_u8(cbb: &server_name_list, TLSEXT_NAMETYPE_host_name) ||
596 !CBB_add_u16_length_prefixed(cbb: &server_name_list, out_contents: &name) ||
597 !CBB_add_bytes(cbb: &name, data: hostname.data(), len: hostname.size()) ||
598 !CBB_flush(cbb: out)) {
599 return false;
600 }
601
602 return true;
603}
604
605static bool ext_sni_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
606 CBS *contents) {
607 // The server may acknowledge SNI with an empty extension. We check the syntax
608 // but otherwise ignore this signal.
609 return contents == NULL || CBS_len(cbs: contents) == 0;
610}
611
612static bool ext_sni_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
613 CBS *contents) {
614 // SNI has already been parsed earlier in the handshake. See |extract_sni|.
615 return true;
616}
617
618static bool ext_sni_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
619 if (hs->ssl->s3->session_reused ||
620 !hs->should_ack_sni) {
621 return true;
622 }
623
624 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_server_name) ||
625 !CBB_add_u16(cbb: out, value: 0 /* length */)) {
626 return false;
627 }
628
629 return true;
630}
631
632
633// Encrypted ClientHello (ECH)
634//
635// https://tools.ietf.org/html/draft-ietf-tls-esni-13
636
637static bool ext_ech_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
638 CBB *out_compressible,
639 ssl_client_hello_type_t type) {
640 if (type == ssl_client_hello_inner) {
641 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_encrypted_client_hello) ||
642 !CBB_add_u16(cbb: out, /* length */ value: 1) ||
643 !CBB_add_u8(cbb: out, ECH_CLIENT_INNER)) {
644 return false;
645 }
646 return true;
647 }
648
649 if (hs->ech_client_outer.empty()) {
650 return true;
651 }
652
653 CBB ech_body;
654 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_encrypted_client_hello) ||
655 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &ech_body) ||
656 !CBB_add_u8(cbb: &ech_body, ECH_CLIENT_OUTER) ||
657 !CBB_add_bytes(cbb: &ech_body, data: hs->ech_client_outer.data(),
658 len: hs->ech_client_outer.size()) ||
659 !CBB_flush(cbb: out)) {
660 return false;
661 }
662 return true;
663}
664
665static bool ext_ech_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
666 CBS *contents) {
667 SSL *const ssl = hs->ssl;
668 if (contents == NULL) {
669 return true;
670 }
671
672 // The ECH extension may not be sent in TLS 1.2 ServerHello, only TLS 1.3
673 // EncryptedExtensions. It also may not be sent in response to an inner ECH
674 // extension.
675 if (ssl_protocol_version(ssl) < TLS1_3_VERSION ||
676 ssl->s3->ech_status == ssl_ech_accepted) {
677 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
678 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
679 return false;
680 }
681
682 if (!ssl_is_valid_ech_config_list(ech_config_list: *contents)) {
683 *out_alert = SSL_AD_DECODE_ERROR;
684 return false;
685 }
686
687 if (ssl->s3->ech_status == ssl_ech_rejected &&
688 !hs->ech_retry_configs.CopyFrom(in: *contents)) {
689 *out_alert = SSL_AD_INTERNAL_ERROR;
690 return false;
691 }
692
693 return true;
694}
695
696static bool ext_ech_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
697 CBS *contents) {
698 if (contents == nullptr) {
699 return true;
700 }
701
702 uint8_t type;
703 if (!CBS_get_u8(cbs: contents, out: &type)) {
704 return false;
705 }
706 if (type == ECH_CLIENT_OUTER) {
707 // Outer ECH extensions are handled outside the callback.
708 return true;
709 }
710 if (type != ECH_CLIENT_INNER || CBS_len(cbs: contents) != 0) {
711 return false;
712 }
713
714 hs->ech_is_inner = true;
715 return true;
716}
717
718static bool ext_ech_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
719 SSL *const ssl = hs->ssl;
720 if (ssl_protocol_version(ssl) < TLS1_3_VERSION ||
721 ssl->s3->ech_status == ssl_ech_accepted || //
722 hs->ech_keys == nullptr) {
723 return true;
724 }
725
726 // Write the list of retry configs to |out|. Note |SSL_CTX_set1_ech_keys|
727 // ensures |ech_keys| contains at least one retry config.
728 CBB body, retry_configs;
729 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_encrypted_client_hello) ||
730 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &body) ||
731 !CBB_add_u16_length_prefixed(cbb: &body, out_contents: &retry_configs)) {
732 return false;
733 }
734 for (const auto &config : hs->ech_keys->configs) {
735 if (!config->is_retry_config()) {
736 continue;
737 }
738 if (!CBB_add_bytes(cbb: &retry_configs, data: config->ech_config().raw.data(),
739 len: config->ech_config().raw.size())) {
740 return false;
741 }
742 }
743 return CBB_flush(cbb: out);
744}
745
746
747// Renegotiation indication.
748//
749// https://tools.ietf.org/html/rfc5746
750
751static bool ext_ri_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
752 CBB *out_compressible,
753 ssl_client_hello_type_t type) {
754 const SSL *const ssl = hs->ssl;
755 // Renegotiation indication is not necessary in TLS 1.3.
756 if (hs->min_version >= TLS1_3_VERSION ||
757 type == ssl_client_hello_inner) {
758 return true;
759 }
760
761 assert(ssl->s3->initial_handshake_complete ==
762 (ssl->s3->previous_client_finished_len != 0));
763
764 CBB contents, prev_finished;
765 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_renegotiate) ||
766 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
767 !CBB_add_u8_length_prefixed(cbb: &contents, out_contents: &prev_finished) ||
768 !CBB_add_bytes(cbb: &prev_finished, data: ssl->s3->previous_client_finished,
769 len: ssl->s3->previous_client_finished_len) ||
770 !CBB_flush(cbb: out)) {
771 return false;
772 }
773
774 return true;
775}
776
777static bool ext_ri_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
778 CBS *contents) {
779 SSL *const ssl = hs->ssl;
780 if (contents != NULL && ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
781 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
782 return false;
783 }
784
785 // Servers may not switch between omitting the extension and supporting it.
786 // See RFC 5746, sections 3.5 and 4.2.
787 if (ssl->s3->initial_handshake_complete &&
788 (contents != NULL) != ssl->s3->send_connection_binding) {
789 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
790 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
791 return false;
792 }
793
794 if (contents == NULL) {
795 // Strictly speaking, if we want to avoid an attack we should *always* see
796 // RI even on initial ServerHello because the client doesn't see any
797 // renegotiation during an attack. However this would mean we could not
798 // connect to any server which doesn't support RI.
799 //
800 // OpenSSL has |SSL_OP_LEGACY_SERVER_CONNECT| to control this, but in
801 // practical terms every client sets it so it's just assumed here.
802 return true;
803 }
804
805 const size_t expected_len = ssl->s3->previous_client_finished_len +
806 ssl->s3->previous_server_finished_len;
807
808 // Check for logic errors
809 assert(!expected_len || ssl->s3->previous_client_finished_len);
810 assert(!expected_len || ssl->s3->previous_server_finished_len);
811 assert(ssl->s3->initial_handshake_complete ==
812 (ssl->s3->previous_client_finished_len != 0));
813 assert(ssl->s3->initial_handshake_complete ==
814 (ssl->s3->previous_server_finished_len != 0));
815
816 // Parse out the extension contents.
817 CBS renegotiated_connection;
818 if (!CBS_get_u8_length_prefixed(cbs: contents, out: &renegotiated_connection) ||
819 CBS_len(cbs: contents) != 0) {
820 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
821 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
822 return false;
823 }
824
825 // Check that the extension matches.
826 if (CBS_len(cbs: &renegotiated_connection) != expected_len) {
827 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
828 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
829 return false;
830 }
831
832 const uint8_t *d = CBS_data(cbs: &renegotiated_connection);
833 bool ok = CRYPTO_memcmp(a: d, b: ssl->s3->previous_client_finished,
834 len: ssl->s3->previous_client_finished_len) == 0;
835#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
836 ok = true;
837#endif
838 if (!ok) {
839 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
840 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
841 return false;
842 }
843 d += ssl->s3->previous_client_finished_len;
844
845 ok = CRYPTO_memcmp(a: d, b: ssl->s3->previous_server_finished,
846 len: ssl->s3->previous_server_finished_len) == 0;
847#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
848 ok = true;
849#endif
850 if (!ok) {
851 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
852 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
853 return false;
854 }
855 ssl->s3->send_connection_binding = true;
856
857 return true;
858}
859
860static bool ext_ri_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
861 CBS *contents) {
862 SSL *const ssl = hs->ssl;
863 // Renegotiation isn't supported as a server so this function should never be
864 // called after the initial handshake.
865 assert(!ssl->s3->initial_handshake_complete);
866
867 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
868 return true;
869 }
870
871 if (contents == NULL) {
872 return true;
873 }
874
875 CBS renegotiated_connection;
876 if (!CBS_get_u8_length_prefixed(cbs: contents, out: &renegotiated_connection) ||
877 CBS_len(cbs: contents) != 0) {
878 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
879 return false;
880 }
881
882 // Check that the extension matches. We do not support renegotiation as a
883 // server, so this must be empty.
884 if (CBS_len(cbs: &renegotiated_connection) != 0) {
885 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
886 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
887 return false;
888 }
889
890 ssl->s3->send_connection_binding = true;
891
892 return true;
893}
894
895static bool ext_ri_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
896 SSL *const ssl = hs->ssl;
897 // Renegotiation isn't supported as a server so this function should never be
898 // called after the initial handshake.
899 assert(!ssl->s3->initial_handshake_complete);
900
901 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
902 return true;
903 }
904
905 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_renegotiate) ||
906 !CBB_add_u16(cbb: out, value: 1 /* length */) ||
907 !CBB_add_u8(cbb: out, value: 0 /* empty renegotiation info */)) {
908 return false;
909 }
910
911 return true;
912}
913
914
915// Extended Master Secret.
916//
917// https://tools.ietf.org/html/rfc7627
918
919static bool ext_ems_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
920 CBB *out_compressible,
921 ssl_client_hello_type_t type) {
922 // Extended master secret is not necessary in TLS 1.3.
923 if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner) {
924 return true;
925 }
926
927 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_extended_master_secret) ||
928 !CBB_add_u16(cbb: out, value: 0 /* length */)) {
929 return false;
930 }
931
932 return true;
933}
934
935static bool ext_ems_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
936 CBS *contents) {
937 SSL *const ssl = hs->ssl;
938
939 if (contents != NULL) {
940 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
941 CBS_len(cbs: contents) != 0) {
942 return false;
943 }
944
945 hs->extended_master_secret = true;
946 }
947
948 // Whether EMS is negotiated may not change on renegotiation.
949 if (ssl->s3->established_session != nullptr &&
950 hs->extended_master_secret !=
951 !!ssl->s3->established_session->extended_master_secret) {
952 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_EMS_MISMATCH);
953 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
954 return false;
955 }
956
957 return true;
958}
959
960static bool ext_ems_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
961 CBS *contents) {
962 if (ssl_protocol_version(ssl: hs->ssl) >= TLS1_3_VERSION) {
963 return true;
964 }
965
966 if (contents == NULL) {
967 return true;
968 }
969
970 if (CBS_len(cbs: contents) != 0) {
971 return false;
972 }
973
974 hs->extended_master_secret = true;
975 return true;
976}
977
978static bool ext_ems_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
979 if (!hs->extended_master_secret) {
980 return true;
981 }
982
983 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_extended_master_secret) ||
984 !CBB_add_u16(cbb: out, value: 0 /* length */)) {
985 return false;
986 }
987
988 return true;
989}
990
991
992// Session tickets.
993//
994// https://tools.ietf.org/html/rfc5077
995
996static bool ext_ticket_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
997 CBB *out_compressible,
998 ssl_client_hello_type_t type) {
999 const SSL *const ssl = hs->ssl;
1000 // TLS 1.3 uses a different ticket extension.
1001 if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner ||
1002 SSL_get_options(ssl) & SSL_OP_NO_TICKET) {
1003 return true;
1004 }
1005
1006 Span<const uint8_t> ticket;
1007
1008 // Renegotiation does not participate in session resumption. However, still
1009 // advertise the extension to avoid potentially breaking servers which carry
1010 // over the state from the previous handshake, such as OpenSSL servers
1011 // without upstream's 3c3f0259238594d77264a78944d409f2127642c4.
1012 if (!ssl->s3->initial_handshake_complete &&
1013 ssl->session != nullptr &&
1014 !ssl->session->ticket.empty() &&
1015 // Don't send TLS 1.3 session tickets in the ticket extension.
1016 ssl_session_protocol_version(session: ssl->session.get()) < TLS1_3_VERSION) {
1017 ticket = ssl->session->ticket;
1018 }
1019
1020 CBB ticket_cbb;
1021 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_session_ticket) ||
1022 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &ticket_cbb) ||
1023 !CBB_add_bytes(cbb: &ticket_cbb, data: ticket.data(), len: ticket.size()) ||
1024 !CBB_flush(cbb: out)) {
1025 return false;
1026 }
1027
1028 return true;
1029}
1030
1031static bool ext_ticket_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1032 CBS *contents) {
1033 SSL *const ssl = hs->ssl;
1034 if (contents == NULL) {
1035 return true;
1036 }
1037
1038 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1039 return false;
1040 }
1041
1042 // If |SSL_OP_NO_TICKET| is set then no extension will have been sent and
1043 // this function should never be called, even if the server tries to send the
1044 // extension.
1045 assert((SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0);
1046
1047 if (CBS_len(cbs: contents) != 0) {
1048 return false;
1049 }
1050
1051 hs->ticket_expected = true;
1052 return true;
1053}
1054
1055static bool ext_ticket_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1056 if (!hs->ticket_expected) {
1057 return true;
1058 }
1059
1060 // If |SSL_OP_NO_TICKET| is set, |ticket_expected| should never be true.
1061 assert((SSL_get_options(hs->ssl) & SSL_OP_NO_TICKET) == 0);
1062
1063 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_session_ticket) ||
1064 !CBB_add_u16(cbb: out, value: 0 /* length */)) {
1065 return false;
1066 }
1067
1068 return true;
1069}
1070
1071
1072// Signature Algorithms.
1073//
1074// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
1075
1076static bool ext_sigalgs_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1077 CBB *out_compressible,
1078 ssl_client_hello_type_t type) {
1079 if (hs->max_version < TLS1_2_VERSION) {
1080 return true;
1081 }
1082
1083 CBB contents, sigalgs_cbb;
1084 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_signature_algorithms) ||
1085 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
1086 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &sigalgs_cbb) ||
1087 !tls12_add_verify_sigalgs(hs, out: &sigalgs_cbb) ||
1088 !CBB_flush(cbb: out_compressible)) {
1089 return false;
1090 }
1091
1092 return true;
1093}
1094
1095static bool ext_sigalgs_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1096 CBS *contents) {
1097 hs->peer_sigalgs.Reset();
1098 if (contents == NULL) {
1099 return true;
1100 }
1101
1102 CBS supported_signature_algorithms;
1103 if (!CBS_get_u16_length_prefixed(cbs: contents, out: &supported_signature_algorithms) ||
1104 CBS_len(cbs: contents) != 0 ||
1105 !tls1_parse_peer_sigalgs(hs, sigalgs: &supported_signature_algorithms)) {
1106 return false;
1107 }
1108
1109 return true;
1110}
1111
1112
1113// OCSP Stapling.
1114//
1115// https://tools.ietf.org/html/rfc6066#section-8
1116
1117static bool ext_ocsp_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1118 CBB *out_compressible,
1119 ssl_client_hello_type_t type) {
1120 if (!hs->config->ocsp_stapling_enabled) {
1121 return true;
1122 }
1123
1124 CBB contents;
1125 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_status_request) ||
1126 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
1127 !CBB_add_u8(cbb: &contents, TLSEXT_STATUSTYPE_ocsp) ||
1128 !CBB_add_u16(cbb: &contents, value: 0 /* empty responder ID list */) ||
1129 !CBB_add_u16(cbb: &contents, value: 0 /* empty request extensions */) ||
1130 !CBB_flush(cbb: out_compressible)) {
1131 return false;
1132 }
1133
1134 return true;
1135}
1136
1137static bool ext_ocsp_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1138 CBS *contents) {
1139 SSL *const ssl = hs->ssl;
1140 if (contents == NULL) {
1141 return true;
1142 }
1143
1144 // TLS 1.3 OCSP responses are included in the Certificate extensions.
1145 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1146 return false;
1147 }
1148
1149 // OCSP stapling is forbidden on non-certificate ciphers.
1150 if (CBS_len(cbs: contents) != 0 ||
1151 !ssl_cipher_uses_certificate_auth(cipher: hs->new_cipher)) {
1152 return false;
1153 }
1154
1155 // Note this does not check for resumption in TLS 1.2. Sending
1156 // status_request here does not make sense, but OpenSSL does so and the
1157 // specification does not say anything. Tolerate it but ignore it.
1158
1159 hs->certificate_status_expected = true;
1160 return true;
1161}
1162
1163static bool ext_ocsp_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1164 CBS *contents) {
1165 if (contents == NULL) {
1166 return true;
1167 }
1168
1169 uint8_t status_type;
1170 if (!CBS_get_u8(cbs: contents, out: &status_type)) {
1171 return false;
1172 }
1173
1174 // We cannot decide whether OCSP stapling will occur yet because the correct
1175 // SSL_CTX might not have been selected.
1176 hs->ocsp_stapling_requested = status_type == TLSEXT_STATUSTYPE_ocsp;
1177
1178 return true;
1179}
1180
1181static bool ext_ocsp_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1182 SSL *const ssl = hs->ssl;
1183 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
1184 !hs->ocsp_stapling_requested || hs->config->cert->ocsp_response == NULL ||
1185 ssl->s3->session_reused ||
1186 !ssl_cipher_uses_certificate_auth(cipher: hs->new_cipher)) {
1187 return true;
1188 }
1189
1190 hs->certificate_status_expected = true;
1191
1192 return CBB_add_u16(cbb: out, TLSEXT_TYPE_status_request) &&
1193 CBB_add_u16(cbb: out, value: 0 /* length */);
1194}
1195
1196
1197// Next protocol negotiation.
1198//
1199// https://htmlpreview.github.io/?https://github.com/agl/technotes/blob/master/nextprotoneg.html
1200
1201static bool ext_npn_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1202 CBB *out_compressible,
1203 ssl_client_hello_type_t type) {
1204 const SSL *const ssl = hs->ssl;
1205 if (ssl->ctx->next_proto_select_cb == NULL ||
1206 // Do not allow NPN to change on renegotiation.
1207 ssl->s3->initial_handshake_complete ||
1208 // NPN is not defined in DTLS or TLS 1.3.
1209 SSL_is_dtls(ssl) || hs->min_version >= TLS1_3_VERSION ||
1210 type == ssl_client_hello_inner) {
1211 return true;
1212 }
1213
1214 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_next_proto_neg) ||
1215 !CBB_add_u16(cbb: out, value: 0 /* length */)) {
1216 return false;
1217 }
1218
1219 return true;
1220}
1221
1222static bool ext_npn_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1223 CBS *contents) {
1224 SSL *const ssl = hs->ssl;
1225 if (contents == NULL) {
1226 return true;
1227 }
1228
1229 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1230 return false;
1231 }
1232
1233 // If any of these are false then we should never have sent the NPN
1234 // extension in the ClientHello and thus this function should never have been
1235 // called.
1236 assert(!ssl->s3->initial_handshake_complete);
1237 assert(!SSL_is_dtls(ssl));
1238 assert(ssl->ctx->next_proto_select_cb != NULL);
1239
1240 if (!ssl->s3->alpn_selected.empty()) {
1241 // NPN and ALPN may not be negotiated in the same connection.
1242 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1243 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
1244 return false;
1245 }
1246
1247 const uint8_t *const orig_contents = CBS_data(cbs: contents);
1248 const size_t orig_len = CBS_len(cbs: contents);
1249
1250 while (CBS_len(cbs: contents) != 0) {
1251 CBS proto;
1252 if (!CBS_get_u8_length_prefixed(cbs: contents, out: &proto) ||
1253 CBS_len(cbs: &proto) == 0) {
1254 return false;
1255 }
1256 }
1257
1258 // |orig_len| fits in |unsigned| because TLS extensions use 16-bit lengths.
1259 uint8_t *selected;
1260 uint8_t selected_len;
1261 if (ssl->ctx->next_proto_select_cb(
1262 ssl, &selected, &selected_len, orig_contents,
1263 static_cast<unsigned>(orig_len),
1264 ssl->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK ||
1265 !ssl->s3->next_proto_negotiated.CopyFrom(
1266 in: MakeConstSpan(ptr: selected, size: selected_len))) {
1267 *out_alert = SSL_AD_INTERNAL_ERROR;
1268 return false;
1269 }
1270
1271 hs->next_proto_neg_seen = true;
1272 return true;
1273}
1274
1275static bool ext_npn_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1276 CBS *contents) {
1277 SSL *const ssl = hs->ssl;
1278 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1279 return true;
1280 }
1281
1282 if (contents != NULL && CBS_len(cbs: contents) != 0) {
1283 return false;
1284 }
1285
1286 if (contents == NULL ||
1287 ssl->s3->initial_handshake_complete ||
1288 ssl->ctx->next_protos_advertised_cb == NULL ||
1289 SSL_is_dtls(ssl)) {
1290 return true;
1291 }
1292
1293 hs->next_proto_neg_seen = true;
1294 return true;
1295}
1296
1297static bool ext_npn_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1298 SSL *const ssl = hs->ssl;
1299 // |next_proto_neg_seen| might have been cleared when an ALPN extension was
1300 // parsed.
1301 if (!hs->next_proto_neg_seen) {
1302 return true;
1303 }
1304
1305 const uint8_t *npa;
1306 unsigned npa_len;
1307
1308 if (ssl->ctx->next_protos_advertised_cb(
1309 ssl, &npa, &npa_len, ssl->ctx->next_protos_advertised_cb_arg) !=
1310 SSL_TLSEXT_ERR_OK) {
1311 hs->next_proto_neg_seen = false;
1312 return true;
1313 }
1314
1315 CBB contents;
1316 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_next_proto_neg) ||
1317 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
1318 !CBB_add_bytes(cbb: &contents, data: npa, len: npa_len) ||
1319 !CBB_flush(cbb: out)) {
1320 return false;
1321 }
1322
1323 return true;
1324}
1325
1326
1327// Signed certificate timestamps.
1328//
1329// https://tools.ietf.org/html/rfc6962#section-3.3.1
1330
1331static bool ext_sct_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1332 CBB *out_compressible,
1333 ssl_client_hello_type_t type) {
1334 if (!hs->config->signed_cert_timestamps_enabled) {
1335 return true;
1336 }
1337
1338 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_certificate_timestamp) ||
1339 !CBB_add_u16(cbb: out_compressible, value: 0 /* length */)) {
1340 return false;
1341 }
1342
1343 return true;
1344}
1345
1346static bool ext_sct_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1347 CBS *contents) {
1348 SSL *const ssl = hs->ssl;
1349 if (contents == NULL) {
1350 return true;
1351 }
1352
1353 // TLS 1.3 SCTs are included in the Certificate extensions.
1354 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1355 *out_alert = SSL_AD_DECODE_ERROR;
1356 return false;
1357 }
1358
1359 // If this is false then we should never have sent the SCT extension in the
1360 // ClientHello and thus this function should never have been called.
1361 assert(hs->config->signed_cert_timestamps_enabled);
1362
1363 if (!ssl_is_sct_list_valid(contents)) {
1364 *out_alert = SSL_AD_DECODE_ERROR;
1365 return false;
1366 }
1367
1368 // Session resumption uses the original session information. The extension
1369 // should not be sent on resumption, but RFC 6962 did not make it a
1370 // requirement, so tolerate this.
1371 //
1372 // TODO(davidben): Enforce this anyway.
1373 if (!ssl->s3->session_reused) {
1374 hs->new_session->signed_cert_timestamp_list.reset(
1375 p: CRYPTO_BUFFER_new_from_CBS(cbs: contents, pool: ssl->ctx->pool));
1376 if (hs->new_session->signed_cert_timestamp_list == nullptr) {
1377 *out_alert = SSL_AD_INTERNAL_ERROR;
1378 return false;
1379 }
1380 }
1381
1382 return true;
1383}
1384
1385static bool ext_sct_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1386 CBS *contents) {
1387 if (contents == NULL) {
1388 return true;
1389 }
1390
1391 if (CBS_len(cbs: contents) != 0) {
1392 return false;
1393 }
1394
1395 hs->scts_requested = true;
1396 return true;
1397}
1398
1399static bool ext_sct_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1400 SSL *const ssl = hs->ssl;
1401 // The extension shouldn't be sent when resuming sessions.
1402 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION || ssl->s3->session_reused ||
1403 hs->config->cert->signed_cert_timestamp_list == NULL) {
1404 return true;
1405 }
1406
1407 CBB contents;
1408 return CBB_add_u16(cbb: out, TLSEXT_TYPE_certificate_timestamp) &&
1409 CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) &&
1410 CBB_add_bytes(
1411 cbb: &contents,
1412 data: CRYPTO_BUFFER_data(
1413 buf: hs->config->cert->signed_cert_timestamp_list.get()),
1414 len: CRYPTO_BUFFER_len(
1415 buf: hs->config->cert->signed_cert_timestamp_list.get())) &&
1416 CBB_flush(cbb: out);
1417}
1418
1419
1420// Application-level Protocol Negotiation.
1421//
1422// https://tools.ietf.org/html/rfc7301
1423
1424static bool ext_alpn_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1425 CBB *out_compressible,
1426 ssl_client_hello_type_t type) {
1427 const SSL *const ssl = hs->ssl;
1428 if (hs->config->alpn_client_proto_list.empty() && ssl->quic_method) {
1429 // ALPN MUST be used with QUIC.
1430 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1431 return false;
1432 }
1433
1434 if (hs->config->alpn_client_proto_list.empty() ||
1435 ssl->s3->initial_handshake_complete) {
1436 return true;
1437 }
1438
1439 CBB contents, proto_list;
1440 if (!CBB_add_u16(cbb: out_compressible,
1441 TLSEXT_TYPE_application_layer_protocol_negotiation) ||
1442 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
1443 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &proto_list) ||
1444 !CBB_add_bytes(cbb: &proto_list, data: hs->config->alpn_client_proto_list.data(),
1445 len: hs->config->alpn_client_proto_list.size()) ||
1446 !CBB_flush(cbb: out_compressible)) {
1447 return false;
1448 }
1449
1450 return true;
1451}
1452
1453static bool ext_alpn_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1454 CBS *contents) {
1455 SSL *const ssl = hs->ssl;
1456 if (contents == NULL) {
1457 if (ssl->quic_method) {
1458 // ALPN is required when QUIC is used.
1459 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1460 *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1461 return false;
1462 }
1463 return true;
1464 }
1465
1466 assert(!ssl->s3->initial_handshake_complete);
1467 assert(!hs->config->alpn_client_proto_list.empty());
1468
1469 if (hs->next_proto_neg_seen) {
1470 // NPN and ALPN may not be negotiated in the same connection.
1471 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1472 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
1473 return false;
1474 }
1475
1476 // The extension data consists of a ProtocolNameList which must have
1477 // exactly one ProtocolName. Each of these is length-prefixed.
1478 CBS protocol_name_list, protocol_name;
1479 if (!CBS_get_u16_length_prefixed(cbs: contents, out: &protocol_name_list) ||
1480 CBS_len(cbs: contents) != 0 ||
1481 !CBS_get_u8_length_prefixed(cbs: &protocol_name_list, out: &protocol_name) ||
1482 // Empty protocol names are forbidden.
1483 CBS_len(cbs: &protocol_name) == 0 ||
1484 CBS_len(cbs: &protocol_name_list) != 0) {
1485 return false;
1486 }
1487
1488 if (!ssl_is_alpn_protocol_allowed(hs, protocol: protocol_name)) {
1489 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
1490 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1491 return false;
1492 }
1493
1494 if (!ssl->s3->alpn_selected.CopyFrom(in: protocol_name)) {
1495 *out_alert = SSL_AD_INTERNAL_ERROR;
1496 return false;
1497 }
1498
1499 return true;
1500}
1501
1502bool ssl_is_valid_alpn_list(Span<const uint8_t> in) {
1503 CBS protocol_name_list = in;
1504 if (CBS_len(cbs: &protocol_name_list) == 0) {
1505 return false;
1506 }
1507 while (CBS_len(cbs: &protocol_name_list) > 0) {
1508 CBS protocol_name;
1509 if (!CBS_get_u8_length_prefixed(cbs: &protocol_name_list, out: &protocol_name) ||
1510 // Empty protocol names are forbidden.
1511 CBS_len(cbs: &protocol_name) == 0) {
1512 return false;
1513 }
1514 }
1515 return true;
1516}
1517
1518bool ssl_is_alpn_protocol_allowed(const SSL_HANDSHAKE *hs,
1519 Span<const uint8_t> protocol) {
1520 if (hs->config->alpn_client_proto_list.empty()) {
1521 return false;
1522 }
1523
1524 if (hs->ssl->ctx->allow_unknown_alpn_protos) {
1525 return true;
1526 }
1527
1528 // Check that the protocol name is one of the ones we advertised.
1529 CBS client_protocol_name_list =
1530 MakeConstSpan(c: hs->config->alpn_client_proto_list),
1531 client_protocol_name;
1532 while (CBS_len(cbs: &client_protocol_name_list) > 0) {
1533 if (!CBS_get_u8_length_prefixed(cbs: &client_protocol_name_list,
1534 out: &client_protocol_name)) {
1535 return false;
1536 }
1537
1538 if (client_protocol_name == protocol) {
1539 return true;
1540 }
1541 }
1542
1543 return false;
1544}
1545
1546bool ssl_negotiate_alpn(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1547 const SSL_CLIENT_HELLO *client_hello) {
1548 SSL *const ssl = hs->ssl;
1549 CBS contents;
1550 if (ssl->ctx->alpn_select_cb == NULL ||
1551 !ssl_client_hello_get_extension(
1552 client_hello, out: &contents,
1553 TLSEXT_TYPE_application_layer_protocol_negotiation)) {
1554 if (ssl->quic_method) {
1555 // ALPN is required when QUIC is used.
1556 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1557 *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1558 return false;
1559 }
1560 // Ignore ALPN if not configured or no extension was supplied.
1561 return true;
1562 }
1563
1564 // ALPN takes precedence over NPN.
1565 hs->next_proto_neg_seen = false;
1566
1567 CBS protocol_name_list;
1568 if (!CBS_get_u16_length_prefixed(cbs: &contents, out: &protocol_name_list) ||
1569 CBS_len(cbs: &contents) != 0 ||
1570 !ssl_is_valid_alpn_list(in: protocol_name_list)) {
1571 OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
1572 *out_alert = SSL_AD_DECODE_ERROR;
1573 return false;
1574 }
1575
1576 // |protocol_name_list| fits in |unsigned| because TLS extensions use 16-bit
1577 // lengths.
1578 const uint8_t *selected;
1579 uint8_t selected_len;
1580 int ret = ssl->ctx->alpn_select_cb(
1581 ssl, &selected, &selected_len, CBS_data(cbs: &protocol_name_list),
1582 static_cast<unsigned>(CBS_len(cbs: &protocol_name_list)),
1583 ssl->ctx->alpn_select_cb_arg);
1584 // ALPN is required when QUIC is used.
1585 if (ssl->quic_method &&
1586 (ret == SSL_TLSEXT_ERR_NOACK || ret == SSL_TLSEXT_ERR_ALERT_WARNING)) {
1587 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1588 }
1589 switch (ret) {
1590 case SSL_TLSEXT_ERR_OK:
1591 if (selected_len == 0) {
1592 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
1593 *out_alert = SSL_AD_INTERNAL_ERROR;
1594 return false;
1595 }
1596 if (!ssl->s3->alpn_selected.CopyFrom(
1597 in: MakeConstSpan(ptr: selected, size: selected_len))) {
1598 *out_alert = SSL_AD_INTERNAL_ERROR;
1599 return false;
1600 }
1601 break;
1602 case SSL_TLSEXT_ERR_NOACK:
1603 case SSL_TLSEXT_ERR_ALERT_WARNING:
1604 break;
1605 case SSL_TLSEXT_ERR_ALERT_FATAL:
1606 *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1607 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1608 return false;
1609 default:
1610 // Invalid return value.
1611 *out_alert = SSL_AD_INTERNAL_ERROR;
1612 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1613 return false;
1614 }
1615
1616 return true;
1617}
1618
1619static bool ext_alpn_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1620 SSL *const ssl = hs->ssl;
1621 if (ssl->s3->alpn_selected.empty()) {
1622 return true;
1623 }
1624
1625 CBB contents, proto_list, proto;
1626 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
1627 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
1628 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &proto_list) ||
1629 !CBB_add_u8_length_prefixed(cbb: &proto_list, out_contents: &proto) ||
1630 !CBB_add_bytes(cbb: &proto, data: ssl->s3->alpn_selected.data(),
1631 len: ssl->s3->alpn_selected.size()) ||
1632 !CBB_flush(cbb: out)) {
1633 return false;
1634 }
1635
1636 return true;
1637}
1638
1639
1640// Channel ID.
1641//
1642// https://tools.ietf.org/html/draft-balfanz-tls-channelid-01
1643
1644static bool ext_channel_id_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1645 CBB *out_compressible,
1646 ssl_client_hello_type_t type) {
1647 const SSL *const ssl = hs->ssl;
1648 if (!hs->config->channel_id_private || SSL_is_dtls(ssl) ||
1649 // Don't offer Channel ID in ClientHelloOuter. ClientHelloOuter handshakes
1650 // are not authenticated for the name that can learn the Channel ID.
1651 //
1652 // We could alternatively offer the extension but sign with a random key.
1653 // For other extensions, we try to align |ssl_client_hello_outer| and
1654 // |ssl_client_hello_unencrypted|, to improve the effectiveness of ECH
1655 // GREASE. However, Channel ID is deprecated and unlikely to be used with
1656 // ECH, so do the simplest thing.
1657 type == ssl_client_hello_outer) {
1658 return true;
1659 }
1660
1661 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_channel_id) ||
1662 !CBB_add_u16(cbb: out, value: 0 /* length */)) {
1663 return false;
1664 }
1665
1666 return true;
1667}
1668
1669static bool ext_channel_id_parse_serverhello(SSL_HANDSHAKE *hs,
1670 uint8_t *out_alert,
1671 CBS *contents) {
1672 if (contents == NULL) {
1673 return true;
1674 }
1675
1676 assert(!SSL_is_dtls(hs->ssl));
1677 assert(hs->config->channel_id_private);
1678
1679 if (CBS_len(cbs: contents) != 0) {
1680 return false;
1681 }
1682
1683 hs->channel_id_negotiated = true;
1684 return true;
1685}
1686
1687static bool ext_channel_id_parse_clienthello(SSL_HANDSHAKE *hs,
1688 uint8_t *out_alert,
1689 CBS *contents) {
1690 SSL *const ssl = hs->ssl;
1691 if (contents == NULL || !hs->config->channel_id_enabled || SSL_is_dtls(ssl)) {
1692 return true;
1693 }
1694
1695 if (CBS_len(cbs: contents) != 0) {
1696 return false;
1697 }
1698
1699 hs->channel_id_negotiated = true;
1700 return true;
1701}
1702
1703static bool ext_channel_id_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1704 if (!hs->channel_id_negotiated) {
1705 return true;
1706 }
1707
1708 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_channel_id) ||
1709 !CBB_add_u16(cbb: out, value: 0 /* length */)) {
1710 return false;
1711 }
1712
1713 return true;
1714}
1715
1716
1717// Secure Real-time Transport Protocol (SRTP) extension.
1718//
1719// https://tools.ietf.org/html/rfc5764
1720
1721static bool ext_srtp_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1722 CBB *out_compressible,
1723 ssl_client_hello_type_t type) {
1724 const SSL *const ssl = hs->ssl;
1725 const STACK_OF(SRTP_PROTECTION_PROFILE) *profiles =
1726 SSL_get_srtp_profiles(ssl);
1727 if (profiles == NULL ||
1728 sk_SRTP_PROTECTION_PROFILE_num(sk: profiles) == 0 ||
1729 !SSL_is_dtls(ssl)) {
1730 return true;
1731 }
1732
1733 CBB contents, profile_ids;
1734 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_srtp) ||
1735 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
1736 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &profile_ids)) {
1737 return false;
1738 }
1739
1740 for (const SRTP_PROTECTION_PROFILE *profile : profiles) {
1741 if (!CBB_add_u16(cbb: &profile_ids, value: profile->id)) {
1742 return false;
1743 }
1744 }
1745
1746 if (!CBB_add_u8(cbb: &contents, value: 0 /* empty use_mki value */) ||
1747 !CBB_flush(cbb: out_compressible)) {
1748 return false;
1749 }
1750
1751 return true;
1752}
1753
1754static bool ext_srtp_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1755 CBS *contents) {
1756 SSL *const ssl = hs->ssl;
1757 if (contents == NULL) {
1758 return true;
1759 }
1760
1761 // The extension consists of a u16-prefixed profile ID list containing a
1762 // single uint16_t profile ID, then followed by a u8-prefixed srtp_mki field.
1763 //
1764 // See https://tools.ietf.org/html/rfc5764#section-4.1.1
1765 assert(SSL_is_dtls(ssl));
1766 CBS profile_ids, srtp_mki;
1767 uint16_t profile_id;
1768 if (!CBS_get_u16_length_prefixed(cbs: contents, out: &profile_ids) ||
1769 !CBS_get_u16(cbs: &profile_ids, out: &profile_id) ||
1770 CBS_len(cbs: &profile_ids) != 0 ||
1771 !CBS_get_u8_length_prefixed(cbs: contents, out: &srtp_mki) ||
1772 CBS_len(cbs: contents) != 0) {
1773 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1774 return false;
1775 }
1776
1777 if (CBS_len(cbs: &srtp_mki) != 0) {
1778 // Must be no MKI, since we never offer one.
1779 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_MKI_VALUE);
1780 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1781 return false;
1782 }
1783
1784 // Check to see if the server gave us something we support and offered.
1785 for (const SRTP_PROTECTION_PROFILE *profile : SSL_get_srtp_profiles(ssl)) {
1786 if (profile->id == profile_id) {
1787 ssl->s3->srtp_profile = profile;
1788 return true;
1789 }
1790 }
1791
1792 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1793 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1794 return false;
1795}
1796
1797static bool ext_srtp_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1798 CBS *contents) {
1799 SSL *const ssl = hs->ssl;
1800 // DTLS-SRTP is only defined for DTLS.
1801 if (contents == NULL || !SSL_is_dtls(ssl)) {
1802 return true;
1803 }
1804
1805 CBS profile_ids, srtp_mki;
1806 if (!CBS_get_u16_length_prefixed(cbs: contents, out: &profile_ids) ||
1807 CBS_len(cbs: &profile_ids) < 2 ||
1808 !CBS_get_u8_length_prefixed(cbs: contents, out: &srtp_mki) ||
1809 CBS_len(cbs: contents) != 0) {
1810 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1811 return false;
1812 }
1813 // Discard the MKI value for now.
1814
1815 const STACK_OF(SRTP_PROTECTION_PROFILE) *server_profiles =
1816 SSL_get_srtp_profiles(ssl);
1817
1818 // Pick the server's most preferred profile.
1819 for (const SRTP_PROTECTION_PROFILE *server_profile : server_profiles) {
1820 CBS profile_ids_tmp;
1821 CBS_init(cbs: &profile_ids_tmp, data: CBS_data(cbs: &profile_ids), len: CBS_len(cbs: &profile_ids));
1822
1823 while (CBS_len(cbs: &profile_ids_tmp) > 0) {
1824 uint16_t profile_id;
1825 if (!CBS_get_u16(cbs: &profile_ids_tmp, out: &profile_id)) {
1826 return false;
1827 }
1828
1829 if (server_profile->id == profile_id) {
1830 ssl->s3->srtp_profile = server_profile;
1831 return true;
1832 }
1833 }
1834 }
1835
1836 return true;
1837}
1838
1839static bool ext_srtp_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1840 SSL *const ssl = hs->ssl;
1841 if (ssl->s3->srtp_profile == NULL) {
1842 return true;
1843 }
1844
1845 assert(SSL_is_dtls(ssl));
1846 CBB contents, profile_ids;
1847 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_srtp) ||
1848 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
1849 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &profile_ids) ||
1850 !CBB_add_u16(cbb: &profile_ids, value: ssl->s3->srtp_profile->id) ||
1851 !CBB_add_u8(cbb: &contents, value: 0 /* empty MKI */) ||
1852 !CBB_flush(cbb: out)) {
1853 return false;
1854 }
1855
1856 return true;
1857}
1858
1859
1860// EC point formats.
1861//
1862// https://tools.ietf.org/html/rfc4492#section-5.1.2
1863
1864static bool ext_ec_point_add_extension(const SSL_HANDSHAKE *hs, CBB *out) {
1865 CBB contents, formats;
1866 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_ec_point_formats) ||
1867 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
1868 !CBB_add_u8_length_prefixed(cbb: &contents, out_contents: &formats) ||
1869 !CBB_add_u8(cbb: &formats, TLSEXT_ECPOINTFORMAT_uncompressed) ||
1870 !CBB_flush(cbb: out)) {
1871 return false;
1872 }
1873
1874 return true;
1875}
1876
1877static bool ext_ec_point_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1878 CBB *out_compressible,
1879 ssl_client_hello_type_t type) {
1880 // The point format extension is unnecessary in TLS 1.3.
1881 if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner) {
1882 return true;
1883 }
1884
1885 return ext_ec_point_add_extension(hs, out);
1886}
1887
1888static bool ext_ec_point_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1889 CBS *contents) {
1890 if (contents == NULL) {
1891 return true;
1892 }
1893
1894 if (ssl_protocol_version(ssl: hs->ssl) >= TLS1_3_VERSION) {
1895 return false;
1896 }
1897
1898 CBS ec_point_format_list;
1899 if (!CBS_get_u8_length_prefixed(cbs: contents, out: &ec_point_format_list) ||
1900 CBS_len(cbs: contents) != 0) {
1901 return false;
1902 }
1903
1904 // Per RFC 4492, section 5.1.2, implementations MUST support the uncompressed
1905 // point format.
1906 if (OPENSSL_memchr(s: CBS_data(cbs: &ec_point_format_list),
1907 TLSEXT_ECPOINTFORMAT_uncompressed,
1908 n: CBS_len(cbs: &ec_point_format_list)) == NULL) {
1909 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1910 return false;
1911 }
1912
1913 return true;
1914}
1915
1916static bool ext_ec_point_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1917 CBS *contents) {
1918 if (ssl_protocol_version(ssl: hs->ssl) >= TLS1_3_VERSION) {
1919 return true;
1920 }
1921
1922 return ext_ec_point_parse_serverhello(hs, out_alert, contents);
1923}
1924
1925static bool ext_ec_point_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1926 SSL *const ssl = hs->ssl;
1927 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1928 return true;
1929 }
1930
1931 const uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1932 const uint32_t alg_a = hs->new_cipher->algorithm_auth;
1933 const bool using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);
1934
1935 if (!using_ecc) {
1936 return true;
1937 }
1938
1939 return ext_ec_point_add_extension(hs, out);
1940}
1941
1942
1943// Pre Shared Key
1944//
1945// https://tools.ietf.org/html/rfc8446#section-4.2.11
1946
1947static bool should_offer_psk(const SSL_HANDSHAKE *hs,
1948 ssl_client_hello_type_t type) {
1949 const SSL *const ssl = hs->ssl;
1950 if (hs->max_version < TLS1_3_VERSION || ssl->session == nullptr ||
1951 ssl_session_protocol_version(session: ssl->session.get()) < TLS1_3_VERSION ||
1952 // TODO(https://crbug.com/boringssl/275): Should we synthesize a
1953 // placeholder PSK, at least when we offer early data? Otherwise
1954 // ClientHelloOuter will contain an early_data extension without a
1955 // pre_shared_key extension and potentially break the recovery flow.
1956 type == ssl_client_hello_outer) {
1957 return false;
1958 }
1959
1960 // Per RFC 8446 section 4.1.4, skip offering the session if the selected
1961 // cipher in HelloRetryRequest does not match. This avoids performing the
1962 // transcript hash transformation for multiple hashes.
1963 if (ssl->s3->used_hello_retry_request &&
1964 ssl->session->cipher->algorithm_prf != hs->new_cipher->algorithm_prf) {
1965 return false;
1966 }
1967
1968 return true;
1969}
1970
1971static size_t ext_pre_shared_key_clienthello_length(
1972 const SSL_HANDSHAKE *hs, ssl_client_hello_type_t type) {
1973 const SSL *const ssl = hs->ssl;
1974 if (!should_offer_psk(hs, type)) {
1975 return 0;
1976 }
1977
1978 size_t binder_len = EVP_MD_size(md: ssl_session_get_digest(session: ssl->session.get()));
1979 return 15 + ssl->session->ticket.size() + binder_len;
1980}
1981
1982static bool ext_pre_shared_key_add_clienthello(const SSL_HANDSHAKE *hs,
1983 CBB *out, bool *out_needs_binder,
1984 ssl_client_hello_type_t type) {
1985 const SSL *const ssl = hs->ssl;
1986 *out_needs_binder = false;
1987 if (!should_offer_psk(hs, type)) {
1988 return true;
1989 }
1990
1991 struct OPENSSL_timeval now;
1992 ssl_get_current_time(ssl, out_clock: &now);
1993 uint32_t ticket_age = 1000 * (now.tv_sec - ssl->session->time);
1994 uint32_t obfuscated_ticket_age = ticket_age + ssl->session->ticket_age_add;
1995
1996 // Fill in a placeholder zero binder of the appropriate length. It will be
1997 // computed and filled in later after length prefixes are computed.
1998 size_t binder_len = EVP_MD_size(md: ssl_session_get_digest(session: ssl->session.get()));
1999
2000 CBB contents, identity, ticket, binders, binder;
2001 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_pre_shared_key) ||
2002 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
2003 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &identity) ||
2004 !CBB_add_u16_length_prefixed(cbb: &identity, out_contents: &ticket) ||
2005 !CBB_add_bytes(cbb: &ticket, data: ssl->session->ticket.data(),
2006 len: ssl->session->ticket.size()) ||
2007 !CBB_add_u32(cbb: &identity, value: obfuscated_ticket_age) ||
2008 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &binders) ||
2009 !CBB_add_u8_length_prefixed(cbb: &binders, out_contents: &binder) ||
2010 !CBB_add_zeros(cbb: &binder, len: binder_len)) {
2011 return false;
2012 }
2013
2014 *out_needs_binder = true;
2015 return CBB_flush(cbb: out);
2016}
2017
2018bool ssl_ext_pre_shared_key_parse_serverhello(SSL_HANDSHAKE *hs,
2019 uint8_t *out_alert,
2020 CBS *contents) {
2021 uint16_t psk_id;
2022 if (!CBS_get_u16(cbs: contents, out: &psk_id) ||
2023 CBS_len(cbs: contents) != 0) {
2024 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2025 *out_alert = SSL_AD_DECODE_ERROR;
2026 return false;
2027 }
2028
2029 // We only advertise one PSK identity, so the only legal index is zero.
2030 if (psk_id != 0) {
2031 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
2032 *out_alert = SSL_AD_UNKNOWN_PSK_IDENTITY;
2033 return false;
2034 }
2035
2036 return true;
2037}
2038
2039bool ssl_ext_pre_shared_key_parse_clienthello(
2040 SSL_HANDSHAKE *hs, CBS *out_ticket, CBS *out_binders,
2041 uint32_t *out_obfuscated_ticket_age, uint8_t *out_alert,
2042 const SSL_CLIENT_HELLO *client_hello, CBS *contents) {
2043 // Verify that the pre_shared_key extension is the last extension in
2044 // ClientHello.
2045 if (CBS_data(cbs: contents) + CBS_len(cbs: contents) !=
2046 client_hello->extensions + client_hello->extensions_len) {
2047 OPENSSL_PUT_ERROR(SSL, SSL_R_PRE_SHARED_KEY_MUST_BE_LAST);
2048 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2049 return false;
2050 }
2051
2052 // We only process the first PSK identity since we don't support pure PSK.
2053 CBS identities, binders;
2054 if (!CBS_get_u16_length_prefixed(cbs: contents, out: &identities) ||
2055 !CBS_get_u16_length_prefixed(cbs: &identities, out: out_ticket) ||
2056 !CBS_get_u32(cbs: &identities, out: out_obfuscated_ticket_age) ||
2057 !CBS_get_u16_length_prefixed(cbs: contents, out: &binders) ||
2058 CBS_len(cbs: &binders) == 0 ||
2059 CBS_len(cbs: contents) != 0) {
2060 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2061 *out_alert = SSL_AD_DECODE_ERROR;
2062 return false;
2063 }
2064
2065 *out_binders = binders;
2066
2067 // Check the syntax of the remaining identities, but do not process them.
2068 size_t num_identities = 1;
2069 while (CBS_len(cbs: &identities) != 0) {
2070 CBS unused_ticket;
2071 uint32_t unused_obfuscated_ticket_age;
2072 if (!CBS_get_u16_length_prefixed(cbs: &identities, out: &unused_ticket) ||
2073 !CBS_get_u32(cbs: &identities, out: &unused_obfuscated_ticket_age)) {
2074 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2075 *out_alert = SSL_AD_DECODE_ERROR;
2076 return false;
2077 }
2078
2079 num_identities++;
2080 }
2081
2082 // Check the syntax of the binders. The value will be checked later if
2083 // resuming.
2084 size_t num_binders = 0;
2085 while (CBS_len(cbs: &binders) != 0) {
2086 CBS binder;
2087 if (!CBS_get_u8_length_prefixed(cbs: &binders, out: &binder)) {
2088 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2089 *out_alert = SSL_AD_DECODE_ERROR;
2090 return false;
2091 }
2092
2093 num_binders++;
2094 }
2095
2096 if (num_identities != num_binders) {
2097 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_BINDER_COUNT_MISMATCH);
2098 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2099 return false;
2100 }
2101
2102 return true;
2103}
2104
2105bool ssl_ext_pre_shared_key_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2106 if (!hs->ssl->s3->session_reused) {
2107 return true;
2108 }
2109
2110 CBB contents;
2111 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_pre_shared_key) ||
2112 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
2113 // We only consider the first identity for resumption
2114 !CBB_add_u16(cbb: &contents, value: 0) ||
2115 !CBB_flush(cbb: out)) {
2116 return false;
2117 }
2118
2119 return true;
2120}
2121
2122
2123// Pre-Shared Key Exchange Modes
2124//
2125// https://tools.ietf.org/html/rfc8446#section-4.2.9
2126
2127static bool ext_psk_key_exchange_modes_add_clienthello(
2128 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2129 ssl_client_hello_type_t type) {
2130 if (hs->max_version < TLS1_3_VERSION) {
2131 return true;
2132 }
2133
2134 CBB contents, ke_modes;
2135 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_psk_key_exchange_modes) ||
2136 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
2137 !CBB_add_u8_length_prefixed(cbb: &contents, out_contents: &ke_modes) ||
2138 !CBB_add_u8(cbb: &ke_modes, SSL_PSK_DHE_KE)) {
2139 return false;
2140 }
2141
2142 return CBB_flush(cbb: out_compressible);
2143}
2144
2145static bool ext_psk_key_exchange_modes_parse_clienthello(SSL_HANDSHAKE *hs,
2146 uint8_t *out_alert,
2147 CBS *contents) {
2148 if (contents == NULL) {
2149 return true;
2150 }
2151
2152 CBS ke_modes;
2153 if (!CBS_get_u8_length_prefixed(cbs: contents, out: &ke_modes) ||
2154 CBS_len(cbs: &ke_modes) == 0 ||
2155 CBS_len(cbs: contents) != 0) {
2156 *out_alert = SSL_AD_DECODE_ERROR;
2157 return false;
2158 }
2159
2160 // We only support tickets with PSK_DHE_KE.
2161 hs->accept_psk_mode = OPENSSL_memchr(s: CBS_data(cbs: &ke_modes), SSL_PSK_DHE_KE,
2162 n: CBS_len(cbs: &ke_modes)) != NULL;
2163
2164 return true;
2165}
2166
2167
2168// Early Data Indication
2169//
2170// https://tools.ietf.org/html/rfc8446#section-4.2.10
2171
2172static bool ext_early_data_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2173 CBB *out_compressible,
2174 ssl_client_hello_type_t type) {
2175 const SSL *const ssl = hs->ssl;
2176 // The second ClientHello never offers early data, and we must have already
2177 // filled in |early_data_reason| by this point.
2178 if (ssl->s3->used_hello_retry_request) {
2179 assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
2180 return true;
2181 }
2182
2183 if (!hs->early_data_offered) {
2184 return true;
2185 }
2186
2187 // If offering ECH, the extension only applies to ClientHelloInner, but we
2188 // send the extension in both ClientHellos. This ensures that, if the server
2189 // handshakes with ClientHelloOuter, it can skip past early data. See
2190 // draft-ietf-tls-esni-13, section 6.1.
2191 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_early_data) ||
2192 !CBB_add_u16(cbb: out_compressible, value: 0) ||
2193 !CBB_flush(cbb: out_compressible)) {
2194 return false;
2195 }
2196
2197 return true;
2198}
2199
2200static bool ext_early_data_parse_serverhello(SSL_HANDSHAKE *hs,
2201 uint8_t *out_alert,
2202 CBS *contents) {
2203 SSL *const ssl = hs->ssl;
2204 if (contents == NULL) {
2205 if (hs->early_data_offered && !ssl->s3->used_hello_retry_request) {
2206 ssl->s3->early_data_reason = ssl->s3->session_reused
2207 ? ssl_early_data_peer_declined
2208 : ssl_early_data_session_not_resumed;
2209 } else {
2210 // We already filled in |early_data_reason| when declining to offer 0-RTT
2211 // or handling the implicit HelloRetryRequest reject.
2212 assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
2213 }
2214 return true;
2215 }
2216
2217 // If we received an HRR, the second ClientHello never offers early data, so
2218 // the extensions logic will automatically reject early data extensions as
2219 // unsolicited. This covered by the ServerAcceptsEarlyDataOnHRR test.
2220 assert(!ssl->s3->used_hello_retry_request);
2221
2222 if (CBS_len(cbs: contents) != 0) {
2223 *out_alert = SSL_AD_DECODE_ERROR;
2224 return false;
2225 }
2226
2227 if (!ssl->s3->session_reused) {
2228 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2229 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
2230 return false;
2231 }
2232
2233 ssl->s3->early_data_reason = ssl_early_data_accepted;
2234 ssl->s3->early_data_accepted = true;
2235 return true;
2236}
2237
2238static bool ext_early_data_parse_clienthello(SSL_HANDSHAKE *hs,
2239 uint8_t *out_alert, CBS *contents) {
2240 SSL *const ssl = hs->ssl;
2241 if (contents == NULL ||
2242 ssl_protocol_version(ssl) < TLS1_3_VERSION) {
2243 return true;
2244 }
2245
2246 if (CBS_len(cbs: contents) != 0) {
2247 *out_alert = SSL_AD_DECODE_ERROR;
2248 return false;
2249 }
2250
2251 hs->early_data_offered = true;
2252 return true;
2253}
2254
2255static bool ext_early_data_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2256 if (!hs->ssl->s3->early_data_accepted) {
2257 return true;
2258 }
2259
2260 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_early_data) ||
2261 !CBB_add_u16(cbb: out, value: 0) ||
2262 !CBB_flush(cbb: out)) {
2263 return false;
2264 }
2265
2266 return true;
2267}
2268
2269
2270// Key Share
2271//
2272// https://tools.ietf.org/html/rfc8446#section-4.2.8
2273
2274bool ssl_setup_key_shares(SSL_HANDSHAKE *hs, uint16_t override_group_id) {
2275 SSL *const ssl = hs->ssl;
2276 hs->key_shares[0].reset();
2277 hs->key_shares[1].reset();
2278 hs->key_share_bytes.Reset();
2279
2280 if (hs->max_version < TLS1_3_VERSION) {
2281 return true;
2282 }
2283
2284 bssl::ScopedCBB cbb;
2285 if (!CBB_init(cbb: cbb.get(), initial_capacity: 64)) {
2286 return false;
2287 }
2288
2289 if (override_group_id == 0 && ssl->ctx->grease_enabled) {
2290 // Add a fake group. See RFC 8701.
2291 if (!CBB_add_u16(cbb: cbb.get(), value: ssl_get_grease_value(hs, index: ssl_grease_group)) ||
2292 !CBB_add_u16(cbb: cbb.get(), value: 1 /* length */) ||
2293 !CBB_add_u8(cbb: cbb.get(), value: 0 /* one byte key share */)) {
2294 return false;
2295 }
2296 }
2297
2298 uint16_t group_id = override_group_id;
2299 uint16_t second_group_id = 0;
2300 if (override_group_id == 0) {
2301 // Predict the most preferred group.
2302 Span<const uint16_t> groups = tls1_get_grouplist(hs);
2303 if (groups.empty()) {
2304 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_GROUPS_SPECIFIED);
2305 return false;
2306 }
2307
2308 group_id = groups[0];
2309
2310 // We'll try to include one post-quantum and one classical initial key
2311 // share.
2312 for (size_t i = 1; i < groups.size() && second_group_id == 0; i++) {
2313 if (is_post_quantum_group(id: group_id) != is_post_quantum_group(id: groups[i])) {
2314 second_group_id = groups[i];
2315 assert(second_group_id != group_id);
2316 }
2317 }
2318 }
2319
2320 CBB key_exchange;
2321 hs->key_shares[0] = SSLKeyShare::Create(group_id);
2322 if (!hs->key_shares[0] || //
2323 !CBB_add_u16(cbb: cbb.get(), value: group_id) ||
2324 !CBB_add_u16_length_prefixed(cbb: cbb.get(), out_contents: &key_exchange) ||
2325 !hs->key_shares[0]->Generate(out_public_key: &key_exchange)) {
2326 return false;
2327 }
2328
2329 if (second_group_id != 0) {
2330 hs->key_shares[1] = SSLKeyShare::Create(group_id: second_group_id);
2331 if (!hs->key_shares[1] || //
2332 !CBB_add_u16(cbb: cbb.get(), value: second_group_id) ||
2333 !CBB_add_u16_length_prefixed(cbb: cbb.get(), out_contents: &key_exchange) ||
2334 !hs->key_shares[1]->Generate(out_public_key: &key_exchange)) {
2335 return false;
2336 }
2337 }
2338
2339 return CBBFinishArray(cbb: cbb.get(), out: &hs->key_share_bytes);
2340}
2341
2342static bool ext_key_share_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2343 CBB *out_compressible,
2344 ssl_client_hello_type_t type) {
2345 if (hs->max_version < TLS1_3_VERSION) {
2346 return true;
2347 }
2348
2349 assert(!hs->key_share_bytes.empty());
2350 CBB contents, kse_bytes;
2351 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_key_share) ||
2352 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
2353 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &kse_bytes) ||
2354 !CBB_add_bytes(cbb: &kse_bytes, data: hs->key_share_bytes.data(),
2355 len: hs->key_share_bytes.size()) ||
2356 !CBB_flush(cbb: out_compressible)) {
2357 return false;
2358 }
2359
2360 return true;
2361}
2362
2363bool ssl_ext_key_share_parse_serverhello(SSL_HANDSHAKE *hs,
2364 Array<uint8_t> *out_secret,
2365 uint8_t *out_alert, CBS *contents) {
2366 CBS ciphertext;
2367 uint16_t group_id;
2368 if (!CBS_get_u16(cbs: contents, out: &group_id) ||
2369 !CBS_get_u16_length_prefixed(cbs: contents, out: &ciphertext) ||
2370 CBS_len(cbs: contents) != 0) {
2371 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2372 *out_alert = SSL_AD_DECODE_ERROR;
2373 return false;
2374 }
2375
2376 SSLKeyShare *key_share = hs->key_shares[0].get();
2377 if (key_share->GroupID() != group_id) {
2378 if (!hs->key_shares[1] || hs->key_shares[1]->GroupID() != group_id) {
2379 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2380 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
2381 return false;
2382 }
2383 key_share = hs->key_shares[1].get();
2384 }
2385
2386 if (!key_share->Decap(out_secret, out_alert, ciphertext)) {
2387 *out_alert = SSL_AD_INTERNAL_ERROR;
2388 return false;
2389 }
2390
2391 hs->new_session->group_id = group_id;
2392 hs->key_shares[0].reset();
2393 hs->key_shares[1].reset();
2394 return true;
2395}
2396
2397bool ssl_ext_key_share_parse_clienthello(SSL_HANDSHAKE *hs, bool *out_found,
2398 Span<const uint8_t> *out_peer_key,
2399 uint8_t *out_alert,
2400 const SSL_CLIENT_HELLO *client_hello) {
2401 // We only support connections that include an ECDHE key exchange.
2402 CBS contents;
2403 if (!ssl_client_hello_get_extension(client_hello, out: &contents,
2404 TLSEXT_TYPE_key_share)) {
2405 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
2406 *out_alert = SSL_AD_MISSING_EXTENSION;
2407 return false;
2408 }
2409
2410 CBS key_shares;
2411 if (!CBS_get_u16_length_prefixed(cbs: &contents, out: &key_shares) ||
2412 CBS_len(cbs: &contents) != 0) {
2413 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2414 return false;
2415 }
2416
2417 // Find the corresponding key share.
2418 const uint16_t group_id = hs->new_session->group_id;
2419 CBS peer_key;
2420 CBS_init(cbs: &peer_key, data: nullptr, len: 0);
2421 while (CBS_len(cbs: &key_shares) > 0) {
2422 uint16_t id;
2423 CBS peer_key_tmp;
2424 if (!CBS_get_u16(cbs: &key_shares, out: &id) ||
2425 !CBS_get_u16_length_prefixed(cbs: &key_shares, out: &peer_key_tmp) ||
2426 CBS_len(cbs: &peer_key_tmp) == 0) {
2427 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2428 return false;
2429 }
2430
2431 if (id == group_id) {
2432 if (CBS_len(cbs: &peer_key) != 0) {
2433 OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_KEY_SHARE);
2434 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2435 return false;
2436 }
2437
2438 peer_key = peer_key_tmp;
2439 // Continue parsing the structure to keep peers honest.
2440 }
2441 }
2442
2443 if (out_peer_key != nullptr) {
2444 *out_peer_key = peer_key;
2445 }
2446 *out_found = CBS_len(cbs: &peer_key) != 0;
2447 return true;
2448}
2449
2450bool ssl_ext_key_share_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2451 CBB entry, ciphertext;
2452 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_key_share) ||
2453 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &entry) ||
2454 !CBB_add_u16(cbb: &entry, value: hs->new_session->group_id) ||
2455 !CBB_add_u16_length_prefixed(cbb: &entry, out_contents: &ciphertext) ||
2456 !CBB_add_bytes(cbb: &ciphertext, data: hs->key_share_ciphertext.data(),
2457 len: hs->key_share_ciphertext.size()) ||
2458 !CBB_flush(cbb: out)) {
2459 return false;
2460 }
2461 return true;
2462}
2463
2464
2465// Supported Versions
2466//
2467// https://tools.ietf.org/html/rfc8446#section-4.2.1
2468
2469static bool ext_supported_versions_add_clienthello(
2470 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2471 ssl_client_hello_type_t type) {
2472 const SSL *const ssl = hs->ssl;
2473 if (hs->max_version <= TLS1_2_VERSION) {
2474 return true;
2475 }
2476
2477 // supported_versions is compressible in ECH if ClientHelloOuter already
2478 // requires TLS 1.3. Otherwise the extensions differ in the older versions.
2479 if (hs->min_version >= TLS1_3_VERSION) {
2480 out = out_compressible;
2481 }
2482
2483 CBB contents, versions;
2484 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_supported_versions) ||
2485 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
2486 !CBB_add_u8_length_prefixed(cbb: &contents, out_contents: &versions)) {
2487 return false;
2488 }
2489
2490 // Add a fake version. See RFC 8701.
2491 if (ssl->ctx->grease_enabled &&
2492 !CBB_add_u16(cbb: &versions, value: ssl_get_grease_value(hs, index: ssl_grease_version))) {
2493 return false;
2494 }
2495
2496 // Encrypted ClientHellos requires TLS 1.3 or later.
2497 uint16_t extra_min_version =
2498 type == ssl_client_hello_inner ? TLS1_3_VERSION : 0;
2499 if (!ssl_add_supported_versions(hs, cbb: &versions, extra_min_version) ||
2500 !CBB_flush(cbb: out)) {
2501 return false;
2502 }
2503
2504 return true;
2505}
2506
2507
2508// Cookie
2509//
2510// https://tools.ietf.org/html/rfc8446#section-4.2.2
2511
2512static bool ext_cookie_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2513 CBB *out_compressible,
2514 ssl_client_hello_type_t type) {
2515 if (hs->cookie.empty()) {
2516 return true;
2517 }
2518
2519 CBB contents, cookie;
2520 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_cookie) ||
2521 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
2522 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &cookie) ||
2523 !CBB_add_bytes(cbb: &cookie, data: hs->cookie.data(), len: hs->cookie.size()) ||
2524 !CBB_flush(cbb: out_compressible)) {
2525 return false;
2526 }
2527
2528 return true;
2529}
2530
2531
2532// Supported Groups
2533//
2534// https://tools.ietf.org/html/rfc4492#section-5.1.1
2535// https://tools.ietf.org/html/rfc8446#section-4.2.7
2536
2537static bool ext_supported_groups_add_clienthello(const SSL_HANDSHAKE *hs,
2538 CBB *out,
2539 CBB *out_compressible,
2540 ssl_client_hello_type_t type) {
2541 const SSL *const ssl = hs->ssl;
2542 CBB contents, groups_bytes;
2543 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_supported_groups) ||
2544 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
2545 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &groups_bytes)) {
2546 return false;
2547 }
2548
2549 // Add a fake group. See RFC 8701.
2550 if (ssl->ctx->grease_enabled &&
2551 !CBB_add_u16(cbb: &groups_bytes,
2552 value: ssl_get_grease_value(hs, index: ssl_grease_group))) {
2553 return false;
2554 }
2555
2556 for (uint16_t group : tls1_get_grouplist(hs)) {
2557 if (is_post_quantum_group(id: group) &&
2558 hs->max_version < TLS1_3_VERSION) {
2559 continue;
2560 }
2561 if (!CBB_add_u16(cbb: &groups_bytes, value: group)) {
2562 return false;
2563 }
2564 }
2565
2566 return CBB_flush(cbb: out_compressible);
2567}
2568
2569static bool ext_supported_groups_parse_serverhello(SSL_HANDSHAKE *hs,
2570 uint8_t *out_alert,
2571 CBS *contents) {
2572 // This extension is not expected to be echoed by servers in TLS 1.2, but some
2573 // BigIP servers send it nonetheless, so do not enforce this.
2574 return true;
2575}
2576
2577static bool parse_u16_array(const CBS *cbs, Array<uint16_t> *out) {
2578 CBS copy = *cbs;
2579 if ((CBS_len(cbs: &copy) & 1) != 0) {
2580 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2581 return false;
2582 }
2583
2584 Array<uint16_t> ret;
2585 if (!ret.Init(new_size: CBS_len(cbs: &copy) / 2)) {
2586 return false;
2587 }
2588 for (size_t i = 0; i < ret.size(); i++) {
2589 if (!CBS_get_u16(cbs: &copy, out: &ret[i])) {
2590 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
2591 return false;
2592 }
2593 }
2594
2595 assert(CBS_len(&copy) == 0);
2596 *out = std::move(ret);
2597 return true;
2598}
2599
2600static bool ext_supported_groups_parse_clienthello(SSL_HANDSHAKE *hs,
2601 uint8_t *out_alert,
2602 CBS *contents) {
2603 if (contents == NULL) {
2604 return true;
2605 }
2606
2607 CBS supported_group_list;
2608 if (!CBS_get_u16_length_prefixed(cbs: contents, out: &supported_group_list) ||
2609 CBS_len(cbs: &supported_group_list) == 0 ||
2610 CBS_len(cbs: contents) != 0 ||
2611 !parse_u16_array(cbs: &supported_group_list, out: &hs->peer_supported_group_list)) {
2612 return false;
2613 }
2614
2615 return true;
2616}
2617
2618
2619// QUIC Transport Parameters
2620
2621static bool ext_quic_transport_params_add_clienthello_impl(
2622 const SSL_HANDSHAKE *hs, CBB *out, bool use_legacy_codepoint) {
2623 if (hs->config->quic_transport_params.empty() && !hs->ssl->quic_method) {
2624 return true;
2625 }
2626 if (hs->config->quic_transport_params.empty() || !hs->ssl->quic_method) {
2627 // QUIC Transport Parameters must be sent over QUIC, and they must not be
2628 // sent over non-QUIC transports. If transport params are set, then
2629 // SSL(_CTX)_set_quic_method must also be called.
2630 OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2631 return false;
2632 }
2633 assert(hs->min_version > TLS1_2_VERSION);
2634 if (use_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2635 // Do nothing, we'll send the other codepoint.
2636 return true;
2637 }
2638
2639 uint16_t extension_type = TLSEXT_TYPE_quic_transport_parameters;
2640 if (hs->config->quic_use_legacy_codepoint) {
2641 extension_type = TLSEXT_TYPE_quic_transport_parameters_legacy;
2642 }
2643
2644 CBB contents;
2645 if (!CBB_add_u16(cbb: out, value: extension_type) ||
2646 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
2647 !CBB_add_bytes(cbb: &contents, data: hs->config->quic_transport_params.data(),
2648 len: hs->config->quic_transport_params.size()) ||
2649 !CBB_flush(cbb: out)) {
2650 return false;
2651 }
2652 return true;
2653}
2654
2655static bool ext_quic_transport_params_add_clienthello(
2656 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2657 ssl_client_hello_type_t type) {
2658 return ext_quic_transport_params_add_clienthello_impl(
2659 hs, out: out_compressible, /*use_legacy_codepoint=*/false);
2660}
2661
2662static bool ext_quic_transport_params_add_clienthello_legacy(
2663 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2664 ssl_client_hello_type_t type) {
2665 return ext_quic_transport_params_add_clienthello_impl(
2666 hs, out: out_compressible, /*use_legacy_codepoint=*/true);
2667}
2668
2669static bool ext_quic_transport_params_parse_serverhello_impl(
2670 SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents,
2671 bool used_legacy_codepoint) {
2672 SSL *const ssl = hs->ssl;
2673 if (contents == nullptr) {
2674 if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2675 // Silently ignore because we expect the other QUIC codepoint.
2676 return true;
2677 }
2678 if (!ssl->quic_method) {
2679 return true;
2680 }
2681 *out_alert = SSL_AD_MISSING_EXTENSION;
2682 return false;
2683 }
2684 // The extensions parser will check for unsolicited extensions before
2685 // calling the callback.
2686 assert(ssl->quic_method != nullptr);
2687 assert(ssl_protocol_version(ssl) == TLS1_3_VERSION);
2688 assert(used_legacy_codepoint == hs->config->quic_use_legacy_codepoint);
2689 return ssl->s3->peer_quic_transport_params.CopyFrom(in: *contents);
2690}
2691
2692static bool ext_quic_transport_params_parse_serverhello(SSL_HANDSHAKE *hs,
2693 uint8_t *out_alert,
2694 CBS *contents) {
2695 return ext_quic_transport_params_parse_serverhello_impl(
2696 hs, out_alert, contents, /*used_legacy_codepoint=*/false);
2697}
2698
2699static bool ext_quic_transport_params_parse_serverhello_legacy(
2700 SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents) {
2701 return ext_quic_transport_params_parse_serverhello_impl(
2702 hs, out_alert, contents, /*used_legacy_codepoint=*/true);
2703}
2704
2705static bool ext_quic_transport_params_parse_clienthello_impl(
2706 SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents,
2707 bool used_legacy_codepoint) {
2708 SSL *const ssl = hs->ssl;
2709 if (!contents) {
2710 if (!ssl->quic_method) {
2711 if (hs->config->quic_transport_params.empty()) {
2712 return true;
2713 }
2714 // QUIC transport parameters must not be set if |ssl| is not configured
2715 // for QUIC.
2716 OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2717 *out_alert = SSL_AD_INTERNAL_ERROR;
2718 return false;
2719 }
2720 if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2721 // Silently ignore because we expect the other QUIC codepoint.
2722 return true;
2723 }
2724 *out_alert = SSL_AD_MISSING_EXTENSION;
2725 return false;
2726 }
2727 if (!ssl->quic_method) {
2728 if (used_legacy_codepoint) {
2729 // Ignore the legacy private-use codepoint because that could be sent
2730 // to mean something else than QUIC transport parameters.
2731 return true;
2732 }
2733 // Fail if we received the codepoint registered with IANA for QUIC
2734 // because that is not allowed outside of QUIC.
2735 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2736 return false;
2737 }
2738 assert(ssl_protocol_version(ssl) == TLS1_3_VERSION);
2739 if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2740 // Silently ignore because we expect the other QUIC codepoint.
2741 return true;
2742 }
2743 return ssl->s3->peer_quic_transport_params.CopyFrom(in: *contents);
2744}
2745
2746static bool ext_quic_transport_params_parse_clienthello(SSL_HANDSHAKE *hs,
2747 uint8_t *out_alert,
2748 CBS *contents) {
2749 return ext_quic_transport_params_parse_clienthello_impl(
2750 hs, out_alert, contents, /*used_legacy_codepoint=*/false);
2751}
2752
2753static bool ext_quic_transport_params_parse_clienthello_legacy(
2754 SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents) {
2755 return ext_quic_transport_params_parse_clienthello_impl(
2756 hs, out_alert, contents, /*used_legacy_codepoint=*/true);
2757}
2758
2759static bool ext_quic_transport_params_add_serverhello_impl(
2760 SSL_HANDSHAKE *hs, CBB *out, bool use_legacy_codepoint) {
2761 if (hs->ssl->quic_method == nullptr && use_legacy_codepoint) {
2762 // Ignore the legacy private-use codepoint because that could be sent
2763 // to mean something else than QUIC transport parameters.
2764 return true;
2765 }
2766 assert(hs->ssl->quic_method != nullptr);
2767 if (hs->config->quic_transport_params.empty()) {
2768 // Transport parameters must be set when using QUIC.
2769 OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2770 return false;
2771 }
2772 if (use_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2773 // Do nothing, we'll send the other codepoint.
2774 return true;
2775 }
2776
2777 uint16_t extension_type = TLSEXT_TYPE_quic_transport_parameters;
2778 if (hs->config->quic_use_legacy_codepoint) {
2779 extension_type = TLSEXT_TYPE_quic_transport_parameters_legacy;
2780 }
2781
2782 CBB contents;
2783 if (!CBB_add_u16(cbb: out, value: extension_type) ||
2784 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
2785 !CBB_add_bytes(cbb: &contents, data: hs->config->quic_transport_params.data(),
2786 len: hs->config->quic_transport_params.size()) ||
2787 !CBB_flush(cbb: out)) {
2788 return false;
2789 }
2790
2791 return true;
2792}
2793
2794static bool ext_quic_transport_params_add_serverhello(SSL_HANDSHAKE *hs,
2795 CBB *out) {
2796 return ext_quic_transport_params_add_serverhello_impl(
2797 hs, out, /*use_legacy_codepoint=*/false);
2798}
2799
2800static bool ext_quic_transport_params_add_serverhello_legacy(SSL_HANDSHAKE *hs,
2801 CBB *out) {
2802 return ext_quic_transport_params_add_serverhello_impl(
2803 hs, out, /*use_legacy_codepoint=*/true);
2804}
2805
2806// Delegated credentials.
2807//
2808// https://tools.ietf.org/html/draft-ietf-tls-subcerts
2809
2810static bool ext_delegated_credential_add_clienthello(
2811 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2812 ssl_client_hello_type_t type) {
2813 return true;
2814}
2815
2816static bool ext_delegated_credential_parse_clienthello(SSL_HANDSHAKE *hs,
2817 uint8_t *out_alert,
2818 CBS *contents) {
2819 if (contents == nullptr || ssl_protocol_version(ssl: hs->ssl) < TLS1_3_VERSION) {
2820 // Don't use delegated credentials unless we're negotiating TLS 1.3 or
2821 // higher.
2822 return true;
2823 }
2824
2825 // The contents of the extension are the signature algorithms the client will
2826 // accept for a delegated credential.
2827 CBS sigalg_list;
2828 if (!CBS_get_u16_length_prefixed(cbs: contents, out: &sigalg_list) ||
2829 CBS_len(cbs: &sigalg_list) == 0 ||
2830 CBS_len(cbs: contents) != 0 ||
2831 !parse_u16_array(cbs: &sigalg_list, out: &hs->peer_delegated_credential_sigalgs)) {
2832 return false;
2833 }
2834
2835 hs->delegated_credential_requested = true;
2836 return true;
2837}
2838
2839// Certificate compression
2840
2841static bool cert_compression_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2842 CBB *out_compressible,
2843 ssl_client_hello_type_t type) {
2844 bool first = true;
2845 CBB contents, algs;
2846
2847 for (const auto &alg : hs->ssl->ctx->cert_compression_algs) {
2848 if (alg.decompress == nullptr) {
2849 continue;
2850 }
2851
2852 if (first &&
2853 (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_cert_compression) ||
2854 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
2855 !CBB_add_u8_length_prefixed(cbb: &contents, out_contents: &algs))) {
2856 return false;
2857 }
2858 first = false;
2859 if (!CBB_add_u16(cbb: &algs, value: alg.alg_id)) {
2860 return false;
2861 }
2862 }
2863
2864 return first || CBB_flush(cbb: out_compressible);
2865}
2866
2867static bool cert_compression_parse_serverhello(SSL_HANDSHAKE *hs,
2868 uint8_t *out_alert,
2869 CBS *contents) {
2870 if (contents == nullptr) {
2871 return true;
2872 }
2873
2874 // The server may not echo this extension. Any server to client negotiation is
2875 // advertised in the CertificateRequest message.
2876 return false;
2877}
2878
2879static bool cert_compression_parse_clienthello(SSL_HANDSHAKE *hs,
2880 uint8_t *out_alert,
2881 CBS *contents) {
2882 if (contents == nullptr) {
2883 return true;
2884 }
2885
2886 const SSL_CTX *ctx = hs->ssl->ctx.get();
2887 const size_t num_algs = ctx->cert_compression_algs.size();
2888
2889 CBS alg_ids;
2890 if (!CBS_get_u8_length_prefixed(cbs: contents, out: &alg_ids) ||
2891 CBS_len(cbs: contents) != 0 ||
2892 CBS_len(cbs: &alg_ids) == 0 ||
2893 CBS_len(cbs: &alg_ids) % 2 == 1) {
2894 return false;
2895 }
2896
2897 const size_t num_given_alg_ids = CBS_len(cbs: &alg_ids) / 2;
2898 Array<uint16_t> given_alg_ids;
2899 if (!given_alg_ids.Init(new_size: num_given_alg_ids)) {
2900 return false;
2901 }
2902
2903 size_t best_index = num_algs;
2904 size_t given_alg_idx = 0;
2905
2906 while (CBS_len(cbs: &alg_ids) > 0) {
2907 uint16_t alg_id;
2908 if (!CBS_get_u16(cbs: &alg_ids, out: &alg_id)) {
2909 return false;
2910 }
2911
2912 given_alg_ids[given_alg_idx++] = alg_id;
2913
2914 for (size_t i = 0; i < num_algs; i++) {
2915 const auto &alg = ctx->cert_compression_algs[i];
2916 if (alg.alg_id == alg_id && alg.compress != nullptr) {
2917 if (i < best_index) {
2918 best_index = i;
2919 }
2920 break;
2921 }
2922 }
2923 }
2924
2925 qsort(base: given_alg_ids.data(), nmemb: given_alg_ids.size(), size: sizeof(uint16_t),
2926 compar: compare_uint16_t);
2927 for (size_t i = 1; i < num_given_alg_ids; i++) {
2928 if (given_alg_ids[i - 1] == given_alg_ids[i]) {
2929 return false;
2930 }
2931 }
2932
2933 if (best_index < num_algs &&
2934 ssl_protocol_version(ssl: hs->ssl) >= TLS1_3_VERSION) {
2935 hs->cert_compression_negotiated = true;
2936 hs->cert_compression_alg_id = ctx->cert_compression_algs[best_index].alg_id;
2937 }
2938
2939 return true;
2940}
2941
2942static bool cert_compression_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2943 return true;
2944}
2945
2946// Application-level Protocol Settings
2947//
2948// https://tools.ietf.org/html/draft-vvv-tls-alps-01
2949
2950bool ssl_get_local_application_settings(const SSL_HANDSHAKE *hs,
2951 Span<const uint8_t> *out_settings,
2952 Span<const uint8_t> protocol) {
2953 for (const ALPSConfig &config : hs->config->alps_configs) {
2954 if (protocol == config.protocol) {
2955 *out_settings = config.settings;
2956 return true;
2957 }
2958 }
2959 return false;
2960}
2961
2962static bool ext_alps_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2963 CBB *out_compressible,
2964 ssl_client_hello_type_t type) {
2965 const SSL *const ssl = hs->ssl;
2966 if (// ALPS requires TLS 1.3.
2967 hs->max_version < TLS1_3_VERSION ||
2968 // Do not offer ALPS without ALPN.
2969 hs->config->alpn_client_proto_list.empty() ||
2970 // Do not offer ALPS if not configured.
2971 hs->config->alps_configs.empty() ||
2972 // Do not offer ALPS on renegotiation handshakes.
2973 ssl->s3->initial_handshake_complete) {
2974 return true;
2975 }
2976
2977 CBB contents, proto_list, proto;
2978 if (!CBB_add_u16(cbb: out_compressible, TLSEXT_TYPE_application_settings) ||
2979 !CBB_add_u16_length_prefixed(cbb: out_compressible, out_contents: &contents) ||
2980 !CBB_add_u16_length_prefixed(cbb: &contents, out_contents: &proto_list)) {
2981 return false;
2982 }
2983
2984 for (const ALPSConfig &config : hs->config->alps_configs) {
2985 if (!CBB_add_u8_length_prefixed(cbb: &proto_list, out_contents: &proto) ||
2986 !CBB_add_bytes(cbb: &proto, data: config.protocol.data(),
2987 len: config.protocol.size())) {
2988 return false;
2989 }
2990 }
2991
2992 return CBB_flush(cbb: out_compressible);
2993}
2994
2995static bool ext_alps_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
2996 CBS *contents) {
2997 SSL *const ssl = hs->ssl;
2998 if (contents == nullptr) {
2999 return true;
3000 }
3001
3002 assert(!ssl->s3->initial_handshake_complete);
3003 assert(!hs->config->alpn_client_proto_list.empty());
3004 assert(!hs->config->alps_configs.empty());
3005
3006 // ALPS requires TLS 1.3.
3007 if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
3008 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
3009 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
3010 return false;
3011 }
3012
3013 // Note extension callbacks may run in any order, so we defer checking
3014 // consistency with ALPN to |ssl_check_serverhello_tlsext|.
3015 if (!hs->new_session->peer_application_settings.CopyFrom(in: *contents)) {
3016 *out_alert = SSL_AD_INTERNAL_ERROR;
3017 return false;
3018 }
3019
3020 hs->new_session->has_application_settings = true;
3021 return true;
3022}
3023
3024static bool ext_alps_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
3025 SSL *const ssl = hs->ssl;
3026 // If early data is accepted, we omit the ALPS extension. It is implicitly
3027 // carried over from the previous connection.
3028 if (hs->new_session == nullptr ||
3029 !hs->new_session->has_application_settings ||
3030 ssl->s3->early_data_accepted) {
3031 return true;
3032 }
3033
3034 CBB contents;
3035 if (!CBB_add_u16(cbb: out, TLSEXT_TYPE_application_settings) ||
3036 !CBB_add_u16_length_prefixed(cbb: out, out_contents: &contents) ||
3037 !CBB_add_bytes(cbb: &contents,
3038 data: hs->new_session->local_application_settings.data(),
3039 len: hs->new_session->local_application_settings.size()) ||
3040 !CBB_flush(cbb: out)) {
3041 return false;
3042 }
3043
3044 return true;
3045}
3046
3047bool ssl_negotiate_alps(SSL_HANDSHAKE *hs, uint8_t *out_alert,
3048 const SSL_CLIENT_HELLO *client_hello) {
3049 SSL *const ssl = hs->ssl;
3050 if (ssl->s3->alpn_selected.empty()) {
3051 return true;
3052 }
3053
3054 // If we negotiate ALPN over TLS 1.3, try to negotiate ALPS.
3055 CBS alps_contents;
3056 Span<const uint8_t> settings;
3057 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
3058 ssl_get_local_application_settings(hs, out_settings: &settings,
3059 protocol: ssl->s3->alpn_selected) &&
3060 ssl_client_hello_get_extension(client_hello, out: &alps_contents,
3061 TLSEXT_TYPE_application_settings)) {
3062 // Check if the client supports ALPS with the selected ALPN.
3063 bool found = false;
3064 CBS alps_list;
3065 if (!CBS_get_u16_length_prefixed(cbs: &alps_contents, out: &alps_list) ||
3066 CBS_len(cbs: &alps_contents) != 0 ||
3067 CBS_len(cbs: &alps_list) == 0) {
3068 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
3069 *out_alert = SSL_AD_DECODE_ERROR;
3070 return false;
3071 }
3072 while (CBS_len(cbs: &alps_list) > 0) {
3073 CBS protocol_name;
3074 if (!CBS_get_u8_length_prefixed(cbs: &alps_list, out: &protocol_name) ||
3075 // Empty protocol names are forbidden.
3076 CBS_len(cbs: &protocol_name) == 0) {
3077 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
3078 *out_alert = SSL_AD_DECODE_ERROR;
3079 return false;
3080 }
3081 if (protocol_name == MakeConstSpan(c: ssl->s3->alpn_selected)) {
3082 found = true;
3083 }
3084 }
3085
3086 // Negotiate ALPS if both client also supports ALPS for this protocol.
3087 if (found) {
3088 hs->new_session->has_application_settings = true;
3089 if (!hs->new_session->local_application_settings.CopyFrom(in: settings)) {
3090 *out_alert = SSL_AD_INTERNAL_ERROR;
3091 return false;
3092 }
3093 }
3094 }
3095
3096 return true;
3097}
3098
3099// kExtensions contains all the supported extensions.
3100static const struct tls_extension kExtensions[] = {
3101 {
3102 TLSEXT_TYPE_server_name,
3103 .add_clienthello: ext_sni_add_clienthello,
3104 .parse_serverhello: ext_sni_parse_serverhello,
3105 .parse_clienthello: ext_sni_parse_clienthello,
3106 .add_serverhello: ext_sni_add_serverhello,
3107 },
3108 {
3109 TLSEXT_TYPE_encrypted_client_hello,
3110 .add_clienthello: ext_ech_add_clienthello,
3111 .parse_serverhello: ext_ech_parse_serverhello,
3112 .parse_clienthello: ext_ech_parse_clienthello,
3113 .add_serverhello: ext_ech_add_serverhello,
3114 },
3115 {
3116 TLSEXT_TYPE_extended_master_secret,
3117 .add_clienthello: ext_ems_add_clienthello,
3118 .parse_serverhello: ext_ems_parse_serverhello,
3119 .parse_clienthello: ext_ems_parse_clienthello,
3120 .add_serverhello: ext_ems_add_serverhello,
3121 },
3122 {
3123 TLSEXT_TYPE_renegotiate,
3124 .add_clienthello: ext_ri_add_clienthello,
3125 .parse_serverhello: ext_ri_parse_serverhello,
3126 .parse_clienthello: ext_ri_parse_clienthello,
3127 .add_serverhello: ext_ri_add_serverhello,
3128 },
3129 {
3130 TLSEXT_TYPE_supported_groups,
3131 .add_clienthello: ext_supported_groups_add_clienthello,
3132 .parse_serverhello: ext_supported_groups_parse_serverhello,
3133 .parse_clienthello: ext_supported_groups_parse_clienthello,
3134 .add_serverhello: dont_add_serverhello,
3135 },
3136 {
3137 TLSEXT_TYPE_ec_point_formats,
3138 .add_clienthello: ext_ec_point_add_clienthello,
3139 .parse_serverhello: ext_ec_point_parse_serverhello,
3140 .parse_clienthello: ext_ec_point_parse_clienthello,
3141 .add_serverhello: ext_ec_point_add_serverhello,
3142 },
3143 {
3144 TLSEXT_TYPE_session_ticket,
3145 .add_clienthello: ext_ticket_add_clienthello,
3146 .parse_serverhello: ext_ticket_parse_serverhello,
3147 // Ticket extension client parsing is handled in ssl_session.c
3148 .parse_clienthello: ignore_parse_clienthello,
3149 .add_serverhello: ext_ticket_add_serverhello,
3150 },
3151 {
3152 TLSEXT_TYPE_application_layer_protocol_negotiation,
3153 .add_clienthello: ext_alpn_add_clienthello,
3154 .parse_serverhello: ext_alpn_parse_serverhello,
3155 // ALPN is negotiated late in |ssl_negotiate_alpn|.
3156 .parse_clienthello: ignore_parse_clienthello,
3157 .add_serverhello: ext_alpn_add_serverhello,
3158 },
3159 {
3160 TLSEXT_TYPE_status_request,
3161 .add_clienthello: ext_ocsp_add_clienthello,
3162 .parse_serverhello: ext_ocsp_parse_serverhello,
3163 .parse_clienthello: ext_ocsp_parse_clienthello,
3164 .add_serverhello: ext_ocsp_add_serverhello,
3165 },
3166 {
3167 TLSEXT_TYPE_signature_algorithms,
3168 .add_clienthello: ext_sigalgs_add_clienthello,
3169 .parse_serverhello: forbid_parse_serverhello,
3170 .parse_clienthello: ext_sigalgs_parse_clienthello,
3171 .add_serverhello: dont_add_serverhello,
3172 },
3173 {
3174 TLSEXT_TYPE_next_proto_neg,
3175 .add_clienthello: ext_npn_add_clienthello,
3176 .parse_serverhello: ext_npn_parse_serverhello,
3177 .parse_clienthello: ext_npn_parse_clienthello,
3178 .add_serverhello: ext_npn_add_serverhello,
3179 },
3180 {
3181 TLSEXT_TYPE_certificate_timestamp,
3182 .add_clienthello: ext_sct_add_clienthello,
3183 .parse_serverhello: ext_sct_parse_serverhello,
3184 .parse_clienthello: ext_sct_parse_clienthello,
3185 .add_serverhello: ext_sct_add_serverhello,
3186 },
3187 {
3188 TLSEXT_TYPE_channel_id,
3189 .add_clienthello: ext_channel_id_add_clienthello,
3190 .parse_serverhello: ext_channel_id_parse_serverhello,
3191 .parse_clienthello: ext_channel_id_parse_clienthello,
3192 .add_serverhello: ext_channel_id_add_serverhello,
3193 },
3194 {
3195 TLSEXT_TYPE_srtp,
3196 .add_clienthello: ext_srtp_add_clienthello,
3197 .parse_serverhello: ext_srtp_parse_serverhello,
3198 .parse_clienthello: ext_srtp_parse_clienthello,
3199 .add_serverhello: ext_srtp_add_serverhello,
3200 },
3201 {
3202 TLSEXT_TYPE_key_share,
3203 .add_clienthello: ext_key_share_add_clienthello,
3204 .parse_serverhello: forbid_parse_serverhello,
3205 .parse_clienthello: ignore_parse_clienthello,
3206 .add_serverhello: dont_add_serverhello,
3207 },
3208 {
3209 TLSEXT_TYPE_psk_key_exchange_modes,
3210 .add_clienthello: ext_psk_key_exchange_modes_add_clienthello,
3211 .parse_serverhello: forbid_parse_serverhello,
3212 .parse_clienthello: ext_psk_key_exchange_modes_parse_clienthello,
3213 .add_serverhello: dont_add_serverhello,
3214 },
3215 {
3216 TLSEXT_TYPE_early_data,
3217 .add_clienthello: ext_early_data_add_clienthello,
3218 .parse_serverhello: ext_early_data_parse_serverhello,
3219 .parse_clienthello: ext_early_data_parse_clienthello,
3220 .add_serverhello: ext_early_data_add_serverhello,
3221 },
3222 {
3223 TLSEXT_TYPE_supported_versions,
3224 .add_clienthello: ext_supported_versions_add_clienthello,
3225 .parse_serverhello: forbid_parse_serverhello,
3226 .parse_clienthello: ignore_parse_clienthello,
3227 .add_serverhello: dont_add_serverhello,
3228 },
3229 {
3230 TLSEXT_TYPE_cookie,
3231 .add_clienthello: ext_cookie_add_clienthello,
3232 .parse_serverhello: forbid_parse_serverhello,
3233 .parse_clienthello: ignore_parse_clienthello,
3234 .add_serverhello: dont_add_serverhello,
3235 },
3236 {
3237 TLSEXT_TYPE_quic_transport_parameters,
3238 .add_clienthello: ext_quic_transport_params_add_clienthello,
3239 .parse_serverhello: ext_quic_transport_params_parse_serverhello,
3240 .parse_clienthello: ext_quic_transport_params_parse_clienthello,
3241 .add_serverhello: ext_quic_transport_params_add_serverhello,
3242 },
3243 {
3244 TLSEXT_TYPE_quic_transport_parameters_legacy,
3245 .add_clienthello: ext_quic_transport_params_add_clienthello_legacy,
3246 .parse_serverhello: ext_quic_transport_params_parse_serverhello_legacy,
3247 .parse_clienthello: ext_quic_transport_params_parse_clienthello_legacy,
3248 .add_serverhello: ext_quic_transport_params_add_serverhello_legacy,
3249 },
3250 {
3251 TLSEXT_TYPE_cert_compression,
3252 .add_clienthello: cert_compression_add_clienthello,
3253 .parse_serverhello: cert_compression_parse_serverhello,
3254 .parse_clienthello: cert_compression_parse_clienthello,
3255 .add_serverhello: cert_compression_add_serverhello,
3256 },
3257 {
3258 TLSEXT_TYPE_delegated_credential,
3259 .add_clienthello: ext_delegated_credential_add_clienthello,
3260 .parse_serverhello: forbid_parse_serverhello,
3261 .parse_clienthello: ext_delegated_credential_parse_clienthello,
3262 .add_serverhello: dont_add_serverhello,
3263 },
3264 {
3265 TLSEXT_TYPE_application_settings,
3266 .add_clienthello: ext_alps_add_clienthello,
3267 .parse_serverhello: ext_alps_parse_serverhello,
3268 // ALPS is negotiated late in |ssl_negotiate_alpn|.
3269 .parse_clienthello: ignore_parse_clienthello,
3270 .add_serverhello: ext_alps_add_serverhello,
3271 },
3272};
3273
3274#define kNumExtensions (sizeof(kExtensions) / sizeof(struct tls_extension))
3275
3276static_assert(kNumExtensions <=
3277 sizeof(((SSL_HANDSHAKE *)NULL)->extensions.sent) * 8,
3278 "too many extensions for sent bitset");
3279static_assert(kNumExtensions <=
3280 sizeof(((SSL_HANDSHAKE *)NULL)->extensions.received) * 8,
3281 "too many extensions for received bitset");
3282
3283bool ssl_setup_extension_permutation(SSL_HANDSHAKE *hs) {
3284 if (!hs->config->permute_extensions) {
3285 return true;
3286 }
3287
3288 static_assert(kNumExtensions <= UINT8_MAX,
3289 "extensions_permutation type is too small");
3290 uint32_t seeds[kNumExtensions - 1];
3291 Array<uint8_t> permutation;
3292 if (!RAND_bytes(buf: reinterpret_cast<uint8_t *>(seeds), len: sizeof(seeds)) ||
3293 !permutation.Init(kNumExtensions)) {
3294 return false;
3295 }
3296 for (size_t i = 0; i < kNumExtensions; i++) {
3297 permutation[i] = i;
3298 }
3299 for (size_t i = kNumExtensions - 1; i > 0; i--) {
3300 // Set element |i| to a randomly-selected element 0 <= j <= i.
3301 std::swap(x&: permutation[i], y&: permutation[seeds[i - 1] % (i + 1)]);
3302 }
3303 hs->extension_permutation = std::move(permutation);
3304 return true;
3305}
3306
3307static const struct tls_extension *tls_extension_find(uint32_t *out_index,
3308 uint16_t value) {
3309 unsigned i;
3310 for (i = 0; i < kNumExtensions; i++) {
3311 if (kExtensions[i].value == value) {
3312 *out_index = i;
3313 return &kExtensions[i];
3314 }
3315 }
3316
3317 return NULL;
3318}
3319
3320static bool add_padding_extension(CBB *cbb, uint16_t ext, size_t len) {
3321 CBB child;
3322 if (!CBB_add_u16(cbb, value: ext) || //
3323 !CBB_add_u16_length_prefixed(cbb, out_contents: &child) ||
3324 !CBB_add_zeros(cbb: &child, len)) {
3325 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3326 return false;
3327 }
3328 return CBB_flush(cbb);
3329}
3330
3331static bool ssl_add_clienthello_tlsext_inner(SSL_HANDSHAKE *hs, CBB *out,
3332 CBB *out_encoded,
3333 bool *out_needs_psk_binder) {
3334 // When writing ClientHelloInner, we construct the real and encoded
3335 // ClientHellos concurrently, to handle compression. Uncompressed extensions
3336 // are written to |extensions| and copied to |extensions_encoded|. Compressed
3337 // extensions are buffered in |compressed| and written to the end. (ECH can
3338 // only compress continguous extensions.)
3339 SSL *const ssl = hs->ssl;
3340 bssl::ScopedCBB compressed, outer_extensions;
3341 CBB extensions, extensions_encoded;
3342 if (!CBB_add_u16_length_prefixed(cbb: out, out_contents: &extensions) ||
3343 !CBB_add_u16_length_prefixed(cbb: out_encoded, out_contents: &extensions_encoded) ||
3344 !CBB_init(cbb: compressed.get(), initial_capacity: 64) ||
3345 !CBB_init(cbb: outer_extensions.get(), initial_capacity: 64)) {
3346 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3347 return false;
3348 }
3349
3350 hs->inner_extensions_sent = 0;
3351
3352 if (ssl->ctx->grease_enabled) {
3353 // Add a fake empty extension. See RFC 8701. This always matches
3354 // |ssl_add_clienthello_tlsext|, so compress it.
3355 uint16_t grease_ext = ssl_get_grease_value(hs, index: ssl_grease_extension1);
3356 if (!add_padding_extension(cbb: compressed.get(), ext: grease_ext, len: 0) ||
3357 !CBB_add_u16(cbb: outer_extensions.get(), value: grease_ext)) {
3358 return false;
3359 }
3360 }
3361
3362 for (size_t unpermuted = 0; unpermuted < kNumExtensions; unpermuted++) {
3363 size_t i = hs->extension_permutation.empty()
3364 ? unpermuted
3365 : hs->extension_permutation[unpermuted];
3366 const size_t len_before = CBB_len(cbb: &extensions);
3367 const size_t len_compressed_before = CBB_len(cbb: compressed.get());
3368 if (!kExtensions[i].add_clienthello(hs, &extensions, compressed.get(),
3369 ssl_client_hello_inner)) {
3370 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3371 ERR_add_error_dataf(format: "extension %u", (unsigned)kExtensions[i].value);
3372 return false;
3373 }
3374
3375 const size_t bytes_written = CBB_len(cbb: &extensions) - len_before;
3376 const size_t bytes_written_compressed =
3377 CBB_len(cbb: compressed.get()) - len_compressed_before;
3378 // The callback may write to at most one output.
3379 assert(bytes_written == 0 || bytes_written_compressed == 0);
3380 if (bytes_written != 0 || bytes_written_compressed != 0) {
3381 hs->inner_extensions_sent |= (1u << i);
3382 }
3383 // If compressed, update the running ech_outer_extensions extension.
3384 if (bytes_written_compressed != 0 &&
3385 !CBB_add_u16(cbb: outer_extensions.get(), value: kExtensions[i].value)) {
3386 return false;
3387 }
3388 }
3389
3390 if (ssl->ctx->grease_enabled) {
3391 // Add a fake non-empty extension. See RFC 8701. This always matches
3392 // |ssl_add_clienthello_tlsext|, so compress it.
3393 uint16_t grease_ext = ssl_get_grease_value(hs, index: ssl_grease_extension2);
3394 if (!add_padding_extension(cbb: compressed.get(), ext: grease_ext, len: 1) ||
3395 !CBB_add_u16(cbb: outer_extensions.get(), value: grease_ext)) {
3396 return false;
3397 }
3398 }
3399
3400 // Uncompressed extensions are encoded as-is.
3401 if (!CBB_add_bytes(cbb: &extensions_encoded, data: CBB_data(cbb: &extensions),
3402 len: CBB_len(cbb: &extensions))) {
3403 return false;
3404 }
3405
3406 // Flush all the compressed extensions.
3407 if (CBB_len(cbb: compressed.get()) != 0) {
3408 CBB extension, child;
3409 // Copy them as-is in the real ClientHelloInner.
3410 if (!CBB_add_bytes(cbb: &extensions, data: CBB_data(cbb: compressed.get()),
3411 len: CBB_len(cbb: compressed.get())) ||
3412 // Replace with ech_outer_extensions in the encoded form.
3413 !CBB_add_u16(cbb: &extensions_encoded, TLSEXT_TYPE_ech_outer_extensions) ||
3414 !CBB_add_u16_length_prefixed(cbb: &extensions_encoded, out_contents: &extension) ||
3415 !CBB_add_u8_length_prefixed(cbb: &extension, out_contents: &child) ||
3416 !CBB_add_bytes(cbb: &child, data: CBB_data(cbb: outer_extensions.get()),
3417 len: CBB_len(cbb: outer_extensions.get())) ||
3418 !CBB_flush(cbb: &extensions_encoded)) {
3419 return false;
3420 }
3421 }
3422
3423 // The PSK extension must be last. It is never compressed. Note, if there is a
3424 // binder, the caller will need to update both ClientHelloInner and
3425 // EncodedClientHelloInner after computing it.
3426 const size_t len_before = CBB_len(cbb: &extensions);
3427 if (!ext_pre_shared_key_add_clienthello(hs, out: &extensions, out_needs_binder: out_needs_psk_binder,
3428 type: ssl_client_hello_inner) ||
3429 !CBB_add_bytes(cbb: &extensions_encoded, data: CBB_data(cbb: &extensions) + len_before,
3430 len: CBB_len(cbb: &extensions) - len_before) ||
3431 !CBB_flush(cbb: out) || //
3432 !CBB_flush(cbb: out_encoded)) {
3433 return false;
3434 }
3435
3436 return true;
3437}
3438
3439bool ssl_add_clienthello_tlsext(SSL_HANDSHAKE *hs, CBB *out, CBB *out_encoded,
3440 bool *out_needs_psk_binder,
3441 ssl_client_hello_type_t type,
3442 size_t header_len) {
3443 *out_needs_psk_binder = false;
3444
3445 if (type == ssl_client_hello_inner) {
3446 return ssl_add_clienthello_tlsext_inner(hs, out, out_encoded,
3447 out_needs_psk_binder);
3448 }
3449
3450 assert(out_encoded == nullptr); // Only ClientHelloInner needs two outputs.
3451 SSL *const ssl = hs->ssl;
3452 CBB extensions;
3453 if (!CBB_add_u16_length_prefixed(cbb: out, out_contents: &extensions)) {
3454 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3455 return false;
3456 }
3457
3458 // Note we may send multiple ClientHellos for DTLS HelloVerifyRequest and TLS
3459 // 1.3 HelloRetryRequest. For the latter, the extensions may change, so it is
3460 // important to reset this value.
3461 hs->extensions.sent = 0;
3462
3463 // Add a fake empty extension. See RFC 8701.
3464 if (ssl->ctx->grease_enabled &&
3465 !add_padding_extension(
3466 cbb: &extensions, ext: ssl_get_grease_value(hs, index: ssl_grease_extension1), len: 0)) {
3467 return false;
3468 }
3469
3470 bool last_was_empty = false;
3471 for (size_t unpermuted = 0; unpermuted < kNumExtensions; unpermuted++) {
3472 size_t i = hs->extension_permutation.empty()
3473 ? unpermuted
3474 : hs->extension_permutation[unpermuted];
3475 const size_t len_before = CBB_len(cbb: &extensions);
3476 if (!kExtensions[i].add_clienthello(hs, &extensions, &extensions, type)) {
3477 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3478 ERR_add_error_dataf(format: "extension %u", (unsigned)kExtensions[i].value);
3479 return false;
3480 }
3481
3482 const size_t bytes_written = CBB_len(cbb: &extensions) - len_before;
3483 if (bytes_written != 0) {
3484 hs->extensions.sent |= (1u << i);
3485 }
3486 // If the difference in lengths is only four bytes then the extension had
3487 // an empty body.
3488 last_was_empty = (bytes_written == 4);
3489 }
3490
3491 if (ssl->ctx->grease_enabled) {
3492 // Add a fake non-empty extension. See RFC 8701.
3493 if (!add_padding_extension(
3494 cbb: &extensions, ext: ssl_get_grease_value(hs, index: ssl_grease_extension2), len: 1)) {
3495 return false;
3496 }
3497 last_was_empty = false;
3498 }
3499
3500 // In cleartext ClientHellos, we add the padding extension to work around
3501 // bugs. We also apply this padding to ClientHelloOuter, to keep the wire
3502 // images aligned.
3503 size_t psk_extension_len = ext_pre_shared_key_clienthello_length(hs, type);
3504 if (!SSL_is_dtls(ssl) && !ssl->quic_method &&
3505 !ssl->s3->used_hello_retry_request) {
3506 header_len +=
3507 SSL3_HM_HEADER_LENGTH + 2 + CBB_len(cbb: &extensions) + psk_extension_len;
3508 size_t padding_len = 0;
3509
3510 // The final extension must be non-empty. WebSphere Application
3511 // Server 7.0 is intolerant to the last extension being zero-length. See
3512 // https://crbug.com/363583.
3513 if (last_was_empty && psk_extension_len == 0) {
3514 padding_len = 1;
3515 // The addition of the padding extension may push us into the F5 bug.
3516 header_len += 4 + padding_len;
3517 }
3518
3519 // Add padding to workaround bugs in F5 terminators. See RFC 7685.
3520 //
3521 // NB: because this code works out the length of all existing extensions
3522 // it MUST always appear last (save for any PSK extension).
3523 if (header_len > 0xff && header_len < 0x200) {
3524 // If our calculations already included a padding extension, remove that
3525 // factor because we're about to change its length.
3526 if (padding_len != 0) {
3527 header_len -= 4 + padding_len;
3528 }
3529 padding_len = 0x200 - header_len;
3530 // Extensions take at least four bytes to encode. Always include at least
3531 // one byte of data if including the extension. WebSphere Application
3532 // Server 7.0 is intolerant to the last extension being zero-length. See
3533 // https://crbug.com/363583.
3534 if (padding_len >= 4 + 1) {
3535 padding_len -= 4;
3536 } else {
3537 padding_len = 1;
3538 }
3539 }
3540
3541 if (padding_len != 0 &&
3542 !add_padding_extension(cbb: &extensions, TLSEXT_TYPE_padding, len: padding_len)) {
3543 return false;
3544 }
3545 }
3546
3547 // The PSK extension must be last, including after the padding.
3548 const size_t len_before = CBB_len(cbb: &extensions);
3549 if (!ext_pre_shared_key_add_clienthello(hs, out: &extensions, out_needs_binder: out_needs_psk_binder,
3550 type)) {
3551 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3552 return false;
3553 }
3554 assert(psk_extension_len == CBB_len(&extensions) - len_before);
3555 (void)len_before; // |assert| is omitted in release builds.
3556
3557 // Discard empty extensions blocks.
3558 if (CBB_len(cbb: &extensions) == 0) {
3559 CBB_discard_child(cbb: out);
3560 }
3561
3562 return CBB_flush(cbb: out);
3563}
3564
3565bool ssl_add_serverhello_tlsext(SSL_HANDSHAKE *hs, CBB *out) {
3566 SSL *const ssl = hs->ssl;
3567 CBB extensions;
3568 if (!CBB_add_u16_length_prefixed(cbb: out, out_contents: &extensions)) {
3569 goto err;
3570 }
3571
3572 for (unsigned i = 0; i < kNumExtensions; i++) {
3573 if (!(hs->extensions.received & (1u << i))) {
3574 // Don't send extensions that were not received.
3575 continue;
3576 }
3577
3578 if (!kExtensions[i].add_serverhello(hs, &extensions)) {
3579 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3580 ERR_add_error_dataf(format: "extension %u", (unsigned)kExtensions[i].value);
3581 goto err;
3582 }
3583 }
3584
3585 // Discard empty extensions blocks before TLS 1.3.
3586 if (ssl_protocol_version(ssl) < TLS1_3_VERSION &&
3587 CBB_len(cbb: &extensions) == 0) {
3588 CBB_discard_child(cbb: out);
3589 }
3590
3591 return CBB_flush(cbb: out);
3592
3593err:
3594 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3595 return false;
3596}
3597
3598static bool ssl_scan_clienthello_tlsext(SSL_HANDSHAKE *hs,
3599 const SSL_CLIENT_HELLO *client_hello,
3600 int *out_alert) {
3601 hs->extensions.received = 0;
3602 CBS extensions;
3603 CBS_init(cbs: &extensions, data: client_hello->extensions, len: client_hello->extensions_len);
3604 while (CBS_len(cbs: &extensions) != 0) {
3605 uint16_t type;
3606 CBS extension;
3607
3608 // Decode the next extension.
3609 if (!CBS_get_u16(cbs: &extensions, out: &type) ||
3610 !CBS_get_u16_length_prefixed(cbs: &extensions, out: &extension)) {
3611 *out_alert = SSL_AD_DECODE_ERROR;
3612 return false;
3613 }
3614
3615 unsigned ext_index;
3616 const struct tls_extension *const ext =
3617 tls_extension_find(out_index: &ext_index, value: type);
3618 if (ext == NULL) {
3619 continue;
3620 }
3621
3622 hs->extensions.received |= (1u << ext_index);
3623 uint8_t alert = SSL_AD_DECODE_ERROR;
3624 if (!ext->parse_clienthello(hs, &alert, &extension)) {
3625 *out_alert = alert;
3626 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
3627 ERR_add_error_dataf(format: "extension %u", (unsigned)type);
3628 return false;
3629 }
3630 }
3631
3632 for (size_t i = 0; i < kNumExtensions; i++) {
3633 if (hs->extensions.received & (1u << i)) {
3634 continue;
3635 }
3636
3637 CBS *contents = NULL, fake_contents;
3638 static const uint8_t kFakeRenegotiateExtension[] = {0};
3639 if (kExtensions[i].value == TLSEXT_TYPE_renegotiate &&
3640 ssl_client_cipher_list_contains_cipher(client_hello,
3641 SSL3_CK_SCSV & 0xffff)) {
3642 // The renegotiation SCSV was received so pretend that we received a
3643 // renegotiation extension.
3644 CBS_init(cbs: &fake_contents, data: kFakeRenegotiateExtension,
3645 len: sizeof(kFakeRenegotiateExtension));
3646 contents = &fake_contents;
3647 hs->extensions.received |= (1u << i);
3648 }
3649
3650 // Extension wasn't observed so call the callback with a NULL
3651 // parameter.
3652 uint8_t alert = SSL_AD_DECODE_ERROR;
3653 if (!kExtensions[i].parse_clienthello(hs, &alert, contents)) {
3654 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
3655 ERR_add_error_dataf(format: "extension %u", (unsigned)kExtensions[i].value);
3656 *out_alert = alert;
3657 return false;
3658 }
3659 }
3660
3661 return true;
3662}
3663
3664bool ssl_parse_clienthello_tlsext(SSL_HANDSHAKE *hs,
3665 const SSL_CLIENT_HELLO *client_hello) {
3666 SSL *const ssl = hs->ssl;
3667 int alert = SSL_AD_DECODE_ERROR;
3668 if (!ssl_scan_clienthello_tlsext(hs, client_hello, out_alert: &alert)) {
3669 ssl_send_alert(ssl, SSL3_AL_FATAL, desc: alert);
3670 return false;
3671 }
3672
3673 if (!ssl_check_clienthello_tlsext(hs)) {
3674 OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_TLSEXT);
3675 return false;
3676 }
3677
3678 return true;
3679}
3680
3681static bool ssl_scan_serverhello_tlsext(SSL_HANDSHAKE *hs, const CBS *cbs,
3682 int *out_alert) {
3683 CBS extensions = *cbs;
3684 if (!tls1_check_duplicate_extensions(cbs: &extensions)) {
3685 *out_alert = SSL_AD_DECODE_ERROR;
3686 return false;
3687 }
3688
3689 uint32_t received = 0;
3690 while (CBS_len(cbs: &extensions) != 0) {
3691 uint16_t type;
3692 CBS extension;
3693
3694 // Decode the next extension.
3695 if (!CBS_get_u16(cbs: &extensions, out: &type) ||
3696 !CBS_get_u16_length_prefixed(cbs: &extensions, out: &extension)) {
3697 *out_alert = SSL_AD_DECODE_ERROR;
3698 return false;
3699 }
3700
3701 unsigned ext_index;
3702 const struct tls_extension *const ext =
3703 tls_extension_find(out_index: &ext_index, value: type);
3704
3705 if (ext == NULL) {
3706 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
3707 ERR_add_error_dataf(format: "extension %u", (unsigned)type);
3708 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
3709 return false;
3710 }
3711
3712 static_assert(kNumExtensions <= sizeof(hs->extensions.sent) * 8,
3713 "too many bits");
3714
3715 if (!(hs->extensions.sent & (1u << ext_index))) {
3716 // If the extension was never sent then it is illegal.
3717 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
3718 ERR_add_error_dataf(format: "extension :%u", (unsigned)type);
3719 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
3720 return false;
3721 }
3722
3723 received |= (1u << ext_index);
3724
3725 uint8_t alert = SSL_AD_DECODE_ERROR;
3726 if (!ext->parse_serverhello(hs, &alert, &extension)) {
3727 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
3728 ERR_add_error_dataf(format: "extension %u", (unsigned)type);
3729 *out_alert = alert;
3730 return false;
3731 }
3732 }
3733
3734 for (size_t i = 0; i < kNumExtensions; i++) {
3735 if (!(received & (1u << i))) {
3736 // Extension wasn't observed so call the callback with a NULL
3737 // parameter.
3738 uint8_t alert = SSL_AD_DECODE_ERROR;
3739 if (!kExtensions[i].parse_serverhello(hs, &alert, NULL)) {
3740 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
3741 ERR_add_error_dataf(format: "extension %u", (unsigned)kExtensions[i].value);
3742 *out_alert = alert;
3743 return false;
3744 }
3745 }
3746 }
3747
3748 return true;
3749}
3750
3751static bool ssl_check_clienthello_tlsext(SSL_HANDSHAKE *hs) {
3752 SSL *const ssl = hs->ssl;
3753 int ret = SSL_TLSEXT_ERR_NOACK;
3754 int al = SSL_AD_UNRECOGNIZED_NAME;
3755 if (ssl->ctx->servername_callback != 0) {
3756 ret = ssl->ctx->servername_callback(ssl, &al, ssl->ctx->servername_arg);
3757 } else if (ssl->session_ctx->servername_callback != 0) {
3758 ret = ssl->session_ctx->servername_callback(
3759 ssl, &al, ssl->session_ctx->servername_arg);
3760 }
3761
3762 switch (ret) {
3763 case SSL_TLSEXT_ERR_ALERT_FATAL:
3764 ssl_send_alert(ssl, SSL3_AL_FATAL, desc: al);
3765 return false;
3766
3767 case SSL_TLSEXT_ERR_NOACK:
3768 hs->should_ack_sni = false;
3769 return true;
3770
3771 default:
3772 return true;
3773 }
3774}
3775
3776static bool ssl_check_serverhello_tlsext(SSL_HANDSHAKE *hs) {
3777 SSL *const ssl = hs->ssl;
3778 // ALPS and ALPN have a dependency between each other, so we defer checking
3779 // consistency to after the callbacks run.
3780 if (hs->new_session != nullptr && hs->new_session->has_application_settings) {
3781 // ALPN must be negotiated.
3782 if (ssl->s3->alpn_selected.empty()) {
3783 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_ALPS_WITHOUT_ALPN);
3784 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
3785 return false;
3786 }
3787
3788 // The negotiated protocol must be one of the ones we advertised for ALPS.
3789 Span<const uint8_t> settings;
3790 if (!ssl_get_local_application_settings(hs, out_settings: &settings,
3791 protocol: ssl->s3->alpn_selected)) {
3792 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
3793 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
3794 return false;
3795 }
3796
3797 if (!hs->new_session->local_application_settings.CopyFrom(in: settings)) {
3798 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3799 return false;
3800 }
3801 }
3802
3803 return true;
3804}
3805
3806bool ssl_parse_serverhello_tlsext(SSL_HANDSHAKE *hs, const CBS *cbs) {
3807 SSL *const ssl = hs->ssl;
3808 int alert = SSL_AD_DECODE_ERROR;
3809 if (!ssl_scan_serverhello_tlsext(hs, cbs, out_alert: &alert)) {
3810 ssl_send_alert(ssl, SSL3_AL_FATAL, desc: alert);
3811 return false;
3812 }
3813
3814 if (!ssl_check_serverhello_tlsext(hs)) {
3815 return false;
3816 }
3817
3818 return true;
3819}
3820
3821static enum ssl_ticket_aead_result_t decrypt_ticket_with_cipher_ctx(
3822 Array<uint8_t> *out, EVP_CIPHER_CTX *cipher_ctx, HMAC_CTX *hmac_ctx,
3823 Span<const uint8_t> ticket) {
3824 size_t iv_len = EVP_CIPHER_CTX_iv_length(ctx: cipher_ctx);
3825
3826 // Check the MAC at the end of the ticket.
3827 uint8_t mac[EVP_MAX_MD_SIZE];
3828 size_t mac_len = HMAC_size(ctx: hmac_ctx);
3829 if (ticket.size() < SSL_TICKET_KEY_NAME_LEN + iv_len + 1 + mac_len) {
3830 // The ticket must be large enough for key name, IV, data, and MAC.
3831 return ssl_ticket_aead_ignore_ticket;
3832 }
3833 // Split the ticket into the ticket and the MAC.
3834 auto ticket_mac = ticket.last(len: mac_len);
3835 ticket = ticket.first(len: ticket.size() - mac_len);
3836 HMAC_Update(ctx: hmac_ctx, data: ticket.data(), data_len: ticket.size());
3837 HMAC_Final(ctx: hmac_ctx, out: mac, NULL);
3838 assert(mac_len == ticket_mac.size());
3839 bool mac_ok = CRYPTO_memcmp(a: mac, b: ticket_mac.data(), len: mac_len) == 0;
3840#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
3841 mac_ok = true;
3842#endif
3843 if (!mac_ok) {
3844 return ssl_ticket_aead_ignore_ticket;
3845 }
3846
3847 // Decrypt the session data.
3848 auto ciphertext = ticket.subspan(SSL_TICKET_KEY_NAME_LEN + iv_len);
3849 Array<uint8_t> plaintext;
3850#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
3851 if (!plaintext.CopyFrom(ciphertext)) {
3852 return ssl_ticket_aead_error;
3853 }
3854#else
3855 if (ciphertext.size() >= INT_MAX) {
3856 return ssl_ticket_aead_ignore_ticket;
3857 }
3858 if (!plaintext.Init(new_size: ciphertext.size())) {
3859 return ssl_ticket_aead_error;
3860 }
3861 int len1, len2;
3862 if (!EVP_DecryptUpdate(ctx: cipher_ctx, out: plaintext.data(), out_len: &len1, in: ciphertext.data(),
3863 in_len: (int)ciphertext.size()) ||
3864 !EVP_DecryptFinal_ex(ctx: cipher_ctx, out: plaintext.data() + len1, out_len: &len2)) {
3865 ERR_clear_error();
3866 return ssl_ticket_aead_ignore_ticket;
3867 }
3868 plaintext.Shrink(new_size: static_cast<size_t>(len1) + len2);
3869#endif
3870
3871 *out = std::move(plaintext);
3872 return ssl_ticket_aead_success;
3873}
3874
3875static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_cb(
3876 SSL_HANDSHAKE *hs, Array<uint8_t> *out, bool *out_renew_ticket,
3877 Span<const uint8_t> ticket) {
3878 assert(ticket.size() >= SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH);
3879 ScopedEVP_CIPHER_CTX cipher_ctx;
3880 ScopedHMAC_CTX hmac_ctx;
3881 auto name = ticket.subspan(pos: 0, SSL_TICKET_KEY_NAME_LEN);
3882 // The actual IV is shorter, but the length is determined by the callback's
3883 // chosen cipher. Instead we pass in |EVP_MAX_IV_LENGTH| worth of IV to ensure
3884 // the callback has enough.
3885 auto iv = ticket.subspan(SSL_TICKET_KEY_NAME_LEN, EVP_MAX_IV_LENGTH);
3886 int cb_ret = hs->ssl->session_ctx->ticket_key_cb(
3887 hs->ssl, const_cast<uint8_t *>(name.data()),
3888 const_cast<uint8_t *>(iv.data()), cipher_ctx.get(), hmac_ctx.get(),
3889 0 /* decrypt */);
3890 if (cb_ret < 0) {
3891 return ssl_ticket_aead_error;
3892 } else if (cb_ret == 0) {
3893 return ssl_ticket_aead_ignore_ticket;
3894 } else if (cb_ret == 2) {
3895 *out_renew_ticket = true;
3896 } else {
3897 assert(cb_ret == 1);
3898 }
3899 return decrypt_ticket_with_cipher_ctx(out, cipher_ctx: cipher_ctx.get(), hmac_ctx: hmac_ctx.get(),
3900 ticket);
3901}
3902
3903static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_ticket_keys(
3904 SSL_HANDSHAKE *hs, Array<uint8_t> *out, Span<const uint8_t> ticket) {
3905 assert(ticket.size() >= SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH);
3906 SSL_CTX *ctx = hs->ssl->session_ctx.get();
3907
3908 // Rotate the ticket key if necessary.
3909 if (!ssl_ctx_rotate_ticket_encryption_key(ctx)) {
3910 return ssl_ticket_aead_error;
3911 }
3912
3913 const EVP_CIPHER *cipher = EVP_aes_128_cbc();
3914 auto name = ticket.subspan(pos: 0, SSL_TICKET_KEY_NAME_LEN);
3915 auto iv =
3916 ticket.subspan(SSL_TICKET_KEY_NAME_LEN, len: EVP_CIPHER_iv_length(cipher));
3917
3918 // Pick the matching ticket key and decrypt.
3919 ScopedEVP_CIPHER_CTX cipher_ctx;
3920 ScopedHMAC_CTX hmac_ctx;
3921 {
3922 MutexReadLock lock(&ctx->lock);
3923 const TicketKey *key;
3924 if (ctx->ticket_key_current && name == ctx->ticket_key_current->name) {
3925 key = ctx->ticket_key_current.get();
3926 } else if (ctx->ticket_key_prev && name == ctx->ticket_key_prev->name) {
3927 key = ctx->ticket_key_prev.get();
3928 } else {
3929 return ssl_ticket_aead_ignore_ticket;
3930 }
3931 if (!HMAC_Init_ex(ctx: hmac_ctx.get(), key: key->hmac_key, key_len: sizeof(key->hmac_key),
3932 tlsext_tick_md(), NULL) ||
3933 !EVP_DecryptInit_ex(ctx: cipher_ctx.get(), cipher, NULL,
3934 key: key->aes_key, iv: iv.data())) {
3935 return ssl_ticket_aead_error;
3936 }
3937 }
3938 return decrypt_ticket_with_cipher_ctx(out, cipher_ctx: cipher_ctx.get(), hmac_ctx: hmac_ctx.get(),
3939 ticket);
3940}
3941
3942static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_method(
3943 SSL_HANDSHAKE *hs, Array<uint8_t> *out, bool *out_renew_ticket,
3944 Span<const uint8_t> ticket) {
3945 Array<uint8_t> plaintext;
3946 if (!plaintext.Init(new_size: ticket.size())) {
3947 return ssl_ticket_aead_error;
3948 }
3949
3950 size_t plaintext_len;
3951 const enum ssl_ticket_aead_result_t result =
3952 hs->ssl->session_ctx->ticket_aead_method->open(
3953 hs->ssl, plaintext.data(), &plaintext_len, ticket.size(),
3954 ticket.data(), ticket.size());
3955 if (result != ssl_ticket_aead_success) {
3956 return result;
3957 }
3958
3959 plaintext.Shrink(new_size: plaintext_len);
3960 *out = std::move(plaintext);
3961 return ssl_ticket_aead_success;
3962}
3963
3964enum ssl_ticket_aead_result_t ssl_process_ticket(
3965 SSL_HANDSHAKE *hs, UniquePtr<SSL_SESSION> *out_session,
3966 bool *out_renew_ticket, Span<const uint8_t> ticket,
3967 Span<const uint8_t> session_id) {
3968 SSL *const ssl = hs->ssl;
3969 *out_renew_ticket = false;
3970 out_session->reset();
3971
3972 if ((SSL_get_options(ssl: hs->ssl) & SSL_OP_NO_TICKET) ||
3973 session_id.size() > SSL_MAX_SSL_SESSION_ID_LENGTH) {
3974 return ssl_ticket_aead_ignore_ticket;
3975 }
3976
3977 // Tickets in TLS 1.3 are tied into pre-shared keys (PSKs), unlike in TLS 1.2
3978 // where that concept doesn't exist. The |decrypted_psk| and |ignore_psk|
3979 // hints only apply to PSKs. We check the version to determine which this is.
3980 const bool is_psk = ssl_protocol_version(ssl) >= TLS1_3_VERSION;
3981
3982 Array<uint8_t> plaintext;
3983 enum ssl_ticket_aead_result_t result;
3984 SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
3985 if (is_psk && hints && !hs->hints_requested &&
3986 !hints->decrypted_psk.empty()) {
3987 result = plaintext.CopyFrom(in: hints->decrypted_psk) ? ssl_ticket_aead_success
3988 : ssl_ticket_aead_error;
3989 } else if (is_psk && hints && !hs->hints_requested && hints->ignore_psk) {
3990 result = ssl_ticket_aead_ignore_ticket;
3991 } else if (!is_psk && hints && !hs->hints_requested &&
3992 !hints->decrypted_ticket.empty()) {
3993 if (plaintext.CopyFrom(in: hints->decrypted_ticket)) {
3994 result = ssl_ticket_aead_success;
3995 *out_renew_ticket = hints->renew_ticket;
3996 } else {
3997 result = ssl_ticket_aead_error;
3998 }
3999 } else if (!is_psk && hints && !hs->hints_requested && hints->ignore_ticket) {
4000 result = ssl_ticket_aead_ignore_ticket;
4001 } else if (ssl->session_ctx->ticket_aead_method != NULL) {
4002 result = ssl_decrypt_ticket_with_method(hs, out: &plaintext, out_renew_ticket,
4003 ticket);
4004 } else {
4005 // Ensure there is room for the key name and the largest IV |ticket_key_cb|
4006 // may try to consume. The real limit may be lower, but the maximum IV
4007 // length should be well under the minimum size for the session material and
4008 // HMAC.
4009 if (ticket.size() < SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH) {
4010 result = ssl_ticket_aead_ignore_ticket;
4011 } else if (ssl->session_ctx->ticket_key_cb != NULL) {
4012 result =
4013 ssl_decrypt_ticket_with_cb(hs, out: &plaintext, out_renew_ticket, ticket);
4014 } else {
4015 result = ssl_decrypt_ticket_with_ticket_keys(hs, out: &plaintext, ticket);
4016 }
4017 }
4018
4019 if (hints && hs->hints_requested) {
4020 if (result == ssl_ticket_aead_ignore_ticket) {
4021 if (is_psk) {
4022 hints->ignore_psk = true;
4023 } else {
4024 hints->ignore_ticket = true;
4025 }
4026 } else if (result == ssl_ticket_aead_success) {
4027 if (is_psk) {
4028 if (!hints->decrypted_psk.CopyFrom(in: plaintext)) {
4029 return ssl_ticket_aead_error;
4030 }
4031 } else {
4032 if (!hints->decrypted_ticket.CopyFrom(in: plaintext)) {
4033 return ssl_ticket_aead_error;
4034 }
4035 hints->renew_ticket = *out_renew_ticket;
4036 }
4037 }
4038 }
4039
4040 if (result != ssl_ticket_aead_success) {
4041 return result;
4042 }
4043
4044 // Decode the session.
4045 UniquePtr<SSL_SESSION> session(SSL_SESSION_from_bytes(
4046 in: plaintext.data(), in_len: plaintext.size(), ctx: ssl->ctx.get()));
4047 if (!session) {
4048 ERR_clear_error(); // Don't leave an error on the queue.
4049 return ssl_ticket_aead_ignore_ticket;
4050 }
4051
4052 // Envoy's tests expect the session to have a session ID that matches the
4053 // placeholder used by the client. It's unclear whether this is a good idea,
4054 // but we maintain it for now.
4055 SHA256(data: ticket.data(), len: ticket.size(), out: session->session_id);
4056 // Other consumers may expect a non-empty session ID to indicate resumption.
4057 session->session_id_length = SHA256_DIGEST_LENGTH;
4058
4059 *out_session = std::move(session);
4060 return ssl_ticket_aead_success;
4061}
4062
4063bool tls1_parse_peer_sigalgs(SSL_HANDSHAKE *hs, const CBS *in_sigalgs) {
4064 // Extension ignored for inappropriate versions
4065 if (ssl_protocol_version(ssl: hs->ssl) < TLS1_2_VERSION) {
4066 return true;
4067 }
4068
4069 // In all contexts, the signature algorithms list may not be empty. (It may be
4070 // omitted by clients in TLS 1.2, but then the entire extension is omitted.)
4071 return CBS_len(cbs: in_sigalgs) != 0 &&
4072 parse_u16_array(cbs: in_sigalgs, out: &hs->peer_sigalgs);
4073}
4074
4075bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey) {
4076 switch (EVP_PKEY_id(pkey)) {
4077 case EVP_PKEY_RSA:
4078 *out = SSL_SIGN_RSA_PKCS1_MD5_SHA1;
4079 return true;
4080 case EVP_PKEY_EC:
4081 *out = SSL_SIGN_ECDSA_SHA1;
4082 return true;
4083 default:
4084 return false;
4085 }
4086}
4087
4088bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out) {
4089 SSL *const ssl = hs->ssl;
4090 CERT *cert = hs->config->cert.get();
4091 DC *dc = cert->dc.get();
4092
4093 // Before TLS 1.2, the signature algorithm isn't negotiated as part of the
4094 // handshake.
4095 if (ssl_protocol_version(ssl) < TLS1_2_VERSION) {
4096 if (!tls1_get_legacy_signature_algorithm(out, pkey: hs->local_pubkey.get())) {
4097 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
4098 return false;
4099 }
4100 return true;
4101 }
4102
4103 Span<const uint16_t> sigalgs = kSignSignatureAlgorithms;
4104 if (ssl_signing_with_dc(hs)) {
4105 sigalgs = MakeConstSpan(ptr: &dc->expected_cert_verify_algorithm, size: 1);
4106 } else if (!cert->sigalgs.empty()) {
4107 sigalgs = cert->sigalgs;
4108 }
4109
4110 Span<const uint16_t> peer_sigalgs = tls1_get_peer_verify_algorithms(hs);
4111
4112 for (uint16_t sigalg : sigalgs) {
4113 if (!ssl_private_key_supports_signature_algorithm(hs, sigalg)) {
4114 continue;
4115 }
4116
4117 for (uint16_t peer_sigalg : peer_sigalgs) {
4118 if (sigalg == peer_sigalg) {
4119 *out = sigalg;
4120 return true;
4121 }
4122 }
4123 }
4124
4125 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
4126 return false;
4127}
4128
4129Span<const uint16_t> tls1_get_peer_verify_algorithms(const SSL_HANDSHAKE *hs) {
4130 Span<const uint16_t> peer_sigalgs = hs->peer_sigalgs;
4131 if (peer_sigalgs.empty() && ssl_protocol_version(ssl: hs->ssl) < TLS1_3_VERSION) {
4132 // If the client didn't specify any signature_algorithms extension then
4133 // we can assume that it supports SHA1. See
4134 // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
4135 static const uint16_t kDefaultPeerAlgorithms[] = {SSL_SIGN_RSA_PKCS1_SHA1,
4136 SSL_SIGN_ECDSA_SHA1};
4137 peer_sigalgs = kDefaultPeerAlgorithms;
4138 }
4139 return peer_sigalgs;
4140}
4141
4142bool tls1_verify_channel_id(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
4143 SSL *const ssl = hs->ssl;
4144 // A Channel ID handshake message is structured to contain multiple
4145 // extensions, but the only one that can be present is Channel ID.
4146 uint16_t extension_type;
4147 CBS channel_id = msg.body, extension;
4148 if (!CBS_get_u16(cbs: &channel_id, out: &extension_type) ||
4149 !CBS_get_u16_length_prefixed(cbs: &channel_id, out: &extension) ||
4150 CBS_len(cbs: &channel_id) != 0 ||
4151 extension_type != TLSEXT_TYPE_channel_id ||
4152 CBS_len(cbs: &extension) != TLSEXT_CHANNEL_ID_SIZE) {
4153 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
4154 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
4155 return false;
4156 }
4157
4158 UniquePtr<EC_GROUP> p256(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
4159 if (!p256) {
4160 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_P256_SUPPORT);
4161 return false;
4162 }
4163
4164 UniquePtr<ECDSA_SIG> sig(ECDSA_SIG_new());
4165 UniquePtr<BIGNUM> x(BN_new()), y(BN_new());
4166 if (!sig || !x || !y) {
4167 return false;
4168 }
4169
4170 const uint8_t *p = CBS_data(cbs: &extension);
4171 if (BN_bin2bn(in: p + 0, len: 32, ret: x.get()) == NULL ||
4172 BN_bin2bn(in: p + 32, len: 32, ret: y.get()) == NULL ||
4173 BN_bin2bn(in: p + 64, len: 32, ret: sig->r) == NULL ||
4174 BN_bin2bn(in: p + 96, len: 32, ret: sig->s) == NULL) {
4175 return false;
4176 }
4177
4178 UniquePtr<EC_KEY> key(EC_KEY_new());
4179 UniquePtr<EC_POINT> point(EC_POINT_new(group: p256.get()));
4180 if (!key || !point ||
4181 !EC_POINT_set_affine_coordinates_GFp(group: p256.get(), point: point.get(), x: x.get(),
4182 y: y.get(), ctx: nullptr) ||
4183 !EC_KEY_set_group(key: key.get(), group: p256.get()) ||
4184 !EC_KEY_set_public_key(key: key.get(), pub: point.get())) {
4185 return false;
4186 }
4187
4188 uint8_t digest[EVP_MAX_MD_SIZE];
4189 size_t digest_len;
4190 if (!tls1_channel_id_hash(hs, out: digest, out_len: &digest_len)) {
4191 return false;
4192 }
4193
4194 bool sig_ok = ECDSA_do_verify(digest, digest_len, sig: sig.get(), key: key.get());
4195#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
4196 sig_ok = true;
4197 ERR_clear_error();
4198#endif
4199 if (!sig_ok) {
4200 OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
4201 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
4202 return false;
4203 }
4204
4205 OPENSSL_memcpy(dst: ssl->s3->channel_id, src: p, n: 64);
4206 ssl->s3->channel_id_valid = true;
4207 return true;
4208}
4209
4210bool tls1_write_channel_id(SSL_HANDSHAKE *hs, CBB *cbb) {
4211 uint8_t digest[EVP_MAX_MD_SIZE];
4212 size_t digest_len;
4213 if (!tls1_channel_id_hash(hs, out: digest, out_len: &digest_len)) {
4214 return false;
4215 }
4216
4217 EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey: hs->config->channel_id_private.get());
4218 if (ec_key == nullptr) {
4219 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
4220 return false;
4221 }
4222
4223 UniquePtr<BIGNUM> x(BN_new()), y(BN_new());
4224 if (!x || !y ||
4225 !EC_POINT_get_affine_coordinates_GFp(group: EC_KEY_get0_group(key: ec_key),
4226 point: EC_KEY_get0_public_key(key: ec_key),
4227 x: x.get(), y: y.get(), ctx: nullptr)) {
4228 return false;
4229 }
4230
4231 UniquePtr<ECDSA_SIG> sig(ECDSA_do_sign(digest, digest_len, key: ec_key));
4232 if (!sig) {
4233 return false;
4234 }
4235
4236 CBB child;
4237 if (!CBB_add_u16(cbb, TLSEXT_TYPE_channel_id) ||
4238 !CBB_add_u16_length_prefixed(cbb, out_contents: &child) ||
4239 !BN_bn2cbb_padded(out: &child, len: 32, in: x.get()) ||
4240 !BN_bn2cbb_padded(out: &child, len: 32, in: y.get()) ||
4241 !BN_bn2cbb_padded(out: &child, len: 32, in: sig->r) ||
4242 !BN_bn2cbb_padded(out: &child, len: 32, in: sig->s) ||
4243 !CBB_flush(cbb)) {
4244 return false;
4245 }
4246
4247 return true;
4248}
4249
4250bool tls1_channel_id_hash(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len) {
4251 SSL *const ssl = hs->ssl;
4252 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
4253 Array<uint8_t> msg;
4254 if (!tls13_get_cert_verify_signature_input(hs, out: &msg,
4255 cert_verify_context: ssl_cert_verify_channel_id)) {
4256 return false;
4257 }
4258 SHA256(data: msg.data(), len: msg.size(), out);
4259 *out_len = SHA256_DIGEST_LENGTH;
4260 return true;
4261 }
4262
4263 SHA256_CTX ctx;
4264
4265 SHA256_Init(sha: &ctx);
4266 static const char kClientIDMagic[] = "TLS Channel ID signature";
4267 SHA256_Update(sha: &ctx, data: kClientIDMagic, len: sizeof(kClientIDMagic));
4268
4269 if (ssl->session != NULL) {
4270 static const char kResumptionMagic[] = "Resumption";
4271 SHA256_Update(sha: &ctx, data: kResumptionMagic, len: sizeof(kResumptionMagic));
4272 if (ssl->session->original_handshake_hash_len == 0) {
4273 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
4274 return false;
4275 }
4276 SHA256_Update(sha: &ctx, data: ssl->session->original_handshake_hash,
4277 len: ssl->session->original_handshake_hash_len);
4278 }
4279
4280 uint8_t hs_hash[EVP_MAX_MD_SIZE];
4281 size_t hs_hash_len;
4282 if (!hs->transcript.GetHash(out: hs_hash, out_len: &hs_hash_len)) {
4283 return false;
4284 }
4285 SHA256_Update(sha: &ctx, data: hs_hash, len: (size_t)hs_hash_len);
4286 SHA256_Final(out, sha: &ctx);
4287 *out_len = SHA256_DIGEST_LENGTH;
4288 return true;
4289}
4290
4291bool tls1_record_handshake_hashes_for_channel_id(SSL_HANDSHAKE *hs) {
4292 SSL *const ssl = hs->ssl;
4293 // This function should never be called for a resumed session because the
4294 // handshake hashes that we wish to record are for the original, full
4295 // handshake.
4296 if (ssl->session != NULL) {
4297 return false;
4298 }
4299
4300 static_assert(
4301 sizeof(hs->new_session->original_handshake_hash) == EVP_MAX_MD_SIZE,
4302 "original_handshake_hash is too small");
4303
4304 size_t digest_len;
4305 if (!hs->transcript.GetHash(out: hs->new_session->original_handshake_hash,
4306 out_len: &digest_len)) {
4307 return false;
4308 }
4309
4310 static_assert(EVP_MAX_MD_SIZE <= 0xff,
4311 "EVP_MAX_MD_SIZE does not fit in uint8_t");
4312 hs->new_session->original_handshake_hash_len = (uint8_t)digest_len;
4313
4314 return true;
4315}
4316
4317bool ssl_is_sct_list_valid(const CBS *contents) {
4318 // Shallow parse the SCT list for sanity. By the RFC
4319 // (https://tools.ietf.org/html/rfc6962#section-3.3) neither the list nor any
4320 // of the SCTs may be empty.
4321 CBS copy = *contents;
4322 CBS sct_list;
4323 if (!CBS_get_u16_length_prefixed(cbs: &copy, out: &sct_list) ||
4324 CBS_len(cbs: &copy) != 0 ||
4325 CBS_len(cbs: &sct_list) == 0) {
4326 return false;
4327 }
4328
4329 while (CBS_len(cbs: &sct_list) > 0) {
4330 CBS sct;
4331 if (!CBS_get_u16_length_prefixed(cbs: &sct_list, out: &sct) ||
4332 CBS_len(cbs: &sct) == 0) {
4333 return false;
4334 }
4335 }
4336
4337 return true;
4338}
4339
4340BSSL_NAMESPACE_END
4341
4342using namespace bssl;
4343
4344int SSL_early_callback_ctx_extension_get(const SSL_CLIENT_HELLO *client_hello,
4345 uint16_t extension_type,
4346 const uint8_t **out_data,
4347 size_t *out_len) {
4348 CBS cbs;
4349 if (!ssl_client_hello_get_extension(client_hello, out: &cbs, extension_type)) {
4350 return 0;
4351 }
4352
4353 *out_data = CBS_data(cbs: &cbs);
4354 *out_len = CBS_len(cbs: &cbs);
4355 return 1;
4356}
4357

source code of flutter_engine/third_party/boringssl/src/ssl/extensions.cc