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