From bd57d52490b4d80965af9cc6ace7dd0951e353e6 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Thu, 29 Jan 2026 13:01:06 +0100 Subject: [PATCH] DRBG: make reseed_counter not be off by 1 Change `reseed_counter` to be the number of requests made since the last reseed, rather than this number minus 1. Thus, reseed when `reseed_counter >= reseed_interval` rather than `reseed_counter > reseed_interval`. The field `reseed_counter` is private so this is not an API change. Signed-off-by: Gilles Peskine --- include/mbedtls/ctr_drbg.h | 3 +-- library/ctr_drbg.c | 4 ++-- library/hmac_drbg.c | 4 ++-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/include/mbedtls/ctr_drbg.h b/include/mbedtls/ctr_drbg.h index 0b7cce1923..c8d64830b5 100644 --- a/include/mbedtls/ctr_drbg.h +++ b/include/mbedtls/ctr_drbg.h @@ -186,8 +186,7 @@ typedef struct mbedtls_ctr_drbg_context { unsigned char MBEDTLS_PRIVATE(counter)[16]; /*!< The counter (V). */ int MBEDTLS_PRIVATE(reseed_counter); /*!< The reseed counter. * This is the number of requests that have - * been made since the last (re)seeding, - * minus one. + * been made since the last (re)seeding. * Before the initial seeding, this field * contains the amount of entropy in bytes * to use as a nonce for the initial seeding, diff --git a/library/ctr_drbg.c b/library/ctr_drbg.c index b82044eb7d..bbbfdacf3d 100644 --- a/library/ctr_drbg.c +++ b/library/ctr_drbg.c @@ -494,7 +494,7 @@ static int mbedtls_ctr_drbg_reseed_internal(mbedtls_ctr_drbg_context *ctx, if ((ret = ctr_drbg_update_internal(ctx, seed)) != 0) { goto exit; } - ctx->reseed_counter = 1; + ctx->reseed_counter = 0; exit: mbedtls_platform_zeroize(seed, sizeof(seed)); @@ -629,7 +629,7 @@ int mbedtls_ctr_drbg_random_with_add(void *p_rng, memset(locals.add_input, 0, MBEDTLS_CTR_DRBG_SEEDLEN); - if (ctx->reseed_counter > ctx->reseed_interval || + if (ctx->reseed_counter >= ctx->reseed_interval || ctx->prediction_resistance) { if ((ret = mbedtls_ctr_drbg_reseed(ctx, additional, add_len)) != 0) { return ret; diff --git a/library/hmac_drbg.c b/library/hmac_drbg.c index 90174d5d17..d51962832e 100644 --- a/library/hmac_drbg.c +++ b/library/hmac_drbg.c @@ -196,7 +196,7 @@ static int hmac_drbg_reseed_core(mbedtls_hmac_drbg_context *ctx, } /* 3. Reset reseed_counter */ - ctx->reseed_counter = 1; + ctx->reseed_counter = 0; exit: /* 4. Done */ @@ -326,7 +326,7 @@ int mbedtls_hmac_drbg_random_with_add(void *p_rng, /* 1. (aka VII and IX) Check reseed counter and PR */ if (ctx->f_entropy != NULL && /* For no-reseeding instances */ (ctx->prediction_resistance == MBEDTLS_HMAC_DRBG_PR_ON || - ctx->reseed_counter > ctx->reseed_interval)) { + ctx->reseed_counter >= ctx->reseed_interval)) { if ((ret = mbedtls_hmac_drbg_reseed(ctx, additional, add_len)) != 0) { return ret; }