NCBI C++ ToolKit
ssl_tls.c
Go to the documentation of this file.

Go to the SVN repository for this file.

1 /*
2  * SSLv3/TLSv1 shared functions
3  *
4  * Copyright The Mbed TLS Contributors
5  * SPDX-License-Identifier: Apache-2.0
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may
8  * not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 /*
20  * The SSL 3.0 specification was drafted by Netscape in 1996,
21  * and became an IETF standard in 1999.
22  *
23  * http://wp.netscape.com/eng/ssl3/
24  * http://www.ietf.org/rfc/rfc2246.txt
25  * http://www.ietf.org/rfc/rfc4346.txt
26  */
27 
28 #include "common.h"
29 
30 #if defined(MBEDTLS_SSL_TLS_C)
31 
32 #include "mbedtls/platform.h"
33 
34 #include "mbedtls/ssl.h"
35 #include "mbedtls/ssl_internal.h"
36 #include "mbedtls/debug.h"
37 #include "mbedtls/error.h"
38 #include "mbedtls/platform_util.h"
39 #include "mbedtls/version.h"
40 #include "mbedtls/constant_time.h"
41 
42 #include <string.h>
43 
44 #if defined(MBEDTLS_USE_PSA_CRYPTO)
45 #include "mbedtls/psa_util.h"
46 #include "psa/crypto.h"
47 #endif
48 
49 #if defined(MBEDTLS_X509_CRT_PARSE_C)
50 #include "mbedtls/oid.h"
51 #endif
52 
53 #if defined(MBEDTLS_SSL_PROTO_DTLS)
54 
55 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
56 /* Top-level Connection ID API */
57 
58 int mbedtls_ssl_conf_cid(mbedtls_ssl_config *conf,
59  size_t len,
60  int ignore_other_cid)
61 {
64  }
65 
66  if (ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_FAIL &&
67  ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_IGNORE) {
69  }
70 
71  conf->ignore_unexpected_cid = ignore_other_cid;
72  conf->cid_len = len;
73  return 0;
74 }
75 
76 int mbedtls_ssl_set_cid(mbedtls_ssl_context *ssl,
77  int enable,
78  unsigned char const *own_cid,
79  size_t own_cid_len)
80 {
83  }
84 
85  ssl->negotiate_cid = enable;
86  if (enable == MBEDTLS_SSL_CID_DISABLED) {
87  MBEDTLS_SSL_DEBUG_MSG(3, ("Disable use of CID extension."));
88  return 0;
89  }
90  MBEDTLS_SSL_DEBUG_MSG(3, ("Enable use of CID extension."));
91  MBEDTLS_SSL_DEBUG_BUF(3, "Own CID", own_cid, own_cid_len);
92 
93  if (own_cid_len != ssl->conf->cid_len) {
94  MBEDTLS_SSL_DEBUG_MSG(3, ("CID length %u does not match CID length %u in config",
95  (unsigned) own_cid_len,
96  (unsigned) ssl->conf->cid_len));
98  }
99 
100  memcpy(ssl->own_cid, own_cid, own_cid_len);
101  /* Truncation is not an issue here because
102  * MBEDTLS_SSL_CID_IN_LEN_MAX at most 255. */
103  ssl->own_cid_len = (uint8_t) own_cid_len;
104 
105  return 0;
106 }
107 
108 int mbedtls_ssl_get_peer_cid(mbedtls_ssl_context *ssl,
109  int *enabled,
110  unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],
111  size_t *peer_cid_len)
112 {
113  *enabled = MBEDTLS_SSL_CID_DISABLED;
114 
118  }
119 
120  /* We report MBEDTLS_SSL_CID_DISABLED in case the CID extensions
121  * were used, but client and server requested the empty CID.
122  * This is indistinguishable from not using the CID extension
123  * in the first place. */
124  if (ssl->transform_in->in_cid_len == 0 &&
125  ssl->transform_in->out_cid_len == 0) {
126  return 0;
127  }
128 
129  if (peer_cid_len != NULL) {
130  *peer_cid_len = ssl->transform_in->out_cid_len;
131  if (peer_cid != NULL) {
132  memcpy(peer_cid, ssl->transform_in->out_cid,
133  ssl->transform_in->out_cid_len);
134  }
135  }
136 
137  *enabled = MBEDTLS_SSL_CID_ENABLED;
138 
139  return 0;
140 }
141 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
142 
143 #endif /* MBEDTLS_SSL_PROTO_DTLS */
144 
145 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
146 /*
147  * Convert max_fragment_length codes to length.
148  * RFC 6066 says:
149  * enum{
150  * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
151  * } MaxFragmentLength;
152  * and we add 0 -> extension unused
153  */
154 static unsigned int ssl_mfl_code_to_length(int mfl)
155 {
156  switch (mfl) {
160  return 512;
162  return 1024;
164  return 2048;
166  return 4096;
167  default:
169  }
170 }
171 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
172 
174  const mbedtls_ssl_session *src)
175 {
177  memcpy(dst, src, sizeof(mbedtls_ssl_session));
178 
179 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
180  dst->ticket = NULL;
181 #endif
182 
183 #if defined(MBEDTLS_X509_CRT_PARSE_C)
184 
185 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
186  if (src->peer_cert != NULL) {
188 
189  dst->peer_cert = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
190  if (dst->peer_cert == NULL) {
192  }
193 
194  mbedtls_x509_crt_init(dst->peer_cert);
195 
196  if ((ret = mbedtls_x509_crt_parse_der(dst->peer_cert, src->peer_cert->raw.p,
197  src->peer_cert->raw.len)) != 0) {
198  mbedtls_free(dst->peer_cert);
199  dst->peer_cert = NULL;
200  return ret;
201  }
202  }
203 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
204  if (src->peer_cert_digest != NULL) {
205  dst->peer_cert_digest =
206  mbedtls_calloc(1, src->peer_cert_digest_len);
207  if (dst->peer_cert_digest == NULL) {
209  }
210 
211  memcpy(dst->peer_cert_digest, src->peer_cert_digest,
212  src->peer_cert_digest_len);
213  dst->peer_cert_digest_type = src->peer_cert_digest_type;
214  dst->peer_cert_digest_len = src->peer_cert_digest_len;
215  }
216 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
217 
218 #endif /* MBEDTLS_X509_CRT_PARSE_C */
219 
220 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
221  if (src->ticket != NULL) {
222  dst->ticket = mbedtls_calloc(1, src->ticket_len);
223  if (dst->ticket == NULL) {
225  }
226 
227  memcpy(dst->ticket, src->ticket, src->ticket_len);
228  }
229 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
230 
231  return 0;
232 }
233 
234 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
236 static int resize_buffer(unsigned char **buffer, size_t len_new, size_t *len_old)
237 {
238  unsigned char *resized_buffer = mbedtls_calloc(1, len_new);
239  if (resized_buffer == NULL) {
240  return -1;
241  }
242 
243  /* We want to copy len_new bytes when downsizing the buffer, and
244  * len_old bytes when upsizing, so we choose the smaller of two sizes,
245  * to fit one buffer into another. Size checks, ensuring that no data is
246  * lost, are done outside of this function. */
247  memcpy(resized_buffer, *buffer,
248  (len_new < *len_old) ? len_new : *len_old);
249  mbedtls_platform_zeroize(*buffer, *len_old);
251 
252  *buffer = resized_buffer;
253  *len_old = len_new;
254 
255  return 0;
256 }
257 
258 static void handle_buffer_resizing(mbedtls_ssl_context *ssl, int downsizing,
259  size_t in_buf_new_len,
260  size_t out_buf_new_len)
261 {
262  int modified = 0;
263  size_t written_in = 0, iv_offset_in = 0, len_offset_in = 0;
264  size_t written_out = 0, iv_offset_out = 0, len_offset_out = 0;
265  if (ssl->in_buf != NULL) {
266  written_in = ssl->in_msg - ssl->in_buf;
267  iv_offset_in = ssl->in_iv - ssl->in_buf;
268  len_offset_in = ssl->in_len - ssl->in_buf;
269  if (downsizing ?
270  ssl->in_buf_len > in_buf_new_len && ssl->in_left < in_buf_new_len :
271  ssl->in_buf_len < in_buf_new_len) {
272  if (resize_buffer(&ssl->in_buf, in_buf_new_len, &ssl->in_buf_len) != 0) {
273  MBEDTLS_SSL_DEBUG_MSG(1, ("input buffer resizing failed - out of memory"));
274  } else {
275  MBEDTLS_SSL_DEBUG_MSG(2, ("Reallocating in_buf to %" MBEDTLS_PRINTF_SIZET,
276  in_buf_new_len));
277  modified = 1;
278  }
279  }
280  }
281 
282  if (ssl->out_buf != NULL) {
283  written_out = ssl->out_msg - ssl->out_buf;
284  iv_offset_out = ssl->out_iv - ssl->out_buf;
285  len_offset_out = ssl->out_len - ssl->out_buf;
286  if (downsizing ?
287  ssl->out_buf_len > out_buf_new_len && ssl->out_left < out_buf_new_len :
288  ssl->out_buf_len < out_buf_new_len) {
289  if (resize_buffer(&ssl->out_buf, out_buf_new_len, &ssl->out_buf_len) != 0) {
290  MBEDTLS_SSL_DEBUG_MSG(1, ("output buffer resizing failed - out of memory"));
291  } else {
292  MBEDTLS_SSL_DEBUG_MSG(2, ("Reallocating out_buf to %" MBEDTLS_PRINTF_SIZET,
293  out_buf_new_len));
294  modified = 1;
295  }
296  }
297  }
298  if (modified) {
299  /* Update pointers here to avoid doing it twice. */
301  /* Fields below might not be properly updated with record
302  * splitting or with CID, so they are manually updated here. */
303  ssl->out_msg = ssl->out_buf + written_out;
304  ssl->out_len = ssl->out_buf + len_offset_out;
305  ssl->out_iv = ssl->out_buf + iv_offset_out;
306 
307  ssl->in_msg = ssl->in_buf + written_in;
308  ssl->in_len = ssl->in_buf + len_offset_in;
309  ssl->in_iv = ssl->in_buf + iv_offset_in;
310  }
311 }
312 #endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */
313 
314 /*
315  * Key material generation
316  */
317 #if defined(MBEDTLS_SSL_PROTO_SSL3)
319 static int ssl3_prf(const unsigned char *secret, size_t slen,
320  const char *label,
321  const unsigned char *random, size_t rlen,
322  unsigned char *dstbuf, size_t dlen)
323 {
324  int ret = 0;
325  size_t i;
328  unsigned char padding[16];
329  unsigned char sha1sum[20];
330  ((void) label);
331 
334 
335  /*
336  * SSLv3:
337  * block =
338  * MD5( secret + SHA1( 'A' + secret + random ) ) +
339  * MD5( secret + SHA1( 'BB' + secret + random ) ) +
340  * MD5( secret + SHA1( 'CCC' + secret + random ) ) +
341  * ...
342  */
343  for (i = 0; i < dlen / 16; i++) {
344  memset(padding, (unsigned char) ('A' + i), 1 + i);
345 
346  if ((ret = mbedtls_sha1_starts_ret(&sha1)) != 0) {
347  goto exit;
348  }
349  if ((ret = mbedtls_sha1_update_ret(&sha1, padding, 1 + i)) != 0) {
350  goto exit;
351  }
352  if ((ret = mbedtls_sha1_update_ret(&sha1, secret, slen)) != 0) {
353  goto exit;
354  }
355  if ((ret = mbedtls_sha1_update_ret(&sha1, random, rlen)) != 0) {
356  goto exit;
357  }
358  if ((ret = mbedtls_sha1_finish_ret(&sha1, sha1sum)) != 0) {
359  goto exit;
360  }
361 
362  if ((ret = mbedtls_md5_starts_ret(&md5)) != 0) {
363  goto exit;
364  }
365  if ((ret = mbedtls_md5_update_ret(&md5, secret, slen)) != 0) {
366  goto exit;
367  }
368  if ((ret = mbedtls_md5_update_ret(&md5, sha1sum, 20)) != 0) {
369  goto exit;
370  }
371  if ((ret = mbedtls_md5_finish_ret(&md5, dstbuf + i * 16)) != 0) {
372  goto exit;
373  }
374  }
375 
376 exit:
379 
381  mbedtls_platform_zeroize(sha1sum, sizeof(sha1sum));
382 
383  return ret;
384 }
385 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
386 
387 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
389 static int tls1_prf(const unsigned char *secret, size_t slen,
390  const char *label,
391  const unsigned char *random, size_t rlen,
392  unsigned char *dstbuf, size_t dlen)
393 {
394  size_t nb, hs;
395  size_t i, j, k;
396  const unsigned char *S1, *S2;
397  unsigned char *tmp;
398  size_t tmp_len = 0;
399  unsigned char h_i[20];
400  const mbedtls_md_info_t *md_info;
401  mbedtls_md_context_t md_ctx;
403 
404  mbedtls_md_init(&md_ctx);
405 
406  tmp_len = 20 + strlen(label) + rlen;
407  tmp = mbedtls_calloc(1, tmp_len);
408  if (tmp == NULL) {
410  goto exit;
411  }
412 
413  hs = (slen + 1) / 2;
414  S1 = secret;
415  S2 = secret + slen - hs;
416 
417  nb = strlen(label);
418  memcpy(tmp + 20, label, nb);
419  memcpy(tmp + 20 + nb, random, rlen);
420  nb += rlen;
421 
422  /*
423  * First compute P_md5(secret,label+random)[0..dlen]
424  */
425  if ((md_info = mbedtls_md_info_from_type(MBEDTLS_MD_MD5)) == NULL) {
427  goto exit;
428  }
429 
430  if ((ret = mbedtls_md_setup(&md_ctx, md_info, 1)) != 0) {
431  goto exit;
432  }
433 
434  ret = mbedtls_md_hmac_starts(&md_ctx, S1, hs);
435  if (ret != 0) {
436  goto exit;
437  }
438  ret = mbedtls_md_hmac_update(&md_ctx, tmp + 20, nb);
439  if (ret != 0) {
440  goto exit;
441  }
442  ret = mbedtls_md_hmac_finish(&md_ctx, 4 + tmp);
443  if (ret != 0) {
444  goto exit;
445  }
446 
447  for (i = 0; i < dlen; i += 16) {
448  ret = mbedtls_md_hmac_reset(&md_ctx);
449  if (ret != 0) {
450  goto exit;
451  }
452  ret = mbedtls_md_hmac_update(&md_ctx, 4 + tmp, 16 + nb);
453  if (ret != 0) {
454  goto exit;
455  }
456  ret = mbedtls_md_hmac_finish(&md_ctx, h_i);
457  if (ret != 0) {
458  goto exit;
459  }
460 
461  ret = mbedtls_md_hmac_reset(&md_ctx);
462  if (ret != 0) {
463  goto exit;
464  }
465  ret = mbedtls_md_hmac_update(&md_ctx, 4 + tmp, 16);
466  if (ret != 0) {
467  goto exit;
468  }
469  ret = mbedtls_md_hmac_finish(&md_ctx, 4 + tmp);
470  if (ret != 0) {
471  goto exit;
472  }
473 
474  k = (i + 16 > dlen) ? dlen % 16 : 16;
475 
476  for (j = 0; j < k; j++) {
477  dstbuf[i + j] = h_i[j];
478  }
479  }
480 
481  mbedtls_md_free(&md_ctx);
482 
483  /*
484  * XOR out with P_sha1(secret,label+random)[0..dlen]
485  */
486  if ((md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1)) == NULL) {
488  goto exit;
489  }
490 
491  if ((ret = mbedtls_md_setup(&md_ctx, md_info, 1)) != 0) {
492  goto exit;
493  }
494 
495  ret = mbedtls_md_hmac_starts(&md_ctx, S2, hs);
496  if (ret != 0) {
497  goto exit;
498  }
499  ret = mbedtls_md_hmac_update(&md_ctx, tmp + 20, nb);
500  if (ret != 0) {
501  goto exit;
502  }
503  ret = mbedtls_md_hmac_finish(&md_ctx, tmp);
504  if (ret != 0) {
505  goto exit;
506  }
507 
508  for (i = 0; i < dlen; i += 20) {
509  ret = mbedtls_md_hmac_reset(&md_ctx);
510  if (ret != 0) {
511  goto exit;
512  }
513  ret = mbedtls_md_hmac_update(&md_ctx, tmp, 20 + nb);
514  if (ret != 0) {
515  goto exit;
516  }
517  ret = mbedtls_md_hmac_finish(&md_ctx, h_i);
518  if (ret != 0) {
519  goto exit;
520  }
521 
522  ret = mbedtls_md_hmac_reset(&md_ctx);
523  if (ret != 0) {
524  goto exit;
525  }
526  ret = mbedtls_md_hmac_update(&md_ctx, tmp, 20);
527  if (ret != 0) {
528  goto exit;
529  }
530  ret = mbedtls_md_hmac_finish(&md_ctx, tmp);
531  if (ret != 0) {
532  goto exit;
533  }
534 
535  k = (i + 20 > dlen) ? dlen % 20 : 20;
536 
537  for (j = 0; j < k; j++) {
538  dstbuf[i + j] = (unsigned char) (dstbuf[i + j] ^ h_i[j]);
539  }
540  }
541 
542 exit:
543  mbedtls_md_free(&md_ctx);
544 
545  mbedtls_platform_zeroize(tmp, tmp_len);
546  mbedtls_platform_zeroize(h_i, sizeof(h_i));
547 
548  mbedtls_free(tmp);
549  return ret;
550 }
551 #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
552 
553 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
554 #if defined(MBEDTLS_USE_PSA_CRYPTO)
555 
556 static psa_status_t setup_psa_key_derivation(psa_key_derivation_operation_t *derivation,
558  psa_algorithm_t alg,
559  const unsigned char *seed, size_t seed_length,
560  const unsigned char *label, size_t label_length,
561  size_t capacity)
562 {
563  psa_status_t status;
564 
565  status = psa_key_derivation_setup(derivation, alg);
566  if (status != PSA_SUCCESS) {
567  return status;
568  }
569 
571  status = psa_key_derivation_input_bytes(derivation,
573  seed, seed_length);
574  if (status != PSA_SUCCESS) {
575  return status;
576  }
577 
581  NULL, 0);
582  } else {
584  derivation, PSA_KEY_DERIVATION_INPUT_SECRET, key);
585  }
586  if (status != PSA_SUCCESS) {
587  return status;
588  }
589 
590  status = psa_key_derivation_input_bytes(derivation,
592  label, label_length);
593  if (status != PSA_SUCCESS) {
594  return status;
595  }
596  } else {
598  }
599 
600  status = psa_key_derivation_set_capacity(derivation, capacity);
601  if (status != PSA_SUCCESS) {
602  return status;
603  }
604 
605  return PSA_SUCCESS;
606 }
607 
609 static int tls_prf_generic(mbedtls_md_type_t md_type,
610  const unsigned char *secret, size_t slen,
611  const char *label,
612  const unsigned char *random, size_t rlen,
613  unsigned char *dstbuf, size_t dlen)
614 {
615  psa_status_t status;
616  psa_algorithm_t alg;
618  psa_key_derivation_operation_t derivation =
620 
621  if (md_type == MBEDTLS_MD_SHA384) {
623  } else {
625  }
626 
627  /* Normally a "secret" should be long enough to be impossible to
628  * find by brute force, and in particular should not be empty. But
629  * this PRF is also used to derive an IV, in particular in EAP-TLS,
630  * and for this use case it makes sense to have a 0-length "secret".
631  * Since the key API doesn't allow importing a key of length 0,
632  * keep master_key=0, which setup_psa_key_derivation() understands
633  * to mean a 0-length "secret" input. */
634  if (slen != 0) {
637  psa_set_key_algorithm(&key_attributes, alg);
638  psa_set_key_type(&key_attributes, PSA_KEY_TYPE_DERIVE);
639 
640  status = psa_import_key(&key_attributes, secret, slen, &master_key);
641  if (status != PSA_SUCCESS) {
643  }
644  }
645 
646  status = setup_psa_key_derivation(&derivation,
647  master_key, alg,
648  random, rlen,
649  (unsigned char const *) label,
650  (size_t) strlen(label),
651  dlen);
652  if (status != PSA_SUCCESS) {
653  psa_key_derivation_abort(&derivation);
654  psa_destroy_key(master_key);
656  }
657 
658  status = psa_key_derivation_output_bytes(&derivation, dstbuf, dlen);
659  if (status != PSA_SUCCESS) {
660  psa_key_derivation_abort(&derivation);
661  psa_destroy_key(master_key);
663  }
664 
665  status = psa_key_derivation_abort(&derivation);
666  if (status != PSA_SUCCESS) {
667  psa_destroy_key(master_key);
669  }
670 
671  if (!mbedtls_svc_key_id_is_null(master_key)) {
672  status = psa_destroy_key(master_key);
673  }
674  if (status != PSA_SUCCESS) {
676  }
677 
678  return 0;
679 }
680 
681 #else /* MBEDTLS_USE_PSA_CRYPTO */
682 
685  const unsigned char *secret, size_t slen,
686  const char *label,
687  const unsigned char *random, size_t rlen,
688  unsigned char *dstbuf, size_t dlen)
689 {
690  size_t nb;
691  size_t i, j, k, md_len;
692  unsigned char *tmp;
693  size_t tmp_len = 0;
694  unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
695  const mbedtls_md_info_t *md_info;
696  mbedtls_md_context_t md_ctx;
698 
699  mbedtls_md_init(&md_ctx);
700 
701  if ((md_info = mbedtls_md_info_from_type(md_type)) == NULL) {
703  }
704 
705  md_len = mbedtls_md_get_size(md_info);
706 
707  tmp_len = md_len + strlen(label) + rlen;
708  tmp = mbedtls_calloc(1, tmp_len);
709  if (tmp == NULL) {
711  goto exit;
712  }
713 
714  nb = strlen(label);
715  memcpy(tmp + md_len, label, nb);
716  memcpy(tmp + md_len + nb, random, rlen);
717  nb += rlen;
718 
719  /*
720  * Compute P_<hash>(secret, label + random)[0..dlen]
721  */
722  if ((ret = mbedtls_md_setup(&md_ctx, md_info, 1)) != 0) {
723  goto exit;
724  }
725 
726  ret = mbedtls_md_hmac_starts(&md_ctx, secret, slen);
727  if (ret != 0) {
728  goto exit;
729  }
730  ret = mbedtls_md_hmac_update(&md_ctx, tmp + md_len, nb);
731  if (ret != 0) {
732  goto exit;
733  }
734  ret = mbedtls_md_hmac_finish(&md_ctx, tmp);
735  if (ret != 0) {
736  goto exit;
737  }
738 
739  for (i = 0; i < dlen; i += md_len) {
740  ret = mbedtls_md_hmac_reset(&md_ctx);
741  if (ret != 0) {
742  goto exit;
743  }
744  ret = mbedtls_md_hmac_update(&md_ctx, tmp, md_len + nb);
745  if (ret != 0) {
746  goto exit;
747  }
748  ret = mbedtls_md_hmac_finish(&md_ctx, h_i);
749  if (ret != 0) {
750  goto exit;
751  }
752 
753  ret = mbedtls_md_hmac_reset(&md_ctx);
754  if (ret != 0) {
755  goto exit;
756  }
757  ret = mbedtls_md_hmac_update(&md_ctx, tmp, md_len);
758  if (ret != 0) {
759  goto exit;
760  }
761  ret = mbedtls_md_hmac_finish(&md_ctx, tmp);
762  if (ret != 0) {
763  goto exit;
764  }
765 
766  k = (i + md_len > dlen) ? dlen % md_len : md_len;
767 
768  for (j = 0; j < k; j++) {
769  dstbuf[i + j] = h_i[j];
770  }
771  }
772 
773 exit:
774  mbedtls_md_free(&md_ctx);
775 
776  if (tmp != NULL) {
777  mbedtls_platform_zeroize(tmp, tmp_len);
778  }
779 
780  mbedtls_platform_zeroize(h_i, sizeof(h_i));
781 
782  mbedtls_free(tmp);
783 
784  return ret;
785 }
786 #endif /* MBEDTLS_USE_PSA_CRYPTO */
787 #if defined(MBEDTLS_SHA256_C)
789 static int tls_prf_sha256(const unsigned char *secret, size_t slen,
790  const char *label,
791  const unsigned char *random, size_t rlen,
792  unsigned char *dstbuf, size_t dlen)
793 {
794  return tls_prf_generic(MBEDTLS_MD_SHA256, secret, slen,
795  label, random, rlen, dstbuf, dlen);
796 }
797 #endif /* MBEDTLS_SHA256_C */
798 
799 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
801 static int tls_prf_sha384(const unsigned char *secret, size_t slen,
802  const char *label,
803  const unsigned char *random, size_t rlen,
804  unsigned char *dstbuf, size_t dlen)
805 {
806  return tls_prf_generic(MBEDTLS_MD_SHA384, secret, slen,
807  label, random, rlen, dstbuf, dlen);
808 }
809 #endif /* MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384 */
810 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
811 
812 static void ssl_update_checksum_start(mbedtls_ssl_context *, const unsigned char *, size_t);
813 
814 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
815  defined(MBEDTLS_SSL_PROTO_TLS1_1)
816 static void ssl_update_checksum_md5sha1(mbedtls_ssl_context *, const unsigned char *, size_t);
817 #endif
818 
819 #if defined(MBEDTLS_SSL_PROTO_SSL3)
820 static void ssl_calc_verify_ssl(const mbedtls_ssl_context *, unsigned char *, size_t *);
821 static void ssl_calc_finished_ssl(mbedtls_ssl_context *, unsigned char *, int);
822 #endif
823 
824 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
825 static void ssl_calc_verify_tls(const mbedtls_ssl_context *, unsigned char *, size_t *);
826 static void ssl_calc_finished_tls(mbedtls_ssl_context *, unsigned char *, int);
827 #endif
828 
829 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
830 #if defined(MBEDTLS_SHA256_C)
831 static void ssl_update_checksum_sha256(mbedtls_ssl_context *, const unsigned char *, size_t);
832 static void ssl_calc_verify_tls_sha256(const mbedtls_ssl_context *, unsigned char *, size_t *);
833 static void ssl_calc_finished_tls_sha256(mbedtls_ssl_context *, unsigned char *, int);
834 #endif
835 
836 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
837 static void ssl_update_checksum_sha384(mbedtls_ssl_context *, const unsigned char *, size_t);
838 static void ssl_calc_verify_tls_sha384(const mbedtls_ssl_context *, unsigned char *, size_t *);
839 static void ssl_calc_finished_tls_sha384(mbedtls_ssl_context *, unsigned char *, int);
840 #endif
841 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
842 
843 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) && \
844  defined(MBEDTLS_USE_PSA_CRYPTO)
846 static int ssl_use_opaque_psk(mbedtls_ssl_context const *ssl)
847 {
848  if (ssl->conf->f_psk != NULL) {
849  /* If we've used a callback to select the PSK,
850  * the static configuration is irrelevant. */
851  if (!mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque)) {
852  return 1;
853  }
854 
855  return 0;
856  }
857 
858  if (!mbedtls_svc_key_id_is_null(ssl->conf->psk_opaque)) {
859  return 1;
860  }
861 
862  return 0;
863 }
864 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
865  MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
866 
867 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
869 {
870 #if defined(MBEDTLS_SSL_PROTO_SSL3)
871  if (tls_prf == ssl3_prf) {
873  } else
874 #endif
875 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
876  if (tls_prf == tls1_prf) {
878  } else
879 #endif
880 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
881 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
882  if (tls_prf == tls_prf_sha384) {
884  } else
885 #endif
886 #if defined(MBEDTLS_SHA256_C)
887  if (tls_prf == tls_prf_sha256) {
889  } else
890 #endif
891 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
893 }
894 #endif /* MBEDTLS_SSL_EXPORT_KEYS */
895 
897  const unsigned char *secret, size_t slen,
898  const char *label,
899  const unsigned char *random, size_t rlen,
900  unsigned char *dstbuf, size_t dlen)
901 {
902  mbedtls_ssl_tls_prf_cb *tls_prf = NULL;
903 
904  switch (prf) {
905 #if defined(MBEDTLS_SSL_PROTO_SSL3)
907  tls_prf = ssl3_prf;
908  break;
909 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
910 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
912  tls_prf = tls1_prf;
913  break;
914 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
915 
916 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
917 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
919  tls_prf = tls_prf_sha384;
920  break;
921 #endif /* MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384 */
922 #if defined(MBEDTLS_SHA256_C)
924  tls_prf = tls_prf_sha256;
925  break;
926 #endif /* MBEDTLS_SHA256_C */
927 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
928  default:
930  }
931 
932  return tls_prf(secret, slen, label, random, rlen, dstbuf, dlen);
933 }
934 
935 /* Type for the TLS PRF */
936 typedef int ssl_tls_prf_t(const unsigned char *, size_t, const char *,
937  const unsigned char *, size_t,
938  unsigned char *, size_t);
939 
940 /*
941  * Populate a transform structure with session keys and all the other
942  * necessary information.
943  *
944  * Parameters:
945  * - [in/out]: transform: structure to populate
946  * [in] must be just initialised with mbedtls_ssl_transform_init()
947  * [out] fully populated, ready for use by mbedtls_ssl_{en,de}crypt_buf()
948  * - [in] ciphersuite
949  * - [in] master
950  * - [in] encrypt_then_mac
951  * - [in] trunc_hmac
952  * - [in] compression
953  * - [in] tls_prf: pointer to PRF to use for key derivation
954  * - [in] randbytes: buffer holding ServerHello.random + ClientHello.random
955  * - [in] minor_ver: SSL/TLS minor version
956  * - [in] endpoint: client or server
957  * - [in] ssl: optionally used for:
958  * - MBEDTLS_SSL_HW_RECORD_ACCEL: whole context (non-const)
959  * - MBEDTLS_SSL_EXPORT_KEYS: ssl->conf->{f,p}_export_keys
960  * - MBEDTLS_DEBUG_C: ssl->conf->{f,p}_dbg
961  */
964  int ciphersuite,
965  const unsigned char master[48],
966 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
967 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
968  int encrypt_then_mac,
969 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
970 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
971  int trunc_hmac,
972 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
973 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
974 #if defined(MBEDTLS_ZLIB_SUPPORT)
975  int compression,
976 #endif
977  ssl_tls_prf_t tls_prf,
978  const unsigned char randbytes[64],
979  int minor_ver,
980  unsigned endpoint,
981 #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
982  const
983 #endif
984  mbedtls_ssl_context *ssl)
985 {
986  int ret = 0;
987 #if defined(MBEDTLS_USE_PSA_CRYPTO)
988  int psa_fallthrough;
989 #endif /* MBEDTLS_USE_PSA_CRYPTO */
990  int do_mbedtls_cipher_setup;
991  unsigned char keyblk[256];
992  unsigned char *key1;
993  unsigned char *key2;
994  unsigned char *mac_enc;
995  unsigned char *mac_dec;
996  size_t mac_key_len = 0;
997  size_t iv_copy_len;
998  unsigned keylen;
999  const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1000  const mbedtls_cipher_info_t *cipher_info;
1001  const mbedtls_md_info_t *md_info;
1002 
1003 #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL) && \
1004  !defined(MBEDTLS_SSL_EXPORT_KEYS) && \
1005  !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
1006  !defined(MBEDTLS_DEBUG_C)
1007  ssl = NULL; /* make sure we don't use it except for those cases */
1008  (void) ssl;
1009 #endif
1010 
1011  /*
1012  * Some data just needs copying into the structure
1013  */
1014 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \
1015  defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1016  transform->encrypt_then_mac = encrypt_then_mac;
1017 #endif
1018  transform->minor_ver = minor_ver;
1019 
1020 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
1021  memcpy(transform->randbytes, randbytes, sizeof(transform->randbytes));
1022 #endif
1023 
1024  /*
1025  * Get various info structures
1026  */
1027  ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(ciphersuite);
1028  if (ciphersuite_info == NULL) {
1029  MBEDTLS_SSL_DEBUG_MSG(1, ("ciphersuite info for %d not found",
1030  ciphersuite));
1032  }
1033 
1034  cipher_info = mbedtls_cipher_info_from_type(ciphersuite_info->cipher);
1035  if (cipher_info == NULL) {
1036  MBEDTLS_SSL_DEBUG_MSG(1, ("cipher info for %u not found",
1037  ciphersuite_info->cipher));
1039  }
1040 
1041  md_info = mbedtls_md_info_from_type(ciphersuite_info->mac);
1042  if (md_info == NULL) {
1043  MBEDTLS_SSL_DEBUG_MSG(1, ("mbedtls_md info for %u not found",
1044  (unsigned) ciphersuite_info->mac));
1046  }
1047 
1048 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1049  /* Copy own and peer's CID if the use of the CID
1050  * extension has been negotiated. */
1051  if (ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_ENABLED) {
1052  MBEDTLS_SSL_DEBUG_MSG(3, ("Copy CIDs into SSL transform"));
1053 
1054  transform->in_cid_len = ssl->own_cid_len;
1055  memcpy(transform->in_cid, ssl->own_cid, ssl->own_cid_len);
1056  MBEDTLS_SSL_DEBUG_BUF(3, "Incoming CID", transform->in_cid,
1057  transform->in_cid_len);
1058 
1059  transform->out_cid_len = ssl->handshake->peer_cid_len;
1060  memcpy(transform->out_cid, ssl->handshake->peer_cid,
1061  ssl->handshake->peer_cid_len);
1062  MBEDTLS_SSL_DEBUG_BUF(3, "Outgoing CID", transform->out_cid,
1063  transform->out_cid_len);
1064  }
1065 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1066 
1067  /*
1068  * Compute key block using the PRF
1069  */
1070  ret = tls_prf(master, 48, "key expansion", randbytes, 64, keyblk, 256);
1071  if (ret != 0) {
1072  MBEDTLS_SSL_DEBUG_RET(1, "prf", ret);
1073  return ret;
1074  }
1075 
1076  MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite = %s",
1077  mbedtls_ssl_get_ciphersuite_name(ciphersuite)));
1078  MBEDTLS_SSL_DEBUG_BUF(3, "master secret", master, 48);
1079  MBEDTLS_SSL_DEBUG_BUF(4, "random bytes", randbytes, 64);
1080  MBEDTLS_SSL_DEBUG_BUF(4, "key block", keyblk, 256);
1081 
1082  /*
1083  * Determine the appropriate key, IV and MAC length.
1084  */
1085 
1086  keylen = cipher_info->key_bitlen / 8;
1087 
1088 #if defined(MBEDTLS_GCM_C) || \
1089  defined(MBEDTLS_CCM_C) || \
1090  defined(MBEDTLS_CHACHAPOLY_C)
1091  if (cipher_info->mode == MBEDTLS_MODE_GCM ||
1092  cipher_info->mode == MBEDTLS_MODE_CCM ||
1093  cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY) {
1094  size_t explicit_ivlen;
1095 
1096  transform->maclen = 0;
1097  mac_key_len = 0;
1098  transform->taglen =
1099  ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1100 
1101  /* All modes haves 96-bit IVs, but the length of the static parts vary
1102  * with mode and version:
1103  * - For GCM and CCM in TLS 1.2, there's a static IV of 4 Bytes
1104  * (to be concatenated with a dynamically chosen IV of 8 Bytes)
1105  * - For ChaChaPoly in TLS 1.2, and all modes in TLS 1.3, there's
1106  * a static IV of 12 Bytes (to be XOR'ed with the 8 Byte record
1107  * sequence number).
1108  */
1109  transform->ivlen = 12;
1110 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
1111  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_4) {
1112  transform->fixed_ivlen = 12;
1113  } else
1114 #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
1115  {
1116  if (cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY) {
1117  transform->fixed_ivlen = 12;
1118  } else {
1119  transform->fixed_ivlen = 4;
1120  }
1121  }
1122 
1123  /* Minimum length of encrypted record */
1124  explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
1125  transform->minlen = explicit_ivlen + transform->taglen;
1126  } else
1127 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
1128 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1129  if (cipher_info->mode == MBEDTLS_MODE_STREAM ||
1130  cipher_info->mode == MBEDTLS_MODE_CBC) {
1131  /* Initialize HMAC contexts */
1132  if ((ret = mbedtls_md_setup(&transform->md_ctx_enc, md_info, 1)) != 0 ||
1133  (ret = mbedtls_md_setup(&transform->md_ctx_dec, md_info, 1)) != 0) {
1134  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_setup", ret);
1135  goto end;
1136  }
1137 
1138  /* Get MAC length */
1139  mac_key_len = mbedtls_md_get_size(md_info);
1140  transform->maclen = mac_key_len;
1141 
1142 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1143  /*
1144  * If HMAC is to be truncated, we shall keep the leftmost bytes,
1145  * (rfc 6066 page 13 or rfc 2104 section 4),
1146  * so we only need to adjust the length here.
1147  */
1148  if (trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED) {
1150 
1151 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
1152  /* Fall back to old, non-compliant version of the truncated
1153  * HMAC implementation which also truncates the key
1154  * (Mbed TLS versions from 1.3 to 2.6.0) */
1155  mac_key_len = transform->maclen;
1156 #endif
1157  }
1158 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1159 
1160  /* IV length */
1161  transform->ivlen = cipher_info->iv_size;
1162 
1163  /* Minimum length */
1164  if (cipher_info->mode == MBEDTLS_MODE_STREAM) {
1165  transform->minlen = transform->maclen;
1166  } else {
1167  /*
1168  * GenericBlockCipher:
1169  * 1. if EtM is in use: one block plus MAC
1170  * otherwise: * first multiple of blocklen greater than maclen
1171  * 2. IV except for SSL3 and TLS 1.0
1172  */
1173 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1174  if (encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED) {
1175  transform->minlen = transform->maclen
1176  + cipher_info->block_size;
1177  } else
1178 #endif
1179  {
1180  transform->minlen = transform->maclen
1181  + cipher_info->block_size
1182  - transform->maclen % cipher_info->block_size;
1183  }
1184 
1185 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1186  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
1187  minor_ver == MBEDTLS_SSL_MINOR_VERSION_1) {
1188  ; /* No need to adjust minlen */
1189  } else
1190 #endif
1191 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1192  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
1193  minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1194  transform->minlen += transform->ivlen;
1195  } else
1196 #endif
1197  {
1198  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1200  goto end;
1201  }
1202  }
1203  } else
1204 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1205  {
1206  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1208  }
1209 
1210  MBEDTLS_SSL_DEBUG_MSG(3, ("keylen: %u, minlen: %u, ivlen: %u, maclen: %u",
1211  (unsigned) keylen,
1212  (unsigned) transform->minlen,
1213  (unsigned) transform->ivlen,
1214  (unsigned) transform->maclen));
1215 
1216  /*
1217  * Finally setup the cipher contexts, IVs and MAC secrets.
1218  */
1219 #if defined(MBEDTLS_SSL_CLI_C)
1220  if (endpoint == MBEDTLS_SSL_IS_CLIENT) {
1221  key1 = keyblk + mac_key_len * 2;
1222  key2 = keyblk + mac_key_len * 2 + keylen;
1223 
1224  mac_enc = keyblk;
1225  mac_dec = keyblk + mac_key_len;
1226 
1227  /*
1228  * This is not used in TLS v1.1.
1229  */
1230  iv_copy_len = (transform->fixed_ivlen) ?
1231  transform->fixed_ivlen : transform->ivlen;
1232  memcpy(transform->iv_enc, key2 + keylen, iv_copy_len);
1233  memcpy(transform->iv_dec, key2 + keylen + iv_copy_len,
1234  iv_copy_len);
1235  } else
1236 #endif /* MBEDTLS_SSL_CLI_C */
1237 #if defined(MBEDTLS_SSL_SRV_C)
1238  if (endpoint == MBEDTLS_SSL_IS_SERVER) {
1239  key1 = keyblk + mac_key_len * 2 + keylen;
1240  key2 = keyblk + mac_key_len * 2;
1241 
1242  mac_enc = keyblk + mac_key_len;
1243  mac_dec = keyblk;
1244 
1245  /*
1246  * This is not used in TLS v1.1.
1247  */
1248  iv_copy_len = (transform->fixed_ivlen) ?
1249  transform->fixed_ivlen : transform->ivlen;
1250  memcpy(transform->iv_dec, key1 + keylen, iv_copy_len);
1251  memcpy(transform->iv_enc, key1 + keylen + iv_copy_len,
1252  iv_copy_len);
1253  } else
1254 #endif /* MBEDTLS_SSL_SRV_C */
1255  {
1256  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1258  goto end;
1259  }
1260 
1261 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1262 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1263  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
1264  if (mac_key_len > sizeof(transform->mac_enc)) {
1265  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1267  goto end;
1268  }
1269 
1270  memcpy(transform->mac_enc, mac_enc, mac_key_len);
1271  memcpy(transform->mac_dec, mac_dec, mac_key_len);
1272  } else
1273 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1274 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1275  defined(MBEDTLS_SSL_PROTO_TLS1_2)
1276  if (minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1) {
1277  /* For HMAC-based ciphersuites, initialize the HMAC transforms.
1278  For AEAD-based ciphersuites, there is nothing to do here. */
1279  if (mac_key_len != 0) {
1280  ret = mbedtls_md_hmac_starts(&transform->md_ctx_enc,
1281  mac_enc, mac_key_len);
1282  if (ret != 0) {
1283  goto end;
1284  }
1285  ret = mbedtls_md_hmac_starts(&transform->md_ctx_dec,
1286  mac_dec, mac_key_len);
1287  if (ret != 0) {
1288  goto end;
1289  }
1290  }
1291  } else
1292 #endif
1293  {
1294  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1296  goto end;
1297  }
1298 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1299 
1300 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
1301  if (mbedtls_ssl_hw_record_init != NULL) {
1302  ret = 0;
1303 
1304  MBEDTLS_SSL_DEBUG_MSG(2, ("going for mbedtls_ssl_hw_record_init()"));
1305 
1306  if ((ret = mbedtls_ssl_hw_record_init(ssl, key1, key2, keylen,
1307  transform->iv_enc, transform->iv_dec,
1308  iv_copy_len,
1309  mac_enc, mac_dec,
1310  mac_key_len)) != 0) {
1311  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_hw_record_init", ret);
1313  goto end;
1314  }
1315  }
1316 #else
1317  ((void) mac_dec);
1318  ((void) mac_enc);
1319 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
1320 
1321 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
1322  if (ssl->conf->f_export_keys != NULL) {
1323  ssl->conf->f_export_keys(ssl->conf->p_export_keys,
1324  master, keyblk,
1325  mac_key_len, keylen,
1326  iv_copy_len);
1327  }
1328 
1329  if (ssl->conf->f_export_keys_ext != NULL) {
1330  ssl->conf->f_export_keys_ext(ssl->conf->p_export_keys,
1331  master, keyblk,
1332  mac_key_len, keylen,
1333  iv_copy_len,
1334  randbytes + 32,
1335  randbytes,
1336  tls_prf_get_type(tls_prf));
1337  }
1338 #endif
1339 
1340  do_mbedtls_cipher_setup = 1;
1341 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1342 
1343  /* Only use PSA-based ciphers for TLS-1.2.
1344  * That's relevant at least for TLS-1.0, where
1345  * we assume that mbedtls_cipher_crypt() updates
1346  * the structure field for the IV, which the PSA-based
1347  * implementation currently doesn't. */
1348 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1349  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1350  ret = mbedtls_cipher_setup_psa(&transform->cipher_ctx_enc,
1351  cipher_info, transform->taglen);
1352  if (ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) {
1353  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup_psa", ret);
1354  goto end;
1355  }
1356 
1357  if (ret == 0) {
1358  MBEDTLS_SSL_DEBUG_MSG(3, ("Successfully setup PSA-based encryption cipher context"));
1359  psa_fallthrough = 0;
1360  } else {
1362  (
1363  "Failed to setup PSA-based cipher context for record encryption - fall through to default setup."));
1364  psa_fallthrough = 1;
1365  }
1366  } else {
1367  psa_fallthrough = 1;
1368  }
1369 #else
1370  psa_fallthrough = 1;
1371 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1372 
1373  if (psa_fallthrough == 0) {
1374  do_mbedtls_cipher_setup = 0;
1375  }
1376 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1377  if (do_mbedtls_cipher_setup &&
1378  (ret = mbedtls_cipher_setup(&transform->cipher_ctx_enc,
1379  cipher_info)) != 0) {
1380  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup", ret);
1381  goto end;
1382  }
1383 
1384  do_mbedtls_cipher_setup = 1;
1385 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1386  /* Only use PSA-based ciphers for TLS-1.2.
1387  * That's relevant at least for TLS-1.0, where
1388  * we assume that mbedtls_cipher_crypt() updates
1389  * the structure field for the IV, which the PSA-based
1390  * implementation currently doesn't. */
1391 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1392  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1393  ret = mbedtls_cipher_setup_psa(&transform->cipher_ctx_dec,
1394  cipher_info, transform->taglen);
1395  if (ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) {
1396  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup_psa", ret);
1397  goto end;
1398  }
1399 
1400  if (ret == 0) {
1401  MBEDTLS_SSL_DEBUG_MSG(3, ("Successfully setup PSA-based decryption cipher context"));
1402  psa_fallthrough = 0;
1403  } else {
1405  (
1406  "Failed to setup PSA-based cipher context for record decryption - fall through to default setup."));
1407  psa_fallthrough = 1;
1408  }
1409  } else {
1410  psa_fallthrough = 1;
1411  }
1412 #else
1413  psa_fallthrough = 1;
1414 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1415 
1416  if (psa_fallthrough == 0) {
1417  do_mbedtls_cipher_setup = 0;
1418  }
1419 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1420  if (do_mbedtls_cipher_setup &&
1421  (ret = mbedtls_cipher_setup(&transform->cipher_ctx_dec,
1422  cipher_info)) != 0) {
1423  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup", ret);
1424  goto end;
1425  }
1426 
1427  if ((ret = mbedtls_cipher_setkey(&transform->cipher_ctx_enc, key1,
1428  cipher_info->key_bitlen,
1429  MBEDTLS_ENCRYPT)) != 0) {
1430  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setkey", ret);
1431  goto end;
1432  }
1433 
1434  if ((ret = mbedtls_cipher_setkey(&transform->cipher_ctx_dec, key2,
1435  cipher_info->key_bitlen,
1436  MBEDTLS_DECRYPT)) != 0) {
1437  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setkey", ret);
1438  goto end;
1439  }
1440 
1441 #if defined(MBEDTLS_CIPHER_MODE_CBC)
1442  if (cipher_info->mode == MBEDTLS_MODE_CBC) {
1443  if ((ret = mbedtls_cipher_set_padding_mode(&transform->cipher_ctx_enc,
1444  MBEDTLS_PADDING_NONE)) != 0) {
1445  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_set_padding_mode", ret);
1446  goto end;
1447  }
1448 
1449  if ((ret = mbedtls_cipher_set_padding_mode(&transform->cipher_ctx_dec,
1450  MBEDTLS_PADDING_NONE)) != 0) {
1451  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_set_padding_mode", ret);
1452  goto end;
1453  }
1454  }
1455 #endif /* MBEDTLS_CIPHER_MODE_CBC */
1456 
1457 
1458  /* Initialize Zlib contexts */
1459 #if defined(MBEDTLS_ZLIB_SUPPORT)
1460  if (compression == MBEDTLS_SSL_COMPRESS_DEFLATE) {
1461  MBEDTLS_SSL_DEBUG_MSG(3, ("Initializing zlib states"));
1462 
1463  memset(&transform->ctx_deflate, 0, sizeof(transform->ctx_deflate));
1464  memset(&transform->ctx_inflate, 0, sizeof(transform->ctx_inflate));
1465 
1466  if (deflateInit(&transform->ctx_deflate,
1468  inflateInit(&transform->ctx_inflate) != Z_OK) {
1469  MBEDTLS_SSL_DEBUG_MSG(1, ("Failed to initialize compression"));
1471  goto end;
1472  }
1473  }
1474 #endif /* MBEDTLS_ZLIB_SUPPORT */
1475 
1476 end:
1477  mbedtls_platform_zeroize(keyblk, sizeof(keyblk));
1478  return ret;
1479 }
1480 
1481 /*
1482  * Set appropriate PRF function and other SSL / TLS 1.0/1.1 / TLS1.2 functions
1483  *
1484  * Inputs:
1485  * - SSL/TLS minor version
1486  * - hash associated with the ciphersuite (only used by TLS 1.2)
1487  *
1488  * Outputs:
1489  * - the tls_prf, calc_verify and calc_finished members of handshake structure
1490  */
1493  int minor_ver,
1495 {
1496 #if !defined(MBEDTLS_SSL_PROTO_TLS1_2) || \
1497  !(defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384))
1498  (void) hash;
1499 #endif
1500 
1501 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1502  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
1503  handshake->tls_prf = ssl3_prf;
1504  handshake->calc_verify = ssl_calc_verify_ssl;
1505  handshake->calc_finished = ssl_calc_finished_ssl;
1506  } else
1507 #endif
1508 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1509  if (minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1510  handshake->tls_prf = tls1_prf;
1511  handshake->calc_verify = ssl_calc_verify_tls;
1512  handshake->calc_finished = ssl_calc_finished_tls;
1513  } else
1514 #endif
1515 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1516 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
1517  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
1518  hash == MBEDTLS_MD_SHA384) {
1519  handshake->tls_prf = tls_prf_sha384;
1522  } else
1523 #endif
1524 #if defined(MBEDTLS_SHA256_C)
1525  if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1526  handshake->tls_prf = tls_prf_sha256;
1529  } else
1530 #endif
1531 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1532  {
1534  }
1535 
1536  return 0;
1537 }
1538 
1539 /*
1540  * Compute master secret if needed
1541  *
1542  * Parameters:
1543  * [in/out] handshake
1544  * [in] resume, premaster, extended_ms, calc_verify, tls_prf
1545  * (PSA-PSK) ciphersuite_info, psk_opaque
1546  * [out] premaster (cleared)
1547  * [out] master
1548  * [in] ssl: optionally used for debugging, EMS and PSA-PSK
1549  * debug: conf->f_dbg, conf->p_dbg
1550  * EMS: passed to calc_verify (debug + (SSL3) session_negotiate)
1551  * PSA-PSA: minor_ver, conf
1552  */
1555  unsigned char *master,
1556  const mbedtls_ssl_context *ssl)
1557 {
1559 
1560  /* cf. RFC 5246, Section 8.1:
1561  * "The master secret is always exactly 48 bytes in length." */
1562  size_t const master_secret_len = 48;
1563 
1564 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1565  unsigned char session_hash[48];
1566 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1567 
1568  /* The label for the KDF used for key expansion.
1569  * This is either "master secret" or "extended master secret"
1570  * depending on whether the Extended Master Secret extension
1571  * is used. */
1572  char const *lbl = "master secret";
1573 
1574  /* The salt for the KDF used for key expansion.
1575  * - If the Extended Master Secret extension is not used,
1576  * this is ClientHello.Random + ServerHello.Random
1577  * (see Sect. 8.1 in RFC 5246).
1578  * - If the Extended Master Secret extension is used,
1579  * this is the transcript of the handshake so far.
1580  * (see Sect. 4 in RFC 7627). */
1581  unsigned char const *salt = handshake->randbytes;
1582  size_t salt_len = 64;
1583 
1584 #if !defined(MBEDTLS_DEBUG_C) && \
1585  !defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \
1586  !(defined(MBEDTLS_USE_PSA_CRYPTO) && \
1587  defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED))
1588  ssl = NULL; /* make sure we don't use it except for those cases */
1589  (void) ssl;
1590 #endif
1591 
1592  if (handshake->resume != 0) {
1593  MBEDTLS_SSL_DEBUG_MSG(3, ("no premaster (session resumed)"));
1594  return 0;
1595  }
1596 
1597 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1598  if (handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED) {
1599  lbl = "extended master secret";
1600  salt = session_hash;
1601  handshake->calc_verify(ssl, session_hash, &salt_len);
1602 
1603  MBEDTLS_SSL_DEBUG_BUF(3, "session hash for extended master secret",
1604  session_hash, salt_len);
1605  }
1606 #endif /* MBEDTLS_SSL_EXTENDED_MS_ENABLED */
1607 
1608 #if defined(MBEDTLS_USE_PSA_CRYPTO) && \
1609  defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1612  ssl_use_opaque_psk(ssl) == 1) {
1613  /* Perform PSK-to-MS expansion in a single step. */
1614  psa_status_t status;
1615  psa_algorithm_t alg;
1616  psa_key_id_t psk;
1617  psa_key_derivation_operation_t derivation =
1619  mbedtls_md_type_t hash_alg = handshake->ciphersuite_info->mac;
1620 
1621  MBEDTLS_SSL_DEBUG_MSG(2, ("perform PSA-based PSK-to-MS expansion"));
1622 
1623  psk = mbedtls_ssl_get_opaque_psk(ssl);
1624 
1625  if (hash_alg == MBEDTLS_MD_SHA384) {
1627  } else {
1629  }
1630 
1631  status = setup_psa_key_derivation(&derivation, psk, alg,
1632  salt, salt_len,
1633  (unsigned char const *) lbl,
1634  (size_t) strlen(lbl),
1635  master_secret_len);
1636  if (status != PSA_SUCCESS) {
1637  psa_key_derivation_abort(&derivation);
1639  }
1640 
1641  status = psa_key_derivation_output_bytes(&derivation,
1642  master,
1643  master_secret_len);
1644  if (status != PSA_SUCCESS) {
1645  psa_key_derivation_abort(&derivation);
1647  }
1648 
1649  status = psa_key_derivation_abort(&derivation);
1650  if (status != PSA_SUCCESS) {
1652  }
1653  } else
1654 #endif
1655  {
1656  ret = handshake->tls_prf(handshake->premaster, handshake->pmslen,
1657  lbl, salt, salt_len,
1658  master,
1659  master_secret_len);
1660  if (ret != 0) {
1661  MBEDTLS_SSL_DEBUG_RET(1, "prf", ret);
1662  return ret;
1663  }
1664 
1665  MBEDTLS_SSL_DEBUG_BUF(3, "premaster secret",
1666  handshake->premaster,
1667  handshake->pmslen);
1668 
1670  sizeof(handshake->premaster));
1671  }
1672 
1673  return 0;
1674 }
1675 
1677 {
1679  const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
1681 
1682  MBEDTLS_SSL_DEBUG_MSG(2, ("=> derive keys"));
1683 
1684  /* Set PRF, calc_verify and calc_finished function pointers */
1685  ret = ssl_set_handshake_prfs(ssl->handshake,
1686  ssl->minor_ver,
1687  ciphersuite_info->mac);
1688  if (ret != 0) {
1689  MBEDTLS_SSL_DEBUG_RET(1, "ssl_set_handshake_prfs", ret);
1690  return ret;
1691  }
1692 
1693  /* Compute master secret if needed */
1694  ret = ssl_compute_master(ssl->handshake,
1695  ssl->session_negotiate->master,
1696  ssl);
1697  if (ret != 0) {
1698  MBEDTLS_SSL_DEBUG_RET(1, "ssl_compute_master", ret);
1699  return ret;
1700  }
1701 
1702  /* Swap the client and server random values:
1703  * - MS derivation wanted client+server (RFC 5246 8.1)
1704  * - key derivation wants server+client (RFC 5246 6.3) */
1705  {
1706  unsigned char tmp[64];
1707  memcpy(tmp, ssl->handshake->randbytes, 64);
1708  memcpy(ssl->handshake->randbytes, tmp + 32, 32);
1709  memcpy(ssl->handshake->randbytes + 32, tmp, 32);
1710  mbedtls_platform_zeroize(tmp, sizeof(tmp));
1711  }
1712 
1713  /* Populate transform structure */
1716  ssl->session_negotiate->master,
1717 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1718 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1719  ssl->session_negotiate->encrypt_then_mac,
1720 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1721 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1722  ssl->session_negotiate->trunc_hmac,
1723 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1724 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1725 #if defined(MBEDTLS_ZLIB_SUPPORT)
1727 #endif
1728  ssl->handshake->tls_prf,
1729  ssl->handshake->randbytes,
1730  ssl->minor_ver,
1731  ssl->conf->endpoint,
1732  ssl);
1733  if (ret != 0) {
1734  MBEDTLS_SSL_DEBUG_RET(1, "ssl_populate_transform", ret);
1735  return ret;
1736  }
1737 
1738  /* We no longer need Server/ClientHello.random values */
1740  sizeof(ssl->handshake->randbytes));
1741 
1742  /* Allocate compression buffer */
1743 #if defined(MBEDTLS_ZLIB_SUPPORT)
1745  ssl->compress_buf == NULL) {
1746  MBEDTLS_SSL_DEBUG_MSG(3, ("Allocating compression buffer"));
1747  ssl->compress_buf = mbedtls_calloc(1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN);
1748  if (ssl->compress_buf == NULL) {
1749  MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%d bytes) failed",
1750  MBEDTLS_SSL_COMPRESS_BUFFER_LEN));
1752  }
1753  }
1754 #endif
1755 
1756  MBEDTLS_SSL_DEBUG_MSG(2, ("<= derive keys"));
1757 
1758  return 0;
1759 }
1760 
1761 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1762 void ssl_calc_verify_ssl(const mbedtls_ssl_context *ssl,
1763  unsigned char *hash,
1764  size_t *hlen)
1765 {
1768  unsigned char pad_1[48];
1769  unsigned char pad_2[48];
1770 
1771  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc verify ssl"));
1772 
1775 
1776  mbedtls_md5_clone(&md5, &ssl->handshake->fin_md5);
1777  mbedtls_sha1_clone(&sha1, &ssl->handshake->fin_sha1);
1778 
1779  memset(pad_1, 0x36, 48);
1780  memset(pad_2, 0x5C, 48);
1781 
1783  mbedtls_md5_update_ret(&md5, pad_1, 48);
1785 
1788  mbedtls_md5_update_ret(&md5, pad_2, 48);
1791 
1793  mbedtls_sha1_update_ret(&sha1, pad_1, 40);
1795 
1798  mbedtls_sha1_update_ret(&sha1, pad_2, 40);
1799  mbedtls_sha1_update_ret(&sha1, hash + 16, 20);
1801 
1802  *hlen = 36;
1803 
1804  MBEDTLS_SSL_DEBUG_BUF(3, "calculated verify result", hash, *hlen);
1805  MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc verify"));
1806 
1809 
1810  return;
1811 }
1812 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
1813 
1814 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1816  unsigned char *hash,
1817  size_t *hlen)
1818 {
1821 
1822  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc verify tls"));
1823 
1826 
1827  mbedtls_md5_clone(&md5, &ssl->handshake->fin_md5);
1828  mbedtls_sha1_clone(&sha1, &ssl->handshake->fin_sha1);
1829 
1832 
1833  *hlen = 36;
1834 
1835  MBEDTLS_SSL_DEBUG_BUF(3, "calculated verify result", hash, *hlen);
1836  MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc verify"));
1837 
1840 
1841  return;
1842 }
1843 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1844 
1845 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1846 #if defined(MBEDTLS_SHA256_C)
1848  unsigned char *hash,
1849  size_t *hlen)
1850 {
1851 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1852  size_t hash_size;
1853  psa_status_t status;
1855 
1856  MBEDTLS_SSL_DEBUG_MSG(2, ("=> PSA calc verify sha256"));
1857  status = psa_hash_clone(&ssl->handshake->fin_sha256_psa, &sha256_psa);
1858  if (status != PSA_SUCCESS) {
1859  MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash clone failed"));
1860  return;
1861  }
1862 
1863  status = psa_hash_finish(&sha256_psa, hash, 32, &hash_size);
1864  if (status != PSA_SUCCESS) {
1865  MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash finish failed"));
1866  return;
1867  }
1868 
1869  *hlen = 32;
1870  MBEDTLS_SSL_DEBUG_BUF(3, "PSA calculated verify result", hash, *hlen);
1871  MBEDTLS_SSL_DEBUG_MSG(2, ("<= PSA calc verify"));
1872 #else
1874 
1876 
1877  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc verify sha256"));
1878 
1879  mbedtls_sha256_clone(&sha256, &ssl->handshake->fin_sha256);
1881 
1882  *hlen = 32;
1883 
1884  MBEDTLS_SSL_DEBUG_BUF(3, "calculated verify result", hash, *hlen);
1885  MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc verify"));
1886 
1888 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1889  return;
1890 }
1891 #endif /* MBEDTLS_SHA256_C */
1892 
1893 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
1895  unsigned char *hash,
1896  size_t *hlen)
1897 {
1898 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1899  size_t hash_size;
1900  psa_status_t status;
1902 
1903  MBEDTLS_SSL_DEBUG_MSG(2, ("=> PSA calc verify sha384"));
1904  status = psa_hash_clone(&ssl->handshake->fin_sha384_psa, &sha384_psa);
1905  if (status != PSA_SUCCESS) {
1906  MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash clone failed"));
1907  return;
1908  }
1909 
1910  status = psa_hash_finish(&sha384_psa, hash, 48, &hash_size);
1911  if (status != PSA_SUCCESS) {
1912  MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash finish failed"));
1913  return;
1914  }
1915 
1916  *hlen = 48;
1917  MBEDTLS_SSL_DEBUG_BUF(3, "PSA calculated verify result", hash, *hlen);
1918  MBEDTLS_SSL_DEBUG_MSG(2, ("<= PSA calc verify"));
1919 #else
1921 
1923 
1924  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc verify sha384"));
1925 
1926  mbedtls_sha512_clone(&sha512, &ssl->handshake->fin_sha512);
1928 
1929  *hlen = 48;
1930 
1931  MBEDTLS_SSL_DEBUG_BUF(3, "calculated verify result", hash, *hlen);
1932  MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc verify"));
1933 
1935 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1936  return;
1937 }
1938 #endif /* MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384 */
1939 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1940 
1941 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
1943 {
1944  unsigned char *p = ssl->handshake->premaster;
1945  unsigned char *end = p + sizeof(ssl->handshake->premaster);
1946  const unsigned char *psk = NULL;
1947  size_t psk_len = 0;
1948 
1949  if (mbedtls_ssl_get_psk(ssl, &psk, &psk_len)
1951  /*
1952  * This should never happen because the existence of a PSK is always
1953  * checked before calling this function
1954  */
1955  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1957  }
1958 
1959  /*
1960  * PMS = struct {
1961  * opaque other_secret<0..2^16-1>;
1962  * opaque psk<0..2^16-1>;
1963  * };
1964  * with "other_secret" depending on the particular key exchange
1965  */
1966 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1967  if (key_ex == MBEDTLS_KEY_EXCHANGE_PSK) {
1968  if (end - p < 2) {
1970  }
1971 
1972  MBEDTLS_PUT_UINT16_BE(psk_len, p, 0);
1973  p += 2;
1974 
1975  if (end < p || (size_t) (end - p) < psk_len) {
1977  }
1978 
1979  memset(p, 0, psk_len);
1980  p += psk_len;
1981  } else
1982 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
1983 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1984  if (key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
1985  /*
1986  * other_secret already set by the ClientKeyExchange message,
1987  * and is 48 bytes long
1988  */
1989  if (end - p < 2) {
1991  }
1992 
1993  *p++ = 0;
1994  *p++ = 48;
1995  p += 48;
1996  } else
1997 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
1998 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1999  if (key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK) {
2001  size_t len;
2002 
2003  /* Write length only when we know the actual value */
2004  if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
2005  p + 2, end - (p + 2), &len,
2006  ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2007  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
2008  return ret;
2009  }
2010  MBEDTLS_PUT_UINT16_BE(len, p, 0);
2011  p += 2 + len;
2012 
2013  MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
2014  } else
2015 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2016 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
2017  if (key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
2019  size_t zlen;
2020 
2021  if ((ret = mbedtls_ecdh_calc_secret(&ssl->handshake->ecdh_ctx, &zlen,
2022  p + 2, end - (p + 2),
2023  ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2024  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_calc_secret", ret);
2025  return ret;
2026  }
2027 
2028  MBEDTLS_PUT_UINT16_BE(zlen, p, 0);
2029  p += 2 + zlen;
2030 
2031  MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
2032  MBEDTLS_DEBUG_ECDH_Z);
2033  } else
2034 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
2035  {
2036  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2038  }
2039 
2040  /* opaque psk<0..2^16-1>; */
2041  if (end - p < 2) {
2043  }
2044 
2045  MBEDTLS_PUT_UINT16_BE(psk_len, p, 0);
2046  p += 2;
2047 
2048  if (end < p || (size_t) (end - p) < psk_len) {
2050  }
2051 
2052  memcpy(p, psk, psk_len);
2053  p += psk_len;
2054 
2055  ssl->handshake->pmslen = p - ssl->handshake->premaster;
2056 
2057  return 0;
2058 }
2059 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
2060 
2061 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2064 
2065 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2067 {
2068  /* If renegotiation is not enforced, retransmit until we would reach max
2069  * timeout if we were using the usual handshake doubling scheme */
2070  if (ssl->conf->renego_max_records < 0) {
2071  uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
2072  unsigned char doublings = 1;
2073 
2074  while (ratio != 0) {
2075  ++doublings;
2076  ratio >>= 1;
2077  }
2078 
2079  if (++ssl->renego_records_seen > doublings) {
2080  MBEDTLS_SSL_DEBUG_MSG(2, ("no longer retransmitting hello request"));
2081  return 0;
2082  }
2083  }
2084 
2085  return ssl_write_hello_request(ssl);
2086 }
2087 #endif
2088 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2089 
2090 #if defined(MBEDTLS_X509_CRT_PARSE_C)
2092 {
2093 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2094  if (session->peer_cert != NULL) {
2095  mbedtls_x509_crt_free(session->peer_cert);
2096  mbedtls_free(session->peer_cert);
2097  session->peer_cert = NULL;
2098  }
2099 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2100  if (session->peer_cert_digest != NULL) {
2101  /* Zeroization is not necessary. */
2102  mbedtls_free(session->peer_cert_digest);
2103  session->peer_cert_digest = NULL;
2104  session->peer_cert_digest_type = MBEDTLS_MD_NONE;
2105  session->peer_cert_digest_len = 0;
2106  }
2107 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2108 }
2109 #endif /* MBEDTLS_X509_CRT_PARSE_C */
2110 
2111 /*
2112  * Handshake functions
2113  */
2114 #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
2115 /* No certificate support -> dummy functions */
2117 {
2118  const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2120 
2121  MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate"));
2122 
2123  if (!mbedtls_ssl_ciphersuite_uses_srv_cert(ciphersuite_info)) {
2124  MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate"));
2125  ssl->state++;
2126  return 0;
2127  }
2128 
2129  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2131 }
2132 
2134 {
2135  const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2137 
2138  MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate"));
2139 
2140  if (!mbedtls_ssl_ciphersuite_uses_srv_cert(ciphersuite_info)) {
2141  MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate"));
2142  ssl->state++;
2143  return 0;
2144  }
2145 
2146  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2148 }
2149 
2150 #else /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
2151 /* Some certificate support -> implement write and parse */
2152 
2154 {
2156  size_t i, n;
2157  const mbedtls_x509_crt *crt;
2158  const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2160 
2161  MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate"));
2162 
2163  if (!mbedtls_ssl_ciphersuite_uses_srv_cert(ciphersuite_info)) {
2164  MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate"));
2165  ssl->state++;
2166  return 0;
2167  }
2168 
2169 #if defined(MBEDTLS_SSL_CLI_C)
2170  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
2171  if (ssl->client_auth == 0) {
2172  MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate"));
2173  ssl->state++;
2174  return 0;
2175  }
2176 
2177 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2178  /*
2179  * If using SSLv3 and got no cert, send an Alert message
2180  * (otherwise an empty Certificate message will be sent).
2181  */
2182  if (mbedtls_ssl_own_cert(ssl) == NULL &&
2184  ssl->out_msglen = 2;
2188 
2189  MBEDTLS_SSL_DEBUG_MSG(2, ("got no certificate to send"));
2190  goto write_msg;
2191  }
2192 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
2193  }
2194 #endif /* MBEDTLS_SSL_CLI_C */
2195 #if defined(MBEDTLS_SSL_SRV_C)
2196  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
2197  if (mbedtls_ssl_own_cert(ssl) == NULL) {
2198  MBEDTLS_SSL_DEBUG_MSG(1, ("got no certificate to send"));
2200  }
2201  }
2202 #endif
2203 
2204  MBEDTLS_SSL_DEBUG_CRT(3, "own certificate", mbedtls_ssl_own_cert(ssl));
2205 
2206  /*
2207  * 0 . 0 handshake type
2208  * 1 . 3 handshake length
2209  * 4 . 6 length of all certs
2210  * 7 . 9 length of cert. 1
2211  * 10 . n-1 peer certificate
2212  * n . n+2 length of cert. 2
2213  * n+3 . ... upper level cert, etc.
2214  */
2215  i = 7;
2216  crt = mbedtls_ssl_own_cert(ssl);
2217 
2218  while (crt != NULL) {
2219  n = crt->raw.len;
2220  if (n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i) {
2221  MBEDTLS_SSL_DEBUG_MSG(1, ("certificate too large, %" MBEDTLS_PRINTF_SIZET
2222  " > %" MBEDTLS_PRINTF_SIZET,
2223  i + 3 + n, (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN));
2225  }
2226 
2227  ssl->out_msg[i] = MBEDTLS_BYTE_2(n);
2228  ssl->out_msg[i + 1] = MBEDTLS_BYTE_1(n);
2229  ssl->out_msg[i + 2] = MBEDTLS_BYTE_0(n);
2230 
2231  i += 3; memcpy(ssl->out_msg + i, crt->raw.p, n);
2232  i += n; crt = crt->next;
2233  }
2234 
2235  ssl->out_msg[4] = MBEDTLS_BYTE_2(i - 7);
2236  ssl->out_msg[5] = MBEDTLS_BYTE_1(i - 7);
2237  ssl->out_msg[6] = MBEDTLS_BYTE_0(i - 7);
2238 
2239  ssl->out_msglen = i;
2242 
2243 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
2244 write_msg:
2245 #endif
2246 
2247  ssl->state++;
2248 
2249  if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
2250  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
2251  return ret;
2252  }
2253 
2254  MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate"));
2255 
2256  return ret;
2257 }
2258 
2259 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2260 
2261 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2263 static int ssl_check_peer_crt_unchanged(mbedtls_ssl_context *ssl,
2264  unsigned char *crt_buf,
2265  size_t crt_buf_len)
2266 {
2267  mbedtls_x509_crt const * const peer_crt = ssl->session->peer_cert;
2268 
2269  if (peer_crt == NULL) {
2270  return -1;
2271  }
2272 
2273  if (peer_crt->raw.len != crt_buf_len) {
2274  return -1;
2275  }
2276 
2277  return memcmp(peer_crt->raw.p, crt_buf, peer_crt->raw.len);
2278 }
2279 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2281 static int ssl_check_peer_crt_unchanged(mbedtls_ssl_context *ssl,
2282  unsigned char *crt_buf,
2283  size_t crt_buf_len)
2284 {
2286  unsigned char const * const peer_cert_digest =
2287  ssl->session->peer_cert_digest;
2288  mbedtls_md_type_t const peer_cert_digest_type =
2289  ssl->session->peer_cert_digest_type;
2290  mbedtls_md_info_t const * const digest_info =
2291  mbedtls_md_info_from_type(peer_cert_digest_type);
2292  unsigned char tmp_digest[MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN];
2293  size_t digest_len;
2294 
2295  if (peer_cert_digest == NULL || digest_info == NULL) {
2296  return -1;
2297  }
2298 
2299  digest_len = mbedtls_md_get_size(digest_info);
2300  if (digest_len > MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN) {
2301  return -1;
2302  }
2303 
2304  ret = mbedtls_md(digest_info, crt_buf, crt_buf_len, tmp_digest);
2305  if (ret != 0) {
2306  return -1;
2307  }
2308 
2309  return memcmp(tmp_digest, peer_cert_digest, digest_len);
2310 }
2311 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2312 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
2313 
2314 /*
2315  * Once the certificate message is read, parse it into a cert chain and
2316  * perform basic checks, but leave actual verification to the caller
2317  */
2319 static int ssl_parse_certificate_chain(mbedtls_ssl_context *ssl,
2320  mbedtls_x509_crt *chain)
2321 {
2323 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2324  int crt_cnt = 0;
2325 #endif
2326  size_t i, n;
2327  uint8_t alert;
2328 
2329  if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
2330  MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2334  }
2335 
2336  if (ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
2337  ssl->in_hslen < mbedtls_ssl_hs_hdr_len(ssl) + 3 + 3) {
2338  MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2342  }
2343 
2344  i = mbedtls_ssl_hs_hdr_len(ssl);
2345 
2346  /*
2347  * Same message structure as in mbedtls_ssl_write_certificate()
2348  */
2349  n = (ssl->in_msg[i+1] << 8) | ssl->in_msg[i+2];
2350 
2351  if (ssl->in_msg[i] != 0 ||
2352  ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len(ssl)) {
2353  MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2357  }
2358 
2359  /* Make &ssl->in_msg[i] point to the beginning of the CRT chain. */
2360  i += 3;
2361 
2362  /* Iterate through and parse the CRTs in the provided chain. */
2363  while (i < ssl->in_hslen) {
2364  /* Check that there's room for the next CRT's length fields. */
2365  if (i + 3 > ssl->in_hslen) {
2366  MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2371  }
2372  /* In theory, the CRT can be up to 2**24 Bytes, but we don't support
2373  * anything beyond 2**16 ~ 64K. */
2374  if (ssl->in_msg[i] != 0) {
2375  MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2380  }
2381 
2382  /* Read length of the next CRT in the chain. */
2383  n = ((unsigned int) ssl->in_msg[i + 1] << 8)
2384  | (unsigned int) ssl->in_msg[i + 2];
2385  i += 3;
2386 
2387  if (n < 128 || i + n > ssl->in_hslen) {
2388  MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2393  }
2394 
2395  /* Check if we're handling the first CRT in the chain. */
2396 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2397  if (crt_cnt++ == 0 &&
2398  ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
2399  ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
2400  /* During client-side renegotiation, check that the server's
2401  * end-CRTs hasn't changed compared to the initial handshake,
2402  * mitigating the triple handshake attack. On success, reuse
2403  * the original end-CRT instead of parsing it again. */
2404  MBEDTLS_SSL_DEBUG_MSG(3, ("Check that peer CRT hasn't changed during renegotiation"));
2405  if (ssl_check_peer_crt_unchanged(ssl,
2406  &ssl->in_msg[i],
2407  n) != 0) {
2408  MBEDTLS_SSL_DEBUG_MSG(1, ("new server cert during renegotiation"));
2413  }
2414 
2415  /* Now we can safely free the original chain. */
2417  }
2418 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
2419 
2420  /* Parse the next certificate in the chain. */
2421 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2422  ret = mbedtls_x509_crt_parse_der(chain, ssl->in_msg + i, n);
2423 #else
2424  /* If we don't need to store the CRT chain permanently, parse
2425  * it in-place from the input buffer instead of making a copy. */
2426  ret = mbedtls_x509_crt_parse_der_nocopy(chain, ssl->in_msg + i, n);
2427 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2428  switch (ret) {
2429  case 0: /*ok*/
2431  /* Ignore certificate with an unknown algorithm: maybe a
2432  prior certificate was already trusted. */
2433  break;
2434 
2437  goto crt_parse_der_failed;
2438 
2441  goto crt_parse_der_failed;
2442 
2443  default:
2445 crt_parse_der_failed:
2447  MBEDTLS_SSL_DEBUG_RET(1, " mbedtls_x509_crt_parse_der", ret);
2448  return ret;
2449  }
2450 
2451  i += n;
2452  }
2453 
2454  MBEDTLS_SSL_DEBUG_CRT(3, "peer certificate", chain);
2455  return 0;
2456 }
2457 
2458 #if defined(MBEDTLS_SSL_SRV_C)
2460 static int ssl_srv_check_client_no_crt_notification(mbedtls_ssl_context *ssl)
2461 {
2462  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
2463  return -1;
2464  }
2465 
2466 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2467  /*
2468  * Check if the client sent an empty certificate
2469  */
2470  if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
2471  if (ssl->in_msglen == 2 &&
2475  MBEDTLS_SSL_DEBUG_MSG(1, ("SSLv3 client has no certificate"));
2476  return 0;
2477  }
2478 
2479  return -1;
2480  }
2481 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
2482 
2483 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2484  defined(MBEDTLS_SSL_PROTO_TLS1_2)
2485  if (ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len(ssl) &&
2487  ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE &&
2488  memcmp(ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl), "\0\0\0", 3) == 0) {
2489  MBEDTLS_SSL_DEBUG_MSG(1, ("TLSv1 client has no certificate"));
2490  return 0;
2491  }
2492 
2493  return -1;
2494 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
2495  MBEDTLS_SSL_PROTO_TLS1_2 */
2496 }
2497 #endif /* MBEDTLS_SSL_SRV_C */
2498 
2499 /* Check if a certificate message is expected.
2500  * Return either
2501  * - SSL_CERTIFICATE_EXPECTED, or
2502  * - SSL_CERTIFICATE_SKIP
2503  * indicating whether a Certificate message is expected or not.
2504  */
2505 #define SSL_CERTIFICATE_EXPECTED 0
2506 #define SSL_CERTIFICATE_SKIP 1
2508 static int ssl_parse_certificate_coordinate(mbedtls_ssl_context *ssl,
2509  int authmode)
2510 {
2511  const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2513 
2514  if (!mbedtls_ssl_ciphersuite_uses_srv_cert(ciphersuite_info)) {
2515  return SSL_CERTIFICATE_SKIP;
2516  }
2517 
2518 #if defined(MBEDTLS_SSL_SRV_C)
2519  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
2520  if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
2521  return SSL_CERTIFICATE_SKIP;
2522  }
2523 
2524  if (authmode == MBEDTLS_SSL_VERIFY_NONE) {
2527  return SSL_CERTIFICATE_SKIP;
2528  }
2529  }
2530 #else
2531  ((void) authmode);
2532 #endif /* MBEDTLS_SSL_SRV_C */
2533 
2534  return SSL_CERTIFICATE_EXPECTED;
2535 }
2536 
2539  int authmode,
2540  mbedtls_x509_crt *chain,
2541  void *rs_ctx)
2542 {
2543  int ret = 0;
2544  const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2546  int have_ca_chain = 0;
2547 
2548  int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *);
2549  void *p_vrfy;
2550 
2551  if (authmode == MBEDTLS_SSL_VERIFY_NONE) {
2552  return 0;
2553  }
2554 
2555  if (ssl->f_vrfy != NULL) {
2556  MBEDTLS_SSL_DEBUG_MSG(3, ("Use context-specific verification callback"));
2557  f_vrfy = ssl->f_vrfy;
2558  p_vrfy = ssl->p_vrfy;
2559  } else {
2560  MBEDTLS_SSL_DEBUG_MSG(3, ("Use configuration-specific verification callback"));
2561  f_vrfy = ssl->conf->f_vrfy;
2562  p_vrfy = ssl->conf->p_vrfy;
2563  }
2564 
2565  /*
2566  * Main check: verify certificate
2567  */
2568 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
2569  if (ssl->conf->f_ca_cb != NULL) {
2570  ((void) rs_ctx);
2571  have_ca_chain = 1;
2572 
2573  MBEDTLS_SSL_DEBUG_MSG(3, ("use CA callback for X.509 CRT verification"));
2574  ret = mbedtls_x509_crt_verify_with_ca_cb(
2575  chain,
2576  ssl->conf->f_ca_cb,
2577  ssl->conf->p_ca_cb,
2578  ssl->conf->cert_profile,
2579  ssl->hostname,
2581  f_vrfy, p_vrfy);
2582  } else
2583 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
2584  {
2585  mbedtls_x509_crt *ca_chain;
2586  mbedtls_x509_crl *ca_crl;
2587 
2588 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2589  if (ssl->handshake->sni_ca_chain != NULL) {
2590  ca_chain = ssl->handshake->sni_ca_chain;
2591  ca_crl = ssl->handshake->sni_ca_crl;
2592  } else
2593 #endif
2594  {
2595  ca_chain = ssl->conf->ca_chain;
2596  ca_crl = ssl->conf->ca_crl;
2597  }
2598 
2599  if (ca_chain != NULL) {
2600  have_ca_chain = 1;
2601  }
2602 
2604  chain,
2605  ca_chain, ca_crl,
2606  ssl->conf->cert_profile,
2607  ssl->hostname,
2609  f_vrfy, p_vrfy, rs_ctx);
2610  }
2611 
2612  if (ret != 0) {
2613  MBEDTLS_SSL_DEBUG_RET(1, "x509_verify_cert", ret);
2614  }
2615 
2616 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2617  if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2619  }
2620 #endif
2621 
2622  /*
2623  * Secondary checks: always done, but change 'ret' only if it was 0
2624  */
2625 
2626 #if defined(MBEDTLS_ECP_C)
2627  {
2628  const mbedtls_pk_context *pk = &chain->pk;
2629 
2630  /* If certificate uses an EC key, make sure the curve is OK.
2631  * This is a public key, so it can't be opaque, so can_do() is a good
2632  * enough check to ensure pk_ec() is safe to use here. */
2634  mbedtls_ssl_check_curve(ssl, mbedtls_pk_ec(*pk)->grp.id) != 0) {
2636 
2637  MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate (EC key curve)"));
2638  if (ret == 0) {
2640  }
2641  }
2642  }
2643 #endif /* MBEDTLS_ECP_C */
2644 
2645  if (mbedtls_ssl_check_cert_usage(chain,
2646  ciphersuite_info,
2647  !ssl->conf->endpoint,
2648  &ssl->session_negotiate->verify_result) != 0) {
2649  MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate (usage extensions)"));
2650  if (ret == 0) {
2652  }
2653  }
2654 
2655  /* mbedtls_x509_crt_verify_with_profile is supposed to report a
2656  * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
2657  * with details encoded in the verification flags. All other kinds
2658  * of error codes, including those from the user provided f_vrfy
2659  * functions, are treated as fatal and lead to a failure of
2660  * ssl_parse_certificate even if verification was optional. */
2661  if (authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
2664  ret = 0;
2665  }
2666 
2667  if (have_ca_chain == 0 && authmode == MBEDTLS_SSL_VERIFY_REQUIRED) {
2668  MBEDTLS_SSL_DEBUG_MSG(1, ("got no CA chain"));
2670  }
2671 
2672  if (ret != 0) {
2673  uint8_t alert;
2674 
2675  /* The certificate may have been rejected for several reasons.
2676  Pick one and send the corresponding alert. Which alert to send
2677  may be a subject of debate in some cases. */
2698  } else {
2700  }
2702  alert);
2703  }
2704 
2705 #if defined(MBEDTLS_DEBUG_C)
2706  if (ssl->session_negotiate->verify_result != 0) {
2707  MBEDTLS_SSL_DEBUG_MSG(3, ("! Certificate verification flags %08x",
2708  (unsigned int) ssl->session_negotiate->verify_result));
2709  } else {
2710  MBEDTLS_SSL_DEBUG_MSG(3, ("Certificate verification flags clear"));
2711  }
2712 #endif /* MBEDTLS_DEBUG_C */
2713 
2714  return ret;
2715 }
2716 
2717 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2719 static int ssl_remember_peer_crt_digest(mbedtls_ssl_context *ssl,
2720  unsigned char *start, size_t len)
2721 {
2723  /* Remember digest of the peer's end-CRT. */
2724  ssl->session_negotiate->peer_cert_digest =
2725  mbedtls_calloc(1, MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN);
2726  if (ssl->session_negotiate->peer_cert_digest == NULL) {
2727  MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%d bytes) failed",
2728  MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN));
2732 
2734  }
2735 
2737  MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE),
2738  start, len,
2739  ssl->session_negotiate->peer_cert_digest);
2740 
2741  ssl->session_negotiate->peer_cert_digest_type =
2742  MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE;
2743  ssl->session_negotiate->peer_cert_digest_len =
2744  MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN;
2745 
2746  return ret;
2747 }
2748 
2750 static int ssl_remember_peer_pubkey(mbedtls_ssl_context *ssl,
2751  unsigned char *start, size_t len)
2752 {
2753  unsigned char *end = start + len;
2755 
2756  /* Make a copy of the peer's raw public key. */
2757  mbedtls_pk_init(&ssl->handshake->peer_pubkey);
2758  ret = mbedtls_pk_parse_subpubkey(&start, end,
2759  &ssl->handshake->peer_pubkey);
2760  if (ret != 0) {
2761  /* We should have parsed the public key before. */
2763  }
2764 
2765  return 0;
2766 }
2767 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2768 
2770 {
2771  int ret = 0;
2772  int crt_expected;
2773 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2774  const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
2775  ? ssl->handshake->sni_authmode
2776  : ssl->conf->authmode;
2777 #else
2778  const int authmode = ssl->conf->authmode;
2779 #endif
2780  void *rs_ctx = NULL;
2781  mbedtls_x509_crt *chain = NULL;
2782 
2783  MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate"));
2784 
2785  crt_expected = ssl_parse_certificate_coordinate(ssl, authmode);
2786  if (crt_expected == SSL_CERTIFICATE_SKIP) {
2787  MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate"));
2788  goto exit;
2789  }
2790 
2791 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2792  if (ssl->handshake->ecrs_enabled &&
2793  ssl->handshake->ecrs_state == ssl_ecrs_crt_verify) {
2794  chain = ssl->handshake->ecrs_peer_cert;
2795  ssl->handshake->ecrs_peer_cert = NULL;
2796  goto crt_verify;
2797  }
2798 #endif
2799 
2800  if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
2801  /* mbedtls_ssl_read_record may have sent an alert already. We
2802  let it decide whether to alert. */
2803  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
2804  goto exit;
2805  }
2806 
2807 #if defined(MBEDTLS_SSL_SRV_C)
2808  if (ssl_srv_check_client_no_crt_notification(ssl) == 0) {
2810 
2811  if (authmode != MBEDTLS_SSL_VERIFY_OPTIONAL) {
2813  }
2814 
2815  goto exit;
2816  }
2817 #endif /* MBEDTLS_SSL_SRV_C */
2818 
2819  /* Clear existing peer CRT structure in case we tried to
2820  * reuse a session but it failed, and allocate a new one. */
2822 
2823  chain = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
2824  if (chain == NULL) {
2825  MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed",
2826  sizeof(mbedtls_x509_crt)));
2830 
2832  goto exit;
2833  }
2834  mbedtls_x509_crt_init(chain);
2835 
2836  ret = ssl_parse_certificate_chain(ssl, chain);
2837  if (ret != 0) {
2838  goto exit;
2839  }
2840 
2841 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2842  if (ssl->handshake->ecrs_enabled) {
2843  ssl->handshake->ecrs_state = ssl_ecrs_crt_verify;
2844  }
2845 
2846 crt_verify:
2847  if (ssl->handshake->ecrs_enabled) {
2848  rs_ctx = &ssl->handshake->ecrs_ctx;
2849  }
2850 #endif
2851 
2852  ret = ssl_parse_certificate_verify(ssl, authmode,
2853  chain, rs_ctx);
2854  if (ret != 0) {
2855  goto exit;
2856  }
2857 
2858 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2859  {
2860  unsigned char *crt_start, *pk_start;
2861  size_t crt_len, pk_len;
2862 
2863  /* We parse the CRT chain without copying, so
2864  * these pointers point into the input buffer,
2865  * and are hence still valid after freeing the
2866  * CRT chain. */
2867 
2868  crt_start = chain->raw.p;
2869  crt_len = chain->raw.len;
2870 
2871  pk_start = chain->pk_raw.p;
2872  pk_len = chain->pk_raw.len;
2873 
2874  /* Free the CRT structures before computing
2875  * digest and copying the peer's public key. */
2876  mbedtls_x509_crt_free(chain);
2877  mbedtls_free(chain);
2878  chain = NULL;
2879 
2880  ret = ssl_remember_peer_crt_digest(ssl, crt_start, crt_len);
2881  if (ret != 0) {
2882  goto exit;
2883  }
2884 
2885  ret = ssl_remember_peer_pubkey(ssl, pk_start, pk_len);
2886  if (ret != 0) {
2887  goto exit;
2888  }
2889  }
2890 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2891  /* Pass ownership to session structure. */
2892  ssl->session_negotiate->peer_cert = chain;
2893  chain = NULL;
2894 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2895 
2896  MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate"));
2897 
2898 exit:
2899 
2900  if (ret == 0) {
2901  ssl->state++;
2902  }
2903 
2904 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2906  ssl->handshake->ecrs_peer_cert = chain;
2907  chain = NULL;
2908  }
2909 #endif
2910 
2911  if (chain != NULL) {
2912  mbedtls_x509_crt_free(chain);
2913  mbedtls_free(chain);
2914  }
2915 
2916  return ret;
2917 }
2918 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
2919 
2921  const mbedtls_ssl_ciphersuite_t *ciphersuite_info)
2922 {
2923  ((void) ciphersuite_info);
2924 
2925 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2926  defined(MBEDTLS_SSL_PROTO_TLS1_1)
2929  } else
2930 #endif
2931 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2932 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
2933  if (ciphersuite_info->mac == MBEDTLS_MD_SHA384) {
2935  } else
2936 #endif
2937 #if defined(MBEDTLS_SHA256_C)
2938  if (ciphersuite_info->mac != MBEDTLS_MD_SHA384) {
2940  } else
2941 #endif
2942 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2943  {
2944  MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2945  return;
2946  }
2947 }
2948 
2950 {
2951 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2952  defined(MBEDTLS_SSL_PROTO_TLS1_1)
2953  mbedtls_md5_starts_ret(&ssl->handshake->fin_md5);
2954  mbedtls_sha1_starts_ret(&ssl->handshake->fin_sha1);
2955 #endif
2956 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2957 #if defined(MBEDTLS_SHA256_C)
2958 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2959  psa_hash_abort(&ssl->handshake->fin_sha256_psa);
2960  psa_hash_setup(&ssl->handshake->fin_sha256_psa, PSA_ALG_SHA_256);
2961 #else
2962  mbedtls_sha256_starts_ret(&ssl->handshake->fin_sha256, 0);
2963 #endif
2964 #endif
2965 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
2966 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2967  psa_hash_abort(&ssl->handshake->fin_sha384_psa);
2968  psa_hash_setup(&ssl->handshake->fin_sha384_psa, PSA_ALG_SHA_384);
2969 #else
2970  mbedtls_sha512_starts_ret(&ssl->handshake->fin_sha512, 1);
2971 #endif
2972 #endif
2973 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2974 }
2975 
2977  const unsigned char *buf, size_t len)
2978 {
2979 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2980  defined(MBEDTLS_SSL_PROTO_TLS1_1)
2981  mbedtls_md5_update_ret(&ssl->handshake->fin_md5, buf, len);
2982  mbedtls_sha1_update_ret(&ssl->handshake->fin_sha1, buf, len);
2983 #endif
2984 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2985 #if defined(MBEDTLS_SHA256_C)
2986 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2987  psa_hash_update(&ssl->handshake->fin_sha256_psa, buf, len);
2988 #else
2989  mbedtls_sha256_update_ret(&ssl->handshake->fin_sha256, buf, len);
2990 #endif
2991 #endif
2992 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
2993 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2994  psa_hash_update(&ssl->handshake->fin_sha384_psa, buf, len);
2995 #else
2996  mbedtls_sha512_update_ret(&ssl->handshake->fin_sha512, buf, len);
2997 #endif
2998 #endif
2999 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3000 }
3001 
3002 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3003  defined(MBEDTLS_SSL_PROTO_TLS1_1)
3005  const unsigned char *buf, size_t len)
3006 {
3007  mbedtls_md5_update_ret(&ssl->handshake->fin_md5, buf, len);
3008  mbedtls_sha1_update_ret(&ssl->handshake->fin_sha1, buf, len);
3009 }
3010 #endif
3011 
3012 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3013 #if defined(MBEDTLS_SHA256_C)
3015  const unsigned char *buf, size_t len)
3016 {
3017 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3018  psa_hash_update(&ssl->handshake->fin_sha256_psa, buf, len);
3019 #else
3020  mbedtls_sha256_update_ret(&ssl->handshake->fin_sha256, buf, len);
3021 #endif
3022 }
3023 #endif
3024 
3025 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
3027  const unsigned char *buf, size_t len)
3028 {
3029 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3030  psa_hash_update(&ssl->handshake->fin_sha384_psa, buf, len);
3031 #else
3032  mbedtls_sha512_update_ret(&ssl->handshake->fin_sha512, buf, len);
3033 #endif
3034 }
3035 #endif
3036 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3037 
3038 #if defined(MBEDTLS_SSL_PROTO_SSL3)
3039 static void ssl_calc_finished_ssl(
3040  mbedtls_ssl_context *ssl, unsigned char *buf, int from)
3041 {
3042  const char *sender;
3045 
3046  unsigned char padbuf[48];
3047  unsigned char md5sum[16];
3048  unsigned char sha1sum[20];
3049 
3050  mbedtls_ssl_session *session = ssl->session_negotiate;
3051  if (!session) {
3052  session = ssl->session;
3053  }
3054 
3055  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc finished ssl"));
3056 
3059 
3060  mbedtls_md5_clone(&md5, &ssl->handshake->fin_md5);
3061  mbedtls_sha1_clone(&sha1, &ssl->handshake->fin_sha1);
3062 
3063  /*
3064  * SSLv3:
3065  * hash =
3066  * MD5( master + pad2 +
3067  * MD5( handshake + sender + master + pad1 ) )
3068  * + SHA1( master + pad2 +
3069  * SHA1( handshake + sender + master + pad1 ) )
3070  */
3071 
3072 #if !defined(MBEDTLS_MD5_ALT)
3073  MBEDTLS_SSL_DEBUG_BUF(4, "finished md5 state", (unsigned char *)
3074  md5.state, sizeof(md5.state));
3075 #endif
3076 
3077 #if !defined(MBEDTLS_SHA1_ALT)
3078  MBEDTLS_SSL_DEBUG_BUF(4, "finished sha1 state", (unsigned char *)
3079  sha1.state, sizeof(sha1.state));
3080 #endif
3081 
3082  sender = (from == MBEDTLS_SSL_IS_CLIENT) ? "CLNT"
3083  : "SRVR";
3084 
3085  memset(padbuf, 0x36, 48);
3086 
3087  mbedtls_md5_update_ret(&md5, (const unsigned char *) sender, 4);
3088  mbedtls_md5_update_ret(&md5, session->master, 48);
3089  mbedtls_md5_update_ret(&md5, padbuf, 48);
3090  mbedtls_md5_finish_ret(&md5, md5sum);
3091 
3092  mbedtls_sha1_update_ret(&sha1, (const unsigned char *) sender, 4);
3093  mbedtls_sha1_update_ret(&sha1, session->master, 48);
3094  mbedtls_sha1_update_ret(&sha1, padbuf, 40);
3095  mbedtls_sha1_finish_ret(&sha1, sha1sum);
3096 
3097  memset(padbuf, 0x5C, 48);
3098 
3100  mbedtls_md5_update_ret(&md5, session->master, 48);
3101  mbedtls_md5_update_ret(&md5, padbuf, 48);
3102  mbedtls_md5_update_ret(&md5, md5sum, 16);
3104 
3106  mbedtls_sha1_update_ret(&sha1, session->master, 48);
3107  mbedtls_sha1_update_ret(&sha1, padbuf, 40);
3108  mbedtls_sha1_update_ret(&sha1, sha1sum, 20);
3110 
3111  MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, 36);
3112 
3115 
3116  mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
3117  mbedtls_platform_zeroize(md5sum, sizeof(md5sum));
3118  mbedtls_platform_zeroize(sha1sum, sizeof(sha1sum));
3119 
3120  MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc finished"));
3121 }
3122 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
3123 
3124 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
3126  mbedtls_ssl_context *ssl, unsigned char *buf, int from)
3127 {
3128  int len = 12;
3129  const char *sender;
3132  unsigned char padbuf[36];
3133 
3134  mbedtls_ssl_session *session = ssl->session_negotiate;
3135  if (!session) {
3136  session = ssl->session;
3137  }
3138 
3139  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc finished tls"));
3140 
3143 
3144  mbedtls_md5_clone(&md5, &ssl->handshake->fin_md5);
3145  mbedtls_sha1_clone(&sha1, &ssl->handshake->fin_sha1);
3146 
3147  /*
3148  * TLSv1:
3149  * hash = PRF( master, finished_label,
3150  * MD5( handshake ) + SHA1( handshake ) )[0..11]
3151  */
3152 
3153 #if !defined(MBEDTLS_MD5_ALT)
3154  MBEDTLS_SSL_DEBUG_BUF(4, "finished md5 state", (unsigned char *)
3155  md5.state, sizeof(md5.state));
3156 #endif
3157 
3158 #if !defined(MBEDTLS_SHA1_ALT)
3159  MBEDTLS_SSL_DEBUG_BUF(4, "finished sha1 state", (unsigned char *)
3160  sha1.state, sizeof(sha1.state));
3161 #endif
3162 
3163  sender = (from == MBEDTLS_SSL_IS_CLIENT)
3164  ? "client finished"
3165  : "server finished";
3166 
3167  mbedtls_md5_finish_ret(&md5, padbuf);
3168  mbedtls_sha1_finish_ret(&sha1, padbuf + 16);
3169 
3170  ssl->handshake->tls_prf(session->master, 48, sender,
3171  padbuf, 36, buf, len);
3172 
3173  MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, len);
3174 
3177 
3178  mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
3179 
3180  MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc finished"));
3181 }
3182 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
3183 
3184 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3185 #if defined(MBEDTLS_SHA256_C)
3187  mbedtls_ssl_context *ssl, unsigned char *buf, int from)
3188 {
3189  int len = 12;
3190  const char *sender;
3191  unsigned char padbuf[32];
3192 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3193  size_t hash_size;
3195  psa_status_t status;
3196 #else
3198 #endif
3199 
3200  mbedtls_ssl_session *session = ssl->session_negotiate;
3201  if (!session) {
3202  session = ssl->session;
3203  }
3204 
3205  sender = (from == MBEDTLS_SSL_IS_CLIENT)
3206  ? "client finished"
3207  : "server finished";
3208 
3209 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3210  sha256_psa = psa_hash_operation_init();
3211 
3212  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc PSA finished tls sha256"));
3213 
3214  status = psa_hash_clone(&ssl->handshake->fin_sha256_psa, &sha256_psa);
3215  if (status != PSA_SUCCESS) {
3216  MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash clone failed"));
3217  return;
3218  }
3219 
3220  status = psa_hash_finish(&sha256_psa, padbuf, sizeof(padbuf), &hash_size);
3221  if (status != PSA_SUCCESS) {
3222  MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash finish failed"));
3223  return;
3224  }
3225  MBEDTLS_SSL_DEBUG_BUF(3, "PSA calculated padbuf", padbuf, 32);
3226 #else
3227 
3229 
3230  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc finished tls sha256"));
3231 
3232  mbedtls_sha256_clone(&sha256, &ssl->handshake->fin_sha256);
3233 
3234  /*
3235  * TLSv1.2:
3236  * hash = PRF( master, finished_label,
3237  * Hash( handshake ) )[0.11]
3238  */
3239 
3240 #if !defined(MBEDTLS_SHA256_ALT)
3241  MBEDTLS_SSL_DEBUG_BUF(4, "finished sha2 state", (unsigned char *)
3242  sha256.state, sizeof(sha256.state));
3243 #endif
3244 
3247 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3248 
3249  ssl->handshake->tls_prf(session->master, 48, sender,
3250  padbuf, 32, buf, len);
3251 
3252  MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, len);
3253 
3254  mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
3255 
3256  MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc finished"));
3257 }
3258 #endif /* MBEDTLS_SHA256_C */
3259 
3260 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
3261 
3263  mbedtls_ssl_context *ssl, unsigned char *buf, int from)
3264 {
3265  int len = 12;
3266  const char *sender;
3267  unsigned char padbuf[48];
3268 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3269  size_t hash_size;
3271  psa_status_t status;
3272 #else
3274 #endif
3275 
3276  mbedtls_ssl_session *session = ssl->session_negotiate;
3277  if (!session) {
3278  session = ssl->session;
3279  }
3280 
3281  sender = (from == MBEDTLS_SSL_IS_CLIENT)
3282  ? "client finished"
3283  : "server finished";
3284 
3285 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3286  sha384_psa = psa_hash_operation_init();
3287 
3288  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc PSA finished tls sha384"));
3289 
3290  status = psa_hash_clone(&ssl->handshake->fin_sha384_psa, &sha384_psa);
3291  if (status != PSA_SUCCESS) {
3292  MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash clone failed"));
3293  return;
3294  }
3295 
3296  status = psa_hash_finish(&sha384_psa, padbuf, sizeof(padbuf), &hash_size);
3297  if (status != PSA_SUCCESS) {
3298  MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash finish failed"));
3299  return;
3300  }
3301  MBEDTLS_SSL_DEBUG_BUF(3, "PSA calculated padbuf", padbuf, 48);
3302 #else
3304 
3305  MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc finished tls sha384"));
3306 
3307  mbedtls_sha512_clone(&sha512, &ssl->handshake->fin_sha512);
3308 
3309  /*
3310  * TLSv1.2:
3311  * hash = PRF( master, finished_label,
3312  * Hash( handshake ) )[0.11]
3313  */
3314 
3315 #if !defined(MBEDTLS_SHA512_ALT)
3316  MBEDTLS_SSL_DEBUG_BUF(4, "finished sha512 state", (unsigned char *)
3317  sha512.state, sizeof(sha512.state));
3318 #endif
3319  /* mbedtls_sha512_finish_ret's output parameter is declared as a
3320  * 64-byte buffer, but since we're using SHA-384, we know that the
3321  * output fits in 48 bytes. This is correct C, but GCC 11.1 warns
3322  * about it.
3323  */
3324 #if defined(__GNUC__) && __GNUC__ >= 11
3325 #pragma GCC diagnostic push
3326 #pragma GCC diagnostic ignored "-Wstringop-overflow"
3327 #endif
3329 #if defined(__GNUC__) && __GNUC__ >= 11
3330 #pragma GCC diagnostic pop
3331 #endif
3332 
3334 #endif
3335 
3336  ssl->handshake->tls_prf(session->master, 48, sender,
3337  padbuf, 48, buf, len);
3338 
3339  MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, len);
3340 
3341  mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
3342 
3343  MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc finished"));
3344 }
3345 #endif /* MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384 */
3346 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3347 
3349 {
3350  MBEDTLS_SSL_DEBUG_MSG(3, ("=> handshake wrapup: final free"));
3351 
3352  /*
3353  * Free our handshake params
3354  */
3356  mbedtls_free(ssl->handshake);
3357  ssl->handshake = NULL;
3358 
3359  /*
3360  * Free the previous transform and switch in the current one
3361  */
3362  if (ssl->transform) {
3364  mbedtls_free(ssl->transform);
3365  }
3366  ssl->transform = ssl->transform_negotiate;
3367  ssl->transform_negotiate = NULL;
3368 
3369  MBEDTLS_SSL_DEBUG_MSG(3, ("<= handshake wrapup: final free"));
3370 }
3371 
3373 {
3374  int resume = ssl->handshake->resume;
3375 
3376  MBEDTLS_SSL_DEBUG_MSG(3, ("=> handshake wrapup"));
3377 
3378 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3379  if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
3380  ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE;
3381  ssl->renego_records_seen = 0;
3382  }
3383 #endif
3384 
3385  /*
3386  * Free the previous session and switch in the current one
3387  */
3388  if (ssl->session) {
3389 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
3390  /* RFC 7366 3.1: keep the EtM state */
3391  ssl->session_negotiate->encrypt_then_mac =
3392  ssl->session->encrypt_then_mac;
3393 #endif
3394 
3396  mbedtls_free(ssl->session);
3397  }
3398  ssl->session = ssl->session_negotiate;
3399  ssl->session_negotiate = NULL;
3400 
3401  /*
3402  * Add cache entry
3403  */
3404  if (ssl->conf->f_set_cache != NULL &&
3405  ssl->session->id_len != 0 &&
3406  resume == 0) {
3407  if (ssl->conf->f_set_cache(ssl->conf->p_cache, ssl->session) != 0) {
3408  MBEDTLS_SSL_DEBUG_MSG(1, ("cache did not store session"));
3409  }
3410  }
3411 
3412 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3414  ssl->handshake->flight != NULL) {
3415  /* Cancel handshake timer */
3416  mbedtls_ssl_set_timer(ssl, 0);
3417 
3418  /* Keep last flight around in case we need to resend it:
3419  * we need the handshake and transform structures for that */
3420  MBEDTLS_SSL_DEBUG_MSG(3, ("skip freeing handshake and transform"));
3421  } else
3422 #endif
3424 
3425  ssl->state++;
3426 
3427  MBEDTLS_SSL_DEBUG_MSG(3, ("<= handshake wrapup"));
3428 }
3429 
3431 {
3432  int ret, hash_len;
3433 
3434  MBEDTLS_SSL_DEBUG_MSG(2, ("=> write finished"));
3435 
3437 
3438  ssl->handshake->calc_finished(ssl, ssl->out_msg + 4, ssl->conf->endpoint);
3439 
3440  /*
3441  * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
3442  * may define some other value. Currently (early 2016), no defined
3443  * ciphersuite does this (and this is unlikely to change as activity has
3444  * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
3445  */
3446  hash_len = (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) ? 36 : 12;
3447 
3448 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3449  ssl->verify_data_len = hash_len;
3450  memcpy(ssl->own_verify_data, ssl->out_msg + 4, hash_len);
3451 #endif
3452 
3453  ssl->out_msglen = 4 + hash_len;
3455  ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED;
3456 
3457  /*
3458  * In case of session resuming, invert the client and server
3459  * ChangeCipherSpec messages order.
3460  */
3461  if (ssl->handshake->resume != 0) {
3462 #if defined(MBEDTLS_SSL_CLI_C)
3463  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
3465  }
3466 #endif
3467 #if defined(MBEDTLS_SSL_SRV_C)
3468  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
3470  }
3471 #endif
3472  } else {
3473  ssl->state++;
3474  }
3475 
3476  /*
3477  * Switch to our negotiated transform and session parameters for outbound
3478  * data.
3479  */
3480  MBEDTLS_SSL_DEBUG_MSG(3, ("switching to new transform spec for outbound data"));
3481 
3482 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3484  unsigned char i;
3485 
3486  /* Remember current epoch settings for resending */
3487  ssl->handshake->alt_transform_out = ssl->transform_out;
3488  memcpy(ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8);
3489 
3490  /* Set sequence_number to zero */
3491  memset(ssl->cur_out_ctr + 2, 0, 6);
3492 
3493  /* Increment epoch */
3494  for (i = 2; i > 0; i--) {
3495  if (++ssl->cur_out_ctr[i - 1] != 0) {
3496  break;
3497  }
3498  }
3499 
3500  /* The loop goes to its end iff the counter is wrapping */
3501  if (i == 0) {
3502  MBEDTLS_SSL_DEBUG_MSG(1, ("DTLS epoch would wrap"));
3504  }
3505  } else
3506 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3507  memset(ssl->cur_out_ctr, 0, 8);
3508 
3509  ssl->transform_out = ssl->transform_negotiate;
3510  ssl->session_out = ssl->session_negotiate;
3511 
3512 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3513  if (mbedtls_ssl_hw_record_activate != NULL) {
3514  if ((ret = mbedtls_ssl_hw_record_activate(ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND)) != 0) {
3515  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_hw_record_activate", ret);
3517  }
3518  }
3519 #endif
3520 
3521 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3524  }
3525 #endif
3526 
3527  if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3528  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3529  return ret;
3530  }
3531 
3532 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3534  (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
3535  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
3536  return ret;
3537  }
3538 #endif
3539 
3540  MBEDTLS_SSL_DEBUG_MSG(2, ("<= write finished"));
3541 
3542  return 0;
3543 }
3544 
3545 #if defined(MBEDTLS_SSL_PROTO_SSL3)
3546 #define SSL_MAX_HASH_LEN 36
3547 #else
3548 #define SSL_MAX_HASH_LEN 12
3549 #endif
3550 
3552 {
3554  unsigned int hash_len;
3555  unsigned char buf[SSL_MAX_HASH_LEN];
3556 
3557  MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse finished"));
3558 
3559  /* There is currently no ciphersuite using another length with TLS 1.2 */
3560 #if defined(MBEDTLS_SSL_PROTO_SSL3)
3561  if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
3562  hash_len = 36;
3563  } else
3564 #endif
3565  hash_len = 12;
3566 
3567  ssl->handshake->calc_finished(ssl, buf, ssl->conf->endpoint ^ 1);
3568 
3569  if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
3570  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
3571  goto exit;
3572  }
3573 
3574  if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
3575  MBEDTLS_SSL_DEBUG_MSG(1, ("bad finished message"));
3579  goto exit;
3580  }
3581 
3582  if (ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
3583  ssl->in_hslen != mbedtls_ssl_hs_hdr_len(ssl) + hash_len) {
3584  MBEDTLS_SSL_DEBUG_MSG(1, ("bad finished message"));
3588  goto exit;
3589  }
3590 
3592  buf, hash_len) != 0) {
3593  MBEDTLS_SSL_DEBUG_MSG(1, ("bad finished message"));
3597  goto exit;
3598  }
3599 
3600 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3601  ssl->verify_data_len = hash_len;
3602  memcpy(ssl->peer_verify_data, buf, hash_len);
3603 #endif
3604 
3605  if (ssl->handshake->resume != 0) {
3606 #if defined(MBEDTLS_SSL_CLI_C)
3607  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
3609  }
3610 #endif
3611 #if defined(MBEDTLS_SSL_SRV_C)
3612  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
3614  }
3615 #endif
3616  } else {
3617  ssl->state++;
3618  }
3619 
3620 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3623  }
3624 #endif
3625 
3626  MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse finished"));
3627 
3628 exit:
3630  return ret;
3631 }
3632 
3634 {
3635  memset(handshake, 0, sizeof(mbedtls_ssl_handshake_params));
3636 
3637 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3638  defined(MBEDTLS_SSL_PROTO_TLS1_1)
3639  mbedtls_md5_init(&handshake->fin_md5);
3640  mbedtls_sha1_init(&handshake->fin_sha1);
3641  mbedtls_md5_starts_ret(&handshake->fin_md5);
3642  mbedtls_sha1_starts_ret(&handshake->fin_sha1);
3643 #endif
3644 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3645 #if defined(MBEDTLS_SHA256_C)
3646 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3647  handshake->fin_sha256_psa = psa_hash_operation_init();
3648  psa_hash_setup(&handshake->fin_sha256_psa, PSA_ALG_SHA_256);
3649 #else
3650  mbedtls_sha256_init(&handshake->fin_sha256);
3651  mbedtls_sha256_starts_ret(&handshake->fin_sha256, 0);
3652 #endif
3653 #endif
3654 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
3655 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3656  handshake->fin_sha384_psa = psa_hash_operation_init();
3657  psa_hash_setup(&handshake->fin_sha384_psa, PSA_ALG_SHA_384);
3658 #else
3659  mbedtls_sha512_init(&handshake->fin_sha512);
3660  mbedtls_sha512_starts_ret(&handshake->fin_sha512, 1);
3661 #endif
3662 #endif
3663 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3664 
3666 
3667 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
3668  defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
3669  mbedtls_ssl_sig_hash_set_init(&handshake->hash_algs);
3670 #endif
3671 
3672 #if defined(MBEDTLS_DHM_C)
3673  mbedtls_dhm_init(&handshake->dhm_ctx);
3674 #endif
3675 #if defined(MBEDTLS_ECDH_C)
3676  mbedtls_ecdh_init(&handshake->ecdh_ctx);
3677 #endif
3678 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3679  mbedtls_ecjpake_init(&handshake->ecjpake_ctx);
3680 #if defined(MBEDTLS_SSL_CLI_C)
3681  handshake->ecjpake_cache = NULL;
3682  handshake->ecjpake_cache_len = 0;
3683 #endif
3684 #endif
3685 
3686 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3687  mbedtls_x509_crt_restart_init(&handshake->ecrs_ctx);
3688 #endif
3689 
3690 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
3691  handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
3692 #endif
3693 
3694 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
3695  !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
3696  mbedtls_pk_init(&handshake->peer_pubkey);
3697 #endif
3698 }
3699 
3701 {
3702  memset(transform, 0, sizeof(mbedtls_ssl_transform));
3703 
3704  mbedtls_cipher_init(&transform->cipher_ctx_enc);
3705  mbedtls_cipher_init(&transform->cipher_ctx_dec);
3706 
3707 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
3708  mbedtls_md_init(&transform->md_ctx_enc);
3709  mbedtls_md_init(&transform->md_ctx_dec);
3710 #endif
3711 }
3712 
3714 {
3715  memset(session, 0, sizeof(mbedtls_ssl_session));
3716 }
3717 
3720 {
3721  /* Clear old handshake information if present */
3722  if (ssl->transform_negotiate) {
3724  }
3725  if (ssl->session_negotiate) {
3727  }
3728  if (ssl->handshake) {
3730  }
3731 
3732  /*
3733  * Either the pointers are now NULL or cleared properly and can be freed.
3734  * Now allocate missing structures.
3735  */
3736  if (ssl->transform_negotiate == NULL) {
3738  }
3739 
3740  if (ssl->session_negotiate == NULL) {
3742  }
3743 
3744  if (ssl->handshake == NULL) {
3746  }
3747 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3748  /* If the buffers are too small - reallocate */
3749 
3750  handle_buffer_resizing(ssl, 0, MBEDTLS_SSL_IN_BUFFER_LEN,
3752 #endif
3753 
3754  /* All pointers should exist and can be directly freed without issue */
3755  if (ssl->handshake == NULL ||
3756  ssl->transform_negotiate == NULL ||
3757  ssl->session_negotiate == NULL) {
3758  MBEDTLS_SSL_DEBUG_MSG(1, ("alloc() of ssl sub-contexts failed"));
3759 
3760  mbedtls_free(ssl->handshake);
3763 
3764  ssl->handshake = NULL;
3765  ssl->transform_negotiate = NULL;
3766  ssl->session_negotiate = NULL;
3767 
3769  }
3770 
3771  /* Initialize structures */
3775 
3776 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3778  ssl->handshake->alt_transform_out = ssl->transform_out;
3779 
3780  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
3781  ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
3782  } else {
3783  ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
3784  }
3785 
3786  mbedtls_ssl_set_timer(ssl, 0);
3787  }
3788 #endif
3789 
3790  return 0;
3791 }
3792 
3793 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
3794 /* Dummy cookie callbacks for defaults */
3796 static int ssl_cookie_write_dummy(void *ctx,
3797  unsigned char **p, unsigned char *end,
3798  const unsigned char *cli_id, size_t cli_id_len)
3799 {
3800  ((void) ctx);
3801  ((void) p);
3802  ((void) end);
3803  ((void) cli_id);
3804  ((void) cli_id_len);
3805 
3807 }
3808 
3810 static int ssl_cookie_check_dummy(void *ctx,
3811  const unsigned char *cookie, size_t cookie_len,
3812  const unsigned char *cli_id, size_t cli_id_len)
3813 {
3814  ((void) ctx);
3815  ((void) cookie);
3816  ((void) cookie_len);
3817  ((void) cli_id);
3818  ((void) cli_id_len);
3819 
3821 }
3822 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
3823 
3824 /*
3825  * Initialize an SSL context
3826  */
3828 {
3829  memset(ssl, 0, sizeof(mbedtls_ssl_context));
3830 }
3831 
3832 /*
3833  * Setup an SSL context
3834  */
3835 
3837  const mbedtls_ssl_config *conf)
3838 {
3840  size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
3841  size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
3842 
3843  ssl->conf = conf;
3844 
3845  /*
3846  * Prepare base structures
3847  */
3848 
3849  /* Set to NULL in case of an error condition */
3850  ssl->out_buf = NULL;
3851 
3852 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3853  ssl->in_buf_len = in_buf_len;
3854 #endif
3855  ssl->in_buf = mbedtls_calloc(1, in_buf_len);
3856  if (ssl->in_buf == NULL) {
3857  MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", in_buf_len));
3859  goto error;
3860  }
3861 
3862 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3863  ssl->out_buf_len = out_buf_len;
3864 #endif
3865  ssl->out_buf = mbedtls_calloc(1, out_buf_len);
3866  if (ssl->out_buf == NULL) {
3867  MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", out_buf_len));
3869  goto error;
3870  }
3871 
3873 
3874 #if defined(MBEDTLS_SSL_DTLS_SRTP)
3875  memset(&ssl->dtls_srtp_info, 0, sizeof(ssl->dtls_srtp_info));
3876 #endif
3877 
3878  if ((ret = ssl_handshake_init(ssl)) != 0) {
3879  goto error;
3880  }
3881 
3882  return 0;
3883 
3884 error:
3885  mbedtls_free(ssl->in_buf);
3886  mbedtls_free(ssl->out_buf);
3887 
3888  ssl->conf = NULL;
3889 
3890 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3891  ssl->in_buf_len = 0;
3892  ssl->out_buf_len = 0;
3893 #endif
3894  ssl->in_buf = NULL;
3895  ssl->out_buf = NULL;
3896 
3897  ssl->in_hdr = NULL;
3898  ssl->in_ctr = NULL;
3899  ssl->in_len = NULL;
3900  ssl->in_iv = NULL;
3901  ssl->in_msg = NULL;
3902 
3903  ssl->out_hdr = NULL;
3904  ssl->out_ctr = NULL;
3905  ssl->out_len = NULL;
3906  ssl->out_iv = NULL;
3907  ssl->out_msg = NULL;
3908 
3909  return ret;
3910 }
3911 
3912 /*
3913  * Reset an initialized and used SSL context for re-use while retaining
3914  * all application-set variables, function pointers and data.
3915  *
3916  * If partial is non-zero, keep data in the input buffer and client ID.
3917  * (Use when a DTLS client reconnects from the same port.)
3918  */
3920 {
3922 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3923  size_t in_buf_len = ssl->in_buf_len;
3924  size_t out_buf_len = ssl->out_buf_len;
3925 #else
3926  size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
3927  size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
3928 #endif
3929 
3930 #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) || \
3931  !defined(MBEDTLS_SSL_SRV_C)
3932  ((void) partial);
3933 #endif
3934 
3936 
3937  /* Cancel any possibly running timer */
3938  mbedtls_ssl_set_timer(ssl, 0);
3939 
3940 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3941  ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
3942  ssl->renego_records_seen = 0;
3943 
3944  ssl->verify_data_len = 0;
3945  memset(ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN);
3946  memset(ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN);
3947 #endif
3949 
3950  ssl->in_offt = NULL;
3952 
3953  ssl->in_msgtype = 0;
3954  ssl->in_msglen = 0;
3955 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3956  ssl->next_record_offset = 0;
3957  ssl->in_epoch = 0;
3958 #endif
3959 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3961 #endif
3962 
3963  ssl->in_hslen = 0;
3964  ssl->nb_zero = 0;
3965 
3966  ssl->keep_current_message = 0;
3967 
3968  ssl->out_msgtype = 0;
3969  ssl->out_msglen = 0;
3970  ssl->out_left = 0;
3971 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
3972  if (ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED) {
3973  ssl->split_done = 0;
3974  }
3975 #endif
3976 
3977  memset(ssl->cur_out_ctr, 0, sizeof(ssl->cur_out_ctr));
3978 
3979  ssl->transform_in = NULL;
3980  ssl->transform_out = NULL;
3981 
3982  ssl->session_in = NULL;
3983  ssl->session_out = NULL;
3984 
3985  memset(ssl->out_buf, 0, out_buf_len);
3986 
3987  int clear_in_buf = 1;
3988 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3989  if (partial != 0) {
3990  clear_in_buf = 0;
3991  }
3992 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3993  if (clear_in_buf) {
3994  ssl->in_left = 0;
3995  memset(ssl->in_buf, 0, in_buf_len);
3996  }
3997 
3998 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3999  if (mbedtls_ssl_hw_record_reset != NULL) {
4000  MBEDTLS_SSL_DEBUG_MSG(2, ("going for mbedtls_ssl_hw_record_reset()"));
4001  if ((ret = mbedtls_ssl_hw_record_reset(ssl)) != 0) {
4002  MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_hw_record_reset", ret);
4004  }
4005  }
4006 #endif
4007 
4008  if (ssl->transform) {
4010  mbedtls_free(ssl->transform);
4011  ssl->transform = NULL;
4012  }
4013 
4014  if (ssl->session) {
4016  mbedtls_free(ssl->session);
4017  ssl->session = NULL;
4018  }
4019 
4020 #if defined(MBEDTLS_SSL_ALPN)
4021  ssl->alpn_chosen = NULL;
4022 #endif
4023 
4024 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
4025  int free_cli_id = 1;
4026 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
4027  if (partial != 0) {
4028  free_cli_id = 0;
4029  }
4030 #endif
4031  if (free_cli_id) {
4032  mbedtls_free(ssl->cli_id);
4033  ssl->cli_id = NULL;
4034  ssl->cli_id_len = 0;
4035  }
4036 #endif
4037 
4038  if ((ret = ssl_handshake_init(ssl)) != 0) {
4039  return ret;
4040  }
4041 
4042  return 0;
4043 }
4044 
4045 /*
4046  * Reset an initialized and used SSL context for re-use while retaining
4047  * all application-set variables, function pointers and data.
4048  */
4050 {
4051  return mbedtls_ssl_session_reset_int(ssl, 0);
4052 }
4053 
4054 /*
4055  * SSL set accessors
4056  */
4058 {
4059  conf->endpoint = endpoint;
4060 }
4061 
4063 {
4064  conf->transport = transport;
4065 }
4066 
4067 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4069 {
4070  conf->anti_replay = mode;
4071 }
4072 #endif
4073 
4074 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
4076 {
4077  conf->badmac_limit = limit;
4078 }
4079 #endif
4080 
4081 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4082 
4084  unsigned allow_packing)
4085 {
4086  ssl->disable_datagram_packing = !allow_packing;
4087 }
4088 
4091 {
4092  conf->hs_timeout_min = min;
4093  conf->hs_timeout_max = max;
4094 }
4095 #endif
4096 
4098 {
4099  conf->authmode = authmode;
4100 }
4101 
4102 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4104  int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
4105  void *p_vrfy)
4106 {
4107  conf->f_vrfy = f_vrfy;
4108  conf->p_vrfy = p_vrfy;
4109 }
4110 #endif /* MBEDTLS_X509_CRT_PARSE_C */
4111 
4113  int (*f_rng)(void *, unsigned char *, size_t),
4114  void *p_rng)
4115 {
4116  conf->f_rng = f_rng;
4117  conf->p_rng = p_rng;
4118 }
4119 
4121  void (*f_dbg)(void *, int, const char *, int, const char *),
4122  void *p_dbg)
4123 {
4124  conf->f_dbg = f_dbg;
4125  conf->p_dbg = p_dbg;
4126 }
4127 
4129  void *p_bio,
4130  mbedtls_ssl_send_t *f_send,
4131  mbedtls_ssl_recv_t *f_recv,
4132  mbedtls_ssl_recv_timeout_t *f_recv_timeout)
4133 {
4134  ssl->p_bio = p_bio;
4135  ssl->f_send = f_send;
4136  ssl->f_recv = f_recv;
4137  ssl->f_recv_timeout = f_recv_timeout;
4138 }
4139 
4140 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4142 {
4143  ssl->mtu = mtu;
4144 }
4145 #endif
4146 
4148 {
4149  conf->read_timeout = timeout;
4150 }
4151 
4153  void *p_timer,
4154  mbedtls_ssl_set_timer_t *f_set_timer,
4155  mbedtls_ssl_get_timer_t *f_get_timer)
4156 {
4157  ssl->p_timer = p_timer;
4158  ssl->f_set_timer = f_set_timer;
4159  ssl->f_get_timer = f_get_timer;
4160 
4161  /* Make sure we start with no timer running */
4162  mbedtls_ssl_set_timer(ssl, 0);
4163 }
4164 
4165 #if defined(MBEDTLS_SSL_SRV_C)
4167  void *p_cache,
4168  int (*f_get_cache)(void *, mbedtls_ssl_session *),
4169  int (*f_set_cache)(void *, const mbedtls_ssl_session *))
4170 {
4171  conf->p_cache = p_cache;
4172  conf->f_get_cache = f_get_cache;
4173  conf->f_set_cache = f_set_cache;
4174 }
4175 #endif /* MBEDTLS_SSL_SRV_C */
4176 
4177 #if defined(MBEDTLS_SSL_CLI_C)
4179 {
4181 
4182  if (ssl == NULL ||
4183  session == NULL ||
4184  ssl->session_negotiate == NULL ||
4185  ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT) {
4187  }
4188 
4190  session)) != 0) {
4191  return ret;
4192  }
4193 
4194  ssl->handshake->resume = 1;
4195 
4196  return 0;
4197 }
4198 #endif /* MBEDTLS_SSL_CLI_C */
4199 
4201  const int *ciphersuites)
4202 {
4203  conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
4204  conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
4205  conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
4206  conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
4207 }
4208 
4210  const int *ciphersuites,
4211  int major, int minor)
4212 {
4213  if (major != MBEDTLS_SSL_MAJOR_VERSION_3) {
4214  return;
4215  }
4216 
4217  if (minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3) {
4218  return;
4219  }
4220 
4221  conf->ciphersuite_list[minor] = ciphersuites;
4222 }
4223 
4224 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4226  const mbedtls_x509_crt_profile *profile)
4227 {
4228  conf->cert_profile = profile;
4229 }
4230 
4231 /* Append a new keycert entry to a (possibly empty) list */
4233 static int ssl_append_key_cert(mbedtls_ssl_key_cert **head,
4234  mbedtls_x509_crt *cert,
4236 {
4237  mbedtls_ssl_key_cert *new_cert;
4238 
4239  new_cert = mbedtls_calloc(1, sizeof(mbedtls_ssl_key_cert));
4240  if (new_cert == NULL) {
4242  }
4243 
4244  new_cert->cert = cert;
4245  new_cert->key = key;
4246  new_cert->next = NULL;
4247 
4248  /* Update head is the list was null, else add to the end */
4249  if (*head == NULL) {
4250  *head = new_cert;
4251  } else {
4252  mbedtls_ssl_key_cert *cur = *head;
4253  while (cur->next != NULL) {
4254  cur = cur->next;
4255  }
4256  cur->next = new_cert;
4257  }
4258 
4259  return 0;
4260 }
4261 
4263  mbedtls_x509_crt *own_cert,
4264  mbedtls_pk_context *pk_key)
4265 {
4266  return ssl_append_key_cert(&conf->key_cert, own_cert, pk_key);
4267 }
4268 
4270  mbedtls_x509_crt *ca_chain,
4271  mbedtls_x509_crl *ca_crl)
4272 {
4273  conf->ca_chain = ca_chain;
4274  conf->ca_crl = ca_crl;
4275 
4276 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
4277  /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
4278  * cannot be used together. */
4279  conf->f_ca_cb = NULL;
4280  conf->p_ca_cb = NULL;
4281 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
4282 }
4283 
4284 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
4285 void mbedtls_ssl_conf_ca_cb(mbedtls_ssl_config *conf,
4286  mbedtls_x509_crt_ca_cb_t f_ca_cb,
4287  void *p_ca_cb)
4288 {
4289  conf->f_ca_cb = f_ca_cb;
4290  conf->p_ca_cb = p_ca_cb;
4291 
4292  /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
4293  * cannot be used together. */
4294  conf->ca_chain = NULL;
4295  conf->ca_crl = NULL;
4296 }
4297 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
4298 #endif /* MBEDTLS_X509_CRT_PARSE_C */
4299 
4300 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4302  mbedtls_x509_crt *own_cert,
4303  mbedtls_pk_context *pk_key)
4304 {
4305  return ssl_append_key_cert(&ssl->handshake->sni_key_cert,
4306  own_cert, pk_key);
4307 }
4308 
4310  mbedtls_x509_crt *ca_chain,
4311  mbedtls_x509_crl *ca_crl)
4312 {
4313  ssl->handshake->sni_ca_chain = ca_chain;
4314  ssl->handshake->sni_ca_crl = ca_crl;
4315 }
4316 
4318  int authmode)
4319 {
4320  ssl->handshake->sni_authmode = authmode;
4321 }
4322 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
4323 
4324 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4326  int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
4327  void *p_vrfy)
4328 {
4329  ssl->f_vrfy = f_vrfy;
4330  ssl->p_vrfy = p_vrfy;
4331 }
4332 #endif
4333 
4334 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4335 /*
4336  * Set EC J-PAKE password for current handshake
4337  */
4338 int mbedtls_ssl_set_hs_ecjpake_password(mbedtls_ssl_context *ssl,
4339  const unsigned char *pw,
4340  size_t pw_len)
4341 {
4342  mbedtls_ecjpake_role role;
4343 
4344  if (ssl->handshake == NULL || ssl->conf == NULL) {
4346  }
4347 
4348  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
4349  role = MBEDTLS_ECJPAKE_SERVER;
4350  } else {
4351  role = MBEDTLS_ECJPAKE_CLIENT;
4352  }
4353 
4354  return mbedtls_ecjpake_setup(&ssl->handshake->ecjpake_ctx,
4355  role,
4358  pw, pw_len);
4359 }
4360 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4361 
4362 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
4363 
4364 static void ssl_conf_remove_psk(mbedtls_ssl_config *conf)
4365 {
4366  /* Remove reference to existing PSK, if any. */
4367 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4368  if (!mbedtls_svc_key_id_is_null(conf->psk_opaque)) {
4369  /* The maintenance of the PSK key slot is the
4370  * user's responsibility. */
4371  conf->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT;
4372  }
4373  /* This and the following branch should never
4374  * be taken simultaneously as we maintain the
4375  * invariant that raw and opaque PSKs are never
4376  * configured simultaneously. As a safeguard,
4377  * though, `else` is omitted here. */
4378 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4379  if (conf->psk != NULL) {
4380  mbedtls_platform_zeroize(conf->psk, conf->psk_len);
4381 
4382  mbedtls_free(conf->psk);
4383  conf->psk = NULL;
4384  conf->psk_len = 0;
4385  }
4386 
4387  /* Remove reference to PSK identity, if any. */
4388  if (conf->psk_identity != NULL) {
4389  mbedtls_free(conf->psk_identity);
4390  conf->psk_identity = NULL;
4391  conf->psk_identity_len = 0;
4392  }
4393 }
4394 
4395 /* This function assumes that PSK identity in the SSL config is unset.
4396  * It checks that the provided identity is well-formed and attempts
4397  * to make a copy of it in the SSL config.
4398  * On failure, the PSK identity in the config remains unset. */
4400 static int ssl_conf_set_psk_identity(mbedtls_ssl_config *conf,
4401  unsigned char const *psk_identity,
4402  size_t psk_identity_len)
4403 {
4404  /* Identity len will be encoded on two bytes */
4405  if (psk_identity == NULL ||
4406  (psk_identity_len >> 16) != 0 ||
4407  psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN) {
4409  }
4410 
4411  conf->psk_identity = mbedtls_calloc(1, psk_identity_len);
4412  if (conf->psk_identity == NULL) {
4414  }
4415 
4416  conf->psk_identity_len = psk_identity_len;
4417  memcpy(conf->psk_identity, psk_identity, conf->psk_identity_len);
4418 
4419  return 0;
4420 }
4421 
4423  const unsigned char *psk, size_t psk_len,
4424  const unsigned char *psk_identity, size_t psk_identity_len)
4425 {
4427  /* Remove opaque/raw PSK + PSK Identity */
4428  ssl_conf_remove_psk(conf);
4429 
4430  /* Check and set raw PSK */
4431  if (psk == NULL) {
4433  }
4434  if (psk_len == 0) {
4436  }
4437  if (psk_len > MBEDTLS_PSK_MAX_LEN) {
4439  }
4440 
4441  if ((conf->psk = mbedtls_calloc(1, psk_len)) == NULL) {
4443  }
4444  conf->psk_len = psk_len;
4445  memcpy(conf->psk, psk, conf->psk_len);
4446 
4447  /* Check and set PSK Identity */
4448  ret = ssl_conf_set_psk_identity(conf, psk_identity, psk_identity_len);
4449  if (ret != 0) {
4450  ssl_conf_remove_psk(conf);
4451  }
4452 
4453  return ret;
4454 }
4455 
4456 static void ssl_remove_psk(mbedtls_ssl_context *ssl)
4457 {
4458 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4459  if (!mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque)) {
4460  ssl->handshake->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT;
4461  } else
4462 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4463  if (ssl->handshake->psk != NULL) {
4465  ssl->handshake->psk_len);
4466  mbedtls_free(ssl->handshake->psk);
4467  ssl->handshake->psk_len = 0;
4468  }
4469 }
4470 
4472  const unsigned char *psk, size_t psk_len)
4473 {
4474  if (psk == NULL || ssl->handshake == NULL) {
4476  }
4477 
4478  if (psk_len > MBEDTLS_PSK_MAX_LEN) {
4480  }
4481 
4482  ssl_remove_psk(ssl);
4483 
4484  if ((ssl->handshake->psk = mbedtls_calloc(1, psk_len)) == NULL) {
4486  }
4487 
4488  ssl->handshake->psk_len = psk_len;
4489  memcpy(ssl->handshake->psk, psk, ssl->handshake->psk_len);
4490 
4491  return 0;
4492 }
4493 
4494 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4495 int mbedtls_ssl_conf_psk_opaque(mbedtls_ssl_config *conf,
4496  psa_key_id_t psk,
4497  const unsigned char *psk_identity,
4498  size_t psk_identity_len)
4499 {
4501  /* Clear opaque/raw PSK + PSK Identity, if present. */
4502  ssl_conf_remove_psk(conf);
4503 
4504  /* Check and set opaque PSK */
4505  if (mbedtls_svc_key_id_is_null(psk)) {
4507  }
4508  conf->psk_opaque = psk;
4509 
4510  /* Check and set PSK Identity */
4511  ret = ssl_conf_set_psk_identity(conf, psk_identity,
4512  psk_identity_len);
4513  if (ret != 0) {
4514  ssl_conf_remove_psk(conf);
4515  }
4516 
4517  return ret;
4518 }
4519 
4520 int mbedtls_ssl_set_hs_psk_opaque(mbedtls_ssl_context *ssl,
4521  psa_key_id_t psk)
4522 {
4523  if ((mbedtls_svc_key_id_is_null(psk)) ||
4524  (ssl->handshake == NULL)) {
4526  }
4527 
4528  ssl_remove_psk(ssl);
4529  ssl->handshake->psk_opaque = psk;
4530  return 0;
4531 }
4532 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4533 
4535  int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
4536  size_t),
4537  void *p_psk)
4538 {
4539  conf->f_psk = f_psk;
4540  conf->p_psk = p_psk;
4541 }
4542 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
4543 
4544 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
4545 
4546 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
4547 int mbedtls_ssl_conf_dh_param(mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G)
4548 {
4550 
4551  if ((ret = mbedtls_mpi_read_string(&conf->dhm_P, 16, dhm_P)) != 0 ||
4552  (ret = mbedtls_mpi_read_string(&conf->dhm_G, 16, dhm_G)) != 0) {
4553  mbedtls_mpi_free(&conf->dhm_P);
4554  mbedtls_mpi_free(&conf->dhm_G);
4555  return ret;
4556  }
4557 
4558  return 0;
4559 }
4560 #endif /* MBEDTLS_DEPRECATED_REMOVED */
4561 
4563  const unsigned char *dhm_P, size_t P_len,
4564  const unsigned char *dhm_G, size_t G_len)
4565 {
4567 
4568  mbedtls_mpi_free(&conf->dhm_P);
4569  mbedtls_mpi_free(&conf->dhm_G);
4570 
4571  if ((ret = mbedtls_mpi_read_binary(&conf->dhm_P, dhm_P, P_len)) != 0 ||
4572  (ret = mbedtls_mpi_read_binary(&conf->dhm_G, dhm_G, G_len)) != 0) {
4573  mbedtls_mpi_free(&conf->dhm_P);
4574  mbedtls_mpi_free(&conf->dhm_G);
4575  return ret;
4576  }
4577 
4578  return 0;
4579 }
4580 
4582 {
4584 
4585  mbedtls_mpi_free(&conf->dhm_P);
4586  mbedtls_mpi_free(&conf->dhm_G);
4587 
4588  if ((ret = mbedtls_mpi_copy(&conf->dhm_P, &dhm_ctx->P)) != 0 ||
4589  (ret = mbedtls_mpi_copy(&conf->dhm_G, &dhm_ctx->G)) != 0) {
4590  mbedtls_mpi_free(&conf->dhm_P);
4591  mbedtls_mpi_free(&conf->dhm_G);
4592  return ret;
4593  }
4594 
4595  return 0;
4596 }
4597 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
4598 
4599 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
4600 /*
4601  * Set the minimum length for Diffie-Hellman parameters
4602  */
4604  unsigned int bitlen)
4605 {
4606  conf->dhm_min_bitlen = bitlen;
4607 }
4608 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
4609 
4610 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
4611 /*
4612  * Set allowed/preferred hashes for handshake signatures
4613  */
4615  const int *hashes)
4616 {
4617  conf->sig_hashes = hashes;
4618 }
4619 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
4620 
4621 #if defined(MBEDTLS_ECP_C)
4622 /*
4623  * Set the allowed elliptic curves
4624  */
4626  const mbedtls_ecp_group_id *curve_list)
4627 {
4628  conf->curve_list = curve_list;
4629 }
4630 #endif /* MBEDTLS_ECP_C */
4631 
4632 #if defined(MBEDTLS_X509_CRT_PARSE_C)
4633 int mbedtls_ssl_set_hostname(mbedtls_ssl_context *ssl, const char *hostname)
4634 {
4635  /* Initialize to suppress unnecessary compiler warning */
4636  size_t hostname_len = 0;
4637 
4638  /* Check if new hostname is valid before
4639  * making any change to current one */
4640  if (hostname != NULL) {
4641  hostname_len = strlen(hostname);
4642 
4643  if (hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN) {
4645  }
4646  }
4647 
4648  /* Now it's clear that we will overwrite the old hostname,
4649  * so we can free it safely */
4650 
4651  if (ssl->hostname != NULL) {
4652  mbedtls_platform_zeroize(ssl->hostname, strlen(ssl->hostname));
4653  mbedtls_free(ssl->hostname);
4654  }
4655 
4656  /* Passing NULL as hostname shall clear the old one */
4657 
4658  if (hostname == NULL) {
4659  ssl->hostname = NULL;
4660  } else {
4661  ssl->hostname = mbedtls_calloc(1, hostname_len + 1);
4662  if (ssl->hostname == NULL) {
4664  }
4665 
4666  memcpy(ssl->hostname, hostname, hostname_len);
4667 
4668  ssl->hostname[hostname_len] = '\0';
4669  }
4670 
4671  return 0;
4672 }
4673 #endif /* MBEDTLS_X509_CRT_PARSE_C */
4674 
4675 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4677  int (*f_sni)(void *, mbedtls_ssl_context *,
4678  const unsigned char *, size_t),
4679  void *p_sni)
4680 {
4681  conf->f_sni = f_sni;
4682  conf->p_sni = p_sni;
4683 }
4684 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
4685 
4686 #if defined(MBEDTLS_SSL_ALPN)
4688 {
4689  size_t cur_len, tot_len;
4690  const char **p;
4691 
4692  /*
4693  * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
4694  * MUST NOT be truncated."
4695  * We check lengths now rather than later.
4696  */
4697  tot_len = 0;
4698  for (p = protos; *p != NULL; p++) {
4699  cur_len = strlen(*p);
4700  tot_len += cur_len;
4701 
4702  if ((cur_len == 0) ||
4703  (cur_len > MBEDTLS_SSL_MAX_ALPN_NAME_LEN) ||
4704  (tot_len > MBEDTLS_SSL_MAX_ALPN_LIST_LEN)) {
4706  }
4707  }
4708 
4709  conf->alpn_list = protos;
4710 
4711  return 0;
4712 }
4713 
4715 {
4716  return ssl->alpn_chosen;
4717 }
4718 #endif /* MBEDTLS_SSL_ALPN */
4719 
4720 #if defined(MBEDTLS_SSL_DTLS_SRTP)
4721 void mbedtls_ssl_conf_srtp_mki_value_supported(mbedtls_ssl_config *conf,
4722  int support_mki_value)
4723 {
4724  conf->dtls_srtp_mki_support = support_mki_value;
4725 }
4726 
4727 int mbedtls_ssl_dtls_srtp_set_mki_value(mbedtls_ssl_context *ssl,
4728  unsigned char *mki_value,
4729  uint16_t mki_len)
4730 {
4731  if (mki_len > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH) {
4733  }
4734 
4735  if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED) {
4737  }
4738 
4739  memcpy(ssl->dtls_srtp_info.mki_value, mki_value, mki_len);
4740  ssl->dtls_srtp_info.mki_len = mki_len;
4741  return 0;
4742 }
4743 
4744 int mbedtls_ssl_conf_dtls_srtp_protection_profiles(mbedtls_ssl_config *conf,
4745  const mbedtls_ssl_srtp_profile *profiles)
4746 {
4747  const mbedtls_ssl_srtp_profile *p;
4748  size_t list_size = 0;
4749 
4750  /* check the profiles list: all entry must be valid,
4751  * its size cannot be more than the total number of supported profiles, currently 4 */
4752  for (p = profiles; *p != MBEDTLS_TLS_SRTP_UNSET &&
4753  list_size <= MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH;
4754  p++) {
4755  if (mbedtls_ssl_check_srtp_profile_value(*p) != MBEDTLS_TLS_SRTP_UNSET) {
4756  list_size++;
4757  } else {
4758  /* unsupported value, stop parsing and set the size to an error value */
4759  list_size = MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH + 1;
4760  }
4761  }
4762 
4763  if (list_size > MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH) {
4764  conf->dtls_srtp_profile_list = NULL;
4765  conf->dtls_srtp_profile_list_len = 0;
4767  }
4768 
4769  conf->dtls_srtp_profile_list = profiles;
4770  conf->dtls_srtp_profile_list_len = list_size;
4771 
4772  return 0;
4773 }
4774 
4775 void mbedtls_ssl_get_dtls_srtp_negotiation_result(const mbedtls_ssl_context *ssl,
4776  mbedtls_dtls_srtp_info *dtls_srtp_info)
4777 {
4778  dtls_srtp_info->chosen_dtls_srtp_profile = ssl->dtls_srtp_info.chosen_dtls_srtp_profile;
4779  /* do not copy the mki value if there is no chosen profile */
4780  if (dtls_srtp_info->chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET) {
4781  dtls_srtp_info->mki_len = 0;
4782  } else {
4783  dtls_srtp_info->mki_len = ssl->dtls_srtp_info.mki_len;
4784  memcpy(dtls_srtp_info->mki_value, ssl->dtls_srtp_info.mki_value,
4785  ssl->dtls_srtp_info.mki_len);
4786  }
4787 }
4788 #endif /* MBEDTLS_SSL_DTLS_SRTP */
4789 
4790 void mbedtls_ssl_conf_max_version(mbedtls_ssl_config *conf, int major, int minor)
4791 {
4792  conf->max_major_ver = major;
4793  conf->max_minor_ver = minor;
4794 }
4795 
4796 void mbedtls_ssl_conf_min_version(mbedtls_ssl_config *conf, int major, int minor)
4797 {
4798  conf->min_major_ver = major;
4799  conf->min_minor_ver = minor;
4800 }
4801 
4802 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
4804 {
4805  conf->fallback = fallback;
4806 }
4807 #endif
4808 
4809 #if defined(MBEDTLS_SSL_SRV_C)
4811  char cert_req_ca_list)
4812 {
4813  conf->cert_req_ca_list = cert_req_ca_list;
4814 }
4815 #endif
4816 
4817 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
4819 {
4820  conf->encrypt_then_mac = etm;
4821 }
4822 #endif
4823 
4824 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
4826 {
4827  conf->extended_ms = ems;
4828 }
4829 #endif
4830 
4831 #if defined(MBEDTLS_ARC4_C)
4833 {
4834  conf->arc4_disabled = arc4;
4835 }
4836 #endif
4837 
4838 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
4839 int mbedtls_ssl_conf_max_frag_len(mbedtls_ssl_config *conf, unsigned char mfl_code)
4840 {
4841  if (mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
4844  }
4845 
4846  conf->mfl_code = mfl_code;
4847 
4848  return 0;
4849 }
4850 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
4851 
4852 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
4854 {
4855  conf->trunc_hmac = truncate;
4856 }
4857 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
4858 
4859 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
4860 void mbedtls_ssl_conf_cbc_record_splitting(mbedtls_ssl_config *conf, char split)
4861 {
4862  conf->cbc_record_splitting = split;
4863 }
4864 #endif
4865 
4867 {
4868  conf->allow_legacy_renegotiation = allow_legacy;
4869 }
4870 
4871 #if defined(MBEDTLS_SSL_RENEGOTIATION)
4873 {
4874  conf->disable_renegotiation = renegotiation;
4875 }
4876 
4878 {
4879  conf->renego_max_records = max_records;
4880 }
4881 
4883  const unsigned char period[8])
4884 {
4885  memcpy(conf->renego_period, period, 8);
4886 }
4887 #endif /* MBEDTLS_SSL_RENEGOTIATION */
4888 
4889 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
4890 #if defined(MBEDTLS_SSL_CLI_C)
4892 {
4893  conf->session_tickets = use_tickets;
4894 }
4895 #endif
4896 
4897 #if defined(MBEDTLS_SSL_SRV_C)
4899  mbedtls_ssl_ticket_write_t *f_ticket_write,
4900  mbedtls_ssl_ticket_parse_t *f_ticket_parse,
4901  void *p_ticket)
4902 {
4903  conf->f_ticket_write = f_ticket_write;
4904  conf->f_ticket_parse = f_ticket_parse;
4905  conf->p_ticket = p_ticket;
4906 }
4907 #endif
4908 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
4909 
4910 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
4912  mbedtls_ssl_export_keys_t *f_export_keys,
4913  void *p_export_keys)
4914 {
4915  conf->f_export_keys = f_export_keys;
4916  conf->p_export_keys = p_export_keys;
4917 }
4918 
4920  mbedtls_ssl_export_keys_ext_t *f_export_keys_ext,
4921  void *p_export_keys)
4922 {
4923  conf->f_export_keys_ext = f_export_keys_ext;
4924  conf->p_export_keys = p_export_keys;
4925 }
4926 #endif
4927 
4928 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
4929 void mbedtls_ssl_conf_async_private_cb(
4930  mbedtls_ssl_config *conf,
4931  mbedtls_ssl_async_sign_t *f_async_sign,
4932  mbedtls_ssl_async_decrypt_t *f_async_decrypt,
4933  mbedtls_ssl_async_resume_t *f_async_resume,
4934  mbedtls_ssl_async_cancel_t *f_async_cancel,
4935  void *async_config_data)
4936 {
4937  conf->f_async_sign_start = f_async_sign;
4938  conf->f_async_decrypt_start = f_async_decrypt;
4939  conf->f_async_resume = f_async_resume;
4940  conf->f_async_cancel = f_async_cancel;
4941  conf->p_async_config_data = async_config_data;
4942 }
4943 
4944 void *mbedtls_ssl_conf_get_async_config_data(const mbedtls_ssl_config *conf)
4945 {
4946  return conf->p_async_config_data;
4947 }
4948 
4949 void *mbedtls_ssl_get_async_operation_data(const mbedtls_ssl_context *ssl)
4950 {
4951  if (ssl->handshake == NULL) {
4952  return NULL;
4953  } else {
4954  return ssl->handshake->user_async_ctx;
4955  }
4956 }
4957 
4958 void mbedtls_ssl_set_async_operation_data(mbedtls_ssl_context *ssl,
4959  void *ctx)
4960 {
4961  if (ssl->handshake != NULL) {
4962  ssl->handshake->user_async_ctx = ctx;
4963  }
4964 }
4965 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
4966 
4967 /*
4968  * SSL get accessors
4969  */
4971 {
4972  if (ssl->session != NULL) {
4973  return ssl->session->verify_result;
4974  }
4975 
4976  if (ssl->session_negotiate != NULL) {
4977  return ssl->session_negotiate->verify_result;
4978  }
4979 
4980  return 0xFFFFFFFF;
4981 }
4982 
4984 {
4985  if (ssl == NULL || ssl->session == NULL) {
4986  return NULL;
4987  }
4988 
4990 }
4991 
4993 {
4994 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4996  switch (ssl->minor_ver) {
4998  return "DTLSv1.0";
4999 
5001  return "DTLSv1.2";
5002 
5003  default:
5004  return "unknown (DTLS)";
5005  }
5006  }
5007 #endif
5008 
5009  switch (ssl->minor_ver) {
5011  return "SSLv3.0";
5012 
5014  return "TLSv1.0";
5015 
5017  return "TLSv1.1";
5018 
5020  return "TLSv1.2";
5021 
5022  default:
5023  return "unknown";
5024  }
5025 }
5026 
5027 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5029 {
5030  size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN;
5031  size_t read_mfl;
5032 
5033  /* Use the configured MFL for the client if we're past SERVER_HELLO_DONE */
5034  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
5036  return ssl_mfl_code_to_length(ssl->conf->mfl_code);
5037  }
5038 
5039  /* Check if a smaller max length was negotiated */
5040  if (ssl->session_out != NULL) {
5041  read_mfl = ssl_mfl_code_to_length(ssl->session_out->mfl_code);
5042  if (read_mfl < max_len) {
5043  max_len = read_mfl;
5044  }
5045  }
5046 
5047  // During a handshake, use the value being negotiated
5048  if (ssl->session_negotiate != NULL) {
5049  read_mfl = ssl_mfl_code_to_length(ssl->session_negotiate->mfl_code);
5050  if (read_mfl < max_len) {
5051  max_len = read_mfl;
5052  }
5053  }
5054 
5055  return max_len;
5056 }
5057 
5059 {
5060  size_t max_len;
5061 
5062  /*
5063  * Assume mfl_code is correct since it was checked when set
5064  */
5065  max_len = ssl_mfl_code_to_length(ssl->conf->mfl_code);
5066 
5067  /* Check if a smaller max length was negotiated */
5068  if (ssl->session_out != NULL &&
5069  ssl_mfl_code_to_length(ssl->session_out->mfl_code) < max_len) {
5070  max_len = ssl_mfl_code_to_length(ssl->session_out->mfl_code);
5071  }
5072 
5073  /* During a handshake, use the value being negotiated */
5074  if (ssl->session_negotiate != NULL &&
5075  ssl_mfl_code_to_length(ssl->session_negotiate->mfl_code) < max_len) {
5076  max_len = ssl_mfl_code_to_length(ssl->session_negotiate->mfl_code);
5077  }
5078 
5079  return max_len;
5080 }
5081 
5082 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
5084 {
5086 }
5087 #endif /* !MBEDTLS_DEPRECATED_REMOVED */
5088 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
5089 
5090 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5092 {
5093  /* Return unlimited mtu for client hello messages to avoid fragmentation. */
5094  if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
5095  (ssl->state == MBEDTLS_SSL_CLIENT_HELLO ||
5096  ssl->state == MBEDTLS_SSL_SERVER_HELLO)) {
5097  return 0;
5098  }
5099 
5100  if (ssl->handshake == NULL || ssl->handshake->mtu == 0) {
5101  return ssl->mtu;
5102  }
5103 
5104  if (ssl->mtu == 0) {
5105  return ssl->handshake->mtu;
5106  }
5107 
5108  return ssl->mtu < ssl->handshake->mtu ?
5109  ssl->mtu : ssl->handshake->mtu;
5110 }
5111 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5112 
5114 {
5115  size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
5116 
5117 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
5118  !defined(MBEDTLS_SSL_PROTO_DTLS)
5119  (void) ssl;
5120 #endif
5121 
5122 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5123  const size_t mfl = mbedtls_ssl_get_output_max_frag_len(ssl);
5124 
5125  if (max_len > mfl) {
5126  max_len = mfl;
5127  }
5128 #endif
5129 
5130 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5131  if (mbedtls_ssl_get_current_mtu(ssl) != 0) {
5132  const size_t mtu = mbedtls_ssl_get_current_mtu(ssl);
5133  const int ret = mbedtls_ssl_get_record_expansion(ssl);
5134  const size_t overhead = (size_t) ret;
5135 
5136  if (ret < 0) {
5137  return ret;
5138  }
5139 
5140  if (mtu <= overhead) {
5141  MBEDTLS_SSL_DEBUG_MSG(1, ("MTU too low for record expansion"));
5143  }
5144 
5145  if (max_len > mtu - overhead) {
5146  max_len = mtu - overhead;
5147  }
5148  }
5149 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5150 
5151 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
5152  !defined(MBEDTLS_SSL_PROTO_DTLS)
5153  ((void) ssl);
5154 #endif
5155 
5156  return (int) max_len;
5157 }
5158 
5159 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5161 {
5162  if (ssl == NULL || ssl->session == NULL) {
5163  return NULL;
5164  }
5165 
5166 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5167  return ssl->session->peer_cert;
5168 #else
5169  return NULL;
5170 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5171 }
5172 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5173 
5174 #if defined(MBEDTLS_SSL_CLI_C)
5176  mbedtls_ssl_session *dst)
5177 {
5178  if (ssl == NULL ||
5179  dst == NULL ||
5180  ssl->session == NULL ||
5181  ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT) {
5183  }
5184 
5185  return mbedtls_ssl_session_copy(dst, ssl->session);
5186 }
5187 #endif /* MBEDTLS_SSL_CLI_C */
5188 
5190 {
5191  if (ssl == NULL) {
5192  return NULL;
5193  }
5194 
5195  return ssl->session;
5196 }
5197 
5198 /*
5199  * Define ticket header determining Mbed TLS version
5200  * and structure of the ticket.
5201  */
5202 
5203 /*
5204  * Define bitflag determining compile-time settings influencing
5205  * structure of serialized SSL sessions.
5206  */
5207 
5208 #if defined(MBEDTLS_HAVE_TIME)
5209 #define SSL_SERIALIZED_SESSION_CONFIG_TIME 1
5210 #else
5211 #define SSL_SERIALIZED_SESSION_CONFIG_TIME 0
5212 #endif /* MBEDTLS_HAVE_TIME */
5213 
5214 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5215 #define SSL_SERIALIZED_SESSION_CONFIG_CRT 1
5216 #else
5217 #define SSL_SERIALIZED_SESSION_CONFIG_CRT 0
5218 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5219 
5220 #if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SESSION_TICKETS)
5221 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 1
5222 #else
5223 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 0
5224 #endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_SESSION_TICKETS */
5225 
5226 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5227 #define SSL_SERIALIZED_SESSION_CONFIG_MFL 1
5228 #else
5229 #define SSL_SERIALIZED_SESSION_CONFIG_MFL 0
5230 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
5231 
5232 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
5233 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 1
5234 #else
5235 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 0
5236 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
5237 
5238 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5239 #define SSL_SERIALIZED_SESSION_CONFIG_ETM 1
5240 #else
5241 #define SSL_SERIALIZED_SESSION_CONFIG_ETM 0
5242 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
5243 
5244 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
5245 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 1
5246 #else
5247 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 0
5248 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
5249 
5250 #define SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT 0
5251 #define SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT 1
5252 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT 2
5253 #define SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT 3
5254 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT 4
5255 #define SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT 5
5256 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT 6
5257 
5258 #define SSL_SERIALIZED_SESSION_CONFIG_BITFLAG \
5259  ((uint16_t) ( \
5260  (SSL_SERIALIZED_SESSION_CONFIG_TIME << SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT) | \
5261  (SSL_SERIALIZED_SESSION_CONFIG_CRT << SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT) | \
5262  (SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET << \
5263  SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT) | \
5264  (SSL_SERIALIZED_SESSION_CONFIG_MFL << SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT) | \
5265  (SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC << \
5266  SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT) | \
5267  (SSL_SERIALIZED_SESSION_CONFIG_ETM << SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT) | \
5268  (SSL_SERIALIZED_SESSION_CONFIG_TICKET << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT)))
5269 
5270 static unsigned char ssl_serialized_session_header[] = {
5276 };
5277 
5278 /*
5279  * Serialize a session in the following format:
5280  * (in the presentation language of TLS, RFC 8446 section 3)
5281  *
5282  * opaque mbedtls_version[3]; // major, minor, patch
5283  * opaque session_format[2]; // version-specific 16-bit field determining
5284  * // the format of the remaining
5285  * // serialized data.
5286  *
5287  * Note: When updating the format, remember to keep
5288  * these version+format bytes.
5289  *
5290  * // In this version, `session_format` determines
5291  * // the setting of those compile-time
5292  * // configuration options which influence
5293  * // the structure of mbedtls_ssl_session.
5294  * uint64 start_time;
5295  * uint8 ciphersuite[2]; // defined by the standard
5296  * uint8 compression; // 0 or 1
5297  * uint8 session_id_len; // at most 32
5298  * opaque session_id[32];
5299  * opaque master[48]; // fixed length in the standard
5300  * uint32 verify_result;
5301  * opaque peer_cert<0..2^24-1>; // length 0 means no peer cert
5302  * opaque ticket<0..2^24-1>; // length 0 means no ticket
5303  * uint32 ticket_lifetime;
5304  * uint8 mfl_code; // up to 255 according to standard
5305  * uint8 trunc_hmac; // 0 or 1
5306  * uint8 encrypt_then_mac; // 0 or 1
5307  *
5308  * The order is the same as in the definition of the structure, except
5309  * verify_result is put before peer_cert so that all mandatory fields come
5310  * together in one block.
5311  */
5313 static int ssl_session_save(const mbedtls_ssl_session *session,
5314  unsigned char omit_header,
5315  unsigned char *buf,
5316  size_t buf_len,
5317  size_t *olen)
5318 {
5319  unsigned char *p = buf;
5320  size_t used = 0;
5321 #if defined(MBEDTLS_HAVE_TIME)
5322  uint64_t start;
5323 #endif
5324 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5325 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5326  size_t cert_len;
5327 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5328 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5329 
5330 
5331  if (!omit_header) {
5332  /*
5333  * Add version identifier
5334  */
5335 
5336  used += sizeof(ssl_serialized_session_header);
5337 
5338  if (used <= buf_len) {
5341  p += sizeof(ssl_serialized_session_header);
5342  }
5343  }
5344 
5345  /*
5346  * Time
5347  */
5348 #if defined(MBEDTLS_HAVE_TIME)
5349  used += 8;
5350 
5351  if (used <= buf_len) {
5352  start = (uint64_t) session->start;
5353 
5354  MBEDTLS_PUT_UINT64_BE(start, p, 0);
5355  p += 8;
5356  }
5357 #endif /* MBEDTLS_HAVE_TIME */
5358 
5359  /*
5360  * Basic mandatory fields
5361  */
5362  used += 2 /* ciphersuite */
5363  + 1 /* compression */
5364  + 1 /* id_len */
5365  + sizeof(session->id)
5366  + sizeof(session->master)
5367  + 4; /* verify_result */
5368 
5369  if (used <= buf_len) {
5370  MBEDTLS_PUT_UINT16_BE(session->ciphersuite, p, 0);
5371  p += 2;
5372 
5373  *p++ = MBEDTLS_BYTE_0(session->compression);
5374 
5375  *p++ = MBEDTLS_BYTE_0(session->id_len);
5376  memcpy(p, session->id, 32);
5377  p += 32;
5378 
5379  memcpy(p, session->master, 48);
5380  p += 48;
5381 
5382  MBEDTLS_PUT_UINT32_BE(session->verify_result, p, 0);
5383  p += 4;
5384  }
5385 
5386  /*
5387  * Peer's end-entity certificate
5388  */
5389 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5390 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5391  if (session->peer_cert == NULL) {
5392  cert_len = 0;
5393  } else {
5394  cert_len = session->peer_cert->raw.len;
5395  }
5396 
5397  used += 3 + cert_len;
5398 
5399  if (used <= buf_len) {
5400  *p++ = MBEDTLS_BYTE_2(cert_len);
5401  *p++ = MBEDTLS_BYTE_1(cert_len);
5402  *p++ = MBEDTLS_BYTE_0(cert_len);
5403 
5404  if (session->peer_cert != NULL) {
5405  memcpy(p, session->peer_cert->raw.p, cert_len);
5406  p += cert_len;
5407  }
5408  }
5409 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5410  if (session->peer_cert_digest != NULL) {
5411  used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len;
5412  if (used <= buf_len) {
5413  *p++ = (unsigned char) session->peer_cert_digest_type;
5414  *p++ = (unsigned char) session->peer_cert_digest_len;
5415  memcpy(p, session->peer_cert_digest,
5416  session->peer_cert_digest_len);
5417  p += session->peer_cert_digest_len;
5418  }
5419  } else {
5420  used += 2;
5421  if (used <= buf_len) {
5422  *p++ = (unsigned char) MBEDTLS_MD_NONE;
5423  *p++ = 0;
5424  }
5425  }
5426 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5427 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5428 
5429  /*
5430  * Session ticket if any, plus associated data
5431  */
5432 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5433  used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */
5434 
5435  if (used <= buf_len) {
5436  *p++ = MBEDTLS_BYTE_2(session->ticket_len);
5437  *p++ = MBEDTLS_BYTE_1(session->ticket_len);
5438  *p++ = MBEDTLS_BYTE_0(session->ticket_len);
5439 
5440  if (session->ticket != NULL) {
5441  memcpy(p, session->ticket, session->ticket_len);
5442  p += session->ticket_len;
5443  }
5444 
5445  MBEDTLS_PUT_UINT32_BE(session->ticket_lifetime, p, 0);
5446  p += 4;
5447  }
5448 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5449 
5450  /*
5451  * Misc extension-related info
5452  */
5453 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5454  used += 1;
5455 
5456  if (used <= buf_len) {
5457  *p++ = session->mfl_code;
5458  }
5459 #endif
5460 
5461 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
5462  used += 1;
5463 
5464  if (used <= buf_len) {
5465  *p++ = (unsigned char) ((session->trunc_hmac) & 0xFF);
5466  }
5467 #endif
5468 
5469 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5470  used += 1;
5471 
5472  if (used <= buf_len) {
5473  *p++ = MBEDTLS_BYTE_0(session->encrypt_then_mac);
5474  }
5475 #endif
5476 
5477  /* Done */
5478  *olen = used;
5479 
5480  if (used > buf_len) {
5482  }
5483 
5484  return 0;
5485 }
5486 
5487 /*
5488  * Public wrapper for ssl_session_save()
5489  */
5491  unsigned char *buf,
5492  size_t buf_len,
5493  size_t *olen)
5494 {
5495  return ssl_session_save(session, 0, buf, buf_len, olen);
5496 }
5497 
5498 /*
5499  * Deserialize session, see mbedtls_ssl_session_save() for format.
5500  *
5501  * This internal version is wrapped by a public function that cleans up in
5502  * case of error, and has an extra option omit_header.
5503  */
5506  unsigned char omit_header,
5507  const unsigned char *buf,
5508  size_t len)
5509 {
5510  const unsigned char *p = buf;
5511  const unsigned char * const end = buf + len;
5512 #if defined(MBEDTLS_HAVE_TIME)
5513  uint64_t start;
5514 #endif
5515 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5516 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5517  size_t cert_len;
5518 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5519 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5520 
5521  if (!omit_header) {
5522  /*
5523  * Check version identifier
5524  */
5525 
5526  if ((size_t) (end - p) < sizeof(ssl_serialized_session_header)) {
5528  }
5529 
5530  if (memcmp(p, ssl_serialized_session_header,
5531  sizeof(ssl_serialized_session_header)) != 0) {
5533  }
5534  p += sizeof(ssl_serialized_session_header);
5535  }
5536 
5537  /*
5538  * Time
5539  */
5540 #if defined(MBEDTLS_HAVE_TIME)
5541  if (8 > (size_t) (end - p)) {
5543  }
5544 
5545  start = ((uint64_t) p[0] << 56) |
5546  ((uint64_t) p[1] << 48) |
5547  ((uint64_t) p[2] << 40) |
5548  ((uint64_t) p[3] << 32) |
5549  ((uint64_t) p[4] << 24) |
5550  ((uint64_t) p[5] << 16) |
5551  ((uint64_t) p[6] << 8) |
5552  ((uint64_t) p[7]);
5553  p += 8;
5554 
5555  session->start = (time_t) start;
5556 #endif /* MBEDTLS_HAVE_TIME */
5557 
5558  /*
5559  * Basic mandatory fields
5560  */
5561  if (2 + 1 + 1 + 32 + 48 + 4 > (size_t) (end - p)) {
5563  }
5564 
5565  session->ciphersuite = (p[0] << 8) | p[1];
5566  p += 2;
5567 
5568  session->compression = *p++;
5569 
5570  session->id_len = *p++;
5571  memcpy(session->id, p, 32);
5572  p += 32;
5573 
5574  memcpy(session->master, p, 48);
5575  p += 48;
5576 
5577  session->verify_result = ((uint32_t) p[0] << 24) |
5578  ((uint32_t) p[1] << 16) |
5579  ((uint32_t) p[2] << 8) |
5580  ((uint32_t) p[3]);
5581  p += 4;
5582 
5583  /* Immediately clear invalid pointer values that have been read, in case
5584  * we exit early before we replaced them with valid ones. */
5585 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5586 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5587  session->peer_cert = NULL;
5588 #else
5589  session->peer_cert_digest = NULL;
5590 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5591 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5592 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5593  session->ticket = NULL;
5594 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5595 
5596  /*
5597  * Peer certificate
5598  */
5599 #if defined(MBEDTLS_X509_CRT_PARSE_C)
5600 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5601  /* Deserialize CRT from the end of the ticket. */
5602  if (3 > (size_t) (end - p)) {
5604  }
5605 
5606  cert_len = (p[0] << 16) | (p[1] << 8) | p[2];
5607  p += 3;
5608 
5609  if (cert_len != 0) {
5611 
5612  if (cert_len > (size_t) (end - p)) {
5614  }
5615 
5616  session->peer_cert = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
5617 
5618  if (session->peer_cert == NULL) {
5620  }
5621 
5622  mbedtls_x509_crt_init(session->peer_cert);
5623 
5624  if ((ret = mbedtls_x509_crt_parse_der(session->peer_cert,
5625  p, cert_len)) != 0) {
5626  mbedtls_x509_crt_free(session->peer_cert);
5627  mbedtls_free(session->peer_cert);
5628  session->peer_cert = NULL;
5629  return ret;
5630  }
5631 
5632  p += cert_len;
5633  }
5634 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5635  /* Deserialize CRT digest from the end of the ticket. */
5636  if (2 > (size_t) (end - p)) {
5638  }
5639 
5640  session->peer_cert_digest_type = (mbedtls_md_type_t) *p++;
5641  session->peer_cert_digest_len = (size_t) *p++;
5642 
5643  if (session->peer_cert_digest_len != 0) {
5644  const mbedtls_md_info_t *md_info =
5645  mbedtls_md_info_from_type(session->peer_cert_digest_type);
5646  if (md_info == NULL) {
5648  }
5649  if (session->peer_cert_digest_len != mbedtls_md_get_size(md_info)) {
5651  }
5652 
5653  if (session->peer_cert_digest_len > (size_t) (end - p)) {
5655  }
5656 
5657  session->peer_cert_digest =
5658  mbedtls_calloc(1, session->peer_cert_digest_len);
5659  if (session->peer_cert_digest == NULL) {
5661  }
5662 
5663  memcpy(session->peer_cert_digest, p,
5664  session->peer_cert_digest_len);
5665  p += session->peer_cert_digest_len;
5666  }
5667 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5668 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5669 
5670  /*
5671  * Session ticket and associated data
5672  */
5673 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5674  if (3 > (size_t) (end - p)) {
5676  }
5677 
5678  session->ticket_len = (p[0] << 16) | (p[1] << 8) | p[2];
5679  p += 3;
5680 
5681  if (session->ticket_len != 0) {
5682  if (session->ticket_len > (size_t) (end - p)) {
5684  }
5685 
5686  session->ticket = mbedtls_calloc(1, session->ticket_len);
5687  if (session->ticket == NULL) {
5689  }
5690 
5691  memcpy(session->ticket, p, session->ticket_len);
5692  p += session->ticket_len;
5693  }
5694 
5695  if (4 > (size_t) (end - p)) {
5697  }
5698 
5699  session->ticket_lifetime = ((uint32_t) p[0] << 24) |
5700  ((uint32_t) p[1] << 16) |
5701  ((uint32_t) p[2] << 8) |
5702  ((