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 <stdio.h>
    114 #include <stdlib.h>
    115 #include <string.h>
    116 
    117 #include <openssl/bytestring.h>
    118 #include <openssl/digest.h>
    119 #include <openssl/err.h>
    120 #include <openssl/evp.h>
    121 #include <openssl/hmac.h>
    122 #include <openssl/mem.h>
    123 #include <openssl/obj.h>
    124 #include <openssl/rand.h>
    125 #include <openssl/type_check.h>
    126 
    127 #include "internal.h"
    128 
    129 
    130 static int ssl_check_clienthello_tlsext(SSL *ssl);
    131 static int ssl_check_serverhello_tlsext(SSL *ssl);
    132 
    133 const SSL3_ENC_METHOD TLSv1_enc_data = {
    134     tls1_prf,
    135     tls1_setup_key_block,
    136     tls1_generate_master_secret,
    137     tls1_change_cipher_state,
    138     tls1_final_finish_mac,
    139     tls1_cert_verify_mac,
    140     TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
    141     TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
    142     tls1_alert_code,
    143     tls1_export_keying_material,
    144     0,
    145 };
    146 
    147 const SSL3_ENC_METHOD TLSv1_1_enc_data = {
    148     tls1_prf,
    149     tls1_setup_key_block,
    150     tls1_generate_master_secret,
    151     tls1_change_cipher_state,
    152     tls1_final_finish_mac,
    153     tls1_cert_verify_mac,
    154     TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
    155     TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
    156     tls1_alert_code,
    157     tls1_export_keying_material,
    158     SSL_ENC_FLAG_EXPLICIT_IV,
    159 };
    160 
    161 const SSL3_ENC_METHOD TLSv1_2_enc_data = {
    162     tls1_prf,
    163     tls1_setup_key_block,
    164     tls1_generate_master_secret,
    165     tls1_change_cipher_state,
    166     tls1_final_finish_mac,
    167     tls1_cert_verify_mac,
    168     TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
    169     TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
    170     tls1_alert_code,
    171     tls1_export_keying_material,
    172     SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS|SSL_ENC_FLAG_SHA256_PRF,
    173 };
    174 
    175 static int compare_uint16_t(const void *p1, const void *p2) {
    176   uint16_t u1 = *((const uint16_t *)p1);
    177   uint16_t u2 = *((const uint16_t *)p2);
    178   if (u1 < u2) {
    179     return -1;
    180   } else if (u1 > u2) {
    181     return 1;
    182   } else {
    183     return 0;
    184   }
    185 }
    186 
    187 /* Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
    188  * more than one extension of the same type in a ClientHello or ServerHello.
    189  * This function does an initial scan over the extensions block to filter those
    190  * out. */
    191 static int tls1_check_duplicate_extensions(const CBS *cbs) {
    192   CBS extensions = *cbs;
    193   size_t num_extensions = 0, i = 0;
    194   uint16_t *extension_types = NULL;
    195   int ret = 0;
    196 
    197   /* First pass: count the extensions. */
    198   while (CBS_len(&extensions) > 0) {
    199     uint16_t type;
    200     CBS extension;
    201 
    202     if (!CBS_get_u16(&extensions, &type) ||
    203         !CBS_get_u16_length_prefixed(&extensions, &extension)) {
    204       goto done;
    205     }
    206 
    207     num_extensions++;
    208   }
    209 
    210   if (num_extensions == 0) {
    211     return 1;
    212   }
    213 
    214   extension_types =
    215       (uint16_t *)OPENSSL_malloc(sizeof(uint16_t) * num_extensions);
    216   if (extension_types == NULL) {
    217     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
    218     goto done;
    219   }
    220 
    221   /* Second pass: gather the extension types. */
    222   extensions = *cbs;
    223   for (i = 0; i < num_extensions; i++) {
    224     CBS extension;
    225 
    226     if (!CBS_get_u16(&extensions, &extension_types[i]) ||
    227         !CBS_get_u16_length_prefixed(&extensions, &extension)) {
    228       /* This should not happen. */
    229       goto done;
    230     }
    231   }
    232   assert(CBS_len(&extensions) == 0);
    233 
    234   /* Sort the extensions and make sure there are no duplicates. */
    235   qsort(extension_types, num_extensions, sizeof(uint16_t), compare_uint16_t);
    236   for (i = 1; i < num_extensions; i++) {
    237     if (extension_types[i - 1] == extension_types[i]) {
    238       goto done;
    239     }
    240   }
    241 
    242   ret = 1;
    243 
    244 done:
    245   OPENSSL_free(extension_types);
    246   return ret;
    247 }
    248 
    249 char ssl_early_callback_init(struct ssl_early_callback_ctx *ctx) {
    250   CBS client_hello, session_id, cipher_suites, compression_methods, extensions;
    251 
    252   CBS_init(&client_hello, ctx->client_hello, ctx->client_hello_len);
    253 
    254   if (/* Skip client version. */
    255       !CBS_skip(&client_hello, 2) ||
    256       /* Skip client nonce. */
    257       !CBS_skip(&client_hello, 32) ||
    258       /* Extract session_id. */
    259       !CBS_get_u8_length_prefixed(&client_hello, &session_id)) {
    260     return 0;
    261   }
    262 
    263   ctx->session_id = CBS_data(&session_id);
    264   ctx->session_id_len = CBS_len(&session_id);
    265 
    266   /* Skip past DTLS cookie */
    267   if (SSL_IS_DTLS(ctx->ssl)) {
    268     CBS cookie;
    269 
    270     if (!CBS_get_u8_length_prefixed(&client_hello, &cookie)) {
    271       return 0;
    272     }
    273   }
    274 
    275   /* Extract cipher_suites. */
    276   if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
    277       CBS_len(&cipher_suites) < 2 || (CBS_len(&cipher_suites) & 1) != 0) {
    278     return 0;
    279   }
    280   ctx->cipher_suites = CBS_data(&cipher_suites);
    281   ctx->cipher_suites_len = CBS_len(&cipher_suites);
    282 
    283   /* Extract compression_methods. */
    284   if (!CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
    285       CBS_len(&compression_methods) < 1) {
    286     return 0;
    287   }
    288   ctx->compression_methods = CBS_data(&compression_methods);
    289   ctx->compression_methods_len = CBS_len(&compression_methods);
    290 
    291   /* If the ClientHello ends here then it's valid, but doesn't have any
    292    * extensions. (E.g. SSLv3.) */
    293   if (CBS_len(&client_hello) == 0) {
    294     ctx->extensions = NULL;
    295     ctx->extensions_len = 0;
    296     return 1;
    297   }
    298 
    299   /* Extract extensions and check it is valid. */
    300   if (!CBS_get_u16_length_prefixed(&client_hello, &extensions) ||
    301       !tls1_check_duplicate_extensions(&extensions) ||
    302       CBS_len(&client_hello) != 0) {
    303     return 0;
    304   }
    305   ctx->extensions = CBS_data(&extensions);
    306   ctx->extensions_len = CBS_len(&extensions);
    307 
    308   return 1;
    309 }
    310 
    311 int SSL_early_callback_ctx_extension_get(
    312     const struct ssl_early_callback_ctx *ctx, uint16_t extension_type,
    313     const uint8_t **out_data, size_t *out_len) {
    314   CBS extensions;
    315 
    316   CBS_init(&extensions, ctx->extensions, ctx->extensions_len);
    317 
    318   while (CBS_len(&extensions) != 0) {
    319     uint16_t type;
    320     CBS extension;
    321 
    322     /* Decode the next extension. */
    323     if (!CBS_get_u16(&extensions, &type) ||
    324         !CBS_get_u16_length_prefixed(&extensions, &extension)) {
    325       return 0;
    326     }
    327 
    328     if (type == extension_type) {
    329       *out_data = CBS_data(&extension);
    330       *out_len = CBS_len(&extension);
    331       return 1;
    332     }
    333   }
    334 
    335   return 0;
    336 }
    337 
    338 static const uint16_t eccurves_default[] = {
    339     SSL_CURVE_SECP256R1,
    340     SSL_CURVE_SECP384R1,
    341 #if defined(BORINGSSL_ANDROID_SYSTEM)
    342     SSL_CURVE_SECP521R1,
    343 #endif
    344 };
    345 
    346 /* tls1_get_curvelist sets |*out_curve_ids| and |*out_curve_ids_len| to the
    347  * list of allowed curve IDs. If |get_peer_curves| is non-zero, return the
    348  * peer's curve list. Otherwise, return the preferred list. */
    349 static void tls1_get_curvelist(SSL *ssl, int get_peer_curves,
    350                                const uint16_t **out_curve_ids,
    351                                size_t *out_curve_ids_len) {
    352   if (get_peer_curves) {
    353     /* Only clients send a curve list, so this function is only called
    354      * on the server. */
    355     assert(ssl->server);
    356     *out_curve_ids = ssl->s3->tmp.peer_ellipticcurvelist;
    357     *out_curve_ids_len = ssl->s3->tmp.peer_ellipticcurvelist_length;
    358     return;
    359   }
    360 
    361   *out_curve_ids = ssl->tlsext_ellipticcurvelist;
    362   *out_curve_ids_len = ssl->tlsext_ellipticcurvelist_length;
    363   if (!*out_curve_ids) {
    364     *out_curve_ids = eccurves_default;
    365     *out_curve_ids_len = sizeof(eccurves_default) / sizeof(eccurves_default[0]);
    366   }
    367 }
    368 
    369 int tls1_get_shared_curve(SSL *ssl, uint16_t *out_curve_id) {
    370   const uint16_t *curves, *peer_curves, *pref, *supp;
    371   size_t curves_len, peer_curves_len, pref_len, supp_len, i, j;
    372 
    373   /* Can't do anything on client side */
    374   if (ssl->server == 0) {
    375     return 0;
    376   }
    377 
    378   tls1_get_curvelist(ssl, 0 /* local curves */, &curves, &curves_len);
    379   tls1_get_curvelist(ssl, 1 /* peer curves */, &peer_curves, &peer_curves_len);
    380 
    381   if (peer_curves_len == 0) {
    382     /* Clients are not required to send a supported_curves extension. In this
    383      * case, the server is free to pick any curve it likes. See RFC 4492,
    384      * section 4, paragraph 3.
    385      *
    386      * However, in the interests of compatibility, we will skip ECDH if the
    387      * client didn't send an extension because we can't be sure that they'll
    388      * support our favoured curve. */
    389     return 0;
    390   }
    391 
    392   if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
    393     pref = curves;
    394     pref_len = curves_len;
    395     supp = peer_curves;
    396     supp_len = peer_curves_len;
    397   } else {
    398     pref = peer_curves;
    399     pref_len = peer_curves_len;
    400     supp = curves;
    401     supp_len = curves_len;
    402   }
    403 
    404   for (i = 0; i < pref_len; i++) {
    405     for (j = 0; j < supp_len; j++) {
    406       if (pref[i] == supp[j]) {
    407         *out_curve_id = pref[i];
    408         return 1;
    409       }
    410     }
    411   }
    412 
    413   return 0;
    414 }
    415 
    416 int tls1_set_curves(uint16_t **out_curve_ids, size_t *out_curve_ids_len,
    417                     const int *curves, size_t ncurves) {
    418   uint16_t *curve_ids;
    419   size_t i;
    420 
    421   curve_ids = (uint16_t *)OPENSSL_malloc(ncurves * sizeof(uint16_t));
    422   if (curve_ids == NULL) {
    423     return 0;
    424   }
    425 
    426   for (i = 0; i < ncurves; i++) {
    427     if (!ssl_nid_to_curve_id(&curve_ids[i], curves[i])) {
    428       OPENSSL_free(curve_ids);
    429       return 0;
    430     }
    431   }
    432 
    433   OPENSSL_free(*out_curve_ids);
    434   *out_curve_ids = curve_ids;
    435   *out_curve_ids_len = ncurves;
    436 
    437   return 1;
    438 }
    439 
    440 /* tls1_curve_params_from_ec_key sets |*out_curve_id| and |*out_comp_id| to the
    441  * TLS curve ID and point format, respectively, for |ec|. It returns one on
    442  * success and zero on failure. */
    443 static int tls1_curve_params_from_ec_key(uint16_t *out_curve_id,
    444                                          uint8_t *out_comp_id, EC_KEY *ec) {
    445   int nid;
    446   uint16_t id;
    447   const EC_GROUP *grp;
    448 
    449   if (ec == NULL) {
    450     return 0;
    451   }
    452 
    453   grp = EC_KEY_get0_group(ec);
    454   if (grp == NULL) {
    455     return 0;
    456   }
    457 
    458   /* Determine curve ID */
    459   nid = EC_GROUP_get_curve_name(grp);
    460   if (!ssl_nid_to_curve_id(&id, nid)) {
    461     return 0;
    462   }
    463 
    464   /* Set the named curve ID. Arbitrary explicit curves are not supported. */
    465   *out_curve_id = id;
    466 
    467   if (out_comp_id) {
    468     if (EC_KEY_get0_public_key(ec) == NULL) {
    469       return 0;
    470     }
    471     if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED) {
    472       *out_comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
    473     } else {
    474       *out_comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
    475     }
    476   }
    477 
    478   return 1;
    479 }
    480 
    481 /* tls1_check_curve_id returns one if |curve_id| is consistent with both our
    482  * and the peer's curve preferences. Note: if called as the client, only our
    483  * preferences are checked; the peer (the server) does not send preferences. */
    484 int tls1_check_curve_id(SSL *ssl, uint16_t curve_id) {
    485   const uint16_t *curves;
    486   size_t curves_len, i, get_peer_curves;
    487 
    488   /* Check against our list, then the peer's list. */
    489   for (get_peer_curves = 0; get_peer_curves <= 1; get_peer_curves++) {
    490     if (get_peer_curves && !ssl->server) {
    491       /* Servers do not present a preference list so, if we are a client, only
    492        * check our list. */
    493       continue;
    494     }
    495 
    496     tls1_get_curvelist(ssl, get_peer_curves, &curves, &curves_len);
    497     if (get_peer_curves && curves_len == 0) {
    498       /* Clients are not required to send a supported_curves extension. In this
    499        * case, the server is free to pick any curve it likes. See RFC 4492,
    500        * section 4, paragraph 3. */
    501       continue;
    502     }
    503     for (i = 0; i < curves_len; i++) {
    504       if (curves[i] == curve_id) {
    505         break;
    506       }
    507     }
    508 
    509     if (i == curves_len) {
    510       return 0;
    511     }
    512   }
    513 
    514   return 1;
    515 }
    516 
    517 int tls1_check_ec_cert(SSL *ssl, X509 *x) {
    518   int ret = 0;
    519   EVP_PKEY *pkey = X509_get_pubkey(x);
    520   uint16_t curve_id;
    521   uint8_t comp_id;
    522 
    523   if (!pkey) {
    524     goto done;
    525   }
    526   EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey);
    527   if (ec_key == NULL ||
    528       !tls1_curve_params_from_ec_key(&curve_id, &comp_id, ec_key) ||
    529       !tls1_check_curve_id(ssl, curve_id) ||
    530       comp_id != TLSEXT_ECPOINTFORMAT_uncompressed) {
    531     goto done;
    532   }
    533 
    534   ret = 1;
    535 
    536 done:
    537   EVP_PKEY_free(pkey);
    538   return ret;
    539 }
    540 
    541 /* List of supported signature algorithms and hashes. Should make this
    542  * customisable at some point, for now include everything we support. */
    543 
    544 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
    545 
    546 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
    547 
    548 #define tlsext_sigalg(md) tlsext_sigalg_rsa(md) tlsext_sigalg_ecdsa(md)
    549 
    550 static const uint8_t tls12_sigalgs[] = {
    551     tlsext_sigalg(TLSEXT_hash_sha512)
    552     tlsext_sigalg(TLSEXT_hash_sha384)
    553     tlsext_sigalg(TLSEXT_hash_sha256)
    554     tlsext_sigalg(TLSEXT_hash_sha224)
    555     tlsext_sigalg(TLSEXT_hash_sha1)
    556 };
    557 
    558 size_t tls12_get_psigalgs(SSL *ssl, const uint8_t **psigs) {
    559   *psigs = tls12_sigalgs;
    560   return sizeof(tls12_sigalgs);
    561 }
    562 
    563 int tls12_check_peer_sigalg(SSL *ssl, const EVP_MD **out_md, int *out_alert,
    564                             uint8_t hash, uint8_t signature, EVP_PKEY *pkey) {
    565   const uint8_t *sent_sigs;
    566   size_t sent_sigslen, i;
    567   int sigalg = tls12_get_sigid(pkey->type);
    568 
    569   /* Should never happen */
    570   if (sigalg == -1) {
    571     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    572     *out_alert = SSL_AD_INTERNAL_ERROR;
    573     return 0;
    574   }
    575 
    576   /* Check key type is consistent with signature */
    577   if (sigalg != signature) {
    578     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SIGNATURE_TYPE);
    579     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    580     return 0;
    581   }
    582 
    583   /* Check signature matches a type we sent */
    584   sent_sigslen = tls12_get_psigalgs(ssl, &sent_sigs);
    585   for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) {
    586     if (hash == sent_sigs[0] && signature == sent_sigs[1]) {
    587       break;
    588     }
    589   }
    590 
    591   if (i == sent_sigslen) {
    592     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SIGNATURE_TYPE);
    593     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    594     return 0;
    595   }
    596 
    597   *out_md = tls12_get_hash(hash);
    598   if (*out_md == NULL) {
    599     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_DIGEST);
    600     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    601     return 0;
    602   }
    603 
    604   return 1;
    605 }
    606 
    607 /* Get a mask of disabled algorithms: an algorithm is disabled if it isn't
    608  * supported or doesn't appear in supported signature algorithms. Unlike
    609  * ssl_cipher_get_disabled this applies to a specific session and not global
    610  * settings. */
    611 void ssl_set_client_disabled(SSL *ssl) {
    612   CERT *c = ssl->cert;
    613   const uint8_t *sigalgs;
    614   size_t i, sigalgslen;
    615   int have_rsa = 0, have_ecdsa = 0;
    616   c->mask_a = 0;
    617   c->mask_k = 0;
    618 
    619   /* Now go through all signature algorithms seeing if we support any for RSA,
    620    * DSA, ECDSA. Do this for all versions not just TLS 1.2. */
    621   sigalgslen = tls12_get_psigalgs(ssl, &sigalgs);
    622   for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) {
    623     switch (sigalgs[1]) {
    624       case TLSEXT_signature_rsa:
    625         have_rsa = 1;
    626         break;
    627 
    628       case TLSEXT_signature_ecdsa:
    629         have_ecdsa = 1;
    630         break;
    631     }
    632   }
    633 
    634   /* Disable auth if we don't include any appropriate signature algorithms. */
    635   if (!have_rsa) {
    636     c->mask_a |= SSL_aRSA;
    637   }
    638   if (!have_ecdsa) {
    639     c->mask_a |= SSL_aECDSA;
    640   }
    641 
    642   /* with PSK there must be client callback set */
    643   if (!ssl->psk_client_callback) {
    644     c->mask_a |= SSL_aPSK;
    645     c->mask_k |= SSL_kPSK;
    646   }
    647 }
    648 
    649 /* tls_extension represents a TLS extension that is handled internally. The
    650  * |init| function is called for each handshake, before any other functions of
    651  * the extension. Then the add and parse callbacks are called as needed.
    652  *
    653  * The parse callbacks receive a |CBS| that contains the contents of the
    654  * extension (i.e. not including the type and length bytes). If an extension is
    655  * not received then the parse callbacks will be called with a NULL CBS so that
    656  * they can do any processing needed to handle the absence of an extension.
    657  *
    658  * The add callbacks receive a |CBB| to which the extension can be appended but
    659  * the function is responsible for appending the type and length bytes too.
    660  *
    661  * All callbacks return one for success and zero for error. If a parse function
    662  * returns zero then a fatal alert with value |*out_alert| will be sent. If
    663  * |*out_alert| isn't set, then a |decode_error| alert will be sent. */
    664 struct tls_extension {
    665   uint16_t value;
    666   void (*init)(SSL *ssl);
    667 
    668   int (*add_clienthello)(SSL *ssl, CBB *out);
    669   int (*parse_serverhello)(SSL *ssl, uint8_t *out_alert, CBS *contents);
    670 
    671   int (*parse_clienthello)(SSL *ssl, uint8_t *out_alert, CBS *contents);
    672   int (*add_serverhello)(SSL *ssl, CBB *out);
    673 };
    674 
    675 
    676 /* Server name indication (SNI).
    677  *
    678  * https://tools.ietf.org/html/rfc6066#section-3. */
    679 
    680 static void ext_sni_init(SSL *ssl) {
    681   ssl->s3->tmp.should_ack_sni = 0;
    682 }
    683 
    684 static int ext_sni_add_clienthello(SSL *ssl, CBB *out) {
    685   if (ssl->tlsext_hostname == NULL) {
    686     return 1;
    687   }
    688 
    689   CBB contents, server_name_list, name;
    690   if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
    691       !CBB_add_u16_length_prefixed(out, &contents) ||
    692       !CBB_add_u16_length_prefixed(&contents, &server_name_list) ||
    693       !CBB_add_u8(&server_name_list, TLSEXT_NAMETYPE_host_name) ||
    694       !CBB_add_u16_length_prefixed(&server_name_list, &name) ||
    695       !CBB_add_bytes(&name, (const uint8_t *)ssl->tlsext_hostname,
    696                      strlen(ssl->tlsext_hostname)) ||
    697       !CBB_flush(out)) {
    698     return 0;
    699   }
    700 
    701   return 1;
    702 }
    703 
    704 static int ext_sni_parse_serverhello(SSL *ssl, uint8_t *out_alert,
    705                                      CBS *contents) {
    706   if (contents == NULL) {
    707     return 1;
    708   }
    709 
    710   if (CBS_len(contents) != 0) {
    711     return 0;
    712   }
    713 
    714   assert(ssl->tlsext_hostname != NULL);
    715 
    716   if (!ssl->hit) {
    717     assert(ssl->session->tlsext_hostname == NULL);
    718     ssl->session->tlsext_hostname = BUF_strdup(ssl->tlsext_hostname);
    719     if (!ssl->session->tlsext_hostname) {
    720       *out_alert = SSL_AD_INTERNAL_ERROR;
    721       return 0;
    722     }
    723   }
    724 
    725   return 1;
    726 }
    727 
    728 static int ext_sni_parse_clienthello(SSL *ssl, uint8_t *out_alert,
    729                                      CBS *contents) {
    730   if (contents == NULL) {
    731     return 1;
    732   }
    733 
    734   /* The servername extension is treated as follows:
    735    *
    736    * - Only the hostname type is supported with a maximum length of 255.
    737    * - The servername is rejected if too long or if it contains zeros, in
    738    *   which case an fatal alert is generated.
    739    * - The servername field is maintained together with the session cache.
    740    * - When a session is resumed, the servername callback is invoked in order
    741    *   to allow the application to position itself to the right context.
    742    * - The servername is acknowledged if it is new for a session or when
    743    *   it is identical to a previously used for the same session.
    744    *   Applications can control the behaviour.  They can at any time
    745    *   set a 'desirable' servername for a new SSL object. This can be the
    746    *   case for example with HTTPS when a Host: header field is received and
    747    *   a renegotiation is requested. In this case, a possible servername
    748    *   presented in the new client hello is only acknowledged if it matches
    749    *   the value of the Host: field.
    750    * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
    751    *   if they provide for changing an explicit servername context for the
    752    *   session,
    753    *   i.e. when the session has been established with a servername extension.
    754    */
    755 
    756   CBS server_name_list;
    757   char have_seen_host_name = 0;
    758 
    759   if (!CBS_get_u16_length_prefixed(contents, &server_name_list) ||
    760       CBS_len(&server_name_list) == 0 ||
    761       CBS_len(contents) != 0) {
    762     return 0;
    763   }
    764 
    765   /* Decode each ServerName in the extension. */
    766   while (CBS_len(&server_name_list) > 0) {
    767     uint8_t name_type;
    768     CBS host_name;
    769 
    770     if (!CBS_get_u8(&server_name_list, &name_type) ||
    771         !CBS_get_u16_length_prefixed(&server_name_list, &host_name)) {
    772       return 0;
    773     }
    774 
    775     /* Only host_name is supported. */
    776     if (name_type != TLSEXT_NAMETYPE_host_name) {
    777       continue;
    778     }
    779 
    780     if (have_seen_host_name) {
    781       /* The ServerNameList MUST NOT contain more than one name of the same
    782        * name_type. */
    783       return 0;
    784     }
    785 
    786     have_seen_host_name = 1;
    787 
    788     if (CBS_len(&host_name) == 0 ||
    789         CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||
    790         CBS_contains_zero_byte(&host_name)) {
    791       *out_alert = SSL_AD_UNRECOGNIZED_NAME;
    792       return 0;
    793     }
    794 
    795     if (!ssl->hit) {
    796       assert(ssl->session->tlsext_hostname == NULL);
    797       if (ssl->session->tlsext_hostname) {
    798         /* This should be impossible. */
    799         return 0;
    800       }
    801 
    802       /* Copy the hostname as a string. */
    803       if (!CBS_strdup(&host_name, &ssl->session->tlsext_hostname)) {
    804         *out_alert = SSL_AD_INTERNAL_ERROR;
    805         return 0;
    806       }
    807 
    808       ssl->s3->tmp.should_ack_sni = 1;
    809     }
    810   }
    811 
    812   return 1;
    813 }
    814 
    815 static int ext_sni_add_serverhello(SSL *ssl, CBB *out) {
    816   if (ssl->hit ||
    817       !ssl->s3->tmp.should_ack_sni ||
    818       ssl->session->tlsext_hostname == NULL) {
    819     return 1;
    820   }
    821 
    822   if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
    823       !CBB_add_u16(out, 0 /* length */)) {
    824     return 0;
    825   }
    826 
    827   return 1;
    828 }
    829 
    830 
    831 /* Renegotiation indication.
    832  *
    833  * https://tools.ietf.org/html/rfc5746 */
    834 
    835 static int ext_ri_add_clienthello(SSL *ssl, CBB *out) {
    836   CBB contents, prev_finished;
    837   if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
    838       !CBB_add_u16_length_prefixed(out, &contents) ||
    839       !CBB_add_u8_length_prefixed(&contents, &prev_finished) ||
    840       !CBB_add_bytes(&prev_finished, ssl->s3->previous_client_finished,
    841                      ssl->s3->previous_client_finished_len) ||
    842       !CBB_flush(out)) {
    843     return 0;
    844   }
    845 
    846   return 1;
    847 }
    848 
    849 static int ext_ri_parse_serverhello(SSL *ssl, uint8_t *out_alert,
    850                                     CBS *contents) {
    851   /* Servers may not switch between omitting the extension and supporting it.
    852    * See RFC 5746, sections 3.5 and 4.2. */
    853   if (ssl->s3->initial_handshake_complete &&
    854       (contents != NULL) != ssl->s3->send_connection_binding) {
    855     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    856     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    857     return 0;
    858   }
    859 
    860   if (contents == NULL) {
    861     /* Strictly speaking, if we want to avoid an attack we should *always* see
    862      * RI even on initial ServerHello because the client doesn't see any
    863      * renegotiation during an attack. However this would mean we could not
    864      * connect to any server which doesn't support RI.
    865      *
    866      * OpenSSL has |SSL_OP_LEGACY_SERVER_CONNECT| to control this, but in
    867      * practical terms every client sets it so it's just assumed here. */
    868     return 1;
    869   }
    870 
    871   const size_t expected_len = ssl->s3->previous_client_finished_len +
    872                               ssl->s3->previous_server_finished_len;
    873 
    874   /* Check for logic errors */
    875   assert(!expected_len || ssl->s3->previous_client_finished_len);
    876   assert(!expected_len || ssl->s3->previous_server_finished_len);
    877 
    878   /* Parse out the extension contents. */
    879   CBS renegotiated_connection;
    880   if (!CBS_get_u8_length_prefixed(contents, &renegotiated_connection) ||
    881       CBS_len(contents) != 0) {
    882     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
    883     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    884     return 0;
    885   }
    886 
    887   /* Check that the extension matches. */
    888   if (CBS_len(&renegotiated_connection) != expected_len) {
    889     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    890     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    891     return 0;
    892   }
    893 
    894   const uint8_t *d = CBS_data(&renegotiated_connection);
    895   if (CRYPTO_memcmp(d, ssl->s3->previous_client_finished,
    896         ssl->s3->previous_client_finished_len)) {
    897     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    898     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    899     return 0;
    900   }
    901   d += ssl->s3->previous_client_finished_len;
    902 
    903   if (CRYPTO_memcmp(d, ssl->s3->previous_server_finished,
    904         ssl->s3->previous_server_finished_len)) {
    905     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    906     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    907     return 0;
    908   }
    909   ssl->s3->send_connection_binding = 1;
    910 
    911   return 1;
    912 }
    913 
    914 static int ext_ri_parse_clienthello(SSL *ssl, uint8_t *out_alert,
    915                                     CBS *contents) {
    916   /* Renegotiation isn't supported as a server so this function should never be
    917    * called after the initial handshake. */
    918   assert(!ssl->s3->initial_handshake_complete);
    919 
    920   CBS fake_contents;
    921   static const uint8_t kFakeExtension[] = {0};
    922 
    923   if (contents == NULL) {
    924     if (ssl->s3->send_connection_binding) {
    925       /* The renegotiation SCSV was received so pretend that we received a
    926        * renegotiation extension. */
    927       CBS_init(&fake_contents, kFakeExtension, sizeof(kFakeExtension));
    928       contents = &fake_contents;
    929       /* We require that the renegotiation extension is at index zero of
    930        * kExtensions. */
    931       ssl->s3->tmp.extensions.received |= (1u << 0);
    932     } else {
    933       return 1;
    934     }
    935   }
    936 
    937   CBS renegotiated_connection;
    938 
    939   if (!CBS_get_u8_length_prefixed(contents, &renegotiated_connection) ||
    940       CBS_len(contents) != 0) {
    941     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
    942     return 0;
    943   }
    944 
    945   /* Check that the extension matches */
    946   if (!CBS_mem_equal(&renegotiated_connection,
    947                      ssl->s3->previous_client_finished,
    948                      ssl->s3->previous_client_finished_len)) {
    949     OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
    950     *out_alert = SSL_AD_HANDSHAKE_FAILURE;
    951     return 0;
    952   }
    953 
    954   ssl->s3->send_connection_binding = 1;
    955 
    956   return 1;
    957 }
    958 
    959 static int ext_ri_add_serverhello(SSL *ssl, CBB *out) {
    960   CBB contents, prev_finished;
    961   if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
    962       !CBB_add_u16_length_prefixed(out, &contents) ||
    963       !CBB_add_u8_length_prefixed(&contents, &prev_finished) ||
    964       !CBB_add_bytes(&prev_finished, ssl->s3->previous_client_finished,
    965                      ssl->s3->previous_client_finished_len) ||
    966       !CBB_add_bytes(&prev_finished, ssl->s3->previous_server_finished,
    967                      ssl->s3->previous_server_finished_len) ||
    968       !CBB_flush(out)) {
    969     return 0;
    970   }
    971 
    972   return 1;
    973 }
    974 
    975 
    976 /* Extended Master Secret.
    977  *
    978  * https://tools.ietf.org/html/draft-ietf-tls-session-hash-05 */
    979 
    980 static void ext_ems_init(SSL *ssl) {
    981   ssl->s3->tmp.extended_master_secret = 0;
    982 }
    983 
    984 static int ext_ems_add_clienthello(SSL *ssl, CBB *out) {
    985   if (ssl->version == SSL3_VERSION) {
    986     return 1;
    987   }
    988 
    989   if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
    990       !CBB_add_u16(out, 0 /* length */)) {
    991     return 0;
    992   }
    993 
    994   return 1;
    995 }
    996 
    997 static int ext_ems_parse_serverhello(SSL *ssl, uint8_t *out_alert,
    998                                      CBS *contents) {
    999   if (contents == NULL) {
   1000     return 1;
   1001   }
   1002 
   1003   if (ssl->version == SSL3_VERSION || CBS_len(contents) != 0) {
   1004     return 0;
   1005   }
   1006 
   1007   ssl->s3->tmp.extended_master_secret = 1;
   1008   return 1;
   1009 }
   1010 
   1011 static int ext_ems_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1012                                      CBS *contents) {
   1013   if (ssl->version == SSL3_VERSION || contents == NULL) {
   1014     return 1;
   1015   }
   1016 
   1017   if (CBS_len(contents) != 0) {
   1018     return 0;
   1019   }
   1020 
   1021   ssl->s3->tmp.extended_master_secret = 1;
   1022   return 1;
   1023 }
   1024 
   1025 static int ext_ems_add_serverhello(SSL *ssl, CBB *out) {
   1026   if (!ssl->s3->tmp.extended_master_secret) {
   1027     return 1;
   1028   }
   1029 
   1030   if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
   1031       !CBB_add_u16(out, 0 /* length */)) {
   1032     return 0;
   1033   }
   1034 
   1035   return 1;
   1036 }
   1037 
   1038 
   1039 /* Session tickets.
   1040  *
   1041  * https://tools.ietf.org/html/rfc5077 */
   1042 
   1043 static int ext_ticket_add_clienthello(SSL *ssl, CBB *out) {
   1044   if (SSL_get_options(ssl) & SSL_OP_NO_TICKET) {
   1045     return 1;
   1046   }
   1047 
   1048   const uint8_t *ticket_data = NULL;
   1049   int ticket_len = 0;
   1050 
   1051   /* Renegotiation does not participate in session resumption. However, still
   1052    * advertise the extension to avoid potentially breaking servers which carry
   1053    * over the state from the previous handshake, such as OpenSSL servers
   1054    * without upstream's 3c3f0259238594d77264a78944d409f2127642c4. */
   1055   if (!ssl->s3->initial_handshake_complete &&
   1056       ssl->session != NULL &&
   1057       ssl->session->tlsext_tick != NULL) {
   1058     ticket_data = ssl->session->tlsext_tick;
   1059     ticket_len = ssl->session->tlsext_ticklen;
   1060   }
   1061 
   1062   CBB ticket;
   1063   if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
   1064       !CBB_add_u16_length_prefixed(out, &ticket) ||
   1065       !CBB_add_bytes(&ticket, ticket_data, ticket_len) ||
   1066       !CBB_flush(out)) {
   1067     return 0;
   1068   }
   1069 
   1070   return 1;
   1071 }
   1072 
   1073 static int ext_ticket_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1074                                         CBS *contents) {
   1075   ssl->tlsext_ticket_expected = 0;
   1076 
   1077   if (contents == NULL) {
   1078     return 1;
   1079   }
   1080 
   1081   /* If |SSL_OP_NO_TICKET| is set then no extension will have been sent and
   1082    * this function should never be called, even if the server tries to send the
   1083    * extension. */
   1084   assert((SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0);
   1085 
   1086   if (CBS_len(contents) != 0) {
   1087     return 0;
   1088   }
   1089 
   1090   ssl->tlsext_ticket_expected = 1;
   1091   return 1;
   1092 }
   1093 
   1094 static int ext_ticket_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1095                                         CBS *contents) {
   1096   /* This function isn't used because the ticket extension from the client is
   1097    * handled in ssl_session.c. */
   1098   return 1;
   1099 }
   1100 
   1101 static int ext_ticket_add_serverhello(SSL *ssl, CBB *out) {
   1102   if (!ssl->tlsext_ticket_expected) {
   1103     return 1;
   1104   }
   1105 
   1106   /* If |SSL_OP_NO_TICKET| is set, |tlsext_ticket_expected| should never be
   1107    * true. */
   1108   assert((SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0);
   1109 
   1110   if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
   1111       !CBB_add_u16(out, 0 /* length */)) {
   1112     return 0;
   1113   }
   1114 
   1115   return 1;
   1116 }
   1117 
   1118 
   1119 /* Signature Algorithms.
   1120  *
   1121  * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   1122 
   1123 static int ext_sigalgs_add_clienthello(SSL *ssl, CBB *out) {
   1124   if (ssl3_version_from_wire(ssl, ssl->client_version) < TLS1_2_VERSION) {
   1125     return 1;
   1126   }
   1127 
   1128   const uint8_t *sigalgs_data;
   1129   const size_t sigalgs_len = tls12_get_psigalgs(ssl, &sigalgs_data);
   1130 
   1131   CBB contents, sigalgs;
   1132   if (!CBB_add_u16(out, TLSEXT_TYPE_signature_algorithms) ||
   1133       !CBB_add_u16_length_prefixed(out, &contents) ||
   1134       !CBB_add_u16_length_prefixed(&contents, &sigalgs) ||
   1135       !CBB_add_bytes(&sigalgs, sigalgs_data, sigalgs_len) ||
   1136       !CBB_flush(out)) {
   1137     return 0;
   1138   }
   1139 
   1140   return 1;
   1141 }
   1142 
   1143 static int ext_sigalgs_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1144                                          CBS *contents) {
   1145   if (contents != NULL) {
   1146     /* Servers MUST NOT send this extension. */
   1147     *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   1148     OPENSSL_PUT_ERROR(SSL, SSL_R_SIGNATURE_ALGORITHMS_EXTENSION_SENT_BY_SERVER);
   1149     return 0;
   1150   }
   1151 
   1152   return 1;
   1153 }
   1154 
   1155 static int ext_sigalgs_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1156                                          CBS *contents) {
   1157   OPENSSL_free(ssl->cert->peer_sigalgs);
   1158   ssl->cert->peer_sigalgs = NULL;
   1159   ssl->cert->peer_sigalgslen = 0;
   1160 
   1161   if (contents == NULL) {
   1162     return 1;
   1163   }
   1164 
   1165   CBS supported_signature_algorithms;
   1166   if (!CBS_get_u16_length_prefixed(contents, &supported_signature_algorithms) ||
   1167       CBS_len(contents) != 0 ||
   1168       CBS_len(&supported_signature_algorithms) == 0 ||
   1169       !tls1_parse_peer_sigalgs(ssl, &supported_signature_algorithms)) {
   1170     return 0;
   1171   }
   1172 
   1173   return 1;
   1174 }
   1175 
   1176 static int ext_sigalgs_add_serverhello(SSL *ssl, CBB *out) {
   1177   /* Servers MUST NOT send this extension. */
   1178   return 1;
   1179 }
   1180 
   1181 
   1182 /* OCSP Stapling.
   1183  *
   1184  * https://tools.ietf.org/html/rfc6066#section-8 */
   1185 
   1186 static void ext_ocsp_init(SSL *ssl) {
   1187   ssl->s3->tmp.certificate_status_expected = 0;
   1188 }
   1189 
   1190 static int ext_ocsp_add_clienthello(SSL *ssl, CBB *out) {
   1191   if (!ssl->ocsp_stapling_enabled) {
   1192     return 1;
   1193   }
   1194 
   1195   CBB contents;
   1196   if (!CBB_add_u16(out, TLSEXT_TYPE_status_request) ||
   1197       !CBB_add_u16_length_prefixed(out, &contents) ||
   1198       !CBB_add_u8(&contents, TLSEXT_STATUSTYPE_ocsp) ||
   1199       !CBB_add_u16(&contents, 0 /* empty responder ID list */) ||
   1200       !CBB_add_u16(&contents, 0 /* empty request extensions */) ||
   1201       !CBB_flush(out)) {
   1202     return 0;
   1203   }
   1204 
   1205   return 1;
   1206 }
   1207 
   1208 static int ext_ocsp_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1209                                       CBS *contents) {
   1210   if (contents == NULL) {
   1211     return 1;
   1212   }
   1213 
   1214   if (CBS_len(contents) != 0) {
   1215     return 0;
   1216   }
   1217 
   1218   ssl->s3->tmp.certificate_status_expected = 1;
   1219   return 1;
   1220 }
   1221 
   1222 static int ext_ocsp_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1223                                       CBS *contents) {
   1224   if (contents == NULL) {
   1225     return 1;
   1226   }
   1227 
   1228   uint8_t status_type;
   1229   if (!CBS_get_u8(contents, &status_type)) {
   1230     return 0;
   1231   }
   1232 
   1233   /* We cannot decide whether OCSP stapling will occur yet because the correct
   1234    * SSL_CTX might not have been selected. */
   1235   ssl->s3->tmp.ocsp_stapling_requested = status_type == TLSEXT_STATUSTYPE_ocsp;
   1236 
   1237   return 1;
   1238 }
   1239 
   1240 static int ext_ocsp_add_serverhello(SSL *ssl, CBB *out) {
   1241   /* The extension shouldn't be sent when resuming sessions. */
   1242   if (ssl->hit ||
   1243       !ssl->s3->tmp.ocsp_stapling_requested ||
   1244       ssl->ctx->ocsp_response_length == 0) {
   1245     return 1;
   1246   }
   1247 
   1248   ssl->s3->tmp.certificate_status_expected = 1;
   1249 
   1250   return CBB_add_u16(out, TLSEXT_TYPE_status_request) &&
   1251          CBB_add_u16(out, 0 /* length */);
   1252 }
   1253 
   1254 
   1255 /* Next protocol negotiation.
   1256  *
   1257  * https://htmlpreview.github.io/?https://github.com/agl/technotes/blob/master/nextprotoneg.html */
   1258 
   1259 static void ext_npn_init(SSL *ssl) {
   1260   ssl->s3->next_proto_neg_seen = 0;
   1261 }
   1262 
   1263 static int ext_npn_add_clienthello(SSL *ssl, CBB *out) {
   1264   if (ssl->s3->initial_handshake_complete ||
   1265       ssl->ctx->next_proto_select_cb == NULL ||
   1266       (ssl->options & SSL_OP_DISABLE_NPN) ||
   1267       SSL_IS_DTLS(ssl)) {
   1268     return 1;
   1269   }
   1270 
   1271   if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
   1272       !CBB_add_u16(out, 0 /* length */)) {
   1273     return 0;
   1274   }
   1275 
   1276   return 1;
   1277 }
   1278 
   1279 static int ext_npn_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1280                                      CBS *contents) {
   1281   if (contents == NULL) {
   1282     return 1;
   1283   }
   1284 
   1285   /* If any of these are false then we should never have sent the NPN
   1286    * extension in the ClientHello and thus this function should never have been
   1287    * called. */
   1288   assert(!ssl->s3->initial_handshake_complete);
   1289   assert(!SSL_IS_DTLS(ssl));
   1290   assert(ssl->ctx->next_proto_select_cb != NULL);
   1291   assert(!(ssl->options & SSL_OP_DISABLE_NPN));
   1292 
   1293   if (ssl->s3->alpn_selected != NULL) {
   1294     /* NPN and ALPN may not be negotiated in the same connection. */
   1295     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1296     OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
   1297     return 0;
   1298   }
   1299 
   1300   const uint8_t *const orig_contents = CBS_data(contents);
   1301   const size_t orig_len = CBS_len(contents);
   1302 
   1303   while (CBS_len(contents) != 0) {
   1304     CBS proto;
   1305     if (!CBS_get_u8_length_prefixed(contents, &proto) ||
   1306         CBS_len(&proto) == 0) {
   1307       return 0;
   1308     }
   1309   }
   1310 
   1311   uint8_t *selected;
   1312   uint8_t selected_len;
   1313   if (ssl->ctx->next_proto_select_cb(
   1314           ssl, &selected, &selected_len, orig_contents, orig_len,
   1315           ssl->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) {
   1316     *out_alert = SSL_AD_INTERNAL_ERROR;
   1317     return 0;
   1318   }
   1319 
   1320   OPENSSL_free(ssl->next_proto_negotiated);
   1321   ssl->next_proto_negotiated = BUF_memdup(selected, selected_len);
   1322   if (ssl->next_proto_negotiated == NULL) {
   1323     *out_alert = SSL_AD_INTERNAL_ERROR;
   1324     return 0;
   1325   }
   1326 
   1327   ssl->next_proto_negotiated_len = selected_len;
   1328   ssl->s3->next_proto_neg_seen = 1;
   1329 
   1330   return 1;
   1331 }
   1332 
   1333 static int ext_npn_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1334                                      CBS *contents) {
   1335   if (contents != NULL && CBS_len(contents) != 0) {
   1336     return 0;
   1337   }
   1338 
   1339   if (contents == NULL ||
   1340       ssl->s3->initial_handshake_complete ||
   1341       /* If the ALPN extension is seen before NPN, ignore it. (If ALPN is seen
   1342        * afterwards, parsing the ALPN extension will clear
   1343        * |next_proto_neg_seen|. */
   1344       ssl->s3->alpn_selected != NULL ||
   1345       ssl->ctx->next_protos_advertised_cb == NULL ||
   1346       SSL_IS_DTLS(ssl)) {
   1347     return 1;
   1348   }
   1349 
   1350   ssl->s3->next_proto_neg_seen = 1;
   1351   return 1;
   1352 }
   1353 
   1354 static int ext_npn_add_serverhello(SSL *ssl, CBB *out) {
   1355   /* |next_proto_neg_seen| might have been cleared when an ALPN extension was
   1356    * parsed. */
   1357   if (!ssl->s3->next_proto_neg_seen) {
   1358     return 1;
   1359   }
   1360 
   1361   const uint8_t *npa;
   1362   unsigned npa_len;
   1363 
   1364   if (ssl->ctx->next_protos_advertised_cb(
   1365           ssl, &npa, &npa_len, ssl->ctx->next_protos_advertised_cb_arg) !=
   1366       SSL_TLSEXT_ERR_OK) {
   1367     ssl->s3->next_proto_neg_seen = 0;
   1368     return 1;
   1369   }
   1370 
   1371   CBB contents;
   1372   if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
   1373       !CBB_add_u16_length_prefixed(out, &contents) ||
   1374       !CBB_add_bytes(&contents, npa, npa_len) ||
   1375       !CBB_flush(out)) {
   1376     return 0;
   1377   }
   1378 
   1379   return 1;
   1380 }
   1381 
   1382 
   1383 /* Signed certificate timestamps.
   1384  *
   1385  * https://tools.ietf.org/html/rfc6962#section-3.3.1 */
   1386 
   1387 static int ext_sct_add_clienthello(SSL *ssl, CBB *out) {
   1388   if (!ssl->signed_cert_timestamps_enabled) {
   1389     return 1;
   1390   }
   1391 
   1392   if (!CBB_add_u16(out, TLSEXT_TYPE_certificate_timestamp) ||
   1393       !CBB_add_u16(out, 0 /* length */)) {
   1394     return 0;
   1395   }
   1396 
   1397   return 1;
   1398 }
   1399 
   1400 static int ext_sct_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1401                                      CBS *contents) {
   1402   if (contents == NULL) {
   1403     return 1;
   1404   }
   1405 
   1406   /* If this is false then we should never have sent the SCT extension in the
   1407    * ClientHello and thus this function should never have been called. */
   1408   assert(ssl->signed_cert_timestamps_enabled);
   1409 
   1410   if (CBS_len(contents) == 0) {
   1411     *out_alert = SSL_AD_DECODE_ERROR;
   1412     return 0;
   1413   }
   1414 
   1415   /* Session resumption uses the original session information. */
   1416   if (!ssl->hit &&
   1417       !CBS_stow(contents, &ssl->session->tlsext_signed_cert_timestamp_list,
   1418                 &ssl->session->tlsext_signed_cert_timestamp_list_length)) {
   1419     *out_alert = SSL_AD_INTERNAL_ERROR;
   1420     return 0;
   1421   }
   1422 
   1423   return 1;
   1424 }
   1425 
   1426 static int ext_sct_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1427                                      CBS *contents) {
   1428   return contents == NULL || CBS_len(contents) == 0;
   1429 }
   1430 
   1431 static int ext_sct_add_serverhello(SSL *ssl, CBB *out) {
   1432   /* The extension shouldn't be sent when resuming sessions. */
   1433   if (ssl->hit ||
   1434       ssl->ctx->signed_cert_timestamp_list_length == 0) {
   1435     return 1;
   1436   }
   1437 
   1438   CBB contents;
   1439   return CBB_add_u16(out, TLSEXT_TYPE_certificate_timestamp) &&
   1440          CBB_add_u16_length_prefixed(out, &contents) &&
   1441          CBB_add_bytes(&contents, ssl->ctx->signed_cert_timestamp_list,
   1442                        ssl->ctx->signed_cert_timestamp_list_length) &&
   1443          CBB_flush(out);
   1444 }
   1445 
   1446 
   1447 /* Application-level Protocol Negotiation.
   1448  *
   1449  * https://tools.ietf.org/html/rfc7301 */
   1450 
   1451 static void ext_alpn_init(SSL *ssl) {
   1452   OPENSSL_free(ssl->s3->alpn_selected);
   1453   ssl->s3->alpn_selected = NULL;
   1454 }
   1455 
   1456 static int ext_alpn_add_clienthello(SSL *ssl, CBB *out) {
   1457   if (ssl->alpn_client_proto_list == NULL ||
   1458       ssl->s3->initial_handshake_complete) {
   1459     return 1;
   1460   }
   1461 
   1462   CBB contents, proto_list;
   1463   if (!CBB_add_u16(out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
   1464       !CBB_add_u16_length_prefixed(out, &contents) ||
   1465       !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
   1466       !CBB_add_bytes(&proto_list, ssl->alpn_client_proto_list,
   1467                      ssl->alpn_client_proto_list_len) ||
   1468       !CBB_flush(out)) {
   1469     return 0;
   1470   }
   1471 
   1472   return 1;
   1473 }
   1474 
   1475 static int ext_alpn_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1476                                       CBS *contents) {
   1477   if (contents == NULL) {
   1478     return 1;
   1479   }
   1480 
   1481   assert(!ssl->s3->initial_handshake_complete);
   1482   assert(ssl->alpn_client_proto_list != NULL);
   1483 
   1484   if (ssl->s3->next_proto_neg_seen) {
   1485     /* NPN and ALPN may not be negotiated in the same connection. */
   1486     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1487     OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
   1488     return 0;
   1489   }
   1490 
   1491   /* The extension data consists of a ProtocolNameList which must have
   1492    * exactly one ProtocolName. Each of these is length-prefixed. */
   1493   CBS protocol_name_list, protocol_name;
   1494   if (!CBS_get_u16_length_prefixed(contents, &protocol_name_list) ||
   1495       CBS_len(contents) != 0 ||
   1496       !CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
   1497       /* Empty protocol names are forbidden. */
   1498       CBS_len(&protocol_name) == 0 ||
   1499       CBS_len(&protocol_name_list) != 0) {
   1500     return 0;
   1501   }
   1502 
   1503   if (!CBS_stow(&protocol_name, &ssl->s3->alpn_selected,
   1504                 &ssl->s3->alpn_selected_len)) {
   1505     *out_alert = SSL_AD_INTERNAL_ERROR;
   1506     return 0;
   1507   }
   1508 
   1509   return 1;
   1510 }
   1511 
   1512 static int ext_alpn_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1513                                       CBS *contents) {
   1514   if (contents == NULL) {
   1515     return 1;
   1516   }
   1517 
   1518   if (ssl->ctx->alpn_select_cb == NULL ||
   1519       ssl->s3->initial_handshake_complete) {
   1520     return 1;
   1521   }
   1522 
   1523   /* ALPN takes precedence over NPN. */
   1524   ssl->s3->next_proto_neg_seen = 0;
   1525 
   1526   CBS protocol_name_list;
   1527   if (!CBS_get_u16_length_prefixed(contents, &protocol_name_list) ||
   1528       CBS_len(contents) != 0 ||
   1529       CBS_len(&protocol_name_list) < 2) {
   1530     return 0;
   1531   }
   1532 
   1533   /* Validate the protocol list. */
   1534   CBS protocol_name_list_copy = protocol_name_list;
   1535   while (CBS_len(&protocol_name_list_copy) > 0) {
   1536     CBS protocol_name;
   1537 
   1538     if (!CBS_get_u8_length_prefixed(&protocol_name_list_copy, &protocol_name) ||
   1539         /* Empty protocol names are forbidden. */
   1540         CBS_len(&protocol_name) == 0) {
   1541       return 0;
   1542     }
   1543   }
   1544 
   1545   const uint8_t *selected;
   1546   uint8_t selected_len;
   1547   if (ssl->ctx->alpn_select_cb(
   1548           ssl, &selected, &selected_len, CBS_data(&protocol_name_list),
   1549           CBS_len(&protocol_name_list),
   1550           ssl->ctx->alpn_select_cb_arg) == SSL_TLSEXT_ERR_OK) {
   1551     OPENSSL_free(ssl->s3->alpn_selected);
   1552     ssl->s3->alpn_selected = BUF_memdup(selected, selected_len);
   1553     if (ssl->s3->alpn_selected == NULL) {
   1554       *out_alert = SSL_AD_INTERNAL_ERROR;
   1555       return 0;
   1556     }
   1557     ssl->s3->alpn_selected_len = selected_len;
   1558   }
   1559 
   1560   return 1;
   1561 }
   1562 
   1563 static int ext_alpn_add_serverhello(SSL *ssl, CBB *out) {
   1564   if (ssl->s3->alpn_selected == NULL) {
   1565     return 1;
   1566   }
   1567 
   1568   CBB contents, proto_list, proto;
   1569   if (!CBB_add_u16(out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
   1570       !CBB_add_u16_length_prefixed(out, &contents) ||
   1571       !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
   1572       !CBB_add_u8_length_prefixed(&proto_list, &proto) ||
   1573       !CBB_add_bytes(&proto, ssl->s3->alpn_selected,
   1574                      ssl->s3->alpn_selected_len) ||
   1575       !CBB_flush(out)) {
   1576     return 0;
   1577   }
   1578 
   1579   return 1;
   1580 }
   1581 
   1582 
   1583 /* Channel ID.
   1584  *
   1585  * https://tools.ietf.org/html/draft-balfanz-tls-channelid-01 */
   1586 
   1587 static void ext_channel_id_init(SSL *ssl) {
   1588   ssl->s3->tlsext_channel_id_valid = 0;
   1589 }
   1590 
   1591 static int ext_channel_id_add_clienthello(SSL *ssl, CBB *out) {
   1592   if (!ssl->tlsext_channel_id_enabled ||
   1593       SSL_IS_DTLS(ssl)) {
   1594     return 1;
   1595   }
   1596 
   1597   if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
   1598       !CBB_add_u16(out, 0 /* length */)) {
   1599     return 0;
   1600   }
   1601 
   1602   return 1;
   1603 }
   1604 
   1605 static int ext_channel_id_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1606                                             CBS *contents) {
   1607   if (contents == NULL) {
   1608     return 1;
   1609   }
   1610 
   1611   assert(!SSL_IS_DTLS(ssl));
   1612   assert(ssl->tlsext_channel_id_enabled);
   1613 
   1614   if (CBS_len(contents) != 0) {
   1615     return 0;
   1616   }
   1617 
   1618   ssl->s3->tlsext_channel_id_valid = 1;
   1619   return 1;
   1620 }
   1621 
   1622 static int ext_channel_id_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1623                                             CBS *contents) {
   1624   if (contents == NULL ||
   1625       !ssl->tlsext_channel_id_enabled ||
   1626       SSL_IS_DTLS(ssl)) {
   1627     return 1;
   1628   }
   1629 
   1630   if (CBS_len(contents) != 0) {
   1631     return 0;
   1632   }
   1633 
   1634   ssl->s3->tlsext_channel_id_valid = 1;
   1635   return 1;
   1636 }
   1637 
   1638 static int ext_channel_id_add_serverhello(SSL *ssl, CBB *out) {
   1639   if (!ssl->s3->tlsext_channel_id_valid) {
   1640     return 1;
   1641   }
   1642 
   1643   if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
   1644       !CBB_add_u16(out, 0 /* length */)) {
   1645     return 0;
   1646   }
   1647 
   1648   return 1;
   1649 }
   1650 
   1651 
   1652 /* Secure Real-time Transport Protocol (SRTP) extension.
   1653  *
   1654  * https://tools.ietf.org/html/rfc5764 */
   1655 
   1656 
   1657 static void ext_srtp_init(SSL *ssl) {
   1658   ssl->srtp_profile = NULL;
   1659 }
   1660 
   1661 static int ext_srtp_add_clienthello(SSL *ssl, CBB *out) {
   1662   STACK_OF(SRTP_PROTECTION_PROFILE) *profiles = SSL_get_srtp_profiles(ssl);
   1663   if (profiles == NULL) {
   1664     return 1;
   1665   }
   1666   const size_t num_profiles = sk_SRTP_PROTECTION_PROFILE_num(profiles);
   1667   if (num_profiles == 0) {
   1668     return 1;
   1669   }
   1670 
   1671   CBB contents, profile_ids;
   1672   if (!CBB_add_u16(out, TLSEXT_TYPE_srtp) ||
   1673       !CBB_add_u16_length_prefixed(out, &contents) ||
   1674       !CBB_add_u16_length_prefixed(&contents, &profile_ids)) {
   1675     return 0;
   1676   }
   1677 
   1678   size_t i;
   1679   for (i = 0; i < num_profiles; i++) {
   1680     if (!CBB_add_u16(&profile_ids,
   1681                      sk_SRTP_PROTECTION_PROFILE_value(profiles, i)->id)) {
   1682       return 0;
   1683     }
   1684   }
   1685 
   1686   if (!CBB_add_u8(&contents, 0 /* empty use_mki value */) ||
   1687       !CBB_flush(out)) {
   1688     return 0;
   1689   }
   1690 
   1691   return 1;
   1692 }
   1693 
   1694 static int ext_srtp_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1695                                       CBS *contents) {
   1696   if (contents == NULL) {
   1697     return 1;
   1698   }
   1699 
   1700   /* The extension consists of a u16-prefixed profile ID list containing a
   1701    * single uint16_t profile ID, then followed by a u8-prefixed srtp_mki field.
   1702    *
   1703    * See https://tools.ietf.org/html/rfc5764#section-4.1.1 */
   1704   CBS profile_ids, srtp_mki;
   1705   uint16_t profile_id;
   1706   if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
   1707       !CBS_get_u16(&profile_ids, &profile_id) ||
   1708       CBS_len(&profile_ids) != 0 ||
   1709       !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
   1710       CBS_len(contents) != 0) {
   1711     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
   1712     return 0;
   1713   }
   1714 
   1715   if (CBS_len(&srtp_mki) != 0) {
   1716     /* Must be no MKI, since we never offer one. */
   1717     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_MKI_VALUE);
   1718     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1719     return 0;
   1720   }
   1721 
   1722   STACK_OF(SRTP_PROTECTION_PROFILE) *profiles = SSL_get_srtp_profiles(ssl);
   1723 
   1724   /* Check to see if the server gave us something we support (and presumably
   1725    * offered). */
   1726   size_t i;
   1727   for (i = 0; i < sk_SRTP_PROTECTION_PROFILE_num(profiles); i++) {
   1728     const SRTP_PROTECTION_PROFILE *profile =
   1729         sk_SRTP_PROTECTION_PROFILE_value(profiles, i);
   1730 
   1731     if (profile->id == profile_id) {
   1732       ssl->srtp_profile = profile;
   1733       return 1;
   1734     }
   1735   }
   1736 
   1737   OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
   1738   *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1739   return 0;
   1740 }
   1741 
   1742 static int ext_srtp_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1743                                       CBS *contents) {
   1744   if (contents == NULL) {
   1745     return 1;
   1746   }
   1747 
   1748   CBS profile_ids, srtp_mki;
   1749   if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
   1750       CBS_len(&profile_ids) < 2 ||
   1751       !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
   1752       CBS_len(contents) != 0) {
   1753     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
   1754     return 0;
   1755   }
   1756   /* Discard the MKI value for now. */
   1757 
   1758   const STACK_OF(SRTP_PROTECTION_PROFILE) *server_profiles =
   1759       SSL_get_srtp_profiles(ssl);
   1760 
   1761   /* Pick the server's most preferred profile. */
   1762   size_t i;
   1763   for (i = 0; i < sk_SRTP_PROTECTION_PROFILE_num(server_profiles); i++) {
   1764     const SRTP_PROTECTION_PROFILE *server_profile =
   1765         sk_SRTP_PROTECTION_PROFILE_value(server_profiles, i);
   1766 
   1767     CBS profile_ids_tmp;
   1768     CBS_init(&profile_ids_tmp, CBS_data(&profile_ids), CBS_len(&profile_ids));
   1769 
   1770     while (CBS_len(&profile_ids_tmp) > 0) {
   1771       uint16_t profile_id;
   1772       if (!CBS_get_u16(&profile_ids_tmp, &profile_id)) {
   1773         return 0;
   1774       }
   1775 
   1776       if (server_profile->id == profile_id) {
   1777         ssl->srtp_profile = server_profile;
   1778         return 1;
   1779       }
   1780     }
   1781   }
   1782 
   1783   return 1;
   1784 }
   1785 
   1786 static int ext_srtp_add_serverhello(SSL *ssl, CBB *out) {
   1787   if (ssl->srtp_profile == NULL) {
   1788     return 1;
   1789   }
   1790 
   1791   CBB contents, profile_ids;
   1792   if (!CBB_add_u16(out, TLSEXT_TYPE_srtp) ||
   1793       !CBB_add_u16_length_prefixed(out, &contents) ||
   1794       !CBB_add_u16_length_prefixed(&contents, &profile_ids) ||
   1795       !CBB_add_u16(&profile_ids, ssl->srtp_profile->id) ||
   1796       !CBB_add_u8(&contents, 0 /* empty MKI */) ||
   1797       !CBB_flush(out)) {
   1798     return 0;
   1799   }
   1800 
   1801   return 1;
   1802 }
   1803 
   1804 
   1805 /* EC point formats.
   1806  *
   1807  * https://tools.ietf.org/html/rfc4492#section-5.1.2 */
   1808 
   1809 static int ssl_any_ec_cipher_suites_enabled(const SSL *ssl) {
   1810   if (ssl->version < TLS1_VERSION && !SSL_IS_DTLS(ssl)) {
   1811     return 0;
   1812   }
   1813 
   1814   const STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(ssl);
   1815 
   1816   size_t i;
   1817   for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) {
   1818     const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(cipher_stack, i);
   1819 
   1820     const uint32_t alg_k = cipher->algorithm_mkey;
   1821     const uint32_t alg_a = cipher->algorithm_auth;
   1822     if ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA)) {
   1823       return 1;
   1824     }
   1825   }
   1826 
   1827   return 0;
   1828 }
   1829 
   1830 static int ext_ec_point_add_extension(SSL *ssl, CBB *out) {
   1831   CBB contents, formats;
   1832   if (!CBB_add_u16(out, TLSEXT_TYPE_ec_point_formats) ||
   1833       !CBB_add_u16_length_prefixed(out, &contents) ||
   1834       !CBB_add_u8_length_prefixed(&contents, &formats) ||
   1835       !CBB_add_u8(&formats, TLSEXT_ECPOINTFORMAT_uncompressed) ||
   1836       !CBB_flush(out)) {
   1837     return 0;
   1838   }
   1839 
   1840   return 1;
   1841 }
   1842 
   1843 static int ext_ec_point_add_clienthello(SSL *ssl, CBB *out) {
   1844   if (!ssl_any_ec_cipher_suites_enabled(ssl)) {
   1845     return 1;
   1846   }
   1847 
   1848   return ext_ec_point_add_extension(ssl, out);
   1849 }
   1850 
   1851 static int ext_ec_point_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1852                                           CBS *contents) {
   1853   if (contents == NULL) {
   1854     return 1;
   1855   }
   1856 
   1857   CBS ec_point_format_list;
   1858   if (!CBS_get_u8_length_prefixed(contents, &ec_point_format_list) ||
   1859       CBS_len(contents) != 0) {
   1860     return 0;
   1861   }
   1862 
   1863   /* Per RFC 4492, section 5.1.2, implementations MUST support the uncompressed
   1864    * point format. */
   1865   if (memchr(CBS_data(&ec_point_format_list), TLSEXT_ECPOINTFORMAT_uncompressed,
   1866              CBS_len(&ec_point_format_list)) == NULL) {
   1867     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1868     return 0;
   1869   }
   1870 
   1871   return 1;
   1872 }
   1873 
   1874 static int ext_ec_point_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1875                                           CBS *contents) {
   1876   return ext_ec_point_parse_serverhello(ssl, out_alert, contents);
   1877 }
   1878 
   1879 static int ext_ec_point_add_serverhello(SSL *ssl, CBB *out) {
   1880   const uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
   1881   const uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
   1882   const int using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);
   1883 
   1884   if (!using_ecc) {
   1885     return 1;
   1886   }
   1887 
   1888   return ext_ec_point_add_extension(ssl, out);
   1889 }
   1890 
   1891 
   1892 /* EC supported curves.
   1893  *
   1894  * https://tools.ietf.org/html/rfc4492#section-5.1.2 */
   1895 
   1896 static void ext_ec_curves_init(SSL *ssl) {
   1897   OPENSSL_free(ssl->s3->tmp.peer_ellipticcurvelist);
   1898   ssl->s3->tmp.peer_ellipticcurvelist = NULL;
   1899   ssl->s3->tmp.peer_ellipticcurvelist_length = 0;
   1900 }
   1901 
   1902 static int ext_ec_curves_add_clienthello(SSL *ssl, CBB *out) {
   1903   if (!ssl_any_ec_cipher_suites_enabled(ssl)) {
   1904     return 1;
   1905   }
   1906 
   1907   CBB contents, curves_bytes;
   1908   if (!CBB_add_u16(out, TLSEXT_TYPE_elliptic_curves) ||
   1909       !CBB_add_u16_length_prefixed(out, &contents) ||
   1910       !CBB_add_u16_length_prefixed(&contents, &curves_bytes)) {
   1911     return 0;
   1912   }
   1913 
   1914   const uint16_t *curves;
   1915   size_t curves_len;
   1916   tls1_get_curvelist(ssl, 0, &curves, &curves_len);
   1917 
   1918   size_t i;
   1919   for (i = 0; i < curves_len; i++) {
   1920     if (!CBB_add_u16(&curves_bytes, curves[i])) {
   1921       return 0;
   1922     }
   1923   }
   1924 
   1925   return CBB_flush(out);
   1926 }
   1927 
   1928 static int ext_ec_curves_parse_serverhello(SSL *ssl, uint8_t *out_alert,
   1929                                            CBS *contents) {
   1930   /* This extension is not expected to be echoed by servers and is ignored. */
   1931   return 1;
   1932 }
   1933 
   1934 static int ext_ec_curves_parse_clienthello(SSL *ssl, uint8_t *out_alert,
   1935                                            CBS *contents) {
   1936   if (contents == NULL) {
   1937     return 1;
   1938   }
   1939 
   1940   CBS elliptic_curve_list;
   1941   if (!CBS_get_u16_length_prefixed(contents, &elliptic_curve_list) ||
   1942       CBS_len(&elliptic_curve_list) == 0 ||
   1943       (CBS_len(&elliptic_curve_list) & 1) != 0 ||
   1944       CBS_len(contents) != 0) {
   1945     return 0;
   1946   }
   1947 
   1948   ssl->s3->tmp.peer_ellipticcurvelist =
   1949       (uint16_t *)OPENSSL_malloc(CBS_len(&elliptic_curve_list));
   1950 
   1951   if (ssl->s3->tmp.peer_ellipticcurvelist == NULL) {
   1952     *out_alert = SSL_AD_INTERNAL_ERROR;
   1953     return 0;
   1954   }
   1955 
   1956   const size_t num_curves = CBS_len(&elliptic_curve_list) / 2;
   1957   size_t i;
   1958   for (i = 0; i < num_curves; i++) {
   1959     if (!CBS_get_u16(&elliptic_curve_list,
   1960                      &ssl->s3->tmp.peer_ellipticcurvelist[i])) {
   1961       goto err;
   1962     }
   1963   }
   1964 
   1965   assert(CBS_len(&elliptic_curve_list) == 0);
   1966   ssl->s3->tmp.peer_ellipticcurvelist_length = num_curves;
   1967 
   1968   return 1;
   1969 
   1970 err:
   1971   OPENSSL_free(ssl->s3->tmp.peer_ellipticcurvelist);
   1972   ssl->s3->tmp.peer_ellipticcurvelist = NULL;
   1973   *out_alert = SSL_AD_INTERNAL_ERROR;
   1974   return 0;
   1975 }
   1976 
   1977 static int ext_ec_curves_add_serverhello(SSL *ssl, CBB *out) {
   1978   /* Servers don't echo this extension. */
   1979   return 1;
   1980 }
   1981 
   1982 
   1983 /* kExtensions contains all the supported extensions. */
   1984 static const struct tls_extension kExtensions[] = {
   1985   {
   1986     /* The renegotiation extension must always be at index zero because the
   1987      * |received| and |sent| bitsets need to be tweaked when the "extension" is
   1988      * sent as an SCSV. */
   1989     TLSEXT_TYPE_renegotiate,
   1990     NULL,
   1991     ext_ri_add_clienthello,
   1992     ext_ri_parse_serverhello,
   1993     ext_ri_parse_clienthello,
   1994     ext_ri_add_serverhello,
   1995   },
   1996   {
   1997     TLSEXT_TYPE_server_name,
   1998     ext_sni_init,
   1999     ext_sni_add_clienthello,
   2000     ext_sni_parse_serverhello,
   2001     ext_sni_parse_clienthello,
   2002     ext_sni_add_serverhello,
   2003   },
   2004   {
   2005     TLSEXT_TYPE_extended_master_secret,
   2006     ext_ems_init,
   2007     ext_ems_add_clienthello,
   2008     ext_ems_parse_serverhello,
   2009     ext_ems_parse_clienthello,
   2010     ext_ems_add_serverhello,
   2011   },
   2012   {
   2013     TLSEXT_TYPE_session_ticket,
   2014     NULL,
   2015     ext_ticket_add_clienthello,
   2016     ext_ticket_parse_serverhello,
   2017     ext_ticket_parse_clienthello,
   2018     ext_ticket_add_serverhello,
   2019   },
   2020   {
   2021     TLSEXT_TYPE_signature_algorithms,
   2022     NULL,
   2023     ext_sigalgs_add_clienthello,
   2024     ext_sigalgs_parse_serverhello,
   2025     ext_sigalgs_parse_clienthello,
   2026     ext_sigalgs_add_serverhello,
   2027   },
   2028   {
   2029     TLSEXT_TYPE_status_request,
   2030     ext_ocsp_init,
   2031     ext_ocsp_add_clienthello,
   2032     ext_ocsp_parse_serverhello,
   2033     ext_ocsp_parse_clienthello,
   2034     ext_ocsp_add_serverhello,
   2035   },
   2036   {
   2037     TLSEXT_TYPE_next_proto_neg,
   2038     ext_npn_init,
   2039     ext_npn_add_clienthello,
   2040     ext_npn_parse_serverhello,
   2041     ext_npn_parse_clienthello,
   2042     ext_npn_add_serverhello,
   2043   },
   2044   {
   2045     TLSEXT_TYPE_certificate_timestamp,
   2046     NULL,
   2047     ext_sct_add_clienthello,
   2048     ext_sct_parse_serverhello,
   2049     ext_sct_parse_clienthello,
   2050     ext_sct_add_serverhello,
   2051   },
   2052   {
   2053     TLSEXT_TYPE_application_layer_protocol_negotiation,
   2054     ext_alpn_init,
   2055     ext_alpn_add_clienthello,
   2056     ext_alpn_parse_serverhello,
   2057     ext_alpn_parse_clienthello,
   2058     ext_alpn_add_serverhello,
   2059   },
   2060   {
   2061     TLSEXT_TYPE_channel_id,
   2062     ext_channel_id_init,
   2063     ext_channel_id_add_clienthello,
   2064     ext_channel_id_parse_serverhello,
   2065     ext_channel_id_parse_clienthello,
   2066     ext_channel_id_add_serverhello,
   2067   },
   2068   {
   2069     TLSEXT_TYPE_srtp,
   2070     ext_srtp_init,
   2071     ext_srtp_add_clienthello,
   2072     ext_srtp_parse_serverhello,
   2073     ext_srtp_parse_clienthello,
   2074     ext_srtp_add_serverhello,
   2075   },
   2076   {
   2077     TLSEXT_TYPE_ec_point_formats,
   2078     NULL,
   2079     ext_ec_point_add_clienthello,
   2080     ext_ec_point_parse_serverhello,
   2081     ext_ec_point_parse_clienthello,
   2082     ext_ec_point_add_serverhello,
   2083   },
   2084   {
   2085     TLSEXT_TYPE_elliptic_curves,
   2086     ext_ec_curves_init,
   2087     ext_ec_curves_add_clienthello,
   2088     ext_ec_curves_parse_serverhello,
   2089     ext_ec_curves_parse_clienthello,
   2090     ext_ec_curves_add_serverhello,
   2091   },
   2092 };
   2093 
   2094 #define kNumExtensions (sizeof(kExtensions) / sizeof(struct tls_extension))
   2095 
   2096 OPENSSL_COMPILE_ASSERT(kNumExtensions <=
   2097                            sizeof(((SSL *)NULL)->s3->tmp.extensions.sent) * 8,
   2098                        too_many_extensions_for_sent_bitset);
   2099 OPENSSL_COMPILE_ASSERT(kNumExtensions <=
   2100                            sizeof(((SSL *)NULL)->s3->tmp.extensions.received) *
   2101                                8,
   2102                        too_many_extensions_for_received_bitset);
   2103 
   2104 static const struct tls_extension *tls_extension_find(uint32_t *out_index,
   2105                                                       uint16_t value) {
   2106   unsigned i;
   2107   for (i = 0; i < kNumExtensions; i++) {
   2108     if (kExtensions[i].value == value) {
   2109       *out_index = i;
   2110       return &kExtensions[i];
   2111     }
   2112   }
   2113 
   2114   return NULL;
   2115 }
   2116 
   2117 int SSL_extension_supported(unsigned extension_value) {
   2118   uint32_t index;
   2119   return extension_value == TLSEXT_TYPE_padding ||
   2120          tls_extension_find(&index, extension_value) != NULL;
   2121 }
   2122 
   2123 int ssl_add_clienthello_tlsext(SSL *ssl, CBB *out, size_t header_len) {
   2124   /* don't add extensions for SSLv3 unless doing secure renegotiation */
   2125   if (ssl->client_version == SSL3_VERSION &&
   2126       !ssl->s3->send_connection_binding) {
   2127     return 1;
   2128   }
   2129 
   2130   CBB extensions;
   2131   if (!CBB_add_u16_length_prefixed(out, &extensions)) {
   2132     goto err;
   2133   }
   2134 
   2135   ssl->s3->tmp.extensions.sent = 0;
   2136   ssl->s3->tmp.custom_extensions.sent = 0;
   2137 
   2138   size_t i;
   2139   for (i = 0; i < kNumExtensions; i++) {
   2140     if (kExtensions[i].init != NULL) {
   2141       kExtensions[i].init(ssl);
   2142     }
   2143   }
   2144 
   2145   for (i = 0; i < kNumExtensions; i++) {
   2146     const size_t len_before = CBB_len(&extensions);
   2147     if (!kExtensions[i].add_clienthello(ssl, &extensions)) {
   2148       OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
   2149       ERR_add_error_dataf("extension: %u", (unsigned)kExtensions[i].value);
   2150       goto err;
   2151     }
   2152 
   2153     if (CBB_len(&extensions) != len_before) {
   2154       ssl->s3->tmp.extensions.sent |= (1u << i);
   2155     }
   2156   }
   2157 
   2158   if (!custom_ext_add_clienthello(ssl, &extensions)) {
   2159     goto err;
   2160   }
   2161 
   2162   if (!SSL_IS_DTLS(ssl)) {
   2163     header_len += 2 + CBB_len(&extensions);
   2164     if (header_len > 0xff && header_len < 0x200) {
   2165       /* Add padding to workaround bugs in F5 terminators. See RFC 7685.
   2166        *
   2167        * NB: because this code works out the length of all existing extensions
   2168        * it MUST always appear last. */
   2169       size_t padding_len = 0x200 - header_len;
   2170       /* Extensions take at least four bytes to encode. Always include least
   2171        * one byte of data if including the extension. WebSphere Application
   2172        * Server 7.0 is intolerant to the last extension being zero-length. */
   2173       if (padding_len >= 4 + 1) {
   2174         padding_len -= 4;
   2175       } else {
   2176         padding_len = 1;
   2177       }
   2178 
   2179       uint8_t *padding_bytes;
   2180       if (!CBB_add_u16(&extensions, TLSEXT_TYPE_padding) ||
   2181           !CBB_add_u16(&extensions, padding_len) ||
   2182           !CBB_add_space(&extensions, &padding_bytes, padding_len)) {
   2183         goto err;
   2184       }
   2185 
   2186       memset(padding_bytes, 0, padding_len);
   2187     }
   2188   }
   2189 
   2190   /* Discard empty extensions blocks. */
   2191   if (CBB_len(&extensions) == 0) {
   2192     CBB_discard_child(out);
   2193   }
   2194 
   2195   return CBB_flush(out);
   2196 
   2197 err:
   2198   OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2199   return 0;
   2200 }
   2201 
   2202 int ssl_add_serverhello_tlsext(SSL *ssl, CBB *out) {
   2203   CBB extensions;
   2204   if (!CBB_add_u16_length_prefixed(out, &extensions)) {
   2205     goto err;
   2206   }
   2207 
   2208   unsigned i;
   2209   for (i = 0; i < kNumExtensions; i++) {
   2210     if (!(ssl->s3->tmp.extensions.received & (1u << i))) {
   2211       /* Don't send extensions that were not received. */
   2212       continue;
   2213     }
   2214 
   2215     if (!kExtensions[i].add_serverhello(ssl, &extensions)) {
   2216       OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
   2217       ERR_add_error_dataf("extension: %u", (unsigned)kExtensions[i].value);
   2218       goto err;
   2219     }
   2220   }
   2221 
   2222   if (!custom_ext_add_serverhello(ssl, &extensions)) {
   2223     goto err;
   2224   }
   2225 
   2226   /* Discard empty extensions blocks. */
   2227   if (CBB_len(&extensions) == 0) {
   2228     CBB_discard_child(out);
   2229   }
   2230 
   2231   return CBB_flush(out);
   2232 
   2233 err:
   2234   OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2235   return 0;
   2236 }
   2237 
   2238 static int ssl_scan_clienthello_tlsext(SSL *ssl, CBS *cbs, int *out_alert) {
   2239   size_t i;
   2240   for (i = 0; i < kNumExtensions; i++) {
   2241     if (kExtensions[i].init != NULL) {
   2242       kExtensions[i].init(ssl);
   2243     }
   2244   }
   2245 
   2246   ssl->s3->tmp.extensions.received = 0;
   2247   ssl->s3->tmp.custom_extensions.received = 0;
   2248   /* The renegotiation extension must always be at index zero because the
   2249    * |received| and |sent| bitsets need to be tweaked when the "extension" is
   2250    * sent as an SCSV. */
   2251   assert(kExtensions[0].value == TLSEXT_TYPE_renegotiate);
   2252 
   2253   /* There may be no extensions. */
   2254   if (CBS_len(cbs) != 0) {
   2255     /* Decode the extensions block and check it is valid. */
   2256     CBS extensions;
   2257     if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
   2258         !tls1_check_duplicate_extensions(&extensions)) {
   2259       *out_alert = SSL_AD_DECODE_ERROR;
   2260       return 0;
   2261     }
   2262 
   2263     while (CBS_len(&extensions) != 0) {
   2264       uint16_t type;
   2265       CBS extension;
   2266 
   2267       /* Decode the next extension. */
   2268       if (!CBS_get_u16(&extensions, &type) ||
   2269           !CBS_get_u16_length_prefixed(&extensions, &extension)) {
   2270         *out_alert = SSL_AD_DECODE_ERROR;
   2271         return 0;
   2272       }
   2273 
   2274       /* RFC 5746 made the existence of extensions in SSL 3.0 somewhat
   2275        * ambiguous. Ignore all but the renegotiation_info extension. */
   2276       if (ssl->version == SSL3_VERSION && type != TLSEXT_TYPE_renegotiate) {
   2277         continue;
   2278       }
   2279 
   2280       unsigned ext_index;
   2281       const struct tls_extension *const ext =
   2282           tls_extension_find(&ext_index, type);
   2283 
   2284       if (ext == NULL) {
   2285         if (!custom_ext_parse_clienthello(ssl, out_alert, type, &extension)) {
   2286           OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
   2287           return 0;
   2288         }
   2289         continue;
   2290       }
   2291 
   2292       ssl->s3->tmp.extensions.received |= (1u << ext_index);
   2293       uint8_t alert = SSL_AD_DECODE_ERROR;
   2294       if (!ext->parse_clienthello(ssl, &alert, &extension)) {
   2295         *out_alert = alert;
   2296         OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
   2297         ERR_add_error_dataf("extension: %u", (unsigned)type);
   2298         return 0;
   2299       }
   2300     }
   2301   }
   2302 
   2303   for (i = 0; i < kNumExtensions; i++) {
   2304     if (!(ssl->s3->tmp.extensions.received & (1u << i))) {
   2305       /* Extension wasn't observed so call the callback with a NULL
   2306        * parameter. */
   2307       uint8_t alert = SSL_AD_DECODE_ERROR;
   2308       if (!kExtensions[i].parse_clienthello(ssl, &alert, NULL)) {
   2309         OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
   2310         ERR_add_error_dataf("extension: %u", (unsigned)kExtensions[i].value);
   2311         *out_alert = alert;
   2312         return 0;
   2313       }
   2314     }
   2315   }
   2316 
   2317   return 1;
   2318 }
   2319 
   2320 int ssl_parse_clienthello_tlsext(SSL *ssl, CBS *cbs) {
   2321   int alert = -1;
   2322   if (ssl_scan_clienthello_tlsext(ssl, cbs, &alert) <= 0) {
   2323     ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
   2324     return 0;
   2325   }
   2326 
   2327   if (ssl_check_clienthello_tlsext(ssl) <= 0) {
   2328     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_TLSEXT);
   2329     return 0;
   2330   }
   2331 
   2332   return 1;
   2333 }
   2334 
   2335 OPENSSL_COMPILE_ASSERT(kNumExtensions <= sizeof(uint32_t) * 8, too_many_bits);
   2336 
   2337 static int ssl_scan_serverhello_tlsext(SSL *ssl, CBS *cbs, int *out_alert) {
   2338   uint32_t received = 0;
   2339 
   2340   if (CBS_len(cbs) != 0) {
   2341     /* Decode the extensions block and check it is valid. */
   2342     CBS extensions;
   2343     if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
   2344         !tls1_check_duplicate_extensions(&extensions)) {
   2345       *out_alert = SSL_AD_DECODE_ERROR;
   2346       return 0;
   2347     }
   2348 
   2349 
   2350     while (CBS_len(&extensions) != 0) {
   2351       uint16_t type;
   2352       CBS extension;
   2353 
   2354       /* Decode the next extension. */
   2355       if (!CBS_get_u16(&extensions, &type) ||
   2356           !CBS_get_u16_length_prefixed(&extensions, &extension)) {
   2357         *out_alert = SSL_AD_DECODE_ERROR;
   2358         return 0;
   2359       }
   2360 
   2361       unsigned ext_index;
   2362       const struct tls_extension *const ext =
   2363           tls_extension_find(&ext_index, type);
   2364 
   2365       if (ext == NULL) {
   2366         if (!custom_ext_parse_serverhello(ssl, out_alert, type, &extension)) {
   2367           return 0;
   2368         }
   2369         continue;
   2370       }
   2371 
   2372       if (!(ssl->s3->tmp.extensions.sent & (1u << ext_index))) {
   2373         /* If the extension was never sent then it is illegal. */
   2374         OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
   2375         ERR_add_error_dataf("extension :%u", (unsigned)type);
   2376         *out_alert = SSL_AD_DECODE_ERROR;
   2377         return 0;
   2378       }
   2379 
   2380       received |= (1u << ext_index);
   2381 
   2382       uint8_t alert = SSL_AD_DECODE_ERROR;
   2383       if (!ext->parse_serverhello(ssl, &alert, &extension)) {
   2384         OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
   2385         ERR_add_error_dataf("extension: %u", (unsigned)type);
   2386         *out_alert = alert;
   2387         return 0;
   2388       }
   2389     }
   2390   }
   2391 
   2392   size_t i;
   2393   for (i = 0; i < kNumExtensions; i++) {
   2394     if (!(received & (1u << i))) {
   2395       /* Extension wasn't observed so call the callback with a NULL
   2396        * parameter. */
   2397       uint8_t alert = SSL_AD_DECODE_ERROR;
   2398       if (!kExtensions[i].parse_serverhello(ssl, &alert, NULL)) {
   2399         OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
   2400         ERR_add_error_dataf("extension: %u", (unsigned)kExtensions[i].value);
   2401         *out_alert = alert;
   2402         return 0;
   2403       }
   2404     }
   2405   }
   2406 
   2407   return 1;
   2408 }
   2409 
   2410 static int ssl_check_clienthello_tlsext(SSL *ssl) {
   2411   int ret = SSL_TLSEXT_ERR_NOACK;
   2412   int al = SSL_AD_UNRECOGNIZED_NAME;
   2413 
   2414   /* The handling of the ECPointFormats extension is done elsewhere, namely in
   2415    * ssl3_choose_cipher in s3_lib.c. */
   2416 
   2417   if (ssl->ctx != NULL && ssl->ctx->tlsext_servername_callback != 0) {
   2418     ret = ssl->ctx->tlsext_servername_callback(ssl, &al,
   2419                                              ssl->ctx->tlsext_servername_arg);
   2420   } else if (ssl->initial_ctx != NULL &&
   2421              ssl->initial_ctx->tlsext_servername_callback != 0) {
   2422     ret = ssl->initial_ctx->tlsext_servername_callback(
   2423         ssl, &al, ssl->initial_ctx->tlsext_servername_arg);
   2424   }
   2425 
   2426   switch (ret) {
   2427     case SSL_TLSEXT_ERR_ALERT_FATAL:
   2428       ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
   2429       return -1;
   2430 
   2431     case SSL_TLSEXT_ERR_ALERT_WARNING:
   2432       ssl3_send_alert(ssl, SSL3_AL_WARNING, al);
   2433       return 1;
   2434 
   2435     case SSL_TLSEXT_ERR_NOACK:
   2436       ssl->s3->tmp.should_ack_sni = 0;
   2437       return 1;
   2438 
   2439     default:
   2440       return 1;
   2441   }
   2442 }
   2443 
   2444 static int ssl_check_serverhello_tlsext(SSL *ssl) {
   2445   int ret = SSL_TLSEXT_ERR_OK;
   2446   int al = SSL_AD_UNRECOGNIZED_NAME;
   2447 
   2448   if (ssl->ctx != NULL && ssl->ctx->tlsext_servername_callback != 0) {
   2449     ret = ssl->ctx->tlsext_servername_callback(ssl, &al,
   2450                                              ssl->ctx->tlsext_servername_arg);
   2451   } else if (ssl->initial_ctx != NULL &&
   2452              ssl->initial_ctx->tlsext_servername_callback != 0) {
   2453     ret = ssl->initial_ctx->tlsext_servername_callback(
   2454         ssl, &al, ssl->initial_ctx->tlsext_servername_arg);
   2455   }
   2456 
   2457   switch (ret) {
   2458     case SSL_TLSEXT_ERR_ALERT_FATAL:
   2459       ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
   2460       return -1;
   2461 
   2462     case SSL_TLSEXT_ERR_ALERT_WARNING:
   2463       ssl3_send_alert(ssl, SSL3_AL_WARNING, al);
   2464       return 1;
   2465 
   2466     default:
   2467       return 1;
   2468   }
   2469 }
   2470 
   2471 int ssl_parse_serverhello_tlsext(SSL *ssl, CBS *cbs) {
   2472   int alert = -1;
   2473   if (ssl_scan_serverhello_tlsext(ssl, cbs, &alert) <= 0) {
   2474     ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
   2475     return 0;
   2476   }
   2477 
   2478   if (ssl_check_serverhello_tlsext(ssl) <= 0) {
   2479     OPENSSL_PUT_ERROR(SSL, SSL_R_SERVERHELLO_TLSEXT);
   2480     return 0;
   2481   }
   2482 
   2483   return 1;
   2484 }
   2485 
   2486 int tls_process_ticket(SSL *ssl, SSL_SESSION **out_session,
   2487                        int *out_send_ticket, const uint8_t *ticket,
   2488                        size_t ticket_len, const uint8_t *session_id,
   2489                        size_t session_id_len) {
   2490   int ret = 1; /* Most errors are non-fatal. */
   2491   SSL_CTX *ssl_ctx = ssl->initial_ctx;
   2492   uint8_t *plaintext = NULL;
   2493 
   2494   HMAC_CTX hmac_ctx;
   2495   HMAC_CTX_init(&hmac_ctx);
   2496   EVP_CIPHER_CTX cipher_ctx;
   2497   EVP_CIPHER_CTX_init(&cipher_ctx);
   2498 
   2499   *out_send_ticket = 0;
   2500   *out_session = NULL;
   2501 
   2502   if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
   2503     goto done;
   2504   }
   2505 
   2506   if (ticket_len == 0) {
   2507     /* The client will accept a ticket but doesn't currently have one. */
   2508     *out_send_ticket = 1;
   2509     goto done;
   2510   }
   2511 
   2512   /* Ensure there is room for the key name and the largest IV
   2513    * |tlsext_ticket_key_cb| may try to consume. The real limit may be lower, but
   2514    * the maximum IV length should be well under the minimum size for the
   2515    * session material and HMAC. */
   2516   if (ticket_len < SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH) {
   2517     goto done;
   2518   }
   2519   const uint8_t *iv = ticket + SSL_TICKET_KEY_NAME_LEN;
   2520 
   2521   if (ssl_ctx->tlsext_ticket_key_cb != NULL) {
   2522     int cb_ret = ssl_ctx->tlsext_ticket_key_cb(
   2523         ssl, (uint8_t *)ticket /* name */, (uint8_t *)iv, &cipher_ctx,
   2524         &hmac_ctx, 0 /* decrypt */);
   2525     if (cb_ret < 0) {
   2526       ret = 0;
   2527       goto done;
   2528     }
   2529     if (cb_ret == 0) {
   2530       goto done;
   2531     }
   2532     if (cb_ret == 2) {
   2533       *out_send_ticket = 1;
   2534     }
   2535   } else {
   2536     /* Check the key name matches. */
   2537     if (memcmp(ticket, ssl_ctx->tlsext_tick_key_name,
   2538                SSL_TICKET_KEY_NAME_LEN) != 0) {
   2539       goto done;
   2540     }
   2541     if (!HMAC_Init_ex(&hmac_ctx, ssl_ctx->tlsext_tick_hmac_key,
   2542                       sizeof(ssl_ctx->tlsext_tick_hmac_key), tlsext_tick_md(),
   2543                       NULL) ||
   2544         !EVP_DecryptInit_ex(&cipher_ctx, EVP_aes_128_cbc(), NULL,
   2545                             ssl_ctx->tlsext_tick_aes_key, iv)) {
   2546       ret = 0;
   2547       goto done;
   2548     }
   2549   }
   2550   size_t iv_len = EVP_CIPHER_CTX_iv_length(&cipher_ctx);
   2551 
   2552   /* Check the MAC at the end of the ticket. */
   2553   uint8_t mac[EVP_MAX_MD_SIZE];
   2554   size_t mac_len = HMAC_size(&hmac_ctx);
   2555   if (ticket_len < SSL_TICKET_KEY_NAME_LEN + iv_len + 1 + mac_len) {
   2556     /* The ticket must be large enough for key name, IV, data, and MAC. */
   2557     goto done;
   2558   }
   2559   HMAC_Update(&hmac_ctx, ticket, ticket_len - mac_len);
   2560   HMAC_Final(&hmac_ctx, mac, NULL);
   2561   if (CRYPTO_memcmp(mac, ticket + (ticket_len - mac_len), mac_len) != 0) {
   2562     goto done;
   2563   }
   2564 
   2565   /* Decrypt the session data. */
   2566   const uint8_t *ciphertext = ticket + SSL_TICKET_KEY_NAME_LEN + iv_len;
   2567   size_t ciphertext_len = ticket_len - SSL_TICKET_KEY_NAME_LEN - iv_len -
   2568                           mac_len;
   2569   plaintext = OPENSSL_malloc(ciphertext_len);
   2570   if (plaintext == NULL) {
   2571     ret = 0;
   2572     goto done;
   2573   }
   2574   if (ciphertext_len >= INT_MAX) {
   2575     goto done;
   2576   }
   2577   int len1, len2;
   2578   if (!EVP_DecryptUpdate(&cipher_ctx, plaintext, &len1, ciphertext,
   2579                          (int)ciphertext_len) ||
   2580       !EVP_DecryptFinal_ex(&cipher_ctx, plaintext + len1, &len2)) {
   2581     ERR_clear_error(); /* Don't leave an error on the queue. */
   2582     goto done;
   2583   }
   2584 
   2585   /* Decode the session. */
   2586   SSL_SESSION *session = SSL_SESSION_from_bytes(plaintext, len1 + len2);
   2587   if (session == NULL) {
   2588     ERR_clear_error(); /* Don't leave an error on the queue. */
   2589     goto done;
   2590   }
   2591 
   2592   /* Copy the client's session ID into the new session, to denote the ticket has
   2593    * been accepted. */
   2594   memcpy(session->session_id, session_id, session_id_len);
   2595   session->session_id_length = session_id_len;
   2596 
   2597   *out_session = session;
   2598 
   2599 done:
   2600   OPENSSL_free(plaintext);
   2601   HMAC_CTX_cleanup(&hmac_ctx);
   2602   EVP_CIPHER_CTX_cleanup(&cipher_ctx);
   2603   return ret;
   2604 }
   2605 
   2606 /* Tables to translate from NIDs to TLS v1.2 ids */
   2607 typedef struct {
   2608   int nid;
   2609   int id;
   2610 } tls12_lookup;
   2611 
   2612 static const tls12_lookup tls12_md[] = {{NID_md5, TLSEXT_hash_md5},
   2613                                         {NID_sha1, TLSEXT_hash_sha1},
   2614                                         {NID_sha224, TLSEXT_hash_sha224},
   2615                                         {NID_sha256, TLSEXT_hash_sha256},
   2616                                         {NID_sha384, TLSEXT_hash_sha384},
   2617                                         {NID_sha512, TLSEXT_hash_sha512}};
   2618 
   2619 static const tls12_lookup tls12_sig[] = {{EVP_PKEY_RSA, TLSEXT_signature_rsa},
   2620                                          {EVP_PKEY_EC, TLSEXT_signature_ecdsa}};
   2621 
   2622 static int tls12_find_id(int nid, const tls12_lookup *table, size_t tlen) {
   2623   size_t i;
   2624   for (i = 0; i < tlen; i++) {
   2625     if (table[i].nid == nid) {
   2626       return table[i].id;
   2627     }
   2628   }
   2629 
   2630   return -1;
   2631 }
   2632 
   2633 int tls12_get_sigid(int pkey_type) {
   2634   return tls12_find_id(pkey_type, tls12_sig,
   2635                        sizeof(tls12_sig) / sizeof(tls12_lookup));
   2636 }
   2637 
   2638 int tls12_add_sigandhash(SSL *ssl, CBB *out, const EVP_MD *md) {
   2639   int md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
   2640                             sizeof(tls12_md) / sizeof(tls12_lookup));
   2641   int sig_id = tls12_get_sigid(ssl_private_key_type(ssl));
   2642 
   2643   return md_id != -1 &&
   2644          sig_id != -1 &&
   2645          CBB_add_u8(out, (uint8_t)md_id) &&
   2646          CBB_add_u8(out, (uint8_t)sig_id);
   2647 }
   2648 
   2649 const EVP_MD *tls12_get_hash(uint8_t hash_alg) {
   2650   switch (hash_alg) {
   2651     case TLSEXT_hash_md5:
   2652       return EVP_md5();
   2653 
   2654     case TLSEXT_hash_sha1:
   2655       return EVP_sha1();
   2656 
   2657     case TLSEXT_hash_sha224:
   2658       return EVP_sha224();
   2659 
   2660     case TLSEXT_hash_sha256:
   2661       return EVP_sha256();
   2662 
   2663     case TLSEXT_hash_sha384:
   2664       return EVP_sha384();
   2665 
   2666     case TLSEXT_hash_sha512:
   2667       return EVP_sha512();
   2668 
   2669     default:
   2670       return NULL;
   2671   }
   2672 }
   2673 
   2674 /* tls12_get_pkey_type returns the EVP_PKEY type corresponding to TLS signature
   2675  * algorithm |sig_alg|. It returns -1 if the type is unknown. */
   2676 static int tls12_get_pkey_type(uint8_t sig_alg) {
   2677   switch (sig_alg) {
   2678     case TLSEXT_signature_rsa:
   2679       return EVP_PKEY_RSA;
   2680 
   2681     case TLSEXT_signature_ecdsa:
   2682       return EVP_PKEY_EC;
   2683 
   2684     default:
   2685       return -1;
   2686   }
   2687 }
   2688 
   2689 OPENSSL_COMPILE_ASSERT(sizeof(TLS_SIGALGS) == 2,
   2690     sizeof_tls_sigalgs_is_not_two);
   2691 
   2692 int tls1_parse_peer_sigalgs(SSL *ssl, const CBS *in_sigalgs) {
   2693   /* Extension ignored for inappropriate versions */
   2694   if (!SSL_USE_SIGALGS(ssl)) {
   2695     return 1;
   2696   }
   2697 
   2698   CERT *const cert = ssl->cert;
   2699   OPENSSL_free(cert->peer_sigalgs);
   2700   cert->peer_sigalgs = NULL;
   2701   cert->peer_sigalgslen = 0;
   2702 
   2703   size_t num_sigalgs = CBS_len(in_sigalgs);
   2704 
   2705   if (num_sigalgs % 2 != 0) {
   2706     return 0;
   2707   }
   2708   num_sigalgs /= 2;
   2709 
   2710   /* supported_signature_algorithms in the certificate request is
   2711    * allowed to be empty. */
   2712   if (num_sigalgs == 0) {
   2713     return 1;
   2714   }
   2715 
   2716   /* This multiplication doesn't overflow because sizeof(TLS_SIGALGS) is two
   2717    * (statically asserted above) and we just divided |num_sigalgs| by two. */
   2718   cert->peer_sigalgs = OPENSSL_malloc(num_sigalgs * sizeof(TLS_SIGALGS));
   2719   if (cert->peer_sigalgs == NULL) {
   2720     return 0;
   2721   }
   2722   cert->peer_sigalgslen = num_sigalgs;
   2723 
   2724   CBS sigalgs;
   2725   CBS_init(&sigalgs, CBS_data(in_sigalgs), CBS_len(in_sigalgs));
   2726 
   2727   size_t i;
   2728   for (i = 0; i < num_sigalgs; i++) {
   2729     TLS_SIGALGS *const sigalg = &cert->peer_sigalgs[i];
   2730     if (!CBS_get_u8(&sigalgs, &sigalg->rhash) ||
   2731         !CBS_get_u8(&sigalgs, &sigalg->rsign)) {
   2732       return 0;
   2733     }
   2734   }
   2735 
   2736   return 1;
   2737 }
   2738 
   2739 const EVP_MD *tls1_choose_signing_digest(SSL *ssl) {
   2740   CERT *cert = ssl->cert;
   2741   int type = ssl_private_key_type(ssl);
   2742   size_t i, j;
   2743 
   2744   static const int kDefaultDigestList[] = {NID_sha256, NID_sha384, NID_sha512,
   2745                                            NID_sha224, NID_sha1};
   2746 
   2747   const int *digest_nids = kDefaultDigestList;
   2748   size_t num_digest_nids =
   2749       sizeof(kDefaultDigestList) / sizeof(kDefaultDigestList[0]);
   2750   if (cert->digest_nids != NULL) {
   2751     digest_nids = cert->digest_nids;
   2752     num_digest_nids = cert->num_digest_nids;
   2753   }
   2754 
   2755   for (i = 0; i < num_digest_nids; i++) {
   2756     const int digest_nid = digest_nids[i];
   2757     for (j = 0; j < cert->peer_sigalgslen; j++) {
   2758       const EVP_MD *md = tls12_get_hash(cert->peer_sigalgs[j].rhash);
   2759       if (md == NULL ||
   2760           digest_nid != EVP_MD_type(md) ||
   2761           tls12_get_pkey_type(cert->peer_sigalgs[j].rsign) != type) {
   2762         continue;
   2763       }
   2764 
   2765       return md;
   2766     }
   2767   }
   2768 
   2769   /* If no suitable digest may be found, default to SHA-1. */
   2770   return EVP_sha1();
   2771 }
   2772 
   2773 int tls1_channel_id_hash(SSL *ssl, uint8_t *out, size_t *out_len) {
   2774   int ret = 0;
   2775   EVP_MD_CTX ctx;
   2776 
   2777   EVP_MD_CTX_init(&ctx);
   2778   if (!EVP_DigestInit_ex(&ctx, EVP_sha256(), NULL)) {
   2779     goto err;
   2780   }
   2781 
   2782   static const char kClientIDMagic[] = "TLS Channel ID signature";
   2783   EVP_DigestUpdate(&ctx, kClientIDMagic, sizeof(kClientIDMagic));
   2784 
   2785   if (ssl->hit) {
   2786     static const char kResumptionMagic[] = "Resumption";
   2787     EVP_DigestUpdate(&ctx, kResumptionMagic, sizeof(kResumptionMagic));
   2788     if (ssl->session->original_handshake_hash_len == 0) {
   2789       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2790       goto err;
   2791     }
   2792     EVP_DigestUpdate(&ctx, ssl->session->original_handshake_hash,
   2793                      ssl->session->original_handshake_hash_len);
   2794   }
   2795 
   2796   uint8_t handshake_hash[EVP_MAX_MD_SIZE];
   2797   int handshake_hash_len = tls1_handshake_digest(ssl, handshake_hash,
   2798                                                  sizeof(handshake_hash));
   2799   if (handshake_hash_len < 0) {
   2800     goto err;
   2801   }
   2802   EVP_DigestUpdate(&ctx, handshake_hash, (size_t)handshake_hash_len);
   2803   unsigned len_u;
   2804   EVP_DigestFinal_ex(&ctx, out, &len_u);
   2805   *out_len = len_u;
   2806 
   2807   ret = 1;
   2808 
   2809 err:
   2810   EVP_MD_CTX_cleanup(&ctx);
   2811   return ret;
   2812 }
   2813 
   2814 /* tls1_record_handshake_hashes_for_channel_id records the current handshake
   2815  * hashes in |ssl->session| so that Channel ID resumptions can sign that
   2816  * data. */
   2817 int tls1_record_handshake_hashes_for_channel_id(SSL *ssl) {
   2818   int digest_len;
   2819   /* This function should never be called for a resumed session because the
   2820    * handshake hashes that we wish to record are for the original, full
   2821    * handshake. */
   2822   if (ssl->hit) {
   2823     return -1;
   2824   }
   2825 
   2826   digest_len =
   2827       tls1_handshake_digest(ssl, ssl->session->original_handshake_hash,
   2828                             sizeof(ssl->session->original_handshake_hash));
   2829   if (digest_len < 0) {
   2830     return -1;
   2831   }
   2832 
   2833   ssl->session->original_handshake_hash_len = digest_len;
   2834 
   2835   return 1;
   2836 }
   2837