Coverage Report

Created: 2024-02-11 06:19

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