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