xref: /optee_os/lib/libmbedtls/mbedtls/library/ssl_tls13_server.c (revision c3deb3d6f3b13d0e17fc9efe5880aec039e47594)
1 /*
2  *  TLS 1.3 server-side functions
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #include "common.h"
9 
10 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
11 
12 #include "debug_internal.h"
13 #include "mbedtls/error.h"
14 #include "mbedtls/platform.h"
15 #include "mbedtls/constant_time.h"
16 #include "mbedtls/oid.h"
17 #include "mbedtls/psa_util.h"
18 
19 #include "ssl_misc.h"
20 #include "ssl_tls13_keys.h"
21 #include "ssl_debug_helpers.h"
22 
23 
ssl_tls13_validate_peer_ciphersuite(mbedtls_ssl_context * ssl,unsigned int cipher_suite)24 static const mbedtls_ssl_ciphersuite_t *ssl_tls13_validate_peer_ciphersuite(
25     mbedtls_ssl_context *ssl,
26     unsigned int cipher_suite)
27 {
28     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
29     if (!mbedtls_ssl_tls13_cipher_suite_is_offered(ssl, cipher_suite)) {
30         return NULL;
31     }
32 
33     ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(cipher_suite);
34     if ((mbedtls_ssl_validate_ciphersuite(ssl, ciphersuite_info,
35                                           ssl->tls_version,
36                                           ssl->tls_version) != 0)) {
37         return NULL;
38     }
39     return ciphersuite_info;
40 }
41 
ssl_tls13_select_ciphersuite(mbedtls_ssl_context * ssl,const unsigned char * cipher_suites,const unsigned char * cipher_suites_end,int psk_ciphersuite_id,psa_algorithm_t psk_hash_alg,const mbedtls_ssl_ciphersuite_t ** selected_ciphersuite_info)42 static void ssl_tls13_select_ciphersuite(
43     mbedtls_ssl_context *ssl,
44     const unsigned char *cipher_suites,
45     const unsigned char *cipher_suites_end,
46     int psk_ciphersuite_id,
47     psa_algorithm_t psk_hash_alg,
48     const mbedtls_ssl_ciphersuite_t **selected_ciphersuite_info)
49 {
50     *selected_ciphersuite_info = NULL;
51 
52     /*
53      * In a compliant ClientHello the byte-length of the list of ciphersuites
54      * is even and this function relies on this fact. This should have been
55      * checked in the main ClientHello parsing function. Double check here.
56      */
57     if ((cipher_suites_end - cipher_suites) & 1) {
58         return;
59     }
60 
61     for (const unsigned char *p = cipher_suites;
62          p < cipher_suites_end; p += 2) {
63         /*
64          * "cipher_suites_end - p is even" is an invariant of the loop. As
65          * cipher_suites_end - p > 0, we have cipher_suites_end - p >= 2 and it
66          * is thus safe to read two bytes.
67          */
68         uint16_t id = MBEDTLS_GET_UINT16_BE(p, 0);
69 
70         const mbedtls_ssl_ciphersuite_t *info =
71             ssl_tls13_validate_peer_ciphersuite(ssl, id);
72         if (info == NULL) {
73             continue;
74         }
75 
76         /*
77          * If a valid PSK ciphersuite identifier has been passed in, we want
78          * an exact match.
79          */
80         if (psk_ciphersuite_id != 0) {
81             if (id != psk_ciphersuite_id) {
82                 continue;
83             }
84         } else if (psk_hash_alg != PSA_ALG_NONE) {
85             if (mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) info->mac) !=
86                 psk_hash_alg) {
87                 continue;
88             }
89         }
90 
91         *selected_ciphersuite_info = info;
92         return;
93     }
94 
95     MBEDTLS_SSL_DEBUG_MSG(1, ("No matched ciphersuite, psk_ciphersuite_id=%x, psk_hash_alg=%lx",
96                               (unsigned) psk_ciphersuite_id,
97                               (unsigned long) psk_hash_alg));
98 }
99 
100 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
101 /* From RFC 8446:
102  *
103  *   enum { psk_ke(0), psk_dhe_ke(1), (255) } PskKeyExchangeMode;
104  *   struct {
105  *       PskKeyExchangeMode ke_modes<1..255>;
106  *   } PskKeyExchangeModes;
107  */
108 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_key_exchange_modes_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)109 static int ssl_tls13_parse_key_exchange_modes_ext(mbedtls_ssl_context *ssl,
110                                                   const unsigned char *buf,
111                                                   const unsigned char *end)
112 {
113     const unsigned char *p = buf;
114     size_t ke_modes_len;
115     int ke_modes = 0;
116 
117     /* Read ke_modes length (1 Byte) */
118     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 1);
119     ke_modes_len = *p++;
120     /* Currently, there are only two PSK modes, so even without looking
121      * at the content, something's wrong if the list has more than 2 items. */
122     if (ke_modes_len > 2) {
123         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
124                                      MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
125         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
126     }
127 
128     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, ke_modes_len);
129 
130     while (ke_modes_len-- != 0) {
131         switch (*p++) {
132             case MBEDTLS_SSL_TLS1_3_PSK_MODE_PURE:
133                 ke_modes |= MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
134                 MBEDTLS_SSL_DEBUG_MSG(3, ("Found PSK KEX MODE"));
135                 break;
136             case MBEDTLS_SSL_TLS1_3_PSK_MODE_ECDHE:
137                 ke_modes |= MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
138                 MBEDTLS_SSL_DEBUG_MSG(3, ("Found PSK_EPHEMERAL KEX MODE"));
139                 break;
140             default:
141                 MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
142                                              MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
143                 return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
144         }
145     }
146 
147     ssl->handshake->tls13_kex_modes = ke_modes;
148     return 0;
149 }
150 
151 /*
152  * Non-error return values of
153  * ssl_tls13_offered_psks_check_identity_match_ticket() and
154  * ssl_tls13_offered_psks_check_identity_match(). They are positive to
155  * not collide with error codes that are negative. Zero
156  * (SSL_TLS1_3_PSK_IDENTITY_MATCH) in case of success as it may be propagated
157  * up by the callers of this function as a generic success condition.
158  *
159  * The return value SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE means
160  * that the pre-shared-key identity matches that of a ticket or an externally-
161  * provisioned pre-shared-key. We have thus been able to retrieve the
162  * attributes of the pre-shared-key but at least one of them does not meet
163  * some criteria and the pre-shared-key cannot be used. For example, a ticket
164  * is expired or its version is not TLS 1.3. Note eventually that the return
165  * value SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE does not have
166  * anything to do with binder check. A binder check is done only when a
167  * suitable pre-shared-key has been selected and only for that selected
168  * pre-shared-key: if the binder check fails, we fail the handshake and we do
169  * not try to find another pre-shared-key for which the binder check would
170  * succeed as recommended by the specification.
171  */
172 #define SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH 2
173 #define SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE 1
174 #define SSL_TLS1_3_PSK_IDENTITY_MATCH 0
175 
176 MBEDTLS_CHECK_RETURN_CRITICAL
177 static int ssl_tls13_key_exchange_is_psk_available(mbedtls_ssl_context *ssl);
178 MBEDTLS_CHECK_RETURN_CRITICAL
179 static int ssl_tls13_key_exchange_is_psk_ephemeral_available(mbedtls_ssl_context *ssl);
180 
181 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
182 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_offered_psks_check_identity_match_ticket(mbedtls_ssl_context * ssl,const unsigned char * identity,size_t identity_len,uint32_t obfuscated_ticket_age,mbedtls_ssl_session * session)183 static int ssl_tls13_offered_psks_check_identity_match_ticket(
184     mbedtls_ssl_context *ssl,
185     const unsigned char *identity,
186     size_t identity_len,
187     uint32_t obfuscated_ticket_age,
188     mbedtls_ssl_session *session)
189 {
190     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
191     unsigned char *ticket_buffer;
192 #if defined(MBEDTLS_HAVE_TIME)
193     mbedtls_ms_time_t now;
194     mbedtls_ms_time_t server_age;
195     uint32_t client_age;
196     mbedtls_ms_time_t age_diff;
197 #endif
198 
199     ((void) obfuscated_ticket_age);
200 
201     MBEDTLS_SSL_DEBUG_MSG(2, ("=> check_identity_match_ticket"));
202 
203     /* Ticket parser is not configured, Skip */
204     if (ssl->conf->f_ticket_parse == NULL || identity_len == 0) {
205         return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
206     }
207 
208     /* We create a copy of the encrypted ticket since the ticket parsing
209      * function is allowed to use its input buffer as an output buffer
210      * (in-place decryption). We do, however, need the original buffer for
211      * computing the PSK binder value.
212      */
213     ticket_buffer = mbedtls_calloc(1, identity_len);
214     if (ticket_buffer == NULL) {
215         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
216     }
217     memcpy(ticket_buffer, identity, identity_len);
218 
219     ret = ssl->conf->f_ticket_parse(ssl->conf->p_ticket,
220                                     session,
221                                     ticket_buffer, identity_len);
222     switch (ret) {
223         case 0:
224             ret = SSL_TLS1_3_PSK_IDENTITY_MATCH;
225             break;
226 
227         case MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED:
228             MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is expired"));
229             ret = SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
230             break;
231 
232         case MBEDTLS_ERR_SSL_INVALID_MAC:
233             MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is not authentic"));
234             ret = SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
235             break;
236 
237         default:
238             MBEDTLS_SSL_DEBUG_RET(1, "ticket_parse", ret);
239             ret = SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
240     }
241 
242     /* We delete the temporary buffer */
243     mbedtls_free(ticket_buffer);
244 
245     if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
246         goto exit;
247     }
248 
249     /*
250      * The identity matches that of a ticket. Now check that it has suitable
251      * attributes and bet it will not be the case.
252      */
253     ret = SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
254 
255     if (session->tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
256         MBEDTLS_SSL_DEBUG_MSG(3, ("Ticket TLS version is not 1.3."));
257         goto exit;
258     }
259 
260 #if defined(MBEDTLS_HAVE_TIME)
261     now = mbedtls_ms_time();
262 
263     if (now < session->ticket_creation_time) {
264         MBEDTLS_SSL_DEBUG_MSG(
265             3, ("Invalid ticket creation time ( now = %" MBEDTLS_PRINTF_MS_TIME
266                 ", creation_time = %" MBEDTLS_PRINTF_MS_TIME " )",
267                 now, session->ticket_creation_time));
268         goto exit;
269     }
270 
271     server_age = now - session->ticket_creation_time;
272 
273     /* RFC 8446 section 4.6.1
274      *
275      * Servers MUST NOT use any value greater than 604800 seconds (7 days).
276      *
277      * RFC 8446 section 4.2.11.1
278      *
279      * Clients MUST NOT attempt to use tickets which have ages greater than
280      * the "ticket_lifetime" value which was provided with the ticket.
281      *
282      */
283     if (server_age > MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME * 1000) {
284         MBEDTLS_SSL_DEBUG_MSG(
285             3, ("Ticket age exceeds limitation ticket_age = %" MBEDTLS_PRINTF_MS_TIME,
286                 server_age));
287         goto exit;
288     }
289 
290     /* RFC 8446 section 4.2.10
291      *
292      * For PSKs provisioned via NewSessionTicket, a server MUST validate that
293      * the ticket age for the selected PSK identity (computed by subtracting
294      * ticket_age_add from PskIdentity.obfuscated_ticket_age modulo 2^32) is
295      * within a small tolerance of the time since the ticket was issued.
296      *
297      * NOTE: The typical accuracy of an RTC crystal is ±100 to ±20 parts per
298      *       million (360 to 72 milliseconds per hour). Default tolerance
299      *       window is 6s, thus in the worst case clients and servers must
300      *       sync up their system time every 6000/360/2~=8 hours.
301      */
302     client_age = obfuscated_ticket_age - session->ticket_age_add;
303     age_diff = server_age - (mbedtls_ms_time_t) client_age;
304     if (age_diff < -MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE ||
305         age_diff > MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE) {
306         MBEDTLS_SSL_DEBUG_MSG(
307             3, ("Ticket age outside tolerance window ( diff = %"
308                 MBEDTLS_PRINTF_MS_TIME ")",
309                 age_diff));
310         goto exit;
311     }
312 #endif /* MBEDTLS_HAVE_TIME */
313 
314     /*
315      * All good, we have found a suitable ticket.
316      */
317     ret = SSL_TLS1_3_PSK_IDENTITY_MATCH;
318 
319 exit:
320     if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
321         mbedtls_ssl_session_free(session);
322     }
323 
324     MBEDTLS_SSL_DEBUG_MSG(2, ("<= check_identity_match_ticket"));
325     return ret;
326 }
327 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
328 
329 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_offered_psks_check_identity_match(mbedtls_ssl_context * ssl,const unsigned char * identity,size_t identity_len,uint32_t obfuscated_ticket_age,int * psk_type,mbedtls_ssl_session * session)330 static int ssl_tls13_offered_psks_check_identity_match(
331     mbedtls_ssl_context *ssl,
332     const unsigned char *identity,
333     size_t identity_len,
334     uint32_t obfuscated_ticket_age,
335     int *psk_type,
336     mbedtls_ssl_session *session)
337 {
338     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
339 
340     ((void) session);
341     ((void) obfuscated_ticket_age);
342     *psk_type = MBEDTLS_SSL_TLS1_3_PSK_EXTERNAL;
343 
344     MBEDTLS_SSL_DEBUG_BUF(4, "identity", identity, identity_len);
345 
346 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
347     ret = ssl_tls13_offered_psks_check_identity_match_ticket(
348         ssl, identity, identity_len, obfuscated_ticket_age, session);
349     if (ret == SSL_TLS1_3_PSK_IDENTITY_MATCH) {
350         *psk_type = MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION;
351         ret = mbedtls_ssl_set_hs_psk(ssl,
352                                      session->resumption_key,
353                                      session->resumption_key_len);
354         if (ret != 0) {
355             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
356             return ret;
357         }
358 
359         MBEDTLS_SSL_DEBUG_BUF(4, "Ticket-resumed PSK:",
360                               session->resumption_key,
361                               session->resumption_key_len);
362         MBEDTLS_SSL_DEBUG_MSG(4, ("ticket: obfuscated_ticket_age: %u",
363                                   (unsigned) obfuscated_ticket_age));
364         return SSL_TLS1_3_PSK_IDENTITY_MATCH;
365     } else if (ret == SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE) {
366         return SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
367     }
368 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
369 
370     /* Check identity with external configured function */
371     if (ssl->conf->f_psk != NULL) {
372         if (ssl->conf->f_psk(
373                 ssl->conf->p_psk, ssl, identity, identity_len) == 0) {
374             return SSL_TLS1_3_PSK_IDENTITY_MATCH;
375         }
376         return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
377     }
378 
379     MBEDTLS_SSL_DEBUG_BUF(5, "identity", identity, identity_len);
380     /* Check identity with pre-configured psk */
381     if (ssl->conf->psk_identity != NULL &&
382         identity_len == ssl->conf->psk_identity_len &&
383         mbedtls_ct_memcmp(ssl->conf->psk_identity,
384                           identity, identity_len) == 0) {
385         ret = mbedtls_ssl_set_hs_psk(ssl, ssl->conf->psk, ssl->conf->psk_len);
386         if (ret != 0) {
387             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
388             return ret;
389         }
390         return SSL_TLS1_3_PSK_IDENTITY_MATCH;
391     }
392 
393     return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
394 }
395 
396 /*
397  * Non-error return values of ssl_tls13_offered_psks_check_binder_match().
398  * They are positive to not collide with error codes that are negative. Zero
399  * (SSL_TLS1_3_BINDER_MATCH) in case of success as it may be propagated up
400  * by the callers of this function as a generic success condition.
401  */
402 #define SSL_TLS1_3_BINDER_DOES_NOT_MATCH 1
403 #define SSL_TLS1_3_BINDER_MATCH 0
404 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_offered_psks_check_binder_match(mbedtls_ssl_context * ssl,const unsigned char * binder,size_t binder_len,int psk_type,psa_algorithm_t psk_hash_alg)405 static int ssl_tls13_offered_psks_check_binder_match(
406     mbedtls_ssl_context *ssl,
407     const unsigned char *binder, size_t binder_len,
408     int psk_type, psa_algorithm_t psk_hash_alg)
409 {
410     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
411 
412     unsigned char transcript[PSA_HASH_MAX_SIZE];
413     size_t transcript_len;
414     unsigned char *psk;
415     size_t psk_len;
416     unsigned char server_computed_binder[PSA_HASH_MAX_SIZE];
417 
418     if (binder_len != PSA_HASH_LENGTH(psk_hash_alg)) {
419         return SSL_TLS1_3_BINDER_DOES_NOT_MATCH;
420     }
421 
422     /* Get current state of handshake transcript. */
423     ret = mbedtls_ssl_get_handshake_transcript(
424         ssl, mbedtls_md_type_from_psa_alg(psk_hash_alg),
425         transcript, sizeof(transcript), &transcript_len);
426     if (ret != 0) {
427         return ret;
428     }
429 
430     ret = mbedtls_ssl_tls13_export_handshake_psk(ssl, &psk, &psk_len);
431     if (ret != 0) {
432         return ret;
433     }
434 
435     ret = mbedtls_ssl_tls13_create_psk_binder(ssl, psk_hash_alg,
436                                               psk, psk_len, psk_type,
437                                               transcript,
438                                               server_computed_binder);
439 #if defined(MBEDTLS_USE_PSA_CRYPTO)
440     mbedtls_free((void *) psk);
441 #endif
442     if (ret != 0) {
443         MBEDTLS_SSL_DEBUG_MSG(1, ("PSK binder calculation failed."));
444         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
445     }
446 
447     MBEDTLS_SSL_DEBUG_BUF(3, "psk binder ( computed ): ",
448                           server_computed_binder, transcript_len);
449     MBEDTLS_SSL_DEBUG_BUF(3, "psk binder ( received ): ", binder, binder_len);
450 
451     if (mbedtls_ct_memcmp(server_computed_binder,
452                           binder,
453                           PSA_HASH_LENGTH(psk_hash_alg)) == 0) {
454         return SSL_TLS1_3_BINDER_MATCH;
455     }
456 
457     mbedtls_platform_zeroize(server_computed_binder,
458                              sizeof(server_computed_binder));
459     return SSL_TLS1_3_BINDER_DOES_NOT_MATCH;
460 }
461 
462 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
463 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_session_copy_ticket(mbedtls_ssl_session * dst,const mbedtls_ssl_session * src)464 static int ssl_tls13_session_copy_ticket(mbedtls_ssl_session *dst,
465                                          const mbedtls_ssl_session *src)
466 {
467     dst->ticket_age_add = src->ticket_age_add;
468     dst->ticket_flags = src->ticket_flags;
469     dst->resumption_key_len = src->resumption_key_len;
470     if (src->resumption_key_len == 0) {
471         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
472     }
473     memcpy(dst->resumption_key, src->resumption_key, src->resumption_key_len);
474 
475 #if defined(MBEDTLS_SSL_EARLY_DATA)
476     dst->max_early_data_size = src->max_early_data_size;
477 
478 #if defined(MBEDTLS_SSL_ALPN)
479     int ret = mbedtls_ssl_session_set_ticket_alpn(dst, src->ticket_alpn);
480     if (ret != 0) {
481         return ret;
482     }
483 #endif /* MBEDTLS_SSL_ALPN */
484 #endif /* MBEDTLS_SSL_EARLY_DATA*/
485 
486     return 0;
487 }
488 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
489 
490 struct psk_attributes {
491     int type;
492     int key_exchange_mode;
493     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
494 };
495 #define PSK_ATTRIBUTES_INIT { 0, 0, NULL }
496 
497 /* Parser for pre_shared_key extension in client hello
498  *    struct {
499  *        opaque identity<1..2^16-1>;
500  *        uint32 obfuscated_ticket_age;
501  *    } PskIdentity;
502  *
503  *    opaque PskBinderEntry<32..255>;
504  *
505  *    struct {
506  *        PskIdentity identities<7..2^16-1>;
507  *        PskBinderEntry binders<33..2^16-1>;
508  *    } OfferedPsks;
509  *
510  *    struct {
511  *        select (Handshake.msg_type) {
512  *            case client_hello: OfferedPsks;
513  *            ....
514  *        };
515  *    } PreSharedKeyExtension;
516  */
517 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_pre_shared_key_ext(mbedtls_ssl_context * ssl,const unsigned char * pre_shared_key_ext,const unsigned char * pre_shared_key_ext_end,const unsigned char * ciphersuites,const unsigned char * ciphersuites_end,struct psk_attributes * psk)518 static int ssl_tls13_parse_pre_shared_key_ext(
519     mbedtls_ssl_context *ssl,
520     const unsigned char *pre_shared_key_ext,
521     const unsigned char *pre_shared_key_ext_end,
522     const unsigned char *ciphersuites,
523     const unsigned char *ciphersuites_end,
524     struct psk_attributes *psk)
525 {
526     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
527     const unsigned char *identities = pre_shared_key_ext;
528     const unsigned char *p_identity_len;
529     size_t identities_len;
530     const unsigned char *identities_end;
531     const unsigned char *binders;
532     const unsigned char *p_binder_len;
533     size_t binders_len;
534     const unsigned char *binders_end;
535     int matched_identity = -1;
536     int identity_id = -1;
537 
538     MBEDTLS_SSL_DEBUG_BUF(3, "pre_shared_key extension",
539                           pre_shared_key_ext,
540                           pre_shared_key_ext_end - pre_shared_key_ext);
541 
542     /* identities_len       2 bytes
543      * identities_data   >= 7 bytes
544      */
545     MBEDTLS_SSL_CHK_BUF_READ_PTR(identities, pre_shared_key_ext_end, 7 + 2);
546     identities_len = MBEDTLS_GET_UINT16_BE(identities, 0);
547     p_identity_len = identities + 2;
548     MBEDTLS_SSL_CHK_BUF_READ_PTR(p_identity_len, pre_shared_key_ext_end,
549                                  identities_len);
550     identities_end = p_identity_len + identities_len;
551 
552     /* binders_len     2  bytes
553      * binders      >= 33 bytes
554      */
555     binders = identities_end;
556     MBEDTLS_SSL_CHK_BUF_READ_PTR(binders, pre_shared_key_ext_end, 33 + 2);
557     binders_len = MBEDTLS_GET_UINT16_BE(binders, 0);
558     p_binder_len = binders + 2;
559     MBEDTLS_SSL_CHK_BUF_READ_PTR(p_binder_len, pre_shared_key_ext_end, binders_len);
560     binders_end = p_binder_len + binders_len;
561 
562     ret = ssl->handshake->update_checksum(ssl, pre_shared_key_ext,
563                                           identities_end - pre_shared_key_ext);
564     if (0 != ret) {
565         MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
566         return ret;
567     }
568 
569     while (p_identity_len < identities_end && p_binder_len < binders_end) {
570         const unsigned char *identity;
571         size_t identity_len;
572         uint32_t obfuscated_ticket_age;
573         const unsigned char *binder;
574         size_t binder_len;
575         int psk_ciphersuite_id;
576         psa_algorithm_t psk_hash_alg;
577         int allowed_key_exchange_modes;
578 
579         mbedtls_ssl_session session;
580         mbedtls_ssl_session_init(&session);
581 
582         MBEDTLS_SSL_CHK_BUF_READ_PTR(p_identity_len, identities_end, 2 + 1 + 4);
583         identity_len = MBEDTLS_GET_UINT16_BE(p_identity_len, 0);
584         identity = p_identity_len + 2;
585         MBEDTLS_SSL_CHK_BUF_READ_PTR(identity, identities_end, identity_len + 4);
586         obfuscated_ticket_age = MBEDTLS_GET_UINT32_BE(identity, identity_len);
587         p_identity_len += identity_len + 6;
588 
589         MBEDTLS_SSL_CHK_BUF_READ_PTR(p_binder_len, binders_end, 1 + 32);
590         binder_len = *p_binder_len;
591         binder = p_binder_len + 1;
592         MBEDTLS_SSL_CHK_BUF_READ_PTR(binder, binders_end, binder_len);
593         p_binder_len += binder_len + 1;
594 
595         identity_id++;
596         if (matched_identity != -1) {
597             continue;
598         }
599 
600         ret = ssl_tls13_offered_psks_check_identity_match(
601             ssl, identity, identity_len, obfuscated_ticket_age,
602             &psk->type, &session);
603         if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
604             continue;
605         }
606 
607         MBEDTLS_SSL_DEBUG_MSG(4, ("found matched identity"));
608 
609         switch (psk->type) {
610             case MBEDTLS_SSL_TLS1_3_PSK_EXTERNAL:
611                 psk_ciphersuite_id = 0;
612                 psk_hash_alg = PSA_ALG_SHA_256;
613                 allowed_key_exchange_modes =
614                     MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
615                 break;
616 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
617             case MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION:
618                 psk_ciphersuite_id = session.ciphersuite;
619                 psk_hash_alg = PSA_ALG_NONE;
620                 ssl->session_negotiate->ticket_flags = session.ticket_flags;
621                 allowed_key_exchange_modes =
622                     session.ticket_flags &
623                     MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
624                 break;
625 #endif
626             default:
627                 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
628         }
629 
630         psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE;
631 
632         if ((allowed_key_exchange_modes &
633              MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL) &&
634             ssl_tls13_key_exchange_is_psk_ephemeral_available(ssl)) {
635             psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
636         } else if ((allowed_key_exchange_modes &
637                     MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK) &&
638                    ssl_tls13_key_exchange_is_psk_available(ssl)) {
639             psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
640         }
641 
642         if (psk->key_exchange_mode == MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE) {
643             MBEDTLS_SSL_DEBUG_MSG(3, ("No suitable PSK key exchange mode"));
644             continue;
645         }
646 
647         ssl_tls13_select_ciphersuite(ssl, ciphersuites, ciphersuites_end,
648                                      psk_ciphersuite_id, psk_hash_alg,
649                                      &psk->ciphersuite_info);
650 
651         if (psk->ciphersuite_info == NULL) {
652 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
653             mbedtls_ssl_session_free(&session);
654 #endif
655             /*
656              * We consider finding a ciphersuite suitable for the PSK as part
657              * of the validation of its binder. Thus if we do not find one, we
658              * abort the handshake with a decrypt_error alert.
659              */
660             MBEDTLS_SSL_PEND_FATAL_ALERT(
661                 MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
662                 MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
663             return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
664         }
665 
666         ret = ssl_tls13_offered_psks_check_binder_match(
667             ssl, binder, binder_len, psk->type,
668             mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) psk->ciphersuite_info->mac));
669         if (ret != SSL_TLS1_3_BINDER_MATCH) {
670             /* For security reasons, the handshake should be aborted when we
671              * fail to validate a binder value. See RFC 8446 section 4.2.11.2
672              * and appendix E.6. */
673 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
674             mbedtls_ssl_session_free(&session);
675 #endif
676             MBEDTLS_SSL_DEBUG_MSG(3, ("Invalid binder."));
677             MBEDTLS_SSL_DEBUG_RET(
678                 1, "ssl_tls13_offered_psks_check_binder_match", ret);
679             MBEDTLS_SSL_PEND_FATAL_ALERT(
680                 MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
681                 MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
682             return ret;
683         }
684 
685         matched_identity = identity_id;
686 
687 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
688         if (psk->type == MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION) {
689             ret = ssl_tls13_session_copy_ticket(ssl->session_negotiate,
690                                                 &session);
691             mbedtls_ssl_session_free(&session);
692             if (ret != 0) {
693                 return ret;
694             }
695         }
696 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
697     }
698 
699     if (p_identity_len != identities_end || p_binder_len != binders_end) {
700         MBEDTLS_SSL_DEBUG_MSG(3, ("pre_shared_key extension decode error"));
701         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
702                                      MBEDTLS_ERR_SSL_DECODE_ERROR);
703         return MBEDTLS_ERR_SSL_DECODE_ERROR;
704     }
705 
706     /* Update the handshake transcript with the binder list. */
707     ret = ssl->handshake->update_checksum(
708         ssl, identities_end, (size_t) (binders_end - identities_end));
709     if (0 != ret) {
710         MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
711         return ret;
712     }
713     if (matched_identity == -1) {
714         MBEDTLS_SSL_DEBUG_MSG(3, ("No usable PSK or ticket."));
715         return MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
716     }
717 
718     ssl->handshake->selected_identity = (uint16_t) matched_identity;
719     MBEDTLS_SSL_DEBUG_MSG(3, ("Pre shared key found"));
720 
721     return 0;
722 }
723 
724 /*
725  * struct {
726  *   select ( Handshake.msg_type ) {
727  *      ....
728  *      case server_hello:
729  *          uint16 selected_identity;
730  *   }
731  * } PreSharedKeyExtension;
732  */
ssl_tls13_write_server_pre_shared_key_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * olen)733 static int ssl_tls13_write_server_pre_shared_key_ext(mbedtls_ssl_context *ssl,
734                                                      unsigned char *buf,
735                                                      unsigned char *end,
736                                                      size_t *olen)
737 {
738     unsigned char *p = (unsigned char *) buf;
739 
740     *olen = 0;
741 
742     int not_using_psk = 0;
743 #if defined(MBEDTLS_USE_PSA_CRYPTO)
744     not_using_psk = (mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque));
745 #else
746     not_using_psk = (ssl->handshake->psk == NULL);
747 #endif
748     if (not_using_psk) {
749         /* We shouldn't have called this extension writer unless we've
750          * chosen to use a PSK. */
751         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
752     }
753 
754     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding pre_shared_key extension"));
755     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 6);
756 
757     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_PRE_SHARED_KEY, p, 0);
758     MBEDTLS_PUT_UINT16_BE(2, p, 2);
759 
760     MBEDTLS_PUT_UINT16_BE(ssl->handshake->selected_identity, p, 4);
761 
762     *olen = 6;
763 
764     MBEDTLS_SSL_DEBUG_MSG(4, ("sent selected_identity: %u",
765                               ssl->handshake->selected_identity));
766 
767     mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_PRE_SHARED_KEY);
768 
769     return 0;
770 }
771 
772 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
773 
774 /* From RFC 8446:
775  *   struct {
776  *          ProtocolVersion versions<2..254>;
777  *   } SupportedVersions;
778  */
779 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_supported_versions_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)780 static int ssl_tls13_parse_supported_versions_ext(mbedtls_ssl_context *ssl,
781                                                   const unsigned char *buf,
782                                                   const unsigned char *end)
783 {
784     const unsigned char *p = buf;
785     size_t versions_len;
786     const unsigned char *versions_end;
787     uint16_t tls_version;
788     int found_supported_version = 0;
789 
790     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 1);
791     versions_len = p[0];
792     p += 1;
793 
794     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, versions_len);
795     versions_end = p + versions_len;
796     while (p < versions_end) {
797         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, versions_end, 2);
798         tls_version = mbedtls_ssl_read_version(p, ssl->conf->transport);
799         p += 2;
800 
801         if (MBEDTLS_SSL_VERSION_TLS1_3 == tls_version) {
802             found_supported_version = 1;
803             break;
804         }
805 
806         if ((MBEDTLS_SSL_VERSION_TLS1_2 == tls_version) &&
807             mbedtls_ssl_conf_is_tls12_enabled(ssl->conf)) {
808             found_supported_version = 1;
809             break;
810         }
811     }
812 
813     if (!found_supported_version) {
814         MBEDTLS_SSL_DEBUG_MSG(1, ("No supported version found."));
815 
816         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION,
817                                      MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION);
818         return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
819     }
820 
821     MBEDTLS_SSL_DEBUG_MSG(1, ("Negotiated version: [%04x]",
822                               (unsigned int) tls_version));
823 
824     return (int) tls_version;
825 }
826 
827 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
828 /*
829  *
830  * From RFC 8446:
831  *   enum {
832  *       ... (0xFFFF)
833  *   } NamedGroup;
834  *   struct {
835  *       NamedGroup named_group_list<2..2^16-1>;
836  *   } NamedGroupList;
837  */
838 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_supported_groups_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)839 static int ssl_tls13_parse_supported_groups_ext(mbedtls_ssl_context *ssl,
840                                                 const unsigned char *buf,
841                                                 const unsigned char *end)
842 {
843     const unsigned char *p = buf;
844     size_t named_group_list_len;
845     const unsigned char *named_group_list_end;
846 
847     MBEDTLS_SSL_DEBUG_BUF(3, "supported_groups extension", p, end - buf);
848     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
849     named_group_list_len = MBEDTLS_GET_UINT16_BE(p, 0);
850     p += 2;
851     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, named_group_list_len);
852     named_group_list_end = p + named_group_list_len;
853     ssl->handshake->hrr_selected_group = 0;
854 
855     while (p < named_group_list_end) {
856         uint16_t named_group;
857         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, named_group_list_end, 2);
858         named_group = MBEDTLS_GET_UINT16_BE(p, 0);
859         p += 2;
860 
861         MBEDTLS_SSL_DEBUG_MSG(2,
862                               ("got named group: %s(%04x)",
863                                mbedtls_ssl_named_group_to_str(named_group),
864                                named_group));
865 
866         if (!mbedtls_ssl_named_group_is_offered(ssl, named_group) ||
867             !mbedtls_ssl_named_group_is_supported(named_group) ||
868             ssl->handshake->hrr_selected_group != 0) {
869             continue;
870         }
871 
872         MBEDTLS_SSL_DEBUG_MSG(2,
873                               ("add named group %s(%04x) into received list.",
874                                mbedtls_ssl_named_group_to_str(named_group),
875                                named_group));
876 
877         ssl->handshake->hrr_selected_group = named_group;
878     }
879 
880     return 0;
881 
882 }
883 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
884 
885 #define SSL_TLS1_3_PARSE_KEY_SHARES_EXT_NO_MATCH 1
886 
887 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
888 /*
889  *  ssl_tls13_parse_key_shares_ext() verifies whether the information in the
890  *  extension is correct and stores the first acceptable key share and its
891  *  associated group.
892  *
893  *  Possible return values are:
894  *  - 0: Successful processing of the client provided key share extension.
895  *  - SSL_TLS1_3_PARSE_KEY_SHARES_EXT_NO_MATCH: The key shares provided by
896  *    the client does not match a group supported by the server. A
897  *    HelloRetryRequest will be needed.
898  *  - A negative value for fatal errors.
899  */
900 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_key_shares_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)901 static int ssl_tls13_parse_key_shares_ext(mbedtls_ssl_context *ssl,
902                                           const unsigned char *buf,
903                                           const unsigned char *end)
904 {
905     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
906     unsigned char const *p = buf;
907     unsigned char const *client_shares_end;
908     size_t client_shares_len;
909 
910     /* From RFC 8446:
911      *
912      * struct {
913      *     KeyShareEntry client_shares<0..2^16-1>;
914      * } KeyShareClientHello;
915      *
916      */
917 
918     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
919     client_shares_len = MBEDTLS_GET_UINT16_BE(p, 0);
920     p += 2;
921     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, client_shares_len);
922 
923     ssl->handshake->offered_group_id = 0;
924     client_shares_end = p + client_shares_len;
925 
926     /* We try to find a suitable key share entry and copy it to the
927      * handshake context. Later, we have to find out whether we can do
928      * something with the provided key share or whether we have to
929      * dismiss it and send a HelloRetryRequest message.
930      */
931 
932     while (p < client_shares_end) {
933         uint16_t group;
934         size_t key_exchange_len;
935         const unsigned char *key_exchange;
936 
937         /*
938          * struct {
939          *    NamedGroup group;
940          *    opaque key_exchange<1..2^16-1>;
941          * } KeyShareEntry;
942          */
943         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, client_shares_end, 4);
944         group = MBEDTLS_GET_UINT16_BE(p, 0);
945         key_exchange_len = MBEDTLS_GET_UINT16_BE(p, 2);
946         p += 4;
947         key_exchange = p;
948         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, client_shares_end, key_exchange_len);
949         p += key_exchange_len;
950 
951         /* Continue parsing even if we have already found a match,
952          * for input validation purposes.
953          */
954         if (!mbedtls_ssl_named_group_is_offered(ssl, group) ||
955             !mbedtls_ssl_named_group_is_supported(group) ||
956             ssl->handshake->offered_group_id != 0) {
957             continue;
958         }
959 
960         /*
961          * ECDHE and FFDHE groups are supported
962          */
963         if (mbedtls_ssl_tls13_named_group_is_ecdhe(group) ||
964             mbedtls_ssl_tls13_named_group_is_ffdh(group)) {
965             MBEDTLS_SSL_DEBUG_MSG(2, ("ECDH/FFDH group: %s (%04x)",
966                                       mbedtls_ssl_named_group_to_str(group),
967                                       group));
968             ret = mbedtls_ssl_tls13_read_public_xxdhe_share(
969                 ssl, key_exchange - 2, key_exchange_len + 2);
970             if (ret != 0) {
971                 return ret;
972             }
973 
974         } else {
975             MBEDTLS_SSL_DEBUG_MSG(4, ("Unrecognized NamedGroup %u",
976                                       (unsigned) group));
977             continue;
978         }
979 
980         ssl->handshake->offered_group_id = group;
981     }
982 
983 
984     if (ssl->handshake->offered_group_id == 0) {
985         MBEDTLS_SSL_DEBUG_MSG(1, ("no matching key share"));
986         return SSL_TLS1_3_PARSE_KEY_SHARES_EXT_NO_MATCH;
987     }
988     return 0;
989 }
990 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
991 
992 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_client_hello_has_exts(mbedtls_ssl_context * ssl,int exts_mask)993 static int ssl_tls13_client_hello_has_exts(mbedtls_ssl_context *ssl,
994                                            int exts_mask)
995 {
996     int masked = ssl->handshake->received_extensions & exts_mask;
997     return masked == exts_mask;
998 }
999 
1000 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
1001 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange(mbedtls_ssl_context * ssl)1002 static int ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange(
1003     mbedtls_ssl_context *ssl)
1004 {
1005     return ssl_tls13_client_hello_has_exts(
1006         ssl,
1007         MBEDTLS_SSL_EXT_MASK(SUPPORTED_GROUPS) |
1008         MBEDTLS_SSL_EXT_MASK(KEY_SHARE)        |
1009         MBEDTLS_SSL_EXT_MASK(SIG_ALG));
1010 }
1011 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
1012 
1013 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED)
1014 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_client_hello_has_exts_for_psk_key_exchange(mbedtls_ssl_context * ssl)1015 static int ssl_tls13_client_hello_has_exts_for_psk_key_exchange(
1016     mbedtls_ssl_context *ssl)
1017 {
1018     return ssl_tls13_client_hello_has_exts(
1019         ssl,
1020         MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)          |
1021         MBEDTLS_SSL_EXT_MASK(PSK_KEY_EXCHANGE_MODES));
1022 }
1023 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED */
1024 
1025 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
1026 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange(mbedtls_ssl_context * ssl)1027 static int ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange(
1028     mbedtls_ssl_context *ssl)
1029 {
1030     return ssl_tls13_client_hello_has_exts(
1031         ssl,
1032         MBEDTLS_SSL_EXT_MASK(SUPPORTED_GROUPS)        |
1033         MBEDTLS_SSL_EXT_MASK(KEY_SHARE)               |
1034         MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)          |
1035         MBEDTLS_SSL_EXT_MASK(PSK_KEY_EXCHANGE_MODES));
1036 }
1037 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED */
1038 
1039 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1040 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_key_exchange_is_psk_available(mbedtls_ssl_context * ssl)1041 static int ssl_tls13_key_exchange_is_psk_available(mbedtls_ssl_context *ssl)
1042 {
1043 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED)
1044     return mbedtls_ssl_conf_tls13_is_psk_enabled(ssl) &&
1045            mbedtls_ssl_tls13_is_psk_supported(ssl) &&
1046            ssl_tls13_client_hello_has_exts_for_psk_key_exchange(ssl);
1047 #else
1048     ((void) ssl);
1049     return 0;
1050 #endif
1051 }
1052 
1053 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_key_exchange_is_psk_ephemeral_available(mbedtls_ssl_context * ssl)1054 static int ssl_tls13_key_exchange_is_psk_ephemeral_available(mbedtls_ssl_context *ssl)
1055 {
1056 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
1057     return mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(ssl) &&
1058            mbedtls_ssl_tls13_is_psk_ephemeral_supported(ssl) &&
1059            ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange(ssl);
1060 #else
1061     ((void) ssl);
1062     return 0;
1063 #endif
1064 }
1065 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
1066 
1067 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_key_exchange_is_ephemeral_available(mbedtls_ssl_context * ssl)1068 static int ssl_tls13_key_exchange_is_ephemeral_available(mbedtls_ssl_context *ssl)
1069 {
1070 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
1071     return mbedtls_ssl_conf_tls13_is_ephemeral_enabled(ssl) &&
1072            ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange(ssl);
1073 #else
1074     ((void) ssl);
1075     return 0;
1076 #endif
1077 }
1078 
1079 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
1080     defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
1081 
1082 #if defined(MBEDTLS_USE_PSA_CRYPTO)
ssl_tls13_iana_sig_alg_to_psa_alg(uint16_t sig_alg)1083 static psa_algorithm_t ssl_tls13_iana_sig_alg_to_psa_alg(uint16_t sig_alg)
1084 {
1085     switch (sig_alg) {
1086         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256:
1087             return PSA_ALG_ECDSA(PSA_ALG_SHA_256);
1088         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384:
1089             return PSA_ALG_ECDSA(PSA_ALG_SHA_384);
1090         case MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512:
1091             return PSA_ALG_ECDSA(PSA_ALG_SHA_512);
1092         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256:
1093             return PSA_ALG_RSA_PSS(PSA_ALG_SHA_256);
1094         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384:
1095             return PSA_ALG_RSA_PSS(PSA_ALG_SHA_384);
1096         case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512:
1097             return PSA_ALG_RSA_PSS(PSA_ALG_SHA_512);
1098         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256:
1099             return PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_256);
1100         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA384:
1101             return PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_384);
1102         case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA512:
1103             return PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_512);
1104         default:
1105             return PSA_ALG_NONE;
1106     }
1107 }
1108 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1109 
1110 /*
1111  * Pick best ( private key, certificate chain ) pair based on the signature
1112  * algorithms supported by the client.
1113  */
1114 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_pick_key_cert(mbedtls_ssl_context * ssl)1115 static int ssl_tls13_pick_key_cert(mbedtls_ssl_context *ssl)
1116 {
1117     mbedtls_ssl_key_cert *key_cert, *key_cert_list;
1118     const uint16_t *sig_alg = ssl->handshake->received_sig_algs;
1119 
1120 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1121     if (ssl->handshake->sni_key_cert != NULL) {
1122         key_cert_list = ssl->handshake->sni_key_cert;
1123     } else
1124 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1125     key_cert_list = ssl->conf->key_cert;
1126 
1127     if (key_cert_list == NULL) {
1128         MBEDTLS_SSL_DEBUG_MSG(3, ("server has no certificate"));
1129         return -1;
1130     }
1131 
1132     for (; *sig_alg != MBEDTLS_TLS1_3_SIG_NONE; sig_alg++) {
1133         if (!mbedtls_ssl_sig_alg_is_offered(ssl, *sig_alg)) {
1134             continue;
1135         }
1136 
1137         if (!mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(*sig_alg)) {
1138             continue;
1139         }
1140 
1141         for (key_cert = key_cert_list; key_cert != NULL;
1142              key_cert = key_cert->next) {
1143 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1144             psa_algorithm_t psa_alg = PSA_ALG_NONE;
1145 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1146 
1147             MBEDTLS_SSL_DEBUG_CRT(3, "certificate (chain) candidate",
1148                                   key_cert->cert);
1149 
1150             /*
1151              * This avoids sending the client a cert it'll reject based on
1152              * keyUsage or other extensions.
1153              */
1154             if (mbedtls_x509_crt_check_key_usage(
1155                     key_cert->cert, MBEDTLS_X509_KU_DIGITAL_SIGNATURE) != 0 ||
1156                 mbedtls_x509_crt_check_extended_key_usage(
1157                     key_cert->cert, MBEDTLS_OID_SERVER_AUTH,
1158                     MBEDTLS_OID_SIZE(MBEDTLS_OID_SERVER_AUTH)) != 0) {
1159                 MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: "
1160                                           "(extended) key usage extension"));
1161                 continue;
1162             }
1163 
1164             MBEDTLS_SSL_DEBUG_MSG(3,
1165                                   ("ssl_tls13_pick_key_cert:"
1166                                    "check signature algorithm %s [%04x]",
1167                                    mbedtls_ssl_sig_alg_to_str(*sig_alg),
1168                                    *sig_alg));
1169 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1170             psa_alg = ssl_tls13_iana_sig_alg_to_psa_alg(*sig_alg);
1171 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1172 
1173             if (mbedtls_ssl_tls13_check_sig_alg_cert_key_match(
1174                     *sig_alg, &key_cert->cert->pk)
1175 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1176                 && psa_alg != PSA_ALG_NONE &&
1177                 mbedtls_pk_can_do_ext(&key_cert->cert->pk, psa_alg,
1178                                       PSA_KEY_USAGE_SIGN_HASH) == 1
1179 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1180                 ) {
1181                 ssl->handshake->key_cert = key_cert;
1182                 MBEDTLS_SSL_DEBUG_MSG(3,
1183                                       ("ssl_tls13_pick_key_cert:"
1184                                        "selected signature algorithm"
1185                                        " %s [%04x]",
1186                                        mbedtls_ssl_sig_alg_to_str(*sig_alg),
1187                                        *sig_alg));
1188                 MBEDTLS_SSL_DEBUG_CRT(
1189                     3, "selected certificate (chain)",
1190                     ssl->handshake->key_cert->cert);
1191                 return 0;
1192             }
1193         }
1194     }
1195 
1196     MBEDTLS_SSL_DEBUG_MSG(2, ("ssl_tls13_pick_key_cert:"
1197                               "no suitable certificate found"));
1198     return -1;
1199 }
1200 #endif /* MBEDTLS_X509_CRT_PARSE_C &&
1201           MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
1202 
1203 /*
1204  *
1205  * STATE HANDLING: ClientHello
1206  *
1207  * There are three possible classes of outcomes when parsing the ClientHello:
1208  *
1209  * 1) The ClientHello was well-formed and matched the server's configuration.
1210  *
1211  *    In this case, the server progresses to sending its ServerHello.
1212  *
1213  * 2) The ClientHello was well-formed but didn't match the server's
1214  *    configuration.
1215  *
1216  *    For example, the client might not have offered a key share which
1217  *    the server supports, or the server might require a cookie.
1218  *
1219  *    In this case, the server sends a HelloRetryRequest.
1220  *
1221  * 3) The ClientHello was ill-formed
1222  *
1223  *    In this case, we abort the handshake.
1224  *
1225  */
1226 
1227 /*
1228  * Structure of this message:
1229  *
1230  * uint16 ProtocolVersion;
1231  * opaque Random[32];
1232  * uint8 CipherSuite[2];    // Cryptographic suite selector
1233  *
1234  * struct {
1235  *      ProtocolVersion legacy_version = 0x0303;    // TLS v1.2
1236  *      Random random;
1237  *      opaque legacy_session_id<0..32>;
1238  *      CipherSuite cipher_suites<2..2^16-2>;
1239  *      opaque legacy_compression_methods<1..2^8-1>;
1240  *      Extension extensions<8..2^16-1>;
1241  * } ClientHello;
1242  */
1243 
1244 #define SSL_CLIENT_HELLO_OK           0
1245 #define SSL_CLIENT_HELLO_HRR_REQUIRED 1
1246 #define SSL_CLIENT_HELLO_TLS1_2       2
1247 
1248 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_client_hello(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)1249 static int ssl_tls13_parse_client_hello(mbedtls_ssl_context *ssl,
1250                                         const unsigned char *buf,
1251                                         const unsigned char *end)
1252 {
1253     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1254     const unsigned char *p = buf;
1255     const unsigned char *random;
1256     size_t legacy_session_id_len;
1257     const unsigned char *legacy_session_id;
1258     size_t cipher_suites_len;
1259     const unsigned char *cipher_suites;
1260     const unsigned char *cipher_suites_end;
1261     size_t extensions_len;
1262     const unsigned char *extensions_end;
1263     const unsigned char *supported_versions_data;
1264     const unsigned char *supported_versions_data_end;
1265     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1266     int hrr_required = 0;
1267     int no_usable_share_for_key_agreement = 0;
1268 
1269 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1270     int got_psk = 0;
1271     struct psk_attributes psk = PSK_ATTRIBUTES_INIT;
1272     const unsigned char *pre_shared_key_ext = NULL;
1273     const unsigned char *pre_shared_key_ext_end = NULL;
1274 #endif
1275 
1276     /*
1277      * ClientHello layout:
1278      *     0  .   1   protocol version
1279      *     2  .  33   random bytes
1280      *    34  .  34   session id length ( 1 byte )
1281      *    35  . 34+x  session id
1282      *    ..  .  ..   ciphersuite list length ( 2 bytes )
1283      *    ..  .  ..   ciphersuite list
1284      *    ..  .  ..   compression alg. list length ( 1 byte )
1285      *    ..  .  ..   compression alg. list
1286      *    ..  .  ..   extensions length ( 2 bytes, optional )
1287      *    ..  .  ..   extensions ( optional )
1288      */
1289 
1290     /*
1291      * Minimal length ( with everything empty and extensions omitted ) is
1292      * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can
1293      * read at least up to session id length without worrying.
1294      */
1295     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 38);
1296 
1297     /* ...
1298      * ProtocolVersion legacy_version = 0x0303; // TLS 1.2
1299      * ...
1300      * with ProtocolVersion defined as:
1301      * uint16 ProtocolVersion;
1302      */
1303     if (mbedtls_ssl_read_version(p, ssl->conf->transport) !=
1304         MBEDTLS_SSL_VERSION_TLS1_2) {
1305         MBEDTLS_SSL_DEBUG_MSG(1, ("Unsupported version of TLS."));
1306         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION,
1307                                      MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION);
1308         return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1309     }
1310     p += 2;
1311 
1312     /* ...
1313      * Random random;
1314      * ...
1315      * with Random defined as:
1316      * opaque Random[32];
1317      */
1318     random = p;
1319     p += MBEDTLS_CLIENT_HELLO_RANDOM_LEN;
1320 
1321     /* ...
1322      * opaque legacy_session_id<0..32>;
1323      * ...
1324      */
1325     legacy_session_id_len = *(p++);
1326     legacy_session_id = p;
1327 
1328     /*
1329      * Check we have enough data for the legacy session identifier
1330      * and the ciphersuite list length.
1331      */
1332     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, legacy_session_id_len + 2);
1333     p += legacy_session_id_len;
1334 
1335     /* ...
1336      * CipherSuite cipher_suites<2..2^16-2>;
1337      * ...
1338      * with CipherSuite defined as:
1339      * uint8 CipherSuite[2];
1340      */
1341     cipher_suites_len = MBEDTLS_GET_UINT16_BE(p, 0);
1342     p += 2;
1343     cipher_suites = p;
1344 
1345     /*
1346      * The length of the ciphersuite list has to be even.
1347      */
1348     if (cipher_suites_len & 1) {
1349         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
1350                                      MBEDTLS_ERR_SSL_DECODE_ERROR);
1351         return MBEDTLS_ERR_SSL_DECODE_ERROR;
1352     }
1353 
1354     /* Check we have enough data for the ciphersuite list, the legacy
1355      * compression methods and the length of the extensions.
1356      *
1357      * cipher_suites                cipher_suites_len bytes
1358      * legacy_compression_methods length            1 byte
1359      */
1360     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, cipher_suites_len + 1);
1361     p += cipher_suites_len;
1362     cipher_suites_end = p;
1363 
1364     /* Check if we have enough data for legacy_compression_methods
1365      * and the length of the extensions (2 bytes).
1366      */
1367     MBEDTLS_SSL_CHK_BUF_READ_PTR(p + 1, end, p[0] + 2);
1368 
1369     /*
1370      * Search for the supported versions extension and parse it to determine
1371      * if the client supports TLS 1.3.
1372      */
1373     ret = mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts(
1374         ssl, p + 1 + p[0], end,
1375         &supported_versions_data, &supported_versions_data_end);
1376     if (ret < 0) {
1377         MBEDTLS_SSL_DEBUG_RET(1,
1378                               ("mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts"), ret);
1379         return ret;
1380     }
1381 
1382     if (ret == 0) {
1383         MBEDTLS_SSL_DEBUG_MSG(2, ("no supported_versions extension"));
1384         return SSL_CLIENT_HELLO_TLS1_2;
1385     }
1386 
1387     if (ret == 1) {
1388         ret = ssl_tls13_parse_supported_versions_ext(ssl,
1389                                                      supported_versions_data,
1390                                                      supported_versions_data_end);
1391         if (ret < 0) {
1392             MBEDTLS_SSL_DEBUG_RET(1,
1393                                   ("ssl_tls13_parse_supported_versions_ext"), ret);
1394             return ret;
1395         }
1396 
1397         /*
1398          * The supported versions extension was parsed successfully as the
1399          * value returned by ssl_tls13_parse_supported_versions_ext() is
1400          * positive. The return value is then equal to
1401          * MBEDTLS_SSL_VERSION_TLS1_2 or MBEDTLS_SSL_VERSION_TLS1_3, defining
1402          * the TLS version to negotiate.
1403          */
1404         if (MBEDTLS_SSL_VERSION_TLS1_2 == ret) {
1405             MBEDTLS_SSL_DEBUG_MSG(2, ("supported_versions without 1.3"));
1406             return SSL_CLIENT_HELLO_TLS1_2;
1407         }
1408     }
1409 
1410     /*
1411      * We negotiate TLS 1.3.
1412      */
1413     ssl->tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
1414     ssl->session_negotiate->tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
1415     ssl->session_negotiate->endpoint = ssl->conf->endpoint;
1416 
1417     /* Before doing any crypto, make sure we can. */
1418     ret = mbedtls_ssl_tls13_crypto_init(ssl);
1419     if (ret != 0) {
1420         return ret;
1421     }
1422 
1423     /*
1424      * We are negotiating the version 1.3 of the protocol. Do what we have
1425      * postponed: copy of the client random bytes, copy of the legacy session
1426      * identifier and selection of the TLS 1.3 cipher suite.
1427      */
1428     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, random bytes",
1429                           random, MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
1430     memcpy(&handshake->randbytes[0], random, MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
1431 
1432     if (legacy_session_id_len > sizeof(ssl->session_negotiate->id)) {
1433         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1434         return MBEDTLS_ERR_SSL_DECODE_ERROR;
1435     }
1436     ssl->session_negotiate->id_len = legacy_session_id_len;
1437     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, session id",
1438                           legacy_session_id, legacy_session_id_len);
1439     memcpy(&ssl->session_negotiate->id[0],
1440            legacy_session_id, legacy_session_id_len);
1441 
1442     /*
1443      * Search for a matching ciphersuite
1444      */
1445     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, list of cipher suites",
1446                           cipher_suites, cipher_suites_len);
1447 
1448     ssl_tls13_select_ciphersuite(ssl, cipher_suites, cipher_suites_end,
1449                                  0, PSA_ALG_NONE, &handshake->ciphersuite_info);
1450 
1451     if (handshake->ciphersuite_info == NULL) {
1452         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
1453                                      MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
1454         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1455     }
1456     ssl->session_negotiate->ciphersuite = handshake->ciphersuite_info->id;
1457 
1458     MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %04x - %s",
1459                               ((unsigned) handshake->ciphersuite_info->id),
1460                               handshake->ciphersuite_info->name));
1461 
1462     /* ...
1463      * opaque legacy_compression_methods<1..2^8-1>;
1464      * ...
1465      */
1466     if (p[0] != 1 || p[1] != MBEDTLS_SSL_COMPRESS_NULL) {
1467         MBEDTLS_SSL_DEBUG_MSG(1, ("bad legacy compression method"));
1468         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1469                                      MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1470         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1471     }
1472     p += 2;
1473 
1474     /* ...
1475      * Extension extensions<8..2^16-1>;
1476      * ...
1477      * with Extension defined as:
1478      * struct {
1479      *    ExtensionType extension_type;
1480      *    opaque extension_data<0..2^16-1>;
1481      * } Extension;
1482      */
1483     extensions_len = MBEDTLS_GET_UINT16_BE(p, 0);
1484     p += 2;
1485     MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, extensions_len);
1486     extensions_end = p + extensions_len;
1487 
1488     MBEDTLS_SSL_DEBUG_BUF(3, "client hello extensions", p, extensions_len);
1489     handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
1490 
1491     while (p < extensions_end) {
1492         unsigned int extension_type;
1493         size_t extension_data_len;
1494         const unsigned char *extension_data_end;
1495         uint32_t allowed_exts = MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CH;
1496 
1497         if (ssl->handshake->hello_retry_request_flag) {
1498             /* Do not accept early data extension in 2nd ClientHello */
1499             allowed_exts &= ~MBEDTLS_SSL_EXT_MASK(EARLY_DATA);
1500         }
1501 
1502         /* RFC 8446, section 4.2.11
1503          *
1504          * The "pre_shared_key" extension MUST be the last extension in the
1505          * ClientHello (this facilitates implementation as described below).
1506          * Servers MUST check that it is the last extension and otherwise fail
1507          * the handshake with an "illegal_parameter" alert.
1508          */
1509         if (handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)) {
1510             MBEDTLS_SSL_DEBUG_MSG(
1511                 3, ("pre_shared_key is not last extension."));
1512             MBEDTLS_SSL_PEND_FATAL_ALERT(
1513                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1514                 MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1515             return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1516         }
1517 
1518         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, 4);
1519         extension_type = MBEDTLS_GET_UINT16_BE(p, 0);
1520         extension_data_len = MBEDTLS_GET_UINT16_BE(p, 2);
1521         p += 4;
1522 
1523         MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, extension_data_len);
1524         extension_data_end = p + extension_data_len;
1525 
1526         ret = mbedtls_ssl_tls13_check_received_extension(
1527             ssl, MBEDTLS_SSL_HS_CLIENT_HELLO, extension_type,
1528             allowed_exts);
1529         if (ret != 0) {
1530             return ret;
1531         }
1532 
1533         switch (extension_type) {
1534 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1535             case MBEDTLS_TLS_EXT_SERVERNAME:
1536                 MBEDTLS_SSL_DEBUG_MSG(3, ("found ServerName extension"));
1537                 ret = mbedtls_ssl_parse_server_name_ext(ssl, p,
1538                                                         extension_data_end);
1539                 if (ret != 0) {
1540                     MBEDTLS_SSL_DEBUG_RET(
1541                         1, "mbedtls_ssl_parse_servername_ext", ret);
1542                     return ret;
1543                 }
1544                 break;
1545 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1546 
1547 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
1548             case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
1549                 MBEDTLS_SSL_DEBUG_MSG(3, ("found supported group extension"));
1550 
1551                 /* Supported Groups Extension
1552                  *
1553                  * When sent by the client, the "supported_groups" extension
1554                  * indicates the named groups which the client supports,
1555                  * ordered from most preferred to least preferred.
1556                  */
1557                 ret = ssl_tls13_parse_supported_groups_ext(
1558                     ssl, p, extension_data_end);
1559                 if (ret != 0) {
1560                     MBEDTLS_SSL_DEBUG_RET(
1561                         1, "ssl_tls13_parse_supported_groups_ext", ret);
1562                     return ret;
1563                 }
1564 
1565                 break;
1566 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH*/
1567 
1568 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
1569             case MBEDTLS_TLS_EXT_KEY_SHARE:
1570                 MBEDTLS_SSL_DEBUG_MSG(3, ("found key share extension"));
1571 
1572                 /*
1573                  * Key Share Extension
1574                  *
1575                  * When sent by the client, the "key_share" extension
1576                  * contains the endpoint's cryptographic parameters for
1577                  * ECDHE/DHE key establishment methods.
1578                  */
1579                 ret = ssl_tls13_parse_key_shares_ext(
1580                     ssl, p, extension_data_end);
1581                 if (ret == SSL_TLS1_3_PARSE_KEY_SHARES_EXT_NO_MATCH) {
1582                     MBEDTLS_SSL_DEBUG_MSG(2, ("No usable share for key agreement."));
1583                     no_usable_share_for_key_agreement = 1;
1584                 }
1585 
1586                 if (ret < 0) {
1587                     MBEDTLS_SSL_DEBUG_RET(
1588                         1, "ssl_tls13_parse_key_shares_ext", ret);
1589                     return ret;
1590                 }
1591 
1592                 break;
1593 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
1594 
1595             case MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS:
1596                 /* Already parsed */
1597                 break;
1598 
1599 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1600             case MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES:
1601                 MBEDTLS_SSL_DEBUG_MSG(
1602                     3, ("found psk key exchange modes extension"));
1603 
1604                 ret = ssl_tls13_parse_key_exchange_modes_ext(
1605                     ssl, p, extension_data_end);
1606                 if (ret != 0) {
1607                     MBEDTLS_SSL_DEBUG_RET(
1608                         1, "ssl_tls13_parse_key_exchange_modes_ext", ret);
1609                     return ret;
1610                 }
1611 
1612                 break;
1613 #endif
1614 
1615             case MBEDTLS_TLS_EXT_PRE_SHARED_KEY:
1616                 MBEDTLS_SSL_DEBUG_MSG(3, ("found pre_shared_key extension"));
1617                 if ((handshake->received_extensions &
1618                      MBEDTLS_SSL_EXT_MASK(PSK_KEY_EXCHANGE_MODES)) == 0) {
1619                     MBEDTLS_SSL_PEND_FATAL_ALERT(
1620                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1621                         MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1622                     return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1623                 }
1624 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1625                 /* Delay processing of the PSK identity once we have
1626                  * found out which algorithms to use. We keep a pointer
1627                  * to the buffer and the size for later processing.
1628                  */
1629                 pre_shared_key_ext = p;
1630                 pre_shared_key_ext_end = extension_data_end;
1631 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
1632                 break;
1633 
1634 #if defined(MBEDTLS_SSL_ALPN)
1635             case MBEDTLS_TLS_EXT_ALPN:
1636                 MBEDTLS_SSL_DEBUG_MSG(3, ("found alpn extension"));
1637 
1638                 ret = mbedtls_ssl_parse_alpn_ext(ssl, p, extension_data_end);
1639                 if (ret != 0) {
1640                     MBEDTLS_SSL_DEBUG_RET(
1641                         1, ("mbedtls_ssl_parse_alpn_ext"), ret);
1642                     return ret;
1643                 }
1644                 break;
1645 #endif /* MBEDTLS_SSL_ALPN */
1646 
1647 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
1648             case MBEDTLS_TLS_EXT_SIG_ALG:
1649                 MBEDTLS_SSL_DEBUG_MSG(3, ("found signature_algorithms extension"));
1650 
1651                 ret = mbedtls_ssl_parse_sig_alg_ext(
1652                     ssl, p, extension_data_end);
1653                 if (ret != 0) {
1654                     MBEDTLS_SSL_DEBUG_RET(
1655                         1, "mbedtls_ssl_parse_sig_alg_ext", ret);
1656                     return ret;
1657                 }
1658                 break;
1659 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
1660 
1661 #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
1662             case MBEDTLS_TLS_EXT_RECORD_SIZE_LIMIT:
1663                 MBEDTLS_SSL_DEBUG_MSG(3, ("found record_size_limit extension"));
1664 
1665                 ret = mbedtls_ssl_tls13_parse_record_size_limit_ext(
1666                     ssl, p, extension_data_end);
1667                 if (ret != 0) {
1668                     MBEDTLS_SSL_DEBUG_RET(
1669                         1, ("mbedtls_ssl_tls13_parse_record_size_limit_ext"), ret);
1670                     return ret;
1671                 }
1672                 break;
1673 #endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
1674 
1675             default:
1676                 MBEDTLS_SSL_PRINT_EXT(
1677                     3, MBEDTLS_SSL_HS_CLIENT_HELLO,
1678                     extension_type, "( ignored )");
1679                 break;
1680         }
1681 
1682         p += extension_data_len;
1683     }
1684 
1685     MBEDTLS_SSL_PRINT_EXTS(3, MBEDTLS_SSL_HS_CLIENT_HELLO,
1686                            handshake->received_extensions);
1687 
1688     ret = mbedtls_ssl_add_hs_hdr_to_checksum(ssl,
1689                                              MBEDTLS_SSL_HS_CLIENT_HELLO,
1690                                              p - buf);
1691     if (0 != ret) {
1692         MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_add_hs_hdr_to_checksum"), ret);
1693         return ret;
1694     }
1695 
1696 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1697     /* Update checksum with either
1698      * - The entire content of the CH message, if no PSK extension is present
1699      * - The content up to but excluding the PSK extension, if present.
1700      * Always parse the pre-shared-key extension when present in the
1701      * ClientHello even if some pre-requisites for PSK key exchange modes are
1702      * not met. That way we always validate the syntax of the extension.
1703      */
1704     if (handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)) {
1705         ret = handshake->update_checksum(ssl, buf,
1706                                          pre_shared_key_ext - buf);
1707         if (0 != ret) {
1708             MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
1709             return ret;
1710         }
1711         ret = ssl_tls13_parse_pre_shared_key_ext(ssl,
1712                                                  pre_shared_key_ext,
1713                                                  pre_shared_key_ext_end,
1714                                                  cipher_suites,
1715                                                  cipher_suites_end,
1716                                                  &psk);
1717         if (ret == 0) {
1718             got_psk = 1;
1719         } else if (ret != MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) {
1720             MBEDTLS_SSL_DEBUG_RET(
1721                 1, "ssl_tls13_parse_pre_shared_key_ext", ret);
1722             return ret;
1723         }
1724     } else
1725 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
1726     {
1727         ret = handshake->update_checksum(ssl, buf, p - buf);
1728         if (0 != ret) {
1729             MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
1730             return ret;
1731         }
1732     }
1733 
1734     /*
1735      * Determine the key exchange algorithm to use.
1736      * There are three types of key exchanges supported in TLS 1.3:
1737      * - (EC)DH with ECDSA,
1738      * - (EC)DH with PSK,
1739      * - plain PSK.
1740      *
1741      * The PSK-based key exchanges may additionally be used with 0-RTT.
1742      *
1743      * Our built-in order of preference is
1744      *  1 ) (EC)DHE-PSK Mode ( psk_ephemeral )
1745      *  2 ) Certificate Mode ( ephemeral )
1746      *  3 ) Plain PSK Mode ( psk )
1747      */
1748 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1749     if (got_psk && (psk.key_exchange_mode ==
1750                     MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL)) {
1751         handshake->key_exchange_mode =
1752             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
1753         MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: psk_ephemeral"));
1754 
1755     } else
1756 #endif
1757     if (ssl_tls13_key_exchange_is_ephemeral_available(ssl)) {
1758         handshake->key_exchange_mode =
1759             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
1760         MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: ephemeral"));
1761 
1762     }
1763 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1764     else if (got_psk && (psk.key_exchange_mode ==
1765                          MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK)) {
1766         handshake->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
1767         MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: psk"));
1768     }
1769 #endif
1770     else {
1771         MBEDTLS_SSL_DEBUG_MSG(
1772             1,
1773             ("ClientHello message misses mandatory extensions."));
1774         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_MISSING_EXTENSION,
1775                                      MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1776         return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1777     }
1778 
1779 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1780     if (handshake->key_exchange_mode &
1781         MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL) {
1782         handshake->ciphersuite_info = psk.ciphersuite_info;
1783         ssl->session_negotiate->ciphersuite = psk.ciphersuite_info->id;
1784 
1785         MBEDTLS_SSL_DEBUG_MSG(2, ("Select PSK ciphersuite: %04x - %s",
1786                                   ((unsigned) psk.ciphersuite_info->id),
1787                                   psk.ciphersuite_info->name));
1788 
1789         if (psk.type == MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION) {
1790             handshake->resume = 1;
1791         }
1792     }
1793 #endif
1794 
1795     if (handshake->key_exchange_mode !=
1796         MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK) {
1797         hrr_required = (no_usable_share_for_key_agreement != 0);
1798     }
1799 
1800     mbedtls_ssl_optimize_checksum(ssl, handshake->ciphersuite_info);
1801 
1802     return hrr_required ? SSL_CLIENT_HELLO_HRR_REQUIRED : SSL_CLIENT_HELLO_OK;
1803 }
1804 
1805 #if defined(MBEDTLS_SSL_EARLY_DATA)
ssl_tls13_check_early_data_requirements(mbedtls_ssl_context * ssl)1806 static int ssl_tls13_check_early_data_requirements(mbedtls_ssl_context *ssl)
1807 {
1808     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1809 
1810     if (ssl->conf->early_data_enabled == MBEDTLS_SSL_EARLY_DATA_DISABLED) {
1811         MBEDTLS_SSL_DEBUG_MSG(
1812             1,
1813             ("EarlyData: rejected, feature disabled in server configuration."));
1814         return -1;
1815     }
1816 
1817     if (!handshake->resume) {
1818         /* We currently support early data only in the case of PSKs established
1819            via a NewSessionTicket message thus in the case of a session
1820            resumption. */
1821         MBEDTLS_SSL_DEBUG_MSG(
1822             1, ("EarlyData: rejected, not a session resumption."));
1823         return -1;
1824     }
1825 
1826     /* RFC 8446 4.2.10
1827      *
1828      * In order to accept early data, the server MUST have accepted a PSK cipher
1829      * suite and selected the first key offered in the client's "pre_shared_key"
1830      * extension. In addition, it MUST verify that the following values are the
1831      * same as those associated with the selected PSK:
1832      * - The TLS version number
1833      * - The selected cipher suite
1834      * - The selected ALPN [RFC7301] protocol, if any
1835      *
1836      * NOTE:
1837      *  - The TLS version number is checked in
1838      *    ssl_tls13_offered_psks_check_identity_match_ticket().
1839      */
1840 
1841     if (handshake->selected_identity != 0) {
1842         MBEDTLS_SSL_DEBUG_MSG(
1843             1, ("EarlyData: rejected, the selected key in "
1844                 "`pre_shared_key` is not the first one."));
1845         return -1;
1846     }
1847 
1848     if (handshake->ciphersuite_info->id !=
1849         ssl->session_negotiate->ciphersuite) {
1850         MBEDTLS_SSL_DEBUG_MSG(
1851             1, ("EarlyData: rejected, the selected ciphersuite is not the one "
1852                 "of the selected pre-shared key."));
1853         return -1;
1854 
1855     }
1856 
1857     if (!mbedtls_ssl_tls13_session_ticket_allow_early_data(ssl->session_negotiate)) {
1858         MBEDTLS_SSL_DEBUG_MSG(
1859             1,
1860             ("EarlyData: rejected, early_data not allowed in ticket "
1861              "permission bits."));
1862         return -1;
1863     }
1864 
1865 #if defined(MBEDTLS_SSL_ALPN)
1866     const char *alpn = mbedtls_ssl_get_alpn_protocol(ssl);
1867     size_t alpn_len;
1868 
1869     if (alpn == NULL && ssl->session_negotiate->ticket_alpn == NULL) {
1870         return 0;
1871     }
1872 
1873     if (alpn != NULL) {
1874         alpn_len = strlen(alpn);
1875     }
1876 
1877     if (alpn == NULL ||
1878         ssl->session_negotiate->ticket_alpn == NULL ||
1879         alpn_len != strlen(ssl->session_negotiate->ticket_alpn) ||
1880         (memcmp(alpn, ssl->session_negotiate->ticket_alpn, alpn_len) != 0)) {
1881         MBEDTLS_SSL_DEBUG_MSG(1, ("EarlyData: rejected, the selected ALPN is different "
1882                                   "from the one associated with the pre-shared key."));
1883         return -1;
1884     }
1885 #endif
1886 
1887     return 0;
1888 }
1889 #endif /* MBEDTLS_SSL_EARLY_DATA */
1890 
1891 /* Update the handshake state machine */
1892 
1893 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_postprocess_client_hello(mbedtls_ssl_context * ssl,int hrr_required)1894 static int ssl_tls13_postprocess_client_hello(mbedtls_ssl_context *ssl,
1895                                               int hrr_required)
1896 {
1897     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1898 
1899     /*
1900      * Server certificate selection
1901      */
1902     if (ssl->conf->f_cert_cb && (ret = ssl->conf->f_cert_cb(ssl)) != 0) {
1903         MBEDTLS_SSL_DEBUG_RET(1, "f_cert_cb", ret);
1904         return ret;
1905     }
1906 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1907     ssl->handshake->sni_name = NULL;
1908     ssl->handshake->sni_name_len = 0;
1909 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1910 
1911     ret = mbedtls_ssl_tls13_key_schedule_stage_early(ssl);
1912     if (ret != 0) {
1913         MBEDTLS_SSL_DEBUG_RET(1,
1914                               "mbedtls_ssl_tls1_3_key_schedule_stage_early", ret);
1915         return ret;
1916     }
1917 
1918 #if defined(MBEDTLS_SSL_EARLY_DATA)
1919     if (ssl->handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(EARLY_DATA)) {
1920         ssl->handshake->early_data_accepted =
1921             (!hrr_required) && (ssl_tls13_check_early_data_requirements(ssl) == 0);
1922 
1923         if (ssl->handshake->early_data_accepted) {
1924             ret = mbedtls_ssl_tls13_compute_early_transform(ssl);
1925             if (ret != 0) {
1926                 MBEDTLS_SSL_DEBUG_RET(
1927                     1, "mbedtls_ssl_tls13_compute_early_transform", ret);
1928                 return ret;
1929             }
1930         } else {
1931             ssl->discard_early_data_record =
1932                 hrr_required ?
1933                 MBEDTLS_SSL_EARLY_DATA_DISCARD :
1934                 MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD;
1935         }
1936     }
1937 #else
1938     ((void) hrr_required);
1939 #endif /* MBEDTLS_SSL_EARLY_DATA */
1940 
1941     return 0;
1942 }
1943 
1944 /*
1945  * Main entry point from the state machine; orchestrates the otherfunctions.
1946  */
1947 
1948 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_client_hello(mbedtls_ssl_context * ssl)1949 static int ssl_tls13_process_client_hello(mbedtls_ssl_context *ssl)
1950 {
1951 
1952     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1953     unsigned char *buf = NULL;
1954     size_t buflen = 0;
1955     int parse_client_hello_ret;
1956 
1957     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client hello"));
1958 
1959     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
1960                              ssl, MBEDTLS_SSL_HS_CLIENT_HELLO,
1961                              &buf, &buflen));
1962 
1963     MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_parse_client_hello(ssl, buf,
1964                                                           buf + buflen));
1965     parse_client_hello_ret = ret; /* Store positive return value of
1966                                    * parse_client_hello,
1967                                    * as negative error codes are handled
1968                                    * by MBEDTLS_SSL_PROC_CHK_NEG. */
1969 
1970     /*
1971      * Version 1.2 of the protocol has to be used for the handshake.
1972      * If TLS 1.2 is not supported, abort the handshake. Otherwise, set the
1973      * ssl->keep_current_message flag for the ClientHello to be kept and parsed
1974      * as a TLS 1.2 ClientHello. We also change ssl->tls_version to
1975      * MBEDTLS_SSL_VERSION_TLS1_2 thus from now on mbedtls_ssl_handshake_step()
1976      * will dispatch to the TLS 1.2 state machine.
1977      */
1978     if (SSL_CLIENT_HELLO_TLS1_2 == parse_client_hello_ret) {
1979         /* Check if server supports TLS 1.2 */
1980         if (!mbedtls_ssl_conf_is_tls12_enabled(ssl->conf)) {
1981             MBEDTLS_SSL_DEBUG_MSG(
1982                 1, ("TLS 1.2 not supported."));
1983             MBEDTLS_SSL_PEND_FATAL_ALERT(
1984                 MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION,
1985                 MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION);
1986             return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1987         }
1988         ssl->keep_current_message = 1;
1989         ssl->tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
1990         MBEDTLS_SSL_DEBUG_MSG(1, ("non-1.3 ClientHello left for later processing"));
1991         return 0;
1992     }
1993 
1994     MBEDTLS_SSL_PROC_CHK(
1995         ssl_tls13_postprocess_client_hello(ssl, parse_client_hello_ret ==
1996                                            SSL_CLIENT_HELLO_HRR_REQUIRED));
1997 
1998     if (SSL_CLIENT_HELLO_OK == parse_client_hello_ret) {
1999         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_HELLO);
2000     } else {
2001         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HELLO_RETRY_REQUEST);
2002     }
2003 
2004 cleanup:
2005 
2006     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client hello"));
2007     return ret;
2008 }
2009 
2010 /*
2011  * Handler for MBEDTLS_SSL_SERVER_HELLO
2012  */
2013 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_prepare_server_hello(mbedtls_ssl_context * ssl)2014 static int ssl_tls13_prepare_server_hello(mbedtls_ssl_context *ssl)
2015 {
2016     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2017     unsigned char *server_randbytes =
2018         ssl->handshake->randbytes + MBEDTLS_CLIENT_HELLO_RANDOM_LEN;
2019 
2020     if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, server_randbytes,
2021                                 MBEDTLS_SERVER_HELLO_RANDOM_LEN)) != 0) {
2022         MBEDTLS_SSL_DEBUG_RET(1, "f_rng", ret);
2023         return ret;
2024     }
2025 
2026     MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes", server_randbytes,
2027                           MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2028 
2029 #if defined(MBEDTLS_HAVE_TIME)
2030     ssl->session_negotiate->start = mbedtls_time(NULL);
2031 #endif /* MBEDTLS_HAVE_TIME */
2032 
2033     return ret;
2034 }
2035 
2036 /*
2037  * ssl_tls13_write_server_hello_supported_versions_ext ():
2038  *
2039  * struct {
2040  *      ProtocolVersion selected_version;
2041  * } SupportedVersions;
2042  */
2043 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_server_hello_supported_versions_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)2044 static int ssl_tls13_write_server_hello_supported_versions_ext(
2045     mbedtls_ssl_context *ssl,
2046     unsigned char *buf,
2047     unsigned char *end,
2048     size_t *out_len)
2049 {
2050     *out_len = 0;
2051 
2052     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, write selected version"));
2053 
2054     /* Check if we have space to write the extension:
2055      * - extension_type         (2 bytes)
2056      * - extension_data_length  (2 bytes)
2057      * - selected_version       (2 bytes)
2058      */
2059     MBEDTLS_SSL_CHK_BUF_PTR(buf, end, 6);
2060 
2061     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS, buf, 0);
2062 
2063     MBEDTLS_PUT_UINT16_BE(2, buf, 2);
2064 
2065     mbedtls_ssl_write_version(buf + 4,
2066                               ssl->conf->transport,
2067                               ssl->tls_version);
2068 
2069     MBEDTLS_SSL_DEBUG_MSG(3, ("supported version: [%04x]",
2070                               ssl->tls_version));
2071 
2072     *out_len = 6;
2073 
2074     mbedtls_ssl_tls13_set_hs_sent_ext_mask(
2075         ssl, MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS);
2076 
2077     return 0;
2078 }
2079 
2080 
2081 
2082 /* Generate and export a single key share. For hybrid KEMs, this can
2083  * be called multiple times with the different components of the hybrid. */
2084 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_generate_and_write_key_share(mbedtls_ssl_context * ssl,uint16_t named_group,unsigned char * buf,unsigned char * end,size_t * out_len)2085 static int ssl_tls13_generate_and_write_key_share(mbedtls_ssl_context *ssl,
2086                                                   uint16_t named_group,
2087                                                   unsigned char *buf,
2088                                                   unsigned char *end,
2089                                                   size_t *out_len)
2090 {
2091     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2092 
2093     *out_len = 0;
2094 
2095 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
2096     if (mbedtls_ssl_tls13_named_group_is_ecdhe(named_group) ||
2097         mbedtls_ssl_tls13_named_group_is_ffdh(named_group)) {
2098         ret = mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange(
2099             ssl, named_group, buf, end, out_len);
2100         if (ret != 0) {
2101             MBEDTLS_SSL_DEBUG_RET(
2102                 1, "mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange",
2103                 ret);
2104             return ret;
2105         }
2106     } else
2107 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
2108     if (0 /* Other kinds of KEMs */) {
2109     } else {
2110         ((void) ssl);
2111         ((void) named_group);
2112         ((void) buf);
2113         ((void) end);
2114         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2115     }
2116 
2117     return ret;
2118 }
2119 
2120 /*
2121  * ssl_tls13_write_key_share_ext
2122  *
2123  * Structure of key_share extension in ServerHello:
2124  *
2125  * struct {
2126  *     NamedGroup group;
2127  *     opaque key_exchange<1..2^16-1>;
2128  * } KeyShareEntry;
2129  * struct {
2130  *     KeyShareEntry server_share;
2131  * } KeyShareServerHello;
2132  */
2133 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_key_share_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)2134 static int ssl_tls13_write_key_share_ext(mbedtls_ssl_context *ssl,
2135                                          unsigned char *buf,
2136                                          unsigned char *end,
2137                                          size_t *out_len)
2138 {
2139     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2140     unsigned char *p = buf;
2141     uint16_t group = ssl->handshake->offered_group_id;
2142     unsigned char *server_share = buf + 4;
2143     size_t key_exchange_length;
2144 
2145     *out_len = 0;
2146 
2147     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding key share extension"));
2148 
2149     MBEDTLS_SSL_DEBUG_MSG(2, ("server hello, write selected_group: %s (%04x)",
2150                               mbedtls_ssl_named_group_to_str(group),
2151                               group));
2152 
2153     /* Check if we have space for header and length fields:
2154      * - extension_type         (2 bytes)
2155      * - extension_data_length  (2 bytes)
2156      * - group                  (2 bytes)
2157      * - key_exchange_length    (2 bytes)
2158      */
2159     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 8);
2160     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_KEY_SHARE, p, 0);
2161     MBEDTLS_PUT_UINT16_BE(group, server_share, 0);
2162     p += 8;
2163 
2164     /* When we introduce PQC-ECDHE hybrids, we'll want to call this
2165      * function multiple times. */
2166     ret = ssl_tls13_generate_and_write_key_share(
2167         ssl, group, server_share + 4, end, &key_exchange_length);
2168     if (ret != 0) {
2169         return ret;
2170     }
2171     p += key_exchange_length;
2172 
2173     MBEDTLS_PUT_UINT16_BE(key_exchange_length, server_share + 2, 0);
2174 
2175     MBEDTLS_PUT_UINT16_BE(p - server_share, buf, 2);
2176 
2177     *out_len = p - buf;
2178 
2179     mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_KEY_SHARE);
2180 
2181     return 0;
2182 }
2183 
2184 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_hrr_key_share_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)2185 static int ssl_tls13_write_hrr_key_share_ext(mbedtls_ssl_context *ssl,
2186                                              unsigned char *buf,
2187                                              unsigned char *end,
2188                                              size_t *out_len)
2189 {
2190     uint16_t selected_group = ssl->handshake->hrr_selected_group;
2191     /* key_share Extension
2192      *
2193      *  struct {
2194      *    select (Handshake.msg_type) {
2195      *      ...
2196      *      case hello_retry_request:
2197      *          NamedGroup selected_group;
2198      *      ...
2199      *    };
2200      * } KeyShare;
2201      */
2202 
2203     *out_len = 0;
2204 
2205     /*
2206      * For a pure PSK key exchange, there is no group to agree upon. The purpose
2207      * of the HRR is then to transmit a cookie to force the client to demonstrate
2208      * reachability at their apparent network address (primarily useful for DTLS).
2209      */
2210     if (!mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(ssl)) {
2211         return 0;
2212     }
2213 
2214     /* We should only send the key_share extension if the client's initial
2215      * key share was not acceptable. */
2216     if (ssl->handshake->offered_group_id != 0) {
2217         MBEDTLS_SSL_DEBUG_MSG(4, ("Skip key_share extension in HRR"));
2218         return 0;
2219     }
2220 
2221     if (selected_group == 0) {
2222         MBEDTLS_SSL_DEBUG_MSG(1, ("no matching named group found"));
2223         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2224     }
2225 
2226     /* Check if we have enough space:
2227      * - extension_type         (2 bytes)
2228      * - extension_data_length  (2 bytes)
2229      * - selected_group         (2 bytes)
2230      */
2231     MBEDTLS_SSL_CHK_BUF_PTR(buf, end, 6);
2232 
2233     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_KEY_SHARE, buf, 0);
2234     MBEDTLS_PUT_UINT16_BE(2, buf, 2);
2235     MBEDTLS_PUT_UINT16_BE(selected_group, buf, 4);
2236 
2237     MBEDTLS_SSL_DEBUG_MSG(3,
2238                           ("HRR selected_group: %s (%x)",
2239                            mbedtls_ssl_named_group_to_str(selected_group),
2240                            selected_group));
2241 
2242     *out_len = 6;
2243 
2244     mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_KEY_SHARE);
2245 
2246     return 0;
2247 }
2248 
2249 /*
2250  * Structure of ServerHello message:
2251  *
2252  *     struct {
2253  *        ProtocolVersion legacy_version = 0x0303;    // TLS v1.2
2254  *        Random random;
2255  *        opaque legacy_session_id_echo<0..32>;
2256  *        CipherSuite cipher_suite;
2257  *        uint8 legacy_compression_method = 0;
2258  *        Extension extensions<6..2^16-1>;
2259  *    } ServerHello;
2260  */
2261 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_server_hello_body(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len,int is_hrr)2262 static int ssl_tls13_write_server_hello_body(mbedtls_ssl_context *ssl,
2263                                              unsigned char *buf,
2264                                              unsigned char *end,
2265                                              size_t *out_len,
2266                                              int is_hrr)
2267 {
2268     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2269     unsigned char *p = buf;
2270     unsigned char *p_extensions_len;
2271     size_t output_len;
2272 
2273     *out_len = 0;
2274     ssl->handshake->sent_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
2275 
2276     /* ...
2277      * ProtocolVersion legacy_version = 0x0303; // TLS 1.2
2278      * ...
2279      * with ProtocolVersion defined as:
2280      * uint16 ProtocolVersion;
2281      */
2282     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
2283     MBEDTLS_PUT_UINT16_BE(0x0303, p, 0);
2284     p += 2;
2285 
2286     /* ...
2287      * Random random;
2288      * ...
2289      * with Random defined as:
2290      * opaque Random[MBEDTLS_SERVER_HELLO_RANDOM_LEN];
2291      */
2292     MBEDTLS_SSL_CHK_BUF_PTR(p, end, MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2293     if (is_hrr) {
2294         memcpy(p, mbedtls_ssl_tls13_hello_retry_request_magic,
2295                MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2296     } else {
2297         memcpy(p, &ssl->handshake->randbytes[MBEDTLS_CLIENT_HELLO_RANDOM_LEN],
2298                MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2299     }
2300     MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes",
2301                           p, MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2302     p += MBEDTLS_SERVER_HELLO_RANDOM_LEN;
2303 
2304     /* ...
2305      * opaque legacy_session_id_echo<0..32>;
2306      * ...
2307      */
2308     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 1 + ssl->session_negotiate->id_len);
2309     *p++ = (unsigned char) ssl->session_negotiate->id_len;
2310     if (ssl->session_negotiate->id_len > 0) {
2311         memcpy(p, &ssl->session_negotiate->id[0],
2312                ssl->session_negotiate->id_len);
2313         p += ssl->session_negotiate->id_len;
2314 
2315         MBEDTLS_SSL_DEBUG_BUF(3, "session id", ssl->session_negotiate->id,
2316                               ssl->session_negotiate->id_len);
2317     }
2318 
2319     /* ...
2320      * CipherSuite cipher_suite;
2321      * ...
2322      * with CipherSuite defined as:
2323      * uint8 CipherSuite[2];
2324      */
2325     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
2326     MBEDTLS_PUT_UINT16_BE(ssl->session_negotiate->ciphersuite, p, 0);
2327     p += 2;
2328     MBEDTLS_SSL_DEBUG_MSG(3,
2329                           ("server hello, chosen ciphersuite: %s ( id=%d )",
2330                            mbedtls_ssl_get_ciphersuite_name(
2331                                ssl->session_negotiate->ciphersuite),
2332                            ssl->session_negotiate->ciphersuite));
2333 
2334     /* ...
2335      * uint8 legacy_compression_method = 0;
2336      * ...
2337      */
2338     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 1);
2339     *p++ = MBEDTLS_SSL_COMPRESS_NULL;
2340 
2341     /* ...
2342      * Extension extensions<6..2^16-1>;
2343      * ...
2344      * struct {
2345      *      ExtensionType extension_type; (2 bytes)
2346      *      opaque extension_data<0..2^16-1>;
2347      * } Extension;
2348      */
2349     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
2350     p_extensions_len = p;
2351     p += 2;
2352 
2353     if ((ret = ssl_tls13_write_server_hello_supported_versions_ext(
2354              ssl, p, end, &output_len)) != 0) {
2355         MBEDTLS_SSL_DEBUG_RET(
2356             1, "ssl_tls13_write_server_hello_supported_versions_ext", ret);
2357         return ret;
2358     }
2359     p += output_len;
2360 
2361     if (mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(ssl)) {
2362         if (is_hrr) {
2363             ret = ssl_tls13_write_hrr_key_share_ext(ssl, p, end, &output_len);
2364         } else {
2365             ret = ssl_tls13_write_key_share_ext(ssl, p, end, &output_len);
2366         }
2367         if (ret != 0) {
2368             return ret;
2369         }
2370         p += output_len;
2371     }
2372 
2373 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
2374     if (!is_hrr && mbedtls_ssl_tls13_key_exchange_mode_with_psk(ssl)) {
2375         ret = ssl_tls13_write_server_pre_shared_key_ext(ssl, p, end, &output_len);
2376         if (ret != 0) {
2377             MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_write_server_pre_shared_key_ext",
2378                                   ret);
2379             return ret;
2380         }
2381         p += output_len;
2382     }
2383 #endif
2384 
2385     MBEDTLS_PUT_UINT16_BE(p - p_extensions_len - 2, p_extensions_len, 0);
2386 
2387     MBEDTLS_SSL_DEBUG_BUF(4, "server hello extensions",
2388                           p_extensions_len, p - p_extensions_len);
2389 
2390     *out_len = p - buf;
2391 
2392     MBEDTLS_SSL_DEBUG_BUF(3, "server hello", buf, *out_len);
2393 
2394     MBEDTLS_SSL_PRINT_EXTS(
2395         3, is_hrr ? MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST :
2396         MBEDTLS_SSL_HS_SERVER_HELLO,
2397         ssl->handshake->sent_extensions);
2398 
2399     return ret;
2400 }
2401 
2402 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_finalize_server_hello(mbedtls_ssl_context * ssl)2403 static int ssl_tls13_finalize_server_hello(mbedtls_ssl_context *ssl)
2404 {
2405     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2406     ret = mbedtls_ssl_tls13_compute_handshake_transform(ssl);
2407     if (ret != 0) {
2408         MBEDTLS_SSL_DEBUG_RET(1,
2409                               "mbedtls_ssl_tls13_compute_handshake_transform",
2410                               ret);
2411         return ret;
2412     }
2413 
2414     return ret;
2415 }
2416 
2417 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_server_hello(mbedtls_ssl_context * ssl)2418 static int ssl_tls13_write_server_hello(mbedtls_ssl_context *ssl)
2419 {
2420     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2421     unsigned char *buf;
2422     size_t buf_len, msg_len;
2423 
2424     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello"));
2425 
2426     MBEDTLS_SSL_PROC_CHK(ssl_tls13_prepare_server_hello(ssl));
2427 
2428     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2429                              ssl, MBEDTLS_SSL_HS_SERVER_HELLO, &buf, &buf_len));
2430 
2431     MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_server_hello_body(ssl, buf,
2432                                                            buf + buf_len,
2433                                                            &msg_len,
2434                                                            0));
2435 
2436     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2437                              ssl, MBEDTLS_SSL_HS_SERVER_HELLO, buf, msg_len));
2438 
2439     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
2440                              ssl, buf_len, msg_len));
2441 
2442     MBEDTLS_SSL_PROC_CHK(ssl_tls13_finalize_server_hello(ssl));
2443 
2444 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
2445     /* The server sends a dummy change_cipher_spec record immediately
2446      * after its first handshake message. This may either be after
2447      * a ServerHello or a HelloRetryRequest.
2448      */
2449     mbedtls_ssl_handshake_set_state(
2450         ssl, MBEDTLS_SSL_SERVER_CCS_AFTER_SERVER_HELLO);
2451 #else
2452     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS);
2453 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
2454 
2455 cleanup:
2456 
2457     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2458     return ret;
2459 }
2460 
2461 
2462 /*
2463  * Handler for MBEDTLS_SSL_HELLO_RETRY_REQUEST
2464  */
2465 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_prepare_hello_retry_request(mbedtls_ssl_context * ssl)2466 static int ssl_tls13_prepare_hello_retry_request(mbedtls_ssl_context *ssl)
2467 {
2468     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2469     if (ssl->handshake->hello_retry_request_flag) {
2470         MBEDTLS_SSL_DEBUG_MSG(1, ("Too many HRRs"));
2471         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
2472                                      MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
2473         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2474     }
2475 
2476     /*
2477      * Create stateless transcript hash for HRR
2478      */
2479     MBEDTLS_SSL_DEBUG_MSG(4, ("Reset transcript for HRR"));
2480     ret = mbedtls_ssl_reset_transcript_for_hrr(ssl);
2481     if (ret != 0) {
2482         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_reset_transcript_for_hrr", ret);
2483         return ret;
2484     }
2485     mbedtls_ssl_session_reset_msg_layer(ssl, 0);
2486 
2487     return 0;
2488 }
2489 
2490 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_hello_retry_request(mbedtls_ssl_context * ssl)2491 static int ssl_tls13_write_hello_retry_request(mbedtls_ssl_context *ssl)
2492 {
2493     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2494     unsigned char *buf;
2495     size_t buf_len, msg_len;
2496 
2497     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write hello retry request"));
2498 
2499     MBEDTLS_SSL_PROC_CHK(ssl_tls13_prepare_hello_retry_request(ssl));
2500 
2501     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2502                              ssl, MBEDTLS_SSL_HS_SERVER_HELLO,
2503                              &buf, &buf_len));
2504 
2505     MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_server_hello_body(ssl, buf,
2506                                                            buf + buf_len,
2507                                                            &msg_len,
2508                                                            1));
2509     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2510                              ssl, MBEDTLS_SSL_HS_SERVER_HELLO, buf, msg_len));
2511 
2512 
2513     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(ssl, buf_len,
2514                                                           msg_len));
2515 
2516     ssl->handshake->hello_retry_request_flag = 1;
2517 
2518 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
2519     /* The server sends a dummy change_cipher_spec record immediately
2520      * after its first handshake message. This may either be after
2521      * a ServerHello or a HelloRetryRequest.
2522      */
2523     mbedtls_ssl_handshake_set_state(
2524         ssl, MBEDTLS_SSL_SERVER_CCS_AFTER_HELLO_RETRY_REQUEST);
2525 #else
2526     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
2527 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
2528 
2529 cleanup:
2530     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write hello retry request"));
2531     return ret;
2532 }
2533 
2534 /*
2535  * Handler for MBEDTLS_SSL_ENCRYPTED_EXTENSIONS
2536  */
2537 
2538 /*
2539  * struct {
2540  *    Extension extensions<0..2 ^ 16 - 1>;
2541  * } EncryptedExtensions;
2542  *
2543  */
2544 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_encrypted_extensions_body(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)2545 static int ssl_tls13_write_encrypted_extensions_body(mbedtls_ssl_context *ssl,
2546                                                      unsigned char *buf,
2547                                                      unsigned char *end,
2548                                                      size_t *out_len)
2549 {
2550     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2551     unsigned char *p = buf;
2552     size_t extensions_len = 0;
2553     unsigned char *p_extensions_len;
2554     size_t output_len;
2555 
2556     *out_len = 0;
2557 
2558     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
2559     p_extensions_len = p;
2560     p += 2;
2561 
2562     ((void) ssl);
2563     ((void) ret);
2564     ((void) output_len);
2565 
2566 #if defined(MBEDTLS_SSL_ALPN)
2567     ret = mbedtls_ssl_write_alpn_ext(ssl, p, end, &output_len);
2568     if (ret != 0) {
2569         return ret;
2570     }
2571     p += output_len;
2572 #endif /* MBEDTLS_SSL_ALPN */
2573 
2574 #if defined(MBEDTLS_SSL_EARLY_DATA)
2575     if (ssl->handshake->early_data_accepted) {
2576         ret = mbedtls_ssl_tls13_write_early_data_ext(
2577             ssl, 0, p, end, &output_len);
2578         if (ret != 0) {
2579             return ret;
2580         }
2581         p += output_len;
2582     }
2583 #endif /* MBEDTLS_SSL_EARLY_DATA */
2584 
2585 #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
2586     if (ssl->handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(RECORD_SIZE_LIMIT)) {
2587         ret = mbedtls_ssl_tls13_write_record_size_limit_ext(
2588             ssl, p, end, &output_len);
2589         if (ret != 0) {
2590             return ret;
2591         }
2592         p += output_len;
2593     }
2594 #endif
2595 
2596     extensions_len = (p - p_extensions_len) - 2;
2597     MBEDTLS_PUT_UINT16_BE(extensions_len, p_extensions_len, 0);
2598 
2599     *out_len = p - buf;
2600 
2601     MBEDTLS_SSL_DEBUG_BUF(4, "encrypted extensions", buf, *out_len);
2602 
2603     MBEDTLS_SSL_PRINT_EXTS(
2604         3, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS, ssl->handshake->sent_extensions);
2605 
2606     return 0;
2607 }
2608 
2609 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_encrypted_extensions(mbedtls_ssl_context * ssl)2610 static int ssl_tls13_write_encrypted_extensions(mbedtls_ssl_context *ssl)
2611 {
2612     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2613     unsigned char *buf;
2614     size_t buf_len, msg_len;
2615 
2616     mbedtls_ssl_set_outbound_transform(ssl,
2617                                        ssl->handshake->transform_handshake);
2618     MBEDTLS_SSL_DEBUG_MSG(
2619         3, ("switching to handshake transform for outbound data"));
2620 
2621     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write encrypted extensions"));
2622 
2623     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2624                              ssl, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
2625                              &buf, &buf_len));
2626 
2627     MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_encrypted_extensions_body(
2628                              ssl, buf, buf + buf_len, &msg_len));
2629 
2630     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2631                              ssl, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
2632                              buf, msg_len));
2633 
2634     MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
2635                              ssl, buf_len, msg_len));
2636 
2637 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2638     if (mbedtls_ssl_tls13_key_exchange_mode_with_psk(ssl)) {
2639         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2640     } else {
2641         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CERTIFICATE_REQUEST);
2642     }
2643 #else
2644     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2645 #endif
2646 
2647 cleanup:
2648 
2649     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write encrypted extensions"));
2650     return ret;
2651 }
2652 
2653 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2654 #define SSL_CERTIFICATE_REQUEST_SEND_REQUEST 0
2655 #define SSL_CERTIFICATE_REQUEST_SKIP         1
2656 /* Coordination:
2657  * Check whether a CertificateRequest message should be written.
2658  * Returns a negative code on failure, or
2659  * - SSL_CERTIFICATE_REQUEST_SEND_REQUEST
2660  * - SSL_CERTIFICATE_REQUEST_SKIP
2661  * indicating if the writing of the CertificateRequest
2662  * should be skipped or not.
2663  */
2664 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_certificate_request_coordinate(mbedtls_ssl_context * ssl)2665 static int ssl_tls13_certificate_request_coordinate(mbedtls_ssl_context *ssl)
2666 {
2667     int authmode;
2668 
2669 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2670     if (ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET) {
2671         authmode = ssl->handshake->sni_authmode;
2672     } else
2673 #endif
2674     authmode = ssl->conf->authmode;
2675 
2676     if (authmode == MBEDTLS_SSL_VERIFY_NONE) {
2677         ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
2678         return SSL_CERTIFICATE_REQUEST_SKIP;
2679     }
2680 
2681     ssl->handshake->certificate_request_sent = 1;
2682 
2683     return SSL_CERTIFICATE_REQUEST_SEND_REQUEST;
2684 }
2685 
2686 /*
2687  * struct {
2688  *   opaque certificate_request_context<0..2^8-1>;
2689  *   Extension extensions<2..2^16-1>;
2690  * } CertificateRequest;
2691  *
2692  */
2693 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_certificate_request_body(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * out_len)2694 static int ssl_tls13_write_certificate_request_body(mbedtls_ssl_context *ssl,
2695                                                     unsigned char *buf,
2696                                                     const unsigned char *end,
2697                                                     size_t *out_len)
2698 {
2699     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2700     unsigned char *p = buf;
2701     size_t output_len = 0;
2702     unsigned char *p_extensions_len;
2703 
2704     *out_len = 0;
2705 
2706     /* Check if we have enough space:
2707      * - certificate_request_context (1 byte)
2708      * - extensions length           (2 bytes)
2709      */
2710     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 3);
2711 
2712     /*
2713      * Write certificate_request_context
2714      */
2715     /*
2716      * We use a zero length context for the normal handshake
2717      * messages. For post-authentication handshake messages
2718      * this request context would be set to a non-zero value.
2719      */
2720     *p++ = 0x0;
2721 
2722     /*
2723      * Write extensions
2724      */
2725     /* The extensions must contain the signature_algorithms. */
2726     p_extensions_len = p;
2727     p += 2;
2728     ret = mbedtls_ssl_write_sig_alg_ext(ssl, p, end, &output_len);
2729     if (ret != 0) {
2730         return ret;
2731     }
2732 
2733     p += output_len;
2734     MBEDTLS_PUT_UINT16_BE(p - p_extensions_len - 2, p_extensions_len, 0);
2735 
2736     *out_len = p - buf;
2737 
2738     MBEDTLS_SSL_PRINT_EXTS(
2739         3, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST, ssl->handshake->sent_extensions);
2740 
2741     return 0;
2742 }
2743 
2744 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_certificate_request(mbedtls_ssl_context * ssl)2745 static int ssl_tls13_write_certificate_request(mbedtls_ssl_context *ssl)
2746 {
2747     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2748 
2749     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate request"));
2750 
2751     MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_certificate_request_coordinate(ssl));
2752 
2753     if (ret == SSL_CERTIFICATE_REQUEST_SEND_REQUEST) {
2754         unsigned char *buf;
2755         size_t buf_len, msg_len;
2756 
2757         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2758                                  ssl, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
2759                                  &buf, &buf_len));
2760 
2761         MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_certificate_request_body(
2762                                  ssl, buf, buf + buf_len, &msg_len));
2763 
2764         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2765                                  ssl, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
2766                                  buf, msg_len));
2767 
2768         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
2769                                  ssl, buf_len, msg_len));
2770     } else if (ret == SSL_CERTIFICATE_REQUEST_SKIP) {
2771         MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate request"));
2772         ret = 0;
2773     } else {
2774         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2775         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2776         goto cleanup;
2777     }
2778 
2779     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_CERTIFICATE);
2780 cleanup:
2781 
2782     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate request"));
2783     return ret;
2784 }
2785 
2786 /*
2787  * Handler for MBEDTLS_SSL_SERVER_CERTIFICATE
2788  */
2789 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_server_certificate(mbedtls_ssl_context * ssl)2790 static int ssl_tls13_write_server_certificate(mbedtls_ssl_context *ssl)
2791 {
2792     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2793 
2794 #if defined(MBEDTLS_X509_CRT_PARSE_C)
2795     if ((ssl_tls13_pick_key_cert(ssl) != 0) ||
2796         mbedtls_ssl_own_cert(ssl) == NULL) {
2797         MBEDTLS_SSL_DEBUG_MSG(2, ("No certificate available."));
2798         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
2799                                      MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
2800         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2801     }
2802 #endif /* MBEDTLS_X509_CRT_PARSE_C */
2803 
2804     ret = mbedtls_ssl_tls13_write_certificate(ssl);
2805     if (ret != 0) {
2806         return ret;
2807     }
2808     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CERTIFICATE_VERIFY);
2809     return 0;
2810 }
2811 
2812 /*
2813  * Handler for MBEDTLS_SSL_CERTIFICATE_VERIFY
2814  */
2815 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_certificate_verify(mbedtls_ssl_context * ssl)2816 static int ssl_tls13_write_certificate_verify(mbedtls_ssl_context *ssl)
2817 {
2818     int ret = mbedtls_ssl_tls13_write_certificate_verify(ssl);
2819     if (ret != 0) {
2820         return ret;
2821     }
2822     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2823     return 0;
2824 }
2825 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
2826 
2827 /*
2828  * RFC 8446 section A.2
2829  *
2830  *                                | Send ServerHello
2831  *                                | K_send = handshake
2832  *                                | Send EncryptedExtensions
2833  *                                | [Send CertificateRequest]
2834  * Can send                       | [Send Certificate + CertificateVerify]
2835  * app data                       | Send Finished
2836  * after   -->                    | K_send = application
2837  * here                  +--------+--------+
2838  *              No 0-RTT |                 | 0-RTT
2839  *                       |                 |
2840  *   K_recv = handshake  |                 | K_recv = early data
2841  * [Skip decrypt errors] |    +------> WAIT_EOED -+
2842  *                       |    |       Recv |      | Recv EndOfEarlyData
2843  *                       |    | early data |      | K_recv = handshake
2844  *                       |    +------------+      |
2845  *                       |                        |
2846  *                       +> WAIT_FLIGHT2 <--------+
2847  *                                |
2848  *                       +--------+--------+
2849  *               No auth |                 | Client auth
2850  *                       |                 |
2851  *                       |                 v
2852  *                       |             WAIT_CERT
2853  *                       |        Recv |       | Recv Certificate
2854  *                       |       empty |       v
2855  *                       | Certificate |    WAIT_CV
2856  *                       |             |       | Recv
2857  *                       |             v       | CertificateVerify
2858  *                       +-> WAIT_FINISHED <---+
2859  *                                | Recv Finished
2860  *
2861  *
2862  * The following function handles the state changes after WAIT_FLIGHT2 in the
2863  * above diagram. We are not going to receive early data related messages
2864  * anymore, prepare to receive the first handshake message of the client
2865  * second flight.
2866  */
ssl_tls13_prepare_for_handshake_second_flight(mbedtls_ssl_context * ssl)2867 static void ssl_tls13_prepare_for_handshake_second_flight(
2868     mbedtls_ssl_context *ssl)
2869 {
2870     if (ssl->handshake->certificate_request_sent) {
2871         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_CERTIFICATE);
2872     } else {
2873         MBEDTLS_SSL_DEBUG_MSG(2, ("skip parse certificate"));
2874         MBEDTLS_SSL_DEBUG_MSG(2, ("skip parse certificate verify"));
2875 
2876         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_FINISHED);
2877     }
2878 }
2879 
2880 /*
2881  * Handler for MBEDTLS_SSL_SERVER_FINISHED
2882  */
2883 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_server_finished(mbedtls_ssl_context * ssl)2884 static int ssl_tls13_write_server_finished(mbedtls_ssl_context *ssl)
2885 {
2886     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2887 
2888     ret = mbedtls_ssl_tls13_write_finished_message(ssl);
2889     if (ret != 0) {
2890         return ret;
2891     }
2892 
2893     ret = mbedtls_ssl_tls13_compute_application_transform(ssl);
2894     if (ret != 0) {
2895         MBEDTLS_SSL_PEND_FATAL_ALERT(
2896             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
2897             MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
2898         return ret;
2899     }
2900 
2901 #if defined(MBEDTLS_SSL_EARLY_DATA)
2902     if (ssl->handshake->early_data_accepted) {
2903         /* See RFC 8446 section A.2 for more information */
2904         MBEDTLS_SSL_DEBUG_MSG(
2905             1, ("Switch to early keys for inbound traffic. "
2906                 "( K_recv = early data )"));
2907         mbedtls_ssl_set_inbound_transform(
2908             ssl, ssl->handshake->transform_earlydata);
2909         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_END_OF_EARLY_DATA);
2910         return 0;
2911     }
2912 #endif /* MBEDTLS_SSL_EARLY_DATA */
2913     MBEDTLS_SSL_DEBUG_MSG(
2914         1, ("Switch to handshake keys for inbound traffic "
2915             "( K_recv = handshake )"));
2916     mbedtls_ssl_set_inbound_transform(ssl, ssl->handshake->transform_handshake);
2917 
2918     ssl_tls13_prepare_for_handshake_second_flight(ssl);
2919 
2920     return 0;
2921 }
2922 
2923 #if defined(MBEDTLS_SSL_EARLY_DATA)
2924 /*
2925  * Handler for MBEDTLS_SSL_END_OF_EARLY_DATA
2926  */
2927 #define SSL_GOT_END_OF_EARLY_DATA      0
2928 #define SSL_GOT_EARLY_DATA             1
2929 /* Coordination:
2930  * Deals with the ambiguity of not knowing if the next message is an
2931  * EndOfEarlyData message or an application message containing early data.
2932  * Returns a negative code on failure, or
2933  * - SSL_GOT_END_OF_EARLY_DATA
2934  * - SSL_GOT_EARLY_DATA
2935  * indicating which message is received.
2936  */
2937 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_end_of_early_data_coordinate(mbedtls_ssl_context * ssl)2938 static int ssl_tls13_end_of_early_data_coordinate(mbedtls_ssl_context *ssl)
2939 {
2940     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2941 
2942     if ((ret = mbedtls_ssl_read_record(ssl, 0)) != 0) {
2943         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
2944         return ret;
2945     }
2946     ssl->keep_current_message = 1;
2947 
2948     if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE        &&
2949         ssl->in_msg[0]  == MBEDTLS_SSL_HS_END_OF_EARLY_DATA) {
2950         MBEDTLS_SSL_DEBUG_MSG(3, ("Received an end_of_early_data message."));
2951         return SSL_GOT_END_OF_EARLY_DATA;
2952     }
2953 
2954     if (ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
2955         if (ssl->in_offt == NULL) {
2956             MBEDTLS_SSL_DEBUG_MSG(3, ("Received early data"));
2957             /* Set the reading pointer */
2958             ssl->in_offt = ssl->in_msg;
2959             ret = mbedtls_ssl_tls13_check_early_data_len(ssl, ssl->in_msglen);
2960             if (ret != 0) {
2961                 return ret;
2962             }
2963         }
2964         return SSL_GOT_EARLY_DATA;
2965     }
2966 
2967     MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
2968                                  MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
2969     return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
2970 }
2971 
2972 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_parse_end_of_early_data(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)2973 static int ssl_tls13_parse_end_of_early_data(mbedtls_ssl_context *ssl,
2974                                              const unsigned char *buf,
2975                                              const unsigned char *end)
2976 {
2977     /* RFC 8446 section 4.5
2978      *
2979      * struct {} EndOfEarlyData;
2980      */
2981     if (buf != end) {
2982         MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
2983                                      MBEDTLS_ERR_SSL_DECODE_ERROR);
2984         return MBEDTLS_ERR_SSL_DECODE_ERROR;
2985     }
2986     return 0;
2987 }
2988 
2989 /*
2990  * RFC 8446 section A.2
2991  *
2992  *                                | Send ServerHello
2993  *                                | K_send = handshake
2994  *                                | Send EncryptedExtensions
2995  *                                | [Send CertificateRequest]
2996  * Can send                       | [Send Certificate + CertificateVerify]
2997  * app data                       | Send Finished
2998  * after   -->                    | K_send = application
2999  * here                  +--------+--------+
3000  *              No 0-RTT |                 | 0-RTT
3001  *                       |                 |
3002  *   K_recv = handshake  |                 | K_recv = early data
3003  * [Skip decrypt errors] |    +------> WAIT_EOED -+
3004  *                       |    |       Recv |      | Recv EndOfEarlyData
3005  *                       |    | early data |      | K_recv = handshake
3006  *                       |    +------------+      |
3007  *                       |                        |
3008  *                       +> WAIT_FLIGHT2 <--------+
3009  *                                |
3010  *                       +--------+--------+
3011  *               No auth |                 | Client auth
3012  *                       |                 |
3013  *                       |                 v
3014  *                       |             WAIT_CERT
3015  *                       |        Recv |       | Recv Certificate
3016  *                       |       empty |       v
3017  *                       | Certificate |    WAIT_CV
3018  *                       |             |       | Recv
3019  *                       |             v       | CertificateVerify
3020  *                       +-> WAIT_FINISHED <---+
3021  *                                | Recv Finished
3022  *
3023  * The function handles actions and state changes from 0-RTT to WAIT_FLIGHT2 in
3024  * the above diagram.
3025  */
3026 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_end_of_early_data(mbedtls_ssl_context * ssl)3027 static int ssl_tls13_process_end_of_early_data(mbedtls_ssl_context *ssl)
3028 {
3029     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3030 
3031     MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_tls13_process_end_of_early_data"));
3032 
3033     MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_end_of_early_data_coordinate(ssl));
3034 
3035     if (ret == SSL_GOT_END_OF_EARLY_DATA) {
3036         unsigned char *buf;
3037         size_t buf_len;
3038 
3039         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
3040                                  ssl, MBEDTLS_SSL_HS_END_OF_EARLY_DATA,
3041                                  &buf, &buf_len));
3042 
3043         MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_end_of_early_data(
3044                                  ssl, buf, buf + buf_len));
3045 
3046         MBEDTLS_SSL_DEBUG_MSG(
3047             1, ("Switch to handshake keys for inbound traffic"
3048                 "( K_recv = handshake )"));
3049         mbedtls_ssl_set_inbound_transform(
3050             ssl, ssl->handshake->transform_handshake);
3051 
3052         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
3053                                  ssl, MBEDTLS_SSL_HS_END_OF_EARLY_DATA,
3054                                  buf, buf_len));
3055 
3056         ssl_tls13_prepare_for_handshake_second_flight(ssl);
3057 
3058     } else if (ret == SSL_GOT_EARLY_DATA) {
3059         ret = MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA;
3060         goto cleanup;
3061     } else {
3062         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3063         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3064         goto cleanup;
3065     }
3066 
3067 cleanup:
3068     MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_tls13_process_end_of_early_data"));
3069     return ret;
3070 }
3071 #endif /* MBEDTLS_SSL_EARLY_DATA */
3072 
3073 /*
3074  * Handler for MBEDTLS_SSL_CLIENT_FINISHED
3075  */
3076 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_process_client_finished(mbedtls_ssl_context * ssl)3077 static int ssl_tls13_process_client_finished(mbedtls_ssl_context *ssl)
3078 {
3079     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3080 
3081     ret = mbedtls_ssl_tls13_process_finished_message(ssl);
3082     if (ret != 0) {
3083         return ret;
3084     }
3085 
3086     ret = mbedtls_ssl_tls13_compute_resumption_master_secret(ssl);
3087     if (ret != 0) {
3088         MBEDTLS_SSL_DEBUG_RET(
3089             1, "mbedtls_ssl_tls13_compute_resumption_master_secret", ret);
3090     }
3091 
3092     mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_WRAPUP);
3093     return 0;
3094 }
3095 
3096 /*
3097  * Handler for MBEDTLS_SSL_HANDSHAKE_WRAPUP
3098  */
3099 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_handshake_wrapup(mbedtls_ssl_context * ssl)3100 static int ssl_tls13_handshake_wrapup(mbedtls_ssl_context *ssl)
3101 {
3102     MBEDTLS_SSL_DEBUG_MSG(2, ("handshake: done"));
3103 
3104     mbedtls_ssl_tls13_handshake_wrapup(ssl);
3105 
3106 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && \
3107     defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
3108 /* TODO: Remove the check of SOME_PSK_ENABLED since SESSION_TICKETS requires
3109  *       SOME_PSK_ENABLED to be enabled. Here is just to make CI happy. It is
3110  *       expected to be resolved with issue#6395.
3111  */
3112     /* Sent NewSessionTicket message only when client supports PSK */
3113     if (mbedtls_ssl_tls13_is_some_psk_supported(ssl)) {
3114         mbedtls_ssl_handshake_set_state(
3115             ssl, MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET);
3116     } else
3117 #endif
3118     {
3119         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
3120     }
3121     return 0;
3122 }
3123 
3124 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3125 /*
3126  * Handler for MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET
3127  */
3128 #define SSL_NEW_SESSION_TICKET_SKIP  0
3129 #define SSL_NEW_SESSION_TICKET_WRITE 1
3130 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_new_session_ticket_coordinate(mbedtls_ssl_context * ssl)3131 static int ssl_tls13_write_new_session_ticket_coordinate(mbedtls_ssl_context *ssl)
3132 {
3133     /* Check whether the use of session tickets is enabled */
3134     if (ssl->conf->f_ticket_write == NULL) {
3135         MBEDTLS_SSL_DEBUG_MSG(2, ("NewSessionTicket: disabled,"
3136                                   " callback is not set"));
3137         return SSL_NEW_SESSION_TICKET_SKIP;
3138     }
3139     if (ssl->conf->new_session_tickets_count == 0) {
3140         MBEDTLS_SSL_DEBUG_MSG(2, ("NewSessionTicket: disabled,"
3141                                   " configured count is zero"));
3142         return SSL_NEW_SESSION_TICKET_SKIP;
3143     }
3144 
3145     if (ssl->handshake->new_session_tickets_count == 0) {
3146         MBEDTLS_SSL_DEBUG_MSG(2, ("NewSessionTicket: all tickets have "
3147                                   "been sent."));
3148         return SSL_NEW_SESSION_TICKET_SKIP;
3149     }
3150 
3151     return SSL_NEW_SESSION_TICKET_WRITE;
3152 }
3153 
3154 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_prepare_new_session_ticket(mbedtls_ssl_context * ssl,unsigned char * ticket_nonce,size_t ticket_nonce_size)3155 static int ssl_tls13_prepare_new_session_ticket(mbedtls_ssl_context *ssl,
3156                                                 unsigned char *ticket_nonce,
3157                                                 size_t ticket_nonce_size)
3158 {
3159     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3160     mbedtls_ssl_session *session = ssl->session;
3161     mbedtls_ssl_ciphersuite_t *ciphersuite_info;
3162     psa_algorithm_t psa_hash_alg;
3163     int hash_length;
3164 
3165     MBEDTLS_SSL_DEBUG_MSG(2, ("=> prepare NewSessionTicket msg"));
3166 
3167     /* Set ticket_flags depends on the advertised psk key exchange mode */
3168     mbedtls_ssl_tls13_session_clear_ticket_flags(
3169         session, MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
3170 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
3171     mbedtls_ssl_tls13_session_set_ticket_flags(
3172         session, ssl->handshake->tls13_kex_modes);
3173 #endif
3174 
3175 #if defined(MBEDTLS_SSL_EARLY_DATA)
3176     if (ssl->conf->early_data_enabled == MBEDTLS_SSL_EARLY_DATA_ENABLED &&
3177         ssl->conf->max_early_data_size > 0) {
3178         mbedtls_ssl_tls13_session_set_ticket_flags(
3179             session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA);
3180         session->max_early_data_size = ssl->conf->max_early_data_size;
3181     }
3182 #endif /* MBEDTLS_SSL_EARLY_DATA */
3183 
3184     MBEDTLS_SSL_PRINT_TICKET_FLAGS(4, session->ticket_flags);
3185 
3186 #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN)
3187     if (session->ticket_alpn == NULL) {
3188         ret = mbedtls_ssl_session_set_ticket_alpn(session, ssl->alpn_chosen);
3189         if (ret != 0) {
3190             return ret;
3191         }
3192     }
3193 #endif
3194 
3195     /* Generate ticket_age_add */
3196     if ((ret = ssl->conf->f_rng(ssl->conf->p_rng,
3197                                 (unsigned char *) &session->ticket_age_add,
3198                                 sizeof(session->ticket_age_add)) != 0)) {
3199         MBEDTLS_SSL_DEBUG_RET(1, "generate_ticket_age_add", ret);
3200         return ret;
3201     }
3202     MBEDTLS_SSL_DEBUG_MSG(3, ("ticket_age_add: %u",
3203                               (unsigned int) session->ticket_age_add));
3204 
3205     /* Generate ticket_nonce */
3206     ret = ssl->conf->f_rng(ssl->conf->p_rng, ticket_nonce, ticket_nonce_size);
3207     if (ret != 0) {
3208         MBEDTLS_SSL_DEBUG_RET(1, "generate_ticket_nonce", ret);
3209         return ret;
3210     }
3211     MBEDTLS_SSL_DEBUG_BUF(3, "ticket_nonce:",
3212                           ticket_nonce, ticket_nonce_size);
3213 
3214     ciphersuite_info =
3215         (mbedtls_ssl_ciphersuite_t *) ssl->handshake->ciphersuite_info;
3216     psa_hash_alg = mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ciphersuite_info->mac);
3217     hash_length = PSA_HASH_LENGTH(psa_hash_alg);
3218     if (hash_length == -1 ||
3219         (size_t) hash_length > sizeof(session->resumption_key)) {
3220         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3221     }
3222 
3223     /* In this code the psk key length equals the length of the hash */
3224     session->resumption_key_len = hash_length;
3225     session->ciphersuite = ciphersuite_info->id;
3226 
3227     /* Compute resumption key
3228      *
3229      *  HKDF-Expand-Label( resumption_master_secret,
3230      *                    "resumption", ticket_nonce, Hash.length )
3231      */
3232     ret = mbedtls_ssl_tls13_hkdf_expand_label(
3233         psa_hash_alg,
3234         session->app_secrets.resumption_master_secret,
3235         hash_length,
3236         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(resumption),
3237         ticket_nonce,
3238         ticket_nonce_size,
3239         session->resumption_key,
3240         hash_length);
3241 
3242     if (ret != 0) {
3243         MBEDTLS_SSL_DEBUG_RET(2,
3244                               "Creating the ticket-resumed PSK failed",
3245                               ret);
3246         return ret;
3247     }
3248     MBEDTLS_SSL_DEBUG_BUF(3, "Ticket-resumed PSK",
3249                           session->resumption_key,
3250                           session->resumption_key_len);
3251 
3252     MBEDTLS_SSL_DEBUG_BUF(3, "resumption_master_secret",
3253                           session->app_secrets.resumption_master_secret,
3254                           hash_length);
3255 
3256     return 0;
3257 }
3258 
3259 /* This function creates a NewSessionTicket message in the following format:
3260  *
3261  * struct {
3262  *    uint32 ticket_lifetime;
3263  *    uint32 ticket_age_add;
3264  *    opaque ticket_nonce<0..255>;
3265  *    opaque ticket<1..2^16-1>;
3266  *    Extension extensions<0..2^16-2>;
3267  * } NewSessionTicket;
3268  *
3269  * The ticket inside the NewSessionTicket message is an encrypted container
3270  * carrying the necessary information so that the server is later able to
3271  * re-start the communication.
3272  *
3273  * The following fields are placed inside the ticket by the
3274  * f_ticket_write() function:
3275  *
3276  *  - creation time (ticket_creation_time)
3277  *  - flags (ticket_flags)
3278  *  - age add (ticket_age_add)
3279  *  - key (resumption_key)
3280  *  - key length (resumption_key_len)
3281  *  - ciphersuite (ciphersuite)
3282  *  - max_early_data_size (max_early_data_size)
3283  */
3284 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_write_new_session_ticket_body(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len,unsigned char * ticket_nonce,size_t ticket_nonce_size)3285 static int ssl_tls13_write_new_session_ticket_body(mbedtls_ssl_context *ssl,
3286                                                    unsigned char *buf,
3287                                                    unsigned char *end,
3288                                                    size_t *out_len,
3289                                                    unsigned char *ticket_nonce,
3290                                                    size_t ticket_nonce_size)
3291 {
3292     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3293     unsigned char *p = buf;
3294     mbedtls_ssl_session *session = ssl->session;
3295     size_t ticket_len;
3296     uint32_t ticket_lifetime;
3297     unsigned char *p_extensions_len;
3298 
3299     *out_len = 0;
3300     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write NewSessionTicket msg"));
3301 
3302     /*
3303      *    ticket_lifetime   4 bytes
3304      *    ticket_age_add    4 bytes
3305      *    ticket_nonce      1 + ticket_nonce_size bytes
3306      *    ticket            >=2 bytes
3307      */
3308     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4 + 4 + 1 + ticket_nonce_size + 2);
3309 
3310     /* Generate ticket and ticket_lifetime */
3311 #if defined(MBEDTLS_HAVE_TIME)
3312     session->ticket_creation_time = mbedtls_ms_time();
3313 #endif
3314     ret = ssl->conf->f_ticket_write(ssl->conf->p_ticket,
3315                                     session,
3316                                     p + 9 + ticket_nonce_size + 2,
3317                                     end,
3318                                     &ticket_len,
3319                                     &ticket_lifetime);
3320     if (ret != 0) {
3321         MBEDTLS_SSL_DEBUG_RET(1, "write_ticket", ret);
3322         return ret;
3323     }
3324 
3325     /* RFC 8446 section 4.6.1
3326      *
3327      *  ticket_lifetime:  Indicates the lifetime in seconds as a 32-bit
3328      *     unsigned integer in network byte order from the time of ticket
3329      *     issuance.  Servers MUST NOT use any value greater than
3330      *     604800 seconds (7 days) ...
3331      */
3332     if (ticket_lifetime > MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME) {
3333         MBEDTLS_SSL_DEBUG_MSG(
3334             1, ("Ticket lifetime (%u) is greater than 7 days.",
3335                 (unsigned int) ticket_lifetime));
3336         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
3337     }
3338 
3339     MBEDTLS_PUT_UINT32_BE(ticket_lifetime, p, 0);
3340     MBEDTLS_SSL_DEBUG_MSG(3, ("ticket_lifetime: %u",
3341                               (unsigned int) ticket_lifetime));
3342 
3343     /* Write ticket_age_add */
3344     MBEDTLS_PUT_UINT32_BE(session->ticket_age_add, p, 4);
3345     MBEDTLS_SSL_DEBUG_MSG(3, ("ticket_age_add: %u",
3346                               (unsigned int) session->ticket_age_add));
3347 
3348     /* Write ticket_nonce */
3349     p[8] = (unsigned char) ticket_nonce_size;
3350     if (ticket_nonce_size > 0) {
3351         memcpy(p + 9, ticket_nonce, ticket_nonce_size);
3352     }
3353     p += 9 + ticket_nonce_size;
3354 
3355     /* Write ticket */
3356     MBEDTLS_PUT_UINT16_BE(ticket_len, p, 0);
3357     p += 2;
3358     MBEDTLS_SSL_DEBUG_BUF(4, "ticket", p, ticket_len);
3359     p += ticket_len;
3360 
3361     /* Ticket Extensions
3362      *
3363      * Extension extensions<0..2^16-2>;
3364      */
3365     ssl->handshake->sent_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
3366 
3367     MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
3368     p_extensions_len = p;
3369     p += 2;
3370 
3371 #if defined(MBEDTLS_SSL_EARLY_DATA)
3372     if (mbedtls_ssl_tls13_session_ticket_allow_early_data(session)) {
3373         size_t output_len;
3374 
3375         if ((ret = mbedtls_ssl_tls13_write_early_data_ext(
3376                  ssl, 1, p, end, &output_len)) != 0) {
3377             MBEDTLS_SSL_DEBUG_RET(
3378                 1, "mbedtls_ssl_tls13_write_early_data_ext", ret);
3379             return ret;
3380         }
3381         p += output_len;
3382     } else {
3383         MBEDTLS_SSL_DEBUG_MSG(
3384             4, ("early_data not allowed, "
3385                 "skip early_data extension in NewSessionTicket"));
3386     }
3387 
3388 #endif /* MBEDTLS_SSL_EARLY_DATA */
3389 
3390     MBEDTLS_PUT_UINT16_BE(p - p_extensions_len - 2, p_extensions_len, 0);
3391 
3392     *out_len = p - buf;
3393     MBEDTLS_SSL_DEBUG_BUF(4, "ticket", buf, *out_len);
3394     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write new session ticket"));
3395 
3396     MBEDTLS_SSL_PRINT_EXTS(
3397         3, MBEDTLS_SSL_HS_NEW_SESSION_TICKET, ssl->handshake->sent_extensions);
3398 
3399     return 0;
3400 }
3401 
3402 /*
3403  * Handler for MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET
3404  */
ssl_tls13_write_new_session_ticket(mbedtls_ssl_context * ssl)3405 static int ssl_tls13_write_new_session_ticket(mbedtls_ssl_context *ssl)
3406 {
3407     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3408 
3409     MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_write_new_session_ticket_coordinate(ssl));
3410 
3411     if (ret == SSL_NEW_SESSION_TICKET_WRITE) {
3412         unsigned char ticket_nonce[MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH];
3413         unsigned char *buf;
3414         size_t buf_len, msg_len;
3415 
3416         MBEDTLS_SSL_PROC_CHK(ssl_tls13_prepare_new_session_ticket(
3417                                  ssl, ticket_nonce, sizeof(ticket_nonce)));
3418 
3419         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
3420                                  ssl, MBEDTLS_SSL_HS_NEW_SESSION_TICKET,
3421                                  &buf, &buf_len));
3422 
3423         MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_new_session_ticket_body(
3424                                  ssl, buf, buf + buf_len, &msg_len,
3425                                  ticket_nonce, sizeof(ticket_nonce)));
3426 
3427         MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
3428                                  ssl, buf_len, msg_len));
3429 
3430         /* Limit session tickets count to one when resumption connection.
3431          *
3432          * See document of mbedtls_ssl_conf_new_session_tickets.
3433          */
3434         if (ssl->handshake->resume == 1) {
3435             ssl->handshake->new_session_tickets_count = 0;
3436         } else {
3437             ssl->handshake->new_session_tickets_count--;
3438         }
3439 
3440         mbedtls_ssl_handshake_set_state(
3441             ssl, MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET_FLUSH);
3442     } else {
3443         mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
3444     }
3445 
3446 cleanup:
3447 
3448     return ret;
3449 }
3450 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3451 
3452 /*
3453  * TLS 1.3 State Machine -- server side
3454  */
mbedtls_ssl_tls13_handshake_server_step(mbedtls_ssl_context * ssl)3455 int mbedtls_ssl_tls13_handshake_server_step(mbedtls_ssl_context *ssl)
3456 {
3457     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3458 
3459     if (ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL) {
3460         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
3461     }
3462 
3463     MBEDTLS_SSL_DEBUG_MSG(2, ("tls13 server state: %s(%d)",
3464                               mbedtls_ssl_states_str((mbedtls_ssl_states) ssl->state),
3465                               ssl->state));
3466 
3467     switch (ssl->state) {
3468         /* start state */
3469         case MBEDTLS_SSL_HELLO_REQUEST:
3470             mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
3471             ret = 0;
3472             break;
3473 
3474         case MBEDTLS_SSL_CLIENT_HELLO:
3475             ret = ssl_tls13_process_client_hello(ssl);
3476             if (ret != 0) {
3477                 MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_process_client_hello", ret);
3478             }
3479             break;
3480 
3481         case MBEDTLS_SSL_HELLO_RETRY_REQUEST:
3482             ret = ssl_tls13_write_hello_retry_request(ssl);
3483             if (ret != 0) {
3484                 MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_write_hello_retry_request", ret);
3485                 return ret;
3486             }
3487             break;
3488 
3489         case MBEDTLS_SSL_SERVER_HELLO:
3490             ret = ssl_tls13_write_server_hello(ssl);
3491             break;
3492 
3493         case MBEDTLS_SSL_ENCRYPTED_EXTENSIONS:
3494             ret = ssl_tls13_write_encrypted_extensions(ssl);
3495             if (ret != 0) {
3496                 MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_write_encrypted_extensions", ret);
3497                 return ret;
3498             }
3499             break;
3500 
3501 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
3502         case MBEDTLS_SSL_CERTIFICATE_REQUEST:
3503             ret = ssl_tls13_write_certificate_request(ssl);
3504             break;
3505 
3506         case MBEDTLS_SSL_SERVER_CERTIFICATE:
3507             ret = ssl_tls13_write_server_certificate(ssl);
3508             break;
3509 
3510         case MBEDTLS_SSL_CERTIFICATE_VERIFY:
3511             ret = ssl_tls13_write_certificate_verify(ssl);
3512             break;
3513 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
3514 
3515             /*
3516              * Injection of dummy-CCS's for middlebox compatibility
3517              */
3518 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
3519         case MBEDTLS_SSL_SERVER_CCS_AFTER_HELLO_RETRY_REQUEST:
3520             ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
3521             if (ret == 0) {
3522                 mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
3523             }
3524             break;
3525 
3526         case MBEDTLS_SSL_SERVER_CCS_AFTER_SERVER_HELLO:
3527             ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
3528             if (ret != 0) {
3529                 break;
3530             }
3531             mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS);
3532             break;
3533 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
3534 
3535         case MBEDTLS_SSL_SERVER_FINISHED:
3536             ret = ssl_tls13_write_server_finished(ssl);
3537             break;
3538 
3539 #if defined(MBEDTLS_SSL_EARLY_DATA)
3540         case MBEDTLS_SSL_END_OF_EARLY_DATA:
3541             ret = ssl_tls13_process_end_of_early_data(ssl);
3542             break;
3543 #endif /* MBEDTLS_SSL_EARLY_DATA */
3544 
3545         case MBEDTLS_SSL_CLIENT_FINISHED:
3546             ret = ssl_tls13_process_client_finished(ssl);
3547             break;
3548 
3549         case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
3550             ret = ssl_tls13_handshake_wrapup(ssl);
3551             break;
3552 
3553 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
3554         case MBEDTLS_SSL_CLIENT_CERTIFICATE:
3555             ret = mbedtls_ssl_tls13_process_certificate(ssl);
3556             if (ret == 0) {
3557                 if (ssl->session_negotiate->peer_cert != NULL) {
3558                     mbedtls_ssl_handshake_set_state(
3559                         ssl, MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY);
3560                 } else {
3561                     MBEDTLS_SSL_DEBUG_MSG(2, ("skip parse certificate verify"));
3562                     mbedtls_ssl_handshake_set_state(
3563                         ssl, MBEDTLS_SSL_CLIENT_FINISHED);
3564                 }
3565             }
3566             break;
3567 
3568         case MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY:
3569             ret = mbedtls_ssl_tls13_process_certificate_verify(ssl);
3570             if (ret == 0) {
3571                 mbedtls_ssl_handshake_set_state(
3572                     ssl, MBEDTLS_SSL_CLIENT_FINISHED);
3573             }
3574             break;
3575 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
3576 
3577 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3578         case MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET:
3579             ret = ssl_tls13_write_new_session_ticket(ssl);
3580             if (ret != 0) {
3581                 MBEDTLS_SSL_DEBUG_RET(1,
3582                                       "ssl_tls13_write_new_session_ticket ",
3583                                       ret);
3584             }
3585             break;
3586         case MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET_FLUSH:
3587             /* This state is necessary to do the flush of the New Session
3588              * Ticket message written in MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET
3589              * as part of ssl_prepare_handshake_step.
3590              */
3591             ret = 0;
3592 
3593             if (ssl->handshake->new_session_tickets_count == 0) {
3594                 mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
3595             } else {
3596                 mbedtls_ssl_handshake_set_state(
3597                     ssl, MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET);
3598             }
3599             break;
3600 
3601 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3602 
3603         default:
3604             MBEDTLS_SSL_DEBUG_MSG(1, ("invalid state %d", ssl->state));
3605             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3606     }
3607 
3608     return ret;
3609 }
3610 
3611 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_PROTO_TLS1_3 */
3612