v2 / thirdparty / mbedtls / library / ssl_msg.c
6611 lines · 5672 sloc · 233.21 KB · 3d9911f887ecec942f9ae2a5be02d064f233b729
Raw
1/*
2 * Generic SSL/TLS messaging layer functions
3 * (record layer + retransmission state machine)
4 *
5 * Copyright The Mbed TLS Contributors
6 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7 */
8/*
9 * http://www.ietf.org/rfc/rfc2246.txt
10 * http://www.ietf.org/rfc/rfc4346.txt
11 */
12
13#include "common.h"
14
15#if defined(MBEDTLS_SSL_TLS_C)
16
17#include "mbedtls/platform.h"
18
19#include "mbedtls/ssl.h"
20#include "ssl_misc.h"
21#include "debug_internal.h"
22#include "ssl_debug_helpers.h"
23#include "mbedtls/error.h"
24#include "mbedtls/platform_util.h"
25#include "mbedtls/version.h"
26#include "constant_time_internal.h"
27#include "mbedtls/constant_time.h"
28
29#include <limits.h>
30#include <string.h>
31
32#if defined(MBEDTLS_USE_PSA_CRYPTO)
33#include "psa_util_internal.h"
34#include "psa/crypto.h"
35#endif
36
37#if defined(MBEDTLS_X509_CRT_PARSE_C)
38#include "mbedtls/oid.h"
39#endif
40
41#if defined(MBEDTLS_USE_PSA_CRYPTO)
42/* Define a local translating function to save code size by not using too many
43 * arguments in each translating place. */
44static int local_err_translation(psa_status_t status)
45{
46 return psa_status_to_mbedtls(status, psa_to_ssl_errors,
47 ARRAY_LENGTH(psa_to_ssl_errors),
48 psa_generic_status_to_mbedtls);
49}
50#define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
51#endif
52
53#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
54
55#if defined(MBEDTLS_USE_PSA_CRYPTO)
56
57#if defined(PSA_WANT_ALG_SHA_384)
58#define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_384)
59#elif defined(PSA_WANT_ALG_SHA_256)
60#define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_256)
61#else /* See check_config.h */
62#define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_1)
63#endif
64
65MBEDTLS_STATIC_TESTABLE
66int mbedtls_ct_hmac(mbedtls_svc_key_id_t key,
67 psa_algorithm_t mac_alg,
68 const unsigned char *add_data,
69 size_t add_data_len,
70 const unsigned char *data,
71 size_t data_len_secret,
72 size_t min_data_len,
73 size_t max_data_len,
74 unsigned char *output)
75{
76 /*
77 * This function breaks the HMAC abstraction and uses psa_hash_clone()
78 * extension in order to get constant-flow behaviour.
79 *
80 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
81 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
82 * patterns (see RFC 2104, sec. 2).
83 *
84 * We'll first compute ikey/okey, then inner_hash = HASH(ikey + msg) by
85 * hashing up to minlen, then cloning the context, and for each byte up
86 * to maxlen finishing up the hash computation, keeping only the
87 * correct result.
88 *
89 * Then we only need to compute HASH(okey + inner_hash) and we're done.
90 */
91 psa_algorithm_t hash_alg = PSA_ALG_HMAC_GET_HASH(mac_alg);
92 const size_t block_size = PSA_HASH_BLOCK_LENGTH(hash_alg);
93 unsigned char key_buf[MAX_HASH_BLOCK_LENGTH];
94 const size_t hash_size = PSA_HASH_LENGTH(hash_alg);
95 psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
96 size_t hash_length;
97
98 unsigned char aux_out[PSA_HASH_MAX_SIZE];
99 psa_hash_operation_t aux_operation = PSA_HASH_OPERATION_INIT;
100 size_t offset;
101 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
102
103 size_t mac_key_length;
104 size_t i;
105
106#define PSA_CHK(func_call) \
107 do { \
108 status = (func_call); \
109 if (status != PSA_SUCCESS) \
110 goto cleanup; \
111 } while (0)
112
113 /* Export MAC key
114 * We assume key length is always exactly the output size
115 * which is never more than the block size, thus we use block_size
116 * as the key buffer size.
117 */
118 PSA_CHK(psa_export_key(key, key_buf, block_size, &mac_key_length));
119
120 /* Calculate ikey */
121 for (i = 0; i < mac_key_length; i++) {
122 key_buf[i] = (unsigned char) (key_buf[i] ^ 0x36);
123 }
124 for (; i < block_size; ++i) {
125 key_buf[i] = 0x36;
126 }
127
128 PSA_CHK(psa_hash_setup(&operation, hash_alg));
129
130 /* Now compute inner_hash = HASH(ikey + msg) */
131 PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
132 PSA_CHK(psa_hash_update(&operation, add_data, add_data_len));
133 PSA_CHK(psa_hash_update(&operation, data, min_data_len));
134
135 /* Fill the hash buffer in advance with something that is
136 * not a valid hash (barring an attack on the hash and
137 * deliberately-crafted input), in case the caller doesn't
138 * check the return status properly. */
139 memset(output, '!', hash_size);
140
141 /* For each possible length, compute the hash up to that point */
142 for (offset = min_data_len; offset <= max_data_len; offset++) {
143 PSA_CHK(psa_hash_clone(&operation, &aux_operation));
144 PSA_CHK(psa_hash_finish(&aux_operation, aux_out,
145 PSA_HASH_MAX_SIZE, &hash_length));
146 /* Keep only the correct inner_hash in the output buffer */
147 mbedtls_ct_memcpy_if(mbedtls_ct_uint_eq(offset, data_len_secret),
148 output, aux_out, NULL, hash_size);
149
150 if (offset < max_data_len) {
151 PSA_CHK(psa_hash_update(&operation, data + offset, 1));
152 }
153 }
154
155 /* Abort current operation to prepare for final operation */
156 PSA_CHK(psa_hash_abort(&operation));
157
158 /* Calculate okey */
159 for (i = 0; i < mac_key_length; i++) {
160 key_buf[i] = (unsigned char) ((key_buf[i] ^ 0x36) ^ 0x5C);
161 }
162 for (; i < block_size; ++i) {
163 key_buf[i] = 0x5C;
164 }
165
166 /* Now compute HASH(okey + inner_hash) */
167 PSA_CHK(psa_hash_setup(&operation, hash_alg));
168 PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
169 PSA_CHK(psa_hash_update(&operation, output, hash_size));
170 PSA_CHK(psa_hash_finish(&operation, output, hash_size, &hash_length));
171
172#undef PSA_CHK
173
174cleanup:
175 mbedtls_platform_zeroize(key_buf, MAX_HASH_BLOCK_LENGTH);
176 mbedtls_platform_zeroize(aux_out, PSA_HASH_MAX_SIZE);
177
178 psa_hash_abort(&operation);
179 psa_hash_abort(&aux_operation);
180 return PSA_TO_MBEDTLS_ERR(status);
181}
182
183#undef MAX_HASH_BLOCK_LENGTH
184
185#else
186MBEDTLS_STATIC_TESTABLE
187int mbedtls_ct_hmac(mbedtls_md_context_t *ctx,
188 const unsigned char *add_data,
189 size_t add_data_len,
190 const unsigned char *data,
191 size_t data_len_secret,
192 size_t min_data_len,
193 size_t max_data_len,
194 unsigned char *output)
195{
196 /*
197 * This function breaks the HMAC abstraction and uses the md_clone()
198 * extension to the MD API in order to get constant-flow behaviour.
199 *
200 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
201 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
202 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
203 *
204 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
205 * minlen, then cloning the context, and for each byte up to maxlen
206 * finishing up the hash computation, keeping only the correct result.
207 *
208 * Then we only need to compute HASH(okey + inner_hash) and we're done.
209 */
210 const mbedtls_md_type_t md_alg = mbedtls_md_get_type(ctx->md_info);
211 /* TLS 1.2 only supports SHA-384, SHA-256, SHA-1, MD-5,
212 * all of which have the same block size except SHA-384. */
213 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
214 const unsigned char * const ikey = ctx->hmac_ctx;
215 const unsigned char * const okey = ikey + block_size;
216 const size_t hash_size = mbedtls_md_get_size(ctx->md_info);
217
218 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
219 mbedtls_md_context_t aux;
220 size_t offset;
221 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
222
223 mbedtls_md_init(&aux);
224
225#define MD_CHK(func_call) \
226 do { \
227 ret = (func_call); \
228 if (ret != 0) \
229 goto cleanup; \
230 } while (0)
231
232 MD_CHK(mbedtls_md_setup(&aux, ctx->md_info, 0));
233
234 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
235 * so we can start directly with the message */
236 MD_CHK(mbedtls_md_update(ctx, add_data, add_data_len));
237 MD_CHK(mbedtls_md_update(ctx, data, min_data_len));
238
239 /* Fill the hash buffer in advance with something that is
240 * not a valid hash (barring an attack on the hash and
241 * deliberately-crafted input), in case the caller doesn't
242 * check the return status properly. */
243 memset(output, '!', hash_size);
244
245 /* For each possible length, compute the hash up to that point */
246 for (offset = min_data_len; offset <= max_data_len; offset++) {
247 MD_CHK(mbedtls_md_clone(&aux, ctx));
248 MD_CHK(mbedtls_md_finish(&aux, aux_out));
249 /* Keep only the correct inner_hash in the output buffer */
250 mbedtls_ct_memcpy_if(mbedtls_ct_uint_eq(offset, data_len_secret),
251 output, aux_out, NULL, hash_size);
252
253 if (offset < max_data_len) {
254 MD_CHK(mbedtls_md_update(ctx, data + offset, 1));
255 }
256 }
257
258 /* The context needs to finish() before it starts() again */
259 MD_CHK(mbedtls_md_finish(ctx, aux_out));
260
261 /* Now compute HASH(okey + inner_hash) */
262 MD_CHK(mbedtls_md_starts(ctx));
263 MD_CHK(mbedtls_md_update(ctx, okey, block_size));
264 MD_CHK(mbedtls_md_update(ctx, output, hash_size));
265 MD_CHK(mbedtls_md_finish(ctx, output));
266
267 /* Done, get ready for next time */
268 MD_CHK(mbedtls_md_hmac_reset(ctx));
269
270#undef MD_CHK
271
272cleanup:
273 mbedtls_md_free(&aux);
274 return ret;
275}
276
277#endif /* MBEDTLS_USE_PSA_CRYPTO */
278
279#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
280
281static uint32_t ssl_get_hs_total_len(mbedtls_ssl_context const *ssl);
282
283/*
284 * Start a timer.
285 * Passing millisecs = 0 cancels a running timer.
286 */
287void mbedtls_ssl_set_timer(mbedtls_ssl_context *ssl, uint32_t millisecs)
288{
289 if (ssl->f_set_timer == NULL) {
290 return;
291 }
292
293 MBEDTLS_SSL_DEBUG_MSG(3, ("set_timer to %d ms", (int) millisecs));
294 ssl->f_set_timer(ssl->p_timer, millisecs / 4, millisecs);
295}
296
297/*
298 * Return -1 is timer is expired, 0 if it isn't.
299 */
300int mbedtls_ssl_check_timer(mbedtls_ssl_context *ssl)
301{
302 if (ssl->f_get_timer == NULL) {
303 return 0;
304 }
305
306 if (ssl->f_get_timer(ssl->p_timer) == 2) {
307 MBEDTLS_SSL_DEBUG_MSG(3, ("timer expired"));
308 return -1;
309 }
310
311 return 0;
312}
313
314MBEDTLS_CHECK_RETURN_CRITICAL
315static int ssl_parse_record_header(mbedtls_ssl_context const *ssl,
316 unsigned char *buf,
317 size_t len,
318 mbedtls_record *rec);
319
320int mbedtls_ssl_check_record(mbedtls_ssl_context const *ssl,
321 unsigned char *buf,
322 size_t buflen)
323{
324 int ret = 0;
325 MBEDTLS_SSL_DEBUG_MSG(3, ("=> mbedtls_ssl_check_record"));
326 MBEDTLS_SSL_DEBUG_BUF(3, "record buffer", buf, buflen);
327
328 /* We don't support record checking in TLS because
329 * there doesn't seem to be a usecase for it.
330 */
331 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM) {
332 ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
333 goto exit;
334 }
335#if defined(MBEDTLS_SSL_PROTO_DTLS)
336 else {
337 mbedtls_record rec;
338
339 ret = ssl_parse_record_header(ssl, buf, buflen, &rec);
340 if (ret != 0) {
341 MBEDTLS_SSL_DEBUG_RET(3, "ssl_parse_record_header", ret);
342 goto exit;
343 }
344
345 if (ssl->transform_in != NULL) {
346 ret = mbedtls_ssl_decrypt_buf(ssl, ssl->transform_in, &rec);
347 if (ret != 0) {
348 MBEDTLS_SSL_DEBUG_RET(3, "mbedtls_ssl_decrypt_buf", ret);
349 goto exit;
350 }
351 }
352 }
353#endif /* MBEDTLS_SSL_PROTO_DTLS */
354
355exit:
356 /* On success, we have decrypted the buffer in-place, so make
357 * sure we don't leak any plaintext data. */
358 mbedtls_platform_zeroize(buf, buflen);
359
360 /* For the purpose of this API, treat messages with unexpected CID
361 * as well as such from future epochs as unexpected. */
362 if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID ||
363 ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
364 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
365 }
366
367 MBEDTLS_SSL_DEBUG_MSG(3, ("<= mbedtls_ssl_check_record"));
368 return ret;
369}
370
371#define SSL_DONT_FORCE_FLUSH 0
372#define SSL_FORCE_FLUSH 1
373
374#if defined(MBEDTLS_SSL_PROTO_DTLS)
375
376/* Forward declarations for functions related to message buffering. */
377static void ssl_buffering_free_slot(mbedtls_ssl_context *ssl,
378 uint8_t slot);
379static void ssl_buffering_shift_slots(mbedtls_ssl_context *ssl, unsigned shift);
380static void ssl_free_buffered_record(mbedtls_ssl_context *ssl);
381MBEDTLS_CHECK_RETURN_CRITICAL
382static int ssl_load_buffered_message(mbedtls_ssl_context *ssl);
383MBEDTLS_CHECK_RETURN_CRITICAL
384static int ssl_load_buffered_record(mbedtls_ssl_context *ssl);
385MBEDTLS_CHECK_RETURN_CRITICAL
386static int ssl_buffer_message(mbedtls_ssl_context *ssl);
387MBEDTLS_CHECK_RETURN_CRITICAL
388static int ssl_buffer_future_record(mbedtls_ssl_context *ssl,
389 mbedtls_record const *rec);
390MBEDTLS_CHECK_RETURN_CRITICAL
391static int ssl_next_record_is_in_datagram(mbedtls_ssl_context *ssl);
392
393static size_t ssl_get_maximum_datagram_size(mbedtls_ssl_context const *ssl)
394{
395 size_t mtu = mbedtls_ssl_get_current_mtu(ssl);
396#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
397 size_t out_buf_len = ssl->out_buf_len;
398#else
399 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
400#endif
401
402 if (mtu != 0 && mtu < out_buf_len) {
403 return mtu;
404 }
405
406 return out_buf_len;
407}
408
409MBEDTLS_CHECK_RETURN_CRITICAL
410static int ssl_get_remaining_space_in_datagram(mbedtls_ssl_context const *ssl)
411{
412 size_t const bytes_written = ssl->out_left;
413 size_t const mtu = ssl_get_maximum_datagram_size(ssl);
414
415 /* Double-check that the write-index hasn't gone
416 * past what we can transmit in a single datagram. */
417 if (bytes_written > mtu) {
418 /* Should never happen... */
419 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
420 }
421
422 return (int) (mtu - bytes_written);
423}
424
425MBEDTLS_CHECK_RETURN_CRITICAL
426static int ssl_get_remaining_payload_in_datagram(mbedtls_ssl_context const *ssl)
427{
428 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
429 size_t remaining, expansion;
430 size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
431
432#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
433 const size_t mfl = mbedtls_ssl_get_output_max_frag_len(ssl);
434
435 if (max_len > mfl) {
436 max_len = mfl;
437 }
438
439 /* By the standard (RFC 6066 Sect. 4), the MFL extension
440 * only limits the maximum record payload size, so in theory
441 * we would be allowed to pack multiple records of payload size
442 * MFL into a single datagram. However, this would mean that there's
443 * no way to explicitly communicate MTU restrictions to the peer.
444 *
445 * The following reduction of max_len makes sure that we never
446 * write datagrams larger than MFL + Record Expansion Overhead.
447 */
448 if (max_len <= ssl->out_left) {
449 return 0;
450 }
451
452 max_len -= ssl->out_left;
453#endif
454
455 ret = ssl_get_remaining_space_in_datagram(ssl);
456 if (ret < 0) {
457 return ret;
458 }
459 remaining = (size_t) ret;
460
461 ret = mbedtls_ssl_get_record_expansion(ssl);
462 if (ret < 0) {
463 return ret;
464 }
465 expansion = (size_t) ret;
466
467 if (remaining <= expansion) {
468 return 0;
469 }
470
471 remaining -= expansion;
472 if (remaining >= max_len) {
473 remaining = max_len;
474 }
475
476 return (int) remaining;
477}
478
479/*
480 * Double the retransmit timeout value, within the allowed range,
481 * returning -1 if the maximum value has already been reached.
482 */
483MBEDTLS_CHECK_RETURN_CRITICAL
484static int ssl_double_retransmit_timeout(mbedtls_ssl_context *ssl)
485{
486 uint32_t new_timeout;
487
488 if (ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max) {
489 return -1;
490 }
491
492 /* Implement the final paragraph of RFC 6347 section 4.1.1.1
493 * in the following way: after the initial transmission and a first
494 * retransmission, back off to a temporary estimated MTU of 508 bytes.
495 * This value is guaranteed to be deliverable (if not guaranteed to be
496 * delivered) of any compliant IPv4 (and IPv6) network, and should work
497 * on most non-IP stacks too. */
498 if (ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min) {
499 ssl->handshake->mtu = 508;
500 MBEDTLS_SSL_DEBUG_MSG(2, ("mtu autoreduction to %d bytes", ssl->handshake->mtu));
501 }
502
503 new_timeout = 2 * ssl->handshake->retransmit_timeout;
504
505 /* Avoid arithmetic overflow and range overflow */
506 if (new_timeout < ssl->handshake->retransmit_timeout ||
507 new_timeout > ssl->conf->hs_timeout_max) {
508 new_timeout = ssl->conf->hs_timeout_max;
509 }
510
511 ssl->handshake->retransmit_timeout = new_timeout;
512 MBEDTLS_SSL_DEBUG_MSG(3, ("update timeout value to %lu millisecs",
513 (unsigned long) ssl->handshake->retransmit_timeout));
514
515 return 0;
516}
517
518static void ssl_reset_retransmit_timeout(mbedtls_ssl_context *ssl)
519{
520 ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
521 MBEDTLS_SSL_DEBUG_MSG(3, ("update timeout value to %lu millisecs",
522 (unsigned long) ssl->handshake->retransmit_timeout));
523}
524#endif /* MBEDTLS_SSL_PROTO_DTLS */
525
526/*
527 * Encryption/decryption functions
528 */
529
530#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
531
532static size_t ssl_compute_padding_length(size_t len,
533 size_t granularity)
534{
535 return (granularity - (len + 1) % granularity) % granularity;
536}
537
538/* This functions transforms a (D)TLS plaintext fragment and a record content
539 * type into an instance of the (D)TLSInnerPlaintext structure. This is used
540 * in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect
541 * a record's content type.
542 *
543 * struct {
544 * opaque content[DTLSPlaintext.length];
545 * ContentType real_type;
546 * uint8 zeros[length_of_padding];
547 * } (D)TLSInnerPlaintext;
548 *
549 * Input:
550 * - `content`: The beginning of the buffer holding the
551 * plaintext to be wrapped.
552 * - `*content_size`: The length of the plaintext in Bytes.
553 * - `max_len`: The number of Bytes available starting from
554 * `content`. This must be `>= *content_size`.
555 * - `rec_type`: The desired record content type.
556 *
557 * Output:
558 * - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure.
559 * - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure.
560 *
561 * Returns:
562 * - `0` on success.
563 * - A negative error code if `max_len` didn't offer enough space
564 * for the expansion.
565 */
566MBEDTLS_CHECK_RETURN_CRITICAL
567static int ssl_build_inner_plaintext(unsigned char *content,
568 size_t *content_size,
569 size_t remaining,
570 uint8_t rec_type,
571 size_t pad)
572{
573 size_t len = *content_size;
574
575 /* Write real content type */
576 if (remaining == 0) {
577 return -1;
578 }
579 content[len] = rec_type;
580 len++;
581 remaining--;
582
583 if (remaining < pad) {
584 return -1;
585 }
586 memset(content + len, 0, pad);
587 len += pad;
588 remaining -= pad;
589
590 *content_size = len;
591 return 0;
592}
593
594/* This function parses a (D)TLSInnerPlaintext structure.
595 * See ssl_build_inner_plaintext() for details. */
596MBEDTLS_CHECK_RETURN_CRITICAL
597static int ssl_parse_inner_plaintext(unsigned char const *content,
598 size_t *content_size,
599 uint8_t *rec_type)
600{
601 size_t remaining = *content_size;
602
603 /* Determine length of padding by skipping zeroes from the back. */
604 do {
605 if (remaining == 0) {
606 return -1;
607 }
608 remaining--;
609 } while (content[remaining] == 0);
610
611 *content_size = remaining;
612 *rec_type = content[remaining];
613
614 return 0;
615}
616#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID || MBEDTLS_SSL_PROTO_TLS1_3 */
617
618/* The size of the `add_data` structure depends on various
619 * factors, namely
620 *
621 * 1) CID functionality disabled
622 *
623 * additional_data =
624 * 8: seq_num +
625 * 1: type +
626 * 2: version +
627 * 2: length of inner plaintext +
628 *
629 * size = 13 bytes
630 *
631 * 2) CID functionality based on RFC 9146 enabled
632 *
633 * size = 8 + 1 + 1 + 1 + 2 + 2 + 6 + 2 + CID-length
634 * = 23 + CID-length
635 *
636 * 3) CID functionality based on legacy CID version
637 according to draft-ietf-tls-dtls-connection-id-05
638 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
639 *
640 * size = 13 + 1 + CID-length
641 *
642 * More information about the CID usage:
643 *
644 * Per Section 5.3 of draft-ietf-tls-dtls-connection-id-05 the
645 * size of the additional data structure is calculated as:
646 *
647 * additional_data =
648 * 8: seq_num +
649 * 1: tls12_cid +
650 * 2: DTLSCipherText.version +
651 * n: cid +
652 * 1: cid_length +
653 * 2: length_of_DTLSInnerPlaintext
654 *
655 * Per RFC 9146 the size of the add_data structure is calculated as:
656 *
657 * additional_data =
658 * 8: seq_num_placeholder +
659 * 1: tls12_cid +
660 * 1: cid_length +
661 * 1: tls12_cid +
662 * 2: DTLSCiphertext.version +
663 * 2: epoch +
664 * 6: sequence_number +
665 * n: cid +
666 * 2: length_of_DTLSInnerPlaintext
667 *
668 */
669static void ssl_extract_add_data_from_record(unsigned char *add_data,
670 size_t *add_data_len,
671 mbedtls_record *rec,
672 mbedtls_ssl_protocol_version
673 tls_version,
674 size_t taglen)
675{
676 /* Several types of ciphers have been defined for use with TLS and DTLS,
677 * and the MAC calculations for those ciphers differ slightly. Further
678 * variants were added when the CID functionality was added with RFC 9146.
679 * This implementations also considers the use of a legacy version of the
680 * CID specification published in draft-ietf-tls-dtls-connection-id-05,
681 * which is used in deployments.
682 *
683 * We will distinguish between the non-CID and the CID cases below.
684 *
685 * --- Non-CID cases ---
686 *
687 * Quoting RFC 5246 (TLS 1.2):
688 *
689 * additional_data = seq_num + TLSCompressed.type +
690 * TLSCompressed.version + TLSCompressed.length;
691 *
692 * For TLS 1.3, the record sequence number is dropped from the AAD
693 * and encoded within the nonce of the AEAD operation instead.
694 * Moreover, the additional data involves the length of the TLS
695 * ciphertext, not the TLS plaintext as in earlier versions.
696 * Quoting RFC 8446 (TLS 1.3):
697 *
698 * additional_data = TLSCiphertext.opaque_type ||
699 * TLSCiphertext.legacy_record_version ||
700 * TLSCiphertext.length
701 *
702 * We pass the tag length to this function in order to compute the
703 * ciphertext length from the inner plaintext length rec->data_len via
704 *
705 * TLSCiphertext.length = TLSInnerPlaintext.length + taglen.
706 *
707 * --- CID cases ---
708 *
709 * RFC 9146 uses a common pattern when constructing the data
710 * passed into a MAC / AEAD cipher.
711 *
712 * Data concatenation for MACs used with block ciphers with
713 * Encrypt-then-MAC Processing (with CID):
714 *
715 * data = seq_num_placeholder +
716 * tls12_cid +
717 * cid_length +
718 * tls12_cid +
719 * DTLSCiphertext.version +
720 * epoch +
721 * sequence_number +
722 * cid +
723 * DTLSCiphertext.length +
724 * IV +
725 * ENC(content + padding + padding_length)
726 *
727 * Data concatenation for MACs used with block ciphers (with CID):
728 *
729 * data = seq_num_placeholder +
730 * tls12_cid +
731 * cid_length +
732 * tls12_cid +
733 * DTLSCiphertext.version +
734 * epoch +
735 * sequence_number +
736 * cid +
737 * length_of_DTLSInnerPlaintext +
738 * DTLSInnerPlaintext.content +
739 * DTLSInnerPlaintext.real_type +
740 * DTLSInnerPlaintext.zeros
741 *
742 * AEAD ciphers use the following additional data calculation (with CIDs):
743 *
744 * additional_data = seq_num_placeholder +
745 * tls12_cid +
746 * cid_length +
747 * tls12_cid +
748 * DTLSCiphertext.version +
749 * epoch +
750 * sequence_number +
751 * cid +
752 * length_of_DTLSInnerPlaintext
753 *
754 * Section 5.3 of draft-ietf-tls-dtls-connection-id-05 (for legacy CID use)
755 * defines the additional data calculation as follows:
756 *
757 * additional_data = seq_num +
758 * tls12_cid +
759 * DTLSCipherText.version +
760 * cid +
761 * cid_length +
762 * length_of_DTLSInnerPlaintext
763 */
764
765 unsigned char *cur = add_data;
766 size_t ad_len_field = rec->data_len;
767
768#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
769 MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
770 const unsigned char seq_num_placeholder[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
771#endif
772
773#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
774 if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
775 /* In TLS 1.3, the AAD contains the length of the TLSCiphertext,
776 * which differs from the length of the TLSInnerPlaintext
777 * by the length of the authentication tag. */
778 ad_len_field += taglen;
779 } else
780#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
781 {
782 ((void) tls_version);
783 ((void) taglen);
784
785#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
786 MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
787 if (rec->cid_len != 0) {
788 // seq_num_placeholder
789 memcpy(cur, seq_num_placeholder, sizeof(seq_num_placeholder));
790 cur += sizeof(seq_num_placeholder);
791
792 // tls12_cid type
793 *cur = rec->type;
794 cur++;
795
796 // cid_length
797 *cur = rec->cid_len;
798 cur++;
799 } else
800#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
801 {
802 // epoch + sequence number
803 memcpy(cur, rec->ctr, sizeof(rec->ctr));
804 cur += sizeof(rec->ctr);
805 }
806 }
807
808 // type
809 *cur = rec->type;
810 cur++;
811
812 // version
813 memcpy(cur, rec->ver, sizeof(rec->ver));
814 cur += sizeof(rec->ver);
815
816#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
817 MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 1
818
819 if (rec->cid_len != 0) {
820 // CID
821 memcpy(cur, rec->cid, rec->cid_len);
822 cur += rec->cid_len;
823
824 // cid_length
825 *cur = rec->cid_len;
826 cur++;
827
828 // length of inner plaintext
829 MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
830 cur += 2;
831 } else
832#elif defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
833 MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
834
835 if (rec->cid_len != 0) {
836 // epoch + sequence number
837 memcpy(cur, rec->ctr, sizeof(rec->ctr));
838 cur += sizeof(rec->ctr);
839
840 // CID
841 memcpy(cur, rec->cid, rec->cid_len);
842 cur += rec->cid_len;
843
844 // length of inner plaintext
845 MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
846 cur += 2;
847 } else
848#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
849 {
850 MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
851 cur += 2;
852 }
853
854 *add_data_len = (size_t) (cur - add_data);
855}
856
857#if defined(MBEDTLS_SSL_HAVE_AEAD)
858MBEDTLS_CHECK_RETURN_CRITICAL
859static int ssl_transform_aead_dynamic_iv_is_explicit(
860 mbedtls_ssl_transform const *transform)
861{
862 return transform->ivlen != transform->fixed_ivlen;
863}
864
865/* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV )
866 *
867 * Concretely, this occurs in two variants:
868 *
869 * a) Fixed and dynamic IV lengths add up to total IV length, giving
870 * IV = fixed_iv || dynamic_iv
871 *
872 * This variant is used in TLS 1.2 when used with GCM or CCM.
873 *
874 * b) Fixed IV lengths matches total IV length, giving
875 * IV = fixed_iv XOR ( 0 || dynamic_iv )
876 *
877 * This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly.
878 *
879 * See also the documentation of mbedtls_ssl_transform.
880 *
881 * This function has the precondition that
882 *
883 * dst_iv_len >= max( fixed_iv_len, dynamic_iv_len )
884 *
885 * which has to be ensured by the caller. If this precondition
886 * violated, the behavior of this function is undefined.
887 */
888static void ssl_build_record_nonce(unsigned char *dst_iv,
889 size_t dst_iv_len,
890 unsigned char const *fixed_iv,
891 size_t fixed_iv_len,
892 unsigned char const *dynamic_iv,
893 size_t dynamic_iv_len)
894{
895 /* Start with Fixed IV || 0 */
896 memset(dst_iv, 0, dst_iv_len);
897 memcpy(dst_iv, fixed_iv, fixed_iv_len);
898
899 dst_iv += dst_iv_len - dynamic_iv_len;
900 mbedtls_xor(dst_iv, dst_iv, dynamic_iv, dynamic_iv_len);
901}
902#endif /* MBEDTLS_SSL_HAVE_AEAD */
903
904int mbedtls_ssl_encrypt_buf(mbedtls_ssl_context *ssl,
905 mbedtls_ssl_transform *transform,
906 mbedtls_record *rec,
907 int (*f_rng)(void *, unsigned char *, size_t),
908 void *p_rng)
909{
910 mbedtls_ssl_mode_t ssl_mode;
911 int auth_done = 0;
912 unsigned char *data;
913 /* For an explanation of the additional data length see
914 * the description of ssl_extract_add_data_from_record().
915 */
916#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
917 unsigned char add_data[23 + MBEDTLS_SSL_CID_OUT_LEN_MAX];
918#else
919 unsigned char add_data[13];
920#endif
921 size_t add_data_len;
922 size_t post_avail;
923
924 /* The SSL context is only used for debugging purposes! */
925#if !defined(MBEDTLS_DEBUG_C)
926 ssl = NULL; /* make sure we don't use it except for debug */
927 ((void) ssl);
928#endif
929
930 /* The PRNG is used for dynamic IV generation that's used
931 * for CBC transformations in TLS 1.2. */
932#if !(defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \
933 defined(MBEDTLS_SSL_PROTO_TLS1_2))
934 ((void) f_rng);
935 ((void) p_rng);
936#endif
937
938 MBEDTLS_SSL_DEBUG_MSG(2, ("=> encrypt buf"));
939
940 if (transform == NULL) {
941 MBEDTLS_SSL_DEBUG_MSG(1, ("no transform provided to encrypt_buf"));
942 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
943 }
944 if (rec == NULL
945 || rec->buf == NULL
946 || rec->buf_len < rec->data_offset
947 || rec->buf_len - rec->data_offset < rec->data_len
948#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
949 || rec->cid_len != 0
950#endif
951 ) {
952 MBEDTLS_SSL_DEBUG_MSG(1, ("bad record structure provided to encrypt_buf"));
953 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
954 }
955
956 ssl_mode = mbedtls_ssl_get_mode_from_transform(transform);
957
958 data = rec->buf + rec->data_offset;
959 post_avail = rec->buf_len - (rec->data_len + rec->data_offset);
960 MBEDTLS_SSL_DEBUG_BUF(4, "before encrypt: output payload",
961 data, rec->data_len);
962
963 if (rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN) {
964 MBEDTLS_SSL_DEBUG_MSG(1, ("Record content %" MBEDTLS_PRINTF_SIZET
965 " too large, maximum %" MBEDTLS_PRINTF_SIZET,
966 rec->data_len,
967 (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN));
968 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
969 }
970
971 /* The following two code paths implement the (D)TLSInnerPlaintext
972 * structure present in TLS 1.3 and DTLS 1.2 + CID.
973 *
974 * See ssl_build_inner_plaintext() for more information.
975 *
976 * Note that this changes `rec->data_len`, and hence
977 * `post_avail` needs to be recalculated afterwards.
978 *
979 * Note also that the two code paths cannot occur simultaneously
980 * since they apply to different versions of the protocol. There
981 * is hence no risk of double-addition of the inner plaintext.
982 */
983#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
984 if (transform->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
985 size_t padding =
986 ssl_compute_padding_length(rec->data_len,
987 MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY);
988 if (ssl_build_inner_plaintext(data,
989 &rec->data_len,
990 post_avail,
991 rec->type,
992 padding) != 0) {
993 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
994 }
995
996 rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA;
997 }
998#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
999
1000#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1001 /*
1002 * Add CID information
1003 */
1004 rec->cid_len = transform->out_cid_len;
1005 memcpy(rec->cid, transform->out_cid, transform->out_cid_len);
1006 MBEDTLS_SSL_DEBUG_BUF(3, "CID", rec->cid, rec->cid_len);
1007
1008 if (rec->cid_len != 0) {
1009 size_t padding =
1010 ssl_compute_padding_length(rec->data_len,
1011 MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY);
1012 /*
1013 * Wrap plaintext into DTLSInnerPlaintext structure.
1014 * See ssl_build_inner_plaintext() for more information.
1015 *
1016 * Note that this changes `rec->data_len`, and hence
1017 * `post_avail` needs to be recalculated afterwards.
1018 */
1019 if (ssl_build_inner_plaintext(data,
1020 &rec->data_len,
1021 post_avail,
1022 rec->type,
1023 padding) != 0) {
1024 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1025 }
1026
1027 rec->type = MBEDTLS_SSL_MSG_CID;
1028 }
1029#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1030
1031 post_avail = rec->buf_len - (rec->data_len + rec->data_offset);
1032
1033 /*
1034 * Add MAC before if needed
1035 */
1036#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
1037 if (ssl_mode == MBEDTLS_SSL_MODE_STREAM ||
1038 ssl_mode == MBEDTLS_SSL_MODE_CBC) {
1039 if (post_avail < transform->maclen) {
1040 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1041 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1042 }
1043#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1044 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
1045 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1046#if defined(MBEDTLS_USE_PSA_CRYPTO)
1047 psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1048 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1049 size_t sign_mac_length = 0;
1050#endif /* MBEDTLS_USE_PSA_CRYPTO */
1051
1052 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
1053 transform->tls_version,
1054 transform->taglen);
1055
1056#if defined(MBEDTLS_USE_PSA_CRYPTO)
1057 status = psa_mac_sign_setup(&operation, transform->psa_mac_enc,
1058 transform->psa_mac_alg);
1059 if (status != PSA_SUCCESS) {
1060 goto hmac_failed_etm_disabled;
1061 }
1062
1063 status = psa_mac_update(&operation, add_data, add_data_len);
1064 if (status != PSA_SUCCESS) {
1065 goto hmac_failed_etm_disabled;
1066 }
1067
1068 status = psa_mac_update(&operation, data, rec->data_len);
1069 if (status != PSA_SUCCESS) {
1070 goto hmac_failed_etm_disabled;
1071 }
1072
1073 status = psa_mac_sign_finish(&operation, mac, MBEDTLS_SSL_MAC_ADD,
1074 &sign_mac_length);
1075 if (status != PSA_SUCCESS) {
1076 goto hmac_failed_etm_disabled;
1077 }
1078#else
1079 ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, add_data,
1080 add_data_len);
1081 if (ret != 0) {
1082 goto hmac_failed_etm_disabled;
1083 }
1084 ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, data, rec->data_len);
1085 if (ret != 0) {
1086 goto hmac_failed_etm_disabled;
1087 }
1088 ret = mbedtls_md_hmac_finish(&transform->md_ctx_enc, mac);
1089 if (ret != 0) {
1090 goto hmac_failed_etm_disabled;
1091 }
1092 ret = mbedtls_md_hmac_reset(&transform->md_ctx_enc);
1093 if (ret != 0) {
1094 goto hmac_failed_etm_disabled;
1095 }
1096#endif /* MBEDTLS_USE_PSA_CRYPTO */
1097
1098 memcpy(data + rec->data_len, mac, transform->maclen);
1099#endif
1100
1101 MBEDTLS_SSL_DEBUG_BUF(4, "computed mac", data + rec->data_len,
1102 transform->maclen);
1103
1104 rec->data_len += transform->maclen;
1105 post_avail -= transform->maclen;
1106 auth_done++;
1107
1108hmac_failed_etm_disabled:
1109 mbedtls_platform_zeroize(mac, transform->maclen);
1110#if defined(MBEDTLS_USE_PSA_CRYPTO)
1111 ret = PSA_TO_MBEDTLS_ERR(status);
1112 status = psa_mac_abort(&operation);
1113 if (ret == 0 && status != PSA_SUCCESS) {
1114 ret = PSA_TO_MBEDTLS_ERR(status);
1115 }
1116#endif /* MBEDTLS_USE_PSA_CRYPTO */
1117 if (ret != 0) {
1118 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_hmac_xxx", ret);
1119 return ret;
1120 }
1121 }
1122#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
1123
1124 /*
1125 * Encrypt
1126 */
1127#if defined(MBEDTLS_SSL_SOME_SUITES_USE_STREAM)
1128 if (ssl_mode == MBEDTLS_SSL_MODE_STREAM) {
1129 MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
1130 "including %d bytes of padding",
1131 rec->data_len, 0));
1132
1133 /* The only supported stream cipher is "NULL",
1134 * so there's nothing to do here.*/
1135 } else
1136#endif /* MBEDTLS_SSL_SOME_SUITES_USE_STREAM */
1137
1138#if defined(MBEDTLS_SSL_HAVE_AEAD)
1139 if (ssl_mode == MBEDTLS_SSL_MODE_AEAD) {
1140 unsigned char iv[12];
1141 unsigned char *dynamic_iv;
1142 size_t dynamic_iv_len;
1143 int dynamic_iv_is_explicit =
1144 ssl_transform_aead_dynamic_iv_is_explicit(transform);
1145#if defined(MBEDTLS_USE_PSA_CRYPTO)
1146 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1147#endif /* MBEDTLS_USE_PSA_CRYPTO */
1148 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1149
1150 /* Check that there's space for the authentication tag. */
1151 if (post_avail < transform->taglen) {
1152 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1153 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1154 }
1155
1156 /*
1157 * Build nonce for AEAD encryption.
1158 *
1159 * Note: In the case of CCM and GCM in TLS 1.2, the dynamic
1160 * part of the IV is prepended to the ciphertext and
1161 * can be chosen freely - in particular, it need not
1162 * agree with the record sequence number.
1163 * However, since ChaChaPoly as well as all AEAD modes
1164 * in TLS 1.3 use the record sequence number as the
1165 * dynamic part of the nonce, we uniformly use the
1166 * record sequence number here in all cases.
1167 */
1168 dynamic_iv = rec->ctr;
1169 dynamic_iv_len = sizeof(rec->ctr);
1170
1171 ssl_build_record_nonce(iv, sizeof(iv),
1172 transform->iv_enc,
1173 transform->fixed_ivlen,
1174 dynamic_iv,
1175 dynamic_iv_len);
1176
1177 /*
1178 * Build additional data for AEAD encryption.
1179 * This depends on the TLS version.
1180 */
1181 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
1182 transform->tls_version,
1183 transform->taglen);
1184
1185 MBEDTLS_SSL_DEBUG_BUF(4, "IV used (internal)",
1186 iv, transform->ivlen);
1187 MBEDTLS_SSL_DEBUG_BUF(4, "IV used (transmitted)",
1188 dynamic_iv,
1189 dynamic_iv_is_explicit ? dynamic_iv_len : 0);
1190 MBEDTLS_SSL_DEBUG_BUF(4, "additional data used for AEAD",
1191 add_data, add_data_len);
1192 MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
1193 "including 0 bytes of padding",
1194 rec->data_len));
1195
1196 /*
1197 * Encrypt and authenticate
1198 */
1199#if defined(MBEDTLS_USE_PSA_CRYPTO)
1200 status = psa_aead_encrypt(transform->psa_key_enc,
1201 transform->psa_alg,
1202 iv, transform->ivlen,
1203 add_data, add_data_len,
1204 data, rec->data_len,
1205 data, rec->buf_len - (data - rec->buf),
1206 &rec->data_len);
1207
1208 if (status != PSA_SUCCESS) {
1209 ret = PSA_TO_MBEDTLS_ERR(status);
1210 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_encrypt_buf", ret);
1211 return ret;
1212 }
1213#else
1214 if ((ret = mbedtls_cipher_auth_encrypt_ext(&transform->cipher_ctx_enc,
1215 iv, transform->ivlen,
1216 add_data, add_data_len,
1217 data, rec->data_len, /* src */
1218 data, rec->buf_len - (size_t) (data - rec->buf), /* dst */
1219 &rec->data_len,
1220 transform->taglen)) != 0) {
1221 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_auth_encrypt_ext", ret);
1222 return ret;
1223 }
1224#endif /* MBEDTLS_USE_PSA_CRYPTO */
1225
1226 MBEDTLS_SSL_DEBUG_BUF(4, "after encrypt: tag",
1227 data + rec->data_len - transform->taglen,
1228 transform->taglen);
1229 /* Account for authentication tag. */
1230 post_avail -= transform->taglen;
1231
1232 /*
1233 * Prefix record content with dynamic IV in case it is explicit.
1234 */
1235 if (dynamic_iv_is_explicit != 0) {
1236 if (rec->data_offset < dynamic_iv_len) {
1237 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1238 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1239 }
1240
1241 memcpy(data - dynamic_iv_len, dynamic_iv, dynamic_iv_len);
1242 rec->data_offset -= dynamic_iv_len;
1243 rec->data_len += dynamic_iv_len;
1244 }
1245
1246 auth_done++;
1247 } else
1248#endif /* MBEDTLS_SSL_HAVE_AEAD */
1249#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
1250 if (ssl_mode == MBEDTLS_SSL_MODE_CBC ||
1251 ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
1252 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1253 size_t padlen, i;
1254 size_t olen;
1255#if defined(MBEDTLS_USE_PSA_CRYPTO)
1256 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1257 size_t part_len;
1258 psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
1259#endif /* MBEDTLS_USE_PSA_CRYPTO */
1260
1261 /* Currently we're always using minimal padding
1262 * (up to 255 bytes would be allowed). */
1263 padlen = transform->ivlen - (rec->data_len + 1) % transform->ivlen;
1264 if (padlen == transform->ivlen) {
1265 padlen = 0;
1266 }
1267
1268 /* Check there's enough space in the buffer for the padding. */
1269 if (post_avail < padlen + 1) {
1270 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1271 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1272 }
1273
1274 for (i = 0; i <= padlen; i++) {
1275 data[rec->data_len + i] = (unsigned char) padlen;
1276 }
1277
1278 rec->data_len += padlen + 1;
1279 post_avail -= padlen + 1;
1280
1281#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1282 /*
1283 * Prepend per-record IV for block cipher in TLS v1.2 as per
1284 * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
1285 */
1286 if (f_rng == NULL) {
1287 MBEDTLS_SSL_DEBUG_MSG(1, ("No PRNG provided to encrypt_record routine"));
1288 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1289 }
1290
1291 if (rec->data_offset < transform->ivlen) {
1292 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1293 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1294 }
1295
1296 /*
1297 * Generate IV
1298 */
1299 ret = f_rng(p_rng, transform->iv_enc, transform->ivlen);
1300 if (ret != 0) {
1301 return ret;
1302 }
1303
1304 memcpy(data - transform->ivlen, transform->iv_enc, transform->ivlen);
1305#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1306
1307 MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
1308 "including %"
1309 MBEDTLS_PRINTF_SIZET
1310 " bytes of IV and %" MBEDTLS_PRINTF_SIZET " bytes of padding",
1311 rec->data_len, transform->ivlen,
1312 padlen + 1));
1313
1314#if defined(MBEDTLS_USE_PSA_CRYPTO)
1315 status = psa_cipher_encrypt_setup(&cipher_op,
1316 transform->psa_key_enc, transform->psa_alg);
1317
1318 if (status != PSA_SUCCESS) {
1319 ret = PSA_TO_MBEDTLS_ERR(status);
1320 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_encrypt_setup", ret);
1321 return ret;
1322 }
1323
1324 status = psa_cipher_set_iv(&cipher_op, transform->iv_enc, transform->ivlen);
1325
1326 if (status != PSA_SUCCESS) {
1327 ret = PSA_TO_MBEDTLS_ERR(status);
1328 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_set_iv", ret);
1329 return ret;
1330
1331 }
1332
1333 status = psa_cipher_update(&cipher_op,
1334 data, rec->data_len,
1335 data, rec->data_len, &olen);
1336
1337 if (status != PSA_SUCCESS) {
1338 ret = PSA_TO_MBEDTLS_ERR(status);
1339 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_update", ret);
1340 return ret;
1341
1342 }
1343
1344 status = psa_cipher_finish(&cipher_op,
1345 data + olen, rec->data_len - olen,
1346 &part_len);
1347
1348 if (status != PSA_SUCCESS) {
1349 ret = PSA_TO_MBEDTLS_ERR(status);
1350 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_finish", ret);
1351 return ret;
1352
1353 }
1354
1355 olen += part_len;
1356#else
1357 if ((ret = mbedtls_cipher_crypt(&transform->cipher_ctx_enc,
1358 transform->iv_enc,
1359 transform->ivlen,
1360 data, rec->data_len,
1361 data, &olen)) != 0) {
1362 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_crypt", ret);
1363 return ret;
1364 }
1365#endif /* MBEDTLS_USE_PSA_CRYPTO */
1366
1367 if (rec->data_len != olen) {
1368 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1369 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1370 }
1371
1372 data -= transform->ivlen;
1373 rec->data_offset -= transform->ivlen;
1374 rec->data_len += transform->ivlen;
1375
1376#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1377 if (auth_done == 0) {
1378 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
1379#if defined(MBEDTLS_USE_PSA_CRYPTO)
1380 psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1381 size_t sign_mac_length = 0;
1382#endif /* MBEDTLS_USE_PSA_CRYPTO */
1383
1384 /* MAC(MAC_write_key, add_data, IV, ENC(content + padding + padding_length))
1385 */
1386
1387 if (post_avail < transform->maclen) {
1388 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1389 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1390 }
1391
1392 ssl_extract_add_data_from_record(add_data, &add_data_len,
1393 rec, transform->tls_version,
1394 transform->taglen);
1395
1396 MBEDTLS_SSL_DEBUG_MSG(3, ("using encrypt then mac"));
1397 MBEDTLS_SSL_DEBUG_BUF(4, "MAC'd meta-data", add_data,
1398 add_data_len);
1399#if defined(MBEDTLS_USE_PSA_CRYPTO)
1400 status = psa_mac_sign_setup(&operation, transform->psa_mac_enc,
1401 transform->psa_mac_alg);
1402 if (status != PSA_SUCCESS) {
1403 goto hmac_failed_etm_enabled;
1404 }
1405
1406 status = psa_mac_update(&operation, add_data, add_data_len);
1407 if (status != PSA_SUCCESS) {
1408 goto hmac_failed_etm_enabled;
1409 }
1410
1411 status = psa_mac_update(&operation, data, rec->data_len);
1412 if (status != PSA_SUCCESS) {
1413 goto hmac_failed_etm_enabled;
1414 }
1415
1416 status = psa_mac_sign_finish(&operation, mac, MBEDTLS_SSL_MAC_ADD,
1417 &sign_mac_length);
1418 if (status != PSA_SUCCESS) {
1419 goto hmac_failed_etm_enabled;
1420 }
1421#else
1422
1423 ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, add_data,
1424 add_data_len);
1425 if (ret != 0) {
1426 goto hmac_failed_etm_enabled;
1427 }
1428 ret = mbedtls_md_hmac_update(&transform->md_ctx_enc,
1429 data, rec->data_len);
1430 if (ret != 0) {
1431 goto hmac_failed_etm_enabled;
1432 }
1433 ret = mbedtls_md_hmac_finish(&transform->md_ctx_enc, mac);
1434 if (ret != 0) {
1435 goto hmac_failed_etm_enabled;
1436 }
1437 ret = mbedtls_md_hmac_reset(&transform->md_ctx_enc);
1438 if (ret != 0) {
1439 goto hmac_failed_etm_enabled;
1440 }
1441#endif /* MBEDTLS_USE_PSA_CRYPTO */
1442
1443 memcpy(data + rec->data_len, mac, transform->maclen);
1444
1445 rec->data_len += transform->maclen;
1446 post_avail -= transform->maclen;
1447 auth_done++;
1448
1449hmac_failed_etm_enabled:
1450 mbedtls_platform_zeroize(mac, transform->maclen);
1451#if defined(MBEDTLS_USE_PSA_CRYPTO)
1452 ret = PSA_TO_MBEDTLS_ERR(status);
1453 status = psa_mac_abort(&operation);
1454 if (ret == 0 && status != PSA_SUCCESS) {
1455 ret = PSA_TO_MBEDTLS_ERR(status);
1456 }
1457#endif /* MBEDTLS_USE_PSA_CRYPTO */
1458 if (ret != 0) {
1459 MBEDTLS_SSL_DEBUG_RET(1, "HMAC calculation failed", ret);
1460 return ret;
1461 }
1462 }
1463#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1464 } else
1465#endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */
1466 {
1467 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1468 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1469 }
1470
1471 /* Make extra sure authentication was performed, exactly once */
1472 if (auth_done != 1) {
1473 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1474 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1475 }
1476
1477 MBEDTLS_SSL_DEBUG_MSG(2, ("<= encrypt buf"));
1478
1479 return 0;
1480}
1481
1482int mbedtls_ssl_decrypt_buf(mbedtls_ssl_context const *ssl,
1483 mbedtls_ssl_transform *transform,
1484 mbedtls_record *rec)
1485{
1486#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) || defined(MBEDTLS_SSL_HAVE_AEAD)
1487 size_t olen;
1488#endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC || MBEDTLS_SSL_HAVE_AEAD */
1489 mbedtls_ssl_mode_t ssl_mode;
1490 int ret;
1491
1492 int auth_done = 0;
1493#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
1494 size_t padlen = 0;
1495 mbedtls_ct_condition_t correct = MBEDTLS_CT_TRUE;
1496#endif
1497 unsigned char *data;
1498 /* For an explanation of the additional data length see
1499 * the description of ssl_extract_add_data_from_record().
1500 */
1501#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1502 unsigned char add_data[23 + MBEDTLS_SSL_CID_IN_LEN_MAX];
1503#else
1504 unsigned char add_data[13];
1505#endif
1506 size_t add_data_len;
1507
1508#if !defined(MBEDTLS_DEBUG_C)
1509 ssl = NULL; /* make sure we don't use it except for debug */
1510 ((void) ssl);
1511#endif
1512
1513 MBEDTLS_SSL_DEBUG_MSG(2, ("=> decrypt buf"));
1514 if (rec == NULL ||
1515 rec->buf == NULL ||
1516 rec->buf_len < rec->data_offset ||
1517 rec->buf_len - rec->data_offset < rec->data_len) {
1518 MBEDTLS_SSL_DEBUG_MSG(1, ("bad record structure provided to decrypt_buf"));
1519 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1520 }
1521
1522 data = rec->buf + rec->data_offset;
1523 ssl_mode = mbedtls_ssl_get_mode_from_transform(transform);
1524
1525#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1526 /*
1527 * Match record's CID with incoming CID.
1528 */
1529 if (rec->cid_len != transform->in_cid_len ||
1530 memcmp(rec->cid, transform->in_cid, rec->cid_len) != 0) {
1531 return MBEDTLS_ERR_SSL_UNEXPECTED_CID;
1532 }
1533#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1534
1535#if defined(MBEDTLS_SSL_SOME_SUITES_USE_STREAM)
1536 if (ssl_mode == MBEDTLS_SSL_MODE_STREAM) {
1537 if (rec->data_len < transform->maclen) {
1538 MBEDTLS_SSL_DEBUG_MSG(1,
1539 ("Record too short for MAC:"
1540 " %" MBEDTLS_PRINTF_SIZET " < %" MBEDTLS_PRINTF_SIZET,
1541 rec->data_len, transform->maclen));
1542 return MBEDTLS_ERR_SSL_INVALID_MAC;
1543 }
1544
1545 /* The only supported stream cipher is "NULL",
1546 * so there's no encryption to do here.*/
1547 } else
1548#endif /* MBEDTLS_SSL_SOME_SUITES_USE_STREAM */
1549#if defined(MBEDTLS_SSL_HAVE_AEAD)
1550 if (ssl_mode == MBEDTLS_SSL_MODE_AEAD) {
1551 unsigned char iv[12];
1552 unsigned char *dynamic_iv;
1553 size_t dynamic_iv_len;
1554#if defined(MBEDTLS_USE_PSA_CRYPTO)
1555 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1556#endif /* MBEDTLS_USE_PSA_CRYPTO */
1557
1558 /*
1559 * Extract dynamic part of nonce for AEAD decryption.
1560 *
1561 * Note: In the case of CCM and GCM in TLS 1.2, the dynamic
1562 * part of the IV is prepended to the ciphertext and
1563 * can be chosen freely - in particular, it need not
1564 * agree with the record sequence number.
1565 */
1566 dynamic_iv_len = sizeof(rec->ctr);
1567 if (ssl_transform_aead_dynamic_iv_is_explicit(transform) == 1) {
1568 if (rec->data_len < dynamic_iv_len) {
1569 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1570 " ) < explicit_iv_len (%" MBEDTLS_PRINTF_SIZET ") ",
1571 rec->data_len,
1572 dynamic_iv_len));
1573 return MBEDTLS_ERR_SSL_INVALID_MAC;
1574 }
1575 dynamic_iv = data;
1576
1577 data += dynamic_iv_len;
1578 rec->data_offset += dynamic_iv_len;
1579 rec->data_len -= dynamic_iv_len;
1580 } else {
1581 dynamic_iv = rec->ctr;
1582 }
1583
1584 /* Check that there's space for the authentication tag. */
1585 if (rec->data_len < transform->taglen) {
1586 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1587 ") < taglen (%" MBEDTLS_PRINTF_SIZET ") ",
1588 rec->data_len,
1589 transform->taglen));
1590 return MBEDTLS_ERR_SSL_INVALID_MAC;
1591 }
1592 rec->data_len -= transform->taglen;
1593
1594 /*
1595 * Prepare nonce from dynamic and static parts.
1596 */
1597 ssl_build_record_nonce(iv, sizeof(iv),
1598 transform->iv_dec,
1599 transform->fixed_ivlen,
1600 dynamic_iv,
1601 dynamic_iv_len);
1602
1603 /*
1604 * Build additional data for AEAD encryption.
1605 * This depends on the TLS version.
1606 */
1607 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
1608 transform->tls_version,
1609 transform->taglen);
1610 MBEDTLS_SSL_DEBUG_BUF(4, "additional data used for AEAD",
1611 add_data, add_data_len);
1612
1613 /* Because of the check above, we know that there are
1614 * explicit_iv_len Bytes preceding data, and taglen
1615 * bytes following data + data_len. This justifies
1616 * the debug message and the invocation of
1617 * mbedtls_cipher_auth_decrypt_ext() below. */
1618
1619 MBEDTLS_SSL_DEBUG_BUF(4, "IV used", iv, transform->ivlen);
1620 MBEDTLS_SSL_DEBUG_BUF(4, "TAG used", data + rec->data_len,
1621 transform->taglen);
1622
1623 /*
1624 * Decrypt and authenticate
1625 */
1626#if defined(MBEDTLS_USE_PSA_CRYPTO)
1627 status = psa_aead_decrypt(transform->psa_key_dec,
1628 transform->psa_alg,
1629 iv, transform->ivlen,
1630 add_data, add_data_len,
1631 data, rec->data_len + transform->taglen,
1632 data, rec->buf_len - (data - rec->buf),
1633 &olen);
1634
1635 if (status != PSA_SUCCESS) {
1636 ret = PSA_TO_MBEDTLS_ERR(status);
1637 MBEDTLS_SSL_DEBUG_RET(1, "psa_aead_decrypt", ret);
1638 return ret;
1639 }
1640#else
1641 if ((ret = mbedtls_cipher_auth_decrypt_ext
1642 (&transform->cipher_ctx_dec,
1643 iv, transform->ivlen,
1644 add_data, add_data_len,
1645 data, rec->data_len + transform->taglen, /* src */
1646 data, rec->buf_len - (size_t) (data - rec->buf), &olen, /* dst */
1647 transform->taglen)) != 0) {
1648 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_auth_decrypt_ext", ret);
1649
1650 if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
1651 return MBEDTLS_ERR_SSL_INVALID_MAC;
1652 }
1653
1654 return ret;
1655 }
1656#endif /* MBEDTLS_USE_PSA_CRYPTO */
1657
1658 auth_done++;
1659
1660 /* Double-check that AEAD decryption doesn't change content length. */
1661 if (olen != rec->data_len) {
1662 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1663 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1664 }
1665 } else
1666#endif /* MBEDTLS_SSL_HAVE_AEAD */
1667#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
1668 if (ssl_mode == MBEDTLS_SSL_MODE_CBC ||
1669 ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
1670 size_t minlen = 0;
1671#if defined(MBEDTLS_USE_PSA_CRYPTO)
1672 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1673 size_t part_len;
1674 psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
1675#endif /* MBEDTLS_USE_PSA_CRYPTO */
1676
1677 /*
1678 * Check immediate ciphertext sanity
1679 */
1680#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1681 /* The ciphertext is prefixed with the CBC IV. */
1682 minlen += transform->ivlen;
1683#endif
1684
1685 /* Size considerations:
1686 *
1687 * - The CBC cipher text must not be empty and hence
1688 * at least of size transform->ivlen.
1689 *
1690 * Together with the potential IV-prefix, this explains
1691 * the first of the two checks below.
1692 *
1693 * - The record must contain a MAC, either in plain or
1694 * encrypted, depending on whether Encrypt-then-MAC
1695 * is used or not.
1696 * - If it is, the message contains the IV-prefix,
1697 * the CBC ciphertext, and the MAC.
1698 * - If it is not, the padded plaintext, and hence
1699 * the CBC ciphertext, has at least length maclen + 1
1700 * because there is at least the padding length byte.
1701 *
1702 * As the CBC ciphertext is not empty, both cases give the
1703 * lower bound minlen + maclen + 1 on the record size, which
1704 * we test for in the second check below.
1705 */
1706 if (rec->data_len < minlen + transform->ivlen ||
1707 rec->data_len < minlen + transform->maclen + 1) {
1708 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1709 ") < max( ivlen(%" MBEDTLS_PRINTF_SIZET
1710 "), maclen (%" MBEDTLS_PRINTF_SIZET ") "
1711 "+ 1 ) ( + expl IV )",
1712 rec->data_len,
1713 transform->ivlen,
1714 transform->maclen));
1715 return MBEDTLS_ERR_SSL_INVALID_MAC;
1716 }
1717
1718 /*
1719 * Authenticate before decrypt if enabled
1720 */
1721#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1722 if (ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
1723#if defined(MBEDTLS_USE_PSA_CRYPTO)
1724 psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1725#else
1726 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
1727#endif /* MBEDTLS_USE_PSA_CRYPTO */
1728
1729 MBEDTLS_SSL_DEBUG_MSG(3, ("using encrypt then mac"));
1730
1731 /* Update data_len in tandem with add_data.
1732 *
1733 * The subtraction is safe because of the previous check
1734 * data_len >= minlen + maclen + 1.
1735 *
1736 * Afterwards, we know that data + data_len is followed by at
1737 * least maclen Bytes, which justifies the call to
1738 * mbedtls_ct_memcmp() below.
1739 *
1740 * Further, we still know that data_len > minlen */
1741 rec->data_len -= transform->maclen;
1742 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
1743 transform->tls_version,
1744 transform->taglen);
1745
1746 /* Calculate expected MAC. */
1747 MBEDTLS_SSL_DEBUG_BUF(4, "MAC'd meta-data", add_data,
1748 add_data_len);
1749#if defined(MBEDTLS_USE_PSA_CRYPTO)
1750 status = psa_mac_verify_setup(&operation, transform->psa_mac_dec,
1751 transform->psa_mac_alg);
1752 if (status != PSA_SUCCESS) {
1753 goto hmac_failed_etm_enabled;
1754 }
1755
1756 status = psa_mac_update(&operation, add_data, add_data_len);
1757 if (status != PSA_SUCCESS) {
1758 goto hmac_failed_etm_enabled;
1759 }
1760
1761 status = psa_mac_update(&operation, data, rec->data_len);
1762 if (status != PSA_SUCCESS) {
1763 goto hmac_failed_etm_enabled;
1764 }
1765
1766 /* Compare expected MAC with MAC at the end of the record. */
1767 status = psa_mac_verify_finish(&operation, data + rec->data_len,
1768 transform->maclen);
1769 if (status != PSA_SUCCESS) {
1770 goto hmac_failed_etm_enabled;
1771 }
1772#else
1773 ret = mbedtls_md_hmac_update(&transform->md_ctx_dec, add_data,
1774 add_data_len);
1775 if (ret != 0) {
1776 goto hmac_failed_etm_enabled;
1777 }
1778 ret = mbedtls_md_hmac_update(&transform->md_ctx_dec,
1779 data, rec->data_len);
1780 if (ret != 0) {
1781 goto hmac_failed_etm_enabled;
1782 }
1783 ret = mbedtls_md_hmac_finish(&transform->md_ctx_dec, mac_expect);
1784 if (ret != 0) {
1785 goto hmac_failed_etm_enabled;
1786 }
1787 ret = mbedtls_md_hmac_reset(&transform->md_ctx_dec);
1788 if (ret != 0) {
1789 goto hmac_failed_etm_enabled;
1790 }
1791
1792 MBEDTLS_SSL_DEBUG_BUF(4, "message mac", data + rec->data_len,
1793 transform->maclen);
1794 MBEDTLS_SSL_DEBUG_BUF(4, "expected mac", mac_expect,
1795 transform->maclen);
1796
1797 /* Compare expected MAC with MAC at the end of the record. */
1798 if (mbedtls_ct_memcmp(data + rec->data_len, mac_expect,
1799 transform->maclen) != 0) {
1800 MBEDTLS_SSL_DEBUG_MSG(1, ("message mac does not match"));
1801 ret = MBEDTLS_ERR_SSL_INVALID_MAC;
1802 goto hmac_failed_etm_enabled;
1803 }
1804#endif /* MBEDTLS_USE_PSA_CRYPTO */
1805 auth_done++;
1806
1807hmac_failed_etm_enabled:
1808#if defined(MBEDTLS_USE_PSA_CRYPTO)
1809 ret = PSA_TO_MBEDTLS_ERR(status);
1810 status = psa_mac_abort(&operation);
1811 if (ret == 0 && status != PSA_SUCCESS) {
1812 ret = PSA_TO_MBEDTLS_ERR(status);
1813 }
1814#else
1815 mbedtls_platform_zeroize(mac_expect, transform->maclen);
1816#endif /* MBEDTLS_USE_PSA_CRYPTO */
1817 if (ret != 0) {
1818 if (ret != MBEDTLS_ERR_SSL_INVALID_MAC) {
1819 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_hmac_xxx", ret);
1820 }
1821 return ret;
1822 }
1823 }
1824#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1825
1826 /*
1827 * Check length sanity
1828 */
1829
1830 /* We know from above that data_len > minlen >= 0,
1831 * so the following check in particular implies that
1832 * data_len >= minlen + ivlen ( = minlen or 2 * minlen ). */
1833 if (rec->data_len % transform->ivlen != 0) {
1834 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1835 ") %% ivlen (%" MBEDTLS_PRINTF_SIZET ") != 0",
1836 rec->data_len, transform->ivlen));
1837 return MBEDTLS_ERR_SSL_INVALID_MAC;
1838 }
1839
1840#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1841 /*
1842 * Initialize for prepended IV for block cipher in TLS v1.2
1843 */
1844 /* Safe because data_len >= minlen + ivlen = 2 * ivlen. */
1845 memcpy(transform->iv_dec, data, transform->ivlen);
1846
1847 data += transform->ivlen;
1848 rec->data_offset += transform->ivlen;
1849 rec->data_len -= transform->ivlen;
1850#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1851
1852 /* We still have data_len % ivlen == 0 and data_len >= ivlen here. */
1853
1854#if defined(MBEDTLS_USE_PSA_CRYPTO)
1855 status = psa_cipher_decrypt_setup(&cipher_op,
1856 transform->psa_key_dec, transform->psa_alg);
1857
1858 if (status != PSA_SUCCESS) {
1859 ret = PSA_TO_MBEDTLS_ERR(status);
1860 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_decrypt_setup", ret);
1861 return ret;
1862 }
1863
1864 status = psa_cipher_set_iv(&cipher_op, transform->iv_dec, transform->ivlen);
1865
1866 if (status != PSA_SUCCESS) {
1867 ret = PSA_TO_MBEDTLS_ERR(status);
1868 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_set_iv", ret);
1869 return ret;
1870 }
1871
1872 status = psa_cipher_update(&cipher_op,
1873 data, rec->data_len,
1874 data, rec->data_len, &olen);
1875
1876 if (status != PSA_SUCCESS) {
1877 ret = PSA_TO_MBEDTLS_ERR(status);
1878 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_update", ret);
1879 return ret;
1880 }
1881
1882 status = psa_cipher_finish(&cipher_op,
1883 data + olen, rec->data_len - olen,
1884 &part_len);
1885
1886 if (status != PSA_SUCCESS) {
1887 ret = PSA_TO_MBEDTLS_ERR(status);
1888 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_finish", ret);
1889 return ret;
1890 }
1891
1892 olen += part_len;
1893#else
1894
1895 if ((ret = mbedtls_cipher_crypt(&transform->cipher_ctx_dec,
1896 transform->iv_dec, transform->ivlen,
1897 data, rec->data_len, data, &olen)) != 0) {
1898 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_crypt", ret);
1899 return ret;
1900 }
1901#endif /* MBEDTLS_USE_PSA_CRYPTO */
1902
1903 /* Double-check that length hasn't changed during decryption. */
1904 if (rec->data_len != olen) {
1905 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1906 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1907 }
1908
1909 /* Safe since data_len >= minlen + maclen + 1, so after having
1910 * subtracted at most minlen and maclen up to this point,
1911 * data_len > 0 (because of data_len % ivlen == 0, it's actually
1912 * >= ivlen ). */
1913 padlen = data[rec->data_len - 1];
1914
1915 if (auth_done == 1) {
1916 const mbedtls_ct_condition_t ge = mbedtls_ct_uint_ge(
1917 rec->data_len,
1918 padlen + 1);
1919 correct = mbedtls_ct_bool_and(ge, correct);
1920 padlen = mbedtls_ct_size_if_else_0(ge, padlen);
1921 } else {
1922#if defined(MBEDTLS_SSL_DEBUG_ALL)
1923 if (rec->data_len < transform->maclen + padlen + 1) {
1924 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1925 ") < maclen (%" MBEDTLS_PRINTF_SIZET
1926 ") + padlen (%" MBEDTLS_PRINTF_SIZET ")",
1927 rec->data_len,
1928 transform->maclen,
1929 padlen + 1));
1930 }
1931#endif
1932 const mbedtls_ct_condition_t ge = mbedtls_ct_uint_ge(
1933 rec->data_len,
1934 transform->maclen + padlen + 1);
1935 correct = mbedtls_ct_bool_and(ge, correct);
1936 padlen = mbedtls_ct_size_if_else_0(ge, padlen);
1937 }
1938
1939 padlen++;
1940
1941 /* Regardless of the validity of the padding,
1942 * we have data_len >= padlen here. */
1943
1944#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1945 /* The padding check involves a series of up to 256
1946 * consecutive memory reads at the end of the record
1947 * plaintext buffer. In order to hide the length and
1948 * validity of the padding, always perform exactly
1949 * `min(256,plaintext_len)` reads (but take into account
1950 * only the last `padlen` bytes for the padding check). */
1951 size_t pad_count = 0;
1952 volatile unsigned char * const check = data;
1953
1954 /* Index of first padding byte; it has been ensured above
1955 * that the subtraction is safe. */
1956 size_t const padding_idx = rec->data_len - padlen;
1957 size_t const num_checks = rec->data_len <= 256 ? rec->data_len : 256;
1958 size_t const start_idx = rec->data_len - num_checks;
1959 size_t idx;
1960
1961 for (idx = start_idx; idx < rec->data_len; idx++) {
1962 /* pad_count += (idx >= padding_idx) &&
1963 * (check[idx] == padlen - 1);
1964 */
1965 const mbedtls_ct_condition_t a = mbedtls_ct_uint_ge(idx, padding_idx);
1966 size_t increment = mbedtls_ct_size_if_else_0(a, 1);
1967 const mbedtls_ct_condition_t b = mbedtls_ct_uint_eq(check[idx], padlen - 1);
1968 increment = mbedtls_ct_size_if_else_0(b, increment);
1969 pad_count += increment;
1970 }
1971 correct = mbedtls_ct_bool_and(mbedtls_ct_uint_eq(pad_count, padlen), correct);
1972
1973#if defined(MBEDTLS_SSL_DEBUG_ALL)
1974 if (padlen > 0 && correct == MBEDTLS_CT_FALSE) {
1975 MBEDTLS_SSL_DEBUG_MSG(1, ("bad padding byte detected"));
1976 }
1977#endif
1978 padlen = mbedtls_ct_size_if_else_0(correct, padlen);
1979
1980#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1981
1982 /* If the padding was found to be invalid, padlen == 0
1983 * and the subtraction is safe. If the padding was found valid,
1984 * padlen hasn't been changed and the previous assertion
1985 * data_len >= padlen still holds. */
1986 rec->data_len -= padlen;
1987 } else
1988#endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */
1989 {
1990 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1991 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1992 }
1993
1994#if defined(MBEDTLS_SSL_DEBUG_ALL)
1995 MBEDTLS_SSL_DEBUG_BUF(4, "raw buffer after decryption",
1996 data, rec->data_len);
1997#endif
1998
1999 /*
2000 * Authenticate if not done yet.
2001 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
2002 */
2003#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
2004 if (auth_done == 0) {
2005 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD] = { 0 };
2006 unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD] = { 0 };
2007
2008 /* For CBC+MAC, If the initial value of padlen was such that
2009 * data_len < maclen + padlen + 1, then padlen
2010 * got reset to 1, and the initial check
2011 * data_len >= minlen + maclen + 1
2012 * guarantees that at this point we still
2013 * have at least data_len >= maclen.
2014 *
2015 * If the initial value of padlen was such that
2016 * data_len >= maclen + padlen + 1, then we have
2017 * subtracted either padlen + 1 (if the padding was correct)
2018 * or 0 (if the padding was incorrect) since then,
2019 * hence data_len >= maclen in any case.
2020 *
2021 * For stream ciphers, we checked above that
2022 * data_len >= maclen.
2023 */
2024 rec->data_len -= transform->maclen;
2025 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
2026 transform->tls_version,
2027 transform->taglen);
2028
2029#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2030 /*
2031 * The next two sizes are the minimum and maximum values of
2032 * data_len over all padlen values.
2033 *
2034 * They're independent of padlen, since we previously did
2035 * data_len -= padlen.
2036 *
2037 * Note that max_len + maclen is never more than the buffer
2038 * length, as we previously did in_msglen -= maclen too.
2039 */
2040 const size_t max_len = rec->data_len + padlen;
2041 const size_t min_len = (max_len > 256) ? max_len - 256 : 0;
2042
2043#if defined(MBEDTLS_USE_PSA_CRYPTO)
2044 ret = mbedtls_ct_hmac(transform->psa_mac_dec,
2045 transform->psa_mac_alg,
2046 add_data, add_data_len,
2047 data, rec->data_len, min_len, max_len,
2048 mac_expect);
2049#else
2050 ret = mbedtls_ct_hmac(&transform->md_ctx_dec,
2051 add_data, add_data_len,
2052 data, rec->data_len, min_len, max_len,
2053 mac_expect);
2054#endif /* MBEDTLS_USE_PSA_CRYPTO */
2055 if (ret != 0) {
2056 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ct_hmac", ret);
2057 goto hmac_failed_etm_disabled;
2058 }
2059
2060 mbedtls_ct_memcpy_offset(mac_peer, data,
2061 rec->data_len,
2062 min_len, max_len,
2063 transform->maclen);
2064#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2065
2066#if defined(MBEDTLS_SSL_DEBUG_ALL)
2067 MBEDTLS_SSL_DEBUG_BUF(4, "expected mac", mac_expect, transform->maclen);
2068 MBEDTLS_SSL_DEBUG_BUF(4, "message mac", mac_peer, transform->maclen);
2069#endif
2070
2071 if (mbedtls_ct_memcmp(mac_peer, mac_expect,
2072 transform->maclen) != 0) {
2073#if defined(MBEDTLS_SSL_DEBUG_ALL)
2074 MBEDTLS_SSL_DEBUG_MSG(1, ("message mac does not match"));
2075#endif
2076 correct = MBEDTLS_CT_FALSE;
2077 }
2078 auth_done++;
2079
2080hmac_failed_etm_disabled:
2081 mbedtls_platform_zeroize(mac_peer, transform->maclen);
2082 mbedtls_platform_zeroize(mac_expect, transform->maclen);
2083 if (ret != 0) {
2084 return ret;
2085 }
2086 }
2087
2088 /*
2089 * Finally check the correct flag
2090 */
2091 if (correct == MBEDTLS_CT_FALSE) {
2092 return MBEDTLS_ERR_SSL_INVALID_MAC;
2093 }
2094#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
2095
2096 /* Make extra sure authentication was performed, exactly once */
2097 if (auth_done != 1) {
2098 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2099 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2100 }
2101
2102#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2103 if (transform->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2104 /* Remove inner padding and infer true content type. */
2105 ret = ssl_parse_inner_plaintext(data, &rec->data_len,
2106 &rec->type);
2107
2108 if (ret != 0) {
2109 return MBEDTLS_ERR_SSL_INVALID_RECORD;
2110 }
2111 }
2112#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2113
2114#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2115 if (rec->cid_len != 0) {
2116 ret = ssl_parse_inner_plaintext(data, &rec->data_len,
2117 &rec->type);
2118 if (ret != 0) {
2119 return MBEDTLS_ERR_SSL_INVALID_RECORD;
2120 }
2121 }
2122#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2123
2124 MBEDTLS_SSL_DEBUG_MSG(2, ("<= decrypt buf"));
2125
2126 return 0;
2127}
2128
2129#undef MAC_NONE
2130#undef MAC_PLAINTEXT
2131#undef MAC_CIPHERTEXT
2132
2133/*
2134 * Fill the input message buffer by appending data to it.
2135 * The amount of data already fetched is in ssl->in_left.
2136 *
2137 * If we return 0, is it guaranteed that (at least) nb_want bytes are
2138 * available (from this read and/or a previous one). Otherwise, an error code
2139 * is returned (possibly EOF or WANT_READ).
2140 *
2141 * With stream transport (TLS) on success ssl->in_left == nb_want, but
2142 * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
2143 * since we always read a whole datagram at once.
2144 *
2145 * For DTLS, it is up to the caller to set ssl->next_record_offset when
2146 * they're done reading a record.
2147 */
2148int mbedtls_ssl_fetch_input(mbedtls_ssl_context *ssl, size_t nb_want)
2149{
2150 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2151 size_t len;
2152#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2153 size_t in_buf_len = ssl->in_buf_len;
2154#else
2155 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
2156#endif
2157
2158 MBEDTLS_SSL_DEBUG_MSG(2, ("=> fetch input"));
2159
2160 if (ssl->f_recv == NULL && ssl->f_recv_timeout == NULL) {
2161 MBEDTLS_SSL_DEBUG_MSG(1, ("Bad usage of mbedtls_ssl_set_bio() "));
2162 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2163 }
2164
2165 if (nb_want > in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf)) {
2166 MBEDTLS_SSL_DEBUG_MSG(1, ("requesting more data than fits"));
2167 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2168 }
2169
2170#if defined(MBEDTLS_SSL_PROTO_DTLS)
2171 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2172 uint32_t timeout;
2173
2174 /*
2175 * The point is, we need to always read a full datagram at once, so we
2176 * sometimes read more then requested, and handle the additional data.
2177 * It could be the rest of the current record (while fetching the
2178 * header) and/or some other records in the same datagram.
2179 */
2180
2181 /*
2182 * Move to the next record in the already read datagram if applicable
2183 */
2184 if (ssl->next_record_offset != 0) {
2185 if (ssl->in_left < ssl->next_record_offset) {
2186 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2187 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2188 }
2189
2190 ssl->in_left -= ssl->next_record_offset;
2191
2192 if (ssl->in_left != 0) {
2193 MBEDTLS_SSL_DEBUG_MSG(2, ("next record in same datagram, offset: %"
2194 MBEDTLS_PRINTF_SIZET,
2195 ssl->next_record_offset));
2196 memmove(ssl->in_hdr,
2197 ssl->in_hdr + ssl->next_record_offset,
2198 ssl->in_left);
2199 }
2200
2201 ssl->next_record_offset = 0;
2202 }
2203
2204 MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
2205 ", nb_want: %" MBEDTLS_PRINTF_SIZET,
2206 ssl->in_left, nb_want));
2207
2208 /*
2209 * Done if we already have enough data.
2210 */
2211 if (nb_want <= ssl->in_left) {
2212 MBEDTLS_SSL_DEBUG_MSG(2, ("<= fetch input"));
2213 return 0;
2214 }
2215
2216 /*
2217 * A record can't be split across datagrams. If we need to read but
2218 * are not at the beginning of a new record, the caller did something
2219 * wrong.
2220 */
2221 if (ssl->in_left != 0) {
2222 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2223 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2224 }
2225
2226 /*
2227 * Don't even try to read if time's out already.
2228 * This avoids by-passing the timer when repeatedly receiving messages
2229 * that will end up being dropped.
2230 */
2231 if (mbedtls_ssl_check_timer(ssl) != 0) {
2232 MBEDTLS_SSL_DEBUG_MSG(2, ("timer has expired"));
2233 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2234 } else {
2235 len = in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf);
2236
2237 if (mbedtls_ssl_is_handshake_over(ssl) == 0) {
2238 timeout = ssl->handshake->retransmit_timeout;
2239 } else {
2240 timeout = ssl->conf->read_timeout;
2241 }
2242
2243 MBEDTLS_SSL_DEBUG_MSG(3, ("f_recv_timeout: %lu ms", (unsigned long) timeout));
2244
2245 if (ssl->f_recv_timeout != NULL) {
2246 ret = ssl->f_recv_timeout(ssl->p_bio, ssl->in_hdr, len,
2247 timeout);
2248 } else {
2249 ret = ssl->f_recv(ssl->p_bio, ssl->in_hdr, len);
2250 }
2251
2252 MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_recv(_timeout)", ret);
2253
2254 if (ret == 0) {
2255 return MBEDTLS_ERR_SSL_CONN_EOF;
2256 }
2257 }
2258
2259 if (ret == MBEDTLS_ERR_SSL_TIMEOUT) {
2260 MBEDTLS_SSL_DEBUG_MSG(2, ("timeout"));
2261 mbedtls_ssl_set_timer(ssl, 0);
2262
2263 if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
2264 if (ssl_double_retransmit_timeout(ssl) != 0) {
2265 MBEDTLS_SSL_DEBUG_MSG(1, ("handshake timeout"));
2266 return MBEDTLS_ERR_SSL_TIMEOUT;
2267 }
2268
2269 if ((ret = mbedtls_ssl_resend(ssl)) != 0) {
2270 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend", ret);
2271 return ret;
2272 }
2273
2274 return MBEDTLS_ERR_SSL_WANT_READ;
2275 }
2276#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2277 else if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
2278 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
2279 if ((ret = mbedtls_ssl_resend_hello_request(ssl)) != 0) {
2280 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend_hello_request",
2281 ret);
2282 return ret;
2283 }
2284
2285 return MBEDTLS_ERR_SSL_WANT_READ;
2286 }
2287#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2288 }
2289
2290 if (ret < 0) {
2291 return ret;
2292 }
2293
2294 ssl->in_left = ret;
2295 } else
2296#endif
2297 {
2298 MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
2299 ", nb_want: %" MBEDTLS_PRINTF_SIZET,
2300 ssl->in_left, nb_want));
2301
2302 while (ssl->in_left < nb_want) {
2303 len = nb_want - ssl->in_left;
2304
2305 if (mbedtls_ssl_check_timer(ssl) != 0) {
2306 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2307 } else {
2308 if (ssl->f_recv_timeout != NULL) {
2309 ret = ssl->f_recv_timeout(ssl->p_bio,
2310 ssl->in_hdr + ssl->in_left, len,
2311 ssl->conf->read_timeout);
2312 } else {
2313 ret = ssl->f_recv(ssl->p_bio,
2314 ssl->in_hdr + ssl->in_left, len);
2315 }
2316 }
2317
2318 MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
2319 ", nb_want: %" MBEDTLS_PRINTF_SIZET,
2320 ssl->in_left, nb_want));
2321 MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_recv(_timeout)", ret);
2322
2323 if (ret == 0) {
2324 return MBEDTLS_ERR_SSL_CONN_EOF;
2325 }
2326
2327 if (ret < 0) {
2328 return ret;
2329 }
2330
2331 if ((size_t) ret > len) {
2332 MBEDTLS_SSL_DEBUG_MSG(1,
2333 ("f_recv returned %d bytes but only %" MBEDTLS_PRINTF_SIZET
2334 " were requested",
2335 ret, len));
2336 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2337 }
2338
2339 ssl->in_left += ret;
2340 }
2341 }
2342
2343 MBEDTLS_SSL_DEBUG_MSG(2, ("<= fetch input"));
2344
2345 return 0;
2346}
2347
2348/*
2349 * Flush any data not yet written
2350 */
2351int mbedtls_ssl_flush_output(mbedtls_ssl_context *ssl)
2352{
2353 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2354 unsigned char *buf;
2355
2356 MBEDTLS_SSL_DEBUG_MSG(2, ("=> flush output"));
2357
2358 if (ssl->f_send == NULL) {
2359 MBEDTLS_SSL_DEBUG_MSG(1, ("Bad usage of mbedtls_ssl_set_bio() "));
2360 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2361 }
2362
2363 /* Avoid incrementing counter if data is flushed */
2364 if (ssl->out_left == 0) {
2365 MBEDTLS_SSL_DEBUG_MSG(2, ("<= flush output"));
2366 return 0;
2367 }
2368
2369 while (ssl->out_left > 0) {
2370 MBEDTLS_SSL_DEBUG_MSG(2, ("message length: %" MBEDTLS_PRINTF_SIZET
2371 ", out_left: %" MBEDTLS_PRINTF_SIZET,
2372 mbedtls_ssl_out_hdr_len(ssl) + ssl->out_msglen, ssl->out_left));
2373
2374 buf = ssl->out_hdr - ssl->out_left;
2375 ret = ssl->f_send(ssl->p_bio, buf, ssl->out_left);
2376
2377 MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_send", ret);
2378
2379 if (ret <= 0) {
2380 return ret;
2381 }
2382
2383 if ((size_t) ret > ssl->out_left) {
2384 MBEDTLS_SSL_DEBUG_MSG(1,
2385 ("f_send returned %d bytes but only %" MBEDTLS_PRINTF_SIZET
2386 " bytes were sent",
2387 ret, ssl->out_left));
2388 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2389 }
2390
2391 ssl->out_left -= ret;
2392 }
2393
2394#if defined(MBEDTLS_SSL_PROTO_DTLS)
2395 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2396 ssl->out_hdr = ssl->out_buf;
2397 } else
2398#endif
2399 {
2400 ssl->out_hdr = ssl->out_buf + 8;
2401 }
2402 mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
2403
2404 MBEDTLS_SSL_DEBUG_MSG(2, ("<= flush output"));
2405
2406 return 0;
2407}
2408
2409/*
2410 * Functions to handle the DTLS retransmission state machine
2411 */
2412#if defined(MBEDTLS_SSL_PROTO_DTLS)
2413/*
2414 * Append current handshake message to current outgoing flight
2415 */
2416MBEDTLS_CHECK_RETURN_CRITICAL
2417static int ssl_flight_append(mbedtls_ssl_context *ssl)
2418{
2419 mbedtls_ssl_flight_item *msg;
2420 MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_flight_append"));
2421 MBEDTLS_SSL_DEBUG_BUF(4, "message appended to flight",
2422 ssl->out_msg, ssl->out_msglen);
2423
2424 /* Allocate space for current message */
2425 if ((msg = mbedtls_calloc(1, sizeof(mbedtls_ssl_flight_item))) == NULL) {
2426 MBEDTLS_SSL_DEBUG_MSG(1, ("alloc %" MBEDTLS_PRINTF_SIZET " bytes failed",
2427 sizeof(mbedtls_ssl_flight_item)));
2428 return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2429 }
2430
2431 if ((msg->p = mbedtls_calloc(1, ssl->out_msglen)) == NULL) {
2432 MBEDTLS_SSL_DEBUG_MSG(1, ("alloc %" MBEDTLS_PRINTF_SIZET " bytes failed",
2433 ssl->out_msglen));
2434 mbedtls_free(msg);
2435 return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2436 }
2437
2438 /* Copy current handshake message with headers */
2439 memcpy(msg->p, ssl->out_msg, ssl->out_msglen);
2440 msg->len = ssl->out_msglen;
2441 msg->type = ssl->out_msgtype;
2442 msg->next = NULL;
2443
2444 /* Append to the current flight */
2445 if (ssl->handshake->flight == NULL) {
2446 ssl->handshake->flight = msg;
2447 } else {
2448 mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
2449 while (cur->next != NULL) {
2450 cur = cur->next;
2451 }
2452 cur->next = msg;
2453 }
2454
2455 MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_flight_append"));
2456 return 0;
2457}
2458
2459/*
2460 * Free the current flight of handshake messages
2461 */
2462void mbedtls_ssl_flight_free(mbedtls_ssl_flight_item *flight)
2463{
2464 mbedtls_ssl_flight_item *cur = flight;
2465 mbedtls_ssl_flight_item *next;
2466
2467 while (cur != NULL) {
2468 next = cur->next;
2469
2470 mbedtls_free(cur->p);
2471 mbedtls_free(cur);
2472
2473 cur = next;
2474 }
2475}
2476
2477/*
2478 * Swap transform_out and out_ctr with the alternative ones
2479 */
2480MBEDTLS_CHECK_RETURN_CRITICAL
2481static int ssl_swap_epochs(mbedtls_ssl_context *ssl)
2482{
2483 mbedtls_ssl_transform *tmp_transform;
2484 unsigned char tmp_out_ctr[MBEDTLS_SSL_SEQUENCE_NUMBER_LEN];
2485
2486 if (ssl->transform_out == ssl->handshake->alt_transform_out) {
2487 MBEDTLS_SSL_DEBUG_MSG(3, ("skip swap epochs"));
2488 return 0;
2489 }
2490
2491 MBEDTLS_SSL_DEBUG_MSG(3, ("swap epochs"));
2492
2493 /* Swap transforms */
2494 tmp_transform = ssl->transform_out;
2495 ssl->transform_out = ssl->handshake->alt_transform_out;
2496 ssl->handshake->alt_transform_out = tmp_transform;
2497
2498 /* Swap epoch + sequence_number */
2499 memcpy(tmp_out_ctr, ssl->cur_out_ctr, sizeof(tmp_out_ctr));
2500 memcpy(ssl->cur_out_ctr, ssl->handshake->alt_out_ctr,
2501 sizeof(ssl->cur_out_ctr));
2502 memcpy(ssl->handshake->alt_out_ctr, tmp_out_ctr,
2503 sizeof(ssl->handshake->alt_out_ctr));
2504
2505 /* Adjust to the newly activated transform */
2506 mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
2507
2508 return 0;
2509}
2510
2511/*
2512 * Retransmit the current flight of messages.
2513 */
2514int mbedtls_ssl_resend(mbedtls_ssl_context *ssl)
2515{
2516 int ret = 0;
2517
2518 MBEDTLS_SSL_DEBUG_MSG(2, ("=> mbedtls_ssl_resend"));
2519
2520 ret = mbedtls_ssl_flight_transmit(ssl);
2521
2522 MBEDTLS_SSL_DEBUG_MSG(2, ("<= mbedtls_ssl_resend"));
2523
2524 return ret;
2525}
2526
2527/*
2528 * Transmit or retransmit the current flight of messages.
2529 *
2530 * Need to remember the current message in case flush_output returns
2531 * WANT_WRITE, causing us to exit this function and come back later.
2532 * This function must be called until state is no longer SENDING.
2533 */
2534int mbedtls_ssl_flight_transmit(mbedtls_ssl_context *ssl)
2535{
2536 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2537 MBEDTLS_SSL_DEBUG_MSG(2, ("=> mbedtls_ssl_flight_transmit"));
2538
2539 if (ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING) {
2540 MBEDTLS_SSL_DEBUG_MSG(2, ("initialise flight transmission"));
2541
2542 ssl->handshake->cur_msg = ssl->handshake->flight;
2543 ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
2544 ret = ssl_swap_epochs(ssl);
2545 if (ret != 0) {
2546 return ret;
2547 }
2548
2549 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
2550 }
2551
2552 while (ssl->handshake->cur_msg != NULL) {
2553 size_t max_frag_len;
2554 const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
2555
2556 int const is_finished =
2557 (cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
2558 cur->p[0] == MBEDTLS_SSL_HS_FINISHED);
2559
2560 int const force_flush = ssl->disable_datagram_packing == 1 ?
2561 SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
2562
2563 /* Swap epochs before sending Finished: we can't do it after
2564 * sending ChangeCipherSpec, in case write returns WANT_READ.
2565 * Must be done before copying, may change out_msg pointer */
2566 if (is_finished && ssl->handshake->cur_msg_p == (cur->p + 12)) {
2567 MBEDTLS_SSL_DEBUG_MSG(2, ("swap epochs to send finished message"));
2568 ret = ssl_swap_epochs(ssl);
2569 if (ret != 0) {
2570 return ret;
2571 }
2572 }
2573
2574 ret = ssl_get_remaining_payload_in_datagram(ssl);
2575 if (ret < 0) {
2576 return ret;
2577 }
2578 max_frag_len = (size_t) ret;
2579
2580 /* CCS is copied as is, while HS messages may need fragmentation */
2581 if (cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
2582 if (max_frag_len == 0) {
2583 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
2584 return ret;
2585 }
2586
2587 continue;
2588 }
2589
2590 memcpy(ssl->out_msg, cur->p, cur->len);
2591 ssl->out_msglen = cur->len;
2592 ssl->out_msgtype = cur->type;
2593
2594 /* Update position inside current message */
2595 ssl->handshake->cur_msg_p += cur->len;
2596 } else {
2597 const unsigned char * const p = ssl->handshake->cur_msg_p;
2598 const size_t hs_len = cur->len - 12;
2599 const size_t frag_off = (size_t) (p - (cur->p + 12));
2600 const size_t rem_len = hs_len - frag_off;
2601 size_t cur_hs_frag_len, max_hs_frag_len;
2602
2603 if ((max_frag_len < 12) || (max_frag_len == 12 && hs_len != 0)) {
2604 if (is_finished) {
2605 ret = ssl_swap_epochs(ssl);
2606 if (ret != 0) {
2607 return ret;
2608 }
2609 }
2610
2611 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
2612 return ret;
2613 }
2614
2615 continue;
2616 }
2617 max_hs_frag_len = max_frag_len - 12;
2618
2619 cur_hs_frag_len = rem_len > max_hs_frag_len ?
2620 max_hs_frag_len : rem_len;
2621
2622 if (frag_off == 0 && cur_hs_frag_len != hs_len) {
2623 MBEDTLS_SSL_DEBUG_MSG(2, ("fragmenting %s handshake message (%u > %u)",
2624 mbedtls_ssl_get_hs_msg_name(cur->p[0]),
2625 (unsigned) cur_hs_frag_len,
2626 (unsigned) max_hs_frag_len));
2627 }
2628
2629 /* Messages are stored with handshake headers as if not fragmented,
2630 * copy beginning of headers then fill fragmentation fields.
2631 * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
2632 memcpy(ssl->out_msg, cur->p, 6);
2633
2634 ssl->out_msg[6] = MBEDTLS_BYTE_2(frag_off);
2635 ssl->out_msg[7] = MBEDTLS_BYTE_1(frag_off);
2636 ssl->out_msg[8] = MBEDTLS_BYTE_0(frag_off);
2637
2638 ssl->out_msg[9] = MBEDTLS_BYTE_2(cur_hs_frag_len);
2639 ssl->out_msg[10] = MBEDTLS_BYTE_1(cur_hs_frag_len);
2640 ssl->out_msg[11] = MBEDTLS_BYTE_0(cur_hs_frag_len);
2641
2642 MBEDTLS_SSL_DEBUG_BUF(3, "handshake header", ssl->out_msg, 12);
2643
2644 /* Copy the handshake message content and set records fields */
2645 memcpy(ssl->out_msg + 12, p, cur_hs_frag_len);
2646 ssl->out_msglen = cur_hs_frag_len + 12;
2647 ssl->out_msgtype = cur->type;
2648
2649 /* Update position inside current message */
2650 ssl->handshake->cur_msg_p += cur_hs_frag_len;
2651 }
2652
2653 /* If done with the current message move to the next one if any */
2654 if (ssl->handshake->cur_msg_p >= cur->p + cur->len) {
2655 if (cur->next != NULL) {
2656 ssl->handshake->cur_msg = cur->next;
2657 ssl->handshake->cur_msg_p = cur->next->p + 12;
2658 } else {
2659 ssl->handshake->cur_msg = NULL;
2660 ssl->handshake->cur_msg_p = NULL;
2661 }
2662 }
2663
2664 /* Actually send the message out */
2665 if ((ret = mbedtls_ssl_write_record(ssl, force_flush)) != 0) {
2666 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
2667 return ret;
2668 }
2669 }
2670
2671 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
2672 return ret;
2673 }
2674
2675 /* Update state and set timer */
2676 if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
2677 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2678 } else {
2679 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2680 mbedtls_ssl_set_timer(ssl, ssl->handshake->retransmit_timeout);
2681 }
2682
2683 MBEDTLS_SSL_DEBUG_MSG(2, ("<= mbedtls_ssl_flight_transmit"));
2684
2685 return 0;
2686}
2687
2688/*
2689 * To be called when the last message of an incoming flight is received.
2690 */
2691void mbedtls_ssl_recv_flight_completed(mbedtls_ssl_context *ssl)
2692{
2693 /* We won't need to resend that one any more */
2694 mbedtls_ssl_flight_free(ssl->handshake->flight);
2695 ssl->handshake->flight = NULL;
2696 ssl->handshake->cur_msg = NULL;
2697
2698 /* The next incoming flight will start with this msg_seq */
2699 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
2700
2701 /* We don't want to remember CCS's across flight boundaries. */
2702 ssl->handshake->buffering.seen_ccs = 0;
2703
2704 /* Clear future message buffering structure. */
2705 mbedtls_ssl_buffering_free(ssl);
2706
2707 /* Cancel timer */
2708 mbedtls_ssl_set_timer(ssl, 0);
2709
2710 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2711 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED) {
2712 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2713 } else {
2714 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
2715 }
2716}
2717
2718/*
2719 * To be called when the last message of an outgoing flight is send.
2720 */
2721void mbedtls_ssl_send_flight_completed(mbedtls_ssl_context *ssl)
2722{
2723 ssl_reset_retransmit_timeout(ssl);
2724 mbedtls_ssl_set_timer(ssl, ssl->handshake->retransmit_timeout);
2725
2726 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2727 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED) {
2728 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2729 } else {
2730 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2731 }
2732}
2733#endif /* MBEDTLS_SSL_PROTO_DTLS */
2734
2735/*
2736 * Handshake layer functions
2737 */
2738int mbedtls_ssl_start_handshake_msg(mbedtls_ssl_context *ssl, unsigned char hs_type,
2739 unsigned char **buf, size_t *buf_len)
2740{
2741 /*
2742 * Reserve 4 bytes for handshake header. ( Section 4,RFC 8446 )
2743 * ...
2744 * HandshakeType msg_type;
2745 * uint24 length;
2746 * ...
2747 */
2748 *buf = ssl->out_msg + 4;
2749 *buf_len = MBEDTLS_SSL_OUT_CONTENT_LEN - 4;
2750
2751 ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2752 ssl->out_msg[0] = hs_type;
2753
2754 return 0;
2755}
2756
2757/*
2758 * Write (DTLS: or queue) current handshake (including CCS) message.
2759 *
2760 * - fill in handshake headers
2761 * - update handshake checksum
2762 * - DTLS: save message for resending
2763 * - then pass to the record layer
2764 *
2765 * DTLS: except for HelloRequest, messages are only queued, and will only be
2766 * actually sent when calling flight_transmit() or resend().
2767 *
2768 * Inputs:
2769 * - ssl->out_msglen: 4 + actual handshake message len
2770 * (4 is the size of handshake headers for TLS)
2771 * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
2772 * - ssl->out_msg + 4: the handshake message body
2773 *
2774 * Outputs, ie state before passing to flight_append() or write_record():
2775 * - ssl->out_msglen: the length of the record contents
2776 * (including handshake headers but excluding record headers)
2777 * - ssl->out_msg: the record contents (handshake headers + content)
2778 */
2779int mbedtls_ssl_write_handshake_msg_ext(mbedtls_ssl_context *ssl,
2780 int update_checksum,
2781 int force_flush)
2782{
2783 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2784 const size_t hs_len = ssl->out_msglen - 4;
2785 const unsigned char hs_type = ssl->out_msg[0];
2786
2787 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write handshake message"));
2788
2789 /*
2790 * Sanity checks
2791 */
2792 if (ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
2793 ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
2794 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2795 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2796 }
2797
2798 /* Whenever we send anything different from a
2799 * HelloRequest we should be in a handshake - double check. */
2800 if (!(ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2801 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST) &&
2802 ssl->handshake == NULL) {
2803 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2804 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2805 }
2806
2807#if defined(MBEDTLS_SSL_PROTO_DTLS)
2808 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2809 ssl->handshake != NULL &&
2810 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING) {
2811 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2812 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2813 }
2814#endif
2815
2816 /* Double-check that we did not exceed the bounds
2817 * of the outgoing record buffer.
2818 * This should never fail as the various message
2819 * writing functions must obey the bounds of the
2820 * outgoing record buffer, but better be safe.
2821 *
2822 * Note: We deliberately do not check for the MTU or MFL here.
2823 */
2824 if (ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN) {
2825 MBEDTLS_SSL_DEBUG_MSG(1, ("Record too large: "
2826 "size %" MBEDTLS_PRINTF_SIZET
2827 ", maximum %" MBEDTLS_PRINTF_SIZET,
2828 ssl->out_msglen,
2829 (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN));
2830 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2831 }
2832
2833 /*
2834 * Fill handshake headers
2835 */
2836 if (ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
2837 ssl->out_msg[1] = MBEDTLS_BYTE_2(hs_len);
2838 ssl->out_msg[2] = MBEDTLS_BYTE_1(hs_len);
2839 ssl->out_msg[3] = MBEDTLS_BYTE_0(hs_len);
2840
2841 /*
2842 * DTLS has additional fields in the Handshake layer,
2843 * between the length field and the actual payload:
2844 * uint16 message_seq;
2845 * uint24 fragment_offset;
2846 * uint24 fragment_length;
2847 */
2848#if defined(MBEDTLS_SSL_PROTO_DTLS)
2849 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2850 /* Make room for the additional DTLS fields */
2851 if (MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8) {
2852 MBEDTLS_SSL_DEBUG_MSG(1, ("DTLS handshake message too large: "
2853 "size %" MBEDTLS_PRINTF_SIZET ", maximum %"
2854 MBEDTLS_PRINTF_SIZET,
2855 hs_len,
2856 (size_t) (MBEDTLS_SSL_OUT_CONTENT_LEN - 12)));
2857 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2858 }
2859
2860 memmove(ssl->out_msg + 12, ssl->out_msg + 4, hs_len);
2861 ssl->out_msglen += 8;
2862
2863 /* Write message_seq and update it, except for HelloRequest */
2864 if (hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST) {
2865 MBEDTLS_PUT_UINT16_BE(ssl->handshake->out_msg_seq, ssl->out_msg, 4);
2866 ++(ssl->handshake->out_msg_seq);
2867 } else {
2868 ssl->out_msg[4] = 0;
2869 ssl->out_msg[5] = 0;
2870 }
2871
2872 /* Handshake hashes are computed without fragmentation,
2873 * so set frag_offset = 0 and frag_len = hs_len for now */
2874 memset(ssl->out_msg + 6, 0x00, 3);
2875 memcpy(ssl->out_msg + 9, ssl->out_msg + 1, 3);
2876 }
2877#endif /* MBEDTLS_SSL_PROTO_DTLS */
2878
2879 /* Update running hashes of handshake messages seen */
2880 if (hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST && update_checksum != 0) {
2881 ret = ssl->handshake->update_checksum(ssl, ssl->out_msg,
2882 ssl->out_msglen);
2883 if (ret != 0) {
2884 MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
2885 return ret;
2886 }
2887 }
2888 }
2889
2890 /* Either send now, or just save to be sent (and resent) later */
2891#if defined(MBEDTLS_SSL_PROTO_DTLS)
2892 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2893 !(ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2894 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST)) {
2895 if ((ret = ssl_flight_append(ssl)) != 0) {
2896 MBEDTLS_SSL_DEBUG_RET(1, "ssl_flight_append", ret);
2897 return ret;
2898 }
2899 } else
2900#endif
2901 {
2902 if ((ret = mbedtls_ssl_write_record(ssl, force_flush)) != 0) {
2903 MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_record", ret);
2904 return ret;
2905 }
2906 }
2907
2908 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write handshake message"));
2909
2910 return 0;
2911}
2912
2913int mbedtls_ssl_finish_handshake_msg(mbedtls_ssl_context *ssl,
2914 size_t buf_len, size_t msg_len)
2915{
2916 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2917 size_t msg_with_header_len;
2918 ((void) buf_len);
2919
2920 /* Add reserved 4 bytes for handshake header */
2921 msg_with_header_len = msg_len + 4;
2922 ssl->out_msglen = msg_with_header_len;
2923 MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_write_handshake_msg_ext(ssl, 0, 0));
2924
2925cleanup:
2926 return ret;
2927}
2928
2929/*
2930 * Record layer functions
2931 */
2932
2933/*
2934 * Write current record.
2935 *
2936 * Uses:
2937 * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
2938 * - ssl->out_msglen: length of the record content (excl headers)
2939 * - ssl->out_msg: record content
2940 */
2941int mbedtls_ssl_write_record(mbedtls_ssl_context *ssl, int force_flush)
2942{
2943 int ret, done = 0;
2944 size_t len = ssl->out_msglen;
2945 int flush = force_flush;
2946
2947 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write record"));
2948
2949 if (!done) {
2950 unsigned i;
2951 size_t protected_record_size;
2952#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2953 size_t out_buf_len = ssl->out_buf_len;
2954#else
2955 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
2956#endif
2957 /* Skip writing the record content type to after the encryption,
2958 * as it may change when using the CID extension. */
2959 mbedtls_ssl_protocol_version tls_ver = ssl->tls_version;
2960#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2961 /* TLS 1.3 still uses the TLS 1.2 version identifier
2962 * for backwards compatibility. */
2963 if (tls_ver == MBEDTLS_SSL_VERSION_TLS1_3) {
2964 tls_ver = MBEDTLS_SSL_VERSION_TLS1_2;
2965 }
2966#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2967 mbedtls_ssl_write_version(ssl->out_hdr + 1, ssl->conf->transport,
2968 tls_ver);
2969
2970 memcpy(ssl->out_ctr, ssl->cur_out_ctr, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
2971 MBEDTLS_PUT_UINT16_BE(len, ssl->out_len, 0);
2972
2973 if (ssl->transform_out != NULL) {
2974 mbedtls_record rec;
2975
2976 rec.buf = ssl->out_iv;
2977 rec.buf_len = out_buf_len - (size_t) (ssl->out_iv - ssl->out_buf);
2978 rec.data_len = ssl->out_msglen;
2979 rec.data_offset = (size_t) (ssl->out_msg - rec.buf);
2980
2981 memcpy(&rec.ctr[0], ssl->out_ctr, sizeof(rec.ctr));
2982 mbedtls_ssl_write_version(rec.ver, ssl->conf->transport, tls_ver);
2983 rec.type = ssl->out_msgtype;
2984
2985#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2986 /* The CID is set by mbedtls_ssl_encrypt_buf(). */
2987 rec.cid_len = 0;
2988#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2989
2990 if ((ret = mbedtls_ssl_encrypt_buf(ssl, ssl->transform_out, &rec,
2991 ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2992 MBEDTLS_SSL_DEBUG_RET(1, "ssl_encrypt_buf", ret);
2993 return ret;
2994 }
2995
2996 if (rec.data_offset != 0) {
2997 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2998 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2999 }
3000
3001 /* Update the record content type and CID. */
3002 ssl->out_msgtype = rec.type;
3003#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3004 memcpy(ssl->out_cid, rec.cid, rec.cid_len);
3005#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3006 ssl->out_msglen = len = rec.data_len;
3007 MBEDTLS_PUT_UINT16_BE(rec.data_len, ssl->out_len, 0);
3008 }
3009
3010 protected_record_size = len + mbedtls_ssl_out_hdr_len(ssl);
3011
3012#if defined(MBEDTLS_SSL_PROTO_DTLS)
3013 /* In case of DTLS, double-check that we don't exceed
3014 * the remaining space in the datagram. */
3015 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3016 ret = ssl_get_remaining_space_in_datagram(ssl);
3017 if (ret < 0) {
3018 return ret;
3019 }
3020
3021 if (protected_record_size > (size_t) ret) {
3022 /* Should never happen */
3023 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3024 }
3025 }
3026#endif /* MBEDTLS_SSL_PROTO_DTLS */
3027
3028 /* Now write the potentially updated record content type. */
3029 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
3030
3031 MBEDTLS_SSL_DEBUG_MSG(3, ("output record: msgtype = %u, "
3032 "version = [%u:%u], msglen = %" MBEDTLS_PRINTF_SIZET,
3033 ssl->out_hdr[0], ssl->out_hdr[1],
3034 ssl->out_hdr[2], len));
3035
3036 MBEDTLS_SSL_DEBUG_BUF(4, "output record sent to network",
3037 ssl->out_hdr, protected_record_size);
3038
3039 ssl->out_left += protected_record_size;
3040 ssl->out_hdr += protected_record_size;
3041 mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
3042
3043 for (i = 8; i > mbedtls_ssl_ep_len(ssl); i--) {
3044 if (++ssl->cur_out_ctr[i - 1] != 0) {
3045 break;
3046 }
3047 }
3048
3049 /* The loop goes to its end if the counter is wrapping */
3050 if (i == mbedtls_ssl_ep_len(ssl)) {
3051 MBEDTLS_SSL_DEBUG_MSG(1, ("outgoing message counter would wrap"));
3052 return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
3053 }
3054 }
3055
3056#if defined(MBEDTLS_SSL_PROTO_DTLS)
3057 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3058 flush == SSL_DONT_FORCE_FLUSH) {
3059 size_t remaining;
3060 ret = ssl_get_remaining_payload_in_datagram(ssl);
3061 if (ret < 0) {
3062 MBEDTLS_SSL_DEBUG_RET(1, "ssl_get_remaining_payload_in_datagram",
3063 ret);
3064 return ret;
3065 }
3066
3067 remaining = (size_t) ret;
3068 if (remaining == 0) {
3069 flush = SSL_FORCE_FLUSH;
3070 } else {
3071 MBEDTLS_SSL_DEBUG_MSG(2,
3072 ("Still %u bytes available in current datagram",
3073 (unsigned) remaining));
3074 }
3075 }
3076#endif /* MBEDTLS_SSL_PROTO_DTLS */
3077
3078 if ((flush == SSL_FORCE_FLUSH) &&
3079 (ret = mbedtls_ssl_flush_output(ssl)) != 0) {
3080 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
3081 return ret;
3082 }
3083
3084 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write record"));
3085
3086 return 0;
3087}
3088
3089#if defined(MBEDTLS_SSL_PROTO_DTLS)
3090
3091MBEDTLS_CHECK_RETURN_CRITICAL
3092static int ssl_hs_is_proper_fragment(mbedtls_ssl_context *ssl)
3093{
3094 if (ssl->in_msglen < ssl->in_hslen ||
3095 memcmp(ssl->in_msg + 6, "\0\0\0", 3) != 0 ||
3096 memcmp(ssl->in_msg + 9, ssl->in_msg + 1, 3) != 0) {
3097 return 1;
3098 }
3099 return 0;
3100}
3101
3102static uint32_t ssl_get_hs_frag_len(mbedtls_ssl_context const *ssl)
3103{
3104 return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 9);
3105}
3106
3107static uint32_t ssl_get_hs_frag_off(mbedtls_ssl_context const *ssl)
3108{
3109 return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 6);
3110}
3111
3112MBEDTLS_CHECK_RETURN_CRITICAL
3113static int ssl_check_hs_header(mbedtls_ssl_context const *ssl)
3114{
3115 uint32_t msg_len, frag_off, frag_len;
3116
3117 msg_len = ssl_get_hs_total_len(ssl);
3118 frag_off = ssl_get_hs_frag_off(ssl);
3119 frag_len = ssl_get_hs_frag_len(ssl);
3120
3121 if (frag_off > msg_len) {
3122 return -1;
3123 }
3124
3125 if (frag_len > msg_len - frag_off) {
3126 return -1;
3127 }
3128
3129 if (frag_len + 12 > ssl->in_msglen) {
3130 return -1;
3131 }
3132
3133 return 0;
3134}
3135
3136/*
3137 * Mark bits in bitmask (used for DTLS HS reassembly)
3138 */
3139static void ssl_bitmask_set(unsigned char *mask, size_t offset, size_t len)
3140{
3141 unsigned int start_bits, end_bits;
3142
3143 start_bits = 8 - (offset % 8);
3144 if (start_bits != 8) {
3145 size_t first_byte_idx = offset / 8;
3146
3147 /* Special case */
3148 if (len <= start_bits) {
3149 for (; len != 0; len--) {
3150 mask[first_byte_idx] |= 1 << (start_bits - len);
3151 }
3152
3153 /* Avoid potential issues with offset or len becoming invalid */
3154 return;
3155 }
3156
3157 offset += start_bits; /* Now offset % 8 == 0 */
3158 len -= start_bits;
3159
3160 for (; start_bits != 0; start_bits--) {
3161 mask[first_byte_idx] |= 1 << (start_bits - 1);
3162 }
3163 }
3164
3165 end_bits = len % 8;
3166 if (end_bits != 0) {
3167 size_t last_byte_idx = (offset + len) / 8;
3168
3169 len -= end_bits; /* Now len % 8 == 0 */
3170
3171 for (; end_bits != 0; end_bits--) {
3172 mask[last_byte_idx] |= 1 << (8 - end_bits);
3173 }
3174 }
3175
3176 memset(mask + offset / 8, 0xFF, len / 8);
3177}
3178
3179/*
3180 * Check that bitmask is full
3181 */
3182MBEDTLS_CHECK_RETURN_CRITICAL
3183static int ssl_bitmask_check(unsigned char *mask, size_t len)
3184{
3185 size_t i;
3186
3187 for (i = 0; i < len / 8; i++) {
3188 if (mask[i] != 0xFF) {
3189 return -1;
3190 }
3191 }
3192
3193 for (i = 0; i < len % 8; i++) {
3194 if ((mask[len / 8] & (1 << (7 - i))) == 0) {
3195 return -1;
3196 }
3197 }
3198
3199 return 0;
3200}
3201
3202/* msg_len does not include the handshake header */
3203static size_t ssl_get_reassembly_buffer_size(size_t msg_len,
3204 unsigned add_bitmap)
3205{
3206 size_t alloc_len;
3207
3208 alloc_len = 12; /* Handshake header */
3209 alloc_len += msg_len; /* Content buffer */
3210
3211 if (add_bitmap) {
3212 alloc_len += msg_len / 8 + (msg_len % 8 != 0); /* Bitmap */
3213
3214 }
3215 return alloc_len;
3216}
3217
3218#endif /* MBEDTLS_SSL_PROTO_DTLS */
3219
3220static uint32_t ssl_get_hs_total_len(mbedtls_ssl_context const *ssl)
3221{
3222 return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 1);
3223}
3224
3225int mbedtls_ssl_prepare_handshake_record(mbedtls_ssl_context *ssl)
3226{
3227 if (ssl->badmac_seen_or_in_hsfraglen == 0) {
3228 /* The handshake message must at least include the header.
3229 * We may not have the full message yet in case of fragmentation.
3230 * To simplify the code, we insist on having the header (and in
3231 * particular the handshake message length) in the first
3232 * fragment. */
3233 if (ssl->in_msglen < mbedtls_ssl_hs_hdr_len(ssl)) {
3234 MBEDTLS_SSL_DEBUG_MSG(1, ("handshake message too short: %" MBEDTLS_PRINTF_SIZET,
3235 ssl->in_msglen));
3236 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3237 }
3238
3239 ssl->in_hslen = mbedtls_ssl_hs_hdr_len(ssl) + ssl_get_hs_total_len(ssl);
3240 }
3241
3242 MBEDTLS_SSL_DEBUG_MSG(3, ("handshake message: msglen ="
3243 " %" MBEDTLS_PRINTF_SIZET ", type = %u, hslen = %"
3244 MBEDTLS_PRINTF_SIZET,
3245 ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen));
3246
3247 if (ssl->transform_in != NULL) {
3248 MBEDTLS_SSL_DEBUG_MSG(4, ("decrypted handshake message:"
3249 " iv-buf=%d hdr-buf=%d hdr-buf=%d",
3250 (int) (ssl->in_iv - ssl->in_buf),
3251 (int) (ssl->in_hdr - ssl->in_buf),
3252 (int) (ssl->in_msg - ssl->in_buf)));
3253 }
3254
3255#if defined(MBEDTLS_SSL_PROTO_DTLS)
3256 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3257 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3258 unsigned int recv_msg_seq = MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
3259
3260 if (ssl_check_hs_header(ssl) != 0) {
3261 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid handshake header"));
3262 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3263 }
3264
3265 if (ssl->in_msg[0] == MBEDTLS_SSL_HS_CLIENT_HELLO &&
3266 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
3267 if (ssl->state == MBEDTLS_SSL_CLIENT_HELLO
3268#if defined(MBEDTLS_SSL_RENEGOTIATION)
3269 && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
3270#endif
3271 ) {
3272 /*
3273 * When establishing the connection, the client may go through
3274 * a series of ClientHello and HelloVerifyRequest requests and
3275 * responses. The server intentionally does not keep trace of
3276 * these initial round trips: minimum allocated ressources as
3277 * long as the reachability of the client has not been
3278 * confirmed. When receiving the "first ClientHello" from
3279 * server perspective, we may thus need to adapt the next
3280 * expected `message_seq` for the incoming and outgoing
3281 * handshake messages.
3282 */
3283 if ((ssl->handshake->in_msg_seq == 0) && (recv_msg_seq > 0)) {
3284 MBEDTLS_SSL_DEBUG_MSG(3, ("shift slots by %u", recv_msg_seq));
3285 ssl_buffering_shift_slots(ssl, recv_msg_seq);
3286 ssl->handshake->in_msg_seq = recv_msg_seq;
3287 ssl->handshake->out_msg_seq = recv_msg_seq;
3288 }
3289
3290 /* Epoch should be 0 for initial handshakes */
3291 if (ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0) {
3292 MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
3293 return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
3294 }
3295
3296 memcpy(&ssl->cur_out_ctr[2], ssl->in_ctr + 2,
3297 sizeof(ssl->cur_out_ctr) - 2);
3298
3299 } else if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
3300 /* In case of a post-handshake ClientHello that initiates a
3301 * renegotiation check that the handshake message sequence
3302 * number is zero.
3303 */
3304 if (recv_msg_seq != 0) {
3305 MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message_seq: "
3306 "%u (expected 0)",
3307 recv_msg_seq));
3308 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3309 }
3310 }
3311 }
3312
3313 if (ssl->handshake != NULL &&
3314 ((mbedtls_ssl_is_handshake_over(ssl) == 0 &&
3315 recv_msg_seq != ssl->handshake->in_msg_seq) ||
3316 (mbedtls_ssl_is_handshake_over(ssl) == 1 &&
3317 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO))) {
3318 if (recv_msg_seq > ssl->handshake->in_msg_seq) {
3319 MBEDTLS_SSL_DEBUG_MSG(2,
3320 (
3321 "received future handshake message of sequence number %u (next %u)",
3322 recv_msg_seq,
3323 ssl->handshake->in_msg_seq));
3324 return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
3325 }
3326
3327 /* Retransmit only on last message from previous flight, to avoid
3328 * too many retransmissions.
3329 * Besides, No sane server ever retransmits HelloVerifyRequest */
3330 if (recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
3331 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST) {
3332 MBEDTLS_SSL_DEBUG_MSG(2, ("received message from last flight, "
3333 "message_seq = %u, start_of_flight = %u",
3334 recv_msg_seq,
3335 ssl->handshake->in_flight_start_seq));
3336
3337 if ((ret = mbedtls_ssl_resend(ssl)) != 0) {
3338 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend", ret);
3339 return ret;
3340 }
3341 } else {
3342 MBEDTLS_SSL_DEBUG_MSG(2, ("dropping out-of-sequence message: "
3343 "message_seq = %u, expected = %u",
3344 recv_msg_seq,
3345 ssl->handshake->in_msg_seq));
3346 }
3347
3348 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
3349 }
3350 /* Wait until message completion to increment in_msg_seq */
3351
3352 /* Message reassembly is handled alongside buffering of future
3353 * messages; the commonality is that both handshake fragments and
3354 * future messages cannot be forwarded immediately to the
3355 * handshake logic layer. */
3356 if (ssl_hs_is_proper_fragment(ssl) == 1) {
3357 MBEDTLS_SSL_DEBUG_MSG(2, ("found fragmented DTLS handshake message"));
3358 return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
3359 }
3360 } else
3361#endif /* MBEDTLS_SSL_PROTO_DTLS */
3362 {
3363 unsigned char *const reassembled_record_start =
3364 ssl->in_buf + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
3365 unsigned char *const payload_start =
3366 reassembled_record_start + mbedtls_ssl_in_hdr_len(ssl);
3367 unsigned char *payload_end = payload_start + ssl->badmac_seen_or_in_hsfraglen;
3368 /* How many more bytes we want to have a complete handshake message. */
3369 const size_t hs_remain = ssl->in_hslen - ssl->badmac_seen_or_in_hsfraglen;
3370 /* How many bytes of the current record are part of the first
3371 * handshake message. There may be more handshake messages (possibly
3372 * incomplete) in the same record; if so, we leave them after the
3373 * current record, and ssl_consume_current_message() will take
3374 * care of consuming the next handshake message. */
3375 const size_t hs_this_fragment_len =
3376 ssl->in_msglen > hs_remain ? hs_remain : ssl->in_msglen;
3377 (void) hs_this_fragment_len;
3378
3379 MBEDTLS_SSL_DEBUG_MSG(3,
3380 ("%s handshake fragment: %" MBEDTLS_PRINTF_SIZET
3381 ", %u..%u of %" MBEDTLS_PRINTF_SIZET,
3382 (ssl->badmac_seen_or_in_hsfraglen != 0 ?
3383 "subsequent" :
3384 hs_this_fragment_len == ssl->in_hslen ?
3385 "sole" :
3386 "initial"),
3387 ssl->in_msglen,
3388 ssl->badmac_seen_or_in_hsfraglen,
3389 ssl->badmac_seen_or_in_hsfraglen +
3390 (unsigned) hs_this_fragment_len,
3391 ssl->in_hslen));
3392
3393 /* Move the received handshake fragment to have the whole message
3394 * (at least the part received so far) in a single segment at a
3395 * known offset in the input buffer.
3396 * - When receiving a non-initial handshake fragment, append it to
3397 * the initial segment.
3398 * - Even the initial handshake fragment is moved, if it was
3399 * encrypted with an explicit IV: decryption leaves the payload
3400 * after the explicit IV, but here we move it to start where the
3401 * IV was.
3402 */
3403#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3404 size_t const in_buf_len = ssl->in_buf_len;
3405#else
3406 size_t const in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
3407#endif
3408 if (payload_end + ssl->in_msglen > ssl->in_buf + in_buf_len) {
3409 MBEDTLS_SSL_DEBUG_MSG(1,
3410 ("Shouldn't happen: no room to move handshake fragment %"
3411 MBEDTLS_PRINTF_SIZET " from %p to %p (buf=%p len=%"
3412 MBEDTLS_PRINTF_SIZET ")",
3413 ssl->in_msglen,
3414 (void *) ssl->in_msg, (void *) payload_end,
3415 (void *) ssl->in_buf, in_buf_len));
3416 return MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3417 }
3418 memmove(payload_end, ssl->in_msg, ssl->in_msglen);
3419
3420 ssl->badmac_seen_or_in_hsfraglen += (unsigned) ssl->in_msglen;
3421 payload_end += ssl->in_msglen;
3422
3423 if (ssl->badmac_seen_or_in_hsfraglen < ssl->in_hslen) {
3424 MBEDTLS_SSL_DEBUG_MSG(3, ("Prepare: waiting for more handshake fragments "
3425 "%u/%" MBEDTLS_PRINTF_SIZET,
3426 ssl->badmac_seen_or_in_hsfraglen, ssl->in_hslen));
3427 ssl->in_hdr = payload_end;
3428 ssl->in_msglen = 0;
3429 mbedtls_ssl_update_in_pointers(ssl);
3430 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
3431 } else {
3432 ssl->in_msglen = ssl->badmac_seen_or_in_hsfraglen;
3433 ssl->badmac_seen_or_in_hsfraglen = 0;
3434 ssl->in_hdr = reassembled_record_start;
3435 mbedtls_ssl_update_in_pointers(ssl);
3436
3437 /* Update the record length in the fully reassembled record */
3438 if (ssl->in_msglen > 0xffff) {
3439 MBEDTLS_SSL_DEBUG_MSG(1,
3440 ("Shouldn't happen: in_msglen=%"
3441 MBEDTLS_PRINTF_SIZET " > 0xffff",
3442 ssl->in_msglen));
3443 return MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3444 }
3445 MBEDTLS_PUT_UINT16_BE(ssl->in_msglen, ssl->in_len, 0);
3446
3447 size_t record_len = mbedtls_ssl_in_hdr_len(ssl) + ssl->in_msglen;
3448 (void) record_len;
3449 MBEDTLS_SSL_DEBUG_BUF(4, "reassembled record",
3450 ssl->in_hdr, record_len);
3451 if (ssl->in_hslen < ssl->in_msglen) {
3452 MBEDTLS_SSL_DEBUG_MSG(3,
3453 ("More handshake messages in the record: "
3454 "%" MBEDTLS_PRINTF_SIZET " + %" MBEDTLS_PRINTF_SIZET,
3455 ssl->in_hslen,
3456 ssl->in_msglen - ssl->in_hslen));
3457 }
3458 }
3459 }
3460
3461 return 0;
3462}
3463
3464int mbedtls_ssl_update_handshake_status(mbedtls_ssl_context *ssl)
3465{
3466 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3467 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
3468
3469 if (mbedtls_ssl_is_handshake_over(ssl) == 0 && hs != NULL) {
3470 ret = ssl->handshake->update_checksum(ssl, ssl->in_msg, ssl->in_hslen);
3471 if (ret != 0) {
3472 MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
3473 return ret;
3474 }
3475 }
3476
3477 /* Handshake message is complete, increment counter */
3478#if defined(MBEDTLS_SSL_PROTO_DTLS)
3479 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3480 ssl->handshake != NULL) {
3481
3482 /* Increment handshake sequence number */
3483 hs->in_msg_seq++;
3484 ssl_buffering_shift_slots(ssl, 1);
3485 }
3486#endif
3487 return 0;
3488}
3489
3490/*
3491 * DTLS anti-replay: RFC 6347 4.1.2.6
3492 *
3493 * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
3494 * Bit n is set iff record number in_window_top - n has been seen.
3495 *
3496 * Usually, in_window_top is the last record number seen and the lsb of
3497 * in_window is set. The only exception is the initial state (record number 0
3498 * not seen yet).
3499 */
3500#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3501void mbedtls_ssl_dtls_replay_reset(mbedtls_ssl_context *ssl)
3502{
3503 ssl->in_window_top = 0;
3504 ssl->in_window = 0;
3505}
3506
3507static inline uint64_t ssl_load_six_bytes(unsigned char *buf)
3508{
3509 return ((uint64_t) buf[0] << 40) |
3510 ((uint64_t) buf[1] << 32) |
3511 ((uint64_t) buf[2] << 24) |
3512 ((uint64_t) buf[3] << 16) |
3513 ((uint64_t) buf[4] << 8) |
3514 ((uint64_t) buf[5]);
3515}
3516
3517MBEDTLS_CHECK_RETURN_CRITICAL
3518static int mbedtls_ssl_dtls_record_replay_check(mbedtls_ssl_context *ssl, uint8_t *record_in_ctr)
3519{
3520 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3521 unsigned char *original_in_ctr;
3522
3523 // save original in_ctr
3524 original_in_ctr = ssl->in_ctr;
3525
3526 // use counter from record
3527 ssl->in_ctr = record_in_ctr;
3528
3529 ret = mbedtls_ssl_dtls_replay_check((mbedtls_ssl_context const *) ssl);
3530
3531 // restore the counter
3532 ssl->in_ctr = original_in_ctr;
3533
3534 return ret;
3535}
3536
3537/*
3538 * Return 0 if sequence number is acceptable, -1 otherwise
3539 */
3540int mbedtls_ssl_dtls_replay_check(mbedtls_ssl_context const *ssl)
3541{
3542 uint64_t rec_seqnum = ssl_load_six_bytes(ssl->in_ctr + 2);
3543 uint64_t bit;
3544
3545 if (ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED) {
3546 return 0;
3547 }
3548
3549 if (rec_seqnum > ssl->in_window_top) {
3550 return 0;
3551 }
3552
3553 bit = ssl->in_window_top - rec_seqnum;
3554
3555 if (bit >= 64) {
3556 return -1;
3557 }
3558
3559 if ((ssl->in_window & ((uint64_t) 1 << bit)) != 0) {
3560 return -1;
3561 }
3562
3563 return 0;
3564}
3565
3566/*
3567 * Update replay window on new validated record
3568 */
3569void mbedtls_ssl_dtls_replay_update(mbedtls_ssl_context *ssl)
3570{
3571 uint64_t rec_seqnum = ssl_load_six_bytes(ssl->in_ctr + 2);