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