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 "mbedtls/error.h"
23 #include "mbedtls/platform_util.h"
24 #include "mbedtls/version.h"
25 #include "constant_time_internal.h"
26 #include "mbedtls/constant_time.h"
27
28 #include <string.h>
29
30 #if defined(MBEDTLS_USE_PSA_CRYPTO)
31 #include "psa_util_internal.h"
32 #include "psa/crypto.h"
33 #endif
34
35 #if defined(MBEDTLS_X509_CRT_PARSE_C)
36 #include "mbedtls/oid.h"
37 #endif
38
39 #if defined(MBEDTLS_USE_PSA_CRYPTO)
40 /* Define a local translating function to save code size by not using too many
41 * arguments in each translating place. */
local_err_translation(psa_status_t status)42 static int local_err_translation(psa_status_t status)
43 {
44 return psa_status_to_mbedtls(status, psa_to_ssl_errors,
45 ARRAY_LENGTH(psa_to_ssl_errors),
46 psa_generic_status_to_mbedtls);
47 }
48 #define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
49 #endif
50
51 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
52
53 #if defined(MBEDTLS_USE_PSA_CRYPTO)
54
55 #if defined(PSA_WANT_ALG_SHA_384)
56 #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_384)
57 #elif defined(PSA_WANT_ALG_SHA_256)
58 #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_256)
59 #else /* See check_config.h */
60 #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_1)
61 #endif
62
63 MBEDTLS_STATIC_TESTABLE
mbedtls_ct_hmac(mbedtls_svc_key_id_t key,psa_algorithm_t mac_alg,const unsigned char * add_data,size_t add_data_len,const unsigned char * data,size_t data_len_secret,size_t min_data_len,size_t max_data_len,unsigned char * output)64 int mbedtls_ct_hmac(mbedtls_svc_key_id_t key,
65 psa_algorithm_t mac_alg,
66 const unsigned char *add_data,
67 size_t add_data_len,
68 const unsigned char *data,
69 size_t data_len_secret,
70 size_t min_data_len,
71 size_t max_data_len,
72 unsigned char *output)
73 {
74 /*
75 * This function breaks the HMAC abstraction and uses psa_hash_clone()
76 * extension in order to get constant-flow behaviour.
77 *
78 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
79 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
80 * patterns (see RFC 2104, sec. 2).
81 *
82 * We'll first compute ikey/okey, then inner_hash = HASH(ikey + msg) by
83 * hashing up to minlen, then cloning the context, and for each byte up
84 * to maxlen finishing up the hash computation, keeping only the
85 * correct result.
86 *
87 * Then we only need to compute HASH(okey + inner_hash) and we're done.
88 */
89 psa_algorithm_t hash_alg = PSA_ALG_HMAC_GET_HASH(mac_alg);
90 const size_t block_size = PSA_HASH_BLOCK_LENGTH(hash_alg);
91 unsigned char key_buf[MAX_HASH_BLOCK_LENGTH];
92 const size_t hash_size = PSA_HASH_LENGTH(hash_alg);
93 psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
94 size_t hash_length;
95
96 unsigned char aux_out[PSA_HASH_MAX_SIZE];
97 psa_hash_operation_t aux_operation = PSA_HASH_OPERATION_INIT;
98 size_t offset;
99 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
100
101 size_t mac_key_length;
102 size_t i;
103
104 #define PSA_CHK(func_call) \
105 do { \
106 status = (func_call); \
107 if (status != PSA_SUCCESS) \
108 goto cleanup; \
109 } while (0)
110
111 /* Export MAC key
112 * We assume key length is always exactly the output size
113 * which is never more than the block size, thus we use block_size
114 * as the key buffer size.
115 */
116 PSA_CHK(psa_export_key(key, key_buf, block_size, &mac_key_length));
117
118 /* Calculate ikey */
119 for (i = 0; i < mac_key_length; i++) {
120 key_buf[i] = (unsigned char) (key_buf[i] ^ 0x36);
121 }
122 for (; i < block_size; ++i) {
123 key_buf[i] = 0x36;
124 }
125
126 PSA_CHK(psa_hash_setup(&operation, hash_alg));
127
128 /* Now compute inner_hash = HASH(ikey + msg) */
129 PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
130 PSA_CHK(psa_hash_update(&operation, add_data, add_data_len));
131 PSA_CHK(psa_hash_update(&operation, data, min_data_len));
132
133 /* Fill the hash buffer in advance with something that is
134 * not a valid hash (barring an attack on the hash and
135 * deliberately-crafted input), in case the caller doesn't
136 * check the return status properly. */
137 memset(output, '!', hash_size);
138
139 /* For each possible length, compute the hash up to that point */
140 for (offset = min_data_len; offset <= max_data_len; offset++) {
141 PSA_CHK(psa_hash_clone(&operation, &aux_operation));
142 PSA_CHK(psa_hash_finish(&aux_operation, aux_out,
143 PSA_HASH_MAX_SIZE, &hash_length));
144 /* Keep only the correct inner_hash in the output buffer */
145 mbedtls_ct_memcpy_if(mbedtls_ct_uint_eq(offset, data_len_secret),
146 output, aux_out, NULL, hash_size);
147
148 if (offset < max_data_len) {
149 PSA_CHK(psa_hash_update(&operation, data + offset, 1));
150 }
151 }
152
153 /* Abort current operation to prepare for final operation */
154 PSA_CHK(psa_hash_abort(&operation));
155
156 /* Calculate okey */
157 for (i = 0; i < mac_key_length; i++) {
158 key_buf[i] = (unsigned char) ((key_buf[i] ^ 0x36) ^ 0x5C);
159 }
160 for (; i < block_size; ++i) {
161 key_buf[i] = 0x5C;
162 }
163
164 /* Now compute HASH(okey + inner_hash) */
165 PSA_CHK(psa_hash_setup(&operation, hash_alg));
166 PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
167 PSA_CHK(psa_hash_update(&operation, output, hash_size));
168 PSA_CHK(psa_hash_finish(&operation, output, hash_size, &hash_length));
169
170 #undef PSA_CHK
171
172 cleanup:
173 mbedtls_platform_zeroize(key_buf, MAX_HASH_BLOCK_LENGTH);
174 mbedtls_platform_zeroize(aux_out, PSA_HASH_MAX_SIZE);
175
176 psa_hash_abort(&operation);
177 psa_hash_abort(&aux_operation);
178 return PSA_TO_MBEDTLS_ERR(status);
179 }
180
181 #undef MAX_HASH_BLOCK_LENGTH
182
183 #else
184 MBEDTLS_STATIC_TESTABLE
mbedtls_ct_hmac(mbedtls_md_context_t * ctx,const unsigned char * add_data,size_t add_data_len,const unsigned char * data,size_t data_len_secret,size_t min_data_len,size_t max_data_len,unsigned char * output)185 int mbedtls_ct_hmac(mbedtls_md_context_t *ctx,
186 const unsigned char *add_data,
187 size_t add_data_len,
188 const unsigned char *data,
189 size_t data_len_secret,
190 size_t min_data_len,
191 size_t max_data_len,
192 unsigned char *output)
193 {
194 /*
195 * This function breaks the HMAC abstraction and uses the md_clone()
196 * extension to the MD API in order to get constant-flow behaviour.
197 *
198 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
199 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
200 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
201 *
202 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
203 * minlen, then cloning the context, and for each byte up to maxlen
204 * finishing up the hash computation, keeping only the correct result.
205 *
206 * Then we only need to compute HASH(okey + inner_hash) and we're done.
207 */
208 const mbedtls_md_type_t md_alg = mbedtls_md_get_type(ctx->md_info);
209 /* TLS 1.2 only supports SHA-384, SHA-256, SHA-1, MD-5,
210 * all of which have the same block size except SHA-384. */
211 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
212 const unsigned char * const ikey = ctx->hmac_ctx;
213 const unsigned char * const okey = ikey + block_size;
214 const size_t hash_size = mbedtls_md_get_size(ctx->md_info);
215
216 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
217 mbedtls_md_context_t aux;
218 size_t offset;
219 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
220
221 mbedtls_md_init(&aux);
222
223 #define MD_CHK(func_call) \
224 do { \
225 ret = (func_call); \
226 if (ret != 0) \
227 goto cleanup; \
228 } while (0)
229
230 MD_CHK(mbedtls_md_setup(&aux, ctx->md_info, 0));
231
232 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
233 * so we can start directly with the message */
234 MD_CHK(mbedtls_md_update(ctx, add_data, add_data_len));
235 MD_CHK(mbedtls_md_update(ctx, data, min_data_len));
236
237 /* Fill the hash buffer in advance with something that is
238 * not a valid hash (barring an attack on the hash and
239 * deliberately-crafted input), in case the caller doesn't
240 * check the return status properly. */
241 memset(output, '!', hash_size);
242
243 /* For each possible length, compute the hash up to that point */
244 for (offset = min_data_len; offset <= max_data_len; offset++) {
245 MD_CHK(mbedtls_md_clone(&aux, ctx));
246 MD_CHK(mbedtls_md_finish(&aux, aux_out));
247 /* Keep only the correct inner_hash in the output buffer */
248 mbedtls_ct_memcpy_if(mbedtls_ct_uint_eq(offset, data_len_secret),
249 output, aux_out, NULL, hash_size);
250
251 if (offset < max_data_len) {
252 MD_CHK(mbedtls_md_update(ctx, data + offset, 1));
253 }
254 }
255
256 /* The context needs to finish() before it starts() again */
257 MD_CHK(mbedtls_md_finish(ctx, aux_out));
258
259 /* Now compute HASH(okey + inner_hash) */
260 MD_CHK(mbedtls_md_starts(ctx));
261 MD_CHK(mbedtls_md_update(ctx, okey, block_size));
262 MD_CHK(mbedtls_md_update(ctx, output, hash_size));
263 MD_CHK(mbedtls_md_finish(ctx, output));
264
265 /* Done, get ready for next time */
266 MD_CHK(mbedtls_md_hmac_reset(ctx));
267
268 #undef MD_CHK
269
270 cleanup:
271 mbedtls_md_free(&aux);
272 return ret;
273 }
274
275 #endif /* MBEDTLS_USE_PSA_CRYPTO */
276
277 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
278
279 static uint32_t ssl_get_hs_total_len(mbedtls_ssl_context const *ssl);
280
281 /*
282 * Start a timer.
283 * Passing millisecs = 0 cancels a running timer.
284 */
mbedtls_ssl_set_timer(mbedtls_ssl_context * ssl,uint32_t millisecs)285 void mbedtls_ssl_set_timer(mbedtls_ssl_context *ssl, uint32_t millisecs)
286 {
287 if (ssl->f_set_timer == NULL) {
288 return;
289 }
290
291 MBEDTLS_SSL_DEBUG_MSG(3, ("set_timer to %d ms", (int) millisecs));
292 ssl->f_set_timer(ssl->p_timer, millisecs / 4, millisecs);
293 }
294
295 /*
296 * Return -1 is timer is expired, 0 if it isn't.
297 */
mbedtls_ssl_check_timer(mbedtls_ssl_context * ssl)298 int mbedtls_ssl_check_timer(mbedtls_ssl_context *ssl)
299 {
300 if (ssl->f_get_timer == NULL) {
301 return 0;
302 }
303
304 if (ssl->f_get_timer(ssl->p_timer) == 2) {
305 MBEDTLS_SSL_DEBUG_MSG(3, ("timer expired"));
306 return -1;
307 }
308
309 return 0;
310 }
311
312 MBEDTLS_CHECK_RETURN_CRITICAL
313 static int ssl_parse_record_header(mbedtls_ssl_context const *ssl,
314 unsigned char *buf,
315 size_t len,
316 mbedtls_record *rec);
317
mbedtls_ssl_check_record(mbedtls_ssl_context const * ssl,unsigned char * buf,size_t buflen)318 int mbedtls_ssl_check_record(mbedtls_ssl_context const *ssl,
319 unsigned char *buf,
320 size_t buflen)
321 {
322 int ret = 0;
323 MBEDTLS_SSL_DEBUG_MSG(1, ("=> mbedtls_ssl_check_record"));
324 MBEDTLS_SSL_DEBUG_BUF(3, "record buffer", buf, buflen);
325
326 /* We don't support record checking in TLS because
327 * there doesn't seem to be a usecase for it.
328 */
329 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM) {
330 ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
331 goto exit;
332 }
333 #if defined(MBEDTLS_SSL_PROTO_DTLS)
334 else {
335 mbedtls_record rec;
336
337 ret = ssl_parse_record_header(ssl, buf, buflen, &rec);
338 if (ret != 0) {
339 MBEDTLS_SSL_DEBUG_RET(3, "ssl_parse_record_header", ret);
340 goto exit;
341 }
342
343 if (ssl->transform_in != NULL) {
344 ret = mbedtls_ssl_decrypt_buf(ssl, ssl->transform_in, &rec);
345 if (ret != 0) {
346 MBEDTLS_SSL_DEBUG_RET(3, "mbedtls_ssl_decrypt_buf", ret);
347 goto exit;
348 }
349 }
350 }
351 #endif /* MBEDTLS_SSL_PROTO_DTLS */
352
353 exit:
354 /* On success, we have decrypted the buffer in-place, so make
355 * sure we don't leak any plaintext data. */
356 mbedtls_platform_zeroize(buf, buflen);
357
358 /* For the purpose of this API, treat messages with unexpected CID
359 * as well as such from future epochs as unexpected. */
360 if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID ||
361 ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
362 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
363 }
364
365 MBEDTLS_SSL_DEBUG_MSG(1, ("<= mbedtls_ssl_check_record"));
366 return ret;
367 }
368
369 #define SSL_DONT_FORCE_FLUSH 0
370 #define SSL_FORCE_FLUSH 1
371
372 #if defined(MBEDTLS_SSL_PROTO_DTLS)
373
374 /* Forward declarations for functions related to message buffering. */
375 static void ssl_buffering_free_slot(mbedtls_ssl_context *ssl,
376 uint8_t slot);
377 static void ssl_free_buffered_record(mbedtls_ssl_context *ssl);
378 MBEDTLS_CHECK_RETURN_CRITICAL
379 static int ssl_load_buffered_message(mbedtls_ssl_context *ssl);
380 MBEDTLS_CHECK_RETURN_CRITICAL
381 static int ssl_load_buffered_record(mbedtls_ssl_context *ssl);
382 MBEDTLS_CHECK_RETURN_CRITICAL
383 static int ssl_buffer_message(mbedtls_ssl_context *ssl);
384 MBEDTLS_CHECK_RETURN_CRITICAL
385 static int ssl_buffer_future_record(mbedtls_ssl_context *ssl,
386 mbedtls_record const *rec);
387 MBEDTLS_CHECK_RETURN_CRITICAL
388 static int ssl_next_record_is_in_datagram(mbedtls_ssl_context *ssl);
389
ssl_get_maximum_datagram_size(mbedtls_ssl_context const * ssl)390 static size_t ssl_get_maximum_datagram_size(mbedtls_ssl_context const *ssl)
391 {
392 size_t mtu = mbedtls_ssl_get_current_mtu(ssl);
393 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
394 size_t out_buf_len = ssl->out_buf_len;
395 #else
396 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
397 #endif
398
399 if (mtu != 0 && mtu < out_buf_len) {
400 return mtu;
401 }
402
403 return out_buf_len;
404 }
405
406 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_get_remaining_space_in_datagram(mbedtls_ssl_context const * ssl)407 static int ssl_get_remaining_space_in_datagram(mbedtls_ssl_context const *ssl)
408 {
409 size_t const bytes_written = ssl->out_left;
410 size_t const mtu = ssl_get_maximum_datagram_size(ssl);
411
412 /* Double-check that the write-index hasn't gone
413 * past what we can transmit in a single datagram. */
414 if (bytes_written > mtu) {
415 /* Should never happen... */
416 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
417 }
418
419 return (int) (mtu - bytes_written);
420 }
421
422 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_get_remaining_payload_in_datagram(mbedtls_ssl_context const * ssl)423 static int ssl_get_remaining_payload_in_datagram(mbedtls_ssl_context const *ssl)
424 {
425 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
426 size_t remaining, expansion;
427 size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
428
429 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
430 const size_t mfl = mbedtls_ssl_get_output_max_frag_len(ssl);
431
432 if (max_len > mfl) {
433 max_len = mfl;
434 }
435
436 /* By the standard (RFC 6066 Sect. 4), the MFL extension
437 * only limits the maximum record payload size, so in theory
438 * we would be allowed to pack multiple records of payload size
439 * MFL into a single datagram. However, this would mean that there's
440 * no way to explicitly communicate MTU restrictions to the peer.
441 *
442 * The following reduction of max_len makes sure that we never
443 * write datagrams larger than MFL + Record Expansion Overhead.
444 */
445 if (max_len <= ssl->out_left) {
446 return 0;
447 }
448
449 max_len -= ssl->out_left;
450 #endif
451
452 ret = ssl_get_remaining_space_in_datagram(ssl);
453 if (ret < 0) {
454 return ret;
455 }
456 remaining = (size_t) ret;
457
458 ret = mbedtls_ssl_get_record_expansion(ssl);
459 if (ret < 0) {
460 return ret;
461 }
462 expansion = (size_t) ret;
463
464 if (remaining <= expansion) {
465 return 0;
466 }
467
468 remaining -= expansion;
469 if (remaining >= max_len) {
470 remaining = max_len;
471 }
472
473 return (int) remaining;
474 }
475
476 /*
477 * Double the retransmit timeout value, within the allowed range,
478 * returning -1 if the maximum value has already been reached.
479 */
480 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_double_retransmit_timeout(mbedtls_ssl_context * ssl)481 static int ssl_double_retransmit_timeout(mbedtls_ssl_context *ssl)
482 {
483 uint32_t new_timeout;
484
485 if (ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max) {
486 return -1;
487 }
488
489 /* Implement the final paragraph of RFC 6347 section 4.1.1.1
490 * in the following way: after the initial transmission and a first
491 * retransmission, back off to a temporary estimated MTU of 508 bytes.
492 * This value is guaranteed to be deliverable (if not guaranteed to be
493 * delivered) of any compliant IPv4 (and IPv6) network, and should work
494 * on most non-IP stacks too. */
495 if (ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min) {
496 ssl->handshake->mtu = 508;
497 MBEDTLS_SSL_DEBUG_MSG(2, ("mtu autoreduction to %d bytes", ssl->handshake->mtu));
498 }
499
500 new_timeout = 2 * ssl->handshake->retransmit_timeout;
501
502 /* Avoid arithmetic overflow and range overflow */
503 if (new_timeout < ssl->handshake->retransmit_timeout ||
504 new_timeout > ssl->conf->hs_timeout_max) {
505 new_timeout = ssl->conf->hs_timeout_max;
506 }
507
508 ssl->handshake->retransmit_timeout = new_timeout;
509 MBEDTLS_SSL_DEBUG_MSG(3, ("update timeout value to %lu millisecs",
510 (unsigned long) ssl->handshake->retransmit_timeout));
511
512 return 0;
513 }
514
ssl_reset_retransmit_timeout(mbedtls_ssl_context * ssl)515 static void ssl_reset_retransmit_timeout(mbedtls_ssl_context *ssl)
516 {
517 ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
518 MBEDTLS_SSL_DEBUG_MSG(3, ("update timeout value to %lu millisecs",
519 (unsigned long) ssl->handshake->retransmit_timeout));
520 }
521 #endif /* MBEDTLS_SSL_PROTO_DTLS */
522
523 /*
524 * Encryption/decryption functions
525 */
526
527 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
528
ssl_compute_padding_length(size_t len,size_t granularity)529 static size_t ssl_compute_padding_length(size_t len,
530 size_t granularity)
531 {
532 return (granularity - (len + 1) % granularity) % granularity;
533 }
534
535 /* This functions transforms a (D)TLS plaintext fragment and a record content
536 * type into an instance of the (D)TLSInnerPlaintext structure. This is used
537 * in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect
538 * a record's content type.
539 *
540 * struct {
541 * opaque content[DTLSPlaintext.length];
542 * ContentType real_type;
543 * uint8 zeros[length_of_padding];
544 * } (D)TLSInnerPlaintext;
545 *
546 * Input:
547 * - `content`: The beginning of the buffer holding the
548 * plaintext to be wrapped.
549 * - `*content_size`: The length of the plaintext in Bytes.
550 * - `max_len`: The number of Bytes available starting from
551 * `content`. This must be `>= *content_size`.
552 * - `rec_type`: The desired record content type.
553 *
554 * Output:
555 * - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure.
556 * - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure.
557 *
558 * Returns:
559 * - `0` on success.
560 * - A negative error code if `max_len` didn't offer enough space
561 * for the expansion.
562 */
563 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_build_inner_plaintext(unsigned char * content,size_t * content_size,size_t remaining,uint8_t rec_type,size_t pad)564 static int ssl_build_inner_plaintext(unsigned char *content,
565 size_t *content_size,
566 size_t remaining,
567 uint8_t rec_type,
568 size_t pad)
569 {
570 size_t len = *content_size;
571
572 /* Write real content type */
573 if (remaining == 0) {
574 return -1;
575 }
576 content[len] = rec_type;
577 len++;
578 remaining--;
579
580 if (remaining < pad) {
581 return -1;
582 }
583 memset(content + len, 0, pad);
584 len += pad;
585 remaining -= pad;
586
587 *content_size = len;
588 return 0;
589 }
590
591 /* This function parses a (D)TLSInnerPlaintext structure.
592 * See ssl_build_inner_plaintext() for details. */
593 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_inner_plaintext(unsigned char const * content,size_t * content_size,uint8_t * rec_type)594 static int ssl_parse_inner_plaintext(unsigned char const *content,
595 size_t *content_size,
596 uint8_t *rec_type)
597 {
598 size_t remaining = *content_size;
599
600 /* Determine length of padding by skipping zeroes from the back. */
601 do {
602 if (remaining == 0) {
603 return -1;
604 }
605 remaining--;
606 } while (content[remaining] == 0);
607
608 *content_size = remaining;
609 *rec_type = content[remaining];
610
611 return 0;
612 }
613 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID || MBEDTLS_SSL_PROTO_TLS1_3 */
614
615 /* The size of the `add_data` structure depends on various
616 * factors, namely
617 *
618 * 1) CID functionality disabled
619 *
620 * additional_data =
621 * 8: seq_num +
622 * 1: type +
623 * 2: version +
624 * 2: length of inner plaintext +
625 *
626 * size = 13 bytes
627 *
628 * 2) CID functionality based on RFC 9146 enabled
629 *
630 * size = 8 + 1 + 1 + 1 + 2 + 2 + 6 + 2 + CID-length
631 * = 23 + CID-length
632 *
633 * 3) CID functionality based on legacy CID version
634 according to draft-ietf-tls-dtls-connection-id-05
635 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
636 *
637 * size = 13 + 1 + CID-length
638 *
639 * More information about the CID usage:
640 *
641 * Per Section 5.3 of draft-ietf-tls-dtls-connection-id-05 the
642 * size of the additional data structure is calculated as:
643 *
644 * additional_data =
645 * 8: seq_num +
646 * 1: tls12_cid +
647 * 2: DTLSCipherText.version +
648 * n: cid +
649 * 1: cid_length +
650 * 2: length_of_DTLSInnerPlaintext
651 *
652 * Per RFC 9146 the size of the add_data structure is calculated as:
653 *
654 * additional_data =
655 * 8: seq_num_placeholder +
656 * 1: tls12_cid +
657 * 1: cid_length +
658 * 1: tls12_cid +
659 * 2: DTLSCiphertext.version +
660 * 2: epoch +
661 * 6: sequence_number +
662 * n: cid +
663 * 2: length_of_DTLSInnerPlaintext
664 *
665 */
ssl_extract_add_data_from_record(unsigned char * add_data,size_t * add_data_len,mbedtls_record * rec,mbedtls_ssl_protocol_version tls_version,size_t taglen)666 static void ssl_extract_add_data_from_record(unsigned char *add_data,
667 size_t *add_data_len,
668 mbedtls_record *rec,
669 mbedtls_ssl_protocol_version
670 tls_version,
671 size_t taglen)
672 {
673 /* Several types of ciphers have been defined for use with TLS and DTLS,
674 * and the MAC calculations for those ciphers differ slightly. Further
675 * variants were added when the CID functionality was added with RFC 9146.
676 * This implementations also considers the use of a legacy version of the
677 * CID specification published in draft-ietf-tls-dtls-connection-id-05,
678 * which is used in deployments.
679 *
680 * We will distinguish between the non-CID and the CID cases below.
681 *
682 * --- Non-CID cases ---
683 *
684 * Quoting RFC 5246 (TLS 1.2):
685 *
686 * additional_data = seq_num + TLSCompressed.type +
687 * TLSCompressed.version + TLSCompressed.length;
688 *
689 * For TLS 1.3, the record sequence number is dropped from the AAD
690 * and encoded within the nonce of the AEAD operation instead.
691 * Moreover, the additional data involves the length of the TLS
692 * ciphertext, not the TLS plaintext as in earlier versions.
693 * Quoting RFC 8446 (TLS 1.3):
694 *
695 * additional_data = TLSCiphertext.opaque_type ||
696 * TLSCiphertext.legacy_record_version ||
697 * TLSCiphertext.length
698 *
699 * We pass the tag length to this function in order to compute the
700 * ciphertext length from the inner plaintext length rec->data_len via
701 *
702 * TLSCiphertext.length = TLSInnerPlaintext.length + taglen.
703 *
704 * --- CID cases ---
705 *
706 * RFC 9146 uses a common pattern when constructing the data
707 * passed into a MAC / AEAD cipher.
708 *
709 * Data concatenation for MACs used with block ciphers with
710 * Encrypt-then-MAC Processing (with CID):
711 *
712 * data = seq_num_placeholder +
713 * tls12_cid +
714 * cid_length +
715 * tls12_cid +
716 * DTLSCiphertext.version +
717 * epoch +
718 * sequence_number +
719 * cid +
720 * DTLSCiphertext.length +
721 * IV +
722 * ENC(content + padding + padding_length)
723 *
724 * Data concatenation for MACs used with block ciphers (with CID):
725 *
726 * data = seq_num_placeholder +
727 * tls12_cid +
728 * cid_length +
729 * tls12_cid +
730 * DTLSCiphertext.version +
731 * epoch +
732 * sequence_number +
733 * cid +
734 * length_of_DTLSInnerPlaintext +
735 * DTLSInnerPlaintext.content +
736 * DTLSInnerPlaintext.real_type +
737 * DTLSInnerPlaintext.zeros
738 *
739 * AEAD ciphers use the following additional data calculation (with CIDs):
740 *
741 * additional_data = seq_num_placeholder +
742 * tls12_cid +
743 * cid_length +
744 * tls12_cid +
745 * DTLSCiphertext.version +
746 * epoch +
747 * sequence_number +
748 * cid +
749 * length_of_DTLSInnerPlaintext
750 *
751 * Section 5.3 of draft-ietf-tls-dtls-connection-id-05 (for legacy CID use)
752 * defines the additional data calculation as follows:
753 *
754 * additional_data = seq_num +
755 * tls12_cid +
756 * DTLSCipherText.version +
757 * cid +
758 * cid_length +
759 * length_of_DTLSInnerPlaintext
760 */
761
762 unsigned char *cur = add_data;
763 size_t ad_len_field = rec->data_len;
764
765 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
766 MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
767 const unsigned char seq_num_placeholder[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
768 #endif
769
770 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
771 if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
772 /* In TLS 1.3, the AAD contains the length of the TLSCiphertext,
773 * which differs from the length of the TLSInnerPlaintext
774 * by the length of the authentication tag. */
775 ad_len_field += taglen;
776 } else
777 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
778 {
779 ((void) tls_version);
780 ((void) taglen);
781
782 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
783 MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
784 if (rec->cid_len != 0) {
785 // seq_num_placeholder
786 memcpy(cur, seq_num_placeholder, sizeof(seq_num_placeholder));
787 cur += sizeof(seq_num_placeholder);
788
789 // tls12_cid type
790 *cur = rec->type;
791 cur++;
792
793 // cid_length
794 *cur = rec->cid_len;
795 cur++;
796 } else
797 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
798 {
799 // epoch + sequence number
800 memcpy(cur, rec->ctr, sizeof(rec->ctr));
801 cur += sizeof(rec->ctr);
802 }
803 }
804
805 // type
806 *cur = rec->type;
807 cur++;
808
809 // version
810 memcpy(cur, rec->ver, sizeof(rec->ver));
811 cur += sizeof(rec->ver);
812
813 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
814 MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 1
815
816 if (rec->cid_len != 0) {
817 // CID
818 memcpy(cur, rec->cid, rec->cid_len);
819 cur += rec->cid_len;
820
821 // cid_length
822 *cur = rec->cid_len;
823 cur++;
824
825 // length of inner plaintext
826 MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
827 cur += 2;
828 } else
829 #elif defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
830 MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
831
832 if (rec->cid_len != 0) {
833 // epoch + sequence number
834 memcpy(cur, rec->ctr, sizeof(rec->ctr));
835 cur += sizeof(rec->ctr);
836
837 // CID
838 memcpy(cur, rec->cid, rec->cid_len);
839 cur += rec->cid_len;
840
841 // length of inner plaintext
842 MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
843 cur += 2;
844 } else
845 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
846 {
847 MBEDTLS_PUT_UINT16_BE(ad_len_field, cur, 0);
848 cur += 2;
849 }
850
851 *add_data_len = (size_t) (cur - add_data);
852 }
853
854 #if defined(MBEDTLS_SSL_HAVE_AEAD)
855 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_transform_aead_dynamic_iv_is_explicit(mbedtls_ssl_transform const * transform)856 static int ssl_transform_aead_dynamic_iv_is_explicit(
857 mbedtls_ssl_transform const *transform)
858 {
859 return transform->ivlen != transform->fixed_ivlen;
860 }
861
862 /* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV )
863 *
864 * Concretely, this occurs in two variants:
865 *
866 * a) Fixed and dynamic IV lengths add up to total IV length, giving
867 * IV = fixed_iv || dynamic_iv
868 *
869 * This variant is used in TLS 1.2 when used with GCM or CCM.
870 *
871 * b) Fixed IV lengths matches total IV length, giving
872 * IV = fixed_iv XOR ( 0 || dynamic_iv )
873 *
874 * This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly.
875 *
876 * See also the documentation of mbedtls_ssl_transform.
877 *
878 * This function has the precondition that
879 *
880 * dst_iv_len >= max( fixed_iv_len, dynamic_iv_len )
881 *
882 * which has to be ensured by the caller. If this precondition
883 * violated, the behavior of this function is undefined.
884 */
ssl_build_record_nonce(unsigned char * dst_iv,size_t dst_iv_len,unsigned char const * fixed_iv,size_t fixed_iv_len,unsigned char const * dynamic_iv,size_t dynamic_iv_len)885 static void ssl_build_record_nonce(unsigned char *dst_iv,
886 size_t dst_iv_len,
887 unsigned char const *fixed_iv,
888 size_t fixed_iv_len,
889 unsigned char const *dynamic_iv,
890 size_t dynamic_iv_len)
891 {
892 /* Start with Fixed IV || 0 */
893 memset(dst_iv, 0, dst_iv_len);
894 memcpy(dst_iv, fixed_iv, fixed_iv_len);
895
896 dst_iv += dst_iv_len - dynamic_iv_len;
897 mbedtls_xor(dst_iv, dst_iv, dynamic_iv, dynamic_iv_len);
898 }
899 #endif /* MBEDTLS_SSL_HAVE_AEAD */
900
mbedtls_ssl_encrypt_buf(mbedtls_ssl_context * ssl,mbedtls_ssl_transform * transform,mbedtls_record * rec,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)901 int mbedtls_ssl_encrypt_buf(mbedtls_ssl_context *ssl,
902 mbedtls_ssl_transform *transform,
903 mbedtls_record *rec,
904 int (*f_rng)(void *, unsigned char *, size_t),
905 void *p_rng)
906 {
907 mbedtls_ssl_mode_t ssl_mode;
908 int auth_done = 0;
909 unsigned char *data;
910 /* For an explanation of the additional data length see
911 * the description of ssl_extract_add_data_from_record().
912 */
913 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
914 unsigned char add_data[23 + MBEDTLS_SSL_CID_OUT_LEN_MAX];
915 #else
916 unsigned char add_data[13];
917 #endif
918 size_t add_data_len;
919 size_t post_avail;
920
921 /* The SSL context is only used for debugging purposes! */
922 #if !defined(MBEDTLS_DEBUG_C)
923 ssl = NULL; /* make sure we don't use it except for debug */
924 ((void) ssl);
925 #endif
926
927 /* The PRNG is used for dynamic IV generation that's used
928 * for CBC transformations in TLS 1.2. */
929 #if !(defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \
930 defined(MBEDTLS_SSL_PROTO_TLS1_2))
931 ((void) f_rng);
932 ((void) p_rng);
933 #endif
934
935 MBEDTLS_SSL_DEBUG_MSG(2, ("=> encrypt buf"));
936
937 if (transform == NULL) {
938 MBEDTLS_SSL_DEBUG_MSG(1, ("no transform provided to encrypt_buf"));
939 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
940 }
941 if (rec == NULL
942 || rec->buf == NULL
943 || rec->buf_len < rec->data_offset
944 || rec->buf_len - rec->data_offset < rec->data_len
945 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
946 || rec->cid_len != 0
947 #endif
948 ) {
949 MBEDTLS_SSL_DEBUG_MSG(1, ("bad record structure provided to encrypt_buf"));
950 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
951 }
952
953 ssl_mode = mbedtls_ssl_get_mode_from_transform(transform);
954
955 data = rec->buf + rec->data_offset;
956 post_avail = rec->buf_len - (rec->data_len + rec->data_offset);
957 MBEDTLS_SSL_DEBUG_BUF(4, "before encrypt: output payload",
958 data, rec->data_len);
959
960 if (rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN) {
961 MBEDTLS_SSL_DEBUG_MSG(1, ("Record content %" MBEDTLS_PRINTF_SIZET
962 " too large, maximum %" MBEDTLS_PRINTF_SIZET,
963 rec->data_len,
964 (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN));
965 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
966 }
967
968 /* The following two code paths implement the (D)TLSInnerPlaintext
969 * structure present in TLS 1.3 and DTLS 1.2 + CID.
970 *
971 * See ssl_build_inner_plaintext() for more information.
972 *
973 * Note that this changes `rec->data_len`, and hence
974 * `post_avail` needs to be recalculated afterwards.
975 *
976 * Note also that the two code paths cannot occur simultaneously
977 * since they apply to different versions of the protocol. There
978 * is hence no risk of double-addition of the inner plaintext.
979 */
980 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
981 if (transform->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
982 size_t padding =
983 ssl_compute_padding_length(rec->data_len,
984 MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY);
985 if (ssl_build_inner_plaintext(data,
986 &rec->data_len,
987 post_avail,
988 rec->type,
989 padding) != 0) {
990 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
991 }
992
993 rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA;
994 }
995 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
996
997 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
998 /*
999 * Add CID information
1000 */
1001 rec->cid_len = transform->out_cid_len;
1002 memcpy(rec->cid, transform->out_cid, transform->out_cid_len);
1003 MBEDTLS_SSL_DEBUG_BUF(3, "CID", rec->cid, rec->cid_len);
1004
1005 if (rec->cid_len != 0) {
1006 size_t padding =
1007 ssl_compute_padding_length(rec->data_len,
1008 MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY);
1009 /*
1010 * Wrap plaintext into DTLSInnerPlaintext structure.
1011 * See ssl_build_inner_plaintext() for more information.
1012 *
1013 * Note that this changes `rec->data_len`, and hence
1014 * `post_avail` needs to be recalculated afterwards.
1015 */
1016 if (ssl_build_inner_plaintext(data,
1017 &rec->data_len,
1018 post_avail,
1019 rec->type,
1020 padding) != 0) {
1021 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1022 }
1023
1024 rec->type = MBEDTLS_SSL_MSG_CID;
1025 }
1026 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1027
1028 post_avail = rec->buf_len - (rec->data_len + rec->data_offset);
1029
1030 /*
1031 * Add MAC before if needed
1032 */
1033 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
1034 if (ssl_mode == MBEDTLS_SSL_MODE_STREAM ||
1035 ssl_mode == MBEDTLS_SSL_MODE_CBC) {
1036 if (post_avail < transform->maclen) {
1037 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1038 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1039 }
1040 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1041 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
1042 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1043 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1044 psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1045 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1046 size_t sign_mac_length = 0;
1047 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1048
1049 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
1050 transform->tls_version,
1051 transform->taglen);
1052
1053 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1054 status = psa_mac_sign_setup(&operation, transform->psa_mac_enc,
1055 transform->psa_mac_alg);
1056 if (status != PSA_SUCCESS) {
1057 goto hmac_failed_etm_disabled;
1058 }
1059
1060 status = psa_mac_update(&operation, add_data, add_data_len);
1061 if (status != PSA_SUCCESS) {
1062 goto hmac_failed_etm_disabled;
1063 }
1064
1065 status = psa_mac_update(&operation, data, rec->data_len);
1066 if (status != PSA_SUCCESS) {
1067 goto hmac_failed_etm_disabled;
1068 }
1069
1070 status = psa_mac_sign_finish(&operation, mac, MBEDTLS_SSL_MAC_ADD,
1071 &sign_mac_length);
1072 if (status != PSA_SUCCESS) {
1073 goto hmac_failed_etm_disabled;
1074 }
1075 #else
1076 ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, add_data,
1077 add_data_len);
1078 if (ret != 0) {
1079 goto hmac_failed_etm_disabled;
1080 }
1081 ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, data, rec->data_len);
1082 if (ret != 0) {
1083 goto hmac_failed_etm_disabled;
1084 }
1085 ret = mbedtls_md_hmac_finish(&transform->md_ctx_enc, mac);
1086 if (ret != 0) {
1087 goto hmac_failed_etm_disabled;
1088 }
1089 ret = mbedtls_md_hmac_reset(&transform->md_ctx_enc);
1090 if (ret != 0) {
1091 goto hmac_failed_etm_disabled;
1092 }
1093 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1094
1095 memcpy(data + rec->data_len, mac, transform->maclen);
1096 #endif
1097
1098 MBEDTLS_SSL_DEBUG_BUF(4, "computed mac", data + rec->data_len,
1099 transform->maclen);
1100
1101 rec->data_len += transform->maclen;
1102 post_avail -= transform->maclen;
1103 auth_done++;
1104
1105 hmac_failed_etm_disabled:
1106 mbedtls_platform_zeroize(mac, transform->maclen);
1107 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1108 ret = PSA_TO_MBEDTLS_ERR(status);
1109 status = psa_mac_abort(&operation);
1110 if (ret == 0 && status != PSA_SUCCESS) {
1111 ret = PSA_TO_MBEDTLS_ERR(status);
1112 }
1113 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1114 if (ret != 0) {
1115 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_hmac_xxx", ret);
1116 return ret;
1117 }
1118 }
1119 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
1120
1121 /*
1122 * Encrypt
1123 */
1124 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_STREAM)
1125 if (ssl_mode == MBEDTLS_SSL_MODE_STREAM) {
1126 MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
1127 "including %d bytes of padding",
1128 rec->data_len, 0));
1129
1130 /* The only supported stream cipher is "NULL",
1131 * so there's nothing to do here.*/
1132 } else
1133 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_STREAM */
1134
1135 #if defined(MBEDTLS_SSL_HAVE_AEAD)
1136 if (ssl_mode == MBEDTLS_SSL_MODE_AEAD) {
1137 unsigned char iv[12];
1138 unsigned char *dynamic_iv;
1139 size_t dynamic_iv_len;
1140 int dynamic_iv_is_explicit =
1141 ssl_transform_aead_dynamic_iv_is_explicit(transform);
1142 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1143 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1144 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1145 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1146
1147 /* Check that there's space for the authentication tag. */
1148 if (post_avail < transform->taglen) {
1149 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1150 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1151 }
1152
1153 /*
1154 * Build nonce for AEAD encryption.
1155 *
1156 * Note: In the case of CCM and GCM in TLS 1.2, the dynamic
1157 * part of the IV is prepended to the ciphertext and
1158 * can be chosen freely - in particular, it need not
1159 * agree with the record sequence number.
1160 * However, since ChaChaPoly as well as all AEAD modes
1161 * in TLS 1.3 use the record sequence number as the
1162 * dynamic part of the nonce, we uniformly use the
1163 * record sequence number here in all cases.
1164 */
1165 dynamic_iv = rec->ctr;
1166 dynamic_iv_len = sizeof(rec->ctr);
1167
1168 ssl_build_record_nonce(iv, sizeof(iv),
1169 transform->iv_enc,
1170 transform->fixed_ivlen,
1171 dynamic_iv,
1172 dynamic_iv_len);
1173
1174 /*
1175 * Build additional data for AEAD encryption.
1176 * This depends on the TLS version.
1177 */
1178 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
1179 transform->tls_version,
1180 transform->taglen);
1181
1182 MBEDTLS_SSL_DEBUG_BUF(4, "IV used (internal)",
1183 iv, transform->ivlen);
1184 MBEDTLS_SSL_DEBUG_BUF(4, "IV used (transmitted)",
1185 dynamic_iv,
1186 dynamic_iv_is_explicit ? dynamic_iv_len : 0);
1187 MBEDTLS_SSL_DEBUG_BUF(4, "additional data used for AEAD",
1188 add_data, add_data_len);
1189 MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
1190 "including 0 bytes of padding",
1191 rec->data_len));
1192
1193 /*
1194 * Encrypt and authenticate
1195 */
1196 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1197 status = psa_aead_encrypt(transform->psa_key_enc,
1198 transform->psa_alg,
1199 iv, transform->ivlen,
1200 add_data, add_data_len,
1201 data, rec->data_len,
1202 data, rec->buf_len - (data - rec->buf),
1203 &rec->data_len);
1204
1205 if (status != PSA_SUCCESS) {
1206 ret = PSA_TO_MBEDTLS_ERR(status);
1207 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_encrypt_buf", ret);
1208 return ret;
1209 }
1210 #else
1211 if ((ret = mbedtls_cipher_auth_encrypt_ext(&transform->cipher_ctx_enc,
1212 iv, transform->ivlen,
1213 add_data, add_data_len,
1214 data, rec->data_len, /* src */
1215 data, rec->buf_len - (size_t) (data - rec->buf), /* dst */
1216 &rec->data_len,
1217 transform->taglen)) != 0) {
1218 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_auth_encrypt_ext", ret);
1219 return ret;
1220 }
1221 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1222
1223 MBEDTLS_SSL_DEBUG_BUF(4, "after encrypt: tag",
1224 data + rec->data_len - transform->taglen,
1225 transform->taglen);
1226 /* Account for authentication tag. */
1227 post_avail -= transform->taglen;
1228
1229 /*
1230 * Prefix record content with dynamic IV in case it is explicit.
1231 */
1232 if (dynamic_iv_is_explicit != 0) {
1233 if (rec->data_offset < dynamic_iv_len) {
1234 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1235 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1236 }
1237
1238 memcpy(data - dynamic_iv_len, dynamic_iv, dynamic_iv_len);
1239 rec->data_offset -= dynamic_iv_len;
1240 rec->data_len += dynamic_iv_len;
1241 }
1242
1243 auth_done++;
1244 } else
1245 #endif /* MBEDTLS_SSL_HAVE_AEAD */
1246 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
1247 if (ssl_mode == MBEDTLS_SSL_MODE_CBC ||
1248 ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
1249 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1250 size_t padlen, i;
1251 size_t olen;
1252 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1253 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1254 size_t part_len;
1255 psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
1256 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1257
1258 /* Currently we're always using minimal padding
1259 * (up to 255 bytes would be allowed). */
1260 padlen = transform->ivlen - (rec->data_len + 1) % transform->ivlen;
1261 if (padlen == transform->ivlen) {
1262 padlen = 0;
1263 }
1264
1265 /* Check there's enough space in the buffer for the padding. */
1266 if (post_avail < padlen + 1) {
1267 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1268 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1269 }
1270
1271 for (i = 0; i <= padlen; i++) {
1272 data[rec->data_len + i] = (unsigned char) padlen;
1273 }
1274
1275 rec->data_len += padlen + 1;
1276 post_avail -= padlen + 1;
1277
1278 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1279 /*
1280 * Prepend per-record IV for block cipher in TLS v1.2 as per
1281 * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
1282 */
1283 if (f_rng == NULL) {
1284 MBEDTLS_SSL_DEBUG_MSG(1, ("No PRNG provided to encrypt_record routine"));
1285 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1286 }
1287
1288 if (rec->data_offset < transform->ivlen) {
1289 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1290 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1291 }
1292
1293 /*
1294 * Generate IV
1295 */
1296 ret = f_rng(p_rng, transform->iv_enc, transform->ivlen);
1297 if (ret != 0) {
1298 return ret;
1299 }
1300
1301 memcpy(data - transform->ivlen, transform->iv_enc, transform->ivlen);
1302 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1303
1304 MBEDTLS_SSL_DEBUG_MSG(3, ("before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", "
1305 "including %"
1306 MBEDTLS_PRINTF_SIZET
1307 " bytes of IV and %" MBEDTLS_PRINTF_SIZET " bytes of padding",
1308 rec->data_len, transform->ivlen,
1309 padlen + 1));
1310
1311 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1312 status = psa_cipher_encrypt_setup(&cipher_op,
1313 transform->psa_key_enc, transform->psa_alg);
1314
1315 if (status != PSA_SUCCESS) {
1316 ret = PSA_TO_MBEDTLS_ERR(status);
1317 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_encrypt_setup", ret);
1318 return ret;
1319 }
1320
1321 status = psa_cipher_set_iv(&cipher_op, transform->iv_enc, transform->ivlen);
1322
1323 if (status != PSA_SUCCESS) {
1324 ret = PSA_TO_MBEDTLS_ERR(status);
1325 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_set_iv", ret);
1326 return ret;
1327
1328 }
1329
1330 status = psa_cipher_update(&cipher_op,
1331 data, rec->data_len,
1332 data, rec->data_len, &olen);
1333
1334 if (status != PSA_SUCCESS) {
1335 ret = PSA_TO_MBEDTLS_ERR(status);
1336 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_update", ret);
1337 return ret;
1338
1339 }
1340
1341 status = psa_cipher_finish(&cipher_op,
1342 data + olen, rec->data_len - olen,
1343 &part_len);
1344
1345 if (status != PSA_SUCCESS) {
1346 ret = PSA_TO_MBEDTLS_ERR(status);
1347 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_finish", ret);
1348 return ret;
1349
1350 }
1351
1352 olen += part_len;
1353 #else
1354 if ((ret = mbedtls_cipher_crypt(&transform->cipher_ctx_enc,
1355 transform->iv_enc,
1356 transform->ivlen,
1357 data, rec->data_len,
1358 data, &olen)) != 0) {
1359 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_crypt", ret);
1360 return ret;
1361 }
1362 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1363
1364 if (rec->data_len != olen) {
1365 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1366 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1367 }
1368
1369 data -= transform->ivlen;
1370 rec->data_offset -= transform->ivlen;
1371 rec->data_len += transform->ivlen;
1372
1373 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1374 if (auth_done == 0) {
1375 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
1376 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1377 psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1378 size_t sign_mac_length = 0;
1379 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1380
1381 /* MAC(MAC_write_key, add_data, IV, ENC(content + padding + padding_length))
1382 */
1383
1384 if (post_avail < transform->maclen) {
1385 MBEDTLS_SSL_DEBUG_MSG(1, ("Buffer provided for encrypted record not large enough"));
1386 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1387 }
1388
1389 ssl_extract_add_data_from_record(add_data, &add_data_len,
1390 rec, transform->tls_version,
1391 transform->taglen);
1392
1393 MBEDTLS_SSL_DEBUG_MSG(3, ("using encrypt then mac"));
1394 MBEDTLS_SSL_DEBUG_BUF(4, "MAC'd meta-data", add_data,
1395 add_data_len);
1396 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1397 status = psa_mac_sign_setup(&operation, transform->psa_mac_enc,
1398 transform->psa_mac_alg);
1399 if (status != PSA_SUCCESS) {
1400 goto hmac_failed_etm_enabled;
1401 }
1402
1403 status = psa_mac_update(&operation, add_data, add_data_len);
1404 if (status != PSA_SUCCESS) {
1405 goto hmac_failed_etm_enabled;
1406 }
1407
1408 status = psa_mac_update(&operation, data, rec->data_len);
1409 if (status != PSA_SUCCESS) {
1410 goto hmac_failed_etm_enabled;
1411 }
1412
1413 status = psa_mac_sign_finish(&operation, mac, MBEDTLS_SSL_MAC_ADD,
1414 &sign_mac_length);
1415 if (status != PSA_SUCCESS) {
1416 goto hmac_failed_etm_enabled;
1417 }
1418 #else
1419
1420 ret = mbedtls_md_hmac_update(&transform->md_ctx_enc, add_data,
1421 add_data_len);
1422 if (ret != 0) {
1423 goto hmac_failed_etm_enabled;
1424 }
1425 ret = mbedtls_md_hmac_update(&transform->md_ctx_enc,
1426 data, rec->data_len);
1427 if (ret != 0) {
1428 goto hmac_failed_etm_enabled;
1429 }
1430 ret = mbedtls_md_hmac_finish(&transform->md_ctx_enc, mac);
1431 if (ret != 0) {
1432 goto hmac_failed_etm_enabled;
1433 }
1434 ret = mbedtls_md_hmac_reset(&transform->md_ctx_enc);
1435 if (ret != 0) {
1436 goto hmac_failed_etm_enabled;
1437 }
1438 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1439
1440 memcpy(data + rec->data_len, mac, transform->maclen);
1441
1442 rec->data_len += transform->maclen;
1443 post_avail -= transform->maclen;
1444 auth_done++;
1445
1446 hmac_failed_etm_enabled:
1447 mbedtls_platform_zeroize(mac, transform->maclen);
1448 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1449 ret = PSA_TO_MBEDTLS_ERR(status);
1450 status = psa_mac_abort(&operation);
1451 if (ret == 0 && status != PSA_SUCCESS) {
1452 ret = PSA_TO_MBEDTLS_ERR(status);
1453 }
1454 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1455 if (ret != 0) {
1456 MBEDTLS_SSL_DEBUG_RET(1, "HMAC calculation failed", ret);
1457 return ret;
1458 }
1459 }
1460 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1461 } else
1462 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */
1463 {
1464 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1465 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1466 }
1467
1468 /* Make extra sure authentication was performed, exactly once */
1469 if (auth_done != 1) {
1470 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1471 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1472 }
1473
1474 MBEDTLS_SSL_DEBUG_MSG(2, ("<= encrypt buf"));
1475
1476 return 0;
1477 }
1478
mbedtls_ssl_decrypt_buf(mbedtls_ssl_context const * ssl,mbedtls_ssl_transform * transform,mbedtls_record * rec)1479 int mbedtls_ssl_decrypt_buf(mbedtls_ssl_context const *ssl,
1480 mbedtls_ssl_transform *transform,
1481 mbedtls_record *rec)
1482 {
1483 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) || defined(MBEDTLS_SSL_HAVE_AEAD)
1484 size_t olen;
1485 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC || MBEDTLS_SSL_HAVE_AEAD */
1486 mbedtls_ssl_mode_t ssl_mode;
1487 int ret;
1488
1489 int auth_done = 0;
1490 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
1491 size_t padlen = 0;
1492 mbedtls_ct_condition_t correct = MBEDTLS_CT_TRUE;
1493 #endif
1494 unsigned char *data;
1495 /* For an explanation of the additional data length see
1496 * the description of ssl_extract_add_data_from_record().
1497 */
1498 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1499 unsigned char add_data[23 + MBEDTLS_SSL_CID_IN_LEN_MAX];
1500 #else
1501 unsigned char add_data[13];
1502 #endif
1503 size_t add_data_len;
1504
1505 #if !defined(MBEDTLS_DEBUG_C)
1506 ssl = NULL; /* make sure we don't use it except for debug */
1507 ((void) ssl);
1508 #endif
1509
1510 MBEDTLS_SSL_DEBUG_MSG(2, ("=> decrypt buf"));
1511 if (rec == NULL ||
1512 rec->buf == NULL ||
1513 rec->buf_len < rec->data_offset ||
1514 rec->buf_len - rec->data_offset < rec->data_len) {
1515 MBEDTLS_SSL_DEBUG_MSG(1, ("bad record structure provided to decrypt_buf"));
1516 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1517 }
1518
1519 data = rec->buf + rec->data_offset;
1520 ssl_mode = mbedtls_ssl_get_mode_from_transform(transform);
1521
1522 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1523 /*
1524 * Match record's CID with incoming CID.
1525 */
1526 if (rec->cid_len != transform->in_cid_len ||
1527 memcmp(rec->cid, transform->in_cid, rec->cid_len) != 0) {
1528 return MBEDTLS_ERR_SSL_UNEXPECTED_CID;
1529 }
1530 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1531
1532 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_STREAM)
1533 if (ssl_mode == MBEDTLS_SSL_MODE_STREAM) {
1534 if (rec->data_len < transform->maclen) {
1535 MBEDTLS_SSL_DEBUG_MSG(1,
1536 ("Record too short for MAC:"
1537 " %" MBEDTLS_PRINTF_SIZET " < %" MBEDTLS_PRINTF_SIZET,
1538 rec->data_len, transform->maclen));
1539 return MBEDTLS_ERR_SSL_INVALID_MAC;
1540 }
1541
1542 /* The only supported stream cipher is "NULL",
1543 * so there's no encryption to do here.*/
1544 } else
1545 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_STREAM */
1546 #if defined(MBEDTLS_SSL_HAVE_AEAD)
1547 if (ssl_mode == MBEDTLS_SSL_MODE_AEAD) {
1548 unsigned char iv[12];
1549 unsigned char *dynamic_iv;
1550 size_t dynamic_iv_len;
1551 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1552 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1553 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1554
1555 /*
1556 * Extract dynamic part of nonce for AEAD decryption.
1557 *
1558 * Note: In the case of CCM and GCM in TLS 1.2, the dynamic
1559 * part of the IV is prepended to the ciphertext and
1560 * can be chosen freely - in particular, it need not
1561 * agree with the record sequence number.
1562 */
1563 dynamic_iv_len = sizeof(rec->ctr);
1564 if (ssl_transform_aead_dynamic_iv_is_explicit(transform) == 1) {
1565 if (rec->data_len < dynamic_iv_len) {
1566 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1567 " ) < explicit_iv_len (%" MBEDTLS_PRINTF_SIZET ") ",
1568 rec->data_len,
1569 dynamic_iv_len));
1570 return MBEDTLS_ERR_SSL_INVALID_MAC;
1571 }
1572 dynamic_iv = data;
1573
1574 data += dynamic_iv_len;
1575 rec->data_offset += dynamic_iv_len;
1576 rec->data_len -= dynamic_iv_len;
1577 } else {
1578 dynamic_iv = rec->ctr;
1579 }
1580
1581 /* Check that there's space for the authentication tag. */
1582 if (rec->data_len < transform->taglen) {
1583 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1584 ") < taglen (%" MBEDTLS_PRINTF_SIZET ") ",
1585 rec->data_len,
1586 transform->taglen));
1587 return MBEDTLS_ERR_SSL_INVALID_MAC;
1588 }
1589 rec->data_len -= transform->taglen;
1590
1591 /*
1592 * Prepare nonce from dynamic and static parts.
1593 */
1594 ssl_build_record_nonce(iv, sizeof(iv),
1595 transform->iv_dec,
1596 transform->fixed_ivlen,
1597 dynamic_iv,
1598 dynamic_iv_len);
1599
1600 /*
1601 * Build additional data for AEAD encryption.
1602 * This depends on the TLS version.
1603 */
1604 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
1605 transform->tls_version,
1606 transform->taglen);
1607 MBEDTLS_SSL_DEBUG_BUF(4, "additional data used for AEAD",
1608 add_data, add_data_len);
1609
1610 /* Because of the check above, we know that there are
1611 * explicit_iv_len Bytes preceding data, and taglen
1612 * bytes following data + data_len. This justifies
1613 * the debug message and the invocation of
1614 * mbedtls_cipher_auth_decrypt_ext() below. */
1615
1616 MBEDTLS_SSL_DEBUG_BUF(4, "IV used", iv, transform->ivlen);
1617 MBEDTLS_SSL_DEBUG_BUF(4, "TAG used", data + rec->data_len,
1618 transform->taglen);
1619
1620 /*
1621 * Decrypt and authenticate
1622 */
1623 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1624 status = psa_aead_decrypt(transform->psa_key_dec,
1625 transform->psa_alg,
1626 iv, transform->ivlen,
1627 add_data, add_data_len,
1628 data, rec->data_len + transform->taglen,
1629 data, rec->buf_len - (data - rec->buf),
1630 &olen);
1631
1632 if (status != PSA_SUCCESS) {
1633 ret = PSA_TO_MBEDTLS_ERR(status);
1634 MBEDTLS_SSL_DEBUG_RET(1, "psa_aead_decrypt", ret);
1635 return ret;
1636 }
1637 #else
1638 if ((ret = mbedtls_cipher_auth_decrypt_ext
1639 (&transform->cipher_ctx_dec,
1640 iv, transform->ivlen,
1641 add_data, add_data_len,
1642 data, rec->data_len + transform->taglen, /* src */
1643 data, rec->buf_len - (size_t) (data - rec->buf), &olen, /* dst */
1644 transform->taglen)) != 0) {
1645 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_auth_decrypt_ext", ret);
1646
1647 if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
1648 return MBEDTLS_ERR_SSL_INVALID_MAC;
1649 }
1650
1651 return ret;
1652 }
1653 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1654
1655 auth_done++;
1656
1657 /* Double-check that AEAD decryption doesn't change content length. */
1658 if (olen != rec->data_len) {
1659 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1660 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1661 }
1662 } else
1663 #endif /* MBEDTLS_SSL_HAVE_AEAD */
1664 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
1665 if (ssl_mode == MBEDTLS_SSL_MODE_CBC ||
1666 ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
1667 size_t minlen = 0;
1668 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1669 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1670 size_t part_len;
1671 psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
1672 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1673
1674 /*
1675 * Check immediate ciphertext sanity
1676 */
1677 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1678 /* The ciphertext is prefixed with the CBC IV. */
1679 minlen += transform->ivlen;
1680 #endif
1681
1682 /* Size considerations:
1683 *
1684 * - The CBC cipher text must not be empty and hence
1685 * at least of size transform->ivlen.
1686 *
1687 * Together with the potential IV-prefix, this explains
1688 * the first of the two checks below.
1689 *
1690 * - The record must contain a MAC, either in plain or
1691 * encrypted, depending on whether Encrypt-then-MAC
1692 * is used or not.
1693 * - If it is, the message contains the IV-prefix,
1694 * the CBC ciphertext, and the MAC.
1695 * - If it is not, the padded plaintext, and hence
1696 * the CBC ciphertext, has at least length maclen + 1
1697 * because there is at least the padding length byte.
1698 *
1699 * As the CBC ciphertext is not empty, both cases give the
1700 * lower bound minlen + maclen + 1 on the record size, which
1701 * we test for in the second check below.
1702 */
1703 if (rec->data_len < minlen + transform->ivlen ||
1704 rec->data_len < minlen + transform->maclen + 1) {
1705 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1706 ") < max( ivlen(%" MBEDTLS_PRINTF_SIZET
1707 "), maclen (%" MBEDTLS_PRINTF_SIZET ") "
1708 "+ 1 ) ( + expl IV )",
1709 rec->data_len,
1710 transform->ivlen,
1711 transform->maclen));
1712 return MBEDTLS_ERR_SSL_INVALID_MAC;
1713 }
1714
1715 /*
1716 * Authenticate before decrypt if enabled
1717 */
1718 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1719 if (ssl_mode == MBEDTLS_SSL_MODE_CBC_ETM) {
1720 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1721 psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1722 #else
1723 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
1724 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1725
1726 MBEDTLS_SSL_DEBUG_MSG(3, ("using encrypt then mac"));
1727
1728 /* Update data_len in tandem with add_data.
1729 *
1730 * The subtraction is safe because of the previous check
1731 * data_len >= minlen + maclen + 1.
1732 *
1733 * Afterwards, we know that data + data_len is followed by at
1734 * least maclen Bytes, which justifies the call to
1735 * mbedtls_ct_memcmp() below.
1736 *
1737 * Further, we still know that data_len > minlen */
1738 rec->data_len -= transform->maclen;
1739 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
1740 transform->tls_version,
1741 transform->taglen);
1742
1743 /* Calculate expected MAC. */
1744 MBEDTLS_SSL_DEBUG_BUF(4, "MAC'd meta-data", add_data,
1745 add_data_len);
1746 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1747 status = psa_mac_verify_setup(&operation, transform->psa_mac_dec,
1748 transform->psa_mac_alg);
1749 if (status != PSA_SUCCESS) {
1750 goto hmac_failed_etm_enabled;
1751 }
1752
1753 status = psa_mac_update(&operation, add_data, add_data_len);
1754 if (status != PSA_SUCCESS) {
1755 goto hmac_failed_etm_enabled;
1756 }
1757
1758 status = psa_mac_update(&operation, data, rec->data_len);
1759 if (status != PSA_SUCCESS) {
1760 goto hmac_failed_etm_enabled;
1761 }
1762
1763 /* Compare expected MAC with MAC at the end of the record. */
1764 status = psa_mac_verify_finish(&operation, data + rec->data_len,
1765 transform->maclen);
1766 if (status != PSA_SUCCESS) {
1767 goto hmac_failed_etm_enabled;
1768 }
1769 #else
1770 ret = mbedtls_md_hmac_update(&transform->md_ctx_dec, add_data,
1771 add_data_len);
1772 if (ret != 0) {
1773 goto hmac_failed_etm_enabled;
1774 }
1775 ret = mbedtls_md_hmac_update(&transform->md_ctx_dec,
1776 data, rec->data_len);
1777 if (ret != 0) {
1778 goto hmac_failed_etm_enabled;
1779 }
1780 ret = mbedtls_md_hmac_finish(&transform->md_ctx_dec, mac_expect);
1781 if (ret != 0) {
1782 goto hmac_failed_etm_enabled;
1783 }
1784 ret = mbedtls_md_hmac_reset(&transform->md_ctx_dec);
1785 if (ret != 0) {
1786 goto hmac_failed_etm_enabled;
1787 }
1788
1789 MBEDTLS_SSL_DEBUG_BUF(4, "message mac", data + rec->data_len,
1790 transform->maclen);
1791 MBEDTLS_SSL_DEBUG_BUF(4, "expected mac", mac_expect,
1792 transform->maclen);
1793
1794 /* Compare expected MAC with MAC at the end of the record. */
1795 if (mbedtls_ct_memcmp(data + rec->data_len, mac_expect,
1796 transform->maclen) != 0) {
1797 MBEDTLS_SSL_DEBUG_MSG(1, ("message mac does not match"));
1798 ret = MBEDTLS_ERR_SSL_INVALID_MAC;
1799 goto hmac_failed_etm_enabled;
1800 }
1801 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1802 auth_done++;
1803
1804 hmac_failed_etm_enabled:
1805 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1806 ret = PSA_TO_MBEDTLS_ERR(status);
1807 status = psa_mac_abort(&operation);
1808 if (ret == 0 && status != PSA_SUCCESS) {
1809 ret = PSA_TO_MBEDTLS_ERR(status);
1810 }
1811 #else
1812 mbedtls_platform_zeroize(mac_expect, transform->maclen);
1813 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1814 if (ret != 0) {
1815 if (ret != MBEDTLS_ERR_SSL_INVALID_MAC) {
1816 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_hmac_xxx", ret);
1817 }
1818 return ret;
1819 }
1820 }
1821 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1822
1823 /*
1824 * Check length sanity
1825 */
1826
1827 /* We know from above that data_len > minlen >= 0,
1828 * so the following check in particular implies that
1829 * data_len >= minlen + ivlen ( = minlen or 2 * minlen ). */
1830 if (rec->data_len % transform->ivlen != 0) {
1831 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1832 ") %% ivlen (%" MBEDTLS_PRINTF_SIZET ") != 0",
1833 rec->data_len, transform->ivlen));
1834 return MBEDTLS_ERR_SSL_INVALID_MAC;
1835 }
1836
1837 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1838 /*
1839 * Initialize for prepended IV for block cipher in TLS v1.2
1840 */
1841 /* Safe because data_len >= minlen + ivlen = 2 * ivlen. */
1842 memcpy(transform->iv_dec, data, transform->ivlen);
1843
1844 data += transform->ivlen;
1845 rec->data_offset += transform->ivlen;
1846 rec->data_len -= transform->ivlen;
1847 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1848
1849 /* We still have data_len % ivlen == 0 and data_len >= ivlen here. */
1850
1851 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1852 status = psa_cipher_decrypt_setup(&cipher_op,
1853 transform->psa_key_dec, transform->psa_alg);
1854
1855 if (status != PSA_SUCCESS) {
1856 ret = PSA_TO_MBEDTLS_ERR(status);
1857 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_decrypt_setup", ret);
1858 return ret;
1859 }
1860
1861 status = psa_cipher_set_iv(&cipher_op, transform->iv_dec, transform->ivlen);
1862
1863 if (status != PSA_SUCCESS) {
1864 ret = PSA_TO_MBEDTLS_ERR(status);
1865 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_set_iv", ret);
1866 return ret;
1867 }
1868
1869 status = psa_cipher_update(&cipher_op,
1870 data, rec->data_len,
1871 data, rec->data_len, &olen);
1872
1873 if (status != PSA_SUCCESS) {
1874 ret = PSA_TO_MBEDTLS_ERR(status);
1875 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_update", ret);
1876 return ret;
1877 }
1878
1879 status = psa_cipher_finish(&cipher_op,
1880 data + olen, rec->data_len - olen,
1881 &part_len);
1882
1883 if (status != PSA_SUCCESS) {
1884 ret = PSA_TO_MBEDTLS_ERR(status);
1885 MBEDTLS_SSL_DEBUG_RET(1, "psa_cipher_finish", ret);
1886 return ret;
1887 }
1888
1889 olen += part_len;
1890 #else
1891
1892 if ((ret = mbedtls_cipher_crypt(&transform->cipher_ctx_dec,
1893 transform->iv_dec, transform->ivlen,
1894 data, rec->data_len, data, &olen)) != 0) {
1895 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_crypt", ret);
1896 return ret;
1897 }
1898 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1899
1900 /* Double-check that length hasn't changed during decryption. */
1901 if (rec->data_len != olen) {
1902 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1903 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1904 }
1905
1906 /* Safe since data_len >= minlen + maclen + 1, so after having
1907 * subtracted at most minlen and maclen up to this point,
1908 * data_len > 0 (because of data_len % ivlen == 0, it's actually
1909 * >= ivlen ). */
1910 padlen = data[rec->data_len - 1];
1911
1912 if (auth_done == 1) {
1913 const mbedtls_ct_condition_t ge = mbedtls_ct_uint_ge(
1914 rec->data_len,
1915 padlen + 1);
1916 correct = mbedtls_ct_bool_and(ge, correct);
1917 padlen = mbedtls_ct_size_if_else_0(ge, padlen);
1918 } else {
1919 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1920 if (rec->data_len < transform->maclen + padlen + 1) {
1921 MBEDTLS_SSL_DEBUG_MSG(1, ("msglen (%" MBEDTLS_PRINTF_SIZET
1922 ") < maclen (%" MBEDTLS_PRINTF_SIZET
1923 ") + padlen (%" MBEDTLS_PRINTF_SIZET ")",
1924 rec->data_len,
1925 transform->maclen,
1926 padlen + 1));
1927 }
1928 #endif
1929 const mbedtls_ct_condition_t ge = mbedtls_ct_uint_ge(
1930 rec->data_len,
1931 transform->maclen + padlen + 1);
1932 correct = mbedtls_ct_bool_and(ge, correct);
1933 padlen = mbedtls_ct_size_if_else_0(ge, padlen);
1934 }
1935
1936 padlen++;
1937
1938 /* Regardless of the validity of the padding,
1939 * we have data_len >= padlen here. */
1940
1941 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1942 /* The padding check involves a series of up to 256
1943 * consecutive memory reads at the end of the record
1944 * plaintext buffer. In order to hide the length and
1945 * validity of the padding, always perform exactly
1946 * `min(256,plaintext_len)` reads (but take into account
1947 * only the last `padlen` bytes for the padding check). */
1948 size_t pad_count = 0;
1949 volatile unsigned char * const check = data;
1950
1951 /* Index of first padding byte; it has been ensured above
1952 * that the subtraction is safe. */
1953 size_t const padding_idx = rec->data_len - padlen;
1954 size_t const num_checks = rec->data_len <= 256 ? rec->data_len : 256;
1955 size_t const start_idx = rec->data_len - num_checks;
1956 size_t idx;
1957
1958 for (idx = start_idx; idx < rec->data_len; idx++) {
1959 /* pad_count += (idx >= padding_idx) &&
1960 * (check[idx] == padlen - 1);
1961 */
1962 const mbedtls_ct_condition_t a = mbedtls_ct_uint_ge(idx, padding_idx);
1963 size_t increment = mbedtls_ct_size_if_else_0(a, 1);
1964 const mbedtls_ct_condition_t b = mbedtls_ct_uint_eq(check[idx], padlen - 1);
1965 increment = mbedtls_ct_size_if_else_0(b, increment);
1966 pad_count += increment;
1967 }
1968 correct = mbedtls_ct_bool_and(mbedtls_ct_uint_eq(pad_count, padlen), correct);
1969
1970 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1971 if (padlen > 0 && correct == MBEDTLS_CT_FALSE) {
1972 MBEDTLS_SSL_DEBUG_MSG(1, ("bad padding byte detected"));
1973 }
1974 #endif
1975 padlen = mbedtls_ct_size_if_else_0(correct, padlen);
1976
1977 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1978
1979 /* If the padding was found to be invalid, padlen == 0
1980 * and the subtraction is safe. If the padding was found valid,
1981 * padlen hasn't been changed and the previous assertion
1982 * data_len >= padlen still holds. */
1983 rec->data_len -= padlen;
1984 } else
1985 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */
1986 {
1987 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1988 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1989 }
1990
1991 #if defined(MBEDTLS_SSL_DEBUG_ALL)
1992 MBEDTLS_SSL_DEBUG_BUF(4, "raw buffer after decryption",
1993 data, rec->data_len);
1994 #endif
1995
1996 /*
1997 * Authenticate if not done yet.
1998 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
1999 */
2000 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
2001 if (auth_done == 0) {
2002 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD] = { 0 };
2003 unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD] = { 0 };
2004
2005 /* For CBC+MAC, If the initial value of padlen was such that
2006 * data_len < maclen + padlen + 1, then padlen
2007 * got reset to 1, and the initial check
2008 * data_len >= minlen + maclen + 1
2009 * guarantees that at this point we still
2010 * have at least data_len >= maclen.
2011 *
2012 * If the initial value of padlen was such that
2013 * data_len >= maclen + padlen + 1, then we have
2014 * subtracted either padlen + 1 (if the padding was correct)
2015 * or 0 (if the padding was incorrect) since then,
2016 * hence data_len >= maclen in any case.
2017 *
2018 * For stream ciphers, we checked above that
2019 * data_len >= maclen.
2020 */
2021 rec->data_len -= transform->maclen;
2022 ssl_extract_add_data_from_record(add_data, &add_data_len, rec,
2023 transform->tls_version,
2024 transform->taglen);
2025
2026 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2027 /*
2028 * The next two sizes are the minimum and maximum values of
2029 * data_len over all padlen values.
2030 *
2031 * They're independent of padlen, since we previously did
2032 * data_len -= padlen.
2033 *
2034 * Note that max_len + maclen is never more than the buffer
2035 * length, as we previously did in_msglen -= maclen too.
2036 */
2037 const size_t max_len = rec->data_len + padlen;
2038 const size_t min_len = (max_len > 256) ? max_len - 256 : 0;
2039
2040 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2041 ret = mbedtls_ct_hmac(transform->psa_mac_dec,
2042 transform->psa_mac_alg,
2043 add_data, add_data_len,
2044 data, rec->data_len, min_len, max_len,
2045 mac_expect);
2046 #else
2047 ret = mbedtls_ct_hmac(&transform->md_ctx_dec,
2048 add_data, add_data_len,
2049 data, rec->data_len, min_len, max_len,
2050 mac_expect);
2051 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2052 if (ret != 0) {
2053 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ct_hmac", ret);
2054 goto hmac_failed_etm_disabled;
2055 }
2056
2057 mbedtls_ct_memcpy_offset(mac_peer, data,
2058 rec->data_len,
2059 min_len, max_len,
2060 transform->maclen);
2061 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2062
2063 #if defined(MBEDTLS_SSL_DEBUG_ALL)
2064 MBEDTLS_SSL_DEBUG_BUF(4, "expected mac", mac_expect, transform->maclen);
2065 MBEDTLS_SSL_DEBUG_BUF(4, "message mac", mac_peer, transform->maclen);
2066 #endif
2067
2068 if (mbedtls_ct_memcmp(mac_peer, mac_expect,
2069 transform->maclen) != 0) {
2070 #if defined(MBEDTLS_SSL_DEBUG_ALL)
2071 MBEDTLS_SSL_DEBUG_MSG(1, ("message mac does not match"));
2072 #endif
2073 correct = MBEDTLS_CT_FALSE;
2074 }
2075 auth_done++;
2076
2077 hmac_failed_etm_disabled:
2078 mbedtls_platform_zeroize(mac_peer, transform->maclen);
2079 mbedtls_platform_zeroize(mac_expect, transform->maclen);
2080 if (ret != 0) {
2081 return ret;
2082 }
2083 }
2084
2085 /*
2086 * Finally check the correct flag
2087 */
2088 if (correct == MBEDTLS_CT_FALSE) {
2089 return MBEDTLS_ERR_SSL_INVALID_MAC;
2090 }
2091 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
2092
2093 /* Make extra sure authentication was performed, exactly once */
2094 if (auth_done != 1) {
2095 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2096 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2097 }
2098
2099 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2100 if (transform->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2101 /* Remove inner padding and infer true content type. */
2102 ret = ssl_parse_inner_plaintext(data, &rec->data_len,
2103 &rec->type);
2104
2105 if (ret != 0) {
2106 return MBEDTLS_ERR_SSL_INVALID_RECORD;
2107 }
2108 }
2109 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2110
2111 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2112 if (rec->cid_len != 0) {
2113 ret = ssl_parse_inner_plaintext(data, &rec->data_len,
2114 &rec->type);
2115 if (ret != 0) {
2116 return MBEDTLS_ERR_SSL_INVALID_RECORD;
2117 }
2118 }
2119 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2120
2121 MBEDTLS_SSL_DEBUG_MSG(2, ("<= decrypt buf"));
2122
2123 return 0;
2124 }
2125
2126 #undef MAC_NONE
2127 #undef MAC_PLAINTEXT
2128 #undef MAC_CIPHERTEXT
2129
2130 /*
2131 * Fill the input message buffer by appending data to it.
2132 * The amount of data already fetched is in ssl->in_left.
2133 *
2134 * If we return 0, is it guaranteed that (at least) nb_want bytes are
2135 * available (from this read and/or a previous one). Otherwise, an error code
2136 * is returned (possibly EOF or WANT_READ).
2137 *
2138 * With stream transport (TLS) on success ssl->in_left == nb_want, but
2139 * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
2140 * since we always read a whole datagram at once.
2141 *
2142 * For DTLS, it is up to the caller to set ssl->next_record_offset when
2143 * they're done reading a record.
2144 */
mbedtls_ssl_fetch_input(mbedtls_ssl_context * ssl,size_t nb_want)2145 int mbedtls_ssl_fetch_input(mbedtls_ssl_context *ssl, size_t nb_want)
2146 {
2147 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2148 size_t len;
2149 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2150 size_t in_buf_len = ssl->in_buf_len;
2151 #else
2152 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
2153 #endif
2154
2155 MBEDTLS_SSL_DEBUG_MSG(2, ("=> fetch input"));
2156
2157 if (ssl->f_recv == NULL && ssl->f_recv_timeout == NULL) {
2158 MBEDTLS_SSL_DEBUG_MSG(1, ("Bad usage of mbedtls_ssl_set_bio() "));
2159 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2160 }
2161
2162 if (nb_want > in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf)) {
2163 MBEDTLS_SSL_DEBUG_MSG(1, ("requesting more data than fits"));
2164 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2165 }
2166
2167 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2168 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2169 uint32_t timeout;
2170
2171 /*
2172 * The point is, we need to always read a full datagram at once, so we
2173 * sometimes read more then requested, and handle the additional data.
2174 * It could be the rest of the current record (while fetching the
2175 * header) and/or some other records in the same datagram.
2176 */
2177
2178 /*
2179 * Move to the next record in the already read datagram if applicable
2180 */
2181 if (ssl->next_record_offset != 0) {
2182 if (ssl->in_left < ssl->next_record_offset) {
2183 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2184 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2185 }
2186
2187 ssl->in_left -= ssl->next_record_offset;
2188
2189 if (ssl->in_left != 0) {
2190 MBEDTLS_SSL_DEBUG_MSG(2, ("next record in same datagram, offset: %"
2191 MBEDTLS_PRINTF_SIZET,
2192 ssl->next_record_offset));
2193 memmove(ssl->in_hdr,
2194 ssl->in_hdr + ssl->next_record_offset,
2195 ssl->in_left);
2196 }
2197
2198 ssl->next_record_offset = 0;
2199 }
2200
2201 MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
2202 ", nb_want: %" MBEDTLS_PRINTF_SIZET,
2203 ssl->in_left, nb_want));
2204
2205 /*
2206 * Done if we already have enough data.
2207 */
2208 if (nb_want <= ssl->in_left) {
2209 MBEDTLS_SSL_DEBUG_MSG(2, ("<= fetch input"));
2210 return 0;
2211 }
2212
2213 /*
2214 * A record can't be split across datagrams. If we need to read but
2215 * are not at the beginning of a new record, the caller did something
2216 * wrong.
2217 */
2218 if (ssl->in_left != 0) {
2219 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2220 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2221 }
2222
2223 /*
2224 * Don't even try to read if time's out already.
2225 * This avoids by-passing the timer when repeatedly receiving messages
2226 * that will end up being dropped.
2227 */
2228 if (mbedtls_ssl_check_timer(ssl) != 0) {
2229 MBEDTLS_SSL_DEBUG_MSG(2, ("timer has expired"));
2230 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2231 } else {
2232 len = in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf);
2233
2234 if (mbedtls_ssl_is_handshake_over(ssl) == 0) {
2235 timeout = ssl->handshake->retransmit_timeout;
2236 } else {
2237 timeout = ssl->conf->read_timeout;
2238 }
2239
2240 MBEDTLS_SSL_DEBUG_MSG(3, ("f_recv_timeout: %lu ms", (unsigned long) timeout));
2241
2242 if (ssl->f_recv_timeout != NULL) {
2243 ret = ssl->f_recv_timeout(ssl->p_bio, ssl->in_hdr, len,
2244 timeout);
2245 } else {
2246 ret = ssl->f_recv(ssl->p_bio, ssl->in_hdr, len);
2247 }
2248
2249 MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_recv(_timeout)", ret);
2250
2251 if (ret == 0) {
2252 return MBEDTLS_ERR_SSL_CONN_EOF;
2253 }
2254 }
2255
2256 if (ret == MBEDTLS_ERR_SSL_TIMEOUT) {
2257 MBEDTLS_SSL_DEBUG_MSG(2, ("timeout"));
2258 mbedtls_ssl_set_timer(ssl, 0);
2259
2260 if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
2261 if (ssl_double_retransmit_timeout(ssl) != 0) {
2262 MBEDTLS_SSL_DEBUG_MSG(1, ("handshake timeout"));
2263 return MBEDTLS_ERR_SSL_TIMEOUT;
2264 }
2265
2266 if ((ret = mbedtls_ssl_resend(ssl)) != 0) {
2267 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend", ret);
2268 return ret;
2269 }
2270
2271 return MBEDTLS_ERR_SSL_WANT_READ;
2272 }
2273 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2274 else if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
2275 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
2276 if ((ret = mbedtls_ssl_resend_hello_request(ssl)) != 0) {
2277 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend_hello_request",
2278 ret);
2279 return ret;
2280 }
2281
2282 return MBEDTLS_ERR_SSL_WANT_READ;
2283 }
2284 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2285 }
2286
2287 if (ret < 0) {
2288 return ret;
2289 }
2290
2291 ssl->in_left = ret;
2292 } else
2293 #endif
2294 {
2295 MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
2296 ", nb_want: %" MBEDTLS_PRINTF_SIZET,
2297 ssl->in_left, nb_want));
2298
2299 while (ssl->in_left < nb_want) {
2300 len = nb_want - ssl->in_left;
2301
2302 if (mbedtls_ssl_check_timer(ssl) != 0) {
2303 ret = MBEDTLS_ERR_SSL_TIMEOUT;
2304 } else {
2305 if (ssl->f_recv_timeout != NULL) {
2306 ret = ssl->f_recv_timeout(ssl->p_bio,
2307 ssl->in_hdr + ssl->in_left, len,
2308 ssl->conf->read_timeout);
2309 } else {
2310 ret = ssl->f_recv(ssl->p_bio,
2311 ssl->in_hdr + ssl->in_left, len);
2312 }
2313 }
2314
2315 MBEDTLS_SSL_DEBUG_MSG(2, ("in_left: %" MBEDTLS_PRINTF_SIZET
2316 ", nb_want: %" MBEDTLS_PRINTF_SIZET,
2317 ssl->in_left, nb_want));
2318 MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_recv(_timeout)", ret);
2319
2320 if (ret == 0) {
2321 return MBEDTLS_ERR_SSL_CONN_EOF;
2322 }
2323
2324 if (ret < 0) {
2325 return ret;
2326 }
2327
2328 if ((size_t) ret > len) {
2329 MBEDTLS_SSL_DEBUG_MSG(1,
2330 ("f_recv returned %d bytes but only %" MBEDTLS_PRINTF_SIZET
2331 " were requested",
2332 ret, len));
2333 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2334 }
2335
2336 ssl->in_left += ret;
2337 }
2338 }
2339
2340 MBEDTLS_SSL_DEBUG_MSG(2, ("<= fetch input"));
2341
2342 return 0;
2343 }
2344
2345 /*
2346 * Flush any data not yet written
2347 */
mbedtls_ssl_flush_output(mbedtls_ssl_context * ssl)2348 int mbedtls_ssl_flush_output(mbedtls_ssl_context *ssl)
2349 {
2350 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2351 unsigned char *buf;
2352
2353 MBEDTLS_SSL_DEBUG_MSG(2, ("=> flush output"));
2354
2355 if (ssl->f_send == NULL) {
2356 MBEDTLS_SSL_DEBUG_MSG(1, ("Bad usage of mbedtls_ssl_set_bio() "));
2357 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2358 }
2359
2360 /* Avoid incrementing counter if data is flushed */
2361 if (ssl->out_left == 0) {
2362 MBEDTLS_SSL_DEBUG_MSG(2, ("<= flush output"));
2363 return 0;
2364 }
2365
2366 while (ssl->out_left > 0) {
2367 MBEDTLS_SSL_DEBUG_MSG(2, ("message length: %" MBEDTLS_PRINTF_SIZET
2368 ", out_left: %" MBEDTLS_PRINTF_SIZET,
2369 mbedtls_ssl_out_hdr_len(ssl) + ssl->out_msglen, ssl->out_left));
2370
2371 buf = ssl->out_hdr - ssl->out_left;
2372 ret = ssl->f_send(ssl->p_bio, buf, ssl->out_left);
2373
2374 MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_send", ret);
2375
2376 if (ret <= 0) {
2377 return ret;
2378 }
2379
2380 if ((size_t) ret > ssl->out_left) {
2381 MBEDTLS_SSL_DEBUG_MSG(1,
2382 ("f_send returned %d bytes but only %" MBEDTLS_PRINTF_SIZET
2383 " bytes were sent",
2384 ret, ssl->out_left));
2385 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2386 }
2387
2388 ssl->out_left -= ret;
2389 }
2390
2391 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2392 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2393 ssl->out_hdr = ssl->out_buf;
2394 } else
2395 #endif
2396 {
2397 ssl->out_hdr = ssl->out_buf + 8;
2398 }
2399 mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
2400
2401 MBEDTLS_SSL_DEBUG_MSG(2, ("<= flush output"));
2402
2403 return 0;
2404 }
2405
2406 /*
2407 * Functions to handle the DTLS retransmission state machine
2408 */
2409 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2410 /*
2411 * Append current handshake message to current outgoing flight
2412 */
2413 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_flight_append(mbedtls_ssl_context * ssl)2414 static int ssl_flight_append(mbedtls_ssl_context *ssl)
2415 {
2416 mbedtls_ssl_flight_item *msg;
2417 MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_flight_append"));
2418 MBEDTLS_SSL_DEBUG_BUF(4, "message appended to flight",
2419 ssl->out_msg, ssl->out_msglen);
2420
2421 /* Allocate space for current message */
2422 if ((msg = mbedtls_calloc(1, sizeof(mbedtls_ssl_flight_item))) == NULL) {
2423 MBEDTLS_SSL_DEBUG_MSG(1, ("alloc %" MBEDTLS_PRINTF_SIZET " bytes failed",
2424 sizeof(mbedtls_ssl_flight_item)));
2425 return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2426 }
2427
2428 if ((msg->p = mbedtls_calloc(1, ssl->out_msglen)) == NULL) {
2429 MBEDTLS_SSL_DEBUG_MSG(1, ("alloc %" MBEDTLS_PRINTF_SIZET " bytes failed",
2430 ssl->out_msglen));
2431 mbedtls_free(msg);
2432 return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2433 }
2434
2435 /* Copy current handshake message with headers */
2436 memcpy(msg->p, ssl->out_msg, ssl->out_msglen);
2437 msg->len = ssl->out_msglen;
2438 msg->type = ssl->out_msgtype;
2439 msg->next = NULL;
2440
2441 /* Append to the current flight */
2442 if (ssl->handshake->flight == NULL) {
2443 ssl->handshake->flight = msg;
2444 } else {
2445 mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
2446 while (cur->next != NULL) {
2447 cur = cur->next;
2448 }
2449 cur->next = msg;
2450 }
2451
2452 MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_flight_append"));
2453 return 0;
2454 }
2455
2456 /*
2457 * Free the current flight of handshake messages
2458 */
mbedtls_ssl_flight_free(mbedtls_ssl_flight_item * flight)2459 void mbedtls_ssl_flight_free(mbedtls_ssl_flight_item *flight)
2460 {
2461 mbedtls_ssl_flight_item *cur = flight;
2462 mbedtls_ssl_flight_item *next;
2463
2464 while (cur != NULL) {
2465 next = cur->next;
2466
2467 mbedtls_free(cur->p);
2468 mbedtls_free(cur);
2469
2470 cur = next;
2471 }
2472 }
2473
2474 /*
2475 * Swap transform_out and out_ctr with the alternative ones
2476 */
2477 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_swap_epochs(mbedtls_ssl_context * ssl)2478 static int ssl_swap_epochs(mbedtls_ssl_context *ssl)
2479 {
2480 mbedtls_ssl_transform *tmp_transform;
2481 unsigned char tmp_out_ctr[MBEDTLS_SSL_SEQUENCE_NUMBER_LEN];
2482
2483 if (ssl->transform_out == ssl->handshake->alt_transform_out) {
2484 MBEDTLS_SSL_DEBUG_MSG(3, ("skip swap epochs"));
2485 return 0;
2486 }
2487
2488 MBEDTLS_SSL_DEBUG_MSG(3, ("swap epochs"));
2489
2490 /* Swap transforms */
2491 tmp_transform = ssl->transform_out;
2492 ssl->transform_out = ssl->handshake->alt_transform_out;
2493 ssl->handshake->alt_transform_out = tmp_transform;
2494
2495 /* Swap epoch + sequence_number */
2496 memcpy(tmp_out_ctr, ssl->cur_out_ctr, sizeof(tmp_out_ctr));
2497 memcpy(ssl->cur_out_ctr, ssl->handshake->alt_out_ctr,
2498 sizeof(ssl->cur_out_ctr));
2499 memcpy(ssl->handshake->alt_out_ctr, tmp_out_ctr,
2500 sizeof(ssl->handshake->alt_out_ctr));
2501
2502 /* Adjust to the newly activated transform */
2503 mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
2504
2505 return 0;
2506 }
2507
2508 /*
2509 * Retransmit the current flight of messages.
2510 */
mbedtls_ssl_resend(mbedtls_ssl_context * ssl)2511 int mbedtls_ssl_resend(mbedtls_ssl_context *ssl)
2512 {
2513 int ret = 0;
2514
2515 MBEDTLS_SSL_DEBUG_MSG(2, ("=> mbedtls_ssl_resend"));
2516
2517 ret = mbedtls_ssl_flight_transmit(ssl);
2518
2519 MBEDTLS_SSL_DEBUG_MSG(2, ("<= mbedtls_ssl_resend"));
2520
2521 return ret;
2522 }
2523
2524 /*
2525 * Transmit or retransmit the current flight of messages.
2526 *
2527 * Need to remember the current message in case flush_output returns
2528 * WANT_WRITE, causing us to exit this function and come back later.
2529 * This function must be called until state is no longer SENDING.
2530 */
mbedtls_ssl_flight_transmit(mbedtls_ssl_context * ssl)2531 int mbedtls_ssl_flight_transmit(mbedtls_ssl_context *ssl)
2532 {
2533 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2534 MBEDTLS_SSL_DEBUG_MSG(2, ("=> mbedtls_ssl_flight_transmit"));
2535
2536 if (ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING) {
2537 MBEDTLS_SSL_DEBUG_MSG(2, ("initialise flight transmission"));
2538
2539 ssl->handshake->cur_msg = ssl->handshake->flight;
2540 ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
2541 ret = ssl_swap_epochs(ssl);
2542 if (ret != 0) {
2543 return ret;
2544 }
2545
2546 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
2547 }
2548
2549 while (ssl->handshake->cur_msg != NULL) {
2550 size_t max_frag_len;
2551 const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
2552
2553 int const is_finished =
2554 (cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
2555 cur->p[0] == MBEDTLS_SSL_HS_FINISHED);
2556
2557 int const force_flush = ssl->disable_datagram_packing == 1 ?
2558 SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
2559
2560 /* Swap epochs before sending Finished: we can't do it after
2561 * sending ChangeCipherSpec, in case write returns WANT_READ.
2562 * Must be done before copying, may change out_msg pointer */
2563 if (is_finished && ssl->handshake->cur_msg_p == (cur->p + 12)) {
2564 MBEDTLS_SSL_DEBUG_MSG(2, ("swap epochs to send finished message"));
2565 ret = ssl_swap_epochs(ssl);
2566 if (ret != 0) {
2567 return ret;
2568 }
2569 }
2570
2571 ret = ssl_get_remaining_payload_in_datagram(ssl);
2572 if (ret < 0) {
2573 return ret;
2574 }
2575 max_frag_len = (size_t) ret;
2576
2577 /* CCS is copied as is, while HS messages may need fragmentation */
2578 if (cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
2579 if (max_frag_len == 0) {
2580 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
2581 return ret;
2582 }
2583
2584 continue;
2585 }
2586
2587 memcpy(ssl->out_msg, cur->p, cur->len);
2588 ssl->out_msglen = cur->len;
2589 ssl->out_msgtype = cur->type;
2590
2591 /* Update position inside current message */
2592 ssl->handshake->cur_msg_p += cur->len;
2593 } else {
2594 const unsigned char * const p = ssl->handshake->cur_msg_p;
2595 const size_t hs_len = cur->len - 12;
2596 const size_t frag_off = (size_t) (p - (cur->p + 12));
2597 const size_t rem_len = hs_len - frag_off;
2598 size_t cur_hs_frag_len, max_hs_frag_len;
2599
2600 if ((max_frag_len < 12) || (max_frag_len == 12 && hs_len != 0)) {
2601 if (is_finished) {
2602 ret = ssl_swap_epochs(ssl);
2603 if (ret != 0) {
2604 return ret;
2605 }
2606 }
2607
2608 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
2609 return ret;
2610 }
2611
2612 continue;
2613 }
2614 max_hs_frag_len = max_frag_len - 12;
2615
2616 cur_hs_frag_len = rem_len > max_hs_frag_len ?
2617 max_hs_frag_len : rem_len;
2618
2619 if (frag_off == 0 && cur_hs_frag_len != hs_len) {
2620 MBEDTLS_SSL_DEBUG_MSG(2, ("fragmenting handshake message (%u > %u)",
2621 (unsigned) cur_hs_frag_len,
2622 (unsigned) max_hs_frag_len));
2623 }
2624
2625 /* Messages are stored with handshake headers as if not fragmented,
2626 * copy beginning of headers then fill fragmentation fields.
2627 * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
2628 memcpy(ssl->out_msg, cur->p, 6);
2629
2630 ssl->out_msg[6] = MBEDTLS_BYTE_2(frag_off);
2631 ssl->out_msg[7] = MBEDTLS_BYTE_1(frag_off);
2632 ssl->out_msg[8] = MBEDTLS_BYTE_0(frag_off);
2633
2634 ssl->out_msg[9] = MBEDTLS_BYTE_2(cur_hs_frag_len);
2635 ssl->out_msg[10] = MBEDTLS_BYTE_1(cur_hs_frag_len);
2636 ssl->out_msg[11] = MBEDTLS_BYTE_0(cur_hs_frag_len);
2637
2638 MBEDTLS_SSL_DEBUG_BUF(3, "handshake header", ssl->out_msg, 12);
2639
2640 /* Copy the handshake message content and set records fields */
2641 memcpy(ssl->out_msg + 12, p, cur_hs_frag_len);
2642 ssl->out_msglen = cur_hs_frag_len + 12;
2643 ssl->out_msgtype = cur->type;
2644
2645 /* Update position inside current message */
2646 ssl->handshake->cur_msg_p += cur_hs_frag_len;
2647 }
2648
2649 /* If done with the current message move to the next one if any */
2650 if (ssl->handshake->cur_msg_p >= cur->p + cur->len) {
2651 if (cur->next != NULL) {
2652 ssl->handshake->cur_msg = cur->next;
2653 ssl->handshake->cur_msg_p = cur->next->p + 12;
2654 } else {
2655 ssl->handshake->cur_msg = NULL;
2656 ssl->handshake->cur_msg_p = NULL;
2657 }
2658 }
2659
2660 /* Actually send the message out */
2661 if ((ret = mbedtls_ssl_write_record(ssl, force_flush)) != 0) {
2662 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
2663 return ret;
2664 }
2665 }
2666
2667 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
2668 return ret;
2669 }
2670
2671 /* Update state and set timer */
2672 if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
2673 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2674 } else {
2675 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2676 mbedtls_ssl_set_timer(ssl, ssl->handshake->retransmit_timeout);
2677 }
2678
2679 MBEDTLS_SSL_DEBUG_MSG(2, ("<= mbedtls_ssl_flight_transmit"));
2680
2681 return 0;
2682 }
2683
2684 /*
2685 * To be called when the last message of an incoming flight is received.
2686 */
mbedtls_ssl_recv_flight_completed(mbedtls_ssl_context * ssl)2687 void mbedtls_ssl_recv_flight_completed(mbedtls_ssl_context *ssl)
2688 {
2689 /* We won't need to resend that one any more */
2690 mbedtls_ssl_flight_free(ssl->handshake->flight);
2691 ssl->handshake->flight = NULL;
2692 ssl->handshake->cur_msg = NULL;
2693
2694 /* The next incoming flight will start with this msg_seq */
2695 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
2696
2697 /* We don't want to remember CCS's across flight boundaries. */
2698 ssl->handshake->buffering.seen_ccs = 0;
2699
2700 /* Clear future message buffering structure. */
2701 mbedtls_ssl_buffering_free(ssl);
2702
2703 /* Cancel timer */
2704 mbedtls_ssl_set_timer(ssl, 0);
2705
2706 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2707 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED) {
2708 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2709 } else {
2710 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
2711 }
2712 }
2713
2714 /*
2715 * To be called when the last message of an outgoing flight is send.
2716 */
mbedtls_ssl_send_flight_completed(mbedtls_ssl_context * ssl)2717 void mbedtls_ssl_send_flight_completed(mbedtls_ssl_context *ssl)
2718 {
2719 ssl_reset_retransmit_timeout(ssl);
2720 mbedtls_ssl_set_timer(ssl, ssl->handshake->retransmit_timeout);
2721
2722 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2723 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED) {
2724 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
2725 } else {
2726 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
2727 }
2728 }
2729 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2730
2731 /*
2732 * Handshake layer functions
2733 */
mbedtls_ssl_start_handshake_msg(mbedtls_ssl_context * ssl,unsigned char hs_type,unsigned char ** buf,size_t * buf_len)2734 int mbedtls_ssl_start_handshake_msg(mbedtls_ssl_context *ssl, unsigned char hs_type,
2735 unsigned char **buf, size_t *buf_len)
2736 {
2737 /*
2738 * Reserve 4 bytes for handshake header. ( Section 4,RFC 8446 )
2739 * ...
2740 * HandshakeType msg_type;
2741 * uint24 length;
2742 * ...
2743 */
2744 *buf = ssl->out_msg + 4;
2745 *buf_len = MBEDTLS_SSL_OUT_CONTENT_LEN - 4;
2746
2747 ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2748 ssl->out_msg[0] = hs_type;
2749
2750 return 0;
2751 }
2752
2753 /*
2754 * Write (DTLS: or queue) current handshake (including CCS) message.
2755 *
2756 * - fill in handshake headers
2757 * - update handshake checksum
2758 * - DTLS: save message for resending
2759 * - then pass to the record layer
2760 *
2761 * DTLS: except for HelloRequest, messages are only queued, and will only be
2762 * actually sent when calling flight_transmit() or resend().
2763 *
2764 * Inputs:
2765 * - ssl->out_msglen: 4 + actual handshake message len
2766 * (4 is the size of handshake headers for TLS)
2767 * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
2768 * - ssl->out_msg + 4: the handshake message body
2769 *
2770 * Outputs, ie state before passing to flight_append() or write_record():
2771 * - ssl->out_msglen: the length of the record contents
2772 * (including handshake headers but excluding record headers)
2773 * - ssl->out_msg: the record contents (handshake headers + content)
2774 */
mbedtls_ssl_write_handshake_msg_ext(mbedtls_ssl_context * ssl,int update_checksum,int force_flush)2775 int mbedtls_ssl_write_handshake_msg_ext(mbedtls_ssl_context *ssl,
2776 int update_checksum,
2777 int force_flush)
2778 {
2779 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2780 const size_t hs_len = ssl->out_msglen - 4;
2781 const unsigned char hs_type = ssl->out_msg[0];
2782
2783 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write handshake message"));
2784
2785 /*
2786 * Sanity checks
2787 */
2788 if (ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
2789 ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
2790 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2791 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2792 }
2793
2794 /* Whenever we send anything different from a
2795 * HelloRequest we should be in a handshake - double check. */
2796 if (!(ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2797 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST) &&
2798 ssl->handshake == NULL) {
2799 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2800 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2801 }
2802
2803 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2804 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2805 ssl->handshake != NULL &&
2806 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING) {
2807 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2808 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2809 }
2810 #endif
2811
2812 /* Double-check that we did not exceed the bounds
2813 * of the outgoing record buffer.
2814 * This should never fail as the various message
2815 * writing functions must obey the bounds of the
2816 * outgoing record buffer, but better be safe.
2817 *
2818 * Note: We deliberately do not check for the MTU or MFL here.
2819 */
2820 if (ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN) {
2821 MBEDTLS_SSL_DEBUG_MSG(1, ("Record too large: "
2822 "size %" MBEDTLS_PRINTF_SIZET
2823 ", maximum %" MBEDTLS_PRINTF_SIZET,
2824 ssl->out_msglen,
2825 (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN));
2826 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2827 }
2828
2829 /*
2830 * Fill handshake headers
2831 */
2832 if (ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
2833 ssl->out_msg[1] = MBEDTLS_BYTE_2(hs_len);
2834 ssl->out_msg[2] = MBEDTLS_BYTE_1(hs_len);
2835 ssl->out_msg[3] = MBEDTLS_BYTE_0(hs_len);
2836
2837 /*
2838 * DTLS has additional fields in the Handshake layer,
2839 * between the length field and the actual payload:
2840 * uint16 message_seq;
2841 * uint24 fragment_offset;
2842 * uint24 fragment_length;
2843 */
2844 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2845 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2846 /* Make room for the additional DTLS fields */
2847 if (MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8) {
2848 MBEDTLS_SSL_DEBUG_MSG(1, ("DTLS handshake message too large: "
2849 "size %" MBEDTLS_PRINTF_SIZET ", maximum %"
2850 MBEDTLS_PRINTF_SIZET,
2851 hs_len,
2852 (size_t) (MBEDTLS_SSL_OUT_CONTENT_LEN - 12)));
2853 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2854 }
2855
2856 memmove(ssl->out_msg + 12, ssl->out_msg + 4, hs_len);
2857 ssl->out_msglen += 8;
2858
2859 /* Write message_seq and update it, except for HelloRequest */
2860 if (hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST) {
2861 MBEDTLS_PUT_UINT16_BE(ssl->handshake->out_msg_seq, ssl->out_msg, 4);
2862 ++(ssl->handshake->out_msg_seq);
2863 } else {
2864 ssl->out_msg[4] = 0;
2865 ssl->out_msg[5] = 0;
2866 }
2867
2868 /* Handshake hashes are computed without fragmentation,
2869 * so set frag_offset = 0 and frag_len = hs_len for now */
2870 memset(ssl->out_msg + 6, 0x00, 3);
2871 memcpy(ssl->out_msg + 9, ssl->out_msg + 1, 3);
2872 }
2873 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2874
2875 /* Update running hashes of handshake messages seen */
2876 if (hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST && update_checksum != 0) {
2877 ret = ssl->handshake->update_checksum(ssl, ssl->out_msg,
2878 ssl->out_msglen);
2879 if (ret != 0) {
2880 MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
2881 return ret;
2882 }
2883 }
2884 }
2885
2886 /* Either send now, or just save to be sent (and resent) later */
2887 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2888 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2889 !(ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
2890 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST)) {
2891 if ((ret = ssl_flight_append(ssl)) != 0) {
2892 MBEDTLS_SSL_DEBUG_RET(1, "ssl_flight_append", ret);
2893 return ret;
2894 }
2895 } else
2896 #endif
2897 {
2898 if ((ret = mbedtls_ssl_write_record(ssl, force_flush)) != 0) {
2899 MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_record", ret);
2900 return ret;
2901 }
2902 }
2903
2904 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write handshake message"));
2905
2906 return 0;
2907 }
2908
mbedtls_ssl_finish_handshake_msg(mbedtls_ssl_context * ssl,size_t buf_len,size_t msg_len)2909 int mbedtls_ssl_finish_handshake_msg(mbedtls_ssl_context *ssl,
2910 size_t buf_len, size_t msg_len)
2911 {
2912 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2913 size_t msg_with_header_len;
2914 ((void) buf_len);
2915
2916 /* Add reserved 4 bytes for handshake header */
2917 msg_with_header_len = msg_len + 4;
2918 ssl->out_msglen = msg_with_header_len;
2919 MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_write_handshake_msg_ext(ssl, 0, 0));
2920
2921 cleanup:
2922 return ret;
2923 }
2924
2925 /*
2926 * Record layer functions
2927 */
2928
2929 /*
2930 * Write current record.
2931 *
2932 * Uses:
2933 * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
2934 * - ssl->out_msglen: length of the record content (excl headers)
2935 * - ssl->out_msg: record content
2936 */
mbedtls_ssl_write_record(mbedtls_ssl_context * ssl,int force_flush)2937 int mbedtls_ssl_write_record(mbedtls_ssl_context *ssl, int force_flush)
2938 {
2939 int ret, done = 0;
2940 size_t len = ssl->out_msglen;
2941 int flush = force_flush;
2942
2943 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write record"));
2944
2945 if (!done) {
2946 unsigned i;
2947 size_t protected_record_size;
2948 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2949 size_t out_buf_len = ssl->out_buf_len;
2950 #else
2951 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
2952 #endif
2953 /* Skip writing the record content type to after the encryption,
2954 * as it may change when using the CID extension. */
2955 mbedtls_ssl_protocol_version tls_ver = ssl->tls_version;
2956 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2957 /* TLS 1.3 still uses the TLS 1.2 version identifier
2958 * for backwards compatibility. */
2959 if (tls_ver == MBEDTLS_SSL_VERSION_TLS1_3) {
2960 tls_ver = MBEDTLS_SSL_VERSION_TLS1_2;
2961 }
2962 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2963 mbedtls_ssl_write_version(ssl->out_hdr + 1, ssl->conf->transport,
2964 tls_ver);
2965
2966 memcpy(ssl->out_ctr, ssl->cur_out_ctr, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
2967 MBEDTLS_PUT_UINT16_BE(len, ssl->out_len, 0);
2968
2969 if (ssl->transform_out != NULL) {
2970 mbedtls_record rec;
2971
2972 rec.buf = ssl->out_iv;
2973 rec.buf_len = out_buf_len - (size_t) (ssl->out_iv - ssl->out_buf);
2974 rec.data_len = ssl->out_msglen;
2975 rec.data_offset = (size_t) (ssl->out_msg - rec.buf);
2976
2977 memcpy(&rec.ctr[0], ssl->out_ctr, sizeof(rec.ctr));
2978 mbedtls_ssl_write_version(rec.ver, ssl->conf->transport, tls_ver);
2979 rec.type = ssl->out_msgtype;
2980
2981 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2982 /* The CID is set by mbedtls_ssl_encrypt_buf(). */
2983 rec.cid_len = 0;
2984 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2985
2986 if ((ret = mbedtls_ssl_encrypt_buf(ssl, ssl->transform_out, &rec,
2987 ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2988 MBEDTLS_SSL_DEBUG_RET(1, "ssl_encrypt_buf", ret);
2989 return ret;
2990 }
2991
2992 if (rec.data_offset != 0) {
2993 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2994 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2995 }
2996
2997 /* Update the record content type and CID. */
2998 ssl->out_msgtype = rec.type;
2999 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3000 memcpy(ssl->out_cid, rec.cid, rec.cid_len);
3001 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3002 ssl->out_msglen = len = rec.data_len;
3003 MBEDTLS_PUT_UINT16_BE(rec.data_len, ssl->out_len, 0);
3004 }
3005
3006 protected_record_size = len + mbedtls_ssl_out_hdr_len(ssl);
3007
3008 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3009 /* In case of DTLS, double-check that we don't exceed
3010 * the remaining space in the datagram. */
3011 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3012 ret = ssl_get_remaining_space_in_datagram(ssl);
3013 if (ret < 0) {
3014 return ret;
3015 }
3016
3017 if (protected_record_size > (size_t) ret) {
3018 /* Should never happen */
3019 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3020 }
3021 }
3022 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3023
3024 /* Now write the potentially updated record content type. */
3025 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
3026
3027 MBEDTLS_SSL_DEBUG_MSG(3, ("output record: msgtype = %u, "
3028 "version = [%u:%u], msglen = %" MBEDTLS_PRINTF_SIZET,
3029 ssl->out_hdr[0], ssl->out_hdr[1],
3030 ssl->out_hdr[2], len));
3031
3032 MBEDTLS_SSL_DEBUG_BUF(4, "output record sent to network",
3033 ssl->out_hdr, protected_record_size);
3034
3035 ssl->out_left += protected_record_size;
3036 ssl->out_hdr += protected_record_size;
3037 mbedtls_ssl_update_out_pointers(ssl, ssl->transform_out);
3038
3039 for (i = 8; i > mbedtls_ssl_ep_len(ssl); i--) {
3040 if (++ssl->cur_out_ctr[i - 1] != 0) {
3041 break;
3042 }
3043 }
3044
3045 /* The loop goes to its end if the counter is wrapping */
3046 if (i == mbedtls_ssl_ep_len(ssl)) {
3047 MBEDTLS_SSL_DEBUG_MSG(1, ("outgoing message counter would wrap"));
3048 return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
3049 }
3050 }
3051
3052 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3053 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3054 flush == SSL_DONT_FORCE_FLUSH) {
3055 size_t remaining;
3056 ret = ssl_get_remaining_payload_in_datagram(ssl);
3057 if (ret < 0) {
3058 MBEDTLS_SSL_DEBUG_RET(1, "ssl_get_remaining_payload_in_datagram",
3059 ret);
3060 return ret;
3061 }
3062
3063 remaining = (size_t) ret;
3064 if (remaining == 0) {
3065 flush = SSL_FORCE_FLUSH;
3066 } else {
3067 MBEDTLS_SSL_DEBUG_MSG(2,
3068 ("Still %u bytes available in current datagram",
3069 (unsigned) remaining));
3070 }
3071 }
3072 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3073
3074 if ((flush == SSL_FORCE_FLUSH) &&
3075 (ret = mbedtls_ssl_flush_output(ssl)) != 0) {
3076 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
3077 return ret;
3078 }
3079
3080 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write record"));
3081
3082 return 0;
3083 }
3084
3085 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3086
3087 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_hs_is_proper_fragment(mbedtls_ssl_context * ssl)3088 static int ssl_hs_is_proper_fragment(mbedtls_ssl_context *ssl)
3089 {
3090 if (ssl->in_msglen < ssl->in_hslen ||
3091 memcmp(ssl->in_msg + 6, "\0\0\0", 3) != 0 ||
3092 memcmp(ssl->in_msg + 9, ssl->in_msg + 1, 3) != 0) {
3093 return 1;
3094 }
3095 return 0;
3096 }
3097
ssl_get_hs_frag_len(mbedtls_ssl_context const * ssl)3098 static uint32_t ssl_get_hs_frag_len(mbedtls_ssl_context const *ssl)
3099 {
3100 return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 9);
3101 }
3102
ssl_get_hs_frag_off(mbedtls_ssl_context const * ssl)3103 static uint32_t ssl_get_hs_frag_off(mbedtls_ssl_context const *ssl)
3104 {
3105 return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 6);
3106 }
3107
3108 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_hs_header(mbedtls_ssl_context const * ssl)3109 static int ssl_check_hs_header(mbedtls_ssl_context const *ssl)
3110 {
3111 uint32_t msg_len, frag_off, frag_len;
3112
3113 msg_len = ssl_get_hs_total_len(ssl);
3114 frag_off = ssl_get_hs_frag_off(ssl);
3115 frag_len = ssl_get_hs_frag_len(ssl);
3116
3117 if (frag_off > msg_len) {
3118 return -1;
3119 }
3120
3121 if (frag_len > msg_len - frag_off) {
3122 return -1;
3123 }
3124
3125 if (frag_len + 12 > ssl->in_msglen) {
3126 return -1;
3127 }
3128
3129 return 0;
3130 }
3131
3132 /*
3133 * Mark bits in bitmask (used for DTLS HS reassembly)
3134 */
ssl_bitmask_set(unsigned char * mask,size_t offset,size_t len)3135 static void ssl_bitmask_set(unsigned char *mask, size_t offset, size_t len)
3136 {
3137 unsigned int start_bits, end_bits;
3138
3139 start_bits = 8 - (offset % 8);
3140 if (start_bits != 8) {
3141 size_t first_byte_idx = offset / 8;
3142
3143 /* Special case */
3144 if (len <= start_bits) {
3145 for (; len != 0; len--) {
3146 mask[first_byte_idx] |= 1 << (start_bits - len);
3147 }
3148
3149 /* Avoid potential issues with offset or len becoming invalid */
3150 return;
3151 }
3152
3153 offset += start_bits; /* Now offset % 8 == 0 */
3154 len -= start_bits;
3155
3156 for (; start_bits != 0; start_bits--) {
3157 mask[first_byte_idx] |= 1 << (start_bits - 1);
3158 }
3159 }
3160
3161 end_bits = len % 8;
3162 if (end_bits != 0) {
3163 size_t last_byte_idx = (offset + len) / 8;
3164
3165 len -= end_bits; /* Now len % 8 == 0 */
3166
3167 for (; end_bits != 0; end_bits--) {
3168 mask[last_byte_idx] |= 1 << (8 - end_bits);
3169 }
3170 }
3171
3172 memset(mask + offset / 8, 0xFF, len / 8);
3173 }
3174
3175 /*
3176 * Check that bitmask is full
3177 */
3178 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_bitmask_check(unsigned char * mask,size_t len)3179 static int ssl_bitmask_check(unsigned char *mask, size_t len)
3180 {
3181 size_t i;
3182
3183 for (i = 0; i < len / 8; i++) {
3184 if (mask[i] != 0xFF) {
3185 return -1;
3186 }
3187 }
3188
3189 for (i = 0; i < len % 8; i++) {
3190 if ((mask[len / 8] & (1 << (7 - i))) == 0) {
3191 return -1;
3192 }
3193 }
3194
3195 return 0;
3196 }
3197
3198 /* msg_len does not include the handshake header */
ssl_get_reassembly_buffer_size(size_t msg_len,unsigned add_bitmap)3199 static size_t ssl_get_reassembly_buffer_size(size_t msg_len,
3200 unsigned add_bitmap)
3201 {
3202 size_t alloc_len;
3203
3204 alloc_len = 12; /* Handshake header */
3205 alloc_len += msg_len; /* Content buffer */
3206
3207 if (add_bitmap) {
3208 alloc_len += msg_len / 8 + (msg_len % 8 != 0); /* Bitmap */
3209
3210 }
3211 return alloc_len;
3212 }
3213
3214 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3215
ssl_get_hs_total_len(mbedtls_ssl_context const * ssl)3216 static uint32_t ssl_get_hs_total_len(mbedtls_ssl_context const *ssl)
3217 {
3218 return MBEDTLS_GET_UINT24_BE(ssl->in_msg, 1);
3219 }
3220
mbedtls_ssl_prepare_handshake_record(mbedtls_ssl_context * ssl)3221 int mbedtls_ssl_prepare_handshake_record(mbedtls_ssl_context *ssl)
3222 {
3223 if (ssl->in_msglen < mbedtls_ssl_hs_hdr_len(ssl)) {
3224 MBEDTLS_SSL_DEBUG_MSG(1, ("handshake message too short: %" MBEDTLS_PRINTF_SIZET,
3225 ssl->in_msglen));
3226 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3227 }
3228
3229 ssl->in_hslen = mbedtls_ssl_hs_hdr_len(ssl) + ssl_get_hs_total_len(ssl);
3230
3231 MBEDTLS_SSL_DEBUG_MSG(3, ("handshake message: msglen ="
3232 " %" MBEDTLS_PRINTF_SIZET ", type = %u, hslen = %"
3233 MBEDTLS_PRINTF_SIZET,
3234 ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen));
3235
3236 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3237 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3238 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3239 unsigned int recv_msg_seq = MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
3240
3241 if (ssl_check_hs_header(ssl) != 0) {
3242 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid handshake header"));
3243 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3244 }
3245
3246 if (ssl->handshake != NULL &&
3247 ((mbedtls_ssl_is_handshake_over(ssl) == 0 &&
3248 recv_msg_seq != ssl->handshake->in_msg_seq) ||
3249 (mbedtls_ssl_is_handshake_over(ssl) == 1 &&
3250 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO))) {
3251 if (recv_msg_seq > ssl->handshake->in_msg_seq) {
3252 MBEDTLS_SSL_DEBUG_MSG(2,
3253 (
3254 "received future handshake message of sequence number %u (next %u)",
3255 recv_msg_seq,
3256 ssl->handshake->in_msg_seq));
3257 return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
3258 }
3259
3260 /* Retransmit only on last message from previous flight, to avoid
3261 * too many retransmissions.
3262 * Besides, No sane server ever retransmits HelloVerifyRequest */
3263 if (recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
3264 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST) {
3265 MBEDTLS_SSL_DEBUG_MSG(2, ("received message from last flight, "
3266 "message_seq = %u, start_of_flight = %u",
3267 recv_msg_seq,
3268 ssl->handshake->in_flight_start_seq));
3269
3270 if ((ret = mbedtls_ssl_resend(ssl)) != 0) {
3271 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend", ret);
3272 return ret;
3273 }
3274 } else {
3275 MBEDTLS_SSL_DEBUG_MSG(2, ("dropping out-of-sequence message: "
3276 "message_seq = %u, expected = %u",
3277 recv_msg_seq,
3278 ssl->handshake->in_msg_seq));
3279 }
3280
3281 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
3282 }
3283 /* Wait until message completion to increment in_msg_seq */
3284
3285 /* Message reassembly is handled alongside buffering of future
3286 * messages; the commonality is that both handshake fragments and
3287 * future messages cannot be forwarded immediately to the
3288 * handshake logic layer. */
3289 if (ssl_hs_is_proper_fragment(ssl) == 1) {
3290 MBEDTLS_SSL_DEBUG_MSG(2, ("found fragmented DTLS handshake message"));
3291 return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
3292 }
3293 } else
3294 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3295 /* With TLS we don't handle fragmentation (for now) */
3296 if (ssl->in_msglen < ssl->in_hslen) {
3297 MBEDTLS_SSL_DEBUG_MSG(1, ("TLS handshake fragmentation not supported"));
3298 return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3299 }
3300
3301 return 0;
3302 }
3303
mbedtls_ssl_update_handshake_status(mbedtls_ssl_context * ssl)3304 int mbedtls_ssl_update_handshake_status(mbedtls_ssl_context *ssl)
3305 {
3306 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3307 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
3308
3309 if (mbedtls_ssl_is_handshake_over(ssl) == 0 && hs != NULL) {
3310 ret = ssl->handshake->update_checksum(ssl, ssl->in_msg, ssl->in_hslen);
3311 if (ret != 0) {
3312 MBEDTLS_SSL_DEBUG_RET(1, "update_checksum", ret);
3313 return ret;
3314 }
3315 }
3316
3317 /* Handshake message is complete, increment counter */
3318 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3319 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3320 ssl->handshake != NULL) {
3321 unsigned offset;
3322 mbedtls_ssl_hs_buffer *hs_buf;
3323
3324 /* Increment handshake sequence number */
3325 hs->in_msg_seq++;
3326
3327 /*
3328 * Clear up handshake buffering and reassembly structure.
3329 */
3330
3331 /* Free first entry */
3332 ssl_buffering_free_slot(ssl, 0);
3333
3334 /* Shift all other entries */
3335 for (offset = 0, hs_buf = &hs->buffering.hs[0];
3336 offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS;
3337 offset++, hs_buf++) {
3338 *hs_buf = *(hs_buf + 1);
3339 }
3340
3341 /* Create a fresh last entry */
3342 memset(hs_buf, 0, sizeof(mbedtls_ssl_hs_buffer));
3343 }
3344 #endif
3345 return 0;
3346 }
3347
3348 /*
3349 * DTLS anti-replay: RFC 6347 4.1.2.6
3350 *
3351 * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
3352 * Bit n is set iff record number in_window_top - n has been seen.
3353 *
3354 * Usually, in_window_top is the last record number seen and the lsb of
3355 * in_window is set. The only exception is the initial state (record number 0
3356 * not seen yet).
3357 */
3358 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
mbedtls_ssl_dtls_replay_reset(mbedtls_ssl_context * ssl)3359 void mbedtls_ssl_dtls_replay_reset(mbedtls_ssl_context *ssl)
3360 {
3361 ssl->in_window_top = 0;
3362 ssl->in_window = 0;
3363 }
3364
ssl_load_six_bytes(unsigned char * buf)3365 static inline uint64_t ssl_load_six_bytes(unsigned char *buf)
3366 {
3367 return ((uint64_t) buf[0] << 40) |
3368 ((uint64_t) buf[1] << 32) |
3369 ((uint64_t) buf[2] << 24) |
3370 ((uint64_t) buf[3] << 16) |
3371 ((uint64_t) buf[4] << 8) |
3372 ((uint64_t) buf[5]);
3373 }
3374
3375 MBEDTLS_CHECK_RETURN_CRITICAL
mbedtls_ssl_dtls_record_replay_check(mbedtls_ssl_context * ssl,uint8_t * record_in_ctr)3376 static int mbedtls_ssl_dtls_record_replay_check(mbedtls_ssl_context *ssl, uint8_t *record_in_ctr)
3377 {
3378 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3379 unsigned char *original_in_ctr;
3380
3381 // save original in_ctr
3382 original_in_ctr = ssl->in_ctr;
3383
3384 // use counter from record
3385 ssl->in_ctr = record_in_ctr;
3386
3387 ret = mbedtls_ssl_dtls_replay_check((mbedtls_ssl_context const *) ssl);
3388
3389 // restore the counter
3390 ssl->in_ctr = original_in_ctr;
3391
3392 return ret;
3393 }
3394
3395 /*
3396 * Return 0 if sequence number is acceptable, -1 otherwise
3397 */
mbedtls_ssl_dtls_replay_check(mbedtls_ssl_context const * ssl)3398 int mbedtls_ssl_dtls_replay_check(mbedtls_ssl_context const *ssl)
3399 {
3400 uint64_t rec_seqnum = ssl_load_six_bytes(ssl->in_ctr + 2);
3401 uint64_t bit;
3402
3403 if (ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED) {
3404 return 0;
3405 }
3406
3407 if (rec_seqnum > ssl->in_window_top) {
3408 return 0;
3409 }
3410
3411 bit = ssl->in_window_top - rec_seqnum;
3412
3413 if (bit >= 64) {
3414 return -1;
3415 }
3416
3417 if ((ssl->in_window & ((uint64_t) 1 << bit)) != 0) {
3418 return -1;
3419 }
3420
3421 return 0;
3422 }
3423
3424 /*
3425 * Update replay window on new validated record
3426 */
mbedtls_ssl_dtls_replay_update(mbedtls_ssl_context * ssl)3427 void mbedtls_ssl_dtls_replay_update(mbedtls_ssl_context *ssl)
3428 {
3429 uint64_t rec_seqnum = ssl_load_six_bytes(ssl->in_ctr + 2);
3430
3431 if (ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED) {
3432 return;
3433 }
3434
3435 if (rec_seqnum > ssl->in_window_top) {
3436 /* Update window_top and the contents of the window */
3437 uint64_t shift = rec_seqnum - ssl->in_window_top;
3438
3439 if (shift >= 64) {
3440 ssl->in_window = 1;
3441 } else {
3442 ssl->in_window <<= shift;
3443 ssl->in_window |= 1;
3444 }
3445
3446 ssl->in_window_top = rec_seqnum;
3447 } else {
3448 /* Mark that number as seen in the current window */
3449 uint64_t bit = ssl->in_window_top - rec_seqnum;
3450
3451 if (bit < 64) { /* Always true, but be extra sure */
3452 ssl->in_window |= (uint64_t) 1 << bit;
3453 }
3454 }
3455 }
3456 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
3457
3458 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3459 /*
3460 * Check if a datagram looks like a ClientHello with a valid cookie,
3461 * and if it doesn't, generate a HelloVerifyRequest message.
3462 * Both input and output include full DTLS headers.
3463 *
3464 * - if cookie is valid, return 0
3465 * - if ClientHello looks superficially valid but cookie is not,
3466 * fill obuf and set olen, then
3467 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3468 * - otherwise return a specific error code
3469 */
3470 MBEDTLS_CHECK_RETURN_CRITICAL
3471 MBEDTLS_STATIC_TESTABLE
mbedtls_ssl_check_dtls_clihlo_cookie(mbedtls_ssl_context * ssl,const unsigned char * cli_id,size_t cli_id_len,const unsigned char * in,size_t in_len,unsigned char * obuf,size_t buf_len,size_t * olen)3472 int mbedtls_ssl_check_dtls_clihlo_cookie(
3473 mbedtls_ssl_context *ssl,
3474 const unsigned char *cli_id, size_t cli_id_len,
3475 const unsigned char *in, size_t in_len,
3476 unsigned char *obuf, size_t buf_len, size_t *olen)
3477 {
3478 size_t sid_len, cookie_len, epoch, fragment_offset;
3479 unsigned char *p;
3480
3481 /*
3482 * Structure of ClientHello with record and handshake headers,
3483 * and expected values. We don't need to check a lot, more checks will be
3484 * done when actually parsing the ClientHello - skipping those checks
3485 * avoids code duplication and does not make cookie forging any easier.
3486 *
3487 * 0-0 ContentType type; copied, must be handshake
3488 * 1-2 ProtocolVersion version; copied
3489 * 3-4 uint16 epoch; copied, must be 0
3490 * 5-10 uint48 sequence_number; copied
3491 * 11-12 uint16 length; (ignored)
3492 *
3493 * 13-13 HandshakeType msg_type; (ignored)
3494 * 14-16 uint24 length; (ignored)
3495 * 17-18 uint16 message_seq; copied
3496 * 19-21 uint24 fragment_offset; copied, must be 0
3497 * 22-24 uint24 fragment_length; (ignored)
3498 *
3499 * 25-26 ProtocolVersion client_version; (ignored)
3500 * 27-58 Random random; (ignored)
3501 * 59-xx SessionID session_id; 1 byte len + sid_len content
3502 * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
3503 * ...
3504 *
3505 * Minimum length is 61 bytes.
3506 */
3507 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: in_len=%u",
3508 (unsigned) in_len));
3509 MBEDTLS_SSL_DEBUG_BUF(4, "cli_id", cli_id, cli_id_len);
3510 if (in_len < 61) {
3511 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: record too short"));
3512 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3513 }
3514
3515 epoch = MBEDTLS_GET_UINT16_BE(in, 3);
3516 fragment_offset = MBEDTLS_GET_UINT24_BE(in, 19);
3517
3518 if (in[0] != MBEDTLS_SSL_MSG_HANDSHAKE || epoch != 0 ||
3519 fragment_offset != 0) {
3520 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: not a good ClientHello"));
3521 MBEDTLS_SSL_DEBUG_MSG(4, (" type=%u epoch=%u fragment_offset=%u",
3522 in[0], (unsigned) epoch,
3523 (unsigned) fragment_offset));
3524 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3525 }
3526
3527 sid_len = in[59];
3528 if (59 + 1 + sid_len + 1 > in_len) {
3529 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: sid_len=%u > %u",
3530 (unsigned) sid_len,
3531 (unsigned) in_len - 61));
3532 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3533 }
3534 MBEDTLS_SSL_DEBUG_BUF(4, "sid received from network",
3535 in + 60, sid_len);
3536
3537 cookie_len = in[60 + sid_len];
3538 if (59 + 1 + sid_len + 1 + cookie_len > in_len) {
3539 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: cookie_len=%u > %u",
3540 (unsigned) cookie_len,
3541 (unsigned) (in_len - sid_len - 61)));
3542 return MBEDTLS_ERR_SSL_DECODE_ERROR;
3543 }
3544
3545 MBEDTLS_SSL_DEBUG_BUF(4, "cookie received from network",
3546 in + sid_len + 61, cookie_len);
3547 if (ssl->conf->f_cookie_check(ssl->conf->p_cookie,
3548 in + sid_len + 61, cookie_len,
3549 cli_id, cli_id_len) == 0) {
3550 MBEDTLS_SSL_DEBUG_MSG(4, ("check cookie: valid"));
3551 return 0;
3552 }
3553
3554 /*
3555 * If we get here, we've got an invalid cookie, let's prepare HVR.
3556 *
3557 * 0-0 ContentType type; copied
3558 * 1-2 ProtocolVersion version; copied
3559 * 3-4 uint16 epoch; copied
3560 * 5-10 uint48 sequence_number; copied
3561 * 11-12 uint16 length; olen - 13
3562 *
3563 * 13-13 HandshakeType msg_type; hello_verify_request
3564 * 14-16 uint24 length; olen - 25
3565 * 17-18 uint16 message_seq; copied
3566 * 19-21 uint24 fragment_offset; copied
3567 * 22-24 uint24 fragment_length; olen - 25
3568 *
3569 * 25-26 ProtocolVersion server_version; 0xfe 0xff
3570 * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
3571 *
3572 * Minimum length is 28.
3573 */
3574 if (buf_len < 28) {
3575 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
3576 }
3577
3578 /* Copy most fields and adapt others */
3579 memcpy(obuf, in, 25);
3580 obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
3581 obuf[25] = 0xfe;
3582 obuf[26] = 0xff;
3583
3584 /* Generate and write actual cookie */
3585 p = obuf + 28;
3586 if (ssl->conf->f_cookie_write(ssl->conf->p_cookie,
3587 &p, obuf + buf_len,
3588 cli_id, cli_id_len) != 0) {
3589 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3590 }
3591
3592 *olen = (size_t) (p - obuf);
3593
3594 /* Go back and fill length fields */
3595 obuf[27] = (unsigned char) (*olen - 28);
3596
3597 obuf[14] = obuf[22] = MBEDTLS_BYTE_2(*olen - 25);
3598 obuf[15] = obuf[23] = MBEDTLS_BYTE_1(*olen - 25);
3599 obuf[16] = obuf[24] = MBEDTLS_BYTE_0(*olen - 25);
3600
3601 MBEDTLS_PUT_UINT16_BE(*olen - 13, obuf, 11);
3602
3603 return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED;
3604 }
3605
3606 /*
3607 * Handle possible client reconnect with the same UDP quadruplet
3608 * (RFC 6347 Section 4.2.8).
3609 *
3610 * Called by ssl_parse_record_header() in case we receive an epoch 0 record
3611 * that looks like a ClientHello.
3612 *
3613 * - if the input looks like a ClientHello without cookies,
3614 * send back HelloVerifyRequest, then return 0
3615 * - if the input looks like a ClientHello with a valid cookie,
3616 * reset the session of the current context, and
3617 * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
3618 * - if anything goes wrong, return a specific error code
3619 *
3620 * This function is called (through ssl_check_client_reconnect()) when an
3621 * unexpected record is found in ssl_get_next_record(), which will discard the
3622 * record if we return 0, and bubble up the return value otherwise (this
3623 * includes the case of MBEDTLS_ERR_SSL_CLIENT_RECONNECT and of unexpected
3624 * errors, and is the right thing to do in both cases).
3625 */
3626 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_handle_possible_reconnect(mbedtls_ssl_context * ssl)3627 static int ssl_handle_possible_reconnect(mbedtls_ssl_context *ssl)
3628 {
3629 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3630 size_t len = 0;
3631
3632 if (ssl->conf->f_cookie_write == NULL ||
3633 ssl->conf->f_cookie_check == NULL) {
3634 /* If we can't use cookies to verify reachability of the peer,
3635 * drop the record. */
3636 MBEDTLS_SSL_DEBUG_MSG(1, ("no cookie callbacks, "
3637 "can't check reconnect validity"));
3638 return 0;
3639 }
3640
3641 ret = mbedtls_ssl_check_dtls_clihlo_cookie(
3642 ssl,
3643 ssl->cli_id, ssl->cli_id_len,
3644 ssl->in_buf, ssl->in_left,
3645 ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len);
3646
3647 MBEDTLS_SSL_DEBUG_RET(2, "mbedtls_ssl_check_dtls_clihlo_cookie", ret);
3648
3649 if (ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) {
3650 int send_ret;
3651 MBEDTLS_SSL_DEBUG_MSG(1, ("sending HelloVerifyRequest"));
3652 MBEDTLS_SSL_DEBUG_BUF(4, "output record sent to network",
3653 ssl->out_buf, len);
3654 /* Don't check write errors as we can't do anything here.
3655 * If the error is permanent we'll catch it later,
3656 * if it's not, then hopefully it'll work next time. */
3657 send_ret = ssl->f_send(ssl->p_bio, ssl->out_buf, len);
3658 MBEDTLS_SSL_DEBUG_RET(2, "ssl->f_send", send_ret);
3659 (void) send_ret;
3660
3661 return 0;
3662 }
3663
3664 if (ret == 0) {
3665 MBEDTLS_SSL_DEBUG_MSG(1, ("cookie is valid, resetting context"));
3666 if ((ret = mbedtls_ssl_session_reset_int(ssl, 1)) != 0) {
3667 MBEDTLS_SSL_DEBUG_RET(1, "reset", ret);
3668 return ret;
3669 }
3670
3671 return MBEDTLS_ERR_SSL_CLIENT_RECONNECT;
3672 }
3673
3674 return ret;
3675 }
3676 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3677
3678 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_record_type(uint8_t record_type)3679 static int ssl_check_record_type(uint8_t record_type)
3680 {
3681 if (record_type != MBEDTLS_SSL_MSG_HANDSHAKE &&
3682 record_type != MBEDTLS_SSL_MSG_ALERT &&
3683 record_type != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3684 record_type != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
3685 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3686 }
3687
3688 return 0;
3689 }
3690
3691 /*
3692 * ContentType type;
3693 * ProtocolVersion version;
3694 * uint16 epoch; // DTLS only
3695 * uint48 sequence_number; // DTLS only
3696 * uint16 length;
3697 *
3698 * Return 0 if header looks sane (and, for DTLS, the record is expected)
3699 * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
3700 * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
3701 *
3702 * With DTLS, mbedtls_ssl_read_record() will:
3703 * 1. proceed with the record if this function returns 0
3704 * 2. drop only the current record if this function returns UNEXPECTED_RECORD
3705 * 3. return CLIENT_RECONNECT if this function return that value
3706 * 4. drop the whole datagram if this function returns anything else.
3707 * Point 2 is needed when the peer is resending, and we have already received
3708 * the first record from a datagram but are still waiting for the others.
3709 */
3710 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_record_header(mbedtls_ssl_context const * ssl,unsigned char * buf,size_t len,mbedtls_record * rec)3711 static int ssl_parse_record_header(mbedtls_ssl_context const *ssl,
3712 unsigned char *buf,
3713 size_t len,
3714 mbedtls_record *rec)
3715 {
3716 mbedtls_ssl_protocol_version tls_version;
3717
3718 size_t const rec_hdr_type_offset = 0;
3719 size_t const rec_hdr_type_len = 1;
3720
3721 size_t const rec_hdr_version_offset = rec_hdr_type_offset +
3722 rec_hdr_type_len;
3723 size_t const rec_hdr_version_len = 2;
3724
3725 size_t const rec_hdr_ctr_len = 8;
3726 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3727 uint32_t rec_epoch;
3728 size_t const rec_hdr_ctr_offset = rec_hdr_version_offset +
3729 rec_hdr_version_len;
3730
3731 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3732 size_t const rec_hdr_cid_offset = rec_hdr_ctr_offset +
3733 rec_hdr_ctr_len;
3734 size_t rec_hdr_cid_len = 0;
3735 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3736 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3737
3738 size_t rec_hdr_len_offset; /* To be determined */
3739 size_t const rec_hdr_len_len = 2;
3740
3741 /*
3742 * Check minimum lengths for record header.
3743 */
3744
3745 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3746 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3747 rec_hdr_len_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len;
3748 } else
3749 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3750 {
3751 rec_hdr_len_offset = rec_hdr_version_offset + rec_hdr_version_len;
3752 }
3753
3754 if (len < rec_hdr_len_offset + rec_hdr_len_len) {
3755 MBEDTLS_SSL_DEBUG_MSG(1,
3756 (
3757 "datagram of length %u too small to hold DTLS record header of length %u",
3758 (unsigned) len,
3759 (unsigned) (rec_hdr_len_len + rec_hdr_len_len)));
3760 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3761 }
3762
3763 /*
3764 * Parse and validate record content type
3765 */
3766
3767 rec->type = buf[rec_hdr_type_offset];
3768
3769 /* Check record content type */
3770 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3771 rec->cid_len = 0;
3772
3773 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3774 ssl->conf->cid_len != 0 &&
3775 rec->type == MBEDTLS_SSL_MSG_CID) {
3776 /* Shift pointers to account for record header including CID
3777 * struct {
3778 * ContentType outer_type = tls12_cid;
3779 * ProtocolVersion version;
3780 * uint16 epoch;
3781 * uint48 sequence_number;
3782 * opaque cid[cid_length]; // Additional field compared to
3783 * // default DTLS record format
3784 * uint16 length;
3785 * opaque enc_content[DTLSCiphertext.length];
3786 * } DTLSCiphertext;
3787 */
3788
3789 /* So far, we only support static CID lengths
3790 * fixed in the configuration. */
3791 rec_hdr_cid_len = ssl->conf->cid_len;
3792 rec_hdr_len_offset += rec_hdr_cid_len;
3793
3794 if (len < rec_hdr_len_offset + rec_hdr_len_len) {
3795 MBEDTLS_SSL_DEBUG_MSG(1,
3796 (
3797 "datagram of length %u too small to hold DTLS record header including CID, length %u",
3798 (unsigned) len,
3799 (unsigned) (rec_hdr_len_offset + rec_hdr_len_len)));
3800 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3801 }
3802
3803 /* configured CID len is guaranteed at most 255, see
3804 * MBEDTLS_SSL_CID_OUT_LEN_MAX in check_config.h */
3805 rec->cid_len = (uint8_t) rec_hdr_cid_len;
3806 memcpy(rec->cid, buf + rec_hdr_cid_offset, rec_hdr_cid_len);
3807 } else
3808 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3809 {
3810 if (ssl_check_record_type(rec->type)) {
3811 MBEDTLS_SSL_DEBUG_MSG(1, ("unknown record type %u",
3812 (unsigned) rec->type));
3813 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3814 }
3815 }
3816
3817 /*
3818 * Parse and validate record version
3819 */
3820 rec->ver[0] = buf[rec_hdr_version_offset + 0];
3821 rec->ver[1] = buf[rec_hdr_version_offset + 1];
3822 tls_version = (mbedtls_ssl_protocol_version) mbedtls_ssl_read_version(
3823 buf + rec_hdr_version_offset,
3824 ssl->conf->transport);
3825
3826 if (tls_version > ssl->conf->max_tls_version) {
3827 MBEDTLS_SSL_DEBUG_MSG(1, ("TLS version mismatch: got %u, expected max %u",
3828 (unsigned) tls_version,
3829 (unsigned) ssl->conf->max_tls_version));
3830
3831 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3832 }
3833 /*
3834 * Parse/Copy record sequence number.
3835 */
3836
3837 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3838 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3839 /* Copy explicit record sequence number from input buffer. */
3840 memcpy(&rec->ctr[0], buf + rec_hdr_ctr_offset,
3841 rec_hdr_ctr_len);
3842 } else
3843 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3844 {
3845 /* Copy implicit record sequence number from SSL context structure. */
3846 memcpy(&rec->ctr[0], ssl->in_ctr, rec_hdr_ctr_len);
3847 }
3848
3849 /*
3850 * Parse record length.
3851 */
3852
3853 rec->data_offset = rec_hdr_len_offset + rec_hdr_len_len;
3854 rec->data_len = MBEDTLS_GET_UINT16_BE(buf, rec_hdr_len_offset);
3855 MBEDTLS_SSL_DEBUG_BUF(4, "input record header", buf, rec->data_offset);
3856
3857 MBEDTLS_SSL_DEBUG_MSG(3, ("input record: msgtype = %u, "
3858 "version = [0x%x], msglen = %" MBEDTLS_PRINTF_SIZET,
3859 rec->type, (unsigned) tls_version, rec->data_len));
3860
3861 rec->buf = buf;
3862 rec->buf_len = rec->data_offset + rec->data_len;
3863
3864 if (rec->data_len == 0) {
3865 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3866 }
3867
3868 /*
3869 * DTLS-related tests.
3870 * Check epoch before checking length constraint because
3871 * the latter varies with the epoch. E.g., if a ChangeCipherSpec
3872 * message gets duplicated before the corresponding Finished message,
3873 * the second ChangeCipherSpec should be discarded because it belongs
3874 * to an old epoch, but not because its length is shorter than
3875 * the minimum record length for packets using the new record transform.
3876 * Note that these two kinds of failures are handled differently,
3877 * as an unexpected record is silently skipped but an invalid
3878 * record leads to the entire datagram being dropped.
3879 */
3880 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3881 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3882 rec_epoch = MBEDTLS_GET_UINT16_BE(rec->ctr, 0);
3883
3884 /* Check that the datagram is large enough to contain a record
3885 * of the advertised length. */
3886 if (len < rec->data_offset + rec->data_len) {
3887 MBEDTLS_SSL_DEBUG_MSG(1,
3888 (
3889 "Datagram of length %u too small to contain record of advertised length %u.",
3890 (unsigned) len,
3891 (unsigned) (rec->data_offset + rec->data_len)));
3892 return MBEDTLS_ERR_SSL_INVALID_RECORD;
3893 }
3894
3895 /* Records from other, non-matching epochs are silently discarded.
3896 * (The case of same-port Client reconnects must be considered in
3897 * the caller). */
3898 if (rec_epoch != ssl->in_epoch) {
3899 MBEDTLS_SSL_DEBUG_MSG(1, ("record from another epoch: "
3900 "expected %u, received %lu",
3901 ssl->in_epoch, (unsigned long) rec_epoch));
3902
3903 /* Records from the next epoch are considered for buffering
3904 * (concretely: early Finished messages). */
3905 if (rec_epoch == (unsigned) ssl->in_epoch + 1) {
3906 MBEDTLS_SSL_DEBUG_MSG(2, ("Consider record for buffering"));
3907 return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
3908 }
3909
3910 return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
3911 }
3912 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3913 /* For records from the correct epoch, check whether their
3914 * sequence number has been seen before. */
3915 else if (mbedtls_ssl_dtls_record_replay_check((mbedtls_ssl_context *) ssl,
3916 &rec->ctr[0]) != 0) {
3917 MBEDTLS_SSL_DEBUG_MSG(1, ("replayed record"));
3918 return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
3919 }
3920 #endif
3921 }
3922 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3923
3924 return 0;
3925 }
3926
3927
3928 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3929 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_client_reconnect(mbedtls_ssl_context * ssl)3930 static int ssl_check_client_reconnect(mbedtls_ssl_context *ssl)
3931 {
3932 unsigned int rec_epoch = MBEDTLS_GET_UINT16_BE(ssl->in_ctr, 0);
3933
3934 /*
3935 * Check for an epoch 0 ClientHello. We can't use in_msg here to
3936 * access the first byte of record content (handshake type), as we
3937 * have an active transform (possibly iv_len != 0), so use the
3938 * fact that the record header len is 13 instead.
3939 */
3940 if (rec_epoch == 0 &&
3941 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
3942 mbedtls_ssl_is_handshake_over(ssl) == 1 &&
3943 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
3944 ssl->in_left > 13 &&
3945 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO) {
3946 MBEDTLS_SSL_DEBUG_MSG(1, ("possible client reconnect "
3947 "from the same port"));
3948 return ssl_handle_possible_reconnect(ssl);
3949 }
3950
3951 return 0;
3952 }
3953 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3954
3955 /*
3956 * If applicable, decrypt record content
3957 */
3958 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_prepare_record_content(mbedtls_ssl_context * ssl,mbedtls_record * rec)3959 static int ssl_prepare_record_content(mbedtls_ssl_context *ssl,
3960 mbedtls_record *rec)
3961 {
3962 int ret, done = 0;
3963
3964 MBEDTLS_SSL_DEBUG_BUF(4, "input record from network",
3965 rec->buf, rec->buf_len);
3966
3967 /*
3968 * In TLS 1.3, always treat ChangeCipherSpec records
3969 * as unencrypted. The only thing we do with them is
3970 * check the length and content and ignore them.
3971 */
3972 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
3973 if (ssl->transform_in != NULL &&
3974 ssl->transform_in->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
3975 if (rec->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
3976 done = 1;
3977 }
3978 }
3979 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
3980
3981 if (!done && ssl->transform_in != NULL) {
3982 unsigned char const old_msg_type = rec->type;
3983
3984 if ((ret = mbedtls_ssl_decrypt_buf(ssl, ssl->transform_in,
3985 rec)) != 0) {
3986 MBEDTLS_SSL_DEBUG_RET(1, "ssl_decrypt_buf", ret);
3987
3988 #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
3989 /*
3990 * Although the server rejected early data, it might receive early
3991 * data as long as it has not received the client Finished message.
3992 * It is encrypted with early keys and should be ignored as stated
3993 * in section 4.2.10 of RFC 8446:
3994 *
3995 * "Ignore the extension and return a regular 1-RTT response. The
3996 * server then skips past early data by attempting to deprotect
3997 * received records using the handshake traffic key, discarding
3998 * records which fail deprotection (up to the configured
3999 * max_early_data_size). Once a record is deprotected successfully,
4000 * it is treated as the start of the client's second flight and the
4001 * server proceeds as with an ordinary 1-RTT handshake."
4002 */
4003 if ((old_msg_type == MBEDTLS_SSL_MSG_APPLICATION_DATA) &&
4004 (ssl->discard_early_data_record ==
4005 MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD)) {
4006 MBEDTLS_SSL_DEBUG_MSG(
4007 3, ("EarlyData: deprotect and discard app data records."));
4008
4009 ret = mbedtls_ssl_tls13_check_early_data_len(ssl, rec->data_len);
4010 if (ret != 0) {
4011 return ret;
4012 }
4013 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4014 }
4015 #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
4016
4017 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4018 if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID &&
4019 ssl->conf->ignore_unexpected_cid
4020 == MBEDTLS_SSL_UNEXPECTED_CID_IGNORE) {
4021 MBEDTLS_SSL_DEBUG_MSG(3, ("ignoring unexpected CID"));
4022 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4023 }
4024 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4025
4026 /*
4027 * The decryption of the record failed, no reason to ignore it,
4028 * return in error with the decryption error code.
4029 */
4030 return ret;
4031 }
4032
4033 #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
4034 /*
4035 * If the server were discarding protected records that it fails to
4036 * deprotect because it has rejected early data, as we have just
4037 * deprotected successfully a record, the server has to resume normal
4038 * operation and fail the connection if the deprotection of a record
4039 * fails.
4040 */
4041 if (ssl->discard_early_data_record ==
4042 MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD) {
4043 ssl->discard_early_data_record = MBEDTLS_SSL_EARLY_DATA_NO_DISCARD;
4044 }
4045 #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
4046
4047 if (old_msg_type != rec->type) {
4048 MBEDTLS_SSL_DEBUG_MSG(4, ("record type after decrypt (before %d): %d",
4049 old_msg_type, rec->type));
4050 }
4051
4052 MBEDTLS_SSL_DEBUG_BUF(4, "input payload after decrypt",
4053 rec->buf + rec->data_offset, rec->data_len);
4054
4055 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4056 /* We have already checked the record content type
4057 * in ssl_parse_record_header(), failing or silently
4058 * dropping the record in the case of an unknown type.
4059 *
4060 * Since with the use of CIDs, the record content type
4061 * might change during decryption, re-check the record
4062 * content type, but treat a failure as fatal this time. */
4063 if (ssl_check_record_type(rec->type)) {
4064 MBEDTLS_SSL_DEBUG_MSG(1, ("unknown record type"));
4065 return MBEDTLS_ERR_SSL_INVALID_RECORD;
4066 }
4067 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4068
4069 if (rec->data_len == 0) {
4070 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4071 if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2
4072 && rec->type != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
4073 /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
4074 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid zero-length message type: %d", ssl->in_msgtype));
4075 return MBEDTLS_ERR_SSL_INVALID_RECORD;
4076 }
4077 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4078
4079 ssl->nb_zero++;
4080
4081 /*
4082 * Three or more empty messages may be a DoS attack
4083 * (excessive CPU consumption).
4084 */
4085 if (ssl->nb_zero > 3) {
4086 MBEDTLS_SSL_DEBUG_MSG(1, ("received four consecutive empty "
4087 "messages, possible DoS attack"));
4088 /* Treat the records as if they were not properly authenticated,
4089 * thereby failing the connection if we see more than allowed
4090 * by the configured bad MAC threshold. */
4091 return MBEDTLS_ERR_SSL_INVALID_MAC;
4092 }
4093 } else {
4094 ssl->nb_zero = 0;
4095 }
4096
4097 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4098 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4099 ; /* in_ctr read from peer, not maintained internally */
4100 } else
4101 #endif
4102 {
4103 unsigned i;
4104 for (i = MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
4105 i > mbedtls_ssl_ep_len(ssl); i--) {
4106 if (++ssl->in_ctr[i - 1] != 0) {
4107 break;
4108 }
4109 }
4110
4111 /* The loop goes to its end iff the counter is wrapping */
4112 if (i == mbedtls_ssl_ep_len(ssl)) {
4113 MBEDTLS_SSL_DEBUG_MSG(1, ("incoming message counter would wrap"));
4114 return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
4115 }
4116 }
4117
4118 }
4119
4120 #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C)
4121 /*
4122 * Although the server rejected early data because it needed to send an
4123 * HelloRetryRequest message, it might receive early data as long as it has
4124 * not received the client Finished message.
4125 * The early data is encrypted with early keys and should be ignored as
4126 * stated in section 4.2.10 of RFC 8446 (second case):
4127 *
4128 * "The server then ignores early data by skipping all records with an
4129 * external content type of "application_data" (indicating that they are
4130 * encrypted), up to the configured max_early_data_size. Ignore application
4131 * data message before 2nd ClientHello when early_data was received in 1st
4132 * ClientHello."
4133 */
4134 if (ssl->discard_early_data_record == MBEDTLS_SSL_EARLY_DATA_DISCARD) {
4135 if (rec->type == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
4136
4137 ret = mbedtls_ssl_tls13_check_early_data_len(ssl, rec->data_len);
4138 if (ret != 0) {
4139 return ret;
4140 }
4141
4142 MBEDTLS_SSL_DEBUG_MSG(
4143 3, ("EarlyData: Ignore application message before 2nd ClientHello"));
4144
4145 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4146 } else if (rec->type == MBEDTLS_SSL_MSG_HANDSHAKE) {
4147 ssl->discard_early_data_record = MBEDTLS_SSL_EARLY_DATA_NO_DISCARD;
4148 }
4149 }
4150 #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
4151
4152 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4153 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4154 mbedtls_ssl_dtls_replay_update(ssl);
4155 }
4156 #endif
4157
4158 /* Check actual (decrypted) record content length against
4159 * configured maximum. */
4160 if (rec->data_len > MBEDTLS_SSL_IN_CONTENT_LEN) {
4161 MBEDTLS_SSL_DEBUG_MSG(1, ("bad message length"));
4162 return MBEDTLS_ERR_SSL_INVALID_RECORD;
4163 }
4164
4165 return 0;
4166 }
4167
4168 /*
4169 * Read a record.
4170 *
4171 * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
4172 * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
4173 *
4174 */
4175
4176 /* Helper functions for mbedtls_ssl_read_record(). */
4177 MBEDTLS_CHECK_RETURN_CRITICAL
4178 static int ssl_consume_current_message(mbedtls_ssl_context *ssl);
4179 MBEDTLS_CHECK_RETURN_CRITICAL
4180 static int ssl_get_next_record(mbedtls_ssl_context *ssl);
4181 MBEDTLS_CHECK_RETURN_CRITICAL
4182 static int ssl_record_is_in_progress(mbedtls_ssl_context *ssl);
4183
mbedtls_ssl_read_record(mbedtls_ssl_context * ssl,unsigned update_hs_digest)4184 int mbedtls_ssl_read_record(mbedtls_ssl_context *ssl,
4185 unsigned update_hs_digest)
4186 {
4187 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4188
4189 MBEDTLS_SSL_DEBUG_MSG(2, ("=> read record"));
4190
4191 if (ssl->keep_current_message == 0) {
4192 do {
4193
4194 ret = ssl_consume_current_message(ssl);
4195 if (ret != 0) {
4196 return ret;
4197 }
4198
4199 if (ssl_record_is_in_progress(ssl) == 0) {
4200 int dtls_have_buffered = 0;
4201 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4202
4203 /* We only check for buffered messages if the
4204 * current datagram is fully consumed. */
4205 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4206 ssl_next_record_is_in_datagram(ssl) == 0) {
4207 if (ssl_load_buffered_message(ssl) == 0) {
4208 dtls_have_buffered = 1;
4209 }
4210 }
4211
4212 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4213 if (dtls_have_buffered == 0) {
4214 ret = ssl_get_next_record(ssl);
4215 if (ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING) {
4216 continue;
4217 }
4218
4219 if (ret != 0) {
4220 MBEDTLS_SSL_DEBUG_RET(1, ("ssl_get_next_record"), ret);
4221 return ret;
4222 }
4223 }
4224 }
4225
4226 ret = mbedtls_ssl_handle_message_type(ssl);
4227
4228 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4229 if (ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
4230 /* Buffer future message */
4231 ret = ssl_buffer_message(ssl);
4232 if (ret != 0) {
4233 return ret;
4234 }
4235
4236 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4237 }
4238 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4239
4240 } while (MBEDTLS_ERR_SSL_NON_FATAL == ret ||
4241 MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret);
4242
4243 if (0 != ret) {
4244 MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_handle_message_type"), ret);
4245 return ret;
4246 }
4247
4248 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4249 update_hs_digest == 1) {
4250 ret = mbedtls_ssl_update_handshake_status(ssl);
4251 if (0 != ret) {
4252 MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_update_handshake_status"), ret);
4253 return ret;
4254 }
4255 }
4256 } else {
4257 MBEDTLS_SSL_DEBUG_MSG(2, ("reuse previously read message"));
4258 ssl->keep_current_message = 0;
4259 }
4260
4261 MBEDTLS_SSL_DEBUG_MSG(2, ("<= read record"));
4262
4263 return 0;
4264 }
4265
4266 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4267 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_next_record_is_in_datagram(mbedtls_ssl_context * ssl)4268 static int ssl_next_record_is_in_datagram(mbedtls_ssl_context *ssl)
4269 {
4270 if (ssl->in_left > ssl->next_record_offset) {
4271 return 1;
4272 }
4273
4274 return 0;
4275 }
4276
4277 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_load_buffered_message(mbedtls_ssl_context * ssl)4278 static int ssl_load_buffered_message(mbedtls_ssl_context *ssl)
4279 {
4280 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4281 mbedtls_ssl_hs_buffer *hs_buf;
4282 int ret = 0;
4283
4284 if (hs == NULL) {
4285 return -1;
4286 }
4287
4288 MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_load_buffered_message"));
4289
4290 if (ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
4291 ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC) {
4292 /* Check if we have seen a ChangeCipherSpec before.
4293 * If yes, synthesize a CCS record. */
4294 if (!hs->buffering.seen_ccs) {
4295 MBEDTLS_SSL_DEBUG_MSG(2, ("CCS not seen in the current flight"));
4296 ret = -1;
4297 goto exit;
4298 }
4299
4300 MBEDTLS_SSL_DEBUG_MSG(2, ("Injecting buffered CCS message"));
4301 ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
4302 ssl->in_msglen = 1;
4303 ssl->in_msg[0] = 1;
4304
4305 /* As long as they are equal, the exact value doesn't matter. */
4306 ssl->in_left = 0;
4307 ssl->next_record_offset = 0;
4308
4309 hs->buffering.seen_ccs = 0;
4310 goto exit;
4311 }
4312
4313 #if defined(MBEDTLS_DEBUG_C)
4314 /* Debug only */
4315 {
4316 unsigned offset;
4317 for (offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++) {
4318 hs_buf = &hs->buffering.hs[offset];
4319 if (hs_buf->is_valid == 1) {
4320 MBEDTLS_SSL_DEBUG_MSG(2, ("Future message with sequence number %u %s buffered.",
4321 hs->in_msg_seq + offset,
4322 hs_buf->is_complete ? "fully" : "partially"));
4323 }
4324 }
4325 }
4326 #endif /* MBEDTLS_DEBUG_C */
4327
4328 /* Check if we have buffered and/or fully reassembled the
4329 * next handshake message. */
4330 hs_buf = &hs->buffering.hs[0];
4331 if ((hs_buf->is_valid == 1) && (hs_buf->is_complete == 1)) {
4332 /* Synthesize a record containing the buffered HS message. */
4333 size_t msg_len = MBEDTLS_GET_UINT24_BE(hs_buf->data, 1);
4334
4335 /* Double-check that we haven't accidentally buffered
4336 * a message that doesn't fit into the input buffer. */
4337 if (msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN) {
4338 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4339 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4340 }
4341
4342 MBEDTLS_SSL_DEBUG_MSG(2, ("Next handshake message has been buffered - load"));
4343 MBEDTLS_SSL_DEBUG_BUF(3, "Buffered handshake message (incl. header)",
4344 hs_buf->data, msg_len + 12);
4345
4346 ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4347 ssl->in_hslen = msg_len + 12;
4348 ssl->in_msglen = msg_len + 12;
4349 memcpy(ssl->in_msg, hs_buf->data, ssl->in_hslen);
4350
4351 ret = 0;
4352 goto exit;
4353 } else {
4354 MBEDTLS_SSL_DEBUG_MSG(2, ("Next handshake message %u not or only partially bufffered",
4355 hs->in_msg_seq));
4356 }
4357
4358 ret = -1;
4359
4360 exit:
4361
4362 MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_load_buffered_message"));
4363 return ret;
4364 }
4365
4366 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_buffer_make_space(mbedtls_ssl_context * ssl,size_t desired)4367 static int ssl_buffer_make_space(mbedtls_ssl_context *ssl,
4368 size_t desired)
4369 {
4370 int offset;
4371 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4372 MBEDTLS_SSL_DEBUG_MSG(2, ("Attempt to free buffered messages to have %u bytes available",
4373 (unsigned) desired));
4374
4375 /* Get rid of future records epoch first, if such exist. */
4376 ssl_free_buffered_record(ssl);
4377
4378 /* Check if we have enough space available now. */
4379 if (desired <= (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4380 hs->buffering.total_bytes_buffered)) {
4381 MBEDTLS_SSL_DEBUG_MSG(2, ("Enough space available after freeing future epoch record"));
4382 return 0;
4383 }
4384
4385 /* We don't have enough space to buffer the next expected handshake
4386 * message. Remove buffers used for future messages to gain space,
4387 * starting with the most distant one. */
4388 for (offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
4389 offset >= 0; offset--) {
4390 MBEDTLS_SSL_DEBUG_MSG(2,
4391 (
4392 "Free buffering slot %d to make space for reassembly of next handshake message",
4393 offset));
4394
4395 ssl_buffering_free_slot(ssl, (uint8_t) offset);
4396
4397 /* Check if we have enough space available now. */
4398 if (desired <= (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4399 hs->buffering.total_bytes_buffered)) {
4400 MBEDTLS_SSL_DEBUG_MSG(2, ("Enough space available after freeing buffered HS messages"));
4401 return 0;
4402 }
4403 }
4404
4405 return -1;
4406 }
4407
4408 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_buffer_message(mbedtls_ssl_context * ssl)4409 static int ssl_buffer_message(mbedtls_ssl_context *ssl)
4410 {
4411 int ret = 0;
4412 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4413
4414 if (hs == NULL) {
4415 return 0;
4416 }
4417
4418 MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_buffer_message"));
4419
4420 switch (ssl->in_msgtype) {
4421 case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
4422 MBEDTLS_SSL_DEBUG_MSG(2, ("Remember CCS message"));
4423
4424 hs->buffering.seen_ccs = 1;
4425 break;
4426
4427 case MBEDTLS_SSL_MSG_HANDSHAKE:
4428 {
4429 unsigned recv_msg_seq_offset;
4430 unsigned recv_msg_seq = MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
4431 mbedtls_ssl_hs_buffer *hs_buf;
4432 size_t msg_len = ssl->in_hslen - 12;
4433
4434 /* We should never receive an old handshake
4435 * message - double-check nonetheless. */
4436 if (recv_msg_seq < ssl->handshake->in_msg_seq) {
4437 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4438 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4439 }
4440
4441 recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
4442 if (recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS) {
4443 /* Silently ignore -- message too far in the future */
4444 MBEDTLS_SSL_DEBUG_MSG(2,
4445 ("Ignore future HS message with sequence number %u, "
4446 "buffering window %u - %u",
4447 recv_msg_seq, ssl->handshake->in_msg_seq,
4448 ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS -
4449 1));
4450
4451 goto exit;
4452 }
4453
4454 MBEDTLS_SSL_DEBUG_MSG(2, ("Buffering HS message with sequence number %u, offset %u ",
4455 recv_msg_seq, recv_msg_seq_offset));
4456
4457 hs_buf = &hs->buffering.hs[recv_msg_seq_offset];
4458
4459 /* Check if the buffering for this seq nr has already commenced. */
4460 if (!hs_buf->is_valid) {
4461 size_t reassembly_buf_sz;
4462
4463 hs_buf->is_fragmented =
4464 (ssl_hs_is_proper_fragment(ssl) == 1);
4465
4466 /* We copy the message back into the input buffer
4467 * after reassembly, so check that it's not too large.
4468 * This is an implementation-specific limitation
4469 * and not one from the standard, hence it is not
4470 * checked in ssl_check_hs_header(). */
4471 if (msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN) {
4472 /* Ignore message */
4473 goto exit;
4474 }
4475
4476 /* Check if we have enough space to buffer the message. */
4477 if (hs->buffering.total_bytes_buffered >
4478 MBEDTLS_SSL_DTLS_MAX_BUFFERING) {
4479 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4480 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4481 }
4482
4483 reassembly_buf_sz = ssl_get_reassembly_buffer_size(msg_len,
4484 hs_buf->is_fragmented);
4485
4486 if (reassembly_buf_sz > (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4487 hs->buffering.total_bytes_buffered)) {
4488 if (recv_msg_seq_offset > 0) {
4489 /* If we can't buffer a future message because
4490 * of space limitations -- ignore. */
4491 MBEDTLS_SSL_DEBUG_MSG(2,
4492 ("Buffering of future message of size %"
4493 MBEDTLS_PRINTF_SIZET
4494 " would exceed the compile-time limit %"
4495 MBEDTLS_PRINTF_SIZET
4496 " (already %" MBEDTLS_PRINTF_SIZET
4497 " bytes buffered) -- ignore\n",
4498 msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4499 hs->buffering.total_bytes_buffered));
4500 goto exit;
4501 } else {
4502 MBEDTLS_SSL_DEBUG_MSG(2,
4503 ("Buffering of future message of size %"
4504 MBEDTLS_PRINTF_SIZET
4505 " would exceed the compile-time limit %"
4506 MBEDTLS_PRINTF_SIZET
4507 " (already %" MBEDTLS_PRINTF_SIZET
4508 " bytes buffered) -- attempt to make space by freeing buffered future messages\n",
4509 msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4510 hs->buffering.total_bytes_buffered));
4511 }
4512
4513 if (ssl_buffer_make_space(ssl, reassembly_buf_sz) != 0) {
4514 MBEDTLS_SSL_DEBUG_MSG(2,
4515 ("Reassembly of next message of size %"
4516 MBEDTLS_PRINTF_SIZET
4517 " (%" MBEDTLS_PRINTF_SIZET
4518 " with bitmap) would exceed"
4519 " the compile-time limit %"
4520 MBEDTLS_PRINTF_SIZET
4521 " (already %" MBEDTLS_PRINTF_SIZET
4522 " bytes buffered) -- fail\n",
4523 msg_len,
4524 reassembly_buf_sz,
4525 (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4526 hs->buffering.total_bytes_buffered));
4527 ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
4528 goto exit;
4529 }
4530 }
4531
4532 MBEDTLS_SSL_DEBUG_MSG(2,
4533 ("initialize reassembly, total length = %"
4534 MBEDTLS_PRINTF_SIZET,
4535 msg_len));
4536
4537 hs_buf->data = mbedtls_calloc(1, reassembly_buf_sz);
4538 if (hs_buf->data == NULL) {
4539 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
4540 goto exit;
4541 }
4542 hs_buf->data_len = reassembly_buf_sz;
4543
4544 /* Prepare final header: copy msg_type, length and message_seq,
4545 * then add standardised fragment_offset and fragment_length */
4546 memcpy(hs_buf->data, ssl->in_msg, 6);
4547 memset(hs_buf->data + 6, 0, 3);
4548 memcpy(hs_buf->data + 9, hs_buf->data + 1, 3);
4549
4550 hs_buf->is_valid = 1;
4551
4552 hs->buffering.total_bytes_buffered += reassembly_buf_sz;
4553 } else {
4554 /* Make sure msg_type and length are consistent */
4555 if (memcmp(hs_buf->data, ssl->in_msg, 4) != 0) {
4556 MBEDTLS_SSL_DEBUG_MSG(1, ("Fragment header mismatch - ignore"));
4557 /* Ignore */
4558 goto exit;
4559 }
4560 }
4561
4562 if (!hs_buf->is_complete) {
4563 size_t frag_len, frag_off;
4564 unsigned char * const msg = hs_buf->data + 12;
4565
4566 /*
4567 * Check and copy current fragment
4568 */
4569
4570 /* Validation of header fields already done in
4571 * mbedtls_ssl_prepare_handshake_record(). */
4572 frag_off = ssl_get_hs_frag_off(ssl);
4573 frag_len = ssl_get_hs_frag_len(ssl);
4574
4575 MBEDTLS_SSL_DEBUG_MSG(2, ("adding fragment, offset = %" MBEDTLS_PRINTF_SIZET
4576 ", length = %" MBEDTLS_PRINTF_SIZET,
4577 frag_off, frag_len));
4578 memcpy(msg + frag_off, ssl->in_msg + 12, frag_len);
4579
4580 if (hs_buf->is_fragmented) {
4581 unsigned char * const bitmask = msg + msg_len;
4582 ssl_bitmask_set(bitmask, frag_off, frag_len);
4583 hs_buf->is_complete = (ssl_bitmask_check(bitmask,
4584 msg_len) == 0);
4585 } else {
4586 hs_buf->is_complete = 1;
4587 }
4588
4589 MBEDTLS_SSL_DEBUG_MSG(2, ("message %scomplete",
4590 hs_buf->is_complete ? "" : "not yet "));
4591 }
4592
4593 break;
4594 }
4595
4596 default:
4597 /* We don't buffer other types of messages. */
4598 break;
4599 }
4600
4601 exit:
4602
4603 MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_buffer_message"));
4604 return ret;
4605 }
4606 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4607
4608 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_consume_current_message(mbedtls_ssl_context * ssl)4609 static int ssl_consume_current_message(mbedtls_ssl_context *ssl)
4610 {
4611 /*
4612 * Consume last content-layer message and potentially
4613 * update in_msglen which keeps track of the contents'
4614 * consumption state.
4615 *
4616 * (1) Handshake messages:
4617 * Remove last handshake message, move content
4618 * and adapt in_msglen.
4619 *
4620 * (2) Alert messages:
4621 * Consume whole record content, in_msglen = 0.
4622 *
4623 * (3) Change cipher spec:
4624 * Consume whole record content, in_msglen = 0.
4625 *
4626 * (4) Application data:
4627 * Don't do anything - the record layer provides
4628 * the application data as a stream transport
4629 * and consumes through mbedtls_ssl_read only.
4630 *
4631 */
4632
4633 /* Case (1): Handshake messages */
4634 if (ssl->in_hslen != 0) {
4635 /* Hard assertion to be sure that no application data
4636 * is in flight, as corrupting ssl->in_msglen during
4637 * ssl->in_offt != NULL is fatal. */
4638 if (ssl->in_offt != NULL) {
4639 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4640 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4641 }
4642
4643 /*
4644 * Get next Handshake message in the current record
4645 */
4646
4647 /* Notes:
4648 * (1) in_hslen is not necessarily the size of the
4649 * current handshake content: If DTLS handshake
4650 * fragmentation is used, that's the fragment
4651 * size instead. Using the total handshake message
4652 * size here is faulty and should be changed at
4653 * some point.
4654 * (2) While it doesn't seem to cause problems, one
4655 * has to be very careful not to assume that in_hslen
4656 * is always <= in_msglen in a sensible communication.
4657 * Again, it's wrong for DTLS handshake fragmentation.
4658 * The following check is therefore mandatory, and
4659 * should not be treated as a silently corrected assertion.
4660 * Additionally, ssl->in_hslen might be arbitrarily out of
4661 * bounds after handling a DTLS message with an unexpected
4662 * sequence number, see mbedtls_ssl_prepare_handshake_record.
4663 */
4664 if (ssl->in_hslen < ssl->in_msglen) {
4665 ssl->in_msglen -= ssl->in_hslen;
4666 memmove(ssl->in_msg, ssl->in_msg + ssl->in_hslen,
4667 ssl->in_msglen);
4668
4669 MBEDTLS_SSL_DEBUG_BUF(4, "remaining content in record",
4670 ssl->in_msg, ssl->in_msglen);
4671 } else {
4672 ssl->in_msglen = 0;
4673 }
4674
4675 ssl->in_hslen = 0;
4676 }
4677 /* Case (4): Application data */
4678 else if (ssl->in_offt != NULL) {
4679 return 0;
4680 }
4681 /* Everything else (CCS & Alerts) */
4682 else {
4683 ssl->in_msglen = 0;
4684 }
4685
4686 return 0;
4687 }
4688
4689 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_record_is_in_progress(mbedtls_ssl_context * ssl)4690 static int ssl_record_is_in_progress(mbedtls_ssl_context *ssl)
4691 {
4692 if (ssl->in_msglen > 0) {
4693 return 1;
4694 }
4695
4696 return 0;
4697 }
4698
4699 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4700
ssl_free_buffered_record(mbedtls_ssl_context * ssl)4701 static void ssl_free_buffered_record(mbedtls_ssl_context *ssl)
4702 {
4703 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4704 if (hs == NULL) {
4705 return;
4706 }
4707
4708 if (hs->buffering.future_record.data != NULL) {
4709 hs->buffering.total_bytes_buffered -=
4710 hs->buffering.future_record.len;
4711
4712 mbedtls_free(hs->buffering.future_record.data);
4713 hs->buffering.future_record.data = NULL;
4714 }
4715 }
4716
4717 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_load_buffered_record(mbedtls_ssl_context * ssl)4718 static int ssl_load_buffered_record(mbedtls_ssl_context *ssl)
4719 {
4720 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4721 unsigned char *rec;
4722 size_t rec_len;
4723 unsigned rec_epoch;
4724 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
4725 size_t in_buf_len = ssl->in_buf_len;
4726 #else
4727 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
4728 #endif
4729 if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4730 return 0;
4731 }
4732
4733 if (hs == NULL) {
4734 return 0;
4735 }
4736
4737 rec = hs->buffering.future_record.data;
4738 rec_len = hs->buffering.future_record.len;
4739 rec_epoch = hs->buffering.future_record.epoch;
4740
4741 if (rec == NULL) {
4742 return 0;
4743 }
4744
4745 /* Only consider loading future records if the
4746 * input buffer is empty. */
4747 if (ssl_next_record_is_in_datagram(ssl) == 1) {
4748 return 0;
4749 }
4750
4751 MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_load_buffered_record"));
4752
4753 if (rec_epoch != ssl->in_epoch) {
4754 MBEDTLS_SSL_DEBUG_MSG(2, ("Buffered record not from current epoch."));
4755 goto exit;
4756 }
4757
4758 MBEDTLS_SSL_DEBUG_MSG(2, ("Found buffered record from current epoch - load"));
4759
4760 /* Double-check that the record is not too large */
4761 if (rec_len > in_buf_len - (size_t) (ssl->in_hdr - ssl->in_buf)) {
4762 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4763 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4764 }
4765
4766 memcpy(ssl->in_hdr, rec, rec_len);
4767 ssl->in_left = rec_len;
4768 ssl->next_record_offset = 0;
4769
4770 ssl_free_buffered_record(ssl);
4771
4772 exit:
4773 MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_load_buffered_record"));
4774 return 0;
4775 }
4776
4777 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_buffer_future_record(mbedtls_ssl_context * ssl,mbedtls_record const * rec)4778 static int ssl_buffer_future_record(mbedtls_ssl_context *ssl,
4779 mbedtls_record const *rec)
4780 {
4781 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4782
4783 /* Don't buffer future records outside handshakes. */
4784 if (hs == NULL) {
4785 return 0;
4786 }
4787
4788 /* Only buffer handshake records (we are only interested
4789 * in Finished messages). */
4790 if (rec->type != MBEDTLS_SSL_MSG_HANDSHAKE) {
4791 return 0;
4792 }
4793
4794 /* Don't buffer more than one future epoch record. */
4795 if (hs->buffering.future_record.data != NULL) {
4796 return 0;
4797 }
4798
4799 /* Don't buffer record if there's not enough buffering space remaining. */
4800 if (rec->buf_len > (MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4801 hs->buffering.total_bytes_buffered)) {
4802 MBEDTLS_SSL_DEBUG_MSG(2, ("Buffering of future epoch record of size %" MBEDTLS_PRINTF_SIZET
4803 " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET
4804 " (already %" MBEDTLS_PRINTF_SIZET
4805 " bytes buffered) -- ignore\n",
4806 rec->buf_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4807 hs->buffering.total_bytes_buffered));
4808 return 0;
4809 }
4810
4811 /* Buffer record */
4812 MBEDTLS_SSL_DEBUG_MSG(2, ("Buffer record from epoch %u",
4813 ssl->in_epoch + 1U));
4814 MBEDTLS_SSL_DEBUG_BUF(3, "Buffered record", rec->buf, rec->buf_len);
4815
4816 /* ssl_parse_record_header() only considers records
4817 * of the next epoch as candidates for buffering. */
4818 hs->buffering.future_record.epoch = ssl->in_epoch + 1;
4819 hs->buffering.future_record.len = rec->buf_len;
4820
4821 hs->buffering.future_record.data =
4822 mbedtls_calloc(1, hs->buffering.future_record.len);
4823 if (hs->buffering.future_record.data == NULL) {
4824 /* If we run out of RAM trying to buffer a
4825 * record from the next epoch, just ignore. */
4826 return 0;
4827 }
4828
4829 memcpy(hs->buffering.future_record.data, rec->buf, rec->buf_len);
4830
4831 hs->buffering.total_bytes_buffered += rec->buf_len;
4832 return 0;
4833 }
4834
4835 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4836
4837 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_get_next_record(mbedtls_ssl_context * ssl)4838 static int ssl_get_next_record(mbedtls_ssl_context *ssl)
4839 {
4840 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4841 mbedtls_record rec;
4842
4843 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4844 /* We might have buffered a future record; if so,
4845 * and if the epoch matches now, load it.
4846 * On success, this call will set ssl->in_left to
4847 * the length of the buffered record, so that
4848 * the calls to ssl_fetch_input() below will
4849 * essentially be no-ops. */
4850 ret = ssl_load_buffered_record(ssl);
4851 if (ret != 0) {
4852 return ret;
4853 }
4854 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4855
4856 /* Ensure that we have enough space available for the default form
4857 * of TLS / DTLS record headers (5 Bytes for TLS, 13 Bytes for DTLS,
4858 * with no space for CIDs counted in). */
4859 ret = mbedtls_ssl_fetch_input(ssl, mbedtls_ssl_in_hdr_len(ssl));
4860 if (ret != 0) {
4861 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
4862 return ret;
4863 }
4864
4865 ret = ssl_parse_record_header(ssl, ssl->in_hdr, ssl->in_left, &rec);
4866 if (ret != 0) {
4867 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4868 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4869 if (ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE) {
4870 ret = ssl_buffer_future_record(ssl, &rec);
4871 if (ret != 0) {
4872 return ret;
4873 }
4874
4875 /* Fall through to handling of unexpected records */
4876 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
4877 }
4878
4879 if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) {
4880 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
4881 /* Reset in pointers to default state for TLS/DTLS records,
4882 * assuming no CID and no offset between record content and
4883 * record plaintext. */
4884 mbedtls_ssl_update_in_pointers(ssl);
4885
4886 /* Setup internal message pointers from record structure. */
4887 ssl->in_msgtype = rec.type;
4888 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
4889 ssl->in_len = ssl->in_cid + rec.cid_len;
4890 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
4891 ssl->in_iv = ssl->in_msg = ssl->in_len + 2;
4892 ssl->in_msglen = rec.data_len;
4893
4894 ret = ssl_check_client_reconnect(ssl);
4895 MBEDTLS_SSL_DEBUG_RET(2, "ssl_check_client_reconnect", ret);
4896 if (ret != 0) {
4897 return ret;
4898 }
4899 #endif
4900
4901 /* Skip unexpected record (but not whole datagram) */
4902 ssl->next_record_offset = rec.buf_len;
4903
4904 MBEDTLS_SSL_DEBUG_MSG(1, ("discarding unexpected record "
4905 "(header)"));
4906 } else {
4907 /* Skip invalid record and the rest of the datagram */
4908 ssl->next_record_offset = 0;
4909 ssl->in_left = 0;
4910
4911 MBEDTLS_SSL_DEBUG_MSG(1, ("discarding invalid record "
4912 "(header)"));
4913 }
4914
4915 /* Get next record */
4916 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4917 } else
4918 #endif
4919 {
4920 return ret;
4921 }
4922 }
4923
4924 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4925 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4926 /* Remember offset of next record within datagram. */
4927 ssl->next_record_offset = rec.buf_len;
4928 if (ssl->next_record_offset < ssl->in_left) {
4929 MBEDTLS_SSL_DEBUG_MSG(3, ("more than one record within datagram"));
4930 }
4931 } else
4932 #endif
4933 {
4934 /*
4935 * Fetch record contents from underlying transport.
4936 */
4937 ret = mbedtls_ssl_fetch_input(ssl, rec.buf_len);
4938 if (ret != 0) {
4939 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
4940 return ret;
4941 }
4942
4943 ssl->in_left = 0;
4944 }
4945
4946 /*
4947 * Decrypt record contents.
4948 */
4949
4950 if ((ret = ssl_prepare_record_content(ssl, &rec)) != 0) {
4951 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4952 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4953 /* Silently discard invalid records */
4954 if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
4955 /* Except when waiting for Finished as a bad mac here
4956 * probably means something went wrong in the handshake
4957 * (eg wrong psk used, mitm downgrade attempt, etc.) */
4958 if (ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
4959 ssl->state == MBEDTLS_SSL_SERVER_FINISHED) {
4960 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
4961 if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
4962 mbedtls_ssl_send_alert_message(ssl,
4963 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4964 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC);
4965 }
4966 #endif
4967 return ret;
4968 }
4969
4970 if (ssl->conf->badmac_limit != 0 &&
4971 ++ssl->badmac_seen >= ssl->conf->badmac_limit) {
4972 MBEDTLS_SSL_DEBUG_MSG(1, ("too many records with bad MAC"));
4973 return MBEDTLS_ERR_SSL_INVALID_MAC;
4974 }
4975
4976 /* As above, invalid records cause
4977 * dismissal of the whole datagram. */
4978
4979 ssl->next_record_offset = 0;
4980 ssl->in_left = 0;
4981
4982 MBEDTLS_SSL_DEBUG_MSG(1, ("discarding invalid record (mac)"));
4983 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
4984 }
4985
4986 return ret;
4987 } else
4988 #endif
4989 {
4990 /* Error out (and send alert) on invalid records */
4991 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
4992 if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
4993 mbedtls_ssl_send_alert_message(ssl,
4994 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4995 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC);
4996 }
4997 #endif
4998 return ret;
4999 }
5000 }
5001
5002
5003 /* Reset in pointers to default state for TLS/DTLS records,
5004 * assuming no CID and no offset between record content and
5005 * record plaintext. */
5006 mbedtls_ssl_update_in_pointers(ssl);
5007 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5008 ssl->in_len = ssl->in_cid + rec.cid_len;
5009 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5010 ssl->in_iv = ssl->in_len + 2;
5011
5012 /* The record content type may change during decryption,
5013 * so re-read it. */
5014 ssl->in_msgtype = rec.type;
5015 /* Also update the input buffer, because unfortunately
5016 * the server-side ssl_parse_client_hello() reparses the
5017 * record header when receiving a ClientHello initiating
5018 * a renegotiation. */
5019 ssl->in_hdr[0] = rec.type;
5020 ssl->in_msg = rec.buf + rec.data_offset;
5021 ssl->in_msglen = rec.data_len;
5022 MBEDTLS_PUT_UINT16_BE(rec.data_len, ssl->in_len, 0);
5023
5024 return 0;
5025 }
5026
mbedtls_ssl_handle_message_type(mbedtls_ssl_context * ssl)5027 int mbedtls_ssl_handle_message_type(mbedtls_ssl_context *ssl)
5028 {
5029 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5030
5031 /*
5032 * Handle particular types of records
5033 */
5034 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
5035 if ((ret = mbedtls_ssl_prepare_handshake_record(ssl)) != 0) {
5036 return ret;
5037 }
5038 }
5039
5040 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
5041 if (ssl->in_msglen != 1) {
5042 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid CCS message, len: %" MBEDTLS_PRINTF_SIZET,
5043 ssl->in_msglen));
5044 return MBEDTLS_ERR_SSL_INVALID_RECORD;
5045 }
5046
5047 if (ssl->in_msg[0] != 1) {
5048 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid CCS message, content: %02x",
5049 ssl->in_msg[0]));
5050 return MBEDTLS_ERR_SSL_INVALID_RECORD;
5051 }
5052
5053 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5054 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5055 ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
5056 ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC) {
5057 if (ssl->handshake == NULL) {
5058 MBEDTLS_SSL_DEBUG_MSG(1, ("dropping ChangeCipherSpec outside handshake"));
5059 return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
5060 }
5061
5062 MBEDTLS_SSL_DEBUG_MSG(1, ("received out-of-order ChangeCipherSpec - remember"));
5063 return MBEDTLS_ERR_SSL_EARLY_MESSAGE;
5064 }
5065 #endif
5066
5067 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
5068 if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
5069 #if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
5070 MBEDTLS_SSL_DEBUG_MSG(1,
5071 ("Ignore ChangeCipherSpec in TLS 1.3 compatibility mode"));
5072 return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
5073 #else
5074 MBEDTLS_SSL_DEBUG_MSG(1,
5075 ("ChangeCipherSpec invalid in TLS 1.3 without compatibility mode"));
5076 return MBEDTLS_ERR_SSL_INVALID_RECORD;
5077 #endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
5078 }
5079 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
5080 }
5081
5082 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT) {
5083 if (ssl->in_msglen != 2) {
5084 /* Note: Standard allows for more than one 2 byte alert
5085 to be packed in a single message, but Mbed TLS doesn't
5086 currently support this. */
5087 MBEDTLS_SSL_DEBUG_MSG(1, ("invalid alert message, len: %" MBEDTLS_PRINTF_SIZET,
5088 ssl->in_msglen));
5089 return MBEDTLS_ERR_SSL_INVALID_RECORD;
5090 }
5091
5092 MBEDTLS_SSL_DEBUG_MSG(2, ("got an alert message, type: [%u:%u]",
5093 ssl->in_msg[0], ssl->in_msg[1]));
5094
5095 /*
5096 * Ignore non-fatal alerts, except close_notify and no_renegotiation
5097 */
5098 if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL) {
5099 MBEDTLS_SSL_DEBUG_MSG(1, ("is a fatal alert message (msg %d)",
5100 ssl->in_msg[1]));
5101 return MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE;
5102 }
5103
5104 if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
5105 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY) {
5106 MBEDTLS_SSL_DEBUG_MSG(2, ("is a close notify message"));
5107 return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY;
5108 }
5109
5110 #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
5111 if (ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
5112 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION) {
5113 MBEDTLS_SSL_DEBUG_MSG(2, ("is a no renegotiation alert"));
5114 /* Will be handled when trying to parse ServerHello */
5115 return 0;
5116 }
5117 #endif
5118 /* Silently ignore: fetch new message */
5119 return MBEDTLS_ERR_SSL_NON_FATAL;
5120 }
5121
5122 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5123 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5124 /* Drop unexpected ApplicationData records,
5125 * except at the beginning of renegotiations */
5126 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
5127 mbedtls_ssl_is_handshake_over(ssl) == 0
5128 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5129 && !(ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
5130 ssl->state == MBEDTLS_SSL_SERVER_HELLO)
5131 #endif
5132 ) {
5133 MBEDTLS_SSL_DEBUG_MSG(1, ("dropping unexpected ApplicationData"));
5134 return MBEDTLS_ERR_SSL_NON_FATAL;
5135 }
5136
5137 if (ssl->handshake != NULL &&
5138 mbedtls_ssl_is_handshake_over(ssl) == 1) {
5139 mbedtls_ssl_handshake_wrapup_free_hs_transform(ssl);
5140 }
5141 }
5142 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5143
5144 return 0;
5145 }
5146
mbedtls_ssl_send_fatal_handshake_failure(mbedtls_ssl_context * ssl)5147 int mbedtls_ssl_send_fatal_handshake_failure(mbedtls_ssl_context *ssl)
5148 {
5149 return mbedtls_ssl_send_alert_message(ssl,
5150 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5151 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
5152 }
5153
mbedtls_ssl_send_alert_message(mbedtls_ssl_context * ssl,unsigned char level,unsigned char message)5154 int mbedtls_ssl_send_alert_message(mbedtls_ssl_context *ssl,
5155 unsigned char level,
5156 unsigned char message)
5157 {
5158 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5159
5160 if (ssl == NULL || ssl->conf == NULL) {
5161 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5162 }
5163
5164 if (ssl->out_left != 0) {
5165 return mbedtls_ssl_flush_output(ssl);
5166 }
5167
5168 MBEDTLS_SSL_DEBUG_MSG(2, ("=> send alert message"));
5169 MBEDTLS_SSL_DEBUG_MSG(3, ("send alert level=%u message=%u", level, message));
5170
5171 ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
5172 ssl->out_msglen = 2;
5173 ssl->out_msg[0] = level;
5174 ssl->out_msg[1] = message;
5175
5176 if ((ret = mbedtls_ssl_write_record(ssl, SSL_FORCE_FLUSH)) != 0) {
5177 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
5178 return ret;
5179 }
5180 MBEDTLS_SSL_DEBUG_MSG(2, ("<= send alert message"));
5181
5182 return 0;
5183 }
5184
mbedtls_ssl_write_change_cipher_spec(mbedtls_ssl_context * ssl)5185 int mbedtls_ssl_write_change_cipher_spec(mbedtls_ssl_context *ssl)
5186 {
5187 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5188
5189 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write change cipher spec"));
5190
5191 ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
5192 ssl->out_msglen = 1;
5193 ssl->out_msg[0] = 1;
5194
5195 ssl->state++;
5196
5197 if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
5198 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
5199 return ret;
5200 }
5201
5202 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write change cipher spec"));
5203
5204 return 0;
5205 }
5206
mbedtls_ssl_parse_change_cipher_spec(mbedtls_ssl_context * ssl)5207 int mbedtls_ssl_parse_change_cipher_spec(mbedtls_ssl_context *ssl)
5208 {
5209 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5210
5211 MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse change cipher spec"));
5212
5213 if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
5214 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
5215 return ret;
5216 }
5217
5218 if (ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC) {
5219 MBEDTLS_SSL_DEBUG_MSG(1, ("bad change cipher spec message"));
5220 mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5221 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
5222 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5223 }
5224
5225 /* CCS records are only accepted if they have length 1 and content '1',
5226 * so we don't need to check this here. */
5227
5228 /*
5229 * Switch to our negotiated transform and session parameters for inbound
5230 * data.
5231 */
5232 MBEDTLS_SSL_DEBUG_MSG(3, ("switching to new transform spec for inbound data"));
5233 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5234 ssl->transform_in = ssl->transform_negotiate;
5235 #endif
5236 ssl->session_in = ssl->session_negotiate;
5237
5238 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5239 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5240 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5241 mbedtls_ssl_dtls_replay_reset(ssl);
5242 #endif
5243
5244 /* Increment epoch */
5245 if (++ssl->in_epoch == 0) {
5246 MBEDTLS_SSL_DEBUG_MSG(1, ("DTLS epoch would wrap"));
5247 /* This is highly unlikely to happen for legitimate reasons, so
5248 treat it as an attack and don't send an alert. */
5249 return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
5250 }
5251 } else
5252 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5253 memset(ssl->in_ctr, 0, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
5254
5255 mbedtls_ssl_update_in_pointers(ssl);
5256
5257 ssl->state++;
5258
5259 MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse change cipher spec"));
5260
5261 return 0;
5262 }
5263
5264 /* Once ssl->out_hdr as the address of the beginning of the
5265 * next outgoing record is set, deduce the other pointers.
5266 *
5267 * Note: For TLS, we save the implicit record sequence number
5268 * (entering MAC computation) in the 8 bytes before ssl->out_hdr,
5269 * and the caller has to make sure there's space for this.
5270 */
5271
ssl_transform_get_explicit_iv_len(mbedtls_ssl_transform const * transform)5272 static size_t ssl_transform_get_explicit_iv_len(
5273 mbedtls_ssl_transform const *transform)
5274 {
5275 return transform->ivlen - transform->fixed_ivlen;
5276 }
5277
mbedtls_ssl_update_out_pointers(mbedtls_ssl_context * ssl,mbedtls_ssl_transform * transform)5278 void mbedtls_ssl_update_out_pointers(mbedtls_ssl_context *ssl,
5279 mbedtls_ssl_transform *transform)
5280 {
5281 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5282 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5283 ssl->out_ctr = ssl->out_hdr + 3;
5284 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5285 ssl->out_cid = ssl->out_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5286 ssl->out_len = ssl->out_cid;
5287 if (transform != NULL) {
5288 ssl->out_len += transform->out_cid_len;
5289 }
5290 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5291 ssl->out_len = ssl->out_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5292 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5293 ssl->out_iv = ssl->out_len + 2;
5294 } else
5295 #endif
5296 {
5297 ssl->out_len = ssl->out_hdr + 3;
5298 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5299 ssl->out_cid = ssl->out_len;
5300 #endif
5301 ssl->out_iv = ssl->out_hdr + 5;
5302 }
5303
5304 ssl->out_msg = ssl->out_iv;
5305 /* Adjust out_msg to make space for explicit IV, if used. */
5306 if (transform != NULL) {
5307 ssl->out_msg += ssl_transform_get_explicit_iv_len(transform);
5308 }
5309 }
5310
5311 /* Once ssl->in_hdr as the address of the beginning of the
5312 * next incoming record is set, deduce the other pointers.
5313 *
5314 * Note: For TLS, we save the implicit record sequence number
5315 * (entering MAC computation) in the 8 bytes before ssl->in_hdr,
5316 * and the caller has to make sure there's space for this.
5317 */
5318
mbedtls_ssl_update_in_pointers(mbedtls_ssl_context * ssl)5319 void mbedtls_ssl_update_in_pointers(mbedtls_ssl_context *ssl)
5320 {
5321 /* This function sets the pointers to match the case
5322 * of unprotected TLS/DTLS records, with both ssl->in_iv
5323 * and ssl->in_msg pointing to the beginning of the record
5324 * content.
5325 *
5326 * When decrypting a protected record, ssl->in_msg
5327 * will be shifted to point to the beginning of the
5328 * record plaintext.
5329 */
5330
5331 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5332 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5333 /* This sets the header pointers to match records
5334 * without CID. When we receive a record containing
5335 * a CID, the fields are shifted accordingly in
5336 * ssl_parse_record_header(). */
5337 ssl->in_ctr = ssl->in_hdr + 3;
5338 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5339 ssl->in_cid = ssl->in_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5340 ssl->in_len = ssl->in_cid; /* Default: no CID */
5341 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5342 ssl->in_len = ssl->in_ctr + MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5343 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5344 ssl->in_iv = ssl->in_len + 2;
5345 } else
5346 #endif
5347 {
5348 ssl->in_ctr = ssl->in_hdr - MBEDTLS_SSL_SEQUENCE_NUMBER_LEN;
5349 ssl->in_len = ssl->in_hdr + 3;
5350 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5351 ssl->in_cid = ssl->in_len;
5352 #endif
5353 ssl->in_iv = ssl->in_hdr + 5;
5354 }
5355
5356 /* This will be adjusted at record decryption time. */
5357 ssl->in_msg = ssl->in_iv;
5358 }
5359
5360 /*
5361 * Setup an SSL context
5362 */
5363
mbedtls_ssl_reset_in_out_pointers(mbedtls_ssl_context * ssl)5364 void mbedtls_ssl_reset_in_out_pointers(mbedtls_ssl_context *ssl)
5365 {
5366 /* Set the incoming and outgoing record pointers. */
5367 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5368 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5369 ssl->out_hdr = ssl->out_buf;
5370 ssl->in_hdr = ssl->in_buf;
5371 } else
5372 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5373 {
5374 ssl->out_ctr = ssl->out_buf;
5375 ssl->out_hdr = ssl->out_buf + 8;
5376 ssl->in_hdr = ssl->in_buf + 8;
5377 }
5378
5379 /* Derive other internal pointers. */
5380 mbedtls_ssl_update_out_pointers(ssl, NULL /* no transform enabled */);
5381 mbedtls_ssl_update_in_pointers(ssl);
5382 }
5383
5384 /*
5385 * SSL get accessors
5386 */
mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context * ssl)5387 size_t mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context *ssl)
5388 {
5389 return ssl->in_offt == NULL ? 0 : ssl->in_msglen;
5390 }
5391
mbedtls_ssl_check_pending(const mbedtls_ssl_context * ssl)5392 int mbedtls_ssl_check_pending(const mbedtls_ssl_context *ssl)
5393 {
5394 /*
5395 * Case A: We're currently holding back
5396 * a message for further processing.
5397 */
5398
5399 if (ssl->keep_current_message == 1) {
5400 MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: record held back for processing"));
5401 return 1;
5402 }
5403
5404 /*
5405 * Case B: Further records are pending in the current datagram.
5406 */
5407
5408 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5409 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5410 ssl->in_left > ssl->next_record_offset) {
5411 MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: more records within current datagram"));
5412 return 1;
5413 }
5414 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5415
5416 /*
5417 * Case C: A handshake message is being processed.
5418 */
5419
5420 if (ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen) {
5421 MBEDTLS_SSL_DEBUG_MSG(3,
5422 ("ssl_check_pending: more handshake messages within current record"));
5423 return 1;
5424 }
5425
5426 /*
5427 * Case D: An application data message is being processed
5428 */
5429 if (ssl->in_offt != NULL) {
5430 MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: application data record is being processed"));
5431 return 1;
5432 }
5433
5434 /*
5435 * In all other cases, the rest of the message can be dropped.
5436 * As in ssl_get_next_record, this needs to be adapted if
5437 * we implement support for multiple alerts in single records.
5438 */
5439
5440 MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_check_pending: nothing pending"));
5441 return 0;
5442 }
5443
5444
mbedtls_ssl_get_record_expansion(const mbedtls_ssl_context * ssl)5445 int mbedtls_ssl_get_record_expansion(const mbedtls_ssl_context *ssl)
5446 {
5447 size_t transform_expansion = 0;
5448 const mbedtls_ssl_transform *transform = ssl->transform_out;
5449 unsigned block_size;
5450 #if defined(MBEDTLS_USE_PSA_CRYPTO)
5451 psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;
5452 psa_key_type_t key_type;
5453 #endif /* MBEDTLS_USE_PSA_CRYPTO */
5454
5455 size_t out_hdr_len = mbedtls_ssl_out_hdr_len(ssl);
5456
5457 if (transform == NULL) {
5458 return (int) out_hdr_len;
5459 }
5460
5461
5462 #if defined(MBEDTLS_USE_PSA_CRYPTO)
5463 if (transform->psa_alg == PSA_ALG_GCM ||
5464 transform->psa_alg == PSA_ALG_CCM ||
5465 transform->psa_alg == PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 8) ||
5466 transform->psa_alg == PSA_ALG_CHACHA20_POLY1305 ||
5467 transform->psa_alg == MBEDTLS_SSL_NULL_CIPHER) {
5468 transform_expansion = transform->minlen;
5469 } else if (transform->psa_alg == PSA_ALG_CBC_NO_PADDING) {
5470 (void) psa_get_key_attributes(transform->psa_key_enc, &attr);
5471 key_type = psa_get_key_type(&attr);
5472
5473 block_size = PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type);
5474
5475 /* Expansion due to the addition of the MAC. */
5476 transform_expansion += transform->maclen;
5477
5478 /* Expansion due to the addition of CBC padding;
5479 * Theoretically up to 256 bytes, but we never use
5480 * more than the block size of the underlying cipher. */
5481 transform_expansion += block_size;
5482
5483 /* For TLS 1.2 or higher, an explicit IV is added
5484 * after the record header. */
5485 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5486 transform_expansion += block_size;
5487 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5488 } else {
5489 MBEDTLS_SSL_DEBUG_MSG(1,
5490 ("Unsupported psa_alg spotted in mbedtls_ssl_get_record_expansion()"));
5491 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
5492 }
5493 #else
5494 switch (mbedtls_cipher_get_cipher_mode(&transform->cipher_ctx_enc)) {
5495 case MBEDTLS_MODE_GCM:
5496 case MBEDTLS_MODE_CCM:
5497 case MBEDTLS_MODE_CHACHAPOLY:
5498 case MBEDTLS_MODE_STREAM:
5499 transform_expansion = transform->minlen;
5500 break;
5501
5502 case MBEDTLS_MODE_CBC:
5503
5504 block_size = mbedtls_cipher_get_block_size(
5505 &transform->cipher_ctx_enc);
5506
5507 /* Expansion due to the addition of the MAC. */
5508 transform_expansion += transform->maclen;
5509
5510 /* Expansion due to the addition of CBC padding;
5511 * Theoretically up to 256 bytes, but we never use
5512 * more than the block size of the underlying cipher. */
5513 transform_expansion += block_size;
5514
5515 /* For TLS 1.2 or higher, an explicit IV is added
5516 * after the record header. */
5517 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5518 transform_expansion += block_size;
5519 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5520
5521 break;
5522
5523 default:
5524 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
5525 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
5526 }
5527 #endif /* MBEDTLS_USE_PSA_CRYPTO */
5528
5529 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
5530 if (transform->out_cid_len != 0) {
5531 transform_expansion += MBEDTLS_SSL_MAX_CID_EXPANSION;
5532 }
5533 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
5534
5535 return (int) (out_hdr_len + transform_expansion);
5536 }
5537
5538 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5539 /*
5540 * Check record counters and renegotiate if they're above the limit.
5541 */
5542 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_ctr_renegotiate(mbedtls_ssl_context * ssl)5543 static int ssl_check_ctr_renegotiate(mbedtls_ssl_context *ssl)
5544 {
5545 size_t ep_len = mbedtls_ssl_ep_len(ssl);
5546 int in_ctr_cmp;
5547 int out_ctr_cmp;
5548
5549 if (mbedtls_ssl_is_handshake_over(ssl) == 0 ||
5550 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
5551 ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED) {
5552 return 0;
5553 }
5554
5555 in_ctr_cmp = memcmp(ssl->in_ctr + ep_len,
5556 &ssl->conf->renego_period[ep_len],
5557 MBEDTLS_SSL_SEQUENCE_NUMBER_LEN - ep_len);
5558 out_ctr_cmp = memcmp(&ssl->cur_out_ctr[ep_len],
5559 &ssl->conf->renego_period[ep_len],
5560 sizeof(ssl->cur_out_ctr) - ep_len);
5561
5562 if (in_ctr_cmp <= 0 && out_ctr_cmp <= 0) {
5563 return 0;
5564 }
5565
5566 MBEDTLS_SSL_DEBUG_MSG(1, ("record counter limit reached: renegotiate"));
5567 return mbedtls_ssl_renegotiate(ssl);
5568 }
5569 #endif /* MBEDTLS_SSL_RENEGOTIATION */
5570
5571 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
5572
5573 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5574 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_check_new_session_ticket(mbedtls_ssl_context * ssl)5575 static int ssl_tls13_check_new_session_ticket(mbedtls_ssl_context *ssl)
5576 {
5577
5578 if ((ssl->in_hslen == mbedtls_ssl_hs_hdr_len(ssl)) ||
5579 (ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET)) {
5580 return 0;
5581 }
5582
5583 ssl->keep_current_message = 1;
5584
5585 MBEDTLS_SSL_DEBUG_MSG(3, ("NewSessionTicket received"));
5586 mbedtls_ssl_handshake_set_state(ssl,
5587 MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET);
5588
5589 return MBEDTLS_ERR_SSL_WANT_READ;
5590 }
5591 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5592
5593 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_handle_hs_message_post_handshake(mbedtls_ssl_context * ssl)5594 static int ssl_tls13_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
5595 {
5596
5597 MBEDTLS_SSL_DEBUG_MSG(3, ("received post-handshake message"));
5598
5599 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5600 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
5601 int ret = ssl_tls13_check_new_session_ticket(ssl);
5602 if (ret != 0) {
5603 return ret;
5604 }
5605 }
5606 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5607
5608 /* Fail in all other cases. */
5609 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5610 }
5611 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
5612
5613 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5614 /* This function is called from mbedtls_ssl_read() when a handshake message is
5615 * received after the initial handshake. In this context, handshake messages
5616 * may only be sent for the purpose of initiating renegotiations.
5617 *
5618 * This function is introduced as a separate helper since the handling
5619 * of post-handshake handshake messages changes significantly in TLS 1.3,
5620 * and having a helper function allows to distinguish between TLS <= 1.2 and
5621 * TLS 1.3 in the future without bloating the logic of mbedtls_ssl_read().
5622 */
5623 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls12_handle_hs_message_post_handshake(mbedtls_ssl_context * ssl)5624 static int ssl_tls12_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
5625 {
5626 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5627
5628 /*
5629 * - For client-side, expect SERVER_HELLO_REQUEST.
5630 * - For server-side, expect CLIENT_HELLO.
5631 * - Fail (TLS) or silently drop record (DTLS) in other cases.
5632 */
5633
5634 #if defined(MBEDTLS_SSL_CLI_C)
5635 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
5636 (ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
5637 ssl->in_hslen != mbedtls_ssl_hs_hdr_len(ssl))) {
5638 MBEDTLS_SSL_DEBUG_MSG(1, ("handshake received (not HelloRequest)"));
5639
5640 /* With DTLS, drop the packet (probably from last handshake) */
5641 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5642 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5643 return 0;
5644 }
5645 #endif
5646 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5647 }
5648 #endif /* MBEDTLS_SSL_CLI_C */
5649
5650 #if defined(MBEDTLS_SSL_SRV_C)
5651 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
5652 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO) {
5653 MBEDTLS_SSL_DEBUG_MSG(1, ("handshake received (not ClientHello)"));
5654
5655 /* With DTLS, drop the packet (probably from last handshake) */
5656 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5657 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5658 return 0;
5659 }
5660 #endif
5661 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5662 }
5663 #endif /* MBEDTLS_SSL_SRV_C */
5664
5665 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5666 /* Determine whether renegotiation attempt should be accepted */
5667 if (!(ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
5668 (ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
5669 ssl->conf->allow_legacy_renegotiation ==
5670 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION))) {
5671 /*
5672 * Accept renegotiation request
5673 */
5674
5675 /* DTLS clients need to know renego is server-initiated */
5676 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5677 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5678 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
5679 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
5680 }
5681 #endif
5682 ret = mbedtls_ssl_start_renegotiation(ssl);
5683 if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
5684 ret != 0) {
5685 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_start_renegotiation",
5686 ret);
5687 return ret;
5688 }
5689 } else
5690 #endif /* MBEDTLS_SSL_RENEGOTIATION */
5691 {
5692 /*
5693 * Refuse renegotiation
5694 */
5695
5696 MBEDTLS_SSL_DEBUG_MSG(3, ("refusing renegotiation, sending alert"));
5697
5698 if ((ret = mbedtls_ssl_send_alert_message(ssl,
5699 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
5700 MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION)) != 0) {
5701 return ret;
5702 }
5703 }
5704
5705 return 0;
5706 }
5707 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5708
5709 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_handle_hs_message_post_handshake(mbedtls_ssl_context * ssl)5710 static int ssl_handle_hs_message_post_handshake(mbedtls_ssl_context *ssl)
5711 {
5712 /* Check protocol version and dispatch accordingly. */
5713 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
5714 if (ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
5715 return ssl_tls13_handle_hs_message_post_handshake(ssl);
5716 }
5717 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
5718
5719 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5720 if (ssl->tls_version <= MBEDTLS_SSL_VERSION_TLS1_2) {
5721 return ssl_tls12_handle_hs_message_post_handshake(ssl);
5722 }
5723 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5724
5725 /* Should never happen */
5726 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
5727 }
5728
5729 /*
5730 * brief Read at most 'len' application data bytes from the input
5731 * buffer.
5732 *
5733 * param ssl SSL context:
5734 * - First byte of application data not read yet in the input
5735 * buffer located at address `in_offt`.
5736 * - The number of bytes of data not read yet is `in_msglen`.
5737 * param buf buffer that will hold the data
5738 * param len maximum number of bytes to read
5739 *
5740 * note The function updates the fields `in_offt` and `in_msglen`
5741 * according to the number of bytes read.
5742 *
5743 * return The number of bytes read.
5744 */
ssl_read_application_data(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)5745 static int ssl_read_application_data(
5746 mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
5747 {
5748 size_t n = (len < ssl->in_msglen) ? len : ssl->in_msglen;
5749
5750 if (len != 0) {
5751 memcpy(buf, ssl->in_offt, n);
5752 ssl->in_msglen -= n;
5753 }
5754
5755 /* Zeroising the plaintext buffer to erase unused application data
5756 from the memory. */
5757 mbedtls_platform_zeroize(ssl->in_offt, n);
5758
5759 if (ssl->in_msglen == 0) {
5760 /* all bytes consumed */
5761 ssl->in_offt = NULL;
5762 ssl->keep_current_message = 0;
5763 } else {
5764 /* more data available */
5765 ssl->in_offt += n;
5766 }
5767
5768 return (int) n;
5769 }
5770
5771 /*
5772 * Receive application data decrypted from the SSL layer
5773 */
mbedtls_ssl_read(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)5774 int mbedtls_ssl_read(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
5775 {
5776 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5777
5778 if (ssl == NULL || ssl->conf == NULL) {
5779 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5780 }
5781
5782 MBEDTLS_SSL_DEBUG_MSG(2, ("=> read"));
5783
5784 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5785 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5786 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
5787 return ret;
5788 }
5789
5790 if (ssl->handshake != NULL &&
5791 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING) {
5792 if ((ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
5793 return ret;
5794 }
5795 }
5796 }
5797 #endif
5798
5799 /*
5800 * Check if renegotiation is necessary and/or handshake is
5801 * in process. If yes, perform/continue, and fall through
5802 * if an unexpected packet is received while the client
5803 * is waiting for the ServerHello.
5804 *
5805 * (There is no equivalent to the last condition on
5806 * the server-side as it is not treated as within
5807 * a handshake while waiting for the ClientHello
5808 * after a renegotiation request.)
5809 */
5810
5811 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5812 ret = ssl_check_ctr_renegotiate(ssl);
5813 if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
5814 ret != 0) {
5815 MBEDTLS_SSL_DEBUG_RET(1, "ssl_check_ctr_renegotiate", ret);
5816 return ret;
5817 }
5818 #endif
5819
5820 if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
5821 ret = mbedtls_ssl_handshake(ssl);
5822 if (ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
5823 ret != 0) {
5824 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
5825 return ret;
5826 }
5827 }
5828
5829 /* Loop as long as no application data record is available */
5830 while (ssl->in_offt == NULL) {
5831 /* Start timer if not already running */
5832 if (ssl->f_get_timer != NULL &&
5833 ssl->f_get_timer(ssl->p_timer) == -1) {
5834 mbedtls_ssl_set_timer(ssl, ssl->conf->read_timeout);
5835 }
5836
5837 if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
5838 if (ret == MBEDTLS_ERR_SSL_CONN_EOF) {
5839 return 0;
5840 }
5841
5842 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
5843 return ret;
5844 }
5845
5846 if (ssl->in_msglen == 0 &&
5847 ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
5848 /*
5849 * OpenSSL sends empty messages to randomize the IV
5850 */
5851 if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
5852 if (ret == MBEDTLS_ERR_SSL_CONN_EOF) {
5853 return 0;
5854 }
5855
5856 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
5857 return ret;
5858 }
5859 }
5860
5861 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE) {
5862 ret = ssl_handle_hs_message_post_handshake(ssl);
5863 if (ret != 0) {
5864 MBEDTLS_SSL_DEBUG_RET(1, "ssl_handle_hs_message_post_handshake",
5865 ret);
5866 return ret;
5867 }
5868
5869 /* At this point, we don't know whether the renegotiation triggered
5870 * by the post-handshake message has been completed or not. The cases
5871 * to consider are the following:
5872 * 1) The renegotiation is complete. In this case, no new record
5873 * has been read yet.
5874 * 2) The renegotiation is incomplete because the client received
5875 * an application data record while awaiting the ServerHello.
5876 * 3) The renegotiation is incomplete because the client received
5877 * a non-handshake, non-application data message while awaiting
5878 * the ServerHello.
5879 *
5880 * In each of these cases, looping will be the proper action:
5881 * - For 1), the next iteration will read a new record and check
5882 * if it's application data.
5883 * - For 2), the loop condition isn't satisfied as application data
5884 * is present, hence continue is the same as break
5885 * - For 3), the loop condition is satisfied and read_record
5886 * will re-deliver the message that was held back by the client
5887 * when expecting the ServerHello.
5888 */
5889
5890 continue;
5891 }
5892 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5893 else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
5894 if (ssl->conf->renego_max_records >= 0) {
5895 if (++ssl->renego_records_seen > ssl->conf->renego_max_records) {
5896 MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation requested, "
5897 "but not honored by client"));
5898 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5899 }
5900 }
5901 }
5902 #endif /* MBEDTLS_SSL_RENEGOTIATION */
5903
5904 /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
5905 if (ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT) {
5906 MBEDTLS_SSL_DEBUG_MSG(2, ("ignoring non-fatal non-closure alert"));
5907 return MBEDTLS_ERR_SSL_WANT_READ;
5908 }
5909
5910 if (ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA) {
5911 MBEDTLS_SSL_DEBUG_MSG(1, ("bad application data message"));
5912 return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
5913 }
5914
5915 ssl->in_offt = ssl->in_msg;
5916
5917 /* We're going to return something now, cancel timer,
5918 * except if handshake (renegotiation) is in progress */
5919 if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
5920 mbedtls_ssl_set_timer(ssl, 0);
5921 }
5922
5923 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5924 /* If we requested renego but received AppData, resend HelloRequest.
5925 * Do it now, after setting in_offt, to avoid taking this branch
5926 * again if ssl_write_hello_request() returns WANT_WRITE */
5927 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
5928 if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
5929 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
5930 if ((ret = mbedtls_ssl_resend_hello_request(ssl)) != 0) {
5931 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_resend_hello_request",
5932 ret);
5933 return ret;
5934 }
5935 }
5936 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
5937 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5938 }
5939
5940 ret = ssl_read_application_data(ssl, buf, len);
5941
5942 MBEDTLS_SSL_DEBUG_MSG(2, ("<= read"));
5943
5944 return ret;
5945 }
5946
5947 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_EARLY_DATA)
mbedtls_ssl_read_early_data(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)5948 int mbedtls_ssl_read_early_data(mbedtls_ssl_context *ssl,
5949 unsigned char *buf, size_t len)
5950 {
5951 if (ssl == NULL || (ssl->conf == NULL)) {
5952 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5953 }
5954
5955 /*
5956 * The server may receive early data only while waiting for the End of
5957 * Early Data handshake message.
5958 */
5959 if ((ssl->state != MBEDTLS_SSL_END_OF_EARLY_DATA) ||
5960 (ssl->in_offt == NULL)) {
5961 return MBEDTLS_ERR_SSL_CANNOT_READ_EARLY_DATA;
5962 }
5963
5964 return ssl_read_application_data(ssl, buf, len);
5965 }
5966 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_EARLY_DATA */
5967
5968 /*
5969 * Send application data to be encrypted by the SSL layer, taking care of max
5970 * fragment length and buffer size.
5971 *
5972 * According to RFC 5246 Section 6.2.1:
5973 *
5974 * Zero-length fragments of Application data MAY be sent as they are
5975 * potentially useful as a traffic analysis countermeasure.
5976 *
5977 * Therefore, it is possible that the input message length is 0 and the
5978 * corresponding return code is 0 on success.
5979 */
5980 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_real(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)5981 static int ssl_write_real(mbedtls_ssl_context *ssl,
5982 const unsigned char *buf, size_t len)
5983 {
5984 int ret = mbedtls_ssl_get_max_out_record_payload(ssl);
5985 const size_t max_len = (size_t) ret;
5986
5987 if (ret < 0) {
5988 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_get_max_out_record_payload", ret);
5989 return ret;
5990 }
5991
5992 if (len > max_len) {
5993 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5994 if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
5995 MBEDTLS_SSL_DEBUG_MSG(1, ("fragment larger than the (negotiated) "
5996 "maximum fragment length: %" MBEDTLS_PRINTF_SIZET
5997 " > %" MBEDTLS_PRINTF_SIZET,
5998 len, max_len));
5999 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6000 } else
6001 #endif
6002 len = max_len;
6003 }
6004
6005 if (ssl->out_left != 0) {
6006 /*
6007 * The user has previously tried to send the data and
6008 * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
6009 * written. In this case, we expect the high-level write function
6010 * (e.g. mbedtls_ssl_write()) to be called with the same parameters
6011 */
6012 if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
6013 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
6014 return ret;
6015 }
6016 } else {
6017 /*
6018 * The user is trying to send a message the first time, so we need to
6019 * copy the data into the internal buffers and setup the data structure
6020 * to keep track of partial writes
6021 */
6022 ssl->out_msglen = len;
6023 ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
6024 if (len > 0) {
6025 memcpy(ssl->out_msg, buf, len);
6026 }
6027
6028 if ((ret = mbedtls_ssl_write_record(ssl, SSL_FORCE_FLUSH)) != 0) {
6029 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_record", ret);
6030 return ret;
6031 }
6032 }
6033
6034 return (int) len;
6035 }
6036
6037 /*
6038 * Write application data (public-facing wrapper)
6039 */
mbedtls_ssl_write(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)6040 int mbedtls_ssl_write(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
6041 {
6042 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6043
6044 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write"));
6045
6046 if (ssl == NULL || ssl->conf == NULL) {
6047 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6048 }
6049
6050 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6051 if ((ret = ssl_check_ctr_renegotiate(ssl)) != 0) {
6052 MBEDTLS_SSL_DEBUG_RET(1, "ssl_check_ctr_renegotiate", ret);
6053 return ret;
6054 }
6055 #endif
6056
6057 if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
6058 if ((ret = mbedtls_ssl_handshake(ssl)) != 0) {
6059 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
6060 return ret;
6061 }
6062 }
6063
6064 ret = ssl_write_real(ssl, buf, len);
6065
6066 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write"));
6067
6068 return ret;
6069 }
6070
6071 #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_write_early_data(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)6072 int mbedtls_ssl_write_early_data(mbedtls_ssl_context *ssl,
6073 const unsigned char *buf, size_t len)
6074 {
6075 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6076 const struct mbedtls_ssl_config *conf;
6077 uint32_t remaining;
6078
6079 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write early_data"));
6080
6081 if (ssl == NULL || (conf = ssl->conf) == NULL) {
6082 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6083 }
6084
6085 if (conf->endpoint != MBEDTLS_SSL_IS_CLIENT) {
6086 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6087 }
6088
6089 if ((!mbedtls_ssl_conf_is_tls13_enabled(conf)) ||
6090 (conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
6091 (conf->early_data_enabled != MBEDTLS_SSL_EARLY_DATA_ENABLED)) {
6092 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6093 }
6094
6095 if (ssl->tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
6096 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6097 }
6098
6099 /*
6100 * If we are at the beginning of the handshake, the early data state being
6101 * equal to MBEDTLS_SSL_EARLY_DATA_STATE_IDLE or
6102 * MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT advance the handshake just
6103 * enough to be able to send early data if possible. That way, we can
6104 * guarantee that when starting the handshake with this function we will
6105 * send at least one record of early data. Note that when the state is
6106 * MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT and not yet
6107 * MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE, we cannot send early data
6108 * as the early data outbound transform has not been set as we may have to
6109 * first send a dummy CCS in clear.
6110 */
6111 if ((ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IDLE) ||
6112 (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT)) {
6113 while ((ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IDLE) ||
6114 (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT)) {
6115 ret = mbedtls_ssl_handshake_step(ssl);
6116 if (ret != 0) {
6117 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake_step", ret);
6118 return ret;
6119 }
6120
6121 ret = mbedtls_ssl_flush_output(ssl);
6122 if (ret != 0) {
6123 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
6124 return ret;
6125 }
6126 }
6127 remaining = ssl->session_negotiate->max_early_data_size;
6128 } else {
6129 /*
6130 * If we are past the point where we can send early data or we have
6131 * already reached the maximum early data size, return immediatly.
6132 * Otherwise, progress the handshake as much as possible to not delay
6133 * it too much. If we reach a point where we can still send early data,
6134 * then we will send some.
6135 */
6136 if ((ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE) &&
6137 (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED)) {
6138 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6139 }
6140
6141 remaining = ssl->session_negotiate->max_early_data_size -
6142 ssl->total_early_data_size;
6143
6144 if (remaining == 0) {
6145 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6146 }
6147
6148 ret = mbedtls_ssl_handshake(ssl);
6149 if ((ret != 0) && (ret != MBEDTLS_ERR_SSL_WANT_READ)) {
6150 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
6151 return ret;
6152 }
6153 }
6154
6155 if (((ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE) &&
6156 (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED))
6157 || (remaining == 0)) {
6158 return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
6159 }
6160
6161 if (len > remaining) {
6162 len = remaining;
6163 }
6164
6165 ret = ssl_write_real(ssl, buf, len);
6166 if (ret >= 0) {
6167 ssl->total_early_data_size += ret;
6168 }
6169
6170 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write early_data, ret=%d", ret));
6171
6172 return ret;
6173 }
6174 #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_CLI_C */
6175
6176 /*
6177 * Notify the peer that the connection is being closed
6178 */
mbedtls_ssl_close_notify(mbedtls_ssl_context * ssl)6179 int mbedtls_ssl_close_notify(mbedtls_ssl_context *ssl)
6180 {
6181 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6182
6183 if (ssl == NULL || ssl->conf == NULL) {
6184 return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6185 }
6186
6187 MBEDTLS_SSL_DEBUG_MSG(2, ("=> write close notify"));
6188
6189 if (mbedtls_ssl_is_handshake_over(ssl) == 1) {
6190 if ((ret = mbedtls_ssl_send_alert_message(ssl,
6191 MBEDTLS_SSL_ALERT_LEVEL_WARNING,
6192 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)) != 0) {
6193 MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_send_alert_message", ret);
6194 return ret;
6195 }
6196 }
6197
6198 MBEDTLS_SSL_DEBUG_MSG(2, ("<= write close notify"));
6199
6200 return 0;
6201 }
6202
mbedtls_ssl_transform_free(mbedtls_ssl_transform * transform)6203 void mbedtls_ssl_transform_free(mbedtls_ssl_transform *transform)
6204 {
6205 if (transform == NULL) {
6206 return;
6207 }
6208
6209 #if defined(MBEDTLS_USE_PSA_CRYPTO)
6210 psa_destroy_key(transform->psa_key_enc);
6211 psa_destroy_key(transform->psa_key_dec);
6212 #else
6213 mbedtls_cipher_free(&transform->cipher_ctx_enc);
6214 mbedtls_cipher_free(&transform->cipher_ctx_dec);
6215 #endif /* MBEDTLS_USE_PSA_CRYPTO */
6216
6217 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
6218 #if defined(MBEDTLS_USE_PSA_CRYPTO)
6219 psa_destroy_key(transform->psa_mac_enc);
6220 psa_destroy_key(transform->psa_mac_dec);
6221 #else
6222 mbedtls_md_free(&transform->md_ctx_enc);
6223 mbedtls_md_free(&transform->md_ctx_dec);
6224 #endif /* MBEDTLS_USE_PSA_CRYPTO */
6225 #endif
6226
6227 mbedtls_platform_zeroize(transform, sizeof(mbedtls_ssl_transform));
6228 }
6229
mbedtls_ssl_set_inbound_transform(mbedtls_ssl_context * ssl,mbedtls_ssl_transform * transform)6230 void mbedtls_ssl_set_inbound_transform(mbedtls_ssl_context *ssl,
6231 mbedtls_ssl_transform *transform)
6232 {
6233 ssl->transform_in = transform;
6234 memset(ssl->in_ctr, 0, MBEDTLS_SSL_SEQUENCE_NUMBER_LEN);
6235 }
6236
mbedtls_ssl_set_outbound_transform(mbedtls_ssl_context * ssl,mbedtls_ssl_transform * transform)6237 void mbedtls_ssl_set_outbound_transform(mbedtls_ssl_context *ssl,
6238 mbedtls_ssl_transform *transform)
6239 {
6240 ssl->transform_out = transform;
6241 memset(ssl->cur_out_ctr, 0, sizeof(ssl->cur_out_ctr));
6242 }
6243
6244 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6245
mbedtls_ssl_buffering_free(mbedtls_ssl_context * ssl)6246 void mbedtls_ssl_buffering_free(mbedtls_ssl_context *ssl)
6247 {
6248 unsigned offset;
6249 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
6250
6251 if (hs == NULL) {
6252 return;
6253 }
6254
6255 ssl_free_buffered_record(ssl);
6256
6257 for (offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++) {
6258 ssl_buffering_free_slot(ssl, offset);
6259 }
6260 }
6261
ssl_buffering_free_slot(mbedtls_ssl_context * ssl,uint8_t slot)6262 static void ssl_buffering_free_slot(mbedtls_ssl_context *ssl,
6263 uint8_t slot)
6264 {
6265 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
6266 mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
6267
6268 if (slot >= MBEDTLS_SSL_MAX_BUFFERED_HS) {
6269 return;
6270 }
6271
6272 if (hs_buf->is_valid == 1) {
6273 hs->buffering.total_bytes_buffered -= hs_buf->data_len;
6274 mbedtls_zeroize_and_free(hs_buf->data, hs_buf->data_len);
6275 memset(hs_buf, 0, sizeof(mbedtls_ssl_hs_buffer));
6276 }
6277 }
6278
6279 #endif /* MBEDTLS_SSL_PROTO_DTLS */
6280
6281 /*
6282 * Convert version numbers to/from wire format
6283 * and, for DTLS, to/from TLS equivalent.
6284 *
6285 * For TLS this is the identity.
6286 * For DTLS, map as follows, then use 1's complement (v -> ~v):
6287 * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2)
6288 * DTLS 1.0 is stored as TLS 1.1 internally
6289 */
mbedtls_ssl_write_version(unsigned char version[2],int transport,mbedtls_ssl_protocol_version tls_version)6290 void mbedtls_ssl_write_version(unsigned char version[2], int transport,
6291 mbedtls_ssl_protocol_version tls_version)
6292 {
6293 uint16_t tls_version_formatted;
6294 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6295 if (transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
6296 tls_version_formatted =
6297 ~(tls_version - (tls_version == 0x0302 ? 0x0202 : 0x0201));
6298 } else
6299 #else
6300 ((void) transport);
6301 #endif
6302 {
6303 tls_version_formatted = (uint16_t) tls_version;
6304 }
6305 MBEDTLS_PUT_UINT16_BE(tls_version_formatted, version, 0);
6306 }
6307
mbedtls_ssl_read_version(const unsigned char version[2],int transport)6308 uint16_t mbedtls_ssl_read_version(const unsigned char version[2],
6309 int transport)
6310 {
6311 uint16_t tls_version = MBEDTLS_GET_UINT16_BE(version, 0);
6312 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6313 if (transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
6314 tls_version =
6315 ~(tls_version - (tls_version == 0xfeff ? 0x0202 : 0x0201));
6316 }
6317 #else
6318 ((void) transport);
6319 #endif
6320 return tls_version;
6321 }
6322
6323 /*
6324 * Send pending fatal alert.
6325 * 0, No alert message.
6326 * !0, if mbedtls_ssl_send_alert_message() returned in error, the error code it
6327 * returned, ssl->alert_reason otherwise.
6328 */
mbedtls_ssl_handle_pending_alert(mbedtls_ssl_context * ssl)6329 int mbedtls_ssl_handle_pending_alert(mbedtls_ssl_context *ssl)
6330 {
6331 int ret;
6332
6333 /* No pending alert, return success*/
6334 if (ssl->send_alert == 0) {
6335 return 0;
6336 }
6337
6338 ret = mbedtls_ssl_send_alert_message(ssl,
6339 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
6340 ssl->alert_type);
6341
6342 /* If mbedtls_ssl_send_alert_message() returned with MBEDTLS_ERR_SSL_WANT_WRITE,
6343 * do not clear the alert to be able to send it later.
6344 */
6345 if (ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
6346 ssl->send_alert = 0;
6347 }
6348
6349 if (ret != 0) {
6350 return ret;
6351 }
6352
6353 return ssl->alert_reason;
6354 }
6355
6356 /*
6357 * Set pending fatal alert flag.
6358 */
mbedtls_ssl_pend_fatal_alert(mbedtls_ssl_context * ssl,unsigned char alert_type,int alert_reason)6359 void mbedtls_ssl_pend_fatal_alert(mbedtls_ssl_context *ssl,
6360 unsigned char alert_type,
6361 int alert_reason)
6362 {
6363 ssl->send_alert = 1;
6364 ssl->alert_type = alert_type;
6365 ssl->alert_reason = alert_reason;
6366 }
6367
6368 #endif /* MBEDTLS_SSL_TLS_C */
6369