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