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