Coverage Report

Created: 2025-03-01 06:26

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