From dcf3b117490bc1e275bee1ea5dc4bf0c4ff61082 Mon Sep 17 00:00:00 2001 From: Ben Taylor Date: Fri, 29 May 2026 08:49:08 +0100 Subject: [PATCH] Tidy ChaCha20 counter limit handling Signed-off-by: Ben Taylor --- include/mbedtls/chacha20.h | 3 ++- library/chacha20.c | 2 +- tests/suites/test_suite_chacha20.function | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/mbedtls/chacha20.h b/include/mbedtls/chacha20.h index 172deb6967..c2c1bff86b 100644 --- a/include/mbedtls/chacha20.h +++ b/include/mbedtls/chacha20.h @@ -38,7 +38,8 @@ extern "C" { typedef struct mbedtls_chacha20_context { uint32_t MBEDTLS_PRIVATE(state)[16]; /*! The state (before round operations). */ uint8_t MBEDTLS_PRIVATE(keystream8)[64]; /*! Leftover keystream bytes. */ - size_t MBEDTLS_PRIVATE(keystream_bytes_used); /*! Number of keystream bytes already used. */ + size_t MBEDTLS_PRIVATE(keystream_bytes_used); /*! Number of keystream bytes already used, + * or an internal sentinel value. */ } mbedtls_chacha20_context; diff --git a/library/chacha20.c b/library/chacha20.c index 84289163fc..0f97116f0c 100644 --- a/library/chacha20.c +++ b/library/chacha20.c @@ -31,7 +31,7 @@ #define CHACHA20_BLOCK_SIZE_BYTES (4U * 16U) -#define CHACHA20_MAX_BLOCKS 0xFFFFFFFF +#define CHACHA20_MAX_BLOCKS UINT32_MAX #define CHACHA20_COUNTER_EXHAUSTED (CHACHA20_BLOCK_SIZE_BYTES + 1U) diff --git a/tests/suites/test_suite_chacha20.function b/tests/suites/test_suite_chacha20.function index 2163fd032d..d8cc8a0eb3 100644 --- a/tests/suites/test_suite_chacha20.function +++ b/tests/suites/test_suite_chacha20.function @@ -96,6 +96,7 @@ void chacha20_input_len_too_long(void) /* Consume the rest of the final counter block, then reject more input. */ TEST_EQUAL(mbedtls_chacha20_update(&ctx, 63, input, output), 0); + TEST_EQUAL(mbedtls_chacha20_update(&ctx, 0, NULL, NULL), 0); TEST_EQUAL(mbedtls_chacha20_update(&ctx, 1, input, output), MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA);