LCOV - code coverage report
Current view: top level - third_party/openssl/ssl - t1_lib.c (source / functions) Hit Total Coverage
Test: tmp.zDYK9MVh93 Lines: 643 1525 42.2 %
Date: 2015-10-10 Functions: 39 56 69.6 %

          Line data    Source code
       1             : /* ssl/t1_lib.c */
       2             : /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
       3             :  * All rights reserved.
       4             :  *
       5             :  * This package is an SSL implementation written
       6             :  * by Eric Young (eay@cryptsoft.com).
       7             :  * The implementation was written so as to conform with Netscapes SSL.
       8             :  *
       9             :  * This library is free for commercial and non-commercial use as long as
      10             :  * the following conditions are aheared to.  The following conditions
      11             :  * apply to all code found in this distribution, be it the RC4, RSA,
      12             :  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
      13             :  * included with this distribution is covered by the same copyright terms
      14             :  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
      15             :  *
      16             :  * Copyright remains Eric Young's, and as such any Copyright notices in
      17             :  * the code are not to be removed.
      18             :  * If this package is used in a product, Eric Young should be given attribution
      19             :  * as the author of the parts of the library used.
      20             :  * This can be in the form of a textual message at program startup or
      21             :  * in documentation (online or textual) provided with the package.
      22             :  *
      23             :  * Redistribution and use in source and binary forms, with or without
      24             :  * modification, are permitted provided that the following conditions
      25             :  * are met:
      26             :  * 1. Redistributions of source code must retain the copyright
      27             :  *    notice, this list of conditions and the following disclaimer.
      28             :  * 2. Redistributions in binary form must reproduce the above copyright
      29             :  *    notice, this list of conditions and the following disclaimer in the
      30             :  *    documentation and/or other materials provided with the distribution.
      31             :  * 3. All advertising materials mentioning features or use of this software
      32             :  *    must display the following acknowledgement:
      33             :  *    "This product includes cryptographic software written by
      34             :  *     Eric Young (eay@cryptsoft.com)"
      35             :  *    The word 'cryptographic' can be left out if the rouines from the library
      36             :  *    being used are not cryptographic related :-).
      37             :  * 4. If you include any Windows specific code (or a derivative thereof) from
      38             :  *    the apps directory (application code) you must include an acknowledgement:
      39             :  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
      40             :  *
      41             :  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
      42             :  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      43             :  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
      44             :  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
      45             :  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      46             :  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
      47             :  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      48             :  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
      49             :  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
      50             :  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
      51             :  * SUCH DAMAGE.
      52             :  *
      53             :  * The licence and distribution terms for any publically available version or
      54             :  * derivative of this code cannot be changed.  i.e. this code cannot simply be
      55             :  * copied and put under another distribution licence
      56             :  * [including the GNU Public Licence.]
      57             :  */
      58             : /* ====================================================================
      59             :  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
      60             :  *
      61             :  * Redistribution and use in source and binary forms, with or without
      62             :  * modification, are permitted provided that the following conditions
      63             :  * are met:
      64             :  *
      65             :  * 1. Redistributions of source code must retain the above copyright
      66             :  *    notice, this list of conditions and the following disclaimer.
      67             :  *
      68             :  * 2. Redistributions in binary form must reproduce the above copyright
      69             :  *    notice, this list of conditions and the following disclaimer in
      70             :  *    the documentation and/or other materials provided with the
      71             :  *    distribution.
      72             :  *
      73             :  * 3. All advertising materials mentioning features or use of this
      74             :  *    software must display the following acknowledgment:
      75             :  *    "This product includes software developed by the OpenSSL Project
      76             :  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
      77             :  *
      78             :  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
      79             :  *    endorse or promote products derived from this software without
      80             :  *    prior written permission. For written permission, please contact
      81             :  *    openssl-core@openssl.org.
      82             :  *
      83             :  * 5. Products derived from this software may not be called "OpenSSL"
      84             :  *    nor may "OpenSSL" appear in their names without prior written
      85             :  *    permission of the OpenSSL Project.
      86             :  *
      87             :  * 6. Redistributions of any form whatsoever must retain the following
      88             :  *    acknowledgment:
      89             :  *    "This product includes software developed by the OpenSSL Project
      90             :  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
      91             :  *
      92             :  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
      93             :  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      94             :  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
      95             :  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
      96             :  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      97             :  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
      98             :  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      99             :  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     100             :  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     101             :  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     102             :  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     103             :  * OF THE POSSIBILITY OF SUCH DAMAGE.
     104             :  * ====================================================================
     105             :  *
     106             :  * This product includes cryptographic software written by Eric Young
     107             :  * (eay@cryptsoft.com).  This product includes software written by Tim
     108             :  * Hudson (tjh@cryptsoft.com).
     109             :  *
     110             :  */
     111             : 
     112             : #include <stdio.h>
     113             : #include <openssl/objects.h>
     114             : #include <openssl/evp.h>
     115             : #include <openssl/hmac.h>
     116             : #ifndef OPENSSL_NO_EC
     117             : #ifdef OPENSSL_NO_EC2M
     118             : # include <openssl/ec.h>
     119             : #endif
     120             : #endif
     121             : #include <openssl/ocsp.h>
     122             : #include <openssl/rand.h>
     123             : #include "ssl_locl.h"
     124             : 
     125             : const char tls1_version_str[] = "TLSv1" OPENSSL_VERSION_PTEXT;
     126             : 
     127             : #ifndef OPENSSL_NO_TLSEXT
     128             : static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
     129             :                               const unsigned char *sess_id, int sesslen,
     130             :                               SSL_SESSION **psess);
     131             : static int ssl_check_clienthello_tlsext_early(SSL *s);
     132             : int ssl_check_serverhello_tlsext(SSL *s);
     133             : #endif
     134             : 
     135             : SSL3_ENC_METHOD TLSv1_enc_data = {
     136             :     tls1_enc,
     137             :     tls1_mac,
     138             :     tls1_setup_key_block,
     139             :     tls1_generate_master_secret,
     140             :     tls1_change_cipher_state,
     141             :     tls1_final_finish_mac,
     142             :     TLS1_FINISH_MAC_LENGTH,
     143             :     tls1_cert_verify_mac,
     144             :     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     145             :     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     146             :     tls1_alert_code,
     147             :     tls1_export_keying_material,
     148             :     0,
     149             :     SSL3_HM_HEADER_LENGTH,
     150             :     ssl3_set_handshake_header,
     151             :     ssl3_handshake_write
     152             : };
     153             : 
     154             : SSL3_ENC_METHOD TLSv1_1_enc_data = {
     155             :     tls1_enc,
     156             :     tls1_mac,
     157             :     tls1_setup_key_block,
     158             :     tls1_generate_master_secret,
     159             :     tls1_change_cipher_state,
     160             :     tls1_final_finish_mac,
     161             :     TLS1_FINISH_MAC_LENGTH,
     162             :     tls1_cert_verify_mac,
     163             :     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     164             :     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     165             :     tls1_alert_code,
     166             :     tls1_export_keying_material,
     167             :     SSL_ENC_FLAG_EXPLICIT_IV,
     168             :     SSL3_HM_HEADER_LENGTH,
     169             :     ssl3_set_handshake_header,
     170             :     ssl3_handshake_write
     171             : };
     172             : 
     173             : SSL3_ENC_METHOD TLSv1_2_enc_data = {
     174             :     tls1_enc,
     175             :     tls1_mac,
     176             :     tls1_setup_key_block,
     177             :     tls1_generate_master_secret,
     178             :     tls1_change_cipher_state,
     179             :     tls1_final_finish_mac,
     180             :     TLS1_FINISH_MAC_LENGTH,
     181             :     tls1_cert_verify_mac,
     182             :     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     183             :     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     184             :     tls1_alert_code,
     185             :     tls1_export_keying_material,
     186             :     SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
     187             :         | SSL_ENC_FLAG_TLS1_2_CIPHERS,
     188             :     SSL3_HM_HEADER_LENGTH,
     189             :     ssl3_set_handshake_header,
     190             :     ssl3_handshake_write
     191             : };
     192             : 
     193         872 : long tls1_default_timeout(void)
     194             : {
     195             :     /*
     196             :      * 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for
     197             :      * http, the cache would over fill
     198             :      */
     199         872 :     return (60 * 60 * 2);
     200             : }
     201             : 
     202         750 : int tls1_new(SSL *s)
     203             : {
     204         750 :     if (!ssl3_new(s))
     205             :         return (0);
     206         750 :     s->method->ssl_clear(s);
     207         749 :     return (1);
     208             : }
     209             : 
     210         750 : void tls1_free(SSL *s)
     211             : {
     212             : #ifndef OPENSSL_NO_TLSEXT
     213         750 :     if (s->tlsext_session_ticket) {
     214           0 :         OPENSSL_free(s->tlsext_session_ticket);
     215             :     }
     216             : #endif                          /* OPENSSL_NO_TLSEXT */
     217         750 :     ssl3_free(s);
     218         750 : }
     219             : 
     220        2992 : void tls1_clear(SSL *s)
     221             : {
     222        2992 :     ssl3_clear(s);
     223        2995 :     s->version = s->method->version;
     224        2995 : }
     225             : 
     226             : #ifndef OPENSSL_NO_EC
     227             : 
     228             : static int nid_list[] = {
     229             :     NID_sect163k1,              /* sect163k1 (1) */
     230             :     NID_sect163r1,              /* sect163r1 (2) */
     231             :     NID_sect163r2,              /* sect163r2 (3) */
     232             :     NID_sect193r1,              /* sect193r1 (4) */
     233             :     NID_sect193r2,              /* sect193r2 (5) */
     234             :     NID_sect233k1,              /* sect233k1 (6) */
     235             :     NID_sect233r1,              /* sect233r1 (7) */
     236             :     NID_sect239k1,              /* sect239k1 (8) */
     237             :     NID_sect283k1,              /* sect283k1 (9) */
     238             :     NID_sect283r1,              /* sect283r1 (10) */
     239             :     NID_sect409k1,              /* sect409k1 (11) */
     240             :     NID_sect409r1,              /* sect409r1 (12) */
     241             :     NID_sect571k1,              /* sect571k1 (13) */
     242             :     NID_sect571r1,              /* sect571r1 (14) */
     243             :     NID_secp160k1,              /* secp160k1 (15) */
     244             :     NID_secp160r1,              /* secp160r1 (16) */
     245             :     NID_secp160r2,              /* secp160r2 (17) */
     246             :     NID_secp192k1,              /* secp192k1 (18) */
     247             :     NID_X9_62_prime192v1,       /* secp192r1 (19) */
     248             :     NID_secp224k1,              /* secp224k1 (20) */
     249             :     NID_secp224r1,              /* secp224r1 (21) */
     250             :     NID_secp256k1,              /* secp256k1 (22) */
     251             :     NID_X9_62_prime256v1,       /* secp256r1 (23) */
     252             :     NID_secp384r1,              /* secp384r1 (24) */
     253             :     NID_secp521r1,              /* secp521r1 (25) */
     254             :     NID_brainpoolP256r1,        /* brainpoolP256r1 (26) */
     255             :     NID_brainpoolP384r1,        /* brainpoolP384r1 (27) */
     256             :     NID_brainpoolP512r1         /* brainpool512r1 (28) */
     257             : };
     258             : 
     259             : static const unsigned char ecformats_default[] = {
     260             :     TLSEXT_ECPOINTFORMAT_uncompressed,
     261             :     TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
     262             :     TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
     263             : };
     264             : 
     265             : /* The client's default curves / the server's 'auto' curves. */
     266             : static const unsigned char eccurves_auto[] = {
     267             :     /* Prefer P-256 which has the fastest and most secure implementations. */
     268             :     0, 23,                      /* secp256r1 (23) */
     269             :     /* Other >= 256-bit prime curves. */
     270             :     0, 25,                      /* secp521r1 (25) */
     271             :     0, 28,                      /* brainpool512r1 (28) */
     272             :     0, 27,                      /* brainpoolP384r1 (27) */
     273             :     0, 24,                      /* secp384r1 (24) */
     274             :     0, 26,                      /* brainpoolP256r1 (26) */
     275             :     0, 22,                      /* secp256k1 (22) */
     276             : # ifndef OPENSSL_NO_EC2M
     277             :     /* >= 256-bit binary curves. */
     278             :     0, 14,                      /* sect571r1 (14) */
     279             :     0, 13,                      /* sect571k1 (13) */
     280             :     0, 11,                      /* sect409k1 (11) */
     281             :     0, 12,                      /* sect409r1 (12) */
     282             :     0, 9,                       /* sect283k1 (9) */
     283             :     0, 10,                      /* sect283r1 (10) */
     284             : # endif
     285             : };
     286             : 
     287             : static const unsigned char eccurves_all[] = {
     288             :     /* Prefer P-256 which has the fastest and most secure implementations. */
     289             :     0, 23,                      /* secp256r1 (23) */
     290             :     /* Other >= 256-bit prime curves. */
     291             :     0, 25,                      /* secp521r1 (25) */
     292             :     0, 28,                      /* brainpool512r1 (28) */
     293             :     0, 27,                      /* brainpoolP384r1 (27) */
     294             :     0, 24,                      /* secp384r1 (24) */
     295             :     0, 26,                      /* brainpoolP256r1 (26) */
     296             :     0, 22,                      /* secp256k1 (22) */
     297             : # ifndef OPENSSL_NO_EC2M
     298             :     /* >= 256-bit binary curves. */
     299             :     0, 14,                      /* sect571r1 (14) */
     300             :     0, 13,                      /* sect571k1 (13) */
     301             :     0, 11,                      /* sect409k1 (11) */
     302             :     0, 12,                      /* sect409r1 (12) */
     303             :     0, 9,                       /* sect283k1 (9) */
     304             :     0, 10,                      /* sect283r1 (10) */
     305             : # endif
     306             :     /*
     307             :      * Remaining curves disabled by default but still permitted if set
     308             :      * via an explicit callback or parameters.
     309             :      */
     310             :     0, 20,                      /* secp224k1 (20) */
     311             :     0, 21,                      /* secp224r1 (21) */
     312             :     0, 18,                      /* secp192k1 (18) */
     313             :     0, 19,                      /* secp192r1 (19) */
     314             :     0, 15,                      /* secp160k1 (15) */
     315             :     0, 16,                      /* secp160r1 (16) */
     316             :     0, 17,                      /* secp160r2 (17) */
     317             : # ifndef OPENSSL_NO_EC2M
     318             :     0, 8,                       /* sect239k1 (8) */
     319             :     0, 6,                       /* sect233k1 (6) */
     320             :     0, 7,                       /* sect233r1 (7) */
     321             :     0, 4,                       /* sect193r1 (4) */
     322             :     0, 5,                       /* sect193r2 (5) */
     323             :     0, 1,                       /* sect163k1 (1) */
     324             :     0, 2,                       /* sect163r1 (2) */
     325             :     0, 3,                       /* sect163r2 (3) */
     326             : # endif
     327             : };
     328             : 
     329             : static const unsigned char suiteb_curves[] = {
     330             :     0, TLSEXT_curve_P_256,
     331             :     0, TLSEXT_curve_P_384
     332             : };
     333             : 
     334             : # ifdef OPENSSL_FIPS
     335             : /* Brainpool not allowed in FIPS mode */
     336             : static const unsigned char fips_curves_default[] = {
     337             : #  ifndef OPENSSL_NO_EC2M
     338             :     0, 14,                      /* sect571r1 (14) */
     339             :     0, 13,                      /* sect571k1 (13) */
     340             : #  endif
     341             :     0, 25,                      /* secp521r1 (25) */
     342             : #  ifndef OPENSSL_NO_EC2M
     343             :     0, 11,                      /* sect409k1 (11) */
     344             :     0, 12,                      /* sect409r1 (12) */
     345             : #  endif
     346             :     0, 24,                      /* secp384r1 (24) */
     347             : #  ifndef OPENSSL_NO_EC2M
     348             :     0, 9,                       /* sect283k1 (9) */
     349             :     0, 10,                      /* sect283r1 (10) */
     350             : #  endif
     351             :     0, 22,                      /* secp256k1 (22) */
     352             :     0, 23,                      /* secp256r1 (23) */
     353             : #  ifndef OPENSSL_NO_EC2M
     354             :     0, 8,                       /* sect239k1 (8) */
     355             :     0, 6,                       /* sect233k1 (6) */
     356             :     0, 7,                       /* sect233r1 (7) */
     357             : #  endif
     358             :     0, 20,                      /* secp224k1 (20) */
     359             :     0, 21,                      /* secp224r1 (21) */
     360             : #  ifndef OPENSSL_NO_EC2M
     361             :     0, 4,                       /* sect193r1 (4) */
     362             :     0, 5,                       /* sect193r2 (5) */
     363             : #  endif
     364             :     0, 18,                      /* secp192k1 (18) */
     365             :     0, 19,                      /* secp192r1 (19) */
     366             : #  ifndef OPENSSL_NO_EC2M
     367             :     0, 1,                       /* sect163k1 (1) */
     368             :     0, 2,                       /* sect163r1 (2) */
     369             :     0, 3,                       /* sect163r2 (3) */
     370             : #  endif
     371             :     0, 15,                      /* secp160k1 (15) */
     372             :     0, 16,                      /* secp160r1 (16) */
     373             :     0, 17,                      /* secp160r2 (17) */
     374             : };
     375             : # endif
     376             : 
     377         370 : int tls1_ec_curve_id2nid(int curve_id)
     378             : {
     379             :     /* ECC curves from RFC 4492 and RFC 7027 */
     380         370 :     if ((curve_id < 1) || ((unsigned int)curve_id >
     381             :                            sizeof(nid_list) / sizeof(nid_list[0])))
     382             :         return 0;
     383         370 :     return nid_list[curve_id - 1];
     384             : }
     385             : 
     386         746 : int tls1_ec_nid2curve_id(int nid)
     387             : {
     388             :     /* ECC curves from RFC 4492 and RFC 7027 */
     389         746 :     switch (nid) {
     390             :     case NID_sect163k1:        /* sect163k1 (1) */
     391             :         return 1;
     392             :     case NID_sect163r1:        /* sect163r1 (2) */
     393           0 :         return 2;
     394             :     case NID_sect163r2:        /* sect163r2 (3) */
     395           0 :         return 3;
     396             :     case NID_sect193r1:        /* sect193r1 (4) */
     397           0 :         return 4;
     398             :     case NID_sect193r2:        /* sect193r2 (5) */
     399           0 :         return 5;
     400             :     case NID_sect233k1:        /* sect233k1 (6) */
     401           0 :         return 6;
     402             :     case NID_sect233r1:        /* sect233r1 (7) */
     403           0 :         return 7;
     404             :     case NID_sect239k1:        /* sect239k1 (8) */
     405           0 :         return 8;
     406             :     case NID_sect283k1:        /* sect283k1 (9) */
     407           0 :         return 9;
     408             :     case NID_sect283r1:        /* sect283r1 (10) */
     409           0 :         return 10;
     410             :     case NID_sect409k1:        /* sect409k1 (11) */
     411           0 :         return 11;
     412             :     case NID_sect409r1:        /* sect409r1 (12) */
     413           0 :         return 12;
     414             :     case NID_sect571k1:        /* sect571k1 (13) */
     415           0 :         return 13;
     416             :     case NID_sect571r1:        /* sect571r1 (14) */
     417           0 :         return 14;
     418             :     case NID_secp160k1:        /* secp160k1 (15) */
     419           0 :         return 15;
     420             :     case NID_secp160r1:        /* secp160r1 (16) */
     421           0 :         return 16;
     422             :     case NID_secp160r2:        /* secp160r2 (17) */
     423           0 :         return 17;
     424             :     case NID_secp192k1:        /* secp192k1 (18) */
     425           0 :         return 18;
     426             :     case NID_X9_62_prime192v1: /* secp192r1 (19) */
     427           0 :         return 19;
     428             :     case NID_secp224k1:        /* secp224k1 (20) */
     429           0 :         return 20;
     430             :     case NID_secp224r1:        /* secp224r1 (21) */
     431           0 :         return 21;
     432             :     case NID_secp256k1:        /* secp256k1 (22) */
     433           0 :         return 22;
     434             :     case NID_X9_62_prime256v1: /* secp256r1 (23) */
     435         746 :         return 23;
     436             :     case NID_secp384r1:        /* secp384r1 (24) */
     437           0 :         return 24;
     438             :     case NID_secp521r1:        /* secp521r1 (25) */
     439           0 :         return 25;
     440             :     case NID_brainpoolP256r1:  /* brainpoolP256r1 (26) */
     441           0 :         return 26;
     442             :     case NID_brainpoolP384r1:  /* brainpoolP384r1 (27) */
     443           0 :         return 27;
     444             :     case NID_brainpoolP512r1:  /* brainpool512r1 (28) */
     445           0 :         return 28;
     446             :     default:
     447           0 :         return 0;
     448             :     }
     449             : }
     450             : 
     451             : /*
     452             :  * Get curves list, if "sess" is set return client curves otherwise
     453             :  * preferred list.
     454             :  * Sets |num_curves| to the number of curves in the list, i.e.,
     455             :  * the length of |pcurves| is 2 * num_curves.
     456             :  * Returns 1 on success and 0 if the client curves list has invalid format.
     457             :  * The latter indicates an internal error: we should not be accepting such
     458             :  * lists in the first place.
     459             :  * TODO(emilia): we should really be storing the curves list in explicitly
     460             :  * parsed form instead. (However, this would affect binary compatibility
     461             :  * so cannot happen in the 1.0.x series.)
     462             :  */
     463        1489 : static int tls1_get_curvelist(SSL *s, int sess,
     464             :                               const unsigned char **pcurves,
     465             :                               size_t *num_curves)
     466             : {
     467             :     size_t pcurveslen = 0;
     468        1489 :     if (sess) {
     469         373 :         *pcurves = s->session->tlsext_ellipticcurvelist;
     470         373 :         pcurveslen = s->session->tlsext_ellipticcurvelist_length;
     471             :     } else {
     472             :         /* For Suite B mode only include P-256, P-384 */
     473        1116 :         switch (tls1_suiteb(s)) {
     474             :         case SSL_CERT_FLAG_SUITEB_128_LOS:
     475           0 :             *pcurves = suiteb_curves;
     476             :             pcurveslen = sizeof(suiteb_curves);
     477           0 :             break;
     478             : 
     479             :         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
     480           0 :             *pcurves = suiteb_curves;
     481             :             pcurveslen = 2;
     482           0 :             break;
     483             : 
     484             :         case SSL_CERT_FLAG_SUITEB_192_LOS:
     485           0 :             *pcurves = suiteb_curves + 2;
     486             :             pcurveslen = 2;
     487           0 :             break;
     488             :         default:
     489        1116 :             *pcurves = s->tlsext_ellipticcurvelist;
     490        1116 :             pcurveslen = s->tlsext_ellipticcurvelist_length;
     491             :         }
     492        1116 :         if (!*pcurves) {
     493             : # ifdef OPENSSL_FIPS
     494             :             if (FIPS_mode()) {
     495             :                 *pcurves = fips_curves_default;
     496             :                 pcurveslen = sizeof(fips_curves_default);
     497             :             } else
     498             : # endif
     499             :             {
     500        1116 :                 if (!s->server || (s->cert && s->cert->ecdh_tmp_auto)) {
     501         743 :                     *pcurves = eccurves_auto;
     502         743 :                     pcurveslen = sizeof(eccurves_auto);
     503             :                 } else {
     504         373 :                     *pcurves = eccurves_all;
     505             :                     pcurveslen = sizeof(eccurves_all);
     506             :                 }
     507             :             }
     508             :         }
     509             :     }
     510             :     /* We do not allow odd length arrays to enter the system. */
     511        1489 :     if (pcurveslen & 1) {
     512           0 :         SSLerr(SSL_F_TLS1_GET_CURVELIST, ERR_R_INTERNAL_ERROR);
     513           0 :         *num_curves = 0;
     514           0 :         return 0;
     515             :     } else {
     516        1489 :         *num_curves = pcurveslen / 2;
     517        1489 :         return 1;
     518             :     }
     519             : }
     520             : 
     521             : /* Check a curve is one of our preferences */
     522         370 : int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
     523             : {
     524             :     const unsigned char *curves;
     525             :     size_t num_curves, i;
     526         370 :     unsigned int suiteb_flags = tls1_suiteb(s);
     527         370 :     if (len != 3 || p[0] != NAMED_CURVE_TYPE)
     528             :         return 0;
     529             :     /* Check curve matches Suite B preferences */
     530         370 :     if (suiteb_flags) {
     531           0 :         unsigned long cid = s->s3->tmp.new_cipher->id;
     532           0 :         if (p[1])
     533             :             return 0;
     534           0 :         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
     535           0 :             if (p[2] != TLSEXT_curve_P_256)
     536             :                 return 0;
     537           0 :         } else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
     538           0 :             if (p[2] != TLSEXT_curve_P_384)
     539             :                 return 0;
     540             :         } else                  /* Should never happen */
     541             :             return 0;
     542             :     }
     543         370 :     if (!tls1_get_curvelist(s, 0, &curves, &num_curves))
     544             :         return 0;
     545           0 :     for (i = 0; i < num_curves; i++, curves += 2) {
     546         370 :         if (p[1] == curves[0] && p[2] == curves[1])
     547             :             return 1;
     548             :     }
     549             :     return 0;
     550             : }
     551             : 
     552             : /*-
     553             :  * Return |nmatch|th shared curve or NID_undef if there is no match.
     554             :  * For nmatch == -1, return number of  matches
     555             :  * For nmatch == -2, return the NID of the curve to use for
     556             :  * an EC tmp key, or NID_undef if there is no match.
     557             :  */
     558           0 : int tls1_shared_curve(SSL *s, int nmatch)
     559             : {
     560             :     const unsigned char *pref, *supp;
     561             :     size_t num_pref, num_supp, i, j;
     562             :     int k;
     563             :     /* Can't do anything on client side */
     564           0 :     if (s->server == 0)
     565             :         return -1;
     566           0 :     if (nmatch == -2) {
     567           0 :         if (tls1_suiteb(s)) {
     568             :             /*
     569             :              * For Suite B ciphersuite determines curve: we already know
     570             :              * these are acceptable due to previous checks.
     571             :              */
     572           0 :             unsigned long cid = s->s3->tmp.new_cipher->id;
     573           0 :             if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
     574             :                 return NID_X9_62_prime256v1; /* P-256 */
     575           0 :             if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
     576             :                 return NID_secp384r1; /* P-384 */
     577             :             /* Should never happen */
     578           0 :             return NID_undef;
     579             :         }
     580             :         /* If not Suite B just return first preference shared curve */
     581             :         nmatch = 0;
     582             :     }
     583             :     /*
     584             :      * Avoid truncation. tls1_get_curvelist takes an int
     585             :      * but s->options is a long...
     586             :      */
     587           0 :     if (!tls1_get_curvelist
     588           0 :         (s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0, &supp,
     589             :          &num_supp))
     590             :         /* In practice, NID_undef == 0 but let's be precise. */
     591             :         return nmatch == -1 ? 0 : NID_undef;
     592           0 :     if (!tls1_get_curvelist
     593           0 :         (s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE), &pref,
     594             :          &num_pref))
     595             :         return nmatch == -1 ? 0 : NID_undef;
     596             : 
     597             :     /*
     598             :      * If the client didn't send the elliptic_curves extension all of them
     599             :      * are allowed.
     600             :      */
     601           0 :     if (num_supp == 0 && (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0) {
     602           0 :         supp = eccurves_all;
     603           0 :         num_supp = sizeof(eccurves_all) / 2;
     604           0 :     } else if (num_pref == 0 &&
     605           0 :         (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) == 0) {
     606           0 :         pref = eccurves_all;
     607           0 :         num_pref = sizeof(eccurves_all) / 2;
     608             :     }
     609             : 
     610             :     k = 0;
     611           0 :     for (i = 0; i < num_pref; i++, pref += 2) {
     612           0 :         const unsigned char *tsupp = supp;
     613           0 :         for (j = 0; j < num_supp; j++, tsupp += 2) {
     614           0 :             if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) {
     615           0 :                 if (nmatch == k) {
     616           0 :                     int id = (pref[0] << 8) | pref[1];
     617           0 :                     return tls1_ec_curve_id2nid(id);
     618             :                 }
     619           0 :                 k++;
     620             :             }
     621             :         }
     622             :     }
     623           0 :     if (nmatch == -1)
     624           0 :         return k;
     625             :     /* Out of range (nmatch > k). */
     626             :     return NID_undef;
     627             : }
     628             : 
     629           0 : int tls1_set_curves(unsigned char **pext, size_t *pextlen,
     630             :                     int *curves, size_t ncurves)
     631             : {
     632             :     unsigned char *clist, *p;
     633             :     size_t i;
     634             :     /*
     635             :      * Bitmap of curves included to detect duplicates: only works while curve
     636             :      * ids < 32
     637             :      */
     638             :     unsigned long dup_list = 0;
     639             : # ifdef OPENSSL_NO_EC2M
     640             :     EC_GROUP *curve;
     641             : # endif
     642             : 
     643           0 :     clist = OPENSSL_malloc(ncurves * 2);
     644           0 :     if (!clist)
     645             :         return 0;
     646           0 :     for (i = 0, p = clist; i < ncurves; i++) {
     647             :         unsigned long idmask;
     648             :         int id;
     649           0 :         id = tls1_ec_nid2curve_id(curves[i]);
     650             : # ifdef OPENSSL_FIPS
     651             :         /* NB: 25 is last curve ID supported by FIPS module */
     652             :         if (FIPS_mode() && id > 25) {
     653             :             OPENSSL_free(clist);
     654             :             return 0;
     655             :         }
     656             : # endif
     657             : # ifdef OPENSSL_NO_EC2M
     658             :         curve = EC_GROUP_new_by_curve_name(curves[i]);
     659             :         if (!curve || EC_METHOD_get_field_type(EC_GROUP_method_of(curve))
     660             :             == NID_X9_62_characteristic_two_field) {
     661             :             if (curve)
     662             :                 EC_GROUP_free(curve);
     663             :             OPENSSL_free(clist);
     664             :             return 0;
     665             :         } else
     666             :             EC_GROUP_free(curve);
     667             : # endif
     668           0 :         idmask = 1L << id;
     669           0 :         if (!id || (dup_list & idmask)) {
     670           0 :             OPENSSL_free(clist);
     671           0 :             return 0;
     672             :         }
     673           0 :         dup_list |= idmask;
     674           0 :         s2n(id, p);
     675             :     }
     676           0 :     if (*pext)
     677           0 :         OPENSSL_free(*pext);
     678           0 :     *pext = clist;
     679           0 :     *pextlen = ncurves * 2;
     680           0 :     return 1;
     681             : }
     682             : 
     683             : # define MAX_CURVELIST   28
     684             : 
     685             : typedef struct {
     686             :     size_t nidcnt;
     687             :     int nid_arr[MAX_CURVELIST];
     688             : } nid_cb_st;
     689             : 
     690           0 : static int nid_cb(const char *elem, int len, void *arg)
     691             : {
     692             :     nid_cb_st *narg = arg;
     693             :     size_t i;
     694             :     int nid;
     695             :     char etmp[20];
     696           0 :     if (elem == NULL)
     697             :         return 0;
     698           0 :     if (narg->nidcnt == MAX_CURVELIST)
     699             :         return 0;
     700           0 :     if (len > (int)(sizeof(etmp) - 1))
     701             :         return 0;
     702           0 :     memcpy(etmp, elem, len);
     703           0 :     etmp[len] = 0;
     704           0 :     nid = EC_curve_nist2nid(etmp);
     705           0 :     if (nid == NID_undef)
     706           0 :         nid = OBJ_sn2nid(etmp);
     707           0 :     if (nid == NID_undef)
     708           0 :         nid = OBJ_ln2nid(etmp);
     709           0 :     if (nid == NID_undef)
     710             :         return 0;
     711           0 :     for (i = 0; i < narg->nidcnt; i++)
     712           0 :         if (narg->nid_arr[i] == nid)
     713             :             return 0;
     714           0 :     narg->nid_arr[narg->nidcnt++] = nid;
     715           0 :     return 1;
     716             : }
     717             : 
     718             : /* Set curves based on a colon separate list */
     719           0 : int tls1_set_curves_list(unsigned char **pext, size_t *pextlen,
     720             :                          const char *str)
     721             : {
     722             :     nid_cb_st ncb;
     723           0 :     ncb.nidcnt = 0;
     724           0 :     if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
     725             :         return 0;
     726           0 :     if (pext == NULL)
     727             :         return 1;
     728           0 :     return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
     729             : }
     730             : 
     731             : /* For an EC key set TLS id and required compression based on parameters */
     732         373 : static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
     733             :                           EC_KEY *ec)
     734             : {
     735             :     int is_prime, id;
     736             :     const EC_GROUP *grp;
     737             :     const EC_METHOD *meth;
     738         373 :     if (!ec)
     739             :         return 0;
     740             :     /* Determine if it is a prime field */
     741         373 :     grp = EC_KEY_get0_group(ec);
     742         373 :     if (!grp)
     743             :         return 0;
     744         373 :     meth = EC_GROUP_method_of(grp);
     745         373 :     if (!meth)
     746             :         return 0;
     747         373 :     if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
     748             :         is_prime = 1;
     749             :     else
     750             :         is_prime = 0;
     751             :     /* Determine curve ID */
     752         373 :     id = EC_GROUP_get_curve_name(grp);
     753         373 :     id = tls1_ec_nid2curve_id(id);
     754             :     /* If we have an ID set it, otherwise set arbitrary explicit curve */
     755         373 :     if (id) {
     756         373 :         curve_id[0] = 0;
     757         373 :         curve_id[1] = (unsigned char)id;
     758             :     } else {
     759           0 :         curve_id[0] = 0xff;
     760           0 :         if (is_prime)
     761           0 :             curve_id[1] = 0x01;
     762             :         else
     763           0 :             curve_id[1] = 0x02;
     764             :     }
     765         373 :     if (comp_id) {
     766           0 :         if (EC_KEY_get0_public_key(ec) == NULL)
     767             :             return 0;
     768           0 :         if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED) {
     769           0 :             if (is_prime)
     770           0 :                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
     771             :             else
     772           0 :                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
     773             :         } else
     774           0 :             *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
     775             :     }
     776             :     return 1;
     777             : }
     778             : 
     779             : /* Check an EC key is compatible with extensions */
     780         373 : static int tls1_check_ec_key(SSL *s,
     781             :                              unsigned char *curve_id, unsigned char *comp_id)
     782             : {
     783             :     const unsigned char *pformats, *pcurves;
     784             :     size_t num_formats, num_curves, i;
     785             :     int j;
     786             :     /*
     787             :      * If point formats extension present check it, otherwise everything is
     788             :      * supported (see RFC4492).
     789             :      */
     790         373 :     if (comp_id && s->session->tlsext_ecpointformatlist) {
     791             :         pformats = s->session->tlsext_ecpointformatlist;
     792           0 :         num_formats = s->session->tlsext_ecpointformatlist_length;
     793           0 :         for (i = 0; i < num_formats; i++, pformats++) {
     794           0 :             if (*comp_id == *pformats)
     795             :                 break;
     796             :         }
     797           0 :         if (i == num_formats)
     798             :             return 0;
     799             :     }
     800         373 :     if (!curve_id)
     801             :         return 1;
     802             :     /* Check curve is consistent with client and server preferences */
     803         746 :     for (j = 0; j <= 1; j++) {
     804         746 :         if (!tls1_get_curvelist(s, j, &pcurves, &num_curves))
     805             :             return 0;
     806         746 :         if (j == 1 && num_curves == 0) {
     807             :             /*
     808             :              * If we've not received any curves then skip this check.
     809             :              * RFC 4492 does not require the supported elliptic curves extension
     810             :              * so if it is not sent we can just choose any curve.
     811             :              * It is invalid to send an empty list in the elliptic curves
     812             :              * extension, so num_curves == 0 always means no extension.
     813             :              */
     814             :             break;
     815             :         }
     816           0 :         for (i = 0; i < num_curves; i++, pcurves += 2) {
     817         746 :             if (pcurves[0] == curve_id[0] && pcurves[1] == curve_id[1])
     818             :                 break;
     819             :         }
     820         746 :         if (i == num_curves)
     821             :             return 0;
     822             :         /* For clients can only check sent curve list */
     823         746 :         if (!s->server)
     824             :             return 1;
     825             :     }
     826             :     return 1;
     827             : }
     828             : 
     829             : static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
     830             :                                 size_t *num_formats)
     831             : {
     832             :     /*
     833             :      * If we have a custom point format list use it otherwise use default
     834             :      */
     835         746 :     if (s->tlsext_ecpointformatlist) {
     836             :         *pformats = s->tlsext_ecpointformatlist;
     837           0 :         *num_formats = s->tlsext_ecpointformatlist_length;
     838             :     } else {
     839             :         *pformats = ecformats_default;
     840             :         /* For Suite B we don't support char2 fields */
     841         746 :         if (tls1_suiteb(s))
     842             :             *num_formats = sizeof(ecformats_default) - 1;
     843             :         else
     844             :             *num_formats = sizeof(ecformats_default);
     845             :     }
     846             : }
     847             : 
     848             : /*
     849             :  * Check cert parameters compatible with extensions: currently just checks EC
     850             :  * certificates have compatible curves and compression.
     851             :  */
     852         373 : static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
     853             : {
     854             :     unsigned char comp_id, curve_id[2];
     855             :     EVP_PKEY *pkey;
     856             :     int rv;
     857         373 :     pkey = X509_get_pubkey(x);
     858         373 :     if (!pkey)
     859             :         return 0;
     860             :     /* If not EC nothing to do */
     861         373 :     if (pkey->type != EVP_PKEY_EC) {
     862         373 :         EVP_PKEY_free(pkey);
     863         373 :         return 1;
     864             :     }
     865           0 :     rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
     866           0 :     EVP_PKEY_free(pkey);
     867           0 :     if (!rv)
     868             :         return 0;
     869             :     /*
     870             :      * Can't check curve_id for client certs as we don't have a supported
     871             :      * curves extension.
     872             :      */
     873           0 :     rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
     874           0 :     if (!rv)
     875             :         return 0;
     876             :     /*
     877             :      * Special case for suite B. We *MUST* sign using SHA256+P-256 or
     878             :      * SHA384+P-384, adjust digest if necessary.
     879             :      */
     880           0 :     if (set_ee_md && tls1_suiteb(s)) {
     881             :         int check_md;
     882             :         size_t i;
     883             :         CERT *c = s->cert;
     884           0 :         if (curve_id[0])
     885             :             return 0;
     886             :         /* Check to see we have necessary signing algorithm */
     887           0 :         if (curve_id[1] == TLSEXT_curve_P_256)
     888             :             check_md = NID_ecdsa_with_SHA256;
     889           0 :         else if (curve_id[1] == TLSEXT_curve_P_384)
     890             :             check_md = NID_ecdsa_with_SHA384;
     891             :         else
     892             :             return 0;           /* Should never happen */
     893           0 :         for (i = 0; i < c->shared_sigalgslen; i++)
     894           0 :             if (check_md == c->shared_sigalgs[i].signandhash_nid)
     895             :                 break;
     896           0 :         if (i == c->shared_sigalgslen)
     897             :             return 0;
     898           0 :         if (set_ee_md == 2) {
     899           0 :             if (check_md == NID_ecdsa_with_SHA256)
     900           0 :                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
     901             :             else
     902           0 :                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
     903             :         }
     904             :     }
     905           0 :     return rv;
     906             : }
     907             : 
     908             : # ifndef OPENSSL_NO_ECDH
     909             : /* Check EC temporary key is compatible with client extensions */
     910         373 : int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
     911             : {
     912             :     unsigned char curve_id[2];
     913         373 :     EC_KEY *ec = s->cert->ecdh_tmp;
     914             : #  ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
     915             :     /* Allow any curve: not just those peer supports */
     916             :     if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
     917             :         return 1;
     918             : #  endif
     919             :     /*
     920             :      * If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
     921             :      * curves permitted.
     922             :      */
     923         373 :     if (tls1_suiteb(s)) {
     924             :         /* Curve to check determined by ciphersuite */
     925           0 :         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
     926           0 :             curve_id[1] = TLSEXT_curve_P_256;
     927           0 :         else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
     928           0 :             curve_id[1] = TLSEXT_curve_P_384;
     929             :         else
     930             :             return 0;
     931           0 :         curve_id[0] = 0;
     932             :         /* Check this curve is acceptable */
     933           0 :         if (!tls1_check_ec_key(s, curve_id, NULL))
     934             :             return 0;
     935             :         /* If auto or setting curve from callback assume OK */
     936           0 :         if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
     937             :             return 1;
     938             :         /* Otherwise check curve is acceptable */
     939             :         else {
     940             :             unsigned char curve_tmp[2];
     941           0 :             if (!ec)
     942             :                 return 0;
     943           0 :             if (!tls1_set_ec_id(curve_tmp, NULL, ec))
     944             :                 return 0;
     945           0 :             if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
     946             :                 return 1;
     947           0 :             return 0;
     948             :         }
     949             : 
     950             :     }
     951         373 :     if (s->cert->ecdh_tmp_auto) {
     952             :         /* Need a shared curve */
     953           0 :         if (tls1_shared_curve(s, 0))
     954             :             return 1;
     955             :         else
     956           0 :             return 0;
     957             :     }
     958         373 :     if (!ec) {
     959           0 :         if (s->cert->ecdh_tmp_cb)
     960             :             return 1;
     961             :         else
     962           0 :             return 0;
     963             :     }
     964         373 :     if (!tls1_set_ec_id(curve_id, NULL, ec))
     965             :         return 0;
     966             : /* Set this to allow use of invalid curves for testing */
     967             : #  if 0
     968             :     return 1;
     969             : #  else
     970         373 :     return tls1_check_ec_key(s, curve_id, NULL);
     971             : #  endif
     972             : }
     973             : # endif                         /* OPENSSL_NO_ECDH */
     974             : 
     975             : #else
     976             : 
     977             : static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
     978             : {
     979             :     return 1;
     980             : }
     981             : 
     982             : #endif                          /* OPENSSL_NO_EC */
     983             : 
     984             : #ifndef OPENSSL_NO_TLSEXT
     985             : 
     986             : /*
     987             :  * List of supported signature algorithms and hashes. Should make this
     988             :  * customisable at some point, for now include everything we support.
     989             :  */
     990             : 
     991             : # ifdef OPENSSL_NO_RSA
     992             : #  define tlsext_sigalg_rsa(md) /* */
     993             : # else
     994             : #  define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
     995             : # endif
     996             : 
     997             : # ifdef OPENSSL_NO_DSA
     998             : #  define tlsext_sigalg_dsa(md) /* */
     999             : # else
    1000             : #  define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
    1001             : # endif
    1002             : 
    1003             : # ifdef OPENSSL_NO_ECDSA
    1004             : #  define tlsext_sigalg_ecdsa(md)
    1005             :                                 /* */
    1006             : # else
    1007             : #  define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
    1008             : # endif
    1009             : 
    1010             : # define tlsext_sigalg(md) \
    1011             :                 tlsext_sigalg_rsa(md) \
    1012             :                 tlsext_sigalg_dsa(md) \
    1013             :                 tlsext_sigalg_ecdsa(md)
    1014             : 
    1015             : static unsigned char tls12_sigalgs[] = {
    1016             : # ifndef OPENSSL_NO_SHA512
    1017             :     tlsext_sigalg(TLSEXT_hash_sha512)
    1018             :         tlsext_sigalg(TLSEXT_hash_sha384)
    1019             : # endif
    1020             : # ifndef OPENSSL_NO_SHA256
    1021             :         tlsext_sigalg(TLSEXT_hash_sha256)
    1022             :         tlsext_sigalg(TLSEXT_hash_sha224)
    1023             : # endif
    1024             : # ifndef OPENSSL_NO_SHA
    1025             :         tlsext_sigalg(TLSEXT_hash_sha1)
    1026             : # endif
    1027             : };
    1028             : 
    1029             : # ifndef OPENSSL_NO_ECDSA
    1030             : static unsigned char suiteb_sigalgs[] = {
    1031             :     tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
    1032             :         tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
    1033             : };
    1034             : # endif
    1035        1489 : size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
    1036             : {
    1037             :     /*
    1038             :      * If Suite B mode use Suite B sigalgs only, ignore any other
    1039             :      * preferences.
    1040             :      */
    1041             : # ifndef OPENSSL_NO_EC
    1042        1489 :     switch (tls1_suiteb(s)) {
    1043             :     case SSL_CERT_FLAG_SUITEB_128_LOS:
    1044           0 :         *psigs = suiteb_sigalgs;
    1045           0 :         return sizeof(suiteb_sigalgs);
    1046             : 
    1047             :     case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
    1048           0 :         *psigs = suiteb_sigalgs;
    1049           0 :         return 2;
    1050             : 
    1051             :     case SSL_CERT_FLAG_SUITEB_192_LOS:
    1052           0 :         *psigs = suiteb_sigalgs + 2;
    1053           0 :         return 2;
    1054             :     }
    1055             : # endif
    1056             :     /* If server use client authentication sigalgs if not NULL */
    1057        1489 :     if (s->server && s->cert->client_sigalgs) {
    1058           0 :         *psigs = s->cert->client_sigalgs;
    1059           0 :         return s->cert->client_sigalgslen;
    1060        1489 :     } else if (s->cert->conf_sigalgs) {
    1061           0 :         *psigs = s->cert->conf_sigalgs;
    1062           0 :         return s->cert->conf_sigalgslen;
    1063             :     } else {
    1064        1489 :         *psigs = tls12_sigalgs;
    1065        1489 :         return sizeof(tls12_sigalgs);
    1066             :     }
    1067             : }
    1068             : 
    1069             : /*
    1070             :  * Check signature algorithm is consistent with sent supported signature
    1071             :  * algorithms and if so return relevant digest.
    1072             :  */
    1073         370 : int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
    1074             :                             const unsigned char *sig, EVP_PKEY *pkey)
    1075             : {
    1076             :     const unsigned char *sent_sigs;
    1077             :     size_t sent_sigslen, i;
    1078             :     int sigalg = tls12_get_sigid(pkey);
    1079             :     /* Should never happen */
    1080         370 :     if (sigalg == -1)
    1081             :         return -1;
    1082             :     /* Check key type is consistent with signature */
    1083         370 :     if (sigalg != (int)sig[1]) {
    1084           0 :         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
    1085           0 :         return 0;
    1086             :     }
    1087             : # ifndef OPENSSL_NO_EC
    1088         370 :     if (pkey->type == EVP_PKEY_EC) {
    1089             :         unsigned char curve_id[2], comp_id;
    1090             :         /* Check compression and curve matches extensions */
    1091           0 :         if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
    1092           0 :             return 0;
    1093           0 :         if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id)) {
    1094           0 :             SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
    1095           0 :             return 0;
    1096             :         }
    1097             :         /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
    1098           0 :         if (tls1_suiteb(s)) {
    1099           0 :             if (curve_id[0])
    1100             :                 return 0;
    1101           0 :             if (curve_id[1] == TLSEXT_curve_P_256) {
    1102           0 :                 if (sig[0] != TLSEXT_hash_sha256) {
    1103           0 :                     SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
    1104             :                            SSL_R_ILLEGAL_SUITEB_DIGEST);
    1105           0 :                     return 0;
    1106             :                 }
    1107           0 :             } else if (curve_id[1] == TLSEXT_curve_P_384) {
    1108           0 :                 if (sig[0] != TLSEXT_hash_sha384) {
    1109           0 :                     SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
    1110             :                            SSL_R_ILLEGAL_SUITEB_DIGEST);
    1111           0 :                     return 0;
    1112             :                 }
    1113             :             } else
    1114             :                 return 0;
    1115             :         }
    1116         370 :     } else if (tls1_suiteb(s))
    1117             :         return 0;
    1118             : # endif
    1119             : 
    1120             :     /* Check signature matches a type we sent */
    1121         370 :     sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
    1122         370 :     for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) {
    1123         370 :         if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
    1124             :             break;
    1125             :     }
    1126             :     /* Allow fallback to SHA1 if not strict mode */
    1127         370 :     if (i == sent_sigslen
    1128           0 :         && (sig[0] != TLSEXT_hash_sha1
    1129           0 :             || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
    1130           0 :         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
    1131           0 :         return 0;
    1132             :     }
    1133         370 :     *pmd = tls12_get_hash(sig[0]);
    1134         370 :     if (*pmd == NULL) {
    1135           0 :         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_UNKNOWN_DIGEST);
    1136           0 :         return 0;
    1137             :     }
    1138             :     /*
    1139             :      * Store the digest used so applications can retrieve it if they wish.
    1140             :      */
    1141         370 :     if (s->session && s->session->sess_cert)
    1142         370 :         s->session->sess_cert->peer_key->digest = *pmd;
    1143             :     return 1;
    1144             : }
    1145             : 
    1146             : /*
    1147             :  * Get a mask of disabled algorithms: an algorithm is disabled if it isn't
    1148             :  * supported or doesn't appear in supported signature algorithms. Unlike
    1149             :  * ssl_cipher_get_disabled this applies to a specific session and not global
    1150             :  * settings.
    1151             :  */
    1152         373 : void ssl_set_client_disabled(SSL *s)
    1153             : {
    1154         373 :     CERT *c = s->cert;
    1155             :     const unsigned char *sigalgs;
    1156             :     size_t i, sigalgslen;
    1157             :     int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
    1158         373 :     c->mask_a = 0;
    1159         373 :     c->mask_k = 0;
    1160             :     /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
    1161         373 :     if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
    1162           0 :         c->mask_ssl = SSL_TLSV1_2;
    1163             :     else
    1164         373 :         c->mask_ssl = 0;
    1165             :     /*
    1166             :      * Now go through all signature algorithms seeing if we support any for
    1167             :      * RSA, DSA, ECDSA. Do this for all versions not just TLS 1.2.
    1168             :      */
    1169         373 :     sigalgslen = tls12_get_psigalgs(s, &sigalgs);
    1170        5968 :     for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) {
    1171        5595 :         switch (sigalgs[1]) {
    1172             : # ifndef OPENSSL_NO_RSA
    1173             :         case TLSEXT_signature_rsa:
    1174             :             have_rsa = 1;
    1175        1865 :             break;
    1176             : # endif
    1177             : # ifndef OPENSSL_NO_DSA
    1178             :         case TLSEXT_signature_dsa:
    1179             :             have_dsa = 1;
    1180        1865 :             break;
    1181             : # endif
    1182             : # ifndef OPENSSL_NO_ECDSA
    1183             :         case TLSEXT_signature_ecdsa:
    1184             :             have_ecdsa = 1;
    1185        1865 :             break;
    1186             : # endif
    1187             :         }
    1188             :     }
    1189             :     /*
    1190             :      * Disable auth and static DH if we don't include any appropriate
    1191             :      * signature algorithms.
    1192             :      */
    1193         373 :     if (!have_rsa) {
    1194           0 :         c->mask_a |= SSL_aRSA;
    1195           0 :         c->mask_k |= SSL_kDHr | SSL_kECDHr;
    1196             :     }
    1197         373 :     if (!have_dsa) {
    1198           0 :         c->mask_a |= SSL_aDSS;
    1199           0 :         c->mask_k |= SSL_kDHd;
    1200             :     }
    1201         373 :     if (!have_ecdsa) {
    1202           0 :         c->mask_a |= SSL_aECDSA;
    1203           0 :         c->mask_k |= SSL_kECDHe;
    1204             :     }
    1205             : # ifndef OPENSSL_NO_KRB5
    1206             :     if (!kssl_tgt_is_available(s->kssl_ctx)) {
    1207             :         c->mask_a |= SSL_aKRB5;
    1208             :         c->mask_k |= SSL_kKRB5;
    1209             :     }
    1210             : # endif
    1211             : # ifndef OPENSSL_NO_PSK
    1212             :     /* with PSK there must be client callback set */
    1213         373 :     if (!s->psk_client_callback) {
    1214         373 :         c->mask_a |= SSL_aPSK;
    1215         373 :         c->mask_k |= SSL_kPSK;
    1216             :     }
    1217             : # endif                         /* OPENSSL_NO_PSK */
    1218             : # ifndef OPENSSL_NO_SRP
    1219         373 :     if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
    1220         373 :         c->mask_a |= SSL_aSRP;
    1221         373 :         c->mask_k |= SSL_kSRP;
    1222             :     }
    1223             : # endif
    1224         373 :     c->valid = 1;
    1225         373 : }
    1226             : 
    1227         373 : unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf,
    1228             :                                           unsigned char *limit, int *al)
    1229             : {
    1230             :     int extdatalen = 0;
    1231             :     unsigned char *orig = buf;
    1232         373 :     unsigned char *ret = buf;
    1233             : # ifndef OPENSSL_NO_EC
    1234             :     /* See if we support any ECC ciphersuites */
    1235             :     int using_ecc = 0;
    1236         373 :     if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) {
    1237             :         int i;
    1238             :         unsigned long alg_k, alg_a;
    1239         373 :         STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
    1240             : 
    1241         373 :         for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) {
    1242         373 :             SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
    1243             : 
    1244         373 :             alg_k = c->algorithm_mkey;
    1245         373 :             alg_a = c->algorithm_auth;
    1246         373 :             if ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)
    1247           0 :                  || (alg_a & SSL_aECDSA))) {
    1248             :                 using_ecc = 1;
    1249             :                 break;
    1250             :             }
    1251             :         }
    1252             :     }
    1253             : # endif
    1254             : 
    1255             :     /* don't add extensions for SSLv3 unless doing secure renegotiation */
    1256         373 :     if (s->client_version == SSL3_VERSION && !s->s3->send_connection_binding)
    1257             :         return orig;
    1258             : 
    1259         373 :     ret += 2;
    1260             : 
    1261         373 :     if (ret >= limit)
    1262             :         return NULL;            /* this really never occurs, but ... */
    1263             : 
    1264         373 :     if (s->tlsext_hostname != NULL) {
    1265             :         /* Add TLS extension servername to the Client Hello message */
    1266             :         unsigned long size_str;
    1267             :         long lenmax;
    1268             : 
    1269             :         /*-
    1270             :          * check for enough space.
    1271             :          * 4 for the servername type and entension length
    1272             :          * 2 for servernamelist length
    1273             :          * 1 for the hostname type
    1274             :          * 2 for hostname length
    1275             :          * + hostname length
    1276             :          */
    1277             : 
    1278         373 :         if ((lenmax = limit - ret - 9) < 0
    1279         746 :             || (size_str =
    1280         373 :                 strlen(s->tlsext_hostname)) > (unsigned long)lenmax)
    1281             :             return NULL;
    1282             : 
    1283             :         /* extension type and length */
    1284         373 :         s2n(TLSEXT_TYPE_server_name, ret);
    1285         373 :         s2n(size_str + 5, ret);
    1286             : 
    1287             :         /* length of servername list */
    1288         373 :         s2n(size_str + 3, ret);
    1289             : 
    1290             :         /* hostname type, length and hostname */
    1291         373 :         *(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name;
    1292         373 :         s2n(size_str, ret);
    1293         373 :         memcpy(ret, s->tlsext_hostname, size_str);
    1294         373 :         ret += size_str;
    1295             :     }
    1296             : 
    1297             :     /* Add RI if renegotiating */
    1298         373 :     if (s->renegotiate) {
    1299             :         int el;
    1300             : 
    1301           0 :         if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) {
    1302           0 :             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1303           0 :             return NULL;
    1304             :         }
    1305             : 
    1306           0 :         if ((limit - ret - 4 - el) < 0)
    1307             :             return NULL;
    1308             : 
    1309           0 :         s2n(TLSEXT_TYPE_renegotiate, ret);
    1310           0 :         s2n(el, ret);
    1311             : 
    1312           0 :         if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) {
    1313           0 :             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1314           0 :             return NULL;
    1315             :         }
    1316             : 
    1317           0 :         ret += el;
    1318             :     }
    1319             : # ifndef OPENSSL_NO_SRP
    1320             :     /* Add SRP username if there is one */
    1321         373 :     if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the
    1322             :                                      * Client Hello message */
    1323             : 
    1324           0 :         int login_len = strlen(s->srp_ctx.login);
    1325           0 :         if (login_len > 255 || login_len == 0) {
    1326           0 :             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1327           0 :             return NULL;
    1328             :         }
    1329             : 
    1330             :         /*-
    1331             :          * check for enough space.
    1332             :          * 4 for the srp type type and entension length
    1333             :          * 1 for the srp user identity
    1334             :          * + srp user identity length
    1335             :          */
    1336           0 :         if ((limit - ret - 5 - login_len) < 0)
    1337             :             return NULL;
    1338             : 
    1339             :         /* fill in the extension */
    1340           0 :         s2n(TLSEXT_TYPE_srp, ret);
    1341           0 :         s2n(login_len + 1, ret);
    1342           0 :         (*ret++) = (unsigned char)login_len;
    1343           0 :         memcpy(ret, s->srp_ctx.login, login_len);
    1344           0 :         ret += login_len;
    1345             :     }
    1346             : # endif
    1347             : 
    1348             : # ifndef OPENSSL_NO_EC
    1349         373 :     if (using_ecc) {
    1350             :         /*
    1351             :          * Add TLS extension ECPointFormats to the ClientHello message
    1352             :          */
    1353             :         long lenmax;
    1354             :         const unsigned char *pcurves, *pformats;
    1355             :         size_t num_curves, num_formats, curves_list_len;
    1356             : 
    1357             :         tls1_get_formatlist(s, &pformats, &num_formats);
    1358             : 
    1359         373 :         if ((lenmax = limit - ret - 5) < 0)
    1360           0 :             return NULL;
    1361         373 :         if (num_formats > (size_t)lenmax)
    1362             :             return NULL;
    1363         373 :         if (num_formats > 255) {
    1364           0 :             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1365           0 :             return NULL;
    1366             :         }
    1367             : 
    1368         373 :         s2n(TLSEXT_TYPE_ec_point_formats, ret);
    1369             :         /* The point format list has 1-byte length. */
    1370         373 :         s2n(num_formats + 1, ret);
    1371         373 :         *(ret++) = (unsigned char)num_formats;
    1372         373 :         memcpy(ret, pformats, num_formats);
    1373         373 :         ret += num_formats;
    1374             : 
    1375             :         /*
    1376             :          * Add TLS extension EllipticCurves to the ClientHello message
    1377             :          */
    1378         373 :         pcurves = s->tlsext_ellipticcurvelist;
    1379         373 :         if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves))
    1380             :             return NULL;
    1381             : 
    1382         373 :         if ((lenmax = limit - ret - 6) < 0)
    1383             :             return NULL;
    1384         373 :         if (num_curves > (size_t)lenmax / 2)
    1385             :             return NULL;
    1386         373 :         if (num_curves > 65532 / 2) {
    1387           0 :             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1388           0 :             return NULL;
    1389             :         }
    1390         373 :         curves_list_len = 2 * num_curves;
    1391         373 :         s2n(TLSEXT_TYPE_elliptic_curves, ret);
    1392         373 :         s2n(curves_list_len + 2, ret);
    1393         373 :         s2n(curves_list_len, ret);
    1394         373 :         memcpy(ret, pcurves, curves_list_len);
    1395         373 :         ret += curves_list_len;
    1396             :     }
    1397             : # endif                         /* OPENSSL_NO_EC */
    1398             : 
    1399         373 :     if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
    1400             :         int ticklen;
    1401         373 :         if (!s->new_session && s->session && s->session->tlsext_tick)
    1402           0 :             ticklen = s->session->tlsext_ticklen;
    1403         373 :         else if (s->session && s->tlsext_session_ticket &&
    1404           0 :                  s->tlsext_session_ticket->data) {
    1405           0 :             ticklen = s->tlsext_session_ticket->length;
    1406           0 :             s->session->tlsext_tick = OPENSSL_malloc(ticklen);
    1407           0 :             if (!s->session->tlsext_tick)
    1408             :                 return NULL;
    1409           0 :             memcpy(s->session->tlsext_tick,
    1410           0 :                    s->tlsext_session_ticket->data, ticklen);
    1411           0 :             s->session->tlsext_ticklen = ticklen;
    1412             :         } else
    1413             :             ticklen = 0;
    1414         373 :         if (ticklen == 0 && s->tlsext_session_ticket &&
    1415           0 :             s->tlsext_session_ticket->data == NULL)
    1416             :             goto skip_ext;
    1417             :         /*
    1418             :          * Check for enough room 2 for extension type, 2 for len rest for
    1419             :          * ticket
    1420             :          */
    1421         373 :         if ((long)(limit - ret - 4 - ticklen) < 0)
    1422             :             return NULL;
    1423         373 :         s2n(TLSEXT_TYPE_session_ticket, ret);
    1424         373 :         s2n(ticklen, ret);
    1425         373 :         if (ticklen) {
    1426           0 :             memcpy(ret, s->session->tlsext_tick, ticklen);
    1427           0 :             ret += ticklen;
    1428             :         }
    1429             :     }
    1430             :  skip_ext:
    1431             : 
    1432         373 :     if (SSL_USE_SIGALGS(s)) {
    1433             :         size_t salglen;
    1434             :         const unsigned char *salg;
    1435         373 :         salglen = tls12_get_psigalgs(s, &salg);
    1436         373 :         if ((size_t)(limit - ret) < salglen + 6)
    1437           0 :             return NULL;
    1438         373 :         s2n(TLSEXT_TYPE_signature_algorithms, ret);
    1439         373 :         s2n(salglen + 2, ret);
    1440         373 :         s2n(salglen, ret);
    1441         373 :         memcpy(ret, salg, salglen);
    1442         373 :         ret += salglen;
    1443             :     }
    1444             : # ifdef TLSEXT_TYPE_opaque_prf_input
    1445             :     if (s->s3->client_opaque_prf_input != NULL) {
    1446             :         size_t col = s->s3->client_opaque_prf_input_len;
    1447             : 
    1448             :         if ((long)(limit - ret - 6 - col < 0))
    1449             :             return NULL;
    1450             :         if (col > 0xFFFD)       /* can't happen */
    1451             :             return NULL;
    1452             : 
    1453             :         s2n(TLSEXT_TYPE_opaque_prf_input, ret);
    1454             :         s2n(col + 2, ret);
    1455             :         s2n(col, ret);
    1456             :         memcpy(ret, s->s3->client_opaque_prf_input, col);
    1457             :         ret += col;
    1458             :     }
    1459             : # endif
    1460             : 
    1461         373 :     if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
    1462             :         int i;
    1463             :         long extlen, idlen, itmp;
    1464             :         OCSP_RESPID *id;
    1465             : 
    1466             :         idlen = 0;
    1467           0 :         for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
    1468           0 :             id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
    1469           0 :             itmp = i2d_OCSP_RESPID(id, NULL);
    1470           0 :             if (itmp <= 0)
    1471             :                 return NULL;
    1472           0 :             idlen += itmp + 2;
    1473             :         }
    1474             : 
    1475           0 :         if (s->tlsext_ocsp_exts) {
    1476           0 :             extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
    1477           0 :             if (extlen < 0)
    1478             :                 return NULL;
    1479             :         } else
    1480             :             extlen = 0;
    1481             : 
    1482           0 :         if ((long)(limit - ret - 7 - extlen - idlen) < 0)
    1483             :             return NULL;
    1484           0 :         s2n(TLSEXT_TYPE_status_request, ret);
    1485           0 :         if (extlen + idlen > 0xFFF0)
    1486             :             return NULL;
    1487           0 :         s2n(extlen + idlen + 5, ret);
    1488           0 :         *(ret++) = TLSEXT_STATUSTYPE_ocsp;
    1489           0 :         s2n(idlen, ret);
    1490           0 :         for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
    1491             :             /* save position of id len */
    1492           0 :             unsigned char *q = ret;
    1493           0 :             id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
    1494             :             /* skip over id len */
    1495           0 :             ret += 2;
    1496           0 :             itmp = i2d_OCSP_RESPID(id, &ret);
    1497             :             /* write id len */
    1498           0 :             s2n(itmp, q);
    1499             :         }
    1500           0 :         s2n(extlen, ret);
    1501           0 :         if (extlen > 0)
    1502           0 :             i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
    1503             :     }
    1504             : # ifndef OPENSSL_NO_HEARTBEATS
    1505             :     /* Add Heartbeat extension */
    1506         373 :     if ((limit - ret - 4 - 1) < 0)
    1507             :         return NULL;
    1508         373 :     s2n(TLSEXT_TYPE_heartbeat, ret);
    1509         373 :     s2n(1, ret);
    1510             :     /*-
    1511             :      * Set mode:
    1512             :      * 1: peer may send requests
    1513             :      * 2: peer not allowed to send requests
    1514             :      */
    1515         373 :     if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
    1516           0 :         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
    1517             :     else
    1518         373 :         *(ret++) = SSL_TLSEXT_HB_ENABLED;
    1519             : # endif
    1520             : 
    1521             : # ifndef OPENSSL_NO_NEXTPROTONEG
    1522         373 :     if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) {
    1523             :         /*
    1524             :          * The client advertises an emtpy extension to indicate its support
    1525             :          * for Next Protocol Negotiation
    1526             :          */
    1527         373 :         if (limit - ret - 4 < 0)
    1528             :             return NULL;
    1529         373 :         s2n(TLSEXT_TYPE_next_proto_neg, ret);
    1530         373 :         s2n(0, ret);
    1531             :     }
    1532             : # endif
    1533             : 
    1534         373 :     if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) {
    1535         373 :         if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
    1536             :             return NULL;
    1537         373 :         s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
    1538         373 :         s2n(2 + s->alpn_client_proto_list_len, ret);
    1539         373 :         s2n(s->alpn_client_proto_list_len, ret);
    1540         373 :         memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len);
    1541         373 :         ret += s->alpn_client_proto_list_len;
    1542             :     }
    1543             : # ifndef OPENSSL_NO_SRTP
    1544         373 :     if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) {
    1545             :         int el;
    1546             : 
    1547           0 :         ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
    1548             : 
    1549           0 :         if ((limit - ret - 4 - el) < 0)
    1550           0 :             return NULL;
    1551             : 
    1552           0 :         s2n(TLSEXT_TYPE_use_srtp, ret);
    1553           0 :         s2n(el, ret);
    1554             : 
    1555           0 :         if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) {
    1556           0 :             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1557           0 :             return NULL;
    1558             :         }
    1559           0 :         ret += el;
    1560             :     }
    1561             : # endif
    1562         373 :     custom_ext_init(&s->cert->cli_ext);
    1563             :     /* Add custom TLS Extensions to ClientHello */
    1564         373 :     if (!custom_ext_add(s, 0, &ret, limit, al))
    1565             :         return NULL;
    1566             : 
    1567             :     /*
    1568             :      * Add padding to workaround bugs in F5 terminators. See
    1569             :      * https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this
    1570             :      * code works out the length of all existing extensions it MUST always
    1571             :      * appear last.
    1572             :      */
    1573         373 :     if (s->options & SSL_OP_TLSEXT_PADDING) {
    1574           0 :         int hlen = ret - (unsigned char *)s->init_buf->data;
    1575             :         /*
    1576             :          * The code in s23_clnt.c to build ClientHello messages includes the
    1577             :          * 5-byte record header in the buffer, while the code in s3_clnt.c
    1578             :          * does not.
    1579             :          */
    1580           0 :         if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
    1581           0 :             hlen -= 5;
    1582           0 :         if (hlen > 0xff && hlen < 0x200) {
    1583           0 :             hlen = 0x200 - hlen;
    1584           0 :             if (hlen >= 4)
    1585           0 :                 hlen -= 4;
    1586             :             else
    1587             :                 hlen = 0;
    1588             : 
    1589           0 :             s2n(TLSEXT_TYPE_padding, ret);
    1590           0 :             s2n(hlen, ret);
    1591           0 :             memset(ret, 0, hlen);
    1592           0 :             ret += hlen;
    1593             :         }
    1594             :     }
    1595             : 
    1596         373 :     if ((extdatalen = ret - orig - 2) == 0)
    1597             :         return orig;
    1598             : 
    1599         373 :     s2n(extdatalen, orig);
    1600         373 :     return ret;
    1601             : }
    1602             : 
    1603         373 : unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,
    1604             :                                           unsigned char *limit, int *al)
    1605             : {
    1606             :     int extdatalen = 0;
    1607             :     unsigned char *orig = buf;
    1608         373 :     unsigned char *ret = buf;
    1609             : # ifndef OPENSSL_NO_NEXTPROTONEG
    1610             :     int next_proto_neg_seen;
    1611             : # endif
    1612             : # ifndef OPENSSL_NO_EC
    1613         373 :     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
    1614         373 :     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
    1615         373 :     int using_ecc = (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
    1616         373 :         || (alg_a & SSL_aECDSA);
    1617         373 :     using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
    1618             : # endif
    1619             :     /*
    1620             :      * don't add extensions for SSLv3, unless doing secure renegotiation
    1621             :      */
    1622         373 :     if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
    1623             :         return orig;
    1624             : 
    1625         373 :     ret += 2;
    1626         373 :     if (ret >= limit)
    1627             :         return NULL;            /* this really never occurs, but ... */
    1628             : 
    1629         373 :     if (!s->hit && s->servername_done == 1
    1630         373 :         && s->session->tlsext_hostname != NULL) {
    1631         373 :         if ((long)(limit - ret - 4) < 0)
    1632             :             return NULL;
    1633             : 
    1634         373 :         s2n(TLSEXT_TYPE_server_name, ret);
    1635         373 :         s2n(0, ret);
    1636             :     }
    1637             : 
    1638         373 :     if (s->s3->send_connection_binding) {
    1639             :         int el;
    1640             : 
    1641         373 :         if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) {
    1642           0 :             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1643           0 :             return NULL;
    1644             :         }
    1645             : 
    1646         373 :         if ((limit - ret - 4 - el) < 0)
    1647             :             return NULL;
    1648             : 
    1649         373 :         s2n(TLSEXT_TYPE_renegotiate, ret);
    1650         373 :         s2n(el, ret);
    1651             : 
    1652         373 :         if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) {
    1653           0 :             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1654           0 :             return NULL;
    1655             :         }
    1656             : 
    1657         373 :         ret += el;
    1658             :     }
    1659             : # ifndef OPENSSL_NO_EC
    1660         373 :     if (using_ecc) {
    1661             :         const unsigned char *plist;
    1662             :         size_t plistlen;
    1663             :         /*
    1664             :          * Add TLS extension ECPointFormats to the ServerHello message
    1665             :          */
    1666             :         long lenmax;
    1667             : 
    1668             :         tls1_get_formatlist(s, &plist, &plistlen);
    1669             : 
    1670         373 :         if ((lenmax = limit - ret - 5) < 0)
    1671             :             return NULL;
    1672         373 :         if (plistlen > (size_t)lenmax)
    1673             :             return NULL;
    1674         373 :         if (plistlen > 255) {
    1675           0 :             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1676           0 :             return NULL;
    1677             :         }
    1678             : 
    1679         373 :         s2n(TLSEXT_TYPE_ec_point_formats, ret);
    1680         373 :         s2n(plistlen + 1, ret);
    1681         373 :         *(ret++) = (unsigned char)plistlen;
    1682         373 :         memcpy(ret, plist, plistlen);
    1683         373 :         ret += plistlen;
    1684             : 
    1685             :     }
    1686             :     /*
    1687             :      * Currently the server should not respond with a SupportedCurves
    1688             :      * extension
    1689             :      */
    1690             : # endif                         /* OPENSSL_NO_EC */
    1691             : 
    1692         373 :     if (s->tlsext_ticket_expected && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
    1693         373 :         if ((long)(limit - ret - 4) < 0)
    1694             :             return NULL;
    1695         373 :         s2n(TLSEXT_TYPE_session_ticket, ret);
    1696         373 :         s2n(0, ret);
    1697             :     }
    1698             : 
    1699         373 :     if (s->tlsext_status_expected) {
    1700           0 :         if ((long)(limit - ret - 4) < 0)
    1701             :             return NULL;
    1702           0 :         s2n(TLSEXT_TYPE_status_request, ret);
    1703           0 :         s2n(0, ret);
    1704             :     }
    1705             : # ifdef TLSEXT_TYPE_opaque_prf_input
    1706             :     if (s->s3->server_opaque_prf_input != NULL) {
    1707             :         size_t sol = s->s3->server_opaque_prf_input_len;
    1708             : 
    1709             :         if ((long)(limit - ret - 6 - sol) < 0)
    1710             :             return NULL;
    1711             :         if (sol > 0xFFFD)       /* can't happen */
    1712             :             return NULL;
    1713             : 
    1714             :         s2n(TLSEXT_TYPE_opaque_prf_input, ret);
    1715             :         s2n(sol + 2, ret);
    1716             :         s2n(sol, ret);
    1717             :         memcpy(ret, s->s3->server_opaque_prf_input, sol);
    1718             :         ret += sol;
    1719             :     }
    1720             : # endif
    1721             : 
    1722             : # ifndef OPENSSL_NO_SRTP
    1723         373 :     if (SSL_IS_DTLS(s) && s->srtp_profile) {
    1724             :         int el;
    1725             : 
    1726           0 :         ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
    1727             : 
    1728           0 :         if ((limit - ret - 4 - el) < 0)
    1729           0 :             return NULL;
    1730             : 
    1731           0 :         s2n(TLSEXT_TYPE_use_srtp, ret);
    1732           0 :         s2n(el, ret);
    1733             : 
    1734           0 :         if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) {
    1735           0 :             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
    1736           0 :             return NULL;
    1737             :         }
    1738           0 :         ret += el;
    1739             :     }
    1740             : # endif
    1741             : 
    1742         746 :     if (((s->s3->tmp.new_cipher->id & 0xFFFF) == 0x80
    1743         373 :          || (s->s3->tmp.new_cipher->id & 0xFFFF) == 0x81)
    1744           0 :         && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) {
    1745           0 :         const unsigned char cryptopro_ext[36] = {
    1746             :             0xfd, 0xe8,         /* 65000 */
    1747             :             0x00, 0x20,         /* 32 bytes length */
    1748             :             0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
    1749             :             0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
    1750             :             0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
    1751             :             0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
    1752             :         };
    1753           0 :         if (limit - ret < 36)
    1754           0 :             return NULL;
    1755             :         memcpy(ret, cryptopro_ext, 36);
    1756           0 :         ret += 36;
    1757             : 
    1758             :     }
    1759             : # ifndef OPENSSL_NO_HEARTBEATS
    1760             :     /* Add Heartbeat extension if we've received one */
    1761         373 :     if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) {
    1762         373 :         if ((limit - ret - 4 - 1) < 0)
    1763             :             return NULL;
    1764         373 :         s2n(TLSEXT_TYPE_heartbeat, ret);
    1765         373 :         s2n(1, ret);
    1766             :         /*-
    1767             :          * Set mode:
    1768             :          * 1: peer may send requests
    1769             :          * 2: peer not allowed to send requests
    1770             :          */
    1771         373 :         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
    1772           0 :             *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
    1773             :         else
    1774         373 :             *(ret++) = SSL_TLSEXT_HB_ENABLED;
    1775             : 
    1776             :     }
    1777             : # endif
    1778             : 
    1779             : # ifndef OPENSSL_NO_NEXTPROTONEG
    1780         373 :     next_proto_neg_seen = s->s3->next_proto_neg_seen;
    1781         373 :     s->s3->next_proto_neg_seen = 0;
    1782         373 :     if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) {
    1783             :         const unsigned char *npa;
    1784             :         unsigned int npalen;
    1785             :         int r;
    1786             : 
    1787           0 :         r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,
    1788             :                                               s->
    1789             :                                               ctx->next_protos_advertised_cb_arg);
    1790           0 :         if (r == SSL_TLSEXT_ERR_OK) {
    1791           0 :             if ((long)(limit - ret - 4 - npalen) < 0)
    1792           0 :                 return NULL;
    1793           0 :             s2n(TLSEXT_TYPE_next_proto_neg, ret);
    1794           0 :             s2n(npalen, ret);
    1795           0 :             memcpy(ret, npa, npalen);
    1796           0 :             ret += npalen;
    1797           0 :             s->s3->next_proto_neg_seen = 1;
    1798             :         }
    1799             :     }
    1800             : # endif
    1801         373 :     if (!custom_ext_add(s, 1, &ret, limit, al))
    1802             :         return NULL;
    1803             : 
    1804         373 :     if (s->s3->alpn_selected) {
    1805             :         const unsigned char *selected = s->s3->alpn_selected;
    1806         373 :         unsigned len = s->s3->alpn_selected_len;
    1807             : 
    1808         373 :         if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
    1809             :             return NULL;
    1810         373 :         s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
    1811         373 :         s2n(3 + len, ret);
    1812         373 :         s2n(1 + len, ret);
    1813         373 :         *ret++ = len;
    1814         373 :         memcpy(ret, selected, len);
    1815         373 :         ret += len;
    1816             :     }
    1817             : 
    1818         373 :     if ((extdatalen = ret - orig - 2) == 0)
    1819             :         return orig;
    1820             : 
    1821         373 :     s2n(extdatalen, orig);
    1822         373 :     return ret;
    1823             : }
    1824             : 
    1825             : # ifndef OPENSSL_NO_EC
    1826             : /*-
    1827             :  * ssl_check_for_safari attempts to fingerprint Safari using OS X
    1828             :  * SecureTransport using the TLS extension block in |d|, of length |n|.
    1829             :  * Safari, since 10.6, sends exactly these extensions, in this order:
    1830             :  *   SNI,
    1831             :  *   elliptic_curves
    1832             :  *   ec_point_formats
    1833             :  *
    1834             :  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
    1835             :  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
    1836             :  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
    1837             :  * 10.8..10.8.3 (which don't work).
    1838             :  */
    1839           0 : static void ssl_check_for_safari(SSL *s, const unsigned char *data,
    1840             :                                  const unsigned char *d, int n)
    1841             : {
    1842             :     unsigned short type, size;
    1843             :     static const unsigned char kSafariExtensionsBlock[] = {
    1844             :         0x00, 0x0a,             /* elliptic_curves extension */
    1845             :         0x00, 0x08,             /* 8 bytes */
    1846             :         0x00, 0x06,             /* 6 bytes of curve ids */
    1847             :         0x00, 0x17,             /* P-256 */
    1848             :         0x00, 0x18,             /* P-384 */
    1849             :         0x00, 0x19,             /* P-521 */
    1850             : 
    1851             :         0x00, 0x0b,             /* ec_point_formats */
    1852             :         0x00, 0x02,             /* 2 bytes */
    1853             :         0x01,                   /* 1 point format */
    1854             :         0x00,                   /* uncompressed */
    1855             :     };
    1856             : 
    1857             :     /* The following is only present in TLS 1.2 */
    1858             :     static const unsigned char kSafariTLS12ExtensionsBlock[] = {
    1859             :         0x00, 0x0d,             /* signature_algorithms */
    1860             :         0x00, 0x0c,             /* 12 bytes */
    1861             :         0x00, 0x0a,             /* 10 bytes */
    1862             :         0x05, 0x01,             /* SHA-384/RSA */
    1863             :         0x04, 0x01,             /* SHA-256/RSA */
    1864             :         0x02, 0x01,             /* SHA-1/RSA */
    1865             :         0x04, 0x03,             /* SHA-256/ECDSA */
    1866             :         0x02, 0x03,             /* SHA-1/ECDSA */
    1867             :     };
    1868             : 
    1869           0 :     if (data >= (d + n - 2))
    1870             :         return;
    1871           0 :     data += 2;
    1872             : 
    1873           0 :     if (data > (d + n - 4))
    1874             :         return;
    1875           0 :     n2s(data, type);
    1876           0 :     n2s(data, size);
    1877             : 
    1878           0 :     if (type != TLSEXT_TYPE_server_name)
    1879             :         return;
    1880             : 
    1881           0 :     if (data + size > d + n)
    1882             :         return;
    1883             :     data += size;
    1884             : 
    1885           0 :     if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
    1886             :         const size_t len1 = sizeof(kSafariExtensionsBlock);
    1887             :         const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
    1888             : 
    1889           0 :         if (data + len1 + len2 != d + n)
    1890             :             return;
    1891           0 :         if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
    1892             :             return;
    1893           0 :         if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
    1894             :             return;
    1895             :     } else {
    1896             :         const size_t len = sizeof(kSafariExtensionsBlock);
    1897             : 
    1898           0 :         if (data + len != d + n)
    1899             :             return;
    1900           0 :         if (memcmp(data, kSafariExtensionsBlock, len) != 0)
    1901             :             return;
    1902             :     }
    1903             : 
    1904           0 :     s->s3->is_probably_safari = 1;
    1905             : }
    1906             : # endif                         /* !OPENSSL_NO_EC */
    1907             : 
    1908             : /*
    1909             :  * tls1_alpn_handle_client_hello is called to process the ALPN extension in a
    1910             :  * ClientHello.  data: the contents of the extension, not including the type
    1911             :  * and length.  data_len: the number of bytes in |data| al: a pointer to the
    1912             :  * alert value to send in the event of a non-zero return.  returns: 0 on
    1913             :  * success.
    1914             :  */
    1915         373 : static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
    1916             :                                          unsigned data_len, int *al)
    1917             : {
    1918             :     unsigned i;
    1919             :     unsigned proto_len;
    1920             :     const unsigned char *selected;
    1921             :     unsigned char selected_len;
    1922             :     int r;
    1923             : 
    1924         373 :     if (s->ctx->alpn_select_cb == NULL)
    1925             :         return 0;
    1926             : 
    1927         373 :     if (data_len < 2)
    1928             :         goto parse_error;
    1929             : 
    1930             :     /*
    1931             :      * data should contain a uint16 length followed by a series of 8-bit,
    1932             :      * length-prefixed strings.
    1933             :      */
    1934         373 :     i = ((unsigned)data[0]) << 8 | ((unsigned)data[1]);
    1935         373 :     data_len -= 2;
    1936         373 :     data += 2;
    1937         373 :     if (data_len != i)
    1938             :         goto parse_error;
    1939             : 
    1940         373 :     if (data_len < 2)
    1941             :         goto parse_error;
    1942             : 
    1943         746 :     for (i = 0; i < data_len;) {
    1944         373 :         proto_len = data[i];
    1945         373 :         i++;
    1946             : 
    1947         373 :         if (proto_len == 0)
    1948             :             goto parse_error;
    1949             : 
    1950         373 :         if (i + proto_len < i || i + proto_len > data_len)
    1951             :             goto parse_error;
    1952             : 
    1953             :         i += proto_len;
    1954             :     }
    1955             : 
    1956         373 :     r = s->ctx->alpn_select_cb(s, &selected, &selected_len, data, data_len,
    1957             :                                s->ctx->alpn_select_cb_arg);
    1958         373 :     if (r == SSL_TLSEXT_ERR_OK) {
    1959         373 :         if (s->s3->alpn_selected)
    1960           0 :             OPENSSL_free(s->s3->alpn_selected);
    1961         373 :         s->s3->alpn_selected = OPENSSL_malloc(selected_len);
    1962         373 :         if (!s->s3->alpn_selected) {
    1963           0 :             *al = SSL_AD_INTERNAL_ERROR;
    1964           0 :             return -1;
    1965             :         }
    1966         373 :         memcpy(s->s3->alpn_selected, selected, selected_len);
    1967         373 :         s->s3->alpn_selected_len = selected_len;
    1968             :     }
    1969             :     return 0;
    1970             : 
    1971             :  parse_error:
    1972           0 :     *al = SSL_AD_DECODE_ERROR;
    1973           0 :     return -1;
    1974             : }
    1975             : 
    1976         373 : static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p,
    1977             :                                        unsigned char *d, int n, int *al)
    1978             : {
    1979             :     unsigned short type;
    1980             :     unsigned short size;
    1981             :     unsigned short len;
    1982         373 :     unsigned char *data = *p;
    1983             :     int renegotiate_seen = 0;
    1984             : 
    1985         373 :     s->servername_done = 0;
    1986         373 :     s->tlsext_status_type = -1;
    1987             : # ifndef OPENSSL_NO_NEXTPROTONEG
    1988         373 :     s->s3->next_proto_neg_seen = 0;
    1989             : # endif
    1990             : 
    1991         373 :     if (s->s3->alpn_selected) {
    1992           0 :         OPENSSL_free(s->s3->alpn_selected);
    1993           0 :         s->s3->alpn_selected = NULL;
    1994             :     }
    1995             : # ifndef OPENSSL_NO_HEARTBEATS
    1996         373 :     s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
    1997             :                              SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
    1998             : # endif
    1999             : 
    2000             : # ifndef OPENSSL_NO_EC
    2001         373 :     if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
    2002           0 :         ssl_check_for_safari(s, data, d, n);
    2003             : # endif                         /* !OPENSSL_NO_EC */
    2004             : 
    2005             :     /* Clear any signature algorithms extension received */
    2006         373 :     if (s->cert->peer_sigalgs) {
    2007           0 :         OPENSSL_free(s->cert->peer_sigalgs);
    2008           0 :         s->cert->peer_sigalgs = NULL;
    2009             :     }
    2010             : # ifndef OPENSSL_NO_SRP
    2011         373 :     if (s->srp_ctx.login != NULL) {
    2012           0 :         OPENSSL_free(s->srp_ctx.login);
    2013           0 :         s->srp_ctx.login = NULL;
    2014             :     }
    2015             : # endif
    2016             : 
    2017         373 :     s->srtp_profile = NULL;
    2018             : 
    2019         373 :     if (data == d + n)
    2020             :         goto ri_check;
    2021             : 
    2022         373 :     if (data > (d + n - 2))
    2023             :         goto err;
    2024             : 
    2025         373 :     n2s(data, len);
    2026             : 
    2027         373 :     if (data > (d + n - len))
    2028             :         goto err;
    2029             : 
    2030        3357 :     while (data <= (d + n - 4)) {
    2031        2984 :         n2s(data, type);
    2032        2984 :         n2s(data, size);
    2033             : 
    2034        2984 :         if (data + size > (d + n))
    2035             :             goto err;
    2036             : # if 0
    2037             :         fprintf(stderr, "Received extension type %d size %d\n", type, size);
    2038             : # endif
    2039        2984 :         if (s->tlsext_debug_cb)
    2040           0 :             s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg);
    2041             : /*-
    2042             :  * The servername extension is treated as follows:
    2043             :  *
    2044             :  * - Only the hostname type is supported with a maximum length of 255.
    2045             :  * - The servername is rejected if too long or if it contains zeros,
    2046             :  *   in which case an fatal alert is generated.
    2047             :  * - The servername field is maintained together with the session cache.
    2048             :  * - When a session is resumed, the servername call back invoked in order
    2049             :  *   to allow the application to position itself to the right context.
    2050             :  * - The servername is acknowledged if it is new for a session or when
    2051             :  *   it is identical to a previously used for the same session.
    2052             :  *   Applications can control the behaviour.  They can at any time
    2053             :  *   set a 'desirable' servername for a new SSL object. This can be the
    2054             :  *   case for example with HTTPS when a Host: header field is received and
    2055             :  *   a renegotiation is requested. In this case, a possible servername
    2056             :  *   presented in the new client hello is only acknowledged if it matches
    2057             :  *   the value of the Host: field.
    2058             :  * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
    2059             :  *   if they provide for changing an explicit servername context for the
    2060             :  *   session, i.e. when the session has been established with a servername
    2061             :  *   extension.
    2062             :  * - On session reconnect, the servername extension may be absent.
    2063             :  *
    2064             :  */
    2065             : 
    2066        2984 :         if (type == TLSEXT_TYPE_server_name) {
    2067             :             unsigned char *sdata;
    2068             :             int servname_type;
    2069             :             int dsize;
    2070             : 
    2071         373 :             if (size < 2)
    2072             :                 goto err;
    2073         373 :             n2s(data, dsize);
    2074         373 :             size -= 2;
    2075         373 :             if (dsize > size)
    2076             :                 goto err;
    2077             : 
    2078             :             sdata = data;
    2079         746 :             while (dsize > 3) {
    2080         373 :                 servname_type = *(sdata++);
    2081         373 :                 n2s(sdata, len);
    2082         373 :                 dsize -= 3;
    2083             : 
    2084         373 :                 if (len > dsize)
    2085             :                     goto err;
    2086             : 
    2087         373 :                 if (s->servername_done == 0)
    2088         373 :                     switch (servname_type) {
    2089             :                     case TLSEXT_NAMETYPE_host_name:
    2090         373 :                         if (!s->hit) {
    2091         373 :                             if (s->session->tlsext_hostname)
    2092             :                                 goto err;
    2093             : 
    2094         373 :                             if (len > TLSEXT_MAXLEN_host_name) {
    2095           0 :                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
    2096           0 :                                 return 0;
    2097             :                             }
    2098         373 :                             if ((s->session->tlsext_hostname =
    2099         373 :                                  OPENSSL_malloc(len + 1)) == NULL) {
    2100           0 :                                 *al = TLS1_AD_INTERNAL_ERROR;
    2101           0 :                                 return 0;
    2102             :                             }
    2103         373 :                             memcpy(s->session->tlsext_hostname, sdata, len);
    2104         373 :                             s->session->tlsext_hostname[len] = '\0';
    2105         373 :                             if (strlen(s->session->tlsext_hostname) != len) {
    2106           0 :                                 OPENSSL_free(s->session->tlsext_hostname);
    2107           0 :                                 s->session->tlsext_hostname = NULL;
    2108           0 :                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
    2109           0 :                                 return 0;
    2110             :                             }
    2111         373 :                             s->servername_done = 1;
    2112             : 
    2113             :                         } else
    2114           0 :                             s->servername_done = s->session->tlsext_hostname
    2115           0 :                                 && strlen(s->session->tlsext_hostname) == len
    2116           0 :                                 && strncmp(s->session->tlsext_hostname,
    2117             :                                            (char *)sdata, len) == 0;
    2118             : 
    2119             :                         break;
    2120             : 
    2121             :                     default:
    2122             :                         break;
    2123             :                     }
    2124             : 
    2125         373 :                 dsize -= len;
    2126             :             }
    2127         373 :             if (dsize != 0)
    2128             :                 goto err;
    2129             : 
    2130             :         }
    2131             : # ifndef OPENSSL_NO_SRP
    2132        2611 :         else if (type == TLSEXT_TYPE_srp) {
    2133           0 :             if (size == 0 || ((len = data[0])) != (size - 1))
    2134             :                 goto err;
    2135           0 :             if (s->srp_ctx.login != NULL)
    2136             :                 goto err;
    2137           0 :             if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL)
    2138             :                 return -1;
    2139           0 :             memcpy(s->srp_ctx.login, &data[1], len);
    2140           0 :             s->srp_ctx.login[len] = '\0';
    2141             : 
    2142           0 :             if (strlen(s->srp_ctx.login) != len)
    2143             :                 goto err;
    2144             :         }
    2145             : # endif
    2146             : 
    2147             : # ifndef OPENSSL_NO_EC
    2148        2611 :         else if (type == TLSEXT_TYPE_ec_point_formats) {
    2149             :             unsigned char *sdata = data;
    2150         373 :             int ecpointformatlist_length = *(sdata++);
    2151             : 
    2152         373 :             if (ecpointformatlist_length != size - 1 ||
    2153             :                 ecpointformatlist_length < 1)
    2154             :                 goto err;
    2155         373 :             if (!s->hit) {
    2156         373 :                 if (s->session->tlsext_ecpointformatlist) {
    2157           0 :                     OPENSSL_free(s->session->tlsext_ecpointformatlist);
    2158           0 :                     s->session->tlsext_ecpointformatlist = NULL;
    2159             :                 }
    2160         373 :                 s->session->tlsext_ecpointformatlist_length = 0;
    2161         373 :                 if ((s->session->tlsext_ecpointformatlist =
    2162         373 :                      OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
    2163           0 :                     *al = TLS1_AD_INTERNAL_ERROR;
    2164           0 :                     return 0;
    2165             :                 }
    2166         373 :                 s->session->tlsext_ecpointformatlist_length =
    2167             :                     ecpointformatlist_length;
    2168         373 :                 memcpy(s->session->tlsext_ecpointformatlist, sdata,
    2169             :                        ecpointformatlist_length);
    2170             :             }
    2171             : #  if 0
    2172             :             fprintf(stderr,
    2173             :                     "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ",
    2174             :                     s->session->tlsext_ecpointformatlist_length);
    2175             :             sdata = s->session->tlsext_ecpointformatlist;
    2176             :             for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
    2177             :                 fprintf(stderr, "%i ", *(sdata++));
    2178             :             fprintf(stderr, "\n");
    2179             : #  endif
    2180        2238 :         } else if (type == TLSEXT_TYPE_elliptic_curves) {
    2181             :             unsigned char *sdata = data;
    2182         373 :             int ellipticcurvelist_length = (*(sdata++) << 8);
    2183         373 :             ellipticcurvelist_length += (*(sdata++));
    2184             : 
    2185         373 :             if (ellipticcurvelist_length != size - 2 ||
    2186         373 :                 ellipticcurvelist_length < 1 ||
    2187             :                 /* Each NamedCurve is 2 bytes. */
    2188         373 :                 ellipticcurvelist_length & 1)
    2189             :                     goto err;
    2190             : 
    2191         373 :             if (!s->hit) {
    2192         373 :                 if (s->session->tlsext_ellipticcurvelist)
    2193             :                     goto err;
    2194             : 
    2195         373 :                 s->session->tlsext_ellipticcurvelist_length = 0;
    2196         373 :                 if ((s->session->tlsext_ellipticcurvelist =
    2197         373 :                      OPENSSL_malloc(ellipticcurvelist_length)) == NULL) {
    2198           0 :                     *al = TLS1_AD_INTERNAL_ERROR;
    2199           0 :                     return 0;
    2200             :                 }
    2201         373 :                 s->session->tlsext_ellipticcurvelist_length =
    2202             :                     ellipticcurvelist_length;
    2203         373 :                 memcpy(s->session->tlsext_ellipticcurvelist, sdata,
    2204             :                        ellipticcurvelist_length);
    2205             :             }
    2206             : #  if 0
    2207             :             fprintf(stderr,
    2208             :                     "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ",
    2209             :                     s->session->tlsext_ellipticcurvelist_length);
    2210             :             sdata = s->session->tlsext_ellipticcurvelist;
    2211             :             for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
    2212             :                 fprintf(stderr, "%i ", *(sdata++));
    2213             :             fprintf(stderr, "\n");
    2214             : #  endif
    2215             :         }
    2216             : # endif                         /* OPENSSL_NO_EC */
    2217             : # ifdef TLSEXT_TYPE_opaque_prf_input
    2218             :         else if (type == TLSEXT_TYPE_opaque_prf_input) {
    2219             :             unsigned char *sdata = data;
    2220             : 
    2221             :             if (size < 2) {
    2222             :                 *al = SSL_AD_DECODE_ERROR;
    2223             :                 return 0;
    2224             :             }
    2225             :             n2s(sdata, s->s3->client_opaque_prf_input_len);
    2226             :             if (s->s3->client_opaque_prf_input_len != size - 2) {
    2227             :                 *al = SSL_AD_DECODE_ERROR;
    2228             :                 return 0;
    2229             :             }
    2230             : 
    2231             :             if (s->s3->client_opaque_prf_input != NULL) {
    2232             :                 /* shouldn't really happen */
    2233             :                 OPENSSL_free(s->s3->client_opaque_prf_input);
    2234             :             }
    2235             : 
    2236             :             /* dummy byte just to get non-NULL */
    2237             :             if (s->s3->client_opaque_prf_input_len == 0)
    2238             :                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
    2239             :             else
    2240             :                 s->s3->client_opaque_prf_input =
    2241             :                     BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
    2242             :             if (s->s3->client_opaque_prf_input == NULL) {
    2243             :                 *al = TLS1_AD_INTERNAL_ERROR;
    2244             :                 return 0;
    2245             :             }
    2246             :         }
    2247             : # endif
    2248        1865 :         else if (type == TLSEXT_TYPE_session_ticket) {
    2249         373 :             if (s->tls_session_ticket_ext_cb &&
    2250           0 :                 !s->tls_session_ticket_ext_cb(s, data, size,
    2251             :                                               s->tls_session_ticket_ext_cb_arg))
    2252             :             {
    2253           0 :                 *al = TLS1_AD_INTERNAL_ERROR;
    2254           0 :                 return 0;
    2255             :             }
    2256        1492 :         } else if (type == TLSEXT_TYPE_renegotiate) {
    2257           0 :             if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
    2258             :                 return 0;
    2259             :             renegotiate_seen = 1;
    2260        1492 :         } else if (type == TLSEXT_TYPE_signature_algorithms) {
    2261             :             int dsize;
    2262         373 :             if (s->cert->peer_sigalgs || size < 2)
    2263             :                 goto err;
    2264         373 :             n2s(data, dsize);
    2265         373 :             size -= 2;
    2266         373 :             if (dsize != size || dsize & 1 || !dsize)
    2267             :                 goto err;
    2268         373 :             if (!tls1_save_sigalgs(s, data, dsize))
    2269             :                 goto err;
    2270        1119 :         } else if (type == TLSEXT_TYPE_status_request) {
    2271             : 
    2272           0 :             if (size < 5)
    2273             :                 goto err;
    2274             : 
    2275           0 :             s->tlsext_status_type = *data++;
    2276           0 :             size--;
    2277           0 :             if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
    2278             :                 const unsigned char *sdata;
    2279             :                 int dsize;
    2280             :                 /* Read in responder_id_list */
    2281           0 :                 n2s(data, dsize);
    2282           0 :                 size -= 2;
    2283           0 :                 if (dsize > size)
    2284             :                     goto err;
    2285           0 :                 while (dsize > 0) {
    2286             :                     OCSP_RESPID *id;
    2287             :                     int idsize;
    2288           0 :                     if (dsize < 4)
    2289             :                         goto err;
    2290           0 :                     n2s(data, idsize);
    2291           0 :                     dsize -= 2 + idsize;
    2292           0 :                     size -= 2 + idsize;
    2293           0 :                     if (dsize < 0)
    2294             :                         goto err;
    2295           0 :                     sdata = data;
    2296           0 :                     data += idsize;
    2297           0 :                     id = d2i_OCSP_RESPID(NULL, &sdata, idsize);
    2298           0 :                     if (!id)
    2299             :                         goto err;
    2300           0 :                     if (data != sdata) {
    2301           0 :                         OCSP_RESPID_free(id);
    2302           0 :                         goto err;
    2303             :                     }
    2304           0 :                     if (!s->tlsext_ocsp_ids
    2305           0 :                         && !(s->tlsext_ocsp_ids =
    2306           0 :                              sk_OCSP_RESPID_new_null())) {
    2307           0 :                         OCSP_RESPID_free(id);
    2308           0 :                         *al = SSL_AD_INTERNAL_ERROR;
    2309           0 :                         return 0;
    2310             :                     }
    2311           0 :                     if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
    2312           0 :                         OCSP_RESPID_free(id);
    2313           0 :                         *al = SSL_AD_INTERNAL_ERROR;
    2314           0 :                         return 0;
    2315             :                     }
    2316             :                 }
    2317             : 
    2318             :                 /* Read in request_extensions */
    2319           0 :                 if (size < 2)
    2320             :                     goto err;
    2321           0 :                 n2s(data, dsize);
    2322           0 :                 size -= 2;
    2323           0 :                 if (dsize != size)
    2324             :                     goto err;
    2325           0 :                 sdata = data;
    2326           0 :                 if (dsize > 0) {
    2327           0 :                     if (s->tlsext_ocsp_exts) {
    2328           0 :                         sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
    2329             :                                                    X509_EXTENSION_free);
    2330             :                     }
    2331             : 
    2332           0 :                     s->tlsext_ocsp_exts =
    2333           0 :                         d2i_X509_EXTENSIONS(NULL, &sdata, dsize);
    2334           0 :                     if (!s->tlsext_ocsp_exts || (data + dsize != sdata))
    2335             :                         goto err;
    2336             :                 }
    2337             :             }
    2338             :             /*
    2339             :              * We don't know what to do with any other type * so ignore it.
    2340             :              */
    2341             :             else
    2342           0 :                 s->tlsext_status_type = -1;
    2343             :         }
    2344             : # ifndef OPENSSL_NO_HEARTBEATS
    2345        1119 :         else if (type == TLSEXT_TYPE_heartbeat) {
    2346         373 :             switch (data[0]) {
    2347             :             case 0x01:         /* Client allows us to send HB requests */
    2348         373 :                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
    2349         373 :                 break;
    2350             :             case 0x02:         /* Client doesn't accept HB requests */
    2351           0 :                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
    2352           0 :                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
    2353           0 :                 break;
    2354             :             default:
    2355           0 :                 *al = SSL_AD_ILLEGAL_PARAMETER;
    2356           0 :                 return 0;
    2357             :             }
    2358             :         }
    2359             : # endif
    2360             : # ifndef OPENSSL_NO_NEXTPROTONEG
    2361        1119 :         else if (type == TLSEXT_TYPE_next_proto_neg &&
    2362         746 :                  s->s3->tmp.finish_md_len == 0 &&
    2363         373 :                  s->s3->alpn_selected == NULL) {
    2364             :             /*-
    2365             :              * We shouldn't accept this extension on a
    2366             :              * renegotiation.
    2367             :              *
    2368             :              * s->new_session will be set on renegotiation, but we
    2369             :              * probably shouldn't rely that it couldn't be set on
    2370             :              * the initial renegotation too in certain cases (when
    2371             :              * there's some other reason to disallow resuming an
    2372             :              * earlier session -- the current code won't be doing
    2373             :              * anything like that, but this might change).
    2374             :              *
    2375             :              * A valid sign that there's been a previous handshake
    2376             :              * in this connection is if s->s3->tmp.finish_md_len >
    2377             :              * 0.  (We are talking about a check that will happen
    2378             :              * in the Hello protocol round, well before a new
    2379             :              * Finished message could have been computed.)
    2380             :              */
    2381         373 :             s->s3->next_proto_neg_seen = 1;
    2382             :         }
    2383             : # endif
    2384             : 
    2385         746 :         else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
    2386         746 :                  s->ctx->alpn_select_cb && s->s3->tmp.finish_md_len == 0) {
    2387         373 :             if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
    2388             :                 return 0;
    2389             : # ifndef OPENSSL_NO_NEXTPROTONEG
    2390             :             /* ALPN takes precedence over NPN. */
    2391         373 :             s->s3->next_proto_neg_seen = 0;
    2392             : # endif
    2393             :         }
    2394             : 
    2395             :         /* session ticket processed earlier */
    2396             : # ifndef OPENSSL_NO_SRTP
    2397           0 :         else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
    2398           0 :                  && type == TLSEXT_TYPE_use_srtp) {
    2399           0 :             if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al))
    2400             :                 return 0;
    2401             :         }
    2402             : # endif
    2403             : 
    2404        2984 :         data += size;
    2405             :     }
    2406             : 
    2407             :     /* Spurious data on the end */
    2408         373 :     if (data != d + n)
    2409             :         goto err;
    2410             : 
    2411         373 :     *p = data;
    2412             : 
    2413             :  ri_check:
    2414             : 
    2415             :     /* Need RI if renegotiating */
    2416             : 
    2417         373 :     if (!renegotiate_seen && s->renegotiate &&
    2418           0 :         !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
    2419           0 :         *al = SSL_AD_HANDSHAKE_FAILURE;
    2420           0 :         SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
    2421             :                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
    2422           0 :         return 0;
    2423             :     }
    2424             : 
    2425             :     return 1;
    2426             : err:
    2427           0 :     *al = SSL_AD_DECODE_ERROR;
    2428           0 :     return 0;
    2429             : }
    2430             : 
    2431             : /*
    2432             :  * Parse any custom extensions found.  "data" is the start of the extension data
    2433             :  * and "limit" is the end of the record. TODO: add strict syntax checking.
    2434             :  */
    2435             : 
    2436         373 : static int ssl_scan_clienthello_custom_tlsext(SSL *s,
    2437             :                                               const unsigned char *data,
    2438             :                                               const unsigned char *limit,
    2439             :                                               int *al)
    2440             : {
    2441             :     unsigned short type, size, len;
    2442             :     /* If resumed session or no custom extensions nothing to do */
    2443         373 :     if (s->hit || s->cert->srv_ext.meths_count == 0)
    2444             :         return 1;
    2445             : 
    2446           0 :     if (data >= limit - 2)
    2447             :         return 1;
    2448           0 :     n2s(data, len);
    2449             : 
    2450           0 :     if (data > limit - len)
    2451             :         return 1;
    2452             : 
    2453           0 :     while (data <= limit - 4) {
    2454           0 :         n2s(data, type);
    2455           0 :         n2s(data, size);
    2456             : 
    2457           0 :         if (data + size > limit)
    2458             :             return 1;
    2459           0 :         if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0)
    2460             :             return 0;
    2461             : 
    2462             :         data += size;
    2463             :     }
    2464             : 
    2465             :     return 1;
    2466             : }
    2467             : 
    2468         373 : int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d,
    2469             :                                  int n)
    2470             : {
    2471         373 :     int al = -1;
    2472         373 :     unsigned char *ptmp = *p;
    2473             :     /*
    2474             :      * Internally supported extensions are parsed first so SNI can be handled
    2475             :      * before custom extensions. An application processing SNI will typically
    2476             :      * switch the parent context using SSL_set_SSL_CTX and custom extensions
    2477             :      * need to be handled by the new SSL_CTX structure.
    2478             :      */
    2479         373 :     if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) {
    2480           0 :         ssl3_send_alert(s, SSL3_AL_FATAL, al);
    2481           0 :         return 0;
    2482             :     }
    2483             : 
    2484         373 :     if (ssl_check_clienthello_tlsext_early(s) <= 0) {
    2485           0 :         SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_CLIENTHELLO_TLSEXT);
    2486           0 :         return 0;
    2487             :     }
    2488             : 
    2489         373 :     custom_ext_init(&s->cert->srv_ext);
    2490         373 :     if (ssl_scan_clienthello_custom_tlsext(s, ptmp, d + n, &al) <= 0) {
    2491           0 :         ssl3_send_alert(s, SSL3_AL_FATAL, al);
    2492           0 :         return 0;
    2493             :     }
    2494             : 
    2495             :     return 1;
    2496             : }
    2497             : 
    2498             : # ifndef OPENSSL_NO_NEXTPROTONEG
    2499             : /*
    2500             :  * ssl_next_proto_validate validates a Next Protocol Negotiation block. No
    2501             :  * elements of zero length are allowed and the set of elements must exactly
    2502             :  * fill the length of the block.
    2503             :  */
    2504             : static char ssl_next_proto_validate(unsigned char *d, unsigned len)
    2505             : {
    2506             :     unsigned int off = 0;
    2507             : 
    2508           0 :     while (off < len) {
    2509           0 :         if (d[off] == 0)
    2510             :             return 0;
    2511           0 :         off += d[off];
    2512           0 :         off++;
    2513             :     }
    2514             : 
    2515           0 :     return off == len;
    2516             : }
    2517             : # endif
    2518             : 
    2519         370 : static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p,
    2520             :                                        unsigned char *d, int n, int *al)
    2521             : {
    2522             :     unsigned short length;
    2523             :     unsigned short type;
    2524             :     unsigned short size;
    2525         370 :     unsigned char *data = *p;
    2526             :     int tlsext_servername = 0;
    2527             :     int renegotiate_seen = 0;
    2528             : 
    2529             : # ifndef OPENSSL_NO_NEXTPROTONEG
    2530         370 :     s->s3->next_proto_neg_seen = 0;
    2531             : # endif
    2532         370 :     s->tlsext_ticket_expected = 0;
    2533             : 
    2534         370 :     if (s->s3->alpn_selected) {
    2535           0 :         OPENSSL_free(s->s3->alpn_selected);
    2536           0 :         s->s3->alpn_selected = NULL;
    2537             :     }
    2538             : # ifndef OPENSSL_NO_HEARTBEATS
    2539         370 :     s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
    2540             :                              SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
    2541             : # endif
    2542             : 
    2543         370 :     if (data >= (d + n - 2))
    2544             :         goto ri_check;
    2545             : 
    2546         370 :     n2s(data, length);
    2547         370 :     if (data + length != d + n) {
    2548           0 :         *al = SSL_AD_DECODE_ERROR;
    2549           0 :         return 0;
    2550             :     }
    2551             : 
    2552        2590 :     while (data <= (d + n - 4)) {
    2553        2220 :         n2s(data, type);
    2554        2220 :         n2s(data, size);
    2555             : 
    2556        2220 :         if (data + size > (d + n))
    2557             :             goto ri_check;
    2558             : 
    2559        2220 :         if (s->tlsext_debug_cb)
    2560           0 :             s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg);
    2561             : 
    2562        2220 :         if (type == TLSEXT_TYPE_server_name) {
    2563         370 :             if (s->tlsext_hostname == NULL || size > 0) {
    2564           0 :                 *al = TLS1_AD_UNRECOGNIZED_NAME;
    2565           0 :                 return 0;
    2566             :             }
    2567             :             tlsext_servername = 1;
    2568             :         }
    2569             : # ifndef OPENSSL_NO_EC
    2570        1850 :         else if (type == TLSEXT_TYPE_ec_point_formats) {
    2571             :             unsigned char *sdata = data;
    2572         370 :             int ecpointformatlist_length = *(sdata++);
    2573             : 
    2574         370 :             if (ecpointformatlist_length != size - 1) {
    2575           0 :                 *al = TLS1_AD_DECODE_ERROR;
    2576           0 :                 return 0;
    2577             :             }
    2578         370 :             if (!s->hit) {
    2579         370 :                 s->session->tlsext_ecpointformatlist_length = 0;
    2580         370 :                 if (s->session->tlsext_ecpointformatlist != NULL)
    2581           0 :                     OPENSSL_free(s->session->tlsext_ecpointformatlist);
    2582         740 :                 if ((s->session->tlsext_ecpointformatlist =
    2583         370 :                      OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
    2584           0 :                     *al = TLS1_AD_INTERNAL_ERROR;
    2585           0 :                     return 0;
    2586             :                 }
    2587         370 :                 s->session->tlsext_ecpointformatlist_length =
    2588             :                     ecpointformatlist_length;
    2589         370 :                 memcpy(s->session->tlsext_ecpointformatlist, sdata,
    2590             :                        ecpointformatlist_length);
    2591             :             }
    2592             : #  if 0
    2593             :             fprintf(stderr,
    2594             :                     "ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
    2595             :             sdata = s->session->tlsext_ecpointformatlist;
    2596             :             for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
    2597             :                 fprintf(stderr, "%i ", *(sdata++));
    2598             :             fprintf(stderr, "\n");
    2599             : #  endif
    2600             :         }
    2601             : # endif                         /* OPENSSL_NO_EC */
    2602             : 
    2603        1480 :         else if (type == TLSEXT_TYPE_session_ticket) {
    2604         370 :             if (s->tls_session_ticket_ext_cb &&
    2605           0 :                 !s->tls_session_ticket_ext_cb(s, data, size,
    2606             :                                               s->tls_session_ticket_ext_cb_arg))
    2607             :             {
    2608           0 :                 *al = TLS1_AD_INTERNAL_ERROR;
    2609           0 :                 return 0;
    2610             :             }
    2611         370 :             if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
    2612         370 :                 || (size > 0)) {
    2613           0 :                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
    2614           0 :                 return 0;
    2615             :             }
    2616         370 :             s->tlsext_ticket_expected = 1;
    2617             :         }
    2618             : # ifdef TLSEXT_TYPE_opaque_prf_input
    2619             :         else if (type == TLSEXT_TYPE_opaque_prf_input) {
    2620             :             unsigned char *sdata = data;
    2621             : 
    2622             :             if (size < 2) {
    2623             :                 *al = SSL_AD_DECODE_ERROR;
    2624             :                 return 0;
    2625             :             }
    2626             :             n2s(sdata, s->s3->server_opaque_prf_input_len);
    2627             :             if (s->s3->server_opaque_prf_input_len != size - 2) {
    2628             :                 *al = SSL_AD_DECODE_ERROR;
    2629             :                 return 0;
    2630             :             }
    2631             : 
    2632             :             if (s->s3->server_opaque_prf_input != NULL) {
    2633             :                 /* shouldn't really happen */
    2634             :                 OPENSSL_free(s->s3->server_opaque_prf_input);
    2635             :             }
    2636             :             if (s->s3->server_opaque_prf_input_len == 0) {
    2637             :                 /* dummy byte just to get non-NULL */
    2638             :                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
    2639             :             } else {
    2640             :                 s->s3->server_opaque_prf_input =
    2641             :                     BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
    2642             :             }
    2643             : 
    2644             :             if (s->s3->server_opaque_prf_input == NULL) {
    2645             :                 *al = TLS1_AD_INTERNAL_ERROR;
    2646             :                 return 0;
    2647             :             }
    2648             :         }
    2649             : # endif
    2650        1110 :         else if (type == TLSEXT_TYPE_status_request) {
    2651             :             /*
    2652             :              * MUST be empty and only sent if we've requested a status
    2653             :              * request message.
    2654             :              */
    2655           0 :             if ((s->tlsext_status_type == -1) || (size > 0)) {
    2656           0 :                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
    2657           0 :                 return 0;
    2658             :             }
    2659             :             /* Set flag to expect CertificateStatus message */
    2660           0 :             s->tlsext_status_expected = 1;
    2661             :         }
    2662             : # ifndef OPENSSL_NO_NEXTPROTONEG
    2663        1110 :         else if (type == TLSEXT_TYPE_next_proto_neg &&
    2664           0 :                  s->s3->tmp.finish_md_len == 0) {
    2665             :             unsigned char *selected;
    2666             :             unsigned char selected_len;
    2667             : 
    2668             :             /* We must have requested it. */
    2669           0 :             if (s->ctx->next_proto_select_cb == NULL) {
    2670           0 :                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
    2671           0 :                 return 0;
    2672             :             }
    2673             :             /* The data must be valid */
    2674           0 :             if (!ssl_next_proto_validate(data, size)) {
    2675           0 :                 *al = TLS1_AD_DECODE_ERROR;
    2676           0 :                 return 0;
    2677             :             }
    2678           0 :             if (s->
    2679           0 :                 ctx->next_proto_select_cb(s, &selected, &selected_len, data,
    2680             :                                           size,
    2681             :                                           s->ctx->next_proto_select_cb_arg) !=
    2682             :                 SSL_TLSEXT_ERR_OK) {
    2683           0 :                 *al = TLS1_AD_INTERNAL_ERROR;
    2684           0 :                 return 0;
    2685             :             }
    2686           0 :             s->next_proto_negotiated = OPENSSL_malloc(selected_len);
    2687           0 :             if (!s->next_proto_negotiated) {
    2688           0 :                 *al = TLS1_AD_INTERNAL_ERROR;
    2689           0 :                 return 0;
    2690             :             }
    2691           0 :             memcpy(s->next_proto_negotiated, selected, selected_len);
    2692           0 :             s->next_proto_negotiated_len = selected_len;
    2693           0 :             s->s3->next_proto_neg_seen = 1;
    2694             :         }
    2695             : # endif
    2696             : 
    2697        1110 :         else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) {
    2698             :             unsigned len;
    2699             : 
    2700             :             /* We must have requested it. */
    2701         370 :             if (s->alpn_client_proto_list == NULL) {
    2702           0 :                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
    2703           0 :                 return 0;
    2704             :             }
    2705         370 :             if (size < 4) {
    2706           0 :                 *al = TLS1_AD_DECODE_ERROR;
    2707           0 :                 return 0;
    2708             :             }
    2709             :             /*-
    2710             :              * The extension data consists of:
    2711             :              *   uint16 list_length
    2712             :              *   uint8 proto_length;
    2713             :              *   uint8 proto[proto_length];
    2714             :              */
    2715         370 :             len = data[0];
    2716         370 :             len <<= 8;
    2717         370 :             len |= data[1];
    2718         370 :             if (len != (unsigned)size - 2) {
    2719           0 :                 *al = TLS1_AD_DECODE_ERROR;
    2720           0 :                 return 0;
    2721             :             }
    2722         370 :             len = data[2];
    2723         370 :             if (len != (unsigned)size - 3) {
    2724           0 :                 *al = TLS1_AD_DECODE_ERROR;
    2725           0 :                 return 0;
    2726             :             }
    2727         370 :             if (s->s3->alpn_selected)
    2728           0 :                 OPENSSL_free(s->s3->alpn_selected);
    2729         370 :             s->s3->alpn_selected = OPENSSL_malloc(len);
    2730         370 :             if (!s->s3->alpn_selected) {
    2731           0 :                 *al = TLS1_AD_INTERNAL_ERROR;
    2732           0 :                 return 0;
    2733             :             }
    2734         370 :             memcpy(s->s3->alpn_selected, data + 3, len);
    2735         370 :             s->s3->alpn_selected_len = len;
    2736             :         }
    2737             : 
    2738         740 :         else if (type == TLSEXT_TYPE_renegotiate) {
    2739         370 :             if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
    2740             :                 return 0;
    2741             :             renegotiate_seen = 1;
    2742             :         }
    2743             : # ifndef OPENSSL_NO_HEARTBEATS
    2744         370 :         else if (type == TLSEXT_TYPE_heartbeat) {
    2745         370 :             switch (data[0]) {
    2746             :             case 0x01:         /* Server allows us to send HB requests */
    2747         370 :                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
    2748         370 :                 break;
    2749             :             case 0x02:         /* Server doesn't accept HB requests */
    2750           0 :                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
    2751           0 :                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
    2752           0 :                 break;
    2753             :             default:
    2754           0 :                 *al = SSL_AD_ILLEGAL_PARAMETER;
    2755           0 :                 return 0;
    2756             :             }
    2757             :         }
    2758             : # endif
    2759             : # ifndef OPENSSL_NO_SRTP
    2760           0 :         else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) {
    2761           0 :             if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al))
    2762             :                 return 0;
    2763             :         }
    2764             : # endif
    2765             :         /*
    2766             :          * If this extension type was not otherwise handled, but matches a
    2767             :          * custom_cli_ext_record, then send it to the c callback
    2768             :          */
    2769           0 :         else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
    2770             :             return 0;
    2771             : 
    2772             :         data += size;
    2773             :     }
    2774             : 
    2775         370 :     if (data != d + n) {
    2776           0 :         *al = SSL_AD_DECODE_ERROR;
    2777           0 :         return 0;
    2778             :     }
    2779             : 
    2780         370 :     if (!s->hit && tlsext_servername == 1) {
    2781         370 :         if (s->tlsext_hostname) {
    2782         370 :             if (s->session->tlsext_hostname == NULL) {
    2783         370 :                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
    2784         370 :                 if (!s->session->tlsext_hostname) {
    2785           0 :                     *al = SSL_AD_UNRECOGNIZED_NAME;
    2786           0 :                     return 0;
    2787             :                 }
    2788             :             } else {
    2789           0 :                 *al = SSL_AD_DECODE_ERROR;
    2790           0 :                 return 0;
    2791             :             }
    2792             :         }
    2793             :     }
    2794             : 
    2795         370 :     *p = data;
    2796             : 
    2797             :  ri_check:
    2798             : 
    2799             :     /*
    2800             :      * Determine if we need to see RI. Strictly speaking if we want to avoid
    2801             :      * an attack we should *always* see RI even on initial server hello
    2802             :      * because the client doesn't see any renegotiation during an attack.
    2803             :      * However this would mean we could not connect to any server which
    2804             :      * doesn't support RI so for the immediate future tolerate RI absence on
    2805             :      * initial connect only.
    2806             :      */
    2807         370 :     if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
    2808           0 :         && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
    2809           0 :         *al = SSL_AD_HANDSHAKE_FAILURE;
    2810           0 :         SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
    2811             :                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
    2812           0 :         return 0;
    2813             :     }
    2814             : 
    2815             :     return 1;
    2816             : }
    2817             : 
    2818         373 : int ssl_prepare_clienthello_tlsext(SSL *s)
    2819             : {
    2820             : 
    2821             : # ifdef TLSEXT_TYPE_opaque_prf_input
    2822             :     {
    2823             :         int r = 1;
    2824             : 
    2825             :         if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
    2826             :             r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
    2827             :                                                          s->
    2828             :                                                          ctx->tlsext_opaque_prf_input_callback_arg);
    2829             :             if (!r)
    2830             :                 return -1;
    2831             :         }
    2832             : 
    2833             :         if (s->tlsext_opaque_prf_input != NULL) {
    2834             :             if (s->s3->client_opaque_prf_input != NULL) {
    2835             :                 /* shouldn't really happen */
    2836             :                 OPENSSL_free(s->s3->client_opaque_prf_input);
    2837             :             }
    2838             : 
    2839             :             if (s->tlsext_opaque_prf_input_len == 0) {
    2840             :                 /* dummy byte just to get non-NULL */
    2841             :                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
    2842             :             } else {
    2843             :                 s->s3->client_opaque_prf_input =
    2844             :                     BUF_memdup(s->tlsext_opaque_prf_input,
    2845             :                                s->tlsext_opaque_prf_input_len);
    2846             :             }
    2847             :             if (s->s3->client_opaque_prf_input == NULL) {
    2848             :                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,
    2849             :                        ERR_R_MALLOC_FAILURE);
    2850             :                 return -1;
    2851             :             }
    2852             :             s->s3->client_opaque_prf_input_len =
    2853             :                 s->tlsext_opaque_prf_input_len;
    2854             :         }
    2855             : 
    2856             :         if (r == 2)
    2857             :             /*
    2858             :              * at callback's request, insist on receiving an appropriate
    2859             :              * server opaque PRF input
    2860             :              */
    2861             :             s->s3->server_opaque_prf_input_len =
    2862             :                 s->tlsext_opaque_prf_input_len;
    2863             :     }
    2864             : # endif
    2865             : 
    2866         373 :     return 1;
    2867             : }
    2868             : 
    2869         373 : int ssl_prepare_serverhello_tlsext(SSL *s)
    2870             : {
    2871         373 :     return 1;
    2872             : }
    2873             : 
    2874         373 : static int ssl_check_clienthello_tlsext_early(SSL *s)
    2875             : {
    2876             :     int ret = SSL_TLSEXT_ERR_NOACK;
    2877         373 :     int al = SSL_AD_UNRECOGNIZED_NAME;
    2878             : 
    2879             : # ifndef OPENSSL_NO_EC
    2880             :     /*
    2881             :      * The handling of the ECPointFormats extension is done elsewhere, namely
    2882             :      * in ssl3_choose_cipher in s3_lib.c.
    2883             :      */
    2884             :     /*
    2885             :      * The handling of the EllipticCurves extension is done elsewhere, namely
    2886             :      * in ssl3_choose_cipher in s3_lib.c.
    2887             :      */
    2888             : # endif
    2889             : 
    2890         373 :     if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
    2891         373 :         ret =
    2892         373 :             s->ctx->tlsext_servername_callback(s, &al,
    2893             :                                                s->ctx->tlsext_servername_arg);
    2894           0 :     else if (s->initial_ctx != NULL
    2895           0 :              && s->initial_ctx->tlsext_servername_callback != 0)
    2896           0 :         ret =
    2897           0 :             s->initial_ctx->tlsext_servername_callback(s, &al,
    2898             :                                                        s->
    2899             :                                                        initial_ctx->tlsext_servername_arg);
    2900             : 
    2901             : # ifdef TLSEXT_TYPE_opaque_prf_input
    2902             :     {
    2903             :         /*
    2904             :          * This sort of belongs into ssl_prepare_serverhello_tlsext(), but we
    2905             :          * might be sending an alert in response to the client hello, so this
    2906             :          * has to happen here in ssl_check_clienthello_tlsext_early().
    2907             :          */
    2908             : 
    2909             :         int r = 1;
    2910             : 
    2911             :         if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
    2912             :             r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
    2913             :                                                          s->
    2914             :                                                          ctx->tlsext_opaque_prf_input_callback_arg);
    2915             :             if (!r) {
    2916             :                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
    2917             :                 al = SSL_AD_INTERNAL_ERROR;
    2918             :                 goto err;
    2919             :             }
    2920             :         }
    2921             : 
    2922             :         if (s->s3->server_opaque_prf_input != NULL) {
    2923             :             /* shouldn't really happen */
    2924             :             OPENSSL_free(s->s3->server_opaque_prf_input);
    2925             :         }
    2926             :         s->s3->server_opaque_prf_input = NULL;
    2927             : 
    2928             :         if (s->tlsext_opaque_prf_input != NULL) {
    2929             :             if (s->s3->client_opaque_prf_input != NULL &&
    2930             :                 s->s3->client_opaque_prf_input_len ==
    2931             :                 s->tlsext_opaque_prf_input_len) {
    2932             :                 /*
    2933             :                  * can only use this extension if we have a server opaque PRF
    2934             :                  * input of the same length as the client opaque PRF input!
    2935             :                  */
    2936             : 
    2937             :                 if (s->tlsext_opaque_prf_input_len == 0) {
    2938             :                     /* dummy byte just to get non-NULL */
    2939             :                     s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
    2940             :                 } else {
    2941             :                     s->s3->server_opaque_prf_input =
    2942             :                         BUF_memdup(s->tlsext_opaque_prf_input,
    2943             :                                    s->tlsext_opaque_prf_input_len);
    2944             :                 }
    2945             :                 if (s->s3->server_opaque_prf_input == NULL) {
    2946             :                     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
    2947             :                     al = SSL_AD_INTERNAL_ERROR;
    2948             :                     goto err;
    2949             :                 }
    2950             :                 s->s3->server_opaque_prf_input_len =
    2951             :                     s->tlsext_opaque_prf_input_len;
    2952             :             }
    2953             :         }
    2954             : 
    2955             :         if (r == 2 && s->s3->server_opaque_prf_input == NULL) {
    2956             :             /*
    2957             :              * The callback wants to enforce use of the extension, but we
    2958             :              * can't do that with the client opaque PRF input; abort the
    2959             :              * handshake.
    2960             :              */
    2961             :             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
    2962             :             al = SSL_AD_HANDSHAKE_FAILURE;
    2963             :         }
    2964             :     }
    2965             : 
    2966             :  err:
    2967             : # endif
    2968         373 :     switch (ret) {
    2969             :     case SSL_TLSEXT_ERR_ALERT_FATAL:
    2970           0 :         ssl3_send_alert(s, SSL3_AL_FATAL, al);
    2971           0 :         return -1;
    2972             : 
    2973             :     case SSL_TLSEXT_ERR_ALERT_WARNING:
    2974           0 :         ssl3_send_alert(s, SSL3_AL_WARNING, al);
    2975           0 :         return 1;
    2976             : 
    2977             :     case SSL_TLSEXT_ERR_NOACK:
    2978           0 :         s->servername_done = 0;
    2979             :     default:
    2980             :         return 1;
    2981             :     }
    2982             : }
    2983             : 
    2984         373 : int tls1_set_server_sigalgs(SSL *s)
    2985             : {
    2986             :     int al;
    2987             :     size_t i;
    2988             :     /* Clear any shared sigtnature algorithms */
    2989         373 :     if (s->cert->shared_sigalgs) {
    2990           0 :         OPENSSL_free(s->cert->shared_sigalgs);
    2991           0 :         s->cert->shared_sigalgs = NULL;
    2992           0 :         s->cert->shared_sigalgslen = 0;
    2993             :     }
    2994             :     /* Clear certificate digests and validity flags */
    2995        2984 :     for (i = 0; i < SSL_PKEY_NUM; i++) {
    2996        2984 :         s->cert->pkeys[i].digest = NULL;
    2997        2984 :         s->cert->pkeys[i].valid_flags = 0;
    2998             :     }
    2999             : 
    3000             :     /* If sigalgs received process it. */
    3001         373 :     if (s->cert->peer_sigalgs) {
    3002         373 :         if (!tls1_process_sigalgs(s)) {
    3003           0 :             SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
    3004             :             al = SSL_AD_INTERNAL_ERROR;
    3005           0 :             goto err;
    3006             :         }
    3007             :         /* Fatal error is no shared signature algorithms */
    3008         373 :         if (!s->cert->shared_sigalgs) {
    3009           0 :             SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
    3010             :                    SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
    3011             :             al = SSL_AD_ILLEGAL_PARAMETER;
    3012           0 :             goto err;
    3013             :         }
    3014             :     } else
    3015           0 :         ssl_cert_set_default_md(s->cert);
    3016             :     return 1;
    3017             :  err:
    3018           0 :     ssl3_send_alert(s, SSL3_AL_FATAL, al);
    3019           0 :     return 0;
    3020             : }
    3021             : 
    3022         373 : int ssl_check_clienthello_tlsext_late(SSL *s)
    3023             : {
    3024             :     int ret = SSL_TLSEXT_ERR_OK;
    3025             :     int al;
    3026             : 
    3027             :     /*
    3028             :      * If status request then ask callback what to do. Note: this must be
    3029             :      * called after servername callbacks in case the certificate has changed,
    3030             :      * and must be called after the cipher has been chosen because this may
    3031             :      * influence which certificate is sent
    3032             :      */
    3033         373 :     if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) {
    3034             :         int r;
    3035             :         CERT_PKEY *certpkey;
    3036           0 :         certpkey = ssl_get_server_send_pkey(s);
    3037             :         /* If no certificate can't return certificate status */
    3038           0 :         if (certpkey == NULL) {
    3039           0 :             s->tlsext_status_expected = 0;
    3040           0 :             return 1;
    3041             :         }
    3042             :         /*
    3043             :          * Set current certificate to one we will use so SSL_get_certificate
    3044             :          * et al can pick it up.
    3045             :          */
    3046           0 :         s->cert->key = certpkey;
    3047           0 :         r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
    3048           0 :         switch (r) {
    3049             :             /* We don't want to send a status request response */
    3050             :         case SSL_TLSEXT_ERR_NOACK:
    3051           0 :             s->tlsext_status_expected = 0;
    3052           0 :             break;
    3053             :             /* status request response should be sent */
    3054             :         case SSL_TLSEXT_ERR_OK:
    3055           0 :             if (s->tlsext_ocsp_resp)
    3056           0 :                 s->tlsext_status_expected = 1;
    3057             :             else
    3058           0 :                 s->tlsext_status_expected = 0;
    3059             :             break;
    3060             :             /* something bad happened */
    3061             :         case SSL_TLSEXT_ERR_ALERT_FATAL:
    3062             :             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
    3063             :             al = SSL_AD_INTERNAL_ERROR;
    3064           0 :             goto err;
    3065             :         }
    3066             :     } else
    3067         373 :         s->tlsext_status_expected = 0;
    3068             : 
    3069             :  err:
    3070         373 :     switch (ret) {
    3071             :     case SSL_TLSEXT_ERR_ALERT_FATAL:
    3072           0 :         ssl3_send_alert(s, SSL3_AL_FATAL, al);
    3073           0 :         return -1;
    3074             : 
    3075             :     case SSL_TLSEXT_ERR_ALERT_WARNING:
    3076           0 :         ssl3_send_alert(s, SSL3_AL_WARNING, al);
    3077           0 :         return 1;
    3078             : 
    3079             :     default:
    3080             :         return 1;
    3081             :     }
    3082             : }
    3083             : 
    3084         370 : int ssl_check_serverhello_tlsext(SSL *s)
    3085             : {
    3086             :     int ret = SSL_TLSEXT_ERR_NOACK;
    3087         370 :     int al = SSL_AD_UNRECOGNIZED_NAME;
    3088             : 
    3089             : # ifndef OPENSSL_NO_EC
    3090             :     /*
    3091             :      * If we are client and using an elliptic curve cryptography cipher
    3092             :      * suite, then if server returns an EC point formats lists extension it
    3093             :      * must contain uncompressed.
    3094             :      */
    3095         370 :     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
    3096         370 :     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
    3097         370 :     if ((s->tlsext_ecpointformatlist != NULL)
    3098           0 :         && (s->tlsext_ecpointformatlist_length > 0)
    3099           0 :         && (s->session->tlsext_ecpointformatlist != NULL)
    3100           0 :         && (s->session->tlsext_ecpointformatlist_length > 0)
    3101           0 :         && ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
    3102           0 :             || (alg_a & SSL_aECDSA))) {
    3103             :         /* we are using an ECC cipher */
    3104             :         size_t i;
    3105             :         unsigned char *list;
    3106             :         int found_uncompressed = 0;
    3107             :         list = s->session->tlsext_ecpointformatlist;
    3108           0 :         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) {
    3109           0 :             if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) {
    3110             :                 found_uncompressed = 1;
    3111             :                 break;
    3112             :             }
    3113             :         }
    3114           0 :         if (!found_uncompressed) {
    3115           0 :             SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,
    3116             :                    SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
    3117           0 :             return -1;
    3118             :         }
    3119             :     }
    3120             :     ret = SSL_TLSEXT_ERR_OK;
    3121             : # endif                         /* OPENSSL_NO_EC */
    3122             : 
    3123         370 :     if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
    3124           0 :         ret =
    3125           0 :             s->ctx->tlsext_servername_callback(s, &al,
    3126             :                                                s->ctx->tlsext_servername_arg);
    3127         370 :     else if (s->initial_ctx != NULL
    3128         370 :              && s->initial_ctx->tlsext_servername_callback != 0)
    3129           0 :         ret =
    3130           0 :             s->initial_ctx->tlsext_servername_callback(s, &al,
    3131             :                                                        s->
    3132             :                                                        initial_ctx->tlsext_servername_arg);
    3133             : 
    3134             : # ifdef TLSEXT_TYPE_opaque_prf_input
    3135             :     if (s->s3->server_opaque_prf_input_len > 0) {
    3136             :         /*
    3137             :          * This case may indicate that we, as a client, want to insist on
    3138             :          * using opaque PRF inputs. So first verify that we really have a
    3139             :          * value from the server too.
    3140             :          */
    3141             : 
    3142             :         if (s->s3->server_opaque_prf_input == NULL) {
    3143             :             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
    3144             :             al = SSL_AD_HANDSHAKE_FAILURE;
    3145             :         }
    3146             : 
    3147             :         /*
    3148             :          * Anytime the server *has* sent an opaque PRF input, we need to
    3149             :          * check that we have a client opaque PRF input of the same size.
    3150             :          */
    3151             :         if (s->s3->client_opaque_prf_input == NULL ||
    3152             :             s->s3->client_opaque_prf_input_len !=
    3153             :             s->s3->server_opaque_prf_input_len) {
    3154             :             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
    3155             :             al = SSL_AD_ILLEGAL_PARAMETER;
    3156             :         }
    3157             :     }
    3158             : # endif
    3159             : 
    3160             :     /*
    3161             :      * If we've requested certificate status and we wont get one tell the
    3162             :      * callback
    3163             :      */
    3164         370 :     if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
    3165           0 :         && s->ctx && s->ctx->tlsext_status_cb) {
    3166             :         int r;
    3167             :         /*
    3168             :          * Set resp to NULL, resplen to -1 so callback knows there is no
    3169             :          * response.
    3170             :          */
    3171           0 :         if (s->tlsext_ocsp_resp) {
    3172           0 :             OPENSSL_free(s->tlsext_ocsp_resp);
    3173           0 :             s->tlsext_ocsp_resp = NULL;
    3174             :         }
    3175           0 :         s->tlsext_ocsp_resplen = -1;
    3176           0 :         r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
    3177           0 :         if (r == 0) {
    3178           0 :             al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
    3179             :             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
    3180             :         }
    3181           0 :         if (r < 0) {
    3182           0 :             al = SSL_AD_INTERNAL_ERROR;
    3183             :             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
    3184             :         }
    3185             :     }
    3186             : 
    3187         370 :     switch (ret) {
    3188             :     case SSL_TLSEXT_ERR_ALERT_FATAL:
    3189           0 :         ssl3_send_alert(s, SSL3_AL_FATAL, al);
    3190           0 :         return -1;
    3191             : 
    3192             :     case SSL_TLSEXT_ERR_ALERT_WARNING:
    3193           0 :         ssl3_send_alert(s, SSL3_AL_WARNING, al);
    3194           0 :         return 1;
    3195             : 
    3196             :     case SSL_TLSEXT_ERR_NOACK:
    3197           0 :         s->servername_done = 0;
    3198             :     default:
    3199             :         return 1;
    3200             :     }
    3201             : }
    3202             : 
    3203         370 : int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d,
    3204             :                                  int n)
    3205             : {
    3206         370 :     int al = -1;
    3207         370 :     if (s->version < SSL3_VERSION)
    3208             :         return 1;
    3209         370 :     if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) {
    3210           0 :         ssl3_send_alert(s, SSL3_AL_FATAL, al);
    3211           0 :         return 0;
    3212             :     }
    3213             : 
    3214         370 :     if (ssl_check_serverhello_tlsext(s) <= 0) {
    3215           0 :         SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_SERVERHELLO_TLSEXT);
    3216           0 :         return 0;
    3217             :     }
    3218             :     return 1;
    3219             : }
    3220             : 
    3221             : /*-
    3222             :  * Since the server cache lookup is done early on in the processing of the
    3223             :  * ClientHello, and other operations depend on the result, we need to handle
    3224             :  * any TLS session ticket extension at the same time.
    3225             :  *
    3226             :  *   session_id: points at the session ID in the ClientHello. This code will
    3227             :  *       read past the end of this in order to parse out the session ticket
    3228             :  *       extension, if any.
    3229             :  *   len: the length of the session ID.
    3230             :  *   limit: a pointer to the first byte after the ClientHello.
    3231             :  *   ret: (output) on return, if a ticket was decrypted, then this is set to
    3232             :  *       point to the resulting session.
    3233             :  *
    3234             :  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
    3235             :  * ciphersuite, in which case we have no use for session tickets and one will
    3236             :  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
    3237             :  *
    3238             :  * Returns:
    3239             :  *   -1: fatal error, either from parsing or decrypting the ticket.
    3240             :  *    0: no ticket was found (or was ignored, based on settings).
    3241             :  *    1: a zero length extension was found, indicating that the client supports
    3242             :  *       session tickets but doesn't currently have one to offer.
    3243             :  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
    3244             :  *       couldn't be decrypted because of a non-fatal error.
    3245             :  *    3: a ticket was successfully decrypted and *ret was set.
    3246             :  *
    3247             :  * Side effects:
    3248             :  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
    3249             :  *   a new session ticket to the client because the client indicated support
    3250             :  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
    3251             :  *   a session ticket or we couldn't use the one it gave us, or if
    3252             :  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
    3253             :  *   Otherwise, s->tlsext_ticket_expected is set to 0.
    3254             :  */
    3255         373 : int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
    3256             :                         const unsigned char *limit, SSL_SESSION **ret)
    3257             : {
    3258             :     /* Point after session ID in client hello */
    3259         373 :     const unsigned char *p = session_id + len;
    3260             :     unsigned short i;
    3261             : 
    3262         373 :     *ret = NULL;
    3263         373 :     s->tlsext_ticket_expected = 0;
    3264             : 
    3265             :     /*
    3266             :      * If tickets disabled behave as if no ticket present to permit stateful
    3267             :      * resumption.
    3268             :      */
    3269         373 :     if (SSL_get_options(s) & SSL_OP_NO_TICKET)
    3270             :         return 0;
    3271         373 :     if ((s->version <= SSL3_VERSION) || !limit)
    3272             :         return 0;
    3273         373 :     if (p >= limit)
    3274             :         return -1;
    3275             :     /* Skip past DTLS cookie */
    3276         373 :     if (SSL_IS_DTLS(s)) {
    3277           0 :         i = *(p++);
    3278           0 :         p += i;
    3279           0 :         if (p >= limit)
    3280             :             return -1;
    3281             :     }
    3282             :     /* Skip past cipher list */
    3283         373 :     n2s(p, i);
    3284         373 :     p += i;
    3285         373 :     if (p >= limit)
    3286             :         return -1;
    3287             :     /* Skip past compression algorithm list */
    3288         373 :     i = *(p++);
    3289         373 :     p += i;
    3290         373 :     if (p > limit)
    3291             :         return -1;
    3292             :     /* Now at start of extensions */
    3293         373 :     if ((p + 2) >= limit)
    3294             :         return 0;
    3295             :     n2s(p, i);
    3296        1492 :     while ((p + 4) <= limit) {
    3297             :         unsigned short type, size;
    3298        1492 :         n2s(p, type);
    3299        1492 :         n2s(p, size);
    3300        1492 :         if (p + size > limit)
    3301             :             return 0;
    3302        1492 :         if (type == TLSEXT_TYPE_session_ticket) {
    3303             :             int r;
    3304         373 :             if (size == 0) {
    3305             :                 /*
    3306             :                  * The client will accept a ticket but doesn't currently have
    3307             :                  * one.
    3308             :                  */
    3309         373 :                 s->tlsext_ticket_expected = 1;
    3310         373 :                 return 1;
    3311             :             }
    3312           0 :             if (s->tls_session_secret_cb) {
    3313             :                 /*
    3314             :                  * Indicate that the ticket couldn't be decrypted rather than
    3315             :                  * generating the session from ticket now, trigger
    3316             :                  * abbreviated handshake based on external mechanism to
    3317             :                  * calculate the master secret later.
    3318             :                  */
    3319             :                 return 2;
    3320             :             }
    3321           0 :             r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
    3322           0 :             switch (r) {
    3323             :             case 2:            /* ticket couldn't be decrypted */
    3324           0 :                 s->tlsext_ticket_expected = 1;
    3325           0 :                 return 2;
    3326             :             case 3:            /* ticket was decrypted */
    3327           0 :                 return r;
    3328             :             case 4:            /* ticket decrypted but need to renew */
    3329           0 :                 s->tlsext_ticket_expected = 1;
    3330           0 :                 return 3;
    3331             :             default:           /* fatal error */
    3332             :                 return -1;
    3333             :             }
    3334             :         }
    3335             :         p += size;
    3336             :     }
    3337             :     return 0;
    3338             : }
    3339             : 
    3340             : /*-
    3341             :  * tls_decrypt_ticket attempts to decrypt a session ticket.
    3342             :  *
    3343             :  *   etick: points to the body of the session ticket extension.
    3344             :  *   eticklen: the length of the session tickets extenion.
    3345             :  *   sess_id: points at the session ID.
    3346             :  *   sesslen: the length of the session ID.
    3347             :  *   psess: (output) on return, if a ticket was decrypted, then this is set to
    3348             :  *       point to the resulting session.
    3349             :  *
    3350             :  * Returns:
    3351             :  *   -1: fatal error, either from parsing or decrypting the ticket.
    3352             :  *    2: the ticket couldn't be decrypted.
    3353             :  *    3: a ticket was successfully decrypted and *psess was set.
    3354             :  *    4: same as 3, but the ticket needs to be renewed.
    3355             :  */
    3356           0 : static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
    3357             :                               int eticklen, const unsigned char *sess_id,
    3358             :                               int sesslen, SSL_SESSION **psess)
    3359             : {
    3360             :     SSL_SESSION *sess;
    3361             :     unsigned char *sdec;
    3362             :     const unsigned char *p;
    3363             :     int slen, mlen, renew_ticket = 0;
    3364             :     unsigned char tick_hmac[EVP_MAX_MD_SIZE];
    3365             :     HMAC_CTX hctx;
    3366             :     EVP_CIPHER_CTX ctx;
    3367           0 :     SSL_CTX *tctx = s->initial_ctx;
    3368             :     /* Need at least keyname + iv + some encrypted data */
    3369           0 :     if (eticklen < 48)
    3370             :         return 2;
    3371             :     /* Initialize session ticket encryption and HMAC contexts */
    3372           0 :     HMAC_CTX_init(&hctx);
    3373           0 :     EVP_CIPHER_CTX_init(&ctx);
    3374           0 :     if (tctx->tlsext_ticket_key_cb) {
    3375             :         unsigned char *nctick = (unsigned char *)etick;
    3376           0 :         int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
    3377             :                                             &ctx, &hctx, 0);
    3378           0 :         if (rv < 0)
    3379             :             return -1;
    3380           0 :         if (rv == 0)
    3381             :             return 2;
    3382           0 :         if (rv == 2)
    3383             :             renew_ticket = 1;
    3384             :     } else {
    3385             :         /* Check key name matches */
    3386           0 :         if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
    3387             :             return 2;
    3388           0 :         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
    3389             :                      tlsext_tick_md(), NULL);
    3390           0 :         EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
    3391           0 :                            tctx->tlsext_tick_aes_key, etick + 16);
    3392             :     }
    3393             :     /*
    3394             :      * Attempt to process session ticket, first conduct sanity and integrity
    3395             :      * checks on ticket.
    3396             :      */
    3397           0 :     mlen = HMAC_size(&hctx);
    3398           0 :     if (mlen < 0) {
    3399           0 :         EVP_CIPHER_CTX_cleanup(&ctx);
    3400           0 :         return -1;
    3401             :     }
    3402           0 :     eticklen -= mlen;
    3403             :     /* Check HMAC of encrypted ticket */
    3404           0 :     HMAC_Update(&hctx, etick, eticklen);
    3405           0 :     HMAC_Final(&hctx, tick_hmac, NULL);
    3406           0 :     HMAC_CTX_cleanup(&hctx);
    3407           0 :     if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
    3408           0 :         EVP_CIPHER_CTX_cleanup(&ctx);
    3409           0 :         return 2;
    3410             :     }
    3411             :     /* Attempt to decrypt session data */
    3412             :     /* Move p after IV to start of encrypted ticket, update length */
    3413           0 :     p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
    3414           0 :     eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
    3415           0 :     sdec = OPENSSL_malloc(eticklen);
    3416           0 :     if (!sdec) {
    3417           0 :         EVP_CIPHER_CTX_cleanup(&ctx);
    3418           0 :         return -1;
    3419             :     }
    3420           0 :     EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
    3421           0 :     if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) {
    3422           0 :         EVP_CIPHER_CTX_cleanup(&ctx);
    3423           0 :         OPENSSL_free(sdec);
    3424           0 :         return 2;
    3425             :     }
    3426           0 :     slen += mlen;
    3427           0 :     EVP_CIPHER_CTX_cleanup(&ctx);
    3428           0 :     p = sdec;
    3429             : 
    3430           0 :     sess = d2i_SSL_SESSION(NULL, &p, slen);
    3431           0 :     OPENSSL_free(sdec);
    3432           0 :     if (sess) {
    3433             :         /*
    3434             :          * The session ID, if non-empty, is used by some clients to detect
    3435             :          * that the ticket has been accepted. So we copy it to the session
    3436             :          * structure. If it is empty set length to zero as required by
    3437             :          * standard.
    3438             :          */
    3439           0 :         if (sesslen)
    3440           0 :             memcpy(sess->session_id, sess_id, sesslen);
    3441           0 :         sess->session_id_length = sesslen;
    3442           0 :         *psess = sess;
    3443           0 :         if (renew_ticket)
    3444             :             return 4;
    3445             :         else
    3446           0 :             return 3;
    3447             :     }
    3448           0 :     ERR_clear_error();
    3449             :     /*
    3450             :      * For session parse failure, indicate that we need to send a new ticket.
    3451             :      */
    3452           0 :     return 2;
    3453             : }
    3454             : 
    3455             : /* Tables to translate from NIDs to TLS v1.2 ids */
    3456             : 
    3457             : typedef struct {
    3458             :     int nid;
    3459             :     int id;
    3460             : } tls12_lookup;
    3461             : 
    3462             : static tls12_lookup tls12_md[] = {
    3463             :     {NID_md5, TLSEXT_hash_md5},
    3464             :     {NID_sha1, TLSEXT_hash_sha1},
    3465             :     {NID_sha224, TLSEXT_hash_sha224},
    3466             :     {NID_sha256, TLSEXT_hash_sha256},
    3467             :     {NID_sha384, TLSEXT_hash_sha384},
    3468             :     {NID_sha512, TLSEXT_hash_sha512}
    3469             : };
    3470             : 
    3471             : static tls12_lookup tls12_sig[] = {
    3472             :     {EVP_PKEY_RSA, TLSEXT_signature_rsa},
    3473             :     {EVP_PKEY_DSA, TLSEXT_signature_dsa},
    3474             :     {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
    3475             : };
    3476             : 
    3477             : static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
    3478             : {
    3479             :     size_t i;
    3480        1865 :     for (i = 0; i < tlen; i++) {
    3481        2981 :         if (table[i].nid == nid)
    3482        1116 :             return table[i].id;
    3483             :     }
    3484             :     return -1;
    3485             : }
    3486             : 
    3487             : static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
    3488             : {
    3489             :     size_t i;
    3490       22380 :     for (i = 0; i < tlen; i++) {
    3491       33570 :         if ((table[i].id) == id)
    3492       11190 :             return table[i].nid;
    3493             :     }
    3494             :     return NID_undef;
    3495             : }
    3496             : 
    3497         373 : int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk,
    3498             :                          const EVP_MD *md)
    3499             : {
    3500             :     int sig_id, md_id;
    3501         373 :     if (!md)
    3502             :         return 0;
    3503         373 :     md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
    3504             :                           sizeof(tls12_md) / sizeof(tls12_lookup));
    3505         373 :     if (md_id == -1)
    3506             :         return 0;
    3507             :     sig_id = tls12_get_sigid(pk);
    3508         373 :     if (sig_id == -1)
    3509             :         return 0;
    3510         373 :     p[0] = (unsigned char)md_id;
    3511         373 :     p[1] = (unsigned char)sig_id;
    3512         373 :     return 1;
    3513             : }
    3514             : 
    3515           0 : int tls12_get_sigid(const EVP_PKEY *pk)
    3516             : {
    3517         743 :     return tls12_find_id(pk->type, tls12_sig,
    3518             :                          sizeof(tls12_sig) / sizeof(tls12_lookup));
    3519             : }
    3520             : 
    3521       12679 : const EVP_MD *tls12_get_hash(unsigned char hash_alg)
    3522             : {
    3523       12679 :     switch (hash_alg) {
    3524             : # ifndef OPENSSL_NO_MD5
    3525             :     case TLSEXT_hash_md5:
    3526             : #  ifdef OPENSSL_FIPS
    3527             :         if (FIPS_mode())
    3528             :             return NULL;
    3529             : #  endif
    3530           0 :         return EVP_md5();
    3531             : # endif
    3532             : # ifndef OPENSSL_NO_SHA
    3533             :     case TLSEXT_hash_sha1:
    3534        2238 :         return EVP_sha1();
    3535             : # endif
    3536             : # ifndef OPENSSL_NO_SHA256
    3537             :     case TLSEXT_hash_sha224:
    3538        2238 :         return EVP_sha224();
    3539             : 
    3540             :     case TLSEXT_hash_sha256:
    3541        2238 :         return EVP_sha256();
    3542             : # endif
    3543             : # ifndef OPENSSL_NO_SHA512
    3544             :     case TLSEXT_hash_sha384:
    3545        2238 :         return EVP_sha384();
    3546             : 
    3547             :     case TLSEXT_hash_sha512:
    3548        3727 :         return EVP_sha512();
    3549             : # endif
    3550             :     default:
    3551             :         return NULL;
    3552             : 
    3553             :     }
    3554             : }
    3555             : 
    3556             : static int tls12_get_pkey_idx(unsigned char sig_alg)
    3557             : {
    3558             :     switch (sig_alg) {
    3559             : # ifndef OPENSSL_NO_RSA
    3560             :     case TLSEXT_signature_rsa:
    3561             :         return SSL_PKEY_RSA_SIGN;
    3562             : # endif
    3563             : # ifndef OPENSSL_NO_DSA
    3564             :     case TLSEXT_signature_dsa:
    3565             :         return SSL_PKEY_DSA_SIGN;
    3566             : # endif
    3567             : # ifndef OPENSSL_NO_ECDSA
    3568             :     case TLSEXT_signature_ecdsa:
    3569             :         return SSL_PKEY_ECC;
    3570             : # endif
    3571             :     }
    3572             :     return -1;
    3573             : }
    3574             : 
    3575             : /* Convert TLS 1.2 signature algorithm extension values into NIDs */
    3576        5595 : static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
    3577             :                                int *psignhash_nid, const unsigned char *data)
    3578             : {
    3579             :     int sign_nid = 0, hash_nid = 0;
    3580        5595 :     if (!phash_nid && !psign_nid && !psignhash_nid)
    3581        5595 :         return;
    3582        5595 :     if (phash_nid || psignhash_nid) {
    3583        5595 :         hash_nid = tls12_find_nid(data[0], tls12_md,
    3584             :                                   sizeof(tls12_md) / sizeof(tls12_lookup));
    3585        5595 :         if (phash_nid)
    3586        5595 :             *phash_nid = hash_nid;
    3587             :     }
    3588        5595 :     if (psign_nid || psignhash_nid) {
    3589        5595 :         sign_nid = tls12_find_nid(data[1], tls12_sig,
    3590             :                                   sizeof(tls12_sig) / sizeof(tls12_lookup));
    3591        5595 :         if (psign_nid)
    3592        5595 :             *psign_nid = sign_nid;
    3593             :     }
    3594        5595 :     if (psignhash_nid) {
    3595        5595 :         if (sign_nid && hash_nid)
    3596        5595 :             OBJ_find_sigid_by_algs(psignhash_nid, hash_nid, sign_nid);
    3597             :         else
    3598           0 :             *psignhash_nid = NID_undef;
    3599             :     }
    3600             : }
    3601             : 
    3602             : /* Given preference and allowed sigalgs set shared sigalgs */
    3603         746 : static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
    3604             :                                    const unsigned char *pref, size_t preflen,
    3605             :                                    const unsigned char *allow,
    3606             :                                    size_t allowlen)
    3607             : {
    3608             :     const unsigned char *ptmp, *atmp;
    3609             :     size_t i, j, nmatch = 0;
    3610       11936 :     for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) {
    3611             :         /* Skip disabled hashes or signature algorithms */
    3612       11190 :         if (tls12_get_hash(ptmp[0]) == NULL)
    3613           0 :             continue;
    3614       11190 :         if (tls12_get_pkey_idx(ptmp[1]) == -1)
    3615           0 :             continue;
    3616       78330 :         for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) {
    3617       89520 :             if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) {
    3618       11190 :                 nmatch++;
    3619       11190 :                 if (shsig) {
    3620        5595 :                     shsig->rhash = ptmp[0];
    3621        5595 :                     shsig->rsign = ptmp[1];
    3622        5595 :                     tls1_lookup_sigalg(&shsig->hash_nid,
    3623             :                                        &shsig->sign_nid,
    3624             :                                        &shsig->signandhash_nid, ptmp);
    3625        5595 :                     shsig++;
    3626             :                 }
    3627             :                 break;
    3628             :             }
    3629             :         }
    3630             :     }
    3631         746 :     return nmatch;
    3632             : }
    3633             : 
    3634             : /* Set shared signature algorithms for SSL structures */
    3635         373 : static int tls1_set_shared_sigalgs(SSL *s)
    3636             : {
    3637             :     const unsigned char *pref, *allow, *conf;
    3638             :     size_t preflen, allowlen, conflen;
    3639             :     size_t nmatch;
    3640             :     TLS_SIGALGS *salgs = NULL;
    3641         373 :     CERT *c = s->cert;
    3642         373 :     unsigned int is_suiteb = tls1_suiteb(s);
    3643         373 :     if (c->shared_sigalgs) {
    3644           0 :         OPENSSL_free(c->shared_sigalgs);
    3645           0 :         c->shared_sigalgs = NULL;
    3646           0 :         c->shared_sigalgslen = 0;
    3647             :     }
    3648             :     /* If client use client signature algorithms if not NULL */
    3649         373 :     if (!s->server && c->client_sigalgs && !is_suiteb) {
    3650           0 :         conf = c->client_sigalgs;
    3651           0 :         conflen = c->client_sigalgslen;
    3652         373 :     } else if (c->conf_sigalgs && !is_suiteb) {
    3653           0 :         conf = c->conf_sigalgs;
    3654           0 :         conflen = c->conf_sigalgslen;
    3655             :     } else
    3656         373 :         conflen = tls12_get_psigalgs(s, &conf);
    3657         373 :     if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
    3658           0 :         pref = conf;
    3659             :         preflen = conflen;
    3660           0 :         allow = c->peer_sigalgs;
    3661           0 :         allowlen = c->peer_sigalgslen;
    3662             :     } else {
    3663         373 :         allow = conf;
    3664             :         allowlen = conflen;
    3665         373 :         pref = c->peer_sigalgs;
    3666         373 :         preflen = c->peer_sigalgslen;
    3667             :     }
    3668         373 :     nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
    3669         373 :     if (nmatch) {
    3670         373 :         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
    3671         373 :         if (!salgs)
    3672             :             return 0;
    3673         373 :         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
    3674             :     } else {
    3675             :         salgs = NULL;
    3676             :     }
    3677         373 :     c->shared_sigalgs = salgs;
    3678         373 :     c->shared_sigalgslen = nmatch;
    3679         373 :     return 1;
    3680             : }
    3681             : 
    3682             : /* Set preferred digest for each key type */
    3683             : 
    3684         373 : int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
    3685             : {
    3686         373 :     CERT *c = s->cert;
    3687             :     /* Extension ignored for inappropriate versions */
    3688         373 :     if (!SSL_USE_SIGALGS(s))
    3689             :         return 1;
    3690             :     /* Should never happen */
    3691         373 :     if (!c)
    3692             :         return 0;
    3693             : 
    3694         373 :     if (c->peer_sigalgs)
    3695           0 :         OPENSSL_free(c->peer_sigalgs);
    3696         373 :     c->peer_sigalgs = OPENSSL_malloc(dsize);
    3697         373 :     if (!c->peer_sigalgs)
    3698             :         return 0;
    3699         373 :     c->peer_sigalgslen = dsize;
    3700             :     memcpy(c->peer_sigalgs, data, dsize);
    3701         373 :     return 1;
    3702             : }
    3703             : 
    3704         373 : int tls1_process_sigalgs(SSL *s)
    3705             : {
    3706             :     int idx;
    3707             :     size_t i;
    3708             :     const EVP_MD *md;
    3709         373 :     CERT *c = s->cert;
    3710             :     TLS_SIGALGS *sigptr;
    3711         373 :     if (!tls1_set_shared_sigalgs(s))
    3712             :         return 0;
    3713             : 
    3714             : # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
    3715             :     if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
    3716             :         /*
    3717             :          * Use first set signature preference to force message digest,
    3718             :          * ignoring any peer preferences.
    3719             :          */
    3720             :         const unsigned char *sigs = NULL;
    3721             :         if (s->server)
    3722             :             sigs = c->conf_sigalgs;
    3723             :         else
    3724             :             sigs = c->client_sigalgs;
    3725             :         if (sigs) {
    3726             :             idx = tls12_get_pkey_idx(sigs[1]);
    3727             :             md = tls12_get_hash(sigs[0]);
    3728             :             c->pkeys[idx].digest = md;
    3729             :             c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
    3730             :             if (idx == SSL_PKEY_RSA_SIGN) {
    3731             :                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
    3732             :                     CERT_PKEY_EXPLICIT_SIGN;
    3733             :                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
    3734             :             }
    3735             :         }
    3736             :     }
    3737             : # endif
    3738             : 
    3739        6341 :     for (i = 0, sigptr = c->shared_sigalgs;
    3740        5595 :          i < c->shared_sigalgslen; i++, sigptr++) {
    3741        5595 :         idx = tls12_get_pkey_idx(sigptr->rsign);
    3742        5595 :         if (idx > 0 && c->pkeys[idx].digest == NULL) {
    3743        1119 :             md = tls12_get_hash(sigptr->rhash);
    3744        1119 :             c->pkeys[idx].digest = md;
    3745        1119 :             c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
    3746        1119 :             if (idx == SSL_PKEY_RSA_SIGN) {
    3747         373 :                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
    3748             :                     CERT_PKEY_EXPLICIT_SIGN;
    3749         373 :                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
    3750             :             }
    3751             :         }
    3752             : 
    3753             :     }
    3754             :     /*
    3755             :      * In strict mode leave unset digests as NULL to indicate we can't use
    3756             :      * the certificate for signing.
    3757             :      */
    3758         373 :     if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
    3759             :         /*
    3760             :          * Set any remaining keys to default values. NOTE: if alg is not
    3761             :          * supported it stays as NULL.
    3762             :          */
    3763             : # ifndef OPENSSL_NO_DSA
    3764         373 :         if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
    3765           0 :             c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
    3766             : # endif
    3767             : # ifndef OPENSSL_NO_RSA
    3768         373 :         if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest) {
    3769           0 :             c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
    3770           0 :             c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
    3771             :         }
    3772             : # endif
    3773             : # ifndef OPENSSL_NO_ECDSA
    3774         373 :         if (!c->pkeys[SSL_PKEY_ECC].digest)
    3775           0 :             c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
    3776             : # endif
    3777             :     }
    3778             :     return 1;
    3779             : }
    3780             : 
    3781           0 : int SSL_get_sigalgs(SSL *s, int idx,
    3782             :                     int *psign, int *phash, int *psignhash,
    3783             :                     unsigned char *rsig, unsigned char *rhash)
    3784             : {
    3785           0 :     const unsigned char *psig = s->cert->peer_sigalgs;
    3786           0 :     if (psig == NULL)
    3787             :         return 0;
    3788           0 :     if (idx >= 0) {
    3789           0 :         idx <<= 1;
    3790           0 :         if (idx >= (int)s->cert->peer_sigalgslen)
    3791             :             return 0;
    3792           0 :         psig += idx;
    3793           0 :         if (rhash)
    3794           0 :             *rhash = psig[0];
    3795           0 :         if (rsig)
    3796           0 :             *rsig = psig[1];
    3797           0 :         tls1_lookup_sigalg(phash, psign, psignhash, psig);
    3798             :     }
    3799           0 :     return s->cert->peer_sigalgslen / 2;
    3800             : }
    3801             : 
    3802           0 : int SSL_get_shared_sigalgs(SSL *s, int idx,
    3803             :                            int *psign, int *phash, int *psignhash,
    3804             :                            unsigned char *rsig, unsigned char *rhash)
    3805             : {
    3806           0 :     TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
    3807           0 :     if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
    3808             :         return 0;
    3809           0 :     shsigalgs += idx;
    3810           0 :     if (phash)
    3811           0 :         *phash = shsigalgs->hash_nid;
    3812           0 :     if (psign)
    3813           0 :         *psign = shsigalgs->sign_nid;
    3814           0 :     if (psignhash)
    3815           0 :         *psignhash = shsigalgs->signandhash_nid;
    3816           0 :     if (rsig)
    3817           0 :         *rsig = shsigalgs->rsign;
    3818           0 :     if (rhash)
    3819           0 :         *rhash = shsigalgs->rhash;
    3820           0 :     return s->cert->shared_sigalgslen;
    3821             : }
    3822             : 
    3823             : # ifndef OPENSSL_NO_HEARTBEATS
    3824           0 : int tls1_process_heartbeat(SSL *s)
    3825             : {
    3826           0 :     unsigned char *p = &s->s3->rrec.data[0], *pl;
    3827             :     unsigned short hbtype;
    3828             :     unsigned int payload;
    3829             :     unsigned int padding = 16;  /* Use minimum padding */
    3830             : 
    3831           0 :     if (s->msg_callback)
    3832           0 :         s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
    3833           0 :                         &s->s3->rrec.data[0], s->s3->rrec.length,
    3834             :                         s, s->msg_callback_arg);
    3835             : 
    3836             :     /* Read type and payload length first */
    3837           0 :     if (1 + 2 + 16 > s->s3->rrec.length)
    3838             :         return 0;               /* silently discard */
    3839           0 :     hbtype = *p++;
    3840           0 :     n2s(p, payload);
    3841           0 :     if (1 + 2 + payload + 16 > s->s3->rrec.length)
    3842             :         return 0;               /* silently discard per RFC 6520 sec. 4 */
    3843           0 :     pl = p;
    3844             : 
    3845           0 :     if (hbtype == TLS1_HB_REQUEST) {
    3846             :         unsigned char *buffer, *bp;
    3847             :         int r;
    3848             : 
    3849             :         /*
    3850             :          * Allocate memory for the response, size is 1 bytes message type,
    3851             :          * plus 2 bytes payload length, plus payload, plus padding
    3852             :          */
    3853           0 :         buffer = OPENSSL_malloc(1 + 2 + payload + padding);
    3854             :         bp = buffer;
    3855             : 
    3856             :         /* Enter response type, length and copy payload */
    3857           0 :         *bp++ = TLS1_HB_RESPONSE;
    3858           0 :         s2n(payload, bp);
    3859           0 :         memcpy(bp, pl, payload);
    3860           0 :         bp += payload;
    3861             :         /* Random padding */
    3862           0 :         if (RAND_pseudo_bytes(bp, padding) < 0) {
    3863           0 :             OPENSSL_free(buffer);
    3864           0 :             return -1;
    3865             :         }
    3866             : 
    3867           0 :         r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer,
    3868             :                              3 + payload + padding);
    3869             : 
    3870           0 :         if (r >= 0 && s->msg_callback)
    3871           0 :             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
    3872             :                             buffer, 3 + payload + padding,
    3873             :                             s, s->msg_callback_arg);
    3874             : 
    3875           0 :         OPENSSL_free(buffer);
    3876             : 
    3877           0 :         if (r < 0)
    3878           0 :             return r;
    3879           0 :     } else if (hbtype == TLS1_HB_RESPONSE) {
    3880             :         unsigned int seq;
    3881             : 
    3882             :         /*
    3883             :          * We only send sequence numbers (2 bytes unsigned int), and 16
    3884             :          * random bytes, so we just try to read the sequence number
    3885             :          */
    3886           0 :         n2s(pl, seq);
    3887             : 
    3888           0 :         if (payload == 18 && seq == s->tlsext_hb_seq) {
    3889           0 :             s->tlsext_hb_seq++;
    3890           0 :             s->tlsext_hb_pending = 0;
    3891             :         }
    3892             :     }
    3893             : 
    3894             :     return 0;
    3895             : }
    3896             : 
    3897           0 : int tls1_heartbeat(SSL *s)
    3898             : {
    3899             :     unsigned char *buf, *p;
    3900             :     int ret = -1;
    3901             :     unsigned int payload = 18;  /* Sequence number + random bytes */
    3902             :     unsigned int padding = 16;  /* Use minimum padding */
    3903             : 
    3904             :     /* Only send if peer supports and accepts HB requests... */
    3905           0 :     if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
    3906             :         s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
    3907           0 :         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
    3908           0 :         return -1;
    3909             :     }
    3910             : 
    3911             :     /* ...and there is none in flight yet... */
    3912           0 :     if (s->tlsext_hb_pending) {
    3913           0 :         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
    3914           0 :         return -1;
    3915             :     }
    3916             : 
    3917             :     /* ...and no handshake in progress. */
    3918           0 :     if (SSL_in_init(s) || s->in_handshake) {
    3919           0 :         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
    3920           0 :         return -1;
    3921             :     }
    3922             : 
    3923             :     /*
    3924             :      * Check if padding is too long, payload and padding must not exceed 2^14
    3925             :      * - 3 = 16381 bytes in total.
    3926             :      */
    3927             :     OPENSSL_assert(payload + padding <= 16381);
    3928             : 
    3929             :     /*-
    3930             :      * Create HeartBeat message, we just use a sequence number
    3931             :      * as payload to distuingish different messages and add
    3932             :      * some random stuff.
    3933             :      *  - Message Type, 1 byte
    3934             :      *  - Payload Length, 2 bytes (unsigned int)
    3935             :      *  - Payload, the sequence number (2 bytes uint)
    3936             :      *  - Payload, random bytes (16 bytes uint)
    3937             :      *  - Padding
    3938             :      */
    3939           0 :     buf = OPENSSL_malloc(1 + 2 + payload + padding);
    3940             :     p = buf;
    3941             :     /* Message Type */
    3942           0 :     *p++ = TLS1_HB_REQUEST;
    3943             :     /* Payload length (18 bytes here) */
    3944           0 :     s2n(payload, p);
    3945             :     /* Sequence number */
    3946           0 :     s2n(s->tlsext_hb_seq, p);
    3947             :     /* 16 random bytes */
    3948           0 :     if (RAND_pseudo_bytes(p, 16) < 0) {
    3949           0 :         SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
    3950           0 :         goto err;
    3951             :     }
    3952           0 :     p += 16;
    3953             :     /* Random padding */
    3954           0 :     if (RAND_pseudo_bytes(p, padding) < 0) {
    3955           0 :         SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
    3956           0 :         goto err;
    3957             :     }
    3958             : 
    3959           0 :     ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
    3960           0 :     if (ret >= 0) {
    3961           0 :         if (s->msg_callback)
    3962           0 :             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
    3963             :                             buf, 3 + payload + padding,
    3964             :                             s, s->msg_callback_arg);
    3965             : 
    3966           0 :         s->tlsext_hb_pending = 1;
    3967             :     }
    3968             : 
    3969             : err:
    3970           0 :     OPENSSL_free(buf);
    3971             : 
    3972           0 :     return ret;
    3973             : }
    3974             : # endif
    3975             : 
    3976             : # define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
    3977             : 
    3978             : typedef struct {
    3979             :     size_t sigalgcnt;
    3980             :     int sigalgs[MAX_SIGALGLEN];
    3981             : } sig_cb_st;
    3982             : 
    3983           0 : static int sig_cb(const char *elem, int len, void *arg)
    3984             : {
    3985             :     sig_cb_st *sarg = arg;
    3986             :     size_t i;
    3987             :     char etmp[20], *p;
    3988             :     int sig_alg, hash_alg;
    3989           0 :     if (elem == NULL)
    3990             :         return 0;
    3991           0 :     if (sarg->sigalgcnt == MAX_SIGALGLEN)
    3992             :         return 0;
    3993           0 :     if (len > (int)(sizeof(etmp) - 1))
    3994             :         return 0;
    3995           0 :     memcpy(etmp, elem, len);
    3996           0 :     etmp[len] = 0;
    3997           0 :     p = strchr(etmp, '+');
    3998           0 :     if (!p)
    3999             :         return 0;
    4000           0 :     *p = 0;
    4001           0 :     p++;
    4002           0 :     if (!*p)
    4003             :         return 0;
    4004             : 
    4005           0 :     if (!strcmp(etmp, "RSA"))
    4006             :         sig_alg = EVP_PKEY_RSA;
    4007           0 :     else if (!strcmp(etmp, "DSA"))
    4008             :         sig_alg = EVP_PKEY_DSA;
    4009           0 :     else if (!strcmp(etmp, "ECDSA"))
    4010             :         sig_alg = EVP_PKEY_EC;
    4011             :     else
    4012             :         return 0;
    4013             : 
    4014           0 :     hash_alg = OBJ_sn2nid(p);
    4015           0 :     if (hash_alg == NID_undef)
    4016           0 :         hash_alg = OBJ_ln2nid(p);
    4017           0 :     if (hash_alg == NID_undef)
    4018             :         return 0;
    4019             : 
    4020           0 :     for (i = 0; i < sarg->sigalgcnt; i += 2) {
    4021           0 :         if (sarg->sigalgs[i] == sig_alg && sarg->sigalgs[i + 1] == hash_alg)
    4022             :             return 0;
    4023             :     }
    4024           0 :     sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
    4025           0 :     sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
    4026           0 :     return 1;
    4027             : }
    4028             : 
    4029             : /*
    4030             :  * Set suppored signature algorithms based on a colon separated list of the
    4031             :  * form sig+hash e.g. RSA+SHA512:DSA+SHA512
    4032             :  */
    4033           0 : int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
    4034             : {
    4035             :     sig_cb_st sig;
    4036           0 :     sig.sigalgcnt = 0;
    4037           0 :     if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
    4038             :         return 0;
    4039           0 :     if (c == NULL)
    4040             :         return 1;
    4041           0 :     return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
    4042             : }
    4043             : 
    4044           0 : int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen,
    4045             :                      int client)
    4046             : {
    4047             :     unsigned char *sigalgs, *sptr;
    4048             :     int rhash, rsign;
    4049             :     size_t i;
    4050           0 :     if (salglen & 1)
    4051             :         return 0;
    4052           0 :     sigalgs = OPENSSL_malloc(salglen);
    4053           0 :     if (sigalgs == NULL)
    4054             :         return 0;
    4055           0 :     for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
    4056           0 :         rhash = tls12_find_id(*psig_nids++, tls12_md,
    4057             :                               sizeof(tls12_md) / sizeof(tls12_lookup));
    4058           0 :         rsign = tls12_find_id(*psig_nids++, tls12_sig,
    4059             :                               sizeof(tls12_sig) / sizeof(tls12_lookup));
    4060             : 
    4061           0 :         if (rhash == -1 || rsign == -1)
    4062             :             goto err;
    4063           0 :         *sptr++ = rhash;
    4064           0 :         *sptr++ = rsign;
    4065             :     }
    4066             : 
    4067           0 :     if (client) {
    4068           0 :         if (c->client_sigalgs)
    4069           0 :             OPENSSL_free(c->client_sigalgs);
    4070           0 :         c->client_sigalgs = sigalgs;
    4071           0 :         c->client_sigalgslen = salglen;
    4072             :     } else {
    4073           0 :         if (c->conf_sigalgs)
    4074           0 :             OPENSSL_free(c->conf_sigalgs);
    4075           0 :         c->conf_sigalgs = sigalgs;
    4076           0 :         c->conf_sigalgslen = salglen;
    4077             :     }
    4078             : 
    4079             :     return 1;
    4080             : 
    4081             :  err:
    4082           0 :     OPENSSL_free(sigalgs);
    4083           0 :     return 0;
    4084             : }
    4085             : 
    4086           0 : static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
    4087             : {
    4088             :     int sig_nid;
    4089             :     size_t i;
    4090           0 :     if (default_nid == -1)
    4091             :         return 1;
    4092           0 :     sig_nid = X509_get_signature_nid(x);
    4093           0 :     if (default_nid)
    4094           0 :         return sig_nid == default_nid ? 1 : 0;
    4095           0 :     for (i = 0; i < c->shared_sigalgslen; i++)
    4096           0 :         if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
    4097             :             return 1;
    4098             :     return 0;
    4099             : }
    4100             : 
    4101             : /* Check to see if a certificate issuer name matches list of CA names */
    4102           0 : static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
    4103             : {
    4104             :     X509_NAME *nm;
    4105             :     int i;
    4106           0 :     nm = X509_get_issuer_name(x);
    4107           0 :     for (i = 0; i < sk_X509_NAME_num(names); i++) {
    4108           0 :         if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
    4109             :             return 1;
    4110             :     }
    4111             :     return 0;
    4112             : }
    4113             : 
    4114             : /*
    4115             :  * Check certificate chain is consistent with TLS extensions and is usable by
    4116             :  * server. This servers two purposes: it allows users to check chains before
    4117             :  * passing them to the server and it allows the server to check chains before
    4118             :  * attempting to use them.
    4119             :  */
    4120             : 
    4121             : /* Flags which need to be set for a certificate when stict mode not set */
    4122             : 
    4123             : # define CERT_PKEY_VALID_FLAGS \
    4124             :         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
    4125             : /* Strict mode flags */
    4126             : # define CERT_PKEY_STRICT_FLAGS \
    4127             :          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
    4128             :          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
    4129             : 
    4130        2238 : int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
    4131             :                      int idx)
    4132             : {
    4133             :     int i;
    4134             :     int rv = 0;
    4135             :     int check_flags = 0, strict_mode;
    4136             :     CERT_PKEY *cpk = NULL;
    4137        2238 :     CERT *c = s->cert;
    4138        2238 :     unsigned int suiteb_flags = tls1_suiteb(s);
    4139             :     /* idx == -1 means checking server chains */
    4140        2238 :     if (idx != -1) {
    4141             :         /* idx == -2 means checking client certificate chains */
    4142        2238 :         if (idx == -2) {
    4143           0 :             cpk = c->key;
    4144           0 :             idx = cpk - c->pkeys;
    4145             :         } else
    4146        2238 :             cpk = c->pkeys + idx;
    4147        2238 :         x = cpk->x509;
    4148        2238 :         pk = cpk->privatekey;
    4149        2238 :         chain = cpk->chain;
    4150        2238 :         strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
    4151             :         /* If no cert or key, forget it */
    4152        2238 :         if (!x || !pk)
    4153             :             goto end;
    4154             : # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
    4155             :         /* Allow any certificate to pass test */
    4156             :         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
    4157             :             rv = CERT_PKEY_STRICT_FLAGS | CERT_PKEY_EXPLICIT_SIGN |
    4158             :                 CERT_PKEY_VALID | CERT_PKEY_SIGN;
    4159             :             cpk->valid_flags = rv;
    4160             :             return rv;
    4161             :         }
    4162             : # endif
    4163             :     } else {
    4164           0 :         if (!x || !pk)
    4165             :             return 0;
    4166           0 :         idx = ssl_cert_type(x, pk);
    4167           0 :         if (idx == -1)
    4168             :             return 0;
    4169           0 :         cpk = c->pkeys + idx;
    4170           0 :         if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
    4171             :             check_flags = CERT_PKEY_STRICT_FLAGS;
    4172             :         else
    4173             :             check_flags = CERT_PKEY_VALID_FLAGS;
    4174             :         strict_mode = 1;
    4175             :     }
    4176             : 
    4177         373 :     if (suiteb_flags) {
    4178             :         int ok;
    4179           0 :         if (check_flags)
    4180           0 :             check_flags |= CERT_PKEY_SUITEB;
    4181           0 :         ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
    4182           0 :         if (ok == X509_V_OK)
    4183             :             rv |= CERT_PKEY_SUITEB;
    4184           0 :         else if (!check_flags)
    4185             :             goto end;
    4186             :     }
    4187             : 
    4188             :     /*
    4189             :      * Check all signature algorithms are consistent with signature
    4190             :      * algorithms extension if TLS 1.2 or later and strict mode.
    4191             :      */
    4192         373 :     if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
    4193             :         int default_nid;
    4194             :         unsigned char rsign = 0;
    4195           0 :         if (c->peer_sigalgs)
    4196             :             default_nid = 0;
    4197             :         /* If no sigalgs extension use defaults from RFC5246 */
    4198             :         else {
    4199             :             switch (idx) {
    4200             :             case SSL_PKEY_RSA_ENC:
    4201             :             case SSL_PKEY_RSA_SIGN:
    4202             :             case SSL_PKEY_DH_RSA:
    4203             :                 rsign = TLSEXT_signature_rsa;
    4204             :                 default_nid = NID_sha1WithRSAEncryption;
    4205             :                 break;
    4206             : 
    4207             :             case SSL_PKEY_DSA_SIGN:
    4208             :             case SSL_PKEY_DH_DSA:
    4209             :                 rsign = TLSEXT_signature_dsa;
    4210             :                 default_nid = NID_dsaWithSHA1;
    4211           0 :                 break;
    4212             : 
    4213             :             case SSL_PKEY_ECC:
    4214             :                 rsign = TLSEXT_signature_ecdsa;
    4215             :                 default_nid = NID_ecdsa_with_SHA1;
    4216           0 :                 break;
    4217             : 
    4218             :             default:
    4219             :                 default_nid = -1;
    4220           0 :                 break;
    4221             :             }
    4222             :         }
    4223             :         /*
    4224             :          * If peer sent no signature algorithms extension and we have set
    4225             :          * preferred signature algorithms check we support sha1.
    4226             :          */
    4227           0 :         if (default_nid > 0 && c->conf_sigalgs) {
    4228             :             size_t j;
    4229             :             const unsigned char *p = c->conf_sigalgs;
    4230           0 :             for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2) {
    4231           0 :                 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
    4232             :                     break;
    4233             :             }
    4234           0 :             if (j == c->conf_sigalgslen) {
    4235           0 :                 if (check_flags)
    4236             :                     goto skip_sigs;
    4237             :                 else
    4238             :                     goto end;
    4239             :             }
    4240             :         }
    4241             :         /* Check signature algorithm of each cert in chain */
    4242           0 :         if (!tls1_check_sig_alg(c, x, default_nid)) {
    4243           0 :             if (!check_flags)
    4244             :                 goto end;
    4245             :         } else
    4246           0 :             rv |= CERT_PKEY_EE_SIGNATURE;
    4247           0 :         rv |= CERT_PKEY_CA_SIGNATURE;
    4248           0 :         for (i = 0; i < sk_X509_num(chain); i++) {
    4249           0 :             if (!tls1_check_sig_alg(c, sk_X509_value(chain, i), default_nid)) {
    4250           0 :                 if (check_flags) {
    4251           0 :                     rv &= ~CERT_PKEY_CA_SIGNATURE;
    4252           0 :                     break;
    4253             :                 } else
    4254             :                     goto end;
    4255             :             }
    4256             :         }
    4257             :     }
    4258             :     /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
    4259         373 :     else if (check_flags)
    4260           0 :         rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
    4261             :  skip_sigs:
    4262             :     /* Check cert parameters are consistent */
    4263         373 :     if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
    4264         373 :         rv |= CERT_PKEY_EE_PARAM;
    4265           0 :     else if (!check_flags)
    4266             :         goto end;
    4267         373 :     if (!s->server)
    4268           0 :         rv |= CERT_PKEY_CA_PARAM;
    4269             :     /* In strict mode check rest of chain too */
    4270         373 :     else if (strict_mode) {
    4271           0 :         rv |= CERT_PKEY_CA_PARAM;
    4272           0 :         for (i = 0; i < sk_X509_num(chain); i++) {
    4273           0 :             X509 *ca = sk_X509_value(chain, i);
    4274           0 :             if (!tls1_check_cert_param(s, ca, 0)) {
    4275           0 :                 if (check_flags) {
    4276           0 :                     rv &= ~CERT_PKEY_CA_PARAM;
    4277           0 :                     break;
    4278             :                 } else
    4279             :                     goto end;
    4280             :             }
    4281             :         }
    4282             :     }
    4283         373 :     if (!s->server && strict_mode) {
    4284             :         STACK_OF(X509_NAME) *ca_dn;
    4285             :         int check_type = 0;
    4286           0 :         switch (pk->type) {
    4287             :         case EVP_PKEY_RSA:
    4288             :             check_type = TLS_CT_RSA_SIGN;
    4289           0 :             break;
    4290             :         case EVP_PKEY_DSA:
    4291             :             check_type = TLS_CT_DSS_SIGN;
    4292           0 :             break;
    4293             :         case EVP_PKEY_EC:
    4294             :             check_type = TLS_CT_ECDSA_SIGN;
    4295           0 :             break;
    4296             :         case EVP_PKEY_DH:
    4297             :         case EVP_PKEY_DHX:
    4298             :             {
    4299           0 :                 int cert_type = X509_certificate_type(x, pk);
    4300           0 :                 if (cert_type & EVP_PKS_RSA)
    4301             :                     check_type = TLS_CT_RSA_FIXED_DH;
    4302           0 :                 if (cert_type & EVP_PKS_DSA)
    4303             :                     check_type = TLS_CT_DSS_FIXED_DH;
    4304             :             }
    4305             :         }
    4306           0 :         if (check_type) {
    4307             :             const unsigned char *ctypes;
    4308             :             int ctypelen;
    4309           0 :             if (c->ctypes) {
    4310             :                 ctypes = c->ctypes;
    4311           0 :                 ctypelen = (int)c->ctype_num;
    4312             :             } else {
    4313           0 :                 ctypes = (unsigned char *)s->s3->tmp.ctype;
    4314           0 :                 ctypelen = s->s3->tmp.ctype_num;
    4315             :             }
    4316           0 :             for (i = 0; i < ctypelen; i++) {
    4317           0 :                 if (ctypes[i] == check_type) {
    4318           0 :                     rv |= CERT_PKEY_CERT_TYPE;
    4319           0 :                     break;
    4320             :                 }
    4321             :             }
    4322           0 :             if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
    4323             :                 goto end;
    4324             :         } else
    4325           0 :             rv |= CERT_PKEY_CERT_TYPE;
    4326             : 
    4327           0 :         ca_dn = s->s3->tmp.ca_names;
    4328             : 
    4329           0 :         if (!sk_X509_NAME_num(ca_dn))
    4330           0 :             rv |= CERT_PKEY_ISSUER_NAME;
    4331             : 
    4332           0 :         if (!(rv & CERT_PKEY_ISSUER_NAME)) {
    4333           0 :             if (ssl_check_ca_name(ca_dn, x))
    4334           0 :                 rv |= CERT_PKEY_ISSUER_NAME;
    4335             :         }
    4336           0 :         if (!(rv & CERT_PKEY_ISSUER_NAME)) {
    4337           0 :             for (i = 0; i < sk_X509_num(chain); i++) {
    4338           0 :                 X509 *xtmp = sk_X509_value(chain, i);
    4339           0 :                 if (ssl_check_ca_name(ca_dn, xtmp)) {
    4340           0 :                     rv |= CERT_PKEY_ISSUER_NAME;
    4341           0 :                     break;
    4342             :                 }
    4343             :             }
    4344             :         }
    4345           0 :         if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
    4346             :             goto end;
    4347             :     } else
    4348         373 :         rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
    4349             : 
    4350         373 :     if (!check_flags || (rv & check_flags) == check_flags)
    4351         373 :         rv |= CERT_PKEY_VALID;
    4352             : 
    4353             :  end:
    4354             : 
    4355        2238 :     if (TLS1_get_version(s) >= TLS1_2_VERSION) {
    4356        2238 :         if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
    4357        1492 :             rv |= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
    4358         746 :         else if (cpk->digest)
    4359           0 :             rv |= CERT_PKEY_SIGN;
    4360             :     } else
    4361           0 :         rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
    4362             : 
    4363             :     /*
    4364             :      * When checking a CERT_PKEY structure all flags are irrelevant if the
    4365             :      * chain is invalid.
    4366             :      */
    4367        2238 :     if (!check_flags) {
    4368        2238 :         if (rv & CERT_PKEY_VALID)
    4369         373 :             cpk->valid_flags = rv;
    4370             :         else {
    4371             :             /* Preserve explicit sign flag, clear rest */
    4372        1865 :             cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
    4373        1865 :             return 0;
    4374             :         }
    4375             :     }
    4376         373 :     return rv;
    4377             : }
    4378             : 
    4379             : /* Set validity of certificates in an SSL structure */
    4380         373 : void tls1_set_cert_validity(SSL *s)
    4381             : {
    4382         373 :     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
    4383         373 :     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
    4384         373 :     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
    4385         373 :     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
    4386         373 :     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
    4387         373 :     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
    4388         373 : }
    4389             : 
    4390             : /* User level utiity function to check a chain is suitable */
    4391           0 : int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
    4392             : {
    4393           0 :     return tls1_check_chain(s, x, pk, chain, -1);
    4394             : }
    4395             : 
    4396             : #endif

Generated by: LCOV version 1.10