Compare commits
16 Commits
v5.8.4-sta
...
wolfEntrop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6ecafced2 | ||
|
|
89f27ceb19 | ||
|
|
eac5c29fdb | ||
|
|
4ccad17a39 | ||
|
|
0786aa2585 | ||
|
|
d49c76945a | ||
|
|
7752df3340 | ||
|
|
ba47f7f333 | ||
|
|
46c704f51f | ||
|
|
09e223baf3 | ||
|
|
15b55ef279 | ||
|
|
176801a21b | ||
|
|
eeb2b09b23 | ||
|
|
4da42ffae9 | ||
|
|
301a4a554b | ||
|
|
dc6fa0ad4e |
@@ -11020,6 +11020,7 @@ AM_CONDITIONAL([BUILD_DILITHIUM],[test "x$ENABLED_DILITHIUM" != "xno" || test "x
|
||||
AM_CONDITIONAL([BUILD_ECCSI],[test "x$ENABLED_ECCSI" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"])
|
||||
AM_CONDITIONAL([BUILD_SAKKE],[test "x$ENABLED_SAKKE" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"])
|
||||
AM_CONDITIONAL([BUILD_MEMORY],[test "x$ENABLED_MEMORY" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"])
|
||||
AM_CONDITIONAL([BUILD_MEMUSE],[test "x$ENABLED_ENTROPY_MEMUSE" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"])
|
||||
AM_CONDITIONAL([BUILD_RSA],[test "x$ENABLED_RSA" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"])
|
||||
AM_CONDITIONAL([BUILD_DH],[test "x$ENABLED_DH" != "xno" || test "x$ENABLED_USERSETTINGS" = "xyes"])
|
||||
AM_CONDITIONAL([BUILD_ASN],[test "x$ENABLED_ASN" != "xno" || test "x$ENABLED_RSA" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"])
|
||||
|
||||
@@ -961,6 +961,9 @@ struct wc_swallow_the_semicolon
|
||||
|
||||
#ifdef LINUXKM_LKCAPI_REGISTER_HASH_DRBG
|
||||
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
#include <wolfssl/wolfcrypt/wolfentropy.h>
|
||||
#endif
|
||||
#include <wolfssl/wolfcrypt/random.h>
|
||||
|
||||
struct wc_linuxkm_drbg_ctx {
|
||||
|
||||
@@ -62,6 +62,9 @@
|
||||
#if defined(WC_NO_RNG)
|
||||
#include <wolfssl/wolfcrypt/integer.h>
|
||||
#else
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
#include <wolfssl/wolfcrypt/wolfentropy.h>
|
||||
#endif
|
||||
#include <wolfssl/wolfcrypt/random.h>
|
||||
#endif
|
||||
#include <wolfssl/wolfcrypt/coding.h>
|
||||
|
||||
@@ -41,6 +41,9 @@
|
||||
#if !defined(NO_CRYPT_TEST) || defined(LINUXKM_LKCAPI_REGISTER)
|
||||
#include <wolfcrypt/test/test.h>
|
||||
#endif
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
#include <wolfssl/wolfcrypt/wolfentropy.h>
|
||||
#endif
|
||||
#include <wolfssl/wolfcrypt/random.h>
|
||||
#include <wolfssl/wolfcrypt/sha256.h>
|
||||
#ifdef NO_INLINE
|
||||
|
||||
@@ -181,6 +181,10 @@ src_libwolfssl@LIBSUFFIX@_la_SOURCES += \
|
||||
wolfcrypt/src/hmac.c \
|
||||
wolfcrypt/src/random.c
|
||||
|
||||
if BUILD_MEMUSE
|
||||
src_libwolfssl@LIBSUFFIX@_la_SOURCES += wolfcrypt/src/wolfentropy.c
|
||||
endif
|
||||
|
||||
src_libwolfssl@LIBSUFFIX@_la_SOURCES += wolfcrypt/src/kdf.c
|
||||
|
||||
if BUILD_RSA
|
||||
@@ -422,6 +426,10 @@ src_libwolfssl@LIBSUFFIX@_la_SOURCES += \
|
||||
wolfcrypt/src/hmac.c \
|
||||
wolfcrypt/src/random.c
|
||||
|
||||
if BUILD_MEMUSE
|
||||
src_libwolfssl@LIBSUFFIX@_la_SOURCES += wolfcrypt/src/wolfentropy.c
|
||||
endif
|
||||
|
||||
src_libwolfssl@LIBSUFFIX@_la_SOURCES += wolfcrypt/src/kdf.c
|
||||
|
||||
if BUILD_RSA
|
||||
@@ -770,6 +778,9 @@ endif !BUILD_FIPS_V5
|
||||
if !BUILD_FIPS_V2_PLUS
|
||||
if BUILD_RNG
|
||||
src_libwolfssl@LIBSUFFIX@_la_SOURCES += wolfcrypt/src/random.c
|
||||
if BUILD_MEMUSE
|
||||
src_libwolfssl@LIBSUFFIX@_la_SOURCES += wolfcrypt/src/wolfentropy.c
|
||||
endif
|
||||
endif
|
||||
endif !BUILD_FIPS_V2_PLUS
|
||||
|
||||
|
||||
@@ -7459,8 +7459,35 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c,
|
||||
#endif /* WOLFSSL_AESGCM_STREAM */
|
||||
|
||||
#ifdef WOLFSSL_ARMASM
|
||||
#define GCM_GMULT_LEN(gcm, x, a, len) \
|
||||
GCM_gmult_len(x, (const byte**)((gcm)->M0), a, len)
|
||||
static void GCM_gmult_len(byte* x, const byte* h, const unsigned char* a,
|
||||
unsigned long len)
|
||||
{
|
||||
byte Z[AES_BLOCK_SIZE];
|
||||
byte V[AES_BLOCK_SIZE];
|
||||
int i;
|
||||
int j;
|
||||
|
||||
while (len >= AES_BLOCK_SIZE) {
|
||||
xorbuf(x, a, AES_BLOCK_SIZE);
|
||||
XMEMSET(Z, 0, AES_BLOCK_SIZE);
|
||||
XMEMCPY(V, x, AES_BLOCK_SIZE);
|
||||
for (i = 0; i < AES_BLOCK_SIZE; i++) {
|
||||
byte y = h[i];
|
||||
for (j = 0; j < 8; j++) {
|
||||
if (y & 0x80) {
|
||||
xorbuf(Z, V, AES_BLOCK_SIZE);
|
||||
}
|
||||
RIGHTSHIFTX(V);
|
||||
y = y << 1;
|
||||
}
|
||||
}
|
||||
XMEMCPY(x, Z, AES_BLOCK_SIZE);
|
||||
len -= AES_BLOCK_SIZE;
|
||||
a += AES_BLOCK_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
#define GCM_GMULT_LEN(gcm, x, a, len) GCM_gmult_len(x, (gcm)->H, a, len)
|
||||
#endif
|
||||
|
||||
#elif defined(GCM_TABLE)
|
||||
|
||||
@@ -69,13 +69,6 @@ This library contains implementation for the random number generator.
|
||||
|
||||
#include <wolfssl/wolfcrypt/random.h>
|
||||
#include <wolfssl/wolfcrypt/cpuid.h>
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
#include <wolfssl/wolfcrypt/sha3.h>
|
||||
#if defined(__APPLE__) || defined(__MACH__)
|
||||
#include <mach/mach_time.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef WC_NO_RNG /* if not FIPS and RNG is disabled then do not compile */
|
||||
|
||||
@@ -240,18 +233,15 @@ This library contains implementation for the random number generator.
|
||||
#define RNG_SECURITY_STRENGTH (256)
|
||||
#endif
|
||||
|
||||
/* wolfentropy.h will define for HAVE_ENTROPY_MEMUSE */
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
#include <wolfssl/wolfcrypt/wolfentropy.h>
|
||||
#endif
|
||||
|
||||
#ifndef ENTROPY_SCALE_FACTOR
|
||||
/* The entropy scale factor should be the whole number inverse of the
|
||||
* minimum bits of entropy per bit of NDRNG output. */
|
||||
#if defined(HAVE_ENTROPY_MEMUSE)
|
||||
/* Full strength, conditioned entropy is requested of MemUse Entropy. */
|
||||
#if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
|
||||
(HAVE_FIPS_VERSION >= 2)
|
||||
#define ENTROPY_SCALE_FACTOR (4)
|
||||
#else
|
||||
#define ENTROPY_SCALE_FACTOR (1)
|
||||
#endif
|
||||
#elif defined(HAVE_AMD_RDSEED)
|
||||
#if defined(HAVE_AMD_RDSEED)
|
||||
/* This will yield a SEED_SZ of 16kb. Since nonceSz will be 0,
|
||||
* we'll add an additional 8kb on top.
|
||||
*
|
||||
@@ -281,7 +271,7 @@ This library contains implementation for the random number generator.
|
||||
/* Setting the default to 1. */
|
||||
#define ENTROPY_SCALE_FACTOR (1)
|
||||
#endif
|
||||
#endif
|
||||
#endif /* !ENTROPY_SCALE_FACTOR */
|
||||
|
||||
#ifndef SEED_BLOCK_SZ
|
||||
/* The seed block size, is the size of the output of the underlying NDRNG.
|
||||
@@ -787,869 +777,6 @@ int wc_RNG_TestSeed(const byte* seed, word32 seedSz)
|
||||
#endif /* HAVE_HASHDRBG */
|
||||
/* End NIST DRBG Code */
|
||||
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
/* Define ENTROPY_MEMUSE_THREAD to force use of counter in a new thread.
|
||||
* Only do this when high resolution timer not otherwise available.
|
||||
*/
|
||||
|
||||
/* Number of bytes that will hold the maximum entropy bits. */
|
||||
#define MAX_ENTROPY_BYTES (MAX_ENTROPY_BITS / 8)
|
||||
/* Number of bits stored for one sample. */
|
||||
#define ENTROPY_BITS_USED 8
|
||||
|
||||
/* Minimum entropy from a sample. */
|
||||
#define ENTROPY_MIN 1
|
||||
/* Number of extra samples to ensure full entropy. */
|
||||
#define ENTROPY_EXTRA 64
|
||||
/* Maximum number of bytes to sample to produce max entropy. */
|
||||
#define MAX_NOISE_CNT (MAX_ENTROPY_BITS * 8 + ENTROPY_EXTRA)
|
||||
|
||||
/* MemUse entropy global state initialized. */
|
||||
static int entropy_memuse_initialized = 0;
|
||||
/* Global SHA-3 object used for conditioning entropy and creating noise. */
|
||||
static wc_Sha3 entropyHash;
|
||||
/* Reset the health tests. */
|
||||
static void Entropy_HealthTest_Reset(void);
|
||||
|
||||
#ifdef CUSTOM_ENTROPY_TIMEHIRES
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
return CUSTOM_ENTROPY_TIMEHIRES();
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && \
|
||||
(defined(__x86_64__) || defined(__i386__))
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit count of CPU cycles.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
unsigned int lo_c, hi_c;
|
||||
__asm__ __volatile__ (
|
||||
"rdtsc"
|
||||
: "=a"(lo_c), "=d"(hi_c) /* out */
|
||||
: "a"(0) /* in */
|
||||
: "%ebx", "%ecx"); /* clobber */
|
||||
return ((word64)lo_c) | (((word64)hi_c) << 32);
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && \
|
||||
(defined(__APPLE__) || defined(__MACH__))
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit time in nanoseconds.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && defined(__aarch64__)
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit timer count.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
word64 cnt;
|
||||
__asm__ __volatile__ (
|
||||
"mrs %[cnt], cntvct_el0"
|
||||
: [cnt] "=r"(cnt)
|
||||
:
|
||||
:
|
||||
);
|
||||
return cnt;
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && defined(__MICROBLAZE__)
|
||||
|
||||
#define LPD_SCNTR_BASE_ADDRESS 0xFF250000
|
||||
|
||||
/* Get the high resolution time counter.
|
||||
* Collect ticks from LPD_SCNTR
|
||||
* @return 64-bit tick count.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
word64 cnt;
|
||||
word32 *ptr;
|
||||
|
||||
ptr = (word32*)LPD_SCNTR_BASE_ADDRESS;
|
||||
cnt = *(ptr+1);
|
||||
cnt = cnt << 32;
|
||||
cnt |= *ptr;
|
||||
|
||||
return cnt;
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && (_POSIX_C_SOURCE >= 199309L)
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit time that is the nanoseconds of current time.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
struct timespec now;
|
||||
|
||||
clock_gettime(CLOCK_REALTIME, &now);
|
||||
|
||||
return now.tv_nsec;
|
||||
}
|
||||
#elif defined(_WIN32) /* USE_WINDOWS_API */
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit timer
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
LARGE_INTEGER count;
|
||||
QueryPerformanceCounter(&count);
|
||||
return (word64)(count.QuadPart);
|
||||
}
|
||||
#elif defined(WOLFSSL_THREAD_NO_JOIN)
|
||||
|
||||
/* Start and stop thread that counts as a proxy for time counter. */
|
||||
#define ENTROPY_MEMUSE_THREADED
|
||||
|
||||
/* Data for entropy thread. */
|
||||
typedef struct ENTROPY_THREAD_DATA {
|
||||
/* Current counter - proxy for time. */
|
||||
word64 counter;
|
||||
/* Whether to stop thread. */
|
||||
int stop;
|
||||
} ENTROPY_THREAD_DATA;
|
||||
|
||||
/* Track whether entropy thread has been started already. */
|
||||
static int entropy_thread_started = 0;
|
||||
/* Data for thread to update/observer. */
|
||||
static volatile ENTROPY_THREAD_DATA entropy_thread_data = { 0, 0 };
|
||||
|
||||
/* Get the high resolution time counter. Counter incremented in thread.
|
||||
*
|
||||
* @return 64-bit counter.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
/* Return counter update in thread. */
|
||||
return entropy_thread_data.counter;
|
||||
}
|
||||
|
||||
/* Thread that increments counter while not told to stop.
|
||||
*
|
||||
* @param [in,out] args Entropy data including: counter and stop flag.
|
||||
* @return NULL always.
|
||||
*/
|
||||
static THREAD_RETURN_NOJOIN WOLFSSL_THREAD_NO_JOIN
|
||||
Entropy_IncCounter(void* args)
|
||||
{
|
||||
(void)args;
|
||||
|
||||
/* Keep going until caller tells us to stop and exit. */
|
||||
while (!entropy_thread_data.stop) {
|
||||
/* Increment counter acting as high resolution timer. */
|
||||
entropy_thread_data.counter++;
|
||||
}
|
||||
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "EXITING ENTROPY COUNTER THREAD\n");
|
||||
#endif
|
||||
|
||||
/* Exit from thread. */
|
||||
RETURN_FROM_THREAD_NOJOIN(0);
|
||||
}
|
||||
|
||||
/* Start a thread that increments counter if not one already.
|
||||
*
|
||||
* Won't start a new thread if one already running.
|
||||
* Waits for thread to start by waiting for counter to have incremented.
|
||||
*
|
||||
* @return 0 on success.
|
||||
* @return Negative on failure.
|
||||
*/
|
||||
static int Entropy_StartThread(void)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
/* Only continue if we haven't started a thread. */
|
||||
if (!entropy_thread_started) {
|
||||
/* Get counter before starting thread. */
|
||||
word64 start_counter = entropy_thread_data.counter;
|
||||
|
||||
/* In case of restarting thread, set stop indicator to false. */
|
||||
entropy_thread_data.stop = 0;
|
||||
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "STARTING ENTROPY COUNTER THREAD\n");
|
||||
#endif
|
||||
/* Create a thread that increments the counter in the data. */
|
||||
/* Thread resources to be disposed of. */
|
||||
ret = wolfSSL_NewThreadNoJoin(Entropy_IncCounter, NULL);
|
||||
if (ret == 0) {
|
||||
/* Wait for the counter to increase indicating thread started. */
|
||||
while (entropy_thread_data.counter == start_counter) {
|
||||
sched_yield();
|
||||
}
|
||||
}
|
||||
|
||||
entropy_thread_started = (ret == 0);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Tell thread to stop and wait for it to complete.
|
||||
*
|
||||
* Called by wolfCrypt_Cleanup().
|
||||
*/
|
||||
static void Entropy_StopThread(void)
|
||||
{
|
||||
/* Only stop a thread if one is running. */
|
||||
if (entropy_thread_started) {
|
||||
/* Tell thread to stop. */
|
||||
entropy_thread_data.stop = 1;
|
||||
/* Stopped thread so no thread started anymore. */
|
||||
entropy_thread_started = 0;
|
||||
}
|
||||
}
|
||||
/* end if defined(HAVE_PTHREAD) */
|
||||
|
||||
#else
|
||||
|
||||
#error "No high precision time available for MemUse Entropy."
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef ENTROPY_NUM_WORDS_BITS
|
||||
/* Number of bits to count of 64-bit words in state. */
|
||||
#define ENTROPY_NUM_WORDS_BITS 14
|
||||
#endif
|
||||
|
||||
/* Floor of 8 yields pool of 256x 64-bit word samples
|
||||
* 9 -> 512x 64-bit word samples
|
||||
* 10 -> 1,024x 64-bit word samples
|
||||
* 11 -> 2,048x 64-bit word samples
|
||||
* 12 -> 4,096x 64-bit word samples
|
||||
* 13 -> 8,192x 64-bit word samples
|
||||
* 14 -> 16,384x 64-bit word samples
|
||||
* 15 -> 32,768x 64-bit word samples
|
||||
* ... doubling every time up to a maximum of:
|
||||
* 30 -> 1,073,741,824x 64-bit word samples
|
||||
* 1 billion+ samples should be more then sufficient for any use-case
|
||||
*/
|
||||
#if ENTROPY_NUM_WORDS_BITS < 8
|
||||
#error "ENTROPY_NUM_WORDS_BITS must be 8 or more"
|
||||
#elif ENTROPY_NUM_WORDS_BITS > 30
|
||||
#error "ENTROPY_NUM_WORDS_BITS must be less than 31"
|
||||
#endif
|
||||
/* Number of 64-bit words in state. */
|
||||
#define ENTROPY_NUM_WORDS (1 << ENTROPY_NUM_WORDS_BITS)
|
||||
|
||||
/* Size of one block of 64-bit words. */
|
||||
#define ENTROPY_BLOCK_SZ (ENTROPY_NUM_WORDS_BITS - 8)
|
||||
|
||||
#ifndef ENTROPY_NUM_UPDATES
|
||||
/* Number of times to update random blocks.
|
||||
* Less than 2^ENTROPY_BLOCK_SZ (default: 2^6 = 64).
|
||||
* Maximize value to maximize entropy per sample.
|
||||
* Limit value to ensure entropy is collected in a timely manner.
|
||||
*/
|
||||
#define ENTROPY_NUM_UPDATES 18
|
||||
/* Upper round of log2(ENTROPY_NUM_UPDATES) */
|
||||
#define ENTROPY_NUM_UPDATES_BITS 5
|
||||
#elif !defined(ENTROPY_NUM_UPDATES_BITS)
|
||||
#define ENTROPY_NUM_UPDATES_BITS ENTROPY_BLOCK_SZ
|
||||
#endif
|
||||
#ifndef ENTROPY_NUM_UPDATES_BITS
|
||||
#error "ENTROPY_NUM_UPDATES_BITS must be defined - " \
|
||||
"upper(log2(ENTROPY_NUM_UPDATES))"
|
||||
#endif
|
||||
#if ENTROPY_NUM_UPDATES_BITS != 0
|
||||
/* Amount to shift offset to get better coverage of a block */
|
||||
#define ENTROPY_OFFSET_SHIFTING \
|
||||
(ENTROPY_BLOCK_SZ / ENTROPY_NUM_UPDATES_BITS)
|
||||
#else
|
||||
/* Amount to shift offset to get better coverage of a block */
|
||||
#define ENTROPY_OFFSET_SHIFTING ENTROPY_BLOCK_SZ
|
||||
#endif
|
||||
|
||||
#ifndef ENTROPY_NUM_64BIT_WORDS
|
||||
/* Number of 64-bit words to update - 32. */
|
||||
#define ENTROPY_NUM_64BIT_WORDS WC_SHA3_256_DIGEST_SIZE
|
||||
#elif ENTROPY_NUM_64BIT_WORDS > WC_SHA3_256_DIGEST_SIZE
|
||||
#error "ENTROPY_NUM_64BIT_WORDS must be <= SHA3-256 digest size in bytes"
|
||||
#endif
|
||||
|
||||
#if ENTROPY_BLOCK_SZ < ENTROPY_NUM_UPDATES_BITS
|
||||
#define EXTRA_ENTROPY_WORDS ENTROPY_NUM_UPDATES
|
||||
#else
|
||||
#define EXTRA_ENTROPY_WORDS 0
|
||||
#endif
|
||||
|
||||
/* State to update that is multiple cache lines long. */
|
||||
static word64 entropy_state[ENTROPY_NUM_WORDS + EXTRA_ENTROPY_WORDS] = {0};
|
||||
|
||||
/* Using memory will take different amount of times depending on the CPU's
|
||||
* caches and business.
|
||||
*/
|
||||
static void Entropy_MemUse(void)
|
||||
{
|
||||
int i;
|
||||
static byte d[WC_SHA3_256_DIGEST_SIZE];
|
||||
int j;
|
||||
|
||||
for (j = 0; j < ENTROPY_NUM_UPDATES; j++) {
|
||||
/* Hash the first 32 64-bit words of state. */
|
||||
wc_Sha3_256_Update(&entropyHash, (byte*)entropy_state,
|
||||
sizeof(*entropy_state) * ENTROPY_NUM_64BIT_WORDS);
|
||||
/* Get pseudo-random indices. */
|
||||
wc_Sha3_256_Final(&entropyHash, d);
|
||||
|
||||
for (i = 0; i < ENTROPY_NUM_64BIT_WORDS; i++) {
|
||||
/* Choose a 64-bit word from a pseudo-random block.*/
|
||||
int idx = ((int)d[i] << ENTROPY_BLOCK_SZ) +
|
||||
(j << ENTROPY_OFFSET_SHIFTING);
|
||||
/* Update a pseudo-random 64-bit word with a pseudo-random value. */
|
||||
entropy_state[idx] += Entropy_TimeHiRes();
|
||||
/* Ensure part of state that is hashed is updated. */
|
||||
entropy_state[i] += entropy_state[idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Last time entropy sample was gathered. */
|
||||
static word64 entropy_last_time = 0;
|
||||
|
||||
/* Get a sample of noise.
|
||||
*
|
||||
* Value is time taken to use memory.
|
||||
*
|
||||
* Called to test raw entropy.
|
||||
*
|
||||
* @return 64-bit value that is the noise.
|
||||
*/
|
||||
static word64 Entropy_GetSample(void)
|
||||
{
|
||||
word64 now;
|
||||
word64 ret;
|
||||
|
||||
#ifdef HAVE_FIPS
|
||||
/* First sample must be disregard when in FIPS. */
|
||||
if (entropy_last_time == 0) {
|
||||
/* Get sample which triggers CAST in FIPS mode. */
|
||||
Entropy_MemUse();
|
||||
/* Start entropy time after CASTs. */
|
||||
entropy_last_time = Entropy_TimeHiRes();
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Use memory such that it will take an unpredictable amount of time. */
|
||||
Entropy_MemUse();
|
||||
|
||||
/* Get the time now to subtract from previous end time. */
|
||||
now = Entropy_TimeHiRes();
|
||||
/* Calculate time diff since last sampling. */
|
||||
ret = now - entropy_last_time;
|
||||
/* Store last time. */
|
||||
entropy_last_time = now;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Get as many samples of noise as required.
|
||||
*
|
||||
* One sample is one byte.
|
||||
*
|
||||
* @param [out] noise Buffer to hold samples.
|
||||
* @param [in] samples Number of one byte samples to get.
|
||||
*/
|
||||
static void Entropy_GetNoise(unsigned char* noise, int samples)
|
||||
{
|
||||
int i;
|
||||
|
||||
/* Do it once to get things going. */
|
||||
Entropy_MemUse();
|
||||
|
||||
/* Get as many samples as required. */
|
||||
for (i = 0; i < samples; i++) {
|
||||
noise[i] = (byte)Entropy_GetSample();
|
||||
}
|
||||
}
|
||||
|
||||
/* Generate raw entropy for performing assessment.
|
||||
*
|
||||
* @param [out] raw Buffer to hold raw entropy data.
|
||||
* @param [in] cnt Number of bytes of raw entropy to get.
|
||||
* @return 0 on success.
|
||||
* @return Negative when creating a thread fails - when no high resolution
|
||||
* clock available.
|
||||
*/
|
||||
int wc_Entropy_GetRawEntropy(unsigned char* raw, int cnt)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Start the counter thread as a proxy for time counter. */
|
||||
ret = Entropy_StartThread();
|
||||
if (ret == 0)
|
||||
#endif
|
||||
{
|
||||
Entropy_GetNoise(raw, cnt);
|
||||
}
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Stop the counter thread to avoid thrashing the system. */
|
||||
Entropy_StopThread();
|
||||
#endif
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
#if ENTROPY_MIN == 1
|
||||
/* SP800-90b 4.4.1 - Repetition Test
|
||||
* C = 1 + upper(-log2(alpha) / H)
|
||||
* When alpha = 2^-30 and H = 1,
|
||||
* C = 1 + upper(30 / 1) = 31
|
||||
*/
|
||||
#define REP_CUTOFF 31
|
||||
#else
|
||||
#error "Minimum entropy not defined to a recognized value."
|
||||
#endif
|
||||
|
||||
/* Have valid previous sample for repetition test. */
|
||||
static int rep_have_prev = 0;
|
||||
/* Previous sample value. */
|
||||
static byte rep_prev_noise;
|
||||
|
||||
static void Entropy_HealthTest_Repetition_Reset(void)
|
||||
{
|
||||
/* No previous stored. */
|
||||
rep_have_prev = 0;
|
||||
/* Clear previous. */
|
||||
rep_prev_noise = 0;
|
||||
}
|
||||
|
||||
/* Test sample value with repetition test.
|
||||
*
|
||||
* @param [in] noise Sample to test.
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_RT_E on failure.
|
||||
*/
|
||||
static int Entropy_HealthTest_Repetition(byte noise)
|
||||
{
|
||||
int ret = 0;
|
||||
/* Number of times previous value has been seen continuously. */
|
||||
static int rep_cnt = 0;
|
||||
|
||||
/* If we don't have a previous then store this one for next time. */
|
||||
if (!rep_have_prev) {
|
||||
rep_prev_noise = noise;
|
||||
rep_have_prev = 1;
|
||||
rep_cnt = 1;
|
||||
}
|
||||
/* Check whether this sample matches last. */
|
||||
else if (noise == rep_prev_noise) {
|
||||
/* Update count of repetitions. */
|
||||
rep_cnt++;
|
||||
/* Fail if we reach cutoff. */
|
||||
if (rep_cnt >= REP_CUTOFF) {
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "REPETITION FAILED: %d\n", noise);
|
||||
#endif
|
||||
Entropy_HealthTest_Repetition_Reset();
|
||||
ret = ENTROPY_RT_E;
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Cache new previous and seen one so far. */
|
||||
rep_prev_noise = noise;
|
||||
rep_cnt = 1;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* SP800-90b 4.4.2 - Adaptive Proportion Test
|
||||
* Para 2
|
||||
* ... The window size W is selected based on the alphabet size ... 512 if
|
||||
* the noise source is not binary ...
|
||||
*/
|
||||
#define PROP_WINDOW_SIZE 512
|
||||
#if ENTROPY_MIN == 1
|
||||
/* SP800-90b 4.4.2 - Adaptive Proportion Test
|
||||
* Note 10
|
||||
* C = 1 + CRITBINOM(W, power(2,( -H)),1-alpha)
|
||||
* alpha = 2^-30 = POWER(2,-30), H = 1, W = 512
|
||||
* C = 1 + CRITBINOM(512, 0.5, 1-POWER(2,-30)) = 1 + 324 = 325
|
||||
*/
|
||||
#define PROP_CUTOFF 325
|
||||
#else
|
||||
#error "Minimum entropy not defined to a recognized value."
|
||||
#endif
|
||||
|
||||
/* Total number of samples storef for Adaptive proportion test.
|
||||
* Need the next 512 samples to compare this this one.
|
||||
*/
|
||||
static word16 prop_total = 0;
|
||||
/* Index of first sample. */
|
||||
static word16 prop_first = 0;
|
||||
/* Index to put next sample in. */
|
||||
static word16 prop_last = 0;
|
||||
/* Count of each value seen in queue. */
|
||||
static word16 prop_cnt[1 << ENTROPY_BITS_USED] = { 0 };
|
||||
/* Circular queue of samples. */
|
||||
static word16 prop_samples[PROP_WINDOW_SIZE];
|
||||
|
||||
/* Resets the data for the Adaptive Proportion Test.
|
||||
*/
|
||||
static void Entropy_HealthTest_Proportion_Reset(void)
|
||||
{
|
||||
/* Clear out samples. */
|
||||
XMEMSET(prop_samples, 0, sizeof(prop_samples));
|
||||
/* Clear out counts. */
|
||||
XMEMSET(prop_cnt, 0, sizeof(prop_cnt));
|
||||
/* Clear stored count. */
|
||||
prop_total = 0;
|
||||
/* Reset first and last index for samples. */
|
||||
prop_first = 0;
|
||||
prop_last = 0;
|
||||
}
|
||||
|
||||
/* Add sample to Adaptive Proportion test.
|
||||
*
|
||||
* SP800-90b 4.4.2 - Adaptive Proportion Test
|
||||
*
|
||||
* Sample is accumulated into buffer until required successive values seen.
|
||||
*
|
||||
* @param [in] noise Sample to test.
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_APT_E on failure.
|
||||
*/
|
||||
static int Entropy_HealthTest_Proportion(byte noise)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
/* Need minimum samples in queue to test with - keep adding while we have
|
||||
* less. */
|
||||
if (prop_total < PROP_CUTOFF - 1) {
|
||||
/* Store sample at last position in circular queue. */
|
||||
prop_samples[prop_last++] = noise;
|
||||
/* Update count of seen value based on new sample. */
|
||||
prop_cnt[noise]++;
|
||||
/* Update count of store values. */
|
||||
prop_total++;
|
||||
}
|
||||
else {
|
||||
/* We have at least a minimum set of samples in queue. */
|
||||
/* Store new sample at end of queue. */
|
||||
prop_samples[prop_last] = noise;
|
||||
/* Update last index now that we have added new sample to queue. */
|
||||
prop_last = (prop_last + 1) % PROP_WINDOW_SIZE;
|
||||
/* Added sample to queue - add count. */
|
||||
prop_cnt[noise]++;
|
||||
/* Update count of store values. */
|
||||
prop_total++;
|
||||
|
||||
/* Check whether first value has too many repetitions in queue. */
|
||||
if (prop_cnt[noise] >= PROP_CUTOFF) {
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "PROPORTION FAILED: %d %d\n", val, prop_cnt[noise]);
|
||||
#endif
|
||||
Entropy_HealthTest_Proportion_Reset();
|
||||
/* Error code returned. */
|
||||
ret = ENTROPY_APT_E;
|
||||
}
|
||||
else if (prop_total == PROP_WINDOW_SIZE) {
|
||||
/* Return to 511 samples in queue. */
|
||||
/* Get first value in queue - value to test. */
|
||||
byte val = (byte)prop_samples[prop_first];
|
||||
/* Update first index to remove first sample from the queue. */
|
||||
prop_first = (prop_first + 1) % PROP_WINDOW_SIZE;
|
||||
/* Removed first sample from queue - remove count. */
|
||||
prop_cnt[val]--;
|
||||
/* Update count of store values. */
|
||||
prop_total--;
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* SP800-90b 4.3 - Requirements for Health Tests
|
||||
* 1.4: The entropy source's startup tests shall run the continuous health
|
||||
* tests over at least 1024 consecutive samples.
|
||||
*
|
||||
* Adaptive Proportion Test requires a number of samples to compared too.
|
||||
*/
|
||||
#define ENTROPY_INITIAL_COUNT (1024 + PROP_WINDOW_SIZE)
|
||||
|
||||
/* Perform startup health testing.
|
||||
*
|
||||
* Fill adaptive proportion test buffer and then do 1024 samples.
|
||||
* Perform repetition test on all samples expect last.
|
||||
*
|
||||
* Discards samples from health tests on failure.
|
||||
*
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
|
||||
*/
|
||||
static int Entropy_HealthTest_Startup(void)
|
||||
{
|
||||
int ret = 0;
|
||||
byte initial[ENTROPY_INITIAL_COUNT];
|
||||
int i;
|
||||
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "STARTUP HEALTH TEST\n");
|
||||
#endif
|
||||
|
||||
/* Reset cached values before testing. */
|
||||
Entropy_HealthTest_Reset();
|
||||
|
||||
/* Fill initial sample buffer with noise. */
|
||||
Entropy_GetNoise(initial, ENTROPY_INITIAL_COUNT);
|
||||
/* Health check initial noise. */
|
||||
for (i = 0; (ret == 0) && (i < ENTROPY_INITIAL_COUNT); i++) {
|
||||
ret = Entropy_HealthTest_Repetition(initial[i]);
|
||||
if (ret == 0) {
|
||||
ret = Entropy_HealthTest_Proportion(initial[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (ret != 0) {
|
||||
/* Failing test only resets its own data. */
|
||||
Entropy_HealthTest_Reset();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Condition raw entropy noise using SHA-3-256.
|
||||
*
|
||||
* Put noise into a hash function: SHA-3-256.
|
||||
* Add the current time counter to help with uniqueness.
|
||||
*
|
||||
* @param [out] output Buffer to conditioned data.
|
||||
* @param [in] len Number of bytes to put into output buffer.
|
||||
* @param [in] noise Buffer with raw noise data.
|
||||
* @param [in] noise_len Length of noise data in bytes.
|
||||
* @return 0 on success.
|
||||
* @return Negative on failure.
|
||||
*/
|
||||
static int Entropy_Condition(byte* output, word32 len, byte* noise,
|
||||
word32 noise_len)
|
||||
{
|
||||
int ret;
|
||||
|
||||
/* Add noise to initialized hash. */
|
||||
ret = wc_Sha3_256_Update(&entropyHash, noise, noise_len);
|
||||
if (ret == 0) {
|
||||
word64 now = Entropy_TimeHiRes();
|
||||
/* Add time now counter. */
|
||||
ret = wc_Sha3_256_Update(&entropyHash, (byte*)&now, sizeof(now));
|
||||
}
|
||||
if (ret == 0) {
|
||||
/* Finalize into output buffer. */
|
||||
if (len == WC_SHA3_256_DIGEST_SIZE) {
|
||||
ret = wc_Sha3_256_Final(&entropyHash, output);
|
||||
}
|
||||
else {
|
||||
byte hash[WC_SHA3_256_DIGEST_SIZE];
|
||||
|
||||
ret = wc_Sha3_256_Final(&entropyHash, hash);
|
||||
if (ret == 0) {
|
||||
XMEMCPY(output, hash, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Mutex to prevent multiple callers requesting entropy operations at the
|
||||
* same time.
|
||||
*/
|
||||
static wolfSSL_Mutex entropy_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(entropy_mutex);
|
||||
|
||||
/* Get entropy of specified strength.
|
||||
*
|
||||
* SP800-90b 2.3.1 - GetEntropy: An Interface to the Entropy Source
|
||||
*
|
||||
* In threaded environment, only one thread at a time can get entropy.
|
||||
*
|
||||
* @param [in] bits Number of entropy bits. 256 is max value.
|
||||
* @param [out] entropy Buffer to hold entropy.
|
||||
* @param [in] len Length of data to put into buffer in bytes.
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
|
||||
* @return BAD_MUTEX_E when unable to lock mutex.
|
||||
*/
|
||||
int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len)
|
||||
{
|
||||
int ret = 0;
|
||||
WC_DECLARE_VAR(noise, byte, MAX_NOISE_CNT, 0);
|
||||
/* Noise length is the number of 8 byte samples required to get the bits of
|
||||
* entropy requested. */
|
||||
int noise_len = (bits + ENTROPY_EXTRA) / ENTROPY_MIN;
|
||||
|
||||
WC_ALLOC_VAR_EX(noise, byte, MAX_NOISE_CNT, NULL, DYNAMIC_TYPE_TMP_BUFFER,
|
||||
return MEMORY_E);
|
||||
|
||||
/* Lock the mutex as collection uses globals. */
|
||||
if ((ret == 0) && (wc_LockMutex(&entropy_mutex) != 0)) {
|
||||
ret = BAD_MUTEX_E;
|
||||
}
|
||||
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
if (ret == 0) {
|
||||
/* Start the counter thread as a proxy for time counter. */
|
||||
ret = Entropy_StartThread();
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Check we have had a startup health check pass. */
|
||||
if ((ret == 0) && ((prop_total == 0) || (!rep_have_prev))) {
|
||||
/* Try again as check failed. */
|
||||
ret = Entropy_HealthTest_Startup();
|
||||
}
|
||||
|
||||
/* Keep putting data into buffer until full. */
|
||||
while ((ret == 0) && (len > 0)) {
|
||||
int i;
|
||||
word32 entropy_len = WC_SHA3_256_DIGEST_SIZE;
|
||||
|
||||
/* Output 32 bytes at a time unless buffer has fewer bytes remaining. */
|
||||
if (len < entropy_len) {
|
||||
entropy_len = len;
|
||||
}
|
||||
|
||||
/* Get raw entropy noise. */
|
||||
Entropy_GetNoise(noise, noise_len);
|
||||
/* Health check each noise value. */
|
||||
for (i = 0; (ret == 0) && (i < noise_len); i++) {
|
||||
ret = Entropy_HealthTest_Repetition(noise[i]);
|
||||
if (ret == 0) {
|
||||
ret = Entropy_HealthTest_Proportion(noise[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (ret == 0) {
|
||||
/* Condition noise value down to 32-bytes or less. */
|
||||
ret = Entropy_Condition(entropy, entropy_len, noise, noise_len);
|
||||
}
|
||||
if (ret == 0) {
|
||||
/* Update buffer pointer and count of bytes left to generate. */
|
||||
entropy += entropy_len;
|
||||
len -= entropy_len;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Stop the counter thread to avoid thrashing the system. */
|
||||
Entropy_StopThread();
|
||||
#endif
|
||||
|
||||
if (ret != WC_NO_ERR_TRACE(BAD_MUTEX_E)) {
|
||||
/* Unlock mutex now we are done. */
|
||||
wc_UnLockMutex(&entropy_mutex);
|
||||
}
|
||||
|
||||
WC_FREE_VAR_EX(noise, NULL, DYNAMIC_TYPE_TMP_BUFFER);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Performs on-demand testing.
|
||||
*
|
||||
* In threaded environment, locks out other threads from getting entropy.
|
||||
*
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
|
||||
* @return BAD_MUTEX_E when unable to lock mutex.
|
||||
*/
|
||||
int wc_Entropy_OnDemandTest(void)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
/* Lock the mutex as we don't want collecting to happen during testing. */
|
||||
if (wc_LockMutex(&entropy_mutex) != 0) {
|
||||
ret = BAD_MUTEX_E;
|
||||
}
|
||||
|
||||
if (ret == 0) {
|
||||
/* Perform startup tests. */
|
||||
ret = Entropy_HealthTest_Startup();
|
||||
}
|
||||
|
||||
if (ret != WC_NO_ERR_TRACE(BAD_MUTEX_E)) {
|
||||
/* Unlock mutex now we are done. */
|
||||
wc_UnLockMutex(&entropy_mutex);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Initialize global state for MemUse Entropy and do startup health test.
|
||||
*
|
||||
* @return 0 on success.
|
||||
* @return Negative on failure.
|
||||
*/
|
||||
int Entropy_Init(void)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
/* Check whether initialization has succeeded before. */
|
||||
if (!entropy_memuse_initialized) {
|
||||
#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_MUTEX_INITIALIZER)
|
||||
ret = wc_InitMutex(&entropy_mutex);
|
||||
#endif
|
||||
if (ret == 0) {
|
||||
/* Initialize a SHA3-256 object for use in entropy operations. */
|
||||
ret = wc_InitSha3_256(&entropyHash, NULL, INVALID_DEVID);
|
||||
}
|
||||
/* Set globals initialized. */
|
||||
entropy_memuse_initialized = (ret == 0);
|
||||
if (ret == 0) {
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Start the counter thread as a proxy for time counter. */
|
||||
ret = Entropy_StartThread();
|
||||
if (ret == 0)
|
||||
#endif
|
||||
{
|
||||
/* Do first startup test now. */
|
||||
ret = Entropy_HealthTest_Startup();
|
||||
}
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Stop the counter thread to avoid thrashing the system. */
|
||||
Entropy_StopThread();
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Finalize the data associated with the MemUse Entropy source.
|
||||
*/
|
||||
void Entropy_Final(void)
|
||||
{
|
||||
/* Only finalize when initialized. */
|
||||
if (entropy_memuse_initialized) {
|
||||
/* Dispose of the SHA3-356 hash object. */
|
||||
wc_Sha3_256_Free(&entropyHash);
|
||||
#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_MUTEX_INITIALIZER)
|
||||
wc_FreeMutex(&entropy_mutex);
|
||||
#endif
|
||||
/* Clear health test data. */
|
||||
Entropy_HealthTest_Reset();
|
||||
/* No longer initialized. */
|
||||
entropy_memuse_initialized = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Reset the data associated with the MemUse Entropy health tests.
|
||||
*/
|
||||
static void Entropy_HealthTest_Reset(void)
|
||||
{
|
||||
Entropy_HealthTest_Repetition_Reset();
|
||||
Entropy_HealthTest_Proportion_Reset();
|
||||
}
|
||||
|
||||
#endif /* HAVE_ENTROPY_MEMUSE */
|
||||
|
||||
static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz,
|
||||
void* heap, int devId)
|
||||
|
||||
@@ -1728,7 +1728,7 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data,
|
||||
2 * sizeof(word32));
|
||||
}
|
||||
#endif
|
||||
#if defined(WOLFSSL_ARMASM)
|
||||
#if defined(WOLFSSL_ARMASM) && !defined(FREESCALE_MMCAU_SHA)
|
||||
ByteReverseWords( &sha256->buffer[WC_SHA256_PAD_SIZE / sizeof(word32)],
|
||||
&sha256->buffer[WC_SHA256_PAD_SIZE / sizeof(word32)],
|
||||
2 * sizeof(word32));
|
||||
|
||||
@@ -92181,58 +92181,7 @@ WC_OMIT_FRAME_POINTER static void sp_384_mont_tpl_12(sp_digit* r,
|
||||
);
|
||||
}
|
||||
|
||||
#ifdef WOLFSSL_SP_SMALL
|
||||
/* Sub b from a into r. (r = a - b)
|
||||
*
|
||||
* r A single precision integer.
|
||||
* a A single precision integer.
|
||||
* b A single precision integer.
|
||||
*/
|
||||
#ifndef WOLFSSL_NO_VAR_ASSIGN_REG
|
||||
WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r_p,
|
||||
const sp_digit* a_p, const sp_digit* b_p)
|
||||
#else
|
||||
WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r,
|
||||
const sp_digit* a, const sp_digit* b)
|
||||
#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */
|
||||
{
|
||||
#ifndef WOLFSSL_NO_VAR_ASSIGN_REG
|
||||
register sp_digit* r asm ("r0") = (sp_digit*)r_p;
|
||||
register const sp_digit* a asm ("r1") = (const sp_digit*)a_p;
|
||||
register const sp_digit* b asm ("r2") = (const sp_digit*)b_p;
|
||||
#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */
|
||||
|
||||
__asm__ __volatile__ (
|
||||
"mov r12, #0\n\t"
|
||||
"add lr, %[a], #48\n\t"
|
||||
"\n"
|
||||
"L_sp_384_sub_12_word_%=: \n\t"
|
||||
"rsbs r12, r12, #0\n\t"
|
||||
"ldm %[a]!, {r3, r4, r5, r6}\n\t"
|
||||
"ldm %[b]!, {r7, r8, r9, r10}\n\t"
|
||||
"sbcs r3, r3, r7\n\t"
|
||||
"sbcs r4, r4, r8\n\t"
|
||||
"sbcs r5, r5, r9\n\t"
|
||||
"sbcs r6, r6, r10\n\t"
|
||||
"stm %[r]!, {r3, r4, r5, r6}\n\t"
|
||||
"sbc r12, r3, r3\n\t"
|
||||
"cmp %[a], lr\n\t"
|
||||
"bne L_sp_384_sub_12_word_%=\n\t"
|
||||
"mov %[r], r12\n\t"
|
||||
#ifndef WOLFSSL_NO_VAR_ASSIGN_REG
|
||||
: [r] "+r" (r), [a] "+r" (a), [b] "+r" (b)
|
||||
:
|
||||
#else
|
||||
:
|
||||
: [r] "r" (r), [a] "r" (a), [b] "r" (b)
|
||||
#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */
|
||||
: "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10",
|
||||
"r12", "lr"
|
||||
);
|
||||
return (word32)(size_t)r;
|
||||
}
|
||||
|
||||
#else
|
||||
#ifndef WOLFSSL_SP_SMALL
|
||||
/* Sub b from a into r. (r = a - b)
|
||||
*
|
||||
* r A single precision integer.
|
||||
@@ -92288,7 +92237,7 @@ WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r,
|
||||
return (word32)(size_t)r;
|
||||
}
|
||||
|
||||
#endif /* WOLFSSL_SP_SMALL */
|
||||
#endif /* !WOLFSSL_SP_SMALL */
|
||||
#ifdef WOLFSSL_SP_SMALL
|
||||
/* Conditionally add a and b using the mask m.
|
||||
* m is -1 to add and 0 when not.
|
||||
|
||||
@@ -45506,63 +45506,7 @@ WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r,
|
||||
);
|
||||
}
|
||||
|
||||
#ifdef WOLFSSL_SP_SMALL
|
||||
/* Sub b from a into r. (r = a - b)
|
||||
*
|
||||
* r A single precision integer.
|
||||
* a A single precision integer.
|
||||
* b A single precision integer.
|
||||
*/
|
||||
#ifndef WOLFSSL_NO_VAR_ASSIGN_REG
|
||||
WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r_p,
|
||||
const sp_digit* a_p, const sp_digit* b_p)
|
||||
#else
|
||||
WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r,
|
||||
const sp_digit* a, const sp_digit* b)
|
||||
#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */
|
||||
{
|
||||
#ifndef WOLFSSL_NO_VAR_ASSIGN_REG
|
||||
register sp_digit* r __asm__ ("r0") = (sp_digit*)r_p;
|
||||
register const sp_digit* a __asm__ ("r1") = (const sp_digit*)a_p;
|
||||
register const sp_digit* b __asm__ ("r2") = (const sp_digit*)b_p;
|
||||
#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */
|
||||
|
||||
__asm__ __volatile__ (
|
||||
"MOV r11, #0x0\n\t"
|
||||
"ADD r12, %[a], #0x30\n\t"
|
||||
"\n"
|
||||
#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000)
|
||||
"L_sp_384_sub_12_word:\n\t"
|
||||
#else
|
||||
"L_sp_384_sub_12_word_%=:\n\t"
|
||||
#endif
|
||||
"RSBS r11, r11, #0x0\n\t"
|
||||
"LDM %[a]!, {r3, r4, r5, r6}\n\t"
|
||||
"LDM %[b]!, {r7, r8, r9, r10}\n\t"
|
||||
"SBCS r3, r3, r7\n\t"
|
||||
"SBCS r4, r4, r8\n\t"
|
||||
"SBCS r5, r5, r9\n\t"
|
||||
"SBCS r6, r6, r10\n\t"
|
||||
"STM %[r]!, {r3, r4, r5, r6}\n\t"
|
||||
"SBC r11, r3, r3\n\t"
|
||||
"CMP %[a], r12\n\t"
|
||||
#if defined(__GNUC__)
|
||||
"BNE L_sp_384_sub_12_word_%=\n\t"
|
||||
#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000)
|
||||
"BNE.N L_sp_384_sub_12_word\n\t"
|
||||
#else
|
||||
"BNE.N L_sp_384_sub_12_word_%=\n\t"
|
||||
#endif
|
||||
"MOV %[r], r11\n\t"
|
||||
: [r] "+r" (r), [a] "+r" (a), [b] "+r" (b)
|
||||
:
|
||||
: "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10",
|
||||
"r11", "r12"
|
||||
);
|
||||
return (word32)(size_t)r;
|
||||
}
|
||||
|
||||
#else
|
||||
#ifndef WOLFSSL_SP_SMALL
|
||||
/* Sub b from a into r. (r = a - b)
|
||||
*
|
||||
* r A single precision integer.
|
||||
@@ -45613,7 +45557,7 @@ WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r,
|
||||
return (word32)(size_t)r;
|
||||
}
|
||||
|
||||
#endif /* WOLFSSL_SP_SMALL */
|
||||
#endif /* !WOLFSSL_SP_SMALL */
|
||||
#ifdef WOLFSSL_SP_SMALL
|
||||
/* Conditionally add a and b using the mask m.
|
||||
* m is -1 to add and 0 when not.
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
#include <wolfssl/wolfcrypt/cpuid.h>
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
#include <wolfssl/wolfcrypt/random.h>
|
||||
#include <wolfssl/wolfcrypt/wolfentropy.h>
|
||||
#endif
|
||||
#ifdef HAVE_ECC
|
||||
#include <wolfssl/wolfcrypt/ecc.h>
|
||||
|
||||
906
wolfcrypt/src/wolfentropy.c
Normal file
906
wolfcrypt/src/wolfentropy.c
Normal file
@@ -0,0 +1,906 @@
|
||||
/* wolfentropy.c
|
||||
*
|
||||
* Copyright (C) 2006-2025 wolfSSL Inc.
|
||||
*
|
||||
* This file is part of wolfSSL.
|
||||
*
|
||||
* wolfSSL is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* wolfSSL is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
DESCRIPTION
|
||||
This library contains implementation for the raw entropy source generator (TRNG)
|
||||
Not to be confused for the DRBG implemented in random.c, this raw entropy is
|
||||
designed to SEED a DRBG, not to be consumed directly for use cases requiring
|
||||
random data. Use the DRBG outputs for consuming applications requesting random
|
||||
data, use this implementation to seed and re-seed the DRBG.
|
||||
|
||||
*/
|
||||
|
||||
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
|
||||
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
|
||||
#include <wolfssl/wolfcrypt/wolfentropy.h>
|
||||
|
||||
#include <wolfssl/wolfcrypt/sha3.h>
|
||||
#if defined(__APPLE__) || defined(__MACH__)
|
||||
#include <mach/mach_time.h>
|
||||
#endif
|
||||
|
||||
/* Define ENTROPY_MEMUSE_THREAD to force use of counter in a new thread.
|
||||
* Only do this when high resolution timer not otherwise available.
|
||||
*/
|
||||
|
||||
/* Number of bytes that will hold the maximum entropy bits. */
|
||||
#define MAX_ENTROPY_BYTES (MAX_ENTROPY_BITS / 8)
|
||||
/* Number of bits stored for one sample. */
|
||||
#define ENTROPY_BITS_USED 8
|
||||
|
||||
/* Minimum entropy from a sample. */
|
||||
#define ENTROPY_MIN 1
|
||||
/* Number of extra samples to ensure full entropy. */
|
||||
#define ENTROPY_EXTRA 64
|
||||
/* Maximum number of bytes to sample to produce max entropy. */
|
||||
#define MAX_NOISE_CNT (MAX_ENTROPY_BITS * 8 + ENTROPY_EXTRA)
|
||||
|
||||
/* MemUse entropy global state initialized. */
|
||||
static int entropy_memuse_initialized = 0;
|
||||
/* Global SHA-3 object used for conditioning entropy and creating noise. */
|
||||
static wc_Sha3 entropyHash;
|
||||
/* Reset the health tests. */
|
||||
static void Entropy_HealthTest_Reset(void);
|
||||
|
||||
#ifdef CUSTOM_ENTROPY_TIMEHIRES
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
return CUSTOM_ENTROPY_TIMEHIRES();
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && \
|
||||
(defined(__x86_64__) || defined(__i386__))
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit count of CPU cycles.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
unsigned int lo_c, hi_c;
|
||||
__asm__ __volatile__ (
|
||||
"rdtsc"
|
||||
: "=a"(lo_c), "=d"(hi_c) /* out */
|
||||
: "a"(0) /* in */
|
||||
: "%ebx", "%ecx"); /* clobber */
|
||||
return ((word64)lo_c) | (((word64)hi_c) << 32);
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && \
|
||||
(defined(__APPLE__) || defined(__MACH__))
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit time in nanoseconds.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && defined(__aarch64__)
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit timer count.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
word64 cnt;
|
||||
__asm__ __volatile__ (
|
||||
"mrs %[cnt], cntvct_el0"
|
||||
: [cnt] "=r"(cnt)
|
||||
:
|
||||
:
|
||||
);
|
||||
return cnt;
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && defined(__MICROBLAZE__)
|
||||
|
||||
#define LPD_SCNTR_BASE_ADDRESS 0xFF250000
|
||||
|
||||
/* Get the high resolution time counter.
|
||||
* Collect ticks from LPD_SCNTR
|
||||
* @return 64-bit tick count.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
word64 cnt;
|
||||
word32 *ptr;
|
||||
|
||||
ptr = (word32*)LPD_SCNTR_BASE_ADDRESS;
|
||||
cnt = *(ptr+1);
|
||||
cnt = cnt << 32;
|
||||
cnt |= *ptr;
|
||||
|
||||
return cnt;
|
||||
}
|
||||
#elif !defined(ENTROPY_MEMUSE_THREAD) && (_POSIX_C_SOURCE >= 199309L)
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit time that is the nanoseconds of current time.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
struct timespec now;
|
||||
|
||||
clock_gettime(CLOCK_REALTIME, &now);
|
||||
|
||||
return now.tv_nsec;
|
||||
}
|
||||
#elif defined(_WIN32) /* USE_WINDOWS_API */
|
||||
/* Get the high resolution time counter.
|
||||
*
|
||||
* @return 64-bit timer
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
LARGE_INTEGER count;
|
||||
QueryPerformanceCounter(&count);
|
||||
return (word64)(count.QuadPart);
|
||||
}
|
||||
#elif defined(WOLFSSL_THREAD_NO_JOIN)
|
||||
|
||||
/* Start and stop thread that counts as a proxy for time counter. */
|
||||
#define ENTROPY_MEMUSE_THREADED
|
||||
|
||||
/* Data for entropy thread. */
|
||||
typedef struct ENTROPY_THREAD_DATA {
|
||||
/* Current counter - proxy for time. */
|
||||
word64 counter;
|
||||
/* Whether to stop thread. */
|
||||
int stop;
|
||||
} ENTROPY_THREAD_DATA;
|
||||
|
||||
/* Track whether entropy thread has been started already. */
|
||||
static int entropy_thread_started = 0;
|
||||
/* Data for thread to update/observer. */
|
||||
static volatile ENTROPY_THREAD_DATA entropy_thread_data = { 0, 0 };
|
||||
|
||||
/* Get the high resolution time counter. Counter incremented in thread.
|
||||
*
|
||||
* @return 64-bit counter.
|
||||
*/
|
||||
static WC_INLINE word64 Entropy_TimeHiRes(void)
|
||||
{
|
||||
/* Return counter update in thread. */
|
||||
return entropy_thread_data.counter;
|
||||
}
|
||||
|
||||
/* Thread that increments counter while not told to stop.
|
||||
*
|
||||
* @param [in,out] args Entropy data including: counter and stop flag.
|
||||
* @return NULL always.
|
||||
*/
|
||||
static THREAD_RETURN_NOJOIN WOLFSSL_THREAD_NO_JOIN
|
||||
Entropy_IncCounter(void* args)
|
||||
{
|
||||
(void)args;
|
||||
|
||||
/* Keep going until caller tells us to stop and exit. */
|
||||
while (!entropy_thread_data.stop) {
|
||||
/* Increment counter acting as high resolution timer. */
|
||||
entropy_thread_data.counter++;
|
||||
}
|
||||
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "EXITING ENTROPY COUNTER THREAD\n");
|
||||
#endif
|
||||
|
||||
/* Exit from thread. */
|
||||
RETURN_FROM_THREAD_NOJOIN(0);
|
||||
}
|
||||
|
||||
/* Start a thread that increments counter if not one already.
|
||||
*
|
||||
* Won't start a new thread if one already running.
|
||||
* Waits for thread to start by waiting for counter to have incremented.
|
||||
*
|
||||
* @return 0 on success.
|
||||
* @return Negative on failure.
|
||||
*/
|
||||
static int Entropy_StartThread(void)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
/* Only continue if we haven't started a thread. */
|
||||
if (!entropy_thread_started) {
|
||||
/* Get counter before starting thread. */
|
||||
word64 start_counter = entropy_thread_data.counter;
|
||||
|
||||
/* In case of restarting thread, set stop indicator to false. */
|
||||
entropy_thread_data.stop = 0;
|
||||
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "STARTING ENTROPY COUNTER THREAD\n");
|
||||
#endif
|
||||
/* Create a thread that increments the counter in the data. */
|
||||
/* Thread resources to be disposed of. */
|
||||
ret = wolfSSL_NewThreadNoJoin(Entropy_IncCounter, NULL);
|
||||
if (ret == 0) {
|
||||
/* Wait for the counter to increase indicating thread started. */
|
||||
while (entropy_thread_data.counter == start_counter) {
|
||||
sched_yield();
|
||||
}
|
||||
}
|
||||
|
||||
entropy_thread_started = (ret == 0);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Tell thread to stop and wait for it to complete.
|
||||
*
|
||||
* Called by wolfCrypt_Cleanup().
|
||||
*/
|
||||
static void Entropy_StopThread(void)
|
||||
{
|
||||
/* Only stop a thread if one is running. */
|
||||
if (entropy_thread_started) {
|
||||
/* Tell thread to stop. */
|
||||
entropy_thread_data.stop = 1;
|
||||
/* Stopped thread so no thread started anymore. */
|
||||
entropy_thread_started = 0;
|
||||
}
|
||||
}
|
||||
/* end if defined(HAVE_PTHREAD) */
|
||||
|
||||
#else
|
||||
|
||||
#error "No high precision time available for MemUse Entropy."
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef ENTROPY_NUM_WORDS_BITS
|
||||
/* Number of bits to count of 64-bit words in state. */
|
||||
#define ENTROPY_NUM_WORDS_BITS 14
|
||||
#endif
|
||||
|
||||
/* Floor of 8 yields pool of 256x 64-bit word samples
|
||||
* 9 -> 512x 64-bit word samples
|
||||
* 10 -> 1,024x 64-bit word samples
|
||||
* 11 -> 2,048x 64-bit word samples
|
||||
* 12 -> 4,096x 64-bit word samples
|
||||
* 13 -> 8,192x 64-bit word samples
|
||||
* 14 -> 16,384x 64-bit word samples
|
||||
* 15 -> 32,768x 64-bit word samples
|
||||
* ... doubling every time up to a maximum of:
|
||||
* 30 -> 1,073,741,824x 64-bit word samples
|
||||
* 1 billion+ samples should be more then sufficient for any use-case
|
||||
*/
|
||||
#if ENTROPY_NUM_WORDS_BITS < 8
|
||||
#error "ENTROPY_NUM_WORDS_BITS must be 8 or more"
|
||||
#elif ENTROPY_NUM_WORDS_BITS > 30
|
||||
#error "ENTROPY_NUM_WORDS_BITS must be less than 31"
|
||||
#endif
|
||||
/* Number of 64-bit words in state. */
|
||||
#define ENTROPY_NUM_WORDS (1 << ENTROPY_NUM_WORDS_BITS)
|
||||
|
||||
/* Size of one block of 64-bit words. */
|
||||
#define ENTROPY_BLOCK_SZ (ENTROPY_NUM_WORDS_BITS - 8)
|
||||
|
||||
#ifndef ENTROPY_NUM_UPDATES
|
||||
/* Number of times to update random blocks.
|
||||
* Less than 2^ENTROPY_BLOCK_SZ (default: 2^6 = 64).
|
||||
* Maximize value to maximize entropy per sample.
|
||||
* Limit value to ensure entropy is collected in a timely manner.
|
||||
*/
|
||||
#define ENTROPY_NUM_UPDATES 18
|
||||
/* Upper round of log2(ENTROPY_NUM_UPDATES) */
|
||||
#define ENTROPY_NUM_UPDATES_BITS 5
|
||||
#elif !defined(ENTROPY_NUM_UPDATES_BITS)
|
||||
#define ENTROPY_NUM_UPDATES_BITS ENTROPY_BLOCK_SZ
|
||||
#endif
|
||||
#ifndef ENTROPY_NUM_UPDATES_BITS
|
||||
#error "ENTROPY_NUM_UPDATES_BITS must be defined - " \
|
||||
"upper(log2(ENTROPY_NUM_UPDATES))"
|
||||
#endif
|
||||
#if ENTROPY_NUM_UPDATES_BITS != 0
|
||||
/* Amount to shift offset to get better coverage of a block */
|
||||
#define ENTROPY_OFFSET_SHIFTING \
|
||||
(ENTROPY_BLOCK_SZ / ENTROPY_NUM_UPDATES_BITS)
|
||||
#else
|
||||
/* Amount to shift offset to get better coverage of a block */
|
||||
#define ENTROPY_OFFSET_SHIFTING ENTROPY_BLOCK_SZ
|
||||
#endif
|
||||
|
||||
#ifndef ENTROPY_NUM_64BIT_WORDS
|
||||
/* Number of 64-bit words to update - 32. */
|
||||
#define ENTROPY_NUM_64BIT_WORDS WC_SHA3_256_DIGEST_SIZE
|
||||
#elif ENTROPY_NUM_64BIT_WORDS > WC_SHA3_256_DIGEST_SIZE
|
||||
#error "ENTROPY_NUM_64BIT_WORDS must be <= SHA3-256 digest size in bytes"
|
||||
#endif
|
||||
|
||||
#if ENTROPY_BLOCK_SZ < ENTROPY_NUM_UPDATES_BITS
|
||||
#define EXTRA_ENTROPY_WORDS ENTROPY_NUM_UPDATES
|
||||
#else
|
||||
#define EXTRA_ENTROPY_WORDS 0
|
||||
#endif
|
||||
|
||||
/* State to update that is multiple cache lines long. */
|
||||
static word64 entropy_state[ENTROPY_NUM_WORDS + EXTRA_ENTROPY_WORDS] = {0};
|
||||
|
||||
/* Using memory will take different amount of times depending on the CPU's
|
||||
* caches and business.
|
||||
*/
|
||||
static void Entropy_MemUse(void)
|
||||
{
|
||||
int i;
|
||||
static byte d[WC_SHA3_256_DIGEST_SIZE];
|
||||
int j;
|
||||
|
||||
for (j = 0; j < ENTROPY_NUM_UPDATES; j++) {
|
||||
/* Hash the first 32 64-bit words of state. */
|
||||
wc_Sha3_256_Update(&entropyHash, (byte*)entropy_state,
|
||||
sizeof(*entropy_state) * ENTROPY_NUM_64BIT_WORDS);
|
||||
/* Get pseudo-random indices. */
|
||||
wc_Sha3_256_Final(&entropyHash, d);
|
||||
|
||||
for (i = 0; i < ENTROPY_NUM_64BIT_WORDS; i++) {
|
||||
/* Choose a 64-bit word from a pseudo-random block.*/
|
||||
int idx = ((int)d[i] << ENTROPY_BLOCK_SZ) +
|
||||
(j << ENTROPY_OFFSET_SHIFTING);
|
||||
/* Update a pseudo-random 64-bit word with a pseudo-random value. */
|
||||
entropy_state[idx] += Entropy_TimeHiRes();
|
||||
/* Ensure part of state that is hashed is updated. */
|
||||
entropy_state[i] += entropy_state[idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Last time entropy sample was gathered. */
|
||||
static word64 entropy_last_time = 0;
|
||||
|
||||
/* Get a sample of noise.
|
||||
*
|
||||
* Value is time taken to use memory.
|
||||
*
|
||||
* Called to test raw entropy.
|
||||
*
|
||||
* @return 64-bit value that is the noise.
|
||||
*/
|
||||
static word64 Entropy_GetSample(void)
|
||||
{
|
||||
word64 now;
|
||||
word64 ret;
|
||||
|
||||
#ifdef HAVE_FIPS
|
||||
/* First sample must be disregard when in FIPS. */
|
||||
if (entropy_last_time == 0) {
|
||||
/* Get sample which triggers CAST in FIPS mode. */
|
||||
Entropy_MemUse();
|
||||
/* Start entropy time after CASTs. */
|
||||
entropy_last_time = Entropy_TimeHiRes();
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Use memory such that it will take an unpredictable amount of time. */
|
||||
Entropy_MemUse();
|
||||
|
||||
/* Get the time now to subtract from previous end time. */
|
||||
now = Entropy_TimeHiRes();
|
||||
/* Calculate time diff since last sampling. */
|
||||
ret = now - entropy_last_time;
|
||||
/* Store last time. */
|
||||
entropy_last_time = now;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Get as many samples of noise as required.
|
||||
*
|
||||
* One sample is one byte.
|
||||
*
|
||||
* @param [out] noise Buffer to hold samples.
|
||||
* @param [in] samples Number of one byte samples to get.
|
||||
*/
|
||||
static void Entropy_GetNoise(unsigned char* noise, int samples)
|
||||
{
|
||||
int i;
|
||||
|
||||
/* Do it once to get things going. */
|
||||
Entropy_MemUse();
|
||||
|
||||
/* Get as many samples as required. */
|
||||
for (i = 0; i < samples; i++) {
|
||||
noise[i] = (byte)Entropy_GetSample();
|
||||
}
|
||||
}
|
||||
|
||||
/* Generate raw entropy for performing assessment.
|
||||
*
|
||||
* @param [out] raw Buffer to hold raw entropy data.
|
||||
* @param [in] cnt Number of bytes of raw entropy to get.
|
||||
* @return 0 on success.
|
||||
* @return Negative when creating a thread fails - when no high resolution
|
||||
* clock available.
|
||||
*/
|
||||
int wc_Entropy_GetRawEntropy(unsigned char* raw, int cnt)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Start the counter thread as a proxy for time counter. */
|
||||
ret = Entropy_StartThread();
|
||||
if (ret == 0)
|
||||
#endif
|
||||
{
|
||||
Entropy_GetNoise(raw, cnt);
|
||||
}
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Stop the counter thread to avoid thrashing the system. */
|
||||
Entropy_StopThread();
|
||||
#endif
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
#if ENTROPY_MIN == 1
|
||||
/* SP800-90b 4.4.1 - Repetition Test
|
||||
* C = 1 + upper(-log2(alpha) / H)
|
||||
* When alpha = 2^-30 and H = 1,
|
||||
* C = 1 + upper(30 / 1) = 31
|
||||
*/
|
||||
#define REP_CUTOFF 31
|
||||
#else
|
||||
#error "Minimum entropy not defined to a recognized value."
|
||||
#endif
|
||||
|
||||
/* Have valid previous sample for repetition test. */
|
||||
static int rep_have_prev = 0;
|
||||
/* Previous sample value. */
|
||||
static byte rep_prev_noise;
|
||||
|
||||
static void Entropy_HealthTest_Repetition_Reset(void)
|
||||
{
|
||||
/* No previous stored. */
|
||||
rep_have_prev = 0;
|
||||
/* Clear previous. */
|
||||
rep_prev_noise = 0;
|
||||
}
|
||||
|
||||
/* Test sample value with repetition test.
|
||||
*
|
||||
* @param [in] noise Sample to test.
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_RT_E on failure.
|
||||
*/
|
||||
static int Entropy_HealthTest_Repetition(byte noise)
|
||||
{
|
||||
int ret = 0;
|
||||
/* Number of times previous value has been seen continuously. */
|
||||
static int rep_cnt = 0;
|
||||
|
||||
/* If we don't have a previous then store this one for next time. */
|
||||
if (!rep_have_prev) {
|
||||
rep_prev_noise = noise;
|
||||
rep_have_prev = 1;
|
||||
rep_cnt = 1;
|
||||
}
|
||||
/* Check whether this sample matches last. */
|
||||
else if (noise == rep_prev_noise) {
|
||||
/* Update count of repetitions. */
|
||||
rep_cnt++;
|
||||
/* Fail if we reach cutoff. */
|
||||
if (rep_cnt >= REP_CUTOFF) {
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "REPETITION FAILED: %d\n", noise);
|
||||
#endif
|
||||
Entropy_HealthTest_Repetition_Reset();
|
||||
ret = ENTROPY_RT_E;
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Cache new previous and seen one so far. */
|
||||
rep_prev_noise = noise;
|
||||
rep_cnt = 1;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* SP800-90b 4.4.2 - Adaptive Proportion Test
|
||||
* Para 2
|
||||
* ... The window size W is selected based on the alphabet size ... 512 if
|
||||
* the noise source is not binary ...
|
||||
*/
|
||||
#define PROP_WINDOW_SIZE 512
|
||||
#if ENTROPY_MIN == 1
|
||||
/* SP800-90b 4.4.2 - Adaptive Proportion Test
|
||||
* Note 10
|
||||
* C = 1 + CRITBINOM(W, power(2,( -H)),1-alpha)
|
||||
* alpha = 2^-30 = POWER(2,-30), H = 1, W = 512
|
||||
* C = 1 + CRITBINOM(512, 0.5, 1-POWER(2,-30)) = 1 + 324 = 325
|
||||
*/
|
||||
#define PROP_CUTOFF 325
|
||||
#else
|
||||
#error "Minimum entropy not defined to a recognized value."
|
||||
#endif
|
||||
|
||||
/* Total number of samples storef for Adaptive proportion test.
|
||||
* Need the next 512 samples to compare this this one.
|
||||
*/
|
||||
static word16 prop_total = 0;
|
||||
/* Index of first sample. */
|
||||
static word16 prop_first = 0;
|
||||
/* Index to put next sample in. */
|
||||
static word16 prop_last = 0;
|
||||
/* Count of each value seen in queue. */
|
||||
static word16 prop_cnt[1 << ENTROPY_BITS_USED] = { 0 };
|
||||
/* Circular queue of samples. */
|
||||
static word16 prop_samples[PROP_WINDOW_SIZE];
|
||||
|
||||
/* Resets the data for the Adaptive Proportion Test.
|
||||
*/
|
||||
static void Entropy_HealthTest_Proportion_Reset(void)
|
||||
{
|
||||
/* Clear out samples. */
|
||||
XMEMSET(prop_samples, 0, sizeof(prop_samples));
|
||||
/* Clear out counts. */
|
||||
XMEMSET(prop_cnt, 0, sizeof(prop_cnt));
|
||||
/* Clear stored count. */
|
||||
prop_total = 0;
|
||||
/* Reset first and last index for samples. */
|
||||
prop_first = 0;
|
||||
prop_last = 0;
|
||||
}
|
||||
|
||||
/* Add sample to Adaptive Proportion test.
|
||||
*
|
||||
* SP800-90b 4.4.2 - Adaptive Proportion Test
|
||||
*
|
||||
* Sample is accumulated into buffer until required successive values seen.
|
||||
*
|
||||
* @param [in] noise Sample to test.
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_APT_E on failure.
|
||||
*/
|
||||
static int Entropy_HealthTest_Proportion(byte noise)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
/* Need minimum samples in queue to test with - keep adding while we have
|
||||
* less. */
|
||||
if (prop_total < PROP_CUTOFF - 1) {
|
||||
/* Store sample at last position in circular queue. */
|
||||
prop_samples[prop_last++] = noise;
|
||||
/* Update count of seen value based on new sample. */
|
||||
prop_cnt[noise]++;
|
||||
/* Update count of store values. */
|
||||
prop_total++;
|
||||
}
|
||||
else {
|
||||
/* We have at least a minimum set of samples in queue. */
|
||||
/* Store new sample at end of queue. */
|
||||
prop_samples[prop_last] = noise;
|
||||
/* Update last index now that we have added new sample to queue. */
|
||||
prop_last = (prop_last + 1) % PROP_WINDOW_SIZE;
|
||||
/* Added sample to queue - add count. */
|
||||
prop_cnt[noise]++;
|
||||
/* Update count of store values. */
|
||||
prop_total++;
|
||||
|
||||
/* Check whether first value has too many repetitions in queue. */
|
||||
if (prop_cnt[noise] >= PROP_CUTOFF) {
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "PROPORTION FAILED: %d %d\n", val, prop_cnt[noise]);
|
||||
#endif
|
||||
Entropy_HealthTest_Proportion_Reset();
|
||||
/* Error code returned. */
|
||||
ret = ENTROPY_APT_E;
|
||||
}
|
||||
else if (prop_total == PROP_WINDOW_SIZE) {
|
||||
/* Return to 511 samples in queue. */
|
||||
/* Get first value in queue - value to test. */
|
||||
byte val = (byte)prop_samples[prop_first];
|
||||
/* Update first index to remove first sample from the queue. */
|
||||
prop_first = (prop_first + 1) % PROP_WINDOW_SIZE;
|
||||
/* Removed first sample from queue - remove count. */
|
||||
prop_cnt[val]--;
|
||||
/* Update count of store values. */
|
||||
prop_total--;
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* SP800-90b 4.3 - Requirements for Health Tests
|
||||
* 1.4: The entropy source's startup tests shall run the continuous health
|
||||
* tests over at least 1024 consecutive samples.
|
||||
*
|
||||
* Adaptive Proportion Test requires a number of samples to compared too.
|
||||
*/
|
||||
#define ENTROPY_INITIAL_COUNT (1024 + PROP_WINDOW_SIZE)
|
||||
|
||||
/* Perform startup health testing.
|
||||
*
|
||||
* Fill adaptive proportion test buffer and then do 1024 samples.
|
||||
* Perform repetition test on all samples expect last.
|
||||
*
|
||||
* Discards samples from health tests on failure.
|
||||
*
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
|
||||
*/
|
||||
static int Entropy_HealthTest_Startup(void)
|
||||
{
|
||||
int ret = 0;
|
||||
byte initial[ENTROPY_INITIAL_COUNT];
|
||||
int i;
|
||||
|
||||
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
|
||||
fprintf(stderr, "STARTUP HEALTH TEST\n");
|
||||
#endif
|
||||
|
||||
/* Reset cached values before testing. */
|
||||
Entropy_HealthTest_Reset();
|
||||
|
||||
/* Fill initial sample buffer with noise. */
|
||||
Entropy_GetNoise(initial, ENTROPY_INITIAL_COUNT);
|
||||
/* Health check initial noise. */
|
||||
for (i = 0; (ret == 0) && (i < ENTROPY_INITIAL_COUNT); i++) {
|
||||
ret = Entropy_HealthTest_Repetition(initial[i]);
|
||||
if (ret == 0) {
|
||||
ret = Entropy_HealthTest_Proportion(initial[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (ret != 0) {
|
||||
/* Failing test only resets its own data. */
|
||||
Entropy_HealthTest_Reset();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Condition raw entropy noise using SHA-3-256.
|
||||
*
|
||||
* Put noise into a hash function: SHA-3-256.
|
||||
* Add the current time counter to help with uniqueness.
|
||||
*
|
||||
* @param [out] output Buffer to conditioned data.
|
||||
* @param [in] len Number of bytes to put into output buffer.
|
||||
* @param [in] noise Buffer with raw noise data.
|
||||
* @param [in] noise_len Length of noise data in bytes.
|
||||
* @return 0 on success.
|
||||
* @return Negative on failure.
|
||||
*/
|
||||
static int Entropy_Condition(byte* output, word32 len, byte* noise,
|
||||
word32 noise_len)
|
||||
{
|
||||
int ret;
|
||||
|
||||
/* Add noise to initialized hash. */
|
||||
ret = wc_Sha3_256_Update(&entropyHash, noise, noise_len);
|
||||
if (ret == 0) {
|
||||
word64 now = Entropy_TimeHiRes();
|
||||
/* Add time now counter. */
|
||||
ret = wc_Sha3_256_Update(&entropyHash, (byte*)&now, sizeof(now));
|
||||
}
|
||||
if (ret == 0) {
|
||||
/* Finalize into output buffer. */
|
||||
if (len == WC_SHA3_256_DIGEST_SIZE) {
|
||||
ret = wc_Sha3_256_Final(&entropyHash, output);
|
||||
}
|
||||
else {
|
||||
byte hash[WC_SHA3_256_DIGEST_SIZE];
|
||||
|
||||
ret = wc_Sha3_256_Final(&entropyHash, hash);
|
||||
if (ret == 0) {
|
||||
XMEMCPY(output, hash, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Mutex to prevent multiple callers requesting entropy operations at the
|
||||
* same time.
|
||||
*/
|
||||
static wolfSSL_Mutex entropy_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(entropy_mutex);
|
||||
|
||||
/* Get entropy of specified strength.
|
||||
*
|
||||
* SP800-90b 2.3.1 - GetEntropy: An Interface to the Entropy Source
|
||||
*
|
||||
* In threaded environment, only one thread at a time can get entropy.
|
||||
*
|
||||
* @param [in] bits Number of entropy bits. 256 is max value.
|
||||
* @param [out] entropy Buffer to hold entropy.
|
||||
* @param [in] len Length of data to put into buffer in bytes.
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
|
||||
* @return BAD_MUTEX_E when unable to lock mutex.
|
||||
*/
|
||||
int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len)
|
||||
{
|
||||
int ret = 0;
|
||||
WC_DECLARE_VAR(noise, byte, MAX_NOISE_CNT, 0);
|
||||
/* Noise length is the number of 8 byte samples required to get the bits of
|
||||
* entropy requested. */
|
||||
int noise_len = (bits + ENTROPY_EXTRA) / ENTROPY_MIN;
|
||||
|
||||
WC_ALLOC_VAR_EX(noise, byte, MAX_NOISE_CNT, NULL, DYNAMIC_TYPE_TMP_BUFFER,
|
||||
return MEMORY_E);
|
||||
|
||||
/* Lock the mutex as collection uses globals. */
|
||||
if ((ret == 0) && (wc_LockMutex(&entropy_mutex) != 0)) {
|
||||
ret = BAD_MUTEX_E;
|
||||
}
|
||||
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
if (ret == 0) {
|
||||
/* Start the counter thread as a proxy for time counter. */
|
||||
ret = Entropy_StartThread();
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Check we have had a startup health check pass. */
|
||||
if ((ret == 0) && ((prop_total == 0) || (!rep_have_prev))) {
|
||||
/* Try again as check failed. */
|
||||
ret = Entropy_HealthTest_Startup();
|
||||
}
|
||||
|
||||
/* Keep putting data into buffer until full. */
|
||||
while ((ret == 0) && (len > 0)) {
|
||||
int i;
|
||||
word32 entropy_len = WC_SHA3_256_DIGEST_SIZE;
|
||||
|
||||
/* Output 32 bytes at a time unless buffer has fewer bytes remaining. */
|
||||
if (len < entropy_len) {
|
||||
entropy_len = len;
|
||||
}
|
||||
|
||||
/* Get raw entropy noise. */
|
||||
Entropy_GetNoise(noise, noise_len);
|
||||
/* Health check each noise value. */
|
||||
for (i = 0; (ret == 0) && (i < noise_len); i++) {
|
||||
ret = Entropy_HealthTest_Repetition(noise[i]);
|
||||
if (ret == 0) {
|
||||
ret = Entropy_HealthTest_Proportion(noise[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (ret == 0) {
|
||||
/* Condition noise value down to 32-bytes or less. */
|
||||
ret = Entropy_Condition(entropy, entropy_len, noise, noise_len);
|
||||
}
|
||||
if (ret == 0) {
|
||||
/* Update buffer pointer and count of bytes left to generate. */
|
||||
entropy += entropy_len;
|
||||
len -= entropy_len;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Stop the counter thread to avoid thrashing the system. */
|
||||
Entropy_StopThread();
|
||||
#endif
|
||||
|
||||
if (ret != WC_NO_ERR_TRACE(BAD_MUTEX_E)) {
|
||||
/* Unlock mutex now we are done. */
|
||||
wc_UnLockMutex(&entropy_mutex);
|
||||
}
|
||||
|
||||
WC_FREE_VAR_EX(noise, NULL, DYNAMIC_TYPE_TMP_BUFFER);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Performs on-demand testing.
|
||||
*
|
||||
* In threaded environment, locks out other threads from getting entropy.
|
||||
*
|
||||
* @return 0 on success.
|
||||
* @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
|
||||
* @return BAD_MUTEX_E when unable to lock mutex.
|
||||
*/
|
||||
int wc_Entropy_OnDemandTest(void)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
/* Lock the mutex as we don't want collecting to happen during testing. */
|
||||
if (wc_LockMutex(&entropy_mutex) != 0) {
|
||||
ret = BAD_MUTEX_E;
|
||||
}
|
||||
|
||||
if (ret == 0) {
|
||||
/* Perform startup tests. */
|
||||
ret = Entropy_HealthTest_Startup();
|
||||
}
|
||||
|
||||
if (ret != WC_NO_ERR_TRACE(BAD_MUTEX_E)) {
|
||||
/* Unlock mutex now we are done. */
|
||||
wc_UnLockMutex(&entropy_mutex);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Initialize global state for MemUse Entropy and do startup health test.
|
||||
*
|
||||
* @return 0 on success.
|
||||
* @return Negative on failure.
|
||||
*/
|
||||
int Entropy_Init(void)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
/* Check whether initialization has succeeded before. */
|
||||
if (!entropy_memuse_initialized) {
|
||||
#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_MUTEX_INITIALIZER)
|
||||
ret = wc_InitMutex(&entropy_mutex);
|
||||
#endif
|
||||
if (ret == 0) {
|
||||
/* Initialize a SHA3-256 object for use in entropy operations. */
|
||||
ret = wc_InitSha3_256(&entropyHash, NULL, INVALID_DEVID);
|
||||
}
|
||||
/* Set globals initialized. */
|
||||
entropy_memuse_initialized = (ret == 0);
|
||||
if (ret == 0) {
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Start the counter thread as a proxy for time counter. */
|
||||
ret = Entropy_StartThread();
|
||||
if (ret == 0)
|
||||
#endif
|
||||
{
|
||||
/* Do first startup test now. */
|
||||
ret = Entropy_HealthTest_Startup();
|
||||
}
|
||||
#ifdef ENTROPY_MEMUSE_THREADED
|
||||
/* Stop the counter thread to avoid thrashing the system. */
|
||||
Entropy_StopThread();
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Finalize the data associated with the MemUse Entropy source.
|
||||
*/
|
||||
void Entropy_Final(void)
|
||||
{
|
||||
/* Only finalize when initialized. */
|
||||
if (entropy_memuse_initialized) {
|
||||
/* Dispose of the SHA3-356 hash object. */
|
||||
wc_Sha3_256_Free(&entropyHash);
|
||||
#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_MUTEX_INITIALIZER)
|
||||
wc_FreeMutex(&entropy_mutex);
|
||||
#endif
|
||||
/* Clear health test data. */
|
||||
Entropy_HealthTest_Reset();
|
||||
/* No longer initialized. */
|
||||
entropy_memuse_initialized = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Reset the data associated with the MemUse Entropy health tests.
|
||||
*/
|
||||
static void Entropy_HealthTest_Reset(void)
|
||||
{
|
||||
Entropy_HealthTest_Repetition_Reset();
|
||||
Entropy_HealthTest_Proportion_Reset();
|
||||
}
|
||||
|
||||
#endif /* HAVE_ENTROPY_MEMUSE */
|
||||
|
||||
@@ -47,6 +47,7 @@ nobase_include_HEADERS+= \
|
||||
wolfssl/wolfcrypt/chacha.h \
|
||||
wolfssl/wolfcrypt/chacha20_poly1305.h \
|
||||
wolfssl/wolfcrypt/random.h \
|
||||
wolfssl/wolfcrypt/wolfentropy.h \
|
||||
wolfssl/wolfcrypt/ripemd.h \
|
||||
wolfssl/wolfcrypt/rsa.h \
|
||||
wolfssl/wolfcrypt/rc2.h \
|
||||
|
||||
@@ -279,19 +279,6 @@ WOLFSSL_API int wc_FreeRng(WC_RNG* rng);
|
||||
void* heap, int devId);
|
||||
#endif /* HAVE_HASHDRBG */
|
||||
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
/* Maximum entropy bits that can be produced. */
|
||||
#define MAX_ENTROPY_BITS 256
|
||||
|
||||
/* For generating data for assessment. */
|
||||
WOLFSSL_API int wc_Entropy_GetRawEntropy(unsigned char* raw, int cnt);
|
||||
WOLFSSL_API int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len);
|
||||
WOLFSSL_API int wc_Entropy_OnDemandTest(void);
|
||||
|
||||
WOLFSSL_LOCAL int Entropy_Init(void);
|
||||
WOLFSSL_LOCAL void Entropy_Final(void);
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
@@ -442,6 +442,8 @@
|
||||
(WOLFSSL_FIPS_VERSION_CODE >= WOLFSSL_MAKE_FIPS_VERSION3(major,minor,patch))
|
||||
#define FIPS_VERSION3_GT(major,minor,patch) \
|
||||
(WOLFSSL_FIPS_VERSION_CODE > WOLFSSL_MAKE_FIPS_VERSION3(major,minor,patch))
|
||||
#define FIPS_VERSION3_NE(major,minor,patch) \
|
||||
(WOLFSSL_FIPS_VERSION_CODE != WOLFSSL_MAKE_FIPS_VERSION3(major,minor,patch))
|
||||
/*------------------------------------------------------------*/
|
||||
|
||||
|
||||
|
||||
72
wolfssl/wolfcrypt/wolfentropy.h
Normal file
72
wolfssl/wolfcrypt/wolfentropy.h
Normal file
@@ -0,0 +1,72 @@
|
||||
/* wolfentropy.h
|
||||
*
|
||||
* Copyright (C) 2006-2025 wolfSSL Inc.
|
||||
*
|
||||
* This file is part of wolfSSL.
|
||||
*
|
||||
* wolfSSL is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* wolfSSL is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
|
||||
*/
|
||||
|
||||
#ifndef WOLFENTROPY_H
|
||||
#define WOLFENTROPY_H
|
||||
|
||||
#include <wolfssl/wolfcrypt/types.h>
|
||||
|
||||
#ifdef HAVE_ENTROPY_MEMUSE
|
||||
|
||||
#if defined(ENTROPY_SCALE_FACTOR) && FIPS_VERSION3_GE(5,2,4) && \
|
||||
FIPS_VERSION3_NE(6,0,0)
|
||||
#error "ENTROPY_SCALE_FACTOR defined elsewhere than wolfEntropy.h"
|
||||
#endif
|
||||
|
||||
#if FIPS_VERSION3_GE(5,2,4) && FIPS_VERSION3_NE(6,0,0)
|
||||
/* Do not allow default fallback to /dev/urandom when in FIPS mode that
|
||||
* supports ESV */
|
||||
#define ENTROPY_MEMUSE_FORCE_FAILURE
|
||||
#endif
|
||||
|
||||
#ifndef ENTROPY_SCALE_FACTOR
|
||||
/* The entropy scale factor should be the whole number inverse of the
|
||||
* minimum bits of entropy per bit of NDRNG output. */
|
||||
/* Full strength, conditioned entropy is requested of MemUse Entropy. */
|
||||
#if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
|
||||
(HAVE_FIPS_VERSION >= 2)
|
||||
#define ENTROPY_SCALE_FACTOR (4)
|
||||
#else
|
||||
#define ENTROPY_SCALE_FACTOR (1)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Maximum entropy bits that can be produced. */
|
||||
#define MAX_ENTROPY_BITS 256
|
||||
|
||||
/* For generating data for assessment. */
|
||||
WOLFSSL_API int wc_Entropy_GetRawEntropy(unsigned char* raw, int cnt);
|
||||
WOLFSSL_API int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len);
|
||||
WOLFSSL_API int wc_Entropy_OnDemandTest(void);
|
||||
|
||||
WOLFSSL_LOCAL int Entropy_Init(void);
|
||||
WOLFSSL_LOCAL void Entropy_Final(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* HAVE_ENTROPY_MEMUSE */
|
||||
#endif /* WOLFENTROPY_H */
|
||||
@@ -165,6 +165,9 @@ fn scan_cfg() -> Result<()> {
|
||||
check_cfg(&binding, "wc_SSH_KDF", "kdf_ssh");
|
||||
check_cfg(&binding, "wc_Tls13_HKDF_Extract_ex", "kdf_tls13");
|
||||
|
||||
/* random */
|
||||
check_cfg(&binding, "wc_RNG_DRBG_Reseed", "random_hashdrbg");
|
||||
|
||||
/* rsa */
|
||||
check_cfg(&binding, "wc_InitRsaKey", "rsa");
|
||||
check_cfg(&binding, "wc_RsaDirect", "rsa_direct");
|
||||
|
||||
@@ -31,3 +31,47 @@ pub mod prf;
|
||||
pub mod random;
|
||||
pub mod rsa;
|
||||
pub mod sha;
|
||||
|
||||
use crate::sys;
|
||||
|
||||
/// Initialize resources used by wolfCrypt.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns either Ok(()) on success or Err(e) containing the wolfSSL
|
||||
/// library error code value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use wolfssl::wolfcrypt::*;
|
||||
/// wolfcrypt_init().expect("Error with wolfcrypt_init()");
|
||||
/// ```
|
||||
pub fn wolfcrypt_init() -> Result<(), i32> {
|
||||
let rc = unsafe { sys::wolfCrypt_Init() };
|
||||
if rc != 0 {
|
||||
return Err(rc);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clean up resources used by wolfCrypt.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns either Ok(()) on success or Err(e) containing the wolfSSL
|
||||
/// library error code value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use wolfssl::wolfcrypt::*;
|
||||
/// wolfcrypt_cleanup().expect("Error with wolfcrypt_cleanup()");
|
||||
/// ```
|
||||
pub fn wolfcrypt_cleanup() -> Result<(), i32> {
|
||||
let rc = unsafe { sys::wolfCrypt_Cleanup() };
|
||||
if rc != 0 {
|
||||
return Err(rc);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -159,6 +159,132 @@ impl RNG {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create and test functionality of DRBG.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `nonce`: Optional nonce to use to initialize DRBG.
|
||||
/// * `seed_a`: Buffer containing seed data (required).
|
||||
/// * `seed_b`: Optional buffer containing more seed data. If present, the
|
||||
/// DRBG will be reseeded.
|
||||
/// * `output`: Output buffer.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns either Ok(()) on success or Err(e) containing the wolfSSL
|
||||
/// library error code value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// #![cfg(random_hashdrbg)]
|
||||
/// use wolfssl::wolfcrypt::random::RNG;
|
||||
/// let nonce = [99u8, 88, 77, 66];
|
||||
/// let seed_a = [42u8, 33, 55, 88];
|
||||
/// let seed_b = [45u8, 10, 20, 30];
|
||||
/// let mut output = [0u8; 128];
|
||||
/// RNG::health_test(Some(&nonce), &seed_a, Some(&seed_b), &mut output).expect("Error with health_test()");
|
||||
/// ```
|
||||
#[cfg(random_hashdrbg)]
|
||||
pub fn health_test(nonce: Option<&[u8]>, seed_a: &[u8], seed_b: Option<&[u8]>, output: &mut [u8]) -> Result<(), i32> {
|
||||
Self::health_test_ex(nonce, seed_a, seed_b, output, None, None)
|
||||
}
|
||||
|
||||
/// Create and test functionality of DRBG with optional heap and device ID.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `nonce`: Optional nonce to use to initialize DRBG.
|
||||
/// * `seed_a`: Buffer containing seed data (required).
|
||||
/// * `seed_b`: Optional buffer containing more seed data. If present, the
|
||||
/// DRBG will be reseeded.
|
||||
/// * `output`: Output buffer.
|
||||
/// * `heap`: Optional heap hint.
|
||||
/// * `dev_id` Optional device ID to use with crypto callbacks or async hardware.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns either Ok(()) on success or Err(e) containing the wolfSSL
|
||||
/// library error code value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// #![cfg(random_hashdrbg)]
|
||||
/// use wolfssl::wolfcrypt::random::RNG;
|
||||
/// let nonce = [99u8, 88, 77, 66];
|
||||
/// let seed_a = [42u8, 33, 55, 88];
|
||||
/// let seed_b = [45u8, 10, 20, 30];
|
||||
/// let mut output = [0u8; 128];
|
||||
/// RNG::health_test_ex(Some(&nonce), &seed_a, Some(&seed_b), &mut output, None, None).expect("Error with health_test_ex()");
|
||||
/// ```
|
||||
#[cfg(random_hashdrbg)]
|
||||
pub fn health_test_ex(nonce: Option<&[u8]>, seed_a: &[u8], seed_b: Option<&[u8]>, output: &mut [u8], heap: Option<*mut std::os::raw::c_void>, dev_id: Option<i32>) -> Result<(), i32> {
|
||||
let mut nonce_ptr = core::ptr::null();
|
||||
let mut nonce_size = 0u32;
|
||||
if let Some(nonce) = nonce {
|
||||
nonce_ptr = nonce.as_ptr();
|
||||
nonce_size = nonce.len() as u32;
|
||||
}
|
||||
let seed_a_size = seed_a.len() as u32;
|
||||
let mut seed_b_ptr = core::ptr::null();
|
||||
let mut seed_b_size = 0u32;
|
||||
if let Some(seed_b) = seed_b {
|
||||
seed_b_ptr = seed_b.as_ptr();
|
||||
seed_b_size = seed_b.len() as u32;
|
||||
}
|
||||
let output_size = output.len() as u32;
|
||||
let heap = match heap {
|
||||
Some(heap) => heap,
|
||||
None => core::ptr::null_mut(),
|
||||
};
|
||||
let dev_id = match dev_id {
|
||||
Some(dev_id) => dev_id,
|
||||
None => sys::INVALID_DEVID,
|
||||
};
|
||||
let rc = unsafe {
|
||||
sys::wc_RNG_HealthTest_ex(if seed_b_size > 0 {1} else {0},
|
||||
nonce_ptr, nonce_size,
|
||||
seed_a.as_ptr(), seed_a_size,
|
||||
seed_b_ptr, seed_b_size,
|
||||
output.as_mut_ptr(), output_size,
|
||||
heap, dev_id)
|
||||
};
|
||||
if rc != 0 {
|
||||
return Err(rc);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test a seed.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `seed`: Buffer containing seed data.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns either Ok(()) on success or Err(e) containing the wolfSSL
|
||||
/// library error code value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// #![cfg(random_hashdrbg)]
|
||||
/// use wolfssl::wolfcrypt::random::RNG;
|
||||
/// let seed = [42u8, 33, 55, 88];
|
||||
/// RNG::test_seed(&seed).expect("Error with test_seed()");
|
||||
/// ```
|
||||
#[cfg(random_hashdrbg)]
|
||||
pub fn test_seed(seed: &[u8]) -> Result<(), i32> {
|
||||
let seed_size = seed.len() as u32;
|
||||
let rc = unsafe { sys::wc_RNG_TestSeed(seed.as_ptr(), seed_size) };
|
||||
if rc != 0 {
|
||||
return Err(rc);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate a single cryptographically secure random byte.
|
||||
///
|
||||
/// This method calls the `wc_RNG_GenerateByte` wolfSSL library function to
|
||||
@@ -202,6 +328,38 @@ impl RNG {
|
||||
Err(rc)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reseed random number generator.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `seed`: Buffer with new seed data.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns either Ok(()) on success or Err(e) containing the wolfSSL
|
||||
/// library error code value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// #![cfg(random_hashdrbg)]
|
||||
/// use wolfssl::wolfcrypt::random::RNG;
|
||||
/// let mut rng = RNG::new().expect("Failed to create RNG");
|
||||
/// let seed = [1u8, 2, 3, 4];
|
||||
/// rng.reseed(&seed).expect("Error with reseed()");
|
||||
/// ```
|
||||
#[cfg(random_hashdrbg)]
|
||||
pub fn reseed(&mut self, seed: &[u8]) -> Result<(), i32> {
|
||||
let seed_size = seed.len() as u32;
|
||||
let rc = unsafe {
|
||||
sys::wc_RNG_DRBG_Reseed(&mut self.wc_rng, seed.as_ptr(), seed_size)
|
||||
};
|
||||
if rc != 0 {
|
||||
return Err(rc);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RNG {
|
||||
|
||||
@@ -28,6 +28,23 @@ fn test_rng_new_with_nonce_ex_and_drop() {
|
||||
let _rng = RNG::new_with_nonce_ex(&mut nonce, None, None).expect("Failed to create RNG");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(random_hashdrbg)]
|
||||
fn test_health_test() {
|
||||
let nonce = [99u8, 88, 77, 66];
|
||||
let seed_a = [42u8, 33, 55, 88];
|
||||
let seed_b = [45u8, 10, 20, 30];
|
||||
let mut output = [0u8; 128];
|
||||
RNG::health_test(Some(&nonce), &seed_a, Some(&seed_b), &mut output).expect("Error with health_test()");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(random_hashdrbg)]
|
||||
fn test_test_seed() {
|
||||
let seed = [42u8, 33, 55, 88];
|
||||
RNG::test_seed(&seed).expect("Error with test_seed()");
|
||||
}
|
||||
|
||||
// Test that generate_byte() returns random values.
|
||||
#[test]
|
||||
fn test_rng_generate_byte() {
|
||||
@@ -70,3 +87,11 @@ fn test_rng_generate_block_u32() {
|
||||
assert_ne!(buffer[buffer.len() - 1], 0u32);
|
||||
assert_ne!(buffer[buffer.len() - 1], 0xFFFF_FFFFu32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(random_hashdrbg)]
|
||||
fn test_rng_reseed() {
|
||||
let mut rng = RNG::new().expect("Failed to create RNG");
|
||||
let seed = [1u8, 2, 3, 4];
|
||||
rng.reseed(&seed).expect("Error with reseed()");
|
||||
}
|
||||
|
||||
11
wrapper/rust/wolfssl/tests/test_wolfcrypt.rs
Normal file
11
wrapper/rust/wolfssl/tests/test_wolfcrypt.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use wolfssl::wolfcrypt::*;
|
||||
|
||||
#[test]
|
||||
fn test_wolfcrypt_init() {
|
||||
wolfcrypt_init().expect("Error with wolfcrypt_init()");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wolfcrypt_cleanup() {
|
||||
wolfcrypt_cleanup().expect("Error with wolfcrypt_cleanup()");
|
||||
}
|
||||
Reference in New Issue
Block a user