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