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