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