quickjs-tart

quickjs-based runtime for wallet-core logic
Log | Files | Refs | README | LICENSE

ssl_msg.c (234347B)


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