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