xref: /optee_os/lib/libmbedtls/mbedtls/library/ssl_tls.c (revision 11fa71b9ddb429088f325cfda430183003ccd1db)
1 // SPDX-License-Identifier: Apache-2.0
2 /*
3  *  SSLv3/TLSv1 shared functions
4  *
5  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  This file is part of mbed TLS (https://tls.mbed.org)
20  */
21 /*
22  *  The SSL 3.0 specification was drafted by Netscape in 1996,
23  *  and became an IETF standard in 1999.
24  *
25  *  http://wp.netscape.com/eng/ssl3/
26  *  http://www.ietf.org/rfc/rfc2246.txt
27  *  http://www.ietf.org/rfc/rfc4346.txt
28  */
29 
30 #if !defined(MBEDTLS_CONFIG_FILE)
31 #include "mbedtls/config.h"
32 #else
33 #include MBEDTLS_CONFIG_FILE
34 #endif
35 
36 #if defined(MBEDTLS_SSL_TLS_C)
37 
38 #if defined(MBEDTLS_PLATFORM_C)
39 #include "mbedtls/platform.h"
40 #else
41 #include <stdlib.h>
42 #define mbedtls_calloc    calloc
43 #define mbedtls_free      free
44 #endif
45 
46 #include "mbedtls/ssl.h"
47 #include "mbedtls/ssl_internal.h"
48 #include "mbedtls/debug.h"
49 #include "mbedtls/error.h"
50 #include "mbedtls/platform_util.h"
51 #include "mbedtls/version.h"
52 
53 #include <string.h>
54 
55 #if defined(MBEDTLS_USE_PSA_CRYPTO)
56 #include "mbedtls/psa_util.h"
57 #include "psa/crypto.h"
58 #endif
59 
60 #if defined(MBEDTLS_X509_CRT_PARSE_C)
61 #include "mbedtls/oid.h"
62 #endif
63 
64 #if defined(MBEDTLS_SSL_PROTO_DTLS)
65 
66 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
67 /* Top-level Connection ID API */
68 
69 int mbedtls_ssl_conf_cid( mbedtls_ssl_config *conf,
70                           size_t len,
71                           int ignore_other_cid )
72 {
73     if( len > MBEDTLS_SSL_CID_IN_LEN_MAX )
74         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
75 
76     if( ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_FAIL &&
77         ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_IGNORE )
78     {
79         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
80     }
81 
82     conf->ignore_unexpected_cid = ignore_other_cid;
83     conf->cid_len = len;
84     return( 0 );
85 }
86 
87 int mbedtls_ssl_set_cid( mbedtls_ssl_context *ssl,
88                          int enable,
89                          unsigned char const *own_cid,
90                          size_t own_cid_len )
91 {
92     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
93         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
94 
95     ssl->negotiate_cid = enable;
96     if( enable == MBEDTLS_SSL_CID_DISABLED )
97     {
98         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Disable use of CID extension." ) );
99         return( 0 );
100     }
101     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Enable use of CID extension." ) );
102     MBEDTLS_SSL_DEBUG_BUF( 3, "Own CID", own_cid, own_cid_len );
103 
104     if( own_cid_len != ssl->conf->cid_len )
105     {
106         MBEDTLS_SSL_DEBUG_MSG( 3, ( "CID length %u does not match CID length %u in config",
107                                     (unsigned) own_cid_len,
108                                     (unsigned) ssl->conf->cid_len ) );
109         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
110     }
111 
112     memcpy( ssl->own_cid, own_cid, own_cid_len );
113     /* Truncation is not an issue here because
114      * MBEDTLS_SSL_CID_IN_LEN_MAX at most 255. */
115     ssl->own_cid_len = (uint8_t) own_cid_len;
116 
117     return( 0 );
118 }
119 
120 int mbedtls_ssl_get_peer_cid( mbedtls_ssl_context *ssl,
121                      int *enabled,
122                      unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ],
123                      size_t *peer_cid_len )
124 {
125     *enabled = MBEDTLS_SSL_CID_DISABLED;
126 
127     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
128         ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
129     {
130         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
131     }
132 
133     /* We report MBEDTLS_SSL_CID_DISABLED in case the CID extensions
134      * were used, but client and server requested the empty CID.
135      * This is indistinguishable from not using the CID extension
136      * in the first place. */
137     if( ssl->transform_in->in_cid_len  == 0 &&
138         ssl->transform_in->out_cid_len == 0 )
139     {
140         return( 0 );
141     }
142 
143     if( peer_cid_len != NULL )
144     {
145         *peer_cid_len = ssl->transform_in->out_cid_len;
146         if( peer_cid != NULL )
147         {
148             memcpy( peer_cid, ssl->transform_in->out_cid,
149                     ssl->transform_in->out_cid_len );
150         }
151     }
152 
153     *enabled = MBEDTLS_SSL_CID_ENABLED;
154 
155     return( 0 );
156 }
157 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
158 
159 #endif /* MBEDTLS_SSL_PROTO_DTLS */
160 
161 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
162 /*
163  * Convert max_fragment_length codes to length.
164  * RFC 6066 says:
165  *    enum{
166  *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
167  *    } MaxFragmentLength;
168  * and we add 0 -> extension unused
169  */
170 static unsigned int ssl_mfl_code_to_length( int mfl )
171 {
172     switch( mfl )
173     {
174     case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:
175         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
176     case MBEDTLS_SSL_MAX_FRAG_LEN_512:
177         return 512;
178     case MBEDTLS_SSL_MAX_FRAG_LEN_1024:
179         return 1024;
180     case MBEDTLS_SSL_MAX_FRAG_LEN_2048:
181         return 2048;
182     case MBEDTLS_SSL_MAX_FRAG_LEN_4096:
183         return 4096;
184     default:
185         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
186     }
187 }
188 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
189 
190 int mbedtls_ssl_session_copy( mbedtls_ssl_session *dst,
191                               const mbedtls_ssl_session *src )
192 {
193     mbedtls_ssl_session_free( dst );
194     memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
195 
196 #if defined(MBEDTLS_X509_CRT_PARSE_C)
197 
198 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
199     if( src->peer_cert != NULL )
200     {
201         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
202 
203         dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
204         if( dst->peer_cert == NULL )
205             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
206 
207         mbedtls_x509_crt_init( dst->peer_cert );
208 
209         if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
210                                         src->peer_cert->raw.len ) ) != 0 )
211         {
212             mbedtls_free( dst->peer_cert );
213             dst->peer_cert = NULL;
214             return( ret );
215         }
216     }
217 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
218     if( src->peer_cert_digest != NULL )
219     {
220         dst->peer_cert_digest =
221             mbedtls_calloc( 1, src->peer_cert_digest_len );
222         if( dst->peer_cert_digest == NULL )
223             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
224 
225         memcpy( dst->peer_cert_digest, src->peer_cert_digest,
226                 src->peer_cert_digest_len );
227         dst->peer_cert_digest_type = src->peer_cert_digest_type;
228         dst->peer_cert_digest_len = src->peer_cert_digest_len;
229     }
230 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
231 
232 #endif /* MBEDTLS_X509_CRT_PARSE_C */
233 
234 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
235     if( src->ticket != NULL )
236     {
237         dst->ticket = mbedtls_calloc( 1, src->ticket_len );
238         if( dst->ticket == NULL )
239             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
240 
241         memcpy( dst->ticket, src->ticket, src->ticket_len );
242     }
243 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
244 
245     return( 0 );
246 }
247 
248 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
249 static int resize_buffer( unsigned char **buffer, size_t len_new, size_t *len_old )
250 {
251     unsigned char* resized_buffer = mbedtls_calloc( 1, len_new );
252     if( resized_buffer == NULL )
253         return -1;
254 
255     /* We want to copy len_new bytes when downsizing the buffer, and
256      * len_old bytes when upsizing, so we choose the smaller of two sizes,
257      * to fit one buffer into another. Size checks, ensuring that no data is
258      * lost, are done outside of this function. */
259     memcpy( resized_buffer, *buffer,
260             ( len_new < *len_old ) ? len_new : *len_old );
261     mbedtls_platform_zeroize( *buffer, *len_old );
262     mbedtls_free( *buffer );
263 
264     *buffer = resized_buffer;
265     *len_old = len_new;
266 
267     return 0;
268 }
269 #endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */
270 
271 /*
272  * Key material generation
273  */
274 #if defined(MBEDTLS_SSL_PROTO_SSL3)
275 static int ssl3_prf( const unsigned char *secret, size_t slen,
276                      const char *label,
277                      const unsigned char *random, size_t rlen,
278                      unsigned char *dstbuf, size_t dlen )
279 {
280     int ret = 0;
281     size_t i;
282     mbedtls_md5_context md5;
283     mbedtls_sha1_context sha1;
284     unsigned char padding[16];
285     unsigned char sha1sum[20];
286     ((void)label);
287 
288     mbedtls_md5_init(  &md5  );
289     mbedtls_sha1_init( &sha1 );
290 
291     /*
292      *  SSLv3:
293      *    block =
294      *      MD5( secret + SHA1( 'A'    + secret + random ) ) +
295      *      MD5( secret + SHA1( 'BB'   + secret + random ) ) +
296      *      MD5( secret + SHA1( 'CCC'  + secret + random ) ) +
297      *      ...
298      */
299     for( i = 0; i < dlen / 16; i++ )
300     {
301         memset( padding, (unsigned char) ('A' + i), 1 + i );
302 
303         if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 )
304             goto exit;
305         if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 )
306             goto exit;
307         if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 )
308             goto exit;
309         if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 )
310             goto exit;
311         if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 )
312             goto exit;
313 
314         if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 )
315             goto exit;
316         if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 )
317             goto exit;
318         if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 )
319             goto exit;
320         if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 )
321             goto exit;
322     }
323 
324 exit:
325     mbedtls_md5_free(  &md5  );
326     mbedtls_sha1_free( &sha1 );
327 
328     mbedtls_platform_zeroize( padding, sizeof( padding ) );
329     mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
330 
331     return( ret );
332 }
333 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
334 
335 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
336 static int tls1_prf( const unsigned char *secret, size_t slen,
337                      const char *label,
338                      const unsigned char *random, size_t rlen,
339                      unsigned char *dstbuf, size_t dlen )
340 {
341     size_t nb, hs;
342     size_t i, j, k;
343     const unsigned char *S1, *S2;
344     unsigned char *tmp;
345     size_t tmp_len = 0;
346     unsigned char h_i[20];
347     const mbedtls_md_info_t *md_info;
348     mbedtls_md_context_t md_ctx;
349     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
350 
351     mbedtls_md_init( &md_ctx );
352 
353     tmp_len = 20 + strlen( label ) + rlen;
354     tmp = mbedtls_calloc( 1, tmp_len );
355     if( tmp == NULL )
356     {
357         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
358         goto exit;
359     }
360 
361     hs = ( slen + 1 ) / 2;
362     S1 = secret;
363     S2 = secret + slen - hs;
364 
365     nb = strlen( label );
366     memcpy( tmp + 20, label, nb );
367     memcpy( tmp + 20 + nb, random, rlen );
368     nb += rlen;
369 
370     /*
371      * First compute P_md5(secret,label+random)[0..dlen]
372      */
373     if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
374     {
375         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
376         goto exit;
377     }
378 
379     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
380     {
381         goto exit;
382     }
383 
384     mbedtls_md_hmac_starts( &md_ctx, S1, hs );
385     mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
386     mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
387 
388     for( i = 0; i < dlen; i += 16 )
389     {
390         mbedtls_md_hmac_reset ( &md_ctx );
391         mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
392         mbedtls_md_hmac_finish( &md_ctx, h_i );
393 
394         mbedtls_md_hmac_reset ( &md_ctx );
395         mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
396         mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
397 
398         k = ( i + 16 > dlen ) ? dlen % 16 : 16;
399 
400         for( j = 0; j < k; j++ )
401             dstbuf[i + j]  = h_i[j];
402     }
403 
404     mbedtls_md_free( &md_ctx );
405 
406     /*
407      * XOR out with P_sha1(secret,label+random)[0..dlen]
408      */
409     if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
410     {
411         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
412         goto exit;
413     }
414 
415     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
416     {
417         goto exit;
418     }
419 
420     mbedtls_md_hmac_starts( &md_ctx, S2, hs );
421     mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
422     mbedtls_md_hmac_finish( &md_ctx, tmp );
423 
424     for( i = 0; i < dlen; i += 20 )
425     {
426         mbedtls_md_hmac_reset ( &md_ctx );
427         mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
428         mbedtls_md_hmac_finish( &md_ctx, h_i );
429 
430         mbedtls_md_hmac_reset ( &md_ctx );
431         mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
432         mbedtls_md_hmac_finish( &md_ctx, tmp );
433 
434         k = ( i + 20 > dlen ) ? dlen % 20 : 20;
435 
436         for( j = 0; j < k; j++ )
437             dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
438     }
439 
440 exit:
441     mbedtls_md_free( &md_ctx );
442 
443     mbedtls_platform_zeroize( tmp, tmp_len );
444     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
445 
446     mbedtls_free( tmp );
447     return( ret );
448 }
449 #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
450 
451 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
452 #if defined(MBEDTLS_USE_PSA_CRYPTO)
453 
454 static psa_status_t setup_psa_key_derivation( psa_key_derivation_operation_t* derivation,
455                                               psa_key_handle_t slot,
456                                               psa_algorithm_t alg,
457                                               const unsigned char* seed, size_t seed_length,
458                                               const unsigned char* label, size_t label_length,
459                                               size_t capacity )
460 {
461     psa_status_t status;
462 
463     status = psa_key_derivation_setup( derivation, alg );
464     if( status != PSA_SUCCESS )
465         return( status );
466 
467     if( PSA_ALG_IS_TLS12_PRF( alg ) || PSA_ALG_IS_TLS12_PSK_TO_MS( alg ) )
468     {
469         status = psa_key_derivation_input_bytes( derivation,
470                                                  PSA_KEY_DERIVATION_INPUT_SEED,
471                                                  seed, seed_length );
472         if( status != PSA_SUCCESS )
473             return( status );
474 
475         if( slot == 0 )
476         {
477             status = psa_key_derivation_input_bytes(
478                 derivation, PSA_KEY_DERIVATION_INPUT_SECRET,
479                 NULL, 0 );
480         }
481         else
482         {
483             status = psa_key_derivation_input_key(
484                 derivation, PSA_KEY_DERIVATION_INPUT_SECRET,
485                 slot );
486         }
487         if( status != PSA_SUCCESS )
488             return( status );
489 
490         status = psa_key_derivation_input_bytes( derivation,
491                                                  PSA_KEY_DERIVATION_INPUT_LABEL,
492                                                  label, label_length );
493         if( status != PSA_SUCCESS )
494             return( status );
495     }
496     else
497     {
498         return( PSA_ERROR_NOT_SUPPORTED );
499     }
500 
501     status = psa_key_derivation_set_capacity( derivation, capacity );
502     if( status != PSA_SUCCESS )
503         return( status );
504 
505     return( PSA_SUCCESS );
506 }
507 
508 static int tls_prf_generic( mbedtls_md_type_t md_type,
509                             const unsigned char *secret, size_t slen,
510                             const char *label,
511                             const unsigned char *random, size_t rlen,
512                             unsigned char *dstbuf, size_t dlen )
513 {
514     psa_status_t status;
515     psa_algorithm_t alg;
516     psa_key_handle_t master_slot = 0;
517     psa_key_derivation_operation_t derivation =
518         PSA_KEY_DERIVATION_OPERATION_INIT;
519 
520     if( md_type == MBEDTLS_MD_SHA384 )
521         alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_384);
522     else
523         alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_256);
524 
525     /* Normally a "secret" should be long enough to be impossible to
526      * find by brute force, and in particular should not be empty. But
527      * this PRF is also used to derive an IV, in particular in EAP-TLS,
528      * and for this use case it makes sense to have a 0-length "secret".
529      * Since the key API doesn't allow importing a key of length 0,
530      * keep master_slot=0, which setup_psa_key_derivation() understands
531      * to mean a 0-length "secret" input. */
532     if( slen != 0 )
533     {
534         psa_key_attributes_t key_attributes = psa_key_attributes_init();
535         psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
536         psa_set_key_algorithm( &key_attributes, alg );
537         psa_set_key_type( &key_attributes, PSA_KEY_TYPE_DERIVE );
538 
539         status = psa_import_key( &key_attributes, secret, slen, &master_slot );
540         if( status != PSA_SUCCESS )
541             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
542     }
543 
544     status = setup_psa_key_derivation( &derivation,
545                                        master_slot, alg,
546                                        random, rlen,
547                                        (unsigned char const *) label,
548                                        (size_t) strlen( label ),
549                                        dlen );
550     if( status != PSA_SUCCESS )
551     {
552         psa_key_derivation_abort( &derivation );
553         psa_destroy_key( master_slot );
554         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
555     }
556 
557     status = psa_key_derivation_output_bytes( &derivation, dstbuf, dlen );
558     if( status != PSA_SUCCESS )
559     {
560         psa_key_derivation_abort( &derivation );
561         psa_destroy_key( master_slot );
562         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
563     }
564 
565     status = psa_key_derivation_abort( &derivation );
566     if( status != PSA_SUCCESS )
567     {
568         psa_destroy_key( master_slot );
569         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
570     }
571 
572     if( master_slot != 0 )
573         status = psa_destroy_key( master_slot );
574     if( status != PSA_SUCCESS )
575         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
576 
577     return( 0 );
578 }
579 
580 #else /* MBEDTLS_USE_PSA_CRYPTO */
581 
582 static int tls_prf_generic( mbedtls_md_type_t md_type,
583                             const unsigned char *secret, size_t slen,
584                             const char *label,
585                             const unsigned char *random, size_t rlen,
586                             unsigned char *dstbuf, size_t dlen )
587 {
588     size_t nb;
589     size_t i, j, k, md_len;
590     unsigned char *tmp;
591     size_t tmp_len = 0;
592     unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
593     const mbedtls_md_info_t *md_info;
594     mbedtls_md_context_t md_ctx;
595     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
596 
597     mbedtls_md_init( &md_ctx );
598 
599     if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
600         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
601 
602     md_len = mbedtls_md_get_size( md_info );
603 
604     tmp_len = md_len + strlen( label ) + rlen;
605     tmp = mbedtls_calloc( 1, tmp_len );
606     if( tmp == NULL )
607     {
608         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
609         goto exit;
610     }
611 
612     nb = strlen( label );
613     memcpy( tmp + md_len, label, nb );
614     memcpy( tmp + md_len + nb, random, rlen );
615     nb += rlen;
616 
617     /*
618      * Compute P_<hash>(secret, label + random)[0..dlen]
619      */
620     if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
621         goto exit;
622 
623     mbedtls_md_hmac_starts( &md_ctx, secret, slen );
624     mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
625     mbedtls_md_hmac_finish( &md_ctx, tmp );
626 
627     for( i = 0; i < dlen; i += md_len )
628     {
629         mbedtls_md_hmac_reset ( &md_ctx );
630         mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
631         mbedtls_md_hmac_finish( &md_ctx, h_i );
632 
633         mbedtls_md_hmac_reset ( &md_ctx );
634         mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
635         mbedtls_md_hmac_finish( &md_ctx, tmp );
636 
637         k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
638 
639         for( j = 0; j < k; j++ )
640             dstbuf[i + j]  = h_i[j];
641     }
642 
643 exit:
644     mbedtls_md_free( &md_ctx );
645 
646     mbedtls_platform_zeroize( tmp, tmp_len );
647     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
648 
649     mbedtls_free( tmp );
650 
651     return( ret );
652 }
653 #endif /* MBEDTLS_USE_PSA_CRYPTO */
654 #if defined(MBEDTLS_SHA256_C)
655 static int tls_prf_sha256( const unsigned char *secret, size_t slen,
656                            const char *label,
657                            const unsigned char *random, size_t rlen,
658                            unsigned char *dstbuf, size_t dlen )
659 {
660     return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
661                              label, random, rlen, dstbuf, dlen ) );
662 }
663 #endif /* MBEDTLS_SHA256_C */
664 
665 #if defined(MBEDTLS_SHA512_C)
666 static int tls_prf_sha384( const unsigned char *secret, size_t slen,
667                            const char *label,
668                            const unsigned char *random, size_t rlen,
669                            unsigned char *dstbuf, size_t dlen )
670 {
671     return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
672                              label, random, rlen, dstbuf, dlen ) );
673 }
674 #endif /* MBEDTLS_SHA512_C */
675 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
676 
677 static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
678 
679 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
680     defined(MBEDTLS_SSL_PROTO_TLS1_1)
681 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
682 #endif
683 
684 #if defined(MBEDTLS_SSL_PROTO_SSL3)
685 static void ssl_calc_verify_ssl( const mbedtls_ssl_context *, unsigned char *, size_t * );
686 static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
687 #endif
688 
689 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
690 static void ssl_calc_verify_tls( const mbedtls_ssl_context *, unsigned char *, size_t * );
691 static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
692 #endif
693 
694 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
695 #if defined(MBEDTLS_SHA256_C)
696 static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
697 static void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *,unsigned char *, size_t * );
698 static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
699 #endif
700 
701 #if defined(MBEDTLS_SHA512_C)
702 static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
703 static void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *, unsigned char *, size_t * );
704 static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
705 #endif
706 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
707 
708 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) && \
709     defined(MBEDTLS_USE_PSA_CRYPTO)
710 static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl )
711 {
712     if( ssl->conf->f_psk != NULL )
713     {
714         /* If we've used a callback to select the PSK,
715          * the static configuration is irrelevant. */
716         if( ssl->handshake->psk_opaque != 0 )
717             return( 1 );
718 
719         return( 0 );
720     }
721 
722     if( ssl->conf->psk_opaque != 0 )
723         return( 1 );
724 
725     return( 0 );
726 }
727 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
728           MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
729 
730 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
731 static mbedtls_tls_prf_types tls_prf_get_type( mbedtls_ssl_tls_prf_cb *tls_prf )
732 {
733 #if defined(MBEDTLS_SSL_PROTO_SSL3)
734     if( tls_prf == ssl3_prf )
735     {
736         return( MBEDTLS_SSL_TLS_PRF_SSL3 );
737     }
738     else
739 #endif
740 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
741     if( tls_prf == tls1_prf )
742     {
743         return( MBEDTLS_SSL_TLS_PRF_TLS1 );
744     }
745     else
746 #endif
747 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
748 #if defined(MBEDTLS_SHA512_C)
749     if( tls_prf == tls_prf_sha384 )
750     {
751         return( MBEDTLS_SSL_TLS_PRF_SHA384 );
752     }
753     else
754 #endif
755 #if defined(MBEDTLS_SHA256_C)
756     if( tls_prf == tls_prf_sha256 )
757     {
758         return( MBEDTLS_SSL_TLS_PRF_SHA256 );
759     }
760     else
761 #endif
762 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
763     return( MBEDTLS_SSL_TLS_PRF_NONE );
764 }
765 #endif /* MBEDTLS_SSL_EXPORT_KEYS */
766 
767 int  mbedtls_ssl_tls_prf( const mbedtls_tls_prf_types prf,
768                           const unsigned char *secret, size_t slen,
769                           const char *label,
770                           const unsigned char *random, size_t rlen,
771                           unsigned char *dstbuf, size_t dlen )
772 {
773     mbedtls_ssl_tls_prf_cb *tls_prf = NULL;
774 
775     switch( prf )
776     {
777 #if defined(MBEDTLS_SSL_PROTO_SSL3)
778         case MBEDTLS_SSL_TLS_PRF_SSL3:
779             tls_prf = ssl3_prf;
780         break;
781 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
782 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
783         case MBEDTLS_SSL_TLS_PRF_TLS1:
784             tls_prf = tls1_prf;
785         break;
786 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
787 
788 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
789 #if defined(MBEDTLS_SHA512_C)
790         case MBEDTLS_SSL_TLS_PRF_SHA384:
791             tls_prf = tls_prf_sha384;
792         break;
793 #endif /* MBEDTLS_SHA512_C */
794 #if defined(MBEDTLS_SHA256_C)
795         case MBEDTLS_SSL_TLS_PRF_SHA256:
796             tls_prf = tls_prf_sha256;
797         break;
798 #endif /* MBEDTLS_SHA256_C */
799 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
800     default:
801         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
802     }
803 
804     return( tls_prf( secret, slen, label, random, rlen, dstbuf, dlen ) );
805 }
806 
807 /* Type for the TLS PRF */
808 typedef int ssl_tls_prf_t(const unsigned char *, size_t, const char *,
809                           const unsigned char *, size_t,
810                           unsigned char *, size_t);
811 
812 /*
813  * Populate a transform structure with session keys and all the other
814  * necessary information.
815  *
816  * Parameters:
817  * - [in/out]: transform: structure to populate
818  *      [in] must be just initialised with mbedtls_ssl_transform_init()
819  *      [out] fully populated, ready for use by mbedtls_ssl_{en,de}crypt_buf()
820  * - [in] ciphersuite
821  * - [in] master
822  * - [in] encrypt_then_mac
823  * - [in] trunc_hmac
824  * - [in] compression
825  * - [in] tls_prf: pointer to PRF to use for key derivation
826  * - [in] randbytes: buffer holding ServerHello.random + ClientHello.random
827  * - [in] minor_ver: SSL/TLS minor version
828  * - [in] endpoint: client or server
829  * - [in] ssl: optionally used for:
830  *        - MBEDTLS_SSL_HW_RECORD_ACCEL: whole context (non-const)
831  *        - MBEDTLS_SSL_EXPORT_KEYS: ssl->conf->{f,p}_export_keys
832  *        - MBEDTLS_DEBUG_C: ssl->conf->{f,p}_dbg
833  */
834 static int ssl_populate_transform( mbedtls_ssl_transform *transform,
835                                    int ciphersuite,
836                                    const unsigned char master[48],
837 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
838 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
839                                    int encrypt_then_mac,
840 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
841 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
842                                    int trunc_hmac,
843 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
844 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
845 #if defined(MBEDTLS_ZLIB_SUPPORT)
846                                    int compression,
847 #endif
848                                    ssl_tls_prf_t tls_prf,
849                                    const unsigned char randbytes[64],
850                                    int minor_ver,
851                                    unsigned endpoint,
852 #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
853                                    const
854 #endif
855                                    mbedtls_ssl_context *ssl )
856 {
857     int ret = 0;
858 #if defined(MBEDTLS_USE_PSA_CRYPTO)
859     int psa_fallthrough;
860 #endif /* MBEDTLS_USE_PSA_CRYPTO */
861     unsigned char keyblk[256];
862     unsigned char *key1;
863     unsigned char *key2;
864     unsigned char *mac_enc;
865     unsigned char *mac_dec;
866     size_t mac_key_len;
867     size_t iv_copy_len;
868     unsigned keylen;
869     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
870     const mbedtls_cipher_info_t *cipher_info;
871     const mbedtls_md_info_t *md_info;
872 
873 #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL) && \
874     !defined(MBEDTLS_SSL_EXPORT_KEYS) && \
875     !defined(MBEDTLS_DEBUG_C)
876     ssl = NULL; /* make sure we don't use it except for those cases */
877     (void) ssl;
878 #endif
879 
880     /*
881      * Some data just needs copying into the structure
882      */
883 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \
884     defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
885     transform->encrypt_then_mac = encrypt_then_mac;
886 #endif
887     transform->minor_ver = minor_ver;
888 
889 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
890     memcpy( transform->randbytes, randbytes, sizeof( transform->randbytes ) );
891 #endif
892 
893     /*
894      * Get various info structures
895      */
896     ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuite );
897     if( ciphersuite_info == NULL )
898     {
899         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %d not found",
900                                     ciphersuite ) );
901         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
902     }
903 
904     cipher_info = mbedtls_cipher_info_from_type( ciphersuite_info->cipher );
905     if( cipher_info == NULL )
906     {
907         MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
908                                     ciphersuite_info->cipher ) );
909         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
910     }
911 
912     md_info = mbedtls_md_info_from_type( ciphersuite_info->mac );
913     if( md_info == NULL )
914     {
915         MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
916                             ciphersuite_info->mac ) );
917         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
918     }
919 
920 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
921     /* Copy own and peer's CID if the use of the CID
922      * extension has been negotiated. */
923     if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_ENABLED )
924     {
925         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Copy CIDs into SSL transform" ) );
926 
927         transform->in_cid_len = ssl->own_cid_len;
928         memcpy( transform->in_cid, ssl->own_cid, ssl->own_cid_len );
929         MBEDTLS_SSL_DEBUG_BUF( 3, "Incoming CID", transform->in_cid,
930                                transform->in_cid_len );
931 
932         transform->out_cid_len = ssl->handshake->peer_cid_len;
933         memcpy( transform->out_cid, ssl->handshake->peer_cid,
934                 ssl->handshake->peer_cid_len );
935         MBEDTLS_SSL_DEBUG_BUF( 3, "Outgoing CID", transform->out_cid,
936                                transform->out_cid_len );
937     }
938 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
939 
940     /*
941      * Compute key block using the PRF
942      */
943     ret = tls_prf( master, 48, "key expansion", randbytes, 64, keyblk, 256 );
944     if( ret != 0 )
945     {
946         MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
947         return( ret );
948     }
949 
950     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
951                            mbedtls_ssl_get_ciphersuite_name( ciphersuite ) ) );
952     MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", master, 48 );
953     MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", randbytes, 64 );
954     MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
955 
956     /*
957      * Determine the appropriate key, IV and MAC length.
958      */
959 
960     keylen = cipher_info->key_bitlen / 8;
961 
962 #if defined(MBEDTLS_GCM_C) ||                           \
963     defined(MBEDTLS_CCM_C) ||                           \
964     defined(MBEDTLS_CHACHAPOLY_C)
965     if( cipher_info->mode == MBEDTLS_MODE_GCM ||
966         cipher_info->mode == MBEDTLS_MODE_CCM ||
967         cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
968     {
969         size_t explicit_ivlen;
970 
971         transform->maclen = 0;
972         mac_key_len = 0;
973         transform->taglen =
974             ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
975 
976         /* All modes haves 96-bit IVs;
977          * GCM and CCM has 4 implicit and 8 explicit bytes
978          * ChachaPoly has all 12 bytes implicit
979          */
980         transform->ivlen = 12;
981         if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
982             transform->fixed_ivlen = 12;
983         else
984             transform->fixed_ivlen = 4;
985 
986         /* Minimum length of encrypted record */
987         explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
988         transform->minlen = explicit_ivlen + transform->taglen;
989     }
990     else
991 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
992 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
993     if( cipher_info->mode == MBEDTLS_MODE_STREAM ||
994         cipher_info->mode == MBEDTLS_MODE_CBC )
995     {
996         /* Initialize HMAC contexts */
997         if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
998             ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
999         {
1000             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
1001             goto end;
1002         }
1003 
1004         /* Get MAC length */
1005         mac_key_len = mbedtls_md_get_size( md_info );
1006         transform->maclen = mac_key_len;
1007 
1008 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1009         /*
1010          * If HMAC is to be truncated, we shall keep the leftmost bytes,
1011          * (rfc 6066 page 13 or rfc 2104 section 4),
1012          * so we only need to adjust the length here.
1013          */
1014         if( trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
1015         {
1016             transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
1017 
1018 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
1019             /* Fall back to old, non-compliant version of the truncated
1020              * HMAC implementation which also truncates the key
1021              * (Mbed TLS versions from 1.3 to 2.6.0) */
1022             mac_key_len = transform->maclen;
1023 #endif
1024         }
1025 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1026 
1027         /* IV length */
1028         transform->ivlen = cipher_info->iv_size;
1029 
1030         /* Minimum length */
1031         if( cipher_info->mode == MBEDTLS_MODE_STREAM )
1032             transform->minlen = transform->maclen;
1033         else
1034         {
1035             /*
1036              * GenericBlockCipher:
1037              * 1. if EtM is in use: one block plus MAC
1038              *    otherwise: * first multiple of blocklen greater than maclen
1039              * 2. IV except for SSL3 and TLS 1.0
1040              */
1041 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1042             if( encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
1043             {
1044                 transform->minlen = transform->maclen
1045                                   + cipher_info->block_size;
1046             }
1047             else
1048 #endif
1049             {
1050                 transform->minlen = transform->maclen
1051                                   + cipher_info->block_size
1052                                   - transform->maclen % cipher_info->block_size;
1053             }
1054 
1055 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1056             if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
1057                 minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
1058                 ; /* No need to adjust minlen */
1059             else
1060 #endif
1061 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1062             if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
1063                 minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
1064             {
1065                 transform->minlen += transform->ivlen;
1066             }
1067             else
1068 #endif
1069             {
1070                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1071                 ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1072                 goto end;
1073             }
1074         }
1075     }
1076     else
1077 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1078     {
1079         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1080         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1081     }
1082 
1083     MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %u, minlen: %u, ivlen: %u, maclen: %u",
1084                                 (unsigned) keylen,
1085                                 (unsigned) transform->minlen,
1086                                 (unsigned) transform->ivlen,
1087                                 (unsigned) transform->maclen ) );
1088 
1089     /*
1090      * Finally setup the cipher contexts, IVs and MAC secrets.
1091      */
1092 #if defined(MBEDTLS_SSL_CLI_C)
1093     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
1094     {
1095         key1 = keyblk + mac_key_len * 2;
1096         key2 = keyblk + mac_key_len * 2 + keylen;
1097 
1098         mac_enc = keyblk;
1099         mac_dec = keyblk + mac_key_len;
1100 
1101         /*
1102          * This is not used in TLS v1.1.
1103          */
1104         iv_copy_len = ( transform->fixed_ivlen ) ?
1105                             transform->fixed_ivlen : transform->ivlen;
1106         memcpy( transform->iv_enc, key2 + keylen,  iv_copy_len );
1107         memcpy( transform->iv_dec, key2 + keylen + iv_copy_len,
1108                 iv_copy_len );
1109     }
1110     else
1111 #endif /* MBEDTLS_SSL_CLI_C */
1112 #if defined(MBEDTLS_SSL_SRV_C)
1113     if( endpoint == MBEDTLS_SSL_IS_SERVER )
1114     {
1115         key1 = keyblk + mac_key_len * 2 + keylen;
1116         key2 = keyblk + mac_key_len * 2;
1117 
1118         mac_enc = keyblk + mac_key_len;
1119         mac_dec = keyblk;
1120 
1121         /*
1122          * This is not used in TLS v1.1.
1123          */
1124         iv_copy_len = ( transform->fixed_ivlen ) ?
1125                             transform->fixed_ivlen : transform->ivlen;
1126         memcpy( transform->iv_dec, key1 + keylen,  iv_copy_len );
1127         memcpy( transform->iv_enc, key1 + keylen + iv_copy_len,
1128                 iv_copy_len );
1129     }
1130     else
1131 #endif /* MBEDTLS_SSL_SRV_C */
1132     {
1133         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1134         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1135         goto end;
1136     }
1137 
1138 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1139 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1140     if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1141     {
1142         if( mac_key_len > sizeof( transform->mac_enc ) )
1143         {
1144             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1145             ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1146             goto end;
1147         }
1148 
1149         memcpy( transform->mac_enc, mac_enc, mac_key_len );
1150         memcpy( transform->mac_dec, mac_dec, mac_key_len );
1151     }
1152     else
1153 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1154 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1155     defined(MBEDTLS_SSL_PROTO_TLS1_2)
1156     if( minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
1157     {
1158         /* For HMAC-based ciphersuites, initialize the HMAC transforms.
1159            For AEAD-based ciphersuites, there is nothing to do here. */
1160         if( mac_key_len != 0 )
1161         {
1162             mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
1163             mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
1164         }
1165     }
1166     else
1167 #endif
1168     {
1169         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1170         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1171         goto end;
1172     }
1173 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1174 
1175 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
1176     if( mbedtls_ssl_hw_record_init != NULL )
1177     {
1178         int ret = 0;
1179 
1180         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
1181 
1182         if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, keylen,
1183                                         transform->iv_enc, transform->iv_dec,
1184                                         iv_copy_len,
1185                                         mac_enc, mac_dec,
1186                                         mac_key_len ) ) != 0 )
1187         {
1188             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
1189             ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
1190             goto end;
1191         }
1192     }
1193 #else
1194     ((void) mac_dec);
1195     ((void) mac_enc);
1196 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
1197 
1198 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
1199     if( ssl->conf->f_export_keys != NULL )
1200     {
1201         ssl->conf->f_export_keys( ssl->conf->p_export_keys,
1202                                   master, keyblk,
1203                                   mac_key_len, keylen,
1204                                   iv_copy_len );
1205     }
1206 
1207     if( ssl->conf->f_export_keys_ext != NULL )
1208     {
1209         ssl->conf->f_export_keys_ext( ssl->conf->p_export_keys,
1210                                       master, keyblk,
1211                                       mac_key_len, keylen,
1212                                       iv_copy_len,
1213                                       randbytes + 32,
1214                                       randbytes,
1215                                       tls_prf_get_type( tls_prf ) );
1216     }
1217 #endif
1218 
1219 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1220 
1221     /* Only use PSA-based ciphers for TLS-1.2.
1222      * That's relevant at least for TLS-1.0, where
1223      * we assume that mbedtls_cipher_crypt() updates
1224      * the structure field for the IV, which the PSA-based
1225      * implementation currently doesn't. */
1226 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1227     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
1228     {
1229         ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_enc,
1230                                         cipher_info, transform->taglen );
1231         if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
1232         {
1233             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret );
1234             goto end;
1235         }
1236 
1237         if( ret == 0 )
1238         {
1239             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Successfully setup PSA-based encryption cipher context" ) );
1240             psa_fallthrough = 0;
1241         }
1242         else
1243         {
1244             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record encryption - fall through to default setup." ) );
1245             psa_fallthrough = 1;
1246         }
1247     }
1248     else
1249         psa_fallthrough = 1;
1250 #else
1251     psa_fallthrough = 1;
1252 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1253 
1254     if( psa_fallthrough == 1 )
1255 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1256     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
1257                                  cipher_info ) ) != 0 )
1258     {
1259         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
1260         goto end;
1261     }
1262 
1263 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1264     /* Only use PSA-based ciphers for TLS-1.2.
1265      * That's relevant at least for TLS-1.0, where
1266      * we assume that mbedtls_cipher_crypt() updates
1267      * the structure field for the IV, which the PSA-based
1268      * implementation currently doesn't. */
1269 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1270     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
1271     {
1272         ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_dec,
1273                                         cipher_info, transform->taglen );
1274         if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
1275         {
1276             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret );
1277             goto end;
1278         }
1279 
1280         if( ret == 0 )
1281         {
1282             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Successfully setup PSA-based decryption cipher context" ) );
1283             psa_fallthrough = 0;
1284         }
1285         else
1286         {
1287             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record decryption - fall through to default setup." ) );
1288             psa_fallthrough = 1;
1289         }
1290     }
1291     else
1292         psa_fallthrough = 1;
1293 #else
1294     psa_fallthrough = 1;
1295 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1296 
1297     if( psa_fallthrough == 1 )
1298 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1299     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
1300                                  cipher_info ) ) != 0 )
1301     {
1302         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
1303         goto end;
1304     }
1305 
1306     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
1307                                cipher_info->key_bitlen,
1308                                MBEDTLS_ENCRYPT ) ) != 0 )
1309     {
1310         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
1311         goto end;
1312     }
1313 
1314     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
1315                                cipher_info->key_bitlen,
1316                                MBEDTLS_DECRYPT ) ) != 0 )
1317     {
1318         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
1319         goto end;
1320     }
1321 
1322 #if defined(MBEDTLS_CIPHER_MODE_CBC)
1323     if( cipher_info->mode == MBEDTLS_MODE_CBC )
1324     {
1325         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
1326                                              MBEDTLS_PADDING_NONE ) ) != 0 )
1327         {
1328             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
1329             goto end;
1330         }
1331 
1332         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
1333                                              MBEDTLS_PADDING_NONE ) ) != 0 )
1334         {
1335             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
1336             goto end;
1337         }
1338     }
1339 #endif /* MBEDTLS_CIPHER_MODE_CBC */
1340 
1341 
1342     /* Initialize Zlib contexts */
1343 #if defined(MBEDTLS_ZLIB_SUPPORT)
1344     if( compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
1345     {
1346         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
1347 
1348         memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
1349         memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
1350 
1351         if( deflateInit( &transform->ctx_deflate,
1352                          Z_DEFAULT_COMPRESSION )   != Z_OK ||
1353             inflateInit( &transform->ctx_inflate ) != Z_OK )
1354         {
1355             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
1356             ret = MBEDTLS_ERR_SSL_COMPRESSION_FAILED;
1357             goto end;
1358         }
1359     }
1360 #endif /* MBEDTLS_ZLIB_SUPPORT */
1361 
1362 end:
1363     mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );
1364     return( ret );
1365 }
1366 
1367 /*
1368  * Set appropriate PRF function and other SSL / TLS 1.0/1.1 / TLS1.2 functions
1369  *
1370  * Inputs:
1371  * - SSL/TLS minor version
1372  * - hash associated with the ciphersuite (only used by TLS 1.2)
1373  *
1374  * Outputs:
1375  * - the tls_prf, calc_verify and calc_finished members of handshake structure
1376  */
1377 static int ssl_set_handshake_prfs( mbedtls_ssl_handshake_params *handshake,
1378                                    int minor_ver,
1379                                    mbedtls_md_type_t hash )
1380 {
1381 #if !defined(MBEDTLS_SSL_PROTO_TLS1_2) || !defined(MBEDTLS_SHA512_C)
1382     (void) hash;
1383 #endif
1384 
1385 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1386     if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
1387     {
1388         handshake->tls_prf = ssl3_prf;
1389         handshake->calc_verify = ssl_calc_verify_ssl;
1390         handshake->calc_finished = ssl_calc_finished_ssl;
1391     }
1392     else
1393 #endif
1394 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1395     if( minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
1396     {
1397         handshake->tls_prf = tls1_prf;
1398         handshake->calc_verify = ssl_calc_verify_tls;
1399         handshake->calc_finished = ssl_calc_finished_tls;
1400     }
1401     else
1402 #endif
1403 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1404 #if defined(MBEDTLS_SHA512_C)
1405     if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
1406         hash == MBEDTLS_MD_SHA384 )
1407     {
1408         handshake->tls_prf = tls_prf_sha384;
1409         handshake->calc_verify = ssl_calc_verify_tls_sha384;
1410         handshake->calc_finished = ssl_calc_finished_tls_sha384;
1411     }
1412     else
1413 #endif
1414 #if defined(MBEDTLS_SHA256_C)
1415     if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
1416     {
1417         handshake->tls_prf = tls_prf_sha256;
1418         handshake->calc_verify = ssl_calc_verify_tls_sha256;
1419         handshake->calc_finished = ssl_calc_finished_tls_sha256;
1420     }
1421     else
1422 #endif
1423 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1424     {
1425         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1426     }
1427 
1428     return( 0 );
1429 }
1430 
1431 /*
1432  * Compute master secret if needed
1433  *
1434  * Parameters:
1435  * [in/out] handshake
1436  *          [in] resume, premaster, extended_ms, calc_verify, tls_prf
1437  *               (PSA-PSK) ciphersuite_info, psk_opaque
1438  *          [out] premaster (cleared)
1439  * [out] master
1440  * [in] ssl: optionally used for debugging, EMS and PSA-PSK
1441  *      debug: conf->f_dbg, conf->p_dbg
1442  *      EMS: passed to calc_verify (debug + (SSL3) session_negotiate)
1443  *      PSA-PSA: minor_ver, conf
1444  */
1445 static int ssl_compute_master( mbedtls_ssl_handshake_params *handshake,
1446                                unsigned char *master,
1447                                const mbedtls_ssl_context *ssl )
1448 {
1449     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1450 
1451     /* cf. RFC 5246, Section 8.1:
1452      * "The master secret is always exactly 48 bytes in length." */
1453     size_t const master_secret_len = 48;
1454 
1455 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1456     unsigned char session_hash[48];
1457 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1458 
1459     /* The label for the KDF used for key expansion.
1460      * This is either "master secret" or "extended master secret"
1461      * depending on whether the Extended Master Secret extension
1462      * is used. */
1463     char const *lbl = "master secret";
1464 
1465     /* The salt for the KDF used for key expansion.
1466      * - If the Extended Master Secret extension is not used,
1467      *   this is ClientHello.Random + ServerHello.Random
1468      *   (see Sect. 8.1 in RFC 5246).
1469      * - If the Extended Master Secret extension is used,
1470      *   this is the transcript of the handshake so far.
1471      *   (see Sect. 4 in RFC 7627). */
1472     unsigned char const *salt = handshake->randbytes;
1473     size_t salt_len = 64;
1474 
1475 #if !defined(MBEDTLS_DEBUG_C) &&                    \
1476     !defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \
1477     !(defined(MBEDTLS_USE_PSA_CRYPTO) &&            \
1478       defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED))
1479     ssl = NULL; /* make sure we don't use it except for those cases */
1480     (void) ssl;
1481 #endif
1482 
1483     if( handshake->resume != 0 )
1484     {
1485         MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
1486         return( 0 );
1487     }
1488 
1489 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1490     if( handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
1491     {
1492         lbl  = "extended master secret";
1493         salt = session_hash;
1494         handshake->calc_verify( ssl, session_hash, &salt_len );
1495 
1496         MBEDTLS_SSL_DEBUG_BUF( 3, "session hash for extended master secret",
1497                                   session_hash, salt_len );
1498     }
1499 #endif /* MBEDTLS_SSL_EXTENDED_MS_ENABLED */
1500 
1501 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&          \
1502     defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1503     if( handshake->ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK &&
1504         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
1505         ssl_use_opaque_psk( ssl ) == 1 )
1506     {
1507         /* Perform PSK-to-MS expansion in a single step. */
1508         psa_status_t status;
1509         psa_algorithm_t alg;
1510         psa_key_handle_t psk;
1511         psa_key_derivation_operation_t derivation =
1512             PSA_KEY_DERIVATION_OPERATION_INIT;
1513         mbedtls_md_type_t hash_alg = handshake->ciphersuite_info->mac;
1514 
1515         MBEDTLS_SSL_DEBUG_MSG( 2, ( "perform PSA-based PSK-to-MS expansion" ) );
1516 
1517         psk = ssl->conf->psk_opaque;
1518         if( handshake->psk_opaque != 0 )
1519             psk = handshake->psk_opaque;
1520 
1521         if( hash_alg == MBEDTLS_MD_SHA384 )
1522             alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384);
1523         else
1524             alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256);
1525 
1526         status = setup_psa_key_derivation( &derivation, psk, alg,
1527                                            salt, salt_len,
1528                                            (unsigned char const *) lbl,
1529                                            (size_t) strlen( lbl ),
1530                                            master_secret_len );
1531         if( status != PSA_SUCCESS )
1532         {
1533             psa_key_derivation_abort( &derivation );
1534             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
1535         }
1536 
1537         status = psa_key_derivation_output_bytes( &derivation,
1538                                                   master,
1539                                                   master_secret_len );
1540         if( status != PSA_SUCCESS )
1541         {
1542             psa_key_derivation_abort( &derivation );
1543             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
1544         }
1545 
1546         status = psa_key_derivation_abort( &derivation );
1547         if( status != PSA_SUCCESS )
1548             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
1549     }
1550     else
1551 #endif
1552     {
1553         ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
1554                                   lbl, salt, salt_len,
1555                                   master,
1556                                   master_secret_len );
1557         if( ret != 0 )
1558         {
1559             MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
1560             return( ret );
1561         }
1562 
1563         MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret",
1564                                handshake->premaster,
1565                                handshake->pmslen );
1566 
1567         mbedtls_platform_zeroize( handshake->premaster,
1568                                   sizeof(handshake->premaster) );
1569     }
1570 
1571     return( 0 );
1572 }
1573 
1574 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
1575 {
1576     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1577     const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
1578         ssl->handshake->ciphersuite_info;
1579 
1580     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
1581 
1582     /* Set PRF, calc_verify and calc_finished function pointers */
1583     ret = ssl_set_handshake_prfs( ssl->handshake,
1584                                   ssl->minor_ver,
1585                                   ciphersuite_info->mac );
1586     if( ret != 0 )
1587     {
1588         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_set_handshake_prfs", ret );
1589         return( ret );
1590     }
1591 
1592     /* Compute master secret if needed */
1593     ret = ssl_compute_master( ssl->handshake,
1594                               ssl->session_negotiate->master,
1595                               ssl );
1596     if( ret != 0 )
1597     {
1598         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compute_master", ret );
1599         return( ret );
1600     }
1601 
1602     /* Swap the client and server random values:
1603      * - MS derivation wanted client+server (RFC 5246 8.1)
1604      * - key derivation wants server+client (RFC 5246 6.3) */
1605     {
1606         unsigned char tmp[64];
1607         memcpy( tmp, ssl->handshake->randbytes, 64 );
1608         memcpy( ssl->handshake->randbytes, tmp + 32, 32 );
1609         memcpy( ssl->handshake->randbytes + 32, tmp, 32 );
1610         mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
1611     }
1612 
1613     /* Populate transform structure */
1614     ret = ssl_populate_transform( ssl->transform_negotiate,
1615                                   ssl->session_negotiate->ciphersuite,
1616                                   ssl->session_negotiate->master,
1617 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1618 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1619                                   ssl->session_negotiate->encrypt_then_mac,
1620 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1621 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1622                                   ssl->session_negotiate->trunc_hmac,
1623 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1624 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1625 #if defined(MBEDTLS_ZLIB_SUPPORT)
1626                                   ssl->session_negotiate->compression,
1627 #endif
1628                                   ssl->handshake->tls_prf,
1629                                   ssl->handshake->randbytes,
1630                                   ssl->minor_ver,
1631                                   ssl->conf->endpoint,
1632                                   ssl );
1633     if( ret != 0 )
1634     {
1635         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_populate_transform", ret );
1636         return( ret );
1637     }
1638 
1639     /* We no longer need Server/ClientHello.random values */
1640     mbedtls_platform_zeroize( ssl->handshake->randbytes,
1641                       sizeof( ssl->handshake->randbytes ) );
1642 
1643     /* Allocate compression buffer */
1644 #if defined(MBEDTLS_ZLIB_SUPPORT)
1645     if( ssl->session_negotiate->compression == MBEDTLS_SSL_COMPRESS_DEFLATE &&
1646         ssl->compress_buf == NULL )
1647     {
1648         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
1649         ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
1650         if( ssl->compress_buf == NULL )
1651         {
1652             MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
1653                                         MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) );
1654             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
1655         }
1656     }
1657 #endif
1658 
1659     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
1660 
1661     return( 0 );
1662 }
1663 
1664 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1665 void ssl_calc_verify_ssl( const mbedtls_ssl_context *ssl,
1666                           unsigned char hash[36],
1667                           size_t *hlen )
1668 {
1669     mbedtls_md5_context md5;
1670     mbedtls_sha1_context sha1;
1671     unsigned char pad_1[48];
1672     unsigned char pad_2[48];
1673 
1674     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
1675 
1676     mbedtls_md5_init( &md5 );
1677     mbedtls_sha1_init( &sha1 );
1678 
1679     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
1680     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
1681 
1682     memset( pad_1, 0x36, 48 );
1683     memset( pad_2, 0x5C, 48 );
1684 
1685     mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
1686     mbedtls_md5_update_ret( &md5, pad_1, 48 );
1687     mbedtls_md5_finish_ret( &md5, hash );
1688 
1689     mbedtls_md5_starts_ret( &md5 );
1690     mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
1691     mbedtls_md5_update_ret( &md5, pad_2, 48 );
1692     mbedtls_md5_update_ret( &md5, hash,  16 );
1693     mbedtls_md5_finish_ret( &md5, hash );
1694 
1695     mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
1696     mbedtls_sha1_update_ret( &sha1, pad_1, 40 );
1697     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
1698 
1699     mbedtls_sha1_starts_ret( &sha1 );
1700     mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
1701     mbedtls_sha1_update_ret( &sha1, pad_2, 40 );
1702     mbedtls_sha1_update_ret( &sha1, hash + 16, 20 );
1703     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
1704 
1705     *hlen = 36;
1706 
1707     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
1708     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1709 
1710     mbedtls_md5_free(  &md5  );
1711     mbedtls_sha1_free( &sha1 );
1712 
1713     return;
1714 }
1715 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1716 
1717 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1718 void ssl_calc_verify_tls( const mbedtls_ssl_context *ssl,
1719                           unsigned char hash[36],
1720                           size_t *hlen )
1721 {
1722     mbedtls_md5_context md5;
1723     mbedtls_sha1_context sha1;
1724 
1725     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
1726 
1727     mbedtls_md5_init( &md5 );
1728     mbedtls_sha1_init( &sha1 );
1729 
1730     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
1731     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
1732 
1733     mbedtls_md5_finish_ret( &md5,  hash );
1734     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
1735 
1736     *hlen = 36;
1737 
1738     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
1739     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1740 
1741     mbedtls_md5_free(  &md5  );
1742     mbedtls_sha1_free( &sha1 );
1743 
1744     return;
1745 }
1746 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1747 
1748 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1749 #if defined(MBEDTLS_SHA256_C)
1750 void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *ssl,
1751                                  unsigned char hash[32],
1752                                  size_t *hlen )
1753 {
1754 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1755     size_t hash_size;
1756     psa_status_t status;
1757     psa_hash_operation_t sha256_psa = psa_hash_operation_init();
1758 
1759     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> PSA calc verify sha256" ) );
1760     status = psa_hash_clone( &ssl->handshake->fin_sha256_psa, &sha256_psa );
1761     if( status != PSA_SUCCESS )
1762     {
1763         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
1764         return;
1765     }
1766 
1767     status = psa_hash_finish( &sha256_psa, hash, 32, &hash_size );
1768     if( status != PSA_SUCCESS )
1769     {
1770         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
1771         return;
1772     }
1773 
1774     *hlen = 32;
1775     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated verify result", hash, *hlen );
1776     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= PSA calc verify" ) );
1777 #else
1778     mbedtls_sha256_context sha256;
1779 
1780     mbedtls_sha256_init( &sha256 );
1781 
1782     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
1783 
1784     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
1785     mbedtls_sha256_finish_ret( &sha256, hash );
1786 
1787     *hlen = 32;
1788 
1789     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
1790     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1791 
1792     mbedtls_sha256_free( &sha256 );
1793 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1794     return;
1795 }
1796 #endif /* MBEDTLS_SHA256_C */
1797 
1798 #if defined(MBEDTLS_SHA512_C)
1799 void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *ssl,
1800                                  unsigned char hash[48],
1801                                  size_t *hlen )
1802 {
1803 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1804     size_t hash_size;
1805     psa_status_t status;
1806     psa_hash_operation_t sha384_psa = psa_hash_operation_init();
1807 
1808     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> PSA calc verify sha384" ) );
1809     status = psa_hash_clone( &ssl->handshake->fin_sha384_psa, &sha384_psa );
1810     if( status != PSA_SUCCESS )
1811     {
1812         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
1813         return;
1814     }
1815 
1816     status = psa_hash_finish( &sha384_psa, hash, 48, &hash_size );
1817     if( status != PSA_SUCCESS )
1818     {
1819         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
1820         return;
1821     }
1822 
1823     *hlen = 48;
1824     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated verify result", hash, *hlen );
1825     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= PSA calc verify" ) );
1826 #else
1827     mbedtls_sha512_context sha512;
1828 
1829     mbedtls_sha512_init( &sha512 );
1830 
1831     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
1832 
1833     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
1834     mbedtls_sha512_finish_ret( &sha512, hash );
1835 
1836     *hlen = 48;
1837 
1838     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
1839     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1840 
1841     mbedtls_sha512_free( &sha512 );
1842 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1843     return;
1844 }
1845 #endif /* MBEDTLS_SHA512_C */
1846 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1847 
1848 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
1849 int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
1850 {
1851     unsigned char *p = ssl->handshake->premaster;
1852     unsigned char *end = p + sizeof( ssl->handshake->premaster );
1853     const unsigned char *psk = ssl->conf->psk;
1854     size_t psk_len = ssl->conf->psk_len;
1855 
1856     /* If the psk callback was called, use its result */
1857     if( ssl->handshake->psk != NULL )
1858     {
1859         psk = ssl->handshake->psk;
1860         psk_len = ssl->handshake->psk_len;
1861     }
1862 
1863     /*
1864      * PMS = struct {
1865      *     opaque other_secret<0..2^16-1>;
1866      *     opaque psk<0..2^16-1>;
1867      * };
1868      * with "other_secret" depending on the particular key exchange
1869      */
1870 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1871     if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
1872     {
1873         if( end - p < 2 )
1874             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1875 
1876         *(p++) = (unsigned char)( psk_len >> 8 );
1877         *(p++) = (unsigned char)( psk_len      );
1878 
1879         if( end < p || (size_t)( end - p ) < psk_len )
1880             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1881 
1882         memset( p, 0, psk_len );
1883         p += psk_len;
1884     }
1885     else
1886 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
1887 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1888     if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
1889     {
1890         /*
1891          * other_secret already set by the ClientKeyExchange message,
1892          * and is 48 bytes long
1893          */
1894         if( end - p < 2 )
1895             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1896 
1897         *p++ = 0;
1898         *p++ = 48;
1899         p += 48;
1900     }
1901     else
1902 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
1903 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1904     if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
1905     {
1906         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1907         size_t len;
1908 
1909         /* Write length only when we know the actual value */
1910         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
1911                                       p + 2, end - ( p + 2 ), &len,
1912                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1913         {
1914             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
1915             return( ret );
1916         }
1917         *(p++) = (unsigned char)( len >> 8 );
1918         *(p++) = (unsigned char)( len );
1919         p += len;
1920 
1921         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
1922     }
1923     else
1924 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
1925 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
1926     if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
1927     {
1928         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1929         size_t zlen;
1930 
1931         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
1932                                        p + 2, end - ( p + 2 ),
1933                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1934         {
1935             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
1936             return( ret );
1937         }
1938 
1939         *(p++) = (unsigned char)( zlen >> 8 );
1940         *(p++) = (unsigned char)( zlen      );
1941         p += zlen;
1942 
1943         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
1944                                 MBEDTLS_DEBUG_ECDH_Z );
1945     }
1946     else
1947 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
1948     {
1949         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1950         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1951     }
1952 
1953     /* opaque psk<0..2^16-1>; */
1954     if( end - p < 2 )
1955         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1956 
1957     *(p++) = (unsigned char)( psk_len >> 8 );
1958     *(p++) = (unsigned char)( psk_len      );
1959 
1960     if( end < p || (size_t)( end - p ) < psk_len )
1961         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1962 
1963     memcpy( p, psk, psk_len );
1964     p += psk_len;
1965 
1966     ssl->handshake->pmslen = p - ssl->handshake->premaster;
1967 
1968     return( 0 );
1969 }
1970 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
1971 
1972 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
1973 static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
1974 
1975 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1976 int mbedtls_ssl_resend_hello_request( mbedtls_ssl_context *ssl )
1977 {
1978     /* If renegotiation is not enforced, retransmit until we would reach max
1979      * timeout if we were using the usual handshake doubling scheme */
1980     if( ssl->conf->renego_max_records < 0 )
1981     {
1982         uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
1983         unsigned char doublings = 1;
1984 
1985         while( ratio != 0 )
1986         {
1987             ++doublings;
1988             ratio >>= 1;
1989         }
1990 
1991         if( ++ssl->renego_records_seen > doublings )
1992         {
1993             MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
1994             return( 0 );
1995         }
1996     }
1997 
1998     return( ssl_write_hello_request( ssl ) );
1999 }
2000 #endif
2001 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2002 
2003 #if defined(MBEDTLS_X509_CRT_PARSE_C)
2004 static void ssl_clear_peer_cert( mbedtls_ssl_session *session )
2005 {
2006 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2007     if( session->peer_cert != NULL )
2008     {
2009         mbedtls_x509_crt_free( session->peer_cert );
2010         mbedtls_free( session->peer_cert );
2011         session->peer_cert = NULL;
2012     }
2013 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2014     if( session->peer_cert_digest != NULL )
2015     {
2016         /* Zeroization is not necessary. */
2017         mbedtls_free( session->peer_cert_digest );
2018         session->peer_cert_digest      = NULL;
2019         session->peer_cert_digest_type = MBEDTLS_MD_NONE;
2020         session->peer_cert_digest_len  = 0;
2021     }
2022 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2023 }
2024 #endif /* MBEDTLS_X509_CRT_PARSE_C */
2025 
2026 /*
2027  * Handshake functions
2028  */
2029 #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
2030 /* No certificate support -> dummy functions */
2031 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
2032 {
2033     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2034         ssl->handshake->ciphersuite_info;
2035 
2036     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
2037 
2038     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
2039     {
2040         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
2041         ssl->state++;
2042         return( 0 );
2043     }
2044 
2045     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2046     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2047 }
2048 
2049 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
2050 {
2051     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2052         ssl->handshake->ciphersuite_info;
2053 
2054     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
2055 
2056     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
2057     {
2058         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
2059         ssl->state++;
2060         return( 0 );
2061     }
2062 
2063     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2064     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2065 }
2066 
2067 #else /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
2068 /* Some certificate support -> implement write and parse */
2069 
2070 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
2071 {
2072     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2073     size_t i, n;
2074     const mbedtls_x509_crt *crt;
2075     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2076         ssl->handshake->ciphersuite_info;
2077 
2078     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
2079 
2080     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
2081     {
2082         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
2083         ssl->state++;
2084         return( 0 );
2085     }
2086 
2087 #if defined(MBEDTLS_SSL_CLI_C)
2088     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
2089     {
2090         if( ssl->client_auth == 0 )
2091         {
2092             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
2093             ssl->state++;
2094             return( 0 );
2095         }
2096 
2097 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2098         /*
2099          * If using SSLv3 and got no cert, send an Alert message
2100          * (otherwise an empty Certificate message will be sent).
2101          */
2102         if( mbedtls_ssl_own_cert( ssl )  == NULL &&
2103             ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
2104         {
2105             ssl->out_msglen  = 2;
2106             ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
2107             ssl->out_msg[0]  = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
2108             ssl->out_msg[1]  = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
2109 
2110             MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
2111             goto write_msg;
2112         }
2113 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
2114     }
2115 #endif /* MBEDTLS_SSL_CLI_C */
2116 #if defined(MBEDTLS_SSL_SRV_C)
2117     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
2118     {
2119         if( mbedtls_ssl_own_cert( ssl ) == NULL )
2120         {
2121             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
2122             return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
2123         }
2124     }
2125 #endif
2126 
2127     MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
2128 
2129     /*
2130      *     0  .  0    handshake type
2131      *     1  .  3    handshake length
2132      *     4  .  6    length of all certs
2133      *     7  .  9    length of cert. 1
2134      *    10  . n-1   peer certificate
2135      *     n  . n+2   length of cert. 2
2136      *    n+3 . ...   upper level cert, etc.
2137      */
2138     i = 7;
2139     crt = mbedtls_ssl_own_cert( ssl );
2140 
2141     while( crt != NULL )
2142     {
2143         n = crt->raw.len;
2144         if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i )
2145         {
2146             MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
2147                            i + 3 + n, MBEDTLS_SSL_OUT_CONTENT_LEN ) );
2148             return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
2149         }
2150 
2151         ssl->out_msg[i    ] = (unsigned char)( n >> 16 );
2152         ssl->out_msg[i + 1] = (unsigned char)( n >>  8 );
2153         ssl->out_msg[i + 2] = (unsigned char)( n       );
2154 
2155         i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
2156         i += n; crt = crt->next;
2157     }
2158 
2159     ssl->out_msg[4]  = (unsigned char)( ( i - 7 ) >> 16 );
2160     ssl->out_msg[5]  = (unsigned char)( ( i - 7 ) >>  8 );
2161     ssl->out_msg[6]  = (unsigned char)( ( i - 7 )       );
2162 
2163     ssl->out_msglen  = i;
2164     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2165     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;
2166 
2167 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
2168 write_msg:
2169 #endif
2170 
2171     ssl->state++;
2172 
2173     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
2174     {
2175         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
2176         return( ret );
2177     }
2178 
2179     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
2180 
2181     return( ret );
2182 }
2183 
2184 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2185 
2186 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2187 static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl,
2188                                          unsigned char *crt_buf,
2189                                          size_t crt_buf_len )
2190 {
2191     mbedtls_x509_crt const * const peer_crt = ssl->session->peer_cert;
2192 
2193     if( peer_crt == NULL )
2194         return( -1 );
2195 
2196     if( peer_crt->raw.len != crt_buf_len )
2197         return( -1 );
2198 
2199     return( memcmp( peer_crt->raw.p, crt_buf, peer_crt->raw.len ) );
2200 }
2201 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2202 static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl,
2203                                          unsigned char *crt_buf,
2204                                          size_t crt_buf_len )
2205 {
2206     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2207     unsigned char const * const peer_cert_digest =
2208         ssl->session->peer_cert_digest;
2209     mbedtls_md_type_t const peer_cert_digest_type =
2210         ssl->session->peer_cert_digest_type;
2211     mbedtls_md_info_t const * const digest_info =
2212         mbedtls_md_info_from_type( peer_cert_digest_type );
2213     unsigned char tmp_digest[MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN];
2214     size_t digest_len;
2215 
2216     if( peer_cert_digest == NULL || digest_info == NULL )
2217         return( -1 );
2218 
2219     digest_len = mbedtls_md_get_size( digest_info );
2220     if( digest_len > MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN )
2221         return( -1 );
2222 
2223     ret = mbedtls_md( digest_info, crt_buf, crt_buf_len, tmp_digest );
2224     if( ret != 0 )
2225         return( -1 );
2226 
2227     return( memcmp( tmp_digest, peer_cert_digest, digest_len ) );
2228 }
2229 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2230 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
2231 
2232 /*
2233  * Once the certificate message is read, parse it into a cert chain and
2234  * perform basic checks, but leave actual verification to the caller
2235  */
2236 static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl,
2237                                         mbedtls_x509_crt *chain )
2238 {
2239     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2240 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2241     int crt_cnt=0;
2242 #endif
2243     size_t i, n;
2244     uint8_t alert;
2245 
2246     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2247     {
2248         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
2249         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2250                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
2251         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2252     }
2253 
2254     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
2255         ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
2256     {
2257         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
2258         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2259                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2260         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
2261     }
2262 
2263     i = mbedtls_ssl_hs_hdr_len( ssl );
2264 
2265     /*
2266      * Same message structure as in mbedtls_ssl_write_certificate()
2267      */
2268     n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
2269 
2270     if( ssl->in_msg[i] != 0 ||
2271         ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
2272     {
2273         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
2274         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2275                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2276         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
2277     }
2278 
2279     /* Make &ssl->in_msg[i] point to the beginning of the CRT chain. */
2280     i += 3;
2281 
2282     /* Iterate through and parse the CRTs in the provided chain. */
2283     while( i < ssl->in_hslen )
2284     {
2285         /* Check that there's room for the next CRT's length fields. */
2286         if ( i + 3 > ssl->in_hslen ) {
2287             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
2288             mbedtls_ssl_send_alert_message( ssl,
2289                               MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2290                               MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2291             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
2292         }
2293         /* In theory, the CRT can be up to 2**24 Bytes, but we don't support
2294          * anything beyond 2**16 ~ 64K. */
2295         if( ssl->in_msg[i] != 0 )
2296         {
2297             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
2298             mbedtls_ssl_send_alert_message( ssl,
2299                             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2300                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2301             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
2302         }
2303 
2304         /* Read length of the next CRT in the chain. */
2305         n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
2306             | (unsigned int) ssl->in_msg[i + 2];
2307         i += 3;
2308 
2309         if( n < 128 || i + n > ssl->in_hslen )
2310         {
2311             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
2312             mbedtls_ssl_send_alert_message( ssl,
2313                                  MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2314                                  MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2315             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
2316         }
2317 
2318         /* Check if we're handling the first CRT in the chain. */
2319 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2320         if( crt_cnt++ == 0 &&
2321             ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
2322             ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
2323         {
2324             /* During client-side renegotiation, check that the server's
2325              * end-CRTs hasn't changed compared to the initial handshake,
2326              * mitigating the triple handshake attack. On success, reuse
2327              * the original end-CRT instead of parsing it again. */
2328             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Check that peer CRT hasn't changed during renegotiation" ) );
2329             if( ssl_check_peer_crt_unchanged( ssl,
2330                                               &ssl->in_msg[i],
2331                                               n ) != 0 )
2332             {
2333                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
2334                 mbedtls_ssl_send_alert_message( ssl,
2335                                                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2336                                                 MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
2337                 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
2338             }
2339 
2340             /* Now we can safely free the original chain. */
2341             ssl_clear_peer_cert( ssl->session );
2342         }
2343 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
2344 
2345         /* Parse the next certificate in the chain. */
2346 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2347         ret = mbedtls_x509_crt_parse_der( chain, ssl->in_msg + i, n );
2348 #else
2349         /* If we don't need to store the CRT chain permanently, parse
2350          * it in-place from the input buffer instead of making a copy. */
2351         ret = mbedtls_x509_crt_parse_der_nocopy( chain, ssl->in_msg + i, n );
2352 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2353         switch( ret )
2354         {
2355             case 0: /*ok*/
2356             case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
2357                 /* Ignore certificate with an unknown algorithm: maybe a
2358                    prior certificate was already trusted. */
2359                 break;
2360 
2361             case MBEDTLS_ERR_X509_ALLOC_FAILED:
2362                 alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
2363                 goto crt_parse_der_failed;
2364 
2365             case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
2366                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2367                 goto crt_parse_der_failed;
2368 
2369             default:
2370                 alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
2371             crt_parse_der_failed:
2372                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
2373                 MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
2374                 return( ret );
2375         }
2376 
2377         i += n;
2378     }
2379 
2380     MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", chain );
2381     return( 0 );
2382 }
2383 
2384 #if defined(MBEDTLS_SSL_SRV_C)
2385 static int ssl_srv_check_client_no_crt_notification( mbedtls_ssl_context *ssl )
2386 {
2387     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
2388         return( -1 );
2389 
2390 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2391     /*
2392      * Check if the client sent an empty certificate
2393      */
2394     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
2395     {
2396         if( ssl->in_msglen  == 2                        &&
2397             ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT            &&
2398             ssl->in_msg[0]  == MBEDTLS_SSL_ALERT_LEVEL_WARNING  &&
2399             ssl->in_msg[1]  == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
2400         {
2401             MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
2402             return( 0 );
2403         }
2404 
2405         return( -1 );
2406     }
2407 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
2408 
2409 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2410     defined(MBEDTLS_SSL_PROTO_TLS1_2)
2411     if( ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
2412         ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&
2413         ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&
2414         memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
2415     {
2416         MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
2417         return( 0 );
2418     }
2419 
2420     return( -1 );
2421 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
2422           MBEDTLS_SSL_PROTO_TLS1_2 */
2423 }
2424 #endif /* MBEDTLS_SSL_SRV_C */
2425 
2426 /* Check if a certificate message is expected.
2427  * Return either
2428  * - SSL_CERTIFICATE_EXPECTED, or
2429  * - SSL_CERTIFICATE_SKIP
2430  * indicating whether a Certificate message is expected or not.
2431  */
2432 #define SSL_CERTIFICATE_EXPECTED 0
2433 #define SSL_CERTIFICATE_SKIP     1
2434 static int ssl_parse_certificate_coordinate( mbedtls_ssl_context *ssl,
2435                                              int authmode )
2436 {
2437     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2438         ssl->handshake->ciphersuite_info;
2439 
2440     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
2441         return( SSL_CERTIFICATE_SKIP );
2442 
2443 #if defined(MBEDTLS_SSL_SRV_C)
2444     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
2445     {
2446         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2447             return( SSL_CERTIFICATE_SKIP );
2448 
2449         if( authmode == MBEDTLS_SSL_VERIFY_NONE )
2450         {
2451             ssl->session_negotiate->verify_result =
2452                 MBEDTLS_X509_BADCERT_SKIP_VERIFY;
2453             return( SSL_CERTIFICATE_SKIP );
2454         }
2455     }
2456 #else
2457     ((void) authmode);
2458 #endif /* MBEDTLS_SSL_SRV_C */
2459 
2460     return( SSL_CERTIFICATE_EXPECTED );
2461 }
2462 
2463 static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl,
2464                                          int authmode,
2465                                          mbedtls_x509_crt *chain,
2466                                          void *rs_ctx )
2467 {
2468     int ret = 0;
2469     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2470         ssl->handshake->ciphersuite_info;
2471     int have_ca_chain = 0;
2472 
2473     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *);
2474     void *p_vrfy;
2475 
2476     if( authmode == MBEDTLS_SSL_VERIFY_NONE )
2477         return( 0 );
2478 
2479     if( ssl->f_vrfy != NULL )
2480     {
2481         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use context-specific verification callback" ) );
2482         f_vrfy = ssl->f_vrfy;
2483         p_vrfy = ssl->p_vrfy;
2484     }
2485     else
2486     {
2487         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use configuration-specific verification callback" ) );
2488         f_vrfy = ssl->conf->f_vrfy;
2489         p_vrfy = ssl->conf->p_vrfy;
2490     }
2491 
2492     /*
2493      * Main check: verify certificate
2494      */
2495 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
2496     if( ssl->conf->f_ca_cb != NULL )
2497     {
2498         ((void) rs_ctx);
2499         have_ca_chain = 1;
2500 
2501         MBEDTLS_SSL_DEBUG_MSG( 3, ( "use CA callback for X.509 CRT verification" ) );
2502         ret = mbedtls_x509_crt_verify_with_ca_cb(
2503             chain,
2504             ssl->conf->f_ca_cb,
2505             ssl->conf->p_ca_cb,
2506             ssl->conf->cert_profile,
2507             ssl->hostname,
2508             &ssl->session_negotiate->verify_result,
2509             f_vrfy, p_vrfy );
2510     }
2511     else
2512 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
2513     {
2514         mbedtls_x509_crt *ca_chain;
2515         mbedtls_x509_crl *ca_crl;
2516 
2517 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2518         if( ssl->handshake->sni_ca_chain != NULL )
2519         {
2520             ca_chain = ssl->handshake->sni_ca_chain;
2521             ca_crl   = ssl->handshake->sni_ca_crl;
2522         }
2523         else
2524 #endif
2525         {
2526             ca_chain = ssl->conf->ca_chain;
2527             ca_crl   = ssl->conf->ca_crl;
2528         }
2529 
2530         if( ca_chain != NULL )
2531             have_ca_chain = 1;
2532 
2533         ret = mbedtls_x509_crt_verify_restartable(
2534             chain,
2535             ca_chain, ca_crl,
2536             ssl->conf->cert_profile,
2537             ssl->hostname,
2538             &ssl->session_negotiate->verify_result,
2539             f_vrfy, p_vrfy, rs_ctx );
2540     }
2541 
2542     if( ret != 0 )
2543     {
2544         MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
2545     }
2546 
2547 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2548     if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2549         return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS );
2550 #endif
2551 
2552     /*
2553      * Secondary checks: always done, but change 'ret' only if it was 0
2554      */
2555 
2556 #if defined(MBEDTLS_ECP_C)
2557     {
2558         const mbedtls_pk_context *pk = &chain->pk;
2559 
2560         /* If certificate uses an EC key, make sure the curve is OK */
2561         if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
2562             mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
2563         {
2564             ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
2565 
2566             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
2567             if( ret == 0 )
2568                 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2569         }
2570     }
2571 #endif /* MBEDTLS_ECP_C */
2572 
2573     if( mbedtls_ssl_check_cert_usage( chain,
2574                                       ciphersuite_info,
2575                                       ! ssl->conf->endpoint,
2576                                       &ssl->session_negotiate->verify_result ) != 0 )
2577     {
2578         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
2579         if( ret == 0 )
2580             ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2581     }
2582 
2583     /* mbedtls_x509_crt_verify_with_profile is supposed to report a
2584      * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
2585      * with details encoded in the verification flags. All other kinds
2586      * of error codes, including those from the user provided f_vrfy
2587      * functions, are treated as fatal and lead to a failure of
2588      * ssl_parse_certificate even if verification was optional. */
2589     if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
2590         ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
2591           ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )
2592     {
2593         ret = 0;
2594     }
2595 
2596     if( have_ca_chain == 0 && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
2597     {
2598         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
2599         ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
2600     }
2601 
2602     if( ret != 0 )
2603     {
2604         uint8_t alert;
2605 
2606         /* The certificate may have been rejected for several reasons.
2607            Pick one and send the corresponding alert. Which alert to send
2608            may be a subject of debate in some cases. */
2609         if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
2610             alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
2611         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
2612             alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
2613         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
2614             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2615         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
2616             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2617         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
2618             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2619         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
2620             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2621         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
2622             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2623         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
2624             alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
2625         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
2626             alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
2627         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
2628             alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
2629         else
2630             alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
2631         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2632                                         alert );
2633     }
2634 
2635 #if defined(MBEDTLS_DEBUG_C)
2636     if( ssl->session_negotiate->verify_result != 0 )
2637     {
2638         MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x",
2639                                     ssl->session_negotiate->verify_result ) );
2640     }
2641     else
2642     {
2643         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
2644     }
2645 #endif /* MBEDTLS_DEBUG_C */
2646 
2647     return( ret );
2648 }
2649 
2650 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2651 static int ssl_remember_peer_crt_digest( mbedtls_ssl_context *ssl,
2652                                          unsigned char *start, size_t len )
2653 {
2654     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2655     /* Remember digest of the peer's end-CRT. */
2656     ssl->session_negotiate->peer_cert_digest =
2657         mbedtls_calloc( 1, MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN );
2658     if( ssl->session_negotiate->peer_cert_digest == NULL )
2659     {
2660         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
2661                                     MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN ) );
2662         mbedtls_ssl_send_alert_message( ssl,
2663                                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2664                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
2665 
2666         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2667     }
2668 
2669     ret = mbedtls_md( mbedtls_md_info_from_type(
2670                           MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE ),
2671                       start, len,
2672                       ssl->session_negotiate->peer_cert_digest );
2673 
2674     ssl->session_negotiate->peer_cert_digest_type =
2675         MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE;
2676     ssl->session_negotiate->peer_cert_digest_len =
2677         MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN;
2678 
2679     return( ret );
2680 }
2681 
2682 static int ssl_remember_peer_pubkey( mbedtls_ssl_context *ssl,
2683                                      unsigned char *start, size_t len )
2684 {
2685     unsigned char *end = start + len;
2686     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2687 
2688     /* Make a copy of the peer's raw public key. */
2689     mbedtls_pk_init( &ssl->handshake->peer_pubkey );
2690     ret = mbedtls_pk_parse_subpubkey( &start, end,
2691                                       &ssl->handshake->peer_pubkey );
2692     if( ret != 0 )
2693     {
2694         /* We should have parsed the public key before. */
2695         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2696     }
2697 
2698     return( 0 );
2699 }
2700 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2701 
2702 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
2703 {
2704     int ret = 0;
2705     int crt_expected;
2706 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2707     const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
2708                        ? ssl->handshake->sni_authmode
2709                        : ssl->conf->authmode;
2710 #else
2711     const int authmode = ssl->conf->authmode;
2712 #endif
2713     void *rs_ctx = NULL;
2714     mbedtls_x509_crt *chain = NULL;
2715 
2716     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
2717 
2718     crt_expected = ssl_parse_certificate_coordinate( ssl, authmode );
2719     if( crt_expected == SSL_CERTIFICATE_SKIP )
2720     {
2721         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
2722         goto exit;
2723     }
2724 
2725 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2726     if( ssl->handshake->ecrs_enabled &&
2727         ssl->handshake->ecrs_state == ssl_ecrs_crt_verify )
2728     {
2729         chain = ssl->handshake->ecrs_peer_cert;
2730         ssl->handshake->ecrs_peer_cert = NULL;
2731         goto crt_verify;
2732     }
2733 #endif
2734 
2735     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
2736     {
2737         /* mbedtls_ssl_read_record may have sent an alert already. We
2738            let it decide whether to alert. */
2739         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2740         goto exit;
2741     }
2742 
2743 #if defined(MBEDTLS_SSL_SRV_C)
2744     if( ssl_srv_check_client_no_crt_notification( ssl ) == 0 )
2745     {
2746         ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
2747 
2748         if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
2749             ret = 0;
2750         else
2751             ret = MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE;
2752 
2753         goto exit;
2754     }
2755 #endif /* MBEDTLS_SSL_SRV_C */
2756 
2757     /* Clear existing peer CRT structure in case we tried to
2758      * reuse a session but it failed, and allocate a new one. */
2759     ssl_clear_peer_cert( ssl->session_negotiate );
2760 
2761     chain = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
2762     if( chain == NULL )
2763     {
2764         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
2765                                     sizeof( mbedtls_x509_crt ) ) );
2766         mbedtls_ssl_send_alert_message( ssl,
2767                                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2768                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
2769 
2770         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
2771         goto exit;
2772     }
2773     mbedtls_x509_crt_init( chain );
2774 
2775     ret = ssl_parse_certificate_chain( ssl, chain );
2776     if( ret != 0 )
2777         goto exit;
2778 
2779 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2780     if( ssl->handshake->ecrs_enabled)
2781         ssl->handshake->ecrs_state = ssl_ecrs_crt_verify;
2782 
2783 crt_verify:
2784     if( ssl->handshake->ecrs_enabled)
2785         rs_ctx = &ssl->handshake->ecrs_ctx;
2786 #endif
2787 
2788     ret = ssl_parse_certificate_verify( ssl, authmode,
2789                                         chain, rs_ctx );
2790     if( ret != 0 )
2791         goto exit;
2792 
2793 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2794     {
2795         unsigned char *crt_start, *pk_start;
2796         size_t crt_len, pk_len;
2797 
2798         /* We parse the CRT chain without copying, so
2799          * these pointers point into the input buffer,
2800          * and are hence still valid after freeing the
2801          * CRT chain. */
2802 
2803         crt_start = chain->raw.p;
2804         crt_len   = chain->raw.len;
2805 
2806         pk_start = chain->pk_raw.p;
2807         pk_len   = chain->pk_raw.len;
2808 
2809         /* Free the CRT structures before computing
2810          * digest and copying the peer's public key. */
2811         mbedtls_x509_crt_free( chain );
2812         mbedtls_free( chain );
2813         chain = NULL;
2814 
2815         ret = ssl_remember_peer_crt_digest( ssl, crt_start, crt_len );
2816         if( ret != 0 )
2817             goto exit;
2818 
2819         ret = ssl_remember_peer_pubkey( ssl, pk_start, pk_len );
2820         if( ret != 0 )
2821             goto exit;
2822     }
2823 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2824     /* Pass ownership to session structure. */
2825     ssl->session_negotiate->peer_cert = chain;
2826     chain = NULL;
2827 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2828 
2829     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
2830 
2831 exit:
2832 
2833     if( ret == 0 )
2834         ssl->state++;
2835 
2836 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2837     if( ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS )
2838     {
2839         ssl->handshake->ecrs_peer_cert = chain;
2840         chain = NULL;
2841     }
2842 #endif
2843 
2844     if( chain != NULL )
2845     {
2846         mbedtls_x509_crt_free( chain );
2847         mbedtls_free( chain );
2848     }
2849 
2850     return( ret );
2851 }
2852 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
2853 
2854 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
2855                             const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
2856 {
2857     ((void) ciphersuite_info);
2858 
2859 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2860     defined(MBEDTLS_SSL_PROTO_TLS1_1)
2861     if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
2862         ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
2863     else
2864 #endif
2865 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2866 #if defined(MBEDTLS_SHA512_C)
2867     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
2868         ssl->handshake->update_checksum = ssl_update_checksum_sha384;
2869     else
2870 #endif
2871 #if defined(MBEDTLS_SHA256_C)
2872     if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
2873         ssl->handshake->update_checksum = ssl_update_checksum_sha256;
2874     else
2875 #endif
2876 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2877     {
2878         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2879         return;
2880     }
2881 }
2882 
2883 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
2884 {
2885 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2886     defined(MBEDTLS_SSL_PROTO_TLS1_1)
2887      mbedtls_md5_starts_ret( &ssl->handshake->fin_md5  );
2888     mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 );
2889 #endif
2890 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2891 #if defined(MBEDTLS_SHA256_C)
2892 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2893     psa_hash_abort( &ssl->handshake->fin_sha256_psa );
2894     psa_hash_setup( &ssl->handshake->fin_sha256_psa, PSA_ALG_SHA_256 );
2895 #else
2896     mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 );
2897 #endif
2898 #endif
2899 #if defined(MBEDTLS_SHA512_C)
2900 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2901     psa_hash_abort( &ssl->handshake->fin_sha384_psa );
2902     psa_hash_setup( &ssl->handshake->fin_sha384_psa, PSA_ALG_SHA_384 );
2903 #else
2904     mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 );
2905 #endif
2906 #endif
2907 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2908 }
2909 
2910 static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
2911                                        const unsigned char *buf, size_t len )
2912 {
2913 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2914     defined(MBEDTLS_SSL_PROTO_TLS1_1)
2915      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
2916     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
2917 #endif
2918 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2919 #if defined(MBEDTLS_SHA256_C)
2920 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2921     psa_hash_update( &ssl->handshake->fin_sha256_psa, buf, len );
2922 #else
2923     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
2924 #endif
2925 #endif
2926 #if defined(MBEDTLS_SHA512_C)
2927 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2928     psa_hash_update( &ssl->handshake->fin_sha384_psa, buf, len );
2929 #else
2930     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
2931 #endif
2932 #endif
2933 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2934 }
2935 
2936 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2937     defined(MBEDTLS_SSL_PROTO_TLS1_1)
2938 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
2939                                          const unsigned char *buf, size_t len )
2940 {
2941      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
2942     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
2943 }
2944 #endif
2945 
2946 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2947 #if defined(MBEDTLS_SHA256_C)
2948 static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
2949                                         const unsigned char *buf, size_t len )
2950 {
2951 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2952     psa_hash_update( &ssl->handshake->fin_sha256_psa, buf, len );
2953 #else
2954     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
2955 #endif
2956 }
2957 #endif
2958 
2959 #if defined(MBEDTLS_SHA512_C)
2960 static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
2961                                         const unsigned char *buf, size_t len )
2962 {
2963 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2964     psa_hash_update( &ssl->handshake->fin_sha384_psa, buf, len );
2965 #else
2966     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
2967 #endif
2968 }
2969 #endif
2970 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2971 
2972 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2973 static void ssl_calc_finished_ssl(
2974                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
2975 {
2976     const char *sender;
2977     mbedtls_md5_context  md5;
2978     mbedtls_sha1_context sha1;
2979 
2980     unsigned char padbuf[48];
2981     unsigned char md5sum[16];
2982     unsigned char sha1sum[20];
2983 
2984     mbedtls_ssl_session *session = ssl->session_negotiate;
2985     if( !session )
2986         session = ssl->session;
2987 
2988     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished ssl" ) );
2989 
2990     mbedtls_md5_init( &md5 );
2991     mbedtls_sha1_init( &sha1 );
2992 
2993     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
2994     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
2995 
2996     /*
2997      * SSLv3:
2998      *   hash =
2999      *      MD5( master + pad2 +
3000      *          MD5( handshake + sender + master + pad1 ) )
3001      *   + SHA1( master + pad2 +
3002      *         SHA1( handshake + sender + master + pad1 ) )
3003      */
3004 
3005 #if !defined(MBEDTLS_MD5_ALT)
3006     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
3007                     md5.state, sizeof(  md5.state ) );
3008 #endif
3009 
3010 #if !defined(MBEDTLS_SHA1_ALT)
3011     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
3012                    sha1.state, sizeof( sha1.state ) );
3013 #endif
3014 
3015     sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
3016                                        : "SRVR";
3017 
3018     memset( padbuf, 0x36, 48 );
3019 
3020     mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 );
3021     mbedtls_md5_update_ret( &md5, session->master, 48 );
3022     mbedtls_md5_update_ret( &md5, padbuf, 48 );
3023     mbedtls_md5_finish_ret( &md5, md5sum );
3024 
3025     mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 );
3026     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
3027     mbedtls_sha1_update_ret( &sha1, padbuf, 40 );
3028     mbedtls_sha1_finish_ret( &sha1, sha1sum );
3029 
3030     memset( padbuf, 0x5C, 48 );
3031 
3032     mbedtls_md5_starts_ret( &md5 );
3033     mbedtls_md5_update_ret( &md5, session->master, 48 );
3034     mbedtls_md5_update_ret( &md5, padbuf, 48 );
3035     mbedtls_md5_update_ret( &md5, md5sum, 16 );
3036     mbedtls_md5_finish_ret( &md5, buf );
3037 
3038     mbedtls_sha1_starts_ret( &sha1 );
3039     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
3040     mbedtls_sha1_update_ret( &sha1, padbuf , 40 );
3041     mbedtls_sha1_update_ret( &sha1, sha1sum, 20 );
3042     mbedtls_sha1_finish_ret( &sha1, buf + 16 );
3043 
3044     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
3045 
3046     mbedtls_md5_free(  &md5  );
3047     mbedtls_sha1_free( &sha1 );
3048 
3049     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
3050     mbedtls_platform_zeroize(  md5sum, sizeof(  md5sum ) );
3051     mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
3052 
3053     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
3054 }
3055 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
3056 
3057 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
3058 static void ssl_calc_finished_tls(
3059                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
3060 {
3061     int len = 12;
3062     const char *sender;
3063     mbedtls_md5_context  md5;
3064     mbedtls_sha1_context sha1;
3065     unsigned char padbuf[36];
3066 
3067     mbedtls_ssl_session *session = ssl->session_negotiate;
3068     if( !session )
3069         session = ssl->session;
3070 
3071     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls" ) );
3072 
3073     mbedtls_md5_init( &md5 );
3074     mbedtls_sha1_init( &sha1 );
3075 
3076     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
3077     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
3078 
3079     /*
3080      * TLSv1:
3081      *   hash = PRF( master, finished_label,
3082      *               MD5( handshake ) + SHA1( handshake ) )[0..11]
3083      */
3084 
3085 #if !defined(MBEDTLS_MD5_ALT)
3086     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
3087                     md5.state, sizeof(  md5.state ) );
3088 #endif
3089 
3090 #if !defined(MBEDTLS_SHA1_ALT)
3091     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
3092                    sha1.state, sizeof( sha1.state ) );
3093 #endif
3094 
3095     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
3096              ? "client finished"
3097              : "server finished";
3098 
3099     mbedtls_md5_finish_ret(  &md5, padbuf );
3100     mbedtls_sha1_finish_ret( &sha1, padbuf + 16 );
3101 
3102     ssl->handshake->tls_prf( session->master, 48, sender,
3103                              padbuf, 36, buf, len );
3104 
3105     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
3106 
3107     mbedtls_md5_free(  &md5  );
3108     mbedtls_sha1_free( &sha1 );
3109 
3110     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
3111 
3112     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
3113 }
3114 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
3115 
3116 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3117 #if defined(MBEDTLS_SHA256_C)
3118 static void ssl_calc_finished_tls_sha256(
3119                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
3120 {
3121     int len = 12;
3122     const char *sender;
3123     unsigned char padbuf[32];
3124 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3125     size_t hash_size;
3126     psa_hash_operation_t sha256_psa = PSA_HASH_OPERATION_INIT;
3127     psa_status_t status;
3128 #else
3129     mbedtls_sha256_context sha256;
3130 #endif
3131 
3132     mbedtls_ssl_session *session = ssl->session_negotiate;
3133     if( !session )
3134         session = ssl->session;
3135 
3136     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
3137              ? "client finished"
3138              : "server finished";
3139 
3140 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3141     sha256_psa = psa_hash_operation_init();
3142 
3143     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc PSA finished tls sha256" ) );
3144 
3145     status = psa_hash_clone( &ssl->handshake->fin_sha256_psa, &sha256_psa );
3146     if( status != PSA_SUCCESS )
3147     {
3148         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
3149         return;
3150     }
3151 
3152     status = psa_hash_finish( &sha256_psa, padbuf, sizeof( padbuf ), &hash_size );
3153     if( status != PSA_SUCCESS )
3154     {
3155         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
3156         return;
3157     }
3158     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated padbuf", padbuf, 32 );
3159 #else
3160 
3161     mbedtls_sha256_init( &sha256 );
3162 
3163     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha256" ) );
3164 
3165     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
3166 
3167     /*
3168      * TLSv1.2:
3169      *   hash = PRF( master, finished_label,
3170      *               Hash( handshake ) )[0.11]
3171      */
3172 
3173 #if !defined(MBEDTLS_SHA256_ALT)
3174     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
3175                    sha256.state, sizeof( sha256.state ) );
3176 #endif
3177 
3178     mbedtls_sha256_finish_ret( &sha256, padbuf );
3179     mbedtls_sha256_free( &sha256 );
3180 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3181 
3182     ssl->handshake->tls_prf( session->master, 48, sender,
3183                              padbuf, 32, buf, len );
3184 
3185     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
3186 
3187     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
3188 
3189     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
3190 }
3191 #endif /* MBEDTLS_SHA256_C */
3192 
3193 #if defined(MBEDTLS_SHA512_C)
3194 static void ssl_calc_finished_tls_sha384(
3195                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
3196 {
3197     int len = 12;
3198     const char *sender;
3199     unsigned char padbuf[48];
3200 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3201     size_t hash_size;
3202     psa_hash_operation_t sha384_psa = PSA_HASH_OPERATION_INIT;
3203     psa_status_t status;
3204 #else
3205     mbedtls_sha512_context sha512;
3206 #endif
3207 
3208     mbedtls_ssl_session *session = ssl->session_negotiate;
3209     if( !session )
3210         session = ssl->session;
3211 
3212     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
3213                 ? "client finished"
3214                 : "server finished";
3215 
3216 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3217     sha384_psa = psa_hash_operation_init();
3218 
3219     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc PSA finished tls sha384" ) );
3220 
3221     status = psa_hash_clone( &ssl->handshake->fin_sha384_psa, &sha384_psa );
3222     if( status != PSA_SUCCESS )
3223     {
3224         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
3225         return;
3226     }
3227 
3228     status = psa_hash_finish( &sha384_psa, padbuf, sizeof( padbuf ), &hash_size );
3229     if( status != PSA_SUCCESS )
3230     {
3231         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
3232         return;
3233     }
3234     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated padbuf", padbuf, 48 );
3235 #else
3236     mbedtls_sha512_init( &sha512 );
3237 
3238     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha384" ) );
3239 
3240     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
3241 
3242     /*
3243      * TLSv1.2:
3244      *   hash = PRF( master, finished_label,
3245      *               Hash( handshake ) )[0.11]
3246      */
3247 
3248 #if !defined(MBEDTLS_SHA512_ALT)
3249     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
3250                    sha512.state, sizeof( sha512.state ) );
3251 #endif
3252 
3253     mbedtls_sha512_finish_ret( &sha512, padbuf );
3254     mbedtls_sha512_free( &sha512 );
3255 #endif
3256 
3257     ssl->handshake->tls_prf( session->master, 48, sender,
3258                              padbuf, 48, buf, len );
3259 
3260     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
3261 
3262     mbedtls_platform_zeroize(  padbuf, sizeof( padbuf ) );
3263 
3264     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
3265 }
3266 #endif /* MBEDTLS_SHA512_C */
3267 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3268 
3269 void mbedtls_ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
3270 {
3271     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
3272 
3273     /*
3274      * Free our handshake params
3275      */
3276     mbedtls_ssl_handshake_free( ssl );
3277     mbedtls_free( ssl->handshake );
3278     ssl->handshake = NULL;
3279 
3280     /*
3281      * Free the previous transform and swith in the current one
3282      */
3283     if( ssl->transform )
3284     {
3285         mbedtls_ssl_transform_free( ssl->transform );
3286         mbedtls_free( ssl->transform );
3287     }
3288     ssl->transform = ssl->transform_negotiate;
3289     ssl->transform_negotiate = NULL;
3290 
3291     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
3292 }
3293 
3294 void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
3295 {
3296     int resume = ssl->handshake->resume;
3297 
3298     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
3299 
3300 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3301     if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
3302     {
3303         ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;
3304         ssl->renego_records_seen = 0;
3305     }
3306 #endif
3307 
3308     /*
3309      * Free the previous session and switch in the current one
3310      */
3311     if( ssl->session )
3312     {
3313 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
3314         /* RFC 7366 3.1: keep the EtM state */
3315         ssl->session_negotiate->encrypt_then_mac =
3316                   ssl->session->encrypt_then_mac;
3317 #endif
3318 
3319         mbedtls_ssl_session_free( ssl->session );
3320         mbedtls_free( ssl->session );
3321     }
3322     ssl->session = ssl->session_negotiate;
3323     ssl->session_negotiate = NULL;
3324 
3325     /*
3326      * Add cache entry
3327      */
3328     if( ssl->conf->f_set_cache != NULL &&
3329         ssl->session->id_len != 0 &&
3330         resume == 0 )
3331     {
3332         if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
3333             MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
3334     }
3335 
3336 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3337     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3338         ssl->handshake->flight != NULL )
3339     {
3340         /* Cancel handshake timer */
3341         mbedtls_ssl_set_timer( ssl, 0 );
3342 
3343         /* Keep last flight around in case we need to resend it:
3344          * we need the handshake and transform structures for that */
3345         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
3346     }
3347     else
3348 #endif
3349         mbedtls_ssl_handshake_wrapup_free_hs_transform( ssl );
3350 
3351     ssl->state++;
3352 
3353     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
3354 }
3355 
3356 int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
3357 {
3358     int ret, hash_len;
3359 
3360     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
3361 
3362     mbedtls_ssl_update_out_pointers( ssl, ssl->transform_negotiate );
3363 
3364     ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
3365 
3366     /*
3367      * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
3368      * may define some other value. Currently (early 2016), no defined
3369      * ciphersuite does this (and this is unlikely to change as activity has
3370      * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
3371      */
3372     hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
3373 
3374 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3375     ssl->verify_data_len = hash_len;
3376     memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
3377 #endif
3378 
3379     ssl->out_msglen  = 4 + hash_len;
3380     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3381     ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;
3382 
3383     /*
3384      * In case of session resuming, invert the client and server
3385      * ChangeCipherSpec messages order.
3386      */
3387     if( ssl->handshake->resume != 0 )
3388     {
3389 #if defined(MBEDTLS_SSL_CLI_C)
3390         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
3391             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
3392 #endif
3393 #if defined(MBEDTLS_SSL_SRV_C)
3394         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
3395             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
3396 #endif
3397     }
3398     else
3399         ssl->state++;
3400 
3401     /*
3402      * Switch to our negotiated transform and session parameters for outbound
3403      * data.
3404      */
3405     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
3406 
3407 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3408     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3409     {
3410         unsigned char i;
3411 
3412         /* Remember current epoch settings for resending */
3413         ssl->handshake->alt_transform_out = ssl->transform_out;
3414         memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8 );
3415 
3416         /* Set sequence_number to zero */
3417         memset( ssl->cur_out_ctr + 2, 0, 6 );
3418 
3419         /* Increment epoch */
3420         for( i = 2; i > 0; i-- )
3421             if( ++ssl->cur_out_ctr[i - 1] != 0 )
3422                 break;
3423 
3424         /* The loop goes to its end iff the counter is wrapping */
3425         if( i == 0 )
3426         {
3427             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
3428             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
3429         }
3430     }
3431     else
3432 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3433     memset( ssl->cur_out_ctr, 0, 8 );
3434 
3435     ssl->transform_out = ssl->transform_negotiate;
3436     ssl->session_out = ssl->session_negotiate;
3437 
3438 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3439     if( mbedtls_ssl_hw_record_activate != NULL )
3440     {
3441         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
3442         {
3443             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
3444             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3445         }
3446     }
3447 #endif
3448 
3449 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3450     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3451         mbedtls_ssl_send_flight_completed( ssl );
3452 #endif
3453 
3454     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
3455     {
3456         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
3457         return( ret );
3458     }
3459 
3460 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3461     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3462         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
3463     {
3464         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
3465         return( ret );
3466     }
3467 #endif
3468 
3469     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
3470 
3471     return( 0 );
3472 }
3473 
3474 #if defined(MBEDTLS_SSL_PROTO_SSL3)
3475 #define SSL_MAX_HASH_LEN 36
3476 #else
3477 #define SSL_MAX_HASH_LEN 12
3478 #endif
3479 
3480 int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
3481 {
3482     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3483     unsigned int hash_len;
3484     unsigned char buf[SSL_MAX_HASH_LEN];
3485 
3486     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
3487 
3488     ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
3489 
3490     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
3491     {
3492         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
3493         return( ret );
3494     }
3495 
3496     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
3497     {
3498         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
3499         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3500                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
3501         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
3502     }
3503 
3504     /* There is currently no ciphersuite using another length with TLS 1.2 */
3505 #if defined(MBEDTLS_SSL_PROTO_SSL3)
3506     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
3507         hash_len = 36;
3508     else
3509 #endif
3510         hash_len = 12;
3511 
3512     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
3513         ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
3514     {
3515         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
3516         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3517                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3518         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
3519     }
3520 
3521     if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
3522                       buf, hash_len ) != 0 )
3523     {
3524         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
3525         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3526                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3527         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
3528     }
3529 
3530 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3531     ssl->verify_data_len = hash_len;
3532     memcpy( ssl->peer_verify_data, buf, hash_len );
3533 #endif
3534 
3535     if( ssl->handshake->resume != 0 )
3536     {
3537 #if defined(MBEDTLS_SSL_CLI_C)
3538         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
3539             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
3540 #endif
3541 #if defined(MBEDTLS_SSL_SRV_C)
3542         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
3543             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
3544 #endif
3545     }
3546     else
3547         ssl->state++;
3548 
3549 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3550     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3551         mbedtls_ssl_recv_flight_completed( ssl );
3552 #endif
3553 
3554     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
3555 
3556     return( 0 );
3557 }
3558 
3559 static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
3560 {
3561     memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
3562 
3563 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3564     defined(MBEDTLS_SSL_PROTO_TLS1_1)
3565      mbedtls_md5_init(   &handshake->fin_md5  );
3566     mbedtls_sha1_init(   &handshake->fin_sha1 );
3567      mbedtls_md5_starts_ret( &handshake->fin_md5  );
3568     mbedtls_sha1_starts_ret( &handshake->fin_sha1 );
3569 #endif
3570 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3571 #if defined(MBEDTLS_SHA256_C)
3572 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3573     handshake->fin_sha256_psa = psa_hash_operation_init();
3574     psa_hash_setup( &handshake->fin_sha256_psa, PSA_ALG_SHA_256 );
3575 #else
3576     mbedtls_sha256_init(   &handshake->fin_sha256    );
3577     mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 );
3578 #endif
3579 #endif
3580 #if defined(MBEDTLS_SHA512_C)
3581 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3582     handshake->fin_sha384_psa = psa_hash_operation_init();
3583     psa_hash_setup( &handshake->fin_sha384_psa, PSA_ALG_SHA_384 );
3584 #else
3585     mbedtls_sha512_init(   &handshake->fin_sha512    );
3586     mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 );
3587 #endif
3588 #endif
3589 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3590 
3591     handshake->update_checksum = ssl_update_checksum_start;
3592 
3593 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
3594     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
3595     mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );
3596 #endif
3597 
3598 #if defined(MBEDTLS_DHM_C)
3599     mbedtls_dhm_init( &handshake->dhm_ctx );
3600 #endif
3601 #if defined(MBEDTLS_ECDH_C)
3602     mbedtls_ecdh_init( &handshake->ecdh_ctx );
3603 #endif
3604 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3605     mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
3606 #if defined(MBEDTLS_SSL_CLI_C)
3607     handshake->ecjpake_cache = NULL;
3608     handshake->ecjpake_cache_len = 0;
3609 #endif
3610 #endif
3611 
3612 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3613     mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx );
3614 #endif
3615 
3616 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
3617     handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
3618 #endif
3619 
3620 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
3621     !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
3622     mbedtls_pk_init( &handshake->peer_pubkey );
3623 #endif
3624 }
3625 
3626 void mbedtls_ssl_transform_init( mbedtls_ssl_transform *transform )
3627 {
3628     memset( transform, 0, sizeof(mbedtls_ssl_transform) );
3629 
3630     mbedtls_cipher_init( &transform->cipher_ctx_enc );
3631     mbedtls_cipher_init( &transform->cipher_ctx_dec );
3632 
3633 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
3634     mbedtls_md_init( &transform->md_ctx_enc );
3635     mbedtls_md_init( &transform->md_ctx_dec );
3636 #endif
3637 }
3638 
3639 void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
3640 {
3641     memset( session, 0, sizeof(mbedtls_ssl_session) );
3642 }
3643 
3644 static int ssl_handshake_init( mbedtls_ssl_context *ssl )
3645 {
3646     /* Clear old handshake information if present */
3647     if( ssl->transform_negotiate )
3648         mbedtls_ssl_transform_free( ssl->transform_negotiate );
3649     if( ssl->session_negotiate )
3650         mbedtls_ssl_session_free( ssl->session_negotiate );
3651     if( ssl->handshake )
3652         mbedtls_ssl_handshake_free( ssl );
3653 
3654     /*
3655      * Either the pointers are now NULL or cleared properly and can be freed.
3656      * Now allocate missing structures.
3657      */
3658     if( ssl->transform_negotiate == NULL )
3659     {
3660         ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
3661     }
3662 
3663     if( ssl->session_negotiate == NULL )
3664     {
3665         ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
3666     }
3667 
3668     if( ssl->handshake == NULL )
3669     {
3670         ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
3671     }
3672 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3673     /* If the buffers are too small - reallocate */
3674     {
3675         int modified = 0;
3676         size_t written_in = 0;
3677         size_t written_out = 0;
3678         if( ssl->in_buf != NULL )
3679         {
3680             written_in = ssl->in_msg - ssl->in_buf;
3681             if( ssl->in_buf_len < MBEDTLS_SSL_IN_BUFFER_LEN )
3682             {
3683                 if( resize_buffer( &ssl->in_buf, MBEDTLS_SSL_IN_BUFFER_LEN,
3684                                    &ssl->in_buf_len ) != 0 )
3685                 {
3686                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "input buffer resizing failed - out of memory" ) );
3687                 }
3688                 else
3689                 {
3690                     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating in_buf to %d", MBEDTLS_SSL_IN_BUFFER_LEN ) );
3691                     modified = 1;
3692                 }
3693             }
3694         }
3695 
3696         if( ssl->out_buf != NULL )
3697         {
3698             written_out = ssl->out_msg - ssl->out_buf;
3699             if( ssl->out_buf_len < MBEDTLS_SSL_OUT_BUFFER_LEN )
3700             {
3701                 if( resize_buffer( &ssl->out_buf, MBEDTLS_SSL_OUT_BUFFER_LEN,
3702                                    &ssl->out_buf_len ) != 0 )
3703                 {
3704                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "output buffer resizing failed - out of memory" ) );
3705                 }
3706                 else
3707                 {
3708                     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating out_buf to %d", MBEDTLS_SSL_OUT_BUFFER_LEN ) );
3709                     modified = 1;
3710                 }
3711             }
3712         }
3713         if( modified )
3714         {
3715             /* Update pointers here to avoid doing it twice. */
3716             mbedtls_ssl_reset_in_out_pointers( ssl );
3717             /* Fields below might not be properly updated with record
3718             * splitting, so they are manually updated here. */
3719             ssl->out_msg = ssl->out_buf + written_out;
3720             ssl->in_msg = ssl->in_buf + written_in;
3721         }
3722     }
3723 #endif
3724 
3725     /* All pointers should exist and can be directly freed without issue */
3726     if( ssl->handshake == NULL ||
3727         ssl->transform_negotiate == NULL ||
3728         ssl->session_negotiate == NULL )
3729     {
3730         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
3731 
3732         mbedtls_free( ssl->handshake );
3733         mbedtls_free( ssl->transform_negotiate );
3734         mbedtls_free( ssl->session_negotiate );
3735 
3736         ssl->handshake = NULL;
3737         ssl->transform_negotiate = NULL;
3738         ssl->session_negotiate = NULL;
3739 
3740         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
3741     }
3742 
3743     /* Initialize structures */
3744     mbedtls_ssl_session_init( ssl->session_negotiate );
3745     mbedtls_ssl_transform_init( ssl->transform_negotiate );
3746     ssl_handshake_params_init( ssl->handshake );
3747 
3748 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3749     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3750     {
3751         ssl->handshake->alt_transform_out = ssl->transform_out;
3752 
3753         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
3754             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
3755         else
3756             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
3757 
3758         mbedtls_ssl_set_timer( ssl, 0 );
3759     }
3760 #endif
3761 
3762     return( 0 );
3763 }
3764 
3765 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
3766 /* Dummy cookie callbacks for defaults */
3767 static int ssl_cookie_write_dummy( void *ctx,
3768                       unsigned char **p, unsigned char *end,
3769                       const unsigned char *cli_id, size_t cli_id_len )
3770 {
3771     ((void) ctx);
3772     ((void) p);
3773     ((void) end);
3774     ((void) cli_id);
3775     ((void) cli_id_len);
3776 
3777     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3778 }
3779 
3780 static int ssl_cookie_check_dummy( void *ctx,
3781                       const unsigned char *cookie, size_t cookie_len,
3782                       const unsigned char *cli_id, size_t cli_id_len )
3783 {
3784     ((void) ctx);
3785     ((void) cookie);
3786     ((void) cookie_len);
3787     ((void) cli_id);
3788     ((void) cli_id_len);
3789 
3790     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3791 }
3792 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
3793 
3794 /*
3795  * Initialize an SSL context
3796  */
3797 void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
3798 {
3799     memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
3800 }
3801 
3802 /*
3803  * Setup an SSL context
3804  */
3805 
3806 int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
3807                        const mbedtls_ssl_config *conf )
3808 {
3809     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3810     size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
3811     size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
3812 
3813     ssl->conf = conf;
3814 
3815     /*
3816      * Prepare base structures
3817      */
3818 
3819     /* Set to NULL in case of an error condition */
3820     ssl->out_buf = NULL;
3821 
3822 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3823     ssl->in_buf_len = in_buf_len;
3824 #endif
3825     ssl->in_buf = mbedtls_calloc( 1, in_buf_len );
3826     if( ssl->in_buf == NULL )
3827     {
3828         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", in_buf_len ) );
3829         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
3830         goto error;
3831     }
3832 
3833 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3834     ssl->out_buf_len = out_buf_len;
3835 #endif
3836     ssl->out_buf = mbedtls_calloc( 1, out_buf_len );
3837     if( ssl->out_buf == NULL )
3838     {
3839         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", out_buf_len ) );
3840         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
3841         goto error;
3842     }
3843 
3844     mbedtls_ssl_reset_in_out_pointers( ssl );
3845 
3846     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
3847         goto error;
3848 
3849     return( 0 );
3850 
3851 error:
3852     mbedtls_free( ssl->in_buf );
3853     mbedtls_free( ssl->out_buf );
3854 
3855     ssl->conf = NULL;
3856 
3857 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3858     ssl->in_buf_len = 0;
3859     ssl->out_buf_len = 0;
3860 #endif
3861     ssl->in_buf = NULL;
3862     ssl->out_buf = NULL;
3863 
3864     ssl->in_hdr = NULL;
3865     ssl->in_ctr = NULL;
3866     ssl->in_len = NULL;
3867     ssl->in_iv = NULL;
3868     ssl->in_msg = NULL;
3869 
3870     ssl->out_hdr = NULL;
3871     ssl->out_ctr = NULL;
3872     ssl->out_len = NULL;
3873     ssl->out_iv = NULL;
3874     ssl->out_msg = NULL;
3875 
3876     return( ret );
3877 }
3878 
3879 /*
3880  * Reset an initialized and used SSL context for re-use while retaining
3881  * all application-set variables, function pointers and data.
3882  *
3883  * If partial is non-zero, keep data in the input buffer and client ID.
3884  * (Use when a DTLS client reconnects from the same port.)
3885  */
3886 int mbedtls_ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
3887 {
3888     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3889 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3890     size_t in_buf_len = ssl->in_buf_len;
3891     size_t out_buf_len = ssl->out_buf_len;
3892 #else
3893     size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
3894     size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
3895 #endif
3896 
3897 #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) ||     \
3898     !defined(MBEDTLS_SSL_SRV_C)
3899     ((void) partial);
3900 #endif
3901 
3902     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
3903 
3904     /* Cancel any possibly running timer */
3905     mbedtls_ssl_set_timer( ssl, 0 );
3906 
3907 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3908     ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
3909     ssl->renego_records_seen = 0;
3910 
3911     ssl->verify_data_len = 0;
3912     memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
3913     memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
3914 #endif
3915     ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
3916 
3917     ssl->in_offt = NULL;
3918     mbedtls_ssl_reset_in_out_pointers( ssl );
3919 
3920     ssl->in_msgtype = 0;
3921     ssl->in_msglen = 0;
3922 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3923     ssl->next_record_offset = 0;
3924     ssl->in_epoch = 0;
3925 #endif
3926 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3927     mbedtls_ssl_dtls_replay_reset( ssl );
3928 #endif
3929 
3930     ssl->in_hslen = 0;
3931     ssl->nb_zero = 0;
3932 
3933     ssl->keep_current_message = 0;
3934 
3935     ssl->out_msgtype = 0;
3936     ssl->out_msglen = 0;
3937     ssl->out_left = 0;
3938 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
3939     if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
3940         ssl->split_done = 0;
3941 #endif
3942 
3943     memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) );
3944 
3945     ssl->transform_in = NULL;
3946     ssl->transform_out = NULL;
3947 
3948     ssl->session_in = NULL;
3949     ssl->session_out = NULL;
3950 
3951     memset( ssl->out_buf, 0, out_buf_len );
3952 
3953 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3954     if( partial == 0 )
3955 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3956     {
3957         ssl->in_left = 0;
3958         memset( ssl->in_buf, 0, in_buf_len );
3959     }
3960 
3961 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3962     if( mbedtls_ssl_hw_record_reset != NULL )
3963     {
3964         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
3965         if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
3966         {
3967             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
3968             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3969         }
3970     }
3971 #endif
3972 
3973     if( ssl->transform )
3974     {
3975         mbedtls_ssl_transform_free( ssl->transform );
3976         mbedtls_free( ssl->transform );
3977         ssl->transform = NULL;
3978     }
3979 
3980     if( ssl->session )
3981     {
3982         mbedtls_ssl_session_free( ssl->session );
3983         mbedtls_free( ssl->session );
3984         ssl->session = NULL;
3985     }
3986 
3987 #if defined(MBEDTLS_SSL_ALPN)
3988     ssl->alpn_chosen = NULL;
3989 #endif
3990 
3991 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
3992 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
3993     if( partial == 0 )
3994 #endif
3995     {
3996         mbedtls_free( ssl->cli_id );
3997         ssl->cli_id = NULL;
3998         ssl->cli_id_len = 0;
3999     }
4000 #endif
4001 
4002     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
4003         return( ret );
4004 
4005     return( 0 );
4006 }
4007 
4008 /*
4009  * Reset an initialized and used SSL context for re-use while retaining
4010  * all application-set variables, function pointers and data.
4011  */
4012 int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
4013 {
4014     return( mbedtls_ssl_session_reset_int( ssl, 0 ) );
4015 }
4016 
4017 /*
4018  * SSL set accessors
4019  */
4020 void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
4021 {
4022     conf->endpoint   = endpoint;
4023 }
4024 
4025 void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
4026 {
4027     conf->transport = transport;
4028 }
4029 
4030 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4031 void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
4032 {
4033     conf->anti_replay = mode;
4034 }
4035 #endif
4036 
4037 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
4038 void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
4039 {
4040     conf->badmac_limit = limit;
4041 }
4042 #endif
4043 
4044 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4045 
4046 void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl,
4047                                        unsigned allow_packing )
4048 {
4049     ssl->disable_datagram_packing = !allow_packing;
4050 }
4051 
4052 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf,
4053                                          uint32_t min, uint32_t max )
4054 {
4055     conf->hs_timeout_min = min;
4056     conf->hs_timeout_max = max;
4057 }
4058 #endif
4059 
4060 void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
4061 {
4062     conf->authmode   = authmode;
4063 }
4064 
4065 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4066 void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
4067                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
4068                      void *p_vrfy )
4069 {
4070     conf->f_vrfy      = f_vrfy;
4071     conf->p_vrfy      = p_vrfy;
4072 }
4073 #endif /* MBEDTLS_X509_CRT_PARSE_C */
4074 
4075 void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
4076                   int (*f_rng)(void *, unsigned char *, size_t),
4077                   void *p_rng )
4078 {
4079     conf->f_rng      = f_rng;
4080     conf->p_rng      = p_rng;
4081 }
4082 
4083 void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
4084                   void (*f_dbg)(void *, int, const char *, int, const char *),
4085                   void  *p_dbg )
4086 {
4087     conf->f_dbg      = f_dbg;
4088     conf->p_dbg      = p_dbg;
4089 }
4090 
4091 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
4092         void *p_bio,
4093         mbedtls_ssl_send_t *f_send,
4094         mbedtls_ssl_recv_t *f_recv,
4095         mbedtls_ssl_recv_timeout_t *f_recv_timeout )
4096 {
4097     ssl->p_bio          = p_bio;
4098     ssl->f_send         = f_send;
4099     ssl->f_recv         = f_recv;
4100     ssl->f_recv_timeout = f_recv_timeout;
4101 }
4102 
4103 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4104 void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu )
4105 {
4106     ssl->mtu = mtu;
4107 }
4108 #endif
4109 
4110 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
4111 {
4112     conf->read_timeout   = timeout;
4113 }
4114 
4115 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
4116                                void *p_timer,
4117                                mbedtls_ssl_set_timer_t *f_set_timer,
4118                                mbedtls_ssl_get_timer_t *f_get_timer )
4119 {
4120     ssl->p_timer        = p_timer;
4121     ssl->f_set_timer    = f_set_timer;
4122     ssl->f_get_timer    = f_get_timer;
4123 
4124     /* Make sure we start with no timer running */
4125     mbedtls_ssl_set_timer( ssl, 0 );
4126 }
4127 
4128 #if defined(MBEDTLS_SSL_SRV_C)
4129 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
4130         void *p_cache,
4131         int (*f_get_cache)(void *, mbedtls_ssl_session *),
4132         int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
4133 {
4134     conf->p_cache = p_cache;
4135     conf->f_get_cache = f_get_cache;
4136     conf->f_set_cache = f_set_cache;
4137 }
4138 #endif /* MBEDTLS_SSL_SRV_C */
4139 
4140 #if defined(MBEDTLS_SSL_CLI_C)
4141 int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
4142 {
4143     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4144 
4145     if( ssl == NULL ||
4146         session == NULL ||
4147         ssl->session_negotiate == NULL ||
4148         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
4149     {
4150         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4151     }
4152 
4153     if( ( ret = mbedtls_ssl_session_copy( ssl->session_negotiate,
4154                                           session ) ) != 0 )
4155         return( ret );
4156 
4157     ssl->handshake->resume = 1;
4158 
4159     return( 0 );
4160 }
4161 #endif /* MBEDTLS_SSL_CLI_C */
4162 
4163 void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
4164                                    const int *ciphersuites )
4165 {
4166     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
4167     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
4168     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
4169     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
4170 }
4171 
4172 void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
4173                                        const int *ciphersuites,
4174                                        int major, int minor )
4175 {
4176     if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
4177         return;
4178 
4179     if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
4180         return;
4181 
4182     conf->ciphersuite_list[minor] = ciphersuites;
4183 }
4184 
4185 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4186 void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
4187                                     const mbedtls_x509_crt_profile *profile )
4188 {
4189     conf->cert_profile = profile;
4190 }
4191 
4192 /* Append a new keycert entry to a (possibly empty) list */
4193 static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
4194                                 mbedtls_x509_crt *cert,
4195                                 mbedtls_pk_context *key )
4196 {
4197     mbedtls_ssl_key_cert *new_cert;
4198 
4199     new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
4200     if( new_cert == NULL )
4201         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4202 
4203     new_cert->cert = cert;
4204     new_cert->key  = key;
4205     new_cert->next = NULL;
4206 
4207     /* Update head is the list was null, else add to the end */
4208     if( *head == NULL )
4209     {
4210         *head = new_cert;
4211     }
4212     else
4213     {
4214         mbedtls_ssl_key_cert *cur = *head;
4215         while( cur->next != NULL )
4216             cur = cur->next;
4217         cur->next = new_cert;
4218     }
4219 
4220     return( 0 );
4221 }
4222 
4223 int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
4224                               mbedtls_x509_crt *own_cert,
4225                               mbedtls_pk_context *pk_key )
4226 {
4227     return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
4228 }
4229 
4230 void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
4231                                mbedtls_x509_crt *ca_chain,
4232                                mbedtls_x509_crl *ca_crl )
4233 {
4234     conf->ca_chain   = ca_chain;
4235     conf->ca_crl     = ca_crl;
4236 
4237 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
4238     /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
4239      * cannot be used together. */
4240     conf->f_ca_cb = NULL;
4241     conf->p_ca_cb = NULL;
4242 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
4243 }
4244 
4245 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
4246 void mbedtls_ssl_conf_ca_cb( mbedtls_ssl_config *conf,
4247                              mbedtls_x509_crt_ca_cb_t f_ca_cb,
4248                              void *p_ca_cb )
4249 {
4250     conf->f_ca_cb = f_ca_cb;
4251     conf->p_ca_cb = p_ca_cb;
4252 
4253     /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
4254      * cannot be used together. */
4255     conf->ca_chain   = NULL;
4256     conf->ca_crl     = NULL;
4257 }
4258 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
4259 #endif /* MBEDTLS_X509_CRT_PARSE_C */
4260 
4261 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4262 int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
4263                                  mbedtls_x509_crt *own_cert,
4264                                  mbedtls_pk_context *pk_key )
4265 {
4266     return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
4267                                  own_cert, pk_key ) );
4268 }
4269 
4270 void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
4271                                   mbedtls_x509_crt *ca_chain,
4272                                   mbedtls_x509_crl *ca_crl )
4273 {
4274     ssl->handshake->sni_ca_chain   = ca_chain;
4275     ssl->handshake->sni_ca_crl     = ca_crl;
4276 }
4277 
4278 void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
4279                                   int authmode )
4280 {
4281     ssl->handshake->sni_authmode = authmode;
4282 }
4283 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
4284 
4285 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4286 void mbedtls_ssl_set_verify( mbedtls_ssl_context *ssl,
4287                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
4288                      void *p_vrfy )
4289 {
4290     ssl->f_vrfy = f_vrfy;
4291     ssl->p_vrfy = p_vrfy;
4292 }
4293 #endif
4294 
4295 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4296 /*
4297  * Set EC J-PAKE password for current handshake
4298  */
4299 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
4300                                          const unsigned char *pw,
4301                                          size_t pw_len )
4302 {
4303     mbedtls_ecjpake_role role;
4304 
4305     if( ssl->handshake == NULL || ssl->conf == NULL )
4306         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4307 
4308     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
4309         role = MBEDTLS_ECJPAKE_SERVER;
4310     else
4311         role = MBEDTLS_ECJPAKE_CLIENT;
4312 
4313     return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
4314                                    role,
4315                                    MBEDTLS_MD_SHA256,
4316                                    MBEDTLS_ECP_DP_SECP256R1,
4317                                    pw, pw_len ) );
4318 }
4319 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4320 
4321 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
4322 
4323 static void ssl_conf_remove_psk( mbedtls_ssl_config *conf )
4324 {
4325     /* Remove reference to existing PSK, if any. */
4326 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4327     if( conf->psk_opaque != 0 )
4328     {
4329         /* The maintenance of the PSK key slot is the
4330          * user's responsibility. */
4331         conf->psk_opaque = 0;
4332     }
4333     /* This and the following branch should never
4334      * be taken simultaenously as we maintain the
4335      * invariant that raw and opaque PSKs are never
4336      * configured simultaneously. As a safeguard,
4337      * though, `else` is omitted here. */
4338 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4339     if( conf->psk != NULL )
4340     {
4341         mbedtls_platform_zeroize( conf->psk, conf->psk_len );
4342 
4343         mbedtls_free( conf->psk );
4344         conf->psk = NULL;
4345         conf->psk_len = 0;
4346     }
4347 
4348     /* Remove reference to PSK identity, if any. */
4349     if( conf->psk_identity != NULL )
4350     {
4351         mbedtls_free( conf->psk_identity );
4352         conf->psk_identity = NULL;
4353         conf->psk_identity_len = 0;
4354     }
4355 }
4356 
4357 /* This function assumes that PSK identity in the SSL config is unset.
4358  * It checks that the provided identity is well-formed and attempts
4359  * to make a copy of it in the SSL config.
4360  * On failure, the PSK identity in the config remains unset. */
4361 static int ssl_conf_set_psk_identity( mbedtls_ssl_config *conf,
4362                                       unsigned char const *psk_identity,
4363                                       size_t psk_identity_len )
4364 {
4365     /* Identity len will be encoded on two bytes */
4366     if( psk_identity               == NULL ||
4367         ( psk_identity_len >> 16 ) != 0    ||
4368         psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
4369     {
4370         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4371     }
4372 
4373     conf->psk_identity = mbedtls_calloc( 1, psk_identity_len );
4374     if( conf->psk_identity == NULL )
4375         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4376 
4377     conf->psk_identity_len = psk_identity_len;
4378     memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
4379 
4380     return( 0 );
4381 }
4382 
4383 int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
4384                 const unsigned char *psk, size_t psk_len,
4385                 const unsigned char *psk_identity, size_t psk_identity_len )
4386 {
4387     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4388     /* Remove opaque/raw PSK + PSK Identity */
4389     ssl_conf_remove_psk( conf );
4390 
4391     /* Check and set raw PSK */
4392     if( psk == NULL )
4393         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4394     if( psk_len == 0 )
4395         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4396     if( psk_len > MBEDTLS_PSK_MAX_LEN )
4397         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4398 
4399     if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
4400         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4401     conf->psk_len = psk_len;
4402     memcpy( conf->psk, psk, conf->psk_len );
4403 
4404     /* Check and set PSK Identity */
4405     ret = ssl_conf_set_psk_identity( conf, psk_identity, psk_identity_len );
4406     if( ret != 0 )
4407         ssl_conf_remove_psk( conf );
4408 
4409     return( ret );
4410 }
4411 
4412 static void ssl_remove_psk( mbedtls_ssl_context *ssl )
4413 {
4414 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4415     if( ssl->handshake->psk_opaque != 0 )
4416     {
4417         ssl->handshake->psk_opaque = 0;
4418     }
4419     else
4420 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4421     if( ssl->handshake->psk != NULL )
4422     {
4423         mbedtls_platform_zeroize( ssl->handshake->psk,
4424                                   ssl->handshake->psk_len );
4425         mbedtls_free( ssl->handshake->psk );
4426         ssl->handshake->psk_len = 0;
4427     }
4428 }
4429 
4430 int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
4431                             const unsigned char *psk, size_t psk_len )
4432 {
4433     if( psk == NULL || ssl->handshake == NULL )
4434         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4435 
4436     if( psk_len > MBEDTLS_PSK_MAX_LEN )
4437         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4438 
4439     ssl_remove_psk( ssl );
4440 
4441     if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
4442         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4443 
4444     ssl->handshake->psk_len = psk_len;
4445     memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
4446 
4447     return( 0 );
4448 }
4449 
4450 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4451 int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf,
4452                                  psa_key_handle_t psk_slot,
4453                                  const unsigned char *psk_identity,
4454                                  size_t psk_identity_len )
4455 {
4456     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4457     /* Clear opaque/raw PSK + PSK Identity, if present. */
4458     ssl_conf_remove_psk( conf );
4459 
4460     /* Check and set opaque PSK */
4461     if( psk_slot == 0 )
4462         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4463     conf->psk_opaque = psk_slot;
4464 
4465     /* Check and set PSK Identity */
4466     ret = ssl_conf_set_psk_identity( conf, psk_identity,
4467                                      psk_identity_len );
4468     if( ret != 0 )
4469         ssl_conf_remove_psk( conf );
4470 
4471     return( ret );
4472 }
4473 
4474 int mbedtls_ssl_set_hs_psk_opaque( mbedtls_ssl_context *ssl,
4475                                    psa_key_handle_t psk_slot )
4476 {
4477     if( psk_slot == 0 || ssl->handshake == NULL )
4478         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4479 
4480     ssl_remove_psk( ssl );
4481     ssl->handshake->psk_opaque = psk_slot;
4482     return( 0 );
4483 }
4484 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4485 
4486 void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
4487                      int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
4488                      size_t),
4489                      void *p_psk )
4490 {
4491     conf->f_psk = f_psk;
4492     conf->p_psk = p_psk;
4493 }
4494 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
4495 
4496 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
4497 
4498 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
4499 int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
4500 {
4501     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4502 
4503     if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||
4504         ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )
4505     {
4506         mbedtls_mpi_free( &conf->dhm_P );
4507         mbedtls_mpi_free( &conf->dhm_G );
4508         return( ret );
4509     }
4510 
4511     return( 0 );
4512 }
4513 #endif /* MBEDTLS_DEPRECATED_REMOVED */
4514 
4515 int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
4516                                    const unsigned char *dhm_P, size_t P_len,
4517                                    const unsigned char *dhm_G, size_t G_len )
4518 {
4519     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4520 
4521     if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 ||
4522         ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 )
4523     {
4524         mbedtls_mpi_free( &conf->dhm_P );
4525         mbedtls_mpi_free( &conf->dhm_G );
4526         return( ret );
4527     }
4528 
4529     return( 0 );
4530 }
4531 
4532 int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
4533 {
4534     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4535 
4536     if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||
4537         ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )
4538     {
4539         mbedtls_mpi_free( &conf->dhm_P );
4540         mbedtls_mpi_free( &conf->dhm_G );
4541         return( ret );
4542     }
4543 
4544     return( 0 );
4545 }
4546 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
4547 
4548 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
4549 /*
4550  * Set the minimum length for Diffie-Hellman parameters
4551  */
4552 void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
4553                                       unsigned int bitlen )
4554 {
4555     conf->dhm_min_bitlen = bitlen;
4556 }
4557 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
4558 
4559 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
4560 /*
4561  * Set allowed/preferred hashes for handshake signatures
4562  */
4563 void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
4564                                   const int *hashes )
4565 {
4566     conf->sig_hashes = hashes;
4567 }
4568 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
4569 
4570 #if defined(MBEDTLS_ECP_C)
4571 /*
4572  * Set the allowed elliptic curves
4573  */
4574 void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
4575                              const mbedtls_ecp_group_id *curve_list )
4576 {
4577     conf->curve_list = curve_list;
4578 }
4579 #endif /* MBEDTLS_ECP_C */
4580 
4581 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4582 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
4583 {
4584     /* Initialize to suppress unnecessary compiler warning */
4585     size_t hostname_len = 0;
4586 
4587     /* Check if new hostname is valid before
4588      * making any change to current one */
4589     if( hostname != NULL )
4590     {
4591         hostname_len = strlen( hostname );
4592 
4593         if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
4594             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4595     }
4596 
4597     /* Now it's clear that we will overwrite the old hostname,
4598      * so we can free it safely */
4599 
4600     if( ssl->hostname != NULL )
4601     {
4602         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
4603         mbedtls_free( ssl->hostname );
4604     }
4605 
4606     /* Passing NULL as hostname shall clear the old one */
4607 
4608     if( hostname == NULL )
4609     {
4610         ssl->hostname = NULL;
4611     }
4612     else
4613     {
4614         ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
4615         if( ssl->hostname == NULL )
4616             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4617 
4618         memcpy( ssl->hostname, hostname, hostname_len );
4619 
4620         ssl->hostname[hostname_len] = '\0';
4621     }
4622 
4623     return( 0 );
4624 }
4625 #endif /* MBEDTLS_X509_CRT_PARSE_C */
4626 
4627 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4628 void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
4629                   int (*f_sni)(void *, mbedtls_ssl_context *,
4630                                 const unsigned char *, size_t),
4631                   void *p_sni )
4632 {
4633     conf->f_sni = f_sni;
4634     conf->p_sni = p_sni;
4635 }
4636 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
4637 
4638 #if defined(MBEDTLS_SSL_ALPN)
4639 int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
4640 {
4641     size_t cur_len, tot_len;
4642     const char **p;
4643 
4644     /*
4645      * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
4646      * MUST NOT be truncated."
4647      * We check lengths now rather than later.
4648      */
4649     tot_len = 0;
4650     for( p = protos; *p != NULL; p++ )
4651     {
4652         cur_len = strlen( *p );
4653         tot_len += cur_len;
4654 
4655         if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
4656             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4657     }
4658 
4659     conf->alpn_list = protos;
4660 
4661     return( 0 );
4662 }
4663 
4664 const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
4665 {
4666     return( ssl->alpn_chosen );
4667 }
4668 #endif /* MBEDTLS_SSL_ALPN */
4669 
4670 void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
4671 {
4672     conf->max_major_ver = major;
4673     conf->max_minor_ver = minor;
4674 }
4675 
4676 void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
4677 {
4678     conf->min_major_ver = major;
4679     conf->min_minor_ver = minor;
4680 }
4681 
4682 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
4683 void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
4684 {
4685     conf->fallback = fallback;
4686 }
4687 #endif
4688 
4689 #if defined(MBEDTLS_SSL_SRV_C)
4690 void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
4691                                           char cert_req_ca_list )
4692 {
4693     conf->cert_req_ca_list = cert_req_ca_list;
4694 }
4695 #endif
4696 
4697 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
4698 void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
4699 {
4700     conf->encrypt_then_mac = etm;
4701 }
4702 #endif
4703 
4704 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
4705 void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
4706 {
4707     conf->extended_ms = ems;
4708 }
4709 #endif
4710 
4711 #if defined(MBEDTLS_ARC4_C)
4712 void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
4713 {
4714     conf->arc4_disabled = arc4;
4715 }
4716 #endif
4717 
4718 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
4719 int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
4720 {
4721     if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
4722         ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN )
4723     {
4724         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4725     }
4726 
4727     conf->mfl_code = mfl_code;
4728 
4729     return( 0 );
4730 }
4731 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
4732 
4733 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
4734 void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
4735 {
4736     conf->trunc_hmac = truncate;
4737 }
4738 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
4739 
4740 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
4741 void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
4742 {
4743     conf->cbc_record_splitting = split;
4744 }
4745 #endif
4746 
4747 void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
4748 {
4749     conf->allow_legacy_renegotiation = allow_legacy;
4750 }
4751 
4752 #if defined(MBEDTLS_SSL_RENEGOTIATION)
4753 void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
4754 {
4755     conf->disable_renegotiation = renegotiation;
4756 }
4757 
4758 void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
4759 {
4760     conf->renego_max_records = max_records;
4761 }
4762 
4763 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
4764                                    const unsigned char period[8] )
4765 {
4766     memcpy( conf->renego_period, period, 8 );
4767 }
4768 #endif /* MBEDTLS_SSL_RENEGOTIATION */
4769 
4770 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
4771 #if defined(MBEDTLS_SSL_CLI_C)
4772 void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
4773 {
4774     conf->session_tickets = use_tickets;
4775 }
4776 #endif
4777 
4778 #if defined(MBEDTLS_SSL_SRV_C)
4779 void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
4780         mbedtls_ssl_ticket_write_t *f_ticket_write,
4781         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
4782         void *p_ticket )
4783 {
4784     conf->f_ticket_write = f_ticket_write;
4785     conf->f_ticket_parse = f_ticket_parse;
4786     conf->p_ticket       = p_ticket;
4787 }
4788 #endif
4789 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
4790 
4791 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
4792 void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
4793         mbedtls_ssl_export_keys_t *f_export_keys,
4794         void *p_export_keys )
4795 {
4796     conf->f_export_keys = f_export_keys;
4797     conf->p_export_keys = p_export_keys;
4798 }
4799 
4800 void mbedtls_ssl_conf_export_keys_ext_cb( mbedtls_ssl_config *conf,
4801         mbedtls_ssl_export_keys_ext_t *f_export_keys_ext,
4802         void *p_export_keys )
4803 {
4804     conf->f_export_keys_ext = f_export_keys_ext;
4805     conf->p_export_keys = p_export_keys;
4806 }
4807 #endif
4808 
4809 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
4810 void mbedtls_ssl_conf_async_private_cb(
4811     mbedtls_ssl_config *conf,
4812     mbedtls_ssl_async_sign_t *f_async_sign,
4813     mbedtls_ssl_async_decrypt_t *f_async_decrypt,
4814     mbedtls_ssl_async_resume_t *f_async_resume,
4815     mbedtls_ssl_async_cancel_t *f_async_cancel,
4816     void *async_config_data )
4817 {
4818     conf->f_async_sign_start = f_async_sign;
4819     conf->f_async_decrypt_start = f_async_decrypt;
4820     conf->f_async_resume = f_async_resume;
4821     conf->f_async_cancel = f_async_cancel;
4822     conf->p_async_config_data = async_config_data;
4823 }
4824 
4825 void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf )
4826 {
4827     return( conf->p_async_config_data );
4828 }
4829 
4830 void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl )
4831 {
4832     if( ssl->handshake == NULL )
4833         return( NULL );
4834     else
4835         return( ssl->handshake->user_async_ctx );
4836 }
4837 
4838 void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,
4839                                  void *ctx )
4840 {
4841     if( ssl->handshake != NULL )
4842         ssl->handshake->user_async_ctx = ctx;
4843 }
4844 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
4845 
4846 /*
4847  * SSL get accessors
4848  */
4849 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
4850 {
4851     if( ssl->session != NULL )
4852         return( ssl->session->verify_result );
4853 
4854     if( ssl->session_negotiate != NULL )
4855         return( ssl->session_negotiate->verify_result );
4856 
4857     return( 0xFFFFFFFF );
4858 }
4859 
4860 const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
4861 {
4862     if( ssl == NULL || ssl->session == NULL )
4863         return( NULL );
4864 
4865     return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
4866 }
4867 
4868 const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
4869 {
4870 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4871     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4872     {
4873         switch( ssl->minor_ver )
4874         {
4875             case MBEDTLS_SSL_MINOR_VERSION_2:
4876                 return( "DTLSv1.0" );
4877 
4878             case MBEDTLS_SSL_MINOR_VERSION_3:
4879                 return( "DTLSv1.2" );
4880 
4881             default:
4882                 return( "unknown (DTLS)" );
4883         }
4884     }
4885 #endif
4886 
4887     switch( ssl->minor_ver )
4888     {
4889         case MBEDTLS_SSL_MINOR_VERSION_0:
4890             return( "SSLv3.0" );
4891 
4892         case MBEDTLS_SSL_MINOR_VERSION_1:
4893             return( "TLSv1.0" );
4894 
4895         case MBEDTLS_SSL_MINOR_VERSION_2:
4896             return( "TLSv1.1" );
4897 
4898         case MBEDTLS_SSL_MINOR_VERSION_3:
4899             return( "TLSv1.2" );
4900 
4901         default:
4902             return( "unknown" );
4903     }
4904 }
4905 
4906 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
4907 size_t mbedtls_ssl_get_input_max_frag_len( const mbedtls_ssl_context *ssl )
4908 {
4909     size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN;
4910     size_t read_mfl;
4911 
4912     /* Use the configured MFL for the client if we're past SERVER_HELLO_DONE */
4913     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
4914         ssl->state >= MBEDTLS_SSL_SERVER_HELLO_DONE )
4915     {
4916         return ssl_mfl_code_to_length( ssl->conf->mfl_code );
4917     }
4918 
4919     /* Check if a smaller max length was negotiated */
4920     if( ssl->session_out != NULL )
4921     {
4922         read_mfl = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
4923         if( read_mfl < max_len )
4924         {
4925             max_len = read_mfl;
4926         }
4927     }
4928 
4929     // During a handshake, use the value being negotiated
4930     if( ssl->session_negotiate != NULL )
4931     {
4932         read_mfl = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
4933         if( read_mfl < max_len )
4934         {
4935             max_len = read_mfl;
4936         }
4937     }
4938 
4939     return( max_len );
4940 }
4941 
4942 size_t mbedtls_ssl_get_output_max_frag_len( const mbedtls_ssl_context *ssl )
4943 {
4944     size_t max_len;
4945 
4946     /*
4947      * Assume mfl_code is correct since it was checked when set
4948      */
4949     max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code );
4950 
4951     /* Check if a smaller max length was negotiated */
4952     if( ssl->session_out != NULL &&
4953         ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len )
4954     {
4955         max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
4956     }
4957 
4958     /* During a handshake, use the value being negotiated */
4959     if( ssl->session_negotiate != NULL &&
4960         ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len )
4961     {
4962         max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
4963     }
4964 
4965     return( max_len );
4966 }
4967 
4968 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
4969 size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
4970 {
4971     return mbedtls_ssl_get_output_max_frag_len( ssl );
4972 }
4973 #endif /* !MBEDTLS_DEPRECATED_REMOVED */
4974 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
4975 
4976 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4977 size_t mbedtls_ssl_get_current_mtu( const mbedtls_ssl_context *ssl )
4978 {
4979     /* Return unlimited mtu for client hello messages to avoid fragmentation. */
4980     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
4981         ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO ||
4982           ssl->state == MBEDTLS_SSL_SERVER_HELLO ) )
4983         return ( 0 );
4984 
4985     if( ssl->handshake == NULL || ssl->handshake->mtu == 0 )
4986         return( ssl->mtu );
4987 
4988     if( ssl->mtu == 0 )
4989         return( ssl->handshake->mtu );
4990 
4991     return( ssl->mtu < ssl->handshake->mtu ?
4992             ssl->mtu : ssl->handshake->mtu );
4993 }
4994 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4995 
4996 int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl )
4997 {
4998     size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
4999 
5000 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
5001     !defined(MBEDTLS_SSL_PROTO_DTLS)
5002     (void) ssl;
5003 #endif
5004 
5005 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5006     const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl );
5007 
5008     if( max_len > mfl )
5009         max_len = mfl;
5010 #endif
5011 
5012 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5013     if( mbedtls_ssl_get_current_mtu( ssl ) != 0 )
5014     {
5015         const size_t mtu = mbedtls_ssl_get_current_mtu( ssl );
5016         const int ret = mbedtls_ssl_get_record_expansion( ssl );
5017         const size_t overhead = (size_t) ret;
5018 
5019         if( ret < 0 )
5020             return( ret );
5021 
5022         if( mtu <= overhead )
5023         {
5024             MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) );
5025             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5026         }
5027 
5028         if( max_len > mtu - overhead )
5029             max_len = mtu - overhead;
5030     }
5031 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5032 
5033 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) &&        \
5034     !defined(MBEDTLS_SSL_PROTO_DTLS)
5035     ((void) ssl);
5036 #endif
5037 
5038     return( (int) max_len );
5039 }
5040 
5041 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5042 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
5043 {
5044     if( ssl == NULL || ssl->session == NULL )
5045         return( NULL );
5046 
5047 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5048     return( ssl->session->peer_cert );
5049 #else
5050     return( NULL );
5051 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5052 }
5053 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5054 
5055 #if defined(MBEDTLS_SSL_CLI_C)
5056 int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl,
5057                              mbedtls_ssl_session *dst )
5058 {
5059     if( ssl == NULL ||
5060         dst == NULL ||
5061         ssl->session == NULL ||
5062         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
5063     {
5064         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5065     }
5066 
5067     return( mbedtls_ssl_session_copy( dst, ssl->session ) );
5068 }
5069 #endif /* MBEDTLS_SSL_CLI_C */
5070 
5071 const mbedtls_ssl_session *mbedtls_ssl_get_session_pointer( const mbedtls_ssl_context *ssl )
5072 {
5073     if( ssl == NULL )
5074         return( NULL );
5075 
5076     return( ssl->session );
5077 }
5078 
5079 /*
5080  * Define ticket header determining Mbed TLS version
5081  * and structure of the ticket.
5082  */
5083 
5084 /*
5085  * Define bitflag determining compile-time settings influencing
5086  * structure of serialized SSL sessions.
5087  */
5088 
5089 #if defined(MBEDTLS_HAVE_TIME)
5090 #define SSL_SERIALIZED_SESSION_CONFIG_TIME 1
5091 #else
5092 #define SSL_SERIALIZED_SESSION_CONFIG_TIME 0
5093 #endif /* MBEDTLS_HAVE_TIME */
5094 
5095 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5096 #define SSL_SERIALIZED_SESSION_CONFIG_CRT 1
5097 #else
5098 #define SSL_SERIALIZED_SESSION_CONFIG_CRT 0
5099 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5100 
5101 #if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SESSION_TICKETS)
5102 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 1
5103 #else
5104 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 0
5105 #endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_SESSION_TICKETS */
5106 
5107 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5108 #define SSL_SERIALIZED_SESSION_CONFIG_MFL 1
5109 #else
5110 #define SSL_SERIALIZED_SESSION_CONFIG_MFL 0
5111 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
5112 
5113 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
5114 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 1
5115 #else
5116 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 0
5117 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
5118 
5119 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5120 #define SSL_SERIALIZED_SESSION_CONFIG_ETM 1
5121 #else
5122 #define SSL_SERIALIZED_SESSION_CONFIG_ETM 0
5123 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
5124 
5125 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
5126 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 1
5127 #else
5128 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 0
5129 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
5130 
5131 #define SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT          0
5132 #define SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT           1
5133 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT 2
5134 #define SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT           3
5135 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT    4
5136 #define SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT           5
5137 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT        6
5138 
5139 #define SSL_SERIALIZED_SESSION_CONFIG_BITFLAG                           \
5140     ( (uint16_t) (                                                      \
5141         ( SSL_SERIALIZED_SESSION_CONFIG_TIME          << SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT          ) | \
5142         ( SSL_SERIALIZED_SESSION_CONFIG_CRT           << SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT           ) | \
5143         ( SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET << SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT ) | \
5144         ( SSL_SERIALIZED_SESSION_CONFIG_MFL           << SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT           ) | \
5145         ( SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC    << SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT    ) | \
5146         ( SSL_SERIALIZED_SESSION_CONFIG_ETM           << SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT           ) | \
5147         ( SSL_SERIALIZED_SESSION_CONFIG_TICKET        << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT        ) ) )
5148 
5149 static unsigned char ssl_serialized_session_header[] = {
5150     MBEDTLS_VERSION_MAJOR,
5151     MBEDTLS_VERSION_MINOR,
5152     MBEDTLS_VERSION_PATCH,
5153     ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 8 ) & 0xFF,
5154     ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 0 ) & 0xFF,
5155 };
5156 
5157 /*
5158  * Serialize a session in the following format:
5159  * (in the presentation language of TLS, RFC 8446 section 3)
5160  *
5161  *  opaque mbedtls_version[3];   // major, minor, patch
5162  *  opaque session_format[2];    // version-specific 16-bit field determining
5163  *                               // the format of the remaining
5164  *                               // serialized data.
5165  *
5166  *  Note: When updating the format, remember to keep
5167  *        these version+format bytes.
5168  *
5169  *                               // In this version, `session_format` determines
5170  *                               // the setting of those compile-time
5171  *                               // configuration options which influence
5172  *                               // the structure of mbedtls_ssl_session.
5173  *  uint64 start_time;
5174  *  uint8 ciphersuite[2];        // defined by the standard
5175  *  uint8 compression;           // 0 or 1
5176  *  uint8 session_id_len;        // at most 32
5177  *  opaque session_id[32];
5178  *  opaque master[48];           // fixed length in the standard
5179  *  uint32 verify_result;
5180  *  opaque peer_cert<0..2^24-1>; // length 0 means no peer cert
5181  *  opaque ticket<0..2^24-1>;    // length 0 means no ticket
5182  *  uint32 ticket_lifetime;
5183  *  uint8 mfl_code;              // up to 255 according to standard
5184  *  uint8 trunc_hmac;            // 0 or 1
5185  *  uint8 encrypt_then_mac;      // 0 or 1
5186  *
5187  * The order is the same as in the definition of the structure, except
5188  * verify_result is put before peer_cert so that all mandatory fields come
5189  * together in one block.
5190  */
5191 static int ssl_session_save( const mbedtls_ssl_session *session,
5192                              unsigned char omit_header,
5193                              unsigned char *buf,
5194                              size_t buf_len,
5195                              size_t *olen )
5196 {
5197     unsigned char *p = buf;
5198     size_t used = 0;
5199 #if defined(MBEDTLS_HAVE_TIME)
5200     uint64_t start;
5201 #endif
5202 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5203 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5204     size_t cert_len;
5205 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5206 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5207 
5208 
5209     if( !omit_header )
5210     {
5211         /*
5212          * Add version identifier
5213          */
5214 
5215         used += sizeof( ssl_serialized_session_header );
5216 
5217         if( used <= buf_len )
5218         {
5219             memcpy( p, ssl_serialized_session_header,
5220                     sizeof( ssl_serialized_session_header ) );
5221             p += sizeof( ssl_serialized_session_header );
5222         }
5223     }
5224 
5225     /*
5226      * Time
5227      */
5228 #if defined(MBEDTLS_HAVE_TIME)
5229     used += 8;
5230 
5231     if( used <= buf_len )
5232     {
5233         start = (uint64_t) session->start;
5234 
5235         *p++ = (unsigned char)( ( start >> 56 ) & 0xFF );
5236         *p++ = (unsigned char)( ( start >> 48 ) & 0xFF );
5237         *p++ = (unsigned char)( ( start >> 40 ) & 0xFF );
5238         *p++ = (unsigned char)( ( start >> 32 ) & 0xFF );
5239         *p++ = (unsigned char)( ( start >> 24 ) & 0xFF );
5240         *p++ = (unsigned char)( ( start >> 16 ) & 0xFF );
5241         *p++ = (unsigned char)( ( start >>  8 ) & 0xFF );
5242         *p++ = (unsigned char)( ( start       ) & 0xFF );
5243     }
5244 #endif /* MBEDTLS_HAVE_TIME */
5245 
5246     /*
5247      * Basic mandatory fields
5248      */
5249     used += 2   /* ciphersuite */
5250           + 1   /* compression */
5251           + 1   /* id_len */
5252           + sizeof( session->id )
5253           + sizeof( session->master )
5254           + 4;  /* verify_result */
5255 
5256     if( used <= buf_len )
5257     {
5258         *p++ = (unsigned char)( ( session->ciphersuite >> 8 ) & 0xFF );
5259         *p++ = (unsigned char)( ( session->ciphersuite      ) & 0xFF );
5260 
5261         *p++ = (unsigned char)( session->compression & 0xFF );
5262 
5263         *p++ = (unsigned char)( session->id_len & 0xFF );
5264         memcpy( p, session->id, 32 );
5265         p += 32;
5266 
5267         memcpy( p, session->master, 48 );
5268         p += 48;
5269 
5270         *p++ = (unsigned char)( ( session->verify_result >> 24 ) & 0xFF );
5271         *p++ = (unsigned char)( ( session->verify_result >> 16 ) & 0xFF );
5272         *p++ = (unsigned char)( ( session->verify_result >>  8 ) & 0xFF );
5273         *p++ = (unsigned char)( ( session->verify_result       ) & 0xFF );
5274     }
5275 
5276     /*
5277      * Peer's end-entity certificate
5278      */
5279 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5280 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5281     if( session->peer_cert == NULL )
5282         cert_len = 0;
5283     else
5284         cert_len = session->peer_cert->raw.len;
5285 
5286     used += 3 + cert_len;
5287 
5288     if( used <= buf_len )
5289     {
5290         *p++ = (unsigned char)( ( cert_len >> 16 ) & 0xFF );
5291         *p++ = (unsigned char)( ( cert_len >>  8 ) & 0xFF );
5292         *p++ = (unsigned char)( ( cert_len       ) & 0xFF );
5293 
5294         if( session->peer_cert != NULL )
5295         {
5296             memcpy( p, session->peer_cert->raw.p, cert_len );
5297             p += cert_len;
5298         }
5299     }
5300 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5301     if( session->peer_cert_digest != NULL )
5302     {
5303         used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len;
5304         if( used <= buf_len )
5305         {
5306             *p++ = (unsigned char) session->peer_cert_digest_type;
5307             *p++ = (unsigned char) session->peer_cert_digest_len;
5308             memcpy( p, session->peer_cert_digest,
5309                     session->peer_cert_digest_len );
5310             p += session->peer_cert_digest_len;
5311         }
5312     }
5313     else
5314     {
5315         used += 2;
5316         if( used <= buf_len )
5317         {
5318             *p++ = (unsigned char) MBEDTLS_MD_NONE;
5319             *p++ = 0;
5320         }
5321     }
5322 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5323 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5324 
5325     /*
5326      * Session ticket if any, plus associated data
5327      */
5328 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5329     used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */
5330 
5331     if( used <= buf_len )
5332     {
5333         *p++ = (unsigned char)( ( session->ticket_len >> 16 ) & 0xFF );
5334         *p++ = (unsigned char)( ( session->ticket_len >>  8 ) & 0xFF );
5335         *p++ = (unsigned char)( ( session->ticket_len       ) & 0xFF );
5336 
5337         if( session->ticket != NULL )
5338         {
5339             memcpy( p, session->ticket, session->ticket_len );
5340             p += session->ticket_len;
5341         }
5342 
5343         *p++ = (unsigned char)( ( session->ticket_lifetime >> 24 ) & 0xFF );
5344         *p++ = (unsigned char)( ( session->ticket_lifetime >> 16 ) & 0xFF );
5345         *p++ = (unsigned char)( ( session->ticket_lifetime >>  8 ) & 0xFF );
5346         *p++ = (unsigned char)( ( session->ticket_lifetime       ) & 0xFF );
5347     }
5348 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5349 
5350     /*
5351      * Misc extension-related info
5352      */
5353 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5354     used += 1;
5355 
5356     if( used <= buf_len )
5357         *p++ = session->mfl_code;
5358 #endif
5359 
5360 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
5361     used += 1;
5362 
5363     if( used <= buf_len )
5364         *p++ = (unsigned char)( ( session->trunc_hmac ) & 0xFF );
5365 #endif
5366 
5367 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5368     used += 1;
5369 
5370     if( used <= buf_len )
5371         *p++ = (unsigned char)( ( session->encrypt_then_mac ) & 0xFF );
5372 #endif
5373 
5374     /* Done */
5375     *olen = used;
5376 
5377     if( used > buf_len )
5378         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
5379 
5380     return( 0 );
5381 }
5382 
5383 /*
5384  * Public wrapper for ssl_session_save()
5385  */
5386 int mbedtls_ssl_session_save( const mbedtls_ssl_session *session,
5387                               unsigned char *buf,
5388                               size_t buf_len,
5389                               size_t *olen )
5390 {
5391     return( ssl_session_save( session, 0, buf, buf_len, olen ) );
5392 }
5393 
5394 /*
5395  * Deserialize session, see mbedtls_ssl_session_save() for format.
5396  *
5397  * This internal version is wrapped by a public function that cleans up in
5398  * case of error, and has an extra option omit_header.
5399  */
5400 static int ssl_session_load( mbedtls_ssl_session *session,
5401                              unsigned char omit_header,
5402                              const unsigned char *buf,
5403                              size_t len )
5404 {
5405     const unsigned char *p = buf;
5406     const unsigned char * const end = buf + len;
5407 #if defined(MBEDTLS_HAVE_TIME)
5408     uint64_t start;
5409 #endif
5410 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5411 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5412     size_t cert_len;
5413 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5414 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5415 
5416     if( !omit_header )
5417     {
5418         /*
5419          * Check version identifier
5420          */
5421 
5422         if( (size_t)( end - p ) < sizeof( ssl_serialized_session_header ) )
5423             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5424 
5425         if( memcmp( p, ssl_serialized_session_header,
5426                     sizeof( ssl_serialized_session_header ) ) != 0 )
5427         {
5428             return( MBEDTLS_ERR_SSL_VERSION_MISMATCH );
5429         }
5430         p += sizeof( ssl_serialized_session_header );
5431     }
5432 
5433     /*
5434      * Time
5435      */
5436 #if defined(MBEDTLS_HAVE_TIME)
5437     if( 8 > (size_t)( end - p ) )
5438         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5439 
5440     start = ( (uint64_t) p[0] << 56 ) |
5441             ( (uint64_t) p[1] << 48 ) |
5442             ( (uint64_t) p[2] << 40 ) |
5443             ( (uint64_t) p[3] << 32 ) |
5444             ( (uint64_t) p[4] << 24 ) |
5445             ( (uint64_t) p[5] << 16 ) |
5446             ( (uint64_t) p[6] <<  8 ) |
5447             ( (uint64_t) p[7]       );
5448     p += 8;
5449 
5450     session->start = (time_t) start;
5451 #endif /* MBEDTLS_HAVE_TIME */
5452 
5453     /*
5454      * Basic mandatory fields
5455      */
5456     if( 2 + 1 + 1 + 32 + 48 + 4 > (size_t)( end - p ) )
5457         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5458 
5459     session->ciphersuite = ( p[0] << 8 ) | p[1];
5460     p += 2;
5461 
5462     session->compression = *p++;
5463 
5464     session->id_len = *p++;
5465     memcpy( session->id, p, 32 );
5466     p += 32;
5467 
5468     memcpy( session->master, p, 48 );
5469     p += 48;
5470 
5471     session->verify_result = ( (uint32_t) p[0] << 24 ) |
5472                              ( (uint32_t) p[1] << 16 ) |
5473                              ( (uint32_t) p[2] <<  8 ) |
5474                              ( (uint32_t) p[3]       );
5475     p += 4;
5476 
5477     /* Immediately clear invalid pointer values that have been read, in case
5478      * we exit early before we replaced them with valid ones. */
5479 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5480 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5481     session->peer_cert = NULL;
5482 #else
5483     session->peer_cert_digest = NULL;
5484 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5485 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5486 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5487     session->ticket = NULL;
5488 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5489 
5490     /*
5491      * Peer certificate
5492      */
5493 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5494 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5495     /* Deserialize CRT from the end of the ticket. */
5496     if( 3 > (size_t)( end - p ) )
5497         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5498 
5499     cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
5500     p += 3;
5501 
5502     if( cert_len != 0 )
5503     {
5504         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5505 
5506         if( cert_len > (size_t)( end - p ) )
5507             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5508 
5509         session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
5510 
5511         if( session->peer_cert == NULL )
5512             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5513 
5514         mbedtls_x509_crt_init( session->peer_cert );
5515 
5516         if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert,
5517                                                 p, cert_len ) ) != 0 )
5518         {
5519             mbedtls_x509_crt_free( session->peer_cert );
5520             mbedtls_free( session->peer_cert );
5521             session->peer_cert = NULL;
5522             return( ret );
5523         }
5524 
5525         p += cert_len;
5526     }
5527 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5528     /* Deserialize CRT digest from the end of the ticket. */
5529     if( 2 > (size_t)( end - p ) )
5530         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5531 
5532     session->peer_cert_digest_type = (mbedtls_md_type_t) *p++;
5533     session->peer_cert_digest_len  = (size_t) *p++;
5534 
5535     if( session->peer_cert_digest_len != 0 )
5536     {
5537         const mbedtls_md_info_t *md_info =
5538             mbedtls_md_info_from_type( session->peer_cert_digest_type );
5539         if( md_info == NULL )
5540             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5541         if( session->peer_cert_digest_len != mbedtls_md_get_size( md_info ) )
5542             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5543 
5544         if( session->peer_cert_digest_len > (size_t)( end - p ) )
5545             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5546 
5547         session->peer_cert_digest =
5548             mbedtls_calloc( 1, session->peer_cert_digest_len );
5549         if( session->peer_cert_digest == NULL )
5550             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5551 
5552         memcpy( session->peer_cert_digest, p,
5553                 session->peer_cert_digest_len );
5554         p += session->peer_cert_digest_len;
5555     }
5556 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5557 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5558 
5559     /*
5560      * Session ticket and associated data
5561      */
5562 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5563     if( 3 > (size_t)( end - p ) )
5564         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5565 
5566     session->ticket_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
5567     p += 3;
5568 
5569     if( session->ticket_len != 0 )
5570     {
5571         if( session->ticket_len > (size_t)( end - p ) )
5572             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5573 
5574         session->ticket = mbedtls_calloc( 1, session->ticket_len );
5575         if( session->ticket == NULL )
5576             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5577 
5578         memcpy( session->ticket, p, session->ticket_len );
5579         p += session->ticket_len;
5580     }
5581 
5582     if( 4 > (size_t)( end - p ) )
5583         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5584 
5585     session->ticket_lifetime = ( (uint32_t) p[0] << 24 ) |
5586                                ( (uint32_t) p[1] << 16 ) |
5587                                ( (uint32_t) p[2] <<  8 ) |
5588                                ( (uint32_t) p[3]       );
5589     p += 4;
5590 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5591 
5592     /*
5593      * Misc extension-related info
5594      */
5595 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5596     if( 1 > (size_t)( end - p ) )
5597         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5598 
5599     session->mfl_code = *p++;
5600 #endif
5601 
5602 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
5603     if( 1 > (size_t)( end - p ) )
5604         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5605 
5606     session->trunc_hmac = *p++;
5607 #endif
5608 
5609 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5610     if( 1 > (size_t)( end - p ) )
5611         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5612 
5613     session->encrypt_then_mac = *p++;
5614 #endif
5615 
5616     /* Done, should have consumed entire buffer */
5617     if( p != end )
5618         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5619 
5620     return( 0 );
5621 }
5622 
5623 /*
5624  * Deserialize session: public wrapper for error cleaning
5625  */
5626 int mbedtls_ssl_session_load( mbedtls_ssl_session *session,
5627                               const unsigned char *buf,
5628                               size_t len )
5629 {
5630     int ret = ssl_session_load( session, 0, buf, len );
5631 
5632     if( ret != 0 )
5633         mbedtls_ssl_session_free( session );
5634 
5635     return( ret );
5636 }
5637 
5638 /*
5639  * Perform a single step of the SSL handshake
5640  */
5641 int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
5642 {
5643     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
5644 
5645     if( ssl == NULL || ssl->conf == NULL )
5646         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5647 
5648 #if defined(MBEDTLS_SSL_CLI_C)
5649     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5650         ret = mbedtls_ssl_handshake_client_step( ssl );
5651 #endif
5652 #if defined(MBEDTLS_SSL_SRV_C)
5653     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5654         ret = mbedtls_ssl_handshake_server_step( ssl );
5655 #endif
5656 
5657     return( ret );
5658 }
5659 
5660 /*
5661  * Perform the SSL handshake
5662  */
5663 int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
5664 {
5665     int ret = 0;
5666 
5667     if( ssl == NULL || ssl->conf == NULL )
5668         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5669 
5670     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
5671 
5672     while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
5673     {
5674         ret = mbedtls_ssl_handshake_step( ssl );
5675 
5676         if( ret != 0 )
5677             break;
5678     }
5679 
5680     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
5681 
5682     return( ret );
5683 }
5684 
5685 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5686 #if defined(MBEDTLS_SSL_SRV_C)
5687 /*
5688  * Write HelloRequest to request renegotiation on server
5689  */
5690 static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
5691 {
5692     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5693 
5694     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
5695 
5696     ssl->out_msglen  = 4;
5697     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
5698     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;
5699 
5700     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
5701     {
5702         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
5703         return( ret );
5704     }
5705 
5706     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
5707 
5708     return( 0 );
5709 }
5710 #endif /* MBEDTLS_SSL_SRV_C */
5711 
5712 /*
5713  * Actually renegotiate current connection, triggered by either:
5714  * - any side: calling mbedtls_ssl_renegotiate(),
5715  * - client: receiving a HelloRequest during mbedtls_ssl_read(),
5716  * - server: receiving any handshake message on server during mbedtls_ssl_read() after
5717  *   the initial handshake is completed.
5718  * If the handshake doesn't complete due to waiting for I/O, it will continue
5719  * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
5720  */
5721 int mbedtls_ssl_start_renegotiation( mbedtls_ssl_context *ssl )
5722 {
5723     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5724 
5725     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
5726 
5727     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5728         return( ret );
5729 
5730     /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
5731      * the ServerHello will have message_seq = 1" */
5732 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5733     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5734         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
5735     {
5736         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5737             ssl->handshake->out_msg_seq = 1;
5738         else
5739             ssl->handshake->in_msg_seq = 1;
5740     }
5741 #endif
5742 
5743     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
5744     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
5745 
5746     if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
5747     {
5748         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
5749         return( ret );
5750     }
5751 
5752     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
5753 
5754     return( 0 );
5755 }
5756 
5757 /*
5758  * Renegotiate current connection on client,
5759  * or request renegotiation on server
5760  */
5761 int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
5762 {
5763     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
5764 
5765     if( ssl == NULL || ssl->conf == NULL )
5766         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5767 
5768 #if defined(MBEDTLS_SSL_SRV_C)
5769     /* On server, just send the request */
5770     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5771     {
5772         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
5773             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5774 
5775         ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
5776 
5777         /* Did we already try/start sending HelloRequest? */
5778         if( ssl->out_left != 0 )
5779             return( mbedtls_ssl_flush_output( ssl ) );
5780 
5781         return( ssl_write_hello_request( ssl ) );
5782     }
5783 #endif /* MBEDTLS_SSL_SRV_C */
5784 
5785 #if defined(MBEDTLS_SSL_CLI_C)
5786     /*
5787      * On client, either start the renegotiation process or,
5788      * if already in progress, continue the handshake
5789      */
5790     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
5791     {
5792         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
5793             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5794 
5795         if( ( ret = mbedtls_ssl_start_renegotiation( ssl ) ) != 0 )
5796         {
5797             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_start_renegotiation", ret );
5798             return( ret );
5799         }
5800     }
5801     else
5802     {
5803         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
5804         {
5805             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
5806             return( ret );
5807         }
5808     }
5809 #endif /* MBEDTLS_SSL_CLI_C */
5810 
5811     return( ret );
5812 }
5813 #endif /* MBEDTLS_SSL_RENEGOTIATION */
5814 
5815 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5816 static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
5817 {
5818     mbedtls_ssl_key_cert *cur = key_cert, *next;
5819 
5820     while( cur != NULL )
5821     {
5822         next = cur->next;
5823         mbedtls_free( cur );
5824         cur = next;
5825     }
5826 }
5827 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5828 
5829 void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl )
5830 {
5831     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
5832 
5833     if( handshake == NULL )
5834         return;
5835 
5836 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
5837     if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 )
5838     {
5839         ssl->conf->f_async_cancel( ssl );
5840         handshake->async_in_progress = 0;
5841     }
5842 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
5843 
5844 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5845     defined(MBEDTLS_SSL_PROTO_TLS1_1)
5846     mbedtls_md5_free(    &handshake->fin_md5  );
5847     mbedtls_sha1_free(   &handshake->fin_sha1 );
5848 #endif
5849 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5850 #if defined(MBEDTLS_SHA256_C)
5851 #if defined(MBEDTLS_USE_PSA_CRYPTO)
5852     psa_hash_abort( &handshake->fin_sha256_psa );
5853 #else
5854     mbedtls_sha256_free(   &handshake->fin_sha256    );
5855 #endif
5856 #endif
5857 #if defined(MBEDTLS_SHA512_C)
5858 #if defined(MBEDTLS_USE_PSA_CRYPTO)
5859     psa_hash_abort( &handshake->fin_sha384_psa );
5860 #else
5861     mbedtls_sha512_free(   &handshake->fin_sha512    );
5862 #endif
5863 #endif
5864 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5865 
5866 #if defined(MBEDTLS_DHM_C)
5867     mbedtls_dhm_free( &handshake->dhm_ctx );
5868 #endif
5869 #if defined(MBEDTLS_ECDH_C)
5870     mbedtls_ecdh_free( &handshake->ecdh_ctx );
5871 #endif
5872 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5873     mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
5874 #if defined(MBEDTLS_SSL_CLI_C)
5875     mbedtls_free( handshake->ecjpake_cache );
5876     handshake->ecjpake_cache = NULL;
5877     handshake->ecjpake_cache_len = 0;
5878 #endif
5879 #endif
5880 
5881 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
5882     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5883     /* explicit void pointer cast for buggy MS compiler */
5884     mbedtls_free( (void *) handshake->curves );
5885 #endif
5886 
5887 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
5888     if( handshake->psk != NULL )
5889     {
5890         mbedtls_platform_zeroize( handshake->psk, handshake->psk_len );
5891         mbedtls_free( handshake->psk );
5892     }
5893 #endif
5894 
5895 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
5896     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
5897     /*
5898      * Free only the linked list wrapper, not the keys themselves
5899      * since the belong to the SNI callback
5900      */
5901     if( handshake->sni_key_cert != NULL )
5902     {
5903         mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
5904 
5905         while( cur != NULL )
5906         {
5907             next = cur->next;
5908             mbedtls_free( cur );
5909             cur = next;
5910         }
5911     }
5912 #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
5913 
5914 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
5915     mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx );
5916     if( handshake->ecrs_peer_cert != NULL )
5917     {
5918         mbedtls_x509_crt_free( handshake->ecrs_peer_cert );
5919         mbedtls_free( handshake->ecrs_peer_cert );
5920     }
5921 #endif
5922 
5923 #if defined(MBEDTLS_X509_CRT_PARSE_C) &&        \
5924     !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5925     mbedtls_pk_free( &handshake->peer_pubkey );
5926 #endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5927 
5928 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5929     mbedtls_free( handshake->verify_cookie );
5930     mbedtls_ssl_flight_free( handshake->flight );
5931     mbedtls_ssl_buffering_free( ssl );
5932 #endif
5933 
5934 #if defined(MBEDTLS_ECDH_C) &&                  \
5935     defined(MBEDTLS_USE_PSA_CRYPTO)
5936     psa_destroy_key( handshake->ecdh_psa_privkey );
5937 #endif /* MBEDTLS_ECDH_C && MBEDTLS_USE_PSA_CRYPTO */
5938 
5939     mbedtls_platform_zeroize( handshake,
5940                               sizeof( mbedtls_ssl_handshake_params ) );
5941 
5942 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
5943     /* If the buffers are too big - reallocate. Because of the way Mbed TLS
5944      * processes datagrams and the fact that a datagram is allowed to have
5945      * several records in it, it is possible that the I/O buffers are not
5946      * empty at this stage */
5947     {
5948         int modified = 0;
5949         uint32_t buf_len = mbedtls_ssl_get_input_buflen( ssl );
5950         size_t written_in = 0;
5951         size_t written_out = 0;
5952         if( ssl->in_buf != NULL )
5953         {
5954             written_in = ssl->in_msg - ssl->in_buf;
5955             if( ssl->in_buf_len > buf_len && ssl->in_left < buf_len )
5956             {
5957                 written_in = ssl->in_msg - ssl->in_buf;
5958                 if( resize_buffer( &ssl->in_buf, buf_len, &ssl->in_buf_len ) != 0 )
5959                 {
5960                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "input buffer resizing failed - out of memory" ) );
5961                 }
5962                 else
5963                 {
5964                     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating in_buf to %d", buf_len ) );
5965                     modified = 1;
5966                 }
5967             }
5968         }
5969 
5970 
5971         buf_len = mbedtls_ssl_get_output_buflen( ssl );
5972         if(ssl->out_buf != NULL )
5973         {
5974             written_out = ssl->out_msg - ssl->out_buf;
5975             if( ssl->out_buf_len > mbedtls_ssl_get_output_buflen( ssl ) &&
5976                 ssl->out_left < buf_len )
5977             {
5978                 if( resize_buffer( &ssl->out_buf, buf_len, &ssl->out_buf_len ) != 0 )
5979                 {
5980                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "output buffer resizing failed - out of memory" ) );
5981                 }
5982                 else
5983                 {
5984                     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating out_buf to %d", buf_len ) );
5985                     modified = 1;
5986                 }
5987             }
5988         }
5989         if( modified )
5990         {
5991             /* Update pointers here to avoid doing it twice. */
5992             mbedtls_ssl_reset_in_out_pointers( ssl );
5993             /* Fields below might not be properly updated with record
5994              * splitting, so they are manually updated here. */
5995             ssl->out_msg = ssl->out_buf + written_out;
5996             ssl->in_msg = ssl->in_buf + written_in;
5997         }
5998     }
5999 #endif
6000 }
6001 
6002 void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
6003 {
6004     if( session == NULL )
6005         return;
6006 
6007 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6008     ssl_clear_peer_cert( session );
6009 #endif
6010 
6011 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
6012     mbedtls_free( session->ticket );
6013 #endif
6014 
6015     mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) );
6016 }
6017 
6018 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
6019 
6020 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
6021 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 1u
6022 #else
6023 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 0u
6024 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
6025 
6026 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
6027 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 1u
6028 #else
6029 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 0u
6030 #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
6031 
6032 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6033 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 1u
6034 #else
6035 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 0u
6036 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
6037 
6038 #if defined(MBEDTLS_SSL_ALPN)
6039 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 1u
6040 #else
6041 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 0u
6042 #endif /* MBEDTLS_SSL_ALPN */
6043 
6044 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT    0
6045 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT     1
6046 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT      2
6047 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT                  3
6048 
6049 #define SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG   \
6050     ( (uint32_t) (                              \
6051         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID     << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT     ) | \
6052         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT      << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT      ) | \
6053         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY       << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT       ) | \
6054         ( SSL_SERIALIZED_CONTEXT_CONFIG_ALPN                   << SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT                   ) | \
6055         0u ) )
6056 
6057 static unsigned char ssl_serialized_context_header[] = {
6058     MBEDTLS_VERSION_MAJOR,
6059     MBEDTLS_VERSION_MINOR,
6060     MBEDTLS_VERSION_PATCH,
6061     ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 8 ) & 0xFF,
6062     ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 0 ) & 0xFF,
6063     ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >> 16 ) & 0xFF,
6064     ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >>  8 ) & 0xFF,
6065     ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >>  0 ) & 0xFF,
6066 };
6067 
6068 /*
6069  * Serialize a full SSL context
6070  *
6071  * The format of the serialized data is:
6072  * (in the presentation language of TLS, RFC 8446 section 3)
6073  *
6074  *  // header
6075  *  opaque mbedtls_version[3];   // major, minor, patch
6076  *  opaque context_format[5];    // version-specific field determining
6077  *                               // the format of the remaining
6078  *                               // serialized data.
6079  *  Note: When updating the format, remember to keep these
6080  *        version+format bytes. (We may make their size part of the API.)
6081  *
6082  *  // session sub-structure
6083  *  opaque session<1..2^32-1>;  // see mbedtls_ssl_session_save()
6084  *  // transform sub-structure
6085  *  uint8 random[64];           // ServerHello.random+ClientHello.random
6086  *  uint8 in_cid<0..2^8-1>      // Connection ID: expected incoming value
6087  *  uint8 out_cid<0..2^8-1>     // Connection ID: outgoing value to use
6088  *  // fields from ssl_context
6089  *  uint32 badmac_seen;         // DTLS: number of records with failing MAC
6090  *  uint64 in_window_top;       // DTLS: last validated record seq_num
6091  *  uint64 in_window;           // DTLS: bitmask for replay protection
6092  *  uint8 disable_datagram_packing; // DTLS: only one record per datagram
6093  *  uint64 cur_out_ctr;         // Record layer: outgoing sequence number
6094  *  uint16 mtu;                 // DTLS: path mtu (max outgoing fragment size)
6095  *  uint8 alpn_chosen<0..2^8-1> // ALPN: negotiated application protocol
6096  *
6097  * Note that many fields of the ssl_context or sub-structures are not
6098  * serialized, as they fall in one of the following categories:
6099  *
6100  *  1. forced value (eg in_left must be 0)
6101  *  2. pointer to dynamically-allocated memory (eg session, transform)
6102  *  3. value can be re-derived from other data (eg session keys from MS)
6103  *  4. value was temporary (eg content of input buffer)
6104  *  5. value will be provided by the user again (eg I/O callbacks and context)
6105  */
6106 int mbedtls_ssl_context_save( mbedtls_ssl_context *ssl,
6107                               unsigned char *buf,
6108                               size_t buf_len,
6109                               size_t *olen )
6110 {
6111     unsigned char *p = buf;
6112     size_t used = 0;
6113     size_t session_len;
6114     int ret = 0;
6115 
6116     /*
6117      * Enforce usage restrictions, see "return BAD_INPUT_DATA" in
6118      * this function's documentation.
6119      *
6120      * These are due to assumptions/limitations in the implementation. Some of
6121      * them are likely to stay (no handshake in progress) some might go away
6122      * (only DTLS) but are currently used to simplify the implementation.
6123      */
6124     /* The initial handshake must be over */
6125     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6126     {
6127         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Initial handshake isn't over" ) );
6128         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6129     }
6130     if( ssl->handshake != NULL )
6131     {
6132         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Handshake isn't completed" ) );
6133         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6134     }
6135     /* Double-check that sub-structures are indeed ready */
6136     if( ssl->transform == NULL || ssl->session == NULL )
6137     {
6138         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Serialised structures aren't ready" ) );
6139         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6140     }
6141     /* There must be no pending incoming or outgoing data */
6142     if( mbedtls_ssl_check_pending( ssl ) != 0 )
6143     {
6144         MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending incoming data" ) );
6145         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6146     }
6147     if( ssl->out_left != 0 )
6148     {
6149         MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending outgoing data" ) );
6150         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6151     }
6152     /* Protocol must be DLTS, not TLS */
6153     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6154     {
6155         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only DTLS is supported" ) );
6156         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6157     }
6158     /* Version must be 1.2 */
6159     if( ssl->major_ver != MBEDTLS_SSL_MAJOR_VERSION_3 )
6160     {
6161         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) );
6162         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6163     }
6164     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
6165     {
6166         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) );
6167         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6168     }
6169     /* We must be using an AEAD ciphersuite */
6170     if( mbedtls_ssl_transform_uses_aead( ssl->transform ) != 1 )
6171     {
6172         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only AEAD ciphersuites supported" ) );
6173         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6174     }
6175     /* Renegotiation must not be enabled */
6176 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6177     if( ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED )
6178     {
6179         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Renegotiation must not be enabled" ) );
6180         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6181     }
6182 #endif
6183 
6184     /*
6185      * Version and format identifier
6186      */
6187     used += sizeof( ssl_serialized_context_header );
6188 
6189     if( used <= buf_len )
6190     {
6191         memcpy( p, ssl_serialized_context_header,
6192                 sizeof( ssl_serialized_context_header ) );
6193         p += sizeof( ssl_serialized_context_header );
6194     }
6195 
6196     /*
6197      * Session (length + data)
6198      */
6199     ret = ssl_session_save( ssl->session, 1, NULL, 0, &session_len );
6200     if( ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL )
6201         return( ret );
6202 
6203     used += 4 + session_len;
6204     if( used <= buf_len )
6205     {
6206         *p++ = (unsigned char)( ( session_len >> 24 ) & 0xFF );
6207         *p++ = (unsigned char)( ( session_len >> 16 ) & 0xFF );
6208         *p++ = (unsigned char)( ( session_len >>  8 ) & 0xFF );
6209         *p++ = (unsigned char)( ( session_len       ) & 0xFF );
6210 
6211         ret = ssl_session_save( ssl->session, 1,
6212                                 p, session_len, &session_len );
6213         if( ret != 0 )
6214             return( ret );
6215 
6216         p += session_len;
6217     }
6218 
6219     /*
6220      * Transform
6221      */
6222     used += sizeof( ssl->transform->randbytes );
6223     if( used <= buf_len )
6224     {
6225         memcpy( p, ssl->transform->randbytes,
6226            sizeof( ssl->transform->randbytes ) );
6227         p += sizeof( ssl->transform->randbytes );
6228     }
6229 
6230 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
6231     used += 2 + ssl->transform->in_cid_len + ssl->transform->out_cid_len;
6232     if( used <= buf_len )
6233     {
6234         *p++ = ssl->transform->in_cid_len;
6235         memcpy( p, ssl->transform->in_cid, ssl->transform->in_cid_len );
6236         p += ssl->transform->in_cid_len;
6237 
6238         *p++ = ssl->transform->out_cid_len;
6239         memcpy( p, ssl->transform->out_cid, ssl->transform->out_cid_len );
6240         p += ssl->transform->out_cid_len;
6241     }
6242 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
6243 
6244     /*
6245      * Saved fields from top-level ssl_context structure
6246      */
6247 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
6248     used += 4;
6249     if( used <= buf_len )
6250     {
6251         *p++ = (unsigned char)( ( ssl->badmac_seen >> 24 ) & 0xFF );
6252         *p++ = (unsigned char)( ( ssl->badmac_seen >> 16 ) & 0xFF );
6253         *p++ = (unsigned char)( ( ssl->badmac_seen >>  8 ) & 0xFF );
6254         *p++ = (unsigned char)( ( ssl->badmac_seen       ) & 0xFF );
6255     }
6256 #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
6257 
6258 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6259     used += 16;
6260     if( used <= buf_len )
6261     {
6262         *p++ = (unsigned char)( ( ssl->in_window_top >> 56 ) & 0xFF );
6263         *p++ = (unsigned char)( ( ssl->in_window_top >> 48 ) & 0xFF );
6264         *p++ = (unsigned char)( ( ssl->in_window_top >> 40 ) & 0xFF );
6265         *p++ = (unsigned char)( ( ssl->in_window_top >> 32 ) & 0xFF );
6266         *p++ = (unsigned char)( ( ssl->in_window_top >> 24 ) & 0xFF );
6267         *p++ = (unsigned char)( ( ssl->in_window_top >> 16 ) & 0xFF );
6268         *p++ = (unsigned char)( ( ssl->in_window_top >>  8 ) & 0xFF );
6269         *p++ = (unsigned char)( ( ssl->in_window_top       ) & 0xFF );
6270 
6271         *p++ = (unsigned char)( ( ssl->in_window >> 56 ) & 0xFF );
6272         *p++ = (unsigned char)( ( ssl->in_window >> 48 ) & 0xFF );
6273         *p++ = (unsigned char)( ( ssl->in_window >> 40 ) & 0xFF );
6274         *p++ = (unsigned char)( ( ssl->in_window >> 32 ) & 0xFF );
6275         *p++ = (unsigned char)( ( ssl->in_window >> 24 ) & 0xFF );
6276         *p++ = (unsigned char)( ( ssl->in_window >> 16 ) & 0xFF );
6277         *p++ = (unsigned char)( ( ssl->in_window >>  8 ) & 0xFF );
6278         *p++ = (unsigned char)( ( ssl->in_window       ) & 0xFF );
6279     }
6280 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
6281 
6282 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6283     used += 1;
6284     if( used <= buf_len )
6285     {
6286         *p++ = ssl->disable_datagram_packing;
6287     }
6288 #endif /* MBEDTLS_SSL_PROTO_DTLS */
6289 
6290     used += 8;
6291     if( used <= buf_len )
6292     {
6293         memcpy( p, ssl->cur_out_ctr, 8 );
6294         p += 8;
6295     }
6296 
6297 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6298     used += 2;
6299     if( used <= buf_len )
6300     {
6301         *p++ = (unsigned char)( ( ssl->mtu >>  8 ) & 0xFF );
6302         *p++ = (unsigned char)( ( ssl->mtu       ) & 0xFF );
6303     }
6304 #endif /* MBEDTLS_SSL_PROTO_DTLS */
6305 
6306 #if defined(MBEDTLS_SSL_ALPN)
6307     {
6308         const uint8_t alpn_len = ssl->alpn_chosen
6309                                ? (uint8_t) strlen( ssl->alpn_chosen )
6310                                : 0;
6311 
6312         used += 1 + alpn_len;
6313         if( used <= buf_len )
6314         {
6315             *p++ = alpn_len;
6316 
6317             if( ssl->alpn_chosen != NULL )
6318             {
6319                 memcpy( p, ssl->alpn_chosen, alpn_len );
6320                 p += alpn_len;
6321             }
6322         }
6323     }
6324 #endif /* MBEDTLS_SSL_ALPN */
6325 
6326     /*
6327      * Done
6328      */
6329     *olen = used;
6330 
6331     if( used > buf_len )
6332         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
6333 
6334     MBEDTLS_SSL_DEBUG_BUF( 4, "saved context", buf, used );
6335 
6336     return( mbedtls_ssl_session_reset_int( ssl, 0 ) );
6337 }
6338 
6339 /*
6340  * Helper to get TLS 1.2 PRF from ciphersuite
6341  * (Duplicates bits of logic from ssl_set_handshake_prfs().)
6342  */
6343 typedef int (*tls_prf_fn)( const unsigned char *secret, size_t slen,
6344                            const char *label,
6345                            const unsigned char *random, size_t rlen,
6346                            unsigned char *dstbuf, size_t dlen );
6347 static tls_prf_fn ssl_tls12prf_from_cs( int ciphersuite_id )
6348 {
6349 #if defined(MBEDTLS_SHA512_C)
6350     const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
6351          mbedtls_ssl_ciphersuite_from_id( ciphersuite_id );
6352 
6353     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
6354         return( tls_prf_sha384 );
6355 #else
6356     (void) ciphersuite_id;
6357 #endif
6358     return( tls_prf_sha256 );
6359 }
6360 
6361 /*
6362  * Deserialize context, see mbedtls_ssl_context_save() for format.
6363  *
6364  * This internal version is wrapped by a public function that cleans up in
6365  * case of error.
6366  */
6367 static int ssl_context_load( mbedtls_ssl_context *ssl,
6368                              const unsigned char *buf,
6369                              size_t len )
6370 {
6371     const unsigned char *p = buf;
6372     const unsigned char * const end = buf + len;
6373     size_t session_len;
6374     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6375 
6376     /*
6377      * The context should have been freshly setup or reset.
6378      * Give the user an error in case of obvious misuse.
6379      * (Checking session is useful because it won't be NULL if we're
6380      * renegotiating, or if the user mistakenly loaded a session first.)
6381      */
6382     if( ssl->state != MBEDTLS_SSL_HELLO_REQUEST ||
6383         ssl->session != NULL )
6384     {
6385         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6386     }
6387 
6388     /*
6389      * We can't check that the config matches the initial one, but we can at
6390      * least check it matches the requirements for serializing.
6391      */
6392     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
6393         ssl->conf->max_major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
6394         ssl->conf->min_major_ver > MBEDTLS_SSL_MAJOR_VERSION_3 ||
6395         ssl->conf->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ||
6396         ssl->conf->min_minor_ver > MBEDTLS_SSL_MINOR_VERSION_3 ||
6397 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6398         ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
6399 #endif
6400         0 )
6401     {
6402         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6403     }
6404 
6405     MBEDTLS_SSL_DEBUG_BUF( 4, "context to load", buf, len );
6406 
6407     /*
6408      * Check version identifier
6409      */
6410     if( (size_t)( end - p ) < sizeof( ssl_serialized_context_header ) )
6411         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6412 
6413     if( memcmp( p, ssl_serialized_context_header,
6414                 sizeof( ssl_serialized_context_header ) ) != 0 )
6415     {
6416         return( MBEDTLS_ERR_SSL_VERSION_MISMATCH );
6417     }
6418     p += sizeof( ssl_serialized_context_header );
6419 
6420     /*
6421      * Session
6422      */
6423     if( (size_t)( end - p ) < 4 )
6424         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6425 
6426     session_len = ( (size_t) p[0] << 24 ) |
6427                   ( (size_t) p[1] << 16 ) |
6428                   ( (size_t) p[2] <<  8 ) |
6429                   ( (size_t) p[3]       );
6430     p += 4;
6431 
6432     /* This has been allocated by ssl_handshake_init(), called by
6433      * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */
6434     ssl->session = ssl->session_negotiate;
6435     ssl->session_in = ssl->session;
6436     ssl->session_out = ssl->session;
6437     ssl->session_negotiate = NULL;
6438 
6439     if( (size_t)( end - p ) < session_len )
6440         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6441 
6442     ret = ssl_session_load( ssl->session, 1, p, session_len );
6443     if( ret != 0 )
6444     {
6445         mbedtls_ssl_session_free( ssl->session );
6446         return( ret );
6447     }
6448 
6449     p += session_len;
6450 
6451     /*
6452      * Transform
6453      */
6454 
6455     /* This has been allocated by ssl_handshake_init(), called by
6456      * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */
6457     ssl->transform = ssl->transform_negotiate;
6458     ssl->transform_in = ssl->transform;
6459     ssl->transform_out = ssl->transform;
6460     ssl->transform_negotiate = NULL;
6461 
6462     /* Read random bytes and populate structure */
6463     if( (size_t)( end - p ) < sizeof( ssl->transform->randbytes ) )
6464         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6465 
6466     ret = ssl_populate_transform( ssl->transform,
6467                   ssl->session->ciphersuite,
6468                   ssl->session->master,
6469 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
6470 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
6471                   ssl->session->encrypt_then_mac,
6472 #endif
6473 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
6474                   ssl->session->trunc_hmac,
6475 #endif
6476 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
6477 #if defined(MBEDTLS_ZLIB_SUPPORT)
6478                   ssl->session->compression,
6479 #endif
6480                   ssl_tls12prf_from_cs( ssl->session->ciphersuite ),
6481                   p, /* currently pointing to randbytes */
6482                   MBEDTLS_SSL_MINOR_VERSION_3, /* (D)TLS 1.2 is forced */
6483                   ssl->conf->endpoint,
6484                   ssl );
6485     if( ret != 0 )
6486         return( ret );
6487 
6488     p += sizeof( ssl->transform->randbytes );
6489 
6490 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
6491     /* Read connection IDs and store them */
6492     if( (size_t)( end - p ) < 1 )
6493         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6494 
6495     ssl->transform->in_cid_len = *p++;
6496 
6497     if( (size_t)( end - p ) < ssl->transform->in_cid_len + 1u )
6498         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6499 
6500     memcpy( ssl->transform->in_cid, p, ssl->transform->in_cid_len );
6501     p += ssl->transform->in_cid_len;
6502 
6503     ssl->transform->out_cid_len = *p++;
6504 
6505     if( (size_t)( end - p ) < ssl->transform->out_cid_len )
6506         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6507 
6508     memcpy( ssl->transform->out_cid, p, ssl->transform->out_cid_len );
6509     p += ssl->transform->out_cid_len;
6510 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
6511 
6512     /*
6513      * Saved fields from top-level ssl_context structure
6514      */
6515 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
6516     if( (size_t)( end - p ) < 4 )
6517         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6518 
6519     ssl->badmac_seen = ( (uint32_t) p[0] << 24 ) |
6520                        ( (uint32_t) p[1] << 16 ) |
6521                        ( (uint32_t) p[2] <<  8 ) |
6522                        ( (uint32_t) p[3]       );
6523     p += 4;
6524 #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
6525 
6526 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6527     if( (size_t)( end - p ) < 16 )
6528         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6529 
6530     ssl->in_window_top = ( (uint64_t) p[0] << 56 ) |
6531                          ( (uint64_t) p[1] << 48 ) |
6532                          ( (uint64_t) p[2] << 40 ) |
6533                          ( (uint64_t) p[3] << 32 ) |
6534                          ( (uint64_t) p[4] << 24 ) |
6535                          ( (uint64_t) p[5] << 16 ) |
6536                          ( (uint64_t) p[6] <<  8 ) |
6537                          ( (uint64_t) p[7]       );
6538     p += 8;
6539 
6540     ssl->in_window = ( (uint64_t) p[0] << 56 ) |
6541                      ( (uint64_t) p[1] << 48 ) |
6542                      ( (uint64_t) p[2] << 40 ) |
6543                      ( (uint64_t) p[3] << 32 ) |
6544                      ( (uint64_t) p[4] << 24 ) |
6545                      ( (uint64_t) p[5] << 16 ) |
6546                      ( (uint64_t) p[6] <<  8 ) |
6547                      ( (uint64_t) p[7]       );
6548     p += 8;
6549 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
6550 
6551 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6552     if( (size_t)( end - p ) < 1 )
6553         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6554 
6555     ssl->disable_datagram_packing = *p++;
6556 #endif /* MBEDTLS_SSL_PROTO_DTLS */
6557 
6558     if( (size_t)( end - p ) < 8 )
6559         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6560 
6561     memcpy( ssl->cur_out_ctr, p, 8 );
6562     p += 8;
6563 
6564 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6565     if( (size_t)( end - p ) < 2 )
6566         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6567 
6568     ssl->mtu = ( p[0] << 8 ) | p[1];
6569     p += 2;
6570 #endif /* MBEDTLS_SSL_PROTO_DTLS */
6571 
6572 #if defined(MBEDTLS_SSL_ALPN)
6573     {
6574         uint8_t alpn_len;
6575         const char **cur;
6576 
6577         if( (size_t)( end - p ) < 1 )
6578             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6579 
6580         alpn_len = *p++;
6581 
6582         if( alpn_len != 0 && ssl->conf->alpn_list != NULL )
6583         {
6584             /* alpn_chosen should point to an item in the configured list */
6585             for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
6586             {
6587                 if( strlen( *cur ) == alpn_len &&
6588                     memcmp( p, cur, alpn_len ) == 0 )
6589                 {
6590                     ssl->alpn_chosen = *cur;
6591                     break;
6592                 }
6593             }
6594         }
6595 
6596         /* can only happen on conf mismatch */
6597         if( alpn_len != 0 && ssl->alpn_chosen == NULL )
6598             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6599 
6600         p += alpn_len;
6601     }
6602 #endif /* MBEDTLS_SSL_ALPN */
6603 
6604     /*
6605      * Forced fields from top-level ssl_context structure
6606      *
6607      * Most of them already set to the correct value by mbedtls_ssl_init() and
6608      * mbedtls_ssl_reset(), so we only need to set the remaining ones.
6609      */
6610     ssl->state = MBEDTLS_SSL_HANDSHAKE_OVER;
6611 
6612     ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
6613     ssl->minor_ver = MBEDTLS_SSL_MINOR_VERSION_3;
6614 
6615     /* Adjust pointers for header fields of outgoing records to
6616      * the given transform, accounting for explicit IV and CID. */
6617     mbedtls_ssl_update_out_pointers( ssl, ssl->transform );
6618 
6619 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6620     ssl->in_epoch = 1;
6621 #endif
6622 
6623     /* mbedtls_ssl_reset() leaves the handshake sub-structure allocated,
6624      * which we don't want - otherwise we'd end up freeing the wrong transform
6625      * by calling mbedtls_ssl_handshake_wrapup_free_hs_transform()
6626      * inappropriately. */
6627     if( ssl->handshake != NULL )
6628     {
6629         mbedtls_ssl_handshake_free( ssl );
6630         mbedtls_free( ssl->handshake );
6631         ssl->handshake = NULL;
6632     }
6633 
6634     /*
6635      * Done - should have consumed entire buffer
6636      */
6637     if( p != end )
6638         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6639 
6640     return( 0 );
6641 }
6642 
6643 /*
6644  * Deserialize context: public wrapper for error cleaning
6645  */
6646 int mbedtls_ssl_context_load( mbedtls_ssl_context *context,
6647                               const unsigned char *buf,
6648                               size_t len )
6649 {
6650     int ret = ssl_context_load( context, buf, len );
6651 
6652     if( ret != 0 )
6653         mbedtls_ssl_free( context );
6654 
6655     return( ret );
6656 }
6657 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
6658 
6659 /*
6660  * Free an SSL context
6661  */
6662 void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
6663 {
6664 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
6665     size_t in_buf_len = ssl->in_buf_len;
6666     size_t out_buf_len = ssl->out_buf_len;
6667 #else
6668     size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
6669     size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
6670 #endif
6671 
6672     if( ssl == NULL )
6673         return;
6674 
6675     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
6676 
6677     if( ssl->out_buf != NULL )
6678     {
6679         mbedtls_platform_zeroize( ssl->out_buf, out_buf_len );
6680         mbedtls_free( ssl->out_buf );
6681         ssl->out_buf = NULL;
6682     }
6683 
6684     if( ssl->in_buf != NULL )
6685     {
6686         mbedtls_platform_zeroize( ssl->in_buf, in_buf_len );
6687         mbedtls_free( ssl->in_buf );
6688         ssl->in_buf = NULL;
6689     }
6690 
6691 #if defined(MBEDTLS_ZLIB_SUPPORT)
6692     if( ssl->compress_buf != NULL )
6693     {
6694         mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
6695         mbedtls_free( ssl->compress_buf );
6696     }
6697 #endif
6698 
6699     if( ssl->transform )
6700     {
6701         mbedtls_ssl_transform_free( ssl->transform );
6702         mbedtls_free( ssl->transform );
6703     }
6704 
6705     if( ssl->handshake )
6706     {
6707         mbedtls_ssl_handshake_free( ssl );
6708         mbedtls_ssl_transform_free( ssl->transform_negotiate );
6709         mbedtls_ssl_session_free( ssl->session_negotiate );
6710 
6711         mbedtls_free( ssl->handshake );
6712         mbedtls_free( ssl->transform_negotiate );
6713         mbedtls_free( ssl->session_negotiate );
6714     }
6715 
6716     if( ssl->session )
6717     {
6718         mbedtls_ssl_session_free( ssl->session );
6719         mbedtls_free( ssl->session );
6720     }
6721 
6722 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6723     if( ssl->hostname != NULL )
6724     {
6725         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
6726         mbedtls_free( ssl->hostname );
6727     }
6728 #endif
6729 
6730 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
6731     if( mbedtls_ssl_hw_record_finish != NULL )
6732     {
6733         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
6734         mbedtls_ssl_hw_record_finish( ssl );
6735     }
6736 #endif
6737 
6738 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
6739     mbedtls_free( ssl->cli_id );
6740 #endif
6741 
6742     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
6743 
6744     /* Actually clear after last debug message */
6745     mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
6746 }
6747 
6748 /*
6749  * Initialze mbedtls_ssl_config
6750  */
6751 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
6752 {
6753     memset( conf, 0, sizeof( mbedtls_ssl_config ) );
6754 }
6755 
6756 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
6757 static int ssl_preset_default_hashes[] = {
6758 #if defined(MBEDTLS_SHA512_C)
6759     MBEDTLS_MD_SHA512,
6760     MBEDTLS_MD_SHA384,
6761 #endif
6762 #if defined(MBEDTLS_SHA256_C)
6763     MBEDTLS_MD_SHA256,
6764     MBEDTLS_MD_SHA224,
6765 #endif
6766 #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
6767     MBEDTLS_MD_SHA1,
6768 #endif
6769     MBEDTLS_MD_NONE
6770 };
6771 #endif
6772 
6773 static int ssl_preset_suiteb_ciphersuites[] = {
6774     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
6775     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
6776     0
6777 };
6778 
6779 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
6780 static int ssl_preset_suiteb_hashes[] = {
6781     MBEDTLS_MD_SHA256,
6782     MBEDTLS_MD_SHA384,
6783     MBEDTLS_MD_NONE
6784 };
6785 #endif
6786 
6787 #if defined(MBEDTLS_ECP_C)
6788 static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
6789 #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
6790     MBEDTLS_ECP_DP_SECP256R1,
6791 #endif
6792 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
6793     MBEDTLS_ECP_DP_SECP384R1,
6794 #endif
6795     MBEDTLS_ECP_DP_NONE
6796 };
6797 #endif
6798 
6799 /*
6800  * Load default in mbedtls_ssl_config
6801  */
6802 int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
6803                                  int endpoint, int transport, int preset )
6804 {
6805 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
6806     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6807 #endif
6808 
6809     /* Use the functions here so that they are covered in tests,
6810      * but otherwise access member directly for efficiency */
6811     mbedtls_ssl_conf_endpoint( conf, endpoint );
6812     mbedtls_ssl_conf_transport( conf, transport );
6813 
6814     /*
6815      * Things that are common to all presets
6816      */
6817 #if defined(MBEDTLS_SSL_CLI_C)
6818     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
6819     {
6820         conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
6821 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
6822         conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
6823 #endif
6824     }
6825 #endif
6826 
6827 #if defined(MBEDTLS_ARC4_C)
6828     conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
6829 #endif
6830 
6831 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
6832     conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
6833 #endif
6834 
6835 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
6836     conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
6837 #endif
6838 
6839 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
6840     conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
6841 #endif
6842 
6843 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
6844     conf->f_cookie_write = ssl_cookie_write_dummy;
6845     conf->f_cookie_check = ssl_cookie_check_dummy;
6846 #endif
6847 
6848 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6849     conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
6850 #endif
6851 
6852 #if defined(MBEDTLS_SSL_SRV_C)
6853     conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
6854 #endif
6855 
6856 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6857     conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
6858     conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
6859 #endif
6860 
6861 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6862     conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
6863     memset( conf->renego_period,     0x00, 2 );
6864     memset( conf->renego_period + 2, 0xFF, 6 );
6865 #endif
6866 
6867 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
6868             if( endpoint == MBEDTLS_SSL_IS_SERVER )
6869             {
6870                 const unsigned char dhm_p[] =
6871                     MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
6872                 const unsigned char dhm_g[] =
6873                     MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
6874 
6875                 if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,
6876                                                dhm_p, sizeof( dhm_p ),
6877                                                dhm_g, sizeof( dhm_g ) ) ) != 0 )
6878                 {
6879                     return( ret );
6880                 }
6881             }
6882 #endif
6883 
6884     /*
6885      * Preset-specific defaults
6886      */
6887     switch( preset )
6888     {
6889         /*
6890          * NSA Suite B
6891          */
6892         case MBEDTLS_SSL_PRESET_SUITEB:
6893             conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
6894             conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
6895             conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
6896             conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
6897 
6898             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
6899             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
6900             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
6901             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
6902                                    ssl_preset_suiteb_ciphersuites;
6903 
6904 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6905             conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
6906 #endif
6907 
6908 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
6909             conf->sig_hashes = ssl_preset_suiteb_hashes;
6910 #endif
6911 
6912 #if defined(MBEDTLS_ECP_C)
6913             conf->curve_list = ssl_preset_suiteb_curves;
6914 #endif
6915             break;
6916 
6917         /*
6918          * Default
6919          */
6920         default:
6921             conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >
6922                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?
6923                                     MBEDTLS_SSL_MIN_MAJOR_VERSION :
6924                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
6925             conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION >
6926                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?
6927                                     MBEDTLS_SSL_MIN_MINOR_VERSION :
6928                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
6929             conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
6930             conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
6931 
6932 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6933             if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6934                 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
6935 #endif
6936 
6937             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
6938             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
6939             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
6940             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
6941                                    mbedtls_ssl_list_ciphersuites();
6942 
6943 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6944             conf->cert_profile = &mbedtls_x509_crt_profile_default;
6945 #endif
6946 
6947 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
6948             conf->sig_hashes = ssl_preset_default_hashes;
6949 #endif
6950 
6951 #if defined(MBEDTLS_ECP_C)
6952             conf->curve_list = mbedtls_ecp_grp_id_list();
6953 #endif
6954 
6955 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
6956             conf->dhm_min_bitlen = 1024;
6957 #endif
6958     }
6959 
6960     return( 0 );
6961 }
6962 
6963 /*
6964  * Free mbedtls_ssl_config
6965  */
6966 void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
6967 {
6968 #if defined(MBEDTLS_DHM_C)
6969     mbedtls_mpi_free( &conf->dhm_P );
6970     mbedtls_mpi_free( &conf->dhm_G );
6971 #endif
6972 
6973 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
6974     if( conf->psk != NULL )
6975     {
6976         mbedtls_platform_zeroize( conf->psk, conf->psk_len );
6977         mbedtls_free( conf->psk );
6978         conf->psk = NULL;
6979         conf->psk_len = 0;
6980     }
6981 
6982     if( conf->psk_identity != NULL )
6983     {
6984         mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len );
6985         mbedtls_free( conf->psk_identity );
6986         conf->psk_identity = NULL;
6987         conf->psk_identity_len = 0;
6988     }
6989 #endif
6990 
6991 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6992     ssl_key_cert_free( conf->key_cert );
6993 #endif
6994 
6995     mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) );
6996 }
6997 
6998 #if defined(MBEDTLS_PK_C) && \
6999     ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
7000 /*
7001  * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
7002  */
7003 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
7004 {
7005 #if defined(MBEDTLS_RSA_C)
7006     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
7007         return( MBEDTLS_SSL_SIG_RSA );
7008 #endif
7009 #if defined(MBEDTLS_ECDSA_C)
7010     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
7011         return( MBEDTLS_SSL_SIG_ECDSA );
7012 #endif
7013     return( MBEDTLS_SSL_SIG_ANON );
7014 }
7015 
7016 unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
7017 {
7018     switch( type ) {
7019         case MBEDTLS_PK_RSA:
7020             return( MBEDTLS_SSL_SIG_RSA );
7021         case MBEDTLS_PK_ECDSA:
7022         case MBEDTLS_PK_ECKEY:
7023             return( MBEDTLS_SSL_SIG_ECDSA );
7024         default:
7025             return( MBEDTLS_SSL_SIG_ANON );
7026     }
7027 }
7028 
7029 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
7030 {
7031     switch( sig )
7032     {
7033 #if defined(MBEDTLS_RSA_C)
7034         case MBEDTLS_SSL_SIG_RSA:
7035             return( MBEDTLS_PK_RSA );
7036 #endif
7037 #if defined(MBEDTLS_ECDSA_C)
7038         case MBEDTLS_SSL_SIG_ECDSA:
7039             return( MBEDTLS_PK_ECDSA );
7040 #endif
7041         default:
7042             return( MBEDTLS_PK_NONE );
7043     }
7044 }
7045 #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
7046 
7047 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
7048     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
7049 
7050 /* Find an entry in a signature-hash set matching a given hash algorithm. */
7051 mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
7052                                                  mbedtls_pk_type_t sig_alg )
7053 {
7054     switch( sig_alg )
7055     {
7056         case MBEDTLS_PK_RSA:
7057             return( set->rsa );
7058         case MBEDTLS_PK_ECDSA:
7059             return( set->ecdsa );
7060         default:
7061             return( MBEDTLS_MD_NONE );
7062     }
7063 }
7064 
7065 /* Add a signature-hash-pair to a signature-hash set */
7066 void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
7067                                    mbedtls_pk_type_t sig_alg,
7068                                    mbedtls_md_type_t md_alg )
7069 {
7070     switch( sig_alg )
7071     {
7072         case MBEDTLS_PK_RSA:
7073             if( set->rsa == MBEDTLS_MD_NONE )
7074                 set->rsa = md_alg;
7075             break;
7076 
7077         case MBEDTLS_PK_ECDSA:
7078             if( set->ecdsa == MBEDTLS_MD_NONE )
7079                 set->ecdsa = md_alg;
7080             break;
7081 
7082         default:
7083             break;
7084     }
7085 }
7086 
7087 /* Allow exactly one hash algorithm for each signature. */
7088 void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
7089                                           mbedtls_md_type_t md_alg )
7090 {
7091     set->rsa   = md_alg;
7092     set->ecdsa = md_alg;
7093 }
7094 
7095 #endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
7096           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
7097 
7098 /*
7099  * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
7100  */
7101 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
7102 {
7103     switch( hash )
7104     {
7105 #if defined(MBEDTLS_MD5_C)
7106         case MBEDTLS_SSL_HASH_MD5:
7107             return( MBEDTLS_MD_MD5 );
7108 #endif
7109 #if defined(MBEDTLS_SHA1_C)
7110         case MBEDTLS_SSL_HASH_SHA1:
7111             return( MBEDTLS_MD_SHA1 );
7112 #endif
7113 #if defined(MBEDTLS_SHA256_C)
7114         case MBEDTLS_SSL_HASH_SHA224:
7115             return( MBEDTLS_MD_SHA224 );
7116         case MBEDTLS_SSL_HASH_SHA256:
7117             return( MBEDTLS_MD_SHA256 );
7118 #endif
7119 #if defined(MBEDTLS_SHA512_C)
7120         case MBEDTLS_SSL_HASH_SHA384:
7121             return( MBEDTLS_MD_SHA384 );
7122         case MBEDTLS_SSL_HASH_SHA512:
7123             return( MBEDTLS_MD_SHA512 );
7124 #endif
7125         default:
7126             return( MBEDTLS_MD_NONE );
7127     }
7128 }
7129 
7130 /*
7131  * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
7132  */
7133 unsigned char mbedtls_ssl_hash_from_md_alg( int md )
7134 {
7135     switch( md )
7136     {
7137 #if defined(MBEDTLS_MD5_C)
7138         case MBEDTLS_MD_MD5:
7139             return( MBEDTLS_SSL_HASH_MD5 );
7140 #endif
7141 #if defined(MBEDTLS_SHA1_C)
7142         case MBEDTLS_MD_SHA1:
7143             return( MBEDTLS_SSL_HASH_SHA1 );
7144 #endif
7145 #if defined(MBEDTLS_SHA256_C)
7146         case MBEDTLS_MD_SHA224:
7147             return( MBEDTLS_SSL_HASH_SHA224 );
7148         case MBEDTLS_MD_SHA256:
7149             return( MBEDTLS_SSL_HASH_SHA256 );
7150 #endif
7151 #if defined(MBEDTLS_SHA512_C)
7152         case MBEDTLS_MD_SHA384:
7153             return( MBEDTLS_SSL_HASH_SHA384 );
7154         case MBEDTLS_MD_SHA512:
7155             return( MBEDTLS_SSL_HASH_SHA512 );
7156 #endif
7157         default:
7158             return( MBEDTLS_SSL_HASH_NONE );
7159     }
7160 }
7161 
7162 #if defined(MBEDTLS_ECP_C)
7163 /*
7164  * Check if a curve proposed by the peer is in our list.
7165  * Return 0 if we're willing to use it, -1 otherwise.
7166  */
7167 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
7168 {
7169     const mbedtls_ecp_group_id *gid;
7170 
7171     if( ssl->conf->curve_list == NULL )
7172         return( -1 );
7173 
7174     for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
7175         if( *gid == grp_id )
7176             return( 0 );
7177 
7178     return( -1 );
7179 }
7180 #endif /* MBEDTLS_ECP_C */
7181 
7182 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
7183 /*
7184  * Check if a hash proposed by the peer is in our list.
7185  * Return 0 if we're willing to use it, -1 otherwise.
7186  */
7187 int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
7188                                 mbedtls_md_type_t md )
7189 {
7190     const int *cur;
7191 
7192     if( ssl->conf->sig_hashes == NULL )
7193         return( -1 );
7194 
7195     for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
7196         if( *cur == (int) md )
7197             return( 0 );
7198 
7199     return( -1 );
7200 }
7201 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
7202 
7203 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7204 int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
7205                           const mbedtls_ssl_ciphersuite_t *ciphersuite,
7206                           int cert_endpoint,
7207                           uint32_t *flags )
7208 {
7209     int ret = 0;
7210 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7211     int usage = 0;
7212 #endif
7213 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7214     const char *ext_oid;
7215     size_t ext_len;
7216 #endif
7217 
7218 #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) &&          \
7219     !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7220     ((void) cert);
7221     ((void) cert_endpoint);
7222     ((void) flags);
7223 #endif
7224 
7225 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7226     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
7227     {
7228         /* Server part of the key exchange */
7229         switch( ciphersuite->key_exchange )
7230         {
7231             case MBEDTLS_KEY_EXCHANGE_RSA:
7232             case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
7233                 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
7234                 break;
7235 
7236             case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
7237             case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
7238             case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
7239                 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7240                 break;
7241 
7242             case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
7243             case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
7244                 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
7245                 break;
7246 
7247             /* Don't use default: we want warnings when adding new values */
7248             case MBEDTLS_KEY_EXCHANGE_NONE:
7249             case MBEDTLS_KEY_EXCHANGE_PSK:
7250             case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
7251             case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
7252             case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
7253                 usage = 0;
7254         }
7255     }
7256     else
7257     {
7258         /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
7259         usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7260     }
7261 
7262     if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
7263     {
7264         *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
7265         ret = -1;
7266     }
7267 #else
7268     ((void) ciphersuite);
7269 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
7270 
7271 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7272     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
7273     {
7274         ext_oid = MBEDTLS_OID_SERVER_AUTH;
7275         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
7276     }
7277     else
7278     {
7279         ext_oid = MBEDTLS_OID_CLIENT_AUTH;
7280         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
7281     }
7282 
7283     if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
7284     {
7285         *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
7286         ret = -1;
7287     }
7288 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
7289 
7290     return( ret );
7291 }
7292 #endif /* MBEDTLS_X509_CRT_PARSE_C */
7293 
7294 int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
7295 {
7296 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
7297     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
7298         return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7299 
7300     switch( md )
7301     {
7302 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
7303 #if defined(MBEDTLS_MD5_C)
7304         case MBEDTLS_SSL_HASH_MD5:
7305             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7306 #endif
7307 #if defined(MBEDTLS_SHA1_C)
7308         case MBEDTLS_SSL_HASH_SHA1:
7309             ssl->handshake->calc_verify = ssl_calc_verify_tls;
7310             break;
7311 #endif
7312 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
7313 #if defined(MBEDTLS_SHA512_C)
7314         case MBEDTLS_SSL_HASH_SHA384:
7315             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
7316             break;
7317 #endif
7318 #if defined(MBEDTLS_SHA256_C)
7319         case MBEDTLS_SSL_HASH_SHA256:
7320             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
7321             break;
7322 #endif
7323         default:
7324             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7325     }
7326 
7327     return 0;
7328 #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
7329     (void) ssl;
7330     (void) md;
7331 
7332     return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7333 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
7334 }
7335 
7336 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
7337     defined(MBEDTLS_SSL_PROTO_TLS1_1)
7338 int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
7339                                         unsigned char *output,
7340                                         unsigned char *data, size_t data_len )
7341 {
7342     int ret = 0;
7343     mbedtls_md5_context mbedtls_md5;
7344     mbedtls_sha1_context mbedtls_sha1;
7345 
7346     mbedtls_md5_init( &mbedtls_md5 );
7347     mbedtls_sha1_init( &mbedtls_sha1 );
7348 
7349     /*
7350      * digitally-signed struct {
7351      *     opaque md5_hash[16];
7352      *     opaque sha_hash[20];
7353      * };
7354      *
7355      * md5_hash
7356      *     MD5(ClientHello.random + ServerHello.random
7357      *                            + ServerParams);
7358      * sha_hash
7359      *     SHA(ClientHello.random + ServerHello.random
7360      *                            + ServerParams);
7361      */
7362     if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 )
7363     {
7364         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret );
7365         goto exit;
7366     }
7367     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5,
7368                                         ssl->handshake->randbytes, 64 ) ) != 0 )
7369     {
7370         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
7371         goto exit;
7372     }
7373     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 )
7374     {
7375         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
7376         goto exit;
7377     }
7378     if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 )
7379     {
7380         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret );
7381         goto exit;
7382     }
7383 
7384     if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 )
7385     {
7386         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret );
7387         goto exit;
7388     }
7389     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1,
7390                                          ssl->handshake->randbytes, 64 ) ) != 0 )
7391     {
7392         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
7393         goto exit;
7394     }
7395     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data,
7396                                          data_len ) ) != 0 )
7397     {
7398         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
7399         goto exit;
7400     }
7401     if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1,
7402                                          output + 16 ) ) != 0 )
7403     {
7404         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret );
7405         goto exit;
7406     }
7407 
7408 exit:
7409     mbedtls_md5_free( &mbedtls_md5 );
7410     mbedtls_sha1_free( &mbedtls_sha1 );
7411 
7412     if( ret != 0 )
7413         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7414                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
7415 
7416     return( ret );
7417 
7418 }
7419 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
7420           MBEDTLS_SSL_PROTO_TLS1_1 */
7421 
7422 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
7423     defined(MBEDTLS_SSL_PROTO_TLS1_2)
7424 
7425 #if defined(MBEDTLS_USE_PSA_CRYPTO)
7426 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
7427                                             unsigned char *hash, size_t *hashlen,
7428                                             unsigned char *data, size_t data_len,
7429                                             mbedtls_md_type_t md_alg )
7430 {
7431     psa_status_t status;
7432     psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT;
7433     psa_algorithm_t hash_alg = mbedtls_psa_translate_md( md_alg );
7434 
7435     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform PSA-based computation of digest of ServerKeyExchange" ) );
7436 
7437     if( ( status = psa_hash_setup( &hash_operation,
7438                                    hash_alg ) ) != PSA_SUCCESS )
7439     {
7440         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_setup", status );
7441         goto exit;
7442     }
7443 
7444     if( ( status = psa_hash_update( &hash_operation, ssl->handshake->randbytes,
7445                                     64 ) ) != PSA_SUCCESS )
7446     {
7447         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_update", status );
7448         goto exit;
7449     }
7450 
7451     if( ( status = psa_hash_update( &hash_operation,
7452                                     data, data_len ) ) != PSA_SUCCESS )
7453     {
7454         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_update", status );
7455         goto exit;
7456     }
7457 
7458     if( ( status = psa_hash_finish( &hash_operation, hash, MBEDTLS_MD_MAX_SIZE,
7459                                     hashlen ) ) != PSA_SUCCESS )
7460     {
7461          MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_finish", status );
7462          goto exit;
7463     }
7464 
7465 exit:
7466     if( status != PSA_SUCCESS )
7467     {
7468         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7469                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
7470         switch( status )
7471         {
7472             case PSA_ERROR_NOT_SUPPORTED:
7473                 return( MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE );
7474             case PSA_ERROR_BAD_STATE: /* Intentional fallthrough */
7475             case PSA_ERROR_BUFFER_TOO_SMALL:
7476                 return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
7477             case PSA_ERROR_INSUFFICIENT_MEMORY:
7478                 return( MBEDTLS_ERR_MD_ALLOC_FAILED );
7479             default:
7480                 return( MBEDTLS_ERR_MD_HW_ACCEL_FAILED );
7481         }
7482     }
7483     return( 0 );
7484 }
7485 
7486 #else
7487 
7488 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
7489                                             unsigned char *hash, size_t *hashlen,
7490                                             unsigned char *data, size_t data_len,
7491                                             mbedtls_md_type_t md_alg )
7492 {
7493     int ret = 0;
7494     mbedtls_md_context_t ctx;
7495     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
7496     *hashlen = mbedtls_md_get_size( md_info );
7497 
7498     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform mbedtls-based computation of digest of ServerKeyExchange" ) );
7499 
7500     mbedtls_md_init( &ctx );
7501 
7502     /*
7503      * digitally-signed struct {
7504      *     opaque client_random[32];
7505      *     opaque server_random[32];
7506      *     ServerDHParams params;
7507      * };
7508      */
7509     if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
7510     {
7511         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
7512         goto exit;
7513     }
7514     if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
7515     {
7516         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret );
7517         goto exit;
7518     }
7519     if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )
7520     {
7521         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
7522         goto exit;
7523     }
7524     if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )
7525     {
7526         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
7527         goto exit;
7528     }
7529     if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 )
7530     {
7531         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret );
7532         goto exit;
7533     }
7534 
7535 exit:
7536     mbedtls_md_free( &ctx );
7537 
7538     if( ret != 0 )
7539         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7540                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
7541 
7542     return( ret );
7543 }
7544 #endif /* MBEDTLS_USE_PSA_CRYPTO */
7545 
7546 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
7547           MBEDTLS_SSL_PROTO_TLS1_2 */
7548 
7549 #endif /* MBEDTLS_SSL_TLS_C */
7550