Home | History | Annotate | Download | only in ssl
      1 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
      2  * All rights reserved.
      3  *
      4  * This package is an SSL implementation written
      5  * by Eric Young (eay (at) 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 (at) 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 (at) 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 (at) 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 (at) 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 (at) cryptsoft.com).  This product includes software written by Tim
    107  * Hudson (tjh (at) 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 <utility>
    117 
    118 #include <openssl/bytestring.h>
    119 #include <openssl/chacha.h>
    120 #include <openssl/digest.h>
    121 #include <openssl/err.h>
    122 #include <openssl/evp.h>
    123 #include <openssl/hmac.h>
    124 #include <openssl/mem.h>
    125 #include <openssl/nid.h>
    126 #include <openssl/rand.h>
    127 
    128 #include "internal.h"
    129 #include "../crypto/internal.h"
    130 
    131 
    132 namespace bssl {
    133 
    134 static int ssl_check_clienthello_tlsext(SSL_HANDSHAKE *hs);
    135 
    136 static int compare_uint16_t(const void *p1, const void *p2) {
    137   uint16_t u1 = *((const uint16_t *)p1);
    138   uint16_t u2 = *((const uint16_t *)p2);
    139   if (u1 < u2) {
    140     return -1;
    141   } else if (u1 > u2) {
    142     return 1;
    143   } else {
    144     return 0;
    145   }
    146 }
    147 
    148 // Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
    149 // more than one extension of the same type in a ClientHello or ServerHello.
    150 // This function does an initial scan over the extensions block to filter those
    151 // out.
    152 static int tls1_check_duplicate_extensions(const CBS *cbs) {
    153   // First pass: count the extensions.
    154   size_t num_extensions = 0;
    155   CBS extensions = *cbs;
    156   while (CBS_len(&extensions) > 0) {
    157     uint16_t type;
    158     CBS extension;
    159 
    160     if (!CBS_get_u16(&extensions, &type) ||
    161         !CBS_get_u16_length_prefixed(&extensions, &extension)) {
    162       return 0;
    163     }
    164 
    165     num_extensions++;
    166   }
    167 
    168   if (num_extensions == 0) {
    169     return 1;
    170   }
    171 
    172   Array<uint16_t> extension_types;
    173   if (!extension_types.Init(num_extensions)) {
    174     return 0;
    175   }
    176 
    177   // Second pass: gather the extension types.
    178   extensions = *cbs;
    179   for (size_t i = 0; i < extension_types.size(); i++) {
    180     CBS extension;
    181 
    182     if (!CBS_get_u16(&extensions, &extension_types[i]) ||
    183         !CBS_get_u16_length_prefixed(&extensions, &extension)) {
    184       // This should not happen.
    185       return 0;
    186     }
    187   }
    188   assert(CBS_len(&extensions) == 0);
    189 
    190   // Sort the extensions and make sure there are no duplicates.
    191   qsort(extension_types.data(), extension_types.size(), sizeof(uint16_t),
    192         compare_uint16_t);
    193   for (size_t i = 1; i < num_extensions; i++) {
    194     if (extension_types[i - 1] == extension_types[i]) {
    195       return 0;
    196     }
    197   }
    198 
    199   return 1;
    200 }
    201 
    202 int ssl_client_hello_init(SSL *ssl, SSL_CLIENT_HELLO *out,
    203                           const SSLMessage &msg) {
    204   OPENSSL_memset(out, 0, sizeof(*out));
    205   out->ssl = ssl;
    206   out->client_hello = CBS_data(&msg.body);
    207   out->client_hello_len = CBS_len(&msg.body);
    208 
    209   CBS client_hello, random, session_id;
    210   CBS_init(&client_hello, out->client_hello, out->client_hello_len);
    211   if (!CBS_get_u16(&client_hello, &out->version) ||
    212       !CBS_get_bytes(&client_hello, &random, SSL3_RANDOM_SIZE) ||
    213       !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
    214       CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
    215     return 0;
    216   }
    217 
    218   out->random = CBS_data(&random);
    219   out->random_len = CBS_len(&random);
    220   out->session_id = CBS_data(&session_id);
    221   out->session_id_len = CBS_len(&session_id);
    222 
    223   // Skip past DTLS cookie
    224   if (SSL_is_dtls(out->ssl)) {
    225     CBS cookie;
    226     if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
    227         CBS_len(&cookie) > DTLS1_COOKIE_LENGTH) {
    228       return 0;
    229     }
    230   }
    231 
    232   CBS cipher_suites, compression_methods;
    233   if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
    234       CBS_len(&cipher_suites) < 2 || (CBS_len(&cipher_suites) & 1) != 0 ||
    235       !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
    236       CBS_len(&compression_methods) < 1) {
    237     return 0;
    238   }
    239 
    240   out->cipher_suites = CBS_data(&cipher_suites);
    241   out->cipher_suites_len = CBS_len(&cipher_suites);
    242   out->compression_methods = CBS_data(&compression_methods);
    243   out->compression_methods_len = CBS_len(&compression_methods);
    244 
    245   // If the ClientHello ends here then it's valid, but doesn't have any
    246   // extensions. (E.g. SSLv3.)
    247   if (CBS_len(&client_hello) == 0) {
    248     out->extensions = NULL;
    249     out->extensions_len = 0;
    250     return 1;
    251   }
    252 
    253   // Extract extensions and check it is valid.
    254   CBS extensions;
    255   if (!CBS_get_u16_length_prefixed(&client_hello, &extensions) ||
    256       !tls1_check_duplicate_extensions(&extensions) ||
    257       CBS_len(&client_hello) != 0) {
    258     return 0;
    259   }
    260 
    261   out->extensions = CBS_data(&extensions);
    262   out->extensions_len = CBS_len(&extensions);
    263 
    264   return 1;
    265 }
    266 
    267 int ssl_client_hello_get_extension(const SSL_CLIENT_HELLO *client_hello,
    268                                    CBS *out, uint16_t extension_type) {
    269   CBS extensions;
    270   CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
    271   while (CBS_len(&extensions) != 0) {
    272     // Decode the next extension.
    273     uint16_t type;
    274     CBS extension;
    275     if (!CBS_get_u16(&extensions, &type) ||
    276         !CBS_get_u16_length_prefixed(&extensions, &extension)) {
    277       return 0;
    278     }
    279 
    280     if (type == extension_type) {
    281       *out = extension;
    282       return 1;
    283     }
    284   }
    285 
    286   return 0;
    287 }
    288 
    289 static const uint16_t kDefaultGroups[] = {
    290     SSL_CURVE_X25519,
    291     SSL_CURVE_SECP256R1,
    292     SSL_CURVE_SECP384R1,
    293 };
    294 
    295 Span<const uint16_t> tls1_get_grouplist(const SSL *ssl) {
    296   if (ssl->supported_group_list != nullptr) {
    297     return MakeConstSpan(ssl->supported_group_list,
    298                          ssl->supported_group_list_len);
    299   }
    300   return Span<const uint16_t>(kDefaultGroups);
    301 }
    302 
    303 int tls1_get_shared_group(SSL_HANDSHAKE *hs, uint16_t *out_group_id) {
    304   SSL *const ssl = hs->ssl;
    305   assert(ssl->server);
    306 
    307   // Clients are not required to send a supported_groups extension. In this
    308   // case, the server is free to pick any group it likes. See RFC 4492,
    309   // section 4, paragraph 3.
    310   //
    311   // However, in the interests of compatibility, we will skip ECDH if the
    312   // client didn't send an extension because we can't be sure that they'll
    313   // support our favoured group. Thus we do not special-case an emtpy
    314   // |peer_supported_group_list|.
    315 
    316   Span<const uint16_t> groups = tls1_get_grouplist(ssl);
    317   Span<const uint16_t> pref, supp;
    318   if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
    319     pref = groups;
    320     supp = hs->peer_supported_group_list;
    321   } else {
    322     pref = hs->peer_supported_group_list;
    323     supp = groups;
    324   }
    325 
    326   for (uint16_t pref_group : pref) {
    327     for (uint16_t supp_group : supp) {
    328       if (pref_group == supp_group) {
    329         *out_group_id = pref_group;
    330         return 1;
    331       }
    332     }
    333   }
    334 
    335   return 0;
    336 }
    337 
    338 int tls1_set_curves(uint16_t **out_group_ids, size_t *out_group_ids_len,
    339                     const int *curves, size_t ncurves) {
    340   uint16_t *group_ids = (uint16_t *)OPENSSL_malloc(ncurves * sizeof(uint16_t));
    341   if (group_ids == NULL) {
    342     return 0;
    343   }
    344 
    345   for (size_t i = 0; i < ncurves; i++) {
    346     if (!ssl_nid_to_group_id(&group_ids[i], curves[i])) {
    347       OPENSSL_free(group_ids);
    348       return 0;
    349     }
    350   }
    351 
    352   OPENSSL_free(*out_group_ids);
    353   *out_group_ids = group_ids;
    354   *out_group_ids_len = ncurves;
    355 
    356   return 1;
    357 }
    358 
    359 int tls1_set_curves_list(uint16_t **out_group_ids, size_t *out_group_ids_len,
    360                          const char *curves) {
    361   uint16_t *group_ids = NULL;
    362   size_t ncurves = 0;
    363 
    364   const char *col;
    365   const char *ptr = curves;
    366 
    367   do {
    368     col = strchr(ptr, ':');
    369 
    370     uint16_t group_id;
    371     if (!ssl_name_to_group_id(&group_id, ptr,
    372                               col ? (size_t)(col - ptr) : strlen(ptr))) {
    373       goto err;
    374     }
    375 
    376     uint16_t *new_group_ids = (uint16_t *)OPENSSL_realloc(
    377         group_ids, (ncurves + 1) * sizeof(uint16_t));
    378     if (new_group_ids == NULL) {
    379       goto err;
    380     }
    381     group_ids = new_group_ids;
    382 
    383     group_ids[ncurves] = group_id;
    384     ncurves++;
    385 
    386     if (col) {
    387       ptr = col + 1;
    388     }
    389   } while (col);
    390 
    391   OPENSSL_free(*out_group_ids);
    392   *out_group_ids = group_ids;
    393   *out_group_ids_len = ncurves;
    394 
    395   return 1;
    396 
    397 err:
    398   OPENSSL_free(group_ids);
    399   return 0;
    400 }
    401 
    402 int tls1_check_group_id(const SSL *ssl, uint16_t group_id) {
    403   for (uint16_t supported : tls1_get_grouplist(ssl)) {
    404     if (supported == group_id) {
    405       return 1;
    406     }
    407   }
    408 
    409   return 0;
    410 }
    411 
    412 // kVerifySignatureAlgorithms is the default list of accepted signature
    413 // algorithms for verifying.
    414 //
    415 // For now, RSA-PSS signature algorithms are not enabled on Android's system
    416 // BoringSSL. Once the change in Chrome has stuck and the values are finalized,
    417 // restore them.
    418 static const uint16_t kVerifySignatureAlgorithms[] = {
    419     // List our preferred algorithms first.
    420     SSL_SIGN_ED25519,
    421     SSL_SIGN_ECDSA_SECP256R1_SHA256,
    422     SSL_SIGN_RSA_PSS_SHA256,
    423     SSL_SIGN_RSA_PKCS1_SHA256,
    424 
    425     // Larger hashes are acceptable.
    426     SSL_SIGN_ECDSA_SECP384R1_SHA384,
    427     SSL_SIGN_RSA_PSS_SHA384,
    428     SSL_SIGN_RSA_PKCS1_SHA384,
    429 
    430     SSL_SIGN_RSA_PSS_SHA512,
    431     SSL_SIGN_RSA_PKCS1_SHA512,
    432 
    433     // For now, SHA-1 is still accepted but least preferable.
    434     SSL_SIGN_RSA_PKCS1_SHA1,
    435 
    436 };
    437 
    438 // kSignSignatureAlgorithms is the default list of supported signature
    439 // algorithms for signing.
    440 //
    441 // For now, RSA-PSS signature algorithms are not enabled on Android's system
    442 // BoringSSL. Once the change in Chrome has stuck and the values are finalized,
    443 // restore them.
    444 static const uint16_t kSignSignatureAlgorithms[] = {
    445     // List our preferred algorithms first.
    446     SSL_SIGN_ED25519,
    447     SSL_SIGN_ECDSA_SECP256R1_SHA256,
    448     SSL_SIGN_RSA_PSS_SHA256,
    449     SSL_SIGN_RSA_PKCS1_SHA256,
    450 
    451     // If needed, sign larger hashes.
    452     //
    453     // TODO(davidben): Determine which of these may be pruned.
    454     SSL_SIGN_ECDSA_SECP384R1_SHA384,
    455     SSL_SIGN_RSA_PSS_SHA384,
    456     SSL_SIGN_RSA_PKCS1_SHA384,
    457 
    458     SSL_SIGN_ECDSA_SECP521R1_SHA512,
    459     SSL_SIGN_RSA_PSS_SHA512,
    460     SSL_SIGN_RSA_PKCS1_SHA512,
    461 
    462     // If the peer supports nothing else, sign with SHA-1.
    463     SSL_SIGN_ECDSA_SHA1,
    464     SSL_SIGN_RSA_PKCS1_SHA1,
    465 };
    466 
    467 bool tls12_add_verify_sigalgs(const SSL *ssl, CBB *out) {
    468   bool use_default = ssl->ctx->num_verify_sigalgs == 0;
    469   Span<const uint16_t> sigalgs = kVerifySignatureAlgorithms;
    470   if (!use_default) {
    471     sigalgs = MakeConstSpan(ssl->ctx->verify_sigalgs,
    472                             ssl->ctx->num_verify_sigalgs);
    473   }
    474 
    475   for (uint16_t sigalg : sigalgs) {
    476     if (use_default &&
    477         sigalg == SSL_SIGN_ED25519 &&
    478         !ssl->ctx->ed25519_enabled) {
    479       continue;
    480     }
    481     if (!CBB_add_u16(out, sigalg)) {
    482       return false;
    483     }
    484   }
    485 
    486   return true;
    487 }
    488 
    489 bool tls12_check_peer_sigalg(const SSL *ssl, uint8_t *out_alert,
    490                              uint16_t sigalg) {
    491   const uint16_t *sigalgs = kVerifySignatureAlgorithms;
    492   size_t num_sigalgs = OPENSSL_ARRAY_SIZE(kVerifySignatureAlgorithms);
    493   if (ssl->ctx->num_verify_sigalgs != 0) {
    494     sigalgs = ssl->ctx->verify_sigalgs;
    495     num_sigalgs = ssl->ctx->num_verify_sigalgs;
    496   }
    497 
    498   for (size_t i = 0; i < num_sigalgs; i++) {
    499     if (sigalgs == kVerifySignatureAlgorithms &&
    500         sigalgs[i] == SSL_SIGN_ED25519 &&
    501         !ssl->ctx->ed25519_enabled) {
    502       continue;
    503     }
    504     if (sigalg == sigalgs[i]) {
    505       return true;
    506     }
    507   }
    508 
    509   OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SIGNATURE_TYPE);
    510   *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    511   return false;
    512 }
    513 
    514 // tls_extension represents a TLS extension that is handled internally. The
    515 // |init| function is called for each handshake, before any other functions of
    516 // the extension. Then the add and parse callbacks are called as needed.
    517 //
    518 // The parse callbacks receive a |CBS| that contains the contents of the
    519 // extension (i.e. not including the type and length bytes). If an extension is
    520 // not received then the parse callbacks will be called with a NULL CBS so that
    521 // they can do any processing needed to handle the absence of an extension.
    522 //
    523 // The add callbacks receive a |CBB| to which the extension can be appended but
    524 // the function is responsible for appending the type and length bytes too.
    525 //
    526 // All callbacks return true for success and false for error. If a parse
    527 // function returns zero then a fatal alert with value |*out_alert| will be
    528 // sent. If |*out_alert| isn't set, then a |decode_error| alert will be sent.
    529 struct tls_extension {
    530   uint16_t value;
    531   void (*init)(SSL_HANDSHAKE *hs);
    532 
    533   bool (*add_clienthello)(SSL_HANDSHAKE *hs, CBB *out);
    534   bool (*parse_serverhello)(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    535                             CBS *contents);
    536 
    537   bool (*parse_clienthello)(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    538                             CBS *contents);
    539   bool (*add_serverhello)(SSL_HANDSHAKE *hs, CBB *out);
    540 };
    541 
    542 static bool forbid_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    543                                     CBS *contents) {
    544   if (contents != NULL) {
    545     // Servers MUST NOT send this extension.
    546     *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
    547     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
    548     return false;
    549   }
    550 
    551   return true;
    552 }
    553 
    554 static bool ignore_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    555                                     CBS *contents) {
    556   // This extension from the client is handled elsewhere.
    557   return true;
    558 }
    559 
    560 static bool ignore_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    561                                      CBS *contents) {
    562   return true;
    563 }
    564 
    565 static bool dont_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
    566   return true;
    567 }
    568 
    569 // Server name indication (SNI).
    570 //
    571 // https://tools.ietf.org/html/rfc6066#section-3.
    572 
    573 static bool ext_sni_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
    574   SSL *const ssl = hs->ssl;
    575   if (ssl->tlsext_hostname == NULL) {
    576     return true;
    577   }
    578 
    579   CBB contents, server_name_list, name;
    580   if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
    581       !CBB_add_u16_length_prefixed(out, &contents) ||
    582       !CBB_add_u16_length_prefixed(&contents, &server_name_list) ||
    583       !CBB_add_u8(&server_name_list, TLSEXT_NAMETYPE_host_name) ||
    584       !CBB_add_u16_length_prefixed(&server_name_list, &name) ||
    585       !CBB_add_bytes(&name, (const uint8_t *)ssl->tlsext_hostname,
    586                      strlen(ssl->tlsext_hostname)) ||
    587       !CBB_flush(out)) {
    588     return false;
    589   }
    590 
    591   return true;
    592 }
    593 
    594 static bool ext_sni_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    595                                       CBS *contents) {
    596   // The server may acknowledge SNI with an empty extension. We check the syntax
    597   // but otherwise ignore this signal.
    598   return contents == NULL || CBS_len(contents) == 0;
    599 }
    600 
    601 static bool ext_sni_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    602                                       CBS *contents) {
    603   SSL *const ssl = hs->ssl;
    604   if (contents == NULL) {
    605     return true;
    606   }
    607 
    608   CBS server_name_list, host_name;
    609   uint8_t name_type;
    610   if (!CBS_get_u16_length_prefixed(contents, &server_name_list) ||
    611       !CBS_get_u8(&server_name_list, &name_type) ||
    612       // Although the server_name extension was intended to be extensible to
    613       // new name types and multiple names, OpenSSL 1.0.x had a bug which meant
    614       // different name types will cause an error. Further, RFC 4366 originally
    615       // defined syntax inextensibly. RFC 6066 corrected this mistake, but
    616       // adding new name types is no longer feasible.
    617       //
    618       // Act as if the extensibility does not exist to simplify parsing.
    619       !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
    620       CBS_len(&server_name_list) != 0 ||
    621       CBS_len(contents) != 0) {
    622     return false;
    623   }
    624 
    625   if (name_type != TLSEXT_NAMETYPE_host_name ||
    626       CBS_len(&host_name) == 0 ||
    627       CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||
    628       CBS_contains_zero_byte(&host_name)) {
    629     *out_alert = SSL_AD_UNRECOGNIZED_NAME;
    630     return false;
    631   }
    632 
    633   // Copy the hostname as a string.
    634   char *raw = nullptr;
    635   if (!CBS_strdup(&host_name, &raw)) {
    636     *out_alert = SSL_AD_INTERNAL_ERROR;
    637     return false;
    638   }
    639   ssl->s3->hostname.reset(raw);
    640 
    641   hs->should_ack_sni = true;
    642   return true;
    643 }
    644 
    645 static bool ext_sni_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
    646   if (hs->ssl->s3->session_reused ||
    647       !hs->should_ack_sni) {
    648     return true;
    649   }
    650 
    651   if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
    652       !CBB_add_u16(out, 0 /* length */)) {
    653     return false;
    654   }
    655 
    656   return true;
    657 }
    658 
    659 
    660 // Renegotiation indication.
    661 //
    662 // https://tools.ietf.org/html/rfc5746
    663 
    664 static bool ext_ri_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
    665   SSL *const ssl = hs->ssl;
    666   // Renegotiation indication is not necessary in TLS 1.3.
    667   if (hs->min_version >= TLS1_3_VERSION) {
    668     return true;
    669   }
    670 
    671   assert(ssl->s3->initial_handshake_complete ==
    672          (ssl->s3->previous_client_finished_len != 0));
    673 
    674   CBB contents, prev_finished;
    675   if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
    676       !CBB_add_u16_length_prefixed(out, &contents) ||
    677       !CBB_add_u8_length_prefixed(&contents, &prev_finished) ||
    678       !CBB_add_bytes(&prev_finished, ssl->s3->previous_client_finished,
    679                      ssl->s3->previous_client_finished_len) ||
    680       !CBB_flush(out)) {
    681     return false;
    682   }
    683 
    684   return true;
    685 }
    686 
    687 static bool ext_ri_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    688                                      CBS *contents) {
    689   SSL *const ssl = hs->ssl;
    690   if (contents != NULL && ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
    691     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    692     return false;
    693   }
    694 
    695   // Servers may not switch between omitting the extension and supporting it.
    696   // See RFC 5746, sections 3.5 and 4.2.
    697   if (ssl->s3->initial_handshake_complete &&
    698       (contents != NULL) != ssl->s3->send_connection_binding) {
    699     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    700     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    701     return false;
    702   }
    703 
    704   if (contents == NULL) {
    705     // Strictly speaking, if we want to avoid an attack we should *always* see
    706     // RI even on initial ServerHello because the client doesn't see any
    707     // renegotiation during an attack. However this would mean we could not
    708     // connect to any server which doesn't support RI.
    709     //
    710     // OpenSSL has |SSL_OP_LEGACY_SERVER_CONNECT| to control this, but in
    711     // practical terms every client sets it so it's just assumed here.
    712     return true;
    713   }
    714 
    715   const size_t expected_len = ssl->s3->previous_client_finished_len +
    716                               ssl->s3->previous_server_finished_len;
    717 
    718   // Check for logic errors
    719   assert(!expected_len || ssl->s3->previous_client_finished_len);
    720   assert(!expected_len || ssl->s3->previous_server_finished_len);
    721   assert(ssl->s3->initial_handshake_complete ==
    722          (ssl->s3->previous_client_finished_len != 0));
    723   assert(ssl->s3->initial_handshake_complete ==
    724          (ssl->s3->previous_server_finished_len != 0));
    725 
    726   // Parse out the extension contents.
    727   CBS renegotiated_connection;
    728   if (!CBS_get_u8_length_prefixed(contents, &renegotiated_connection) ||
    729       CBS_len(contents) != 0) {
    730     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
    731     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    732     return false;
    733   }
    734 
    735   // Check that the extension matches.
    736   if (CBS_len(&renegotiated_connection) != expected_len) {
    737     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    738     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    739     return false;
    740   }
    741 
    742   const uint8_t *d = CBS_data(&renegotiated_connection);
    743   bool ok = CRYPTO_memcmp(d, ssl->s3->previous_client_finished,
    744                           ssl->s3->previous_client_finished_len) == 0;
    745 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
    746   ok = true;
    747 #endif
    748   if (!ok) {
    749     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    750     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    751     return false;
    752   }
    753   d += ssl->s3->previous_client_finished_len;
    754 
    755   ok = CRYPTO_memcmp(d, ssl->s3->previous_server_finished,
    756                      ssl->s3->previous_server_finished_len) == 0;
    757 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
    758   ok = true;
    759 #endif
    760   if (!ok) {
    761     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    762     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    763     return false;
    764   }
    765   ssl->s3->send_connection_binding = true;
    766 
    767   return true;
    768 }
    769 
    770 static bool ext_ri_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    771                                      CBS *contents) {
    772   SSL *const ssl = hs->ssl;
    773   // Renegotiation isn't supported as a server so this function should never be
    774   // called after the initial handshake.
    775   assert(!ssl->s3->initial_handshake_complete);
    776 
    777   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
    778     return true;
    779   }
    780 
    781   if (contents == NULL) {
    782     return true;
    783   }
    784 
    785   CBS renegotiated_connection;
    786   if (!CBS_get_u8_length_prefixed(contents, &renegotiated_connection) ||
    787       CBS_len(contents) != 0) {
    788     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
    789     return false;
    790   }
    791 
    792   // Check that the extension matches. We do not support renegotiation as a
    793   // server, so this must be empty.
    794   if (CBS_len(&renegotiated_connection) != 0) {
    795     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    796     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    797     return false;
    798   }
    799 
    800   ssl->s3->send_connection_binding = true;
    801 
    802   return true;
    803 }
    804 
    805 static bool ext_ri_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
    806   SSL *const ssl = hs->ssl;
    807   // Renegotiation isn't supported as a server so this function should never be
    808   // called after the initial handshake.
    809   assert(!ssl->s3->initial_handshake_complete);
    810 
    811   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
    812     return true;
    813   }
    814 
    815   if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
    816       !CBB_add_u16(out, 1 /* length */) ||
    817       !CBB_add_u8(out, 0 /* empty renegotiation info */)) {
    818     return false;
    819   }
    820 
    821   return true;
    822 }
    823 
    824 
    825 // Extended Master Secret.
    826 //
    827 // https://tools.ietf.org/html/rfc7627
    828 
    829 static bool ext_ems_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
    830   // Extended master secret is not necessary in TLS 1.3.
    831   if (hs->min_version >= TLS1_3_VERSION || hs->max_version <= SSL3_VERSION) {
    832     return true;
    833   }
    834 
    835   if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
    836       !CBB_add_u16(out, 0 /* length */)) {
    837     return false;
    838   }
    839 
    840   return true;
    841 }
    842 
    843 static bool ext_ems_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    844                                       CBS *contents) {
    845   SSL *const ssl = hs->ssl;
    846 
    847   if (contents != NULL) {
    848     if (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
    849         ssl->version == SSL3_VERSION ||
    850         CBS_len(contents) != 0) {
    851       return false;
    852     }
    853 
    854     hs->extended_master_secret = true;
    855   }
    856 
    857   // Whether EMS is negotiated may not change on renegotiation.
    858   if (ssl->s3->established_session != nullptr &&
    859       hs->extended_master_secret !=
    860           !!ssl->s3->established_session->extended_master_secret) {
    861     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_EMS_MISMATCH);
    862     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    863     return false;
    864   }
    865 
    866   return true;
    867 }
    868 
    869 static bool ext_ems_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    870                                       CBS *contents) {
    871   uint16_t version = ssl_protocol_version(hs->ssl);
    872   if (version >= TLS1_3_VERSION ||
    873       version == SSL3_VERSION) {
    874     return true;
    875   }
    876 
    877   if (contents == NULL) {
    878     return true;
    879   }
    880 
    881   if (CBS_len(contents) != 0) {
    882     return false;
    883   }
    884 
    885   hs->extended_master_secret = true;
    886   return true;
    887 }
    888 
    889 static bool ext_ems_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
    890   if (!hs->extended_master_secret) {
    891     return true;
    892   }
    893 
    894   if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
    895       !CBB_add_u16(out, 0 /* length */)) {
    896     return false;
    897   }
    898 
    899   return true;
    900 }
    901 
    902 
    903 // Session tickets.
    904 //
    905 // https://tools.ietf.org/html/rfc5077
    906 
    907 static bool ext_ticket_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
    908   SSL *const ssl = hs->ssl;
    909   // TLS 1.3 uses a different ticket extension.
    910   if (hs->min_version >= TLS1_3_VERSION ||
    911       SSL_get_options(ssl) & SSL_OP_NO_TICKET) {
    912     return true;
    913   }
    914 
    915   const uint8_t *ticket_data = NULL;
    916   int ticket_len = 0;
    917 
    918   // Renegotiation does not participate in session resumption. However, still
    919   // advertise the extension to avoid potentially breaking servers which carry
    920   // over the state from the previous handshake, such as OpenSSL servers
    921   // without upstream's 3c3f0259238594d77264a78944d409f2127642c4.
    922   if (!ssl->s3->initial_handshake_complete &&
    923       ssl->session != NULL &&
    924       ssl->session->tlsext_tick != NULL &&
    925       // Don't send TLS 1.3 session tickets in the ticket extension.
    926       ssl_session_protocol_version(ssl->session) < TLS1_3_VERSION) {
    927     ticket_data = ssl->session->tlsext_tick;
    928     ticket_len = ssl->session->tlsext_ticklen;
    929   }
    930 
    931   CBB ticket;
    932   if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
    933       !CBB_add_u16_length_prefixed(out, &ticket) ||
    934       !CBB_add_bytes(&ticket, ticket_data, ticket_len) ||
    935       !CBB_flush(out)) {
    936     return false;
    937   }
    938 
    939   return true;
    940 }
    941 
    942 static bool ext_ticket_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    943                                          CBS *contents) {
    944   SSL *const ssl = hs->ssl;
    945   if (contents == NULL) {
    946     return true;
    947   }
    948 
    949   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
    950     return false;
    951   }
    952 
    953   // If |SSL_OP_NO_TICKET| is set then no extension will have been sent and
    954   // this function should never be called, even if the server tries to send the
    955   // extension.
    956   assert((SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0);
    957 
    958   if (CBS_len(contents) != 0) {
    959     return false;
    960   }
    961 
    962   hs->ticket_expected = true;
    963   return true;
    964 }
    965 
    966 static bool ext_ticket_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
    967   if (!hs->ticket_expected) {
    968     return true;
    969   }
    970 
    971   // If |SSL_OP_NO_TICKET| is set, |ticket_expected| should never be true.
    972   assert((SSL_get_options(hs->ssl) & SSL_OP_NO_TICKET) == 0);
    973 
    974   if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
    975       !CBB_add_u16(out, 0 /* length */)) {
    976     return false;
    977   }
    978 
    979   return true;
    980 }
    981 
    982 
    983 // Signature Algorithms.
    984 //
    985 // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
    986 
    987 static bool ext_sigalgs_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
    988   SSL *const ssl = hs->ssl;
    989   if (hs->max_version < TLS1_2_VERSION) {
    990     return true;
    991   }
    992 
    993   CBB contents, sigalgs_cbb;
    994   if (!CBB_add_u16(out, TLSEXT_TYPE_signature_algorithms) ||
    995       !CBB_add_u16_length_prefixed(out, &contents) ||
    996       !CBB_add_u16_length_prefixed(&contents, &sigalgs_cbb) ||
    997       !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb) ||
    998       !CBB_flush(out)) {
    999     return false;
   1000   }
   1001 
   1002   return true;
   1003 }
   1004 
   1005 static bool ext_sigalgs_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1006                                           CBS *contents) {
   1007   hs->peer_sigalgs.Reset();
   1008   if (contents == NULL) {
   1009     return true;
   1010   }
   1011 
   1012   CBS supported_signature_algorithms;
   1013   if (!CBS_get_u16_length_prefixed(contents, &supported_signature_algorithms) ||
   1014       CBS_len(contents) != 0 ||
   1015       CBS_len(&supported_signature_algorithms) == 0 ||
   1016       !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
   1017     return false;
   1018   }
   1019 
   1020   return true;
   1021 }
   1022 
   1023 
   1024 // OCSP Stapling.
   1025 //
   1026 // https://tools.ietf.org/html/rfc6066#section-8
   1027 
   1028 static bool ext_ocsp_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1029   SSL *const ssl = hs->ssl;
   1030   if (!ssl->ocsp_stapling_enabled) {
   1031     return true;
   1032   }
   1033 
   1034   CBB contents;
   1035   if (!CBB_add_u16(out, TLSEXT_TYPE_status_request) ||
   1036       !CBB_add_u16_length_prefixed(out, &contents) ||
   1037       !CBB_add_u8(&contents, TLSEXT_STATUSTYPE_ocsp) ||
   1038       !CBB_add_u16(&contents, 0 /* empty responder ID list */) ||
   1039       !CBB_add_u16(&contents, 0 /* empty request extensions */) ||
   1040       !CBB_flush(out)) {
   1041     return false;
   1042   }
   1043 
   1044   return true;
   1045 }
   1046 
   1047 static bool ext_ocsp_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1048                                        CBS *contents) {
   1049   SSL *const ssl = hs->ssl;
   1050   if (contents == NULL) {
   1051     return true;
   1052   }
   1053 
   1054   // TLS 1.3 OCSP responses are included in the Certificate extensions.
   1055   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
   1056     return false;
   1057   }
   1058 
   1059   // OCSP stapling is forbidden on non-certificate ciphers.
   1060   if (CBS_len(contents) != 0 ||
   1061       !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
   1062     return false;
   1063   }
   1064 
   1065   // Note this does not check for resumption in TLS 1.2. Sending
   1066   // status_request here does not make sense, but OpenSSL does so and the
   1067   // specification does not say anything. Tolerate it but ignore it.
   1068 
   1069   hs->certificate_status_expected = true;
   1070   return true;
   1071 }
   1072 
   1073 static bool ext_ocsp_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1074                                        CBS *contents) {
   1075   if (contents == NULL) {
   1076     return true;
   1077   }
   1078 
   1079   uint8_t status_type;
   1080   if (!CBS_get_u8(contents, &status_type)) {
   1081     return false;
   1082   }
   1083 
   1084   // We cannot decide whether OCSP stapling will occur yet because the correct
   1085   // SSL_CTX might not have been selected.
   1086   hs->ocsp_stapling_requested = status_type == TLSEXT_STATUSTYPE_ocsp;
   1087 
   1088   return true;
   1089 }
   1090 
   1091 static bool ext_ocsp_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   1092   SSL *const ssl = hs->ssl;
   1093   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
   1094       !hs->ocsp_stapling_requested ||
   1095       ssl->cert->ocsp_response == NULL ||
   1096       ssl->s3->session_reused ||
   1097       !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
   1098     return true;
   1099   }
   1100 
   1101   hs->certificate_status_expected = true;
   1102 
   1103   return CBB_add_u16(out, TLSEXT_TYPE_status_request) &&
   1104          CBB_add_u16(out, 0 /* length */);
   1105 }
   1106 
   1107 
   1108 // Next protocol negotiation.
   1109 //
   1110 // https://htmlpreview.github.io/?https://github.com/agl/technotes/blob/master/nextprotoneg.html
   1111 
   1112 static bool ext_npn_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1113   SSL *const ssl = hs->ssl;
   1114   if (ssl->s3->initial_handshake_complete ||
   1115       ssl->ctx->next_proto_select_cb == NULL ||
   1116       SSL_is_dtls(ssl)) {
   1117     return true;
   1118   }
   1119 
   1120   if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
   1121       !CBB_add_u16(out, 0 /* length */)) {
   1122     return false;
   1123   }
   1124 
   1125   return true;
   1126 }
   1127 
   1128 static bool ext_npn_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1129                                       CBS *contents) {
   1130   SSL *const ssl = hs->ssl;
   1131   if (contents == NULL) {
   1132     return true;
   1133   }
   1134 
   1135   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
   1136     return false;
   1137   }
   1138 
   1139   // If any of these are false then we should never have sent the NPN
   1140   // extension in the ClientHello and thus this function should never have been
   1141   // called.
   1142   assert(!ssl->s3->initial_handshake_complete);
   1143   assert(!SSL_is_dtls(ssl));
   1144   assert(ssl->ctx->next_proto_select_cb != NULL);
   1145 
   1146   if (!ssl->s3->alpn_selected.empty()) {
   1147     // NPN and ALPN may not be negotiated in the same connection.
   1148     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1149     OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
   1150     return false;
   1151   }
   1152 
   1153   const uint8_t *const orig_contents = CBS_data(contents);
   1154   const size_t orig_len = CBS_len(contents);
   1155 
   1156   while (CBS_len(contents) != 0) {
   1157     CBS proto;
   1158     if (!CBS_get_u8_length_prefixed(contents, &proto) ||
   1159         CBS_len(&proto) == 0) {
   1160       return false;
   1161     }
   1162   }
   1163 
   1164   uint8_t *selected;
   1165   uint8_t selected_len;
   1166   if (ssl->ctx->next_proto_select_cb(
   1167           ssl, &selected, &selected_len, orig_contents, orig_len,
   1168           ssl->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK ||
   1169       !ssl->s3->next_proto_negotiated.CopyFrom(
   1170           MakeConstSpan(selected, selected_len))) {
   1171     *out_alert = SSL_AD_INTERNAL_ERROR;
   1172     return false;
   1173   }
   1174 
   1175   hs->next_proto_neg_seen = true;
   1176   return true;
   1177 }
   1178 
   1179 static bool ext_npn_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1180                                       CBS *contents) {
   1181   SSL *const ssl = hs->ssl;
   1182   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
   1183     return true;
   1184   }
   1185 
   1186   if (contents != NULL && CBS_len(contents) != 0) {
   1187     return false;
   1188   }
   1189 
   1190   if (contents == NULL ||
   1191       ssl->s3->initial_handshake_complete ||
   1192       ssl->ctx->next_protos_advertised_cb == NULL ||
   1193       SSL_is_dtls(ssl)) {
   1194     return true;
   1195   }
   1196 
   1197   hs->next_proto_neg_seen = true;
   1198   return true;
   1199 }
   1200 
   1201 static bool ext_npn_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   1202   SSL *const ssl = hs->ssl;
   1203   // |next_proto_neg_seen| might have been cleared when an ALPN extension was
   1204   // parsed.
   1205   if (!hs->next_proto_neg_seen) {
   1206     return true;
   1207   }
   1208 
   1209   const uint8_t *npa;
   1210   unsigned npa_len;
   1211 
   1212   if (ssl->ctx->next_protos_advertised_cb(
   1213           ssl, &npa, &npa_len, ssl->ctx->next_protos_advertised_cb_arg) !=
   1214       SSL_TLSEXT_ERR_OK) {
   1215     hs->next_proto_neg_seen = false;
   1216     return true;
   1217   }
   1218 
   1219   CBB contents;
   1220   if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
   1221       !CBB_add_u16_length_prefixed(out, &contents) ||
   1222       !CBB_add_bytes(&contents, npa, npa_len) ||
   1223       !CBB_flush(out)) {
   1224     return false;
   1225   }
   1226 
   1227   return true;
   1228 }
   1229 
   1230 
   1231 // Signed certificate timestamps.
   1232 //
   1233 // https://tools.ietf.org/html/rfc6962#section-3.3.1
   1234 
   1235 static bool ext_sct_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1236   SSL *const ssl = hs->ssl;
   1237   if (!ssl->signed_cert_timestamps_enabled) {
   1238     return true;
   1239   }
   1240 
   1241   if (!CBB_add_u16(out, TLSEXT_TYPE_certificate_timestamp) ||
   1242       !CBB_add_u16(out, 0 /* length */)) {
   1243     return false;
   1244   }
   1245 
   1246   return true;
   1247 }
   1248 
   1249 static bool ext_sct_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1250                                       CBS *contents) {
   1251   SSL *const ssl = hs->ssl;
   1252   if (contents == NULL) {
   1253     return true;
   1254   }
   1255 
   1256   // TLS 1.3 SCTs are included in the Certificate extensions.
   1257   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
   1258     *out_alert = SSL_AD_DECODE_ERROR;
   1259     return false;
   1260   }
   1261 
   1262   // If this is false then we should never have sent the SCT extension in the
   1263   // ClientHello and thus this function should never have been called.
   1264   assert(ssl->signed_cert_timestamps_enabled);
   1265 
   1266   if (!ssl_is_sct_list_valid(contents)) {
   1267     *out_alert = SSL_AD_DECODE_ERROR;
   1268     return false;
   1269   }
   1270 
   1271   // Session resumption uses the original session information. The extension
   1272   // should not be sent on resumption, but RFC 6962 did not make it a
   1273   // requirement, so tolerate this.
   1274   //
   1275   // TODO(davidben): Enforce this anyway.
   1276   if (!ssl->s3->session_reused) {
   1277     CRYPTO_BUFFER_free(hs->new_session->signed_cert_timestamp_list);
   1278     hs->new_session->signed_cert_timestamp_list =
   1279         CRYPTO_BUFFER_new_from_CBS(contents, ssl->ctx->pool);
   1280     if (hs->new_session->signed_cert_timestamp_list == nullptr) {
   1281       *out_alert = SSL_AD_INTERNAL_ERROR;
   1282       return false;
   1283     }
   1284   }
   1285 
   1286   return true;
   1287 }
   1288 
   1289 static bool ext_sct_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1290                                       CBS *contents) {
   1291   if (contents == NULL) {
   1292     return true;
   1293   }
   1294 
   1295   if (CBS_len(contents) != 0) {
   1296     return false;
   1297   }
   1298 
   1299   hs->scts_requested = true;
   1300   return true;
   1301 }
   1302 
   1303 static bool ext_sct_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   1304   SSL *const ssl = hs->ssl;
   1305   // The extension shouldn't be sent when resuming sessions.
   1306   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
   1307       ssl->s3->session_reused ||
   1308       ssl->cert->signed_cert_timestamp_list == NULL) {
   1309     return true;
   1310   }
   1311 
   1312   CBB contents;
   1313   return CBB_add_u16(out, TLSEXT_TYPE_certificate_timestamp) &&
   1314          CBB_add_u16_length_prefixed(out, &contents) &&
   1315          CBB_add_bytes(
   1316              &contents,
   1317              CRYPTO_BUFFER_data(ssl->cert->signed_cert_timestamp_list),
   1318              CRYPTO_BUFFER_len(ssl->cert->signed_cert_timestamp_list)) &&
   1319          CBB_flush(out);
   1320 }
   1321 
   1322 
   1323 // Application-level Protocol Negotiation.
   1324 //
   1325 // https://tools.ietf.org/html/rfc7301
   1326 
   1327 static bool ext_alpn_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1328   SSL *const ssl = hs->ssl;
   1329   if (ssl->alpn_client_proto_list == NULL ||
   1330       ssl->s3->initial_handshake_complete) {
   1331     return true;
   1332   }
   1333 
   1334   CBB contents, proto_list;
   1335   if (!CBB_add_u16(out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
   1336       !CBB_add_u16_length_prefixed(out, &contents) ||
   1337       !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
   1338       !CBB_add_bytes(&proto_list, ssl->alpn_client_proto_list,
   1339                      ssl->alpn_client_proto_list_len) ||
   1340       !CBB_flush(out)) {
   1341     return false;
   1342   }
   1343 
   1344   return true;
   1345 }
   1346 
   1347 static bool ext_alpn_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1348                                        CBS *contents) {
   1349   SSL *const ssl = hs->ssl;
   1350   if (contents == NULL) {
   1351     return true;
   1352   }
   1353 
   1354   assert(!ssl->s3->initial_handshake_complete);
   1355   assert(ssl->alpn_client_proto_list != NULL);
   1356 
   1357   if (hs->next_proto_neg_seen) {
   1358     // NPN and ALPN may not be negotiated in the same connection.
   1359     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1360     OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
   1361     return false;
   1362   }
   1363 
   1364   // The extension data consists of a ProtocolNameList which must have
   1365   // exactly one ProtocolName. Each of these is length-prefixed.
   1366   CBS protocol_name_list, protocol_name;
   1367   if (!CBS_get_u16_length_prefixed(contents, &protocol_name_list) ||
   1368       CBS_len(contents) != 0 ||
   1369       !CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
   1370       // Empty protocol names are forbidden.
   1371       CBS_len(&protocol_name) == 0 ||
   1372       CBS_len(&protocol_name_list) != 0) {
   1373     return false;
   1374   }
   1375 
   1376   if (!ssl_is_alpn_protocol_allowed(ssl, protocol_name)) {
   1377     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
   1378     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1379     return false;
   1380   }
   1381 
   1382   if (!ssl->s3->alpn_selected.CopyFrom(protocol_name)) {
   1383     *out_alert = SSL_AD_INTERNAL_ERROR;
   1384     return false;
   1385   }
   1386 
   1387   return true;
   1388 }
   1389 
   1390 bool ssl_is_alpn_protocol_allowed(const SSL *ssl,
   1391                                   Span<const uint8_t> protocol) {
   1392   if (ssl->alpn_client_proto_list == nullptr) {
   1393     return false;
   1394   }
   1395 
   1396   if (ssl->ctx->allow_unknown_alpn_protos) {
   1397     return true;
   1398   }
   1399 
   1400   // Check that the protocol name is one of the ones we advertised.
   1401   CBS client_protocol_name_list, client_protocol_name;
   1402   CBS_init(&client_protocol_name_list, ssl->alpn_client_proto_list,
   1403            ssl->alpn_client_proto_list_len);
   1404   while (CBS_len(&client_protocol_name_list) > 0) {
   1405     if (!CBS_get_u8_length_prefixed(&client_protocol_name_list,
   1406                                     &client_protocol_name)) {
   1407       return false;
   1408     }
   1409 
   1410     if (client_protocol_name == protocol) {
   1411       return true;
   1412     }
   1413   }
   1414 
   1415   return false;
   1416 }
   1417 
   1418 bool ssl_negotiate_alpn(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1419                         const SSL_CLIENT_HELLO *client_hello) {
   1420   SSL *const ssl = hs->ssl;
   1421   CBS contents;
   1422   if (ssl->ctx->alpn_select_cb == NULL ||
   1423       !ssl_client_hello_get_extension(
   1424           client_hello, &contents,
   1425           TLSEXT_TYPE_application_layer_protocol_negotiation)) {
   1426     // Ignore ALPN if not configured or no extension was supplied.
   1427     return true;
   1428   }
   1429 
   1430   // ALPN takes precedence over NPN.
   1431   hs->next_proto_neg_seen = false;
   1432 
   1433   CBS protocol_name_list;
   1434   if (!CBS_get_u16_length_prefixed(&contents, &protocol_name_list) ||
   1435       CBS_len(&contents) != 0 ||
   1436       CBS_len(&protocol_name_list) < 2) {
   1437     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
   1438     *out_alert = SSL_AD_DECODE_ERROR;
   1439     return false;
   1440   }
   1441 
   1442   // Validate the protocol list.
   1443   CBS protocol_name_list_copy = protocol_name_list;
   1444   while (CBS_len(&protocol_name_list_copy) > 0) {
   1445     CBS protocol_name;
   1446 
   1447     if (!CBS_get_u8_length_prefixed(&protocol_name_list_copy, &protocol_name) ||
   1448         // Empty protocol names are forbidden.
   1449         CBS_len(&protocol_name) == 0) {
   1450       OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
   1451       *out_alert = SSL_AD_DECODE_ERROR;
   1452       return false;
   1453     }
   1454   }
   1455 
   1456   const uint8_t *selected;
   1457   uint8_t selected_len;
   1458   if (ssl->ctx->alpn_select_cb(
   1459           ssl, &selected, &selected_len, CBS_data(&protocol_name_list),
   1460           CBS_len(&protocol_name_list),
   1461           ssl->ctx->alpn_select_cb_arg) == SSL_TLSEXT_ERR_OK) {
   1462     if (!ssl->s3->alpn_selected.CopyFrom(
   1463             MakeConstSpan(selected, selected_len))) {
   1464       *out_alert = SSL_AD_INTERNAL_ERROR;
   1465       return false;
   1466     }
   1467   }
   1468 
   1469   return true;
   1470 }
   1471 
   1472 static bool ext_alpn_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   1473   SSL *const ssl = hs->ssl;
   1474   if (ssl->s3->alpn_selected.empty()) {
   1475     return true;
   1476   }
   1477 
   1478   CBB contents, proto_list, proto;
   1479   if (!CBB_add_u16(out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
   1480       !CBB_add_u16_length_prefixed(out, &contents) ||
   1481       !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
   1482       !CBB_add_u8_length_prefixed(&proto_list, &proto) ||
   1483       !CBB_add_bytes(&proto, ssl->s3->alpn_selected.data(),
   1484                      ssl->s3->alpn_selected.size()) ||
   1485       !CBB_flush(out)) {
   1486     return false;
   1487   }
   1488 
   1489   return true;
   1490 }
   1491 
   1492 
   1493 // Channel ID.
   1494 //
   1495 // https://tools.ietf.org/html/draft-balfanz-tls-channelid-01
   1496 
   1497 static void ext_channel_id_init(SSL_HANDSHAKE *hs) {
   1498   hs->ssl->s3->tlsext_channel_id_valid = false;
   1499 }
   1500 
   1501 static bool ext_channel_id_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1502   SSL *const ssl = hs->ssl;
   1503   if (!ssl->tlsext_channel_id_enabled ||
   1504       SSL_is_dtls(ssl)) {
   1505     return true;
   1506   }
   1507 
   1508   if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
   1509       !CBB_add_u16(out, 0 /* length */)) {
   1510     return false;
   1511   }
   1512 
   1513   return true;
   1514 }
   1515 
   1516 static bool ext_channel_id_parse_serverhello(SSL_HANDSHAKE *hs,
   1517                                              uint8_t *out_alert,
   1518                                              CBS *contents) {
   1519   SSL *const ssl = hs->ssl;
   1520   if (contents == NULL) {
   1521     return true;
   1522   }
   1523 
   1524   assert(!SSL_is_dtls(ssl));
   1525   assert(ssl->tlsext_channel_id_enabled);
   1526 
   1527   if (CBS_len(contents) != 0) {
   1528     return false;
   1529   }
   1530 
   1531   ssl->s3->tlsext_channel_id_valid = true;
   1532   return true;
   1533 }
   1534 
   1535 static bool ext_channel_id_parse_clienthello(SSL_HANDSHAKE *hs,
   1536                                              uint8_t *out_alert,
   1537                                              CBS *contents) {
   1538   SSL *const ssl = hs->ssl;
   1539   if (contents == NULL ||
   1540       !ssl->tlsext_channel_id_enabled ||
   1541       SSL_is_dtls(ssl)) {
   1542     return true;
   1543   }
   1544 
   1545   if (CBS_len(contents) != 0) {
   1546     return false;
   1547   }
   1548 
   1549   ssl->s3->tlsext_channel_id_valid = true;
   1550   return true;
   1551 }
   1552 
   1553 static bool ext_channel_id_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   1554   SSL *const ssl = hs->ssl;
   1555   if (!ssl->s3->tlsext_channel_id_valid) {
   1556     return true;
   1557   }
   1558 
   1559   if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
   1560       !CBB_add_u16(out, 0 /* length */)) {
   1561     return false;
   1562   }
   1563 
   1564   return true;
   1565 }
   1566 
   1567 
   1568 // Secure Real-time Transport Protocol (SRTP) extension.
   1569 //
   1570 // https://tools.ietf.org/html/rfc5764
   1571 
   1572 
   1573 static void ext_srtp_init(SSL_HANDSHAKE *hs) {
   1574   hs->ssl->srtp_profile = NULL;
   1575 }
   1576 
   1577 static bool ext_srtp_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1578   SSL *const ssl = hs->ssl;
   1579   STACK_OF(SRTP_PROTECTION_PROFILE) *profiles = SSL_get_srtp_profiles(ssl);
   1580   if (profiles == NULL ||
   1581       sk_SRTP_PROTECTION_PROFILE_num(profiles) == 0) {
   1582     return true;
   1583   }
   1584 
   1585   CBB contents, profile_ids;
   1586   if (!CBB_add_u16(out, TLSEXT_TYPE_srtp) ||
   1587       !CBB_add_u16_length_prefixed(out, &contents) ||
   1588       !CBB_add_u16_length_prefixed(&contents, &profile_ids)) {
   1589     return false;
   1590   }
   1591 
   1592   for (const SRTP_PROTECTION_PROFILE *profile : profiles) {
   1593     if (!CBB_add_u16(&profile_ids, profile->id)) {
   1594       return false;
   1595     }
   1596   }
   1597 
   1598   if (!CBB_add_u8(&contents, 0 /* empty use_mki value */) ||
   1599       !CBB_flush(out)) {
   1600     return false;
   1601   }
   1602 
   1603   return true;
   1604 }
   1605 
   1606 static bool ext_srtp_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1607                                        CBS *contents) {
   1608   SSL *const ssl = hs->ssl;
   1609   if (contents == NULL) {
   1610     return true;
   1611   }
   1612 
   1613   // The extension consists of a u16-prefixed profile ID list containing a
   1614   // single uint16_t profile ID, then followed by a u8-prefixed srtp_mki field.
   1615   //
   1616   // See https://tools.ietf.org/html/rfc5764#section-4.1.1
   1617   CBS profile_ids, srtp_mki;
   1618   uint16_t profile_id;
   1619   if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
   1620       !CBS_get_u16(&profile_ids, &profile_id) ||
   1621       CBS_len(&profile_ids) != 0 ||
   1622       !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
   1623       CBS_len(contents) != 0) {
   1624     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
   1625     return false;
   1626   }
   1627 
   1628   if (CBS_len(&srtp_mki) != 0) {
   1629     // Must be no MKI, since we never offer one.
   1630     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_MKI_VALUE);
   1631     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1632     return false;
   1633   }
   1634 
   1635   STACK_OF(SRTP_PROTECTION_PROFILE) *profiles = SSL_get_srtp_profiles(ssl);
   1636 
   1637   // Check to see if the server gave us something we support (and presumably
   1638   // offered).
   1639   for (const SRTP_PROTECTION_PROFILE *profile : profiles) {
   1640     if (profile->id == profile_id) {
   1641       ssl->srtp_profile = profile;
   1642       return true;
   1643     }
   1644   }
   1645 
   1646   OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
   1647   *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1648   return false;
   1649 }
   1650 
   1651 static bool ext_srtp_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1652                                        CBS *contents) {
   1653   SSL *const ssl = hs->ssl;
   1654   if (contents == NULL) {
   1655     return true;
   1656   }
   1657 
   1658   CBS profile_ids, srtp_mki;
   1659   if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
   1660       CBS_len(&profile_ids) < 2 ||
   1661       !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
   1662       CBS_len(contents) != 0) {
   1663     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
   1664     return false;
   1665   }
   1666   // Discard the MKI value for now.
   1667 
   1668   const STACK_OF(SRTP_PROTECTION_PROFILE) *server_profiles =
   1669       SSL_get_srtp_profiles(ssl);
   1670 
   1671   // Pick the server's most preferred profile.
   1672   for (const SRTP_PROTECTION_PROFILE *server_profile : server_profiles) {
   1673     CBS profile_ids_tmp;
   1674     CBS_init(&profile_ids_tmp, CBS_data(&profile_ids), CBS_len(&profile_ids));
   1675 
   1676     while (CBS_len(&profile_ids_tmp) > 0) {
   1677       uint16_t profile_id;
   1678       if (!CBS_get_u16(&profile_ids_tmp, &profile_id)) {
   1679         return false;
   1680       }
   1681 
   1682       if (server_profile->id == profile_id) {
   1683         ssl->srtp_profile = server_profile;
   1684         return true;
   1685       }
   1686     }
   1687   }
   1688 
   1689   return true;
   1690 }
   1691 
   1692 static bool ext_srtp_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   1693   SSL *const ssl = hs->ssl;
   1694   if (ssl->srtp_profile == NULL) {
   1695     return true;
   1696   }
   1697 
   1698   CBB contents, profile_ids;
   1699   if (!CBB_add_u16(out, TLSEXT_TYPE_srtp) ||
   1700       !CBB_add_u16_length_prefixed(out, &contents) ||
   1701       !CBB_add_u16_length_prefixed(&contents, &profile_ids) ||
   1702       !CBB_add_u16(&profile_ids, ssl->srtp_profile->id) ||
   1703       !CBB_add_u8(&contents, 0 /* empty MKI */) ||
   1704       !CBB_flush(out)) {
   1705     return false;
   1706   }
   1707 
   1708   return true;
   1709 }
   1710 
   1711 
   1712 // EC point formats.
   1713 //
   1714 // https://tools.ietf.org/html/rfc4492#section-5.1.2
   1715 
   1716 static bool ext_ec_point_add_extension(SSL_HANDSHAKE *hs, CBB *out) {
   1717   CBB contents, formats;
   1718   if (!CBB_add_u16(out, TLSEXT_TYPE_ec_point_formats) ||
   1719       !CBB_add_u16_length_prefixed(out, &contents) ||
   1720       !CBB_add_u8_length_prefixed(&contents, &formats) ||
   1721       !CBB_add_u8(&formats, TLSEXT_ECPOINTFORMAT_uncompressed) ||
   1722       !CBB_flush(out)) {
   1723     return false;
   1724   }
   1725 
   1726   return true;
   1727 }
   1728 
   1729 static bool ext_ec_point_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1730   // The point format extension is unneccessary in TLS 1.3.
   1731   if (hs->min_version >= TLS1_3_VERSION) {
   1732     return true;
   1733   }
   1734 
   1735   return ext_ec_point_add_extension(hs, out);
   1736 }
   1737 
   1738 static bool ext_ec_point_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1739                                            CBS *contents) {
   1740   if (contents == NULL) {
   1741     return true;
   1742   }
   1743 
   1744   if (ssl_protocol_version(hs->ssl) >= TLS1_3_VERSION) {
   1745     return false;
   1746   }
   1747 
   1748   CBS ec_point_format_list;
   1749   if (!CBS_get_u8_length_prefixed(contents, &ec_point_format_list) ||
   1750       CBS_len(contents) != 0) {
   1751     return false;
   1752   }
   1753 
   1754   // Per RFC 4492, section 5.1.2, implementations MUST support the uncompressed
   1755   // point format.
   1756   if (OPENSSL_memchr(CBS_data(&ec_point_format_list),
   1757                      TLSEXT_ECPOINTFORMAT_uncompressed,
   1758                      CBS_len(&ec_point_format_list)) == NULL) {
   1759     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1760     return false;
   1761   }
   1762 
   1763   return true;
   1764 }
   1765 
   1766 static bool ext_ec_point_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
   1767                                           CBS *contents) {
   1768   if (ssl_protocol_version(hs->ssl) >= TLS1_3_VERSION) {
   1769     return true;
   1770   }
   1771 
   1772   return ext_ec_point_parse_serverhello(hs, out_alert, contents);
   1773 }
   1774 
   1775 static bool ext_ec_point_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   1776   SSL *const ssl = hs->ssl;
   1777   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
   1778     return true;
   1779   }
   1780 
   1781   const uint32_t alg_k = hs->new_cipher->algorithm_mkey;
   1782   const uint32_t alg_a = hs->new_cipher->algorithm_auth;
   1783   const bool using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);
   1784 
   1785   if (!using_ecc) {
   1786     return true;
   1787   }
   1788 
   1789   return ext_ec_point_add_extension(hs, out);
   1790 }
   1791 
   1792 
   1793 // Pre Shared Key
   1794 //
   1795 // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.6
   1796 
   1797 static size_t ext_pre_shared_key_clienthello_length(SSL_HANDSHAKE *hs) {
   1798   SSL *const ssl = hs->ssl;
   1799   if (hs->max_version < TLS1_3_VERSION || ssl->session == NULL ||
   1800       ssl_session_protocol_version(ssl->session) < TLS1_3_VERSION) {
   1801     return 0;
   1802   }
   1803 
   1804   size_t binder_len = EVP_MD_size(ssl_session_get_digest(ssl->session));
   1805   return 15 + ssl->session->tlsext_ticklen + binder_len;
   1806 }
   1807 
   1808 static bool ext_pre_shared_key_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1809   SSL *const ssl = hs->ssl;
   1810   hs->needs_psk_binder = false;
   1811   if (hs->max_version < TLS1_3_VERSION || ssl->session == NULL ||
   1812       ssl_session_protocol_version(ssl->session) < TLS1_3_VERSION) {
   1813     return true;
   1814   }
   1815 
   1816   // Per draft-ietf-tls-tls13-21 section 4.1.4, skip offering the session if the
   1817   // selected cipher in HelloRetryRequest does not match. This avoids performing
   1818   // the transcript hash transformation for multiple hashes.
   1819   if (hs->received_hello_retry_request &&
   1820       ssl->session->cipher->algorithm_prf != hs->new_cipher->algorithm_prf) {
   1821     return true;
   1822   }
   1823 
   1824   struct OPENSSL_timeval now;
   1825   ssl_get_current_time(ssl, &now);
   1826   uint32_t ticket_age = 1000 * (now.tv_sec - ssl->session->time);
   1827   uint32_t obfuscated_ticket_age = ticket_age + ssl->session->ticket_age_add;
   1828 
   1829   // Fill in a placeholder zero binder of the appropriate length. It will be
   1830   // computed and filled in later after length prefixes are computed.
   1831   uint8_t zero_binder[EVP_MAX_MD_SIZE] = {0};
   1832   size_t binder_len = EVP_MD_size(ssl_session_get_digest(ssl->session));
   1833 
   1834   CBB contents, identity, ticket, binders, binder;
   1835   if (!CBB_add_u16(out, TLSEXT_TYPE_pre_shared_key) ||
   1836       !CBB_add_u16_length_prefixed(out, &contents) ||
   1837       !CBB_add_u16_length_prefixed(&contents, &identity) ||
   1838       !CBB_add_u16_length_prefixed(&identity, &ticket) ||
   1839       !CBB_add_bytes(&ticket, ssl->session->tlsext_tick,
   1840                      ssl->session->tlsext_ticklen) ||
   1841       !CBB_add_u32(&identity, obfuscated_ticket_age) ||
   1842       !CBB_add_u16_length_prefixed(&contents, &binders) ||
   1843       !CBB_add_u8_length_prefixed(&binders, &binder) ||
   1844       !CBB_add_bytes(&binder, zero_binder, binder_len)) {
   1845     return false;
   1846   }
   1847 
   1848   hs->needs_psk_binder = true;
   1849   return CBB_flush(out);
   1850 }
   1851 
   1852 bool ssl_ext_pre_shared_key_parse_serverhello(SSL_HANDSHAKE *hs,
   1853                                               uint8_t *out_alert,
   1854                                               CBS *contents) {
   1855   uint16_t psk_id;
   1856   if (!CBS_get_u16(contents, &psk_id) ||
   1857       CBS_len(contents) != 0) {
   1858     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1859     *out_alert = SSL_AD_DECODE_ERROR;
   1860     return false;
   1861   }
   1862 
   1863   // We only advertise one PSK identity, so the only legal index is zero.
   1864   if (psk_id != 0) {
   1865     OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
   1866     *out_alert = SSL_AD_UNKNOWN_PSK_IDENTITY;
   1867     return false;
   1868   }
   1869 
   1870   return true;
   1871 }
   1872 
   1873 bool ssl_ext_pre_shared_key_parse_clienthello(
   1874     SSL_HANDSHAKE *hs, CBS *out_ticket, CBS *out_binders,
   1875     uint32_t *out_obfuscated_ticket_age, uint8_t *out_alert, CBS *contents) {
   1876   // We only process the first PSK identity since we don't support pure PSK.
   1877   CBS identities, binders;
   1878   if (!CBS_get_u16_length_prefixed(contents, &identities) ||
   1879       !CBS_get_u16_length_prefixed(&identities, out_ticket) ||
   1880       !CBS_get_u32(&identities, out_obfuscated_ticket_age) ||
   1881       !CBS_get_u16_length_prefixed(contents, &binders) ||
   1882       CBS_len(&binders) == 0 ||
   1883       CBS_len(contents) != 0) {
   1884     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1885     *out_alert = SSL_AD_DECODE_ERROR;
   1886     return false;
   1887   }
   1888 
   1889   *out_binders = binders;
   1890 
   1891   // Check the syntax of the remaining identities, but do not process them.
   1892   size_t num_identities = 1;
   1893   while (CBS_len(&identities) != 0) {
   1894     CBS unused_ticket;
   1895     uint32_t unused_obfuscated_ticket_age;
   1896     if (!CBS_get_u16_length_prefixed(&identities, &unused_ticket) ||
   1897         !CBS_get_u32(&identities, &unused_obfuscated_ticket_age)) {
   1898       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1899       *out_alert = SSL_AD_DECODE_ERROR;
   1900       return false;
   1901     }
   1902 
   1903     num_identities++;
   1904   }
   1905 
   1906   // Check the syntax of the binders. The value will be checked later if
   1907   // resuming.
   1908   size_t num_binders = 0;
   1909   while (CBS_len(&binders) != 0) {
   1910     CBS binder;
   1911     if (!CBS_get_u8_length_prefixed(&binders, &binder)) {
   1912       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1913       *out_alert = SSL_AD_DECODE_ERROR;
   1914       return false;
   1915     }
   1916 
   1917     num_binders++;
   1918   }
   1919 
   1920   if (num_identities != num_binders) {
   1921     OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_BINDER_COUNT_MISMATCH);
   1922     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1923     return false;
   1924   }
   1925 
   1926   return true;
   1927 }
   1928 
   1929 bool ssl_ext_pre_shared_key_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   1930   if (!hs->ssl->s3->session_reused) {
   1931     return true;
   1932   }
   1933 
   1934   CBB contents;
   1935   if (!CBB_add_u16(out, TLSEXT_TYPE_pre_shared_key) ||
   1936       !CBB_add_u16_length_prefixed(out, &contents) ||
   1937       // We only consider the first identity for resumption
   1938       !CBB_add_u16(&contents, 0) ||
   1939       !CBB_flush(out)) {
   1940     return false;
   1941   }
   1942 
   1943   return true;
   1944 }
   1945 
   1946 
   1947 // Pre-Shared Key Exchange Modes
   1948 //
   1949 // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.7
   1950 
   1951 static bool ext_psk_key_exchange_modes_add_clienthello(SSL_HANDSHAKE *hs,
   1952                                                        CBB *out) {
   1953   if (hs->max_version < TLS1_3_VERSION) {
   1954     return true;
   1955   }
   1956 
   1957   CBB contents, ke_modes;
   1958   if (!CBB_add_u16(out, TLSEXT_TYPE_psk_key_exchange_modes) ||
   1959       !CBB_add_u16_length_prefixed(out, &contents) ||
   1960       !CBB_add_u8_length_prefixed(&contents, &ke_modes) ||
   1961       !CBB_add_u8(&ke_modes, SSL_PSK_DHE_KE)) {
   1962     return false;
   1963   }
   1964 
   1965   return CBB_flush(out);
   1966 }
   1967 
   1968 static bool ext_psk_key_exchange_modes_parse_clienthello(SSL_HANDSHAKE *hs,
   1969                                                          uint8_t *out_alert,
   1970                                                          CBS *contents) {
   1971   if (contents == NULL) {
   1972     return true;
   1973   }
   1974 
   1975   CBS ke_modes;
   1976   if (!CBS_get_u8_length_prefixed(contents, &ke_modes) ||
   1977       CBS_len(&ke_modes) == 0 ||
   1978       CBS_len(contents) != 0) {
   1979     *out_alert = SSL_AD_DECODE_ERROR;
   1980     return false;
   1981   }
   1982 
   1983   // We only support tickets with PSK_DHE_KE.
   1984   hs->accept_psk_mode = OPENSSL_memchr(CBS_data(&ke_modes), SSL_PSK_DHE_KE,
   1985                                        CBS_len(&ke_modes)) != NULL;
   1986 
   1987   return true;
   1988 }
   1989 
   1990 
   1991 // Early Data Indication
   1992 //
   1993 // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8
   1994 
   1995 static bool ext_early_data_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   1996   SSL *const ssl = hs->ssl;
   1997   if (!ssl->cert->enable_early_data ||
   1998       // Session must be 0-RTT capable.
   1999       ssl->session == NULL ||
   2000       ssl_session_protocol_version(ssl->session) < TLS1_3_VERSION ||
   2001       ssl->session->ticket_max_early_data == 0 ||
   2002       // The second ClientHello never offers early data.
   2003       hs->received_hello_retry_request ||
   2004       // In case ALPN preferences changed since this session was established,
   2005       // avoid reporting a confusing value in |SSL_get0_alpn_selected|.
   2006       (ssl->session->early_alpn_len != 0 &&
   2007        !ssl_is_alpn_protocol_allowed(
   2008            ssl, MakeConstSpan(ssl->session->early_alpn,
   2009                               ssl->session->early_alpn_len)))) {
   2010     return true;
   2011   }
   2012 
   2013   hs->early_data_offered = true;
   2014 
   2015   if (!CBB_add_u16(out, TLSEXT_TYPE_early_data) ||
   2016       !CBB_add_u16(out, 0) ||
   2017       !CBB_flush(out)) {
   2018     return false;
   2019   }
   2020 
   2021   return true;
   2022 }
   2023 
   2024 static bool ext_early_data_parse_serverhello(SSL_HANDSHAKE *hs,
   2025                                              uint8_t *out_alert, CBS *contents) {
   2026   SSL *const ssl = hs->ssl;
   2027   if (contents == NULL) {
   2028     return true;
   2029   }
   2030 
   2031   if (CBS_len(contents) != 0) {
   2032     *out_alert = SSL_AD_DECODE_ERROR;
   2033     return false;
   2034   }
   2035 
   2036   if (!ssl->s3->session_reused) {
   2037     *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   2038     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
   2039     return false;
   2040   }
   2041 
   2042   ssl->s3->early_data_accepted = true;
   2043   return true;
   2044 }
   2045 
   2046 static bool ext_early_data_parse_clienthello(SSL_HANDSHAKE *hs,
   2047                                              uint8_t *out_alert, CBS *contents) {
   2048   SSL *const ssl = hs->ssl;
   2049   if (contents == NULL ||
   2050       ssl_protocol_version(ssl) < TLS1_3_VERSION) {
   2051     return true;
   2052   }
   2053 
   2054   if (CBS_len(contents) != 0) {
   2055     *out_alert = SSL_AD_DECODE_ERROR;
   2056     return false;
   2057   }
   2058 
   2059   hs->early_data_offered = true;
   2060   return true;
   2061 }
   2062 
   2063 static bool ext_early_data_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   2064   if (!hs->ssl->s3->early_data_accepted) {
   2065     return true;
   2066   }
   2067 
   2068   if (!CBB_add_u16(out, TLSEXT_TYPE_early_data) ||
   2069       !CBB_add_u16(out, 0) ||
   2070       !CBB_flush(out)) {
   2071     return false;
   2072   }
   2073 
   2074   return true;
   2075 }
   2076 
   2077 
   2078 // Key Share
   2079 //
   2080 // https://tools.ietf.org/html/draft-ietf-tls-tls13-16#section-4.2.5
   2081 
   2082 static bool ext_key_share_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   2083   SSL *const ssl = hs->ssl;
   2084   if (hs->max_version < TLS1_3_VERSION) {
   2085     return true;
   2086   }
   2087 
   2088   CBB contents, kse_bytes;
   2089   if (!CBB_add_u16(out, TLSEXT_TYPE_key_share) ||
   2090       !CBB_add_u16_length_prefixed(out, &contents) ||
   2091       !CBB_add_u16_length_prefixed(&contents, &kse_bytes)) {
   2092     return false;
   2093   }
   2094 
   2095   uint16_t group_id = hs->retry_group;
   2096   if (hs->received_hello_retry_request) {
   2097     // We received a HelloRetryRequest without a new curve, so there is no new
   2098     // share to append. Leave |hs->key_share| as-is.
   2099     if (group_id == 0 &&
   2100         !CBB_add_bytes(&kse_bytes, hs->key_share_bytes.data(),
   2101                        hs->key_share_bytes.size())) {
   2102       return false;
   2103     }
   2104     hs->key_share_bytes.Reset();
   2105     if (group_id == 0) {
   2106       return CBB_flush(out);
   2107     }
   2108   } else {
   2109     // Add a fake group. See draft-davidben-tls-grease-01.
   2110     if (ssl->ctx->grease_enabled &&
   2111         (!CBB_add_u16(&kse_bytes,
   2112                       ssl_get_grease_value(hs, ssl_grease_group)) ||
   2113          !CBB_add_u16(&kse_bytes, 1 /* length */) ||
   2114          !CBB_add_u8(&kse_bytes, 0 /* one byte key share */))) {
   2115       return false;
   2116     }
   2117 
   2118     // Predict the most preferred group.
   2119     Span<const uint16_t> groups = tls1_get_grouplist(ssl);
   2120     if (groups.empty()) {
   2121       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_GROUPS_SPECIFIED);
   2122       return false;
   2123     }
   2124 
   2125     group_id = groups[0];
   2126   }
   2127 
   2128   hs->key_share = SSLKeyShare::Create(group_id);
   2129   CBB key_exchange;
   2130   if (!hs->key_share ||
   2131       !CBB_add_u16(&kse_bytes, group_id) ||
   2132       !CBB_add_u16_length_prefixed(&kse_bytes, &key_exchange) ||
   2133       !hs->key_share->Offer(&key_exchange) ||
   2134       !CBB_flush(&kse_bytes)) {
   2135     return false;
   2136   }
   2137 
   2138   // Save the contents of the extension to repeat it in the second ClientHello.
   2139   if (!hs->received_hello_retry_request &&
   2140       !hs->key_share_bytes.CopyFrom(
   2141           MakeConstSpan(CBB_data(&kse_bytes), CBB_len(&kse_bytes)))) {
   2142     return false;
   2143   }
   2144 
   2145   return CBB_flush(out);
   2146 }
   2147 
   2148 bool ssl_ext_key_share_parse_serverhello(SSL_HANDSHAKE *hs,
   2149                                          Array<uint8_t> *out_secret,
   2150                                          uint8_t *out_alert, CBS *contents) {
   2151   CBS peer_key;
   2152   uint16_t group_id;
   2153   if (!CBS_get_u16(contents, &group_id) ||
   2154       !CBS_get_u16_length_prefixed(contents, &peer_key) ||
   2155       CBS_len(contents) != 0) {
   2156     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   2157     *out_alert = SSL_AD_DECODE_ERROR;
   2158     return false;
   2159   }
   2160 
   2161   if (hs->key_share->GroupID() != group_id) {
   2162     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   2163     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
   2164     return false;
   2165   }
   2166 
   2167   if (!hs->key_share->Finish(out_secret, out_alert, peer_key)) {
   2168     *out_alert = SSL_AD_INTERNAL_ERROR;
   2169     return false;
   2170   }
   2171 
   2172   hs->new_session->group_id = group_id;
   2173   hs->key_share.reset();
   2174   return true;
   2175 }
   2176 
   2177 bool ssl_ext_key_share_parse_clienthello(SSL_HANDSHAKE *hs, bool *out_found,
   2178                                          Array<uint8_t> *out_secret,
   2179                                          uint8_t *out_alert, CBS *contents) {
   2180   uint16_t group_id;
   2181   CBS key_shares;
   2182   if (!tls1_get_shared_group(hs, &group_id)) {
   2183     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_GROUP);
   2184     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
   2185     return false;
   2186   }
   2187 
   2188   if (!CBS_get_u16_length_prefixed(contents, &key_shares) ||
   2189       CBS_len(contents) != 0) {
   2190     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   2191     return false;
   2192   }
   2193 
   2194   // Find the corresponding key share.
   2195   CBS peer_key;
   2196   CBS_init(&peer_key, NULL, 0);
   2197   while (CBS_len(&key_shares) > 0) {
   2198     uint16_t id;
   2199     CBS peer_key_tmp;
   2200     if (!CBS_get_u16(&key_shares, &id) ||
   2201         !CBS_get_u16_length_prefixed(&key_shares, &peer_key_tmp) ||
   2202         CBS_len(&peer_key_tmp) == 0) {
   2203       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   2204       return false;
   2205     }
   2206 
   2207     if (id == group_id) {
   2208       if (CBS_len(&peer_key) != 0) {
   2209         OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_KEY_SHARE);
   2210         *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   2211         return false;
   2212       }
   2213 
   2214       peer_key = peer_key_tmp;
   2215       // Continue parsing the structure to keep peers honest.
   2216     }
   2217   }
   2218 
   2219   if (CBS_len(&peer_key) == 0) {
   2220     *out_found = false;
   2221     out_secret->Reset();
   2222     return true;
   2223   }
   2224 
   2225   // Compute the DH secret.
   2226   Array<uint8_t> secret;
   2227   ScopedCBB public_key;
   2228   UniquePtr<SSLKeyShare> key_share = SSLKeyShare::Create(group_id);
   2229   if (!key_share ||
   2230       !CBB_init(public_key.get(), 32) ||
   2231       !key_share->Accept(public_key.get(), &secret, out_alert, peer_key) ||
   2232       !CBBFinishArray(public_key.get(), &hs->ecdh_public_key)) {
   2233     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   2234     return false;
   2235   }
   2236 
   2237   *out_secret = std::move(secret);
   2238   *out_found = true;
   2239   return true;
   2240 }
   2241 
   2242 bool ssl_ext_key_share_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   2243   uint16_t group_id;
   2244   CBB kse_bytes, public_key;
   2245   if (!tls1_get_shared_group(hs, &group_id) ||
   2246       !CBB_add_u16(out, TLSEXT_TYPE_key_share) ||
   2247       !CBB_add_u16_length_prefixed(out, &kse_bytes) ||
   2248       !CBB_add_u16(&kse_bytes, group_id) ||
   2249       !CBB_add_u16_length_prefixed(&kse_bytes, &public_key) ||
   2250       !CBB_add_bytes(&public_key, hs->ecdh_public_key.data(),
   2251                      hs->ecdh_public_key.size()) ||
   2252       !CBB_flush(out)) {
   2253     return false;
   2254   }
   2255 
   2256   hs->ecdh_public_key.Reset();
   2257 
   2258   hs->new_session->group_id = group_id;
   2259   return true;
   2260 }
   2261 
   2262 
   2263 // Supported Versions
   2264 //
   2265 // https://tools.ietf.org/html/draft-ietf-tls-tls13-16#section-4.2.1
   2266 
   2267 static bool ext_supported_versions_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   2268   SSL *const ssl = hs->ssl;
   2269   if (hs->max_version <= TLS1_2_VERSION) {
   2270     return true;
   2271   }
   2272 
   2273   CBB contents, versions;
   2274   if (!CBB_add_u16(out, TLSEXT_TYPE_supported_versions) ||
   2275       !CBB_add_u16_length_prefixed(out, &contents) ||
   2276       !CBB_add_u8_length_prefixed(&contents, &versions)) {
   2277     return false;
   2278   }
   2279 
   2280   // Add a fake version. See draft-davidben-tls-grease-01.
   2281   if (ssl->ctx->grease_enabled &&
   2282       !CBB_add_u16(&versions, ssl_get_grease_value(hs, ssl_grease_version))) {
   2283     return false;
   2284   }
   2285 
   2286   if (!ssl_add_supported_versions(hs, &versions) ||
   2287       !CBB_flush(out)) {
   2288     return false;
   2289   }
   2290 
   2291   return true;
   2292 }
   2293 
   2294 
   2295 // Cookie
   2296 //
   2297 // https://tools.ietf.org/html/draft-ietf-tls-tls13-16#section-4.2.2
   2298 
   2299 static bool ext_cookie_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   2300   if (hs->cookie.empty()) {
   2301     return true;
   2302   }
   2303 
   2304   CBB contents, cookie;
   2305   if (!CBB_add_u16(out, TLSEXT_TYPE_cookie) ||
   2306       !CBB_add_u16_length_prefixed(out, &contents) ||
   2307       !CBB_add_u16_length_prefixed(&contents, &cookie) ||
   2308       !CBB_add_bytes(&cookie, hs->cookie.data(), hs->cookie.size()) ||
   2309       !CBB_flush(out)) {
   2310     return false;
   2311   }
   2312 
   2313   // The cookie is no longer needed in memory.
   2314   hs->cookie.Reset();
   2315   return true;
   2316 }
   2317 
   2318 
   2319 // Dummy PQ Padding extension
   2320 //
   2321 // Dummy post-quantum padding invovles the client (and later server) sending
   2322 // useless, random-looking bytes in an extension in their ClientHello or
   2323 // ServerHello. These extensions are sized to simulate a post-quantum
   2324 // key-exchange and so enable measurement of the latency impact of the
   2325 // additional bandwidth.
   2326 
   2327 static bool ext_dummy_pq_padding_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   2328   const size_t len = hs->ssl->dummy_pq_padding_len;
   2329   if (len == 0) {
   2330     return true;
   2331   }
   2332 
   2333   CBB contents;
   2334   uint8_t *buffer;
   2335   if (!CBB_add_u16(out, TLSEXT_TYPE_dummy_pq_padding) ||
   2336       !CBB_add_u16_length_prefixed(out, &contents) ||
   2337       !CBB_add_space(&contents, &buffer, len)) {
   2338     return false;
   2339   }
   2340 
   2341   // The length is used as the nonce so that different length extensions have
   2342   // different contents. There's no reason this has to be the case, it just
   2343   // makes things a little more obvious in a packet dump.
   2344   uint8_t nonce[12] = {0};
   2345   memcpy(nonce, &len, sizeof(len));
   2346 
   2347   memset(buffer, 0, len);
   2348   static const uint8_t kZeroKey[32] = {0};
   2349   CRYPTO_chacha_20(buffer, buffer, len, kZeroKey, nonce, 0);
   2350 
   2351   return CBB_flush(out);
   2352 }
   2353 
   2354 
   2355 // Negotiated Groups
   2356 //
   2357 // https://tools.ietf.org/html/rfc4492#section-5.1.2
   2358 // https://tools.ietf.org/html/draft-ietf-tls-tls13-16#section-4.2.4
   2359 
   2360 static bool ext_supported_groups_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   2361   SSL *const ssl = hs->ssl;
   2362   CBB contents, groups_bytes;
   2363   if (!CBB_add_u16(out, TLSEXT_TYPE_supported_groups) ||
   2364       !CBB_add_u16_length_prefixed(out, &contents) ||
   2365       !CBB_add_u16_length_prefixed(&contents, &groups_bytes)) {
   2366     return false;
   2367   }
   2368 
   2369   // Add a fake group. See draft-davidben-tls-grease-01.
   2370   if (ssl->ctx->grease_enabled &&
   2371       !CBB_add_u16(&groups_bytes,
   2372                    ssl_get_grease_value(hs, ssl_grease_group))) {
   2373     return false;
   2374   }
   2375 
   2376   for (uint16_t group : tls1_get_grouplist(ssl)) {
   2377     if (!CBB_add_u16(&groups_bytes, group)) {
   2378       return false;
   2379     }
   2380   }
   2381 
   2382   return CBB_flush(out);
   2383 }
   2384 
   2385 static bool ext_supported_groups_parse_serverhello(SSL_HANDSHAKE *hs,
   2386                                                    uint8_t *out_alert,
   2387                                                    CBS *contents) {
   2388   // This extension is not expected to be echoed by servers in TLS 1.2, but some
   2389   // BigIP servers send it nonetheless, so do not enforce this.
   2390   return true;
   2391 }
   2392 
   2393 static bool parse_u16_array(const CBS *cbs, Array<uint16_t> *out) {
   2394   CBS copy = *cbs;
   2395   if ((CBS_len(&copy) & 1) != 0) {
   2396     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   2397     return false;
   2398   }
   2399 
   2400   Array<uint16_t> ret;
   2401   if (!ret.Init(CBS_len(&copy) / 2)) {
   2402     return false;
   2403   }
   2404   for (size_t i = 0; i < ret.size(); i++) {
   2405     if (!CBS_get_u16(&copy, &ret[i])) {
   2406       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2407       return false;
   2408     }
   2409   }
   2410 
   2411   assert(CBS_len(&copy) == 0);
   2412   *out = std::move(ret);
   2413   return 1;
   2414 }
   2415 
   2416 static bool ext_supported_groups_parse_clienthello(SSL_HANDSHAKE *hs,
   2417                                                   uint8_t *out_alert,
   2418                                                    CBS *contents) {
   2419   if (contents == NULL) {
   2420     return true;
   2421   }
   2422 
   2423   CBS supported_group_list;
   2424   if (!CBS_get_u16_length_prefixed(contents, &supported_group_list) ||
   2425       CBS_len(&supported_group_list) == 0 ||
   2426       CBS_len(contents) != 0 ||
   2427       !parse_u16_array(&supported_group_list, &hs->peer_supported_group_list)) {
   2428     return false;
   2429   }
   2430 
   2431   return true;
   2432 }
   2433 
   2434 // Token Binding
   2435 //
   2436 // https://tools.ietf.org/html/draft-ietf-tokbind-negotiation-10
   2437 
   2438 // The Token Binding version number currently matches the draft number of
   2439 // draft-ietf-tokbind-protocol, and when published as an RFC it will be 0x0100.
   2440 // Since there are no wire changes to the protocol from draft 13 through the
   2441 // current draft (16), this implementation supports all versions in that range.
   2442 static uint16_t kTokenBindingMaxVersion = 16;
   2443 static uint16_t kTokenBindingMinVersion = 13;
   2444 
   2445 static bool ext_token_binding_add_clienthello(SSL_HANDSHAKE *hs, CBB *out) {
   2446   SSL *const ssl = hs->ssl;
   2447   if (ssl->token_binding_params == nullptr || SSL_is_dtls(ssl)) {
   2448     return true;
   2449   }
   2450 
   2451   CBB contents, params;
   2452   if (!CBB_add_u16(out, TLSEXT_TYPE_token_binding) ||
   2453       !CBB_add_u16_length_prefixed(out, &contents) ||
   2454       !CBB_add_u16(&contents, kTokenBindingMaxVersion) ||
   2455       !CBB_add_u8_length_prefixed(&contents, &params) ||
   2456       !CBB_add_bytes(&params, ssl->token_binding_params,
   2457                      ssl->token_binding_params_len) ||
   2458       !CBB_flush(out)) {
   2459     return false;
   2460   }
   2461 
   2462   return true;
   2463 }
   2464 
   2465 static bool ext_token_binding_parse_serverhello(SSL_HANDSHAKE *hs,
   2466                                                 uint8_t *out_alert,
   2467                                                 CBS *contents) {
   2468   SSL *const ssl = hs->ssl;
   2469   if (contents == nullptr) {
   2470     return true;
   2471   }
   2472 
   2473   CBS params_list;
   2474   uint16_t version;
   2475   uint8_t param;
   2476   if (!CBS_get_u16(contents, &version) ||
   2477       !CBS_get_u8_length_prefixed(contents, &params_list) ||
   2478       !CBS_get_u8(&params_list, &param) ||
   2479       CBS_len(&params_list) > 0 ||
   2480       CBS_len(contents) > 0) {
   2481     *out_alert = SSL_AD_DECODE_ERROR;
   2482     return false;
   2483   }
   2484 
   2485   // The server-negotiated version must be less than or equal to our version.
   2486   if (version > kTokenBindingMaxVersion) {
   2487     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   2488     return false;
   2489   }
   2490 
   2491   // If the server-selected version is less than what we support, then Token
   2492   // Binding wasn't negotiated (but the extension was parsed successfully).
   2493   if (version < kTokenBindingMinVersion) {
   2494     return true;
   2495   }
   2496 
   2497   for (size_t i = 0; i < ssl->token_binding_params_len; ++i) {
   2498     if (param == ssl->token_binding_params[i]) {
   2499       ssl->negotiated_token_binding_param = param;
   2500       ssl->token_binding_negotiated = true;
   2501       return true;
   2502     }
   2503   }
   2504 
   2505   *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   2506   return false;
   2507 }
   2508 
   2509 // select_tb_param looks for the first token binding param in
   2510 // |ssl->token_binding_params| that is also in |params| and puts it in
   2511 // |ssl->negotiated_token_binding_param|. It returns true if a token binding
   2512 // param is found, and false otherwise.
   2513 static bool select_tb_param(SSL *ssl, Span<const uint8_t> peer_params) {
   2514   for (size_t i = 0; i < ssl->token_binding_params_len; ++i) {
   2515     uint8_t tb_param = ssl->token_binding_params[i];
   2516     for (uint8_t peer_param : peer_params) {
   2517       if (tb_param == peer_param) {
   2518         ssl->negotiated_token_binding_param = tb_param;
   2519         return true;
   2520       }
   2521     }
   2522   }
   2523   return false;
   2524 }
   2525 
   2526 static bool ext_token_binding_parse_clienthello(SSL_HANDSHAKE *hs,
   2527                                                 uint8_t *out_alert,
   2528                                                 CBS *contents) {
   2529   SSL *const ssl = hs->ssl;
   2530   if (contents == nullptr || ssl->token_binding_params == nullptr) {
   2531     return true;
   2532   }
   2533 
   2534   CBS params;
   2535   uint16_t version;
   2536   if (!CBS_get_u16(contents, &version) ||
   2537       !CBS_get_u8_length_prefixed(contents, &params) ||
   2538       CBS_len(&params) == 0 ||
   2539       CBS_len(contents) > 0) {
   2540     *out_alert = SSL_AD_DECODE_ERROR;
   2541     return false;
   2542   }
   2543 
   2544   // If the client-selected version is less than what we support, then Token
   2545   // Binding wasn't negotiated (but the extension was parsed successfully).
   2546   if (version < kTokenBindingMinVersion) {
   2547     return true;
   2548   }
   2549 
   2550   // If the client-selected version is higher than we support, use our max
   2551   // version. Otherwise, use the client's version.
   2552   hs->negotiated_token_binding_version =
   2553       std::min(version, kTokenBindingMaxVersion);
   2554   if (!select_tb_param(ssl, params)) {
   2555     return true;
   2556   }
   2557 
   2558   ssl->token_binding_negotiated = true;
   2559   return true;
   2560 }
   2561 
   2562 static bool ext_token_binding_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
   2563   SSL *const ssl = hs->ssl;
   2564 
   2565   if (!ssl->token_binding_negotiated) {
   2566     return true;
   2567   }
   2568 
   2569   CBB contents, params;
   2570   if (!CBB_add_u16(out, TLSEXT_TYPE_token_binding) ||
   2571       !CBB_add_u16_length_prefixed(out, &contents) ||
   2572       !CBB_add_u16(&contents, hs->negotiated_token_binding_version) ||
   2573       !CBB_add_u8_length_prefixed(&contents, &params) ||
   2574       !CBB_add_u8(&params, ssl->negotiated_token_binding_param) ||
   2575       !CBB_flush(out)) {
   2576     return false;
   2577   }
   2578 
   2579   return true;
   2580 }
   2581 
   2582 // QUIC Transport Parameters
   2583 
   2584 static bool ext_quic_transport_params_add_clienthello(SSL_HANDSHAKE *hs,
   2585                                                       CBB *out) {
   2586   SSL *const ssl = hs->ssl;
   2587   if (!ssl->quic_transport_params || hs->max_version <= TLS1_2_VERSION) {
   2588     return true;
   2589   }
   2590 
   2591   CBB contents;
   2592   if (!CBB_add_u16(out, TLSEXT_TYPE_quic_transport_parameters) ||
   2593       !CBB_add_u16_length_prefixed(out, &contents) ||
   2594       !CBB_add_bytes(&contents, ssl->quic_transport_params,
   2595                      ssl->quic_transport_params_len) ||
   2596       !CBB_flush(out)) {
   2597     return false;
   2598   }
   2599   return true;
   2600 }
   2601 
   2602 static bool ext_quic_transport_params_parse_serverhello(SSL_HANDSHAKE *hs,
   2603                                                         uint8_t *out_alert,
   2604                                                         CBS *contents) {
   2605   SSL *const ssl = hs->ssl;
   2606   if (contents == nullptr) {
   2607     return true;
   2608   }
   2609   // QUIC requires TLS 1.3.
   2610   if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
   2611     *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   2612     return false;
   2613   }
   2614 
   2615   return ssl->s3->peer_quic_transport_params.CopyFrom(*contents);
   2616 }
   2617 
   2618 static bool ext_quic_transport_params_parse_clienthello(SSL_HANDSHAKE *hs,
   2619                                                         uint8_t *out_alert,
   2620                                                         CBS *contents) {
   2621   SSL *const ssl = hs->ssl;
   2622   if (!contents || !ssl->quic_transport_params) {
   2623     return true;
   2624   }
   2625   // Ignore the extension before TLS 1.3.
   2626   if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
   2627     return true;
   2628   }
   2629 
   2630   return ssl->s3->peer_quic_transport_params.CopyFrom(*contents);
   2631 }
   2632 
   2633 static bool ext_quic_transport_params_add_serverhello(SSL_HANDSHAKE *hs,
   2634                                                       CBB *out) {
   2635   SSL *const ssl = hs->ssl;
   2636   if (!ssl->quic_transport_params) {
   2637     return true;
   2638   }
   2639 
   2640   CBB contents;
   2641   if (!CBB_add_u16(out, TLSEXT_TYPE_quic_transport_parameters) ||
   2642       !CBB_add_u16_length_prefixed(out, &contents) ||
   2643       !CBB_add_bytes(&contents, ssl->quic_transport_params,
   2644                      ssl->quic_transport_params_len) ||
   2645       !CBB_flush(out)) {
   2646     return false;
   2647   }
   2648 
   2649   return true;
   2650 }
   2651 
   2652 
   2653 // kExtensions contains all the supported extensions.
   2654 static const struct tls_extension kExtensions[] = {
   2655   {
   2656     TLSEXT_TYPE_renegotiate,
   2657     NULL,
   2658     ext_ri_add_clienthello,
   2659     ext_ri_parse_serverhello,
   2660     ext_ri_parse_clienthello,
   2661     ext_ri_add_serverhello,
   2662   },
   2663   {
   2664     TLSEXT_TYPE_server_name,
   2665     NULL,
   2666     ext_sni_add_clienthello,
   2667     ext_sni_parse_serverhello,
   2668     ext_sni_parse_clienthello,
   2669     ext_sni_add_serverhello,
   2670   },
   2671   {
   2672     TLSEXT_TYPE_extended_master_secret,
   2673     NULL,
   2674     ext_ems_add_clienthello,
   2675     ext_ems_parse_serverhello,
   2676     ext_ems_parse_clienthello,
   2677     ext_ems_add_serverhello,
   2678   },
   2679   {
   2680     TLSEXT_TYPE_session_ticket,
   2681     NULL,
   2682     ext_ticket_add_clienthello,
   2683     ext_ticket_parse_serverhello,
   2684     // Ticket extension client parsing is handled in ssl_session.c
   2685     ignore_parse_clienthello,
   2686     ext_ticket_add_serverhello,
   2687   },
   2688   {
   2689     TLSEXT_TYPE_signature_algorithms,
   2690     NULL,
   2691     ext_sigalgs_add_clienthello,
   2692     forbid_parse_serverhello,
   2693     ext_sigalgs_parse_clienthello,
   2694     dont_add_serverhello,
   2695   },
   2696   {
   2697     TLSEXT_TYPE_status_request,
   2698     NULL,
   2699     ext_ocsp_add_clienthello,
   2700     ext_ocsp_parse_serverhello,
   2701     ext_ocsp_parse_clienthello,
   2702     ext_ocsp_add_serverhello,
   2703   },
   2704   {
   2705     TLSEXT_TYPE_next_proto_neg,
   2706     NULL,
   2707     ext_npn_add_clienthello,
   2708     ext_npn_parse_serverhello,
   2709     ext_npn_parse_clienthello,
   2710     ext_npn_add_serverhello,
   2711   },
   2712   {
   2713     TLSEXT_TYPE_certificate_timestamp,
   2714     NULL,
   2715     ext_sct_add_clienthello,
   2716     ext_sct_parse_serverhello,
   2717     ext_sct_parse_clienthello,
   2718     ext_sct_add_serverhello,
   2719   },
   2720   {
   2721     TLSEXT_TYPE_application_layer_protocol_negotiation,
   2722     NULL,
   2723     ext_alpn_add_clienthello,
   2724     ext_alpn_parse_serverhello,
   2725     // ALPN is negotiated late in |ssl_negotiate_alpn|.
   2726     ignore_parse_clienthello,
   2727     ext_alpn_add_serverhello,
   2728   },
   2729   {
   2730     TLSEXT_TYPE_channel_id,
   2731     ext_channel_id_init,
   2732     ext_channel_id_add_clienthello,
   2733     ext_channel_id_parse_serverhello,
   2734     ext_channel_id_parse_clienthello,
   2735     ext_channel_id_add_serverhello,
   2736   },
   2737   {
   2738     TLSEXT_TYPE_srtp,
   2739     ext_srtp_init,
   2740     ext_srtp_add_clienthello,
   2741     ext_srtp_parse_serverhello,
   2742     ext_srtp_parse_clienthello,
   2743     ext_srtp_add_serverhello,
   2744   },
   2745   {
   2746     TLSEXT_TYPE_ec_point_formats,
   2747     NULL,
   2748     ext_ec_point_add_clienthello,
   2749     ext_ec_point_parse_serverhello,
   2750     ext_ec_point_parse_clienthello,
   2751     ext_ec_point_add_serverhello,
   2752   },
   2753   {
   2754     TLSEXT_TYPE_key_share,
   2755     NULL,
   2756     ext_key_share_add_clienthello,
   2757     forbid_parse_serverhello,
   2758     ignore_parse_clienthello,
   2759     dont_add_serverhello,
   2760   },
   2761   {
   2762     TLSEXT_TYPE_psk_key_exchange_modes,
   2763     NULL,
   2764     ext_psk_key_exchange_modes_add_clienthello,
   2765     forbid_parse_serverhello,
   2766     ext_psk_key_exchange_modes_parse_clienthello,
   2767     dont_add_serverhello,
   2768   },
   2769   {
   2770     TLSEXT_TYPE_early_data,
   2771     NULL,
   2772     ext_early_data_add_clienthello,
   2773     ext_early_data_parse_serverhello,
   2774     ext_early_data_parse_clienthello,
   2775     ext_early_data_add_serverhello,
   2776   },
   2777   {
   2778     TLSEXT_TYPE_supported_versions,
   2779     NULL,
   2780     ext_supported_versions_add_clienthello,
   2781     forbid_parse_serverhello,
   2782     ignore_parse_clienthello,
   2783     dont_add_serverhello,
   2784   },
   2785   {
   2786     TLSEXT_TYPE_cookie,
   2787     NULL,
   2788     ext_cookie_add_clienthello,
   2789     forbid_parse_serverhello,
   2790     ignore_parse_clienthello,
   2791     dont_add_serverhello,
   2792   },
   2793   {
   2794     TLSEXT_TYPE_dummy_pq_padding,
   2795     NULL,
   2796     ext_dummy_pq_padding_add_clienthello,
   2797     ignore_parse_serverhello,
   2798     ignore_parse_clienthello,
   2799     dont_add_serverhello,
   2800   },
   2801   {
   2802     TLSEXT_TYPE_quic_transport_parameters,
   2803     NULL,
   2804     ext_quic_transport_params_add_clienthello,
   2805     ext_quic_transport_params_parse_serverhello,
   2806     ext_quic_transport_params_parse_clienthello,
   2807     ext_quic_transport_params_add_serverhello,
   2808   },
   2809   // The final extension must be non-empty. WebSphere Application Server 7.0 is
   2810   // intolerant to the last extension being zero-length. See
   2811   // https://crbug.com/363583.
   2812   {
   2813     TLSEXT_TYPE_supported_groups,
   2814     NULL,
   2815     ext_supported_groups_add_clienthello,
   2816     ext_supported_groups_parse_serverhello,
   2817     ext_supported_groups_parse_clienthello,
   2818     dont_add_serverhello,
   2819   },
   2820   {
   2821     TLSEXT_TYPE_token_binding,
   2822     NULL,
   2823     ext_token_binding_add_clienthello,
   2824     ext_token_binding_parse_serverhello,
   2825     ext_token_binding_parse_clienthello,
   2826     ext_token_binding_add_serverhello,
   2827   },
   2828 };
   2829 
   2830 #define kNumExtensions (sizeof(kExtensions) / sizeof(struct tls_extension))
   2831 
   2832 static_assert(kNumExtensions <=
   2833                   sizeof(((SSL_HANDSHAKE *)NULL)->extensions.sent) * 8,
   2834               "too many extensions for sent bitset");
   2835 static_assert(kNumExtensions <=
   2836                   sizeof(((SSL_HANDSHAKE *)NULL)->extensions.received) * 8,
   2837               "too many extensions for received bitset");
   2838 
   2839 static const struct tls_extension *tls_extension_find(uint32_t *out_index,
   2840                                                       uint16_t value) {
   2841   unsigned i;
   2842   for (i = 0; i < kNumExtensions; i++) {
   2843     if (kExtensions[i].value == value) {
   2844       *out_index = i;
   2845       return &kExtensions[i];
   2846     }
   2847   }
   2848 
   2849   return NULL;
   2850 }
   2851 
   2852 int ssl_add_clienthello_tlsext(SSL_HANDSHAKE *hs, CBB *out, size_t header_len) {
   2853   SSL *const ssl = hs->ssl;
   2854   // Don't add extensions for SSLv3 unless doing secure renegotiation.
   2855   if (hs->client_version == SSL3_VERSION &&
   2856       !ssl->s3->send_connection_binding) {
   2857     return 1;
   2858   }
   2859 
   2860   CBB extensions;
   2861   if (!CBB_add_u16_length_prefixed(out, &extensions)) {
   2862     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2863     return 0;
   2864   }
   2865 
   2866   hs->extensions.sent = 0;
   2867   hs->custom_extensions.sent = 0;
   2868 
   2869   for (size_t i = 0; i < kNumExtensions; i++) {
   2870     if (kExtensions[i].init != NULL) {
   2871       kExtensions[i].init(hs);
   2872     }
   2873   }
   2874 
   2875   uint16_t grease_ext1 = 0;
   2876   if (ssl->ctx->grease_enabled) {
   2877     // Add a fake empty extension. See draft-davidben-tls-grease-01.
   2878     grease_ext1 = ssl_get_grease_value(hs, ssl_grease_extension1);
   2879     if (!CBB_add_u16(&extensions, grease_ext1) ||
   2880         !CBB_add_u16(&extensions, 0 /* zero length */)) {
   2881       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2882       return 0;
   2883     }
   2884   }
   2885 
   2886   for (size_t i = 0; i < kNumExtensions; i++) {
   2887     const size_t len_before = CBB_len(&extensions);
   2888     if (!kExtensions[i].add_clienthello(hs, &extensions)) {
   2889       OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
   2890       ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
   2891       return 0;
   2892     }
   2893 
   2894     if (CBB_len(&extensions) != len_before) {
   2895       hs->extensions.sent |= (1u << i);
   2896     }
   2897   }
   2898 
   2899   if (!custom_ext_add_clienthello(hs, &extensions)) {
   2900     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2901     return 0;
   2902   }
   2903 
   2904   if (ssl->ctx->grease_enabled) {
   2905     // Add a fake non-empty extension. See draft-davidben-tls-grease-01.
   2906     uint16_t grease_ext2 = ssl_get_grease_value(hs, ssl_grease_extension2);
   2907 
   2908     // The two fake extensions must not have the same value. GREASE values are
   2909     // of the form 0x1a1a, 0x2a2a, 0x3a3a, etc., so XOR to generate a different
   2910     // one.
   2911     if (grease_ext1 == grease_ext2) {
   2912       grease_ext2 ^= 0x1010;
   2913     }
   2914 
   2915     if (!CBB_add_u16(&extensions, grease_ext2) ||
   2916         !CBB_add_u16(&extensions, 1 /* one byte length */) ||
   2917         !CBB_add_u8(&extensions, 0 /* single zero byte as contents */)) {
   2918       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2919       return 0;
   2920     }
   2921   }
   2922 
   2923   if (!SSL_is_dtls(ssl)) {
   2924     size_t psk_extension_len = ext_pre_shared_key_clienthello_length(hs);
   2925     header_len += 2 + CBB_len(&extensions) + psk_extension_len;
   2926     if (header_len > 0xff && header_len < 0x200) {
   2927       // Add padding to workaround bugs in F5 terminators. See RFC 7685.
   2928       //
   2929       // NB: because this code works out the length of all existing extensions
   2930       // it MUST always appear last.
   2931       size_t padding_len = 0x200 - header_len;
   2932       // Extensions take at least four bytes to encode. Always include at least
   2933       // one byte of data if including the extension. WebSphere Application
   2934       // Server 7.0 is intolerant to the last extension being zero-length. See
   2935       // https://crbug.com/363583.
   2936       if (padding_len >= 4 + 1) {
   2937         padding_len -= 4;
   2938       } else {
   2939         padding_len = 1;
   2940       }
   2941 
   2942       uint8_t *padding_bytes;
   2943       if (!CBB_add_u16(&extensions, TLSEXT_TYPE_padding) ||
   2944           !CBB_add_u16(&extensions, padding_len) ||
   2945           !CBB_add_space(&extensions, &padding_bytes, padding_len)) {
   2946         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2947         return 0;
   2948       }
   2949 
   2950       OPENSSL_memset(padding_bytes, 0, padding_len);
   2951     }
   2952   }
   2953 
   2954   // The PSK extension must be last, including after the padding.
   2955   if (!ext_pre_shared_key_add_clienthello(hs, &extensions)) {
   2956     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2957     return 0;
   2958   }
   2959 
   2960   // Discard empty extensions blocks.
   2961   if (CBB_len(&extensions) == 0) {
   2962     CBB_discard_child(out);
   2963   }
   2964 
   2965   return CBB_flush(out);
   2966 }
   2967 
   2968 int ssl_add_serverhello_tlsext(SSL_HANDSHAKE *hs, CBB *out) {
   2969   SSL *const ssl = hs->ssl;
   2970   CBB extensions;
   2971   if (!CBB_add_u16_length_prefixed(out, &extensions)) {
   2972     goto err;
   2973   }
   2974 
   2975   for (unsigned i = 0; i < kNumExtensions; i++) {
   2976     if (!(hs->extensions.received & (1u << i))) {
   2977       // Don't send extensions that were not received.
   2978       continue;
   2979     }
   2980 
   2981     if (!kExtensions[i].add_serverhello(hs, &extensions)) {
   2982       OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
   2983       ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
   2984       goto err;
   2985     }
   2986   }
   2987 
   2988   if (!custom_ext_add_serverhello(hs, &extensions)) {
   2989     goto err;
   2990   }
   2991 
   2992   // Discard empty extensions blocks before TLS 1.3.
   2993   if (ssl_protocol_version(ssl) < TLS1_3_VERSION &&
   2994       CBB_len(&extensions) == 0) {
   2995     CBB_discard_child(out);
   2996   }
   2997 
   2998   return CBB_flush(out);
   2999 
   3000 err:
   3001   OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   3002   return 0;
   3003 }
   3004 
   3005 static int ssl_scan_clienthello_tlsext(SSL_HANDSHAKE *hs,
   3006                                        const SSL_CLIENT_HELLO *client_hello,
   3007                                        int *out_alert) {
   3008   SSL *const ssl = hs->ssl;
   3009   for (size_t i = 0; i < kNumExtensions; i++) {
   3010     if (kExtensions[i].init != NULL) {
   3011       kExtensions[i].init(hs);
   3012     }
   3013   }
   3014 
   3015   hs->extensions.received = 0;
   3016   hs->custom_extensions.received = 0;
   3017   CBS extensions;
   3018   CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
   3019   while (CBS_len(&extensions) != 0) {
   3020     uint16_t type;
   3021     CBS extension;
   3022 
   3023     // Decode the next extension.
   3024     if (!CBS_get_u16(&extensions, &type) ||
   3025         !CBS_get_u16_length_prefixed(&extensions, &extension)) {
   3026       *out_alert = SSL_AD_DECODE_ERROR;
   3027       return 0;
   3028     }
   3029 
   3030     // RFC 5746 made the existence of extensions in SSL 3.0 somewhat
   3031     // ambiguous. Ignore all but the renegotiation_info extension.
   3032     if (ssl->version == SSL3_VERSION && type != TLSEXT_TYPE_renegotiate) {
   3033       continue;
   3034     }
   3035 
   3036     unsigned ext_index;
   3037     const struct tls_extension *const ext =
   3038         tls_extension_find(&ext_index, type);
   3039 
   3040     if (ext == NULL) {
   3041       if (!custom_ext_parse_clienthello(hs, out_alert, type, &extension)) {
   3042         OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
   3043         return 0;
   3044       }
   3045       continue;
   3046     }
   3047 
   3048     hs->extensions.received |= (1u << ext_index);
   3049     uint8_t alert = SSL_AD_DECODE_ERROR;
   3050     if (!ext->parse_clienthello(hs, &alert, &extension)) {
   3051       *out_alert = alert;
   3052       OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
   3053       ERR_add_error_dataf("extension %u", (unsigned)type);
   3054       return 0;
   3055     }
   3056   }
   3057 
   3058   for (size_t i = 0; i < kNumExtensions; i++) {
   3059     if (hs->extensions.received & (1u << i)) {
   3060       continue;
   3061     }
   3062 
   3063     CBS *contents = NULL, fake_contents;
   3064     static const uint8_t kFakeRenegotiateExtension[] = {0};
   3065     if (kExtensions[i].value == TLSEXT_TYPE_renegotiate &&
   3066         ssl_client_cipher_list_contains_cipher(client_hello,
   3067                                                SSL3_CK_SCSV & 0xffff)) {
   3068       // The renegotiation SCSV was received so pretend that we received a
   3069       // renegotiation extension.
   3070       CBS_init(&fake_contents, kFakeRenegotiateExtension,
   3071                sizeof(kFakeRenegotiateExtension));
   3072       contents = &fake_contents;
   3073       hs->extensions.received |= (1u << i);
   3074     }
   3075 
   3076     // Extension wasn't observed so call the callback with a NULL
   3077     // parameter.
   3078     uint8_t alert = SSL_AD_DECODE_ERROR;
   3079     if (!kExtensions[i].parse_clienthello(hs, &alert, contents)) {
   3080       OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
   3081       ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
   3082       *out_alert = alert;
   3083       return 0;
   3084     }
   3085   }
   3086 
   3087   return 1;
   3088 }
   3089 
   3090 int ssl_parse_clienthello_tlsext(SSL_HANDSHAKE *hs,
   3091                                  const SSL_CLIENT_HELLO *client_hello) {
   3092   SSL *const ssl = hs->ssl;
   3093   int alert = SSL_AD_DECODE_ERROR;
   3094   if (ssl_scan_clienthello_tlsext(hs, client_hello, &alert) <= 0) {
   3095     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
   3096     return 0;
   3097   }
   3098 
   3099   if (ssl_check_clienthello_tlsext(hs) <= 0) {
   3100     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_TLSEXT);
   3101     return 0;
   3102   }
   3103 
   3104   return 1;
   3105 }
   3106 
   3107 static int ssl_scan_serverhello_tlsext(SSL_HANDSHAKE *hs, CBS *cbs,
   3108                                        int *out_alert) {
   3109   SSL *const ssl = hs->ssl;
   3110   // Before TLS 1.3, ServerHello extensions blocks may be omitted if empty.
   3111   if (CBS_len(cbs) == 0 && ssl_protocol_version(ssl) < TLS1_3_VERSION) {
   3112     return 1;
   3113   }
   3114 
   3115   // Decode the extensions block and check it is valid.
   3116   CBS extensions;
   3117   if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
   3118       !tls1_check_duplicate_extensions(&extensions)) {
   3119     *out_alert = SSL_AD_DECODE_ERROR;
   3120     return 0;
   3121   }
   3122 
   3123   uint32_t received = 0;
   3124   while (CBS_len(&extensions) != 0) {
   3125     uint16_t type;
   3126     CBS extension;
   3127 
   3128     // Decode the next extension.
   3129     if (!CBS_get_u16(&extensions, &type) ||
   3130         !CBS_get_u16_length_prefixed(&extensions, &extension)) {
   3131       *out_alert = SSL_AD_DECODE_ERROR;
   3132       return 0;
   3133     }
   3134 
   3135     unsigned ext_index;
   3136     const struct tls_extension *const ext =
   3137         tls_extension_find(&ext_index, type);
   3138 
   3139     if (ext == NULL) {
   3140       hs->received_custom_extension = true;
   3141       if (!custom_ext_parse_serverhello(hs, out_alert, type, &extension)) {
   3142         return 0;
   3143       }
   3144       continue;
   3145     }
   3146 
   3147     static_assert(kNumExtensions <= sizeof(hs->extensions.sent) * 8,
   3148                   "too many bits");
   3149 
   3150     if (!(hs->extensions.sent & (1u << ext_index)) &&
   3151         type != TLSEXT_TYPE_renegotiate) {
   3152       // If the extension was never sent then it is illegal, except for the
   3153       // renegotiation extension which, in SSL 3.0, is signaled via SCSV.
   3154       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
   3155       ERR_add_error_dataf("extension :%u", (unsigned)type);
   3156       *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   3157       return 0;
   3158     }
   3159 
   3160     received |= (1u << ext_index);
   3161 
   3162     uint8_t alert = SSL_AD_DECODE_ERROR;
   3163     if (!ext->parse_serverhello(hs, &alert, &extension)) {
   3164       OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
   3165       ERR_add_error_dataf("extension %u", (unsigned)type);
   3166       *out_alert = alert;
   3167       return 0;
   3168     }
   3169   }
   3170 
   3171   for (size_t i = 0; i < kNumExtensions; i++) {
   3172     if (!(received & (1u << i))) {
   3173       // Extension wasn't observed so call the callback with a NULL
   3174       // parameter.
   3175       uint8_t alert = SSL_AD_DECODE_ERROR;
   3176       if (!kExtensions[i].parse_serverhello(hs, &alert, NULL)) {
   3177         OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
   3178         ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
   3179         *out_alert = alert;
   3180         return 0;
   3181       }
   3182     }
   3183   }
   3184 
   3185   return 1;
   3186 }
   3187 
   3188 static int ssl_check_clienthello_tlsext(SSL_HANDSHAKE *hs) {
   3189   SSL *const ssl = hs->ssl;
   3190 
   3191   if (ssl->token_binding_negotiated &&
   3192       !(SSL_get_secure_renegotiation_support(ssl) &&
   3193         SSL_get_extms_support(ssl))) {
   3194     OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_TB_WITHOUT_EMS_OR_RI);
   3195     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
   3196     return -1;
   3197   }
   3198 
   3199   int ret = SSL_TLSEXT_ERR_NOACK;
   3200   int al = SSL_AD_UNRECOGNIZED_NAME;
   3201 
   3202   if (ssl->ctx->tlsext_servername_callback != 0) {
   3203     ret = ssl->ctx->tlsext_servername_callback(ssl, &al,
   3204                                                ssl->ctx->tlsext_servername_arg);
   3205   } else if (ssl->session_ctx->tlsext_servername_callback != 0) {
   3206     ret = ssl->session_ctx->tlsext_servername_callback(
   3207         ssl, &al, ssl->session_ctx->tlsext_servername_arg);
   3208   }
   3209 
   3210   switch (ret) {
   3211     case SSL_TLSEXT_ERR_ALERT_FATAL:
   3212       ssl_send_alert(ssl, SSL3_AL_FATAL, al);
   3213       return -1;
   3214 
   3215     case SSL_TLSEXT_ERR_NOACK:
   3216       hs->should_ack_sni = false;
   3217       return 1;
   3218 
   3219     default:
   3220       return 1;
   3221   }
   3222 }
   3223 
   3224 int ssl_parse_serverhello_tlsext(SSL_HANDSHAKE *hs, CBS *cbs) {
   3225   SSL *const ssl = hs->ssl;
   3226   int alert = SSL_AD_DECODE_ERROR;
   3227   if (ssl_scan_serverhello_tlsext(hs, cbs, &alert) <= 0) {
   3228     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
   3229     return 0;
   3230   }
   3231 
   3232   return 1;
   3233 }
   3234 
   3235 static enum ssl_ticket_aead_result_t decrypt_ticket_with_cipher_ctx(
   3236     uint8_t **out, size_t *out_len, EVP_CIPHER_CTX *cipher_ctx,
   3237     HMAC_CTX *hmac_ctx, const uint8_t *ticket, size_t ticket_len) {
   3238   size_t iv_len = EVP_CIPHER_CTX_iv_length(cipher_ctx);
   3239 
   3240   // Check the MAC at the end of the ticket.
   3241   uint8_t mac[EVP_MAX_MD_SIZE];
   3242   size_t mac_len = HMAC_size(hmac_ctx);
   3243   if (ticket_len < SSL_TICKET_KEY_NAME_LEN + iv_len + 1 + mac_len) {
   3244     // The ticket must be large enough for key name, IV, data, and MAC.
   3245     return ssl_ticket_aead_ignore_ticket;
   3246   }
   3247   HMAC_Update(hmac_ctx, ticket, ticket_len - mac_len);
   3248   HMAC_Final(hmac_ctx, mac, NULL);
   3249   int mac_ok =
   3250       CRYPTO_memcmp(mac, ticket + (ticket_len - mac_len), mac_len) == 0;
   3251 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
   3252   mac_ok = 1;
   3253 #endif
   3254   if (!mac_ok) {
   3255     return ssl_ticket_aead_ignore_ticket;
   3256   }
   3257 
   3258   // Decrypt the session data.
   3259   const uint8_t *ciphertext = ticket + SSL_TICKET_KEY_NAME_LEN + iv_len;
   3260   size_t ciphertext_len = ticket_len - SSL_TICKET_KEY_NAME_LEN - iv_len -
   3261                           mac_len;
   3262   UniquePtr<uint8_t> plaintext((uint8_t *)OPENSSL_malloc(ciphertext_len));
   3263   if (!plaintext) {
   3264     return ssl_ticket_aead_error;
   3265   }
   3266   size_t plaintext_len;
   3267 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
   3268   OPENSSL_memcpy(plaintext.get(), ciphertext, ciphertext_len);
   3269   plaintext_len = ciphertext_len;
   3270 #else
   3271   if (ciphertext_len >= INT_MAX) {
   3272     return ssl_ticket_aead_ignore_ticket;
   3273   }
   3274   int len1, len2;
   3275   if (!EVP_DecryptUpdate(cipher_ctx, plaintext.get(), &len1, ciphertext,
   3276                          (int)ciphertext_len) ||
   3277       !EVP_DecryptFinal_ex(cipher_ctx, plaintext.get() + len1, &len2)) {
   3278     ERR_clear_error();
   3279     return ssl_ticket_aead_ignore_ticket;
   3280   }
   3281   plaintext_len = (size_t)(len1) + len2;
   3282 #endif
   3283 
   3284   *out = plaintext.release();
   3285   *out_len = plaintext_len;
   3286   return ssl_ticket_aead_success;
   3287 }
   3288 
   3289 static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_cb(
   3290     SSL *ssl, uint8_t **out, size_t *out_len, bool *out_renew_ticket,
   3291     const uint8_t *ticket, size_t ticket_len) {
   3292   assert(ticket_len >= SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH);
   3293   ScopedEVP_CIPHER_CTX cipher_ctx;
   3294   ScopedHMAC_CTX hmac_ctx;
   3295   const uint8_t *iv = ticket + SSL_TICKET_KEY_NAME_LEN;
   3296   int cb_ret = ssl->session_ctx->tlsext_ticket_key_cb(
   3297       ssl, (uint8_t *)ticket /* name */, (uint8_t *)iv, cipher_ctx.get(),
   3298       hmac_ctx.get(), 0 /* decrypt */);
   3299   if (cb_ret < 0) {
   3300     return ssl_ticket_aead_error;
   3301   } else if (cb_ret == 0) {
   3302     return ssl_ticket_aead_ignore_ticket;
   3303   } else if (cb_ret == 2) {
   3304     *out_renew_ticket = true;
   3305   } else {
   3306     assert(cb_ret == 1);
   3307   }
   3308   return decrypt_ticket_with_cipher_ctx(out, out_len, cipher_ctx.get(),
   3309                                         hmac_ctx.get(), ticket, ticket_len);
   3310 }
   3311 
   3312 static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_ticket_keys(
   3313     SSL *ssl, uint8_t **out, size_t *out_len, const uint8_t *ticket,
   3314     size_t ticket_len) {
   3315   assert(ticket_len >= SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH);
   3316   SSL_CTX *ctx = ssl->session_ctx;
   3317 
   3318   // Rotate the ticket key if necessary.
   3319   if (!ssl_ctx_rotate_ticket_encryption_key(ctx)) {
   3320     return ssl_ticket_aead_error;
   3321   }
   3322 
   3323   // Pick the matching ticket key and decrypt.
   3324   ScopedEVP_CIPHER_CTX cipher_ctx;
   3325   ScopedHMAC_CTX hmac_ctx;
   3326   {
   3327     MutexReadLock lock(&ctx->lock);
   3328     const tlsext_ticket_key *key;
   3329     if (ctx->tlsext_ticket_key_current &&
   3330         !OPENSSL_memcmp(ctx->tlsext_ticket_key_current->name, ticket,
   3331                         SSL_TICKET_KEY_NAME_LEN)) {
   3332       key = ctx->tlsext_ticket_key_current;
   3333     } else if (ctx->tlsext_ticket_key_prev &&
   3334                !OPENSSL_memcmp(ctx->tlsext_ticket_key_prev->name, ticket,
   3335                                SSL_TICKET_KEY_NAME_LEN)) {
   3336       key = ctx->tlsext_ticket_key_prev;
   3337     } else {
   3338       return ssl_ticket_aead_ignore_ticket;
   3339     }
   3340     const uint8_t *iv = ticket + SSL_TICKET_KEY_NAME_LEN;
   3341     if (!HMAC_Init_ex(hmac_ctx.get(), key->hmac_key, sizeof(key->hmac_key),
   3342                       tlsext_tick_md(), NULL) ||
   3343         !EVP_DecryptInit_ex(cipher_ctx.get(), EVP_aes_128_cbc(), NULL,
   3344                             key->aes_key, iv)) {
   3345       return ssl_ticket_aead_error;
   3346     }
   3347   }
   3348   return decrypt_ticket_with_cipher_ctx(out, out_len, cipher_ctx.get(),
   3349                                         hmac_ctx.get(), ticket, ticket_len);
   3350 }
   3351 
   3352 static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_method(
   3353     SSL *ssl, uint8_t **out, size_t *out_len, bool *out_renew_ticket,
   3354     const uint8_t *ticket, size_t ticket_len) {
   3355   uint8_t *plaintext = (uint8_t *)OPENSSL_malloc(ticket_len);
   3356   if (plaintext == NULL) {
   3357     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   3358     return ssl_ticket_aead_error;
   3359   }
   3360 
   3361   size_t plaintext_len;
   3362   const enum ssl_ticket_aead_result_t result =
   3363       ssl->session_ctx->ticket_aead_method->open(
   3364           ssl, plaintext, &plaintext_len, ticket_len, ticket, ticket_len);
   3365 
   3366   if (result == ssl_ticket_aead_success) {
   3367     *out = plaintext;
   3368     plaintext = NULL;
   3369     *out_len = plaintext_len;
   3370   }
   3371 
   3372   OPENSSL_free(plaintext);
   3373   return result;
   3374 }
   3375 
   3376 enum ssl_ticket_aead_result_t ssl_process_ticket(
   3377     SSL *ssl, UniquePtr<SSL_SESSION> *out_session, bool *out_renew_ticket,
   3378     const uint8_t *ticket, size_t ticket_len, const uint8_t *session_id,
   3379     size_t session_id_len) {
   3380   *out_renew_ticket = false;
   3381   out_session->reset();
   3382 
   3383   if ((SSL_get_options(ssl) & SSL_OP_NO_TICKET) ||
   3384       session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
   3385     return ssl_ticket_aead_ignore_ticket;
   3386   }
   3387 
   3388   uint8_t *plaintext = NULL;
   3389   size_t plaintext_len;
   3390   enum ssl_ticket_aead_result_t result;
   3391   if (ssl->session_ctx->ticket_aead_method != NULL) {
   3392     result = ssl_decrypt_ticket_with_method(
   3393         ssl, &plaintext, &plaintext_len, out_renew_ticket, ticket, ticket_len);
   3394   } else {
   3395     // Ensure there is room for the key name and the largest IV
   3396     // |tlsext_ticket_key_cb| may try to consume. The real limit may be lower,
   3397     // but the maximum IV length should be well under the minimum size for the
   3398     // session material and HMAC.
   3399     if (ticket_len < SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH) {
   3400       return ssl_ticket_aead_ignore_ticket;
   3401     }
   3402     if (ssl->session_ctx->tlsext_ticket_key_cb != NULL) {
   3403       result = ssl_decrypt_ticket_with_cb(ssl, &plaintext, &plaintext_len,
   3404                                           out_renew_ticket, ticket, ticket_len);
   3405     } else {
   3406       result = ssl_decrypt_ticket_with_ticket_keys(
   3407           ssl, &plaintext, &plaintext_len, ticket, ticket_len);
   3408     }
   3409   }
   3410 
   3411   if (result != ssl_ticket_aead_success) {
   3412     return result;
   3413   }
   3414 
   3415   // Decode the session.
   3416   UniquePtr<SSL_SESSION> session(
   3417       SSL_SESSION_from_bytes(plaintext, plaintext_len, ssl->ctx));
   3418   OPENSSL_free(plaintext);
   3419 
   3420   if (!session) {
   3421     ERR_clear_error();  // Don't leave an error on the queue.
   3422     return ssl_ticket_aead_ignore_ticket;
   3423   }
   3424 
   3425   // Copy the client's session ID into the new session, to denote the ticket has
   3426   // been accepted.
   3427   OPENSSL_memcpy(session->session_id, session_id, session_id_len);
   3428   session->session_id_length = session_id_len;
   3429 
   3430   *out_session = std::move(session);
   3431   return ssl_ticket_aead_success;
   3432 }
   3433 
   3434 bool tls1_parse_peer_sigalgs(SSL_HANDSHAKE *hs, const CBS *in_sigalgs) {
   3435   // Extension ignored for inappropriate versions
   3436   if (ssl_protocol_version(hs->ssl) < TLS1_2_VERSION) {
   3437     return true;
   3438   }
   3439 
   3440   return parse_u16_array(in_sigalgs, &hs->peer_sigalgs);
   3441 }
   3442 
   3443 bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey) {
   3444   switch (EVP_PKEY_id(pkey)) {
   3445     case EVP_PKEY_RSA:
   3446       *out = SSL_SIGN_RSA_PKCS1_MD5_SHA1;
   3447       return true;
   3448     case EVP_PKEY_EC:
   3449       *out = SSL_SIGN_ECDSA_SHA1;
   3450       return true;
   3451     default:
   3452       return false;
   3453   }
   3454 }
   3455 
   3456 bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out) {
   3457   SSL *const ssl = hs->ssl;
   3458   CERT *cert = ssl->cert;
   3459 
   3460   // Before TLS 1.2, the signature algorithm isn't negotiated as part of the
   3461   // handshake.
   3462   if (ssl_protocol_version(ssl) < TLS1_2_VERSION) {
   3463     if (!tls1_get_legacy_signature_algorithm(out, hs->local_pubkey.get())) {
   3464       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
   3465       return false;
   3466     }
   3467     return true;
   3468   }
   3469 
   3470   Span<const uint16_t> sigalgs = kSignSignatureAlgorithms;
   3471   if (cert->sigalgs != nullptr) {
   3472     sigalgs = MakeConstSpan(cert->sigalgs, cert->num_sigalgs);
   3473   }
   3474 
   3475   Span<const uint16_t> peer_sigalgs = hs->peer_sigalgs;
   3476   if (peer_sigalgs.empty() && ssl_protocol_version(ssl) < TLS1_3_VERSION) {
   3477     // If the client didn't specify any signature_algorithms extension then
   3478     // we can assume that it supports SHA1. See
   3479     // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
   3480     static const uint16_t kDefaultPeerAlgorithms[] = {SSL_SIGN_RSA_PKCS1_SHA1,
   3481                                                       SSL_SIGN_ECDSA_SHA1};
   3482     peer_sigalgs = kDefaultPeerAlgorithms;
   3483   }
   3484 
   3485   for (uint16_t sigalg : sigalgs) {
   3486     // SSL_SIGN_RSA_PKCS1_MD5_SHA1 is an internal value and should never be
   3487     // negotiated.
   3488     if (sigalg == SSL_SIGN_RSA_PKCS1_MD5_SHA1 ||
   3489         !ssl_private_key_supports_signature_algorithm(hs, sigalg)) {
   3490       continue;
   3491     }
   3492 
   3493     for (uint16_t peer_sigalg : peer_sigalgs) {
   3494       if (sigalg == peer_sigalg) {
   3495         *out = sigalg;
   3496         return true;
   3497       }
   3498     }
   3499   }
   3500 
   3501   OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
   3502   return false;
   3503 }
   3504 
   3505 int tls1_verify_channel_id(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
   3506   SSL *const ssl = hs->ssl;
   3507   // A Channel ID handshake message is structured to contain multiple
   3508   // extensions, but the only one that can be present is Channel ID.
   3509   uint16_t extension_type;
   3510   CBS channel_id = msg.body, extension;
   3511   if (!CBS_get_u16(&channel_id, &extension_type) ||
   3512       !CBS_get_u16_length_prefixed(&channel_id, &extension) ||
   3513       CBS_len(&channel_id) != 0 ||
   3514       extension_type != TLSEXT_TYPE_channel_id ||
   3515       CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE) {
   3516     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   3517     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   3518     return 0;
   3519   }
   3520 
   3521   UniquePtr<EC_GROUP> p256(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
   3522   if (!p256) {
   3523     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_P256_SUPPORT);
   3524     return 0;
   3525   }
   3526 
   3527   UniquePtr<ECDSA_SIG> sig(ECDSA_SIG_new());
   3528   UniquePtr<BIGNUM> x(BN_new()), y(BN_new());
   3529   if (!sig || !x || !y) {
   3530     return 0;
   3531   }
   3532 
   3533   const uint8_t *p = CBS_data(&extension);
   3534   if (BN_bin2bn(p + 0, 32, x.get()) == NULL ||
   3535       BN_bin2bn(p + 32, 32, y.get()) == NULL ||
   3536       BN_bin2bn(p + 64, 32, sig->r) == NULL ||
   3537       BN_bin2bn(p + 96, 32, sig->s) == NULL) {
   3538     return 0;
   3539   }
   3540 
   3541   UniquePtr<EC_KEY> key(EC_KEY_new());
   3542   UniquePtr<EC_POINT> point(EC_POINT_new(p256.get()));
   3543   if (!key || !point ||
   3544       !EC_POINT_set_affine_coordinates_GFp(p256.get(), point.get(), x.get(),
   3545                                            y.get(), nullptr) ||
   3546       !EC_KEY_set_group(key.get(), p256.get()) ||
   3547       !EC_KEY_set_public_key(key.get(), point.get())) {
   3548     return 0;
   3549   }
   3550 
   3551   uint8_t digest[EVP_MAX_MD_SIZE];
   3552   size_t digest_len;
   3553   if (!tls1_channel_id_hash(hs, digest, &digest_len)) {
   3554     return 0;
   3555   }
   3556 
   3557   int sig_ok = ECDSA_do_verify(digest, digest_len, sig.get(), key.get());
   3558 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
   3559   sig_ok = 1;
   3560   ERR_clear_error();
   3561 #endif
   3562   if (!sig_ok) {
   3563     OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
   3564     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
   3565     ssl->s3->tlsext_channel_id_valid = false;
   3566     return 0;
   3567   }
   3568 
   3569   OPENSSL_memcpy(ssl->s3->tlsext_channel_id, p, 64);
   3570   return 1;
   3571 }
   3572 
   3573 bool tls1_write_channel_id(SSL_HANDSHAKE *hs, CBB *cbb) {
   3574   SSL *const ssl = hs->ssl;
   3575   uint8_t digest[EVP_MAX_MD_SIZE];
   3576   size_t digest_len;
   3577   if (!tls1_channel_id_hash(hs, digest, &digest_len)) {
   3578     return false;
   3579   }
   3580 
   3581   EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(ssl->tlsext_channel_id_private);
   3582   if (ec_key == nullptr) {
   3583     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   3584     return false;
   3585   }
   3586 
   3587   UniquePtr<BIGNUM> x(BN_new()), y(BN_new());
   3588   if (!x || !y ||
   3589       !EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(ec_key),
   3590                                            EC_KEY_get0_public_key(ec_key),
   3591                                            x.get(), y.get(), nullptr)) {
   3592     return false;
   3593   }
   3594 
   3595   UniquePtr<ECDSA_SIG> sig(ECDSA_do_sign(digest, digest_len, ec_key));
   3596   if (!sig) {
   3597     return false;
   3598   }
   3599 
   3600   CBB child;
   3601   if (!CBB_add_u16(cbb, TLSEXT_TYPE_channel_id) ||
   3602       !CBB_add_u16_length_prefixed(cbb, &child) ||
   3603       !BN_bn2cbb_padded(&child, 32, x.get()) ||
   3604       !BN_bn2cbb_padded(&child, 32, y.get()) ||
   3605       !BN_bn2cbb_padded(&child, 32, sig->r) ||
   3606       !BN_bn2cbb_padded(&child, 32, sig->s) ||
   3607       !CBB_flush(cbb)) {
   3608     return false;
   3609   }
   3610 
   3611   return true;
   3612 }
   3613 
   3614 int tls1_channel_id_hash(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len) {
   3615   SSL *const ssl = hs->ssl;
   3616   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
   3617     Array<uint8_t> msg;
   3618     if (!tls13_get_cert_verify_signature_input(hs, &msg,
   3619                                                ssl_cert_verify_channel_id)) {
   3620       return 0;
   3621     }
   3622     SHA256(msg.data(), msg.size(), out);
   3623     *out_len = SHA256_DIGEST_LENGTH;
   3624     return 1;
   3625   }
   3626 
   3627   SHA256_CTX ctx;
   3628 
   3629   SHA256_Init(&ctx);
   3630   static const char kClientIDMagic[] = "TLS Channel ID signature";
   3631   SHA256_Update(&ctx, kClientIDMagic, sizeof(kClientIDMagic));
   3632 
   3633   if (ssl->session != NULL) {
   3634     static const char kResumptionMagic[] = "Resumption";
   3635     SHA256_Update(&ctx, kResumptionMagic, sizeof(kResumptionMagic));
   3636     if (ssl->session->original_handshake_hash_len == 0) {
   3637       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   3638       return 0;
   3639     }
   3640     SHA256_Update(&ctx, ssl->session->original_handshake_hash,
   3641                   ssl->session->original_handshake_hash_len);
   3642   }
   3643 
   3644   uint8_t hs_hash[EVP_MAX_MD_SIZE];
   3645   size_t hs_hash_len;
   3646   if (!hs->transcript.GetHash(hs_hash, &hs_hash_len)) {
   3647     return 0;
   3648   }
   3649   SHA256_Update(&ctx, hs_hash, (size_t)hs_hash_len);
   3650   SHA256_Final(out, &ctx);
   3651   *out_len = SHA256_DIGEST_LENGTH;
   3652   return 1;
   3653 }
   3654 
   3655 // tls1_record_handshake_hashes_for_channel_id records the current handshake
   3656 // hashes in |hs->new_session| so that Channel ID resumptions can sign that
   3657 // data.
   3658 int tls1_record_handshake_hashes_for_channel_id(SSL_HANDSHAKE *hs) {
   3659   SSL *const ssl = hs->ssl;
   3660   // This function should never be called for a resumed session because the
   3661   // handshake hashes that we wish to record are for the original, full
   3662   // handshake.
   3663   if (ssl->session != NULL) {
   3664     return 0;
   3665   }
   3666 
   3667   static_assert(
   3668       sizeof(hs->new_session->original_handshake_hash) == EVP_MAX_MD_SIZE,
   3669       "original_handshake_hash is too small");
   3670 
   3671   size_t digest_len;
   3672   if (!hs->transcript.GetHash(hs->new_session->original_handshake_hash,
   3673                               &digest_len)) {
   3674     return 0;
   3675   }
   3676 
   3677   static_assert(EVP_MAX_MD_SIZE <= 0xff,
   3678                 "EVP_MAX_MD_SIZE does not fit in uint8_t");
   3679   hs->new_session->original_handshake_hash_len = (uint8_t)digest_len;
   3680 
   3681   return 1;
   3682 }
   3683 
   3684 int ssl_do_channel_id_callback(SSL *ssl) {
   3685   if (ssl->tlsext_channel_id_private != NULL ||
   3686       ssl->ctx->channel_id_cb == NULL) {
   3687     return 1;
   3688   }
   3689 
   3690   EVP_PKEY *key = NULL;
   3691   ssl->ctx->channel_id_cb(ssl, &key);
   3692   if (key == NULL) {
   3693     // The caller should try again later.
   3694     return 1;
   3695   }
   3696 
   3697   int ret = SSL_set1_tls_channel_id(ssl, key);
   3698   EVP_PKEY_free(key);
   3699   return ret;
   3700 }
   3701 
   3702 int ssl_is_sct_list_valid(const CBS *contents) {
   3703   // Shallow parse the SCT list for sanity. By the RFC
   3704   // (https://tools.ietf.org/html/rfc6962#section-3.3) neither the list nor any
   3705   // of the SCTs may be empty.
   3706   CBS copy = *contents;
   3707   CBS sct_list;
   3708   if (!CBS_get_u16_length_prefixed(&copy, &sct_list) ||
   3709       CBS_len(&copy) != 0 ||
   3710       CBS_len(&sct_list) == 0) {
   3711     return 0;
   3712   }
   3713 
   3714   while (CBS_len(&sct_list) > 0) {
   3715     CBS sct;
   3716     if (!CBS_get_u16_length_prefixed(&sct_list, &sct) ||
   3717         CBS_len(&sct) == 0) {
   3718       return 0;
   3719     }
   3720   }
   3721 
   3722   return 1;
   3723 }
   3724 
   3725 }  // namespace bssl
   3726 
   3727 using namespace bssl;
   3728 
   3729 int SSL_early_callback_ctx_extension_get(const SSL_CLIENT_HELLO *client_hello,
   3730                                          uint16_t extension_type,
   3731                                          const uint8_t **out_data,
   3732                                          size_t *out_len) {
   3733   CBS cbs;
   3734   if (!ssl_client_hello_get_extension(client_hello, &cbs, extension_type)) {
   3735     return 0;
   3736   }
   3737 
   3738   *out_data = CBS_data(&cbs);
   3739   *out_len = CBS_len(&cbs);
   3740   return 1;
   3741 }
   3742 
   3743 void SSL_CTX_set_ed25519_enabled(SSL_CTX *ctx, int enabled) {
   3744   ctx->ed25519_enabled = !!enabled;
   3745 }
   3746 
   3747 int SSL_extension_supported(unsigned extension_value) {
   3748   uint32_t index;
   3749   return extension_value == TLSEXT_TYPE_padding ||
   3750          tls_extension_find(&index, extension_value) != NULL;
   3751 }
   3752