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