Skip to content

Commit 26538a2

Browse files
Merge pull request #10884 from kareem-wolfssl/zd22127_2
Adjust wolfEntropy size calculation and error out if an invalid combination of settings is given.
2 parents 6722de5 + e187696 commit 26538a2

1 file changed

Lines changed: 39 additions & 3 deletions

File tree

wolfcrypt/src/wolfentropy.c

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -343,10 +343,46 @@ static void Entropy_StopThread(void)
343343
#error "ENTROPY_NUM_64BIT_WORDS must be <= SHA3-256 digest size in bytes"
344344
#endif
345345

346-
#if ENTROPY_BLOCK_SZ < ENTROPY_NUM_UPDATES_BITS
347-
#define EXTRA_ENTROPY_WORDS ENTROPY_NUM_UPDATES
346+
#if ENTROPY_NUM_UPDATES < 1
347+
#error "ENTROPY_NUM_UPDATES must be 1 or more"
348+
#endif
349+
350+
/* Largest offset added within the final block by Entropy_MemUse().
351+
*
352+
* Entropy_MemUse() computes, for a byte d[i] in [0, 255] and j in
353+
* [0, ENTROPY_NUM_UPDATES - 1]:
354+
* idx = (d[i] << ENTROPY_BLOCK_SZ) + (j << ENTROPY_OFFSET_SHIFTING)
355+
* As 256 << ENTROPY_BLOCK_SZ == ENTROPY_NUM_WORDS, the first term reaches
356+
* ENTROPY_NUM_WORDS - (1 << ENTROPY_BLOCK_SZ), and the maximum value added on
357+
* top of it is the offset below.
358+
*/
359+
#define ENTROPY_MAX_BLOCK_OFFSET \
360+
((ENTROPY_NUM_UPDATES - 1) << ENTROPY_OFFSET_SHIFTING)
361+
362+
/* Number of extra words entropy_state needs beyond ENTROPY_NUM_WORDS.
363+
*
364+
* The largest index accessed is:
365+
* (ENTROPY_NUM_WORDS - (1 << ENTROPY_BLOCK_SZ)) + ENTROPY_MAX_BLOCK_OFFSET
366+
* so the final block must hold (ENTROPY_MAX_BLOCK_OFFSET + 1) words. When that
367+
* exceeds one block the shifted offset spills past ENTROPY_NUM_WORDS, so
368+
* allocate exactly the overflow as extra words; otherwise the offset stays
369+
* within the block and no extra words are needed.
370+
*
371+
* This sizing keeps every access in bounds for any ENTROPY_NUM_UPDATES >= 1,
372+
* regardless of whether ENTROPY_NUM_UPDATES_BITS was supplied or left to
373+
* default to ENTROPY_BLOCK_SZ.
374+
*/
375+
#if (ENTROPY_MAX_BLOCK_OFFSET + 1) > (1 << ENTROPY_BLOCK_SZ)
376+
#define EXTRA_ENTROPY_WORDS \
377+
(ENTROPY_MAX_BLOCK_OFFSET + 1 - (1 << ENTROPY_BLOCK_SZ))
348378
#else
349-
#define EXTRA_ENTROPY_WORDS 0
379+
#define EXTRA_ENTROPY_WORDS 0
380+
#endif
381+
382+
#if (ENTROPY_MAX_BLOCK_OFFSET >= ((1 << ENTROPY_BLOCK_SZ) + EXTRA_ENTROPY_WORDS))
383+
#error "entropy_state sizing insufficient - Entropy_MemUse index would " \
384+
"exceed its bounds. This indicates an internal logic error in " \
385+
"the ENTROPY_* macro definitions."
350386
#endif
351387

352388
/* State to update that is multiple cache lines long. */

0 commit comments

Comments
 (0)