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