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