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