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 "mbedtls/debug.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
ssl_write_hostname_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)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     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  */
113 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_alpn_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * out_len)114 static 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 = 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 
216 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_supported_groups_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,int flags,size_t * out_len)217 static 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 = 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 = 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 
316 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_client_hello_cipher_suites(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,int * tls12_uses_ec,size_t * out_len)317 static 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 = 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 = 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  */
435 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_client_hello_body(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len,size_t * binders_len)436 static 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_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_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_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 = 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 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
695     MBEDTLS_SSL_PRINT_EXTS(
696         3, MBEDTLS_SSL_HS_CLIENT_HELLO, handshake->sent_extensions);
697 #endif
698 
699     *out_len = p - buf;
700     return 0;
701 }
702 
703 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_generate_random(mbedtls_ssl_context * ssl)704 static int ssl_generate_random(mbedtls_ssl_context *ssl)
705 {
706     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
707     unsigned char *randbytes = ssl->handshake->randbytes;
708     size_t gmt_unix_time_len = 0;
709 
710     /*
711      * Generate the random bytes
712      *
713      * TLS 1.2 case:
714      * struct {
715      *     uint32 gmt_unix_time;
716      *     opaque random_bytes[28];
717      * } Random;
718      *
719      * TLS 1.3 case:
720      * opaque Random[32];
721      */
722     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
723 #if defined(MBEDTLS_HAVE_TIME)
724         mbedtls_time_t gmt_unix_time = mbedtls_time(NULL);
725         MBEDTLS_PUT_UINT32_BE(gmt_unix_time, randbytes, 0);
726         gmt_unix_time_len = 4;
727 
728         MBEDTLS_SSL_DEBUG_MSG(3,
729                               ("client hello, current time: %" MBEDTLS_PRINTF_LONGLONG,
730                                (long long) gmt_unix_time));
731 #endif /* MBEDTLS_HAVE_TIME */
732     }
733 
734     ret = ssl->conf->f_rng(ssl->conf->p_rng,
735                            randbytes + gmt_unix_time_len,
736                            MBEDTLS_CLIENT_HELLO_RANDOM_LEN - gmt_unix_time_len);
737     return ret;
738 }
739 
740 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_prepare_client_hello(mbedtls_ssl_context * ssl)741 static int ssl_prepare_client_hello(mbedtls_ssl_context *ssl)
742 {
743     int ret;
744     size_t session_id_len;
745     mbedtls_ssl_session *session_negotiate = ssl->session_negotiate;
746 
747     if (session_negotiate == NULL) {
748         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
749     }
750 
751 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
752     defined(MBEDTLS_SSL_SESSION_TICKETS) && \
753     defined(MBEDTLS_HAVE_TIME)
754 
755     /* Check if a tls13 ticket has been configured. */
756     if (ssl->handshake->resume != 0 &&
757         session_negotiate->tls_version == MBEDTLS_SSL_VERSION_TLS1_3 &&
758         session_negotiate->ticket != NULL) {
759         mbedtls_time_t now = mbedtls_time(NULL);
760         uint64_t age = (uint64_t) (now - session_negotiate->ticket_received);
761         if (session_negotiate->ticket_received > now ||
762             age > session_negotiate->ticket_lifetime) {
763             /* Without valid ticket, disable session resumption.*/
764             MBEDTLS_SSL_DEBUG_MSG(
765                 3, ("Ticket expired, disable session resumption"));
766             ssl->handshake->resume = 0;
767         }
768     }
769 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 &&
770           MBEDTLS_SSL_SESSION_TICKETS &&
771           MBEDTLS_HAVE_TIME */
772 
773     if (ssl->conf->f_rng == NULL) {
774         MBEDTLS_SSL_DEBUG_MSG(1, ("no RNG provided"));
775         return MBEDTLS_ERR_SSL_NO_RNG;
776     }
777 
778     /* Bet on the highest configured version if we are not in a TLS 1.2
779      * renegotiation or session resumption.
780      */
781 #if defined(MBEDTLS_SSL_RENEGOTIATION)
782     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
783         ssl->handshake->min_tls_version = ssl->tls_version;
784     } else
785 #endif
786     {
787         if (ssl->handshake->resume) {
788             ssl->tls_version = session_negotiate->tls_version;
789             ssl->handshake->min_tls_version = ssl->tls_version;
790         } else {
791             ssl->handshake->min_tls_version = ssl->conf->min_tls_version;
792         }
793     }
794 
795     /*
796      * Generate the random bytes, except when responding to a verify request
797      * where we MUST reuse the previously generated random bytes
798      * (RFC 6347 4.2.1).
799      */
800 #if defined(MBEDTLS_SSL_PROTO_DTLS)
801     if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
802         (ssl->handshake->cookie == NULL))
803 #endif
804     {
805         ret = ssl_generate_random(ssl);
806         if (ret != 0) {
807             MBEDTLS_SSL_DEBUG_RET(1, "Random bytes generation failed", ret);
808             return ret;
809         }
810     }
811 
812     /*
813      * Prepare session identifier. At that point, the length of the session
814      * identifier in the SSL context `ssl->session_negotiate->id_len` is equal
815      * to zero, except in the case of a TLS 1.2 session renegotiation or
816      * session resumption.
817      */
818     session_id_len = session_negotiate->id_len;
819 
820 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
821     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
822         if (session_id_len < 16 || session_id_len > 32 ||
823 #if defined(MBEDTLS_SSL_RENEGOTIATION)
824             ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
825 #endif
826             ssl->handshake->resume == 0) {
827             session_id_len = 0;
828         }
829 
830 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
831         /*
832          * RFC 5077 section 3.4: "When presenting a ticket, the client MAY
833          * generate and include a Session ID in the TLS ClientHello."
834          */
835         int renegotiating = 0;
836 #if defined(MBEDTLS_SSL_RENEGOTIATION)
837         if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
838             renegotiating = 1;
839         }
840 #endif
841         if (!renegotiating) {
842             if ((session_negotiate->ticket != NULL) &&
843                 (session_negotiate->ticket_len != 0)) {
844                 session_id_len = 32;
845             }
846         }
847 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
848     }
849 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
850 
851 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
852     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
853         /*
854          * Create a legacy session identifier for the purpose of middlebox
855          * compatibility only if one has not been created already, which is
856          * the case if we are here for the TLS 1.3 second ClientHello.
857          *
858          * Versions of TLS before TLS 1.3 supported a "session resumption"
859          * feature which has been merged with pre-shared keys in TLS 1.3
860          * version. A client which has a cached session ID set by a pre-TLS 1.3
861          * server SHOULD set this field to that value. In compatibility mode,
862          * this field MUST be non-empty, so a client not offering a pre-TLS 1.3
863          * session MUST generate a new 32-byte value. This value need not be
864          * random but SHOULD be unpredictable to avoid implementations fixating
865          * on a specific value (also known as ossification). Otherwise, it MUST
866          * be set as a zero-length vector ( i.e., a zero-valued single byte
867          * length field ).
868          */
869         session_id_len = 32;
870     }
871 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
872 
873     if (session_id_len != session_negotiate->id_len) {
874         session_negotiate->id_len = session_id_len;
875         if (session_id_len > 0) {
876             ret = ssl->conf->f_rng(ssl->conf->p_rng,
877                                    session_negotiate->id,
878                                    session_id_len);
879             if (ret != 0) {
880                 MBEDTLS_SSL_DEBUG_RET(1, "creating session id failed", ret);
881                 return ret;
882             }
883         }
884     }
885 
886 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
887     defined(MBEDTLS_SSL_SESSION_TICKETS) && \
888     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
889     if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3  &&
890         ssl->handshake->resume) {
891         int hostname_mismatch = ssl->hostname != NULL ||
892                                 session_negotiate->hostname != NULL;
893         if (ssl->hostname != NULL && session_negotiate->hostname != NULL) {
894             hostname_mismatch = strcmp(
895                 ssl->hostname, session_negotiate->hostname) != 0;
896         }
897 
898         if (hostname_mismatch) {
899             MBEDTLS_SSL_DEBUG_MSG(
900                 1, ("Hostname mismatch the session ticket, "
901                     "disable session resumption."));
902             return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
903         }
904     } else {
905         return mbedtls_ssl_session_set_hostname(session_negotiate,
906                                                 ssl->hostname);
907     }
908 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 &&
909           MBEDTLS_SSL_SESSION_TICKETS &&
910           MBEDTLS_SSL_SERVER_NAME_INDICATION */
911 
912     return 0;
913 }
914 /*
915  * Write ClientHello handshake message.
916  * Handler for MBEDTLS_SSL_CLIENT_HELLO
917  */
mbedtls_ssl_write_client_hello(mbedtls_ssl_context * ssl)918 int mbedtls_ssl_write_client_hello(mbedtls_ssl_context *ssl)
919 {
920     int ret = 0;
921     unsigned char *buf;
922     size_t buf_len, msg_len, binders_len;
923 
924     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write client hello"));
925 
926     MBEDTLS_SSL_PROC_CHK(ssl_prepare_client_hello(ssl));
927 
928     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
929                              ssl, MBEDTLS_SSL_HS_CLIENT_HELLO,
930                              &buf, &buf_len));
931 
932     MBEDTLS_SSL_PROC_CHK(ssl_write_client_hello_body(ssl, buf,
933                                                      buf + buf_len,
934                                                      &msg_len,
935                                                      &binders_len));
936 
937 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_SSL_PROTO_DTLS)
938     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
939         ssl->out_msglen = msg_len + 4;
940         mbedtls_ssl_send_flight_completed(ssl);
941 
942         /*
943          * The two functions below may try to send data on the network and
944          * can return with the MBEDTLS_ERR_SSL_WANT_READ error code when they
945          * fail to do so and the transmission has to be retried later. In that
946          * case as in fatal error cases, we return immediately. But we must have
947          * set the handshake state to the next state at that point to ensure
948          * that we will not write and send again a ClientHello when we
949          * eventually succeed in sending the pending data.
950          */
951         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_HELLO);
952 
953         if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
954             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
955             return ret;
956         }
957 
958         if ((ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
959             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
960             return ret;
961         }
962     } else
963 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_SSL_PROTO_DTLS */
964     {
965 
966         ret = mbedtls_ssl_add_hs_hdr_to_checksum(ssl,
967                                                  MBEDTLS_SSL_HS_CLIENT_HELLO,
968                                                  msg_len);
969         if (ret != 0) {
970             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_add_hs_hdr_to_checksum", ret);
971             return ret;
972         }
973         ret = ssl->handshake->update_checksum(ssl, buf, msg_len - binders_len);
974         if (ret != 0) {
975             MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
976             return ret;
977         }
978 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
979         if (binders_len > 0) {
980             MBEDTLS_SSL_PROC_CHK(
981                 mbedtls_ssl_tls13_write_binders_of_pre_shared_key_ext(
982                     ssl, buf + msg_len - binders_len, buf + msg_len));
983             ret = ssl->handshake->update_checksum(ssl, buf + msg_len - binders_len,
984                                                   binders_len);
985             if (ret != 0) {
986                 MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
987                 return ret;
988             }
989         }
990 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
991 
992         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(ssl,
993                                                               buf_len,
994                                                               msg_len));
995 
996         /*
997          * Set next state. Note that if TLS 1.3 is proposed, this may be
998          * overwritten by mbedtls_ssl_tls13_finalize_client_hello().
999          */
1000         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_HELLO);
1001 
1002 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1003         if (ssl->handshake->min_tls_version <=  MBEDTLS_SSL_VERSION_TLS1_3 &&
1004             MBEDTLS_SSL_VERSION_TLS1_3 <= ssl->tls_version) {
1005             ret = mbedtls_ssl_tls13_finalize_client_hello(ssl);
1006         }
1007 #endif
1008     }
1009 
1010 cleanup:
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