• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  TLS 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  *  http://www.ietf.org/rfc/rfc2246.txt
21  *  http://www.ietf.org/rfc/rfc4346.txt
22  */
23 
24 #include "common.h"
25 
26 #if defined(MBEDTLS_SSL_TLS_C)
27 
28 #include <assert.h>
29 
30 #include "mbedtls/platform.h"
31 
32 #include "mbedtls/ssl.h"
33 #include "ssl_client.h"
34 #include "ssl_debug_helpers.h"
35 #include "ssl_misc.h"
36 
37 #include "mbedtls/debug.h"
38 #include "mbedtls/error.h"
39 #include "mbedtls/platform_util.h"
40 #include "mbedtls/version.h"
41 #include "mbedtls/constant_time.h"
42 
43 #include <string.h>
44 
45 #if defined(MBEDTLS_USE_PSA_CRYPTO)
46 #include "mbedtls/psa_util.h"
47 #include "psa/crypto.h"
48 #endif
49 #include "mbedtls/legacy_or_psa.h"
50 
51 #if defined(MBEDTLS_X509_CRT_PARSE_C)
52 #include "mbedtls/oid.h"
53 #endif
54 
55 #if defined(MBEDTLS_TEST_HOOKS)
56 static mbedtls_ssl_chk_buf_ptr_args chk_buf_ptr_fail_args;
57 
mbedtls_ssl_set_chk_buf_ptr_fail_args(const uint8_t * cur,const uint8_t * end,size_t need)58 void mbedtls_ssl_set_chk_buf_ptr_fail_args(
59     const uint8_t *cur, const uint8_t *end, size_t need )
60 {
61     chk_buf_ptr_fail_args.cur = cur;
62     chk_buf_ptr_fail_args.end = end;
63     chk_buf_ptr_fail_args.need = need;
64 }
65 
mbedtls_ssl_reset_chk_buf_ptr_fail_args(void)66 void mbedtls_ssl_reset_chk_buf_ptr_fail_args( void )
67 {
68     memset( &chk_buf_ptr_fail_args, 0, sizeof( chk_buf_ptr_fail_args ) );
69 }
70 
mbedtls_ssl_cmp_chk_buf_ptr_fail_args(mbedtls_ssl_chk_buf_ptr_args * args)71 int mbedtls_ssl_cmp_chk_buf_ptr_fail_args( mbedtls_ssl_chk_buf_ptr_args *args )
72 {
73     return( ( chk_buf_ptr_fail_args.cur  != args->cur  ) ||
74             ( chk_buf_ptr_fail_args.end  != args->end  ) ||
75             ( chk_buf_ptr_fail_args.need != args->need ) );
76 }
77 #endif /* MBEDTLS_TEST_HOOKS */
78 
79 #if defined(MBEDTLS_SSL_PROTO_DTLS)
80 
81 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
82 /* Top-level Connection ID API */
83 
mbedtls_ssl_conf_cid(mbedtls_ssl_config * conf,size_t len,int ignore_other_cid)84 int mbedtls_ssl_conf_cid( mbedtls_ssl_config *conf,
85                           size_t len,
86                           int ignore_other_cid )
87 {
88     if( len > MBEDTLS_SSL_CID_IN_LEN_MAX )
89         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
90 
91     if( ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_FAIL &&
92         ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_IGNORE )
93     {
94         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
95     }
96 
97     conf->ignore_unexpected_cid = ignore_other_cid;
98     conf->cid_len = len;
99     return( 0 );
100 }
101 
mbedtls_ssl_set_cid(mbedtls_ssl_context * ssl,int enable,unsigned char const * own_cid,size_t own_cid_len)102 int mbedtls_ssl_set_cid( mbedtls_ssl_context *ssl,
103                          int enable,
104                          unsigned char const *own_cid,
105                          size_t own_cid_len )
106 {
107     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
108         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
109 
110     ssl->negotiate_cid = enable;
111     if( enable == MBEDTLS_SSL_CID_DISABLED )
112     {
113         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Disable use of CID extension." ) );
114         return( 0 );
115     }
116     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Enable use of CID extension." ) );
117     MBEDTLS_SSL_DEBUG_BUF( 3, "Own CID", own_cid, own_cid_len );
118 
119     if( own_cid_len != ssl->conf->cid_len )
120     {
121         MBEDTLS_SSL_DEBUG_MSG( 3, ( "CID length %u does not match CID length %u in config",
122                                     (unsigned) own_cid_len,
123                                     (unsigned) ssl->conf->cid_len ) );
124         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
125     }
126 
127     memcpy( ssl->own_cid, own_cid, own_cid_len );
128     /* Truncation is not an issue here because
129      * MBEDTLS_SSL_CID_IN_LEN_MAX at most 255. */
130     ssl->own_cid_len = (uint8_t) own_cid_len;
131 
132     return( 0 );
133 }
134 
mbedtls_ssl_get_own_cid(mbedtls_ssl_context * ssl,int * enabled,unsigned char own_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],size_t * own_cid_len)135 int mbedtls_ssl_get_own_cid( mbedtls_ssl_context *ssl,
136                               int *enabled,
137                               unsigned char own_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],
138                               size_t *own_cid_len )
139 {
140     *enabled = MBEDTLS_SSL_CID_DISABLED;
141 
142     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
143         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
144 
145     /* We report MBEDTLS_SSL_CID_DISABLED in case the CID length is
146      * zero as this is indistinguishable from not requesting to use
147      * the CID extension. */
148     if( ssl->own_cid_len == 0 || ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED )
149         return( 0 );
150 
151     if( own_cid_len != NULL )
152     {
153         *own_cid_len = ssl->own_cid_len;
154         if( own_cid != NULL )
155             memcpy( own_cid, ssl->own_cid, ssl->own_cid_len );
156     }
157 
158     *enabled = MBEDTLS_SSL_CID_ENABLED;
159 
160     return( 0 );
161 }
162 
mbedtls_ssl_get_peer_cid(mbedtls_ssl_context * ssl,int * enabled,unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],size_t * peer_cid_len)163 int mbedtls_ssl_get_peer_cid( mbedtls_ssl_context *ssl,
164                      int *enabled,
165                      unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ],
166                      size_t *peer_cid_len )
167 {
168     *enabled = MBEDTLS_SSL_CID_DISABLED;
169 
170     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
171         mbedtls_ssl_is_handshake_over( ssl ) == 0 )
172     {
173         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
174     }
175 
176     /* We report MBEDTLS_SSL_CID_DISABLED in case the CID extensions
177      * were used, but client and server requested the empty CID.
178      * This is indistinguishable from not using the CID extension
179      * in the first place. */
180     if( ssl->transform_in->in_cid_len  == 0 &&
181         ssl->transform_in->out_cid_len == 0 )
182     {
183         return( 0 );
184     }
185 
186     if( peer_cid_len != NULL )
187     {
188         *peer_cid_len = ssl->transform_in->out_cid_len;
189         if( peer_cid != NULL )
190         {
191             memcpy( peer_cid, ssl->transform_in->out_cid,
192                     ssl->transform_in->out_cid_len );
193         }
194     }
195 
196     *enabled = MBEDTLS_SSL_CID_ENABLED;
197 
198     return( 0 );
199 }
200 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
201 
202 #endif /* MBEDTLS_SSL_PROTO_DTLS */
203 
204 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
205 /*
206  * Convert max_fragment_length codes to length.
207  * RFC 6066 says:
208  *    enum{
209  *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
210  *    } MaxFragmentLength;
211  * and we add 0 -> extension unused
212  */
ssl_mfl_code_to_length(int mfl)213 static unsigned int ssl_mfl_code_to_length( int mfl )
214 {
215     switch( mfl )
216     {
217     case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:
218         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
219     case MBEDTLS_SSL_MAX_FRAG_LEN_512:
220         return 512;
221     case MBEDTLS_SSL_MAX_FRAG_LEN_1024:
222         return 1024;
223     case MBEDTLS_SSL_MAX_FRAG_LEN_2048:
224         return 2048;
225     case MBEDTLS_SSL_MAX_FRAG_LEN_4096:
226         return 4096;
227     default:
228         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
229     }
230 }
231 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
232 
mbedtls_ssl_session_copy(mbedtls_ssl_session * dst,const mbedtls_ssl_session * src)233 int mbedtls_ssl_session_copy( mbedtls_ssl_session *dst,
234                               const mbedtls_ssl_session *src )
235 {
236     mbedtls_ssl_session_free( dst );
237     memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
238 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
239     dst->ticket = NULL;
240 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
241     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
242     dst->hostname = NULL;
243 #endif
244 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
245 
246 #if defined(MBEDTLS_X509_CRT_PARSE_C)
247 
248 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
249     if( src->peer_cert != NULL )
250     {
251         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
252 
253         dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
254         if( dst->peer_cert == NULL )
255             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
256 
257         mbedtls_x509_crt_init( dst->peer_cert );
258 
259         if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
260                                         src->peer_cert->raw.len ) ) != 0 )
261         {
262             mbedtls_free( dst->peer_cert );
263             dst->peer_cert = NULL;
264             return( ret );
265         }
266     }
267 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
268     if( src->peer_cert_digest != NULL )
269     {
270         dst->peer_cert_digest =
271             mbedtls_calloc( 1, src->peer_cert_digest_len );
272         if( dst->peer_cert_digest == NULL )
273             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
274 
275         memcpy( dst->peer_cert_digest, src->peer_cert_digest,
276                 src->peer_cert_digest_len );
277         dst->peer_cert_digest_type = src->peer_cert_digest_type;
278         dst->peer_cert_digest_len = src->peer_cert_digest_len;
279     }
280 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
281 
282 #endif /* MBEDTLS_X509_CRT_PARSE_C */
283 
284 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
285     if( src->ticket != NULL )
286     {
287         dst->ticket = mbedtls_calloc( 1, src->ticket_len );
288         if( dst->ticket == NULL )
289             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
290 
291         memcpy( dst->ticket, src->ticket, src->ticket_len );
292     }
293 
294 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
295     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
296     if( src->endpoint == MBEDTLS_SSL_IS_CLIENT )
297     {
298         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
299         ret = mbedtls_ssl_session_set_hostname( dst, src->hostname );
300         if( ret != 0 )
301             return ( ret );
302     }
303 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 &&
304           MBEDTLS_SSL_SERVER_NAME_INDICATION */
305 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
306 
307     return( 0 );
308 }
309 
310 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
311 MBEDTLS_CHECK_RETURN_CRITICAL
resize_buffer(unsigned char ** buffer,size_t len_new,size_t * len_old)312 static int resize_buffer( unsigned char **buffer, size_t len_new, size_t *len_old )
313 {
314     unsigned char* resized_buffer = mbedtls_calloc( 1, len_new );
315     if( resized_buffer == NULL )
316         return -1;
317 
318     /* We want to copy len_new bytes when downsizing the buffer, and
319      * len_old bytes when upsizing, so we choose the smaller of two sizes,
320      * to fit one buffer into another. Size checks, ensuring that no data is
321      * lost, are done outside of this function. */
322     memcpy( resized_buffer, *buffer,
323             ( len_new < *len_old ) ? len_new : *len_old );
324     mbedtls_platform_zeroize( *buffer, *len_old );
325     mbedtls_free( *buffer );
326 
327     *buffer = resized_buffer;
328     *len_old = len_new;
329 
330     return 0;
331 }
332 
handle_buffer_resizing(mbedtls_ssl_context * ssl,int downsizing,size_t in_buf_new_len,size_t out_buf_new_len)333 static void handle_buffer_resizing( mbedtls_ssl_context *ssl, int downsizing,
334                                     size_t in_buf_new_len,
335                                     size_t out_buf_new_len )
336 {
337     int modified = 0;
338     size_t written_in = 0, iv_offset_in = 0, len_offset_in = 0;
339     size_t written_out = 0, iv_offset_out = 0, len_offset_out = 0;
340     if( ssl->in_buf != NULL )
341     {
342         written_in = ssl->in_msg - ssl->in_buf;
343         iv_offset_in = ssl->in_iv - ssl->in_buf;
344         len_offset_in = ssl->in_len - ssl->in_buf;
345         if( downsizing ?
346             ssl->in_buf_len > in_buf_new_len && ssl->in_left < in_buf_new_len :
347             ssl->in_buf_len < in_buf_new_len )
348         {
349             if( resize_buffer( &ssl->in_buf, in_buf_new_len, &ssl->in_buf_len ) != 0 )
350             {
351                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "input buffer resizing failed - out of memory" ) );
352             }
353             else
354             {
355                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating in_buf to %" MBEDTLS_PRINTF_SIZET,
356                                             in_buf_new_len ) );
357                 modified = 1;
358             }
359         }
360     }
361 
362     if( ssl->out_buf != NULL )
363     {
364         written_out = ssl->out_msg - ssl->out_buf;
365         iv_offset_out = ssl->out_iv - ssl->out_buf;
366         len_offset_out = ssl->out_len - ssl->out_buf;
367         if( downsizing ?
368             ssl->out_buf_len > out_buf_new_len && ssl->out_left < out_buf_new_len :
369             ssl->out_buf_len < out_buf_new_len )
370         {
371             if( resize_buffer( &ssl->out_buf, out_buf_new_len, &ssl->out_buf_len ) != 0 )
372             {
373                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "output buffer resizing failed - out of memory" ) );
374             }
375             else
376             {
377                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating out_buf to %" MBEDTLS_PRINTF_SIZET,
378                                             out_buf_new_len ) );
379                 modified = 1;
380             }
381         }
382     }
383     if( modified )
384     {
385         /* Update pointers here to avoid doing it twice. */
386         mbedtls_ssl_reset_in_out_pointers( ssl );
387         /* Fields below might not be properly updated with record
388          * splitting or with CID, so they are manually updated here. */
389         ssl->out_msg = ssl->out_buf + written_out;
390         ssl->out_len = ssl->out_buf + len_offset_out;
391         ssl->out_iv = ssl->out_buf + iv_offset_out;
392 
393         ssl->in_msg = ssl->in_buf + written_in;
394         ssl->in_len = ssl->in_buf + len_offset_in;
395         ssl->in_iv = ssl->in_buf + iv_offset_in;
396     }
397 }
398 #endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */
399 
400 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
401 
402 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
403 typedef int (*tls_prf_fn)( const unsigned char *secret, size_t slen,
404                            const char *label,
405                            const unsigned char *random, size_t rlen,
406                            unsigned char *dstbuf, size_t dlen );
407 
408 static tls_prf_fn ssl_tls12prf_from_cs( int ciphersuite_id );
409 
410 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
411 
412 /* Type for the TLS PRF */
413 typedef int ssl_tls_prf_t(const unsigned char *, size_t, const char *,
414                           const unsigned char *, size_t,
415                           unsigned char *, size_t);
416 
417 MBEDTLS_CHECK_RETURN_CRITICAL
418 static int ssl_tls12_populate_transform( mbedtls_ssl_transform *transform,
419                                    int ciphersuite,
420                                    const unsigned char master[48],
421 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
422                                    int encrypt_then_mac,
423 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
424                                    ssl_tls_prf_t tls_prf,
425                                    const unsigned char randbytes[64],
426                                    mbedtls_ssl_protocol_version tls_version,
427                                    unsigned endpoint,
428                                    const mbedtls_ssl_context *ssl );
429 
430 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
431 MBEDTLS_CHECK_RETURN_CRITICAL
432 static int tls_prf_sha256( const unsigned char *secret, size_t slen,
433                            const char *label,
434                            const unsigned char *random, size_t rlen,
435                            unsigned char *dstbuf, size_t dlen );
436 static void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *,unsigned char*, size_t * );
437 static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
438 
439 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
440 
441 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
442 MBEDTLS_CHECK_RETURN_CRITICAL
443 static int tls_prf_sha384( const unsigned char *secret, size_t slen,
444                            const char *label,
445                            const unsigned char *random, size_t rlen,
446                            unsigned char *dstbuf, size_t dlen );
447 
448 static void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *, unsigned char*, size_t * );
449 static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
450 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
451 
452 static size_t ssl_tls12_session_save( const mbedtls_ssl_session *session,
453                                       unsigned char *buf,
454                                       size_t buf_len );
455 
456 MBEDTLS_CHECK_RETURN_CRITICAL
457 static int ssl_tls12_session_load( mbedtls_ssl_session *session,
458                                    const unsigned char *buf,
459                                    size_t len );
460 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
461 
462 static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
463 
464 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
465 static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
466 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
467 
468 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
469 static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
470 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
471 
mbedtls_ssl_tls_prf(const mbedtls_tls_prf_types prf,const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)472 int  mbedtls_ssl_tls_prf( const mbedtls_tls_prf_types prf,
473                           const unsigned char *secret, size_t slen,
474                           const char *label,
475                           const unsigned char *random, size_t rlen,
476                           unsigned char *dstbuf, size_t dlen )
477 {
478     mbedtls_ssl_tls_prf_cb *tls_prf = NULL;
479 
480     switch( prf )
481     {
482 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
483 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
484         case MBEDTLS_SSL_TLS_PRF_SHA384:
485             tls_prf = tls_prf_sha384;
486         break;
487 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
488 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
489         case MBEDTLS_SSL_TLS_PRF_SHA256:
490             tls_prf = tls_prf_sha256;
491         break;
492 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
493 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
494     default:
495         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
496     }
497 
498     return( tls_prf( secret, slen, label, random, rlen, dstbuf, dlen ) );
499 }
500 
501 #if defined(MBEDTLS_X509_CRT_PARSE_C)
ssl_clear_peer_cert(mbedtls_ssl_session * session)502 static void ssl_clear_peer_cert( mbedtls_ssl_session *session )
503 {
504 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
505     if( session->peer_cert != NULL )
506     {
507         mbedtls_x509_crt_free( session->peer_cert );
508         mbedtls_free( session->peer_cert );
509         session->peer_cert = NULL;
510     }
511 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
512     if( session->peer_cert_digest != NULL )
513     {
514         /* Zeroization is not necessary. */
515         mbedtls_free( session->peer_cert_digest );
516         session->peer_cert_digest      = NULL;
517         session->peer_cert_digest_type = MBEDTLS_MD_NONE;
518         session->peer_cert_digest_len  = 0;
519     }
520 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
521 }
522 #endif /* MBEDTLS_X509_CRT_PARSE_C */
523 
mbedtls_ssl_get_extension_id(unsigned int extension_type)524 uint32_t mbedtls_ssl_get_extension_id( unsigned int extension_type )
525 {
526     switch( extension_type )
527     {
528         case MBEDTLS_TLS_EXT_SERVERNAME:
529             return( MBEDTLS_SSL_EXT_ID_SERVERNAME );
530 
531         case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
532             return( MBEDTLS_SSL_EXT_ID_MAX_FRAGMENT_LENGTH );
533 
534         case MBEDTLS_TLS_EXT_STATUS_REQUEST:
535             return( MBEDTLS_SSL_EXT_ID_STATUS_REQUEST );
536 
537         case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
538             return( MBEDTLS_SSL_EXT_ID_SUPPORTED_GROUPS );
539 
540         case MBEDTLS_TLS_EXT_SIG_ALG:
541             return( MBEDTLS_SSL_EXT_ID_SIG_ALG );
542 
543         case MBEDTLS_TLS_EXT_USE_SRTP:
544             return( MBEDTLS_SSL_EXT_ID_USE_SRTP );
545 
546         case MBEDTLS_TLS_EXT_HEARTBEAT:
547             return( MBEDTLS_SSL_EXT_ID_HEARTBEAT );
548 
549         case MBEDTLS_TLS_EXT_ALPN:
550             return( MBEDTLS_SSL_EXT_ID_ALPN );
551 
552         case MBEDTLS_TLS_EXT_SCT:
553             return( MBEDTLS_SSL_EXT_ID_SCT );
554 
555         case MBEDTLS_TLS_EXT_CLI_CERT_TYPE:
556             return( MBEDTLS_SSL_EXT_ID_CLI_CERT_TYPE );
557 
558         case MBEDTLS_TLS_EXT_SERV_CERT_TYPE:
559             return( MBEDTLS_SSL_EXT_ID_SERV_CERT_TYPE );
560 
561         case MBEDTLS_TLS_EXT_PADDING:
562             return( MBEDTLS_SSL_EXT_ID_PADDING );
563 
564         case MBEDTLS_TLS_EXT_PRE_SHARED_KEY:
565             return( MBEDTLS_SSL_EXT_ID_PRE_SHARED_KEY );
566 
567         case MBEDTLS_TLS_EXT_EARLY_DATA:
568             return( MBEDTLS_SSL_EXT_ID_EARLY_DATA );
569 
570         case MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS:
571             return( MBEDTLS_SSL_EXT_ID_SUPPORTED_VERSIONS );
572 
573         case MBEDTLS_TLS_EXT_COOKIE:
574             return( MBEDTLS_SSL_EXT_ID_COOKIE );
575 
576         case MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES:
577             return( MBEDTLS_SSL_EXT_ID_PSK_KEY_EXCHANGE_MODES );
578 
579         case MBEDTLS_TLS_EXT_CERT_AUTH:
580             return( MBEDTLS_SSL_EXT_ID_CERT_AUTH );
581 
582         case MBEDTLS_TLS_EXT_OID_FILTERS:
583             return( MBEDTLS_SSL_EXT_ID_OID_FILTERS );
584 
585         case MBEDTLS_TLS_EXT_POST_HANDSHAKE_AUTH:
586             return( MBEDTLS_SSL_EXT_ID_POST_HANDSHAKE_AUTH );
587 
588         case MBEDTLS_TLS_EXT_SIG_ALG_CERT:
589             return( MBEDTLS_SSL_EXT_ID_SIG_ALG_CERT );
590 
591         case MBEDTLS_TLS_EXT_KEY_SHARE:
592             return( MBEDTLS_SSL_EXT_ID_KEY_SHARE );
593 
594         case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
595             return( MBEDTLS_SSL_EXT_ID_TRUNCATED_HMAC );
596 
597         case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
598             return( MBEDTLS_SSL_EXT_ID_SUPPORTED_POINT_FORMATS );
599 
600         case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
601             return( MBEDTLS_SSL_EXT_ID_ENCRYPT_THEN_MAC );
602 
603         case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
604             return( MBEDTLS_SSL_EXT_ID_EXTENDED_MASTER_SECRET );
605 
606         case MBEDTLS_TLS_EXT_SESSION_TICKET:
607             return( MBEDTLS_SSL_EXT_ID_SESSION_TICKET );
608 
609     }
610 
611     return( MBEDTLS_SSL_EXT_ID_UNRECOGNIZED );
612 }
613 
mbedtls_ssl_get_extension_mask(unsigned int extension_type)614 uint32_t mbedtls_ssl_get_extension_mask( unsigned int extension_type )
615 {
616     return( 1 << mbedtls_ssl_get_extension_id( extension_type ) );
617 }
618 
619 #if defined(MBEDTLS_DEBUG_C)
620 static const char *extension_name_table[] = {
621     [MBEDTLS_SSL_EXT_ID_UNRECOGNIZED] = "unrecognized",
622     [MBEDTLS_SSL_EXT_ID_SERVERNAME] = "server_name",
623     [MBEDTLS_SSL_EXT_ID_MAX_FRAGMENT_LENGTH] = "max_fragment_length",
624     [MBEDTLS_SSL_EXT_ID_STATUS_REQUEST] = "status_request",
625     [MBEDTLS_SSL_EXT_ID_SUPPORTED_GROUPS] = "supported_groups",
626     [MBEDTLS_SSL_EXT_ID_SIG_ALG] = "signature_algorithms",
627     [MBEDTLS_SSL_EXT_ID_USE_SRTP] = "use_srtp",
628     [MBEDTLS_SSL_EXT_ID_HEARTBEAT] = "heartbeat",
629     [MBEDTLS_SSL_EXT_ID_ALPN] = "application_layer_protocol_negotiation",
630     [MBEDTLS_SSL_EXT_ID_SCT] = "signed_certificate_timestamp",
631     [MBEDTLS_SSL_EXT_ID_CLI_CERT_TYPE] = "client_certificate_type",
632     [MBEDTLS_SSL_EXT_ID_SERV_CERT_TYPE] = "server_certificate_type",
633     [MBEDTLS_SSL_EXT_ID_PADDING] = "padding",
634     [MBEDTLS_SSL_EXT_ID_PRE_SHARED_KEY] = "pre_shared_key",
635     [MBEDTLS_SSL_EXT_ID_EARLY_DATA] = "early_data",
636     [MBEDTLS_SSL_EXT_ID_SUPPORTED_VERSIONS] = "supported_versions",
637     [MBEDTLS_SSL_EXT_ID_COOKIE] = "cookie",
638     [MBEDTLS_SSL_EXT_ID_PSK_KEY_EXCHANGE_MODES] = "psk_key_exchange_modes",
639     [MBEDTLS_SSL_EXT_ID_CERT_AUTH] = "certificate_authorities",
640     [MBEDTLS_SSL_EXT_ID_OID_FILTERS] = "oid_filters",
641     [MBEDTLS_SSL_EXT_ID_POST_HANDSHAKE_AUTH] = "post_handshake_auth",
642     [MBEDTLS_SSL_EXT_ID_SIG_ALG_CERT] = "signature_algorithms_cert",
643     [MBEDTLS_SSL_EXT_ID_KEY_SHARE] = "key_share",
644     [MBEDTLS_SSL_EXT_ID_TRUNCATED_HMAC] = "truncated_hmac",
645     [MBEDTLS_SSL_EXT_ID_SUPPORTED_POINT_FORMATS] = "supported_point_formats",
646     [MBEDTLS_SSL_EXT_ID_ENCRYPT_THEN_MAC] = "encrypt_then_mac",
647     [MBEDTLS_SSL_EXT_ID_EXTENDED_MASTER_SECRET] = "extended_master_secret",
648     [MBEDTLS_SSL_EXT_ID_SESSION_TICKET] = "session_ticket"
649 };
650 
651 static unsigned int extension_type_table[]={
652     [MBEDTLS_SSL_EXT_ID_UNRECOGNIZED] = 0xff,
653     [MBEDTLS_SSL_EXT_ID_SERVERNAME] = MBEDTLS_TLS_EXT_SERVERNAME,
654     [MBEDTLS_SSL_EXT_ID_MAX_FRAGMENT_LENGTH] = MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH,
655     [MBEDTLS_SSL_EXT_ID_STATUS_REQUEST] = MBEDTLS_TLS_EXT_STATUS_REQUEST,
656     [MBEDTLS_SSL_EXT_ID_SUPPORTED_GROUPS] = MBEDTLS_TLS_EXT_SUPPORTED_GROUPS,
657     [MBEDTLS_SSL_EXT_ID_SIG_ALG] = MBEDTLS_TLS_EXT_SIG_ALG,
658     [MBEDTLS_SSL_EXT_ID_USE_SRTP] = MBEDTLS_TLS_EXT_USE_SRTP,
659     [MBEDTLS_SSL_EXT_ID_HEARTBEAT] = MBEDTLS_TLS_EXT_HEARTBEAT,
660     [MBEDTLS_SSL_EXT_ID_ALPN] = MBEDTLS_TLS_EXT_ALPN,
661     [MBEDTLS_SSL_EXT_ID_SCT] = MBEDTLS_TLS_EXT_SCT,
662     [MBEDTLS_SSL_EXT_ID_CLI_CERT_TYPE] = MBEDTLS_TLS_EXT_CLI_CERT_TYPE,
663     [MBEDTLS_SSL_EXT_ID_SERV_CERT_TYPE] = MBEDTLS_TLS_EXT_SERV_CERT_TYPE,
664     [MBEDTLS_SSL_EXT_ID_PADDING] = MBEDTLS_TLS_EXT_PADDING,
665     [MBEDTLS_SSL_EXT_ID_PRE_SHARED_KEY] = MBEDTLS_TLS_EXT_PRE_SHARED_KEY,
666     [MBEDTLS_SSL_EXT_ID_EARLY_DATA] = MBEDTLS_TLS_EXT_EARLY_DATA,
667     [MBEDTLS_SSL_EXT_ID_SUPPORTED_VERSIONS] = MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS,
668     [MBEDTLS_SSL_EXT_ID_COOKIE] = MBEDTLS_TLS_EXT_COOKIE,
669     [MBEDTLS_SSL_EXT_ID_PSK_KEY_EXCHANGE_MODES] = MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES,
670     [MBEDTLS_SSL_EXT_ID_CERT_AUTH] = MBEDTLS_TLS_EXT_CERT_AUTH,
671     [MBEDTLS_SSL_EXT_ID_OID_FILTERS] = MBEDTLS_TLS_EXT_OID_FILTERS,
672     [MBEDTLS_SSL_EXT_ID_POST_HANDSHAKE_AUTH] = MBEDTLS_TLS_EXT_POST_HANDSHAKE_AUTH,
673     [MBEDTLS_SSL_EXT_ID_SIG_ALG_CERT] = MBEDTLS_TLS_EXT_SIG_ALG_CERT,
674     [MBEDTLS_SSL_EXT_ID_KEY_SHARE] = MBEDTLS_TLS_EXT_KEY_SHARE,
675     [MBEDTLS_SSL_EXT_ID_TRUNCATED_HMAC] = MBEDTLS_TLS_EXT_TRUNCATED_HMAC,
676     [MBEDTLS_SSL_EXT_ID_SUPPORTED_POINT_FORMATS] = MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS,
677     [MBEDTLS_SSL_EXT_ID_ENCRYPT_THEN_MAC] = MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC,
678     [MBEDTLS_SSL_EXT_ID_EXTENDED_MASTER_SECRET] = MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET,
679     [MBEDTLS_SSL_EXT_ID_SESSION_TICKET] = MBEDTLS_TLS_EXT_SESSION_TICKET
680 };
681 
mbedtls_ssl_get_extension_name(unsigned int extension_type)682 const char *mbedtls_ssl_get_extension_name( unsigned int extension_type )
683 {
684     return( extension_name_table[
685                 mbedtls_ssl_get_extension_id( extension_type ) ] );
686 }
687 
ssl_tls13_get_hs_msg_name(int hs_msg_type)688 static const char *ssl_tls13_get_hs_msg_name( int hs_msg_type )
689 {
690     switch( hs_msg_type )
691     {
692         case MBEDTLS_SSL_HS_CLIENT_HELLO:
693             return( "ClientHello" );
694         case MBEDTLS_SSL_HS_SERVER_HELLO:
695             return( "ServerHello" );
696         case MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST:
697             return( "HelloRetryRequest" );
698         case MBEDTLS_SSL_HS_NEW_SESSION_TICKET:
699             return( "NewSessionTicket" );
700         case MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS:
701             return( "EncryptedExtensions" );
702         case MBEDTLS_SSL_HS_CERTIFICATE:
703             return( "Certificate" );
704         case MBEDTLS_SSL_HS_CERTIFICATE_REQUEST:
705             return( "CertificateRequest" );
706     }
707     return( "Unknown" );
708 }
709 
mbedtls_ssl_print_extension(const mbedtls_ssl_context * ssl,int level,const char * file,int line,int hs_msg_type,unsigned int extension_type,const char * extra_msg0,const char * extra_msg1)710 void mbedtls_ssl_print_extension( const mbedtls_ssl_context *ssl,
711                                   int level, const char *file, int line,
712                                   int hs_msg_type, unsigned int extension_type,
713                                   const char *extra_msg0, const char *extra_msg1 )
714 {
715     const char *extra_msg;
716     if( extra_msg0 && extra_msg1 )
717     {
718         mbedtls_debug_print_msg(
719             ssl, level, file, line,
720             "%s: %s(%u) extension %s %s.",
721             ssl_tls13_get_hs_msg_name( hs_msg_type ),
722             mbedtls_ssl_get_extension_name( extension_type ),
723             extension_type,
724             extra_msg0, extra_msg1 );
725         return;
726     }
727 
728     extra_msg = extra_msg0 ? extra_msg0 : extra_msg1;
729     if( extra_msg )
730     {
731         mbedtls_debug_print_msg(
732             ssl, level, file, line,
733             "%s: %s(%u) extension %s.", ssl_tls13_get_hs_msg_name( hs_msg_type ),
734             mbedtls_ssl_get_extension_name( extension_type ), extension_type,
735             extra_msg );
736         return;
737     }
738 
739     mbedtls_debug_print_msg(
740         ssl, level, file, line,
741         "%s: %s(%u) extension.", ssl_tls13_get_hs_msg_name( hs_msg_type ),
742         mbedtls_ssl_get_extension_name( extension_type ), extension_type );
743 }
744 
mbedtls_ssl_print_extensions(const mbedtls_ssl_context * ssl,int level,const char * file,int line,int hs_msg_type,uint32_t extensions_mask,const char * extra)745 void mbedtls_ssl_print_extensions( const mbedtls_ssl_context *ssl,
746                                    int level, const char *file, int line,
747                                    int hs_msg_type, uint32_t extensions_mask,
748                                    const char *extra )
749 {
750 
751     for( unsigned i = 0;
752          i < sizeof( extension_name_table ) / sizeof( extension_name_table[0] );
753          i++ )
754     {
755         mbedtls_ssl_print_extension(
756             ssl, level, file, line, hs_msg_type, extension_type_table[i],
757             extensions_mask & ( 1 << i ) ? "exists" : "does not exist", extra );
758     }
759 }
760 
761 #endif /* MBEDTLS_DEBUG_C */
762 
mbedtls_ssl_optimize_checksum(mbedtls_ssl_context * ssl,const mbedtls_ssl_ciphersuite_t * ciphersuite_info)763 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
764                             const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
765 {
766     ((void) ciphersuite_info);
767 
768 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
769     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
770         ssl->handshake->update_checksum = ssl_update_checksum_sha384;
771     else
772 #endif
773 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
774     if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
775         ssl->handshake->update_checksum = ssl_update_checksum_sha256;
776     else
777 #endif
778     {
779         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
780         return;
781     }
782 }
783 
mbedtls_ssl_add_hs_hdr_to_checksum(mbedtls_ssl_context * ssl,unsigned hs_type,size_t total_hs_len)784 void mbedtls_ssl_add_hs_hdr_to_checksum( mbedtls_ssl_context *ssl,
785                                          unsigned hs_type,
786                                          size_t total_hs_len )
787 {
788     unsigned char hs_hdr[4];
789 
790     /* Build HS header for checksum update. */
791     hs_hdr[0] = MBEDTLS_BYTE_0( hs_type );
792     hs_hdr[1] = MBEDTLS_BYTE_2( total_hs_len );
793     hs_hdr[2] = MBEDTLS_BYTE_1( total_hs_len );
794     hs_hdr[3] = MBEDTLS_BYTE_0( total_hs_len );
795 
796     ssl->handshake->update_checksum( ssl, hs_hdr, sizeof( hs_hdr ) );
797 }
798 
mbedtls_ssl_add_hs_msg_to_checksum(mbedtls_ssl_context * ssl,unsigned hs_type,unsigned char const * msg,size_t msg_len)799 void mbedtls_ssl_add_hs_msg_to_checksum( mbedtls_ssl_context *ssl,
800                                          unsigned hs_type,
801                                          unsigned char const *msg,
802                                          size_t msg_len )
803 {
804     mbedtls_ssl_add_hs_hdr_to_checksum( ssl, hs_type, msg_len );
805     ssl->handshake->update_checksum( ssl, msg, msg_len );
806 }
807 
mbedtls_ssl_reset_checksum(mbedtls_ssl_context * ssl)808 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
809 {
810     ((void) ssl);
811 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
812 #if defined(MBEDTLS_USE_PSA_CRYPTO)
813     psa_hash_abort( &ssl->handshake->fin_sha256_psa );
814     psa_hash_setup( &ssl->handshake->fin_sha256_psa, PSA_ALG_SHA_256 );
815 #else
816     mbedtls_sha256_starts( &ssl->handshake->fin_sha256, 0 );
817 #endif
818 #endif
819 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
820 #if defined(MBEDTLS_USE_PSA_CRYPTO)
821     psa_hash_abort( &ssl->handshake->fin_sha384_psa );
822     psa_hash_setup( &ssl->handshake->fin_sha384_psa, PSA_ALG_SHA_384 );
823 #else
824     mbedtls_sha512_starts( &ssl->handshake->fin_sha384, 1 );
825 #endif
826 #endif
827 }
828 
ssl_update_checksum_start(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)829 static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
830                                        const unsigned char *buf, size_t len )
831 {
832 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
833 #if defined(MBEDTLS_USE_PSA_CRYPTO)
834     psa_hash_update( &ssl->handshake->fin_sha256_psa, buf, len );
835 #else
836     mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len );
837 #endif
838 #endif
839 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
840 #if defined(MBEDTLS_USE_PSA_CRYPTO)
841     psa_hash_update( &ssl->handshake->fin_sha384_psa, buf, len );
842 #else
843     mbedtls_sha512_update( &ssl->handshake->fin_sha384, buf, len );
844 #endif
845 #endif
846 #if !defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
847     !defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
848     (void) ssl;
849     (void) buf;
850     (void) len;
851 #endif
852 }
853 
854 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
ssl_update_checksum_sha256(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)855 static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
856                                         const unsigned char *buf, size_t len )
857 {
858 #if defined(MBEDTLS_USE_PSA_CRYPTO)
859     psa_hash_update( &ssl->handshake->fin_sha256_psa, buf, len );
860 #else
861     mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len );
862 #endif
863 }
864 #endif
865 
866 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
ssl_update_checksum_sha384(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)867 static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
868                                         const unsigned char *buf, size_t len )
869 {
870 #if defined(MBEDTLS_USE_PSA_CRYPTO)
871     psa_hash_update( &ssl->handshake->fin_sha384_psa, buf, len );
872 #else
873     mbedtls_sha512_update( &ssl->handshake->fin_sha384, buf, len );
874 #endif
875 }
876 #endif
877 
ssl_handshake_params_init(mbedtls_ssl_handshake_params * handshake)878 static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
879 {
880     memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
881 
882 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
883 #if defined(MBEDTLS_USE_PSA_CRYPTO)
884     handshake->fin_sha256_psa = psa_hash_operation_init();
885     psa_hash_setup( &handshake->fin_sha256_psa, PSA_ALG_SHA_256 );
886 #else
887     mbedtls_sha256_init(   &handshake->fin_sha256    );
888     mbedtls_sha256_starts( &handshake->fin_sha256, 0 );
889 #endif
890 #endif
891 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
892 #if defined(MBEDTLS_USE_PSA_CRYPTO)
893     handshake->fin_sha384_psa = psa_hash_operation_init();
894     psa_hash_setup( &handshake->fin_sha384_psa, PSA_ALG_SHA_384 );
895 #else
896     mbedtls_sha512_init(   &handshake->fin_sha384    );
897     mbedtls_sha512_starts( &handshake->fin_sha384, 1 );
898 #endif
899 #endif
900 
901     handshake->update_checksum = ssl_update_checksum_start;
902 
903 #if defined(MBEDTLS_DHM_C)
904     mbedtls_dhm_init( &handshake->dhm_ctx );
905 #endif
906 #if !defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_ECDH_C)
907     mbedtls_ecdh_init( &handshake->ecdh_ctx );
908 #endif
909 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
910 #if defined(MBEDTLS_USE_PSA_CRYPTO)
911     handshake->psa_pake_ctx = psa_pake_operation_init();
912     handshake->psa_pake_password = MBEDTLS_SVC_KEY_ID_INIT;
913 #else
914     mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
915 #endif /* MBEDTLS_USE_PSA_CRYPTO */
916 #if defined(MBEDTLS_SSL_CLI_C)
917     handshake->ecjpake_cache = NULL;
918     handshake->ecjpake_cache_len = 0;
919 #endif
920 #endif
921 
922 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
923     mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx );
924 #endif
925 
926 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
927     handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
928 #endif
929 
930 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
931     !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
932     mbedtls_pk_init( &handshake->peer_pubkey );
933 #endif
934 }
935 
mbedtls_ssl_transform_init(mbedtls_ssl_transform * transform)936 void mbedtls_ssl_transform_init( mbedtls_ssl_transform *transform )
937 {
938     memset( transform, 0, sizeof(mbedtls_ssl_transform) );
939 
940 #if defined(MBEDTLS_USE_PSA_CRYPTO)
941     transform->psa_key_enc = MBEDTLS_SVC_KEY_ID_INIT;
942     transform->psa_key_dec = MBEDTLS_SVC_KEY_ID_INIT;
943 #else
944     mbedtls_cipher_init( &transform->cipher_ctx_enc );
945     mbedtls_cipher_init( &transform->cipher_ctx_dec );
946 #endif
947 
948 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
949 #if defined(MBEDTLS_USE_PSA_CRYPTO)
950     transform->psa_mac_enc = MBEDTLS_SVC_KEY_ID_INIT;
951     transform->psa_mac_dec = MBEDTLS_SVC_KEY_ID_INIT;
952 #else
953     mbedtls_md_init( &transform->md_ctx_enc );
954     mbedtls_md_init( &transform->md_ctx_dec );
955 #endif
956 #endif
957 }
958 
mbedtls_ssl_session_init(mbedtls_ssl_session * session)959 void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
960 {
961     memset( session, 0, sizeof(mbedtls_ssl_session) );
962 }
963 
964 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_handshake_init(mbedtls_ssl_context * ssl)965 static int ssl_handshake_init( mbedtls_ssl_context *ssl )
966 {
967     /* Clear old handshake information if present */
968     if( ssl->transform_negotiate )
969         mbedtls_ssl_transform_free( ssl->transform_negotiate );
970     if( ssl->session_negotiate )
971         mbedtls_ssl_session_free( ssl->session_negotiate );
972     if( ssl->handshake )
973         mbedtls_ssl_handshake_free( ssl );
974 
975     /*
976      * Either the pointers are now NULL or cleared properly and can be freed.
977      * Now allocate missing structures.
978      */
979     if( ssl->transform_negotiate == NULL )
980     {
981         ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
982     }
983 
984     if( ssl->session_negotiate == NULL )
985     {
986         ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
987     }
988 
989     if( ssl->handshake == NULL )
990     {
991         ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
992     }
993 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
994     /* If the buffers are too small - reallocate */
995 
996     handle_buffer_resizing( ssl, 0, MBEDTLS_SSL_IN_BUFFER_LEN,
997                                     MBEDTLS_SSL_OUT_BUFFER_LEN );
998 #endif
999 
1000     /* All pointers should exist and can be directly freed without issue */
1001     if( ssl->handshake == NULL ||
1002         ssl->transform_negotiate == NULL ||
1003         ssl->session_negotiate == NULL )
1004     {
1005         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
1006 
1007         mbedtls_free( ssl->handshake );
1008         mbedtls_free( ssl->transform_negotiate );
1009         mbedtls_free( ssl->session_negotiate );
1010 
1011         ssl->handshake = NULL;
1012         ssl->transform_negotiate = NULL;
1013         ssl->session_negotiate = NULL;
1014 
1015         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
1016     }
1017 
1018     /* Initialize structures */
1019     mbedtls_ssl_session_init( ssl->session_negotiate );
1020     mbedtls_ssl_transform_init( ssl->transform_negotiate );
1021     ssl_handshake_params_init( ssl->handshake );
1022 
1023 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
1024     defined(MBEDTLS_SSL_SRV_C) && \
1025     defined(MBEDTLS_SSL_SESSION_TICKETS)
1026     ssl->handshake->new_session_tickets_count =
1027         ssl->conf->new_session_tickets_count ;
1028 #endif
1029 
1030 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1031     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1032     {
1033         ssl->handshake->alt_transform_out = ssl->transform_out;
1034 
1035         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
1036             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
1037         else
1038             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
1039 
1040         mbedtls_ssl_set_timer( ssl, 0 );
1041     }
1042 #endif
1043 
1044 /*
1045  * curve_list is translated to IANA TLS group identifiers here because
1046  * mbedtls_ssl_conf_curves returns void and so can't return
1047  * any error codes.
1048  */
1049 #if defined(MBEDTLS_ECP_C)
1050 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
1051     /* Heap allocate and translate curve_list from internal to IANA group ids */
1052     if ( ssl->conf->curve_list != NULL )
1053     {
1054         size_t length;
1055         const mbedtls_ecp_group_id *curve_list = ssl->conf->curve_list;
1056 
1057         for( length = 0;  ( curve_list[length] != MBEDTLS_ECP_DP_NONE ) &&
1058                           ( length < MBEDTLS_ECP_DP_MAX ); length++ ) {}
1059 
1060         /* Leave room for zero termination */
1061         uint16_t *group_list = mbedtls_calloc( length + 1, sizeof(uint16_t) );
1062         if ( group_list == NULL )
1063             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
1064 
1065         for( size_t i = 0; i < length; i++ )
1066         {
1067             const mbedtls_ecp_curve_info *info =
1068                         mbedtls_ecp_curve_info_from_grp_id( curve_list[i] );
1069             if ( info == NULL )
1070             {
1071                 mbedtls_free( group_list );
1072                 return( MBEDTLS_ERR_SSL_BAD_CONFIG );
1073             }
1074             group_list[i] = info->tls_id;
1075         }
1076 
1077         group_list[length] = 0;
1078 
1079         ssl->handshake->group_list = group_list;
1080         ssl->handshake->group_list_heap_allocated = 1;
1081     }
1082     else
1083     {
1084         ssl->handshake->group_list = ssl->conf->group_list;
1085         ssl->handshake->group_list_heap_allocated = 0;
1086     }
1087 #endif /* MBEDTLS_DEPRECATED_REMOVED */
1088 #endif /* MBEDTLS_ECP_C */
1089 
1090 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1091 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
1092 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1093     /* Heap allocate and translate sig_hashes from internal hash identifiers to
1094        signature algorithms IANA identifiers.  */
1095     if ( mbedtls_ssl_conf_is_tls12_only( ssl->conf ) &&
1096          ssl->conf->sig_hashes != NULL )
1097     {
1098         const int *md;
1099         const int *sig_hashes = ssl->conf->sig_hashes;
1100         size_t sig_algs_len = 0;
1101         uint16_t *p;
1102 
1103 #if defined(static_assert)
1104         static_assert( MBEDTLS_SSL_MAX_SIG_ALG_LIST_LEN
1105                        <= ( SIZE_MAX - ( 2 * sizeof(uint16_t) ) ),
1106                        "MBEDTLS_SSL_MAX_SIG_ALG_LIST_LEN too big" );
1107 #endif
1108 
1109         for( md = sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
1110         {
1111             if( mbedtls_ssl_hash_from_md_alg( *md ) == MBEDTLS_SSL_HASH_NONE )
1112                 continue;
1113 #if defined(MBEDTLS_ECDSA_C)
1114             sig_algs_len += sizeof( uint16_t );
1115 #endif
1116 
1117 #if defined(MBEDTLS_RSA_C)
1118             sig_algs_len += sizeof( uint16_t );
1119 #endif
1120             if( sig_algs_len > MBEDTLS_SSL_MAX_SIG_ALG_LIST_LEN )
1121                 return( MBEDTLS_ERR_SSL_BAD_CONFIG );
1122         }
1123 
1124         if( sig_algs_len < MBEDTLS_SSL_MIN_SIG_ALG_LIST_LEN )
1125             return( MBEDTLS_ERR_SSL_BAD_CONFIG );
1126 
1127         ssl->handshake->sig_algs = mbedtls_calloc( 1, sig_algs_len +
1128                                                       sizeof( uint16_t ));
1129         if( ssl->handshake->sig_algs == NULL )
1130             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
1131 
1132         p = (uint16_t *)ssl->handshake->sig_algs;
1133         for( md = sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
1134         {
1135             unsigned char hash = mbedtls_ssl_hash_from_md_alg( *md );
1136             if( hash == MBEDTLS_SSL_HASH_NONE )
1137                 continue;
1138 #if defined(MBEDTLS_ECDSA_C)
1139             *p = (( hash << 8 ) | MBEDTLS_SSL_SIG_ECDSA);
1140             p++;
1141 #endif
1142 #if defined(MBEDTLS_RSA_C)
1143             *p = (( hash << 8 ) | MBEDTLS_SSL_SIG_RSA);
1144             p++;
1145 #endif
1146         }
1147         *p = MBEDTLS_TLS_SIG_NONE;
1148         ssl->handshake->sig_algs_heap_allocated = 1;
1149     }
1150     else
1151 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1152     {
1153         ssl->handshake->sig_algs_heap_allocated = 0;
1154     }
1155 #endif /* !MBEDTLS_DEPRECATED_REMOVED */
1156 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1157     return( 0 );
1158 }
1159 
1160 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
1161 /* Dummy cookie callbacks for defaults */
1162 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_cookie_write_dummy(void * ctx,unsigned char ** p,unsigned char * end,const unsigned char * cli_id,size_t cli_id_len)1163 static int ssl_cookie_write_dummy( void *ctx,
1164                       unsigned char **p, unsigned char *end,
1165                       const unsigned char *cli_id, size_t cli_id_len )
1166 {
1167     ((void) ctx);
1168     ((void) p);
1169     ((void) end);
1170     ((void) cli_id);
1171     ((void) cli_id_len);
1172 
1173     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1174 }
1175 
1176 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_cookie_check_dummy(void * ctx,const unsigned char * cookie,size_t cookie_len,const unsigned char * cli_id,size_t cli_id_len)1177 static int ssl_cookie_check_dummy( void *ctx,
1178                       const unsigned char *cookie, size_t cookie_len,
1179                       const unsigned char *cli_id, size_t cli_id_len )
1180 {
1181     ((void) ctx);
1182     ((void) cookie);
1183     ((void) cookie_len);
1184     ((void) cli_id);
1185     ((void) cli_id_len);
1186 
1187     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1188 }
1189 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
1190 
1191 /*
1192  * Initialize an SSL context
1193  */
mbedtls_ssl_init(mbedtls_ssl_context * ssl)1194 void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
1195 {
1196     memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
1197 }
1198 
1199 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_conf_version_check(const mbedtls_ssl_context * ssl)1200 static int ssl_conf_version_check( const mbedtls_ssl_context *ssl )
1201 {
1202     const mbedtls_ssl_config *conf = ssl->conf;
1203 
1204 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1205     if( mbedtls_ssl_conf_is_tls13_only( conf ) )
1206     {
1207         if( conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1208         {
1209              MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS 1.3 is not yet supported." ) );
1210              return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1211         }
1212 
1213         MBEDTLS_SSL_DEBUG_MSG( 4, ( "The SSL configuration is tls13 only." ) );
1214         return( 0 );
1215     }
1216 #endif
1217 
1218 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1219     if( mbedtls_ssl_conf_is_tls12_only( conf ) )
1220     {
1221         MBEDTLS_SSL_DEBUG_MSG( 4, ( "The SSL configuration is tls12 only." ) );
1222         return( 0 );
1223     }
1224 #endif
1225 
1226 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
1227     if( mbedtls_ssl_conf_is_hybrid_tls12_tls13( conf ) )
1228     {
1229         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1230         {
1231              MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS not yet supported in Hybrid TLS 1.3 + TLS 1.2" ) );
1232              return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1233         }
1234 
1235         if( conf->endpoint == MBEDTLS_SSL_IS_SERVER )
1236         {
1237             MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS 1.3 server is not supported yet." ) );
1238             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1239         }
1240 
1241 
1242         MBEDTLS_SSL_DEBUG_MSG( 4, ( "The SSL configuration is TLS 1.3 or TLS 1.2." ) );
1243         return( 0 );
1244     }
1245 #endif
1246 
1247     MBEDTLS_SSL_DEBUG_MSG( 1, ( "The SSL configuration is invalid." ) );
1248     return( MBEDTLS_ERR_SSL_BAD_CONFIG );
1249 }
1250 
1251 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_conf_check(const mbedtls_ssl_context * ssl)1252 static int ssl_conf_check(const mbedtls_ssl_context *ssl)
1253 {
1254     int ret;
1255     ret = ssl_conf_version_check( ssl );
1256     if( ret != 0 )
1257         return( ret );
1258 
1259 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1260     /* RFC 8446 section 4.4.3
1261      *
1262      * If the verification fails, the receiver MUST terminate the handshake with
1263      * a "decrypt_error" alert.
1264      *
1265      * If the client is configured as TLS 1.3 only with optional verify, return
1266      * bad config.
1267      *
1268      */
1269     if( mbedtls_ssl_conf_tls13_ephemeral_enabled(
1270             (mbedtls_ssl_context *)ssl )                            &&
1271         ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT                &&
1272         ssl->conf->max_tls_version == MBEDTLS_SSL_VERSION_TLS1_3    &&
1273         ssl->conf->min_tls_version == MBEDTLS_SSL_VERSION_TLS1_3    &&
1274         ssl->conf->authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
1275     {
1276         MBEDTLS_SSL_DEBUG_MSG(
1277             1, ( "Optional verify auth mode "
1278                  "is not available for TLS 1.3 client" ) );
1279         return( MBEDTLS_ERR_SSL_BAD_CONFIG );
1280     }
1281 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1282 
1283     /* Space for further checks */
1284 
1285     return( 0 );
1286 }
1287 
1288 /*
1289  * Setup an SSL context
1290  */
1291 
mbedtls_ssl_setup(mbedtls_ssl_context * ssl,const mbedtls_ssl_config * conf)1292 int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
1293                        const mbedtls_ssl_config *conf )
1294 {
1295     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1296     size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
1297     size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
1298 
1299     ssl->conf = conf;
1300 
1301     if( ( ret = ssl_conf_check( ssl ) ) != 0 )
1302         return( ret );
1303 
1304     /*
1305      * Prepare base structures
1306      */
1307 
1308     /* Set to NULL in case of an error condition */
1309     ssl->out_buf = NULL;
1310 
1311 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
1312     ssl->in_buf_len = in_buf_len;
1313 #endif
1314     ssl->in_buf = mbedtls_calloc( 1, in_buf_len );
1315     if( ssl->in_buf == NULL )
1316     {
1317         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", in_buf_len ) );
1318         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1319         goto error;
1320     }
1321 
1322 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
1323     ssl->out_buf_len = out_buf_len;
1324 #endif
1325     ssl->out_buf = mbedtls_calloc( 1, out_buf_len );
1326     if( ssl->out_buf == NULL )
1327     {
1328         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", out_buf_len ) );
1329         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1330         goto error;
1331     }
1332 
1333     mbedtls_ssl_reset_in_out_pointers( ssl );
1334 
1335 #if defined(MBEDTLS_SSL_DTLS_SRTP)
1336     memset( &ssl->dtls_srtp_info, 0, sizeof(ssl->dtls_srtp_info) );
1337 #endif
1338 
1339     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
1340         goto error;
1341 
1342     return( 0 );
1343 
1344 error:
1345     mbedtls_free( ssl->in_buf );
1346     mbedtls_free( ssl->out_buf );
1347 
1348     ssl->conf = NULL;
1349 
1350 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
1351     ssl->in_buf_len = 0;
1352     ssl->out_buf_len = 0;
1353 #endif
1354     ssl->in_buf = NULL;
1355     ssl->out_buf = NULL;
1356 
1357     ssl->in_hdr = NULL;
1358     ssl->in_ctr = NULL;
1359     ssl->in_len = NULL;
1360     ssl->in_iv = NULL;
1361     ssl->in_msg = NULL;
1362 
1363     ssl->out_hdr = NULL;
1364     ssl->out_ctr = NULL;
1365     ssl->out_len = NULL;
1366     ssl->out_iv = NULL;
1367     ssl->out_msg = NULL;
1368 
1369     return( ret );
1370 }
1371 
1372 /*
1373  * Reset an initialized and used SSL context for re-use while retaining
1374  * all application-set variables, function pointers and data.
1375  *
1376  * If partial is non-zero, keep data in the input buffer and client ID.
1377  * (Use when a DTLS client reconnects from the same port.)
1378  */
mbedtls_ssl_session_reset_msg_layer(mbedtls_ssl_context * ssl,int partial)1379 void mbedtls_ssl_session_reset_msg_layer( mbedtls_ssl_context *ssl,
1380                                           int partial )
1381 {
1382 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
1383     size_t in_buf_len = ssl->in_buf_len;
1384     size_t out_buf_len = ssl->out_buf_len;
1385 #else
1386     size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
1387     size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
1388 #endif
1389 
1390 #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) || !defined(MBEDTLS_SSL_SRV_C)
1391     partial = 0;
1392 #endif
1393 
1394     /* Cancel any possibly running timer */
1395     mbedtls_ssl_set_timer( ssl, 0 );
1396 
1397     mbedtls_ssl_reset_in_out_pointers( ssl );
1398 
1399     /* Reset incoming message parsing */
1400     ssl->in_offt    = NULL;
1401     ssl->nb_zero    = 0;
1402     ssl->in_msgtype = 0;
1403     ssl->in_msglen  = 0;
1404     ssl->in_hslen   = 0;
1405     ssl->keep_current_message = 0;
1406     ssl->transform_in  = NULL;
1407 
1408 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1409     ssl->next_record_offset = 0;
1410     ssl->in_epoch = 0;
1411 #endif
1412 
1413     /* Keep current datagram if partial == 1 */
1414     if( partial == 0 )
1415     {
1416         ssl->in_left = 0;
1417         memset( ssl->in_buf, 0, in_buf_len );
1418     }
1419 
1420     ssl->send_alert = 0;
1421 
1422     /* Reset outgoing message writing */
1423     ssl->out_msgtype = 0;
1424     ssl->out_msglen  = 0;
1425     ssl->out_left    = 0;
1426     memset( ssl->out_buf, 0, out_buf_len );
1427     memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) );
1428     ssl->transform_out = NULL;
1429 
1430 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1431     mbedtls_ssl_dtls_replay_reset( ssl );
1432 #endif
1433 
1434 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1435     if( ssl->transform )
1436     {
1437         mbedtls_ssl_transform_free( ssl->transform );
1438         mbedtls_free( ssl->transform );
1439         ssl->transform = NULL;
1440     }
1441 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1442 
1443 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1444     mbedtls_ssl_transform_free( ssl->transform_application );
1445     mbedtls_free( ssl->transform_application );
1446     ssl->transform_application = NULL;
1447 
1448     if( ssl->handshake != NULL )
1449     {
1450 #if defined(MBEDTLS_SSL_EARLY_DATA)
1451         mbedtls_ssl_transform_free( ssl->handshake->transform_earlydata );
1452         mbedtls_free( ssl->handshake->transform_earlydata );
1453         ssl->handshake->transform_earlydata = NULL;
1454 #endif
1455 
1456         mbedtls_ssl_transform_free( ssl->handshake->transform_handshake );
1457         mbedtls_free( ssl->handshake->transform_handshake );
1458         ssl->handshake->transform_handshake = NULL;
1459     }
1460 
1461 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1462 }
1463 
mbedtls_ssl_session_reset_int(mbedtls_ssl_context * ssl,int partial)1464 int mbedtls_ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
1465 {
1466     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1467 
1468     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
1469 
1470     mbedtls_ssl_session_reset_msg_layer( ssl, partial );
1471 
1472     /* Reset renegotiation state */
1473 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1474     ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
1475     ssl->renego_records_seen = 0;
1476 
1477     ssl->verify_data_len = 0;
1478     memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
1479     memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
1480 #endif
1481     ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
1482 
1483     ssl->session_in  = NULL;
1484     ssl->session_out = NULL;
1485     if( ssl->session )
1486     {
1487         mbedtls_ssl_session_free( ssl->session );
1488         mbedtls_free( ssl->session );
1489         ssl->session = NULL;
1490     }
1491 
1492 #if defined(MBEDTLS_SSL_ALPN)
1493     ssl->alpn_chosen = NULL;
1494 #endif
1495 
1496 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
1497     int free_cli_id = 1;
1498 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
1499     free_cli_id = ( partial == 0 );
1500 #endif
1501     if( free_cli_id )
1502     {
1503         mbedtls_free( ssl->cli_id );
1504         ssl->cli_id = NULL;
1505         ssl->cli_id_len = 0;
1506     }
1507 #endif
1508 
1509     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
1510         return( ret );
1511 
1512     return( 0 );
1513 }
1514 
1515 /*
1516  * Reset an initialized and used SSL context for re-use while retaining
1517  * all application-set variables, function pointers and data.
1518  */
mbedtls_ssl_session_reset(mbedtls_ssl_context * ssl)1519 int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
1520 {
1521     return( mbedtls_ssl_session_reset_int( ssl, 0 ) );
1522 }
1523 
1524 /*
1525  * SSL set accessors
1526  */
mbedtls_ssl_conf_endpoint(mbedtls_ssl_config * conf,int endpoint)1527 void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
1528 {
1529     conf->endpoint   = endpoint;
1530 }
1531 
mbedtls_ssl_conf_transport(mbedtls_ssl_config * conf,int transport)1532 void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
1533 {
1534     conf->transport = transport;
1535 }
1536 
1537 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
mbedtls_ssl_conf_dtls_anti_replay(mbedtls_ssl_config * conf,char mode)1538 void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
1539 {
1540     conf->anti_replay = mode;
1541 }
1542 #endif
1543 
mbedtls_ssl_conf_dtls_badmac_limit(mbedtls_ssl_config * conf,unsigned limit)1544 void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
1545 {
1546     conf->badmac_limit = limit;
1547 }
1548 
1549 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1550 
mbedtls_ssl_set_datagram_packing(mbedtls_ssl_context * ssl,unsigned allow_packing)1551 void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl,
1552                                        unsigned allow_packing )
1553 {
1554     ssl->disable_datagram_packing = !allow_packing;
1555 }
1556 
mbedtls_ssl_conf_handshake_timeout(mbedtls_ssl_config * conf,uint32_t min,uint32_t max)1557 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf,
1558                                          uint32_t min, uint32_t max )
1559 {
1560     conf->hs_timeout_min = min;
1561     conf->hs_timeout_max = max;
1562 }
1563 #endif
1564 
mbedtls_ssl_conf_authmode(mbedtls_ssl_config * conf,int authmode)1565 void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
1566 {
1567     conf->authmode   = authmode;
1568 }
1569 
1570 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_conf_verify(mbedtls_ssl_config * conf,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)1571 void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
1572                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
1573                      void *p_vrfy )
1574 {
1575     conf->f_vrfy      = f_vrfy;
1576     conf->p_vrfy      = p_vrfy;
1577 }
1578 #endif /* MBEDTLS_X509_CRT_PARSE_C */
1579 
mbedtls_ssl_conf_rng(mbedtls_ssl_config * conf,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1580 void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
1581                   int (*f_rng)(void *, unsigned char *, size_t),
1582                   void *p_rng )
1583 {
1584     conf->f_rng      = f_rng;
1585     conf->p_rng      = p_rng;
1586 }
1587 
mbedtls_ssl_conf_dbg(mbedtls_ssl_config * conf,void (* f_dbg)(void *,int,const char *,int,const char *),void * p_dbg)1588 void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
1589                   void (*f_dbg)(void *, int, const char *, int, const char *),
1590                   void  *p_dbg )
1591 {
1592     conf->f_dbg      = f_dbg;
1593     conf->p_dbg      = p_dbg;
1594 }
1595 
mbedtls_ssl_set_bio(mbedtls_ssl_context * ssl,void * p_bio,mbedtls_ssl_send_t * f_send,mbedtls_ssl_recv_t * f_recv,mbedtls_ssl_recv_timeout_t * f_recv_timeout)1596 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
1597         void *p_bio,
1598         mbedtls_ssl_send_t *f_send,
1599         mbedtls_ssl_recv_t *f_recv,
1600         mbedtls_ssl_recv_timeout_t *f_recv_timeout )
1601 {
1602     ssl->p_bio          = p_bio;
1603     ssl->f_send         = f_send;
1604     ssl->f_recv         = f_recv;
1605     ssl->f_recv_timeout = f_recv_timeout;
1606 }
1607 
1608 #if defined(MBEDTLS_SSL_PROTO_DTLS)
mbedtls_ssl_set_mtu(mbedtls_ssl_context * ssl,uint16_t mtu)1609 void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu )
1610 {
1611     ssl->mtu = mtu;
1612 }
1613 #endif
1614 
mbedtls_ssl_conf_read_timeout(mbedtls_ssl_config * conf,uint32_t timeout)1615 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
1616 {
1617     conf->read_timeout   = timeout;
1618 }
1619 
mbedtls_ssl_set_timer_cb(mbedtls_ssl_context * ssl,void * p_timer,mbedtls_ssl_set_timer_t * f_set_timer,mbedtls_ssl_get_timer_t * f_get_timer)1620 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
1621                                void *p_timer,
1622                                mbedtls_ssl_set_timer_t *f_set_timer,
1623                                mbedtls_ssl_get_timer_t *f_get_timer )
1624 {
1625     ssl->p_timer        = p_timer;
1626     ssl->f_set_timer    = f_set_timer;
1627     ssl->f_get_timer    = f_get_timer;
1628 
1629     /* Make sure we start with no timer running */
1630     mbedtls_ssl_set_timer( ssl, 0 );
1631 }
1632 
1633 #if defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_conf_session_cache(mbedtls_ssl_config * conf,void * p_cache,mbedtls_ssl_cache_get_t * f_get_cache,mbedtls_ssl_cache_set_t * f_set_cache)1634 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
1635                                      void *p_cache,
1636                                      mbedtls_ssl_cache_get_t *f_get_cache,
1637                                      mbedtls_ssl_cache_set_t *f_set_cache )
1638 {
1639     conf->p_cache = p_cache;
1640     conf->f_get_cache = f_get_cache;
1641     conf->f_set_cache = f_set_cache;
1642 }
1643 #endif /* MBEDTLS_SSL_SRV_C */
1644 
1645 #if defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_set_session(mbedtls_ssl_context * ssl,const mbedtls_ssl_session * session)1646 int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
1647 {
1648     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1649 
1650     if( ssl == NULL ||
1651         session == NULL ||
1652         ssl->session_negotiate == NULL ||
1653         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
1654     {
1655         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1656     }
1657 
1658     if( ssl->handshake->resume == 1 )
1659         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1660 
1661 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1662     if( session->tls_version == MBEDTLS_SSL_VERSION_TLS1_3 )
1663     {
1664         const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
1665                     mbedtls_ssl_ciphersuite_from_id( session->ciphersuite );
1666 
1667         if( mbedtls_ssl_validate_ciphersuite(
1668                 ssl, ciphersuite_info, MBEDTLS_SSL_VERSION_TLS1_3,
1669                 MBEDTLS_SSL_VERSION_TLS1_3 ) != 0 )
1670         {
1671             MBEDTLS_SSL_DEBUG_MSG( 4, ( "%d is not a valid TLS 1.3 ciphersuite.",
1672                                         session->ciphersuite ) );
1673             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1674         }
1675     }
1676 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1677 
1678     if( ( ret = mbedtls_ssl_session_copy( ssl->session_negotiate,
1679                                           session ) ) != 0 )
1680         return( ret );
1681 
1682     ssl->handshake->resume = 1;
1683 
1684     return( 0 );
1685 }
1686 #endif /* MBEDTLS_SSL_CLI_C */
1687 
mbedtls_ssl_conf_ciphersuites(mbedtls_ssl_config * conf,const int * ciphersuites)1688 void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
1689                                     const int *ciphersuites )
1690 {
1691     conf->ciphersuite_list = ciphersuites;
1692 }
1693 
1694 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
mbedtls_ssl_conf_tls13_key_exchange_modes(mbedtls_ssl_config * conf,const int kex_modes)1695 void mbedtls_ssl_conf_tls13_key_exchange_modes( mbedtls_ssl_config *conf,
1696                                                 const int kex_modes )
1697 {
1698     conf->tls13_kex_modes = kex_modes & MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_ALL;
1699 }
1700 
1701 #if defined(MBEDTLS_SSL_EARLY_DATA)
mbedtls_ssl_tls13_conf_early_data(mbedtls_ssl_config * conf,int early_data_enabled)1702 void mbedtls_ssl_tls13_conf_early_data( mbedtls_ssl_config *conf,
1703                                         int early_data_enabled )
1704 {
1705     conf->early_data_enabled = early_data_enabled;
1706 }
1707 
1708 #if defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_tls13_conf_max_early_data_size(mbedtls_ssl_config * conf,uint32_t max_early_data_size)1709 void mbedtls_ssl_tls13_conf_max_early_data_size(
1710          mbedtls_ssl_config *conf, uint32_t max_early_data_size )
1711 {
1712     conf->max_early_data_size = max_early_data_size;
1713 }
1714 #endif /* MBEDTLS_SSL_SRV_C */
1715 
1716 #endif /* MBEDTLS_SSL_EARLY_DATA */
1717 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1718 
1719 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_conf_cert_profile(mbedtls_ssl_config * conf,const mbedtls_x509_crt_profile * profile)1720 void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
1721                                     const mbedtls_x509_crt_profile *profile )
1722 {
1723     conf->cert_profile = profile;
1724 }
1725 
ssl_key_cert_free(mbedtls_ssl_key_cert * key_cert)1726 static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
1727 {
1728     mbedtls_ssl_key_cert *cur = key_cert, *next;
1729 
1730     while( cur != NULL )
1731     {
1732         next = cur->next;
1733         mbedtls_free( cur );
1734         cur = next;
1735     }
1736 }
1737 
1738 /* Append a new keycert entry to a (possibly empty) list */
1739 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_append_key_cert(mbedtls_ssl_key_cert ** head,mbedtls_x509_crt * cert,mbedtls_pk_context * key)1740 static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
1741                                 mbedtls_x509_crt *cert,
1742                                 mbedtls_pk_context *key )
1743 {
1744     mbedtls_ssl_key_cert *new_cert;
1745 
1746     if( cert == NULL )
1747     {
1748         /* Free list if cert is null */
1749         ssl_key_cert_free( *head );
1750         *head = NULL;
1751         return( 0 );
1752     }
1753 
1754     new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
1755     if( new_cert == NULL )
1756         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
1757 
1758     new_cert->cert = cert;
1759     new_cert->key  = key;
1760     new_cert->next = NULL;
1761 
1762     /* Update head if the list was null, else add to the end */
1763     if( *head == NULL )
1764     {
1765         *head = new_cert;
1766     }
1767     else
1768     {
1769         mbedtls_ssl_key_cert *cur = *head;
1770         while( cur->next != NULL )
1771             cur = cur->next;
1772         cur->next = new_cert;
1773     }
1774 
1775     return( 0 );
1776 }
1777 
mbedtls_ssl_conf_own_cert(mbedtls_ssl_config * conf,mbedtls_x509_crt * own_cert,mbedtls_pk_context * pk_key)1778 int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
1779                               mbedtls_x509_crt *own_cert,
1780                               mbedtls_pk_context *pk_key )
1781 {
1782     return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
1783 }
1784 
mbedtls_ssl_conf_ca_chain(mbedtls_ssl_config * conf,mbedtls_x509_crt * ca_chain,mbedtls_x509_crl * ca_crl)1785 void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
1786                                mbedtls_x509_crt *ca_chain,
1787                                mbedtls_x509_crl *ca_crl )
1788 {
1789     conf->ca_chain   = ca_chain;
1790     conf->ca_crl     = ca_crl;
1791 
1792 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
1793     /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
1794      * cannot be used together. */
1795     conf->f_ca_cb = NULL;
1796     conf->p_ca_cb = NULL;
1797 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
1798 }
1799 
1800 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
mbedtls_ssl_conf_ca_cb(mbedtls_ssl_config * conf,mbedtls_x509_crt_ca_cb_t f_ca_cb,void * p_ca_cb)1801 void mbedtls_ssl_conf_ca_cb( mbedtls_ssl_config *conf,
1802                              mbedtls_x509_crt_ca_cb_t f_ca_cb,
1803                              void *p_ca_cb )
1804 {
1805     conf->f_ca_cb = f_ca_cb;
1806     conf->p_ca_cb = p_ca_cb;
1807 
1808     /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
1809      * cannot be used together. */
1810     conf->ca_chain   = NULL;
1811     conf->ca_crl     = NULL;
1812 }
1813 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
1814 #endif /* MBEDTLS_X509_CRT_PARSE_C */
1815 
1816 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
mbedtls_ssl_get_hs_sni(mbedtls_ssl_context * ssl,size_t * name_len)1817 const unsigned char *mbedtls_ssl_get_hs_sni( mbedtls_ssl_context *ssl,
1818                                              size_t *name_len )
1819 {
1820     *name_len = ssl->handshake->sni_name_len;
1821     return( ssl->handshake->sni_name );
1822 }
1823 
mbedtls_ssl_set_hs_own_cert(mbedtls_ssl_context * ssl,mbedtls_x509_crt * own_cert,mbedtls_pk_context * pk_key)1824 int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
1825                                  mbedtls_x509_crt *own_cert,
1826                                  mbedtls_pk_context *pk_key )
1827 {
1828     return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
1829                                  own_cert, pk_key ) );
1830 }
1831 
mbedtls_ssl_set_hs_ca_chain(mbedtls_ssl_context * ssl,mbedtls_x509_crt * ca_chain,mbedtls_x509_crl * ca_crl)1832 void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
1833                                   mbedtls_x509_crt *ca_chain,
1834                                   mbedtls_x509_crl *ca_crl )
1835 {
1836     ssl->handshake->sni_ca_chain   = ca_chain;
1837     ssl->handshake->sni_ca_crl     = ca_crl;
1838 }
1839 
1840 #if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
mbedtls_ssl_set_hs_dn_hints(mbedtls_ssl_context * ssl,const mbedtls_x509_crt * crt)1841 void mbedtls_ssl_set_hs_dn_hints( mbedtls_ssl_context *ssl,
1842                                   const mbedtls_x509_crt *crt)
1843 {
1844     ssl->handshake->dn_hints = crt;
1845 }
1846 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
1847 
mbedtls_ssl_set_hs_authmode(mbedtls_ssl_context * ssl,int authmode)1848 void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
1849                                   int authmode )
1850 {
1851     ssl->handshake->sni_authmode = authmode;
1852 }
1853 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1854 
1855 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_set_verify(mbedtls_ssl_context * ssl,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)1856 void mbedtls_ssl_set_verify( mbedtls_ssl_context *ssl,
1857                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
1858                      void *p_vrfy )
1859 {
1860     ssl->f_vrfy = f_vrfy;
1861     ssl->p_vrfy = p_vrfy;
1862 }
1863 #endif
1864 
1865 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1866 /*
1867  * Set EC J-PAKE password for current handshake
1868  */
1869 #if defined(MBEDTLS_USE_PSA_CRYPTO)
mbedtls_ssl_set_hs_ecjpake_password(mbedtls_ssl_context * ssl,const unsigned char * pw,size_t pw_len)1870 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
1871                                          const unsigned char *pw,
1872                                          size_t pw_len )
1873 {
1874     psa_pake_cipher_suite_t cipher_suite = psa_pake_cipher_suite_init();
1875     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1876     psa_pake_role_t psa_role;
1877     psa_status_t status;
1878 
1879     if( ssl->handshake == NULL || ssl->conf == NULL )
1880         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1881 
1882     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
1883         psa_role = PSA_PAKE_ROLE_SERVER;
1884     else
1885         psa_role = PSA_PAKE_ROLE_CLIENT;
1886 
1887     /* Empty password is not valid  */
1888     if( ( pw == NULL) || ( pw_len == 0 ) )
1889         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1890 
1891     psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_DERIVE );
1892     psa_set_key_algorithm( &attributes, PSA_ALG_JPAKE );
1893     psa_set_key_type( &attributes, PSA_KEY_TYPE_PASSWORD );
1894 
1895     status = psa_import_key( &attributes, pw, pw_len,
1896                                 &ssl->handshake->psa_pake_password );
1897     if( status != PSA_SUCCESS )
1898         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
1899 
1900     psa_pake_cs_set_algorithm( &cipher_suite, PSA_ALG_JPAKE );
1901     psa_pake_cs_set_primitive( &cipher_suite,
1902                                PSA_PAKE_PRIMITIVE( PSA_PAKE_PRIMITIVE_TYPE_ECC,
1903                                                    PSA_ECC_FAMILY_SECP_R1,
1904                                                    256) );
1905     psa_pake_cs_set_hash( &cipher_suite, PSA_ALG_SHA_256 );
1906 
1907     status = psa_pake_setup( &ssl->handshake->psa_pake_ctx, &cipher_suite );
1908     if( status != PSA_SUCCESS )
1909     {
1910         psa_destroy_key( ssl->handshake->psa_pake_password );
1911         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
1912     }
1913 
1914     status = psa_pake_set_role( &ssl->handshake->psa_pake_ctx, psa_role );
1915     if( status != PSA_SUCCESS )
1916     {
1917         psa_destroy_key( ssl->handshake->psa_pake_password );
1918         psa_pake_abort( &ssl->handshake->psa_pake_ctx );
1919         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
1920     }
1921 
1922     psa_pake_set_password_key( &ssl->handshake->psa_pake_ctx,
1923                                 ssl->handshake->psa_pake_password );
1924     if( status != PSA_SUCCESS )
1925     {
1926         psa_destroy_key( ssl->handshake->psa_pake_password );
1927         psa_pake_abort( &ssl->handshake->psa_pake_ctx );
1928         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
1929     }
1930 
1931     ssl->handshake->psa_pake_ctx_is_ok = 1;
1932 
1933     return( 0 );
1934 }
1935 #else /* MBEDTLS_USE_PSA_CRYPTO */
mbedtls_ssl_set_hs_ecjpake_password(mbedtls_ssl_context * ssl,const unsigned char * pw,size_t pw_len)1936 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
1937                                          const unsigned char *pw,
1938                                          size_t pw_len )
1939 {
1940     mbedtls_ecjpake_role role;
1941 
1942     if( ssl->handshake == NULL || ssl->conf == NULL )
1943         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1944 
1945     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
1946         role = MBEDTLS_ECJPAKE_SERVER;
1947     else
1948         role = MBEDTLS_ECJPAKE_CLIENT;
1949 
1950     return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
1951                                    role,
1952                                    MBEDTLS_MD_SHA256,
1953                                    MBEDTLS_ECP_DP_SECP256R1,
1954                                    pw, pw_len ) );
1955 }
1956 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1957 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1958 
1959 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
mbedtls_ssl_conf_has_static_psk(mbedtls_ssl_config const * conf)1960 int mbedtls_ssl_conf_has_static_psk( mbedtls_ssl_config const *conf )
1961 {
1962     if( conf->psk_identity     == NULL ||
1963         conf->psk_identity_len == 0     )
1964     {
1965         return( 0 );
1966     }
1967 
1968 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1969     if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) )
1970         return( 1 );
1971 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1972 
1973     if( conf->psk != NULL && conf->psk_len != 0 )
1974         return( 1 );
1975 
1976     return( 0 );
1977 }
1978 
ssl_conf_remove_psk(mbedtls_ssl_config * conf)1979 static void ssl_conf_remove_psk( mbedtls_ssl_config *conf )
1980 {
1981     /* Remove reference to existing PSK, if any. */
1982 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1983     if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) )
1984     {
1985         /* The maintenance of the PSK key slot is the
1986          * user's responsibility. */
1987         conf->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT;
1988     }
1989 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1990     if( conf->psk != NULL )
1991     {
1992         mbedtls_platform_zeroize( conf->psk, conf->psk_len );
1993 
1994         mbedtls_free( conf->psk );
1995         conf->psk = NULL;
1996         conf->psk_len = 0;
1997     }
1998 
1999     /* Remove reference to PSK identity, if any. */
2000     if( conf->psk_identity != NULL )
2001     {
2002         mbedtls_free( conf->psk_identity );
2003         conf->psk_identity = NULL;
2004         conf->psk_identity_len = 0;
2005     }
2006 }
2007 
2008 /* This function assumes that PSK identity in the SSL config is unset.
2009  * It checks that the provided identity is well-formed and attempts
2010  * to make a copy of it in the SSL config.
2011  * On failure, the PSK identity in the config remains unset. */
2012 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_conf_set_psk_identity(mbedtls_ssl_config * conf,unsigned char const * psk_identity,size_t psk_identity_len)2013 static int ssl_conf_set_psk_identity( mbedtls_ssl_config *conf,
2014                                       unsigned char const *psk_identity,
2015                                       size_t psk_identity_len )
2016 {
2017     /* Identity len will be encoded on two bytes */
2018     if( psk_identity               == NULL ||
2019         psk_identity_len           == 0    ||
2020         ( psk_identity_len >> 16 ) != 0    ||
2021         psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
2022     {
2023         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2024     }
2025 
2026     conf->psk_identity = mbedtls_calloc( 1, psk_identity_len );
2027     if( conf->psk_identity == NULL )
2028         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2029 
2030     conf->psk_identity_len = psk_identity_len;
2031     memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
2032 
2033     return( 0 );
2034 }
2035 
mbedtls_ssl_conf_psk(mbedtls_ssl_config * conf,const unsigned char * psk,size_t psk_len,const unsigned char * psk_identity,size_t psk_identity_len)2036 int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
2037                 const unsigned char *psk, size_t psk_len,
2038                 const unsigned char *psk_identity, size_t psk_identity_len )
2039 {
2040     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2041 
2042     /* We currently only support one PSK, raw or opaque. */
2043     if( mbedtls_ssl_conf_has_static_psk( conf ) )
2044         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2045 
2046     /* Check and set raw PSK */
2047     if( psk == NULL )
2048         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2049     if( psk_len == 0 )
2050         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2051     if( psk_len > MBEDTLS_PSK_MAX_LEN )
2052         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2053 
2054     if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
2055         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2056     conf->psk_len = psk_len;
2057     memcpy( conf->psk, psk, conf->psk_len );
2058 
2059     /* Check and set PSK Identity */
2060     ret = ssl_conf_set_psk_identity( conf, psk_identity, psk_identity_len );
2061     if( ret != 0 )
2062         ssl_conf_remove_psk( conf );
2063 
2064     return( ret );
2065 }
2066 
ssl_remove_psk(mbedtls_ssl_context * ssl)2067 static void ssl_remove_psk( mbedtls_ssl_context *ssl )
2068 {
2069 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2070     if( ! mbedtls_svc_key_id_is_null( ssl->handshake->psk_opaque ) )
2071     {
2072         /* The maintenance of the external PSK key slot is the
2073          * user's responsibility. */
2074         if( ssl->handshake->psk_opaque_is_internal )
2075         {
2076             psa_destroy_key( ssl->handshake->psk_opaque );
2077             ssl->handshake->psk_opaque_is_internal = 0;
2078         }
2079         ssl->handshake->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT;
2080     }
2081 #else
2082     if( ssl->handshake->psk != NULL )
2083     {
2084         mbedtls_platform_zeroize( ssl->handshake->psk,
2085                                   ssl->handshake->psk_len );
2086         mbedtls_free( ssl->handshake->psk );
2087         ssl->handshake->psk_len = 0;
2088     }
2089 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2090 }
2091 
mbedtls_ssl_set_hs_psk(mbedtls_ssl_context * ssl,const unsigned char * psk,size_t psk_len)2092 int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
2093                             const unsigned char *psk, size_t psk_len )
2094 {
2095 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2096     psa_key_attributes_t key_attributes = psa_key_attributes_init();
2097     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2098     psa_algorithm_t alg = PSA_ALG_NONE;
2099     mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2100 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2101 
2102     if( psk == NULL || ssl->handshake == NULL )
2103         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2104 
2105     if( psk_len > MBEDTLS_PSK_MAX_LEN )
2106         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2107 
2108     ssl_remove_psk( ssl );
2109 
2110 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2111 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2112     if( ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2 )
2113     {
2114         if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
2115             alg = PSA_ALG_TLS12_PSK_TO_MS( PSA_ALG_SHA_384 );
2116         else
2117             alg = PSA_ALG_TLS12_PSK_TO_MS( PSA_ALG_SHA_256 );
2118         psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
2119     }
2120 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2121 
2122 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2123     if( ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3 )
2124     {
2125         alg = PSA_ALG_HKDF_EXTRACT( PSA_ALG_ANY_HASH );
2126         psa_set_key_usage_flags( &key_attributes,
2127                                  PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
2128     }
2129 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2130 
2131     psa_set_key_algorithm( &key_attributes, alg );
2132     psa_set_key_type( &key_attributes, PSA_KEY_TYPE_DERIVE );
2133 
2134     status = psa_import_key( &key_attributes, psk, psk_len, &key );
2135     if( status != PSA_SUCCESS )
2136         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2137 
2138     /* Allow calling psa_destroy_key() on psk remove */
2139     ssl->handshake->psk_opaque_is_internal = 1;
2140     return mbedtls_ssl_set_hs_psk_opaque( ssl, key );
2141 #else
2142     if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
2143         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2144 
2145     ssl->handshake->psk_len = psk_len;
2146     memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
2147 
2148     return( 0 );
2149 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2150 }
2151 
2152 #if defined(MBEDTLS_USE_PSA_CRYPTO)
mbedtls_ssl_conf_psk_opaque(mbedtls_ssl_config * conf,mbedtls_svc_key_id_t psk,const unsigned char * psk_identity,size_t psk_identity_len)2153 int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf,
2154                                  mbedtls_svc_key_id_t psk,
2155                                  const unsigned char *psk_identity,
2156                                  size_t psk_identity_len )
2157 {
2158     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2159 
2160     /* We currently only support one PSK, raw or opaque. */
2161     if( mbedtls_ssl_conf_has_static_psk( conf ) )
2162         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2163 
2164     /* Check and set opaque PSK */
2165     if( mbedtls_svc_key_id_is_null( psk ) )
2166         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2167     conf->psk_opaque = psk;
2168 
2169     /* Check and set PSK Identity */
2170     ret = ssl_conf_set_psk_identity( conf, psk_identity,
2171                                      psk_identity_len );
2172     if( ret != 0 )
2173         ssl_conf_remove_psk( conf );
2174 
2175     return( ret );
2176 }
2177 
mbedtls_ssl_set_hs_psk_opaque(mbedtls_ssl_context * ssl,mbedtls_svc_key_id_t psk)2178 int mbedtls_ssl_set_hs_psk_opaque( mbedtls_ssl_context *ssl,
2179                                    mbedtls_svc_key_id_t psk )
2180 {
2181     if( ( mbedtls_svc_key_id_is_null( psk ) ) ||
2182         ( ssl->handshake == NULL ) )
2183         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2184 
2185     ssl_remove_psk( ssl );
2186     ssl->handshake->psk_opaque = psk;
2187     return( 0 );
2188 }
2189 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2190 
2191 #if defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_conf_psk_cb(mbedtls_ssl_config * conf,int (* f_psk)(void *,mbedtls_ssl_context *,const unsigned char *,size_t),void * p_psk)2192 void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
2193                      int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
2194                      size_t),
2195                      void *p_psk )
2196 {
2197     conf->f_psk = f_psk;
2198     conf->p_psk = p_psk;
2199 }
2200 #endif /* MBEDTLS_SSL_SRV_C */
2201 
2202 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
2203 
2204 #if defined(MBEDTLS_USE_PSA_CRYPTO)
mbedtls_ssl_get_base_mode(psa_algorithm_t alg)2205 static mbedtls_ssl_mode_t mbedtls_ssl_get_base_mode(
2206         psa_algorithm_t alg )
2207 {
2208 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
2209     if( alg == PSA_ALG_CBC_NO_PADDING )
2210         return( MBEDTLS_SSL_MODE_CBC );
2211 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
2212     if( PSA_ALG_IS_AEAD( alg ) )
2213         return( MBEDTLS_SSL_MODE_AEAD );
2214     return( MBEDTLS_SSL_MODE_STREAM );
2215 }
2216 
2217 #else /* MBEDTLS_USE_PSA_CRYPTO */
2218 
mbedtls_ssl_get_base_mode(mbedtls_cipher_mode_t mode)2219 static mbedtls_ssl_mode_t mbedtls_ssl_get_base_mode(
2220         mbedtls_cipher_mode_t mode )
2221 {
2222 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
2223     if( mode == MBEDTLS_MODE_CBC )
2224         return( MBEDTLS_SSL_MODE_CBC );
2225 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
2226 
2227 #if defined(MBEDTLS_GCM_C) || \
2228     defined(MBEDTLS_CCM_C) || \
2229     defined(MBEDTLS_CHACHAPOLY_C)
2230     if( mode == MBEDTLS_MODE_GCM ||
2231         mode == MBEDTLS_MODE_CCM ||
2232         mode == MBEDTLS_MODE_CHACHAPOLY )
2233         return( MBEDTLS_SSL_MODE_AEAD );
2234 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
2235 
2236     return( MBEDTLS_SSL_MODE_STREAM );
2237 }
2238 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2239 
mbedtls_ssl_get_actual_mode(mbedtls_ssl_mode_t base_mode,int encrypt_then_mac)2240 static mbedtls_ssl_mode_t mbedtls_ssl_get_actual_mode(
2241     mbedtls_ssl_mode_t base_mode,
2242     int encrypt_then_mac )
2243 {
2244 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
2245     if( encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED &&
2246         base_mode == MBEDTLS_SSL_MODE_CBC )
2247     {
2248         return( MBEDTLS_SSL_MODE_CBC_ETM );
2249     }
2250 #else
2251     (void) encrypt_then_mac;
2252 #endif
2253     return( base_mode );
2254 }
2255 
mbedtls_ssl_get_mode_from_transform(const mbedtls_ssl_transform * transform)2256 mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_transform(
2257                     const mbedtls_ssl_transform *transform )
2258 {
2259     mbedtls_ssl_mode_t base_mode = mbedtls_ssl_get_base_mode(
2260 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2261             transform->psa_alg
2262 #else
2263             mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc )
2264 #endif
2265         );
2266 
2267     int encrypt_then_mac = 0;
2268 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
2269     encrypt_then_mac = transform->encrypt_then_mac;
2270 #endif
2271     return( mbedtls_ssl_get_actual_mode( base_mode, encrypt_then_mac ) );
2272 }
2273 
mbedtls_ssl_get_mode_from_ciphersuite(int encrypt_then_mac,const mbedtls_ssl_ciphersuite_t * suite)2274 mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_ciphersuite(
2275 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
2276         int encrypt_then_mac,
2277 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
2278         const mbedtls_ssl_ciphersuite_t *suite )
2279 {
2280     mbedtls_ssl_mode_t base_mode = MBEDTLS_SSL_MODE_STREAM;
2281 
2282 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2283     psa_status_t status;
2284     psa_algorithm_t alg;
2285     psa_key_type_t type;
2286     size_t size;
2287     status = mbedtls_ssl_cipher_to_psa( suite->cipher, 0, &alg, &type, &size );
2288     if( status == PSA_SUCCESS )
2289         base_mode = mbedtls_ssl_get_base_mode( alg );
2290 #else
2291     const mbedtls_cipher_info_t *cipher =
2292             mbedtls_cipher_info_from_type( suite->cipher );
2293     if( cipher != NULL )
2294     {
2295         base_mode =
2296             mbedtls_ssl_get_base_mode(
2297                 mbedtls_cipher_info_get_mode( cipher ) );
2298     }
2299 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2300 
2301 #if !defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
2302     int encrypt_then_mac = 0;
2303 #endif
2304     return( mbedtls_ssl_get_actual_mode( base_mode, encrypt_then_mac ) );
2305 }
2306 
2307 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
2308 
2309 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2310 /* Serialization of TLS 1.3 sessions:
2311  *
2312  *     struct {
2313  *       opaque hostname<0..2^16-1>;
2314  *       uint64 ticket_received;
2315  *       uint32 ticket_lifetime;
2316  *       opaque ticket<1..2^16-1>;
2317  *     } ClientOnlyData;
2318  *
2319  *     struct {
2320  *       uint8 endpoint;
2321  *       uint8 ciphersuite[2];
2322  *       uint32 ticket_age_add;
2323  *       uint8 ticket_flags;
2324  *       opaque resumption_key<0..255>;
2325  *       select ( endpoint ) {
2326  *            case client: ClientOnlyData;
2327  *            case server: uint64 start_time;
2328  *        };
2329  *     } serialized_session_tls13;
2330  *
2331  */
2332 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2333 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_session_save(const mbedtls_ssl_session * session,unsigned char * buf,size_t buf_len,size_t * olen)2334 static int ssl_tls13_session_save( const mbedtls_ssl_session *session,
2335                                    unsigned char *buf,
2336                                    size_t buf_len,
2337                                    size_t *olen )
2338 {
2339     unsigned char *p = buf;
2340 #if defined(MBEDTLS_SSL_CLI_C) && \
2341     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2342     size_t hostname_len = ( session->hostname == NULL ) ?
2343                             0 : strlen( session->hostname ) + 1;
2344 #endif
2345     size_t needed =   1                             /* endpoint */
2346                     + 2                             /* ciphersuite */
2347                     + 4                             /* ticket_age_add */
2348                     + 1                             /* ticket_flags */
2349                     + 1;                            /* resumption_key length */
2350     *olen = 0;
2351 
2352     if( session->resumption_key_len > MBEDTLS_SSL_TLS1_3_TICKET_RESUMPTION_KEY_LEN )
2353         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2354     needed += session->resumption_key_len;  /* resumption_key */
2355 
2356 #if defined(MBEDTLS_HAVE_TIME)
2357     needed += 8; /* start_time or ticket_received */
2358 #endif
2359 
2360 #if defined(MBEDTLS_SSL_CLI_C)
2361     if( session->endpoint == MBEDTLS_SSL_IS_CLIENT )
2362     {
2363 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2364         needed +=  2                        /* hostname_len */
2365                + hostname_len;              /* hostname */
2366 #endif
2367 
2368         needed +=   4                       /* ticket_lifetime */
2369                   + 2;                      /* ticket_len */
2370 
2371         /* Check size_t overflow */
2372         if( session->ticket_len > SIZE_MAX - needed )
2373             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2374 
2375         needed += session->ticket_len;      /* ticket */
2376     }
2377 #endif /* MBEDTLS_SSL_CLI_C */
2378 
2379     *olen = needed;
2380     if( needed > buf_len )
2381         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
2382 
2383     p[0] = session->endpoint;
2384     MBEDTLS_PUT_UINT16_BE( session->ciphersuite, p, 1 );
2385     MBEDTLS_PUT_UINT32_BE( session->ticket_age_add, p, 3 );
2386     p[7] = session->ticket_flags;
2387 
2388     /* save resumption_key */
2389     p[8] = session->resumption_key_len;
2390     p += 9;
2391     memcpy( p, session->resumption_key, session->resumption_key_len );
2392     p += session->resumption_key_len;
2393 
2394 #if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
2395     if( session->endpoint == MBEDTLS_SSL_IS_SERVER )
2396     {
2397         MBEDTLS_PUT_UINT64_BE( (uint64_t) session->start, p, 0 );
2398         p += 8;
2399     }
2400 #endif /* MBEDTLS_HAVE_TIME */
2401 
2402 #if defined(MBEDTLS_SSL_CLI_C)
2403     if( session->endpoint == MBEDTLS_SSL_IS_CLIENT )
2404     {
2405 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2406         MBEDTLS_PUT_UINT16_BE( hostname_len, p, 0 );
2407         p += 2;
2408         if( hostname_len > 0 )
2409         {
2410             /* save host name */
2411             memcpy( p, session->hostname, hostname_len );
2412             p += hostname_len;
2413         }
2414 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
2415 
2416 #if defined(MBEDTLS_HAVE_TIME)
2417         MBEDTLS_PUT_UINT64_BE( (uint64_t) session->ticket_received, p, 0 );
2418         p += 8;
2419 #endif
2420         MBEDTLS_PUT_UINT32_BE( session->ticket_lifetime, p, 0 );
2421         p += 4;
2422 
2423         MBEDTLS_PUT_UINT16_BE( session->ticket_len, p, 0 );
2424         p += 2;
2425 
2426         if( session->ticket != NULL && session->ticket_len > 0 )
2427         {
2428             memcpy( p, session->ticket, session->ticket_len );
2429             p += session->ticket_len;
2430         }
2431     }
2432 #endif /* MBEDTLS_SSL_CLI_C */
2433     return( 0 );
2434 }
2435 
2436 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_session_load(mbedtls_ssl_session * session,const unsigned char * buf,size_t len)2437 static int ssl_tls13_session_load( mbedtls_ssl_session *session,
2438                                    const unsigned char *buf,
2439                                    size_t len )
2440 {
2441     const unsigned char *p = buf;
2442     const unsigned char *end = buf + len;
2443 
2444     if( end - p < 9 )
2445         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2446     session->endpoint = p[0];
2447     session->ciphersuite = MBEDTLS_GET_UINT16_BE( p, 1 );
2448     session->ticket_age_add = MBEDTLS_GET_UINT32_BE( p, 3 );
2449     session->ticket_flags = p[7];
2450 
2451     /* load resumption_key */
2452     session->resumption_key_len = p[8];
2453     p += 9;
2454 
2455     if( end - p < session->resumption_key_len )
2456         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2457 
2458     if( sizeof( session->resumption_key ) < session->resumption_key_len )
2459         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2460     memcpy( session->resumption_key, p, session->resumption_key_len );
2461     p += session->resumption_key_len;
2462 
2463 #if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
2464     if( session->endpoint == MBEDTLS_SSL_IS_SERVER )
2465     {
2466         if( end - p < 8 )
2467             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2468         session->start = MBEDTLS_GET_UINT64_BE( p, 0 );
2469         p += 8;
2470     }
2471 #endif /* MBEDTLS_HAVE_TIME */
2472 
2473 #if defined(MBEDTLS_SSL_CLI_C)
2474     if( session->endpoint == MBEDTLS_SSL_IS_CLIENT )
2475     {
2476 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \
2477     defined(MBEDTLS_SSL_SESSION_TICKETS)
2478         size_t hostname_len;
2479         /* load host name */
2480         if( end - p < 2 )
2481             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2482         hostname_len = MBEDTLS_GET_UINT16_BE( p, 0 );
2483         p += 2;
2484 
2485         if( end - p < ( long int )hostname_len )
2486             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2487         if( hostname_len > 0 )
2488         {
2489             session->hostname = mbedtls_calloc( 1, hostname_len );
2490             if( session->hostname == NULL )
2491                 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2492             memcpy( session->hostname, p, hostname_len );
2493             p += hostname_len;
2494         }
2495 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION &&
2496           MBEDTLS_SSL_SESSION_TICKETS */
2497 
2498 #if defined(MBEDTLS_HAVE_TIME)
2499         if( end - p < 8 )
2500             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2501         session->ticket_received = MBEDTLS_GET_UINT64_BE( p, 0 );
2502         p += 8;
2503 #endif
2504         if( end - p < 4 )
2505             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2506         session->ticket_lifetime = MBEDTLS_GET_UINT32_BE( p, 0 );
2507         p += 4;
2508 
2509         if( end - p <  2 )
2510             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2511         session->ticket_len = MBEDTLS_GET_UINT16_BE( p, 0 );
2512         p += 2;
2513 
2514         if( end - p < ( long int )session->ticket_len )
2515             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2516         if( session->ticket_len > 0 )
2517         {
2518             session->ticket = mbedtls_calloc( 1, session->ticket_len );
2519             if( session->ticket == NULL )
2520                 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2521             memcpy( session->ticket, p, session->ticket_len );
2522             p += session->ticket_len;
2523         }
2524     }
2525 #endif /* MBEDTLS_SSL_CLI_C */
2526 
2527     return( 0 );
2528 
2529 }
2530 #else /* MBEDTLS_SSL_SESSION_TICKETS */
2531 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_session_save(const mbedtls_ssl_session * session,unsigned char * buf,size_t buf_len,size_t * olen)2532 static int ssl_tls13_session_save( const mbedtls_ssl_session *session,
2533                                    unsigned char *buf,
2534                                    size_t buf_len,
2535                                    size_t *olen )
2536 {
2537     ((void) session);
2538     ((void) buf);
2539     ((void) buf_len);
2540     *olen = 0;
2541     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2542 }
2543 
ssl_tls13_session_load(const mbedtls_ssl_session * session,unsigned char * buf,size_t buf_len)2544 static int ssl_tls13_session_load( const mbedtls_ssl_session *session,
2545                                    unsigned char *buf,
2546                                    size_t buf_len )
2547 {
2548     ((void) session);
2549     ((void) buf);
2550     ((void) buf_len);
2551     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2552 }
2553 #endif /* !MBEDTLS_SSL_SESSION_TICKETS */
2554 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2555 
mbedtls_ssl_cipher_to_psa(mbedtls_cipher_type_t mbedtls_cipher_type,size_t taglen,psa_algorithm_t * alg,psa_key_type_t * key_type,size_t * key_size)2556 psa_status_t mbedtls_ssl_cipher_to_psa( mbedtls_cipher_type_t mbedtls_cipher_type,
2557                                     size_t taglen,
2558                                     psa_algorithm_t *alg,
2559                                     psa_key_type_t *key_type,
2560                                     size_t *key_size )
2561 {
2562     switch ( mbedtls_cipher_type )
2563     {
2564         case MBEDTLS_CIPHER_AES_128_CBC:
2565             *alg = PSA_ALG_CBC_NO_PADDING;
2566             *key_type = PSA_KEY_TYPE_AES;
2567             *key_size = 128;
2568             break;
2569         case MBEDTLS_CIPHER_AES_128_CCM:
2570             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2571             *key_type = PSA_KEY_TYPE_AES;
2572             *key_size = 128;
2573             break;
2574         case MBEDTLS_CIPHER_AES_128_GCM:
2575             *alg = PSA_ALG_GCM;
2576             *key_type = PSA_KEY_TYPE_AES;
2577             *key_size = 128;
2578             break;
2579         case MBEDTLS_CIPHER_AES_192_CCM:
2580             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2581             *key_type = PSA_KEY_TYPE_AES;
2582             *key_size = 192;
2583             break;
2584         case MBEDTLS_CIPHER_AES_192_GCM:
2585             *alg = PSA_ALG_GCM;
2586             *key_type = PSA_KEY_TYPE_AES;
2587             *key_size = 192;
2588             break;
2589         case MBEDTLS_CIPHER_AES_256_CBC:
2590             *alg = PSA_ALG_CBC_NO_PADDING;
2591             *key_type = PSA_KEY_TYPE_AES;
2592             *key_size = 256;
2593             break;
2594         case MBEDTLS_CIPHER_AES_256_CCM:
2595             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2596             *key_type = PSA_KEY_TYPE_AES;
2597             *key_size = 256;
2598             break;
2599         case MBEDTLS_CIPHER_AES_256_GCM:
2600             *alg = PSA_ALG_GCM;
2601             *key_type = PSA_KEY_TYPE_AES;
2602             *key_size = 256;
2603             break;
2604         case MBEDTLS_CIPHER_ARIA_128_CBC:
2605             *alg = PSA_ALG_CBC_NO_PADDING;
2606             *key_type = PSA_KEY_TYPE_ARIA;
2607             *key_size = 128;
2608             break;
2609         case MBEDTLS_CIPHER_ARIA_128_CCM:
2610             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2611             *key_type = PSA_KEY_TYPE_ARIA;
2612             *key_size = 128;
2613             break;
2614         case MBEDTLS_CIPHER_ARIA_128_GCM:
2615             *alg = PSA_ALG_GCM;
2616             *key_type = PSA_KEY_TYPE_ARIA;
2617             *key_size = 128;
2618             break;
2619         case MBEDTLS_CIPHER_ARIA_192_CCM:
2620             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2621             *key_type = PSA_KEY_TYPE_ARIA;
2622             *key_size = 192;
2623             break;
2624         case MBEDTLS_CIPHER_ARIA_192_GCM:
2625             *alg = PSA_ALG_GCM;
2626             *key_type = PSA_KEY_TYPE_ARIA;
2627             *key_size = 192;
2628             break;
2629         case MBEDTLS_CIPHER_ARIA_256_CBC:
2630             *alg = PSA_ALG_CBC_NO_PADDING;
2631             *key_type = PSA_KEY_TYPE_ARIA;
2632             *key_size = 256;
2633             break;
2634         case MBEDTLS_CIPHER_ARIA_256_CCM:
2635             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2636             *key_type = PSA_KEY_TYPE_ARIA;
2637             *key_size = 256;
2638             break;
2639         case MBEDTLS_CIPHER_ARIA_256_GCM:
2640             *alg = PSA_ALG_GCM;
2641             *key_type = PSA_KEY_TYPE_ARIA;
2642             *key_size = 256;
2643             break;
2644         case MBEDTLS_CIPHER_CAMELLIA_128_CBC:
2645             *alg = PSA_ALG_CBC_NO_PADDING;
2646             *key_type = PSA_KEY_TYPE_CAMELLIA;
2647             *key_size = 128;
2648             break;
2649         case MBEDTLS_CIPHER_CAMELLIA_128_CCM:
2650             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2651             *key_type = PSA_KEY_TYPE_CAMELLIA;
2652             *key_size = 128;
2653             break;
2654         case MBEDTLS_CIPHER_CAMELLIA_128_GCM:
2655             *alg = PSA_ALG_GCM;
2656             *key_type = PSA_KEY_TYPE_CAMELLIA;
2657             *key_size = 128;
2658             break;
2659         case MBEDTLS_CIPHER_CAMELLIA_192_CCM:
2660             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2661             *key_type = PSA_KEY_TYPE_CAMELLIA;
2662             *key_size = 192;
2663             break;
2664         case MBEDTLS_CIPHER_CAMELLIA_192_GCM:
2665             *alg = PSA_ALG_GCM;
2666             *key_type = PSA_KEY_TYPE_CAMELLIA;
2667             *key_size = 192;
2668             break;
2669         case MBEDTLS_CIPHER_CAMELLIA_256_CBC:
2670             *alg = PSA_ALG_CBC_NO_PADDING;
2671             *key_type = PSA_KEY_TYPE_CAMELLIA;
2672             *key_size = 256;
2673             break;
2674         case MBEDTLS_CIPHER_CAMELLIA_256_CCM:
2675             *alg = taglen ? PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) : PSA_ALG_CCM;
2676             *key_type = PSA_KEY_TYPE_CAMELLIA;
2677             *key_size = 256;
2678             break;
2679         case MBEDTLS_CIPHER_CAMELLIA_256_GCM:
2680             *alg = PSA_ALG_GCM;
2681             *key_type = PSA_KEY_TYPE_CAMELLIA;
2682             *key_size = 256;
2683             break;
2684         case MBEDTLS_CIPHER_CHACHA20_POLY1305:
2685             *alg = PSA_ALG_CHACHA20_POLY1305;
2686             *key_type = PSA_KEY_TYPE_CHACHA20;
2687             *key_size = 256;
2688             break;
2689         case MBEDTLS_CIPHER_NULL:
2690             *alg = MBEDTLS_SSL_NULL_CIPHER;
2691             *key_type = 0;
2692             *key_size = 0;
2693             break;
2694         default:
2695             return PSA_ERROR_NOT_SUPPORTED;
2696     }
2697 
2698     return PSA_SUCCESS;
2699 }
2700 #endif /* MBEDTLS_USE_PSA_CRYPTO || MBEDTLS_SSL_PROTO_TLS1_3 */
2701 
2702 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_conf_dh_param_bin(mbedtls_ssl_config * conf,const unsigned char * dhm_P,size_t P_len,const unsigned char * dhm_G,size_t G_len)2703 int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
2704                                    const unsigned char *dhm_P, size_t P_len,
2705                                    const unsigned char *dhm_G, size_t G_len )
2706 {
2707     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2708 
2709     mbedtls_mpi_free( &conf->dhm_P );
2710     mbedtls_mpi_free( &conf->dhm_G );
2711 
2712     if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 ||
2713         ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 )
2714     {
2715         mbedtls_mpi_free( &conf->dhm_P );
2716         mbedtls_mpi_free( &conf->dhm_G );
2717         return( ret );
2718     }
2719 
2720     return( 0 );
2721 }
2722 
mbedtls_ssl_conf_dh_param_ctx(mbedtls_ssl_config * conf,mbedtls_dhm_context * dhm_ctx)2723 int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
2724 {
2725     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2726 
2727     mbedtls_mpi_free( &conf->dhm_P );
2728     mbedtls_mpi_free( &conf->dhm_G );
2729 
2730     if( ( ret = mbedtls_dhm_get_value( dhm_ctx, MBEDTLS_DHM_PARAM_P,
2731                                        &conf->dhm_P ) ) != 0 ||
2732         ( ret = mbedtls_dhm_get_value( dhm_ctx, MBEDTLS_DHM_PARAM_G,
2733                                        &conf->dhm_G ) ) != 0 )
2734     {
2735         mbedtls_mpi_free( &conf->dhm_P );
2736         mbedtls_mpi_free( &conf->dhm_G );
2737         return( ret );
2738     }
2739 
2740     return( 0 );
2741 }
2742 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
2743 
2744 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
2745 /*
2746  * Set the minimum length for Diffie-Hellman parameters
2747  */
mbedtls_ssl_conf_dhm_min_bitlen(mbedtls_ssl_config * conf,unsigned int bitlen)2748 void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
2749                                       unsigned int bitlen )
2750 {
2751     conf->dhm_min_bitlen = bitlen;
2752 }
2753 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
2754 
2755 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2756 #if !defined(MBEDTLS_DEPRECATED_REMOVED) && defined(MBEDTLS_SSL_PROTO_TLS1_2)
2757 /*
2758  * Set allowed/preferred hashes for handshake signatures
2759  */
mbedtls_ssl_conf_sig_hashes(mbedtls_ssl_config * conf,const int * hashes)2760 void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
2761                                   const int *hashes )
2762 {
2763     conf->sig_hashes = hashes;
2764 }
2765 #endif /* !MBEDTLS_DEPRECATED_REMOVED && MBEDTLS_SSL_PROTO_TLS1_2 */
2766 
2767 /* Configure allowed signature algorithms for handshake */
mbedtls_ssl_conf_sig_algs(mbedtls_ssl_config * conf,const uint16_t * sig_algs)2768 void mbedtls_ssl_conf_sig_algs( mbedtls_ssl_config *conf,
2769                                 const uint16_t* sig_algs )
2770 {
2771 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
2772     conf->sig_hashes = NULL;
2773 #endif /* !MBEDTLS_DEPRECATED_REMOVED */
2774     conf->sig_algs = sig_algs;
2775 }
2776 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2777 
2778 #if defined(MBEDTLS_ECP_C)
2779 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
2780 /*
2781  * Set the allowed elliptic curves
2782  *
2783  * mbedtls_ssl_setup() takes the provided list
2784  * and translates it to a list of IANA TLS group identifiers,
2785  * stored in ssl->handshake->group_list.
2786  *
2787  */
mbedtls_ssl_conf_curves(mbedtls_ssl_config * conf,const mbedtls_ecp_group_id * curve_list)2788 void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
2789                              const mbedtls_ecp_group_id *curve_list )
2790 {
2791     conf->curve_list = curve_list;
2792     conf->group_list = NULL;
2793 }
2794 #endif /* MBEDTLS_DEPRECATED_REMOVED */
2795 #endif /* MBEDTLS_ECP_C */
2796 
2797 /*
2798  * Set the allowed groups
2799  */
mbedtls_ssl_conf_groups(mbedtls_ssl_config * conf,const uint16_t * group_list)2800 void mbedtls_ssl_conf_groups( mbedtls_ssl_config *conf,
2801                               const uint16_t *group_list )
2802 {
2803 #if defined(MBEDTLS_ECP_C) && !defined(MBEDTLS_DEPRECATED_REMOVED)
2804     conf->curve_list = NULL;
2805 #endif
2806     conf->group_list = group_list;
2807 }
2808 
2809 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_set_hostname(mbedtls_ssl_context * ssl,const char * hostname)2810 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
2811 {
2812     /* Initialize to suppress unnecessary compiler warning */
2813     size_t hostname_len = 0;
2814 
2815     /* Check if new hostname is valid before
2816      * making any change to current one */
2817     if( hostname != NULL )
2818     {
2819         hostname_len = strlen( hostname );
2820 
2821         if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
2822             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2823     }
2824 
2825     /* Now it's clear that we will overwrite the old hostname,
2826      * so we can free it safely */
2827 
2828     if( ssl->hostname != NULL )
2829     {
2830         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
2831         mbedtls_free( ssl->hostname );
2832     }
2833 
2834     /* Passing NULL as hostname shall clear the old one */
2835 
2836     if( hostname == NULL )
2837     {
2838         ssl->hostname = NULL;
2839     }
2840     else
2841     {
2842         ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
2843         if( ssl->hostname == NULL )
2844             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2845 
2846         memcpy( ssl->hostname, hostname, hostname_len );
2847 
2848         ssl->hostname[hostname_len] = '\0';
2849     }
2850 
2851     return( 0 );
2852 }
2853 #endif /* MBEDTLS_X509_CRT_PARSE_C */
2854 
2855 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
mbedtls_ssl_conf_sni(mbedtls_ssl_config * conf,int (* f_sni)(void *,mbedtls_ssl_context *,const unsigned char *,size_t),void * p_sni)2856 void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
2857                   int (*f_sni)(void *, mbedtls_ssl_context *,
2858                                 const unsigned char *, size_t),
2859                   void *p_sni )
2860 {
2861     conf->f_sni = f_sni;
2862     conf->p_sni = p_sni;
2863 }
2864 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
2865 
2866 #if defined(MBEDTLS_SSL_ALPN)
mbedtls_ssl_conf_alpn_protocols(mbedtls_ssl_config * conf,const char ** protos)2867 int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
2868 {
2869     size_t cur_len, tot_len;
2870     const char **p;
2871 
2872     /*
2873      * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
2874      * MUST NOT be truncated."
2875      * We check lengths now rather than later.
2876      */
2877     tot_len = 0;
2878     for( p = protos; *p != NULL; p++ )
2879     {
2880         cur_len = strlen( *p );
2881         tot_len += cur_len;
2882 
2883         if( ( cur_len == 0 ) ||
2884             ( cur_len > MBEDTLS_SSL_MAX_ALPN_NAME_LEN ) ||
2885             ( tot_len > MBEDTLS_SSL_MAX_ALPN_LIST_LEN ) )
2886             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2887     }
2888 
2889     conf->alpn_list = protos;
2890 
2891     return( 0 );
2892 }
2893 
mbedtls_ssl_get_alpn_protocol(const mbedtls_ssl_context * ssl)2894 const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
2895 {
2896     return( ssl->alpn_chosen );
2897 }
2898 #endif /* MBEDTLS_SSL_ALPN */
2899 
2900 #if defined(MBEDTLS_SSL_DTLS_SRTP)
mbedtls_ssl_conf_srtp_mki_value_supported(mbedtls_ssl_config * conf,int support_mki_value)2901 void mbedtls_ssl_conf_srtp_mki_value_supported( mbedtls_ssl_config *conf,
2902                                                 int support_mki_value )
2903 {
2904     conf->dtls_srtp_mki_support = support_mki_value;
2905 }
2906 
mbedtls_ssl_dtls_srtp_set_mki_value(mbedtls_ssl_context * ssl,unsigned char * mki_value,uint16_t mki_len)2907 int mbedtls_ssl_dtls_srtp_set_mki_value( mbedtls_ssl_context *ssl,
2908                                          unsigned char *mki_value,
2909                                          uint16_t mki_len )
2910 {
2911     if( mki_len > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH )
2912     {
2913         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2914     }
2915 
2916     if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED )
2917     {
2918         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2919     }
2920 
2921     memcpy( ssl->dtls_srtp_info.mki_value, mki_value, mki_len );
2922     ssl->dtls_srtp_info.mki_len = mki_len;
2923     return( 0 );
2924 }
2925 
mbedtls_ssl_conf_dtls_srtp_protection_profiles(mbedtls_ssl_config * conf,const mbedtls_ssl_srtp_profile * profiles)2926 int mbedtls_ssl_conf_dtls_srtp_protection_profiles( mbedtls_ssl_config *conf,
2927                                                     const mbedtls_ssl_srtp_profile *profiles )
2928 {
2929     const mbedtls_ssl_srtp_profile *p;
2930     size_t list_size = 0;
2931 
2932     /* check the profiles list: all entry must be valid,
2933      * its size cannot be more than the total number of supported profiles, currently 4 */
2934     for( p = profiles; *p != MBEDTLS_TLS_SRTP_UNSET &&
2935                        list_size <= MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH;
2936          p++ )
2937     {
2938         if( mbedtls_ssl_check_srtp_profile_value( *p ) != MBEDTLS_TLS_SRTP_UNSET )
2939         {
2940             list_size++;
2941         }
2942         else
2943         {
2944             /* unsupported value, stop parsing and set the size to an error value */
2945             list_size = MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH + 1;
2946         }
2947     }
2948 
2949     if( list_size > MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH )
2950     {
2951                 conf->dtls_srtp_profile_list = NULL;
2952                 conf->dtls_srtp_profile_list_len = 0;
2953                 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2954     }
2955 
2956     conf->dtls_srtp_profile_list = profiles;
2957     conf->dtls_srtp_profile_list_len = list_size;
2958 
2959     return( 0 );
2960 }
2961 
mbedtls_ssl_get_dtls_srtp_negotiation_result(const mbedtls_ssl_context * ssl,mbedtls_dtls_srtp_info * dtls_srtp_info)2962 void mbedtls_ssl_get_dtls_srtp_negotiation_result( const mbedtls_ssl_context *ssl,
2963                                                    mbedtls_dtls_srtp_info *dtls_srtp_info )
2964 {
2965     dtls_srtp_info->chosen_dtls_srtp_profile = ssl->dtls_srtp_info.chosen_dtls_srtp_profile;
2966     /* do not copy the mki value if there is no chosen profile */
2967     if( dtls_srtp_info->chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET )
2968     {
2969         dtls_srtp_info->mki_len = 0;
2970     }
2971     else
2972     {
2973         dtls_srtp_info->mki_len = ssl->dtls_srtp_info.mki_len;
2974         memcpy( dtls_srtp_info->mki_value, ssl->dtls_srtp_info.mki_value,
2975                 ssl->dtls_srtp_info.mki_len );
2976     }
2977 }
2978 #endif /* MBEDTLS_SSL_DTLS_SRTP */
2979 
2980 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
mbedtls_ssl_conf_max_version(mbedtls_ssl_config * conf,int major,int minor)2981 void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
2982 {
2983     conf->max_tls_version = (major << 8) | minor;
2984 }
2985 
mbedtls_ssl_conf_min_version(mbedtls_ssl_config * conf,int major,int minor)2986 void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
2987 {
2988     conf->min_tls_version = (major << 8) | minor;
2989 }
2990 #endif /* MBEDTLS_DEPRECATED_REMOVED */
2991 
2992 #if defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_conf_cert_req_ca_list(mbedtls_ssl_config * conf,char cert_req_ca_list)2993 void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
2994                                           char cert_req_ca_list )
2995 {
2996     conf->cert_req_ca_list = cert_req_ca_list;
2997 }
2998 #endif
2999 
3000 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
mbedtls_ssl_conf_encrypt_then_mac(mbedtls_ssl_config * conf,char etm)3001 void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
3002 {
3003     conf->encrypt_then_mac = etm;
3004 }
3005 #endif
3006 
3007 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
mbedtls_ssl_conf_extended_master_secret(mbedtls_ssl_config * conf,char ems)3008 void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
3009 {
3010     conf->extended_ms = ems;
3011 }
3012 #endif
3013 
3014 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
mbedtls_ssl_conf_max_frag_len(mbedtls_ssl_config * conf,unsigned char mfl_code)3015 int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
3016 {
3017     if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
3018         ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN )
3019     {
3020         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3021     }
3022 
3023     conf->mfl_code = mfl_code;
3024 
3025     return( 0 );
3026 }
3027 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
3028 
mbedtls_ssl_conf_legacy_renegotiation(mbedtls_ssl_config * conf,int allow_legacy)3029 void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
3030 {
3031     conf->allow_legacy_renegotiation = allow_legacy;
3032 }
3033 
3034 #if defined(MBEDTLS_SSL_RENEGOTIATION)
mbedtls_ssl_conf_renegotiation(mbedtls_ssl_config * conf,int renegotiation)3035 void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
3036 {
3037     conf->disable_renegotiation = renegotiation;
3038 }
3039 
mbedtls_ssl_conf_renegotiation_enforced(mbedtls_ssl_config * conf,int max_records)3040 void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
3041 {
3042     conf->renego_max_records = max_records;
3043 }
3044 
mbedtls_ssl_conf_renegotiation_period(mbedtls_ssl_config * conf,const unsigned char period[8])3045 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
3046                                    const unsigned char period[8] )
3047 {
3048     memcpy( conf->renego_period, period, 8 );
3049 }
3050 #endif /* MBEDTLS_SSL_RENEGOTIATION */
3051 
3052 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3053 #if defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_conf_session_tickets(mbedtls_ssl_config * conf,int use_tickets)3054 void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
3055 {
3056     conf->session_tickets = use_tickets;
3057 }
3058 #endif
3059 
3060 #if defined(MBEDTLS_SSL_SRV_C)
3061 
3062 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS)
mbedtls_ssl_conf_new_session_tickets(mbedtls_ssl_config * conf,uint16_t num_tickets)3063 void mbedtls_ssl_conf_new_session_tickets( mbedtls_ssl_config *conf,
3064                                            uint16_t num_tickets )
3065 {
3066     conf->new_session_tickets_count = num_tickets;
3067 }
3068 #endif
3069 
mbedtls_ssl_conf_session_tickets_cb(mbedtls_ssl_config * conf,mbedtls_ssl_ticket_write_t * f_ticket_write,mbedtls_ssl_ticket_parse_t * f_ticket_parse,void * p_ticket)3070 void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
3071         mbedtls_ssl_ticket_write_t *f_ticket_write,
3072         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
3073         void *p_ticket )
3074 {
3075     conf->f_ticket_write = f_ticket_write;
3076     conf->f_ticket_parse = f_ticket_parse;
3077     conf->p_ticket       = p_ticket;
3078 }
3079 #endif
3080 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3081 
mbedtls_ssl_set_export_keys_cb(mbedtls_ssl_context * ssl,mbedtls_ssl_export_keys_t * f_export_keys,void * p_export_keys)3082 void mbedtls_ssl_set_export_keys_cb( mbedtls_ssl_context *ssl,
3083                                      mbedtls_ssl_export_keys_t *f_export_keys,
3084                                      void *p_export_keys )
3085 {
3086     ssl->f_export_keys = f_export_keys;
3087     ssl->p_export_keys = p_export_keys;
3088 }
3089 
3090 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
mbedtls_ssl_conf_async_private_cb(mbedtls_ssl_config * conf,mbedtls_ssl_async_sign_t * f_async_sign,mbedtls_ssl_async_decrypt_t * f_async_decrypt,mbedtls_ssl_async_resume_t * f_async_resume,mbedtls_ssl_async_cancel_t * f_async_cancel,void * async_config_data)3091 void mbedtls_ssl_conf_async_private_cb(
3092     mbedtls_ssl_config *conf,
3093     mbedtls_ssl_async_sign_t *f_async_sign,
3094     mbedtls_ssl_async_decrypt_t *f_async_decrypt,
3095     mbedtls_ssl_async_resume_t *f_async_resume,
3096     mbedtls_ssl_async_cancel_t *f_async_cancel,
3097     void *async_config_data )
3098 {
3099     conf->f_async_sign_start = f_async_sign;
3100     conf->f_async_decrypt_start = f_async_decrypt;
3101     conf->f_async_resume = f_async_resume;
3102     conf->f_async_cancel = f_async_cancel;
3103     conf->p_async_config_data = async_config_data;
3104 }
3105 
mbedtls_ssl_conf_get_async_config_data(const mbedtls_ssl_config * conf)3106 void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf )
3107 {
3108     return( conf->p_async_config_data );
3109 }
3110 
mbedtls_ssl_get_async_operation_data(const mbedtls_ssl_context * ssl)3111 void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl )
3112 {
3113     if( ssl->handshake == NULL )
3114         return( NULL );
3115     else
3116         return( ssl->handshake->user_async_ctx );
3117 }
3118 
mbedtls_ssl_set_async_operation_data(mbedtls_ssl_context * ssl,void * ctx)3119 void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,
3120                                  void *ctx )
3121 {
3122     if( ssl->handshake != NULL )
3123         ssl->handshake->user_async_ctx = ctx;
3124 }
3125 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3126 
3127 /*
3128  * SSL get accessors
3129  */
mbedtls_ssl_get_verify_result(const mbedtls_ssl_context * ssl)3130 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
3131 {
3132     if( ssl->session != NULL )
3133         return( ssl->session->verify_result );
3134 
3135     if( ssl->session_negotiate != NULL )
3136         return( ssl->session_negotiate->verify_result );
3137 
3138     return( 0xFFFFFFFF );
3139 }
3140 
mbedtls_ssl_get_ciphersuite_id_from_ssl(const mbedtls_ssl_context * ssl)3141 int mbedtls_ssl_get_ciphersuite_id_from_ssl( const mbedtls_ssl_context *ssl )
3142 {
3143     if( ssl == NULL || ssl->session == NULL )
3144         return( 0 );
3145 
3146     return( ssl->session->ciphersuite );
3147 }
3148 
mbedtls_ssl_get_ciphersuite(const mbedtls_ssl_context * ssl)3149 const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
3150 {
3151     if( ssl == NULL || ssl->session == NULL )
3152         return( NULL );
3153 
3154     return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
3155 }
3156 
mbedtls_ssl_get_version(const mbedtls_ssl_context * ssl)3157 const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
3158 {
3159 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3160     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3161     {
3162         switch( ssl->tls_version )
3163         {
3164             case MBEDTLS_SSL_VERSION_TLS1_2:
3165                 return( "DTLSv1.2" );
3166             default:
3167                 return( "unknown (DTLS)" );
3168         }
3169     }
3170 #endif
3171 
3172     switch( ssl->tls_version )
3173     {
3174         case MBEDTLS_SSL_VERSION_TLS1_2:
3175             return( "TLSv1.2" );
3176         case MBEDTLS_SSL_VERSION_TLS1_3:
3177             return( "TLSv1.3" );
3178         default:
3179             return( "unknown" );
3180     }
3181 }
3182 
3183 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
mbedtls_ssl_get_input_max_frag_len(const mbedtls_ssl_context * ssl)3184 size_t mbedtls_ssl_get_input_max_frag_len( const mbedtls_ssl_context *ssl )
3185 {
3186     size_t max_len = MBEDTLS_SSL_IN_CONTENT_LEN;
3187     size_t read_mfl;
3188 
3189     /* Use the configured MFL for the client if we're past SERVER_HELLO_DONE */
3190     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
3191         ssl->state >= MBEDTLS_SSL_SERVER_HELLO_DONE )
3192     {
3193         return ssl_mfl_code_to_length( ssl->conf->mfl_code );
3194     }
3195 
3196     /* Check if a smaller max length was negotiated */
3197     if( ssl->session_out != NULL )
3198     {
3199         read_mfl = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
3200         if( read_mfl < max_len )
3201         {
3202             max_len = read_mfl;
3203         }
3204     }
3205 
3206     // During a handshake, use the value being negotiated
3207     if( ssl->session_negotiate != NULL )
3208     {
3209         read_mfl = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
3210         if( read_mfl < max_len )
3211         {
3212             max_len = read_mfl;
3213         }
3214     }
3215 
3216     return( max_len );
3217 }
3218 
mbedtls_ssl_get_output_max_frag_len(const mbedtls_ssl_context * ssl)3219 size_t mbedtls_ssl_get_output_max_frag_len( const mbedtls_ssl_context *ssl )
3220 {
3221     size_t max_len;
3222 
3223     /*
3224      * Assume mfl_code is correct since it was checked when set
3225      */
3226     max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code );
3227 
3228     /* Check if a smaller max length was negotiated */
3229     if( ssl->session_out != NULL &&
3230         ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len )
3231     {
3232         max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
3233     }
3234 
3235     /* During a handshake, use the value being negotiated */
3236     if( ssl->session_negotiate != NULL &&
3237         ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len )
3238     {
3239         max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
3240     }
3241 
3242     return( max_len );
3243 }
3244 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
3245 
3246 #if defined(MBEDTLS_SSL_PROTO_DTLS)
mbedtls_ssl_get_current_mtu(const mbedtls_ssl_context * ssl)3247 size_t mbedtls_ssl_get_current_mtu( const mbedtls_ssl_context *ssl )
3248 {
3249     /* Return unlimited mtu for client hello messages to avoid fragmentation. */
3250     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
3251         ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO ||
3252           ssl->state == MBEDTLS_SSL_SERVER_HELLO ) )
3253         return ( 0 );
3254 
3255     if( ssl->handshake == NULL || ssl->handshake->mtu == 0 )
3256         return( ssl->mtu );
3257 
3258     if( ssl->mtu == 0 )
3259         return( ssl->handshake->mtu );
3260 
3261     return( ssl->mtu < ssl->handshake->mtu ?
3262             ssl->mtu : ssl->handshake->mtu );
3263 }
3264 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3265 
mbedtls_ssl_get_max_out_record_payload(const mbedtls_ssl_context * ssl)3266 int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl )
3267 {
3268     size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
3269 
3270 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
3271     !defined(MBEDTLS_SSL_PROTO_DTLS)
3272     (void) ssl;
3273 #endif
3274 
3275 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
3276     const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl );
3277 
3278     if( max_len > mfl )
3279         max_len = mfl;
3280 #endif
3281 
3282 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3283     if( mbedtls_ssl_get_current_mtu( ssl ) != 0 )
3284     {
3285         const size_t mtu = mbedtls_ssl_get_current_mtu( ssl );
3286         const int ret = mbedtls_ssl_get_record_expansion( ssl );
3287         const size_t overhead = (size_t) ret;
3288 
3289         if( ret < 0 )
3290             return( ret );
3291 
3292         if( mtu <= overhead )
3293         {
3294             MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) );
3295             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3296         }
3297 
3298         if( max_len > mtu - overhead )
3299             max_len = mtu - overhead;
3300     }
3301 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3302 
3303 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) &&        \
3304     !defined(MBEDTLS_SSL_PROTO_DTLS)
3305     ((void) ssl);
3306 #endif
3307 
3308     return( (int) max_len );
3309 }
3310 
mbedtls_ssl_get_max_in_record_payload(const mbedtls_ssl_context * ssl)3311 int mbedtls_ssl_get_max_in_record_payload( const mbedtls_ssl_context *ssl )
3312 {
3313     size_t max_len = MBEDTLS_SSL_IN_CONTENT_LEN;
3314 
3315 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
3316     (void) ssl;
3317 #endif
3318 
3319 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
3320     const size_t mfl = mbedtls_ssl_get_input_max_frag_len( ssl );
3321 
3322     if( max_len > mfl )
3323         max_len = mfl;
3324 #endif
3325 
3326     return( (int) max_len );
3327 }
3328 
3329 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_get_peer_cert(const mbedtls_ssl_context * ssl)3330 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
3331 {
3332     if( ssl == NULL || ssl->session == NULL )
3333         return( NULL );
3334 
3335 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
3336     return( ssl->session->peer_cert );
3337 #else
3338     return( NULL );
3339 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
3340 }
3341 #endif /* MBEDTLS_X509_CRT_PARSE_C */
3342 
3343 #if defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_get_session(const mbedtls_ssl_context * ssl,mbedtls_ssl_session * dst)3344 int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl,
3345                              mbedtls_ssl_session *dst )
3346 {
3347     int ret;
3348 
3349     if( ssl == NULL ||
3350         dst == NULL ||
3351         ssl->session == NULL ||
3352         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
3353     {
3354         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3355     }
3356 
3357     /* Since Mbed TLS 3.0, mbedtls_ssl_get_session() is no longer
3358      * idempotent: Each session can only be exported once.
3359      *
3360      * (This is in preparation for TLS 1.3 support where we will
3361      * need the ability to export multiple sessions (aka tickets),
3362      * which will be achieved by calling mbedtls_ssl_get_session()
3363      * multiple times until it fails.)
3364      *
3365      * Check whether we have already exported the current session,
3366      * and fail if so.
3367      */
3368     if( ssl->session->exported == 1 )
3369         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3370 
3371     ret = mbedtls_ssl_session_copy( dst, ssl->session );
3372     if( ret != 0 )
3373         return( ret );
3374 
3375     /* Remember that we've exported the session. */
3376     ssl->session->exported = 1;
3377     return( 0 );
3378 }
3379 #endif /* MBEDTLS_SSL_CLI_C */
3380 
3381 /*
3382  * Define ticket header determining Mbed TLS version
3383  * and structure of the ticket.
3384  */
3385 
3386 /*
3387  * Define bitflag determining compile-time settings influencing
3388  * structure of serialized SSL sessions.
3389  */
3390 
3391 #if defined(MBEDTLS_HAVE_TIME)
3392 #define SSL_SERIALIZED_SESSION_CONFIG_TIME 1
3393 #else
3394 #define SSL_SERIALIZED_SESSION_CONFIG_TIME 0
3395 #endif /* MBEDTLS_HAVE_TIME */
3396 
3397 #if defined(MBEDTLS_X509_CRT_PARSE_C)
3398 #define SSL_SERIALIZED_SESSION_CONFIG_CRT 1
3399 #else
3400 #define SSL_SERIALIZED_SESSION_CONFIG_CRT 0
3401 #endif /* MBEDTLS_X509_CRT_PARSE_C */
3402 
3403 #if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SESSION_TICKETS)
3404 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 1
3405 #else
3406 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 0
3407 #endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_SESSION_TICKETS */
3408 
3409 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
3410 #define SSL_SERIALIZED_SESSION_CONFIG_MFL 1
3411 #else
3412 #define SSL_SERIALIZED_SESSION_CONFIG_MFL 0
3413 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
3414 
3415 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
3416 #define SSL_SERIALIZED_SESSION_CONFIG_ETM 1
3417 #else
3418 #define SSL_SERIALIZED_SESSION_CONFIG_ETM 0
3419 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
3420 
3421 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3422 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 1
3423 #else
3424 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 0
3425 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3426 
3427 #define SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT          0
3428 #define SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT           1
3429 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT 2
3430 #define SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT           3
3431 #define SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT           4
3432 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT        5
3433 
3434 #define SSL_SERIALIZED_SESSION_CONFIG_BITFLAG                           \
3435     ( (uint16_t) (                                                      \
3436         ( SSL_SERIALIZED_SESSION_CONFIG_TIME          << SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT          ) | \
3437         ( SSL_SERIALIZED_SESSION_CONFIG_CRT           << SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT           ) | \
3438         ( SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET << SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT ) | \
3439         ( SSL_SERIALIZED_SESSION_CONFIG_MFL           << SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT           ) | \
3440         ( SSL_SERIALIZED_SESSION_CONFIG_ETM           << SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT           ) | \
3441         ( SSL_SERIALIZED_SESSION_CONFIG_TICKET        << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT        ) ) )
3442 
3443 static unsigned char ssl_serialized_session_header[] = {
3444     MBEDTLS_VERSION_MAJOR,
3445     MBEDTLS_VERSION_MINOR,
3446     MBEDTLS_VERSION_PATCH,
3447     MBEDTLS_BYTE_1( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG ),
3448     MBEDTLS_BYTE_0( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG ),
3449 };
3450 
3451 /*
3452  * Serialize a session in the following format:
3453  * (in the presentation language of TLS, RFC 8446 section 3)
3454  *
3455  *  struct {
3456  *
3457  *    opaque mbedtls_version[3];   // library version: major, minor, patch
3458  *    opaque session_format[2];    // library-version specific 16-bit field
3459  *                                 // determining the format of the remaining
3460  *                                 // serialized data.
3461  *
3462  *          Note: When updating the format, remember to keep
3463  *          these version+format bytes.
3464  *
3465  *                                 // In this version, `session_format` determines
3466  *                                 // the setting of those compile-time
3467  *                                 // configuration options which influence
3468  *                                 // the structure of mbedtls_ssl_session.
3469  *
3470  *    uint8_t minor_ver;           // Protocol minor version. Possible values:
3471  *                                 // - TLS 1.2 (3)
3472  *
3473  *    select (serialized_session.tls_version) {
3474  *
3475  *      case MBEDTLS_SSL_VERSION_TLS1_2:
3476  *        serialized_session_tls12 data;
3477  *
3478  *   };
3479  *
3480  * } serialized_session;
3481  *
3482  */
3483 
3484 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_session_save(const mbedtls_ssl_session * session,unsigned char omit_header,unsigned char * buf,size_t buf_len,size_t * olen)3485 static int ssl_session_save( const mbedtls_ssl_session *session,
3486                              unsigned char omit_header,
3487                              unsigned char *buf,
3488                              size_t buf_len,
3489                              size_t *olen )
3490 {
3491     unsigned char *p = buf;
3492     size_t used = 0;
3493     size_t remaining_len;
3494 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
3495     size_t out_len;
3496     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3497 #endif
3498     if( session == NULL )
3499         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3500 
3501     if( !omit_header )
3502     {
3503         /*
3504          * Add Mbed TLS version identifier
3505          */
3506         used += sizeof( ssl_serialized_session_header );
3507 
3508         if( used <= buf_len )
3509         {
3510             memcpy( p, ssl_serialized_session_header,
3511                     sizeof( ssl_serialized_session_header ) );
3512             p += sizeof( ssl_serialized_session_header );
3513         }
3514     }
3515 
3516     /*
3517      * TLS version identifier
3518      */
3519     used += 1;
3520     if( used <= buf_len )
3521     {
3522         *p++ = MBEDTLS_BYTE_0( session->tls_version );
3523     }
3524 
3525     /* Forward to version-specific serialization routine. */
3526     remaining_len = (buf_len >= used) ? buf_len - used : 0;
3527     switch( session->tls_version )
3528     {
3529 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3530     case MBEDTLS_SSL_VERSION_TLS1_2:
3531         used += ssl_tls12_session_save( session, p, remaining_len );
3532         break;
3533 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3534 
3535 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
3536     case MBEDTLS_SSL_VERSION_TLS1_3:
3537         ret = ssl_tls13_session_save( session, p, remaining_len, &out_len );
3538         if( ret != 0 && ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL )
3539             return( ret );
3540         used += out_len;
3541         break;
3542 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
3543 
3544     default:
3545         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3546     }
3547 
3548     *olen = used;
3549     if( used > buf_len )
3550         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3551 
3552     return( 0 );
3553 }
3554 
3555 /*
3556  * Public wrapper for ssl_session_save()
3557  */
mbedtls_ssl_session_save(const mbedtls_ssl_session * session,unsigned char * buf,size_t buf_len,size_t * olen)3558 int mbedtls_ssl_session_save( const mbedtls_ssl_session *session,
3559                               unsigned char *buf,
3560                               size_t buf_len,
3561                               size_t *olen )
3562 {
3563     return( ssl_session_save( session, 0, buf, buf_len, olen ) );
3564 }
3565 
3566 /*
3567  * Deserialize session, see mbedtls_ssl_session_save() for format.
3568  *
3569  * This internal version is wrapped by a public function that cleans up in
3570  * case of error, and has an extra option omit_header.
3571  */
3572 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_session_load(mbedtls_ssl_session * session,unsigned char omit_header,const unsigned char * buf,size_t len)3573 static int ssl_session_load( mbedtls_ssl_session *session,
3574                              unsigned char omit_header,
3575                              const unsigned char *buf,
3576                              size_t len )
3577 {
3578     const unsigned char *p = buf;
3579     const unsigned char * const end = buf + len;
3580     size_t remaining_len;
3581 
3582 
3583     if( session == NULL )
3584         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3585 
3586     if( !omit_header )
3587     {
3588         /*
3589          * Check Mbed TLS version identifier
3590          */
3591 
3592         if( (size_t)( end - p ) < sizeof( ssl_serialized_session_header ) )
3593             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3594 
3595         if( memcmp( p, ssl_serialized_session_header,
3596                     sizeof( ssl_serialized_session_header ) ) != 0 )
3597         {
3598             return( MBEDTLS_ERR_SSL_VERSION_MISMATCH );
3599         }
3600         p += sizeof( ssl_serialized_session_header );
3601     }
3602 
3603     /*
3604      * TLS version identifier
3605      */
3606     if( 1 > (size_t)( end - p ) )
3607         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3608     session->tls_version = 0x0300 | *p++;
3609 
3610     /* Dispatch according to TLS version. */
3611     remaining_len = ( end - p );
3612     switch( session->tls_version )
3613     {
3614 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3615     case MBEDTLS_SSL_VERSION_TLS1_2:
3616         return( ssl_tls12_session_load( session, p, remaining_len ) );
3617 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3618 
3619 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
3620     case MBEDTLS_SSL_VERSION_TLS1_3:
3621         return( ssl_tls13_session_load( session, p, remaining_len ) );
3622 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
3623 
3624     default:
3625         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3626     }
3627 }
3628 
3629 /*
3630  * Deserialize session: public wrapper for error cleaning
3631  */
mbedtls_ssl_session_load(mbedtls_ssl_session * session,const unsigned char * buf,size_t len)3632 int mbedtls_ssl_session_load( mbedtls_ssl_session *session,
3633                               const unsigned char *buf,
3634                               size_t len )
3635 {
3636     int ret = ssl_session_load( session, 0, buf, len );
3637 
3638     if( ret != 0 )
3639         mbedtls_ssl_session_free( session );
3640 
3641     return( ret );
3642 }
3643 
3644 /*
3645  * Perform a single step of the SSL handshake
3646  */
3647 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_prepare_handshake_step(mbedtls_ssl_context * ssl)3648 static int ssl_prepare_handshake_step( mbedtls_ssl_context *ssl )
3649 {
3650     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3651 
3652     /*
3653      * We may have not been able to send to the peer all the handshake data
3654      * that were written into the output buffer by the previous handshake step,
3655      * if the write to the network callback returned with the
3656      * #MBEDTLS_ERR_SSL_WANT_WRITE error code.
3657      * We proceed to the next handshake step only when all data from the
3658      * previous one have been sent to the peer, thus we make sure that this is
3659      * the case here by calling `mbedtls_ssl_flush_output()`. The function may
3660      * return with the #MBEDTLS_ERR_SSL_WANT_WRITE error code in which case
3661      * we have to wait before to go ahead.
3662      * In the case of TLS 1.3, handshake step handlers do not send data to the
3663      * peer. Data are only sent here and through
3664      * `mbedtls_ssl_handle_pending_alert` in case an error that triggered an
3665      * alert occurred.
3666      */
3667     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
3668         return( ret );
3669 
3670 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3671     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3672         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
3673     {
3674         if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
3675             return( ret );
3676     }
3677 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3678 
3679     return( ret );
3680 }
3681 
mbedtls_ssl_handshake_step(mbedtls_ssl_context * ssl)3682 int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
3683 {
3684     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3685 
3686     if( ssl            == NULL                       ||
3687         ssl->conf      == NULL                       ||
3688         ssl->handshake == NULL                       ||
3689         ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER  )
3690     {
3691         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3692     }
3693 
3694     ret = ssl_prepare_handshake_step( ssl );
3695     if( ret != 0 )
3696         return( ret );
3697 
3698     ret = mbedtls_ssl_handle_pending_alert( ssl );
3699     if( ret != 0 )
3700         goto cleanup;
3701 
3702     /* If ssl->conf->endpoint is not one of MBEDTLS_SSL_IS_CLIENT or
3703      * MBEDTLS_SSL_IS_SERVER, this is the return code we give */
3704     ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
3705 
3706 #if defined(MBEDTLS_SSL_CLI_C)
3707     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
3708     {
3709         MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %s",
3710                                     mbedtls_ssl_states_str( ssl->state ) ) );
3711 
3712         switch( ssl->state )
3713         {
3714             case MBEDTLS_SSL_HELLO_REQUEST:
3715                 ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
3716                 ret = 0;
3717                 break;
3718 
3719             case MBEDTLS_SSL_CLIENT_HELLO:
3720                 ret = mbedtls_ssl_write_client_hello( ssl );
3721                 break;
3722 
3723             default:
3724 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
3725                 if( ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3 )
3726                     ret = mbedtls_ssl_tls13_handshake_client_step( ssl );
3727                 else
3728                     ret = mbedtls_ssl_handshake_client_step( ssl );
3729 #elif defined(MBEDTLS_SSL_PROTO_TLS1_2)
3730                 ret = mbedtls_ssl_handshake_client_step( ssl );
3731 #else
3732                 ret = mbedtls_ssl_tls13_handshake_client_step( ssl );
3733 #endif
3734         }
3735     }
3736 #endif
3737 #if defined(MBEDTLS_SSL_SRV_C)
3738     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
3739     {
3740 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
3741         if( mbedtls_ssl_conf_is_tls13_only( ssl->conf ) )
3742             ret = mbedtls_ssl_tls13_handshake_server_step( ssl );
3743 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
3744 
3745 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3746         if( mbedtls_ssl_conf_is_tls12_only( ssl->conf ) )
3747             ret = mbedtls_ssl_handshake_server_step( ssl );
3748 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3749     }
3750 #endif
3751 
3752     if( ret != 0 )
3753     {
3754         /* handshake_step return error. And it is same
3755          * with alert_reason.
3756          */
3757         if( ssl->send_alert )
3758         {
3759             ret = mbedtls_ssl_handle_pending_alert( ssl );
3760             goto cleanup;
3761         }
3762     }
3763 
3764 cleanup:
3765     return( ret );
3766 }
3767 
3768 /*
3769  * Perform the SSL handshake
3770  */
mbedtls_ssl_handshake(mbedtls_ssl_context * ssl)3771 int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
3772 {
3773     int ret = 0;
3774 
3775     /* Sanity checks */
3776 
3777     if( ssl == NULL || ssl->conf == NULL )
3778         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3779 
3780 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3781     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3782         ( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL ) )
3783     {
3784         MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
3785                                      "mbedtls_ssl_set_timer_cb() for DTLS" ) );
3786         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3787     }
3788 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3789 
3790     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
3791 
3792     /* Main handshake loop */
3793     while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
3794     {
3795         ret = mbedtls_ssl_handshake_step( ssl );
3796 
3797         if( ret != 0 )
3798             break;
3799     }
3800 
3801     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
3802 
3803     return( ret );
3804 }
3805 
3806 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3807 #if defined(MBEDTLS_SSL_SRV_C)
3808 /*
3809  * Write HelloRequest to request renegotiation on server
3810  */
3811 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_hello_request(mbedtls_ssl_context * ssl)3812 static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
3813 {
3814     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3815 
3816     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
3817 
3818     ssl->out_msglen  = 4;
3819     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3820     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;
3821 
3822     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
3823     {
3824         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
3825         return( ret );
3826     }
3827 
3828     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
3829 
3830     return( 0 );
3831 }
3832 #endif /* MBEDTLS_SSL_SRV_C */
3833 
3834 /*
3835  * Actually renegotiate current connection, triggered by either:
3836  * - any side: calling mbedtls_ssl_renegotiate(),
3837  * - client: receiving a HelloRequest during mbedtls_ssl_read(),
3838  * - server: receiving any handshake message on server during mbedtls_ssl_read() after
3839  *   the initial handshake is completed.
3840  * If the handshake doesn't complete due to waiting for I/O, it will continue
3841  * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
3842  */
mbedtls_ssl_start_renegotiation(mbedtls_ssl_context * ssl)3843 int mbedtls_ssl_start_renegotiation( mbedtls_ssl_context *ssl )
3844 {
3845     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3846 
3847     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
3848 
3849     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
3850         return( ret );
3851 
3852     /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
3853      * the ServerHello will have message_seq = 1" */
3854 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3855     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3856         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
3857     {
3858         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
3859             ssl->handshake->out_msg_seq = 1;
3860         else
3861             ssl->handshake->in_msg_seq = 1;
3862     }
3863 #endif
3864 
3865     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
3866     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
3867 
3868     if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
3869     {
3870         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
3871         return( ret );
3872     }
3873 
3874     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
3875 
3876     return( 0 );
3877 }
3878 
3879 /*
3880  * Renegotiate current connection on client,
3881  * or request renegotiation on server
3882  */
mbedtls_ssl_renegotiate(mbedtls_ssl_context * ssl)3883 int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
3884 {
3885     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3886 
3887     if( ssl == NULL || ssl->conf == NULL )
3888         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3889 
3890 #if defined(MBEDTLS_SSL_SRV_C)
3891     /* On server, just send the request */
3892     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
3893     {
3894         if( mbedtls_ssl_is_handshake_over( ssl ) == 0 )
3895             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3896 
3897         ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
3898 
3899         /* Did we already try/start sending HelloRequest? */
3900         if( ssl->out_left != 0 )
3901             return( mbedtls_ssl_flush_output( ssl ) );
3902 
3903         return( ssl_write_hello_request( ssl ) );
3904     }
3905 #endif /* MBEDTLS_SSL_SRV_C */
3906 
3907 #if defined(MBEDTLS_SSL_CLI_C)
3908     /*
3909      * On client, either start the renegotiation process or,
3910      * if already in progress, continue the handshake
3911      */
3912     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
3913     {
3914         if( mbedtls_ssl_is_handshake_over( ssl ) == 0 )
3915             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3916 
3917         if( ( ret = mbedtls_ssl_start_renegotiation( ssl ) ) != 0 )
3918         {
3919             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_start_renegotiation", ret );
3920             return( ret );
3921         }
3922     }
3923     else
3924     {
3925         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
3926         {
3927             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
3928             return( ret );
3929         }
3930     }
3931 #endif /* MBEDTLS_SSL_CLI_C */
3932 
3933     return( ret );
3934 }
3935 #endif /* MBEDTLS_SSL_RENEGOTIATION */
3936 
mbedtls_ssl_handshake_free(mbedtls_ssl_context * ssl)3937 void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl )
3938 {
3939     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3940 
3941     if( handshake == NULL )
3942         return;
3943 
3944 #if defined(MBEDTLS_ECP_C)
3945 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
3946     if ( ssl->handshake->group_list_heap_allocated )
3947         mbedtls_free( (void*) handshake->group_list );
3948     handshake->group_list = NULL;
3949 #endif /* MBEDTLS_DEPRECATED_REMOVED */
3950 #endif /* MBEDTLS_ECP_C */
3951 
3952 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
3953 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
3954     if ( ssl->handshake->sig_algs_heap_allocated )
3955         mbedtls_free( (void*) handshake->sig_algs );
3956     handshake->sig_algs = NULL;
3957 #endif /* MBEDTLS_DEPRECATED_REMOVED */
3958 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
3959     if( ssl->handshake->certificate_request_context )
3960     {
3961         mbedtls_free( (void*) handshake->certificate_request_context );
3962     }
3963 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
3964 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
3965 
3966 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3967     if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 )
3968     {
3969         ssl->conf->f_async_cancel( ssl );
3970         handshake->async_in_progress = 0;
3971     }
3972 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3973 
3974 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
3975 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3976     psa_hash_abort( &handshake->fin_sha256_psa );
3977 #else
3978     mbedtls_sha256_free(   &handshake->fin_sha256    );
3979 #endif
3980 #endif
3981 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
3982 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3983     psa_hash_abort( &handshake->fin_sha384_psa );
3984 #else
3985     mbedtls_sha512_free(   &handshake->fin_sha384    );
3986 #endif
3987 #endif
3988 
3989 #if defined(MBEDTLS_DHM_C)
3990     mbedtls_dhm_free( &handshake->dhm_ctx );
3991 #endif
3992 #if !defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_ECDH_C)
3993     mbedtls_ecdh_free( &handshake->ecdh_ctx );
3994 #endif
3995 
3996 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3997 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3998     psa_pake_abort( &handshake->psa_pake_ctx );
3999     psa_destroy_key( handshake->psa_pake_password );
4000     handshake->psa_pake_password = MBEDTLS_SVC_KEY_ID_INIT;
4001 #else
4002     mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
4003 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4004 #if defined(MBEDTLS_SSL_CLI_C)
4005     mbedtls_free( handshake->ecjpake_cache );
4006     handshake->ecjpake_cache = NULL;
4007     handshake->ecjpake_cache_len = 0;
4008 #endif
4009 #endif
4010 
4011 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
4012     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4013     /* explicit void pointer cast for buggy MS compiler */
4014     mbedtls_free( (void *) handshake->curves );
4015 #endif
4016 
4017 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
4018 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4019     if( ! mbedtls_svc_key_id_is_null( ssl->handshake->psk_opaque ) )
4020     {
4021         /* The maintenance of the external PSK key slot is the
4022          * user's responsibility. */
4023         if( ssl->handshake->psk_opaque_is_internal )
4024         {
4025             psa_destroy_key( ssl->handshake->psk_opaque );
4026             ssl->handshake->psk_opaque_is_internal = 0;
4027         }
4028         ssl->handshake->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT;
4029     }
4030 #else
4031     if( handshake->psk != NULL )
4032     {
4033         mbedtls_platform_zeroize( handshake->psk, handshake->psk_len );
4034         mbedtls_free( handshake->psk );
4035     }
4036 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4037 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
4038 
4039 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
4040     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4041     /*
4042      * Free only the linked list wrapper, not the keys themselves
4043      * since the belong to the SNI callback
4044      */
4045     ssl_key_cert_free( handshake->sni_key_cert );
4046 #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
4047 
4048 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
4049     mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx );
4050     if( handshake->ecrs_peer_cert != NULL )
4051     {
4052         mbedtls_x509_crt_free( handshake->ecrs_peer_cert );
4053         mbedtls_free( handshake->ecrs_peer_cert );
4054     }
4055 #endif
4056 
4057 #if defined(MBEDTLS_X509_CRT_PARSE_C) &&        \
4058     !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4059     mbedtls_pk_free( &handshake->peer_pubkey );
4060 #endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4061 
4062 #if defined(MBEDTLS_SSL_CLI_C) && \
4063     ( defined(MBEDTLS_SSL_PROTO_DTLS) || defined(MBEDTLS_SSL_PROTO_TLS1_3) )
4064     mbedtls_free( handshake->cookie );
4065 #endif /* MBEDTLS_SSL_CLI_C &&
4066           ( MBEDTLS_SSL_PROTO_DTLS || MBEDTLS_SSL_PROTO_TLS1_3 ) */
4067 
4068 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4069     mbedtls_ssl_flight_free( handshake->flight );
4070     mbedtls_ssl_buffering_free( ssl );
4071 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4072 
4073 #if defined(MBEDTLS_ECDH_C) && \
4074     ( defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3) )
4075     if( handshake->ecdh_psa_privkey_is_external == 0 )
4076         psa_destroy_key( handshake->ecdh_psa_privkey );
4077 #endif /* MBEDTLS_ECDH_C && MBEDTLS_USE_PSA_CRYPTO */
4078 
4079 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
4080     mbedtls_ssl_transform_free( handshake->transform_handshake );
4081     mbedtls_free( handshake->transform_handshake );
4082 #if defined(MBEDTLS_SSL_EARLY_DATA)
4083     mbedtls_ssl_transform_free( handshake->transform_earlydata );
4084     mbedtls_free( handshake->transform_earlydata );
4085 #endif
4086 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
4087 
4088 
4089 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
4090     /* If the buffers are too big - reallocate. Because of the way Mbed TLS
4091      * processes datagrams and the fact that a datagram is allowed to have
4092      * several records in it, it is possible that the I/O buffers are not
4093      * empty at this stage */
4094     handle_buffer_resizing( ssl, 1, mbedtls_ssl_get_input_buflen( ssl ),
4095                                     mbedtls_ssl_get_output_buflen( ssl ) );
4096 #endif
4097 
4098     /* mbedtls_platform_zeroize MUST be last one in this function */
4099     mbedtls_platform_zeroize( handshake,
4100                               sizeof( mbedtls_ssl_handshake_params ) );
4101 }
4102 
mbedtls_ssl_session_free(mbedtls_ssl_session * session)4103 void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
4104 {
4105     if( session == NULL )
4106         return;
4107 
4108 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4109     ssl_clear_peer_cert( session );
4110 #endif
4111 
4112 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
4113 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
4114     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4115     mbedtls_free( session->hostname );
4116 #endif
4117     mbedtls_free( session->ticket );
4118 #endif
4119 
4120     mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) );
4121 }
4122 
4123 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
4124 
4125 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4126 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 1u
4127 #else
4128 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 0u
4129 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4130 
4131 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 1u
4132 
4133 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4134 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 1u
4135 #else
4136 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 0u
4137 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
4138 
4139 #if defined(MBEDTLS_SSL_ALPN)
4140 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 1u
4141 #else
4142 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 0u
4143 #endif /* MBEDTLS_SSL_ALPN */
4144 
4145 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT    0
4146 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT     1
4147 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT      2
4148 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT                  3
4149 
4150 #define SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG   \
4151     ( (uint32_t) (                              \
4152         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID     << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT     ) | \
4153         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT      << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT      ) | \
4154         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY       << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT       ) | \
4155         ( SSL_SERIALIZED_CONTEXT_CONFIG_ALPN                   << SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT                   ) | \
4156         0u ) )
4157 
4158 static unsigned char ssl_serialized_context_header[] = {
4159     MBEDTLS_VERSION_MAJOR,
4160     MBEDTLS_VERSION_MINOR,
4161     MBEDTLS_VERSION_PATCH,
4162     MBEDTLS_BYTE_1( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG ),
4163     MBEDTLS_BYTE_0( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG ),
4164     MBEDTLS_BYTE_2( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG ),
4165     MBEDTLS_BYTE_1( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG ),
4166     MBEDTLS_BYTE_0( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG ),
4167 };
4168 
4169 /*
4170  * Serialize a full SSL context
4171  *
4172  * The format of the serialized data is:
4173  * (in the presentation language of TLS, RFC 8446 section 3)
4174  *
4175  *  // header
4176  *  opaque mbedtls_version[3];   // major, minor, patch
4177  *  opaque context_format[5];    // version-specific field determining
4178  *                               // the format of the remaining
4179  *                               // serialized data.
4180  *  Note: When updating the format, remember to keep these
4181  *        version+format bytes. (We may make their size part of the API.)
4182  *
4183  *  // session sub-structure
4184  *  opaque session<1..2^32-1>;  // see mbedtls_ssl_session_save()
4185  *  // transform sub-structure
4186  *  uint8 random[64];           // ServerHello.random+ClientHello.random
4187  *  uint8 in_cid<0..2^8-1>      // Connection ID: expected incoming value
4188  *  uint8 out_cid<0..2^8-1>     // Connection ID: outgoing value to use
4189  *  // fields from ssl_context
4190  *  uint32 badmac_seen;         // DTLS: number of records with failing MAC
4191  *  uint64 in_window_top;       // DTLS: last validated record seq_num
4192  *  uint64 in_window;           // DTLS: bitmask for replay protection
4193  *  uint8 disable_datagram_packing; // DTLS: only one record per datagram
4194  *  uint64 cur_out_ctr;         // Record layer: outgoing sequence number
4195  *  uint16 mtu;                 // DTLS: path mtu (max outgoing fragment size)
4196  *  uint8 alpn_chosen<0..2^8-1> // ALPN: negotiated application protocol
4197  *
4198  * Note that many fields of the ssl_context or sub-structures are not
4199  * serialized, as they fall in one of the following categories:
4200  *
4201  *  1. forced value (eg in_left must be 0)
4202  *  2. pointer to dynamically-allocated memory (eg session, transform)
4203  *  3. value can be re-derived from other data (eg session keys from MS)
4204  *  4. value was temporary (eg content of input buffer)
4205  *  5. value will be provided by the user again (eg I/O callbacks and context)
4206  */
mbedtls_ssl_context_save(mbedtls_ssl_context * ssl,unsigned char * buf,size_t buf_len,size_t * olen)4207 int mbedtls_ssl_context_save( mbedtls_ssl_context *ssl,
4208                               unsigned char *buf,
4209                               size_t buf_len,
4210                               size_t *olen )
4211 {
4212     unsigned char *p = buf;
4213     size_t used = 0;
4214     size_t session_len;
4215     int ret = 0;
4216 
4217     /*
4218      * Enforce usage restrictions, see "return BAD_INPUT_DATA" in
4219      * this function's documentation.
4220      *
4221      * These are due to assumptions/limitations in the implementation. Some of
4222      * them are likely to stay (no handshake in progress) some might go away
4223      * (only DTLS) but are currently used to simplify the implementation.
4224      */
4225     /* The initial handshake must be over */
4226     if( mbedtls_ssl_is_handshake_over( ssl ) == 0 )
4227     {
4228         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Initial handshake isn't over" ) );
4229         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4230     }
4231     if( ssl->handshake != NULL )
4232     {
4233         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Handshake isn't completed" ) );
4234         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4235     }
4236     /* Double-check that sub-structures are indeed ready */
4237     if( ssl->transform == NULL || ssl->session == NULL )
4238     {
4239         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Serialised structures aren't ready" ) );
4240         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4241     }
4242     /* There must be no pending incoming or outgoing data */
4243     if( mbedtls_ssl_check_pending( ssl ) != 0 )
4244     {
4245         MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending incoming data" ) );
4246         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4247     }
4248     if( ssl->out_left != 0 )
4249     {
4250         MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending outgoing data" ) );
4251         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4252     }
4253     /* Protocol must be DTLS, not TLS */
4254     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4255     {
4256         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only DTLS is supported" ) );
4257         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4258     }
4259     /* Version must be 1.2 */
4260     if( ssl->tls_version != MBEDTLS_SSL_VERSION_TLS1_2 )
4261     {
4262         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) );
4263         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4264     }
4265     /* We must be using an AEAD ciphersuite */
4266     if( mbedtls_ssl_transform_uses_aead( ssl->transform ) != 1 )
4267     {
4268         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only AEAD ciphersuites supported" ) );
4269         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4270     }
4271     /* Renegotiation must not be enabled */
4272 #if defined(MBEDTLS_SSL_RENEGOTIATION)
4273     if( ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED )
4274     {
4275         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Renegotiation must not be enabled" ) );
4276         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4277     }
4278 #endif
4279 
4280     /*
4281      * Version and format identifier
4282      */
4283     used += sizeof( ssl_serialized_context_header );
4284 
4285     if( used <= buf_len )
4286     {
4287         memcpy( p, ssl_serialized_context_header,
4288                 sizeof( ssl_serialized_context_header ) );
4289         p += sizeof( ssl_serialized_context_header );
4290     }
4291 
4292     /*
4293      * Session (length + data)
4294      */
4295     ret = ssl_session_save( ssl->session, 1, NULL, 0, &session_len );
4296     if( ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL )
4297         return( ret );
4298 
4299     used += 4 + session_len;
4300     if( used <= buf_len )
4301     {
4302         MBEDTLS_PUT_UINT32_BE( session_len, p, 0 );
4303         p += 4;
4304 
4305         ret = ssl_session_save( ssl->session, 1,
4306                                 p, session_len, &session_len );
4307         if( ret != 0 )
4308             return( ret );
4309 
4310         p += session_len;
4311     }
4312 
4313     /*
4314      * Transform
4315      */
4316     used += sizeof( ssl->transform->randbytes );
4317     if( used <= buf_len )
4318     {
4319         memcpy( p, ssl->transform->randbytes,
4320            sizeof( ssl->transform->randbytes ) );
4321         p += sizeof( ssl->transform->randbytes );
4322     }
4323 
4324 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4325     used += 2 + ssl->transform->in_cid_len + ssl->transform->out_cid_len;
4326     if( used <= buf_len )
4327     {
4328         *p++ = ssl->transform->in_cid_len;
4329         memcpy( p, ssl->transform->in_cid, ssl->transform->in_cid_len );
4330         p += ssl->transform->in_cid_len;
4331 
4332         *p++ = ssl->transform->out_cid_len;
4333         memcpy( p, ssl->transform->out_cid, ssl->transform->out_cid_len );
4334         p += ssl->transform->out_cid_len;
4335     }
4336 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4337 
4338     /*
4339      * Saved fields from top-level ssl_context structure
4340      */
4341     used += 4;
4342     if( used <= buf_len )
4343     {
4344         MBEDTLS_PUT_UINT32_BE( ssl->badmac_seen, p, 0 );
4345         p += 4;
4346     }
4347 
4348 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4349     used += 16;
4350     if( used <= buf_len )
4351     {
4352         MBEDTLS_PUT_UINT64_BE( ssl->in_window_top, p, 0 );
4353         p += 8;
4354 
4355         MBEDTLS_PUT_UINT64_BE( ssl->in_window, p, 0 );
4356         p += 8;
4357     }
4358 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
4359 
4360 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4361     used += 1;
4362     if( used <= buf_len )
4363     {
4364         *p++ = ssl->disable_datagram_packing;
4365     }
4366 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4367 
4368     used += MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
4369     if( used <= buf_len )
4370     {
4371         memcpy( p, ssl->cur_out_ctr, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN );
4372         p += MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
4373     }
4374 
4375 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4376     used += 2;
4377     if( used <= buf_len )
4378     {
4379         MBEDTLS_PUT_UINT16_BE( ssl->mtu, p, 0 );
4380         p += 2;
4381     }
4382 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4383 
4384 #if defined(MBEDTLS_SSL_ALPN)
4385     {
4386         const uint8_t alpn_len = ssl->alpn_chosen
4387                                ? (uint8_t) strlen( ssl->alpn_chosen )
4388                                : 0;
4389 
4390         used += 1 + alpn_len;
4391         if( used <= buf_len )
4392         {
4393             *p++ = alpn_len;
4394 
4395             if( ssl->alpn_chosen != NULL )
4396             {
4397                 memcpy( p, ssl->alpn_chosen, alpn_len );
4398                 p += alpn_len;
4399             }
4400         }
4401     }
4402 #endif /* MBEDTLS_SSL_ALPN */
4403 
4404     /*
4405      * Done
4406      */
4407     *olen = used;
4408 
4409     if( used > buf_len )
4410         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
4411 
4412     MBEDTLS_SSL_DEBUG_BUF( 4, "saved context", buf, used );
4413 
4414     return( mbedtls_ssl_session_reset_int( ssl, 0 ) );
4415 }
4416 
4417 /*
4418  * Deserialize context, see mbedtls_ssl_context_save() for format.
4419  *
4420  * This internal version is wrapped by a public function that cleans up in
4421  * case of error.
4422  */
4423 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_context_load(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)4424 static int ssl_context_load( mbedtls_ssl_context *ssl,
4425                              const unsigned char *buf,
4426                              size_t len )
4427 {
4428     const unsigned char *p = buf;
4429     const unsigned char * const end = buf + len;
4430     size_t session_len;
4431     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4432 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4433     tls_prf_fn prf_func = NULL;
4434 #endif
4435 
4436     /*
4437      * The context should have been freshly setup or reset.
4438      * Give the user an error in case of obvious misuse.
4439      * (Checking session is useful because it won't be NULL if we're
4440      * renegotiating, or if the user mistakenly loaded a session first.)
4441      */
4442     if( ssl->state != MBEDTLS_SSL_HELLO_REQUEST ||
4443         ssl->session != NULL )
4444     {
4445         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4446     }
4447 
4448     /*
4449      * We can't check that the config matches the initial one, but we can at
4450      * least check it matches the requirements for serializing.
4451      */
4452     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
4453         ssl->conf->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2 ||
4454         ssl->conf->min_tls_version > MBEDTLS_SSL_VERSION_TLS1_2 ||
4455 #if defined(MBEDTLS_SSL_RENEGOTIATION)
4456         ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
4457 #endif
4458         0 )
4459     {
4460         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4461     }
4462 
4463     MBEDTLS_SSL_DEBUG_BUF( 4, "context to load", buf, len );
4464 
4465     /*
4466      * Check version identifier
4467      */
4468     if( (size_t)( end - p ) < sizeof( ssl_serialized_context_header ) )
4469         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4470 
4471     if( memcmp( p, ssl_serialized_context_header,
4472                 sizeof( ssl_serialized_context_header ) ) != 0 )
4473     {
4474         return( MBEDTLS_ERR_SSL_VERSION_MISMATCH );
4475     }
4476     p += sizeof( ssl_serialized_context_header );
4477 
4478     /*
4479      * Session
4480      */
4481     if( (size_t)( end - p ) < 4 )
4482         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4483 
4484     session_len = ( (size_t) p[0] << 24 ) |
4485                   ( (size_t) p[1] << 16 ) |
4486                   ( (size_t) p[2] <<  8 ) |
4487                   ( (size_t) p[3]       );
4488     p += 4;
4489 
4490     /* This has been allocated by ssl_handshake_init(), called by
4491      * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */
4492     ssl->session = ssl->session_negotiate;
4493     ssl->session_in = ssl->session;
4494     ssl->session_out = ssl->session;
4495     ssl->session_negotiate = NULL;
4496 
4497     if( (size_t)( end - p ) < session_len )
4498         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4499 
4500     ret = ssl_session_load( ssl->session, 1, p, session_len );
4501     if( ret != 0 )
4502     {
4503         mbedtls_ssl_session_free( ssl->session );
4504         return( ret );
4505     }
4506 
4507     p += session_len;
4508 
4509     /*
4510      * Transform
4511      */
4512 
4513     /* This has been allocated by ssl_handshake_init(), called by
4514      * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */
4515     ssl->transform = ssl->transform_negotiate;
4516     ssl->transform_in = ssl->transform;
4517     ssl->transform_out = ssl->transform;
4518     ssl->transform_negotiate = NULL;
4519 
4520 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4521     prf_func = ssl_tls12prf_from_cs( ssl->session->ciphersuite );
4522     if( prf_func == NULL )
4523         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4524 
4525     /* Read random bytes and populate structure */
4526     if( (size_t)( end - p ) < sizeof( ssl->transform->randbytes ) )
4527         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4528 
4529     ret = ssl_tls12_populate_transform( ssl->transform,
4530                   ssl->session->ciphersuite,
4531                   ssl->session->master,
4532 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
4533                   ssl->session->encrypt_then_mac,
4534 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
4535                   prf_func,
4536                   p, /* currently pointing to randbytes */
4537                   MBEDTLS_SSL_VERSION_TLS1_2, /* (D)TLS 1.2 is forced */
4538                   ssl->conf->endpoint,
4539                   ssl );
4540     if( ret != 0 )
4541         return( ret );
4542 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4543     p += sizeof( ssl->transform->randbytes );
4544 
4545 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4546     /* Read connection IDs and store them */
4547     if( (size_t)( end - p ) < 1 )
4548         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4549 
4550     ssl->transform->in_cid_len = *p++;
4551 
4552     if( (size_t)( end - p ) < ssl->transform->in_cid_len + 1u )
4553         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4554 
4555     memcpy( ssl->transform->in_cid, p, ssl->transform->in_cid_len );
4556     p += ssl->transform->in_cid_len;
4557 
4558     ssl->transform->out_cid_len = *p++;
4559 
4560     if( (size_t)( end - p ) < ssl->transform->out_cid_len )
4561         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4562 
4563     memcpy( ssl->transform->out_cid, p, ssl->transform->out_cid_len );
4564     p += ssl->transform->out_cid_len;
4565 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4566 
4567     /*
4568      * Saved fields from top-level ssl_context structure
4569      */
4570     if( (size_t)( end - p ) < 4 )
4571         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4572 
4573     ssl->badmac_seen = ( (uint32_t) p[0] << 24 ) |
4574                        ( (uint32_t) p[1] << 16 ) |
4575                        ( (uint32_t) p[2] <<  8 ) |
4576                        ( (uint32_t) p[3]       );
4577     p += 4;
4578 
4579 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4580     if( (size_t)( end - p ) < 16 )
4581         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4582 
4583     ssl->in_window_top = ( (uint64_t) p[0] << 56 ) |
4584                          ( (uint64_t) p[1] << 48 ) |
4585                          ( (uint64_t) p[2] << 40 ) |
4586                          ( (uint64_t) p[3] << 32 ) |
4587                          ( (uint64_t) p[4] << 24 ) |
4588                          ( (uint64_t) p[5] << 16 ) |
4589                          ( (uint64_t) p[6] <<  8 ) |
4590                          ( (uint64_t) p[7]       );
4591     p += 8;
4592 
4593     ssl->in_window = ( (uint64_t) p[0] << 56 ) |
4594                      ( (uint64_t) p[1] << 48 ) |
4595                      ( (uint64_t) p[2] << 40 ) |
4596                      ( (uint64_t) p[3] << 32 ) |
4597                      ( (uint64_t) p[4] << 24 ) |
4598                      ( (uint64_t) p[5] << 16 ) |
4599                      ( (uint64_t) p[6] <<  8 ) |
4600                      ( (uint64_t) p[7]       );
4601     p += 8;
4602 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
4603 
4604 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4605     if( (size_t)( end - p ) < 1 )
4606         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4607 
4608     ssl->disable_datagram_packing = *p++;
4609 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4610 
4611     if( (size_t)( end - p ) < sizeof( ssl->cur_out_ctr ) )
4612         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4613     memcpy( ssl->cur_out_ctr, p, sizeof( ssl->cur_out_ctr ) );
4614     p += sizeof( ssl->cur_out_ctr );
4615 
4616 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4617     if( (size_t)( end - p ) < 2 )
4618         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4619 
4620     ssl->mtu = ( p[0] << 8 ) | p[1];
4621     p += 2;
4622 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4623 
4624 #if defined(MBEDTLS_SSL_ALPN)
4625     {
4626         uint8_t alpn_len;
4627         const char **cur;
4628 
4629         if( (size_t)( end - p ) < 1 )
4630             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4631 
4632         alpn_len = *p++;
4633 
4634         if( alpn_len != 0 && ssl->conf->alpn_list != NULL )
4635         {
4636             /* alpn_chosen should point to an item in the configured list */
4637             for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
4638             {
4639                 if( strlen( *cur ) == alpn_len &&
4640                     memcmp( p, cur, alpn_len ) == 0 )
4641                 {
4642                     ssl->alpn_chosen = *cur;
4643                     break;
4644                 }
4645             }
4646         }
4647 
4648         /* can only happen on conf mismatch */
4649         if( alpn_len != 0 && ssl->alpn_chosen == NULL )
4650             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4651 
4652         p += alpn_len;
4653     }
4654 #endif /* MBEDTLS_SSL_ALPN */
4655 
4656     /*
4657      * Forced fields from top-level ssl_context structure
4658      *
4659      * Most of them already set to the correct value by mbedtls_ssl_init() and
4660      * mbedtls_ssl_reset(), so we only need to set the remaining ones.
4661      */
4662     ssl->state = MBEDTLS_SSL_HANDSHAKE_OVER;
4663     ssl->tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
4664 
4665     /* Adjust pointers for header fields of outgoing records to
4666      * the given transform, accounting for explicit IV and CID. */
4667     mbedtls_ssl_update_out_pointers( ssl, ssl->transform );
4668 
4669 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4670     ssl->in_epoch = 1;
4671 #endif
4672 
4673     /* mbedtls_ssl_reset() leaves the handshake sub-structure allocated,
4674      * which we don't want - otherwise we'd end up freeing the wrong transform
4675      * by calling mbedtls_ssl_handshake_wrapup_free_hs_transform()
4676      * inappropriately. */
4677     if( ssl->handshake != NULL )
4678     {
4679         mbedtls_ssl_handshake_free( ssl );
4680         mbedtls_free( ssl->handshake );
4681         ssl->handshake = NULL;
4682     }
4683 
4684     /*
4685      * Done - should have consumed entire buffer
4686      */
4687     if( p != end )
4688         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4689 
4690     return( 0 );
4691 }
4692 
4693 /*
4694  * Deserialize context: public wrapper for error cleaning
4695  */
mbedtls_ssl_context_load(mbedtls_ssl_context * context,const unsigned char * buf,size_t len)4696 int mbedtls_ssl_context_load( mbedtls_ssl_context *context,
4697                               const unsigned char *buf,
4698                               size_t len )
4699 {
4700     int ret = ssl_context_load( context, buf, len );
4701 
4702     if( ret != 0 )
4703         mbedtls_ssl_free( context );
4704 
4705     return( ret );
4706 }
4707 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
4708 
4709 /*
4710  * Free an SSL context
4711  */
mbedtls_ssl_free(mbedtls_ssl_context * ssl)4712 void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
4713 {
4714     if( ssl == NULL )
4715         return;
4716 
4717     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
4718 
4719     if( ssl->out_buf != NULL )
4720     {
4721 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
4722         size_t out_buf_len = ssl->out_buf_len;
4723 #else
4724         size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
4725 #endif
4726 
4727         mbedtls_platform_zeroize( ssl->out_buf, out_buf_len );
4728         mbedtls_free( ssl->out_buf );
4729         ssl->out_buf = NULL;
4730     }
4731 
4732     if( ssl->in_buf != NULL )
4733     {
4734 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
4735         size_t in_buf_len = ssl->in_buf_len;
4736 #else
4737         size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
4738 #endif
4739 
4740         mbedtls_platform_zeroize( ssl->in_buf, in_buf_len );
4741         mbedtls_free( ssl->in_buf );
4742         ssl->in_buf = NULL;
4743     }
4744 
4745     if( ssl->transform )
4746     {
4747         mbedtls_ssl_transform_free( ssl->transform );
4748         mbedtls_free( ssl->transform );
4749     }
4750 
4751     if( ssl->handshake )
4752     {
4753         mbedtls_ssl_handshake_free( ssl );
4754         mbedtls_ssl_transform_free( ssl->transform_negotiate );
4755         mbedtls_ssl_session_free( ssl->session_negotiate );
4756 
4757         mbedtls_free( ssl->handshake );
4758         mbedtls_free( ssl->transform_negotiate );
4759         mbedtls_free( ssl->session_negotiate );
4760     }
4761 
4762 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
4763     mbedtls_ssl_transform_free( ssl->transform_application );
4764     mbedtls_free( ssl->transform_application );
4765 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
4766 
4767     if( ssl->session )
4768     {
4769         mbedtls_ssl_session_free( ssl->session );
4770         mbedtls_free( ssl->session );
4771     }
4772 
4773 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4774     if( ssl->hostname != NULL )
4775     {
4776         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
4777         mbedtls_free( ssl->hostname );
4778     }
4779 #endif
4780 
4781 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
4782     mbedtls_free( ssl->cli_id );
4783 #endif
4784 
4785     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
4786 
4787     /* Actually clear after last debug message */
4788     mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
4789 }
4790 
4791 /*
4792  * Initialize mbedtls_ssl_config
4793  */
mbedtls_ssl_config_init(mbedtls_ssl_config * conf)4794 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
4795 {
4796     memset( conf, 0, sizeof( mbedtls_ssl_config ) );
4797 }
4798 
4799 /* The selection should be the same as mbedtls_x509_crt_profile_default in
4800  * x509_crt.c, plus Montgomery curves for ECDHE. Here, the order matters:
4801  * curves with a lower resource usage come first.
4802  * See the documentation of mbedtls_ssl_conf_curves() for what we promise
4803  * about this list.
4804  */
4805 static uint16_t ssl_preset_default_groups[] = {
4806 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
4807     MBEDTLS_SSL_IANA_TLS_GROUP_X25519,
4808 #endif
4809 #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
4810     MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
4811 #endif
4812 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
4813     MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1,
4814 #endif
4815 #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
4816     MBEDTLS_SSL_IANA_TLS_GROUP_X448,
4817 #endif
4818 #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
4819     MBEDTLS_SSL_IANA_TLS_GROUP_SECP521R1,
4820 #endif
4821 #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
4822     MBEDTLS_SSL_IANA_TLS_GROUP_BP256R1,
4823 #endif
4824 #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
4825     MBEDTLS_SSL_IANA_TLS_GROUP_BP384R1,
4826 #endif
4827 #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
4828     MBEDTLS_SSL_IANA_TLS_GROUP_BP512R1,
4829 #endif
4830     MBEDTLS_SSL_IANA_TLS_GROUP_NONE
4831 };
4832 
4833 static int ssl_preset_suiteb_ciphersuites[] = {
4834     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
4835     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
4836     0
4837 };
4838 
4839 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
4840 
4841 /* NOTICE:
4842  *   For ssl_preset_*_sig_algs and ssl_tls12_preset_*_sig_algs, the following
4843  *   rules SHOULD be upheld.
4844  *   - No duplicate entries.
4845  *   - But if there is a good reason, do not change the order of the algorithms.
4846  *   - ssl_tls12_preset* is for TLS 1.2 use only.
4847  *   - ssl_preset_* is for TLS 1.3 only or hybrid TLS 1.3/1.2 handshakes.
4848  */
4849 static uint16_t ssl_preset_default_sig_algs[] = {
4850 
4851 #if defined(MBEDTLS_ECDSA_C) &&  defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
4852     defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
4853     MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256,
4854 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA &&
4855           MBEDTLS_ECP_DP_SECP256R1_ENABLED */
4856 
4857 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
4858     defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
4859     MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384,
4860 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA&&
4861           MBEDTLS_ECP_DP_SECP384R1_ENABLED */
4862 
4863 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
4864     defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
4865     MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512,
4866 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA&&
4867           MBEDTLS_ECP_DP_SECP521R1_ENABLED */
4868 
4869 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) && defined(MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4870     MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512,
4871 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT && MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
4872 
4873 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) && defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4874     MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384,
4875 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT && MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
4876 
4877 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) && defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4878     MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256,
4879 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT && MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
4880 
4881 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4882     MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA512,
4883 #endif /* MBEDTLS_RSA_C && MBEDTLS_SHA512_C */
4884 
4885 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4886     MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA384,
4887 #endif /* MBEDTLS_RSA_C && MBEDTLS_SHA384_C */
4888 
4889 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4890     MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256,
4891 #endif /* MBEDTLS_RSA_C && MBEDTLS_SHA256_C */
4892 
4893     MBEDTLS_TLS_SIG_NONE
4894 };
4895 
4896 /* NOTICE: see above */
4897 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4898 static uint16_t ssl_tls12_preset_default_sig_algs[] = {
4899 #if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4900 #if defined(MBEDTLS_ECDSA_C)
4901     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_ECDSA, MBEDTLS_SSL_HASH_SHA512 ),
4902 #endif
4903 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
4904     MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512,
4905 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
4906 #if defined(MBEDTLS_RSA_C)
4907     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_RSA, MBEDTLS_SSL_HASH_SHA512 ),
4908 #endif
4909 #endif /* MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
4910 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4911 #if defined(MBEDTLS_ECDSA_C)
4912     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_ECDSA, MBEDTLS_SSL_HASH_SHA384 ),
4913 #endif
4914 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
4915     MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384,
4916 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
4917 #if defined(MBEDTLS_RSA_C)
4918     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_RSA, MBEDTLS_SSL_HASH_SHA384 ),
4919 #endif
4920 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
4921 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4922 #if defined(MBEDTLS_ECDSA_C)
4923     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_ECDSA, MBEDTLS_SSL_HASH_SHA256 ),
4924 #endif
4925 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
4926     MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256,
4927 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
4928 #if defined(MBEDTLS_RSA_C)
4929     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_RSA, MBEDTLS_SSL_HASH_SHA256 ),
4930 #endif
4931 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
4932     MBEDTLS_TLS_SIG_NONE
4933 };
4934 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4935 /* NOTICE: see above */
4936 static uint16_t ssl_preset_suiteb_sig_algs[] = {
4937 
4938 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
4939     defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
4940     MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256,
4941 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA&&
4942           MBEDTLS_ECP_DP_SECP256R1_ENABLED */
4943 
4944 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
4945     defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
4946     MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384,
4947 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA&&
4948           MBEDTLS_ECP_DP_SECP384R1_ENABLED */
4949 
4950 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) && defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4951     MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256,
4952 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT && MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
4953 
4954 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4955     MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256,
4956 #endif /* MBEDTLS_RSA_C && MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
4957 
4958     MBEDTLS_TLS_SIG_NONE
4959 };
4960 
4961 /* NOTICE: see above */
4962 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4963 static uint16_t ssl_tls12_preset_suiteb_sig_algs[] = {
4964 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4965 #if defined(MBEDTLS_ECDSA_C)
4966     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_ECDSA, MBEDTLS_SSL_HASH_SHA256 ),
4967 #endif
4968 #if defined(MBEDTLS_RSA_C)
4969     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_RSA, MBEDTLS_SSL_HASH_SHA256 ),
4970 #endif
4971 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
4972 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
4973 #if defined(MBEDTLS_ECDSA_C)
4974     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_ECDSA, MBEDTLS_SSL_HASH_SHA384 ),
4975 #endif
4976 #if defined(MBEDTLS_RSA_C)
4977     MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG( MBEDTLS_SSL_SIG_RSA, MBEDTLS_SSL_HASH_SHA384 ),
4978 #endif
4979 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
4980     MBEDTLS_TLS_SIG_NONE
4981 };
4982 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4983 
4984 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
4985 
4986 static uint16_t ssl_preset_suiteb_groups[] = {
4987 #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
4988     MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
4989 #endif
4990 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
4991     MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1,
4992 #endif
4993     MBEDTLS_SSL_IANA_TLS_GROUP_NONE
4994 };
4995 
4996 #if defined(MBEDTLS_DEBUG_C) && defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
4997 /* Function for checking `ssl_preset_*_sig_algs` and `ssl_tls12_preset_*_sig_algs`
4998  * to make sure there are no duplicated signature algorithm entries. */
4999 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_no_sig_alg_duplication(uint16_t * sig_algs)5000 static int ssl_check_no_sig_alg_duplication( uint16_t * sig_algs )
5001 {
5002     size_t i, j;
5003     int ret = 0;
5004 
5005     for( i = 0; sig_algs[i] != MBEDTLS_TLS_SIG_NONE; i++ )
5006     {
5007         for( j = 0; j < i; j++ )
5008         {
5009             if( sig_algs[i] != sig_algs[j] )
5010                 continue;
5011             mbedtls_printf( " entry(%04x,%" MBEDTLS_PRINTF_SIZET
5012                             ") is duplicated at %" MBEDTLS_PRINTF_SIZET "\n",
5013                             sig_algs[i], j, i );
5014             ret = -1;
5015         }
5016     }
5017     return( ret );
5018 }
5019 
5020 #endif /* MBEDTLS_DEBUG_C && MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
5021 
5022 /*
5023  * Load default in mbedtls_ssl_config
5024  */
mbedtls_ssl_config_defaults(mbedtls_ssl_config * conf,int endpoint,int transport,int preset)5025 int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
5026                                  int endpoint, int transport, int preset )
5027 {
5028 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
5029     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5030 #endif
5031 
5032 #if defined(MBEDTLS_DEBUG_C) && defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
5033     if( ssl_check_no_sig_alg_duplication( ssl_preset_suiteb_sig_algs ) )
5034     {
5035         mbedtls_printf( "ssl_preset_suiteb_sig_algs has duplicated entries\n" );
5036         return( MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED );
5037     }
5038 
5039     if( ssl_check_no_sig_alg_duplication( ssl_preset_default_sig_algs ) )
5040     {
5041         mbedtls_printf( "ssl_preset_default_sig_algs has duplicated entries\n" );
5042         return( MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED );
5043     }
5044 
5045 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5046     if( ssl_check_no_sig_alg_duplication( ssl_tls12_preset_suiteb_sig_algs ) )
5047     {
5048         mbedtls_printf( "ssl_tls12_preset_suiteb_sig_algs has duplicated entries\n" );
5049         return( MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED );
5050     }
5051 
5052     if( ssl_check_no_sig_alg_duplication( ssl_tls12_preset_default_sig_algs ) )
5053     {
5054         mbedtls_printf( "ssl_tls12_preset_default_sig_algs has duplicated entries\n" );
5055         return( MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED );
5056     }
5057 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5058 #endif /* MBEDTLS_DEBUG_C && MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
5059 
5060     /* Use the functions here so that they are covered in tests,
5061      * but otherwise access member directly for efficiency */
5062     mbedtls_ssl_conf_endpoint( conf, endpoint );
5063     mbedtls_ssl_conf_transport( conf, transport );
5064 
5065     /*
5066      * Things that are common to all presets
5067      */
5068 #if defined(MBEDTLS_SSL_CLI_C)
5069     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
5070     {
5071         conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
5072 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
5073         conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
5074 #endif
5075     }
5076 #endif
5077 
5078 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5079     conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
5080 #endif
5081 
5082 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
5083     conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
5084 #endif
5085 
5086 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5087     conf->f_cookie_write = ssl_cookie_write_dummy;
5088     conf->f_cookie_check = ssl_cookie_check_dummy;
5089 #endif
5090 
5091 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5092     conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
5093 #endif
5094 
5095 #if defined(MBEDTLS_SSL_SRV_C)
5096     conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
5097     conf->respect_cli_pref = MBEDTLS_SSL_SRV_CIPHERSUITE_ORDER_SERVER;
5098 #endif
5099 
5100 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5101     conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
5102     conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
5103 #endif
5104 
5105 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5106     conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
5107     memset( conf->renego_period,     0x00, 2 );
5108     memset( conf->renego_period + 2, 0xFF, 6 );
5109 #endif
5110 
5111 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
5112     if( endpoint == MBEDTLS_SSL_IS_SERVER )
5113     {
5114         const unsigned char dhm_p[] =
5115             MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
5116         const unsigned char dhm_g[] =
5117             MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
5118 
5119         if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,
5120                                                     dhm_p, sizeof( dhm_p ),
5121                                                     dhm_g, sizeof( dhm_g ) ) ) != 0 )
5122         {
5123             return( ret );
5124         }
5125     }
5126 #endif
5127 
5128 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
5129 
5130 #if defined(MBEDTLS_SSL_EARLY_DATA)
5131     mbedtls_ssl_tls13_conf_early_data( conf, MBEDTLS_SSL_EARLY_DATA_DISABLED );
5132 #if defined(MBEDTLS_SSL_SRV_C)
5133     mbedtls_ssl_tls13_conf_max_early_data_size(
5134         conf, MBEDTLS_SSL_MAX_EARLY_DATA_SIZE );
5135 #endif
5136 #endif /* MBEDTLS_SSL_EARLY_DATA */
5137 
5138 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SESSION_TICKETS)
5139     mbedtls_ssl_conf_new_session_tickets(
5140         conf, MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS );
5141 #endif
5142     /*
5143      * Allow all TLS 1.3 key exchange modes by default.
5144      */
5145     conf->tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_ALL;
5146 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
5147 
5148     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM  )
5149     {
5150 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5151         conf->min_tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
5152         conf->max_tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
5153 #else
5154         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5155 #endif
5156     }
5157     else
5158     {
5159 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_SSL_PROTO_TLS1_3)
5160         if( endpoint == MBEDTLS_SSL_IS_CLIENT )
5161         {
5162             conf->min_tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
5163             conf->max_tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
5164         }
5165         else
5166         /* Hybrid TLS 1.2 / 1.3 is not supported on server side yet */
5167         {
5168             conf->min_tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
5169             conf->max_tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
5170         }
5171 #elif defined(MBEDTLS_SSL_PROTO_TLS1_3)
5172         conf->min_tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
5173         conf->max_tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
5174 #elif defined(MBEDTLS_SSL_PROTO_TLS1_2)
5175         conf->min_tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
5176         conf->max_tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
5177 #else
5178         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5179 #endif
5180     }
5181 
5182     /*
5183      * Preset-specific defaults
5184      */
5185     switch( preset )
5186     {
5187         /*
5188          * NSA Suite B
5189          */
5190         case MBEDTLS_SSL_PRESET_SUITEB:
5191 
5192             conf->ciphersuite_list = ssl_preset_suiteb_ciphersuites;
5193 
5194 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5195             conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
5196 #endif
5197 
5198 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
5199 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5200             if( mbedtls_ssl_conf_is_tls12_only( conf ) )
5201                 conf->sig_algs = ssl_tls12_preset_suiteb_sig_algs;
5202             else
5203 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5204                 conf->sig_algs = ssl_preset_suiteb_sig_algs;
5205 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
5206 
5207 #if defined(MBEDTLS_ECP_C) && !defined(MBEDTLS_DEPRECATED_REMOVED)
5208             conf->curve_list = NULL;
5209 #endif
5210             conf->group_list = ssl_preset_suiteb_groups;
5211             break;
5212 
5213         /*
5214          * Default
5215          */
5216         default:
5217 
5218             conf->ciphersuite_list = mbedtls_ssl_list_ciphersuites();
5219 
5220 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5221             conf->cert_profile = &mbedtls_x509_crt_profile_default;
5222 #endif
5223 
5224 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
5225 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5226             if( mbedtls_ssl_conf_is_tls12_only( conf ) )
5227                 conf->sig_algs = ssl_tls12_preset_default_sig_algs;
5228             else
5229 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5230                 conf->sig_algs = ssl_preset_default_sig_algs;
5231 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
5232 
5233 #if defined(MBEDTLS_ECP_C) && !defined(MBEDTLS_DEPRECATED_REMOVED)
5234             conf->curve_list = NULL;
5235 #endif
5236             conf->group_list = ssl_preset_default_groups;
5237 
5238 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
5239             conf->dhm_min_bitlen = 1024;
5240 #endif
5241     }
5242 
5243     return( 0 );
5244 }
5245 
5246 /*
5247  * Free mbedtls_ssl_config
5248  */
mbedtls_ssl_config_free(mbedtls_ssl_config * conf)5249 void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
5250 {
5251 #if defined(MBEDTLS_DHM_C)
5252     mbedtls_mpi_free( &conf->dhm_P );
5253     mbedtls_mpi_free( &conf->dhm_G );
5254 #endif
5255 
5256 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
5257 #if defined(MBEDTLS_USE_PSA_CRYPTO)
5258     if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) )
5259     {
5260         conf->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT;
5261     }
5262 #endif /* MBEDTLS_USE_PSA_CRYPTO */
5263     if( conf->psk != NULL )
5264     {
5265         mbedtls_platform_zeroize( conf->psk, conf->psk_len );
5266         mbedtls_free( conf->psk );
5267         conf->psk = NULL;
5268         conf->psk_len = 0;
5269     }
5270 
5271     if( conf->psk_identity != NULL )
5272     {
5273         mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len );
5274         mbedtls_free( conf->psk_identity );
5275         conf->psk_identity = NULL;
5276         conf->psk_identity_len = 0;
5277     }
5278 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
5279 
5280 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5281     ssl_key_cert_free( conf->key_cert );
5282 #endif
5283 
5284     mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) );
5285 }
5286 
5287 #if defined(MBEDTLS_PK_C) && \
5288     ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
5289 /*
5290  * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
5291  */
mbedtls_ssl_sig_from_pk(mbedtls_pk_context * pk)5292 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
5293 {
5294 #if defined(MBEDTLS_RSA_C)
5295     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
5296         return( MBEDTLS_SSL_SIG_RSA );
5297 #endif
5298 #if defined(MBEDTLS_ECDSA_C)
5299     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
5300         return( MBEDTLS_SSL_SIG_ECDSA );
5301 #endif
5302     return( MBEDTLS_SSL_SIG_ANON );
5303 }
5304 
mbedtls_ssl_sig_from_pk_alg(mbedtls_pk_type_t type)5305 unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
5306 {
5307     switch( type ) {
5308         case MBEDTLS_PK_RSA:
5309             return( MBEDTLS_SSL_SIG_RSA );
5310         case MBEDTLS_PK_ECDSA:
5311         case MBEDTLS_PK_ECKEY:
5312             return( MBEDTLS_SSL_SIG_ECDSA );
5313         default:
5314             return( MBEDTLS_SSL_SIG_ANON );
5315     }
5316 }
5317 
mbedtls_ssl_pk_alg_from_sig(unsigned char sig)5318 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
5319 {
5320     switch( sig )
5321     {
5322 #if defined(MBEDTLS_RSA_C)
5323         case MBEDTLS_SSL_SIG_RSA:
5324             return( MBEDTLS_PK_RSA );
5325 #endif
5326 #if defined(MBEDTLS_ECDSA_C)
5327         case MBEDTLS_SSL_SIG_ECDSA:
5328             return( MBEDTLS_PK_ECDSA );
5329 #endif
5330         default:
5331             return( MBEDTLS_PK_NONE );
5332     }
5333 }
5334 #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
5335 
5336 /*
5337  * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
5338  */
mbedtls_ssl_md_alg_from_hash(unsigned char hash)5339 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
5340 {
5341     switch( hash )
5342     {
5343 #if defined(MBEDTLS_HAS_ALG_MD5_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5344         case MBEDTLS_SSL_HASH_MD5:
5345             return( MBEDTLS_MD_MD5 );
5346 #endif
5347 #if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5348         case MBEDTLS_SSL_HASH_SHA1:
5349             return( MBEDTLS_MD_SHA1 );
5350 #endif
5351 #if defined(MBEDTLS_HAS_ALG_SHA_224_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5352         case MBEDTLS_SSL_HASH_SHA224:
5353             return( MBEDTLS_MD_SHA224 );
5354 #endif
5355 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5356         case MBEDTLS_SSL_HASH_SHA256:
5357             return( MBEDTLS_MD_SHA256 );
5358 #endif
5359 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5360         case MBEDTLS_SSL_HASH_SHA384:
5361             return( MBEDTLS_MD_SHA384 );
5362 #endif
5363 #if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5364         case MBEDTLS_SSL_HASH_SHA512:
5365             return( MBEDTLS_MD_SHA512 );
5366 #endif
5367         default:
5368             return( MBEDTLS_MD_NONE );
5369     }
5370 }
5371 
5372 /*
5373  * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
5374  */
mbedtls_ssl_hash_from_md_alg(int md)5375 unsigned char mbedtls_ssl_hash_from_md_alg( int md )
5376 {
5377     switch( md )
5378     {
5379 #if defined(MBEDTLS_HAS_ALG_MD5_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5380         case MBEDTLS_MD_MD5:
5381             return( MBEDTLS_SSL_HASH_MD5 );
5382 #endif
5383 #if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5384         case MBEDTLS_MD_SHA1:
5385             return( MBEDTLS_SSL_HASH_SHA1 );
5386 #endif
5387 #if defined(MBEDTLS_HAS_ALG_SHA_224_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5388         case MBEDTLS_MD_SHA224:
5389             return( MBEDTLS_SSL_HASH_SHA224 );
5390 #endif
5391 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5392         case MBEDTLS_MD_SHA256:
5393             return( MBEDTLS_SSL_HASH_SHA256 );
5394 #endif
5395 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5396         case MBEDTLS_MD_SHA384:
5397             return( MBEDTLS_SSL_HASH_SHA384 );
5398 #endif
5399 #if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5400         case MBEDTLS_MD_SHA512:
5401             return( MBEDTLS_SSL_HASH_SHA512 );
5402 #endif
5403         default:
5404             return( MBEDTLS_SSL_HASH_NONE );
5405     }
5406 }
5407 
5408 /*
5409  * Check if a curve proposed by the peer is in our list.
5410  * Return 0 if we're willing to use it, -1 otherwise.
5411  */
mbedtls_ssl_check_curve_tls_id(const mbedtls_ssl_context * ssl,uint16_t tls_id)5412 int mbedtls_ssl_check_curve_tls_id( const mbedtls_ssl_context *ssl, uint16_t tls_id )
5413 {
5414     const uint16_t *group_list = mbedtls_ssl_get_groups( ssl );
5415 
5416     if( group_list == NULL )
5417         return( -1 );
5418 
5419     for( ; *group_list != 0; group_list++ )
5420     {
5421         if( *group_list == tls_id )
5422             return( 0 );
5423     }
5424 
5425     return( -1 );
5426 }
5427 
5428 #if defined(MBEDTLS_ECP_C)
5429 /*
5430  * Same as mbedtls_ssl_check_curve_tls_id() but with a mbedtls_ecp_group_id.
5431  */
mbedtls_ssl_check_curve(const mbedtls_ssl_context * ssl,mbedtls_ecp_group_id grp_id)5432 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
5433 {
5434     const mbedtls_ecp_curve_info *grp_info =
5435         mbedtls_ecp_curve_info_from_grp_id( grp_id );
5436 
5437     if ( grp_info == NULL )
5438         return -1;
5439 
5440     uint16_t tls_id = grp_info->tls_id;
5441 
5442     return mbedtls_ssl_check_curve_tls_id( ssl, tls_id );
5443 }
5444 #endif /* MBEDTLS_ECP_C */
5445 
5446 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_check_cert_usage(const mbedtls_x509_crt * cert,const mbedtls_ssl_ciphersuite_t * ciphersuite,int cert_endpoint,uint32_t * flags)5447 int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
5448                           const mbedtls_ssl_ciphersuite_t *ciphersuite,
5449                           int cert_endpoint,
5450                           uint32_t *flags )
5451 {
5452     int ret = 0;
5453     int usage = 0;
5454     const char *ext_oid;
5455     size_t ext_len;
5456 
5457     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
5458     {
5459         /* Server part of the key exchange */
5460         switch( ciphersuite->key_exchange )
5461         {
5462             case MBEDTLS_KEY_EXCHANGE_RSA:
5463             case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
5464                 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
5465                 break;
5466 
5467             case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
5468             case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
5469             case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
5470                 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
5471                 break;
5472 
5473             case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
5474             case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
5475                 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
5476                 break;
5477 
5478             /* Don't use default: we want warnings when adding new values */
5479             case MBEDTLS_KEY_EXCHANGE_NONE:
5480             case MBEDTLS_KEY_EXCHANGE_PSK:
5481             case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
5482             case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
5483             case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
5484                 usage = 0;
5485         }
5486     }
5487     else
5488     {
5489         /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
5490         usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
5491     }
5492 
5493     if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
5494     {
5495         *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
5496         ret = -1;
5497     }
5498 
5499     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
5500     {
5501         ext_oid = MBEDTLS_OID_SERVER_AUTH;
5502         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
5503     }
5504     else
5505     {
5506         ext_oid = MBEDTLS_OID_CLIENT_AUTH;
5507         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
5508     }
5509 
5510     if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
5511     {
5512         *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
5513         ret = -1;
5514     }
5515 
5516     return( ret );
5517 }
5518 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5519 
5520 #if defined(MBEDTLS_USE_PSA_CRYPTO)
mbedtls_ssl_get_handshake_transcript(mbedtls_ssl_context * ssl,const mbedtls_md_type_t md,unsigned char * dst,size_t dst_len,size_t * olen)5521 int mbedtls_ssl_get_handshake_transcript( mbedtls_ssl_context *ssl,
5522                                           const mbedtls_md_type_t md,
5523                                           unsigned char *dst,
5524                                           size_t dst_len,
5525                                           size_t *olen )
5526 {
5527     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5528     psa_hash_operation_t *hash_operation_to_clone;
5529     psa_hash_operation_t hash_operation = psa_hash_operation_init();
5530 
5531     *olen = 0;
5532 
5533     switch( md )
5534     {
5535 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5536     case MBEDTLS_MD_SHA384:
5537         hash_operation_to_clone = &ssl->handshake->fin_sha384_psa;
5538         break;
5539 #endif
5540 
5541 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5542     case MBEDTLS_MD_SHA256:
5543         hash_operation_to_clone = &ssl->handshake->fin_sha256_psa;
5544         break;
5545 #endif
5546 
5547     default:
5548         goto exit;
5549     }
5550 
5551     status = psa_hash_clone( hash_operation_to_clone, &hash_operation );
5552     if( status != PSA_SUCCESS )
5553         goto exit;
5554 
5555     status = psa_hash_finish( &hash_operation, dst, dst_len, olen );
5556     if( status != PSA_SUCCESS )
5557         goto exit;
5558 
5559 exit:
5560 #if !defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
5561     !defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5562     (void) ssl;
5563 #endif
5564     return( psa_ssl_status_to_mbedtls( status ) );
5565 }
5566 #else /* MBEDTLS_USE_PSA_CRYPTO */
5567 
5568 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5569 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_get_handshake_transcript_sha384(mbedtls_ssl_context * ssl,unsigned char * dst,size_t dst_len,size_t * olen)5570 static int ssl_get_handshake_transcript_sha384( mbedtls_ssl_context *ssl,
5571                                                 unsigned char *dst,
5572                                                 size_t dst_len,
5573                                                 size_t *olen )
5574 {
5575     int ret;
5576     mbedtls_sha512_context sha512;
5577 
5578     if( dst_len < 48 )
5579         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
5580 
5581     mbedtls_sha512_init( &sha512 );
5582     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha384 );
5583 
5584     if( ( ret = mbedtls_sha512_finish( &sha512, dst ) ) != 0 )
5585     {
5586         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_finish", ret );
5587         goto exit;
5588     }
5589 
5590     *olen = 48;
5591 
5592 exit:
5593 
5594     mbedtls_sha512_free( &sha512 );
5595     return( ret );
5596 }
5597 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
5598 
5599 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5600 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_get_handshake_transcript_sha256(mbedtls_ssl_context * ssl,unsigned char * dst,size_t dst_len,size_t * olen)5601 static int ssl_get_handshake_transcript_sha256( mbedtls_ssl_context *ssl,
5602                                                 unsigned char *dst,
5603                                                 size_t dst_len,
5604                                                 size_t *olen )
5605 {
5606     int ret;
5607     mbedtls_sha256_context sha256;
5608 
5609     if( dst_len < 32 )
5610         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
5611 
5612     mbedtls_sha256_init( &sha256 );
5613     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
5614 
5615     if( ( ret = mbedtls_sha256_finish( &sha256, dst ) ) != 0 )
5616     {
5617         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha256_finish", ret );
5618         goto exit;
5619     }
5620 
5621     *olen = 32;
5622 
5623 exit:
5624 
5625     mbedtls_sha256_free( &sha256 );
5626     return( ret );
5627 }
5628 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
5629 
mbedtls_ssl_get_handshake_transcript(mbedtls_ssl_context * ssl,const mbedtls_md_type_t md,unsigned char * dst,size_t dst_len,size_t * olen)5630 int mbedtls_ssl_get_handshake_transcript( mbedtls_ssl_context *ssl,
5631                                           const mbedtls_md_type_t md,
5632                                           unsigned char *dst,
5633                                           size_t dst_len,
5634                                           size_t *olen )
5635 {
5636     switch( md )
5637     {
5638 
5639 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5640     case MBEDTLS_MD_SHA384:
5641         return( ssl_get_handshake_transcript_sha384( ssl, dst, dst_len, olen ) );
5642 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
5643 
5644 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5645     case MBEDTLS_MD_SHA256:
5646         return( ssl_get_handshake_transcript_sha256( ssl, dst, dst_len, olen ) );
5647 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
5648 
5649     default:
5650 #if !defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
5651     !defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
5652     (void) ssl;
5653     (void) dst;
5654     (void) dst_len;
5655     (void) olen;
5656 #endif
5657         break;
5658     }
5659     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
5660 }
5661 
5662 #endif /* !MBEDTLS_USE_PSA_CRYPTO */
5663 
5664 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
5665 /* mbedtls_ssl_parse_sig_alg_ext()
5666  *
5667  * The `extension_data` field of signature algorithm contains  a `SignatureSchemeList`
5668  * value (TLS 1.3 RFC8446):
5669  *      enum {
5670  *         ....
5671  *        ecdsa_secp256r1_sha256( 0x0403 ),
5672  *        ecdsa_secp384r1_sha384( 0x0503 ),
5673  *        ecdsa_secp521r1_sha512( 0x0603 ),
5674  *         ....
5675  *      } SignatureScheme;
5676  *
5677  *      struct {
5678  *         SignatureScheme supported_signature_algorithms<2..2^16-2>;
5679  *      } SignatureSchemeList;
5680  *
5681  * The `extension_data` field of signature algorithm contains a `SignatureAndHashAlgorithm`
5682  * value (TLS 1.2 RFC5246):
5683  *      enum {
5684  *          none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
5685  *          sha512(6), (255)
5686  *      } HashAlgorithm;
5687  *
5688  *      enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
5689  *        SignatureAlgorithm;
5690  *
5691  *      struct {
5692  *          HashAlgorithm hash;
5693  *          SignatureAlgorithm signature;
5694  *      } SignatureAndHashAlgorithm;
5695  *
5696  *      SignatureAndHashAlgorithm
5697  *        supported_signature_algorithms<2..2^16-2>;
5698  *
5699  * The TLS 1.3 signature algorithm extension was defined to be a compatible
5700  * generalization of the TLS 1.2 signature algorithm extension.
5701  * `SignatureAndHashAlgorithm` field of TLS 1.2 can be represented by
5702  * `SignatureScheme` field of TLS 1.3
5703  *
5704  */
mbedtls_ssl_parse_sig_alg_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)5705 int mbedtls_ssl_parse_sig_alg_ext( mbedtls_ssl_context *ssl,
5706                                    const unsigned char *buf,
5707                                    const unsigned char *end )
5708 {
5709     const unsigned char *p = buf;
5710     size_t supported_sig_algs_len = 0;
5711     const unsigned char *supported_sig_algs_end;
5712     uint16_t sig_alg;
5713     uint32_t common_idx = 0;
5714 
5715     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 2 );
5716     supported_sig_algs_len = MBEDTLS_GET_UINT16_BE( p, 0 );
5717     p += 2;
5718 
5719     memset( ssl->handshake->received_sig_algs, 0,
5720             sizeof(ssl->handshake->received_sig_algs) );
5721 
5722     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, supported_sig_algs_len );
5723     supported_sig_algs_end = p + supported_sig_algs_len;
5724     while( p < supported_sig_algs_end )
5725     {
5726         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, supported_sig_algs_end, 2 );
5727         sig_alg = MBEDTLS_GET_UINT16_BE( p, 0 );
5728         p += 2;
5729         MBEDTLS_SSL_DEBUG_MSG( 4, ( "received signature algorithm: 0x%x %s",
5730                                     sig_alg,
5731                                     mbedtls_ssl_sig_alg_to_str( sig_alg ) ) );
5732 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5733         if( ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2 &&
5734             ( ! ( mbedtls_ssl_sig_alg_is_supported( ssl, sig_alg ) &&
5735                   mbedtls_ssl_sig_alg_is_offered( ssl, sig_alg ) ) ) )
5736         {
5737             continue;
5738         }
5739 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5740 
5741         MBEDTLS_SSL_DEBUG_MSG( 4, ( "valid signature algorithm: %s",
5742                                     mbedtls_ssl_sig_alg_to_str( sig_alg ) ) );
5743 
5744         if( common_idx + 1 < MBEDTLS_RECEIVED_SIG_ALGS_SIZE )
5745         {
5746             ssl->handshake->received_sig_algs[common_idx] = sig_alg;
5747             common_idx += 1;
5748         }
5749     }
5750     /* Check that we consumed all the message. */
5751     if( p != end )
5752     {
5753         MBEDTLS_SSL_DEBUG_MSG( 1,
5754             ( "Signature algorithms extension length misaligned" ) );
5755         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
5756                                       MBEDTLS_ERR_SSL_DECODE_ERROR );
5757         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
5758     }
5759 
5760     if( common_idx == 0 )
5761     {
5762         MBEDTLS_SSL_DEBUG_MSG( 3, ( "no signature algorithm in common" ) );
5763         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
5764                                       MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
5765         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
5766     }
5767 
5768     ssl->handshake->received_sig_algs[common_idx] = MBEDTLS_TLS_SIG_NONE;
5769     return( 0 );
5770 }
5771 
5772 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
5773 
5774 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5775 
5776 #if defined(MBEDTLS_USE_PSA_CRYPTO)
5777 
setup_psa_key_derivation(psa_key_derivation_operation_t * derivation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,const unsigned char * raw_psk,size_t raw_psk_length,const unsigned char * seed,size_t seed_length,const unsigned char * label,size_t label_length,const unsigned char * other_secret,size_t other_secret_length,size_t capacity)5778 static psa_status_t setup_psa_key_derivation( psa_key_derivation_operation_t* derivation,
5779                                               mbedtls_svc_key_id_t key,
5780                                               psa_algorithm_t alg,
5781                                               const unsigned char* raw_psk, size_t raw_psk_length,
5782                                               const unsigned char* seed, size_t seed_length,
5783                                               const unsigned char* label, size_t label_length,
5784                                               const unsigned char* other_secret,
5785                                               size_t other_secret_length,
5786                                               size_t capacity )
5787 {
5788     psa_status_t status;
5789 
5790     status = psa_key_derivation_setup( derivation, alg );
5791     if( status != PSA_SUCCESS )
5792         return( status );
5793 
5794     if( PSA_ALG_IS_TLS12_PRF( alg ) || PSA_ALG_IS_TLS12_PSK_TO_MS( alg ) )
5795     {
5796         status = psa_key_derivation_input_bytes( derivation,
5797                                                  PSA_KEY_DERIVATION_INPUT_SEED,
5798                                                  seed, seed_length );
5799         if( status != PSA_SUCCESS )
5800             return( status );
5801 
5802         if ( other_secret != NULL )
5803         {
5804             status = psa_key_derivation_input_bytes( derivation,
5805                                         PSA_KEY_DERIVATION_INPUT_OTHER_SECRET,
5806                                         other_secret, other_secret_length );
5807             if( status != PSA_SUCCESS )
5808                 return( status );
5809         }
5810 
5811         if( mbedtls_svc_key_id_is_null( key ) )
5812         {
5813             status = psa_key_derivation_input_bytes(
5814                 derivation, PSA_KEY_DERIVATION_INPUT_SECRET,
5815                 raw_psk, raw_psk_length );
5816         }
5817         else
5818         {
5819             status = psa_key_derivation_input_key(
5820                 derivation, PSA_KEY_DERIVATION_INPUT_SECRET, key );
5821         }
5822         if( status != PSA_SUCCESS )
5823             return( status );
5824 
5825         status = psa_key_derivation_input_bytes( derivation,
5826                                                  PSA_KEY_DERIVATION_INPUT_LABEL,
5827                                                  label, label_length );
5828         if( status != PSA_SUCCESS )
5829             return( status );
5830     }
5831     else
5832     {
5833         return( PSA_ERROR_NOT_SUPPORTED );
5834     }
5835 
5836     status = psa_key_derivation_set_capacity( derivation, capacity );
5837     if( status != PSA_SUCCESS )
5838         return( status );
5839 
5840     return( PSA_SUCCESS );
5841 }
5842 
5843 #if defined(PSA_WANT_ALG_SHA_384) || \
5844     defined(PSA_WANT_ALG_SHA_256)
5845 MBEDTLS_CHECK_RETURN_CRITICAL
tls_prf_generic(mbedtls_md_type_t md_type,const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)5846 static int tls_prf_generic( mbedtls_md_type_t md_type,
5847                             const unsigned char *secret, size_t slen,
5848                             const char *label,
5849                             const unsigned char *random, size_t rlen,
5850                             unsigned char *dstbuf, size_t dlen )
5851 {
5852     psa_status_t status;
5853     psa_algorithm_t alg;
5854     mbedtls_svc_key_id_t master_key = MBEDTLS_SVC_KEY_ID_INIT;
5855     psa_key_derivation_operation_t derivation =
5856         PSA_KEY_DERIVATION_OPERATION_INIT;
5857 
5858     if( md_type == MBEDTLS_MD_SHA384 )
5859         alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_384);
5860     else
5861         alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_256);
5862 
5863     /* Normally a "secret" should be long enough to be impossible to
5864      * find by brute force, and in particular should not be empty. But
5865      * this PRF is also used to derive an IV, in particular in EAP-TLS,
5866      * and for this use case it makes sense to have a 0-length "secret".
5867      * Since the key API doesn't allow importing a key of length 0,
5868      * keep master_key=0, which setup_psa_key_derivation() understands
5869      * to mean a 0-length "secret" input. */
5870     if( slen != 0 )
5871     {
5872         psa_key_attributes_t key_attributes = psa_key_attributes_init();
5873         psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
5874         psa_set_key_algorithm( &key_attributes, alg );
5875         psa_set_key_type( &key_attributes, PSA_KEY_TYPE_DERIVE );
5876 
5877         status = psa_import_key( &key_attributes, secret, slen, &master_key );
5878         if( status != PSA_SUCCESS )
5879             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5880     }
5881 
5882     status = setup_psa_key_derivation( &derivation,
5883                                        master_key, alg,
5884                                        NULL, 0,
5885                                        random, rlen,
5886                                        (unsigned char const *) label,
5887                                        (size_t) strlen( label ),
5888                                        NULL, 0,
5889                                        dlen );
5890     if( status != PSA_SUCCESS )
5891     {
5892         psa_key_derivation_abort( &derivation );
5893         psa_destroy_key( master_key );
5894         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5895     }
5896 
5897     status = psa_key_derivation_output_bytes( &derivation, dstbuf, dlen );
5898     if( status != PSA_SUCCESS )
5899     {
5900         psa_key_derivation_abort( &derivation );
5901         psa_destroy_key( master_key );
5902         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5903     }
5904 
5905     status = psa_key_derivation_abort( &derivation );
5906     if( status != PSA_SUCCESS )
5907     {
5908         psa_destroy_key( master_key );
5909         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5910     }
5911 
5912     if( ! mbedtls_svc_key_id_is_null( master_key ) )
5913         status = psa_destroy_key( master_key );
5914     if( status != PSA_SUCCESS )
5915         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5916 
5917     return( 0 );
5918 }
5919 #endif /* PSA_WANT_ALG_SHA_256 || PSA_WANT_ALG_SHA_384 */
5920 #else /* MBEDTLS_USE_PSA_CRYPTO */
5921 
5922 #if defined(MBEDTLS_MD_C) &&       \
5923     ( defined(MBEDTLS_SHA256_C) || \
5924       defined(MBEDTLS_SHA384_C) )
5925 MBEDTLS_CHECK_RETURN_CRITICAL
tls_prf_generic(mbedtls_md_type_t md_type,const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)5926 static int tls_prf_generic( mbedtls_md_type_t md_type,
5927                             const unsigned char *secret, size_t slen,
5928                             const char *label,
5929                             const unsigned char *random, size_t rlen,
5930                             unsigned char *dstbuf, size_t dlen )
5931 {
5932     size_t nb;
5933     size_t i, j, k, md_len;
5934     unsigned char *tmp;
5935     size_t tmp_len = 0;
5936     unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
5937     const mbedtls_md_info_t *md_info;
5938     mbedtls_md_context_t md_ctx;
5939     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5940 
5941     mbedtls_md_init( &md_ctx );
5942 
5943     if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
5944         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
5945 
5946     md_len = mbedtls_md_get_size( md_info );
5947 
5948     tmp_len = md_len + strlen( label ) + rlen;
5949     tmp = mbedtls_calloc( 1, tmp_len );
5950     if( tmp == NULL )
5951     {
5952         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
5953         goto exit;
5954     }
5955 
5956     nb = strlen( label );
5957     memcpy( tmp + md_len, label, nb );
5958     memcpy( tmp + md_len + nb, random, rlen );
5959     nb += rlen;
5960 
5961     /*
5962      * Compute P_<hash>(secret, label + random)[0..dlen]
5963      */
5964     if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
5965         goto exit;
5966 
5967     ret = mbedtls_md_hmac_starts( &md_ctx, secret, slen );
5968     if( ret != 0 )
5969         goto exit;
5970     ret = mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
5971     if( ret != 0 )
5972         goto exit;
5973     ret = mbedtls_md_hmac_finish( &md_ctx, tmp );
5974     if( ret != 0 )
5975         goto exit;
5976 
5977     for( i = 0; i < dlen; i += md_len )
5978     {
5979         ret = mbedtls_md_hmac_reset ( &md_ctx );
5980         if( ret != 0 )
5981             goto exit;
5982         ret = mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
5983         if( ret != 0 )
5984             goto exit;
5985         ret = mbedtls_md_hmac_finish( &md_ctx, h_i );
5986         if( ret != 0 )
5987             goto exit;
5988 
5989         ret = mbedtls_md_hmac_reset ( &md_ctx );
5990         if( ret != 0 )
5991             goto exit;
5992         ret = mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
5993         if( ret != 0 )
5994             goto exit;
5995         ret = mbedtls_md_hmac_finish( &md_ctx, tmp );
5996         if( ret != 0 )
5997             goto exit;
5998 
5999         k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
6000 
6001         for( j = 0; j < k; j++ )
6002             dstbuf[i + j]  = h_i[j];
6003     }
6004 
6005 exit:
6006     mbedtls_md_free( &md_ctx );
6007 
6008     if ( tmp != NULL )
6009         mbedtls_platform_zeroize( tmp, tmp_len );
6010 
6011     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
6012 
6013     mbedtls_free( tmp );
6014 
6015     return( ret );
6016 }
6017 #endif /* MBEDTLS_MD_C && ( MBEDTLS_SHA256_C || MBEDTLS_SHA384_C ) */
6018 #endif /* MBEDTLS_USE_PSA_CRYPTO */
6019 
6020 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
6021 MBEDTLS_CHECK_RETURN_CRITICAL
tls_prf_sha256(const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)6022 static int tls_prf_sha256( const unsigned char *secret, size_t slen,
6023                            const char *label,
6024                            const unsigned char *random, size_t rlen,
6025                            unsigned char *dstbuf, size_t dlen )
6026 {
6027     return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
6028                              label, random, rlen, dstbuf, dlen ) );
6029 }
6030 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
6031 
6032 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
6033 MBEDTLS_CHECK_RETURN_CRITICAL
tls_prf_sha384(const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)6034 static int tls_prf_sha384( const unsigned char *secret, size_t slen,
6035                            const char *label,
6036                            const unsigned char *random, size_t rlen,
6037                            unsigned char *dstbuf, size_t dlen )
6038 {
6039     return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
6040                              label, random, rlen, dstbuf, dlen ) );
6041 }
6042 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
6043 
6044 /*
6045  * Set appropriate PRF function and other SSL / TLS1.2 functions
6046  *
6047  * Inputs:
6048  * - hash associated with the ciphersuite (only used by TLS 1.2)
6049  *
6050  * Outputs:
6051  * - the tls_prf, calc_verify and calc_finished members of handshake structure
6052  */
6053 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_set_handshake_prfs(mbedtls_ssl_handshake_params * handshake,mbedtls_md_type_t hash)6054 static int ssl_set_handshake_prfs( mbedtls_ssl_handshake_params *handshake,
6055                                    mbedtls_md_type_t hash )
6056 {
6057 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
6058     if( hash == MBEDTLS_MD_SHA384 )
6059     {
6060         handshake->tls_prf = tls_prf_sha384;
6061         handshake->calc_verify = ssl_calc_verify_tls_sha384;
6062         handshake->calc_finished = ssl_calc_finished_tls_sha384;
6063     }
6064     else
6065 #endif
6066 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
6067     {
6068         (void) hash;
6069         handshake->tls_prf = tls_prf_sha256;
6070         handshake->calc_verify = ssl_calc_verify_tls_sha256;
6071         handshake->calc_finished = ssl_calc_finished_tls_sha256;
6072     }
6073 #else
6074     {
6075         (void) handshake;
6076         (void) hash;
6077         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6078     }
6079 #endif
6080 
6081     return( 0 );
6082 }
6083 
6084 /*
6085  * Compute master secret if needed
6086  *
6087  * Parameters:
6088  * [in/out] handshake
6089  *          [in] resume, premaster, extended_ms, calc_verify, tls_prf
6090  *               (PSA-PSK) ciphersuite_info, psk_opaque
6091  *          [out] premaster (cleared)
6092  * [out] master
6093  * [in] ssl: optionally used for debugging, EMS and PSA-PSK
6094  *      debug: conf->f_dbg, conf->p_dbg
6095  *      EMS: passed to calc_verify (debug + session_negotiate)
6096  *      PSA-PSA: conf
6097  */
6098 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_compute_master(mbedtls_ssl_handshake_params * handshake,unsigned char * master,const mbedtls_ssl_context * ssl)6099 static int ssl_compute_master( mbedtls_ssl_handshake_params *handshake,
6100                                unsigned char *master,
6101                                const mbedtls_ssl_context *ssl )
6102 {
6103     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6104 
6105     /* cf. RFC 5246, Section 8.1:
6106      * "The master secret is always exactly 48 bytes in length." */
6107     size_t const master_secret_len = 48;
6108 
6109 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
6110     unsigned char session_hash[48];
6111 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
6112 
6113     /* The label for the KDF used for key expansion.
6114      * This is either "master secret" or "extended master secret"
6115      * depending on whether the Extended Master Secret extension
6116      * is used. */
6117     char const *lbl = "master secret";
6118 
6119     /* The seed for the KDF used for key expansion.
6120      * - If the Extended Master Secret extension is not used,
6121      *   this is ClientHello.Random + ServerHello.Random
6122      *   (see Sect. 8.1 in RFC 5246).
6123      * - If the Extended Master Secret extension is used,
6124      *   this is the transcript of the handshake so far.
6125      *   (see Sect. 4 in RFC 7627). */
6126     unsigned char const *seed = handshake->randbytes;
6127     size_t seed_len = 64;
6128 
6129 #if !defined(MBEDTLS_DEBUG_C) &&                    \
6130     !defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \
6131     !(defined(MBEDTLS_USE_PSA_CRYPTO) &&            \
6132       defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED))
6133     ssl = NULL; /* make sure we don't use it except for those cases */
6134     (void) ssl;
6135 #endif
6136 
6137     if( handshake->resume != 0 )
6138     {
6139         MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
6140         return( 0 );
6141     }
6142 
6143 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
6144     if( handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
6145     {
6146         lbl  = "extended master secret";
6147         seed = session_hash;
6148         handshake->calc_verify( ssl, session_hash, &seed_len );
6149 
6150         MBEDTLS_SSL_DEBUG_BUF( 3, "session hash for extended master secret",
6151                                   session_hash, seed_len );
6152     }
6153 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
6154 
6155 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                   \
6156     defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
6157     if( mbedtls_ssl_ciphersuite_uses_psk( handshake->ciphersuite_info ) == 1 )
6158     {
6159         /* Perform PSK-to-MS expansion in a single step. */
6160         psa_status_t status;
6161         psa_algorithm_t alg;
6162         mbedtls_svc_key_id_t psk;
6163         psa_key_derivation_operation_t derivation =
6164             PSA_KEY_DERIVATION_OPERATION_INIT;
6165         mbedtls_md_type_t hash_alg = handshake->ciphersuite_info->mac;
6166 
6167         MBEDTLS_SSL_DEBUG_MSG( 2, ( "perform PSA-based PSK-to-MS expansion" ) );
6168 
6169         psk = mbedtls_ssl_get_opaque_psk( ssl );
6170 
6171         if( hash_alg == MBEDTLS_MD_SHA384 )
6172             alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384);
6173         else
6174             alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256);
6175 
6176         size_t other_secret_len = 0;
6177         unsigned char* other_secret = NULL;
6178 
6179         switch( handshake->ciphersuite_info->key_exchange )
6180         {
6181             /* Provide other secret.
6182              * Other secret is stored in premaster, where first 2 bytes hold the
6183              * length of the other key.
6184              */
6185             case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
6186                 /* For RSA-PSK other key length is always 48 bytes. */
6187                 other_secret_len = 48;
6188                 other_secret = handshake->premaster + 2;
6189                 break;
6190             case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
6191             case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
6192                 other_secret_len = MBEDTLS_GET_UINT16_BE(handshake->premaster, 0);
6193                 other_secret = handshake->premaster + 2;
6194                 break;
6195             default:
6196                 break;
6197         }
6198 
6199         status = setup_psa_key_derivation( &derivation, psk, alg,
6200                                            ssl->conf->psk, ssl->conf->psk_len,
6201                                            seed, seed_len,
6202                                            (unsigned char const *) lbl,
6203                                            (size_t) strlen( lbl ),
6204                                            other_secret, other_secret_len,
6205                                            master_secret_len );
6206         if( status != PSA_SUCCESS )
6207         {
6208             psa_key_derivation_abort( &derivation );
6209             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
6210         }
6211 
6212         status = psa_key_derivation_output_bytes( &derivation,
6213                                                   master,
6214                                                   master_secret_len );
6215         if( status != PSA_SUCCESS )
6216         {
6217             psa_key_derivation_abort( &derivation );
6218             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
6219         }
6220 
6221         status = psa_key_derivation_abort( &derivation );
6222         if( status != PSA_SUCCESS )
6223             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
6224     }
6225     else
6226 #endif
6227     {
6228 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                              \
6229     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
6230         if( handshake->ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
6231         {
6232             psa_status_t status;
6233             psa_algorithm_t alg = PSA_ALG_TLS12_ECJPAKE_TO_PMS;
6234             psa_key_derivation_operation_t derivation =
6235                 PSA_KEY_DERIVATION_OPERATION_INIT;
6236 
6237             MBEDTLS_SSL_DEBUG_MSG( 2, ( "perform PSA-based PMS KDF for ECJPAKE" ) );
6238 
6239             handshake->pmslen = PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE;
6240 
6241             status = psa_key_derivation_setup( &derivation, alg );
6242             if( status != PSA_SUCCESS )
6243                 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
6244 
6245             status = psa_key_derivation_set_capacity( &derivation,
6246                                             PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE );
6247             if( status != PSA_SUCCESS )
6248             {
6249                 psa_key_derivation_abort( &derivation );
6250                 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
6251             }
6252 
6253             status = psa_pake_get_implicit_key( &handshake->psa_pake_ctx,
6254                                                 &derivation );
6255             if( status != PSA_SUCCESS )
6256             {
6257                 psa_key_derivation_abort( &derivation );
6258                 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
6259             }
6260 
6261             status = psa_key_derivation_output_bytes( &derivation,
6262                                                       handshake->premaster,
6263                                                       handshake->pmslen );
6264             if( status != PSA_SUCCESS )
6265             {
6266                 psa_key_derivation_abort( &derivation );
6267                 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
6268             }
6269 
6270             status = psa_key_derivation_abort( &derivation );
6271             if( status != PSA_SUCCESS )
6272             {
6273                 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
6274             }
6275         }
6276 #endif
6277         ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
6278                                   lbl, seed, seed_len,
6279                                   master,
6280                                   master_secret_len );
6281         if( ret != 0 )
6282         {
6283             MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
6284             return( ret );
6285         }
6286 
6287         MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret",
6288                                handshake->premaster,
6289                                handshake->pmslen );
6290 
6291         mbedtls_platform_zeroize( handshake->premaster,
6292                                   sizeof(handshake->premaster) );
6293     }
6294 
6295     return( 0 );
6296 }
6297 
mbedtls_ssl_derive_keys(mbedtls_ssl_context * ssl)6298 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
6299 {
6300     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6301     const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
6302         ssl->handshake->ciphersuite_info;
6303 
6304     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
6305 
6306     /* Set PRF, calc_verify and calc_finished function pointers */
6307     ret = ssl_set_handshake_prfs( ssl->handshake,
6308                                   ciphersuite_info->mac );
6309     if( ret != 0 )
6310     {
6311         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_set_handshake_prfs", ret );
6312         return( ret );
6313     }
6314 
6315     /* Compute master secret if needed */
6316     ret = ssl_compute_master( ssl->handshake,
6317                               ssl->session_negotiate->master,
6318                               ssl );
6319     if( ret != 0 )
6320     {
6321         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compute_master", ret );
6322         return( ret );
6323     }
6324 
6325     /* Swap the client and server random values:
6326      * - MS derivation wanted client+server (RFC 5246 8.1)
6327      * - key derivation wants server+client (RFC 5246 6.3) */
6328     {
6329         unsigned char tmp[64];
6330         memcpy( tmp, ssl->handshake->randbytes, 64 );
6331         memcpy( ssl->handshake->randbytes, tmp + 32, 32 );
6332         memcpy( ssl->handshake->randbytes + 32, tmp, 32 );
6333         mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
6334     }
6335 
6336     /* Populate transform structure */
6337     ret = ssl_tls12_populate_transform( ssl->transform_negotiate,
6338                                         ssl->session_negotiate->ciphersuite,
6339                                         ssl->session_negotiate->master,
6340 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
6341                                         ssl->session_negotiate->encrypt_then_mac,
6342 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
6343                                         ssl->handshake->tls_prf,
6344                                         ssl->handshake->randbytes,
6345                                         ssl->tls_version,
6346                                         ssl->conf->endpoint,
6347                                         ssl );
6348     if( ret != 0 )
6349     {
6350         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_tls12_populate_transform", ret );
6351         return( ret );
6352     }
6353 
6354     /* We no longer need Server/ClientHello.random values */
6355     mbedtls_platform_zeroize( ssl->handshake->randbytes,
6356                       sizeof( ssl->handshake->randbytes ) );
6357 
6358     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
6359 
6360     return( 0 );
6361 }
6362 
mbedtls_ssl_set_calc_verify_md(mbedtls_ssl_context * ssl,int md)6363 int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
6364 {
6365     switch( md )
6366     {
6367 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
6368         case MBEDTLS_SSL_HASH_SHA384:
6369             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
6370             break;
6371 #endif
6372 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
6373         case MBEDTLS_SSL_HASH_SHA256:
6374             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
6375             break;
6376 #endif
6377         default:
6378             return( -1 );
6379     }
6380 #if !defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
6381     !defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
6382     (void) ssl;
6383 #endif
6384     return( 0 );
6385 }
6386 
6387 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
ssl_calc_verify_tls_sha256(const mbedtls_ssl_context * ssl,unsigned char * hash,size_t * hlen)6388 void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *ssl,
6389                                  unsigned char *hash,
6390                                  size_t *hlen )
6391 {
6392 #if defined(MBEDTLS_USE_PSA_CRYPTO)
6393     size_t hash_size;
6394     psa_status_t status;
6395     psa_hash_operation_t sha256_psa = psa_hash_operation_init();
6396 
6397     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> PSA calc verify sha256" ) );
6398     status = psa_hash_clone( &ssl->handshake->fin_sha256_psa, &sha256_psa );
6399     if( status != PSA_SUCCESS )
6400     {
6401         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
6402         return;
6403     }
6404 
6405     status = psa_hash_finish( &sha256_psa, hash, 32, &hash_size );
6406     if( status != PSA_SUCCESS )
6407     {
6408         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
6409         return;
6410     }
6411 
6412     *hlen = 32;
6413     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated verify result", hash, *hlen );
6414     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= PSA calc verify" ) );
6415 #else
6416     mbedtls_sha256_context sha256;
6417 
6418     mbedtls_sha256_init( &sha256 );
6419 
6420     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
6421 
6422     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
6423     mbedtls_sha256_finish( &sha256, hash );
6424 
6425     *hlen = 32;
6426 
6427     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
6428     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
6429 
6430     mbedtls_sha256_free( &sha256 );
6431 #endif /* MBEDTLS_USE_PSA_CRYPTO */
6432     return;
6433 }
6434 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
6435 
6436 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
ssl_calc_verify_tls_sha384(const mbedtls_ssl_context * ssl,unsigned char * hash,size_t * hlen)6437 void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *ssl,
6438                                  unsigned char *hash,
6439                                  size_t *hlen )
6440 {
6441 #if defined(MBEDTLS_USE_PSA_CRYPTO)
6442     size_t hash_size;
6443     psa_status_t status;
6444     psa_hash_operation_t sha384_psa = psa_hash_operation_init();
6445 
6446     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> PSA calc verify sha384" ) );
6447     status = psa_hash_clone( &ssl->handshake->fin_sha384_psa, &sha384_psa );
6448     if( status != PSA_SUCCESS )
6449     {
6450         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
6451         return;
6452     }
6453 
6454     status = psa_hash_finish( &sha384_psa, hash, 48, &hash_size );
6455     if( status != PSA_SUCCESS )
6456     {
6457         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
6458         return;
6459     }
6460 
6461     *hlen = 48;
6462     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated verify result", hash, *hlen );
6463     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= PSA calc verify" ) );
6464 #else
6465     mbedtls_sha512_context sha512;
6466 
6467     mbedtls_sha512_init( &sha512 );
6468 
6469     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
6470 
6471     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha384 );
6472     mbedtls_sha512_finish( &sha512, hash );
6473 
6474     *hlen = 48;
6475 
6476     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
6477     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
6478 
6479     mbedtls_sha512_free( &sha512 );
6480 #endif /* MBEDTLS_USE_PSA_CRYPTO */
6481     return;
6482 }
6483 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
6484 
6485 #if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                      \
6486     defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
mbedtls_ssl_psk_derive_premaster(mbedtls_ssl_context * ssl,mbedtls_key_exchange_type_t key_ex)6487 int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
6488 {
6489     unsigned char *p = ssl->handshake->premaster;
6490     unsigned char *end = p + sizeof( ssl->handshake->premaster );
6491     const unsigned char *psk = NULL;
6492     size_t psk_len = 0;
6493     int psk_ret = mbedtls_ssl_get_psk( ssl, &psk, &psk_len );
6494 
6495     if( psk_ret == MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED )
6496     {
6497         /*
6498          * This should never happen because the existence of a PSK is always
6499          * checked before calling this function.
6500          *
6501          * The exception is opaque DHE-PSK. For DHE-PSK fill premaster with
6502          * the shared secret without PSK.
6503          */
6504         if ( key_ex != MBEDTLS_KEY_EXCHANGE_DHE_PSK )
6505         {
6506             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6507             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6508         }
6509     }
6510 
6511     /*
6512      * PMS = struct {
6513      *     opaque other_secret<0..2^16-1>;
6514      *     opaque psk<0..2^16-1>;
6515      * };
6516      * with "other_secret" depending on the particular key exchange
6517      */
6518 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
6519     if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
6520     {
6521         if( end - p < 2 )
6522             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6523 
6524         MBEDTLS_PUT_UINT16_BE( psk_len, p, 0 );
6525         p += 2;
6526 
6527         if( end < p || (size_t)( end - p ) < psk_len )
6528             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6529 
6530         memset( p, 0, psk_len );
6531         p += psk_len;
6532     }
6533     else
6534 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
6535 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
6536     if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
6537     {
6538         /*
6539          * other_secret already set by the ClientKeyExchange message,
6540          * and is 48 bytes long
6541          */
6542         if( end - p < 2 )
6543             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6544 
6545         *p++ = 0;
6546         *p++ = 48;
6547         p += 48;
6548     }
6549     else
6550 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
6551 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
6552     if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
6553     {
6554         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6555         size_t len;
6556 
6557         /* Write length only when we know the actual value */
6558         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
6559                                       p + 2, end - ( p + 2 ), &len,
6560                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
6561         {
6562             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
6563             return( ret );
6564         }
6565         MBEDTLS_PUT_UINT16_BE( len, p, 0 );
6566         p += 2 + len;
6567 
6568         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
6569     }
6570     else
6571 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
6572 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
6573     if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
6574     {
6575         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6576         size_t zlen;
6577 
6578         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
6579                                        p + 2, end - ( p + 2 ),
6580                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
6581         {
6582             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
6583             return( ret );
6584         }
6585 
6586         MBEDTLS_PUT_UINT16_BE( zlen, p, 0 );
6587         p += 2 + zlen;
6588 
6589         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
6590                                 MBEDTLS_DEBUG_ECDH_Z );
6591     }
6592     else
6593 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
6594     {
6595         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6596         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6597     }
6598 
6599     /* opaque psk<0..2^16-1>; */
6600     if( end - p < 2 )
6601         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6602 
6603     MBEDTLS_PUT_UINT16_BE( psk_len, p, 0 );
6604     p += 2;
6605 
6606     if( end < p || (size_t)( end - p ) < psk_len )
6607         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6608 
6609     memcpy( p, psk, psk_len );
6610     p += psk_len;
6611 
6612     ssl->handshake->pmslen = p - ssl->handshake->premaster;
6613 
6614     return( 0 );
6615 }
6616 #endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
6617 
6618 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
6619 MBEDTLS_CHECK_RETURN_CRITICAL
6620 static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
6621 
6622 #if defined(MBEDTLS_SSL_PROTO_DTLS)
mbedtls_ssl_resend_hello_request(mbedtls_ssl_context * ssl)6623 int mbedtls_ssl_resend_hello_request( mbedtls_ssl_context *ssl )
6624 {
6625     /* If renegotiation is not enforced, retransmit until we would reach max
6626      * timeout if we were using the usual handshake doubling scheme */
6627     if( ssl->conf->renego_max_records < 0 )
6628     {
6629         uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
6630         unsigned char doublings = 1;
6631 
6632         while( ratio != 0 )
6633         {
6634             ++doublings;
6635             ratio >>= 1;
6636         }
6637 
6638         if( ++ssl->renego_records_seen > doublings )
6639         {
6640             MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
6641             return( 0 );
6642         }
6643     }
6644 
6645     return( ssl_write_hello_request( ssl ) );
6646 }
6647 #endif
6648 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
6649 
6650 /*
6651  * Handshake functions
6652  */
6653 #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
6654 /* No certificate support -> dummy functions */
mbedtls_ssl_write_certificate(mbedtls_ssl_context * ssl)6655 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
6656 {
6657     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
6658         ssl->handshake->ciphersuite_info;
6659 
6660     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
6661 
6662     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
6663     {
6664         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
6665         ssl->state++;
6666         return( 0 );
6667     }
6668 
6669     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6670     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6671 }
6672 
mbedtls_ssl_parse_certificate(mbedtls_ssl_context * ssl)6673 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
6674 {
6675     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
6676         ssl->handshake->ciphersuite_info;
6677 
6678     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
6679 
6680     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
6681     {
6682         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
6683         ssl->state++;
6684         return( 0 );
6685     }
6686 
6687     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6688     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6689 }
6690 
6691 #else /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
6692 /* Some certificate support -> implement write and parse */
6693 
mbedtls_ssl_write_certificate(mbedtls_ssl_context * ssl)6694 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
6695 {
6696     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6697     size_t i, n;
6698     const mbedtls_x509_crt *crt;
6699     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
6700         ssl->handshake->ciphersuite_info;
6701 
6702     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
6703 
6704     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
6705     {
6706         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
6707         ssl->state++;
6708         return( 0 );
6709     }
6710 
6711 #if defined(MBEDTLS_SSL_CLI_C)
6712     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
6713     {
6714         if( ssl->handshake->client_auth == 0 )
6715         {
6716             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
6717             ssl->state++;
6718             return( 0 );
6719         }
6720     }
6721 #endif /* MBEDTLS_SSL_CLI_C */
6722 #if defined(MBEDTLS_SSL_SRV_C)
6723     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6724     {
6725         if( mbedtls_ssl_own_cert( ssl ) == NULL )
6726         {
6727             /* Should never happen because we shouldn't have picked the
6728              * ciphersuite if we don't have a certificate. */
6729             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6730         }
6731     }
6732 #endif
6733 
6734     MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
6735 
6736     /*
6737      *     0  .  0    handshake type
6738      *     1  .  3    handshake length
6739      *     4  .  6    length of all certs
6740      *     7  .  9    length of cert. 1
6741      *    10  . n-1   peer certificate
6742      *     n  . n+2   length of cert. 2
6743      *    n+3 . ...   upper level cert, etc.
6744      */
6745     i = 7;
6746     crt = mbedtls_ssl_own_cert( ssl );
6747 
6748     while( crt != NULL )
6749     {
6750         n = crt->raw.len;
6751         if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i )
6752         {
6753             MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %" MBEDTLS_PRINTF_SIZET
6754                                         " > %" MBEDTLS_PRINTF_SIZET,
6755                            i + 3 + n, (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN ) );
6756             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
6757         }
6758 
6759         ssl->out_msg[i    ] = MBEDTLS_BYTE_2( n );
6760         ssl->out_msg[i + 1] = MBEDTLS_BYTE_1( n );
6761         ssl->out_msg[i + 2] = MBEDTLS_BYTE_0( n );
6762 
6763         i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
6764         i += n; crt = crt->next;
6765     }
6766 
6767     ssl->out_msg[4]  = MBEDTLS_BYTE_2( i - 7 );
6768     ssl->out_msg[5]  = MBEDTLS_BYTE_1( i - 7 );
6769     ssl->out_msg[6]  = MBEDTLS_BYTE_0( i - 7 );
6770 
6771     ssl->out_msglen  = i;
6772     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
6773     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;
6774 
6775     ssl->state++;
6776 
6777     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
6778     {
6779         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
6780         return( ret );
6781     }
6782 
6783     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
6784 
6785     return( ret );
6786 }
6787 
6788 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
6789 
6790 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
6791 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_peer_crt_unchanged(mbedtls_ssl_context * ssl,unsigned char * crt_buf,size_t crt_buf_len)6792 static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl,
6793                                          unsigned char *crt_buf,
6794                                          size_t crt_buf_len )
6795 {
6796     mbedtls_x509_crt const * const peer_crt = ssl->session->peer_cert;
6797 
6798     if( peer_crt == NULL )
6799         return( -1 );
6800 
6801     if( peer_crt->raw.len != crt_buf_len )
6802         return( -1 );
6803 
6804     return( memcmp( peer_crt->raw.p, crt_buf, peer_crt->raw.len ) );
6805 }
6806 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
6807 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_peer_crt_unchanged(mbedtls_ssl_context * ssl,unsigned char * crt_buf,size_t crt_buf_len)6808 static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl,
6809                                          unsigned char *crt_buf,
6810                                          size_t crt_buf_len )
6811 {
6812     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6813     unsigned char const * const peer_cert_digest =
6814         ssl->session->peer_cert_digest;
6815     mbedtls_md_type_t const peer_cert_digest_type =
6816         ssl->session->peer_cert_digest_type;
6817     mbedtls_md_info_t const * const digest_info =
6818         mbedtls_md_info_from_type( peer_cert_digest_type );
6819     unsigned char tmp_digest[MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN];
6820     size_t digest_len;
6821 
6822     if( peer_cert_digest == NULL || digest_info == NULL )
6823         return( -1 );
6824 
6825     digest_len = mbedtls_md_get_size( digest_info );
6826     if( digest_len > MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN )
6827         return( -1 );
6828 
6829     ret = mbedtls_md( digest_info, crt_buf, crt_buf_len, tmp_digest );
6830     if( ret != 0 )
6831         return( -1 );
6832 
6833     return( memcmp( tmp_digest, peer_cert_digest, digest_len ) );
6834 }
6835 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
6836 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
6837 
6838 /*
6839  * Once the certificate message is read, parse it into a cert chain and
6840  * perform basic checks, but leave actual verification to the caller
6841  */
6842 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_certificate_chain(mbedtls_ssl_context * ssl,mbedtls_x509_crt * chain)6843 static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl,
6844                                         mbedtls_x509_crt *chain )
6845 {
6846     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6847 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
6848     int crt_cnt=0;
6849 #endif
6850     size_t i, n;
6851     uint8_t alert;
6852 
6853     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
6854     {
6855         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
6856         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6857                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
6858         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6859     }
6860 
6861     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE  )
6862     {
6863         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6864                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
6865         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6866     }
6867 
6868     if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
6869     {
6870         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
6871         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6872                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
6873         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
6874     }
6875 
6876     i = mbedtls_ssl_hs_hdr_len( ssl );
6877 
6878     /*
6879      * Same message structure as in mbedtls_ssl_write_certificate()
6880      */
6881     n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
6882 
6883     if( ssl->in_msg[i] != 0 ||
6884         ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
6885     {
6886         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
6887         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6888                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
6889         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
6890     }
6891 
6892     /* Make &ssl->in_msg[i] point to the beginning of the CRT chain. */
6893     i += 3;
6894 
6895     /* Iterate through and parse the CRTs in the provided chain. */
6896     while( i < ssl->in_hslen )
6897     {
6898         /* Check that there's room for the next CRT's length fields. */
6899         if ( i + 3 > ssl->in_hslen ) {
6900             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
6901             mbedtls_ssl_send_alert_message( ssl,
6902                               MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6903                               MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
6904             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
6905         }
6906         /* In theory, the CRT can be up to 2**24 Bytes, but we don't support
6907          * anything beyond 2**16 ~ 64K. */
6908         if( ssl->in_msg[i] != 0 )
6909         {
6910             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
6911             mbedtls_ssl_send_alert_message( ssl,
6912                             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6913                             MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT );
6914             return( MBEDTLS_ERR_SSL_BAD_CERTIFICATE );
6915         }
6916 
6917         /* Read length of the next CRT in the chain. */
6918         n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
6919             | (unsigned int) ssl->in_msg[i + 2];
6920         i += 3;
6921 
6922         if( n < 128 || i + n > ssl->in_hslen )
6923         {
6924             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
6925             mbedtls_ssl_send_alert_message( ssl,
6926                                  MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6927                                  MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
6928             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
6929         }
6930 
6931         /* Check if we're handling the first CRT in the chain. */
6932 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
6933         if( crt_cnt++ == 0 &&
6934             ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
6935             ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
6936         {
6937             /* During client-side renegotiation, check that the server's
6938              * end-CRTs hasn't changed compared to the initial handshake,
6939              * mitigating the triple handshake attack. On success, reuse
6940              * the original end-CRT instead of parsing it again. */
6941             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Check that peer CRT hasn't changed during renegotiation" ) );
6942             if( ssl_check_peer_crt_unchanged( ssl,
6943                                               &ssl->in_msg[i],
6944                                               n ) != 0 )
6945             {
6946                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
6947                 mbedtls_ssl_send_alert_message( ssl,
6948                                                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6949                                                 MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
6950                 return( MBEDTLS_ERR_SSL_BAD_CERTIFICATE );
6951             }
6952 
6953             /* Now we can safely free the original chain. */
6954             ssl_clear_peer_cert( ssl->session );
6955         }
6956 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
6957 
6958         /* Parse the next certificate in the chain. */
6959 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
6960         ret = mbedtls_x509_crt_parse_der( chain, ssl->in_msg + i, n );
6961 #else
6962         /* If we don't need to store the CRT chain permanently, parse
6963          * it in-place from the input buffer instead of making a copy. */
6964         ret = mbedtls_x509_crt_parse_der_nocopy( chain, ssl->in_msg + i, n );
6965 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
6966         switch( ret )
6967         {
6968             case 0: /*ok*/
6969             case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
6970                 /* Ignore certificate with an unknown algorithm: maybe a
6971                    prior certificate was already trusted. */
6972                 break;
6973 
6974             case MBEDTLS_ERR_X509_ALLOC_FAILED:
6975                 alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
6976                 goto crt_parse_der_failed;
6977 
6978             case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
6979                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
6980                 goto crt_parse_der_failed;
6981 
6982             default:
6983                 alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
6984             crt_parse_der_failed:
6985                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
6986                 MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
6987                 return( ret );
6988         }
6989 
6990         i += n;
6991     }
6992 
6993     MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", chain );
6994     return( 0 );
6995 }
6996 
6997 #if defined(MBEDTLS_SSL_SRV_C)
6998 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_srv_check_client_no_crt_notification(mbedtls_ssl_context * ssl)6999 static int ssl_srv_check_client_no_crt_notification( mbedtls_ssl_context *ssl )
7000 {
7001     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
7002         return( -1 );
7003 
7004     if( ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
7005         ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&
7006         ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&
7007         memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
7008     {
7009         MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer has no certificate" ) );
7010         return( 0 );
7011     }
7012     return( -1 );
7013 }
7014 #endif /* MBEDTLS_SSL_SRV_C */
7015 
7016 /* Check if a certificate message is expected.
7017  * Return either
7018  * - SSL_CERTIFICATE_EXPECTED, or
7019  * - SSL_CERTIFICATE_SKIP
7020  * indicating whether a Certificate message is expected or not.
7021  */
7022 #define SSL_CERTIFICATE_EXPECTED 0
7023 #define SSL_CERTIFICATE_SKIP     1
7024 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_certificate_coordinate(mbedtls_ssl_context * ssl,int authmode)7025 static int ssl_parse_certificate_coordinate( mbedtls_ssl_context *ssl,
7026                                              int authmode )
7027 {
7028     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
7029         ssl->handshake->ciphersuite_info;
7030 
7031     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
7032         return( SSL_CERTIFICATE_SKIP );
7033 
7034 #if defined(MBEDTLS_SSL_SRV_C)
7035     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
7036     {
7037         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
7038             return( SSL_CERTIFICATE_SKIP );
7039 
7040         if( authmode == MBEDTLS_SSL_VERIFY_NONE )
7041         {
7042             ssl->session_negotiate->verify_result =
7043                 MBEDTLS_X509_BADCERT_SKIP_VERIFY;
7044             return( SSL_CERTIFICATE_SKIP );
7045         }
7046     }
7047 #else
7048     ((void) authmode);
7049 #endif /* MBEDTLS_SSL_SRV_C */
7050 
7051     return( SSL_CERTIFICATE_EXPECTED );
7052 }
7053 
7054 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_certificate_verify(mbedtls_ssl_context * ssl,int authmode,mbedtls_x509_crt * chain,void * rs_ctx)7055 static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl,
7056                                          int authmode,
7057                                          mbedtls_x509_crt *chain,
7058                                          void *rs_ctx )
7059 {
7060     int ret = 0;
7061     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
7062         ssl->handshake->ciphersuite_info;
7063     int have_ca_chain = 0;
7064 
7065     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *);
7066     void *p_vrfy;
7067 
7068     if( authmode == MBEDTLS_SSL_VERIFY_NONE )
7069         return( 0 );
7070 
7071     if( ssl->f_vrfy != NULL )
7072     {
7073         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use context-specific verification callback" ) );
7074         f_vrfy = ssl->f_vrfy;
7075         p_vrfy = ssl->p_vrfy;
7076     }
7077     else
7078     {
7079         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use configuration-specific verification callback" ) );
7080         f_vrfy = ssl->conf->f_vrfy;
7081         p_vrfy = ssl->conf->p_vrfy;
7082     }
7083 
7084     /*
7085      * Main check: verify certificate
7086      */
7087 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
7088     if( ssl->conf->f_ca_cb != NULL )
7089     {
7090         ((void) rs_ctx);
7091         have_ca_chain = 1;
7092 
7093         MBEDTLS_SSL_DEBUG_MSG( 3, ( "use CA callback for X.509 CRT verification" ) );
7094         ret = mbedtls_x509_crt_verify_with_ca_cb(
7095             chain,
7096             ssl->conf->f_ca_cb,
7097             ssl->conf->p_ca_cb,
7098             ssl->conf->cert_profile,
7099             ssl->hostname,
7100             &ssl->session_negotiate->verify_result,
7101             f_vrfy, p_vrfy );
7102     }
7103     else
7104 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
7105     {
7106         mbedtls_x509_crt *ca_chain;
7107         mbedtls_x509_crl *ca_crl;
7108 
7109 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
7110         if( ssl->handshake->sni_ca_chain != NULL )
7111         {
7112             ca_chain = ssl->handshake->sni_ca_chain;
7113             ca_crl   = ssl->handshake->sni_ca_crl;
7114         }
7115         else
7116 #endif
7117         {
7118             ca_chain = ssl->conf->ca_chain;
7119             ca_crl   = ssl->conf->ca_crl;
7120         }
7121 
7122         if( ca_chain != NULL )
7123             have_ca_chain = 1;
7124 
7125         ret = mbedtls_x509_crt_verify_restartable(
7126             chain,
7127             ca_chain, ca_crl,
7128             ssl->conf->cert_profile,
7129             ssl->hostname,
7130             &ssl->session_negotiate->verify_result,
7131             f_vrfy, p_vrfy, rs_ctx );
7132     }
7133 
7134     if( ret != 0 )
7135     {
7136         MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
7137     }
7138 
7139 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
7140     if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
7141         return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS );
7142 #endif
7143 
7144     /*
7145      * Secondary checks: always done, but change 'ret' only if it was 0
7146      */
7147 
7148 #if defined(MBEDTLS_ECP_C)
7149     {
7150         const mbedtls_pk_context *pk = &chain->pk;
7151 
7152         /* If certificate uses an EC key, make sure the curve is OK.
7153          * This is a public key, so it can't be opaque, so can_do() is a good
7154          * enough check to ensure pk_ec() is safe to use here. */
7155         if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) )
7156         {
7157             /* and in the unlikely case the above assumption no longer holds
7158              * we are making sure that pk_ec() here does not return a NULL
7159              */
7160             const mbedtls_ecp_keypair *ec = mbedtls_pk_ec( *pk );
7161             if( ec == NULL )
7162             {
7163                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_pk_ec() returned NULL" ) );
7164                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
7165             }
7166 
7167             if( mbedtls_ssl_check_curve( ssl, ec->grp.id ) != 0 )
7168             {
7169                 ssl->session_negotiate->verify_result |=
7170                     MBEDTLS_X509_BADCERT_BAD_KEY;
7171 
7172                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
7173                 if( ret == 0 )
7174                     ret = MBEDTLS_ERR_SSL_BAD_CERTIFICATE;
7175             }
7176         }
7177     }
7178 #endif /* MBEDTLS_ECP_C */
7179 
7180     if( mbedtls_ssl_check_cert_usage( chain,
7181                                       ciphersuite_info,
7182                                       ! ssl->conf->endpoint,
7183                                       &ssl->session_negotiate->verify_result ) != 0 )
7184     {
7185         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
7186         if( ret == 0 )
7187             ret = MBEDTLS_ERR_SSL_BAD_CERTIFICATE;
7188     }
7189 
7190     /* mbedtls_x509_crt_verify_with_profile is supposed to report a
7191      * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
7192      * with details encoded in the verification flags. All other kinds
7193      * of error codes, including those from the user provided f_vrfy
7194      * functions, are treated as fatal and lead to a failure of
7195      * ssl_parse_certificate even if verification was optional. */
7196     if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
7197         ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
7198           ret == MBEDTLS_ERR_SSL_BAD_CERTIFICATE ) )
7199     {
7200         ret = 0;
7201     }
7202 
7203     if( have_ca_chain == 0 && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
7204     {
7205         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
7206         ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
7207     }
7208 
7209     if( ret != 0 )
7210     {
7211         uint8_t alert;
7212 
7213         /* The certificate may have been rejected for several reasons.
7214            Pick one and send the corresponding alert. Which alert to send
7215            may be a subject of debate in some cases. */
7216         if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
7217             alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
7218         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
7219             alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
7220         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
7221             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
7222         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
7223             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
7224         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
7225             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
7226         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
7227             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
7228         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
7229             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
7230         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
7231             alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
7232         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
7233             alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
7234         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
7235             alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
7236         else
7237             alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
7238         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7239                                         alert );
7240     }
7241 
7242 #if defined(MBEDTLS_DEBUG_C)
7243     if( ssl->session_negotiate->verify_result != 0 )
7244     {
7245         MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %08x",
7246                                     (unsigned int) ssl->session_negotiate->verify_result ) );
7247     }
7248     else
7249     {
7250         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
7251     }
7252 #endif /* MBEDTLS_DEBUG_C */
7253 
7254     return( ret );
7255 }
7256 
7257 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
7258 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_remember_peer_crt_digest(mbedtls_ssl_context * ssl,unsigned char * start,size_t len)7259 static int ssl_remember_peer_crt_digest( mbedtls_ssl_context *ssl,
7260                                          unsigned char *start, size_t len )
7261 {
7262     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
7263     /* Remember digest of the peer's end-CRT. */
7264     ssl->session_negotiate->peer_cert_digest =
7265         mbedtls_calloc( 1, MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN );
7266     if( ssl->session_negotiate->peer_cert_digest == NULL )
7267     {
7268         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
7269                                     MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN ) );
7270         mbedtls_ssl_send_alert_message( ssl,
7271                                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7272                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
7273 
7274         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
7275     }
7276 
7277     ret = mbedtls_md( mbedtls_md_info_from_type(
7278                           MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE ),
7279                       start, len,
7280                       ssl->session_negotiate->peer_cert_digest );
7281 
7282     ssl->session_negotiate->peer_cert_digest_type =
7283         MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE;
7284     ssl->session_negotiate->peer_cert_digest_len =
7285         MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN;
7286 
7287     return( ret );
7288 }
7289 
7290 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_remember_peer_pubkey(mbedtls_ssl_context * ssl,unsigned char * start,size_t len)7291 static int ssl_remember_peer_pubkey( mbedtls_ssl_context *ssl,
7292                                      unsigned char *start, size_t len )
7293 {
7294     unsigned char *end = start + len;
7295     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
7296 
7297     /* Make a copy of the peer's raw public key. */
7298     mbedtls_pk_init( &ssl->handshake->peer_pubkey );
7299     ret = mbedtls_pk_parse_subpubkey( &start, end,
7300                                       &ssl->handshake->peer_pubkey );
7301     if( ret != 0 )
7302     {
7303         /* We should have parsed the public key before. */
7304         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
7305     }
7306 
7307     return( 0 );
7308 }
7309 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
7310 
mbedtls_ssl_parse_certificate(mbedtls_ssl_context * ssl)7311 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
7312 {
7313     int ret = 0;
7314     int crt_expected;
7315 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
7316     const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
7317                        ? ssl->handshake->sni_authmode
7318                        : ssl->conf->authmode;
7319 #else
7320     const int authmode = ssl->conf->authmode;
7321 #endif
7322     void *rs_ctx = NULL;
7323     mbedtls_x509_crt *chain = NULL;
7324 
7325     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
7326 
7327     crt_expected = ssl_parse_certificate_coordinate( ssl, authmode );
7328     if( crt_expected == SSL_CERTIFICATE_SKIP )
7329     {
7330         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
7331         goto exit;
7332     }
7333 
7334 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
7335     if( ssl->handshake->ecrs_enabled &&
7336         ssl->handshake->ecrs_state == ssl_ecrs_crt_verify )
7337     {
7338         chain = ssl->handshake->ecrs_peer_cert;
7339         ssl->handshake->ecrs_peer_cert = NULL;
7340         goto crt_verify;
7341     }
7342 #endif
7343 
7344     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
7345     {
7346         /* mbedtls_ssl_read_record may have sent an alert already. We
7347            let it decide whether to alert. */
7348         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
7349         goto exit;
7350     }
7351 
7352 #if defined(MBEDTLS_SSL_SRV_C)
7353     if( ssl_srv_check_client_no_crt_notification( ssl ) == 0 )
7354     {
7355         ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
7356 
7357         if( authmode != MBEDTLS_SSL_VERIFY_OPTIONAL )
7358             ret = MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE;
7359 
7360         goto exit;
7361     }
7362 #endif /* MBEDTLS_SSL_SRV_C */
7363 
7364     /* Clear existing peer CRT structure in case we tried to
7365      * reuse a session but it failed, and allocate a new one. */
7366     ssl_clear_peer_cert( ssl->session_negotiate );
7367 
7368     chain = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
7369     if( chain == NULL )
7370     {
7371         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed",
7372                                     sizeof( mbedtls_x509_crt ) ) );
7373         mbedtls_ssl_send_alert_message( ssl,
7374                                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7375                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
7376 
7377         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
7378         goto exit;
7379     }
7380     mbedtls_x509_crt_init( chain );
7381 
7382     ret = ssl_parse_certificate_chain( ssl, chain );
7383     if( ret != 0 )
7384         goto exit;
7385 
7386 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
7387     if( ssl->handshake->ecrs_enabled)
7388         ssl->handshake->ecrs_state = ssl_ecrs_crt_verify;
7389 
7390 crt_verify:
7391     if( ssl->handshake->ecrs_enabled)
7392         rs_ctx = &ssl->handshake->ecrs_ctx;
7393 #endif
7394 
7395     ret = ssl_parse_certificate_verify( ssl, authmode,
7396                                         chain, rs_ctx );
7397     if( ret != 0 )
7398         goto exit;
7399 
7400 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
7401     {
7402         unsigned char *crt_start, *pk_start;
7403         size_t crt_len, pk_len;
7404 
7405         /* We parse the CRT chain without copying, so
7406          * these pointers point into the input buffer,
7407          * and are hence still valid after freeing the
7408          * CRT chain. */
7409 
7410         crt_start = chain->raw.p;
7411         crt_len   = chain->raw.len;
7412 
7413         pk_start = chain->pk_raw.p;
7414         pk_len   = chain->pk_raw.len;
7415 
7416         /* Free the CRT structures before computing
7417          * digest and copying the peer's public key. */
7418         mbedtls_x509_crt_free( chain );
7419         mbedtls_free( chain );
7420         chain = NULL;
7421 
7422         ret = ssl_remember_peer_crt_digest( ssl, crt_start, crt_len );
7423         if( ret != 0 )
7424             goto exit;
7425 
7426         ret = ssl_remember_peer_pubkey( ssl, pk_start, pk_len );
7427         if( ret != 0 )
7428             goto exit;
7429     }
7430 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
7431     /* Pass ownership to session structure. */
7432     ssl->session_negotiate->peer_cert = chain;
7433     chain = NULL;
7434 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
7435 
7436     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
7437 
7438 exit:
7439 
7440     if( ret == 0 )
7441         ssl->state++;
7442 
7443 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
7444     if( ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS )
7445     {
7446         ssl->handshake->ecrs_peer_cert = chain;
7447         chain = NULL;
7448     }
7449 #endif
7450 
7451     if( chain != NULL )
7452     {
7453         mbedtls_x509_crt_free( chain );
7454         mbedtls_free( chain );
7455     }
7456 
7457     return( ret );
7458 }
7459 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
7460 
7461 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
ssl_calc_finished_tls_sha256(mbedtls_ssl_context * ssl,unsigned char * buf,int from)7462 static void ssl_calc_finished_tls_sha256(
7463                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
7464 {
7465     int len = 12;
7466     const char *sender;
7467     unsigned char padbuf[32];
7468 #if defined(MBEDTLS_USE_PSA_CRYPTO)
7469     size_t hash_size;
7470     psa_hash_operation_t sha256_psa = PSA_HASH_OPERATION_INIT;
7471     psa_status_t status;
7472 #else
7473     mbedtls_sha256_context sha256;
7474 #endif
7475 
7476     mbedtls_ssl_session *session = ssl->session_negotiate;
7477     if( !session )
7478         session = ssl->session;
7479 
7480     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
7481              ? "client finished"
7482              : "server finished";
7483 
7484 #if defined(MBEDTLS_USE_PSA_CRYPTO)
7485     sha256_psa = psa_hash_operation_init();
7486 
7487     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc PSA finished tls sha256" ) );
7488 
7489     status = psa_hash_clone( &ssl->handshake->fin_sha256_psa, &sha256_psa );
7490     if( status != PSA_SUCCESS )
7491     {
7492         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
7493         return;
7494     }
7495 
7496     status = psa_hash_finish( &sha256_psa, padbuf, sizeof( padbuf ), &hash_size );
7497     if( status != PSA_SUCCESS )
7498     {
7499         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
7500         return;
7501     }
7502     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated padbuf", padbuf, 32 );
7503 #else
7504 
7505     mbedtls_sha256_init( &sha256 );
7506 
7507     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha256" ) );
7508 
7509     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
7510 
7511     /*
7512      * TLSv1.2:
7513      *   hash = PRF( master, finished_label,
7514      *               Hash( handshake ) )[0.11]
7515      */
7516 
7517 #if !defined(MBEDTLS_SHA256_ALT)
7518     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
7519                    sha256.state, sizeof( sha256.state ) );
7520 #endif
7521 
7522     mbedtls_sha256_finish( &sha256, padbuf );
7523     mbedtls_sha256_free( &sha256 );
7524 #endif /* MBEDTLS_USE_PSA_CRYPTO */
7525 
7526     ssl->handshake->tls_prf( session->master, 48, sender,
7527                              padbuf, 32, buf, len );
7528 
7529     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
7530 
7531     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
7532 
7533     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
7534 }
7535 #endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
7536 
7537 
7538 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
ssl_calc_finished_tls_sha384(mbedtls_ssl_context * ssl,unsigned char * buf,int from)7539 static void ssl_calc_finished_tls_sha384(
7540                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
7541 {
7542     int len = 12;
7543     const char *sender;
7544     unsigned char padbuf[48];
7545 #if defined(MBEDTLS_USE_PSA_CRYPTO)
7546     size_t hash_size;
7547     psa_hash_operation_t sha384_psa = PSA_HASH_OPERATION_INIT;
7548     psa_status_t status;
7549 #else
7550     mbedtls_sha512_context sha512;
7551 #endif
7552 
7553     mbedtls_ssl_session *session = ssl->session_negotiate;
7554     if( !session )
7555         session = ssl->session;
7556 
7557     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
7558                 ? "client finished"
7559                 : "server finished";
7560 
7561 #if defined(MBEDTLS_USE_PSA_CRYPTO)
7562     sha384_psa = psa_hash_operation_init();
7563 
7564     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc PSA finished tls sha384" ) );
7565 
7566     status = psa_hash_clone( &ssl->handshake->fin_sha384_psa, &sha384_psa );
7567     if( status != PSA_SUCCESS )
7568     {
7569         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
7570         return;
7571     }
7572 
7573     status = psa_hash_finish( &sha384_psa, padbuf, sizeof( padbuf ), &hash_size );
7574     if( status != PSA_SUCCESS )
7575     {
7576         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
7577         return;
7578     }
7579     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated padbuf", padbuf, 48 );
7580 #else
7581     mbedtls_sha512_init( &sha512 );
7582 
7583     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha384" ) );
7584 
7585     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha384 );
7586 
7587     /*
7588      * TLSv1.2:
7589      *   hash = PRF( master, finished_label,
7590      *               Hash( handshake ) )[0.11]
7591      */
7592 
7593 #if !defined(MBEDTLS_SHA512_ALT)
7594     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
7595                    sha512.state, sizeof( sha512.state ) );
7596 #endif
7597     mbedtls_sha512_finish( &sha512, padbuf );
7598 
7599     mbedtls_sha512_free( &sha512 );
7600 #endif
7601 
7602     ssl->handshake->tls_prf( session->master, 48, sender,
7603                              padbuf, 48, buf, len );
7604 
7605     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
7606 
7607     mbedtls_platform_zeroize(  padbuf, sizeof( padbuf ) );
7608 
7609     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
7610 }
7611 #endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA*/
7612 
mbedtls_ssl_handshake_wrapup_free_hs_transform(mbedtls_ssl_context * ssl)7613 void mbedtls_ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
7614 {
7615     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
7616 
7617     /*
7618      * Free our handshake params
7619      */
7620     mbedtls_ssl_handshake_free( ssl );
7621     mbedtls_free( ssl->handshake );
7622     ssl->handshake = NULL;
7623 
7624     /*
7625      * Free the previous transform and switch in the current one
7626      */
7627     if( ssl->transform )
7628     {
7629         mbedtls_ssl_transform_free( ssl->transform );
7630         mbedtls_free( ssl->transform );
7631     }
7632     ssl->transform = ssl->transform_negotiate;
7633     ssl->transform_negotiate = NULL;
7634 
7635     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
7636 }
7637 
mbedtls_ssl_handshake_wrapup(mbedtls_ssl_context * ssl)7638 void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
7639 {
7640     int resume = ssl->handshake->resume;
7641 
7642     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
7643 
7644 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7645     if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
7646     {
7647         ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;
7648         ssl->renego_records_seen = 0;
7649     }
7650 #endif
7651 
7652     /*
7653      * Free the previous session and switch in the current one
7654      */
7655     if( ssl->session )
7656     {
7657 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
7658         /* RFC 7366 3.1: keep the EtM state */
7659         ssl->session_negotiate->encrypt_then_mac =
7660                   ssl->session->encrypt_then_mac;
7661 #endif
7662 
7663         mbedtls_ssl_session_free( ssl->session );
7664         mbedtls_free( ssl->session );
7665     }
7666     ssl->session = ssl->session_negotiate;
7667     ssl->session_negotiate = NULL;
7668 
7669     /*
7670      * Add cache entry
7671      */
7672     if( ssl->conf->f_set_cache != NULL &&
7673         ssl->session->id_len != 0 &&
7674         resume == 0 )
7675     {
7676         if( ssl->conf->f_set_cache( ssl->conf->p_cache,
7677                                     ssl->session->id,
7678                                     ssl->session->id_len,
7679                                     ssl->session ) != 0 )
7680             MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
7681     }
7682 
7683 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7684     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
7685         ssl->handshake->flight != NULL )
7686     {
7687         /* Cancel handshake timer */
7688         mbedtls_ssl_set_timer( ssl, 0 );
7689 
7690         /* Keep last flight around in case we need to resend it:
7691          * we need the handshake and transform structures for that */
7692         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
7693     }
7694     else
7695 #endif
7696         mbedtls_ssl_handshake_wrapup_free_hs_transform( ssl );
7697 
7698     ssl->state = MBEDTLS_SSL_HANDSHAKE_OVER;
7699 
7700     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
7701 }
7702 
mbedtls_ssl_write_finished(mbedtls_ssl_context * ssl)7703 int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
7704 {
7705     int ret, hash_len;
7706 
7707     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
7708 
7709     mbedtls_ssl_update_out_pointers( ssl, ssl->transform_negotiate );
7710 
7711     ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
7712 
7713     /*
7714      * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
7715      * may define some other value. Currently (early 2016), no defined
7716      * ciphersuite does this (and this is unlikely to change as activity has
7717      * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
7718      */
7719     hash_len = 12;
7720 
7721 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7722     ssl->verify_data_len = hash_len;
7723     memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
7724 #endif
7725 
7726     ssl->out_msglen  = 4 + hash_len;
7727     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
7728     ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;
7729 
7730     /*
7731      * In case of session resuming, invert the client and server
7732      * ChangeCipherSpec messages order.
7733      */
7734     if( ssl->handshake->resume != 0 )
7735     {
7736 #if defined(MBEDTLS_SSL_CLI_C)
7737         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
7738             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
7739 #endif
7740 #if defined(MBEDTLS_SSL_SRV_C)
7741         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
7742             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
7743 #endif
7744     }
7745     else
7746         ssl->state++;
7747 
7748     /*
7749      * Switch to our negotiated transform and session parameters for outbound
7750      * data.
7751      */
7752     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
7753 
7754 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7755     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7756     {
7757         unsigned char i;
7758 
7759         /* Remember current epoch settings for resending */
7760         ssl->handshake->alt_transform_out = ssl->transform_out;
7761         memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr,
7762                 sizeof( ssl->handshake->alt_out_ctr ) );
7763 
7764         /* Set sequence_number to zero */
7765         memset( &ssl->cur_out_ctr[2], 0, sizeof( ssl->cur_out_ctr ) - 2 );
7766 
7767 
7768         /* Increment epoch */
7769         for( i = 2; i > 0; i-- )
7770             if( ++ssl->cur_out_ctr[i - 1] != 0 )
7771                 break;
7772 
7773         /* The loop goes to its end iff the counter is wrapping */
7774         if( i == 0 )
7775         {
7776             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
7777             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
7778         }
7779     }
7780     else
7781 #endif /* MBEDTLS_SSL_PROTO_DTLS */
7782     memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) );
7783 
7784     ssl->transform_out = ssl->transform_negotiate;
7785     ssl->session_out = ssl->session_negotiate;
7786 
7787 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7788     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7789         mbedtls_ssl_send_flight_completed( ssl );
7790 #endif
7791 
7792     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
7793     {
7794         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
7795         return( ret );
7796     }
7797 
7798 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7799     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
7800         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
7801     {
7802         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
7803         return( ret );
7804     }
7805 #endif
7806 
7807     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
7808 
7809     return( 0 );
7810 }
7811 
7812 #define SSL_MAX_HASH_LEN 12
7813 
mbedtls_ssl_parse_finished(mbedtls_ssl_context * ssl)7814 int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
7815 {
7816     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
7817     unsigned int hash_len = 12;
7818     unsigned char buf[SSL_MAX_HASH_LEN];
7819 
7820     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
7821 
7822     ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
7823 
7824     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
7825     {
7826         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
7827         goto exit;
7828     }
7829 
7830     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
7831     {
7832         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
7833         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7834                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
7835         ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
7836         goto exit;
7837     }
7838 
7839     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED  )
7840     {
7841         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7842                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
7843         ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
7844         goto exit;
7845     }
7846 
7847     if( ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
7848     {
7849         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
7850         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7851                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
7852         ret = MBEDTLS_ERR_SSL_DECODE_ERROR;
7853         goto exit;
7854     }
7855 
7856     if( mbedtls_ct_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
7857                       buf, hash_len ) != 0 )
7858     {
7859         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
7860         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7861                                         MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
7862         ret = MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
7863         goto exit;
7864     }
7865 
7866 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7867     ssl->verify_data_len = hash_len;
7868     memcpy( ssl->peer_verify_data, buf, hash_len );
7869 #endif
7870 
7871     if( ssl->handshake->resume != 0 )
7872     {
7873 #if defined(MBEDTLS_SSL_CLI_C)
7874         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
7875             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
7876 #endif
7877 #if defined(MBEDTLS_SSL_SRV_C)
7878         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
7879             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
7880 #endif
7881     }
7882     else
7883         ssl->state++;
7884 
7885 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7886     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7887         mbedtls_ssl_recv_flight_completed( ssl );
7888 #endif
7889 
7890     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
7891 
7892 exit:
7893     mbedtls_platform_zeroize( buf, hash_len );
7894     return( ret );
7895 }
7896 
7897 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
7898 /*
7899  * Helper to get TLS 1.2 PRF from ciphersuite
7900  * (Duplicates bits of logic from ssl_set_handshake_prfs().)
7901  */
ssl_tls12prf_from_cs(int ciphersuite_id)7902 static tls_prf_fn ssl_tls12prf_from_cs( int ciphersuite_id )
7903 {
7904     const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
7905              mbedtls_ssl_ciphersuite_from_id( ciphersuite_id );
7906 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
7907     if( ciphersuite_info != NULL && ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
7908         return( tls_prf_sha384 );
7909     else
7910 #endif
7911 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
7912     {
7913         if( ciphersuite_info != NULL && ciphersuite_info->mac == MBEDTLS_MD_SHA256 )
7914             return( tls_prf_sha256 );
7915     }
7916 #endif
7917 #if !defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
7918     !defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
7919     (void) ciphersuite_info;
7920 #endif
7921 
7922     return( NULL );
7923 }
7924 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
7925 
tls_prf_get_type(mbedtls_ssl_tls_prf_cb * tls_prf)7926 static mbedtls_tls_prf_types tls_prf_get_type( mbedtls_ssl_tls_prf_cb *tls_prf )
7927 {
7928     ((void) tls_prf);
7929 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
7930     if( tls_prf == tls_prf_sha384 )
7931     {
7932         return( MBEDTLS_SSL_TLS_PRF_SHA384 );
7933     }
7934     else
7935 #endif
7936 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA)
7937     if( tls_prf == tls_prf_sha256 )
7938     {
7939         return( MBEDTLS_SSL_TLS_PRF_SHA256 );
7940     }
7941     else
7942 #endif
7943     return( MBEDTLS_SSL_TLS_PRF_NONE );
7944 }
7945 
7946 /*
7947  * Populate a transform structure with session keys and all the other
7948  * necessary information.
7949  *
7950  * Parameters:
7951  * - [in/out]: transform: structure to populate
7952  *      [in] must be just initialised with mbedtls_ssl_transform_init()
7953  *      [out] fully populated, ready for use by mbedtls_ssl_{en,de}crypt_buf()
7954  * - [in] ciphersuite
7955  * - [in] master
7956  * - [in] encrypt_then_mac
7957  * - [in] tls_prf: pointer to PRF to use for key derivation
7958  * - [in] randbytes: buffer holding ServerHello.random + ClientHello.random
7959  * - [in] tls_version: TLS version
7960  * - [in] endpoint: client or server
7961  * - [in] ssl: used for:
7962  *        - ssl->conf->{f,p}_export_keys
7963  *      [in] optionally used for:
7964  *        - MBEDTLS_DEBUG_C: ssl->conf->{f,p}_dbg
7965  */
7966 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls12_populate_transform(mbedtls_ssl_transform * transform,int ciphersuite,const unsigned char master[48],int encrypt_then_mac,ssl_tls_prf_t tls_prf,const unsigned char randbytes[64],mbedtls_ssl_protocol_version tls_version,unsigned endpoint,const mbedtls_ssl_context * ssl)7967 static int ssl_tls12_populate_transform( mbedtls_ssl_transform *transform,
7968                                    int ciphersuite,
7969                                    const unsigned char master[48],
7970 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
7971                                    int encrypt_then_mac,
7972 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
7973                                    ssl_tls_prf_t tls_prf,
7974                                    const unsigned char randbytes[64],
7975                                    mbedtls_ssl_protocol_version tls_version,
7976                                    unsigned endpoint,
7977                                    const mbedtls_ssl_context *ssl )
7978 {
7979     int ret = 0;
7980     unsigned char keyblk[256];
7981     unsigned char *key1;
7982     unsigned char *key2;
7983     unsigned char *mac_enc;
7984     unsigned char *mac_dec;
7985     size_t mac_key_len = 0;
7986     size_t iv_copy_len;
7987     size_t keylen;
7988     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
7989     mbedtls_ssl_mode_t ssl_mode;
7990 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
7991     const mbedtls_cipher_info_t *cipher_info;
7992     const mbedtls_md_info_t *md_info;
7993 #endif /* !MBEDTLS_USE_PSA_CRYPTO */
7994 
7995 #if defined(MBEDTLS_USE_PSA_CRYPTO)
7996     psa_key_type_t key_type;
7997     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7998     psa_algorithm_t alg;
7999     psa_algorithm_t mac_alg = 0;
8000     size_t key_bits;
8001     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8002 #endif
8003 
8004 #if !defined(MBEDTLS_DEBUG_C) && \
8005     !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
8006     if( ssl->f_export_keys == NULL )
8007     {
8008         ssl = NULL; /* make sure we don't use it except for these cases */
8009         (void) ssl;
8010     }
8011 #endif
8012 
8013     /*
8014      * Some data just needs copying into the structure
8015      */
8016 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
8017     transform->encrypt_then_mac = encrypt_then_mac;
8018 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
8019     transform->tls_version = tls_version;
8020 
8021 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
8022     memcpy( transform->randbytes, randbytes, sizeof( transform->randbytes ) );
8023 #endif
8024 
8025 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
8026     if( tls_version == MBEDTLS_SSL_VERSION_TLS1_3 )
8027     {
8028         /* At the moment, we keep TLS <= 1.2 and TLS 1.3 transform
8029          * generation separate. This should never happen. */
8030         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
8031     }
8032 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
8033 
8034     /*
8035      * Get various info structures
8036      */
8037     ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuite );
8038     if( ciphersuite_info == NULL )
8039     {
8040         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %d not found",
8041                                     ciphersuite ) );
8042         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
8043     }
8044 
8045     ssl_mode = mbedtls_ssl_get_mode_from_ciphersuite(
8046 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
8047                                         encrypt_then_mac,
8048 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
8049                                         ciphersuite_info );
8050 
8051     if( ssl_mode == MBEDTLS_SSL_MODE_AEAD )
8052         transform->taglen =
8053             ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
8054 
8055 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8056     if( ( status = mbedtls_ssl_cipher_to_psa( ciphersuite_info->cipher,
8057                                  transform->taglen,
8058                                  &alg,
8059                                  &key_type,
8060                                  &key_bits ) ) != PSA_SUCCESS )
8061     {
8062         ret = psa_ssl_status_to_mbedtls( status );
8063         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_cipher_to_psa", ret );
8064         goto end;
8065     }
8066 #else
8067     cipher_info = mbedtls_cipher_info_from_type( ciphersuite_info->cipher );
8068     if( cipher_info == NULL )
8069     {
8070         MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %u not found",
8071                                     ciphersuite_info->cipher ) );
8072         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
8073     }
8074 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8075 
8076 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8077     mac_alg = mbedtls_hash_info_psa_from_md( ciphersuite_info->mac );
8078     if( mac_alg == 0 )
8079     {
8080         MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_hash_info_psa_from_md for %u not found",
8081                             (unsigned) ciphersuite_info->mac ) );
8082         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
8083     }
8084 #else
8085     md_info = mbedtls_md_info_from_type( ciphersuite_info->mac );
8086     if( md_info == NULL )
8087     {
8088         MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %u not found",
8089                             (unsigned) ciphersuite_info->mac ) );
8090         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
8091     }
8092 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8093 
8094 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
8095     /* Copy own and peer's CID if the use of the CID
8096      * extension has been negotiated. */
8097     if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_ENABLED )
8098     {
8099         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Copy CIDs into SSL transform" ) );
8100 
8101         transform->in_cid_len = ssl->own_cid_len;
8102         memcpy( transform->in_cid, ssl->own_cid, ssl->own_cid_len );
8103         MBEDTLS_SSL_DEBUG_BUF( 3, "Incoming CID", transform->in_cid,
8104                                transform->in_cid_len );
8105 
8106         transform->out_cid_len = ssl->handshake->peer_cid_len;
8107         memcpy( transform->out_cid, ssl->handshake->peer_cid,
8108                 ssl->handshake->peer_cid_len );
8109         MBEDTLS_SSL_DEBUG_BUF( 3, "Outgoing CID", transform->out_cid,
8110                                transform->out_cid_len );
8111     }
8112 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
8113 
8114     /*
8115      * Compute key block using the PRF
8116      */
8117     ret = tls_prf( master, 48, "key expansion", randbytes, 64, keyblk, 256 );
8118     if( ret != 0 )
8119     {
8120         MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
8121         return( ret );
8122     }
8123 
8124     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
8125                            mbedtls_ssl_get_ciphersuite_name( ciphersuite ) ) );
8126     MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", master, 48 );
8127     MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", randbytes, 64 );
8128     MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
8129 
8130     /*
8131      * Determine the appropriate key, IV and MAC length.
8132      */
8133 
8134 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8135     keylen = PSA_BITS_TO_BYTES(key_bits);
8136 #else
8137     keylen = mbedtls_cipher_info_get_key_bitlen( cipher_info ) / 8;
8138 #endif
8139 
8140 #if defined(MBEDTLS_GCM_C) ||                           \
8141     defined(MBEDTLS_CCM_C) ||                           \
8142     defined(MBEDTLS_CHACHAPOLY_C)
8143     if( ssl_mode == MBEDTLS_SSL_MODE_AEAD )
8144     {
8145         size_t explicit_ivlen;
8146 
8147         transform->maclen = 0;
8148         mac_key_len = 0;
8149 
8150         /* All modes haves 96-bit IVs, but the length of the static parts vary
8151          * with mode and version:
8152          * - For GCM and CCM in TLS 1.2, there's a static IV of 4 Bytes
8153          *   (to be concatenated with a dynamically chosen IV of 8 Bytes)
8154          * - For ChaChaPoly in TLS 1.2, and all modes in TLS 1.3, there's
8155          *   a static IV of 12 Bytes (to be XOR'ed with the 8 Byte record
8156          *   sequence number).
8157          */
8158         transform->ivlen = 12;
8159 
8160         int is_chachapoly = 0;
8161 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8162         is_chachapoly = ( key_type == PSA_KEY_TYPE_CHACHA20 );
8163 #else
8164         is_chachapoly = ( mbedtls_cipher_info_get_mode( cipher_info )
8165                 == MBEDTLS_MODE_CHACHAPOLY );
8166 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8167 
8168         if( is_chachapoly )
8169             transform->fixed_ivlen = 12;
8170         else
8171             transform->fixed_ivlen = 4;
8172 
8173         /* Minimum length of encrypted record */
8174         explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
8175         transform->minlen = explicit_ivlen + transform->taglen;
8176     }
8177     else
8178 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
8179 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
8180     if( ssl_mode == MBEDTLS_SSL_MODE_STREAM ||
8181         ssl_mode == MBEDTLS_SSL_MODE_CBC ||
8182         ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM )
8183     {
8184 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8185         size_t block_size = PSA_BLOCK_CIPHER_BLOCK_LENGTH( key_type );
8186 #else
8187         size_t block_size = cipher_info->block_size;
8188 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8189 
8190 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8191         /* Get MAC length */
8192         mac_key_len = PSA_HASH_LENGTH(mac_alg);
8193 #else
8194         /* Initialize HMAC contexts */
8195         if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
8196             ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
8197         {
8198             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
8199             goto end;
8200         }
8201 
8202         /* Get MAC length */
8203         mac_key_len = mbedtls_md_get_size( md_info );
8204 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8205         transform->maclen = mac_key_len;
8206 
8207         /* IV length */
8208 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8209         transform->ivlen = PSA_CIPHER_IV_LENGTH( key_type, alg );
8210 #else
8211         transform->ivlen = cipher_info->iv_size;
8212 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8213 
8214         /* Minimum length */
8215         if( ssl_mode == MBEDTLS_SSL_MODE_STREAM )
8216             transform->minlen = transform->maclen;
8217         else
8218         {
8219             /*
8220              * GenericBlockCipher:
8221              * 1. if EtM is in use: one block plus MAC
8222              *    otherwise: * first multiple of blocklen greater than maclen
8223              * 2. IV
8224              */
8225 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
8226             if( ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM )
8227             {
8228                 transform->minlen = transform->maclen
8229                                   + block_size;
8230             }
8231             else
8232 #endif
8233             {
8234                 transform->minlen = transform->maclen
8235                                   + block_size
8236                                   - transform->maclen % block_size;
8237             }
8238 
8239             if( tls_version == MBEDTLS_SSL_VERSION_TLS1_2 )
8240             {
8241                 transform->minlen += transform->ivlen;
8242             }
8243             else
8244             {
8245                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
8246                 ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
8247                 goto end;
8248             }
8249         }
8250     }
8251     else
8252 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
8253     {
8254         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
8255         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
8256     }
8257 
8258     MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %u, minlen: %u, ivlen: %u, maclen: %u",
8259                                 (unsigned) keylen,
8260                                 (unsigned) transform->minlen,
8261                                 (unsigned) transform->ivlen,
8262                                 (unsigned) transform->maclen ) );
8263 
8264     /*
8265      * Finally setup the cipher contexts, IVs and MAC secrets.
8266      */
8267 #if defined(MBEDTLS_SSL_CLI_C)
8268     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
8269     {
8270         key1 = keyblk + mac_key_len * 2;
8271         key2 = keyblk + mac_key_len * 2 + keylen;
8272 
8273         mac_enc = keyblk;
8274         mac_dec = keyblk + mac_key_len;
8275 
8276         iv_copy_len = ( transform->fixed_ivlen ) ?
8277                             transform->fixed_ivlen : transform->ivlen;
8278         memcpy( transform->iv_enc, key2 + keylen,  iv_copy_len );
8279         memcpy( transform->iv_dec, key2 + keylen + iv_copy_len,
8280                 iv_copy_len );
8281     }
8282     else
8283 #endif /* MBEDTLS_SSL_CLI_C */
8284 #if defined(MBEDTLS_SSL_SRV_C)
8285     if( endpoint == MBEDTLS_SSL_IS_SERVER )
8286     {
8287         key1 = keyblk + mac_key_len * 2 + keylen;
8288         key2 = keyblk + mac_key_len * 2;
8289 
8290         mac_enc = keyblk + mac_key_len;
8291         mac_dec = keyblk;
8292 
8293         iv_copy_len = ( transform->fixed_ivlen ) ?
8294                             transform->fixed_ivlen : transform->ivlen;
8295         memcpy( transform->iv_dec, key1 + keylen,  iv_copy_len );
8296         memcpy( transform->iv_enc, key1 + keylen + iv_copy_len,
8297                 iv_copy_len );
8298     }
8299     else
8300 #endif /* MBEDTLS_SSL_SRV_C */
8301     {
8302         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
8303         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
8304         goto end;
8305     }
8306 
8307     if( ssl != NULL && ssl->f_export_keys != NULL )
8308     {
8309         ssl->f_export_keys( ssl->p_export_keys,
8310                             MBEDTLS_SSL_KEY_EXPORT_TLS12_MASTER_SECRET,
8311                             master, 48,
8312                             randbytes + 32,
8313                             randbytes,
8314                             tls_prf_get_type( tls_prf ) );
8315     }
8316 
8317 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8318     transform->psa_alg = alg;
8319 
8320     if ( alg != MBEDTLS_SSL_NULL_CIPHER )
8321     {
8322         psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_ENCRYPT );
8323         psa_set_key_algorithm( &attributes, alg );
8324         psa_set_key_type( &attributes, key_type );
8325 
8326         if( ( status = psa_import_key( &attributes,
8327                                 key1,
8328                                 PSA_BITS_TO_BYTES( key_bits ),
8329                                 &transform->psa_key_enc ) ) != PSA_SUCCESS )
8330         {
8331             MBEDTLS_SSL_DEBUG_RET( 3, "psa_import_key", (int)status );
8332             ret = psa_ssl_status_to_mbedtls( status );
8333             MBEDTLS_SSL_DEBUG_RET( 1, "psa_import_key", ret );
8334             goto end;
8335         }
8336 
8337         psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_DECRYPT );
8338 
8339         if( ( status = psa_import_key( &attributes,
8340                                 key2,
8341                                 PSA_BITS_TO_BYTES( key_bits ),
8342                                 &transform->psa_key_dec ) ) != PSA_SUCCESS )
8343         {
8344             ret = psa_ssl_status_to_mbedtls( status );
8345             MBEDTLS_SSL_DEBUG_RET( 1, "psa_import_key", ret );
8346             goto end;
8347         }
8348     }
8349 #else
8350     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
8351                                  cipher_info ) ) != 0 )
8352     {
8353         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
8354         goto end;
8355     }
8356 
8357     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
8358                                  cipher_info ) ) != 0 )
8359     {
8360         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
8361         goto end;
8362     }
8363 
8364     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
8365                                (int) mbedtls_cipher_info_get_key_bitlen( cipher_info ),
8366                                MBEDTLS_ENCRYPT ) ) != 0 )
8367     {
8368         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
8369         goto end;
8370     }
8371 
8372     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
8373                                (int) mbedtls_cipher_info_get_key_bitlen( cipher_info ),
8374                                MBEDTLS_DECRYPT ) ) != 0 )
8375     {
8376         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
8377         goto end;
8378     }
8379 
8380 #if defined(MBEDTLS_CIPHER_MODE_CBC)
8381     if( mbedtls_cipher_info_get_mode( cipher_info ) == MBEDTLS_MODE_CBC )
8382     {
8383         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
8384                                              MBEDTLS_PADDING_NONE ) ) != 0 )
8385         {
8386             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
8387             goto end;
8388         }
8389 
8390         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
8391                                              MBEDTLS_PADDING_NONE ) ) != 0 )
8392         {
8393             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
8394             goto end;
8395         }
8396     }
8397 #endif /* MBEDTLS_CIPHER_MODE_CBC */
8398 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8399 
8400 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
8401     /* For HMAC-based ciphersuites, initialize the HMAC transforms.
8402        For AEAD-based ciphersuites, there is nothing to do here. */
8403     if( mac_key_len != 0 )
8404     {
8405 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8406         transform->psa_mac_alg = PSA_ALG_HMAC( mac_alg );
8407 
8408         psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_MESSAGE );
8409         psa_set_key_algorithm( &attributes, PSA_ALG_HMAC( mac_alg ) );
8410         psa_set_key_type( &attributes, PSA_KEY_TYPE_HMAC );
8411 
8412         if( ( status = psa_import_key( &attributes,
8413                                        mac_enc, mac_key_len,
8414                                        &transform->psa_mac_enc ) ) != PSA_SUCCESS )
8415         {
8416             ret = psa_ssl_status_to_mbedtls( status );
8417             MBEDTLS_SSL_DEBUG_RET( 1, "psa_import_mac_key", ret );
8418             goto end;
8419         }
8420 
8421         if( ( transform->psa_alg == MBEDTLS_SSL_NULL_CIPHER ) ||
8422             ( ( transform->psa_alg == PSA_ALG_CBC_NO_PADDING )
8423 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
8424               && ( transform->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED )
8425 #endif
8426             ) )
8427             /* mbedtls_ct_hmac() requires the key to be exportable */
8428             psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_EXPORT |
8429                                                   PSA_KEY_USAGE_VERIFY_HASH );
8430         else
8431             psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_VERIFY_HASH );
8432 
8433         if( ( status = psa_import_key( &attributes,
8434                                        mac_dec, mac_key_len,
8435                                        &transform->psa_mac_dec ) ) != PSA_SUCCESS )
8436         {
8437             ret = psa_ssl_status_to_mbedtls( status );
8438             MBEDTLS_SSL_DEBUG_RET( 1, "psa_import_mac_key", ret );
8439             goto end;
8440         }
8441 #else
8442         ret = mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
8443         if( ret != 0 )
8444             goto end;
8445         ret = mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
8446         if( ret != 0 )
8447             goto end;
8448 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8449     }
8450 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
8451 
8452     ((void) mac_dec);
8453     ((void) mac_enc);
8454 
8455 end:
8456     mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );
8457     return( ret );
8458 }
8459 
8460 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
8461     defined(MBEDTLS_USE_PSA_CRYPTO)
mbedtls_psa_ecjpake_read_round(psa_pake_operation_t * pake_ctx,const unsigned char * buf,size_t len,mbedtls_ecjpake_rounds_t round)8462 int mbedtls_psa_ecjpake_read_round(
8463                                     psa_pake_operation_t *pake_ctx,
8464                                     const unsigned char *buf,
8465                                     size_t len, mbedtls_ecjpake_rounds_t round )
8466 {
8467     psa_status_t status;
8468     size_t input_offset = 0;
8469     /*
8470      * At round one repeat the KEY_SHARE, ZK_PUBLIC & ZF_PROOF twice
8471      * At round two perform a single cycle
8472      */
8473     unsigned int remaining_steps = ( round == MBEDTLS_ECJPAKE_ROUND_ONE) ? 2 : 1;
8474 
8475     for( ; remaining_steps > 0; remaining_steps-- )
8476     {
8477         for( psa_pake_step_t step = PSA_PAKE_STEP_KEY_SHARE;
8478              step <= PSA_PAKE_STEP_ZK_PROOF;
8479              ++step )
8480         {
8481             /* Length is stored at the first byte */
8482             size_t length = buf[input_offset];
8483             input_offset += 1;
8484 
8485             if( input_offset + length > len )
8486             {
8487                 return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
8488             }
8489 
8490             status = psa_pake_input( pake_ctx, step,
8491                                      buf + input_offset, length );
8492             if( status != PSA_SUCCESS)
8493             {
8494                 return psa_ssl_status_to_mbedtls( status );
8495             }
8496 
8497             input_offset += length;
8498         }
8499     }
8500 
8501     if( input_offset != len )
8502         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
8503 
8504     return( 0 );
8505 }
8506 
mbedtls_psa_ecjpake_write_round(psa_pake_operation_t * pake_ctx,unsigned char * buf,size_t len,size_t * olen,mbedtls_ecjpake_rounds_t round)8507 int mbedtls_psa_ecjpake_write_round(
8508                                     psa_pake_operation_t *pake_ctx,
8509                                     unsigned char *buf,
8510                                     size_t len, size_t *olen,
8511                                     mbedtls_ecjpake_rounds_t round )
8512 {
8513     psa_status_t status;
8514     size_t output_offset = 0;
8515     size_t output_len;
8516     /*
8517      * At round one repeat the KEY_SHARE, ZK_PUBLIC & ZF_PROOF twice
8518      * At round two perform a single cycle
8519      */
8520     unsigned int remaining_steps = ( round == MBEDTLS_ECJPAKE_ROUND_ONE) ? 2 : 1;
8521 
8522     for( ; remaining_steps > 0; remaining_steps-- )
8523     {
8524         for( psa_pake_step_t step = PSA_PAKE_STEP_KEY_SHARE;
8525             step <= PSA_PAKE_STEP_ZK_PROOF;
8526             ++step )
8527         {
8528             /*
8529              * For each step, prepend 1 byte with the length of the data as
8530              * given by psa_pake_output().
8531              */
8532             status = psa_pake_output( pake_ctx, step,
8533                                         buf + output_offset + 1,
8534                                         len - output_offset - 1,
8535                                         &output_len );
8536             if( status != PSA_SUCCESS )
8537             {
8538                 return( psa_ssl_status_to_mbedtls( status ) );
8539             }
8540 
8541             *(buf + output_offset) = (uint8_t) output_len;
8542 
8543             output_offset += output_len + 1;
8544         }
8545     }
8546 
8547     *olen = output_offset;
8548 
8549     return( 0 );
8550 }
8551 #endif //MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED && MBEDTLS_USE_PSA_CRYPTO
8552 
8553 #if defined(MBEDTLS_USE_PSA_CRYPTO)
mbedtls_ssl_get_key_exchange_md_tls1_2(mbedtls_ssl_context * ssl,unsigned char * hash,size_t * hashlen,unsigned char * data,size_t data_len,mbedtls_md_type_t md_alg)8554 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
8555                                             unsigned char *hash, size_t *hashlen,
8556                                             unsigned char *data, size_t data_len,
8557                                             mbedtls_md_type_t md_alg )
8558 {
8559     psa_status_t status;
8560     psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT;
8561     psa_algorithm_t hash_alg = mbedtls_hash_info_psa_from_md( md_alg );
8562 
8563     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform PSA-based computation of digest of ServerKeyExchange" ) );
8564 
8565     if( ( status = psa_hash_setup( &hash_operation,
8566                                    hash_alg ) ) != PSA_SUCCESS )
8567     {
8568         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_setup", status );
8569         goto exit;
8570     }
8571 
8572     if( ( status = psa_hash_update( &hash_operation, ssl->handshake->randbytes,
8573                                     64 ) ) != PSA_SUCCESS )
8574     {
8575         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_update", status );
8576         goto exit;
8577     }
8578 
8579     if( ( status = psa_hash_update( &hash_operation,
8580                                     data, data_len ) ) != PSA_SUCCESS )
8581     {
8582         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_update", status );
8583         goto exit;
8584     }
8585 
8586     if( ( status = psa_hash_finish( &hash_operation, hash, PSA_HASH_MAX_SIZE,
8587                                     hashlen ) ) != PSA_SUCCESS )
8588     {
8589          MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_finish", status );
8590          goto exit;
8591     }
8592 
8593 exit:
8594     if( status != PSA_SUCCESS )
8595     {
8596         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
8597                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
8598         switch( status )
8599         {
8600             case PSA_ERROR_NOT_SUPPORTED:
8601                 return( MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE );
8602             case PSA_ERROR_BAD_STATE: /* Intentional fallthrough */
8603             case PSA_ERROR_BUFFER_TOO_SMALL:
8604                 return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
8605             case PSA_ERROR_INSUFFICIENT_MEMORY:
8606                 return( MBEDTLS_ERR_MD_ALLOC_FAILED );
8607             default:
8608                 return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
8609         }
8610     }
8611     return( 0 );
8612 }
8613 
8614 #else
8615 
mbedtls_ssl_get_key_exchange_md_tls1_2(mbedtls_ssl_context * ssl,unsigned char * hash,size_t * hashlen,unsigned char * data,size_t data_len,mbedtls_md_type_t md_alg)8616 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
8617                                             unsigned char *hash, size_t *hashlen,
8618                                             unsigned char *data, size_t data_len,
8619                                             mbedtls_md_type_t md_alg )
8620 {
8621     int ret = 0;
8622     mbedtls_md_context_t ctx;
8623     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
8624     *hashlen = mbedtls_md_get_size( md_info );
8625 
8626     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform mbedtls-based computation of digest of ServerKeyExchange" ) );
8627 
8628     mbedtls_md_init( &ctx );
8629 
8630     /*
8631      * digitally-signed struct {
8632      *     opaque client_random[32];
8633      *     opaque server_random[32];
8634      *     ServerDHParams params;
8635      * };
8636      */
8637     if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
8638     {
8639         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
8640         goto exit;
8641     }
8642     if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
8643     {
8644         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret );
8645         goto exit;
8646     }
8647     if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )
8648     {
8649         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
8650         goto exit;
8651     }
8652     if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )
8653     {
8654         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
8655         goto exit;
8656     }
8657     if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 )
8658     {
8659         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret );
8660         goto exit;
8661     }
8662 
8663 exit:
8664     mbedtls_md_free( &ctx );
8665 
8666     if( ret != 0 )
8667         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
8668                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
8669 
8670     return( ret );
8671 }
8672 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8673 
8674 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
8675 
8676 /* Find the preferred hash for a given signature algorithm. */
mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(mbedtls_ssl_context * ssl,unsigned int sig_alg)8677 unsigned int mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
8678                 mbedtls_ssl_context *ssl,
8679                 unsigned int sig_alg )
8680 {
8681     unsigned int i;
8682     uint16_t *received_sig_algs = ssl->handshake->received_sig_algs;
8683 
8684     if( sig_alg == MBEDTLS_SSL_SIG_ANON )
8685         return( MBEDTLS_SSL_HASH_NONE );
8686 
8687     for( i = 0; received_sig_algs[i] != MBEDTLS_TLS_SIG_NONE; i++ )
8688     {
8689         unsigned int hash_alg_received =
8690                     MBEDTLS_SSL_TLS12_HASH_ALG_FROM_SIG_AND_HASH_ALG(
8691                         received_sig_algs[i] );
8692         unsigned int sig_alg_received =
8693                     MBEDTLS_SSL_TLS12_SIG_ALG_FROM_SIG_AND_HASH_ALG(
8694                         received_sig_algs[i] );
8695 
8696         if( sig_alg == sig_alg_received )
8697         {
8698 #if defined(MBEDTLS_USE_PSA_CRYPTO)
8699             if( ssl->handshake->key_cert && ssl->handshake->key_cert->key )
8700             {
8701                 psa_algorithm_t psa_hash_alg =
8702                                 mbedtls_hash_info_psa_from_md( hash_alg_received );
8703 
8704                 if( sig_alg_received == MBEDTLS_SSL_SIG_ECDSA &&
8705                     ! mbedtls_pk_can_do_ext( ssl->handshake->key_cert->key,
8706                                              PSA_ALG_ECDSA( psa_hash_alg ),
8707                                              PSA_KEY_USAGE_SIGN_HASH ) )
8708                     continue;
8709 
8710                 if( sig_alg_received == MBEDTLS_SSL_SIG_RSA &&
8711                     ! mbedtls_pk_can_do_ext( ssl->handshake->key_cert->key,
8712                                              PSA_ALG_RSA_PKCS1V15_SIGN(
8713                                                             psa_hash_alg ),
8714                                              PSA_KEY_USAGE_SIGN_HASH ) )
8715                     continue;
8716             }
8717 #endif /* MBEDTLS_USE_PSA_CRYPTO */
8718 
8719             return( hash_alg_received );
8720         }
8721     }
8722 
8723     return( MBEDTLS_SSL_HASH_NONE );
8724 }
8725 
8726 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
8727 
8728 /* Serialization of TLS 1.2 sessions:
8729  *
8730  * struct {
8731  *    uint64 start_time;
8732  *    uint8 ciphersuite[2];           // defined by the standard
8733  *    uint8 session_id_len;           // at most 32
8734  *    opaque session_id[32];
8735  *    opaque master[48];              // fixed length in the standard
8736  *    uint32 verify_result;
8737  *    opaque peer_cert<0..2^24-1>;    // length 0 means no peer cert
8738  *    opaque ticket<0..2^24-1>;       // length 0 means no ticket
8739  *    uint32 ticket_lifetime;
8740  *    uint8 mfl_code;                 // up to 255 according to standard
8741  *    uint8 encrypt_then_mac;         // 0 or 1
8742  * } serialized_session_tls12;
8743  *
8744  */
ssl_tls12_session_save(const mbedtls_ssl_session * session,unsigned char * buf,size_t buf_len)8745 static size_t ssl_tls12_session_save( const mbedtls_ssl_session *session,
8746                                       unsigned char *buf,
8747                                       size_t buf_len )
8748 {
8749     unsigned char *p = buf;
8750     size_t used = 0;
8751 
8752 #if defined(MBEDTLS_HAVE_TIME)
8753     uint64_t start;
8754 #endif
8755 #if defined(MBEDTLS_X509_CRT_PARSE_C)
8756 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
8757     size_t cert_len;
8758 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
8759 #endif /* MBEDTLS_X509_CRT_PARSE_C */
8760 
8761     /*
8762      * Time
8763      */
8764 #if defined(MBEDTLS_HAVE_TIME)
8765     used += 8;
8766 
8767     if( used <= buf_len )
8768     {
8769         start = (uint64_t) session->start;
8770 
8771         MBEDTLS_PUT_UINT64_BE( start, p, 0 );
8772         p += 8;
8773     }
8774 #endif /* MBEDTLS_HAVE_TIME */
8775 
8776     /*
8777      * Basic mandatory fields
8778      */
8779     used += 2   /* ciphersuite */
8780           + 1   /* id_len */
8781           + sizeof( session->id )
8782           + sizeof( session->master )
8783           + 4;  /* verify_result */
8784 
8785     if( used <= buf_len )
8786     {
8787         MBEDTLS_PUT_UINT16_BE( session->ciphersuite, p, 0 );
8788         p += 2;
8789 
8790         *p++ = MBEDTLS_BYTE_0( session->id_len );
8791         memcpy( p, session->id, 32 );
8792         p += 32;
8793 
8794         memcpy( p, session->master, 48 );
8795         p += 48;
8796 
8797         MBEDTLS_PUT_UINT32_BE( session->verify_result, p, 0 );
8798         p += 4;
8799     }
8800 
8801     /*
8802      * Peer's end-entity certificate
8803      */
8804 #if defined(MBEDTLS_X509_CRT_PARSE_C)
8805 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
8806     if( session->peer_cert == NULL )
8807         cert_len = 0;
8808     else
8809         cert_len = session->peer_cert->raw.len;
8810 
8811     used += 3 + cert_len;
8812 
8813     if( used <= buf_len )
8814     {
8815         *p++ = MBEDTLS_BYTE_2( cert_len );
8816         *p++ = MBEDTLS_BYTE_1( cert_len );
8817         *p++ = MBEDTLS_BYTE_0( cert_len );
8818 
8819         if( session->peer_cert != NULL )
8820         {
8821             memcpy( p, session->peer_cert->raw.p, cert_len );
8822             p += cert_len;
8823         }
8824     }
8825 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
8826     if( session->peer_cert_digest != NULL )
8827     {
8828         used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len;
8829         if( used <= buf_len )
8830         {
8831             *p++ = (unsigned char) session->peer_cert_digest_type;
8832             *p++ = (unsigned char) session->peer_cert_digest_len;
8833             memcpy( p, session->peer_cert_digest,
8834                     session->peer_cert_digest_len );
8835             p += session->peer_cert_digest_len;
8836         }
8837     }
8838     else
8839     {
8840         used += 2;
8841         if( used <= buf_len )
8842         {
8843             *p++ = (unsigned char) MBEDTLS_MD_NONE;
8844             *p++ = 0;
8845         }
8846     }
8847 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
8848 #endif /* MBEDTLS_X509_CRT_PARSE_C */
8849 
8850     /*
8851      * Session ticket if any, plus associated data
8852      */
8853 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
8854     used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */
8855 
8856     if( used <= buf_len )
8857     {
8858         *p++ = MBEDTLS_BYTE_2( session->ticket_len );
8859         *p++ = MBEDTLS_BYTE_1( session->ticket_len );
8860         *p++ = MBEDTLS_BYTE_0( session->ticket_len );
8861 
8862         if( session->ticket != NULL )
8863         {
8864             memcpy( p, session->ticket, session->ticket_len );
8865             p += session->ticket_len;
8866         }
8867 
8868         MBEDTLS_PUT_UINT32_BE( session->ticket_lifetime, p, 0 );
8869         p += 4;
8870     }
8871 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
8872 
8873     /*
8874      * Misc extension-related info
8875      */
8876 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
8877     used += 1;
8878 
8879     if( used <= buf_len )
8880         *p++ = session->mfl_code;
8881 #endif
8882 
8883 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
8884     used += 1;
8885 
8886     if( used <= buf_len )
8887         *p++ = MBEDTLS_BYTE_0( session->encrypt_then_mac );
8888 #endif
8889 
8890     return( used );
8891 }
8892 
8893 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls12_session_load(mbedtls_ssl_session * session,const unsigned char * buf,size_t len)8894 static int ssl_tls12_session_load( mbedtls_ssl_session *session,
8895                                    const unsigned char *buf,
8896                                    size_t len )
8897 {
8898 #if defined(MBEDTLS_HAVE_TIME)
8899     uint64_t start;
8900 #endif
8901 #if defined(MBEDTLS_X509_CRT_PARSE_C)
8902 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
8903     size_t cert_len;
8904 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
8905 #endif /* MBEDTLS_X509_CRT_PARSE_C */
8906 
8907     const unsigned char *p = buf;
8908     const unsigned char * const end = buf + len;
8909 
8910     /*
8911      * Time
8912      */
8913 #if defined(MBEDTLS_HAVE_TIME)
8914     if( 8 > (size_t)( end - p ) )
8915         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
8916 
8917     start = ( (uint64_t) p[0] << 56 ) |
8918             ( (uint64_t) p[1] << 48 ) |
8919             ( (uint64_t) p[2] << 40 ) |
8920             ( (uint64_t) p[3] << 32 ) |
8921             ( (uint64_t) p[4] << 24 ) |
8922             ( (uint64_t) p[5] << 16 ) |
8923             ( (uint64_t) p[6] <<  8 ) |
8924             ( (uint64_t) p[7]       );
8925     p += 8;
8926 
8927     session->start = (time_t) start;
8928 #endif /* MBEDTLS_HAVE_TIME */
8929 
8930     /*
8931      * Basic mandatory fields
8932      */
8933     if( 2 + 1 + 32 + 48 + 4 > (size_t)( end - p ) )
8934         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
8935 
8936     session->ciphersuite = ( p[0] << 8 ) | p[1];
8937     p += 2;
8938 
8939     session->id_len = *p++;
8940     memcpy( session->id, p, 32 );
8941     p += 32;
8942 
8943     memcpy( session->master, p, 48 );
8944     p += 48;
8945 
8946     session->verify_result = ( (uint32_t) p[0] << 24 ) |
8947                              ( (uint32_t) p[1] << 16 ) |
8948                              ( (uint32_t) p[2] <<  8 ) |
8949                              ( (uint32_t) p[3]       );
8950     p += 4;
8951 
8952     /* Immediately clear invalid pointer values that have been read, in case
8953      * we exit early before we replaced them with valid ones. */
8954 #if defined(MBEDTLS_X509_CRT_PARSE_C)
8955 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
8956     session->peer_cert = NULL;
8957 #else
8958     session->peer_cert_digest = NULL;
8959 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
8960 #endif /* MBEDTLS_X509_CRT_PARSE_C */
8961 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
8962     session->ticket = NULL;
8963 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
8964 
8965     /*
8966      * Peer certificate
8967      */
8968 #if defined(MBEDTLS_X509_CRT_PARSE_C)
8969 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
8970     /* Deserialize CRT from the end of the ticket. */
8971     if( 3 > (size_t)( end - p ) )
8972         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
8973 
8974     cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
8975     p += 3;
8976 
8977     if( cert_len != 0 )
8978     {
8979         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
8980 
8981         if( cert_len > (size_t)( end - p ) )
8982             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
8983 
8984         session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
8985 
8986         if( session->peer_cert == NULL )
8987             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
8988 
8989         mbedtls_x509_crt_init( session->peer_cert );
8990 
8991         if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert,
8992                                                 p, cert_len ) ) != 0 )
8993         {
8994             mbedtls_x509_crt_free( session->peer_cert );
8995             mbedtls_free( session->peer_cert );
8996             session->peer_cert = NULL;
8997             return( ret );
8998         }
8999 
9000         p += cert_len;
9001     }
9002 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
9003     /* Deserialize CRT digest from the end of the ticket. */
9004     if( 2 > (size_t)( end - p ) )
9005         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9006 
9007     session->peer_cert_digest_type = (mbedtls_md_type_t) *p++;
9008     session->peer_cert_digest_len  = (size_t) *p++;
9009 
9010     if( session->peer_cert_digest_len != 0 )
9011     {
9012         const mbedtls_md_info_t *md_info =
9013             mbedtls_md_info_from_type( session->peer_cert_digest_type );
9014         if( md_info == NULL )
9015             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9016         if( session->peer_cert_digest_len != mbedtls_md_get_size( md_info ) )
9017             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9018 
9019         if( session->peer_cert_digest_len > (size_t)( end - p ) )
9020             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9021 
9022         session->peer_cert_digest =
9023             mbedtls_calloc( 1, session->peer_cert_digest_len );
9024         if( session->peer_cert_digest == NULL )
9025             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
9026 
9027         memcpy( session->peer_cert_digest, p,
9028                 session->peer_cert_digest_len );
9029         p += session->peer_cert_digest_len;
9030     }
9031 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
9032 #endif /* MBEDTLS_X509_CRT_PARSE_C */
9033 
9034     /*
9035      * Session ticket and associated data
9036      */
9037 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
9038     if( 3 > (size_t)( end - p ) )
9039         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9040 
9041     session->ticket_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
9042     p += 3;
9043 
9044     if( session->ticket_len != 0 )
9045     {
9046         if( session->ticket_len > (size_t)( end - p ) )
9047             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9048 
9049         session->ticket = mbedtls_calloc( 1, session->ticket_len );
9050         if( session->ticket == NULL )
9051             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
9052 
9053         memcpy( session->ticket, p, session->ticket_len );
9054         p += session->ticket_len;
9055     }
9056 
9057     if( 4 > (size_t)( end - p ) )
9058         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9059 
9060     session->ticket_lifetime = ( (uint32_t) p[0] << 24 ) |
9061                                ( (uint32_t) p[1] << 16 ) |
9062                                ( (uint32_t) p[2] <<  8 ) |
9063                                ( (uint32_t) p[3]       );
9064     p += 4;
9065 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
9066 
9067     /*
9068      * Misc extension-related info
9069      */
9070 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
9071     if( 1 > (size_t)( end - p ) )
9072         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9073 
9074     session->mfl_code = *p++;
9075 #endif
9076 
9077 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
9078     if( 1 > (size_t)( end - p ) )
9079         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9080 
9081     session->encrypt_then_mac = *p++;
9082 #endif
9083 
9084     /* Done, should have consumed entire buffer */
9085     if( p != end )
9086         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9087 
9088     return( 0 );
9089 }
9090 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
9091 
mbedtls_ssl_validate_ciphersuite(const mbedtls_ssl_context * ssl,const mbedtls_ssl_ciphersuite_t * suite_info,mbedtls_ssl_protocol_version min_tls_version,mbedtls_ssl_protocol_version max_tls_version)9092 int mbedtls_ssl_validate_ciphersuite(
9093     const mbedtls_ssl_context *ssl,
9094     const mbedtls_ssl_ciphersuite_t *suite_info,
9095     mbedtls_ssl_protocol_version min_tls_version,
9096     mbedtls_ssl_protocol_version max_tls_version )
9097 {
9098     (void) ssl;
9099 
9100     if( suite_info == NULL )
9101         return( -1 );
9102 
9103     if( ( suite_info->min_tls_version > max_tls_version ) ||
9104         ( suite_info->max_tls_version < min_tls_version ) )
9105     {
9106         return( -1 );
9107     }
9108 
9109 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_SSL_CLI_C)
9110 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
9111 #if defined(MBEDTLS_USE_PSA_CRYPTO)
9112     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
9113         ssl->handshake->psa_pake_ctx_is_ok != 1 )
9114 #else
9115     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
9116         mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
9117 #endif /* MBEDTLS_USE_PSA_CRYPTO */
9118     {
9119         return( -1 );
9120     }
9121 #endif
9122 
9123     /* Don't suggest PSK-based ciphersuite if no PSK is available. */
9124 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
9125     if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) &&
9126         mbedtls_ssl_conf_has_static_psk( ssl->conf ) == 0 )
9127     {
9128         return( -1 );
9129     }
9130 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
9131 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
9132 
9133     return( 0 );
9134 }
9135 
9136 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
9137 /*
9138  * Function for writing a signature algorithm extension.
9139  *
9140  * The `extension_data` field of signature algorithm contains  a `SignatureSchemeList`
9141  * value (TLS 1.3 RFC8446):
9142  *      enum {
9143  *         ....
9144  *        ecdsa_secp256r1_sha256( 0x0403 ),
9145  *        ecdsa_secp384r1_sha384( 0x0503 ),
9146  *        ecdsa_secp521r1_sha512( 0x0603 ),
9147  *         ....
9148  *      } SignatureScheme;
9149  *
9150  *      struct {
9151  *         SignatureScheme supported_signature_algorithms<2..2^16-2>;
9152  *      } SignatureSchemeList;
9153  *
9154  * The `extension_data` field of signature algorithm contains a `SignatureAndHashAlgorithm`
9155  * value (TLS 1.2 RFC5246):
9156  *      enum {
9157  *          none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
9158  *          sha512(6), (255)
9159  *      } HashAlgorithm;
9160  *
9161  *      enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
9162  *        SignatureAlgorithm;
9163  *
9164  *      struct {
9165  *          HashAlgorithm hash;
9166  *          SignatureAlgorithm signature;
9167  *      } SignatureAndHashAlgorithm;
9168  *
9169  *      SignatureAndHashAlgorithm
9170  *        supported_signature_algorithms<2..2^16-2>;
9171  *
9172  * The TLS 1.3 signature algorithm extension was defined to be a compatible
9173  * generalization of the TLS 1.2 signature algorithm extension.
9174  * `SignatureAndHashAlgorithm` field of TLS 1.2 can be represented by
9175  * `SignatureScheme` field of TLS 1.3
9176  *
9177  */
mbedtls_ssl_write_sig_alg_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * out_len)9178 int mbedtls_ssl_write_sig_alg_ext( mbedtls_ssl_context *ssl, unsigned char *buf,
9179                                    const unsigned char *end, size_t *out_len )
9180 {
9181     unsigned char *p = buf;
9182     unsigned char *supported_sig_alg; /* Start of supported_signature_algorithms */
9183     size_t supported_sig_alg_len = 0; /* Length of supported_signature_algorithms */
9184 
9185     *out_len = 0;
9186 
9187     MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding signature_algorithms extension" ) );
9188 
9189     /* Check if we have space for header and length field:
9190      * - extension_type         (2 bytes)
9191      * - extension_data_length  (2 bytes)
9192      * - supported_signature_algorithms_length   (2 bytes)
9193      */
9194     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 );
9195     p += 6;
9196 
9197     /*
9198      * Write supported_signature_algorithms
9199      */
9200     supported_sig_alg = p;
9201     const uint16_t *sig_alg = mbedtls_ssl_get_sig_algs( ssl );
9202     if( sig_alg == NULL )
9203         return( MBEDTLS_ERR_SSL_BAD_CONFIG );
9204 
9205     for( ; *sig_alg != MBEDTLS_TLS1_3_SIG_NONE; sig_alg++ )
9206     {
9207         MBEDTLS_SSL_DEBUG_MSG( 3, ( "got signature scheme [%x] %s",
9208                                     *sig_alg,
9209                                     mbedtls_ssl_sig_alg_to_str( *sig_alg ) ) );
9210         if( ! mbedtls_ssl_sig_alg_is_supported( ssl, *sig_alg ) )
9211             continue;
9212         MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
9213         MBEDTLS_PUT_UINT16_BE( *sig_alg, p, 0 );
9214         p += 2;
9215         MBEDTLS_SSL_DEBUG_MSG( 3, ( "sent signature scheme [%x] %s",
9216                                     *sig_alg,
9217                                     mbedtls_ssl_sig_alg_to_str( *sig_alg ) ) );
9218     }
9219 
9220     /* Length of supported_signature_algorithms */
9221     supported_sig_alg_len = p - supported_sig_alg;
9222     if( supported_sig_alg_len == 0 )
9223     {
9224         MBEDTLS_SSL_DEBUG_MSG( 1, ( "No signature algorithms defined." ) );
9225         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
9226     }
9227 
9228     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_SIG_ALG, buf, 0 );
9229     MBEDTLS_PUT_UINT16_BE( supported_sig_alg_len + 2, buf, 2 );
9230     MBEDTLS_PUT_UINT16_BE( supported_sig_alg_len, buf, 4 );
9231 
9232     *out_len = p - buf;
9233 
9234 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
9235     mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_SIG_ALG );
9236 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
9237 
9238     return( 0 );
9239 }
9240 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
9241 
9242 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
9243 /*
9244  * mbedtls_ssl_parse_server_name_ext
9245  *
9246  * Structure of server_name extension:
9247  *
9248  *  enum {
9249  *        host_name(0), (255)
9250  *     } NameType;
9251  *  opaque HostName<1..2^16-1>;
9252  *
9253  *  struct {
9254  *          NameType name_type;
9255  *          select (name_type) {
9256  *             case host_name: HostName;
9257  *           } name;
9258  *     } ServerName;
9259  *  struct {
9260  *          ServerName server_name_list<1..2^16-1>
9261  *     } ServerNameList;
9262  */
9263 MBEDTLS_CHECK_RETURN_CRITICAL
mbedtls_ssl_parse_server_name_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)9264 int mbedtls_ssl_parse_server_name_ext( mbedtls_ssl_context *ssl,
9265                                        const unsigned char *buf,
9266                                        const unsigned char *end )
9267 {
9268     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
9269     const unsigned char *p = buf;
9270     size_t server_name_list_len, hostname_len;
9271     const unsigned char *server_name_list_end;
9272 
9273     MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) );
9274 
9275     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 2 );
9276     server_name_list_len = MBEDTLS_GET_UINT16_BE( p, 0 );
9277     p += 2;
9278 
9279     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, server_name_list_len );
9280     server_name_list_end = p + server_name_list_len;
9281     while( p < server_name_list_end )
9282     {
9283         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, server_name_list_end, 3 );
9284         hostname_len = MBEDTLS_GET_UINT16_BE( p, 1 );
9285         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, server_name_list_end,
9286                                       hostname_len + 3 );
9287 
9288         if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME )
9289         {
9290             /* sni_name is intended to be used only during the parsing of the
9291              * ClientHello message (it is reset to NULL before the end of
9292              * the message parsing). Thus it is ok to just point to the
9293              * reception buffer and not make a copy of it.
9294              */
9295             ssl->handshake->sni_name = p + 3;
9296             ssl->handshake->sni_name_len = hostname_len;
9297             if( ssl->conf->f_sni == NULL )
9298                 return( 0 );
9299             ret = ssl->conf->f_sni( ssl->conf->p_sni,
9300                                     ssl, p + 3, hostname_len );
9301             if( ret != 0 )
9302             {
9303                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret );
9304                 MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME,
9305                                               MBEDTLS_ERR_SSL_UNRECOGNIZED_NAME );
9306                 return( MBEDTLS_ERR_SSL_UNRECOGNIZED_NAME );
9307             }
9308             return( 0 );
9309         }
9310 
9311         p += hostname_len + 3;
9312     }
9313 
9314     return( 0 );
9315 }
9316 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
9317 
9318 #if defined(MBEDTLS_SSL_ALPN)
9319 MBEDTLS_CHECK_RETURN_CRITICAL
mbedtls_ssl_parse_alpn_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,const unsigned char * end)9320 int mbedtls_ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
9321                                 const unsigned char *buf,
9322                                 const unsigned char *end )
9323 {
9324     const unsigned char *p = buf;
9325     size_t protocol_name_list_len;
9326     const unsigned char *protocol_name_list;
9327     const unsigned char *protocol_name_list_end;
9328     size_t protocol_name_len;
9329 
9330     /* If ALPN not configured, just ignore the extension */
9331     if( ssl->conf->alpn_list == NULL )
9332         return( 0 );
9333 
9334     /*
9335      * RFC7301, section 3.1
9336      *      opaque ProtocolName<1..2^8-1>;
9337      *
9338      *      struct {
9339      *          ProtocolName protocol_name_list<2..2^16-1>
9340      *      } ProtocolNameList;
9341      */
9342 
9343     /*
9344      * protocol_name_list_len    2 bytes
9345      * protocol_name_len         1 bytes
9346      * protocol_name             >=1 byte
9347      */
9348     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 4 );
9349 
9350     protocol_name_list_len = MBEDTLS_GET_UINT16_BE( p, 0 );
9351     p += 2;
9352     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, protocol_name_list_len );
9353     protocol_name_list = p;
9354     protocol_name_list_end = p + protocol_name_list_len;
9355 
9356     /* Validate peer's list (lengths) */
9357     while( p < protocol_name_list_end )
9358     {
9359         protocol_name_len = *p++;
9360         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, protocol_name_list_end,
9361                                       protocol_name_len );
9362         if( protocol_name_len == 0 )
9363         {
9364             MBEDTLS_SSL_PEND_FATAL_ALERT(
9365                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
9366                 MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
9367             return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
9368         }
9369 
9370         p += protocol_name_len;
9371     }
9372 
9373     /* Use our order of preference */
9374     for( const char **alpn = ssl->conf->alpn_list; *alpn != NULL; alpn++ )
9375     {
9376         size_t const alpn_len = strlen( *alpn );
9377         p = protocol_name_list;
9378         while( p < protocol_name_list_end )
9379         {
9380             protocol_name_len = *p++;
9381             if( protocol_name_len == alpn_len &&
9382                 memcmp( p, *alpn, alpn_len ) == 0 )
9383             {
9384                 ssl->alpn_chosen = *alpn;
9385                 return( 0 );
9386             }
9387 
9388             p += protocol_name_len;
9389         }
9390     }
9391 
9392     /* If we get here, no match was found */
9393     MBEDTLS_SSL_PEND_FATAL_ALERT(
9394             MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL,
9395             MBEDTLS_ERR_SSL_NO_APPLICATION_PROTOCOL );
9396     return( MBEDTLS_ERR_SSL_NO_APPLICATION_PROTOCOL );
9397 }
9398 
mbedtls_ssl_write_alpn_ext(mbedtls_ssl_context * ssl,unsigned char * buf,unsigned char * end,size_t * out_len)9399 int mbedtls_ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
9400                                 unsigned char *buf,
9401                                 unsigned char *end,
9402                                 size_t *out_len )
9403 {
9404     unsigned char *p = buf;
9405     size_t protocol_name_len;
9406     *out_len = 0;
9407 
9408     if( ssl->alpn_chosen == NULL )
9409     {
9410         return( 0 );
9411     }
9412 
9413     protocol_name_len = strlen( ssl->alpn_chosen );
9414     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 7 + protocol_name_len );
9415 
9416     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server side, adding alpn extension" ) );
9417     /*
9418      * 0 . 1    ext identifier
9419      * 2 . 3    ext length
9420      * 4 . 5    protocol list length
9421      * 6 . 6    protocol name length
9422      * 7 . 7+n  protocol name
9423      */
9424     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_ALPN, p, 0 );
9425 
9426     *out_len = 7 + protocol_name_len;
9427 
9428     MBEDTLS_PUT_UINT16_BE( protocol_name_len + 3, p, 2 );
9429     MBEDTLS_PUT_UINT16_BE( protocol_name_len + 1, p, 4 );
9430     /* Note: the length of the chosen protocol has been checked to be less
9431      * than 255 bytes in `mbedtls_ssl_conf_alpn_protocols`.
9432      */
9433     p[6] = MBEDTLS_BYTE_0( protocol_name_len );
9434 
9435     memcpy( p + 7, ssl->alpn_chosen, protocol_name_len );
9436 
9437 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
9438     mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_ALPN );
9439 #endif
9440 
9441     return ( 0 );
9442 }
9443 #endif /* MBEDTLS_SSL_ALPN */
9444 
9445 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
9446     defined(MBEDTLS_SSL_SESSION_TICKETS) && \
9447     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \
9448     defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_session_set_hostname(mbedtls_ssl_session * session,const char * hostname)9449 int mbedtls_ssl_session_set_hostname( mbedtls_ssl_session *session,
9450                                       const char *hostname )
9451 {
9452     /* Initialize to suppress unnecessary compiler warning */
9453     size_t hostname_len = 0;
9454 
9455     /* Check if new hostname is valid before
9456      * making any change to current one */
9457     if( hostname != NULL )
9458     {
9459         hostname_len = strlen( hostname );
9460 
9461         if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
9462             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
9463     }
9464 
9465     /* Now it's clear that we will overwrite the old hostname,
9466      * so we can free it safely */
9467     if( session->hostname != NULL )
9468     {
9469         mbedtls_platform_zeroize( session->hostname,
9470                                   strlen( session->hostname ) );
9471         mbedtls_free( session->hostname );
9472     }
9473 
9474     /* Passing NULL as hostname shall clear the old one */
9475     if( hostname == NULL )
9476     {
9477         session->hostname = NULL;
9478     }
9479     else
9480     {
9481         session->hostname = mbedtls_calloc( 1, hostname_len + 1 );
9482         if( session->hostname == NULL )
9483             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
9484 
9485         memcpy( session->hostname, hostname, hostname_len );
9486     }
9487 
9488     return( 0 );
9489 }
9490 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 &&
9491           MBEDTLS_SSL_SESSION_TICKETS &&
9492           MBEDTLS_SSL_SERVER_NAME_INDICATION &&
9493           MBEDTLS_SSL_CLI_C */
9494 
9495 #endif /* MBEDTLS_SSL_TLS_C */
9496