Coverage Report

Created: 2023-11-19 06:42

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