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