vxx2 / 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);
3572
3573 if (ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED) {
3574 return;
3575 }
3576
3577 if (rec_seqnum > ssl->in_window_top) {
3578 /* Update window_top and the contents of the window */
3579 uint64_t shift = rec_seqnum - ssl->in_window_top;
3580
3581 if (shift >= 64) {
3582 ssl->in_window = 1;
3583 } else {
3584 ssl->in_window <<= shift;
3585 ssl->in_window |= 1;
3586 }
3587
3588 ssl->in_window_top = rec_seqnum;
3589 } else {
3590 /* Mark that number as seen in the current window */
3591 uint64_t bit = ssl->in_window_top - rec_seqnum;
3592
3593 if (bit < 64) { /* Always true, but be extra sure */
3594 ssl->in_window |= (uint64_t) 1 << bit;
3595 }
3596 }
3597}
3598#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
3599
3600#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3601/*
3602 * Check if a datagram looks like a ClientHello with a valid cookie,
3603 * and if it doesn't, generate a HelloVerifyRequest message.
3604 * Both input and output include full DTLS headers.
3605 *
3606 * - if cookie is valid, return 0
3607 * - if ClientHello looks superficially valid but cookie is not,
3608 * fill obuf and set olen, then
3609 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3610 * - otherwise return a specific error code
3611 */
3612MBEDTLS_CHECK_RETURN_CRITICAL
3613MBEDTLS_STATIC_TESTABLE
3614int mbedtls_ssl_check_dtls_clihlo_cookie(
3615 mbedtls_ssl_context *ssl,
3616 const unsigned char *cli_id, size_t cli_id_len,
3617 const unsigned char *in, size_t in_len,
3618 unsigned char *obuf, size_t buf_len, size_t *olen)
3619{
3620 size_t sid_len, cookie_len, epoch, fragment_offset;
3621 unsigned char *p;
3622
3623 /*
3624 * Structure of ClientHello with record and handshake headers,
3625 * and expected values. We don't need to check a lot, more checks will be
3626 * done when actually parsing the ClientHello - skipping those checks
3627 * avoids code duplication and does not make cookie forging any easier.
3628 *
3629 * 0-0 ContentType type; copied, must be handshake
3630 * 1-2 ProtocolVersion version; copied
3631 * 3-4 uint16 epoch; copied, must be 0
3632 * 5-10 uint48 sequence_number; copied
3633 * 11-12 uint16 length; (ignored)
3634 *
3635 * 13-13 HandshakeType msg_type; (ignored)
3636 * 14-16 uint24 length; (ignored)
3637 * 17-18 uint16 message_seq; copied
3638 * 19-21 uint24 fragment_offset; copied, must be 0
3639 * 22-24 uint24 fragment_length; (ignored)
3640 *
3641 * 25-26 ProtocolVersion client_version; (ignored)
3642 * 27-58 Random random; (ignored)
3643 * 59-xx SessionID session_id; 1 byte len + sid_len content
3644 * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
3645 * ...
3646 *
3647 * Minimum length is 61 bytes.
3648 */
3649 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: in_len=%u",
3650 (unsigned) in_len));
3651 MBEDTLS_SSL_DEBUG_BUF(4, "cli_id", cli_id, cli_id_len);
3652 if (in_len < 61) {
3653 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: record too short"));
3654 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3655 }
3656
3657 epoch = MBEDTLS_GET_UINT16_BE(in, 3);
3658 fragment_offset = MBEDTLS_GET_UINT24_BE(in, 19);
3659
3660 if (in[0] != MBEDTLS_SSL_MSG_HANDSHAKE || epoch != 0 ||
3661 fragment_offset != 0) {
3662 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: not a good ClientHello"));
3663 MBEDTLS_SSL_DEBUG_MSG(4, (" type=%u epoch=%u fragment_offset=%u",
3664 in[0], (unsigned) epoch,
3665 (unsigned) fragment_offset));
3666 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3667 }
3668
3669 sid_len = in[59];
3670 if (59 + 1 + sid_len + 1 > in_len) {
3671 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: sid_len=%u > %u",
3672 (unsigned) sid_len,
3673 (unsigned) in_len - 61));
3674 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3675 }
3676 MBEDTLS_SSL_DEBUG_BUF(4, "sid received from network",
3677 in + 60, sid_len);
3678
3679 cookie_len = in[60 + sid_len];
3680 if (59 + 1 + sid_len + 1 + cookie_len > in_len) {
3681 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: cookie_len=%u > %u",
3682 (unsigned) cookie_len,
3683 (unsigned) (in_len - sid_len - 61)));
3684 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3685 }
3686
3687 MBEDTLS_SSL_DEBUG_BUF(4, "cookie received from network",
3688 in + sid_len + 61, cookie_len);
3689 if (ssl->conf->f_cookie_check(ssl->conf->p_cookie,
3690 in + sid_len + 61, cookie_len,
3691 cli_id, cli_id_len) == 0) {
3692 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: valid"));
3693 return 0;
3694 }
3695
3696 /*
3697 * If we get here, we've got an invalid cookie, let's prepare HVR.
3698 *
3699 * 0-0 ContentType type; copied
3700 * 1-2 ProtocolVersion version; copied
3701 * 3-4 uint16 epoch; copied
3702 * 5-10 uint48 sequence_number; copied
3703 * 11-12 uint16 length; olen - 13
3704 *
3705 * 13-13 HandshakeType msg_type; hello_verify_request
3706 * 14-16 uint24 length; olen - 25
3707 * 17-18 uint16 message_seq; copied
3708 * 19-21 uint24 fragment_offset; copied
3709 * 22-24 uint24 fragment_length; olen - 25
3710 *
3711 * 25-26 ProtocolVersion server_version; 0xfe 0xff
3712 * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
3713 *
3714 * Minimum length is 28.
3715 */
3716 if (buf_len < 28) {
3717 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
3718 }
3719
3720 /* Copy most fields and adapt others */
3721 memcpy(obuf, in, 25);
3722 obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
3723 obuf[25] = 0xfe;
3724 obuf[26] = 0xff;
3725
3726 /* Generate and write actual cookie */
3727 p = obuf + 28;
3728 if (ssl->conf->f_cookie_write(ssl->conf->p_cookie,
3729 &p, obuf + buf_len,
3730 cli_id, cli_id_len) != 0) {
3731 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3732 }
3733
3734 *olen = (size_t) (p - obuf);
3735
3736 /* Go back and fill length fields */
3737 obuf[27] = (unsigned char) (*olen - 28);
3738
3739 obuf[14] = obuf[22] = MBEDTLS_BYTE_2(*olen - 25);
3740 obuf[15] = obuf[23] = MBEDTLS_BYTE_1(*olen - 25);
3741 obuf[16] = obuf[24] = MBEDTLS_BYTE_0(*olen - 25);
3742
3743 MBEDTLS_PUT_UINT16_BE(*olen - 13, obuf, 11);
3744
3745 return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED;
3746}
3747
3748/*
3749 * Handle possible client reconnect with the same UDP quadruplet
3750 * (RFC 6347 Section 4.2.8).
3751 *
3752 * Called by ssl_parse_record_header() in case we receive an epoch 0 record
3753 * that looks like a ClientHello.
3754 *
3755 * - if the input looks like a ClientHello without cookies,
3756 * send back HelloVerifyRequest, then return 0
3757 * - if the input looks like a ClientHello with a valid cookie,
3758 * reset the session of the current context, and
3759 * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
3760 * - if anything goes wrong, return a specific error code
3761 *
3762 * This function is called (through ssl_check_client_reconnect()) when an
3763 * unexpected record is found in ssl_get_next_record(), which will discard the
3764 * record if we return 0, and bubble up the return value otherwise (this
3765 * includes the case of MBEDTLS_ERR_SSL_CLIENT_RECONNECT and of unexpected
3766 * errors, and is the right thing to do in both cases).
3767 */
3768MBEDTLS_CHECK_RETURN_CRITICAL
3769static int ssl_handle_possible_reconnect(mbedtls_ssl_context *ssl)
3770{
3771 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3772 size_t len = 0;
3773
3774 if (ssl->conf->f_cookie_write == NULL ||
3775 ssl->conf->f_cookie_check == NULL) {
3776 /* If we can't use cookies to verify reachability of the peer,
3777 * drop the record. */
3778 MBEDTLS_SSL_DEBUG_MSG(1, ("no cookie callbacks, "
3779 "can't check reconnect validity"));
3780 return 0;
3781 }
3782
3783 ret = mbedtls_ssl_check_dtls_clihlo_cookie(
3784 ssl,
3785 ssl->cli_id, ssl->cli_id_len,
3786 ssl->in_buf, ssl->in_left,
3787 ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len);
3788
3789 MBEDTLS_SSL_DEBUG_RET(2, "mbedtls_ssl_check_dtls_clihlo_cookie", ret);
3790
3791 if (ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) {
3792 int send_ret;
3793 MBEDTLS_SSL_DEBUG_MSG(1, ("sending HelloVerifyRequest"));
3794 MBEDTLS_SSL_DEBUG_BUF(4, "output record sent to network",
3795 ssl->out_buf, len);
3796 /* Don't check write errors as we can't do anything here.
3797 * If the error is permanent we'll catch it later,
3798 * if it's not, then hopefully it'll work next time. */
3799 send_ret = ssl->f_send(ssl->p_bio, ssl->out_buf, len);
3800 MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_send", send_ret);
3801 (void) send_ret;
3802
3803 return 0;
3804 }
3805
3806 if (ret == 0) {
3807 MBEDTLS_SSL_DEBUG_MSG(1, ("cookie is valid, resetting context"));
3808 if ((ret = mbedtls_ssl_session_reset_int(ssl, 1)) != 0) {
3809 MBEDTLS_SSL_DEBUG_RET(1, "reset", ret);
3810 return ret;
3811 }
3812
3813 return MBEDTLS_ERR_SSL_CLIENT_RECONNECT;
3814 }
3815
3816 return ret;
3817}
3818#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3819
3820MBEDTLS_CHECK_RETURN_CRITICAL
3821static int ssl_check_record_type(uint8_t record_type)
3822{
3823 if (record_type != MBEDTLS_SSL_MSG_HANDSHAKE &&
3824 record_type != MBEDTLS_SSL_MSG_ALERT &&
3825 record_type != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3826 record_type != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
3827 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3828 }
3829
3830 return 0;
3831}
3832
3833/*
3834 * ContentType type;
3835 * ProtocolVersion version;
3836 * uint16 epoch; // DTLS only
3837 * uint48 sequence_number; // DTLS only
3838 * uint16 length;
3839 *
3840 * Return 0 if header looks sane (and, for DTLS, the record is expected)
3841 * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
3842 * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
3843 *
3844 * With DTLS, mbedtls_ssl_read_record() will:
3845 * 1. proceed with the record if this function returns 0
3846 * 2. drop only the current record if this function returns UNEXPECTED_RECORD
3847 * 3. return CLIENT_RECONNECT if this function return that value
3848 * 4. drop the whole datagram if this function returns anything else.
3849 * Point 2 is needed when the peer is resending, and we have already received
3850 * the first record from a datagram but are still waiting for the others.
3851 */
3852MBEDTLS_CHECK_RETURN_CRITICAL
3853static int ssl_parse_record_header(mbedtls_ssl_context const *ssl,
3854 unsigned char *buf,
3855 size_t len,
3856 mbedtls_record *rec)
3857{
3858 mbedtls_ssl_protocol_version tls_version;
3859
3860 size_t const rec_hdr_type_offset = 0;
3861 size_t const rec_hdr_type_len = 1;
3862
3863 size_t const rec_hdr_version_offset = rec_hdr_type_offset +
3864 rec_hdr_type_len;
3865 size_t const rec_hdr_version_len = 2;
3866
3867 size_t const rec_hdr_ctr_len = 8;
3868#if defined(MBEDTLS_SSL_PROTO_DTLS)
3869 uint32_t rec_epoch;
3870 size_t const rec_hdr_ctr_offset = rec_hdr_version_offset +
3871 rec_hdr_version_len;
3872
3873#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3874 size_t const rec_hdr_cid_offset = rec_hdr_ctr_offset +
3875 rec_hdr_ctr_len;
3876 size_t rec_hdr_cid_len = 0;
3877#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3878#endif /* MBEDTLS_SSL_PROTO_DTLS */
3879
3880 size_t rec_hdr_len_offset; /* To be determined */
3881 size_t const rec_hdr_len_len = 2;
3882
3883 /*
3884 * Check minimum lengths for record header.
3885 */
3886
3887#if defined(MBEDTLS_SSL_PROTO_DTLS)
3888 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3889 rec_hdr_len_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len;
3890 } else
3891#endif /* MBEDTLS_SSL_PROTO_DTLS */
3892 {
3893 rec_hdr_len_offset = rec_hdr_version_offset + rec_hdr_version_len;
3894 }
3895
3896 if (len < rec_hdr_len_offset + rec_hdr_len_len) {
3897 MBEDTLS_SSL_DEBUG_MSG(1,
3898 (
3899 "datagram of length %u too small to hold DTLS record header of length %u",
3900 (unsigned) len,
3901 (unsigned) (rec_hdr_len_offset + rec_hdr_len_len)));
3902 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3903 }
3904
3905 /*
3906 * Parse and validate record content type
3907 */
3908
3909 rec->type = buf[rec_hdr_type_offset];
3910
3911 /* Check record content type */
3912#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3913 rec->cid_len = 0;
3914
3915 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3916 ssl->conf->cid_len != 0 &&
3917 rec->type == MBEDTLS_SSL_MSG_CID) {
3918 /* Shift pointers to account for record header including CID
3919 * struct {
3920 * ContentType outer_type = tls12_cid;
3921 * ProtocolVersion version;
3922 * uint16 epoch;
3923 * uint48 sequence_number;
3924 * opaque cid[cid_length]; // Additional field compared to
3925 * // default DTLS record format
3926 * uint16 length;
3927 * opaque enc_content[DTLSCiphertext.length];
3928 * } DTLSCiphertext;
3929 */
3930
3931 /* So far, we only support static CID lengths
3932 * fixed in the configuration. */
3933 rec_hdr_cid_len = ssl->conf->cid_len;
3934 rec_hdr_len_offset += rec_hdr_cid_len;
3935
3936 if (len < rec_hdr_len_offset + rec_hdr_len_len) {
3937 MBEDTLS_SSL_DEBUG_MSG(1,
3938 (
3939 "datagram of length %u too small to hold DTLS record header including CID, length %u",
3940 (unsigned) len,
3941 (unsigned) (rec_hdr_len_offset + rec_hdr_len_len)));
3942 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3943 }
3944
3945 /* configured CID len is guaranteed at most 255, see
3946 * MBEDTLS_SSL_CID_OUT_LEN_MAX in check_config.h */
3947 rec->cid_len = (uint8_t) rec_hdr_cid_len;
3948 memcpy(rec->cid, buf + rec_hdr_cid_offset, rec_hdr_cid_len);
3949 } else
3950#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3951 {
3952 if (ssl_check_record_type(rec->type)) {
3953 MBEDTLS_SSL_DEBUG_MSG(1, ("unknown record type %u",
3954 (unsigned) rec->type));
3955 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3956 }
3957 }
3958
3959 /*
3960 * Parse and validate record version
3961 */
3962 rec->ver[0] = buf[rec_hdr_version_offset + 0];
3963 rec->ver[1] = buf[rec_hdr_version_offset + 1];
3964 tls_version = (mbedtls_ssl_protocol_version) mbedtls_ssl_read_version(
3965 buf + rec_hdr_version_offset,
3966 ssl->conf->transport);
3967
3968 if (tls_version > ssl->conf->max_tls_version) {
3969 MBEDTLS_SSL_DEBUG_MSG(1, ("TLS version mismatch: got %u, expected max %u",
3970 (unsigned) tls_version,
3971 (unsigned) ssl->conf->max_tls_version));
3972
3973 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3974 }
3975 /*
3976 * Parse/Copy record sequence number.
3977 */
3978
3979#if defined(MBEDTLS_SSL_PROTO_DTLS)
3980 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3981 /* Copy explicit record sequence number from input buffer. */
3982 memcpy(&rec->ctr[0], buf + rec_hdr_ctr_offset,
3983 rec_hdr_ctr_len);
3984 } else
3985#endif /* MBEDTLS_SSL_PROTO_DTLS */
3986 {
3987 /* Copy implicit record sequence number from SSL context structure. */
3988 memcpy(&rec->ctr[0], ssl->in_ctr, rec_hdr_ctr_len);
3989 }
3990
3991 /*
3992 * Parse record length.
3993 */
3994
3995 rec->data_offset = rec_hdr_len_offset + rec_hdr_len_len;
3996 rec->data_len = MBEDTLS_GET_UINT16_BE(buf, rec_hdr_len_offset);
3997 MBEDTLS_SSL_DEBUG_BUF(4, "input record header", buf, rec->data_offset);
3998
3999 MBEDTLS_SSL_DEBUG_MSG(3, ("input record: msgtype = %u, "
4000 "version = [0x%x], msglen = %" MBEDTLS_PRINTF_SIZET,
4001 rec->type, (unsigned) tls_version, rec->data_len));
4002
4003 rec->buf = buf;
4004 rec->buf_len = rec->data_offset + rec->data_len;
4005
4006 if (rec->data_len == 0) {
4007 MBEDTLS_SSL_DEBUG_MSG(1, ("rejecting empty record"));
4008 return MBEDTLS_ERR_SSL_INVALID_RECORD;
4009 }
4010
4011 /*
4012 * DTLS-related tests.
4013 * Check epoch before checking length constraint because
4014 * the latter varies with the epoch. E.g., if a ChangeCipherSpec
4015 * message gets duplicated before the corresponding Finished message,
4016 * the second ChangeCipherSpec should be discarded because it belongs
4017 * to an old epoch, but not because its length is shorter than
4018 * the minimum record length for packets using the new record transform.
4019 * Note that these two kinds of failures are handled differently,
4020 * as an unexpected record is silently skipped but an invalid
4021 * record leads to the entire datagram being dropped.
4022 */
4023#if defined(MBEDTLS_SSL_PROTO_DTLS)
4024 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4025 rec_epoch = MBEDTLS_GET_UINT16_BE(rec->ctr, 0);
4026
4027 /* Check that the datagram is large enough to contain a record
4028 * of the advertised length. */
4029 if (len < rec->data_offset + rec->data_len) {
4030 MBEDTLS_SSL_DEBUG_MSG(1,
4031 (
4032 "Datagram of length %u too small to contain record of advertised length %u.",
4033 (unsigned) len,
4034 (unsigned) (rec->data_offset + rec->data_len)));
4035 return MBEDTLS_ERR_SSL_INVALID_RECORD;
4036 }
4037
4038 /* Records from other, non-matching epochs are silently discarded.
4039 * (The case of same-port Client reconnects must be considered in
4040 * the caller). */
4041 if (rec_epoch != ssl->in_epoch) {
4042 MBEDTLS_SSL_DEBUG_MSG(1, ("record from another epoch: "
4043 "expected %u, received %lu",
4044 ssl->in_epoch, (unsigned long) rec_epoch));
4045
4046 /* Records from the next epoch are considered for buffering
4047 * (concretely: early Finished messages). */
4048 if (rec_epoch == (unsigned) ssl->in_epoch + 1) {
4049 MBEDTLS_SSL_DEBUG_MSG(2, ("Consider record for buffering"));
4050 return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
4051 }
4052
4053 return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
4054 }
4055#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4056 /* For records from the correct epoch, check whether their
4057 * sequence number has been seen before. */
4058 else if (mbedtls_ssl_dtls_record_replay_check((mbedtls_ssl_context *) ssl,
4059 &rec->ctr[0]) != 0) {
4060 MBEDTLS_SSL_DEBUG_MSG(1, ("replayed record"));
4061 return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
4062 }
4063#endif
4064 }
4065#endif /* MBEDTLS_SSL_PROTO_DTLS */
4066
4067 return 0;
4068}
4069
4070
4071#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
4072MBEDTLS_CHECK_RETURN_CRITICAL
4073static int ssl_check_client_reconnect(mbedtls_ssl_context *ssl)
4074{
4075 unsigned int rec_epoch = MBEDTLS_GET_UINT16_BE(ssl->in_ctr, 0);
4076
4077 /*
4078 * Check for an epoch 0 ClientHello. We can't use in_msg here to
4079 * access the first byte of record content (handshake type), as we
4080 * have an active transform (possibly iv_len != 0), so use the
4081 * fact that the record header len is 13 instead.
4082 */
4083 if (rec_epoch == 0 &&
4084 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4085 mbedtls_ssl_is_handshake_over(ssl) == 1 &&
4086 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4087 ssl->in_left > 13 &&
4088 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO) {
4089 MBEDTLS_SSL_DEBUG_MSG(1, ("possible client reconnect "
4090 "from the same port"));
4091 return ssl_handle_possible_reconnect(ssl);
4092 }
4093
4094 return 0;
4095}
4096#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
4097
4098/*
4099 * If applicable, decrypt record content
4100 */
4101MBEDTLS_CHECK_RETURN_CRITICAL
4102static int ssl_prepare_record_content(mbedtls_ssl_context *ssl,
4103 mbedtls_record *rec)
4104{
4105 int ret, done = 0;
4106
4107 MBEDTLS_SSL_DEBUG_BUF(4, "input record from network",
4108 rec->buf, rec->buf_len);
4109
4110 /*
4111 * In TLS 1.3, always treat ChangeCipherSpec records
4112 * as unencrypted. The only thing we do with them is
4113 * check the length and content and ignore them.
4114 */
4115#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
4116 if (ssl->transform_in != NULL &&
4117 ssl->transform_in->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
4118 if (rec->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
4119 done = 1;
4120 }
4121 }
4122#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
4123
4124 if (!done && ssl->transform_in != NULL) {
4125 unsigned char const old_msg_type = rec->type;
4126
4127 if ((ret = mbedtls_ssl_decrypt_buf(ssl, ssl->transform_in,
4128 rec)) != 0) {
4129 MBEDTLS_SSL_DEBUG_RET(1, "ssl_decrypt_buf", ret);
4130
4131#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
4132 /*
4133 * Although the server rejected early data, it might receive early
4134 * data as long as it has not received the client Finished message.
4135 * It is encrypted with early keys and should be ignored as stated
4136 * in section 4.2.10 of RFC 8446:
4137 *
4138 * "Ignore the extension and return a regular 1-RTT response. The
4139 * server then skips past early data by attempting to deprotect
4140 * received records using the handshake traffic key, discarding
4141 * records which fail deprotection (up to the configured
4142 * max_early_data_size). Once a record is deprotected successfully,
4143 * it is treated as the start of the client's second flight and the
4144 * server proceeds as with an ordinary 1-RTT handshake."
4145 */
4146 if ((old_msg_type == MBEDTLS_SSL_MSG_APPLICATION_DATA) &&
4147 (ssl->discard_early_data_record ==
4148 MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD)) {
4149 MBEDTLS_SSL_DEBUG_MSG(
4150 3, ("EarlyData: deprotect and discard app data records."));
4151
4152 ret = mbedtls_ssl_tls13_check_early_data_len(ssl, rec->data_len);
4153 if (ret != 0) {
4154 return ret;
4155 }
4156 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4157 }
4158#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
4159
4160#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4161 if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID &&
4162 ssl->conf->ignore_unexpected_cid
4163 == MBEDTLS_SSL_UNEXPECTED_CID_IGNORE) {
4164 MBEDTLS_SSL_DEBUG_MSG(3, ("ignoring unexpected CID"));
4165 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4166 }
4167#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4168
4169 /*
4170 * The decryption of the record failed, no reason to ignore it,
4171 * return in error with the decryption error code.
4172 */
4173 return ret;
4174 }
4175
4176#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
4177 /*
4178 * If the server were discarding protected records that it fails to
4179 * deprotect because it has rejected early data, as we have just
4180 * deprotected successfully a record, the server has to resume normal
4181 * operation and fail the connection if the deprotection of a record
4182 * fails.
4183 */
4184 if (ssl->discard_early_data_record ==
4185 MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD) {
4186 ssl->discard_early_data_record = MBEDTLS_SSL_EARLY_DATA_NO_DISCARD;
4187 }
4188#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
4189
4190 if (old_msg_type != rec->type) {
4191 MBEDTLS_SSL_DEBUG_MSG(4, ("record type after decrypt (before %d): %d",
4192 old_msg_type, rec->type));
4193 }
4194
4195 MBEDTLS_SSL_DEBUG_BUF(4, "input payload after decrypt",
4196 rec->buf + rec->data_offset, rec->data_len);
4197
4198#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4199 /* We have already checked the record content type
4200 * in ssl_parse_record_header(), failing or silently
4201 * dropping the record in the case of an unknown type.
4202 *
4203 * Since with the use of CIDs, the record content type
4204 * might change during decryption, re-check the record
4205 * content type, but treat a failure as fatal this time. */
4206 if (ssl_check_record_type(rec->type)) {
4207 MBEDTLS_SSL_DEBUG_MSG(1, ("unknown record type"));
4208 return MBEDTLS_ERR_SSL_INVALID_RECORD;
4209 }
4210#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4211
4212 if (rec->data_len == 0) {
4213#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4214 if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2
4215 && rec->type != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
4216 /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
4217 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid zero-length message type: %d", ssl->in_msgtype));
4218 return MBEDTLS_ERR_SSL_INVALID_RECORD;
4219 }
4220#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4221
4222 ssl->nb_zero++;
4223
4224 /*
4225 * Three or more empty messages may be a DoS attack
4226 * (excessive CPU consumption).
4227 */
4228 if (ssl->nb_zero > 3) {
4229 MBEDTLS_SSL_DEBUG_MSG(1, ("received four consecutive empty "
4230 "messages, possible DoS attack"));
4231 /* Treat the records as if they were not properly authenticated,
4232 * thereby failing the connection if we see more than allowed
4233 * by the configured bad MAC threshold. */
4234 return MBEDTLS_ERR_SSL_INVALID_MAC;
4235 }
4236 } else {
4237 ssl->nb_zero = 0;
4238 }
4239
4240#if defined(MBEDTLS_SSL_PROTO_DTLS)
4241 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4242 ; /* in_ctr read from peer, not maintained internally */
4243 } else
4244#endif
4245 {
4246 unsigned i;
4247 for (i = MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
4248 i > mbedtls_ssl_ep_len(ssl); i--) {
4249 if (++ssl->in_ctr[i - 1] != 0) {
4250 break;
4251 }
4252 }
4253
4254 /* The loop goes to its end iff the counter is wrapping */
4255 if (i == mbedtls_ssl_ep_len(ssl)) {
4256 MBEDTLS_SSL_DEBUG_MSG(1, ("incoming message counter would wrap"));
4257 return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
4258 }
4259 }
4260
4261 }
4262
4263#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
4264 /*
4265 * Although the server rejected early data because it needed to send an
4266 * HelloRetryRequest message, it might receive early data as long as it has
4267 * not received the client Finished message.
4268 * The early data is encrypted with early keys and should be ignored as
4269 * stated in section 4.2.10 of RFC 8446 (second case):
4270 *
4271 * "The server then ignores early data by skipping all records with an
4272 * external content type of "application_data" (indicating that they are
4273 * encrypted), up to the configured max_early_data_size. Ignore application
4274 * data message before 2nd ClientHello when early_data was received in 1st
4275 * ClientHello."
4276 */
4277 if (ssl->discard_early_data_record == MBEDTLS_SSL_EARLY_DATA_DISCARD) {
4278 if (rec->type == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
4279
4280 ret = mbedtls_ssl_tls13_check_early_data_len(ssl, rec->data_len);
4281 if (ret != 0) {
4282 return ret;
4283 }
4284
4285 MBEDTLS_SSL_DEBUG_MSG(
4286 3, ("EarlyData: Ignore application message before 2nd ClientHello"));
4287
4288 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4289 } else if (rec->type == MBEDTLS_SSL_MSG_HANDSHAKE) {
4290 ssl->discard_early_data_record = MBEDTLS_SSL_EARLY_DATA_NO_DISCARD;
4291 }
4292 }
4293#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
4294
4295#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4296 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4297 mbedtls_ssl_dtls_replay_update(ssl);
4298 }
4299#endif
4300
4301 /* Check actual (decrypted) record content length against
4302 * configured maximum. */
4303 if (rec->data_len > MBEDTLS_SSL_IN_CONTENT_LEN) {
4304 MBEDTLS_SSL_DEBUG_MSG(1, ("bad message length"));
4305 return MBEDTLS_ERR_SSL_INVALID_RECORD;
4306 }
4307
4308 return 0;
4309}
4310
4311/*
4312 * Read a record.
4313 *
4314 * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
4315 * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
4316 *
4317 */
4318
4319/* Helper functions for mbedtls_ssl_read_record(). */
4320MBEDTLS_CHECK_RETURN_CRITICAL
4321static int ssl_consume_current_message(mbedtls_ssl_context *ssl);
4322MBEDTLS_CHECK_RETURN_CRITICAL
4323static int ssl_get_next_record(mbedtls_ssl_context *ssl);
4324MBEDTLS_CHECK_RETURN_CRITICAL
4325static int ssl_record_is_in_progress(mbedtls_ssl_context *ssl);
4326
4327int mbedtls_ssl_read_record(mbedtls_ssl_context *ssl,
4328 unsigned update_hs_digest)
4329{
4330 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4331
4332 MBEDTLS_SSL_DEBUG_MSG(2, ("=> read record"));
4333
4334 if (ssl->keep_current_message == 0) {
4335 do {
4336
4337 ret = ssl_consume_current_message(ssl);
4338 if (ret != 0) {
4339 return ret;
4340 }
4341
4342 if (ssl_record_is_in_progress(ssl) == 0) {
4343 int dtls_have_buffered = 0;
4344#if defined(MBEDTLS_SSL_PROTO_DTLS)
4345
4346 /* We only check for buffered messages if the
4347 * current datagram is fully consumed. */
4348 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4349 ssl_next_record_is_in_datagram(ssl) == 0) {
4350 if (ssl_load_buffered_message(ssl) == 0) {
4351 dtls_have_buffered = 1;
4352 }
4353 }
4354
4355#endif /* MBEDTLS_SSL_PROTO_DTLS */
4356 if (dtls_have_buffered == 0) {
4357 ret = ssl_get_next_record(ssl);
4358 if (ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING) {
4359 continue;
4360 }
4361
4362 if (ret != 0) {
4363 MBEDTLS_SSL_DEBUG_RET(1, ("ssl_get_next_record"), ret);
4364 return ret;
4365 }
4366 }
4367 }
4368
4369 ret = mbedtls_ssl_handle_message_type(ssl);
4370
4371#if defined(MBEDTLS_SSL_PROTO_DTLS)
4372 if (ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
4373 /* Buffer future message */
4374 ret = ssl_buffer_message(ssl);
4375 if (ret != 0) {
4376 return ret;
4377 }
4378
4379 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4380 }
4381#endif /* MBEDTLS_SSL_PROTO_DTLS */
4382
4383 } while (MBEDTLS_ERR_SSL_NON_FATAL == ret ||
4384 MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret);
4385
4386 if (0 != ret) {
4387 MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_handle_message_type"), ret);
4388 return ret;
4389 }
4390
4391 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4392 update_hs_digest == 1) {
4393 ret = mbedtls_ssl_update_handshake_status(ssl);
4394 if (0 != ret) {
4395 MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_update_handshake_status"), ret);
4396 return ret;
4397 }
4398 }
4399 } else {
4400 MBEDTLS_SSL_DEBUG_MSG(2, ("reuse previously read message"));
4401 ssl->keep_current_message = 0;
4402 }
4403
4404 MBEDTLS_SSL_DEBUG_MSG(2, ("<= read record"));
4405
4406 return 0;
4407}
4408
4409#if defined(MBEDTLS_SSL_PROTO_DTLS)
4410MBEDTLS_CHECK_RETURN_CRITICAL
4411static int ssl_next_record_is_in_datagram(mbedtls_ssl_context *ssl)
4412{
4413 if (ssl->in_left > ssl->next_record_offset) {
4414 return 1;
4415 }
4416
4417 return 0;
4418}
4419
4420MBEDTLS_CHECK_RETURN_CRITICAL
4421static int ssl_load_buffered_message(mbedtls_ssl_context *ssl)
4422{
4423 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4424 mbedtls_ssl_hs_buffer *hs_buf;
4425 int ret = 0;
4426
4427 if (hs == NULL) {
4428 return -1;
4429 }
4430
4431 MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_load_buffered_message"));
4432
4433 if (ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
4434 ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC) {
4435 /* Check if we have seen a ChangeCipherSpec before.
4436 * If yes, synthesize a CCS record. */
4437 if (!hs->buffering.seen_ccs) {
4438 MBEDTLS_SSL_DEBUG_MSG(2, ("CCS not seen in the current flight"));
4439 ret = -1;
4440 goto exit;
4441 }
4442
4443 MBEDTLS_SSL_DEBUG_MSG(2, ("Injecting buffered CCS message"));
4444 ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
4445 ssl->in_msglen = 1;
4446 ssl->in_msg[0] = 1;
4447
4448 /* As long as they are equal, the exact value doesn't matter. */
4449 ssl->in_left = 0;
4450 ssl->next_record_offset = 0;
4451
4452 hs->buffering.seen_ccs = 0;
4453 goto exit;
4454 }
4455
4456#if defined(MBEDTLS_DEBUG_C)
4457 /* Debug only */
4458 {
4459 unsigned offset;
4460 for (offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++) {
4461 hs_buf = &hs->buffering.hs[offset];
4462 if (hs_buf->is_valid == 1) {
4463 MBEDTLS_SSL_DEBUG_MSG(2, ("Future message with sequence number %u %s buffered.",
4464 hs->in_msg_seq + offset,
4465 hs_buf->is_complete ? "fully" : "partially"));
4466 }
4467 }
4468 }
4469#endif /* MBEDTLS_DEBUG_C */
4470
4471 /* Check if we have buffered and/or fully reassembled the
4472 * next handshake message. */
4473 hs_buf = &hs->buffering.hs[0];
4474 if ((hs_buf->is_valid == 1) && (hs_buf->is_complete == 1)) {
4475 /* Synthesize a record containing the buffered HS message. */
4476 size_t msg_len = MBEDTLS_GET_UINT24_BE(hs_buf->data, 1);
4477
4478 /* Double-check that we haven't accidentally buffered
4479 * a message that doesn't fit into the input buffer. */
4480 if (msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN) {
4481 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4482 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4483 }
4484
4485 MBEDTLS_SSL_DEBUG_MSG(2, ("%s handshake message has been buffered%s",
4486 mbedtls_ssl_get_hs_msg_name(hs_buf->data[0]),
4487 hs_buf->is_fragmented ? " and reassembled" : ""));
4488 MBEDTLS_SSL_DEBUG_BUF(3, "Buffered handshake message (incl. header)",
4489 hs_buf->data, msg_len + 12);
4490
4491 ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4492 ssl->in_hslen = msg_len + 12;
4493 ssl->in_msglen = msg_len + 12;
4494 memcpy(ssl->in_msg, hs_buf->data, ssl->in_hslen);
4495
4496 ret = 0;
4497 goto exit;
4498 } else {
4499 MBEDTLS_SSL_DEBUG_MSG(2, ("Next handshake message %u not or only partially buffered",
4500 hs->in_msg_seq));
4501 }
4502
4503 ret = -1;
4504
4505exit:
4506
4507 MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_load_buffered_message"));
4508 return ret;
4509}
4510
4511MBEDTLS_CHECK_RETURN_CRITICAL
4512static int ssl_buffer_make_space(mbedtls_ssl_context *ssl,
4513 size_t desired)
4514{
4515 int offset;
4516 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4517 MBEDTLS_SSL_DEBUG_MSG(2, ("Attempt to free buffered messages to have %u bytes available",
4518 (unsigned) desired));
4519
4520 /* Get rid of future records epoch first, if such exist. */
4521 ssl_free_buffered_record(ssl);
4522
4523 /* Check if we have enough space available now. */
4524 if (desired <= (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4525 hs->buffering.total_bytes_buffered)) {
4526 MBEDTLS_SSL_DEBUG_MSG(2, ("Enough space available after freeing future epoch record"));
4527 return 0;
4528 }
4529
4530 /* We don't have enough space to buffer the next expected handshake
4531 * message. Remove buffers used for future messages to gain space,
4532 * starting with the most distant one. */
4533 for (offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
4534 offset >= 0; offset--) {
4535 MBEDTLS_SSL_DEBUG_MSG(2,
4536 (
4537 "Free buffering slot %d to make space for reassembly of next handshake message",
4538 offset));
4539
4540 ssl_buffering_free_slot(ssl, (uint8_t) offset);
4541
4542 /* Check if we have enough space available now. */
4543 if (desired <= (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4544 hs->buffering.total_bytes_buffered)) {
4545 MBEDTLS_SSL_DEBUG_MSG(2, ("Enough space available after freeing buffered HS messages"));
4546 return 0;
4547 }
4548 }
4549
4550 return -1;
4551}
4552
4553MBEDTLS_CHECK_RETURN_CRITICAL
4554static int ssl_buffer_message(mbedtls_ssl_context *ssl)
4555{
4556 int ret = 0;
4557 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4558
4559 if (hs == NULL) {
4560 return 0;
4561 }
4562
4563 MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_buffer_message"));
4564
4565 switch (ssl->in_msgtype) {
4566 case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
4567 MBEDTLS_SSL_DEBUG_MSG(2, ("Remember CCS message"));
4568
4569 hs->buffering.seen_ccs = 1;
4570 break;
4571
4572 case MBEDTLS_SSL_MSG_HANDSHAKE:
4573 {
4574 unsigned recv_msg_seq_offset;
4575 unsigned recv_msg_seq = MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
4576 mbedtls_ssl_hs_buffer *hs_buf;
4577 size_t msg_len = ssl->in_hslen - 12;
4578
4579 /* We should never receive an old handshake
4580 * message - double-check nonetheless. */
4581 if (recv_msg_seq < ssl->handshake->in_msg_seq) {
4582 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4583 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4584 }
4585
4586 recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
4587 if (recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS) {
4588 /* Silently ignore -- message too far in the future */
4589 MBEDTLS_SSL_DEBUG_MSG(2,
4590 ("Ignore future HS message with sequence number %u, "
4591 "buffering window %u - %u",
4592 recv_msg_seq, ssl->handshake->in_msg_seq,
4593 ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS -
4594 1));
4595
4596 goto exit;
4597 }
4598
4599 MBEDTLS_SSL_DEBUG_MSG(2, ("Buffering HS message with sequence number %u, offset %u ",
4600 recv_msg_seq, recv_msg_seq_offset));
4601
4602 hs_buf = &hs->buffering.hs[recv_msg_seq_offset];
4603
4604 /* Check if the buffering for this seq nr has already commenced. */
4605 if (!hs_buf->is_valid) {
4606 size_t reassembly_buf_sz;
4607
4608 hs_buf->is_fragmented =
4609 (ssl_hs_is_proper_fragment(ssl) == 1);
4610
4611 /* We copy the message back into the input buffer
4612 * after reassembly, so check that it's not too large.
4613 * This is an implementation-specific limitation
4614 * and not one from the standard, hence it is not
4615 * checked in ssl_check_hs_header(). */
4616 if (msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN) {
4617 /* Ignore message */
4618 goto exit;
4619 }
4620
4621 /* Check if we have enough space to buffer the message. */
4622 if (hs->buffering.total_bytes_buffered >
4623 MBEDTLS_SSL_DTLS_MAX_BUFFERING) {
4624 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4625 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4626 }
4627
4628 reassembly_buf_sz = ssl_get_reassembly_buffer_size(msg_len,
4629 hs_buf->is_fragmented);
4630
4631 if (reassembly_buf_sz > (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4632 hs->buffering.total_bytes_buffered)) {
4633 if (recv_msg_seq_offset > 0) {
4634 /* If we can't buffer a future message because
4635 * of space limitations -- ignore. */
4636 MBEDTLS_SSL_DEBUG_MSG(2,
4637 ("Buffering of future message of size %"
4638 MBEDTLS_PRINTF_SIZET
4639 " would exceed the compile-time limit %"
4640 MBEDTLS_PRINTF_SIZET
4641 " (already %" MBEDTLS_PRINTF_SIZET
4642 " bytes buffered) -- ignore\n",
4643 msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4644 hs->buffering.total_bytes_buffered));
4645 goto exit;
4646 } else {
4647 MBEDTLS_SSL_DEBUG_MSG(2,
4648 ("Buffering of future message of size %"
4649 MBEDTLS_PRINTF_SIZET
4650 " would exceed the compile-time limit %"
4651 MBEDTLS_PRINTF_SIZET
4652 " (already %" MBEDTLS_PRINTF_SIZET
4653 " bytes buffered) -- attempt to make space by freeing buffered future messages\n",
4654 msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4655 hs->buffering.total_bytes_buffered));
4656 }
4657
4658 if (ssl_buffer_make_space(ssl, reassembly_buf_sz) != 0) {
4659 MBEDTLS_SSL_DEBUG_MSG(2,
4660 ("Reassembly of next message of size %"
4661 MBEDTLS_PRINTF_SIZET
4662 " (%" MBEDTLS_PRINTF_SIZET
4663 " with bitmap) would exceed"
4664 " the compile-time limit %"
4665 MBEDTLS_PRINTF_SIZET
4666 " (already %" MBEDTLS_PRINTF_SIZET
4667 " bytes buffered) -- fail\n",
4668 msg_len,
4669 reassembly_buf_sz,
4670 (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4671 hs->buffering.total_bytes_buffered));
4672 ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
4673 goto exit;
4674 }
4675 }
4676
4677 MBEDTLS_SSL_DEBUG_MSG(2,
4678 ("initialize reassembly, total length = %"
4679 MBEDTLS_PRINTF_SIZET,
4680 msg_len));
4681
4682 hs_buf->data = mbedtls_calloc(1, reassembly_buf_sz);
4683 if (hs_buf->data == NULL) {
4684 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
4685 goto exit;
4686 }
4687 hs_buf->data_len = reassembly_buf_sz;
4688
4689 /* Prepare final header: copy msg_type, length and message_seq,
4690 * then add standardised fragment_offset and fragment_length */
4691 memcpy(hs_buf->data, ssl->in_msg, 6);
4692 memset(hs_buf->data + 6, 0, 3);
4693 memcpy(hs_buf->data + 9, hs_buf->data + 1, 3);
4694
4695 hs_buf->is_valid = 1;
4696
4697 hs->buffering.total_bytes_buffered += reassembly_buf_sz;
4698 } else {
4699 /* Make sure msg_type and length are consistent */
4700 if (memcmp(hs_buf->data, ssl->in_msg, 4) != 0) {
4701 MBEDTLS_SSL_DEBUG_MSG(1, ("Fragment header mismatch - ignore"));
4702 /* Ignore */
4703 goto exit;
4704 }
4705 }
4706
4707 if (!hs_buf->is_complete) {
4708 size_t frag_len, frag_off;
4709 unsigned char * const msg = hs_buf->data + 12;
4710
4711 /*
4712 * Check and copy current fragment
4713 */
4714
4715 /* Validation of header fields already done in
4716 * mbedtls_ssl_prepare_handshake_record(). */
4717 frag_off = ssl_get_hs_frag_off(ssl);
4718 frag_len = ssl_get_hs_frag_len(ssl);
4719
4720 MBEDTLS_SSL_DEBUG_MSG(2, ("adding fragment, offset = %" MBEDTLS_PRINTF_SIZET
4721 ", length = %" MBEDTLS_PRINTF_SIZET,
4722 frag_off, frag_len));
4723 memcpy(msg + frag_off, ssl->in_msg + 12, frag_len);
4724
4725 if (hs_buf->is_fragmented) {
4726 unsigned char * const bitmask = msg + msg_len;
4727 ssl_bitmask_set(bitmask, frag_off, frag_len);
4728 hs_buf->is_complete = (ssl_bitmask_check(bitmask,
4729 msg_len) == 0);
4730 } else {
4731 hs_buf->is_complete = 1;
4732 }
4733
4734 MBEDTLS_SSL_DEBUG_MSG(2, ("message %scomplete",
4735 hs_buf->is_complete ? "" : "not yet "));
4736 }
4737
4738 break;
4739 }
4740
4741 default:
4742 /* We don't buffer other types of messages. */
4743 break;
4744 }
4745
4746exit:
4747
4748 MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_buffer_message"));
4749 return ret;
4750}
4751#endif /* MBEDTLS_SSL_PROTO_DTLS */
4752
4753MBEDTLS_CHECK_RETURN_CRITICAL
4754static int ssl_consume_current_message(mbedtls_ssl_context *ssl)
4755{
4756 /*
4757 * Consume last content-layer message and potentially
4758 * update in_msglen which keeps track of the contents'
4759 * consumption state.
4760 *
4761 * (1) Handshake messages:
4762 * Remove last handshake message, move content
4763 * and adapt in_msglen.
4764 *
4765 * (2) Alert messages:
4766 * Consume whole record content, in_msglen = 0.
4767 *
4768 * (3) Change cipher spec:
4769 * Consume whole record content, in_msglen = 0.
4770 *
4771 * (4) Application data:
4772 * Don't do anything - the record layer provides
4773 * the application data as a stream transport
4774 * and consumes through mbedtls_ssl_read only.
4775 *
4776 */
4777
4778 /* Case (1): Handshake messages */
4779 if (ssl->in_hslen != 0) {
4780 /* Hard assertion to be sure that no application data
4781 * is in flight, as corrupting ssl->in_msglen during
4782 * ssl->in_offt != NULL is fatal. */
4783 if (ssl->in_offt != NULL) {
4784 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4785 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4786 }
4787
4788 if (ssl->badmac_seen_or_in_hsfraglen != 0) {
4789 /* Not all handshake fragments have arrived, do not consume. */
4790 MBEDTLS_SSL_DEBUG_MSG(3, ("Consume: waiting for more handshake fragments "
4791 "%u/%" MBEDTLS_PRINTF_SIZET,
4792 ssl->badmac_seen_or_in_hsfraglen, ssl->in_hslen));
4793 return 0;
4794 }
4795
4796 /*
4797 * Get next Handshake message in the current record
4798 */
4799
4800 /* Notes:
4801 * (1) in_hslen is not necessarily the size of the
4802 * current handshake content: If DTLS handshake
4803 * fragmentation is used, that's the fragment
4804 * size instead. Using the total handshake message
4805 * size here is faulty and should be changed at
4806 * some point.
4807 * (2) While it doesn't seem to cause problems, one
4808 * has to be very careful not to assume that in_hslen
4809 * is always <= in_msglen in a sensible communication.
4810 * Again, it's wrong for DTLS handshake fragmentation.
4811 * The following check is therefore mandatory, and
4812 * should not be treated as a silently corrected assertion.
4813 * Additionally, ssl->in_hslen might be arbitrarily out of
4814 * bounds after handling a DTLS message with an unexpected
4815 * sequence number, see mbedtls_ssl_prepare_handshake_record.
4816 */
4817 if (ssl->in_hslen < ssl->in_msglen) {
4818 ssl->in_msglen -= ssl->in_hslen;
4819 memmove(ssl->in_msg, ssl->in_msg + ssl->in_hslen,
4820 ssl->in_msglen);
4821 MBEDTLS_PUT_UINT16_BE(ssl->in_msglen, ssl->in_len, 0);
4822
4823 MBEDTLS_SSL_DEBUG_BUF(4, "remaining content in record",
4824 ssl->in_msg, ssl->in_msglen);
4825 } else {
4826 ssl->in_msglen = 0;
4827 }
4828
4829 ssl->in_hslen = 0;
4830 }
4831 /* Case (4): Application data */
4832 else if (ssl->in_offt != NULL) {
4833 return 0;
4834 }
4835 /* Everything else (CCS & Alerts) */
4836 else {
4837 ssl->in_msglen = 0;
4838 }
4839
4840 return 0;
4841}
4842
4843MBEDTLS_CHECK_RETURN_CRITICAL
4844static int ssl_record_is_in_progress(mbedtls_ssl_context *ssl)
4845{
4846 if (ssl->in_msglen > 0) {
4847 return 1;
4848 }
4849
4850 return 0;
4851}
4852
4853#if defined(MBEDTLS_SSL_PROTO_DTLS)
4854
4855static void ssl_free_buffered_record(mbedtls_ssl_context *ssl)
4856{
4857 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4858 if (hs == NULL) {
4859 return;
4860 }
4861
4862 if (hs->buffering.future_record.data != NULL) {
4863 hs->buffering.total_bytes_buffered -=
4864 hs->buffering.future_record.len;
4865
4866 mbedtls_free(hs->buffering.future_record.data);
4867 hs->buffering.future_record.data = NULL;
4868 }
4869}
4870
4871MBEDTLS_CHECK_RETURN_CRITICAL
4872static int ssl_load_buffered_record(mbedtls_ssl_context *ssl)
4873{
4874 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4875 unsigned char *rec;
4876 size_t rec_len;
4877 unsigned rec_epoch;
4878#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
4879 size_t in_buf_len = ssl->in_buf_len;
4880#else
4881 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
4882#endif
4883 if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4884 return 0;
4885 }
4886
4887 if (hs == NULL) {
4888 return 0;
4889 }
4890
4891 rec = hs->buffering.future_record.data;
4892 rec_len = hs->buffering.future_record.len;
4893 rec_epoch = hs->buffering.future_record.epoch;
4894
4895 if (rec == NULL) {
4896 return 0;
4897 }
4898
4899 /* Only consider loading future records if the
4900 * input buffer is empty. */
4901 if (ssl_next_record_is_in_datagram(ssl) == 1) {
4902 return 0;
4903 }
4904
4905 MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_load_buffered_record"));
4906
4907 if (rec_epoch != ssl->in_epoch) {
4908 MBEDTLS_SSL_DEBUG_MSG(2, ("Buffered record not from current epoch."));
4909 goto exit;
4910 }
4911
4912 MBEDTLS_SSL_DEBUG_MSG(2, ("Found buffered record from current epoch - load"));
4913
4914 /* Double-check that the record is not too large */
4915 if (rec_len > in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf)) {
4916 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4917 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4918 }
4919
4920 memcpy(ssl->in_hdr, rec, rec_len);
4921 ssl->in_left = rec_len;
4922 ssl->next_record_offset = 0;
4923
4924 ssl_free_buffered_record(ssl);
4925
4926exit:
4927 MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_load_buffered_record"));
4928 return 0;
4929}
4930
4931MBEDTLS_CHECK_RETURN_CRITICAL
4932static int ssl_buffer_future_record(mbedtls_ssl_context *ssl,
4933 mbedtls_record const *rec)
4934{
4935 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4936
4937 /* Don't buffer future records outside handshakes. */
4938 if (hs == NULL) {
4939 return 0;
4940 }
4941
4942 /* Only buffer handshake records (we are only interested
4943 * in Finished messages). */
4944 if (rec->type != MBEDTLS_SSL_MSG_HANDSHAKE) {
4945 return 0;
4946 }
4947
4948 /* Don't buffer more than one future epoch record. */
4949 if (hs->buffering.future_record.data != NULL) {
4950 return 0;
4951 }
4952
4953 /* Don't buffer record if there's not enough buffering space remaining. */
4954 if (rec->buf_len > (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4955 hs->buffering.total_bytes_buffered)) {
4956 MBEDTLS_SSL_DEBUG_MSG(2, ("Buffering of future epoch record of size %" MBEDTLS_PRINTF_SIZET
4957 " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET
4958 " (already %" MBEDTLS_PRINTF_SIZET
4959 " bytes buffered) -- ignore\n",
4960 rec->buf_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4961 hs->buffering.total_bytes_buffered));
4962 return 0;
4963 }
4964
4965 /* Buffer record */
4966 MBEDTLS_SSL_DEBUG_MSG(2, ("Buffer record from epoch %u",
4967 ssl->in_epoch + 1U));
4968 MBEDTLS_SSL_DEBUG_BUF(3, "Buffered record", rec->buf, rec->buf_len);
4969
4970 /* ssl_parse_record_header() only considers records
4971 * of the next epoch as candidates for buffering. */
4972 hs->buffering.future_record.epoch = ssl->in_epoch + 1;
4973 hs->buffering.future_record.len = rec->buf_len;
4974
4975 hs->buffering.future_record.data =
4976 mbedtls_calloc(1, hs->buffering.future_record.len);
4977 if (hs->buffering.future_record.data == NULL) {
4978 /* If we run out of RAM trying to buffer a
4979 * record from the next epoch, just ignore. */
4980 return 0;
4981 }
4982
4983 memcpy(hs->buffering.future_record.data, rec->buf, rec->buf_len);
4984
4985 hs->buffering.total_bytes_buffered += rec->buf_len;
4986 return 0;
4987}
4988
4989#endif /* MBEDTLS_SSL_PROTO_DTLS */
4990
4991MBEDTLS_CHECK_RETURN_CRITICAL
4992static int ssl_get_next_record(mbedtls_ssl_context *ssl)
4993{
4994 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4995 mbedtls_record rec;
4996
4997#if defined(MBEDTLS_SSL_PROTO_DTLS)
4998 /* We might have buffered a future record; if so,
4999 * and if the epoch matches now, load it.
5000 * On success, this call will set ssl->in_left to
5001 * the length of the buffered record, so that
5002 * the calls to ssl_fetch_input() below will
5003 * essentially be no-ops. */
5004 ret = ssl_load_buffered_record(ssl);
5005 if (ret != 0) {
5006 return ret;
5007 }
5008#endif /* MBEDTLS_SSL_PROTO_DTLS */
5009
5010 /* Ensure that we have enough space available for the default form
5011 * of TLS / DTLS record headers (5 Bytes for TLS, 13 Bytes for DTLS,
5012 * with no space for CIDs counted in). */
5013 ret = mbedtls_ssl_fetch_input(ssl, mbedtls_ssl_in_hdr_len(ssl));
5014 if (ret != 0) {
5015 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
5016 return ret;
5017 }
5018
5019 ret = ssl_parse_record_header(ssl, ssl->in_hdr, ssl->in_left, &rec);
5020 if (ret != 0) {
5021#if defined(MBEDTLS_SSL_PROTO_DTLS)
5022 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5023 if (ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
5024 ret = ssl_buffer_future_record(ssl, &rec);
5025 if (ret != 0) {
5026 return ret;
5027 }
5028
5029 /* Fall through to handling of unexpected records */
5030 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
5031 }
5032
5033#if defined(MBEDTLS_SSL_SRV_C)
5034 /*
5035 * In DTLS, invalid records are usually ignored because it is easy
5036 * for an attacker to inject UDP datagrams, and we do not want such
5037 * packets to disrupt the entire connection.
5038 *
5039 * However, when expecting the ClientHello, we reject invalid or
5040 * unexpected records. This avoids waiting for further records
5041 * before receiving at least one valid message. Such records could
5042 * be leftover messages from a previous connection, accidental
5043 * input, or part of a DoS attempt.
5044 *
5045 * Since no valid message has been received yet, immediately
5046 * closing the connection does not result in any loss.
5047 */
5048 if ((ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) &&
5049 (ssl->state == MBEDTLS_SSL_CLIENT_HELLO)
5050#if defined(MBEDTLS_SSL_RENEGOTIATION)
5051 && (ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE)
5052#endif
5053 ) {
5054 return ret;
5055 }
5056#endif /* MBEDTLS_SSL_SRV_C */
5057
5058 if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) {
5059#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
5060 /* Reset in pointers to default state for TLS/DTLS records,
5061 * assuming no CID and no offset between record content and
5062 * record plaintext. */
5063 mbedtls_ssl_update_in_pointers(ssl);
5064
5065 /* Setup internal message pointers from record structure. */
5066 ssl->in_msgtype = rec.type;
5067#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5068 ssl->in_len = ssl->in_cid + rec.cid_len;
5069#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5070 ssl->in_iv = ssl->in_msg = ssl->in_len + 2;
5071 ssl->in_msglen = rec.data_len;
5072
5073 ret = ssl_check_client_reconnect(ssl);
5074 MBEDTLS_SSL_DEBUG_RET(2, "ssl_check_client_reconnect", ret);
5075 if (ret != 0) {
5076 return ret;
5077 }
5078#endif
5079
5080 /* Skip unexpected record (but not whole datagram) */
5081 ssl->next_record_offset = rec.buf_len;
5082
5083 MBEDTLS_SSL_DEBUG_MSG(1, ("discarding unexpected record "
5084 "(header)"));
5085 } else {
5086 /* Skip invalid record and the rest of the datagram */
5087 ssl->next_record_offset = 0;
5088 ssl->in_left = 0;
5089
5090 MBEDTLS_SSL_DEBUG_MSG(1, ("discarding invalid record "
5091 "(header)"));
5092 }
5093
5094 /* Get next record */
5095 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
5096 } else
5097#endif
5098 {
5099 return ret;
5100 }
5101 }
5102
5103#if defined(MBEDTLS_SSL_PROTO_DTLS)
5104 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5105 /* Remember offset of next record within datagram. */
5106 ssl->next_record_offset = rec.buf_len;
5107 if (ssl->next_record_offset < ssl->in_left) {
5108 MBEDTLS_SSL_DEBUG_MSG(3, ("more than one record within datagram"));
5109 }
5110 } else
5111#endif
5112 {
5113 /*
5114 * Fetch record contents from underlying transport.
5115 */
5116 ret = mbedtls_ssl_fetch_input(ssl, rec.buf_len);
5117 if (ret != 0) {
5118 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
5119 return ret;
5120 }
5121
5122 ssl->in_left = 0;
5123 }
5124
5125 /*
5126 * Decrypt record contents.
5127 */
5128
5129 if ((ret = ssl_prepare_record_content(ssl, &rec)) != 0) {
5130#if defined(MBEDTLS_SSL_PROTO_DTLS)
5131 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5132 /* Silently discard invalid records */
5133 if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
5134 /* Except when waiting for Finished as a bad mac here
5135 * probably means something went wrong in the handshake
5136 * (eg wrong psk used, mitm downgrade attempt, etc.) */
5137 if (ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
5138 ssl->state == MBEDTLS_SSL_SERVER_FINISHED) {
5139#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
5140 if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
5141 mbedtls_ssl_send_alert_message(ssl,
5142 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5143 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC);
5144 }
5145#endif
5146 return ret;
5147 }
5148
5149 if (ssl->conf->badmac_limit != 0) {
5150 ++ssl->badmac_seen_or_in_hsfraglen;
5151 if (ssl->badmac_seen_or_in_hsfraglen >= ssl->conf->badmac_limit) {
5152 MBEDTLS_SSL_DEBUG_MSG(1, ("too many records with bad MAC"));
5153 return MBEDTLS_ERR_SSL_INVALID_MAC;
5154 }
5155 }
5156
5157 /* As above, invalid records cause
5158 * dismissal of the whole datagram. */
5159
5160 ssl->next_record_offset = 0;
5161 ssl->in_left = 0;
5162
5163 MBEDTLS_SSL_DEBUG_MSG(1, ("discarding invalid record (mac)"));
5164 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
5165 }
5166
5167 return ret;
5168 } else
5169#endif
5170 {
5171 /* Error out (and send alert) on invalid records */
5172#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
5173 if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
5174 mbedtls_ssl_send_alert_message(ssl,
5175 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5176 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC);
5177 }
5178#endif
5179 return ret;
5180 }
5181 }
5182
5183
5184 /* Reset in pointers to default state for TLS/DTLS records,
5185 * assuming no CID and no offset between record content and
5186 * record plaintext. */
5187 mbedtls_ssl_update_in_pointers(ssl);
5188#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5189 ssl->in_len = ssl->in_cid + rec.cid_len;
5190#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5191 ssl->in_iv = ssl->in_len + 2;
5192
5193 /* The record content type may change during decryption,
5194 * so re-read it. */
5195 ssl->in_msgtype = rec.type;
5196
5197 ssl->in_msg = rec.buf + rec.data_offset;
5198 ssl->in_msglen = rec.data_len;
5199
5200 return 0;
5201}
5202
5203int mbedtls_ssl_handle_message_type(mbedtls_ssl_context *ssl)
5204{
5205 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5206
5207 /* If we're in the middle of a fragmented TLS handshake message,
5208 * we don't accept any other message type. For TLS 1.3, the spec forbids
5209 * interleaving other message types between handshake fragments. For TLS
5210 * 1.2, the spec does not forbid it but we do. */
5211 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM &&
5212 ssl->badmac_seen_or_in_hsfraglen != 0 &&
5213 ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
5214 MBEDTLS_SSL_DEBUG_MSG(1, ("non-handshake message in the middle"
5215 " of a fragmented handshake message"));
5216 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5217 }
5218
5219 /*
5220 * Handle particular types of records
5221 */
5222 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
5223 if ((ret = mbedtls_ssl_prepare_handshake_record(ssl)) != 0) {
5224 return ret;
5225 }
5226 }
5227
5228 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
5229 if (ssl->in_msglen != 1) {
5230 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid CCS message, len: %" MBEDTLS_PRINTF_SIZET,
5231 ssl->in_msglen));
5232 return MBEDTLS_ERR_SSL_INVALID_RECORD;
5233 }
5234
5235 if (ssl->in_msg[0] != 1) {
5236 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid CCS message, content: %02x",
5237 ssl->in_msg[0]));
5238 return MBEDTLS_ERR_SSL_INVALID_RECORD;
5239 }
5240
5241#if defined(MBEDTLS_SSL_PROTO_DTLS)
5242 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5243 ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
5244 ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC) {
5245 if (ssl->handshake == NULL) {
5246 MBEDTLS_SSL_DEBUG_MSG(1, ("dropping ChangeCipherSpec outside handshake"));
5247 return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
5248 }
5249
5250 MBEDTLS_SSL_DEBUG_MSG(1, ("received out-of-order ChangeCipherSpec - remember"));
5251 return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
5252 }
5253#endif
5254
5255#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
5256 if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
5257 MBEDTLS_SSL_DEBUG_MSG(2,
5258 ("Ignore ChangeCipherSpec in TLS 1.3 compatibility mode"));
5259 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
5260 }
5261#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
5262 }
5263
5264 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT) {
5265 if (ssl->in_msglen != 2) {
5266 /* Note: Standard allows for more than one 2 byte alert
5267 to be packed in a single message, but Mbed TLS doesn't
5268 currently support this. */
5269 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid alert message, len: %" MBEDTLS_PRINTF_SIZET,
5270 ssl->in_msglen));
5271 return MBEDTLS_ERR_SSL_INVALID_RECORD;
5272 }
5273
5274 MBEDTLS_SSL_DEBUG_MSG(2, ("got an alert message, type: [%u:%u]",
5275 ssl->in_msg[0], ssl->in_msg[1]));
5276
5277 /*
5278 * Ignore non-fatal alerts, except close_notify and no_renegotiation
5279 */
5280 if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL) {
5281 MBEDTLS_SSL_DEBUG_MSG(1, ("is a fatal alert message (msg %d)",
5282 ssl->in_msg[1]));
5283 return MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE;
5284 }
5285
5286 if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
5287 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY) {
5288 MBEDTLS_SSL_DEBUG_MSG(2, ("is a close notify message"));
5289 return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY;
5290 }
5291
5292#if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
5293 if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
5294 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION) {
5295 MBEDTLS_SSL_DEBUG_MSG(2, ("is a no renegotiation alert"));
5296 /* Will be handled when trying to parse ServerHello */
5297 return 0;
5298 }
5299#endif
5300 /* Silently ignore: fetch new message */
5301 return MBEDTLS_ERR_SSL_NON_FATAL;
5302 }
5303
5304#if defined(MBEDTLS_SSL_PROTO_DTLS)
5305 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5306 /* Drop unexpected ApplicationData records,
5307 * except at the beginning of renegotiations */
5308 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
5309 mbedtls_ssl_is_handshake_over(ssl) == 0
5310#if defined(MBEDTLS_SSL_RENEGOTIATION)
5311 && !(ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
5312 ssl->state == MBEDTLS_SSL_SERVER_HELLO)
5313#endif
5314 ) {
5315 MBEDTLS_SSL_DEBUG_MSG(1, ("dropping unexpected ApplicationData"));
5316 return MBEDTLS_ERR_SSL_NON_FATAL;
5317 }
5318
5319 if (ssl->handshake != NULL &&
5320 mbedtls_ssl_is_handshake_over(ssl) == 1) {
5321 mbedtls_ssl_handshake_wrapup_free_hs_transform(ssl);
5322 }
5323 }
5324#endif /* MBEDTLS_SSL_PROTO_DTLS */
5325
5326 return 0;
5327}
5328
5329int mbedtls_ssl_send_fatal_handshake_failure(mbedtls_ssl_context *ssl)
5330{
5331 return mbedtls_ssl_send_alert_message(ssl,
5332 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5333 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
5334}
5335
5336int mbedtls_ssl_send_alert_message(mbedtls_ssl_context *ssl,
5337 unsigned char level,
5338 unsigned char message)
5339{
5340 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5341
5342 if (ssl == NULL || ssl->conf == NULL) {
5343 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5344 }
5345
5346 if (ssl->out_left != 0) {
5347 return mbedtls_ssl_flush_output(ssl);
5348 }
5349
5350 MBEDTLS_SSL_DEBUG_MSG(2, ("=> send alert message"));
5351 MBEDTLS_SSL_DEBUG_MSG(3, ("send alert level=%u message=%u", level, message));
5352
5353 ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
5354 ssl->out_msglen = 2;
5355 ssl->out_msg[0] = level;
5356 ssl->out_msg[1] = message;
5357
5358 if ((ret = mbedtls_ssl_write_record(ssl, SSL_FORCE_FLUSH)) != 0) {
5359 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
5360 return ret;
5361 }
5362 MBEDTLS_SSL_DEBUG_MSG(2, ("<= send alert message"));
5363
5364 return 0;
5365}
5366
5367int mbedtls_ssl_write_change_cipher_spec(mbedtls_ssl_context *ssl)
5368{
5369 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5370
5371 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write change cipher spec"));
5372
5373 ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
5374 ssl->out_msglen = 1;
5375 ssl->out_msg[0] = 1;
5376
5377 mbedtls_ssl_handshake_increment_state(ssl);
5378
5379 if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
5380 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
5381 return ret;
5382 }
5383
5384 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write change cipher spec"));
5385
5386 return 0;
5387}
5388
5389int mbedtls_ssl_parse_change_cipher_spec(mbedtls_ssl_context *ssl)
5390{
5391 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5392
5393 MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse change cipher spec"));
5394
5395 if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
5396 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
5397 return ret;
5398 }
5399
5400 if (ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
5401 MBEDTLS_SSL_DEBUG_MSG(1, ("bad change cipher spec message"));
5402 mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5403 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
5404 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5405 }
5406
5407 /* CCS records are only accepted if they have length 1 and content '1',
5408 * so we don't need to check this here. */
5409
5410 /*
5411 * Switch to our negotiated transform and session parameters for inbound
5412 * data.
5413 */
5414 MBEDTLS_SSL_DEBUG_MSG(3, ("switching to new transform spec for inbound data"));
5415#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5416 ssl->transform_in = ssl->transform_negotiate;
5417#endif
5418 ssl->session_in = ssl->session_negotiate;
5419
5420#if defined(MBEDTLS_SSL_PROTO_DTLS)
5421 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5422#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5423 mbedtls_ssl_dtls_replay_reset(ssl);
5424#endif
5425
5426 /* Increment epoch */
5427 if (++ssl->in_epoch == 0) {
5428 MBEDTLS_SSL_DEBUG_MSG(1, ("DTLS epoch would wrap"));
5429 /* This is highly unlikely to happen for legitimate reasons, so
5430 treat it as an attack and don't send an alert. */
5431 return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
5432 }
5433 } else
5434#endif /* MBEDTLS_SSL_PROTO_DTLS */
5435 memset(ssl->in_ctr, 0, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
5436
5437 mbedtls_ssl_update_in_pointers(ssl);
5438
5439 mbedtls_ssl_handshake_increment_state(ssl);
5440
5441 MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse change cipher spec"));
5442
5443 return 0;
5444}
5445
5446/* Once ssl->out_hdr as the address of the beginning of the
5447 * next outgoing record is set, deduce the other pointers.
5448 *
5449 * Note: For TLS, we save the implicit record sequence number
5450 * (entering MAC computation) in the 8 bytes before ssl->out_hdr,
5451 * and the caller has to make sure there's space for this.
5452 */
5453
5454static size_t ssl_transform_get_explicit_iv_len(
5455 mbedtls_ssl_transform const *transform)
5456{
5457 return transform->ivlen - transform->fixed_ivlen;
5458}
5459
5460void mbedtls_ssl_update_out_pointers(mbedtls_ssl_context *ssl,
5461 mbedtls_ssl_transform *transform)
5462{
5463#if defined(MBEDTLS_SSL_PROTO_DTLS)
5464 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5465 ssl->out_ctr = ssl->out_hdr + 3;
5466#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5467 ssl->out_cid = ssl->out_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5468 ssl->out_len = ssl->out_cid;
5469 if (transform != NULL) {
5470 ssl->out_len += transform->out_cid_len;
5471 }
5472#else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5473 ssl->out_len = ssl->out_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5474#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5475 ssl->out_iv = ssl->out_len + 2;
5476 } else
5477#endif
5478 {
5479 ssl->out_len = ssl->out_hdr + 3;
5480#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5481 ssl->out_cid = ssl->out_len;
5482#endif
5483 ssl->out_iv = ssl->out_hdr + 5;
5484 }
5485
5486 ssl->out_msg = ssl->out_iv;
5487 /* Adjust out_msg to make space for explicit IV, if used. */
5488 if (transform != NULL) {
5489 ssl->out_msg += ssl_transform_get_explicit_iv_len(transform);
5490 }
5491}
5492
5493/* Once ssl->in_hdr as the address of the beginning of the
5494 * next incoming record is set, deduce the other pointers.
5495 *
5496 * Note: For TLS, we save the implicit record sequence number
5497 * (entering MAC computation) in the 8 bytes before ssl->in_hdr,
5498 * and the caller has to make sure there's space for this.
5499 */
5500
5501void mbedtls_ssl_update_in_pointers(mbedtls_ssl_context *ssl)
5502{
5503 /* This function sets the pointers to match the case
5504 * of unprotected TLS/DTLS records, with both ssl->in_iv
5505 * and ssl->in_msg pointing to the beginning of the record
5506 * content.
5507 *
5508 * When decrypting a protected record, ssl->in_msg
5509 * will be shifted to point to the beginning of the
5510 * record plaintext.
5511 */
5512
5513#if defined(MBEDTLS_SSL_PROTO_DTLS)
5514 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5515 /* This sets the header pointers to match records
5516 * without CID. When we receive a record containing
5517 * a CID, the fields are shifted accordingly in
5518 * ssl_parse_record_header(). */
5519 ssl->in_ctr = ssl->in_hdr + 3;
5520#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5521 ssl->in_cid = ssl->in_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5522 ssl->in_len = ssl->in_cid; /* Default: no CID */
5523#else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5524 ssl->in_len = ssl->in_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5525#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5526 ssl->in_iv = ssl->in_len + 2;
5527 } else
5528#endif
5529 {
5530 ssl->in_ctr = ssl->in_buf;
5531 ssl->in_len = ssl->in_hdr + 3;
5532#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5533 ssl->in_cid = ssl->in_len;
5534#endif
5535 ssl->in_iv = ssl->in_hdr + 5;
5536 }
5537
5538 /* This will be adjusted at record decryption time. */
5539 ssl->in_msg = ssl->in_iv;
5540}
5541
5542/*
5543 * Setup an SSL context
5544 */
5545
5546void mbedtls_ssl_reset_in_pointers(mbedtls_ssl_context *ssl)
5547{
5548#if defined(MBEDTLS_SSL_PROTO_DTLS)
5549 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5550 ssl->in_hdr = ssl->in_buf;
5551 } else
5552#endif /* MBEDTLS_SSL_PROTO_DTLS */
5553 {
5554 ssl->in_hdr = ssl->in_buf + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5555 }
5556
5557 /* Derive other internal pointers. */
5558 mbedtls_ssl_update_in_pointers(ssl);
5559}
5560
5561void mbedtls_ssl_reset_out_pointers(mbedtls_ssl_context *ssl)
5562{
5563 /* Set the incoming and outgoing record pointers. */
5564#if defined(MBEDTLS_SSL_PROTO_DTLS)
5565 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5566 ssl->out_hdr = ssl->out_buf;
5567 } else
5568#endif /* MBEDTLS_SSL_PROTO_DTLS */
5569 {
5570 ssl->out_ctr = ssl->out_buf;
5571 ssl->out_hdr = ssl->out_buf + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5572 }
5573 /* Derive other internal pointers. */
5574 mbedtls_ssl_update_out_pointers(ssl, NULL /* no transform enabled */);
5575}
5576
5577/*
5578 * SSL get accessors
5579 */
5580size_t mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context *ssl)
5581{
5582 return ssl->in_offt == NULL ? 0 : ssl->in_msglen;
5583}
5584
5585int mbedtls_ssl_check_pending(const mbedtls_ssl_context *ssl)
5586{
5587 /*
5588 * Case A: We're currently holding back
5589 * a message for further processing.
5590 */
5591
5592 if (ssl->keep_current_message == 1) {
5593 MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: record held back for processing"));
5594 return 1;
5595 }
5596
5597 /*
5598 * Case B: Further records are pending in the current datagram.
5599 */
5600
5601#if defined(MBEDTLS_SSL_PROTO_DTLS)
5602 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5603 ssl->in_left > ssl->next_record_offset) {
5604 MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: more records within current datagram"));
5605 return 1;
5606 }
5607#endif /* MBEDTLS_SSL_PROTO_DTLS */
5608
5609 /*
5610 * Case C: A handshake message is being processed.
5611 */
5612
5613 if (ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen) {
5614 MBEDTLS_SSL_DEBUG_MSG(3,
5615 ("ssl_check_pending: more handshake messages within current record"));
5616 return 1;
5617 }
5618
5619 /*
5620 * Case D: An application data message is being processed
5621 */
5622 if (ssl->in_offt != NULL) {
5623 MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: application data record is being processed"));
5624 return 1;
5625 }
5626
5627 /*
5628 * In all other cases, the rest of the message can be dropped.
5629 * As in ssl_get_next_record, this needs to be adapted if
5630 * we implement support for multiple alerts in single records.
5631 */
5632
5633 MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: nothing pending"));
5634 return 0;
5635}
5636
5637
5638int mbedtls_ssl_get_record_expansion(const mbedtls_ssl_context *ssl)
5639{
5640 size_t transform_expansion = 0;
5641 const mbedtls_ssl_transform *transform = ssl->transform_out;
5642 unsigned block_size;
5643#if defined(MBEDTLS_USE_PSA_CRYPTO)
5644 psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;
5645 psa_key_type_t key_type;
5646#endif /* MBEDTLS_USE_PSA_CRYPTO */
5647
5648 size_t out_hdr_len = mbedtls_ssl_out_hdr_len(ssl);
5649
5650 if (transform == NULL) {
5651 return (int) out_hdr_len;
5652 }
5653
5654
5655#if defined(MBEDTLS_USE_PSA_CRYPTO)
5656 if (transform->psa_alg == PSA_ALG_GCM ||
5657 transform->psa_alg == PSA_ALG_CCM ||
5658 transform->psa_alg == PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 8) ||
5659 transform->psa_alg == PSA_ALG_CHACHA20_POLY1305 ||
5660 transform->psa_alg == MBEDTLS_SSL_NULL_CIPHER) {
5661 transform_expansion = transform->minlen;
5662 } else if (transform->psa_alg == PSA_ALG_CBC_NO_PADDING) {
5663 (void) psa_get_key_attributes(transform->psa_key_enc, &attr);
5664 key_type = psa_get_key_type(&attr);
5665
5666 block_size = PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type);
5667
5668 /* Expansion due to the addition of the MAC. */
5669 transform_expansion += transform->maclen;
5670
5671 /* Expansion due to the addition of CBC padding;
5672 * Theoretically up to 256 bytes, but we never use
5673 * more than the block size of the underlying cipher. */
5674 transform_expansion += block_size;
5675
5676 /* For TLS 1.2 or higher, an explicit IV is added
5677 * after the record header. */
5678#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5679 transform_expansion += block_size;
5680#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5681 } else {
5682 MBEDTLS_SSL_DEBUG_MSG(1,
5683 ("Unsupported psa_alg spotted in mbedtls_ssl_get_record_expansion()"));
5684 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
5685 }
5686#else
5687 switch (mbedtls_cipher_get_cipher_mode(&transform->cipher_ctx_enc)) {
5688 case MBEDTLS_MODE_GCM:
5689 case MBEDTLS_MODE_CCM:
5690 case MBEDTLS_MODE_CHACHAPOLY:
5691 case MBEDTLS_MODE_STREAM:
5692 transform_expansion = transform->minlen;
5693 break;
5694
5695 case MBEDTLS_MODE_CBC:
5696
5697 block_size = mbedtls_cipher_get_block_size(
5698 &transform->cipher_ctx_enc);
5699
5700 /* Expansion due to the addition of the MAC. */
5701 transform_expansion += transform->maclen;
5702
5703 /* Expansion due to the addition of CBC padding;
5704 * Theoretically up to 256 bytes, but we never use
5705 * more than the block size of the underlying cipher. */
5706 transform_expansion += block_size;
5707
5708 /* For TLS 1.2 or higher, an explicit IV is added
5709 * after the record header. */
5710#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5711 transform_expansion += block_size;
5712#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5713
5714 break;
5715
5716 default:
5717 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
5718 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
5719 }
5720#endif /* MBEDTLS_USE_PSA_CRYPTO */
5721
5722#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5723 if (transform->out_cid_len != 0) {
5724 transform_expansion += MBEDTLS_SSL_MAX_CID_EXPANSION;
5725 }
5726#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5727
5728 return (int) (out_hdr_len + transform_expansion);
5729}
5730
5731#if defined(MBEDTLS_SSL_RENEGOTIATION)
5732/*
5733 * Check record counters and renegotiate if they're above the limit.
5734 */
5735MBEDTLS_CHECK_RETURN_CRITICAL
5736static int ssl_check_ctr_renegotiate(mbedtls_ssl_context *ssl)
5737{
5738 size_t ep_len = mbedtls_ssl_ep_len(ssl);
5739 int in_ctr_cmp;
5740 int out_ctr_cmp;
5741
5742 if (mbedtls_ssl_is_handshake_over(ssl) == 0 ||
5743 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
5744 ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED) {
5745 return 0;
5746 }
5747
5748 in_ctr_cmp = memcmp(ssl->in_ctr + ep_len,
5749 &ssl->conf->renego_period[ep_len],
5750 MBEDTLS_SSL_SEQUENCE_NUMBER_LEN - ep_len);
5751 out_ctr_cmp = memcmp(&ssl->cur_out_ctr[ep_len],
5752 &ssl->conf->renego_period[ep_len],
5753 sizeof(ssl->cur_out_ctr) - ep_len);
5754
5755 if (in_ctr_cmp <= 0 && out_ctr_cmp <= 0) {
5756 return 0;
5757 }
5758
5759 MBEDTLS_SSL_DEBUG_MSG(1, ("record counter limit reached: renegotiate"));
5760 return mbedtls_ssl_renegotiate(ssl);
5761}
5762#endif /* MBEDTLS_SSL_RENEGOTIATION */
5763
5764#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
5765
5766#if defined(MBEDTLS_SSL_CLI_C)
5767MBEDTLS_CHECK_RETURN_CRITICAL
5768static int ssl_tls13_is_new_session_ticket(mbedtls_ssl_context *ssl)
5769{
5770
5771 if ((ssl->in_hslen == mbedtls_ssl_hs_hdr_len(ssl)) ||
5772 (ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET)) {
5773 return 0;
5774 }
5775
5776 return 1;
5777}
5778#endif /* MBEDTLS_SSL_CLI_C */
5779
5780MBEDTLS_CHECK_RETURN_CRITICAL
5781static int ssl_tls13_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
5782{
5783
5784 MBEDTLS_SSL_DEBUG_MSG(3, ("received post-handshake message"));
5785
5786#if defined(MBEDTLS_SSL_CLI_C)
5787 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
5788 if (ssl_tls13_is_new_session_ticket(ssl)) {
5789#if defined(MBEDTLS_SSL_SESSION_TICKETS)
5790 MBEDTLS_SSL_DEBUG_MSG(3, ("NewSessionTicket received"));
5791 if (mbedtls_ssl_conf_is_signal_new_session_tickets_enabled(ssl->conf) ==
5792 MBEDTLS_SSL_TLS1_3_SIGNAL_NEW_SESSION_TICKETS_ENABLED) {
5793 ssl->keep_current_message = 1;
5794
5795 mbedtls_ssl_handshake_set_state(ssl,
5796 MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET);
5797 return MBEDTLS_ERR_SSL_WANT_READ;
5798 } else {
5799 MBEDTLS_SSL_DEBUG_MSG(3, ("Ignoring NewSessionTicket, handling disabled."));
5800 return 0;
5801 }
5802#else
5803 MBEDTLS_SSL_DEBUG_MSG(3, ("Ignoring NewSessionTicket, not supported."));
5804 return 0;
5805#endif
5806 }
5807 }
5808#endif /* MBEDTLS_SSL_CLI_C */
5809
5810 /* Fail in all other cases. */
5811 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5812}
5813#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
5814
5815#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5816/* This function is called from mbedtls_ssl_read() when a handshake message is
5817 * received after the initial handshake. In this context, handshake messages
5818 * may only be sent for the purpose of initiating renegotiations.
5819 *
5820 * This function is introduced as a separate helper since the handling
5821 * of post-handshake handshake messages changes significantly in TLS 1.3,
5822 * and having a helper function allows to distinguish between TLS <= 1.2 and
5823 * TLS 1.3 in the future without bloating the logic of mbedtls_ssl_read().
5824 */
5825MBEDTLS_CHECK_RETURN_CRITICAL
5826static int ssl_tls12_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
5827{
5828 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5829
5830 /*
5831 * - For client-side, expect SERVER_HELLO_REQUEST.
5832 * - For server-side, expect CLIENT_HELLO.
5833 * - Fail (TLS) or silently drop record (DTLS) in other cases.
5834 */
5835
5836#if defined(MBEDTLS_SSL_CLI_C)
5837 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
5838 (ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
5839 ssl->in_hslen != mbedtls_ssl_hs_hdr_len(ssl))) {
5840 MBEDTLS_SSL_DEBUG_MSG(1, ("handshake received (not HelloRequest)"));
5841
5842 /* With DTLS, drop the packet (probably from last handshake) */
5843#if defined(MBEDTLS_SSL_PROTO_DTLS)
5844 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5845 return 0;
5846 }
5847#endif
5848 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5849 }
5850#endif /* MBEDTLS_SSL_CLI_C */
5851
5852#if defined(MBEDTLS_SSL_SRV_C)
5853 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
5854 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO) {
5855 MBEDTLS_SSL_DEBUG_MSG(1, ("handshake received (not ClientHello)"));
5856
5857 /* With DTLS, drop the packet (probably from last handshake) */
5858#if defined(MBEDTLS_SSL_PROTO_DTLS)
5859 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5860 return 0;
5861 }
5862#endif
5863 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5864 }
5865#endif /* MBEDTLS_SSL_SRV_C */
5866
5867#if defined(MBEDTLS_SSL_RENEGOTIATION)
5868 /* Determine whether renegotiation attempt should be accepted */
5869 if (!(ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
5870 (ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
5871 ssl->conf->allow_legacy_renegotiation ==
5872 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION))) {
5873 /*
5874 * Accept renegotiation request
5875 */
5876
5877 /* DTLS clients need to know renego is server-initiated */
5878#if defined(MBEDTLS_SSL_PROTO_DTLS)
5879 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5880 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
5881 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
5882 }
5883#endif
5884
5885 /* Keep the ClientHello message for ssl_parse_client_hello() */
5886 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
5887 ssl->keep_current_message = 1;
5888 }
5889 ret = mbedtls_ssl_start_renegotiation(ssl);
5890 if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
5891 ret != 0) {
5892 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_start_renegotiation",
5893 ret);
5894 return ret;
5895 }
5896 } else
5897#endif /* MBEDTLS_SSL_RENEGOTIATION */
5898 {
5899 /*
5900 * Refuse renegotiation
5901 */
5902
5903 MBEDTLS_SSL_DEBUG_MSG(3, ("refusing renegotiation, sending alert"));
5904
5905 if ((ret = mbedtls_ssl_send_alert_message(ssl,
5906 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
5907 MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION)) != 0) {
5908 return ret;
5909 }
5910 }
5911
5912 return 0;
5913}
5914#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5915
5916MBEDTLS_CHECK_RETURN_CRITICAL
5917static int ssl_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
5918{
5919 /* Check protocol version and dispatch accordingly. */
5920#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
5921 if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
5922 return ssl_tls13_handle_hs_message_post_handshake(ssl);
5923 }
5924#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
5925
5926#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5927 if (ssl->tls_version <= MBEDTLS_SSL_VERSION_TLS1_2) {
5928 return ssl_tls12_handle_hs_message_post_handshake(ssl);
5929 }
5930#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5931
5932 /* Should never happen */
5933 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
5934}
5935
5936/*
5937 * brief Read at most 'len' application data bytes from the input
5938 * buffer.
5939 *
5940 * param ssl SSL context:
5941 * - First byte of application data not read yet in the input
5942 * buffer located at address `in_offt`.
5943 * - The number of bytes of data not read yet is `in_msglen`.
5944 * param buf buffer that will hold the data
5945 * param len maximum number of bytes to read
5946 *
5947 * note The function updates the fields `in_offt` and `in_msglen`
5948 * according to the number of bytes read.
5949 *
5950 * return The number of bytes read.
5951 */
5952static int ssl_read_application_data(
5953 mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
5954{
5955 size_t n = (len < ssl->in_msglen) ? len : ssl->in_msglen;
5956
5957 if (len != 0) {
5958 memcpy(buf, ssl->in_offt, n);
5959 ssl->in_msglen -= n;
5960 }
5961
5962 /* Zeroising the plaintext buffer to erase unused application data
5963 from the memory. */
5964 mbedtls_platform_zeroize(ssl->in_offt, n);
5965
5966 if (ssl->in_msglen == 0) {
5967 /* all bytes consumed */
5968 ssl->in_offt = NULL;
5969 ssl->keep_current_message = 0;
5970 } else {
5971 /* more data available */
5972 ssl->in_offt += n;
5973 }
5974
5975 return (int) n;
5976}
5977
5978/*
5979 * Receive application data decrypted from the SSL layer
5980 */
5981int mbedtls_ssl_read(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
5982{
5983 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5984
5985 if (ssl == NULL || ssl->conf == NULL) {
5986 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5987 }
5988
5989 MBEDTLS_SSL_DEBUG_MSG(2, ("=> read"));
5990
5991#if defined(MBEDTLS_SSL_PROTO_DTLS)
5992 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5993 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
5994 return ret;
5995 }
5996
5997 if (ssl->handshake != NULL &&
5998 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING) {
5999 if ((ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
6000 return ret;
6001 }
6002 }
6003 }
6004#endif
6005
6006 /*
6007 * Check if renegotiation is necessary and/or handshake is
6008 * in process. If yes, perform/continue, and fall through
6009 * if an unexpected packet is received while the client
6010 * is waiting for the ServerHello.
6011 *
6012 * (There is no equivalent to the last condition on
6013 * the server-side as it is not treated as within
6014 * a handshake while waiting for the ClientHello
6015 * after a renegotiation request.)
6016 */
6017
6018#if defined(MBEDTLS_SSL_RENEGOTIATION)
6019 ret = ssl_check_ctr_renegotiate(ssl);
6020 if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
6021 ret != 0) {
6022 MBEDTLS_SSL_DEBUG_RET(1, "ssl_check_ctr_renegotiate", ret);
6023 return ret;
6024 }
6025#endif
6026
6027 if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
6028 ret = mbedtls_ssl_handshake(ssl);
6029 if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
6030 ret != 0) {
6031 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
6032 return ret;
6033 }
6034 }
6035
6036 /* Loop as long as no application data record is available */
6037 while (ssl->in_offt == NULL) {
6038 /* Start timer if not already running */
6039 if (ssl->f_get_timer != NULL &&
6040 ssl->f_get_timer(ssl->p_timer) == -1) {
6041 mbedtls_ssl_set_timer(ssl, ssl->conf->read_timeout);
6042 }
6043
6044 if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
6045 if (ret == MBEDTLS_ERR_SSL_CONN_EOF) {
6046 return 0;
6047 }
6048
6049 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
6050 return ret;
6051 }
6052
6053 if (ssl->in_msglen == 0 &&
6054 ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
6055 /*
6056 * OpenSSL sends empty messages to randomize the IV
6057 */
6058 if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
6059 if (ret == MBEDTLS_ERR_SSL_CONN_EOF) {
6060 return 0;
6061 }
6062
6063 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
6064 return ret;
6065 }
6066 }
6067
6068 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
6069 ret = ssl_handle_hs_message_post_handshake(ssl);
6070 if (ret != 0) {
6071 MBEDTLS_SSL_DEBUG_RET(1, "ssl_handle_hs_message_post_handshake",
6072 ret);
6073 return ret;
6074 }
6075
6076 /* At this point, we don't know whether the renegotiation triggered
6077 * by the post-handshake message has been completed or not. The cases
6078 * to consider are the following:
6079 * 1) The renegotiation is complete. In this case, no new record
6080 * has been read yet.
6081 * 2) The renegotiation is incomplete because the client received
6082 * an application data record while awaiting the ServerHello.
6083 * 3) The renegotiation is incomplete because the client received
6084 * a non-handshake, non-application data message while awaiting
6085 * the ServerHello.
6086 *
6087 * In each of these cases, looping will be the proper action:
6088 * - For 1), the next iteration will read a new record and check
6089 * if it's application data.
6090 * - For 2), the loop condition isn't satisfied as application data
6091 * is present, hence continue is the same as break
6092 * - For 3), the loop condition is satisfied and read_record
6093 * will re-deliver the message that was held back by the client
6094 * when expecting the ServerHello.
6095 */
6096
6097 continue;
6098 }
6099#if defined(MBEDTLS_SSL_RENEGOTIATION)
6100 else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
6101 if (ssl->conf->renego_max_records >= 0) {
6102 if (++ssl->renego_records_seen > ssl->conf->renego_max_records) {
6103 MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation requested, "
6104 "but not honored by client"));
6105 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
6106 }
6107 }
6108 }
6109#endif /* MBEDTLS_SSL_RENEGOTIATION */
6110
6111 /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
6112 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT) {
6113 MBEDTLS_SSL_DEBUG_MSG(2, ("ignoring non-fatal non-closure alert"));
6114 return MBEDTLS_ERR_SSL_WANT_READ;
6115 }
6116
6117 if (ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
6118 MBEDTLS_SSL_DEBUG_MSG(1, ("bad application data message"));
6119 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
6120 }
6121
6122 ssl->in_offt = ssl->in_msg;
6123
6124 /* We're going to return something now, cancel timer,
6125 * except if handshake (renegotiation) is in progress */
6126 if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
6127 mbedtls_ssl_set_timer(ssl, 0);
6128 }
6129
6130#if defined(MBEDTLS_SSL_PROTO_DTLS)
6131 /* If we requested renego but received AppData, resend HelloRequest.
6132 * Do it now, after setting in_offt, to avoid taking this branch
6133 * again if ssl_write_hello_request() returns WANT_WRITE */
6134#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
6135 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
6136 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
6137 if ((ret = mbedtls_ssl_resend_hello_request(ssl)) != 0) {
6138 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend_hello_request",
6139 ret);
6140 return ret;
6141 }
6142 }
6143#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
6144#endif /* MBEDTLS_SSL_PROTO_DTLS */
6145 }
6146
6147 ret = ssl_read_application_data(ssl, buf, len);
6148
6149 MBEDTLS_SSL_DEBUG_MSG(2, ("<= read"));
6150
6151 return ret;
6152}
6153
6154#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_EARLY_DATA)
6155int mbedtls_ssl_read_early_data(mbedtls_ssl_context *ssl,
6156 unsigned char *buf, size_t len)
6157{
6158 if (ssl == NULL || (ssl->conf == NULL)) {
6159 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6160 }
6161
6162 /*
6163 * The server may receive early data only while waiting for the End of
6164 * Early Data handshake message.
6165 */
6166 if ((ssl->state != MBEDTLS_SSL_END_OF_EARLY_DATA) ||
6167 (ssl->in_offt == NULL)) {
6168 return MBEDTLS_ERR_SSL_CANNOT_READ_EARLY_DATA;
6169 }
6170
6171 return ssl_read_application_data(ssl, buf, len);
6172}
6173#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_EARLY_DATA */
6174
6175/*
6176 * Send application data to be encrypted by the SSL layer, taking care of max
6177 * fragment length and buffer size.
6178 *
6179 * According to RFC 5246 Section 6.2.1:
6180 *
6181 * Zero-length fragments of Application data MAY be sent as they are
6182 * potentially useful as a traffic analysis countermeasure.
6183 *
6184 * Therefore, it is possible that the input message length is 0 and the
6185 * corresponding return code is 0 on success.
6186 */
6187MBEDTLS_CHECK_RETURN_CRITICAL
6188static int ssl_write_real(mbedtls_ssl_context *ssl,
6189 const unsigned char *buf, size_t len)
6190{
6191 int ret = mbedtls_ssl_get_max_out_record_payload(ssl);
6192 const size_t max_len = (size_t) ret;
6193
6194 if (ret < 0) {
6195 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_get_max_out_record_payload", ret);
6196 return ret;
6197 }
6198
6199 if (len > max_len) {
6200#if defined(MBEDTLS_SSL_PROTO_DTLS)
6201 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
6202 MBEDTLS_SSL_DEBUG_MSG(1, ("fragment larger than the (negotiated) "
6203 "maximum fragment length: %" MBEDTLS_PRINTF_SIZET
6204 " > %" MBEDTLS_PRINTF_SIZET,
6205 len, max_len));
6206 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6207 } else
6208#endif
6209 len = max_len;
6210 }
6211
6212 if (ssl->out_left != 0) {
6213 /*
6214 * The user has previously tried to send the data and
6215 * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
6216 * written. In this case, we expect the high-level write function
6217 * (e.g. mbedtls_ssl_write()) to be called with the same parameters
6218 */
6219 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
6220 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
6221 return ret;
6222 }
6223 } else {
6224 /*
6225 * The user is trying to send a message the first time, so we need to
6226 * copy the data into the internal buffers and setup the data structure
6227 * to keep track of partial writes
6228 */
6229 ssl->out_msglen = len;
6230 ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
6231 if (len > 0) {
6232 memcpy(ssl->out_msg, buf, len);
6233 }
6234
6235 if ((ret = mbedtls_ssl_write_record(ssl, SSL_FORCE_FLUSH)) != 0) {
6236 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
6237 return ret;
6238 }
6239 }
6240
6241 return (int) len;
6242}
6243
6244/*
6245 * Write application data (public-facing wrapper)
6246 */
6247int mbedtls_ssl_write(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
6248{
6249 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6250
6251 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write"));
6252
6253 if (ssl == NULL || ssl->conf == NULL) {
6254 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6255 }
6256
6257#if defined(MBEDTLS_SSL_RENEGOTIATION)
6258 if ((ret = ssl_check_ctr_renegotiate(ssl)) != 0) {
6259 MBEDTLS_SSL_DEBUG_RET(1, "ssl_check_ctr_renegotiate", ret);
6260 return ret;
6261 }
6262#endif
6263
6264 if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
6265 if ((ret = mbedtls_ssl_handshake(ssl)) != 0) {
6266 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
6267 return ret;
6268 }
6269 }
6270
6271 ret = ssl_write_real(ssl, buf, len);
6272
6273 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write"));
6274
6275 return ret;
6276}
6277
6278#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_CLI_C)
6279int mbedtls_ssl_write_early_data(mbedtls_ssl_context *ssl,
6280 const unsigned char *buf, size_t len)
6281{
6282 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6283 const struct mbedtls_ssl_config *conf;
6284 uint32_t remaining;
6285
6286 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write early_data"));
6287
6288 if (ssl == NULL || (conf = ssl->conf) == NULL) {
6289 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6290 }
6291
6292 if (conf->endpoint != MBEDTLS_SSL_IS_CLIENT) {
6293 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6294 }
6295
6296 if ((!mbedtls_ssl_conf_is_tls13_enabled(conf)) ||
6297 (conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
6298 (conf->early_data_enabled != MBEDTLS_SSL_EARLY_DATA_ENABLED)) {
6299 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6300 }
6301
6302 if (ssl->tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
6303 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6304 }
6305
6306 /*
6307 * If we are at the beginning of the handshake, the early data state being
6308 * equal to MBEDTLS_SSL_EARLY_DATA_STATE_IDLE or
6309 * MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT advance the handshake just
6310 * enough to be able to send early data if possible. That way, we can
6311 * guarantee that when starting the handshake with this function we will
6312 * send at least one record of early data. Note that when the state is
6313 * MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT and not yet
6314 * MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE, we cannot send early data
6315 * as the early data outbound transform has not been set as we may have to
6316 * first send a dummy CCS in clear.
6317 */
6318 if ((ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IDLE) ||
6319 (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT)) {
6320 while ((ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IDLE) ||
6321 (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT)) {
6322 ret = mbedtls_ssl_handshake_step(ssl);
6323 if (ret != 0) {
6324 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake_step", ret);
6325 return ret;
6326 }
6327
6328 ret = mbedtls_ssl_flush_output(ssl);
6329 if (ret != 0) {
6330 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
6331 return ret;
6332 }
6333 }
6334 remaining = ssl->session_negotiate->max_early_data_size;
6335 } else {
6336 /*
6337 * If we are past the point where we can send early data or we have
6338 * already reached the maximum early data size, return immediately.
6339 * Otherwise, progress the handshake as much as possible to not delay
6340 * it too much. If we reach a point where we can still send early data,
6341 * then we will send some.
6342 */
6343 if ((ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE) &&
6344 (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED)) {
6345 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6346 }
6347
6348 remaining = ssl->session_negotiate->max_early_data_size -
6349 ssl->total_early_data_size;
6350
6351 if (remaining == 0) {
6352 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6353 }
6354
6355 ret = mbedtls_ssl_handshake(ssl);
6356 if ((ret != 0) && (ret != MBEDTLS_ERR_SSL_WANT_READ)) {
6357 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
6358 return ret;
6359 }
6360 }
6361
6362 if (((ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE) &&
6363 (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED))
6364 || (remaining == 0)) {
6365 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6366 }
6367
6368 if (len > remaining) {
6369 len = remaining;
6370 }
6371
6372 ret = ssl_write_real(ssl, buf, len);
6373 if (ret >= 0) {
6374 ssl->total_early_data_size += ret;
6375 }
6376
6377 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write early_data, ret=%d", ret));
6378
6379 return ret;
6380}
6381#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_CLI_C */
6382
6383/*
6384 * Notify the peer that the connection is being closed
6385 */
6386int mbedtls_ssl_close_notify(mbedtls_ssl_context *ssl)
6387{
6388 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6389
6390 if (ssl == NULL || ssl->conf == NULL) {
6391 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6392 }
6393
6394 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write close notify"));
6395
6396 if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
6397 if ((ret = mbedtls_ssl_send_alert_message(ssl,
6398 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
6399 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)) != 0) {
6400 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_send_alert_message", ret);
6401 return ret;
6402 }
6403 }
6404
6405 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write close notify"));
6406
6407 return 0;
6408}
6409
6410void mbedtls_ssl_transform_free(mbedtls_ssl_transform *transform)
6411{
6412 if (transform == NULL) {
6413 return;
6414 }
6415
6416#if defined(MBEDTLS_USE_PSA_CRYPTO)
6417 psa_destroy_key(transform->psa_key_enc);
6418 psa_destroy_key(transform->psa_key_dec);
6419#else
6420 mbedtls_cipher_free(&transform->cipher_ctx_enc);
6421 mbedtls_cipher_free(&transform->cipher_ctx_dec);
6422#endif /* MBEDTLS_USE_PSA_CRYPTO */
6423
6424#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
6425#if defined(MBEDTLS_USE_PSA_CRYPTO)
6426 psa_destroy_key(transform->psa_mac_enc);
6427 psa_destroy_key(transform->psa_mac_dec);
6428#else
6429 mbedtls_md_free(&transform->md_ctx_enc);
6430 mbedtls_md_free(&transform->md_ctx_dec);
6431#endif /* MBEDTLS_USE_PSA_CRYPTO */
6432#endif
6433
6434 mbedtls_platform_zeroize(transform, sizeof(mbedtls_ssl_transform));
6435}
6436
6437void mbedtls_ssl_set_inbound_transform(mbedtls_ssl_context *ssl,
6438 mbedtls_ssl_transform *transform)
6439{
6440 ssl->transform_in = transform;
6441 memset(ssl->in_ctr, 0, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
6442}
6443
6444void mbedtls_ssl_set_outbound_transform(mbedtls_ssl_context *ssl,
6445 mbedtls_ssl_transform *transform)
6446{
6447 ssl->transform_out = transform;
6448 memset(ssl->cur_out_ctr, 0, sizeof(ssl->cur_out_ctr));
6449}
6450
6451#if defined(MBEDTLS_SSL_PROTO_DTLS)
6452
6453void mbedtls_ssl_buffering_free(mbedtls_ssl_context *ssl)
6454{
6455 unsigned offset;
6456 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
6457
6458 if (hs == NULL) {
6459 return;
6460 }
6461
6462 ssl_free_buffered_record(ssl);
6463
6464 for (offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++) {
6465 ssl_buffering_free_slot(ssl, offset);
6466 }
6467}
6468
6469static void ssl_buffering_free_slot(mbedtls_ssl_context *ssl,
6470 uint8_t slot)
6471{
6472 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
6473 mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
6474
6475 if (slot >= MBEDTLS_SSL_MAX_BUFFERED_HS) {
6476 return;
6477 }
6478
6479 if (hs_buf->is_valid == 1) {
6480 hs->buffering.total_bytes_buffered -= hs_buf->data_len;
6481 mbedtls_zeroize_and_free(hs_buf->data, hs_buf->data_len);
6482 memset(hs_buf, 0, sizeof(mbedtls_ssl_hs_buffer));
6483 }
6484}
6485
6486/*
6487 * Shift the buffering slots to the left by `shift` positions.
6488 * After the operation, slot i contains the previous slot i + shift.
6489 */
6490static void ssl_buffering_shift_slots(mbedtls_ssl_context *ssl,
6491 unsigned shift)
6492{
6493 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
6494 unsigned offset;
6495
6496 if (shift == 0) {
6497 return;
6498 }
6499
6500 if (shift >= MBEDTLS_SSL_MAX_BUFFERED_HS) {
6501 shift = MBEDTLS_SSL_MAX_BUFFERED_HS;
6502 }
6503
6504 /* Free discarded entries */
6505 for (offset = 0; offset < shift; offset++) {
6506 ssl_buffering_free_slot(ssl, offset);
6507 }
6508
6509 /* Shift remaining entries left */
6510 for (offset = 0; offset + shift < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++) {
6511 hs->buffering.hs[offset] = hs->buffering.hs[offset + shift];
6512 }
6513
6514 /* Reset the remaining entries at the end. Some may already have been
6515 * cleared by the loop freeing the discarded entries, but resetting all
6516 * of them is simpler and avoids tracking which ones were already handled.
6517 */
6518 for (; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++) {
6519 memset(&hs->buffering.hs[offset], 0, sizeof(hs->buffering.hs[offset]));
6520 }
6521}
6522#endif /* MBEDTLS_SSL_PROTO_DTLS */
6523
6524/*
6525 * Convert version numbers to/from wire format
6526 * and, for DTLS, to/from TLS equivalent.
6527 *
6528 * For TLS this is the identity.
6529 * For DTLS, map as follows, then use 1's complement (v -> ~v):
6530 * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2)
6531 * DTLS 1.0 is stored as TLS 1.1 internally
6532 */
6533void mbedtls_ssl_write_version(unsigned char version[2], int transport,
6534 mbedtls_ssl_protocol_version tls_version)
6535{
6536 uint16_t tls_version_formatted;
6537#if defined(MBEDTLS_SSL_PROTO_DTLS)
6538 if (transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
6539 tls_version_formatted =
6540 ~(tls_version - (tls_version == 0x0302 ? 0x0202 : 0x0201));
6541 } else
6542#else
6543 ((void) transport);
6544#endif
6545 {
6546 tls_version_formatted = (uint16_t) tls_version;
6547 }
6548 MBEDTLS_PUT_UINT16_BE(tls_version_formatted, version, 0);
6549}
6550
6551uint16_t mbedtls_ssl_read_version(const unsigned char version[2],
6552 int transport)
6553{
6554 uint16_t tls_version = MBEDTLS_GET_UINT16_BE(version, 0);
6555#if defined(MBEDTLS_SSL_PROTO_DTLS)
6556 if (transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
6557 tls_version =
6558 ~(tls_version - (tls_version == 0xfeff ? 0x0202 : 0x0201));
6559 }
6560#else
6561 ((void) transport);
6562#endif
6563 return tls_version;
6564}
6565
6566/*
6567 * Send pending fatal alert.
6568 * 0, No alert message.
6569 * !0, if mbedtls_ssl_send_alert_message() returned in error, the error code it
6570 * returned, ssl->alert_reason otherwise.
6571 */
6572int mbedtls_ssl_handle_pending_alert(mbedtls_ssl_context *ssl)
6573{
6574 int ret;
6575
6576 /* No pending alert, return success*/
6577 if (ssl->send_alert == 0) {
6578 return 0;
6579 }
6580
6581 ret = mbedtls_ssl_send_alert_message(ssl,
6582 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6583 ssl->alert_type);
6584
6585 /* If mbedtls_ssl_send_alert_message() returned with MBEDTLS_ERR_SSL_WANT_WRITE,
6586 * do not clear the alert to be able to send it later.
6587 */
6588 if (ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
6589 ssl->send_alert = 0;
6590 }
6591
6592 if (ret != 0) {
6593 return ret;
6594 }
6595
6596 return ssl->alert_reason;
6597}
6598
6599/*
6600 * Set pending fatal alert flag.
6601 */
6602void mbedtls_ssl_pend_fatal_alert(mbedtls_ssl_context *ssl,
6603 unsigned char alert_type,
6604 int alert_reason)
6605{
6606 ssl->send_alert = 1;
6607 ssl->alert_type = alert_type;
6608 ssl->alert_reason = alert_reason;
6609}
6610
6611#endif /* MBEDTLS_SSL_TLS_C */
6612