quickjs-tart

quickjs-based runtime for wallet-core logic
Log | Files | Refs | README | LICENSE

ssl_client.c (34767B)


      1 /*
      2  *  TLS 1.2 and 1.3 client-side functions
      3  *
      4  *  Copyright The Mbed TLS Contributors
      5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
      6  */
      7 
      8 #include "common.h"
      9 
     10 #if defined(MBEDTLS_SSL_CLI_C)
     11 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
     12 
     13 #include <string.h>
     14 
     15 #include "debug_internal.h"
     16 #include "mbedtls/error.h"
     17 #include "mbedtls/platform.h"
     18 
     19 #include "ssl_client.h"
     20 #include "ssl_misc.h"
     21 #include "ssl_tls13_keys.h"
     22 #include "ssl_debug_helpers.h"
     23 
     24 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
     25 MBEDTLS_CHECK_RETURN_CRITICAL
     26 static int ssl_write_hostname_ext(mbedtls_ssl_context *ssl,
     27                                   unsigned char *buf,
     28                                   const unsigned char *end,
     29                                   size_t *olen)
     30 {
     31     unsigned char *p = buf;
     32     const char *hostname = mbedtls_ssl_get_hostname_pointer(ssl);
     33     size_t hostname_len;
     34 
     35     *olen = 0;
     36 
     37     if (hostname == NULL) {
     38         return 0;
     39     }
     40 
     41     MBEDTLS_SSL_DEBUG_MSG(3,
     42                           ("client hello, adding server name extension: %s",
     43                            hostname));
     44 
     45     hostname_len = strlen(hostname);
     46 
     47     MBEDTLS_SSL_CHK_BUF_PTR(p, end, hostname_len + 9);
     48 
     49     /*
     50      * Sect. 3, RFC 6066 (TLS Extensions Definitions)
     51      *
     52      * In order to provide any of the server names, clients MAY include an
     53      * extension of type "server_name" in the (extended) client hello. The
     54      * "extension_data" field of this extension SHALL contain
     55      * "ServerNameList" where:
     56      *
     57      * struct {
     58      *     NameType name_type;
     59      *     select (name_type) {
     60      *         case host_name: HostName;
     61      *     } name;
     62      * } ServerName;
     63      *
     64      * enum {
     65      *     host_name(0), (255)
     66      * } NameType;
     67      *
     68      * opaque HostName<1..2^16-1>;
     69      *
     70      * struct {
     71      *     ServerName server_name_list<1..2^16-1>
     72      * } ServerNameList;
     73      *
     74      */
     75     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SERVERNAME, p, 0);
     76     p += 2;
     77 
     78     MBEDTLS_PUT_UINT16_BE(hostname_len + 5, p, 0);
     79     p += 2;
     80 
     81     MBEDTLS_PUT_UINT16_BE(hostname_len + 3, p, 0);
     82     p += 2;
     83 
     84     *p++ = MBEDTLS_BYTE_0(MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME);
     85 
     86     MBEDTLS_PUT_UINT16_BE(hostname_len, p, 0);
     87     p += 2;
     88 
     89     memcpy(p, hostname, hostname_len);
     90 
     91     *olen = hostname_len + 9;
     92 
     93 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
     94     mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_SERVERNAME);
     95 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
     96     return 0;
     97 }
     98 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
     99 
    100 #if defined(MBEDTLS_SSL_ALPN)
    101 /*
    102  * ssl_write_alpn_ext()
    103  *
    104  * Structure of the application_layer_protocol_negotiation extension in
    105  * ClientHello:
    106  *
    107  * opaque ProtocolName<1..2^8-1>;
    108  *
    109  * struct {
    110  *     ProtocolName protocol_name_list<2..2^16-1>
    111  * } ProtocolNameList;
    112  *
    113  */
    114 MBEDTLS_CHECK_RETURN_CRITICAL
    115 static int ssl_write_alpn_ext(mbedtls_ssl_context *ssl,
    116                               unsigned char *buf,
    117                               const unsigned char *end,
    118                               size_t *out_len)
    119 {
    120     unsigned char *p = buf;
    121 
    122     *out_len = 0;
    123 
    124     if (ssl->conf->alpn_list == NULL) {
    125         return 0;
    126     }
    127 
    128     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, adding alpn extension"));
    129 
    130 
    131     /* Check we have enough space for the extension type (2 bytes), the
    132      * extension length (2 bytes) and the protocol_name_list length (2 bytes).
    133      */
    134     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 6);
    135     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ALPN, p, 0);
    136     /* Skip writing extension and list length for now */
    137     p += 6;
    138 
    139     /*
    140      * opaque ProtocolName<1..2^8-1>;
    141      *
    142      * struct {
    143      *     ProtocolName protocol_name_list<2..2^16-1>
    144      * } ProtocolNameList;
    145      */
    146     for (const char **cur = ssl->conf->alpn_list; *cur != NULL; cur++) {
    147         /*
    148          * mbedtls_ssl_conf_set_alpn_protocols() checked that the length of
    149          * protocol names is less than 255.
    150          */
    151         size_t protocol_name_len = strlen(*cur);
    152 
    153         MBEDTLS_SSL_CHK_BUF_PTR(p, end, 1 + protocol_name_len);
    154         *p++ = (unsigned char) protocol_name_len;
    155         memcpy(p, *cur, protocol_name_len);
    156         p += protocol_name_len;
    157     }
    158 
    159     *out_len = (size_t) (p - buf);
    160 
    161     /* List length = *out_len - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
    162     MBEDTLS_PUT_UINT16_BE(*out_len - 6, buf, 4);
    163 
    164     /* Extension length = *out_len - 2 (ext_type) - 2 (ext_len) */
    165     MBEDTLS_PUT_UINT16_BE(*out_len - 4, buf, 2);
    166 
    167 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
    168     mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_ALPN);
    169 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
    170     return 0;
    171 }
    172 #endif /* MBEDTLS_SSL_ALPN */
    173 
    174 #if defined(MBEDTLS_SSL_TLS1_2_SOME_ECC) || \
    175     defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
    176 /*
    177  * Function for writing a supported groups (TLS 1.3) or supported elliptic
    178  * curves (TLS 1.2) extension.
    179  *
    180  * The "extension_data" field of a supported groups extension contains a
    181  * "NamedGroupList" value (TLS 1.3 RFC8446):
    182  *      enum {
    183  *          secp256r1(0x0017), secp384r1(0x0018), secp521r1(0x0019),
    184  *          x25519(0x001D), x448(0x001E),
    185  *          ffdhe2048(0x0100), ffdhe3072(0x0101), ffdhe4096(0x0102),
    186  *          ffdhe6144(0x0103), ffdhe8192(0x0104),
    187  *          ffdhe_private_use(0x01FC..0x01FF),
    188  *          ecdhe_private_use(0xFE00..0xFEFF),
    189  *          (0xFFFF)
    190  *      } NamedGroup;
    191  *      struct {
    192  *          NamedGroup named_group_list<2..2^16-1>;
    193  *      } NamedGroupList;
    194  *
    195  * The "extension_data" field of a supported elliptic curves extension contains
    196  * a "NamedCurveList" value (TLS 1.2 RFC 8422):
    197  * enum {
    198  *      deprecated(1..22),
    199  *      secp256r1 (23), secp384r1 (24), secp521r1 (25),
    200  *      x25519(29), x448(30),
    201  *      reserved (0xFE00..0xFEFF),
    202  *      deprecated(0xFF01..0xFF02),
    203  *      (0xFFFF)
    204  *  } NamedCurve;
    205  * struct {
    206  *      NamedCurve named_curve_list<2..2^16-1>
    207  *  } NamedCurveList;
    208  *
    209  * The TLS 1.3 supported groups extension was defined to be a compatible
    210  * generalization of the TLS 1.2 supported elliptic curves extension. They both
    211  * share the same extension identifier.
    212  *
    213  */
    214 #define SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_2_FLAG 1
    215 #define SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_3_FLAG 2
    216 
    217 MBEDTLS_CHECK_RETURN_CRITICAL
    218 static int ssl_write_supported_groups_ext(mbedtls_ssl_context *ssl,
    219                                           unsigned char *buf,
    220                                           const unsigned char *end,
    221                                           int flags,
    222                                           size_t *out_len)
    223 {
    224     unsigned char *p = buf;
    225     unsigned char *named_group_list; /* Start of named_group_list */
    226     size_t named_group_list_len;     /* Length of named_group_list */
    227     const uint16_t *group_list = mbedtls_ssl_get_groups(ssl);
    228 
    229     *out_len = 0;
    230 
    231     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, adding supported_groups extension"));
    232 
    233     /* Check if we have space for header and length fields:
    234      * - extension_type            (2 bytes)
    235      * - extension_data_length     (2 bytes)
    236      * - named_group_list_length   (2 bytes)
    237      */
    238     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 6);
    239     p += 6;
    240 
    241     named_group_list = p;
    242 
    243     if (group_list == NULL) {
    244         return MBEDTLS_ERR_SSL_BAD_CONFIG;
    245     }
    246 
    247     for (; *group_list != 0; group_list++) {
    248         int propose_group = 0;
    249 
    250         MBEDTLS_SSL_DEBUG_MSG(3, ("got supported group(%04x)", *group_list));
    251 
    252 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
    253         if (flags & SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_3_FLAG) {
    254 #if defined(PSA_WANT_ALG_ECDH)
    255             if (mbedtls_ssl_tls13_named_group_is_ecdhe(*group_list) &&
    256                 (mbedtls_ssl_get_ecp_group_id_from_tls_id(*group_list) !=
    257                  MBEDTLS_ECP_DP_NONE)) {
    258                 propose_group = 1;
    259             }
    260 #endif
    261 #if defined(PSA_WANT_ALG_FFDH)
    262             if (mbedtls_ssl_tls13_named_group_is_ffdh(*group_list)) {
    263                 propose_group = 1;
    264             }
    265 #endif
    266         }
    267 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
    268 
    269 #if defined(MBEDTLS_SSL_TLS1_2_SOME_ECC)
    270         if ((flags & SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_2_FLAG) &&
    271             mbedtls_ssl_tls12_named_group_is_ecdhe(*group_list) &&
    272             (mbedtls_ssl_get_ecp_group_id_from_tls_id(*group_list) !=
    273              MBEDTLS_ECP_DP_NONE)) {
    274             propose_group = 1;
    275         }
    276 #endif /* MBEDTLS_SSL_TLS1_2_SOME_ECC */
    277 
    278         if (propose_group) {
    279             MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
    280             MBEDTLS_PUT_UINT16_BE(*group_list, p, 0);
    281             p += 2;
    282             MBEDTLS_SSL_DEBUG_MSG(3, ("NamedGroup: %s ( %x )",
    283                                       mbedtls_ssl_named_group_to_str(*group_list),
    284                                       *group_list));
    285         }
    286     }
    287 
    288     /* Length of named_group_list */
    289     named_group_list_len = (size_t) (p - named_group_list);
    290     if (named_group_list_len == 0) {
    291         MBEDTLS_SSL_DEBUG_MSG(1, ("No group available."));
    292         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
    293     }
    294 
    295     /* Write extension_type */
    296     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_GROUPS, buf, 0);
    297     /* Write extension_data_length */
    298     MBEDTLS_PUT_UINT16_BE(named_group_list_len + 2, buf, 2);
    299     /* Write length of named_group_list */
    300     MBEDTLS_PUT_UINT16_BE(named_group_list_len, buf, 4);
    301 
    302     MBEDTLS_SSL_DEBUG_BUF(3, "Supported groups extension",
    303                           buf + 4, named_group_list_len + 2);
    304 
    305     *out_len = (size_t) (p - buf);
    306 
    307 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
    308     mbedtls_ssl_tls13_set_hs_sent_ext_mask(
    309         ssl, MBEDTLS_TLS_EXT_SUPPORTED_GROUPS);
    310 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
    311 
    312     return 0;
    313 }
    314 #endif /* MBEDTLS_SSL_TLS1_2_SOME_ECC ||
    315           MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
    316 
    317 MBEDTLS_CHECK_RETURN_CRITICAL
    318 static int ssl_write_client_hello_cipher_suites(
    319     mbedtls_ssl_context *ssl,
    320     unsigned char *buf,
    321     unsigned char *end,
    322     int *tls12_uses_ec,
    323     size_t *out_len)
    324 {
    325     unsigned char *p = buf;
    326     const int *ciphersuite_list;
    327     unsigned char *cipher_suites; /* Start of the cipher_suites list */
    328     size_t cipher_suites_len;
    329 
    330     *tls12_uses_ec = 0;
    331     *out_len = 0;
    332 
    333     /*
    334      * Ciphersuite list
    335      *
    336      * This is a list of the symmetric cipher options supported by
    337      * the client, specifically the record protection algorithm
    338      * ( including secret key length ) and a hash to be used with
    339      * HKDF, in descending order of client preference.
    340      */
    341     ciphersuite_list = ssl->conf->ciphersuite_list;
    342 
    343     /* Check there is space for the cipher suite list length (2 bytes). */
    344     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
    345     p += 2;
    346 
    347     /* Write cipher_suites
    348      * CipherSuite cipher_suites<2..2^16-2>;
    349      */
    350     cipher_suites = p;
    351     for (size_t i = 0; ciphersuite_list[i] != 0; i++) {
    352         int cipher_suite = ciphersuite_list[i];
    353         const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
    354 
    355         ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(cipher_suite);
    356 
    357         if (mbedtls_ssl_validate_ciphersuite(ssl, ciphersuite_info,
    358                                              ssl->handshake->min_tls_version,
    359                                              ssl->tls_version) != 0) {
    360             continue;
    361         }
    362 
    363 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
    364         (defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
    365         defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
    366         defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED))
    367         *tls12_uses_ec |= mbedtls_ssl_ciphersuite_uses_ec(ciphersuite_info);
    368 #endif
    369 
    370         MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, add ciphersuite: %04x, %s",
    371                                   (unsigned int) cipher_suite,
    372                                   ciphersuite_info->name));
    373 
    374         /* Check there is space for the cipher suite identifier (2 bytes). */
    375         MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
    376         MBEDTLS_PUT_UINT16_BE(cipher_suite, p, 0);
    377         p += 2;
    378     }
    379 
    380     /*
    381      * Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
    382      */
    383     int renegotiating = 0;
    384 #if defined(MBEDTLS_SSL_RENEGOTIATION)
    385     renegotiating = (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE);
    386 #endif
    387     if (!renegotiating) {
    388         MBEDTLS_SSL_DEBUG_MSG(3, ("adding EMPTY_RENEGOTIATION_INFO_SCSV"));
    389         MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
    390         MBEDTLS_PUT_UINT16_BE(MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO, p, 0);
    391         p += 2;
    392     }
    393 
    394     /* Write the cipher_suites length in number of bytes */
    395     cipher_suites_len = (size_t) (p - cipher_suites);
    396     MBEDTLS_PUT_UINT16_BE(cipher_suites_len, buf, 0);
    397     MBEDTLS_SSL_DEBUG_MSG(3,
    398                           ("client hello, got %" MBEDTLS_PRINTF_SIZET " cipher suites",
    399                            cipher_suites_len/2));
    400 
    401     /* Output the total length of cipher_suites field. */
    402     *out_len = (size_t) (p - buf);
    403 
    404     return 0;
    405 }
    406 
    407 /*
    408  * Structure of the TLS 1.3 ClientHello message:
    409  *
    410  *    struct {
    411  *        ProtocolVersion legacy_version = 0x0303;    // TLS v1.2
    412  *        Random random;
    413  *        opaque legacy_session_id<0..32>;
    414  *        CipherSuite cipher_suites<2..2^16-2>;
    415  *        opaque legacy_compression_methods<1..2^8-1>;
    416  *        Extension extensions<8..2^16-1>;
    417  *    } ClientHello;
    418  *
    419  * Structure of the (D)TLS 1.2 ClientHello message:
    420  *
    421  * struct {
    422  *     ProtocolVersion client_version;
    423  *     Random random;
    424  *     SessionID session_id;
    425  *     opaque cookie<0..2^8-1>; // DTLS 1.2 ONLY
    426  *     CipherSuite cipher_suites<2..2^16-2>;
    427  *     CompressionMethod compression_methods<1..2^8-1>;
    428  *     select (extensions_present) {
    429  *         case false:
    430  *             struct {};
    431  *         case true:
    432  *             Extension extensions<0..2^16-1>;
    433  *     };
    434  * } ClientHello;
    435  */
    436 MBEDTLS_CHECK_RETURN_CRITICAL
    437 static int ssl_write_client_hello_body(mbedtls_ssl_context *ssl,
    438                                        unsigned char *buf,
    439                                        unsigned char *end,
    440                                        size_t *out_len,
    441                                        size_t *binders_len)
    442 {
    443     int ret;
    444     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
    445     unsigned char *p = buf;
    446     unsigned char *p_extensions_len; /* Pointer to extensions length */
    447     size_t output_len;               /* Length of buffer used by function */
    448     size_t extensions_len;           /* Length of the list of extensions*/
    449     int tls12_uses_ec = 0;
    450 
    451     *out_len = 0;
    452     *binders_len = 0;
    453 
    454 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
    455     unsigned char propose_tls12 =
    456         (handshake->min_tls_version <= MBEDTLS_SSL_VERSION_TLS1_2)
    457         &&
    458         (MBEDTLS_SSL_VERSION_TLS1_2 <= ssl->tls_version);
    459 #endif
    460 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
    461     unsigned char propose_tls13 =
    462         (handshake->min_tls_version <= MBEDTLS_SSL_VERSION_TLS1_3)
    463         &&
    464         (MBEDTLS_SSL_VERSION_TLS1_3 <= ssl->tls_version);
    465 #endif
    466 
    467     /*
    468      * Write client_version (TLS 1.2) or legacy_version (TLS 1.3)
    469      *
    470      * In all cases this is the TLS 1.2 version.
    471      */
    472     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
    473     mbedtls_ssl_write_version(p, ssl->conf->transport,
    474                               MBEDTLS_SSL_VERSION_TLS1_2);
    475     p += 2;
    476 
    477     /* ...
    478      * Random random;
    479      * ...
    480      *
    481      * The random bytes have been prepared by ssl_prepare_client_hello() into
    482      * the handshake->randbytes buffer and are copied here into the output
    483      * buffer.
    484      */
    485     MBEDTLS_SSL_CHK_BUF_PTR(p, end, MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
    486     memcpy(p, handshake->randbytes, MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
    487     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, random bytes",
    488                           p, MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
    489     p += MBEDTLS_CLIENT_HELLO_RANDOM_LEN;
    490 
    491     /* TLS 1.2:
    492      * ...
    493      * SessionID session_id;
    494      * ...
    495      * with
    496      * opaque SessionID<0..32>;
    497      *
    498      * TLS 1.3:
    499      * ...
    500      * opaque legacy_session_id<0..32>;
    501      * ...
    502      *
    503      * The (legacy) session identifier bytes have been prepared by
    504      * ssl_prepare_client_hello() into the ssl->session_negotiate->id buffer
    505      * and are copied here into the output buffer.
    506      */
    507     MBEDTLS_SSL_CHK_BUF_PTR(p, end, ssl->session_negotiate->id_len + 1);
    508     *p++ = (unsigned char) ssl->session_negotiate->id_len;
    509     memcpy(p, ssl->session_negotiate->id, ssl->session_negotiate->id_len);
    510     p += ssl->session_negotiate->id_len;
    511 
    512     MBEDTLS_SSL_DEBUG_BUF(3, "session id", ssl->session_negotiate->id,
    513                           ssl->session_negotiate->id_len);
    514 
    515     /* DTLS 1.2 ONLY
    516      * ...
    517      * opaque cookie<0..2^8-1>;
    518      * ...
    519      */
    520 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_SSL_PROTO_DTLS)
    521     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
    522 #if !defined(MBEDTLS_SSL_PROTO_TLS1_3)
    523         uint8_t cookie_len = 0;
    524 #else
    525         uint16_t cookie_len = 0;
    526 #endif /* !MBEDTLS_SSL_PROTO_TLS1_3 */
    527 
    528         if (handshake->cookie != NULL) {
    529             MBEDTLS_SSL_DEBUG_BUF(3, "client hello, cookie",
    530                                   handshake->cookie,
    531                                   handshake->cookie_len);
    532             cookie_len = handshake->cookie_len;
    533         }
    534 
    535         MBEDTLS_SSL_CHK_BUF_PTR(p, end, cookie_len + 1);
    536         *p++ = (unsigned char) cookie_len;
    537         if (cookie_len > 0) {
    538             memcpy(p, handshake->cookie, cookie_len);
    539             p += cookie_len;
    540         }
    541     }
    542 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_SSL_PROTO_DTLS */
    543 
    544     /* Write cipher_suites */
    545     ret = ssl_write_client_hello_cipher_suites(ssl, p, end,
    546                                                &tls12_uses_ec,
    547                                                &output_len);
    548     if (ret != 0) {
    549         return ret;
    550     }
    551     p += output_len;
    552 
    553     /* Write legacy_compression_methods (TLS 1.3) or
    554      * compression_methods (TLS 1.2)
    555      *
    556      * For every TLS 1.3 ClientHello, this vector MUST contain exactly
    557      * one byte set to zero, which corresponds to the 'null' compression
    558      * method in prior versions of TLS.
    559      *
    560      * For TLS 1.2 ClientHello, for security reasons we do not support
    561      * compression anymore, thus also just the 'null' compression method.
    562      */
    563     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
    564     *p++ = 1;
    565     *p++ = MBEDTLS_SSL_COMPRESS_NULL;
    566 
    567     /* Write extensions */
    568 
    569 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
    570     /* Keeping track of the included extensions */
    571     handshake->sent_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
    572 #endif
    573 
    574     /* First write extensions, then the total length */
    575     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
    576     p_extensions_len = p;
    577     p += 2;
    578 
    579 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
    580     /* Write server name extension */
    581     ret = ssl_write_hostname_ext(ssl, p, end, &output_len);
    582     if (ret != 0) {
    583         return ret;
    584     }
    585     p += output_len;
    586 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
    587 
    588 #if defined(MBEDTLS_SSL_ALPN)
    589     ret = ssl_write_alpn_ext(ssl, p, end, &output_len);
    590     if (ret != 0) {
    591         return ret;
    592     }
    593     p += output_len;
    594 #endif /* MBEDTLS_SSL_ALPN */
    595 
    596 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
    597     if (propose_tls13) {
    598         ret = mbedtls_ssl_tls13_write_client_hello_exts(ssl, p, end,
    599                                                         &output_len);
    600         if (ret != 0) {
    601             return ret;
    602         }
    603         p += output_len;
    604     }
    605 #endif
    606 
    607 #if defined(MBEDTLS_SSL_TLS1_2_SOME_ECC) || \
    608     defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
    609     {
    610         int ssl_write_supported_groups_ext_flags = 0;
    611 
    612 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
    613         if (propose_tls13 && mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(ssl)) {
    614             ssl_write_supported_groups_ext_flags |=
    615                 SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_3_FLAG;
    616         }
    617 #endif
    618 #if defined(MBEDTLS_SSL_TLS1_2_SOME_ECC)
    619         if (propose_tls12 && tls12_uses_ec) {
    620             ssl_write_supported_groups_ext_flags |=
    621                 SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_2_FLAG;
    622         }
    623 #endif
    624         if (ssl_write_supported_groups_ext_flags != 0) {
    625             ret = ssl_write_supported_groups_ext(ssl, p, end,
    626                                                  ssl_write_supported_groups_ext_flags,
    627                                                  &output_len);
    628             if (ret != 0) {
    629                 return ret;
    630             }
    631             p += output_len;
    632         }
    633     }
    634 #endif /* MBEDTLS_SSL_TLS1_2_SOME_ECC ||
    635           MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
    636 
    637 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
    638     int write_sig_alg_ext = 0;
    639 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
    640     write_sig_alg_ext = write_sig_alg_ext ||
    641                         (propose_tls13 && mbedtls_ssl_conf_tls13_is_ephemeral_enabled(ssl));
    642 #endif
    643 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
    644     write_sig_alg_ext = write_sig_alg_ext || propose_tls12;
    645 #endif
    646 
    647     if (write_sig_alg_ext) {
    648         ret = mbedtls_ssl_write_sig_alg_ext(ssl, p, end, &output_len);
    649         if (ret != 0) {
    650             return ret;
    651         }
    652         p += output_len;
    653     }
    654 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
    655 
    656 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
    657     if (propose_tls12) {
    658         ret = mbedtls_ssl_tls12_write_client_hello_exts(ssl, p, end,
    659                                                         tls12_uses_ec,
    660                                                         &output_len);
    661         if (ret != 0) {
    662             return ret;
    663         }
    664         p += output_len;
    665     }
    666 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
    667 
    668 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
    669     /* The "pre_shared_key" extension (RFC 8446 Section 4.2.11)
    670      * MUST be the last extension in the ClientHello.
    671      */
    672     if (propose_tls13 && mbedtls_ssl_conf_tls13_is_some_psk_enabled(ssl)) {
    673         ret = mbedtls_ssl_tls13_write_identities_of_pre_shared_key_ext(
    674             ssl, p, end, &output_len, binders_len);
    675         if (ret != 0) {
    676             return ret;
    677         }
    678         p += output_len;
    679     }
    680 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
    681 
    682     /* Write the length of the list of extensions. */
    683     extensions_len = (size_t) (p - p_extensions_len) - 2;
    684 
    685     if (extensions_len == 0) {
    686         p = p_extensions_len;
    687     } else {
    688         MBEDTLS_PUT_UINT16_BE(extensions_len, p_extensions_len, 0);
    689         MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, total extension length: %" \
    690                                   MBEDTLS_PRINTF_SIZET, extensions_len));
    691         MBEDTLS_SSL_DEBUG_BUF(3, "client hello extensions",
    692                               p_extensions_len, extensions_len);
    693     }
    694 
    695     *out_len = (size_t) (p - buf);
    696     return 0;
    697 }
    698 
    699 MBEDTLS_CHECK_RETURN_CRITICAL
    700 static int ssl_generate_random(mbedtls_ssl_context *ssl)
    701 {
    702     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
    703     unsigned char *randbytes = ssl->handshake->randbytes;
    704     size_t gmt_unix_time_len = 0;
    705 
    706     /*
    707      * Generate the random bytes
    708      *
    709      * TLS 1.2 case:
    710      * struct {
    711      *     uint32 gmt_unix_time;
    712      *     opaque random_bytes[28];
    713      * } Random;
    714      *
    715      * TLS 1.3 case:
    716      * opaque Random[32];
    717      */
    718     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
    719 #if defined(MBEDTLS_HAVE_TIME)
    720         mbedtls_time_t gmt_unix_time = mbedtls_time(NULL);
    721         MBEDTLS_PUT_UINT32_BE(gmt_unix_time, randbytes, 0);
    722         gmt_unix_time_len = 4;
    723 
    724         MBEDTLS_SSL_DEBUG_MSG(3,
    725                               ("client hello, current time: %" MBEDTLS_PRINTF_LONGLONG,
    726                                (long long) gmt_unix_time));
    727 #endif /* MBEDTLS_HAVE_TIME */
    728     }
    729 
    730     ret = ssl->conf->f_rng(ssl->conf->p_rng,
    731                            randbytes + gmt_unix_time_len,
    732                            MBEDTLS_CLIENT_HELLO_RANDOM_LEN - gmt_unix_time_len);
    733     return ret;
    734 }
    735 
    736 MBEDTLS_CHECK_RETURN_CRITICAL
    737 static int ssl_prepare_client_hello(mbedtls_ssl_context *ssl)
    738 {
    739     int ret;
    740     size_t session_id_len;
    741     mbedtls_ssl_session *session_negotiate = ssl->session_negotiate;
    742 
    743     if (session_negotiate == NULL) {
    744         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
    745     }
    746 
    747 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
    748     defined(MBEDTLS_SSL_SESSION_TICKETS) && \
    749     defined(MBEDTLS_HAVE_TIME)
    750 
    751     /* Check if a tls13 ticket has been configured. */
    752     if (ssl->handshake->resume != 0 &&
    753         session_negotiate->tls_version == MBEDTLS_SSL_VERSION_TLS1_3 &&
    754         session_negotiate->ticket != NULL) {
    755         mbedtls_ms_time_t now = mbedtls_ms_time();
    756         mbedtls_ms_time_t age = now - session_negotiate->ticket_reception_time;
    757         if (age < 0 ||
    758             age > (mbedtls_ms_time_t) session_negotiate->ticket_lifetime * 1000) {
    759             /* Without valid ticket, disable session resumption.*/
    760             MBEDTLS_SSL_DEBUG_MSG(
    761                 3, ("Ticket expired, disable session resumption"));
    762             ssl->handshake->resume = 0;
    763         }
    764     }
    765 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 &&
    766           MBEDTLS_SSL_SESSION_TICKETS &&
    767           MBEDTLS_HAVE_TIME */
    768 
    769     /* Bet on the highest configured version if we are not in a TLS 1.2
    770      * renegotiation or session resumption.
    771      */
    772 #if defined(MBEDTLS_SSL_RENEGOTIATION)
    773     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
    774         ssl->handshake->min_tls_version = ssl->tls_version;
    775     } else
    776 #endif
    777     {
    778         if (ssl->handshake->resume) {
    779             ssl->tls_version = session_negotiate->tls_version;
    780             ssl->handshake->min_tls_version = ssl->tls_version;
    781         } else {
    782             ssl->handshake->min_tls_version = ssl->conf->min_tls_version;
    783         }
    784     }
    785 
    786     /*
    787      * Generate the random bytes, except when responding to a verify request
    788      * where we MUST reuse the previously generated random bytes
    789      * (RFC 6347 4.2.1).
    790      */
    791 #if defined(MBEDTLS_SSL_PROTO_DTLS)
    792     if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
    793         (ssl->handshake->cookie == NULL))
    794 #endif
    795     {
    796 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
    797         if (!ssl->handshake->hello_retry_request_flag)
    798 #endif
    799         {
    800             ret = ssl_generate_random(ssl);
    801             if (ret != 0) {
    802                 MBEDTLS_SSL_DEBUG_RET(1, "Random bytes generation failed", ret);
    803                 return ret;
    804             }
    805         }
    806     }
    807 
    808     /*
    809      * Prepare session identifier. At that point, the length of the session
    810      * identifier in the SSL context `ssl->session_negotiate->id_len` is equal
    811      * to zero, except in the case of a TLS 1.2 session renegotiation or
    812      * session resumption.
    813      */
    814     session_id_len = session_negotiate->id_len;
    815 
    816 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
    817     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
    818         if (session_id_len < 16 || session_id_len > 32 ||
    819 #if defined(MBEDTLS_SSL_RENEGOTIATION)
    820             ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
    821 #endif
    822             ssl->handshake->resume == 0) {
    823             session_id_len = 0;
    824         }
    825 
    826 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
    827         /*
    828          * RFC 5077 section 3.4: "When presenting a ticket, the client MAY
    829          * generate and include a Session ID in the TLS ClientHello."
    830          */
    831         int renegotiating = 0;
    832 #if defined(MBEDTLS_SSL_RENEGOTIATION)
    833         if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
    834             renegotiating = 1;
    835         }
    836 #endif
    837         if (!renegotiating) {
    838             if ((session_negotiate->ticket != NULL) &&
    839                 (session_negotiate->ticket_len != 0)) {
    840                 session_id_len = 32;
    841             }
    842         }
    843 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
    844     }
    845 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
    846 
    847 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
    848     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
    849         /*
    850          * Create a legacy session identifier for the purpose of middlebox
    851          * compatibility only if one has not been created already, which is
    852          * the case if we are here for the TLS 1.3 second ClientHello.
    853          *
    854          * Versions of TLS before TLS 1.3 supported a "session resumption"
    855          * feature which has been merged with pre-shared keys in TLS 1.3
    856          * version. A client which has a cached session ID set by a pre-TLS 1.3
    857          * server SHOULD set this field to that value. In compatibility mode,
    858          * this field MUST be non-empty, so a client not offering a pre-TLS 1.3
    859          * session MUST generate a new 32-byte value. This value need not be
    860          * random but SHOULD be unpredictable to avoid implementations fixating
    861          * on a specific value (also known as ossification). Otherwise, it MUST
    862          * be set as a zero-length vector ( i.e., a zero-valued single byte
    863          * length field ).
    864          */
    865         session_id_len = 32;
    866     }
    867 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
    868 
    869     if (session_id_len != session_negotiate->id_len) {
    870         session_negotiate->id_len = session_id_len;
    871         if (session_id_len > 0) {
    872             ret = ssl->conf->f_rng(ssl->conf->p_rng,
    873                                    session_negotiate->id,
    874                                    session_id_len);
    875             if (ret != 0) {
    876                 MBEDTLS_SSL_DEBUG_RET(1, "creating session id failed", ret);
    877                 return ret;
    878             }
    879         }
    880     }
    881 
    882 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
    883     defined(MBEDTLS_SSL_SESSION_TICKETS) && \
    884     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
    885     const char *context_hostname = mbedtls_ssl_get_hostname_pointer(ssl);
    886     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3  &&
    887         ssl->handshake->resume) {
    888         int hostname_mismatch = context_hostname != NULL ||
    889                                 session_negotiate->hostname != NULL;
    890         if (context_hostname != NULL && session_negotiate->hostname != NULL) {
    891             hostname_mismatch = strcmp(
    892                 context_hostname, session_negotiate->hostname) != 0;
    893         }
    894 
    895         if (hostname_mismatch) {
    896             MBEDTLS_SSL_DEBUG_MSG(
    897                 1, ("Hostname mismatch the session ticket, "
    898                     "disable session resumption."));
    899             return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
    900         }
    901     } else {
    902         return mbedtls_ssl_session_set_hostname(session_negotiate,
    903                                                 context_hostname);
    904     }
    905 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 &&
    906           MBEDTLS_SSL_SESSION_TICKETS &&
    907           MBEDTLS_SSL_SERVER_NAME_INDICATION */
    908 
    909     return 0;
    910 }
    911 /*
    912  * Write ClientHello handshake message.
    913  * Handler for MBEDTLS_SSL_CLIENT_HELLO
    914  */
    915 int mbedtls_ssl_write_client_hello(mbedtls_ssl_context *ssl)
    916 {
    917     int ret = 0;
    918     unsigned char *buf;
    919     size_t buf_len, msg_len, binders_len;
    920 
    921     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write client hello"));
    922 
    923     MBEDTLS_SSL_PROC_CHK(ssl_prepare_client_hello(ssl));
    924 
    925     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
    926                              ssl, MBEDTLS_SSL_HS_CLIENT_HELLO,
    927                              &buf, &buf_len));
    928 
    929     MBEDTLS_SSL_PROC_CHK(ssl_write_client_hello_body(ssl, buf,
    930                                                      buf + buf_len,
    931                                                      &msg_len,
    932                                                      &binders_len));
    933 
    934 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_SSL_PROTO_DTLS)
    935     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
    936         ssl->out_msglen = msg_len + 4;
    937         mbedtls_ssl_send_flight_completed(ssl);
    938 
    939         /*
    940          * The two functions below may try to send data on the network and
    941          * can return with the MBEDTLS_ERR_SSL_WANT_READ error code when they
    942          * fail to do so and the transmission has to be retried later. In that
    943          * case as in fatal error cases, we return immediately. But we must have
    944          * set the handshake state to the next state at that point to ensure
    945          * that we will not write and send again a ClientHello when we
    946          * eventually succeed in sending the pending data.
    947          */
    948         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_HELLO);
    949 
    950         if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
    951             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
    952             return ret;
    953         }
    954 
    955         if ((ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
    956             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
    957             return ret;
    958         }
    959     } else
    960 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_SSL_PROTO_DTLS */
    961     {
    962 
    963         ret = mbedtls_ssl_add_hs_hdr_to_checksum(ssl,
    964                                                  MBEDTLS_SSL_HS_CLIENT_HELLO,
    965                                                  msg_len);
    966         if (ret != 0) {
    967             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_add_hs_hdr_to_checksum", ret);
    968             return ret;
    969         }
    970         ret = ssl->handshake->update_checksum(ssl, buf, msg_len - binders_len);
    971         if (ret != 0) {
    972             MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
    973             return ret;
    974         }
    975 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
    976         if (binders_len > 0) {
    977             MBEDTLS_SSL_PROC_CHK(
    978                 mbedtls_ssl_tls13_write_binders_of_pre_shared_key_ext(
    979                     ssl, buf + msg_len - binders_len, buf + msg_len));
    980             ret = ssl->handshake->update_checksum(ssl, buf + msg_len - binders_len,
    981                                                   binders_len);
    982             if (ret != 0) {
    983                 MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
    984                 return ret;
    985             }
    986         }
    987 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
    988 
    989         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(ssl,
    990                                                               buf_len,
    991                                                               msg_len));
    992 
    993         /*
    994          * Set next state. Note that if TLS 1.3 is proposed, this may be
    995          * overwritten by mbedtls_ssl_tls13_finalize_client_hello().
    996          */
    997         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_HELLO);
    998 
    999 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
   1000         if (ssl->handshake->min_tls_version <=  MBEDTLS_SSL_VERSION_TLS1_3 &&
   1001             MBEDTLS_SSL_VERSION_TLS1_3 <= ssl->tls_version) {
   1002             ret = mbedtls_ssl_tls13_finalize_client_hello(ssl);
   1003         }
   1004 #endif
   1005     }
   1006 
   1007 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
   1008     MBEDTLS_SSL_PRINT_EXTS(
   1009         3, MBEDTLS_SSL_HS_CLIENT_HELLO, ssl->handshake->sent_extensions);
   1010 #endif
   1011 
   1012 cleanup:
   1013 
   1014     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write client hello"));
   1015     return ret;
   1016 }
   1017 
   1018 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 || MBEDTLS_SSL_PROTO_TLS1_2 */
   1019 #endif /* MBEDTLS_SSL_CLI_C */