1 /*
2  *  TLS 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) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
11 
12 #include <string.h>
13 
14 #include "debug_internal.h"
15 #include "mbedtls/error.h"
16 #include "mbedtls/platform.h"
17 
18 #include "ssl_misc.h"
19 #include "ssl_client.h"
20 #include "ssl_tls13_keys.h"
21 #include "ssl_debug_helpers.h"
22 #include "mbedtls/psa_util.h"
23 
24 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
25 /* Define a local translating function to save code size by not using too many
26  * arguments in each translating place. */
local_err_translation(psa_status_t status)27 static int local_err_translation(psa_status_t status)
28 {
29     return psa_status_to_mbedtls(status, psa_to_ssl_errors,
30                                  ARRAY_LENGTH(psa_to_ssl_errors),
31                                  psa_generic_status_to_mbedtls);
32 }
33 #define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
34 #endif
35 
36 /* Write extensions */
37 
38 /*
39  * ssl_tls13_write_supported_versions_ext():
40  *
41  * struct {
42  *      ProtocolVersion versions<2..254>;
43  * } SupportedVersions;
44  */
45 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_supported_versions_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)46 static int ssl_tls13_write_supported_versions_ext(mbedtls_ssl_context *ssl,
47                                                   unsigned char *buf,
48                                                   unsigned char *end,
49                                                   size_t *out_len)
50 {
51     unsigned char *p = buf;
52     unsigned char versions_len = (ssl->handshake->min_tls_version <=
53                                   MBEDTLS_SSL_VERSION_TLS1_2) ? 4 : 2;
54 
55     *out_len = 0;
56 
57     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, adding supported versions extension"));
58 
59     /* Check if we have space to write the extension:
60      * - extension_type         (2 bytes)
61      * - extension_data_length  (2 bytes)
62      * - versions_length        (1 byte )
63      * - versions               (2 or 4 bytes)
64      */
65     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 5 + versions_len);
66 
67     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS, p, 0);
68     MBEDTLS_PUT_UINT16_BE(versions_len + 1, p, 2);
69     p += 4;
70 
71     /* Length of versions */
72     *p++ = versions_len;
73 
74     /* Write values of supported versions.
75      * They are defined by the configuration.
76      * Currently, we advertise only TLS 1.3 or both TLS 1.3 and TLS 1.2.
77      */
78     mbedtls_ssl_write_version(p, MBEDTLS_SSL_TRANSPORT_STREAM,
79                               MBEDTLS_SSL_VERSION_TLS1_3);
80     MBEDTLS_SSL_DEBUG_MSG(3, ("supported version: [3:4]"));
81 
82 
83     if (ssl->handshake->min_tls_version <= MBEDTLS_SSL_VERSION_TLS1_2) {
84         mbedtls_ssl_write_version(p + 2, MBEDTLS_SSL_TRANSPORT_STREAM,
85                                   MBEDTLS_SSL_VERSION_TLS1_2);
86         MBEDTLS_SSL_DEBUG_MSG(3, ("supported version: [3:3]"));
87     }
88 
89     *out_len = 5 + versions_len;
90 
91     mbedtls_ssl_tls13_set_hs_sent_ext_mask(
92         ssl, MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS);
93 
94     return 0;
95 }
96 
97 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_supported_versions_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)98 static int ssl_tls13_parse_supported_versions_ext(mbedtls_ssl_context *ssl,
99                                                   const unsigned char *buf,
100                                                   const unsigned char *end)
101 {
102     ((void) ssl);
103 
104     MBEDTLS_SSL_CHK_BUF_READ_PTR(buf, end, 2);
105     if (mbedtls_ssl_read_version(buf, ssl->conf->transport) !=
106         MBEDTLS_SSL_VERSION_TLS1_3) {
107         MBEDTLS_SSL_DEBUG_MSG(1, ("unexpected version"));
108 
109         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
110                                      MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
111         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
112     }
113 
114     if (&buf[2] != end) {
115         MBEDTLS_SSL_DEBUG_MSG(
116             1, ("supported_versions ext data length incorrect"));
117         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
118                                      MBEDTLS_ERR_SSL_DECODE_ERROR);
119         return MBEDTLS_ERR_SSL_DECODE_ERROR;
120     }
121 
122     return 0;
123 }
124 
125 #if defined(MBEDTLS_SSL_ALPN)
126 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_alpn_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)127 static int ssl_tls13_parse_alpn_ext(mbedtls_ssl_context *ssl,
128                                     const unsigned char *buf, size_t len)
129 {
130     const unsigned char *p = buf;
131     const unsigned char *end = buf + len;
132     size_t protocol_name_list_len, protocol_name_len;
133     const unsigned char *protocol_name_list_end;
134 
135     /* If we didn't send it, the server shouldn't send it */
136     if (ssl->conf->alpn_list == NULL) {
137         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
138     }
139 
140     /*
141      * opaque ProtocolName<1..2^8-1>;
142      *
143      * struct {
144      *     ProtocolName protocol_name_list<2..2^16-1>
145      * } ProtocolNameList;
146      *
147      * the "ProtocolNameList" MUST contain exactly one "ProtocolName"
148      */
149 
150     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
151     protocol_name_list_len = MBEDTLS_GET_UINT16_BE(p, 0);
152     p += 2;
153 
154     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, protocol_name_list_len);
155     protocol_name_list_end = p + protocol_name_list_len;
156 
157     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, protocol_name_list_end, 1);
158     protocol_name_len = *p++;
159 
160     /* Check that the server chosen protocol was in our list and save it */
161     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, protocol_name_list_end, protocol_name_len);
162     for (const char **alpn = ssl->conf->alpn_list; *alpn != NULL; alpn++) {
163         if (protocol_name_len == strlen(*alpn) &&
164             memcmp(p, *alpn, protocol_name_len) == 0) {
165             ssl->alpn_chosen = *alpn;
166             return 0;
167         }
168     }
169 
170     return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
171 }
172 #endif /* MBEDTLS_SSL_ALPN */
173 
174 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_reset_key_share(mbedtls_ssl_context * ssl)175 static int ssl_tls13_reset_key_share(mbedtls_ssl_context *ssl)
176 {
177     uint16_t group_id = ssl->handshake->offered_group_id;
178 
179     if (group_id == 0) {
180         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
181     }
182 
183 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
184     if (mbedtls_ssl_tls13_named_group_is_ecdhe(group_id) ||
185         mbedtls_ssl_tls13_named_group_is_ffdh(group_id)) {
186         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
187         psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
188 
189         /* Destroy generated private key. */
190         status = psa_destroy_key(ssl->handshake->xxdh_psa_privkey);
191         if (status != PSA_SUCCESS) {
192             ret = PSA_TO_MBEDTLS_ERR(status);
193             MBEDTLS_SSL_DEBUG_RET(1, "psa_destroy_key", ret);
194             return ret;
195         }
196 
197         ssl->handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
198         return 0;
199     } else
200 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
201     if (0 /* other KEMs? */) {
202         /* Do something */
203     }
204 
205     return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
206 }
207 
208 /*
209  * Functions for writing key_share extension.
210  */
211 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
212 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_get_default_group_id(mbedtls_ssl_context * ssl,uint16_t * group_id)213 static int ssl_tls13_get_default_group_id(mbedtls_ssl_context *ssl,
214                                           uint16_t *group_id)
215 {
216     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
217 
218 
219 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
220     const uint16_t *group_list = mbedtls_ssl_get_groups(ssl);
221     /* Pick first available ECDHE group compatible with TLS 1.3 */
222     if (group_list == NULL) {
223         return MBEDTLS_ERR_SSL_BAD_CONFIG;
224     }
225 
226     for (; *group_list != 0; group_list++) {
227 #if defined(PSA_WANT_ALG_ECDH)
228         if ((mbedtls_ssl_get_psa_curve_info_from_tls_id(
229                  *group_list, NULL, NULL) == PSA_SUCCESS) &&
230             mbedtls_ssl_tls13_named_group_is_ecdhe(*group_list)) {
231             *group_id = *group_list;
232             return 0;
233         }
234 #endif
235 #if defined(PSA_WANT_ALG_FFDH)
236         if (mbedtls_ssl_tls13_named_group_is_ffdh(*group_list)) {
237             *group_id = *group_list;
238             return 0;
239         }
240 #endif
241     }
242 #else
243     ((void) ssl);
244     ((void) group_id);
245 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
246 
247     return ret;
248 }
249 
250 /*
251  * ssl_tls13_write_key_share_ext
252  *
253  * Structure of key_share extension in ClientHello:
254  *
255  *  struct {
256  *          NamedGroup group;
257  *          opaque key_exchange<1..2^16-1>;
258  *      } KeyShareEntry;
259  *  struct {
260  *          KeyShareEntry client_shares<0..2^16-1>;
261  *      } KeyShareClientHello;
262  */
263 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_key_share_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)264 static int ssl_tls13_write_key_share_ext(mbedtls_ssl_context *ssl,
265                                          unsigned char *buf,
266                                          unsigned char *end,
267                                          size_t *out_len)
268 {
269     unsigned char *p = buf;
270     unsigned char *client_shares; /* Start of client_shares */
271     size_t client_shares_len;     /* Length of client_shares */
272     uint16_t group_id;
273     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
274 
275     *out_len = 0;
276 
277     /* Check if we have space for header and length fields:
278      * - extension_type         (2 bytes)
279      * - extension_data_length  (2 bytes)
280      * - client_shares_length   (2 bytes)
281      */
282     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 6);
283     p += 6;
284 
285     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello: adding key share extension"));
286 
287     /* HRR could already have requested something else. */
288     group_id = ssl->handshake->offered_group_id;
289     if (!mbedtls_ssl_tls13_named_group_is_ecdhe(group_id) &&
290         !mbedtls_ssl_tls13_named_group_is_ffdh(group_id)) {
291         MBEDTLS_SSL_PROC_CHK(ssl_tls13_get_default_group_id(ssl,
292                                                             &group_id));
293     }
294 
295     /*
296      * Dispatch to type-specific key generation function.
297      *
298      * So far, we're only supporting ECDHE. With the introduction
299      * of PQC KEMs, we'll want to have multiple branches, one per
300      * type of KEM, and dispatch to the corresponding crypto. And
301      * only one key share entry is allowed.
302      */
303     client_shares = p;
304 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
305     if (mbedtls_ssl_tls13_named_group_is_ecdhe(group_id) ||
306         mbedtls_ssl_tls13_named_group_is_ffdh(group_id)) {
307         /* Pointer to group */
308         unsigned char *group = p;
309         /* Length of key_exchange */
310         size_t key_exchange_len = 0;
311 
312         /* Check there is space for header of KeyShareEntry
313          * - group                  (2 bytes)
314          * - key_exchange_length    (2 bytes)
315          */
316         MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4);
317         p += 4;
318         ret = mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange(
319             ssl, group_id, p, end, &key_exchange_len);
320         p += key_exchange_len;
321         if (ret != 0) {
322             return ret;
323         }
324 
325         /* Write group */
326         MBEDTLS_PUT_UINT16_BE(group_id, group, 0);
327         /* Write key_exchange_length */
328         MBEDTLS_PUT_UINT16_BE(key_exchange_len, group, 2);
329     } else
330 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
331     if (0 /* other KEMs? */) {
332         /* Do something */
333     } else {
334         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
335     }
336 
337     /* Length of client_shares */
338     client_shares_len = p - client_shares;
339     if (client_shares_len == 0) {
340         MBEDTLS_SSL_DEBUG_MSG(1, ("No key share defined."));
341         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
342     }
343     /* Write extension_type */
344     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_KEY_SHARE, buf, 0);
345     /* Write extension_data_length */
346     MBEDTLS_PUT_UINT16_BE(client_shares_len + 2, buf, 2);
347     /* Write client_shares_length */
348     MBEDTLS_PUT_UINT16_BE(client_shares_len, buf, 4);
349 
350     /* Update offered_group_id field */
351     ssl->handshake->offered_group_id = group_id;
352 
353     /* Output the total length of key_share extension. */
354     *out_len = p - buf;
355 
356     MBEDTLS_SSL_DEBUG_BUF(
357         3, "client hello, key_share extension", buf, *out_len);
358 
359     mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_KEY_SHARE);
360 
361 cleanup:
362 
363     return ret;
364 }
365 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
366 
367 /*
368  * ssl_tls13_parse_hrr_key_share_ext()
369  *      Parse key_share extension in Hello Retry Request
370  *
371  * struct {
372  *        NamedGroup selected_group;
373  * } KeyShareHelloRetryRequest;
374  */
375 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_hrr_key_share_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)376 static int ssl_tls13_parse_hrr_key_share_ext(mbedtls_ssl_context *ssl,
377                                              const unsigned char *buf,
378                                              const unsigned char *end)
379 {
380 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
381     const unsigned char *p = buf;
382     int selected_group;
383     int found = 0;
384 
385     const uint16_t *group_list = mbedtls_ssl_get_groups(ssl);
386     if (group_list == NULL) {
387         return MBEDTLS_ERR_SSL_BAD_CONFIG;
388     }
389 
390     MBEDTLS_SSL_DEBUG_BUF(3, "key_share extension", p, end - buf);
391 
392     /* Read selected_group */
393     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
394     selected_group = MBEDTLS_GET_UINT16_BE(p, 0);
395     MBEDTLS_SSL_DEBUG_MSG(3, ("selected_group ( %d )", selected_group));
396 
397     /* Upon receipt of this extension in a HelloRetryRequest, the client
398      * MUST first verify that the selected_group field corresponds to a
399      * group which was provided in the "supported_groups" extension in the
400      * original ClientHello.
401      * The supported_group was based on the info in ssl->conf->group_list.
402      *
403      * If the server provided a key share that was not sent in the ClientHello
404      * then the client MUST abort the handshake with an "illegal_parameter" alert.
405      */
406     for (; *group_list != 0; group_list++) {
407 #if defined(PSA_WANT_ALG_ECDH)
408         if (mbedtls_ssl_tls13_named_group_is_ecdhe(*group_list)) {
409             if ((mbedtls_ssl_get_psa_curve_info_from_tls_id(
410                      *group_list, NULL, NULL) == PSA_ERROR_NOT_SUPPORTED) ||
411                 *group_list != selected_group) {
412                 found = 1;
413                 break;
414             }
415         }
416 #endif /* PSA_WANT_ALG_ECDH */
417 #if defined(PSA_WANT_ALG_FFDH)
418         if (mbedtls_ssl_tls13_named_group_is_ffdh(*group_list)) {
419             found = 1;
420             break;
421         }
422 #endif /* PSA_WANT_ALG_FFDH */
423     }
424 
425     /* Client MUST verify that the selected_group field does not
426      * correspond to a group which was provided in the "key_share"
427      * extension in the original ClientHello. If the server sent an
428      * HRR message with a key share already provided in the
429      * ClientHello then the client MUST abort the handshake with
430      * an "illegal_parameter" alert.
431      */
432     if (found == 0 || selected_group == ssl->handshake->offered_group_id) {
433         MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid key share in HRR"));
434         MBEDTLS_SSL_PEND_FATAL_ALERT(
435             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
436             MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
437         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
438     }
439 
440     /* Remember server's preference for next ClientHello */
441     ssl->handshake->offered_group_id = selected_group;
442 
443     return 0;
444 #else /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
445     (void) ssl;
446     (void) buf;
447     (void) end;
448     return MBEDTLS_ERR_SSL_BAD_CONFIG;
449 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
450 }
451 
452 /*
453  * ssl_tls13_parse_key_share_ext()
454  *      Parse key_share extension in Server Hello
455  *
456  * struct {
457  *        KeyShareEntry server_share;
458  * } KeyShareServerHello;
459  * struct {
460  *        NamedGroup group;
461  *        opaque key_exchange<1..2^16-1>;
462  * } KeyShareEntry;
463  */
464 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_key_share_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)465 static int ssl_tls13_parse_key_share_ext(mbedtls_ssl_context *ssl,
466                                          const unsigned char *buf,
467                                          const unsigned char *end)
468 {
469     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
470     const unsigned char *p = buf;
471     uint16_t group, offered_group;
472 
473     /* ...
474      * NamedGroup group; (2 bytes)
475      * ...
476      */
477     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
478     group = MBEDTLS_GET_UINT16_BE(p, 0);
479     p += 2;
480 
481     /* Check that the chosen group matches the one we offered. */
482     offered_group = ssl->handshake->offered_group_id;
483     if (offered_group != group) {
484         MBEDTLS_SSL_DEBUG_MSG(
485             1, ("Invalid server key share, our group %u, their group %u",
486                 (unsigned) offered_group, (unsigned) group));
487         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
488                                      MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
489         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
490     }
491 
492 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
493     if (mbedtls_ssl_tls13_named_group_is_ecdhe(group) ||
494         mbedtls_ssl_tls13_named_group_is_ffdh(group)) {
495         MBEDTLS_SSL_DEBUG_MSG(2,
496                               ("DHE group name: %s", mbedtls_ssl_named_group_to_str(group)));
497         ret = mbedtls_ssl_tls13_read_public_xxdhe_share(ssl, p, end - p);
498         if (ret != 0) {
499             return ret;
500         }
501     } else
502 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
503     if (0 /* other KEMs? */) {
504         /* Do something */
505     } else {
506         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
507     }
508 
509     return ret;
510 }
511 
512 /*
513  * ssl_tls13_parse_cookie_ext()
514  *      Parse cookie extension in Hello Retry Request
515  *
516  * struct {
517  *        opaque cookie<1..2^16-1>;
518  * } Cookie;
519  *
520  * When sending a HelloRetryRequest, the server MAY provide a "cookie"
521  * extension to the client (this is an exception to the usual rule that
522  * the only extensions that may be sent are those that appear in the
523  * ClientHello).  When sending the new ClientHello, the client MUST copy
524  * the contents of the extension received in the HelloRetryRequest into
525  * a "cookie" extension in the new ClientHello.  Clients MUST NOT use
526  * cookies in their initial ClientHello in subsequent connections.
527  */
528 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_cookie_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)529 static int ssl_tls13_parse_cookie_ext(mbedtls_ssl_context *ssl,
530                                       const unsigned char *buf,
531                                       const unsigned char *end)
532 {
533     uint16_t cookie_len;
534     const unsigned char *p = buf;
535     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
536 
537     /* Retrieve length field of cookie */
538     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
539     cookie_len = MBEDTLS_GET_UINT16_BE(p, 0);
540     p += 2;
541 
542     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, cookie_len);
543     MBEDTLS_SSL_DEBUG_BUF(3, "cookie extension", p, cookie_len);
544 
545     mbedtls_free(handshake->cookie);
546     handshake->cookie_len = 0;
547     handshake->cookie = mbedtls_calloc(1, cookie_len);
548     if (handshake->cookie == NULL) {
549         MBEDTLS_SSL_DEBUG_MSG(1,
550                               ("alloc failed ( %ud bytes )",
551                                cookie_len));
552         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
553     }
554 
555     memcpy(handshake->cookie, p, cookie_len);
556     handshake->cookie_len = cookie_len;
557 
558     return 0;
559 }
560 
561 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_cookie_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)562 static int ssl_tls13_write_cookie_ext(mbedtls_ssl_context *ssl,
563                                       unsigned char *buf,
564                                       unsigned char *end,
565                                       size_t *out_len)
566 {
567     unsigned char *p = buf;
568     *out_len = 0;
569     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
570 
571     if (handshake->cookie == NULL) {
572         MBEDTLS_SSL_DEBUG_MSG(3, ("no cookie to send; skip extension"));
573         return 0;
574     }
575 
576     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, cookie",
577                           handshake->cookie,
578                           handshake->cookie_len);
579 
580     MBEDTLS_SSL_CHK_BUF_PTR(p, end, handshake->cookie_len + 6);
581 
582     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, adding cookie extension"));
583 
584     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_COOKIE, p, 0);
585     MBEDTLS_PUT_UINT16_BE(handshake->cookie_len + 2, p, 2);
586     MBEDTLS_PUT_UINT16_BE(handshake->cookie_len, p, 4);
587     p += 6;
588 
589     /* Cookie */
590     memcpy(p, handshake->cookie, handshake->cookie_len);
591 
592     *out_len = handshake->cookie_len + 6;
593 
594     mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_COOKIE);
595 
596     return 0;
597 }
598 
599 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
600 /*
601  * ssl_tls13_write_psk_key_exchange_modes_ext() structure:
602  *
603  * enum { psk_ke( 0 ), psk_dhe_ke( 1 ), ( 255 ) } PskKeyExchangeMode;
604  *
605  * struct {
606  *     PskKeyExchangeMode ke_modes<1..255>;
607  * } PskKeyExchangeModes;
608  */
609 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_psk_key_exchange_modes_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)610 static int ssl_tls13_write_psk_key_exchange_modes_ext(mbedtls_ssl_context *ssl,
611                                                       unsigned char *buf,
612                                                       unsigned char *end,
613                                                       size_t *out_len)
614 {
615     unsigned char *p = buf;
616     int ke_modes_len = 0;
617 
618     ((void) ke_modes_len);
619     *out_len = 0;
620 
621     /* Skip writing extension if no PSK key exchange mode
622      * is enabled in the config.
623      */
624     if (!mbedtls_ssl_conf_tls13_is_some_psk_enabled(ssl)) {
625         MBEDTLS_SSL_DEBUG_MSG(3, ("skip psk_key_exchange_modes extension"));
626         return 0;
627     }
628 
629     /* Require 7 bytes of data, otherwise fail,
630      * even if extension might be shorter.
631      */
632     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 7);
633     MBEDTLS_SSL_DEBUG_MSG(
634         3, ("client hello, adding psk_key_exchange_modes extension"));
635 
636     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES, p, 0);
637 
638     /* Skip extension length (2 bytes) and
639      * ke_modes length (1 byte) for now.
640      */
641     p += 5;
642 
643     if (mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(ssl)) {
644         *p++ = MBEDTLS_SSL_TLS1_3_PSK_MODE_ECDHE;
645         ke_modes_len++;
646 
647         MBEDTLS_SSL_DEBUG_MSG(4, ("Adding PSK-ECDHE key exchange mode"));
648     }
649 
650     if (mbedtls_ssl_conf_tls13_is_psk_enabled(ssl)) {
651         *p++ = MBEDTLS_SSL_TLS1_3_PSK_MODE_PURE;
652         ke_modes_len++;
653 
654         MBEDTLS_SSL_DEBUG_MSG(4, ("Adding pure PSK key exchange mode"));
655     }
656 
657     /* Now write the extension and ke_modes length */
658     MBEDTLS_PUT_UINT16_BE(ke_modes_len + 1, buf, 2);
659     buf[4] = ke_modes_len;
660 
661     *out_len = p - buf;
662 
663     mbedtls_ssl_tls13_set_hs_sent_ext_mask(
664         ssl, MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES);
665 
666     return 0;
667 }
668 
669 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_tls13_get_ciphersuite_hash_alg(int ciphersuite)670 static psa_algorithm_t ssl_tls13_get_ciphersuite_hash_alg(int ciphersuite)
671 {
672     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = NULL;
673     ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(ciphersuite);
674 
675     if (ciphersuite_info != NULL) {
676         return mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ciphersuite_info->mac);
677     }
678 
679     return PSA_ALG_NONE;
680 }
681 
ssl_tls13_has_configured_ticket(mbedtls_ssl_context * ssl)682 static int ssl_tls13_has_configured_ticket(mbedtls_ssl_context *ssl)
683 {
684     mbedtls_ssl_session *session = ssl->session_negotiate;
685     return ssl->handshake->resume &&
686            session != NULL && session->ticket != NULL &&
687            mbedtls_ssl_conf_tls13_is_kex_mode_enabled(
688         ssl, mbedtls_ssl_tls13_session_get_ticket_flags(
689             session, MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL));
690 }
691 
692 #if defined(MBEDTLS_SSL_EARLY_DATA)
ssl_tls13_early_data_has_valid_ticket(mbedtls_ssl_context * ssl)693 static int ssl_tls13_early_data_has_valid_ticket(mbedtls_ssl_context *ssl)
694 {
695     mbedtls_ssl_session *session = ssl->session_negotiate;
696     return ssl->handshake->resume &&
697            session->tls_version == MBEDTLS_SSL_VERSION_TLS1_3 &&
698            mbedtls_ssl_tls13_session_ticket_allow_early_data(session) &&
699            mbedtls_ssl_tls13_cipher_suite_is_offered(ssl, session->ciphersuite);
700 }
701 #endif
702 
703 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_ticket_get_identity(mbedtls_ssl_context * ssl,psa_algorithm_t * hash_alg,const unsigned char ** identity,size_t * identity_len)704 static int ssl_tls13_ticket_get_identity(mbedtls_ssl_context *ssl,
705                                          psa_algorithm_t *hash_alg,
706                                          const unsigned char **identity,
707                                          size_t *identity_len)
708 {
709     mbedtls_ssl_session *session = ssl->session_negotiate;
710 
711     if (!ssl_tls13_has_configured_ticket(ssl)) {
712         return -1;
713     }
714 
715     *hash_alg = ssl_tls13_get_ciphersuite_hash_alg(session->ciphersuite);
716     *identity = session->ticket;
717     *identity_len = session->ticket_len;
718     return 0;
719 }
720 
721 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_ticket_get_psk(mbedtls_ssl_context * ssl,psa_algorithm_t * hash_alg,const unsigned char ** psk,size_t * psk_len)722 static int ssl_tls13_ticket_get_psk(mbedtls_ssl_context *ssl,
723                                     psa_algorithm_t *hash_alg,
724                                     const unsigned char **psk,
725                                     size_t *psk_len)
726 {
727 
728     mbedtls_ssl_session *session = ssl->session_negotiate;
729 
730     if (!ssl_tls13_has_configured_ticket(ssl)) {
731         return -1;
732     }
733 
734     *hash_alg = ssl_tls13_get_ciphersuite_hash_alg(session->ciphersuite);
735     *psk = session->resumption_key;
736     *psk_len = session->resumption_key_len;
737 
738     return 0;
739 }
740 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
741 
742 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_psk_get_identity(mbedtls_ssl_context * ssl,psa_algorithm_t * hash_alg,const unsigned char ** identity,size_t * identity_len)743 static int ssl_tls13_psk_get_identity(mbedtls_ssl_context *ssl,
744                                       psa_algorithm_t *hash_alg,
745                                       const unsigned char **identity,
746                                       size_t *identity_len)
747 {
748 
749     if (!mbedtls_ssl_conf_has_static_psk(ssl->conf)) {
750         return -1;
751     }
752 
753     *hash_alg = PSA_ALG_SHA_256;
754     *identity = ssl->conf->psk_identity;
755     *identity_len = ssl->conf->psk_identity_len;
756     return 0;
757 }
758 
759 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_psk_get_psk(mbedtls_ssl_context * ssl,psa_algorithm_t * hash_alg,const unsigned char ** psk,size_t * psk_len)760 static int ssl_tls13_psk_get_psk(mbedtls_ssl_context *ssl,
761                                  psa_algorithm_t *hash_alg,
762                                  const unsigned char **psk,
763                                  size_t *psk_len)
764 {
765 
766     if (!mbedtls_ssl_conf_has_static_psk(ssl->conf)) {
767         return -1;
768     }
769 
770     *hash_alg = PSA_ALG_SHA_256;
771     *psk = ssl->conf->psk;
772     *psk_len = ssl->conf->psk_len;
773     return 0;
774 }
775 
ssl_tls13_get_configured_psk_count(mbedtls_ssl_context * ssl)776 static int ssl_tls13_get_configured_psk_count(mbedtls_ssl_context *ssl)
777 {
778     int configured_psk_count = 0;
779 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
780     if (ssl_tls13_has_configured_ticket(ssl)) {
781         MBEDTLS_SSL_DEBUG_MSG(3, ("Ticket is configured"));
782         configured_psk_count++;
783     }
784 #endif
785     if (mbedtls_ssl_conf_has_static_psk(ssl->conf)) {
786         MBEDTLS_SSL_DEBUG_MSG(3, ("PSK is configured"));
787         configured_psk_count++;
788     }
789     return configured_psk_count;
790 }
791 
792 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_identity(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,const unsigned char * identity,size_t identity_len,uint32_t obfuscated_ticket_age,size_t * out_len)793 static int ssl_tls13_write_identity(mbedtls_ssl_context *ssl,
794                                     unsigned char *buf,
795                                     unsigned char *end,
796                                     const unsigned char *identity,
797                                     size_t identity_len,
798                                     uint32_t obfuscated_ticket_age,
799                                     size_t *out_len)
800 {
801     ((void) ssl);
802     *out_len = 0;
803 
804     /*
805      * - identity_len           (2 bytes)
806      * - identity               (psk_identity_len bytes)
807      * - obfuscated_ticket_age  (4 bytes)
808      */
809     MBEDTLS_SSL_CHK_BUF_PTR(buf, end, 6 + identity_len);
810 
811     MBEDTLS_PUT_UINT16_BE(identity_len, buf, 0);
812     memcpy(buf + 2, identity, identity_len);
813     MBEDTLS_PUT_UINT32_BE(obfuscated_ticket_age, buf, 2 + identity_len);
814 
815     MBEDTLS_SSL_DEBUG_BUF(4, "write identity", buf, 6 + identity_len);
816 
817     *out_len = 6 + identity_len;
818 
819     return 0;
820 }
821 
822 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_binder(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,int psk_type,psa_algorithm_t hash_alg,const unsigned char * psk,size_t psk_len,size_t * out_len)823 static int ssl_tls13_write_binder(mbedtls_ssl_context *ssl,
824                                   unsigned char *buf,
825                                   unsigned char *end,
826                                   int psk_type,
827                                   psa_algorithm_t hash_alg,
828                                   const unsigned char *psk,
829                                   size_t psk_len,
830                                   size_t *out_len)
831 {
832     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
833     unsigned char binder_len;
834     unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
835     size_t transcript_len = 0;
836 
837     *out_len = 0;
838 
839     binder_len = PSA_HASH_LENGTH(hash_alg);
840 
841     /*
842      * - binder_len           (1 bytes)
843      * - binder               (binder_len bytes)
844      */
845     MBEDTLS_SSL_CHK_BUF_PTR(buf, end, 1 + binder_len);
846 
847     buf[0] = binder_len;
848 
849     /* Get current state of handshake transcript. */
850     ret = mbedtls_ssl_get_handshake_transcript(
851         ssl, mbedtls_md_type_from_psa_alg(hash_alg),
852         transcript, sizeof(transcript), &transcript_len);
853     if (ret != 0) {
854         return ret;
855     }
856 
857     ret = mbedtls_ssl_tls13_create_psk_binder(ssl, hash_alg,
858                                               psk, psk_len, psk_type,
859                                               transcript, buf + 1);
860     if (ret != 0) {
861         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_create_psk_binder", ret);
862         return ret;
863     }
864     MBEDTLS_SSL_DEBUG_BUF(4, "write binder", buf, 1 + binder_len);
865 
866     *out_len = 1 + binder_len;
867 
868     return 0;
869 }
870 
871 /*
872  * mbedtls_ssl_tls13_write_identities_of_pre_shared_key_ext() structure:
873  *
874  * struct {
875  *   opaque identity<1..2^16-1>;
876  *   uint32 obfuscated_ticket_age;
877  * } PskIdentity;
878  *
879  * opaque PskBinderEntry<32..255>;
880  *
881  * struct {
882  *   PskIdentity identities<7..2^16-1>;
883  *   PskBinderEntry binders<33..2^16-1>;
884  * } OfferedPsks;
885  *
886  * struct {
887  *   select (Handshake.msg_type) {
888  *      case client_hello: OfferedPsks;
889  *      ...
890  *   };
891  * } PreSharedKeyExtension;
892  *
893  */
mbedtls_ssl_tls13_write_identities_of_pre_shared_key_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len,size_t * binders_len)894 int mbedtls_ssl_tls13_write_identities_of_pre_shared_key_ext(
895     mbedtls_ssl_context *ssl, unsigned char *buf, unsigned char *end,
896     size_t *out_len, size_t *binders_len)
897 {
898     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
899     int configured_psk_count = 0;
900     unsigned char *p = buf;
901     psa_algorithm_t hash_alg = PSA_ALG_NONE;
902     const unsigned char *identity;
903     size_t identity_len;
904     size_t l_binders_len = 0;
905     size_t output_len;
906 
907     *out_len = 0;
908     *binders_len = 0;
909 
910     /* Check if we have any PSKs to offer. If no, skip pre_shared_key */
911     configured_psk_count = ssl_tls13_get_configured_psk_count(ssl);
912     if (configured_psk_count == 0) {
913         MBEDTLS_SSL_DEBUG_MSG(3, ("skip pre_shared_key extensions"));
914         return 0;
915     }
916 
917     MBEDTLS_SSL_DEBUG_MSG(4, ("Pre-configured PSK number = %d",
918                               configured_psk_count));
919 
920     /* Check if we have space to write the extension, binders included.
921      * - extension_type         (2 bytes)
922      * - extension_data_len     (2 bytes)
923      * - identities_len         (2 bytes)
924      */
925     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 6);
926     p += 6;
927 
928 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
929     if (ssl_tls13_ticket_get_identity(
930             ssl, &hash_alg, &identity, &identity_len) == 0) {
931 #if defined(MBEDTLS_HAVE_TIME)
932         mbedtls_ms_time_t now = mbedtls_ms_time();
933         mbedtls_ssl_session *session = ssl->session_negotiate;
934         /* The ticket age has been checked to be smaller than the
935          * `ticket_lifetime` in ssl_prepare_client_hello() which is smaller than
936          * 7 days (enforced in ssl_tls13_parse_new_session_ticket()) . Thus the
937          * cast to `uint32_t` of the ticket age is safe. */
938         uint32_t obfuscated_ticket_age =
939             (uint32_t) (now - session->ticket_reception_time);
940         obfuscated_ticket_age += session->ticket_age_add;
941 
942         ret = ssl_tls13_write_identity(ssl, p, end,
943                                        identity, identity_len,
944                                        obfuscated_ticket_age,
945                                        &output_len);
946 #else
947         ret = ssl_tls13_write_identity(ssl, p, end, identity, identity_len,
948                                        0, &output_len);
949 #endif /* MBEDTLS_HAVE_TIME */
950         if (ret != 0) {
951             return ret;
952         }
953 
954         p += output_len;
955         l_binders_len += 1 + PSA_HASH_LENGTH(hash_alg);
956     }
957 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
958 
959     if (ssl_tls13_psk_get_identity(
960             ssl, &hash_alg, &identity, &identity_len) == 0) {
961 
962         ret = ssl_tls13_write_identity(ssl, p, end, identity, identity_len, 0,
963                                        &output_len);
964         if (ret != 0) {
965             return ret;
966         }
967 
968         p += output_len;
969         l_binders_len += 1 + PSA_HASH_LENGTH(hash_alg);
970     }
971 
972     MBEDTLS_SSL_DEBUG_MSG(3,
973                           ("client hello, adding pre_shared_key extension, "
974                            "omitting PSK binder list"));
975 
976     /* Take into account the two bytes for the length of the binders. */
977     l_binders_len += 2;
978     /* Check if there is enough space for binders */
979     MBEDTLS_SSL_CHK_BUF_PTR(p, end, l_binders_len);
980 
981     /*
982      * - extension_type         (2 bytes)
983      * - extension_data_len     (2 bytes)
984      * - identities_len         (2 bytes)
985      */
986     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_PRE_SHARED_KEY, buf, 0);
987     MBEDTLS_PUT_UINT16_BE(p - buf - 4 + l_binders_len, buf, 2);
988     MBEDTLS_PUT_UINT16_BE(p - buf - 6, buf, 4);
989 
990     *out_len = (p - buf) + l_binders_len;
991     *binders_len = l_binders_len;
992 
993     MBEDTLS_SSL_DEBUG_BUF(3, "pre_shared_key identities", buf, p - buf);
994 
995     return 0;
996 }
997 
mbedtls_ssl_tls13_write_binders_of_pre_shared_key_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end)998 int mbedtls_ssl_tls13_write_binders_of_pre_shared_key_ext(
999     mbedtls_ssl_context *ssl, unsigned char *buf, unsigned char *end)
1000 {
1001     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1002     unsigned char *p = buf;
1003     psa_algorithm_t hash_alg = PSA_ALG_NONE;
1004     const unsigned char *psk;
1005     size_t psk_len;
1006     size_t output_len;
1007 
1008     /* Check if we have space to write binders_len.
1009      * - binders_len         (2 bytes)
1010      */
1011     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
1012     p += 2;
1013 
1014 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1015     if (ssl_tls13_ticket_get_psk(ssl, &hash_alg, &psk, &psk_len) == 0) {
1016 
1017         ret = ssl_tls13_write_binder(ssl, p, end,
1018                                      MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION,
1019                                      hash_alg, psk, psk_len,
1020                                      &output_len);
1021         if (ret != 0) {
1022             return ret;
1023         }
1024         p += output_len;
1025     }
1026 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
1027 
1028     if (ssl_tls13_psk_get_psk(ssl, &hash_alg, &psk, &psk_len) == 0) {
1029 
1030         ret = ssl_tls13_write_binder(ssl, p, end,
1031                                      MBEDTLS_SSL_TLS1_3_PSK_EXTERNAL,
1032                                      hash_alg, psk, psk_len,
1033                                      &output_len);
1034         if (ret != 0) {
1035             return ret;
1036         }
1037         p += output_len;
1038     }
1039 
1040     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, adding PSK binder list."));
1041 
1042     /*
1043      * - binders_len         (2 bytes)
1044      */
1045     MBEDTLS_PUT_UINT16_BE(p - buf - 2, buf, 0);
1046 
1047     MBEDTLS_SSL_DEBUG_BUF(3, "pre_shared_key binders", buf, p - buf);
1048 
1049     mbedtls_ssl_tls13_set_hs_sent_ext_mask(
1050         ssl, MBEDTLS_TLS_EXT_PRE_SHARED_KEY);
1051 
1052     return 0;
1053 }
1054 
1055 /*
1056  * struct {
1057  *   opaque identity<1..2^16-1>;
1058  *   uint32 obfuscated_ticket_age;
1059  * } PskIdentity;
1060  *
1061  * opaque PskBinderEntry<32..255>;
1062  *
1063  * struct {
1064  *
1065  *   select (Handshake.msg_type) {
1066  *         ...
1067  *         case server_hello: uint16 selected_identity;
1068  *   };
1069  *
1070  * } PreSharedKeyExtension;
1071  *
1072  */
1073 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_server_pre_shared_key_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)1074 static int ssl_tls13_parse_server_pre_shared_key_ext(mbedtls_ssl_context *ssl,
1075                                                      const unsigned char *buf,
1076                                                      const unsigned char *end)
1077 {
1078     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1079     int selected_identity;
1080     const unsigned char *psk;
1081     size_t psk_len;
1082     psa_algorithm_t hash_alg;
1083 
1084     MBEDTLS_SSL_CHK_BUF_READ_PTR(buf, end, 2);
1085     selected_identity = MBEDTLS_GET_UINT16_BE(buf, 0);
1086     ssl->handshake->selected_identity = (uint16_t) selected_identity;
1087 
1088     MBEDTLS_SSL_DEBUG_MSG(3, ("selected_identity = %d", selected_identity));
1089 
1090     if (selected_identity >= ssl_tls13_get_configured_psk_count(ssl)) {
1091         MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid PSK identity."));
1092 
1093         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1094                                      MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1095         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1096     }
1097 
1098 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1099     if (selected_identity == 0 && ssl_tls13_has_configured_ticket(ssl)) {
1100         ret = ssl_tls13_ticket_get_psk(ssl, &hash_alg, &psk, &psk_len);
1101     } else
1102 #endif
1103     if (mbedtls_ssl_conf_has_static_psk(ssl->conf)) {
1104         ret = ssl_tls13_psk_get_psk(ssl, &hash_alg, &psk, &psk_len);
1105     } else {
1106         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1107         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1108     }
1109     if (ret != 0) {
1110         return ret;
1111     }
1112 
1113     if (mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ssl->handshake->ciphersuite_info->mac)
1114         != hash_alg) {
1115         MBEDTLS_SSL_DEBUG_MSG(
1116             1, ("Invalid ciphersuite for external psk."));
1117 
1118         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1119                                      MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1120         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1121     }
1122 
1123     ret = mbedtls_ssl_set_hs_psk(ssl, psk, psk_len);
1124     if (ret != 0) {
1125         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
1126         return ret;
1127     }
1128 
1129     return 0;
1130 }
1131 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
1132 
mbedtls_ssl_tls13_write_client_hello_exts(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)1133 int mbedtls_ssl_tls13_write_client_hello_exts(mbedtls_ssl_context *ssl,
1134                                               unsigned char *buf,
1135                                               unsigned char *end,
1136                                               size_t *out_len)
1137 {
1138     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1139     unsigned char *p = buf;
1140     size_t ext_len;
1141 
1142     *out_len = 0;
1143 
1144     ret = mbedtls_ssl_tls13_crypto_init(ssl);
1145     if (ret != 0) {
1146         return ret;
1147     }
1148 
1149     /* Write supported_versions extension
1150      *
1151      * Supported Versions Extension is mandatory with TLS 1.3.
1152      */
1153     ret = ssl_tls13_write_supported_versions_ext(ssl, p, end, &ext_len);
1154     if (ret != 0) {
1155         return ret;
1156     }
1157     p += ext_len;
1158 
1159     /* Echo the cookie if the server provided one in its preceding
1160      * HelloRetryRequest message.
1161      */
1162     ret = ssl_tls13_write_cookie_ext(ssl, p, end, &ext_len);
1163     if (ret != 0) {
1164         return ret;
1165     }
1166     p += ext_len;
1167 
1168 #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
1169     ret = mbedtls_ssl_tls13_write_record_size_limit_ext(
1170         ssl, p, end, &ext_len);
1171     if (ret != 0) {
1172         return ret;
1173     }
1174     p += ext_len;
1175 #endif
1176 
1177 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
1178     if (mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(ssl)) {
1179         ret = ssl_tls13_write_key_share_ext(ssl, p, end, &ext_len);
1180         if (ret != 0) {
1181             return ret;
1182         }
1183         p += ext_len;
1184     }
1185 #endif
1186 
1187 #if defined(MBEDTLS_SSL_EARLY_DATA)
1188     /* In the first ClientHello, write the early data indication extension if
1189      * necessary and update the early data state.
1190      * If an HRR has been received and thus we are currently writing the
1191      * second ClientHello, the second ClientHello must not contain an early
1192      * data extension and the early data state must stay as it is:
1193      * MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT or
1194      * MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED.
1195      */
1196     if (!ssl->handshake->hello_retry_request_flag) {
1197         if (mbedtls_ssl_conf_tls13_is_some_psk_enabled(ssl) &&
1198             ssl_tls13_early_data_has_valid_ticket(ssl) &&
1199             ssl->conf->early_data_enabled == MBEDTLS_SSL_EARLY_DATA_ENABLED) {
1200             ret = mbedtls_ssl_tls13_write_early_data_ext(
1201                 ssl, 0, p, end, &ext_len);
1202             if (ret != 0) {
1203                 return ret;
1204             }
1205             p += ext_len;
1206 
1207             ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT;
1208         } else {
1209             ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT;
1210         }
1211     }
1212 #endif /* MBEDTLS_SSL_EARLY_DATA */
1213 
1214 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1215     /* For PSK-based key exchange we need the pre_shared_key extension
1216      * and the psk_key_exchange_modes extension.
1217      *
1218      * The pre_shared_key extension MUST be the last extension in the
1219      * ClientHello. Servers MUST check that it is the last extension and
1220      * otherwise fail the handshake with an "illegal_parameter" alert.
1221      *
1222      * Add the psk_key_exchange_modes extension.
1223      */
1224     ret = ssl_tls13_write_psk_key_exchange_modes_ext(ssl, p, end, &ext_len);
1225     if (ret != 0) {
1226         return ret;
1227     }
1228     p += ext_len;
1229 #endif
1230 
1231     *out_len = p - buf;
1232 
1233     return 0;
1234 }
1235 
mbedtls_ssl_tls13_finalize_client_hello(mbedtls_ssl_context * ssl)1236 int mbedtls_ssl_tls13_finalize_client_hello(mbedtls_ssl_context *ssl)
1237 {
1238     ((void) ssl);
1239 
1240 #if defined(MBEDTLS_SSL_EARLY_DATA)
1241     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1242     psa_algorithm_t hash_alg = PSA_ALG_NONE;
1243     const unsigned char *psk;
1244     size_t psk_len;
1245     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1246 
1247     if (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT) {
1248         MBEDTLS_SSL_DEBUG_MSG(
1249             1, ("Set hs psk for early data when writing the first psk"));
1250 
1251         ret = ssl_tls13_ticket_get_psk(ssl, &hash_alg, &psk, &psk_len);
1252         if (ret != 0) {
1253             MBEDTLS_SSL_DEBUG_RET(
1254                 1, "ssl_tls13_ticket_get_psk", ret);
1255             return ret;
1256         }
1257 
1258         ret = mbedtls_ssl_set_hs_psk(ssl, psk, psk_len);
1259         if (ret  != 0) {
1260             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
1261             return ret;
1262         }
1263 
1264         /*
1265          * Early data are going to be encrypted using the ciphersuite
1266          * associated with the pre-shared key used for the handshake.
1267          * Note that if the server rejects early data, the handshake
1268          * based on the pre-shared key may complete successfully
1269          * with a selected ciphersuite different from the ciphersuite
1270          * associated with the pre-shared key. Only the hashes of the
1271          * two ciphersuites have to be the same. In that case, the
1272          * encrypted handshake data and application data are
1273          * encrypted using a different ciphersuite than the one used for
1274          * the rejected early data.
1275          */
1276         ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(
1277             ssl->session_negotiate->ciphersuite);
1278         ssl->handshake->ciphersuite_info = ciphersuite_info;
1279 
1280         /* Enable psk and psk_ephemeral to make stage early happy */
1281         ssl->handshake->key_exchange_mode =
1282             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
1283 
1284         /* Start the TLS 1.3 key schedule:
1285          *     Set the PSK and derive early secret.
1286          */
1287         ret = mbedtls_ssl_tls13_key_schedule_stage_early(ssl);
1288         if (ret != 0) {
1289             MBEDTLS_SSL_DEBUG_RET(
1290                 1, "mbedtls_ssl_tls13_key_schedule_stage_early", ret);
1291             return ret;
1292         }
1293 
1294         /* Derive early data key material */
1295         ret = mbedtls_ssl_tls13_compute_early_transform(ssl);
1296         if (ret != 0) {
1297             MBEDTLS_SSL_DEBUG_RET(
1298                 1, "mbedtls_ssl_tls13_compute_early_transform", ret);
1299             return ret;
1300         }
1301 
1302 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
1303         mbedtls_ssl_handshake_set_state(
1304             ssl, MBEDTLS_SSL_CLIENT_CCS_AFTER_CLIENT_HELLO);
1305 #else
1306         MBEDTLS_SSL_DEBUG_MSG(
1307             1, ("Switch to early data keys for outbound traffic"));
1308         mbedtls_ssl_set_outbound_transform(
1309             ssl, ssl->handshake->transform_earlydata);
1310         ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE;
1311 #endif
1312     }
1313 #endif /* MBEDTLS_SSL_EARLY_DATA */
1314     return 0;
1315 }
1316 /*
1317  * Functions for parsing and processing Server Hello
1318  */
1319 
1320 /**
1321  * \brief Detect if the ServerHello contains a supported_versions extension
1322  *        or not.
1323  *
1324  * \param[in] ssl  SSL context
1325  * \param[in] buf  Buffer containing the ServerHello message
1326  * \param[in] end  End of the buffer containing the ServerHello message
1327  *
1328  * \return 0 if the ServerHello does not contain a supported_versions extension
1329  * \return 1 if the ServerHello contains a supported_versions extension
1330  * \return A negative value if an error occurred while parsing the ServerHello.
1331  */
1332 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_is_supported_versions_ext_present(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)1333 static int ssl_tls13_is_supported_versions_ext_present(
1334     mbedtls_ssl_context *ssl,
1335     const unsigned char *buf,
1336     const unsigned char *end)
1337 {
1338     const unsigned char *p = buf;
1339     size_t legacy_session_id_echo_len;
1340     const unsigned char *supported_versions_data;
1341     const unsigned char *supported_versions_data_end;
1342 
1343     /*
1344      * Check there is enough data to access the legacy_session_id_echo vector
1345      * length:
1346      * - legacy_version                 2 bytes
1347      * - random                         MBEDTLS_SERVER_HELLO_RANDOM_LEN bytes
1348      * - legacy_session_id_echo length  1 byte
1349      */
1350     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, MBEDTLS_SERVER_HELLO_RANDOM_LEN + 3);
1351     p += MBEDTLS_SERVER_HELLO_RANDOM_LEN + 2;
1352     legacy_session_id_echo_len = *p;
1353 
1354     /*
1355      * Jump to the extensions, jumping over:
1356      * - legacy_session_id_echo     (legacy_session_id_echo_len + 1) bytes
1357      * - cipher_suite               2 bytes
1358      * - legacy_compression_method  1 byte
1359      */
1360     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, legacy_session_id_echo_len + 4);
1361     p += legacy_session_id_echo_len + 4;
1362 
1363     return mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts(
1364         ssl, p, end,
1365         &supported_versions_data, &supported_versions_data_end);
1366 }
1367 
1368 /* Returns a negative value on failure, and otherwise
1369  * - 1 if the last eight bytes of the ServerHello random bytes indicate that
1370  *     the server is TLS 1.3 capable but negotiating TLS 1.2 or below.
1371  * - 0 otherwise
1372  */
1373 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_is_downgrade_negotiation(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)1374 static int ssl_tls13_is_downgrade_negotiation(mbedtls_ssl_context *ssl,
1375                                               const unsigned char *buf,
1376                                               const unsigned char *end)
1377 {
1378     /* First seven bytes of the magic downgrade strings, see RFC 8446 4.1.3 */
1379     static const unsigned char magic_downgrade_string[] =
1380     { 0x44, 0x4F, 0x57, 0x4E, 0x47, 0x52, 0x44 };
1381     const unsigned char *last_eight_bytes_of_random;
1382     unsigned char last_byte_of_random;
1383 
1384     MBEDTLS_SSL_CHK_BUF_READ_PTR(buf, end, MBEDTLS_SERVER_HELLO_RANDOM_LEN + 2);
1385     last_eight_bytes_of_random = buf + 2 + MBEDTLS_SERVER_HELLO_RANDOM_LEN - 8;
1386 
1387     if (memcmp(last_eight_bytes_of_random,
1388                magic_downgrade_string,
1389                sizeof(magic_downgrade_string)) == 0) {
1390         last_byte_of_random = last_eight_bytes_of_random[7];
1391         return last_byte_of_random == 0 ||
1392                last_byte_of_random == 1;
1393     }
1394 
1395     return 0;
1396 }
1397 
1398 /* Returns a negative value on failure, and otherwise
1399  * - SSL_SERVER_HELLO or
1400  * - SSL_SERVER_HELLO_HRR
1401  * to indicate which message is expected and to be parsed next.
1402  */
1403 #define SSL_SERVER_HELLO 0
1404 #define SSL_SERVER_HELLO_HRR 1
1405 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_server_hello_is_hrr(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)1406 static int ssl_server_hello_is_hrr(mbedtls_ssl_context *ssl,
1407                                    const unsigned char *buf,
1408                                    const unsigned char *end)
1409 {
1410 
1411     /* Check whether this message is a HelloRetryRequest ( HRR ) message.
1412      *
1413      * Server Hello and HRR are only distinguished by Random set to the
1414      * special value of the SHA-256 of "HelloRetryRequest".
1415      *
1416      * struct {
1417      *    ProtocolVersion legacy_version = 0x0303;
1418      *    Random random;
1419      *    opaque legacy_session_id_echo<0..32>;
1420      *    CipherSuite cipher_suite;
1421      *    uint8 legacy_compression_method = 0;
1422      *    Extension extensions<6..2^16-1>;
1423      * } ServerHello;
1424      *
1425      */
1426     MBEDTLS_SSL_CHK_BUF_READ_PTR(
1427         buf, end, 2 + sizeof(mbedtls_ssl_tls13_hello_retry_request_magic));
1428 
1429     if (memcmp(buf + 2, mbedtls_ssl_tls13_hello_retry_request_magic,
1430                sizeof(mbedtls_ssl_tls13_hello_retry_request_magic)) == 0) {
1431         return SSL_SERVER_HELLO_HRR;
1432     }
1433 
1434     return SSL_SERVER_HELLO;
1435 }
1436 
1437 /*
1438  * Returns a negative value on failure, and otherwise
1439  * - SSL_SERVER_HELLO or
1440  * - SSL_SERVER_HELLO_HRR or
1441  * - SSL_SERVER_HELLO_TLS1_2
1442  */
1443 #define SSL_SERVER_HELLO_TLS1_2 2
1444 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_preprocess_server_hello(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)1445 static int ssl_tls13_preprocess_server_hello(mbedtls_ssl_context *ssl,
1446                                              const unsigned char *buf,
1447                                              const unsigned char *end)
1448 {
1449     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1450     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1451 
1452     MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_is_supported_versions_ext_present(
1453                                  ssl, buf, end));
1454 
1455     if (ret == 0) {
1456         MBEDTLS_SSL_PROC_CHK_NEG(
1457             ssl_tls13_is_downgrade_negotiation(ssl, buf, end));
1458 
1459         /* If the server is negotiating TLS 1.2 or below and:
1460          * . we did not propose TLS 1.2 or
1461          * . the server responded it is TLS 1.3 capable but negotiating a lower
1462          *   version of the protocol and thus we are under downgrade attack
1463          * abort the handshake with an "illegal parameter" alert.
1464          */
1465         if (handshake->min_tls_version > MBEDTLS_SSL_VERSION_TLS1_2 || ret) {
1466             MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1467                                          MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1468             return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1469         }
1470 
1471         /*
1472          * Version 1.2 of the protocol has been negotiated, set the
1473          * ssl->keep_current_message flag for the ServerHello to be kept and
1474          * parsed as a TLS 1.2 ServerHello. We also change ssl->tls_version to
1475          * MBEDTLS_SSL_VERSION_TLS1_2 thus from now on mbedtls_ssl_handshake_step()
1476          * will dispatch to the TLS 1.2 state machine.
1477          */
1478         ssl->keep_current_message = 1;
1479         ssl->tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
1480         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
1481                                  ssl, MBEDTLS_SSL_HS_SERVER_HELLO,
1482                                  buf, (size_t) (end - buf)));
1483 
1484         if (mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(ssl)) {
1485             ret = ssl_tls13_reset_key_share(ssl);
1486             if (ret != 0) {
1487                 return ret;
1488             }
1489         }
1490 
1491         return SSL_SERVER_HELLO_TLS1_2;
1492     }
1493 
1494     ssl->session_negotiate->tls_version = ssl->tls_version;
1495     ssl->session_negotiate->endpoint = ssl->conf->endpoint;
1496 
1497     handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
1498 
1499     ret = ssl_server_hello_is_hrr(ssl, buf, end);
1500     switch (ret) {
1501         case SSL_SERVER_HELLO:
1502             MBEDTLS_SSL_DEBUG_MSG(2, ("received ServerHello message"));
1503             break;
1504         case SSL_SERVER_HELLO_HRR:
1505             MBEDTLS_SSL_DEBUG_MSG(2, ("received HelloRetryRequest message"));
1506             /* If a client receives a second HelloRetryRequest in the same
1507              * connection (i.e., where the ClientHello was itself in response
1508              * to a HelloRetryRequest), it MUST abort the handshake with an
1509              * "unexpected_message" alert.
1510              */
1511             if (handshake->hello_retry_request_flag) {
1512                 MBEDTLS_SSL_DEBUG_MSG(1, ("Multiple HRRs received"));
1513                 MBEDTLS_SSL_PEND_FATAL_ALERT(
1514                     MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
1515                     MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
1516                 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
1517             }
1518             /*
1519              * Clients must abort the handshake with an "illegal_parameter"
1520              * alert if the HelloRetryRequest would not result in any change
1521              * in the ClientHello.
1522              * In a PSK only key exchange that what we expect.
1523              */
1524             if (!mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(ssl)) {
1525                 MBEDTLS_SSL_DEBUG_MSG(1,
1526                                       ("Unexpected HRR in pure PSK key exchange."));
1527                 MBEDTLS_SSL_PEND_FATAL_ALERT(
1528                     MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1529                     MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1530                 return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1531             }
1532 
1533             handshake->hello_retry_request_flag = 1;
1534 
1535             break;
1536     }
1537 
1538 cleanup:
1539 
1540     return ret;
1541 }
1542 
1543 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_check_server_hello_session_id_echo(mbedtls_ssl_context * ssl,const unsigned char ** buf,const unsigned char * end)1544 static int ssl_tls13_check_server_hello_session_id_echo(mbedtls_ssl_context *ssl,
1545                                                         const unsigned char **buf,
1546                                                         const unsigned char *end)
1547 {
1548     const unsigned char *p = *buf;
1549     size_t legacy_session_id_echo_len;
1550 
1551     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 1);
1552     legacy_session_id_echo_len = *p++;
1553 
1554     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, legacy_session_id_echo_len);
1555 
1556     /* legacy_session_id_echo */
1557     if (ssl->session_negotiate->id_len != legacy_session_id_echo_len ||
1558         memcmp(ssl->session_negotiate->id, p, legacy_session_id_echo_len) != 0) {
1559         MBEDTLS_SSL_DEBUG_BUF(3, "Expected Session ID",
1560                               ssl->session_negotiate->id,
1561                               ssl->session_negotiate->id_len);
1562         MBEDTLS_SSL_DEBUG_BUF(3, "Received Session ID", p,
1563                               legacy_session_id_echo_len);
1564 
1565         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1566                                      MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1567 
1568         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1569     }
1570 
1571     p += legacy_session_id_echo_len;
1572     *buf = p;
1573 
1574     MBEDTLS_SSL_DEBUG_BUF(3, "Session ID", ssl->session_negotiate->id,
1575                           ssl->session_negotiate->id_len);
1576     return 0;
1577 }
1578 
1579 /* Parse ServerHello message and configure context
1580  *
1581  * struct {
1582  *    ProtocolVersion legacy_version = 0x0303; // TLS 1.2
1583  *    Random random;
1584  *    opaque legacy_session_id_echo<0..32>;
1585  *    CipherSuite cipher_suite;
1586  *    uint8 legacy_compression_method = 0;
1587  *    Extension extensions<6..2^16-1>;
1588  * } ServerHello;
1589  */
1590 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_server_hello(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end,int is_hrr)1591 static int ssl_tls13_parse_server_hello(mbedtls_ssl_context *ssl,
1592                                         const unsigned char *buf,
1593                                         const unsigned char *end,
1594                                         int is_hrr)
1595 {
1596     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1597     const unsigned char *p = buf;
1598     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1599     size_t extensions_len;
1600     const unsigned char *extensions_end;
1601     uint16_t cipher_suite;
1602     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1603     int fatal_alert = 0;
1604     uint32_t allowed_extensions_mask;
1605     int hs_msg_type = is_hrr ? MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST :
1606                       MBEDTLS_SSL_HS_SERVER_HELLO;
1607 
1608     /*
1609      * Check there is space for minimal fields
1610      *
1611      * - legacy_version             ( 2 bytes)
1612      * - random                     (MBEDTLS_SERVER_HELLO_RANDOM_LEN bytes)
1613      * - legacy_session_id_echo     ( 1 byte ), minimum size
1614      * - cipher_suite               ( 2 bytes)
1615      * - legacy_compression_method  ( 1 byte )
1616      */
1617     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, MBEDTLS_SERVER_HELLO_RANDOM_LEN + 6);
1618 
1619     MBEDTLS_SSL_DEBUG_BUF(4, "server hello", p, end - p);
1620     MBEDTLS_SSL_DEBUG_BUF(3, "server hello, version", p, 2);
1621 
1622     /* ...
1623      * ProtocolVersion legacy_version = 0x0303; // TLS 1.2
1624      * ...
1625      * with ProtocolVersion defined as:
1626      * uint16 ProtocolVersion;
1627      */
1628     if (mbedtls_ssl_read_version(p, ssl->conf->transport) !=
1629         MBEDTLS_SSL_VERSION_TLS1_2) {
1630         MBEDTLS_SSL_DEBUG_MSG(1, ("Unsupported version of TLS."));
1631         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION,
1632                                      MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION);
1633         ret = MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1634         goto cleanup;
1635     }
1636     p += 2;
1637 
1638     /* ...
1639      * Random random;
1640      * ...
1641      * with Random defined as:
1642      * opaque Random[MBEDTLS_SERVER_HELLO_RANDOM_LEN];
1643      */
1644     if (!is_hrr) {
1645         memcpy(&handshake->randbytes[MBEDTLS_CLIENT_HELLO_RANDOM_LEN], p,
1646                MBEDTLS_SERVER_HELLO_RANDOM_LEN);
1647         MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes",
1648                               p, MBEDTLS_SERVER_HELLO_RANDOM_LEN);
1649     }
1650     p += MBEDTLS_SERVER_HELLO_RANDOM_LEN;
1651 
1652     /* ...
1653      * opaque legacy_session_id_echo<0..32>;
1654      * ...
1655      */
1656     if (ssl_tls13_check_server_hello_session_id_echo(ssl, &p, end) != 0) {
1657         fatal_alert = MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
1658         goto cleanup;
1659     }
1660 
1661     /* ...
1662      * CipherSuite cipher_suite;
1663      * ...
1664      * with CipherSuite defined as:
1665      * uint8 CipherSuite[2];
1666      */
1667     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
1668     cipher_suite = MBEDTLS_GET_UINT16_BE(p, 0);
1669     p += 2;
1670 
1671 
1672     ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(cipher_suite);
1673     /*
1674      * Check whether this ciphersuite is valid and offered.
1675      */
1676     if ((mbedtls_ssl_validate_ciphersuite(ssl, ciphersuite_info,
1677                                           ssl->tls_version,
1678                                           ssl->tls_version) != 0) ||
1679         !mbedtls_ssl_tls13_cipher_suite_is_offered(ssl, cipher_suite)) {
1680         fatal_alert = MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
1681     }
1682     /*
1683      * If we received an HRR before and that the proposed selected
1684      * ciphersuite in this server hello is not the same as the one
1685      * proposed in the HRR, we abort the handshake and send an
1686      * "illegal_parameter" alert.
1687      */
1688     else if ((!is_hrr) && handshake->hello_retry_request_flag &&
1689              (cipher_suite != ssl->session_negotiate->ciphersuite)) {
1690         fatal_alert = MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
1691     }
1692 
1693     if (fatal_alert == MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER) {
1694         MBEDTLS_SSL_DEBUG_MSG(1, ("invalid ciphersuite(%04x) parameter",
1695                                   cipher_suite));
1696         goto cleanup;
1697     }
1698 
1699     /* Configure ciphersuites */
1700     mbedtls_ssl_optimize_checksum(ssl, ciphersuite_info);
1701 
1702     handshake->ciphersuite_info = ciphersuite_info;
1703     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen ciphersuite: ( %04x ) - %s",
1704                               cipher_suite, ciphersuite_info->name));
1705 
1706 #if defined(MBEDTLS_HAVE_TIME)
1707     ssl->session_negotiate->start = mbedtls_time(NULL);
1708 #endif /* MBEDTLS_HAVE_TIME */
1709 
1710     /* ...
1711      * uint8 legacy_compression_method = 0;
1712      * ...
1713      */
1714     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 1);
1715     if (p[0] != MBEDTLS_SSL_COMPRESS_NULL) {
1716         MBEDTLS_SSL_DEBUG_MSG(1, ("bad legacy compression method"));
1717         fatal_alert = MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
1718         goto cleanup;
1719     }
1720     p++;
1721 
1722     /* ...
1723      * Extension extensions<6..2^16-1>;
1724      * ...
1725      * struct {
1726      *      ExtensionType extension_type; (2 bytes)
1727      *      opaque extension_data<0..2^16-1>;
1728      * } Extension;
1729      */
1730     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
1731     extensions_len = MBEDTLS_GET_UINT16_BE(p, 0);
1732     p += 2;
1733 
1734     /* Check extensions do not go beyond the buffer of data. */
1735     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, extensions_len);
1736     extensions_end = p + extensions_len;
1737 
1738     MBEDTLS_SSL_DEBUG_BUF(3, "server hello extensions", p, extensions_len);
1739 
1740     handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
1741     allowed_extensions_mask = is_hrr ?
1742                               MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_HRR :
1743                               MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_SH;
1744 
1745     while (p < extensions_end) {
1746         unsigned int extension_type;
1747         size_t extension_data_len;
1748         const unsigned char *extension_data_end;
1749 
1750         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, 4);
1751         extension_type = MBEDTLS_GET_UINT16_BE(p, 0);
1752         extension_data_len = MBEDTLS_GET_UINT16_BE(p, 2);
1753         p += 4;
1754 
1755         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, extension_data_len);
1756         extension_data_end = p + extension_data_len;
1757 
1758         ret = mbedtls_ssl_tls13_check_received_extension(
1759             ssl, hs_msg_type, extension_type, allowed_extensions_mask);
1760         if (ret != 0) {
1761             return ret;
1762         }
1763 
1764         switch (extension_type) {
1765             case MBEDTLS_TLS_EXT_COOKIE:
1766 
1767                 ret = ssl_tls13_parse_cookie_ext(ssl,
1768                                                  p, extension_data_end);
1769                 if (ret != 0) {
1770                     MBEDTLS_SSL_DEBUG_RET(1,
1771                                           "ssl_tls13_parse_cookie_ext",
1772                                           ret);
1773                     goto cleanup;
1774                 }
1775                 break;
1776 
1777             case MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS:
1778                 ret = ssl_tls13_parse_supported_versions_ext(ssl,
1779                                                              p,
1780                                                              extension_data_end);
1781                 if (ret != 0) {
1782                     goto cleanup;
1783                 }
1784                 break;
1785 
1786 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1787             case MBEDTLS_TLS_EXT_PRE_SHARED_KEY:
1788                 MBEDTLS_SSL_DEBUG_MSG(3, ("found pre_shared_key extension"));
1789 
1790                 if ((ret = ssl_tls13_parse_server_pre_shared_key_ext(
1791                          ssl, p, extension_data_end)) != 0) {
1792                     MBEDTLS_SSL_DEBUG_RET(
1793                         1, ("ssl_tls13_parse_server_pre_shared_key_ext"), ret);
1794                     return ret;
1795                 }
1796                 break;
1797 #endif
1798 
1799             case MBEDTLS_TLS_EXT_KEY_SHARE:
1800                 MBEDTLS_SSL_DEBUG_MSG(3, ("found key_shares extension"));
1801                 if (!mbedtls_ssl_conf_tls13_is_some_ephemeral_enabled(ssl)) {
1802                     fatal_alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT;
1803                     goto cleanup;
1804                 }
1805 
1806                 if (is_hrr) {
1807                     ret = ssl_tls13_parse_hrr_key_share_ext(ssl,
1808                                                             p, extension_data_end);
1809                 } else {
1810                     ret = ssl_tls13_parse_key_share_ext(ssl,
1811                                                         p, extension_data_end);
1812                 }
1813                 if (ret != 0) {
1814                     MBEDTLS_SSL_DEBUG_RET(1,
1815                                           "ssl_tls13_parse_key_share_ext",
1816                                           ret);
1817                     goto cleanup;
1818                 }
1819                 break;
1820 
1821             default:
1822                 ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1823                 goto cleanup;
1824         }
1825 
1826         p += extension_data_len;
1827     }
1828 
1829     MBEDTLS_SSL_PRINT_EXTS(3, hs_msg_type, handshake->received_extensions);
1830 
1831 cleanup:
1832 
1833     if (fatal_alert == MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT) {
1834         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT,
1835                                      MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION);
1836         ret = MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION;
1837     } else if (fatal_alert == MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER) {
1838         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1839                                      MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1840         ret = MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1841     }
1842     return ret;
1843 }
1844 
1845 #if defined(MBEDTLS_DEBUG_C)
ssl_tls13_get_kex_mode_str(int mode)1846 static const char *ssl_tls13_get_kex_mode_str(int mode)
1847 {
1848     switch (mode) {
1849         case MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK:
1850             return "psk";
1851         case MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL:
1852             return "ephemeral";
1853         case MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL:
1854             return "psk_ephemeral";
1855         default:
1856             return "unknown mode";
1857     }
1858 }
1859 #endif /* MBEDTLS_DEBUG_C */
1860 
1861 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_postprocess_server_hello(mbedtls_ssl_context * ssl)1862 static int ssl_tls13_postprocess_server_hello(mbedtls_ssl_context *ssl)
1863 {
1864     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1865     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1866 
1867     /* Determine the key exchange mode:
1868      * 1) If both the pre_shared_key and key_share extensions were received
1869      *    then the key exchange mode is PSK with EPHEMERAL.
1870      * 2) If only the pre_shared_key extension was received then the key
1871      *    exchange mode is PSK-only.
1872      * 3) If only the key_share extension was received then the key
1873      *    exchange mode is EPHEMERAL-only.
1874      */
1875     switch (handshake->received_extensions &
1876             (MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY) |
1877              MBEDTLS_SSL_EXT_MASK(KEY_SHARE))) {
1878         /* Only the pre_shared_key extension was received */
1879         case MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY):
1880             handshake->key_exchange_mode =
1881                 MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
1882             break;
1883 
1884         /* Only the key_share extension was received */
1885         case MBEDTLS_SSL_EXT_MASK(KEY_SHARE):
1886             handshake->key_exchange_mode =
1887                 MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
1888             break;
1889 
1890         /* Both the pre_shared_key and key_share extensions were received */
1891         case (MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY) |
1892               MBEDTLS_SSL_EXT_MASK(KEY_SHARE)):
1893             handshake->key_exchange_mode =
1894                 MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
1895             break;
1896 
1897         /* Neither pre_shared_key nor key_share extension was received */
1898         default:
1899             MBEDTLS_SSL_DEBUG_MSG(1, ("Unknown key exchange."));
1900             ret = MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1901             goto cleanup;
1902     }
1903 
1904     if (!mbedtls_ssl_conf_tls13_is_kex_mode_enabled(
1905             ssl, handshake->key_exchange_mode)) {
1906         ret = MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1907         MBEDTLS_SSL_DEBUG_MSG(
1908             2, ("Key exchange mode(%s) is not supported.",
1909                 ssl_tls13_get_kex_mode_str(handshake->key_exchange_mode)));
1910         goto cleanup;
1911     }
1912 
1913     MBEDTLS_SSL_DEBUG_MSG(
1914         3, ("Selected key exchange mode: %s",
1915             ssl_tls13_get_kex_mode_str(handshake->key_exchange_mode)));
1916 
1917     /* Start the TLS 1.3 key scheduling if not already done.
1918      *
1919      * If we proposed early data then we have already derived an
1920      * early secret using the selected PSK and its associated hash.
1921      * It means that if the negotiated key exchange mode is psk or
1922      * psk_ephemeral, we have already correctly computed the
1923      * early secret and thus we do not do it again. In all other
1924      * cases we compute it here.
1925      */
1926 #if defined(MBEDTLS_SSL_EARLY_DATA)
1927     if (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT ||
1928         handshake->key_exchange_mode ==
1929         MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL)
1930 #endif
1931     {
1932         ret = mbedtls_ssl_tls13_key_schedule_stage_early(ssl);
1933         if (ret != 0) {
1934             MBEDTLS_SSL_DEBUG_RET(
1935                 1, "mbedtls_ssl_tls13_key_schedule_stage_early", ret);
1936             goto cleanup;
1937         }
1938     }
1939 
1940     ret = mbedtls_ssl_tls13_compute_handshake_transform(ssl);
1941     if (ret != 0) {
1942         MBEDTLS_SSL_DEBUG_RET(1,
1943                               "mbedtls_ssl_tls13_compute_handshake_transform",
1944                               ret);
1945         goto cleanup;
1946     }
1947 
1948     mbedtls_ssl_set_inbound_transform(ssl, handshake->transform_handshake);
1949     MBEDTLS_SSL_DEBUG_MSG(1, ("Switch to handshake keys for inbound traffic"));
1950     ssl->session_in = ssl->session_negotiate;
1951 
1952 cleanup:
1953     if (ret != 0) {
1954         MBEDTLS_SSL_PEND_FATAL_ALERT(
1955             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
1956             MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
1957     }
1958 
1959     return ret;
1960 }
1961 
1962 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_postprocess_hrr(mbedtls_ssl_context * ssl)1963 static int ssl_tls13_postprocess_hrr(mbedtls_ssl_context *ssl)
1964 {
1965     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1966 
1967     mbedtls_ssl_session_reset_msg_layer(ssl, 0);
1968 
1969     /*
1970      * We are going to re-generate a shared secret corresponding to the group
1971      * selected by the server, which is different from the group for which we
1972      * generated a shared secret in the first client hello.
1973      * Thus, reset the shared secret.
1974      */
1975     ret = ssl_tls13_reset_key_share(ssl);
1976     if (ret != 0) {
1977         return ret;
1978     }
1979 
1980     ssl->session_negotiate->ciphersuite = ssl->handshake->ciphersuite_info->id;
1981 
1982 #if defined(MBEDTLS_SSL_EARLY_DATA)
1983     if (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT) {
1984         ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED;
1985     }
1986 #endif
1987 
1988     return 0;
1989 }
1990 
1991 /*
1992  * Wait and parse ServerHello handshake message.
1993  * Handler for MBEDTLS_SSL_SERVER_HELLO
1994  */
1995 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_server_hello(mbedtls_ssl_context * ssl)1996 static int ssl_tls13_process_server_hello(mbedtls_ssl_context *ssl)
1997 {
1998     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1999     unsigned char *buf = NULL;
2000     size_t buf_len = 0;
2001     int is_hrr = 0;
2002 
2003     MBEDTLS_SSL_DEBUG_MSG(2, ("=> %s", __func__));
2004 
2005     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
2006                              ssl, MBEDTLS_SSL_HS_SERVER_HELLO, &buf, &buf_len));
2007 
2008     ret = ssl_tls13_preprocess_server_hello(ssl, buf, buf + buf_len);
2009     if (ret < 0) {
2010         goto cleanup;
2011     } else {
2012         is_hrr = (ret == SSL_SERVER_HELLO_HRR);
2013     }
2014 
2015     if (ret == SSL_SERVER_HELLO_TLS1_2) {
2016         ret = 0;
2017         goto cleanup;
2018     }
2019 
2020     MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_server_hello(ssl, buf,
2021                                                       buf + buf_len,
2022                                                       is_hrr));
2023     if (is_hrr) {
2024         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_reset_transcript_for_hrr(ssl));
2025     }
2026 
2027     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2028                              ssl, MBEDTLS_SSL_HS_SERVER_HELLO, buf, buf_len));
2029 
2030     if (is_hrr) {
2031         MBEDTLS_SSL_PROC_CHK(ssl_tls13_postprocess_hrr(ssl));
2032 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
2033         /* If not offering early data, the client sends a dummy CCS record
2034          * immediately before its second flight. This may either be before
2035          * its second ClientHello or before its encrypted handshake flight.
2036          */
2037         mbedtls_ssl_handshake_set_state(
2038             ssl, MBEDTLS_SSL_CLIENT_CCS_BEFORE_2ND_CLIENT_HELLO);
2039 #else
2040         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
2041 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
2042     } else {
2043         MBEDTLS_SSL_PROC_CHK(ssl_tls13_postprocess_server_hello(ssl));
2044         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS);
2045     }
2046 
2047 cleanup:
2048     MBEDTLS_SSL_DEBUG_MSG(2, ("<= %s ( %s )", __func__,
2049                               is_hrr ? "HelloRetryRequest" : "ServerHello"));
2050     return ret;
2051 }
2052 
2053 /*
2054  *
2055  * Handler for MBEDTLS_SSL_ENCRYPTED_EXTENSIONS
2056  *
2057  * The EncryptedExtensions message contains any extensions which
2058  * should be protected, i.e., any which are not needed to establish
2059  * the cryptographic context.
2060  */
2061 
2062 /* Parse EncryptedExtensions message
2063  * struct {
2064  *     Extension extensions<0..2^16-1>;
2065  * } EncryptedExtensions;
2066  */
2067 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_encrypted_extensions(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)2068 static int ssl_tls13_parse_encrypted_extensions(mbedtls_ssl_context *ssl,
2069                                                 const unsigned char *buf,
2070                                                 const unsigned char *end)
2071 {
2072     int ret = 0;
2073     size_t extensions_len;
2074     const unsigned char *p = buf;
2075     const unsigned char *extensions_end;
2076     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2077 
2078     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
2079     extensions_len = MBEDTLS_GET_UINT16_BE(p, 0);
2080     p += 2;
2081 
2082     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, extensions_len);
2083     extensions_end = p + extensions_len;
2084 
2085     MBEDTLS_SSL_DEBUG_BUF(3, "encrypted extensions", p, extensions_len);
2086 
2087     handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
2088 
2089     while (p < extensions_end) {
2090         unsigned int extension_type;
2091         size_t extension_data_len;
2092 
2093         /*
2094          * struct {
2095          *     ExtensionType extension_type; (2 bytes)
2096          *     opaque extension_data<0..2^16-1>;
2097          * } Extension;
2098          */
2099         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, 4);
2100         extension_type = MBEDTLS_GET_UINT16_BE(p, 0);
2101         extension_data_len = MBEDTLS_GET_UINT16_BE(p, 2);
2102         p += 4;
2103 
2104         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, extension_data_len);
2105 
2106         ret = mbedtls_ssl_tls13_check_received_extension(
2107             ssl, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS, extension_type,
2108             MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_EE);
2109         if (ret != 0) {
2110             return ret;
2111         }
2112 
2113         switch (extension_type) {
2114 #if defined(MBEDTLS_SSL_ALPN)
2115             case MBEDTLS_TLS_EXT_ALPN:
2116                 MBEDTLS_SSL_DEBUG_MSG(3, ("found alpn extension"));
2117 
2118                 if ((ret = ssl_tls13_parse_alpn_ext(
2119                          ssl, p, (size_t) extension_data_len)) != 0) {
2120                     return ret;
2121                 }
2122 
2123                 break;
2124 #endif /* MBEDTLS_SSL_ALPN */
2125 
2126 #if defined(MBEDTLS_SSL_EARLY_DATA)
2127             case MBEDTLS_TLS_EXT_EARLY_DATA:
2128 
2129                 if (extension_data_len != 0) {
2130                     /* The message must be empty. */
2131                     MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
2132                                                  MBEDTLS_ERR_SSL_DECODE_ERROR);
2133                     return MBEDTLS_ERR_SSL_DECODE_ERROR;
2134                 }
2135 
2136                 break;
2137 #endif /* MBEDTLS_SSL_EARLY_DATA */
2138 
2139 #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
2140             case MBEDTLS_TLS_EXT_RECORD_SIZE_LIMIT:
2141                 MBEDTLS_SSL_DEBUG_MSG(3, ("found record_size_limit extension"));
2142 
2143                 ret = mbedtls_ssl_tls13_parse_record_size_limit_ext(
2144                     ssl, p, p + extension_data_len);
2145                 if (ret != 0) {
2146                     MBEDTLS_SSL_DEBUG_RET(
2147                         1, ("mbedtls_ssl_tls13_parse_record_size_limit_ext"), ret);
2148                     return ret;
2149                 }
2150                 break;
2151 #endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
2152 
2153             default:
2154                 MBEDTLS_SSL_PRINT_EXT(
2155                     3, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
2156                     extension_type, "( ignored )");
2157                 break;
2158         }
2159 
2160         p += extension_data_len;
2161     }
2162 
2163     if ((handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(RECORD_SIZE_LIMIT)) &&
2164         (handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(MAX_FRAGMENT_LENGTH))) {
2165         MBEDTLS_SSL_DEBUG_MSG(3,
2166                               (
2167                                   "Record size limit extension cannot be used with max fragment length extension"));
2168         MBEDTLS_SSL_PEND_FATAL_ALERT(
2169             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
2170             MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
2171         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2172     }
2173 
2174     MBEDTLS_SSL_PRINT_EXTS(3, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
2175                            handshake->received_extensions);
2176 
2177     /* Check that we consumed all the message. */
2178     if (p != end) {
2179         MBEDTLS_SSL_DEBUG_MSG(1, ("EncryptedExtension lengths misaligned"));
2180         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
2181                                      MBEDTLS_ERR_SSL_DECODE_ERROR);
2182         return MBEDTLS_ERR_SSL_DECODE_ERROR;
2183     }
2184 
2185     return ret;
2186 }
2187 
2188 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_encrypted_extensions(mbedtls_ssl_context * ssl)2189 static int ssl_tls13_process_encrypted_extensions(mbedtls_ssl_context *ssl)
2190 {
2191     int ret;
2192     unsigned char *buf;
2193     size_t buf_len;
2194     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2195 
2196     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse encrypted extensions"));
2197 
2198     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
2199                              ssl, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
2200                              &buf, &buf_len));
2201 
2202     /* Process the message contents */
2203     MBEDTLS_SSL_PROC_CHK(
2204         ssl_tls13_parse_encrypted_extensions(ssl, buf, buf + buf_len));
2205 
2206 #if defined(MBEDTLS_SSL_EARLY_DATA)
2207     if (handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(EARLY_DATA)) {
2208         /* RFC8446 4.2.11
2209          * If the server supplies an "early_data" extension, the
2210          * client MUST verify that the server's selected_identity
2211          * is 0. If any other value is returned, the client MUST
2212          * abort the handshake with an "illegal_parameter" alert.
2213          *
2214          * RFC 8446 4.2.10
2215          * In order to accept early data, the server MUST have accepted a PSK
2216          * cipher suite and selected the first key offered in the client's
2217          * "pre_shared_key" extension. In addition, it MUST verify that the
2218          * following values are the same as those associated with the
2219          * selected PSK:
2220          * - The TLS version number
2221          * - The selected cipher suite
2222          * - The selected ALPN [RFC7301] protocol, if any
2223          *
2224          * The server has sent an early data extension in its Encrypted
2225          * Extension message thus accepted to receive early data. We
2226          * check here that the additional constraints on the handshake
2227          * parameters, when early data are exchanged, are met,
2228          * namely:
2229          * - a PSK has been selected for the handshake
2230          * - the selected PSK for the handshake was the first one proposed
2231          *   by the client.
2232          * - the selected ciphersuite for the handshake is the ciphersuite
2233          *   associated with the selected PSK.
2234          */
2235         if ((!mbedtls_ssl_tls13_key_exchange_mode_with_psk(ssl)) ||
2236             handshake->selected_identity != 0 ||
2237             handshake->ciphersuite_info->id !=
2238             ssl->session_negotiate->ciphersuite) {
2239 
2240             MBEDTLS_SSL_PEND_FATAL_ALERT(
2241                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
2242                 MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
2243             return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2244         }
2245 
2246         ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED;
2247     } else if (ssl->early_data_state !=
2248                MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT) {
2249         ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED;
2250     }
2251 #endif
2252 
2253     /*
2254      * In case the client has proposed a PSK associated with a ticket,
2255      * `ssl->session_negotiate->ciphersuite` still contains at this point the
2256      * identifier of the ciphersuite associated with the ticket. This is that
2257      * way because, if an exchange of early data is agreed upon, we need
2258      * it to check that the ciphersuite selected for the handshake is the
2259      * ticket ciphersuite (see above). This information is not needed
2260      * anymore thus we can now set it to the identifier of the ciphersuite
2261      * used in this session under negotiation.
2262      */
2263     ssl->session_negotiate->ciphersuite = handshake->ciphersuite_info->id;
2264 
2265     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2266                              ssl, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
2267                              buf, buf_len));
2268 
2269 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2270     if (mbedtls_ssl_tls13_key_exchange_mode_with_psk(ssl)) {
2271         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2272     } else {
2273         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CERTIFICATE_REQUEST);
2274     }
2275 #else
2276     ((void) ssl);
2277     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2278 #endif
2279 
2280 cleanup:
2281 
2282     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse encrypted extensions"));
2283     return ret;
2284 
2285 }
2286 
2287 #if defined(MBEDTLS_SSL_EARLY_DATA)
2288 /*
2289  * Handler for MBEDTLS_SSL_END_OF_EARLY_DATA
2290  *
2291  * RFC 8446 section 4.5
2292  *
2293  * struct {} EndOfEarlyData;
2294  *
2295  * If the server sent an "early_data" extension in EncryptedExtensions, the
2296  * client MUST send an EndOfEarlyData message after receiving the server
2297  * Finished. Otherwise, the client MUST NOT send an EndOfEarlyData message.
2298  */
2299 
2300 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_end_of_early_data(mbedtls_ssl_context * ssl)2301 static int ssl_tls13_write_end_of_early_data(mbedtls_ssl_context *ssl)
2302 {
2303     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2304     unsigned char *buf = NULL;
2305     size_t buf_len;
2306     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write EndOfEarlyData"));
2307 
2308     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2309                              ssl, MBEDTLS_SSL_HS_END_OF_EARLY_DATA,
2310                              &buf, &buf_len));
2311 
2312     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_hdr_to_checksum(
2313                              ssl, MBEDTLS_SSL_HS_END_OF_EARLY_DATA, 0));
2314 
2315     MBEDTLS_SSL_PROC_CHK(
2316         mbedtls_ssl_finish_handshake_msg(ssl, buf_len, 0));
2317 
2318     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_CERTIFICATE);
2319 
2320 cleanup:
2321 
2322     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write EndOfEarlyData"));
2323     return ret;
2324 }
2325 
mbedtls_ssl_get_early_data_status(mbedtls_ssl_context * ssl)2326 int mbedtls_ssl_get_early_data_status(mbedtls_ssl_context *ssl)
2327 {
2328     if ((ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT) ||
2329         (!mbedtls_ssl_is_handshake_over(ssl))) {
2330         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2331     }
2332 
2333     switch (ssl->early_data_state) {
2334         case MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT:
2335             return MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_INDICATED;
2336             break;
2337 
2338         case MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED:
2339             return MBEDTLS_SSL_EARLY_DATA_STATUS_REJECTED;
2340             break;
2341 
2342         case MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED:
2343             return MBEDTLS_SSL_EARLY_DATA_STATUS_ACCEPTED;
2344             break;
2345 
2346         default:
2347             return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2348     }
2349 }
2350 #endif /* MBEDTLS_SSL_EARLY_DATA */
2351 
2352 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2353 /*
2354  * STATE HANDLING: CertificateRequest
2355  *
2356  */
2357 #define SSL_CERTIFICATE_REQUEST_EXPECT_REQUEST 0
2358 #define SSL_CERTIFICATE_REQUEST_SKIP           1
2359 /* Coordination:
2360  * Deals with the ambiguity of not knowing if a CertificateRequest
2361  * will be sent. Returns a negative code on failure, or
2362  * - SSL_CERTIFICATE_REQUEST_EXPECT_REQUEST
2363  * - SSL_CERTIFICATE_REQUEST_SKIP
2364  * indicating if a Certificate Request is expected or not.
2365  */
2366 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_certificate_request_coordinate(mbedtls_ssl_context * ssl)2367 static int ssl_tls13_certificate_request_coordinate(mbedtls_ssl_context *ssl)
2368 {
2369     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2370 
2371     if ((ret = mbedtls_ssl_read_record(ssl, 0)) != 0) {
2372         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
2373         return ret;
2374     }
2375     ssl->keep_current_message = 1;
2376 
2377     if ((ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) &&
2378         (ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST)) {
2379         MBEDTLS_SSL_DEBUG_MSG(3, ("got a certificate request"));
2380         return SSL_CERTIFICATE_REQUEST_EXPECT_REQUEST;
2381     }
2382 
2383     MBEDTLS_SSL_DEBUG_MSG(3, ("got no certificate request"));
2384 
2385     return SSL_CERTIFICATE_REQUEST_SKIP;
2386 }
2387 
2388 /*
2389  * ssl_tls13_parse_certificate_request()
2390  *     Parse certificate request
2391  * struct {
2392  *   opaque certificate_request_context<0..2^8-1>;
2393  *   Extension extensions<2..2^16-1>;
2394  * } CertificateRequest;
2395  */
2396 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_certificate_request(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)2397 static int ssl_tls13_parse_certificate_request(mbedtls_ssl_context *ssl,
2398                                                const unsigned char *buf,
2399                                                const unsigned char *end)
2400 {
2401     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2402     const unsigned char *p = buf;
2403     size_t certificate_request_context_len = 0;
2404     size_t extensions_len = 0;
2405     const unsigned char *extensions_end;
2406     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2407 
2408     /* ...
2409      * opaque certificate_request_context<0..2^8-1>
2410      * ...
2411      */
2412     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 1);
2413     certificate_request_context_len = (size_t) p[0];
2414     p += 1;
2415 
2416     if (certificate_request_context_len > 0) {
2417         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, certificate_request_context_len);
2418         MBEDTLS_SSL_DEBUG_BUF(3, "Certificate Request Context",
2419                               p, certificate_request_context_len);
2420 
2421         handshake->certificate_request_context =
2422             mbedtls_calloc(1, certificate_request_context_len);
2423         if (handshake->certificate_request_context == NULL) {
2424             MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
2425             return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2426         }
2427         memcpy(handshake->certificate_request_context, p,
2428                certificate_request_context_len);
2429         p += certificate_request_context_len;
2430     }
2431 
2432     /* ...
2433      * Extension extensions<2..2^16-1>;
2434      * ...
2435      */
2436     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
2437     extensions_len = MBEDTLS_GET_UINT16_BE(p, 0);
2438     p += 2;
2439 
2440     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, extensions_len);
2441     extensions_end = p + extensions_len;
2442 
2443     handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
2444 
2445     while (p < extensions_end) {
2446         unsigned int extension_type;
2447         size_t extension_data_len;
2448 
2449         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, 4);
2450         extension_type = MBEDTLS_GET_UINT16_BE(p, 0);
2451         extension_data_len = MBEDTLS_GET_UINT16_BE(p, 2);
2452         p += 4;
2453 
2454         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, extension_data_len);
2455 
2456         ret = mbedtls_ssl_tls13_check_received_extension(
2457             ssl, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST, extension_type,
2458             MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CR);
2459         if (ret != 0) {
2460             return ret;
2461         }
2462 
2463         switch (extension_type) {
2464             case MBEDTLS_TLS_EXT_SIG_ALG:
2465                 MBEDTLS_SSL_DEBUG_MSG(3,
2466                                       ("found signature algorithms extension"));
2467                 ret = mbedtls_ssl_parse_sig_alg_ext(ssl, p,
2468                                                     p + extension_data_len);
2469                 if (ret != 0) {
2470                     return ret;
2471                 }
2472 
2473                 break;
2474 
2475             default:
2476                 MBEDTLS_SSL_PRINT_EXT(
2477                     3, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
2478                     extension_type, "( ignored )");
2479                 break;
2480         }
2481 
2482         p += extension_data_len;
2483     }
2484 
2485     MBEDTLS_SSL_PRINT_EXTS(3, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
2486                            handshake->received_extensions);
2487 
2488     /* Check that we consumed all the message. */
2489     if (p != end) {
2490         MBEDTLS_SSL_DEBUG_MSG(1,
2491                               ("CertificateRequest misaligned"));
2492         goto decode_error;
2493     }
2494 
2495     /* RFC 8446 section 4.3.2
2496      *
2497      * The "signature_algorithms" extension MUST be specified
2498      */
2499     if ((handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(SIG_ALG)) == 0) {
2500         MBEDTLS_SSL_DEBUG_MSG(3,
2501                               ("no signature algorithms extension found"));
2502         goto decode_error;
2503     }
2504 
2505     ssl->handshake->client_auth = 1;
2506     return 0;
2507 
2508 decode_error:
2509     MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
2510                                  MBEDTLS_ERR_SSL_DECODE_ERROR);
2511     return MBEDTLS_ERR_SSL_DECODE_ERROR;
2512 }
2513 
2514 /*
2515  * Handler for  MBEDTLS_SSL_CERTIFICATE_REQUEST
2516  */
2517 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_certificate_request(mbedtls_ssl_context * ssl)2518 static int ssl_tls13_process_certificate_request(mbedtls_ssl_context *ssl)
2519 {
2520     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2521 
2522     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate request"));
2523 
2524     MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_certificate_request_coordinate(ssl));
2525 
2526     if (ret == SSL_CERTIFICATE_REQUEST_EXPECT_REQUEST) {
2527         unsigned char *buf;
2528         size_t buf_len;
2529 
2530         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
2531                                  ssl, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
2532                                  &buf, &buf_len));
2533 
2534         MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_certificate_request(
2535                                  ssl, buf, buf + buf_len));
2536 
2537         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2538                                  ssl, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
2539                                  buf, buf_len));
2540     } else if (ret == SSL_CERTIFICATE_REQUEST_SKIP) {
2541         ret = 0;
2542     } else {
2543         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2544         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2545         goto cleanup;
2546     }
2547 
2548     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_CERTIFICATE);
2549 
2550 cleanup:
2551 
2552     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate request"));
2553     return ret;
2554 }
2555 
2556 /*
2557  * Handler for MBEDTLS_SSL_SERVER_CERTIFICATE
2558  */
2559 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_server_certificate(mbedtls_ssl_context * ssl)2560 static int ssl_tls13_process_server_certificate(mbedtls_ssl_context *ssl)
2561 {
2562     int ret;
2563 
2564     ret = mbedtls_ssl_tls13_process_certificate(ssl);
2565     if (ret != 0) {
2566         return ret;
2567     }
2568 
2569     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CERTIFICATE_VERIFY);
2570     return 0;
2571 }
2572 
2573 /*
2574  * Handler for MBEDTLS_SSL_CERTIFICATE_VERIFY
2575  */
2576 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_certificate_verify(mbedtls_ssl_context * ssl)2577 static int ssl_tls13_process_certificate_verify(mbedtls_ssl_context *ssl)
2578 {
2579     int ret;
2580 
2581     ret = mbedtls_ssl_tls13_process_certificate_verify(ssl);
2582     if (ret != 0) {
2583         return ret;
2584     }
2585 
2586     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2587     return 0;
2588 }
2589 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
2590 
2591 /*
2592  * Handler for MBEDTLS_SSL_SERVER_FINISHED
2593  */
2594 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_server_finished(mbedtls_ssl_context * ssl)2595 static int ssl_tls13_process_server_finished(mbedtls_ssl_context *ssl)
2596 {
2597     int ret;
2598 
2599     ret = mbedtls_ssl_tls13_process_finished_message(ssl);
2600     if (ret != 0) {
2601         return ret;
2602     }
2603 
2604     ret = mbedtls_ssl_tls13_compute_application_transform(ssl);
2605     if (ret != 0) {
2606         MBEDTLS_SSL_PEND_FATAL_ALERT(
2607             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
2608             MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
2609         return ret;
2610     }
2611 
2612 #if defined(MBEDTLS_SSL_EARLY_DATA)
2613     if (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED) {
2614         ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED;
2615         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_END_OF_EARLY_DATA);
2616     } else
2617 #endif /* MBEDTLS_SSL_EARLY_DATA */
2618     {
2619 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
2620         mbedtls_ssl_handshake_set_state(
2621             ssl, MBEDTLS_SSL_CLIENT_CCS_AFTER_SERVER_FINISHED);
2622 #else
2623         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_CERTIFICATE);
2624 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
2625     }
2626 
2627     return 0;
2628 }
2629 
2630 /*
2631  * Handler for MBEDTLS_SSL_CLIENT_CERTIFICATE
2632  */
2633 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_client_certificate(mbedtls_ssl_context * ssl)2634 static int ssl_tls13_write_client_certificate(mbedtls_ssl_context *ssl)
2635 {
2636     int non_empty_certificate_msg = 0;
2637 
2638     MBEDTLS_SSL_DEBUG_MSG(1,
2639                           ("Switch to handshake traffic keys for outbound traffic"));
2640     mbedtls_ssl_set_outbound_transform(ssl, ssl->handshake->transform_handshake);
2641 
2642 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2643     if (ssl->handshake->client_auth) {
2644         int ret = mbedtls_ssl_tls13_write_certificate(ssl);
2645         if (ret != 0) {
2646             return ret;
2647         }
2648 
2649         if (mbedtls_ssl_own_cert(ssl) != NULL) {
2650             non_empty_certificate_msg = 1;
2651         }
2652     } else {
2653         MBEDTLS_SSL_DEBUG_MSG(2, ("skip write certificate"));
2654     }
2655 #endif
2656 
2657     if (non_empty_certificate_msg) {
2658         mbedtls_ssl_handshake_set_state(ssl,
2659                                         MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY);
2660     } else {
2661         MBEDTLS_SSL_DEBUG_MSG(2, ("skip write certificate verify"));
2662         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_FINISHED);
2663     }
2664 
2665     return 0;
2666 }
2667 
2668 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2669 /*
2670  * Handler for MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY
2671  */
2672 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_client_certificate_verify(mbedtls_ssl_context * ssl)2673 static int ssl_tls13_write_client_certificate_verify(mbedtls_ssl_context *ssl)
2674 {
2675     int ret = mbedtls_ssl_tls13_write_certificate_verify(ssl);
2676 
2677     if (ret == 0) {
2678         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_FINISHED);
2679     }
2680 
2681     return ret;
2682 }
2683 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
2684 
2685 /*
2686  * Handler for MBEDTLS_SSL_CLIENT_FINISHED
2687  */
2688 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_client_finished(mbedtls_ssl_context * ssl)2689 static int ssl_tls13_write_client_finished(mbedtls_ssl_context *ssl)
2690 {
2691     int ret;
2692 
2693     ret = mbedtls_ssl_tls13_write_finished_message(ssl);
2694     if (ret != 0) {
2695         return ret;
2696     }
2697 
2698     ret = mbedtls_ssl_tls13_compute_resumption_master_secret(ssl);
2699     if (ret != 0) {
2700         MBEDTLS_SSL_DEBUG_RET(
2701             1, "mbedtls_ssl_tls13_compute_resumption_master_secret ", ret);
2702         return ret;
2703     }
2704 
2705     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_FLUSH_BUFFERS);
2706     return 0;
2707 }
2708 
2709 /*
2710  * Handler for MBEDTLS_SSL_FLUSH_BUFFERS
2711  */
2712 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_flush_buffers(mbedtls_ssl_context * ssl)2713 static int ssl_tls13_flush_buffers(mbedtls_ssl_context *ssl)
2714 {
2715     MBEDTLS_SSL_DEBUG_MSG(2, ("handshake: done"));
2716     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_WRAPUP);
2717     return 0;
2718 }
2719 
2720 /*
2721  * Handler for MBEDTLS_SSL_HANDSHAKE_WRAPUP
2722  */
2723 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_handshake_wrapup(mbedtls_ssl_context * ssl)2724 static int ssl_tls13_handshake_wrapup(mbedtls_ssl_context *ssl)
2725 {
2726 
2727     mbedtls_ssl_tls13_handshake_wrapup(ssl);
2728 
2729     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
2730     return 0;
2731 }
2732 
2733 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2734 
2735 #if defined(MBEDTLS_SSL_EARLY_DATA)
2736 /* From RFC 8446 section 4.2.10
2737  *
2738  * struct {
2739  *     select (Handshake.msg_type) {
2740  *         case new_session_ticket:   uint32 max_early_data_size;
2741  *         ...
2742  *     };
2743  * } EarlyDataIndication;
2744  */
2745 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_new_session_ticket_early_data_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)2746 static int ssl_tls13_parse_new_session_ticket_early_data_ext(
2747     mbedtls_ssl_context *ssl,
2748     const unsigned char *buf,
2749     const unsigned char *end)
2750 {
2751     mbedtls_ssl_session *session = ssl->session;
2752 
2753     MBEDTLS_SSL_CHK_BUF_READ_PTR(buf, end, 4);
2754 
2755     session->max_early_data_size = MBEDTLS_GET_UINT32_BE(buf, 0);
2756     mbedtls_ssl_tls13_session_set_ticket_flags(
2757         session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA);
2758     MBEDTLS_SSL_DEBUG_MSG(
2759         3, ("received max_early_data_size: %u",
2760             (unsigned int) session->max_early_data_size));
2761 
2762     return 0;
2763 }
2764 #endif /* MBEDTLS_SSL_EARLY_DATA */
2765 
2766 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_new_session_ticket_exts(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)2767 static int ssl_tls13_parse_new_session_ticket_exts(mbedtls_ssl_context *ssl,
2768                                                    const unsigned char *buf,
2769                                                    const unsigned char *end)
2770 {
2771     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2772     const unsigned char *p = buf;
2773 
2774 
2775     handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
2776 
2777     while (p < end) {
2778         unsigned int extension_type;
2779         size_t extension_data_len;
2780         int ret;
2781 
2782         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 4);
2783         extension_type = MBEDTLS_GET_UINT16_BE(p, 0);
2784         extension_data_len = MBEDTLS_GET_UINT16_BE(p, 2);
2785         p += 4;
2786 
2787         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, extension_data_len);
2788 
2789         ret = mbedtls_ssl_tls13_check_received_extension(
2790             ssl, MBEDTLS_SSL_HS_NEW_SESSION_TICKET, extension_type,
2791             MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_NST);
2792         if (ret != 0) {
2793             return ret;
2794         }
2795 
2796         switch (extension_type) {
2797 #if defined(MBEDTLS_SSL_EARLY_DATA)
2798             case MBEDTLS_TLS_EXT_EARLY_DATA:
2799                 ret = ssl_tls13_parse_new_session_ticket_early_data_ext(
2800                     ssl, p, p + extension_data_len);
2801                 if (ret != 0) {
2802                     MBEDTLS_SSL_DEBUG_RET(
2803                         1, "ssl_tls13_parse_new_session_ticket_early_data_ext",
2804                         ret);
2805                 }
2806                 break;
2807 #endif /* MBEDTLS_SSL_EARLY_DATA */
2808 
2809             default:
2810                 MBEDTLS_SSL_PRINT_EXT(
2811                     3, MBEDTLS_SSL_HS_NEW_SESSION_TICKET,
2812                     extension_type, "( ignored )");
2813                 break;
2814         }
2815 
2816         p +=  extension_data_len;
2817     }
2818 
2819     MBEDTLS_SSL_PRINT_EXTS(3, MBEDTLS_SSL_HS_NEW_SESSION_TICKET,
2820                            handshake->received_extensions);
2821 
2822     return 0;
2823 }
2824 
2825 /*
2826  * From RFC8446, page 74
2827  *
2828  * struct {
2829  *    uint32 ticket_lifetime;
2830  *    uint32 ticket_age_add;
2831  *    opaque ticket_nonce<0..255>;
2832  *    opaque ticket<1..2^16-1>;
2833  *    Extension extensions<0..2^16-2>;
2834  * } NewSessionTicket;
2835  *
2836  */
2837 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_new_session_ticket(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,unsigned char ** ticket_nonce,size_t * ticket_nonce_len)2838 static int ssl_tls13_parse_new_session_ticket(mbedtls_ssl_context *ssl,
2839                                               unsigned char *buf,
2840                                               unsigned char *end,
2841                                               unsigned char **ticket_nonce,
2842                                               size_t *ticket_nonce_len)
2843 {
2844     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2845     unsigned char *p = buf;
2846     mbedtls_ssl_session *session = ssl->session;
2847     size_t ticket_len;
2848     unsigned char *ticket;
2849     size_t extensions_len;
2850 
2851     *ticket_nonce = NULL;
2852     *ticket_nonce_len = 0;
2853     /*
2854      *    ticket_lifetime   4 bytes
2855      *    ticket_age_add    4 bytes
2856      *    ticket_nonce_len  1 byte
2857      */
2858     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 9);
2859 
2860     session->ticket_lifetime = MBEDTLS_GET_UINT32_BE(p, 0);
2861     MBEDTLS_SSL_DEBUG_MSG(3,
2862                           ("ticket_lifetime: %u",
2863                            (unsigned int) session->ticket_lifetime));
2864     if (session->ticket_lifetime >
2865         MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME) {
2866         MBEDTLS_SSL_DEBUG_MSG(3, ("ticket_lifetime exceeds 7 days."));
2867         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2868     }
2869 
2870     session->ticket_age_add = MBEDTLS_GET_UINT32_BE(p, 4);
2871     MBEDTLS_SSL_DEBUG_MSG(3,
2872                           ("ticket_age_add: %u",
2873                            (unsigned int) session->ticket_age_add));
2874 
2875     *ticket_nonce_len = p[8];
2876     p += 9;
2877 
2878     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, *ticket_nonce_len);
2879     *ticket_nonce = p;
2880     MBEDTLS_SSL_DEBUG_BUF(3, "ticket_nonce:", *ticket_nonce, *ticket_nonce_len);
2881     p += *ticket_nonce_len;
2882 
2883     /* Ticket */
2884     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
2885     ticket_len = MBEDTLS_GET_UINT16_BE(p, 0);
2886     p += 2;
2887     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, ticket_len);
2888     MBEDTLS_SSL_DEBUG_BUF(3, "received ticket", p, ticket_len);
2889 
2890     /* Check if we previously received a ticket already. */
2891     if (session->ticket != NULL || session->ticket_len > 0) {
2892         mbedtls_free(session->ticket);
2893         session->ticket = NULL;
2894         session->ticket_len = 0;
2895     }
2896 
2897     if ((ticket = mbedtls_calloc(1, ticket_len)) == NULL) {
2898         MBEDTLS_SSL_DEBUG_MSG(1, ("ticket alloc failed"));
2899         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2900     }
2901     memcpy(ticket, p, ticket_len);
2902     p += ticket_len;
2903     session->ticket = ticket;
2904     session->ticket_len = ticket_len;
2905 
2906     /* Clear all flags in ticket_flags */
2907     mbedtls_ssl_tls13_session_clear_ticket_flags(
2908         session, MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
2909 
2910     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
2911     extensions_len = MBEDTLS_GET_UINT16_BE(p, 0);
2912     p += 2;
2913     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, extensions_len);
2914 
2915     MBEDTLS_SSL_DEBUG_BUF(3, "ticket extension", p, extensions_len);
2916 
2917     ret = ssl_tls13_parse_new_session_ticket_exts(ssl, p, p + extensions_len);
2918     if (ret != 0) {
2919         MBEDTLS_SSL_DEBUG_RET(1,
2920                               "ssl_tls13_parse_new_session_ticket_exts",
2921                               ret);
2922         return ret;
2923     }
2924 
2925     return 0;
2926 }
2927 
2928 /* Non negative return values for ssl_tls13_postprocess_new_session_ticket().
2929  * - POSTPROCESS_NEW_SESSION_TICKET_SIGNAL, all good, we have to signal the
2930  *   application that a valid ticket has been received.
2931  * - POSTPROCESS_NEW_SESSION_TICKET_DISCARD, no fatal error, we keep the
2932  *   connection alive but we do not signal the ticket to the application.
2933  */
2934 #define POSTPROCESS_NEW_SESSION_TICKET_SIGNAL 0
2935 #define POSTPROCESS_NEW_SESSION_TICKET_DISCARD 1
2936 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_postprocess_new_session_ticket(mbedtls_ssl_context * ssl,unsigned char * ticket_nonce,size_t ticket_nonce_len)2937 static int ssl_tls13_postprocess_new_session_ticket(mbedtls_ssl_context *ssl,
2938                                                     unsigned char *ticket_nonce,
2939                                                     size_t ticket_nonce_len)
2940 {
2941     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2942     mbedtls_ssl_session *session = ssl->session;
2943     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
2944     psa_algorithm_t psa_hash_alg;
2945     int hash_length;
2946 
2947     if (session->ticket_lifetime == 0) {
2948         return POSTPROCESS_NEW_SESSION_TICKET_DISCARD;
2949     }
2950 
2951 #if defined(MBEDTLS_HAVE_TIME)
2952     /* Store ticket creation time */
2953     session->ticket_reception_time = mbedtls_ms_time();
2954 #endif
2955 
2956     ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(session->ciphersuite);
2957     if (ciphersuite_info == NULL) {
2958         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2959         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2960     }
2961 
2962     psa_hash_alg = mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ciphersuite_info->mac);
2963     hash_length = PSA_HASH_LENGTH(psa_hash_alg);
2964     if (hash_length == -1 ||
2965         (size_t) hash_length > sizeof(session->resumption_key)) {
2966         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2967     }
2968 
2969 
2970     MBEDTLS_SSL_DEBUG_BUF(3, "resumption_master_secret",
2971                           session->app_secrets.resumption_master_secret,
2972                           hash_length);
2973 
2974     /* Compute resumption key
2975      *
2976      *  HKDF-Expand-Label( resumption_master_secret,
2977      *                    "resumption", ticket_nonce, Hash.length )
2978      */
2979     ret = mbedtls_ssl_tls13_hkdf_expand_label(
2980         psa_hash_alg,
2981         session->app_secrets.resumption_master_secret,
2982         hash_length,
2983         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(resumption),
2984         ticket_nonce,
2985         ticket_nonce_len,
2986         session->resumption_key,
2987         hash_length);
2988 
2989     if (ret != 0) {
2990         MBEDTLS_SSL_DEBUG_RET(2,
2991                               "Creating the ticket-resumed PSK failed",
2992                               ret);
2993         return ret;
2994     }
2995 
2996     session->resumption_key_len = hash_length;
2997 
2998     MBEDTLS_SSL_DEBUG_BUF(3, "Ticket-resumed PSK",
2999                           session->resumption_key,
3000                           session->resumption_key_len);
3001 
3002     /* Set ticket_flags depends on the selected key exchange modes */
3003     mbedtls_ssl_tls13_session_set_ticket_flags(
3004         session, ssl->conf->tls13_kex_modes);
3005     MBEDTLS_SSL_PRINT_TICKET_FLAGS(4, session->ticket_flags);
3006 
3007     return POSTPROCESS_NEW_SESSION_TICKET_SIGNAL;
3008 }
3009 
3010 /*
3011  * Handler for MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET
3012  */
3013 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_new_session_ticket(mbedtls_ssl_context * ssl)3014 static int ssl_tls13_process_new_session_ticket(mbedtls_ssl_context *ssl)
3015 {
3016     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3017     unsigned char *buf;
3018     size_t buf_len;
3019     unsigned char *ticket_nonce;
3020     size_t ticket_nonce_len;
3021 
3022     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse new session ticket"));
3023 
3024     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
3025                              ssl, MBEDTLS_SSL_HS_NEW_SESSION_TICKET,
3026                              &buf, &buf_len));
3027 
3028     /*
3029      * We are about to update (maybe only partially) ticket data thus block
3030      * any session export for the time being.
3031      */
3032     ssl->session->exported = 1;
3033 
3034     MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_new_session_ticket(
3035                              ssl, buf, buf + buf_len,
3036                              &ticket_nonce, &ticket_nonce_len));
3037 
3038     MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_postprocess_new_session_ticket(
3039                                  ssl, ticket_nonce, ticket_nonce_len));
3040 
3041     switch (ret) {
3042         case POSTPROCESS_NEW_SESSION_TICKET_SIGNAL:
3043             /*
3044              * All good, we have received a new valid ticket, session data can
3045              * be exported now and we signal the ticket to the application.
3046              */
3047             ssl->session->exported = 0;
3048             ret = MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
3049             break;
3050 
3051         case POSTPROCESS_NEW_SESSION_TICKET_DISCARD:
3052             ret = 0;
3053             MBEDTLS_SSL_DEBUG_MSG(2, ("Discard new session ticket"));
3054             break;
3055 
3056         default:
3057             ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3058     }
3059 
3060     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
3061 
3062 cleanup:
3063 
3064     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse new session ticket"));
3065     return ret;
3066 }
3067 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3068 
mbedtls_ssl_tls13_handshake_client_step(mbedtls_ssl_context * ssl)3069 int mbedtls_ssl_tls13_handshake_client_step(mbedtls_ssl_context *ssl)
3070 {
3071     int ret = 0;
3072 
3073     switch (ssl->state) {
3074         case MBEDTLS_SSL_HELLO_REQUEST:
3075             mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
3076             break;
3077 
3078         case MBEDTLS_SSL_CLIENT_HELLO:
3079             ret = mbedtls_ssl_write_client_hello(ssl);
3080             break;
3081 
3082         case MBEDTLS_SSL_SERVER_HELLO:
3083             ret = ssl_tls13_process_server_hello(ssl);
3084             break;
3085 
3086         case MBEDTLS_SSL_ENCRYPTED_EXTENSIONS:
3087             ret = ssl_tls13_process_encrypted_extensions(ssl);
3088             break;
3089 
3090 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
3091         case MBEDTLS_SSL_CERTIFICATE_REQUEST:
3092             ret = ssl_tls13_process_certificate_request(ssl);
3093             break;
3094 
3095         case MBEDTLS_SSL_SERVER_CERTIFICATE:
3096             ret = ssl_tls13_process_server_certificate(ssl);
3097             break;
3098 
3099         case MBEDTLS_SSL_CERTIFICATE_VERIFY:
3100             ret = ssl_tls13_process_certificate_verify(ssl);
3101             break;
3102 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
3103 
3104         case MBEDTLS_SSL_SERVER_FINISHED:
3105             ret = ssl_tls13_process_server_finished(ssl);
3106             break;
3107 
3108 #if defined(MBEDTLS_SSL_EARLY_DATA)
3109         case MBEDTLS_SSL_END_OF_EARLY_DATA:
3110             ret = ssl_tls13_write_end_of_early_data(ssl);
3111             break;
3112 #endif
3113 
3114         case MBEDTLS_SSL_CLIENT_CERTIFICATE:
3115             ret = ssl_tls13_write_client_certificate(ssl);
3116             break;
3117 
3118 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
3119         case MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY:
3120             ret = ssl_tls13_write_client_certificate_verify(ssl);
3121             break;
3122 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
3123 
3124         case MBEDTLS_SSL_CLIENT_FINISHED:
3125             ret = ssl_tls13_write_client_finished(ssl);
3126             break;
3127 
3128         case MBEDTLS_SSL_FLUSH_BUFFERS:
3129             ret = ssl_tls13_flush_buffers(ssl);
3130             break;
3131 
3132         case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
3133             ret = ssl_tls13_handshake_wrapup(ssl);
3134             break;
3135 
3136             /*
3137              * Injection of dummy-CCS's for middlebox compatibility
3138              */
3139 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
3140         case MBEDTLS_SSL_CLIENT_CCS_BEFORE_2ND_CLIENT_HELLO:
3141             ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
3142             if (ret != 0) {
3143                 break;
3144             }
3145             mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
3146             break;
3147 
3148         case MBEDTLS_SSL_CLIENT_CCS_AFTER_SERVER_FINISHED:
3149             ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
3150             if (ret != 0) {
3151                 break;
3152             }
3153             mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_CERTIFICATE);
3154             break;
3155 
3156 #if defined(MBEDTLS_SSL_EARLY_DATA)
3157         case MBEDTLS_SSL_CLIENT_CCS_AFTER_CLIENT_HELLO:
3158             ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
3159             if (ret == 0) {
3160                 mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_HELLO);
3161 
3162                 MBEDTLS_SSL_DEBUG_MSG(
3163                     1, ("Switch to early data keys for outbound traffic"));
3164                 mbedtls_ssl_set_outbound_transform(
3165                     ssl, ssl->handshake->transform_earlydata);
3166                 ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE;
3167             }
3168             break;
3169 #endif /* MBEDTLS_SSL_EARLY_DATA */
3170 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
3171 
3172 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3173         case MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET:
3174             ret = ssl_tls13_process_new_session_ticket(ssl);
3175             break;
3176 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3177 
3178         default:
3179             MBEDTLS_SSL_DEBUG_MSG(1, ("invalid state %d", ssl->state));
3180             return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
3181     }
3182 
3183     return ret;
3184 }
3185 
3186 #endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_PROTO_TLS1_3 */
3187