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