Coverage Report

Created: 2026-05-12 06:58

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