diff --git a/benchmark/Makefile b/benchmark/Makefile index 874d96cb4..c80ce04ba 100644 --- a/benchmark/Makefile +++ b/benchmark/Makefile @@ -40,7 +40,7 @@ ARCHFLAGS ?= # Enable extra C compiler warnings CFLAGS_EXTRA = -Werror -Wall -Wextra # Place functions / data into separate sections to allow unused code removal -CFLAGS_EXTRA += -ffunction-sections -fdata-sections +CFLAGS_EXTRA += -ffunction-sections -fdata-sections -Wdeclaration-after-statement # C standard to use (default to c90 if not specified) CSTD ?= -std=c90 diff --git a/benchmark/bench_modules/wh_bench_mod_curve25519.c b/benchmark/bench_modules/wh_bench_mod_curve25519.c index 954ac2a4b..85c0283c6 100644 --- a/benchmark/bench_modules/wh_bench_mod_curve25519.c +++ b/benchmark/bench_modules/wh_bench_mod_curve25519.c @@ -52,9 +52,6 @@ uint8_t key2_der[] = { int wh_Bench_Mod_Curve25519KeyGen(whClientContext* client, whBenchOpContext* ctx, int id, void* params) { - (void)client; - (void)params; - int ret = 0; curve25519_key key[1] = {0}; WC_RNG rng[1] = {0}; @@ -62,6 +59,9 @@ int wh_Bench_Mod_Curve25519KeyGen(whClientContext* client, int initialized_rng = 0; int initialized_key = 0; + (void)client; + (void)params; + /* Initialize the RNG for key generation */ ret = wc_InitRng_ex(rng, NULL, WH_DEV_ID); if (ret != 0) { @@ -126,8 +126,6 @@ int wh_Bench_Mod_Curve25519SharedSecret(whClientContext* client, whBenchOpContext* ctx, int id, void* params) { - (void)params; - int ret = 0; word32 outLen; curve25519_key keyAlice[1] = {0}; @@ -140,6 +138,8 @@ int wh_Bench_Mod_Curve25519SharedSecret(whClientContext* client, whKeyId keyIdBob = WH_KEYID_ERASED; char keyLabel[] = "bench-key"; + (void)params; + /* Cache Alice's key in the HSM */ ret = wh_Client_KeyCache(client, WH_NVM_FLAGS_USAGE_ANY, (uint8_t*)keyLabel, strlen(keyLabel), key1_der, sizeof(key1_der), diff --git a/benchmark/bench_modules/wh_bench_mod_ecc.c b/benchmark/bench_modules/wh_bench_mod_ecc.c index a944e2182..269b94a74 100644 --- a/benchmark/bench_modules/wh_bench_mod_ecc.c +++ b/benchmark/bench_modules/wh_bench_mod_ecc.c @@ -293,8 +293,6 @@ int _benchEccVerify(whClientContext* client, whBenchOpContext* ctx, int id, int _benchEccKeyGen(whClientContext* client, whBenchOpContext* ctx, int id, int curveSize, int devId) { - (void)client; - int ret = 0; ecc_key key[1] = {0}; WC_RNG rng[1] = {0}; @@ -302,6 +300,8 @@ int _benchEccKeyGen(whClientContext* client, whBenchOpContext* ctx, int id, int initialized_rng = 0; int initialized_key = 0; + (void)client; + /* Initialize the RNG for key generation */ ret = wc_InitRng_ex(rng, NULL, devId); if (ret != 0) { diff --git a/benchmark/bench_modules/wh_bench_mod_echo.c b/benchmark/bench_modules/wh_bench_mod_echo.c index ece61edad..75c1b3384 100644 --- a/benchmark/bench_modules/wh_bench_mod_echo.c +++ b/benchmark/bench_modules/wh_bench_mod_echo.c @@ -25,8 +25,6 @@ int wh_Bench_Mod_Echo(whClientContext* client, whBenchOpContext* benchCtx, int id, void* params) { - (void)params; - int i; int ret; uint16_t send_len; @@ -36,6 +34,8 @@ int wh_Bench_Mod_Echo(whClientContext* client, whBenchOpContext* benchCtx, int startRet; int stopRet; + (void)params; + /* Send an entire comm buffer's worth of data */ memset(send_buffer, 0xAA, sizeof(send_buffer)); memset(recv_buffer, 0x55, sizeof(recv_buffer)); diff --git a/benchmark/bench_modules/wh_bench_mod_hmac.c b/benchmark/bench_modules/wh_bench_mod_hmac.c index 1b8a248e4..d1c661971 100644 --- a/benchmark/bench_modules/wh_bench_mod_hmac.c +++ b/benchmark/bench_modules/wh_bench_mod_hmac.c @@ -34,8 +34,6 @@ static const size_t keyLen = sizeof(key) - 1; /* -1 for null terminator */ int _benchHmacSha256(whClientContext* client, whBenchOpContext* ctx, int id, int devId) { - (void)client; - int ret = 0; Hmac hmac[1]; uint8_t out[WC_SHA256_DIGEST_SIZE]; @@ -44,6 +42,8 @@ int _benchHmacSha256(whClientContext* client, whBenchOpContext* ctx, int id, const uint8_t* in; size_t inLen; + (void)client; + #if defined(WOLFHSM_CFG_DMA) if (devId == WH_DEV_ID_DMA) { in = WH_BENCH_DMA_BUFFER; diff --git a/benchmark/bench_modules/wh_bench_mod_mldsa.c b/benchmark/bench_modules/wh_bench_mod_mldsa.c index 09205c042..79bf18116 100644 --- a/benchmark/bench_modules/wh_bench_mod_mldsa.c +++ b/benchmark/bench_modules/wh_bench_mod_mldsa.c @@ -898,8 +898,6 @@ static int _benchMlDsaVerify(whClientContext* client, whBenchOpContext* ctx, static int _benchMlDsaKeyGen(whClientContext* client, whBenchOpContext* ctx, int id, int securityLevel, int devId) { - (void)client; - int ret = 0; MlDsaKey key; WC_RNG rng[1] = {0}; @@ -907,6 +905,9 @@ static int _benchMlDsaKeyGen(whClientContext* client, whBenchOpContext* ctx, int initialized_rng = 0; int initialized_key = 0; + (void)client; + + /* Initialize the RNG */ ret = wc_InitRng_ex(rng, NULL, devId); if (ret != 0) { diff --git a/benchmark/bench_modules/wh_bench_mod_rng.c b/benchmark/bench_modules/wh_bench_mod_rng.c index 9a7651b2f..a35fcf8ee 100644 --- a/benchmark/bench_modules/wh_bench_mod_rng.c +++ b/benchmark/bench_modules/wh_bench_mod_rng.c @@ -27,8 +27,6 @@ int _benchRng(whClientContext* client, whBenchOpContext* ctx, int id, int devId) { - (void)client; - int ret = 0; WC_RNG rng; int i = 0; @@ -36,6 +34,8 @@ int _benchRng(whClientContext* client, whBenchOpContext* ctx, int id, int devId) uint8_t* out = WH_BENCH_DATA_OUT_BUFFER; word32 outLen = WOLFHSM_CFG_BENCH_DATA_BUFFER_SIZE; + (void)client; + ret = wc_InitRng_ex(&rng, NULL, devId); if (ret != 0) { WH_BENCH_PRINTF("Failed to wc_InitRng_ex %d\n", ret); diff --git a/benchmark/bench_modules/wh_bench_mod_rsa.c b/benchmark/bench_modules/wh_bench_mod_rsa.c index 0e1433a66..6ff5edf4a 100644 --- a/benchmark/bench_modules/wh_bench_mod_rsa.c +++ b/benchmark/bench_modules/wh_bench_mod_rsa.c @@ -16,6 +16,7 @@ * You should have received a copy of the GNU General Public License * along with wolfHSM. If not, see . */ +#include #include "wh_bench_mod.h" #include "wolfhsm/wh_error.h" #include "wolfhsm/wh_client.h" @@ -384,10 +385,10 @@ int _benchRsaCrypt(whClientContext* client, whBenchOpContext* ctx, int id, goto exit; } - strcpy((char*)inBuf, inStr); + strncpy((char*)inBuf, inStr, sizeof(inBuf)-1); /* Do an initial encryption to get the size of the output */ - encSz = ret = wc_RsaPublicEncrypt(inBuf, sizeof(inStr), outBuf, + encSz = ret = wc_RsaPublicEncrypt(inBuf, strlen(inStr), outBuf, sizeof(outBuf), rsa, rng); if (ret < 0) { WH_BENCH_PRINTF("Failed to wc_RsaPublicEncrypt %d\n", ret); @@ -408,7 +409,7 @@ int _benchRsaCrypt(whClientContext* client, whBenchOpContext* ctx, int id, if (operation == RSA_PUBLIC_ENCRYPT) { benchStartRet = wh_Bench_StartOp(ctx, id); - opRet = wc_RsaPublicEncrypt(inBuf, sizeof(inStr), outBuf, + opRet = wc_RsaPublicEncrypt(inBuf, strlen(inStr), outBuf, sizeof(outBuf), rsa, rng); benchStopRet = wh_Bench_StopOp(ctx, id); } @@ -696,8 +697,6 @@ int _benchRsaSign(whClientContext* client, whBenchOpContext* ctx, int id, int _benchRsaKeyGen(whClientContext* client, whBenchOpContext* ctx, int id, int keySize, int devId) { - (void)client; - int ret = 0; RsaKey rsa[1]; WC_RNG rng[1]; @@ -706,6 +705,8 @@ int _benchRsaKeyGen(whClientContext* client, whBenchOpContext* ctx, int id, int initialized_rsa = 0; long exponent = WC_RSA_EXPONENT; /* Standard RSA exponent (65537) */ + (void)client; + /* Initialize RNG for RSA operations */ ret = wc_InitRng_ex(rng, NULL, devId); if (ret != 0) { diff --git a/benchmark/bench_modules/wh_bench_mod_sha2.c b/benchmark/bench_modules/wh_bench_mod_sha2.c index 65270d311..6da4bec77 100644 --- a/benchmark/bench_modules/wh_bench_mod_sha2.c +++ b/benchmark/bench_modules/wh_bench_mod_sha2.c @@ -34,8 +34,6 @@ int _benchSha256(whClientContext* client, whBenchOpContext* ctx, int id, int devId) { - (void)client; - int ret = 0; wc_Sha256* sha256 = NULL; wc_Sha256 sha256Stack; @@ -46,6 +44,8 @@ int _benchSha256(whClientContext* client, whBenchOpContext* ctx, int id, const uint8_t* in; size_t inLen; + (void)client; + sha256 = &sha256Stack; out = outStack; @@ -192,8 +192,6 @@ int wh_Bench_Mod_Sha256Dma(whClientContext* client, whBenchOpContext* ctx, int _benchSha224(whClientContext* client, whBenchOpContext* ctx, int id, int devId) { - (void)client; - int ret = 0; wc_Sha224 sha224[1]; uint8_t out[WC_SHA224_DIGEST_SIZE]; @@ -202,6 +200,8 @@ int _benchSha224(whClientContext* client, whBenchOpContext* ctx, int id, const uint8_t* in; size_t inLen; + (void)client; + #if defined(WOLFHSM_CFG_DMA) if (devId == WH_DEV_ID_DMA) { in = WH_BENCH_DMA_BUFFER; @@ -313,8 +313,6 @@ int wh_Bench_Mod_Sha224Dma(whClientContext* client, whBenchOpContext* ctx, int _benchSha384(whClientContext* client, whBenchOpContext* ctx, int id, int devId) { - (void)client; - int ret = 0; wc_Sha384 sha384[1]; uint8_t out[WC_SHA384_DIGEST_SIZE]; @@ -323,6 +321,8 @@ int _benchSha384(whClientContext* client, whBenchOpContext* ctx, int id, const uint8_t* in; size_t inLen; + (void)client; + #if defined(WOLFHSM_CFG_DMA) if (devId == WH_DEV_ID_DMA) { in = WH_BENCH_DMA_BUFFER; @@ -433,8 +433,6 @@ int wh_Bench_Mod_Sha384Dma(whClientContext* client, whBenchOpContext* ctx, int _benchSha512(whClientContext* client, whBenchOpContext* ctx, int id, int devId) { - (void)client; - int ret = 0; wc_Sha512 sha512[1]; uint8_t out[WC_SHA512_DIGEST_SIZE]; @@ -443,6 +441,8 @@ int _benchSha512(whClientContext* client, whBenchOpContext* ctx, int id, const uint8_t* in; size_t inLen; + (void)client; + #if defined(WOLFHSM_CFG_DMA) if (devId == WH_DEV_ID_DMA) { in = WH_BENCH_DMA_BUFFER; diff --git a/benchmark/wh_bench.c b/benchmark/wh_bench.c index 1fb979360..35cb520a5 100644 --- a/benchmark/wh_bench.c +++ b/benchmark/wh_bench.c @@ -58,7 +58,8 @@ /* Buffer sizes for transport */ /* Large enough to handle an RSA 4096 key */ #define BUFFER_SIZE \ - sizeof(whTransportMemCsr) + sizeof(whCommHeader) + WOLFHSM_CFG_COMM_DATA_LEN + (sizeof(whTransportMemCsr) + sizeof(whCommHeader) + \ + WOLFHSM_CFG_COMM_DATA_LEN) #define FLASH_RAM_SIZE (1024 * 1024) /* 1MB */ typedef struct BenchModule { @@ -826,14 +827,14 @@ static void _whBenchClientServerThreadTest(whClientConfig* c_conf, rc = pthread_create(&cthread, NULL, _whBenchClientTask, &clientData); if (rc == 0) { /* Wait for client to finish, then cancel server */ - pthread_join(cthread, &retval); - pthread_cancel(sthread); - pthread_join(sthread, &retval); + (void)pthread_join(cthread, &retval); + (void)pthread_cancel(sthread); + (void)pthread_join(sthread, &retval); } else { /* If client thread creation failed, cancel server */ - pthread_cancel(sthread); - pthread_join(sthread, &retval); + (void)pthread_cancel(sthread); + (void)pthread_join(sthread, &retval); } } } @@ -1029,19 +1030,6 @@ int wh_Bench_ClientServer_Posix(int transport, int moduleIndex) /* Server configuration/contexts */ whServerConfig s_conf[1] = {{0}}; - /* Configure transport based on type */ - ret = _configureClientTransport(transport, c_conf); - if (ret != WH_ERROR_OK) { - WH_BENCH_PRINTF("Failed to configure client transport: %d\n", ret); - return ret; - } - - ret = _configureServerTransport(transport, s_conf); - if (ret != WH_ERROR_OK) { - WH_BENCH_PRINTF("Failed to configure server transport: %d\n", ret); - return ret; - } - /* RamSim Flash state and configuration */ whFlashRamsimCtx fc[1] = {0}; whFlashRamsimCfg fc_conf[1] = {{ @@ -1076,6 +1064,19 @@ int wh_Bench_ClientServer_Posix(int transport, int moduleIndex) }}; #endif + /* Configure transport based on type */ + ret = _configureClientTransport(transport, c_conf); + if (ret != WH_ERROR_OK) { + WH_BENCH_PRINTF("Failed to configure client transport: %d\n", ret); + return ret; + } + + ret = _configureServerTransport(transport, s_conf); + if (ret != WH_ERROR_OK) { + WH_BENCH_PRINTF("Failed to configure server transport: %d\n", ret); + return ret; + } + /* Set up server configuration with NVM and crypto */ s_conf[0].nvm = nvm; #ifndef WOLFHSM_CFG_NO_CRYPTO diff --git a/benchmark/wh_bench_main.c b/benchmark/wh_bench_main.c index aca1aafea..a4dfb70d0 100644 --- a/benchmark/wh_bench_main.c +++ b/benchmark/wh_bench_main.c @@ -41,6 +41,7 @@ int main(int argc, char** argv) int transport = WH_BENCH_TRANSPORT_MEM; int moduleIndex = -1; int i; + int ret = 0; WH_BENCH_PRINTF("wolfHSM POSIX benchmark built with wolfSSL version %s\n", LIBWOLFSSL_VERSION_STRING); @@ -82,7 +83,7 @@ int main(int argc, char** argv) } #if defined(WOLFHSM_CFG_TEST_POSIX) - int ret = wh_Bench_ClientServer_Posix(transport, moduleIndex); + ret = wh_Bench_ClientServer_Posix(transport, moduleIndex); if (ret != 0) { WH_BENCH_PRINTF("Memory transport benchmark failed: %d\n", ret); return ret; diff --git a/benchmark/wh_bench_ops.c b/benchmark/wh_bench_ops.c index 509c7726e..8d810223f 100644 --- a/benchmark/wh_bench_ops.c +++ b/benchmark/wh_bench_ops.c @@ -282,6 +282,7 @@ int wh_Bench_PrintResults(whBenchOpContext* ctx) { int i; uint64_t avgTime; + char buffer[20] = {0}; if (ctx == NULL) { return WH_ERROR_BADARGS; @@ -340,33 +341,32 @@ int wh_Bench_PrintResults(whBenchOpContext* ctx) (unsigned long long)ctx->ops[i].maxTimeUs); /* Print throughput - directly using printf with formatting */ - char buffer[20] = {0}; if (ctx->ops[i].throughputType == BENCH_THROUGHPUT_XBPS) { double throughput = ctx->ops[i].throughput; if (throughput < 1024.0) { /* Bytes per second */ - WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "%.2f B/s", - throughput); + (void)WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "%.2f B/s", + throughput); } else if (throughput < 1024.0 * 1024.0) { /* Kilobytes per second */ - WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "%.2f KB/s", - throughput / 1024.0); + (void)WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "%.2f KB/s", + throughput / 1024.0); } else { /* Megabytes per second */ - WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "%.2f MB/s", - throughput / (1024.0 * 1024.0)); + (void)WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "%.2f MB/s", + throughput / (1024.0 * 1024.0)); } } else if (ctx->ops[i].throughputType == BENCH_THROUGHPUT_OPS) { - WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "%.2f ops/s", - ctx->ops[i].throughput); + (void)WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "%.2f ops/s", + ctx->ops[i].throughput); } else { /* No throughput */ - WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "N/A"); + (void)WH_BENCH_SNPRINTF(buffer, sizeof(buffer), "N/A"); } WH_BENCH_PRINTF("%-18s |\n", buffer); } diff --git a/examples/demo/client/wh_demo_client_crypto.c b/examples/demo/client/wh_demo_client_crypto.c index 58e259cb2..ba8ed7271 100644 --- a/examples/demo/client/wh_demo_client_crypto.c +++ b/examples/demo/client/wh_demo_client_crypto.c @@ -56,8 +56,6 @@ */ int wh_DemoClient_CryptoRsa(whClientContext* clientContext) { - (void)clientContext; - int ret = 0; int encSz = 0; const char plainString[] = "The quick brown fox jumps over the lazy dog."; @@ -66,8 +64,10 @@ int wh_DemoClient_CryptoRsa(whClientContext* clientContext) RsaKey rsa[1]; WC_RNG rng[1]; + (void)clientContext; + /* set the plainText to the test string */ - strcpy((char*)plainText, plainString); + strncpy((char*)plainText, plainString, sizeof(plainText)-1); /* initialize rng to make the rsa key */ ret = wc_InitRng_ex(rng, NULL, WH_DEV_ID); @@ -144,7 +144,7 @@ int wh_DemoClient_CryptoRsaImport(whClientContext* clientContext) WC_RNG rng[1]; /* set the plainText to the test string */ - strcpy((char*)plainText, plainString); + strncpy((char*)plainText, plainString, sizeof(plainText)-1); /* initialize rng to encrypt with the rsa key */ ret = wc_InitRng_ex(rng, NULL, WH_DEV_ID); @@ -243,8 +243,6 @@ int wh_DemoClient_CryptoRsaImport(whClientContext* clientContext) */ int wh_DemoClient_CryptoCurve25519(whClientContext* clientContext) { - (void)clientContext; - int ret = 0; word32 outLen; uint8_t sharedOne[CURVE25519_KEYSIZE]; @@ -254,6 +252,8 @@ int wh_DemoClient_CryptoCurve25519(whClientContext* clientContext) curve25519_key curve25519PublicKey[1]; WC_RNG rng[1]; + (void)clientContext; + /* initialize rng to make the curve25519 keys */ ret = wc_InitRng_ex(rng, NULL, WH_DEV_ID); if (ret != 0) { @@ -482,8 +482,6 @@ int wh_DemoClient_CryptoCurve25519Import(whClientContext* clientContext) */ int wh_DemoClient_CryptoEcc(whClientContext* clientContext) { - (void)clientContext; - int ret = 0; int res; word32 outLen; @@ -496,8 +494,10 @@ int wh_DemoClient_CryptoEcc(whClientContext* clientContext) byte message[sizeof(plainMessage)]; byte signature[128]; + (void)clientContext; + /* Set the message to the test string */ - strcpy((char*)message, plainMessage); + strncpy((char*)message, plainMessage, sizeof(message)-1); /* Initialize the rng to make the ecc keys */ ret = wc_InitRng_ex(rng, NULL, WH_DEV_ID); @@ -627,7 +627,7 @@ int wh_DemoClient_CryptoEccImport(whClientContext* clientContext) uint8_t keyBuf[256]; /* Set the message to the test string */ - strcpy((char*)message, plainMessage); + strncpy((char*)message, plainMessage, sizeof(message)-1); /* Initialize the rng for signature signing */ ret = wc_InitRng_ex(rng, NULL, WH_DEV_ID); @@ -823,8 +823,6 @@ int wh_DemoClient_CryptoEccImport(whClientContext* clientContext) */ int wh_DemoClient_CryptoAesCbc(whClientContext* clientContext) { - (void)clientContext; - int ret = 0; Aes aes[1]; byte key[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; @@ -832,6 +830,8 @@ int wh_DemoClient_CryptoAesCbc(whClientContext* clientContext) byte cipherText[16]; byte finalText[16]; + (void)clientContext; + /* Initialize the aes struct */ ret = wc_AesInit(aes, NULL, WH_DEV_ID); if (ret != 0) { @@ -977,8 +977,6 @@ int wh_DemoClient_CryptoAesCbcImport(whClientContext* clientContext) */ int wh_DemoClient_CryptoAesGcm(whClientContext* clientContext) { - (void)clientContext; - int ret = 0; Aes aes[1]; byte key[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; @@ -989,6 +987,8 @@ int wh_DemoClient_CryptoAesGcm(whClientContext* clientContext) byte cipherText[16]; byte finalText[16]; + (void)clientContext; + /* initialize the aes struct */ ret = wc_AesInit(aes, NULL, WH_DEV_ID); if (ret != 0) { @@ -1133,8 +1133,6 @@ int wh_DemoClient_CryptoAesGcmImport(whClientContext* clientContext) */ int wh_DemoClient_CryptoCmac(whClientContext* clientContext) { - (void)clientContext; - int ret = 0; word32 outLen; Cmac cmac[1]; @@ -1142,6 +1140,8 @@ int wh_DemoClient_CryptoCmac(whClientContext* clientContext) char message[] = "hash and verify me!"; byte tag[16]; + (void)clientContext; + /* initialize the cmac struct and set the key */ ret = wc_InitCmac_ex(cmac, key, sizeof(key), WC_CMAC_AES, NULL, NULL, WH_DEV_ID); diff --git a/examples/demo/client/wh_demo_client_nvm.c b/examples/demo/client/wh_demo_client_nvm.c index f2f3b6342..291201aed 100644 --- a/examples/demo/client/wh_demo_client_nvm.c +++ b/examples/demo/client/wh_demo_client_nvm.c @@ -16,8 +16,6 @@ */ int wh_DemoClient_Nvm(whClientContext* clientContext) { - (void)clientContext; - const int NUM_OBJECTS = 3; int32_t rc; @@ -26,6 +24,7 @@ int wh_DemoClient_Nvm(whClientContext* clientContext) uint32_t reclaimSize; whNvmId availObjects; whNvmId reclaimObjects; + int i; whNvmId objectIds[] = {1, 2, 3}; uint8_t labels[][7] = {"label1", "label2", "label3"}; @@ -34,6 +33,8 @@ int wh_DemoClient_Nvm(whClientContext* clientContext) whNvmSize dataLen = 6; whNvmSize readLen; + (void)clientContext; + if (clientContext == NULL) { WOLFHSM_CFG_PRINTF("Client context is NULL\n"); return WH_ERROR_BADARGS; @@ -50,7 +51,6 @@ int wh_DemoClient_Nvm(whClientContext* clientContext) /* Add multiple objects, reading back each one and comparing the data * against what we wrote */ - int i; for (i = 0; i < NUM_OBJECTS; i++) { /* Add an object */ rc = wh_Client_NvmAddObject( diff --git a/examples/demo/client/wh_demo_client_secboot.c b/examples/demo/client/wh_demo_client_secboot.c index 692768743..8d48c0cdb 100644 --- a/examples/demo/client/wh_demo_client_secboot.c +++ b/examples/demo/client/wh_demo_client_secboot.c @@ -128,9 +128,9 @@ static int _sha256File(const char* file_to_measure, uint8_t* hash) close(fd); if (ptr != (void*)-1) { + wc_Sha256 sha256[1]; WOLFHSM_CFG_PRINTF("Generating SHA256 of %s over %u bytes at %p\n", file_to_measure, (unsigned int)size, ptr); - wc_Sha256 sha256[1]; ret = wc_InitSha256_ex(sha256, NULL, WH_DEV_ID); if (ret == 0) { ret = wc_Sha256Update(sha256, ptr, (word32)size); @@ -256,14 +256,16 @@ int wh_DemoClient_SecBoot_Boot(whClientContext* clientContext) WOLFHSM_CFG_PRINTF("SecBoot Client starting...\n"); ret = wh_Client_CommInit(clientContext, &client_id, &server_id); if (ret == WH_ERROR_OK) { + uint8_t sig[ECC_MAX_SIG_SIZE] = {0}; + whNvmSize siglen = 0; + int32_t rc = 0; + uint8_t hash[WC_SHA256_DIGEST_SIZE] = {0}; + WOLFHSM_CFG_PRINTF("SecBoot Client connected to server id %u with client id %u\n", server_id, client_id); _showNvm(clientContext); - uint8_t sig[ECC_MAX_SIG_SIZE] = {0}; - whNvmSize siglen = 0; - int32_t rc = 0; WOLFHSM_CFG_PRINTF("SecBoot Client loading signature from NVM as nvmId %u\n", sig_nvmId); ret = wh_Client_NvmGetMetadata(clientContext, @@ -283,8 +285,6 @@ int wh_DemoClient_SecBoot_Boot(whClientContext* clientContext) } wh_Utils_Hexdump("Signature:\n", sig, siglen); - - uint8_t hash[WC_SHA256_DIGEST_SIZE] = {0}; WOLFHSM_CFG_PRINTF("Measuring image %s...\n", file_to_measure); ret = _sha256File(file_to_measure, hash); if (ret == WH_ERROR_OK) { diff --git a/examples/posix/wh_posix_client/Makefile b/examples/posix/wh_posix_client/Makefile index be0481230..d0eaa1b3f 100644 --- a/examples/posix/wh_posix_client/Makefile +++ b/examples/posix/wh_posix_client/Makefile @@ -39,7 +39,7 @@ ARCHFLAGS ?= # Enable extra C compiler warnings CFLAGS_EXTRA = -Werror -Wall -Wextra # Place functions / data into separate sections to allow unused code removal -CFLAGS_EXTRA += -ffunction-sections -fdata-sections +CFLAGS_EXTRA += -ffunction-sections -fdata-sections -Wdeclaration-after-statement # C standard to use (default to c90 if not specified) CSTD ?= -std=c90 diff --git a/examples/posix/wh_posix_client/wh_posix_client_cfg.c b/examples/posix/wh_posix_client/wh_posix_client_cfg.c index 8f54faca2..0ec429e43 100644 --- a/examples/posix/wh_posix_client/wh_posix_client_cfg.c +++ b/examples/posix/wh_posix_client/wh_posix_client_cfg.c @@ -181,9 +181,9 @@ static unsigned int psk_tls12_client_cb(WOLFSSL* ssl, const char* hint, unsigned int key_max_len) { size_t len; + const char* exampleIdentity = "PSK_EXAMPLE_CLIENT_IDENTITY"; memset(key, 0, key_max_len); - const char* exampleIdentity = "PSK_EXAMPLE_CLIENT_IDENTITY"; printf("PSK server identity hint: %s\n", hint); printf("PSK using identity: %s\n", exampleIdentity); diff --git a/examples/posix/wh_posix_server/Makefile b/examples/posix/wh_posix_server/Makefile index c5a86cd90..a3fc1e348 100644 --- a/examples/posix/wh_posix_server/Makefile +++ b/examples/posix/wh_posix_server/Makefile @@ -38,7 +38,7 @@ ARCHFLAGS ?= # Compiler and linker flags ASFLAGS ?= $(ARCHFLAGS) -CFLAGS_EXTRA ?= -Wextra +CFLAGS_EXTRA ?= -Wextra -Wdeclaration-after-statement CFLAGS ?= $(ARCHFLAGS) -Wno-cpp -std=c99 -Wall -Werror $(CFLAGS_EXTRA) LDFLAGS ?= $(ARCHFLAGS) diff --git a/examples/posix/wh_posix_server/wh_posix_server.c b/examples/posix/wh_posix_server/wh_posix_server.c index 0f0d9bca1..ddd41cd7b 100644 --- a/examples/posix/wh_posix_server/wh_posix_server.c +++ b/examples/posix/wh_posix_server/wh_posix_server.c @@ -232,11 +232,11 @@ static int wh_ServerTask(void* cf, const char* keyFilePath, int keyId, #if !defined(WOLFHSM_CFG_NO_CRYPTO) static int _hardwareCryptoCb(int devId, struct wc_CryptoInfo* info, void* ctx) { - (void)devId; - (void)ctx; - /* Default response */ int ret = CRYPTOCB_UNAVAILABLE; + + (void)devId; (void)ctx; + switch (info->algo_type) { case WC_ALGO_TYPE_RNG: { /*WOLFHSM_CFG_PRINTF("Hardware Crypto Callback: RNG operation requested\n");*/ @@ -302,6 +302,19 @@ int main(int argc, char** argv) uint8_t memory[WH_POSIX_FLASH_RAM_SIZE] = {0}; whServerConfig s_conf[1]; +#if !defined(WOLFHSM_CFG_NO_CRYPTO) + /* Crypto context */ + whServerCryptoContext crypto[1] = {{ + .devId = INVALID_DEVID, + }}; + WC_RNG rng[1]; + uint8_t buffer[128] = {0}; + +#if defined(WOLFHSM_CFG_SHE_EXTENSION) + whServerSheContext she[1] = {{0}}; +#endif +#endif /* !defined(WOLFHSM_CFG_NO_CRYPTO) */ + WOLFHSM_CFG_PRINTF("Example wolfHSM POSIX server "); #ifndef WOLFHSM_CFG_NO_CRYPTO WOLFHSM_CFG_PRINTF("built with wolfSSL version %s\n", LIBWOLFSSL_VERSION_STRING); @@ -328,9 +341,10 @@ int main(int argc, char** argv) } else if (strcmp(argv[i], "--flags") == 0 && i + 1 < argc) { char* end; - errno = 0; - unsigned long val = strtoul(argv[i + 1], &end, 0); + unsigned long val; + errno = 0; + val = strtoul(argv[i + 1], &end, 0); if (errno || *end || val > 0xFFFF) { WOLFHSM_CFG_PRINTF("Invalid --flags value: %s\n", argv[i + 1]); return -1; @@ -414,17 +428,8 @@ int main(int argc, char** argv) WOLFHSM_CFG_PRINTF("Failed to initialize NVM: %d\n", rc); return rc; } -#if !defined(WOLFHSM_CFG_NO_CRYPTO) - /* Crypto context */ - whServerCryptoContext crypto[1] = {{ - .devId = INVALID_DEVID, - }}; - -#if defined(WOLFHSM_CFG_SHE_EXTENSION) - whServerSheContext she[1] = {{0}}; -#endif - +#if !defined(WOLFHSM_CFG_NO_CRYPTO) s_conf->crypto = crypto; s_conf->devId = INVALID_DEVID; #if defined(WOLFHSM_CFG_SHE_EXTENSION) @@ -435,8 +440,6 @@ int main(int argc, char** argv) wolfCrypt_Init(); /* Context 3: Server Software Crypto */ - WC_RNG rng[1]; - uint8_t buffer[128] = {0}; wc_InitRng_ex(rng, NULL, INVALID_DEVID); wc_RNG_GenerateBlock(rng, buffer, sizeof(buffer)); wc_FreeRng(rng); diff --git a/examples/posix/wh_posix_server/wh_posix_server_cfg.c b/examples/posix/wh_posix_server/wh_posix_server_cfg.c index 754a0b821..20e47349f 100644 --- a/examples/posix/wh_posix_server/wh_posix_server_cfg.c +++ b/examples/posix/wh_posix_server/wh_posix_server_cfg.c @@ -352,14 +352,15 @@ static void stripComment(char* line) /* Function to trim leading and trailing whitespace */ static void trimWhitespace(char* str) { - /* Trim leading whitespace */ char* start = str; + char* end = start + strlen(start) - 1; + + /* Trim leading whitespace */ while (*start != '\0' && isspace((unsigned char)*start)) { start++; } /* Trim trailing whitespace */ - char* end = start + strlen(start) - 1; while (end > start && isspace((unsigned char)*end)) { *end = '\0'; end--; @@ -389,16 +390,21 @@ static int parseInteger(const char* str, uint32_t maxValue, uint32_t* result) /* Function to parse the NVM init file and build the linked list */ static void parseNvmInitFile(const char* filePath) { - FILE* file = fopen(filePath, "r"); + FILE* file = NULL; + char line[MAX_LINE_LENGTH]; + int lineNumber = 0; + + file = fopen(filePath, "r"); if (!file) { perror("Error opening NVM init file"); exit(EXIT_FAILURE); } - char line[MAX_LINE_LENGTH]; - int lineNumber = 0; - while (fgets(line, sizeof(line), file)) { + char* token; + char label[256], filePath[PATH_MAX]; + uint32_t clientId = 0, id, access, flags; + lineNumber++; stripComment(line); trimWhitespace(line); @@ -408,10 +414,6 @@ static void parseNvmInitFile(const char* filePath) continue; } - char* token; - char label[256], filePath[PATH_MAX]; - uint32_t clientId = 0, id, access, flags; - /* Check if the line defines a key or an object */ if (strncmp(line, "key", 3) == 0) { /* Parse client ID for key entries */ @@ -478,7 +480,7 @@ static void parseNvmInitFile(const char* filePath) fclose(file); exit(EXIT_FAILURE); } - snprintf(label, sizeof(label), "%s", token); + (void)snprintf(label, sizeof(label), "%s", token); /* Parse the file path */ token = strtok(NULL, " "); @@ -500,7 +502,14 @@ static void parseNvmInitFile(const char* filePath) /* Process an entry by reading the file and adding it to NVM */ static void processEntry(Entry* entry, int isKey, whNvmContext* nvmContext) { - FILE* file = fopen(entry->filePath, "rb"); + long fileSize = 0; + FILE* file = NULL; + size_t bytesRead = 0; + uint8_t* buffer = NULL; + whNvmMetadata meta = {0}; + int rc = 0; + + file = fopen(entry->filePath, "rb"); if (file == NULL) { WOLFHSM_CFG_PRINTF("Error processing entry: Unable to open file %s\n", entry->filePath); @@ -508,12 +517,12 @@ static void processEntry(Entry* entry, int isKey, whNvmContext* nvmContext) } /* Get the file size */ - fseek(file, 0, SEEK_END); - long fileSize = ftell(file); - fseek(file, 0, SEEK_SET); + (void)fseek(file, 0, SEEK_END); + fileSize = ftell(file); + (void)fseek(file, 0, SEEK_SET); /* Allocate memory for the file data */ - uint8_t* buffer = (uint8_t*)malloc(fileSize); + buffer = (uint8_t*)malloc(fileSize); if (buffer == NULL) { WOLFHSM_CFG_PRINTF("Error: Memory allocation failed for file %s\n", entry->filePath); @@ -522,7 +531,7 @@ static void processEntry(Entry* entry, int isKey, whNvmContext* nvmContext) } /* Read the file data into the buffer */ - size_t bytesRead = fread(buffer, 1, fileSize, file); + bytesRead = fread(buffer, 1, fileSize, file); fclose(file); if (bytesRead != (size_t)fileSize) { @@ -533,7 +542,6 @@ static void processEntry(Entry* entry, int isKey, whNvmContext* nvmContext) } /* Create metadata for the new entry */ - whNvmMetadata meta = {0}; if (isKey) { /* Keys have special ID format */ meta.id = WH_MAKE_KEYID(WH_KEYTYPE_CRYPTO, entry->clientId, entry->id); @@ -553,9 +561,9 @@ static void processEntry(Entry* entry, int isKey, whNvmContext* nvmContext) meta.access = entry->access; meta.flags = entry->flags; meta.len = fileSize; - snprintf((char*)meta.label, WH_NVM_LABEL_LEN, "%s", entry->label); + (void)snprintf((char*)meta.label, WH_NVM_LABEL_LEN, "%s", entry->label); - int rc = wh_Nvm_AddObject(nvmContext, &meta, fileSize, buffer); + rc = wh_Nvm_AddObject(nvmContext, &meta, fileSize, buffer); if (rc != 0) { WOLFHSM_CFG_PRINTF("Error: Failed to add entry ID %u to NVM, ret = %d\n", meta.id, rc); diff --git a/port/posix/posix_flash_file.c b/port/posix/posix_flash_file.c index 3a32c74d0..451990642 100644 --- a/port/posix/posix_flash_file.c +++ b/port/posix/posix_flash_file.c @@ -41,7 +41,7 @@ enum { }; /** Local declarations */ -#define MAX_OFFSET(_context) (_context->partition_size * 2) +#define MAX_OFFSET(_context) ((_context)->partition_size * 2) /* Helper for pwrite like memset. Write the byte in c to filedes for size * bytes starting at offset */ @@ -151,8 +151,10 @@ int posixFlashFile_WriteLock( void* c, uint32_t offset, uint32_t size) { - (void)offset; (void)size; posixFlashFileContext* context = c; + + (void)offset; (void)size; + if (context == NULL) { return WH_ERROR_BADARGS; } @@ -163,8 +165,10 @@ int posixFlashFile_WriteUnlock(void* c, uint32_t offset, uint32_t size) { - (void)offset; (void)size; posixFlashFileContext* context = c; + + (void)offset; (void)size; + if (context == NULL) { return WH_ERROR_BADARGS; } @@ -178,6 +182,8 @@ int posixFlashFile_Read( void* c, uint8_t* data) { posixFlashFileContext* context = c; + ssize_t rc = 0; + if ( (context == NULL) || (offset + size > MAX_OFFSET(context))){ return WH_ERROR_BADARGS; @@ -189,10 +195,10 @@ int posixFlashFile_Read( void* c, return 0; } - ssize_t rc = pread( context->fd_p1 - 1, - (void*) data, - (size_t) size, - (off_t) offset); + rc = pread(context->fd_p1 - 1, + (void*) data, + (size_t) size, + (off_t) offset); if (rc != size) { /* Error while reading */ return WH_ERROR_ABORTED; @@ -204,6 +210,8 @@ int posixFlashFile_Program(void* c, uint32_t offset, uint32_t size, const uint8_t* data) { posixFlashFileContext* context = c; + ssize_t rc = 0; + if ( (context == NULL) || (offset + size > MAX_OFFSET(context))){ return WH_ERROR_BADARGS; @@ -220,10 +228,10 @@ int posixFlashFile_Program(void* c, return WH_ERROR_LOCKED; } - ssize_t rc = pwrite( context->fd_p1 - 1, - (void*) data, - (size_t) size, - (off_t) offset); + rc = pwrite(context->fd_p1 - 1, + (void*) data, + (size_t) size, + (off_t) offset); if (rc != size) { /* Error while writing */ return WH_ERROR_ABORTED; @@ -277,6 +285,8 @@ int posixFlashFile_Erase(void* c, uint32_t offset, uint32_t size) { posixFlashFileContext* context = c; + ssize_t rc = 0; + if ( (context == NULL) || (offset + size > MAX_OFFSET(context))){ return WH_ERROR_BADARGS; @@ -292,10 +302,10 @@ int posixFlashFile_Erase(void* c, return WH_ERROR_LOCKED; } - ssize_t rc = pfill( context->fd_p1 - 1, - context->erased_byte, - (size_t) size, - (off_t) offset); + rc = pfill(context->fd_p1 - 1, + context->erased_byte, + (size_t) size, + (off_t) offset); if (rc != size) { /* Error while writing */ return WH_ERROR_ABORTED; diff --git a/port/posix/posix_log_file.c b/port/posix/posix_log_file.c index 764fede4a..b9bdae8c6 100644 --- a/port/posix/posix_log_file.c +++ b/port/posix/posix_log_file.c @@ -54,79 +54,81 @@ static whLogLevel posixLogFile_StringToLevel(const char* str) return WH_LOG_LEVEL_INFO; /* Default */ } -int posixLogFile_Init(void* c, const void* cf) +int posixLogFile_Init(void* context, const void* config) { - posixLogFileContext* context = c; - const posixLogFileConfig* config = cf; - int rc = 0; + posixLogFileContext* ctx = context; + const posixLogFileConfig* cfg = config; + int rc = 0; - if ((context == NULL) || (config == NULL) || (config->filename == NULL)) { + if ((ctx == NULL) || (cfg == NULL) || (cfg->filename == NULL)) { return WH_ERROR_BADARGS; } /* Initialize context */ - memset(context, 0, sizeof(*context)); - context->fd = -1; + memset(ctx, 0, sizeof(*ctx)); + ctx->fd = -1; /* Initialize mutex */ - rc = pthread_mutex_init(&context->mutex, NULL); + rc = pthread_mutex_init(&ctx->mutex, NULL); if (rc != 0) { return WH_ERROR_ABORTED; } /* Copy filename */ - strncpy(context->filename, config->filename, sizeof(context->filename) - 1); - context->filename[sizeof(context->filename) - 1] = '\0'; + strncpy(ctx->filename, cfg->filename, sizeof(ctx->filename) - 1); + ctx->filename[sizeof(ctx->filename) - 1] = '\0'; /* Open log file for append/create */ - context->fd = - open(context->filename, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); - if (context->fd < 0) { - pthread_mutex_destroy(&context->mutex); + ctx->fd = + open(ctx->filename, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); + if (ctx->fd < 0) { + (void)pthread_mutex_destroy(&ctx->mutex); return WH_ERROR_ABORTED; } - context->initialized = 1; + ctx->initialized = 1; return WH_ERROR_OK; } -int posixLogFile_Cleanup(void* c) +int posixLogFile_Cleanup(void* context) { - posixLogFileContext* context = c; + posixLogFileContext* ctx = context; - if (context == NULL) { + if (ctx == NULL) { return WH_ERROR_BADARGS; } - if (context->initialized) { - if (context->fd >= 0) { - close(context->fd); - context->fd = -1; + if (ctx->initialized) { + if (ctx->fd >= 0) { + close(ctx->fd); + ctx->fd = -1; } - pthread_mutex_destroy(&context->mutex); - context->initialized = 0; + (void)pthread_mutex_destroy(&ctx->mutex); + ctx->initialized = 0; } return WH_ERROR_OK; } -int posixLogFile_AddEntry(void* c, const whLogEntry* entry) +int posixLogFile_AddEntry(void* context, const whLogEntry* entry) { - posixLogFileContext* context = c; + posixLogFileContext* ctx = context; char buffer[1024]; int len; ssize_t bytes_written; - if ((context == NULL) || (entry == NULL)) { + if ((ctx == NULL) || (entry == NULL)) { return WH_ERROR_BADARGS; } - if (!context->initialized || context->fd < 0) { + if (!ctx->initialized || ctx->fd < 0) { return WH_ERROR_ABORTED; } /* Lock mutex */ - pthread_mutex_lock(&context->mutex); + if (pthread_mutex_lock(&ctx->mutex) != 0) { + return WH_ERROR_ABORTED; + } /* Format log entry: TIMESTAMP|LEVEL|FILE:LINE|FUNCTION|MESSAGE\n */ len = snprintf(buffer, sizeof(buffer), "%llu|%s|%s:%u|%s|%.*s\n", @@ -137,15 +139,15 @@ int posixLogFile_AddEntry(void* c, const whLogEntry* entry) entry->msg); if (len < 0 || (size_t)len >= sizeof(buffer)) { - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); return WH_ERROR_ABORTED; } /* Write to file */ - bytes_written = write(context->fd, buffer, len); + bytes_written = write(ctx->fd, buffer, len); /* Unlock mutex */ - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); if (bytes_written != len) { return WH_ERROR_ABORTED; @@ -154,19 +156,20 @@ int posixLogFile_AddEntry(void* c, const whLogEntry* entry) return WH_ERROR_OK; } -int posixLogFile_Export(void* c, void* export_arg) +int posixLogFile_Export(void* context, void* export_arg) { - posixLogFileContext* context = c; + posixLogFileContext* ctx = context; FILE* out_fp = (FILE*)export_arg; FILE* in_fp = NULL; char line[2048]; int ret = 0; + int fd_dup = -1; - if (context == NULL) { + if (ctx == NULL) { return WH_ERROR_BADARGS; } - if (!context->initialized || context->fd < 0) { + if (!ctx->initialized || ctx->fd < 0) { return WH_ERROR_ABORTED; } @@ -176,18 +179,20 @@ int posixLogFile_Export(void* c, void* export_arg) } /* Lock mutex */ - pthread_mutex_lock(&context->mutex); + if (pthread_mutex_lock(&ctx->mutex) != 0) { + return WH_ERROR_ABORTED; + } /* Flush any pending writes */ - if (fsync(context->fd) != 0) { - pthread_mutex_unlock(&context->mutex); + if (fsync(ctx->fd) != 0) { + (void)pthread_mutex_unlock(&ctx->mutex); return WH_ERROR_ABORTED; } /* Open file for reading (using fdopen with dup'd fd) */ - int fd_dup = dup(context->fd); + fd_dup = dup(ctx->fd); if (fd_dup < 0) { - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); return WH_ERROR_ABORTED; } @@ -197,7 +202,7 @@ int posixLogFile_Export(void* c, void* export_arg) in_fp = fdopen(fd_dup, "r"); if (in_fp == NULL) { close(fd_dup); - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); return WH_ERROR_ABORTED; } @@ -212,39 +217,43 @@ int posixLogFile_Export(void* c, void* export_arg) fclose(in_fp); /* Also closes fd_dup */ /* Unlock mutex */ - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); return ret; } -int posixLogFile_Iterate(void* c, whLogIterateCb iterate_cb, void* iterate_arg) +int posixLogFile_Iterate(void* context, whLogIterateCb iterate_cb, + void* iterate_arg) { - posixLogFileContext* context = c; + posixLogFileContext* ctx = context; FILE* fp = NULL; char line[2048]; int ret = 0; + int fd_dup = -1; - if ((context == NULL) || (iterate_cb == NULL)) { + if ((ctx == NULL) || (iterate_cb == NULL)) { return WH_ERROR_BADARGS; } - if (!context->initialized || context->fd < 0) { + if (!ctx->initialized || ctx->fd < 0) { return WH_ERROR_ABORTED; } /* Lock mutex */ - pthread_mutex_lock(&context->mutex); + if (pthread_mutex_lock(&ctx->mutex) != 0) { + return WH_ERROR_ABORTED; + } /* Flush any pending writes */ - if (fsync(context->fd) != 0) { - pthread_mutex_unlock(&context->mutex); + if (fsync(ctx->fd) != 0) { + (void)pthread_mutex_unlock(&ctx->mutex); return WH_ERROR_ABORTED; } /* Open file for reading (using fdopen with dup'd fd) */ - int fd_dup = dup(context->fd); + fd_dup = dup(ctx->fd); if (fd_dup < 0) { - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); return WH_ERROR_ABORTED; } @@ -254,7 +263,7 @@ int posixLogFile_Iterate(void* c, whLogIterateCb iterate_cb, void* iterate_arg) fp = fdopen(fd_dup, "r"); if (fp == NULL) { close(fd_dup); - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); return WH_ERROR_ABORTED; } @@ -267,13 +276,14 @@ int posixLogFile_Iterate(void* c, whLogIterateCb iterate_cb, void* iterate_arg) char msg_buf[WOLFHSM_CFG_LOG_MSG_MAX]; unsigned long long timestamp; unsigned int line_num; + int parsed = 0; memset(&entry, 0, sizeof(entry)); /* Parse: TIMESTAMP|LEVEL|FILE:LINE|FUNCTION|MESSAGE\n */ - int parsed = sscanf(line, "%llu|%31[^|]|%255[^:]:%u|%255[^|]|%255[^\n]", - ×tamp, level_str, file_buf, &line_num, - func_buf, msg_buf); + parsed = sscanf(line, "%llu|%31[^|]|%255[^:]:%u|%255[^|]|%255[^\n]", + ×tamp, level_str, file_buf, &line_num, + func_buf, msg_buf); /* Minimum number of fields to parse is 5, msg is optional */ if (parsed >= 5) { @@ -300,41 +310,43 @@ int posixLogFile_Iterate(void* c, whLogIterateCb iterate_cb, void* iterate_arg) fclose(fp); /* Also closes fd_dup */ /* Unlock mutex */ - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); return ret; } -int posixLogFile_Clear(void* c) +int posixLogFile_Clear(void* context) { - posixLogFileContext* context = c; + posixLogFileContext* ctx = context; int ret = 0; - if (context == NULL) { + if (ctx == NULL) { return WH_ERROR_BADARGS; } - if (!context->initialized || context->fd < 0) { + if (!ctx->initialized || ctx->fd < 0) { return WH_ERROR_ABORTED; } /* Lock mutex */ - pthread_mutex_lock(&context->mutex); + if (pthread_mutex_lock(&ctx->mutex) != 0) { + return WH_ERROR_ABORTED; + } /* Truncate file to zero length */ - if (ftruncate(context->fd, 0) != 0) { + if (ftruncate(ctx->fd, 0) != 0) { ret = WH_ERROR_ABORTED; } /* Seek to beginning */ if (ret == 0) { - if (lseek(context->fd, 0, SEEK_SET) < 0) { + if (lseek(ctx->fd, 0, SEEK_SET) < 0) { ret = WH_ERROR_ABORTED; } } /* Unlock mutex */ - pthread_mutex_unlock(&context->mutex); + (void)pthread_mutex_unlock(&ctx->mutex); return ret; } diff --git a/port/posix/posix_transport_shm.c b/port/posix/posix_transport_shm.c index 7a2f6f76d..23e9ff5a9 100644 --- a/port/posix/posix_transport_shm.c +++ b/port/posix/posix_transport_shm.c @@ -400,7 +400,7 @@ int posixTransportShm_ServerInit(void* c, const void* cf, if (ret == WH_ERROR_OK) { memset(ctx, 0, sizeof(*ctx)); - snprintf(ctx->name, sizeof(ctx->name), "%s", config->name); + (void)snprintf(ctx->name, sizeof(ctx->name), "%s", config->name); ctx->connectcb = connectcb; ctx->connectcb_arg = connectcb_arg; @@ -446,7 +446,7 @@ int posixTransportShm_ClientInit(void* c, const void* cf, } memset(ctx, 0, sizeof(*ctx)); - snprintf(ctx->name, sizeof(ctx->name), "%s", config->name); + (void)snprintf(ctx->name, sizeof(ctx->name), "%s", config->name); ctx->connectcb = connectcb; ctx->connectcb_arg = connectcb_arg; diff --git a/port/posix/posix_transport_tcp.c b/port/posix/posix_transport_tcp.c index 9e652d4f8..bab9d8577 100644 --- a/port/posix/posix_transport_tcp.c +++ b/port/posix/posix_transport_tcp.c @@ -110,6 +110,7 @@ static int posixTransportTcp_Send(int fd, uint16_t* buffer_offset, int send_size = 0; uint32_t* packet_len = (uint32_t*)&(buffer[0]); void* packet_data = &(buffer[sizeof(uint32_t)]); + int remaining_size = 0; if ( (fd < 0) || (buffer_offset == NULL) || @@ -127,7 +128,7 @@ static int posixTransportTcp_Send(int fd, uint16_t* buffer_offset, memcpy(packet_data, data, size); send_size = sizeof(uint32_t) + size; } - int remaining_size = send_size - *buffer_offset; + remaining_size = send_size - *buffer_offset; rc = send(fd, &(buffer[*buffer_offset]), remaining_size, MSG_NOSIGNAL); diff --git a/src/wh_client_cert.c b/src/wh_client_cert.c index d233da5e8..8d772693b 100644 --- a/src/wh_client_cert.c +++ b/src/wh_client_cert.c @@ -279,9 +279,10 @@ int wh_Client_CertEraseTrusted(whClientContext* c, whNvmId id, int32_t* out_rc) int wh_Client_CertReadTrustedRequest(whClientContext* c, whNvmId id, uint32_t cert_len) { - (void)cert_len; whMessageCert_ReadTrustedRequest req = {0}; + (void)cert_len; + if (c == NULL) { return WH_ERROR_BADARGS; } diff --git a/src/wh_client_crypto.c b/src/wh_client_crypto.c index 6e2518fba..e6fd8932e 100644 --- a/src/wh_client_crypto.c +++ b/src/wh_client_crypto.c @@ -185,11 +185,17 @@ static int _getCryptoResponse(uint8_t* respBuf, uint16_t type, /** Implementations */ int wh_Client_RngGenerate(whClientContext* ctx, uint8_t* out, uint32_t size) { - int ret = WH_ERROR_OK; - whMessageCrypto_RngRequest* req; - whMessageCrypto_RngResponse* res; - uint8_t* dataPtr; - uint8_t* reqData; + int ret = WH_ERROR_OK; + whMessageCrypto_RngRequest* req = NULL; + whMessageCrypto_RngResponse* res = NULL; + uint8_t* dataPtr = NULL; + uint8_t* reqData = NULL; + + /* Calculate maximum data size client can request (subtract headers) */ + const uint32_t client_max_data = + WOLFHSM_CFG_COMM_DATA_LEN - + sizeof(whMessageCrypto_GenericRequestHeader) - + sizeof(whMessageCrypto_RngRequest); if (ctx == NULL) { return WH_ERROR_BADARGS; @@ -207,12 +213,6 @@ int wh_Client_RngGenerate(whClientContext* ctx, uint8_t* out, uint32_t size) /* Setup request header */ req = (whMessageCrypto_RngRequest*)reqData; - /* Calculate maximum data size client can request (subtract headers) */ - const uint32_t client_max_data = - WOLFHSM_CFG_COMM_DATA_LEN - - sizeof(whMessageCrypto_GenericRequestHeader) - - sizeof(whMessageCrypto_RngRequest); - while ((size > 0) && (ret == WH_ERROR_OK)) { /* Request Message */ uint16_t group = WH_MESSAGE_GROUP_CRYPTO; @@ -341,43 +341,46 @@ int wh_Client_RngGenerateDma(whClientContext* ctx, uint8_t* out, uint32_t size) int wh_Client_AesCtr(whClientContext* ctx, Aes* aes, int enc, const uint8_t* in, uint32_t len, uint8_t* out) { - int ret = WH_ERROR_OK; - whMessageCrypto_AesCtrRequest* req; - whMessageCrypto_AesCtrResponse* res; - uint8_t* dataPtr; - - if ((ctx == NULL) || (aes == NULL) || (in == NULL) || (out == NULL)) { - return WH_ERROR_BADARGS; - } - - uint32_t key_len = aes->keylen; - const uint8_t* key = (const uint8_t*)(aes->devKey); - whKeyId key_id = WH_DEVCTX_TO_KEYID(aes->devCtx); - uint8_t* iv = (uint8_t*)aes->reg; - uint32_t iv_len = AES_IV_SIZE; - uint32_t left = aes->left; - uint8_t* tmp = (uint8_t*)aes->tmp; + int ret = WH_ERROR_OK; + whMessageCrypto_AesCtrRequest* req = NULL; + whMessageCrypto_AesCtrResponse* res = NULL; + uint8_t* dataPtr = NULL; + uint32_t key_len = aes->keylen; + const uint8_t* key = (const uint8_t*)(aes->devKey); + whKeyId key_id = WH_DEVCTX_TO_KEYID(aes->devCtx); + uint8_t* iv = (uint8_t*)aes->reg; + uint32_t iv_len = AES_IV_SIZE; + uint32_t left = aes->left; + uint8_t* tmp = (uint8_t*)aes->tmp; + uint8_t* req_in = NULL; + uint8_t* req_key = NULL; + uint8_t* req_iv = NULL; + uint8_t* req_tmp = NULL; + uint64_t req_len = 0; uint16_t group = WH_MESSAGE_GROUP_CRYPTO; uint16_t action = WC_ALGO_TYPE_CIPHER; uint16_t type = WC_CIPHER_AES_CTR; + if ((ctx == NULL) || (aes == NULL) || (in == NULL) || (out == NULL)) { + return WH_ERROR_BADARGS; + } + /* Get data buffer */ dataPtr = wh_CommClient_GetDataPtr(ctx->comm); if (dataPtr == NULL) { return WH_ERROR_BADARGS; } /* Setup generic header and get pointer to request data */ - req = (whMessageCrypto_AesCtrRequest*)_createCryptoRequest( - dataPtr, WC_CIPHER_AES_CTR); - uint8_t* req_in = (uint8_t*)(req + 1); - uint8_t* req_key = req_in + len; - uint8_t* req_iv = req_key + key_len; - uint8_t* req_tmp = req_iv + iv_len; - uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + len + key_len + iv_len + - AES_BLOCK_SIZE; - WH_DEBUG_CLIENT_VERBOSE("enc:%d keylen:%d ivsz:%d insz:%d reqsz:%u " + req = (whMessageCrypto_AesCtrRequest*)_createCryptoRequest( + dataPtr, WC_CIPHER_AES_CTR); + req_in = (uint8_t*)(req + 1); + req_key = req_in + len; + req_iv = req_key + key_len; + req_tmp = req_iv + iv_len; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + len + key_len + iv_len + AES_BLOCK_SIZE; + WH_DEBUG_CLIENT_VERBOSE("enc:%d keylen:%d ivsz:%d insz:%d reqsz:%lu " "left:%d\n", enc, key_len, iv_len, len, req_len, left); if (req_len > WOLFHSM_CFG_COMM_DATA_LEN) { @@ -454,15 +457,18 @@ int wh_Client_AesCtrDma(whClientContext* ctx, Aes* aes, int enc, uint8_t* dataPtr = NULL; uintptr_t inAddr = 0; uintptr_t outAddr = 0; + const uint8_t* key = NULL; + uint8_t* iv = (uint8_t*)aes->reg; + uint8_t* tmp = (uint8_t*)aes->tmp; + uint8_t* req_iv = NULL; + uint8_t* req_tmp = NULL; + uint8_t* req_key = NULL; + uint16_t req_len = 0; uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; uint16_t action = WC_ALGO_TYPE_CIPHER; uint16_t type = WC_CIPHER_AES_CTR; - const uint8_t* key = NULL; - uint8_t* iv = (uint8_t*)aes->reg; - uint8_t* tmp = (uint8_t*)aes->tmp; - if (ctx == NULL || aes == NULL || in == NULL || out == NULL ) { return WH_ERROR_BADARGS; } @@ -474,13 +480,13 @@ int wh_Client_AesCtrDma(whClientContext* ctx, Aes* aes, int enc, } /* Setup generic header and get pointer to request data */ - req = (whMessageCrypto_AesCtrDmaRequest*)_createCryptoRequest( - dataPtr, WC_CIPHER_AES_CTR); - uint8_t* req_iv = (uint8_t*)req + sizeof(whMessageCrypto_AesCtrDmaRequest); - uint8_t* req_tmp = req_iv + AES_IV_SIZE; - uint8_t* req_key = req_tmp + AES_BLOCK_SIZE; - uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + AES_IV_SIZE + AES_BLOCK_SIZE; + req = (whMessageCrypto_AesCtrDmaRequest*)_createCryptoRequest( + dataPtr, WC_CIPHER_AES_CTR); + req_iv = (uint8_t*)req + sizeof(whMessageCrypto_AesCtrDmaRequest); + req_tmp = req_iv + AES_IV_SIZE; + req_key = req_tmp + AES_BLOCK_SIZE; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + AES_IV_SIZE + AES_BLOCK_SIZE; /* Setup request packet */ memset(req, 0, sizeof(*req)); @@ -590,9 +596,19 @@ int wh_Client_AesEcb(whClientContext* ctx, Aes* aes, int enc, const uint8_t* in, { int ret = WH_ERROR_OK; uint16_t blocks = len / AES_BLOCK_SIZE; - whMessageCrypto_AesEcbRequest* req; - whMessageCrypto_AesEcbResponse* res; - uint8_t* dataPtr; + whMessageCrypto_AesEcbRequest* req = NULL; + whMessageCrypto_AesEcbResponse* res = NULL; + uint8_t* dataPtr = NULL; + uint32_t key_len = aes->keylen; + const uint8_t* key = (const uint8_t*)(aes->devKey); + whKeyId key_id = WH_DEVCTX_TO_KEYID(aes->devCtx); + uint8_t* req_in = NULL; + uint8_t* req_key = NULL; + uint64_t req_len = 0; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO; + uint16_t action = WC_ALGO_TYPE_CIPHER; + uint16_t type = WC_CIPHER_AES_ECB; if (blocks == 0) { /* Nothing to do. */ @@ -604,27 +620,19 @@ int wh_Client_AesEcb(whClientContext* ctx, Aes* aes, int enc, const uint8_t* in, return WH_ERROR_BADARGS; } - uint32_t key_len = aes->keylen; - const uint8_t* key = (const uint8_t*)(aes->devKey); - whKeyId key_id = WH_DEVCTX_TO_KEYID(aes->devCtx); - - uint16_t group = WH_MESSAGE_GROUP_CRYPTO; - uint16_t action = WC_ALGO_TYPE_CIPHER; - uint16_t type = WC_CIPHER_AES_ECB; - /* Get data buffer */ dataPtr = wh_CommClient_GetDataPtr(ctx->comm); if (dataPtr == NULL) { return WH_ERROR_BADARGS; } + /* Setup generic header and get pointer to request data */ req = (whMessageCrypto_AesEcbRequest*)_createCryptoRequest( dataPtr, WC_CIPHER_AES_ECB); - uint8_t* req_in = (uint8_t*)(req + 1); - uint8_t* req_key = req_in + len; - uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + len + key_len; - + req_in = (uint8_t*)(req + 1); + req_key = req_in + len; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + len + key_len; WH_DEBUG_CLIENT_VERBOSE("enc:%d keylen:%d insz:%d reqsz:%u blocks:%u \n", enc, (int)key_len, (int)len, (unsigned int)req_len, @@ -683,12 +691,13 @@ int wh_Client_AesEcbDma(whClientContext* ctx, Aes* aes, int enc, uint8_t* dataPtr = NULL; uintptr_t inAddr = 0; uintptr_t outAddr = 0; + const uint8_t* key = NULL; + uint8_t* req_key = NULL; + uint16_t req_len = 0; - uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; - uint16_t action = WC_ALGO_TYPE_CIPHER; - uint16_t type = WC_CIPHER_AES_ECB; - - const uint8_t* key = NULL; + uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; + uint16_t action = WC_ALGO_TYPE_CIPHER; + uint16_t type = WC_CIPHER_AES_ECB; if (ctx == NULL || aes == NULL || in == NULL || out == NULL) { return WH_ERROR_BADARGS; @@ -706,10 +715,9 @@ int wh_Client_AesEcbDma(whClientContext* ctx, Aes* aes, int enc, /* Setup generic header and get pointer to request data */ req = (whMessageCrypto_AesEcbDmaRequest*)_createCryptoRequest( - dataPtr, WC_CIPHER_AES_ECB); - uint8_t* req_key = (uint8_t*)req + sizeof(whMessageCrypto_AesEcbDmaRequest); - uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req); + dataPtr, WC_CIPHER_AES_ECB); + req_key = (uint8_t*)req + sizeof(whMessageCrypto_AesEcbDmaRequest); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); /* Setup request packet */ memset(req, 0, sizeof(*req)); @@ -800,11 +808,24 @@ int wh_Client_AesEcbDma(whClientContext* ctx, Aes* aes, int enc, int wh_Client_AesCbc(whClientContext* ctx, Aes* aes, int enc, const uint8_t* in, uint32_t len, uint8_t* out) { - int ret = WH_ERROR_OK; - uint16_t blocks = len / AES_BLOCK_SIZE; - whMessageCrypto_AesCbcRequest* req; - whMessageCrypto_AesCbcResponse* res; - uint8_t* dataPtr; + int ret = WH_ERROR_OK; + uint16_t blocks = len / AES_BLOCK_SIZE; + whMessageCrypto_AesCbcRequest* req = NULL; + whMessageCrypto_AesCbcResponse* res = NULL; + uint8_t* dataPtr = NULL; + uint32_t key_len = aes->keylen; + const uint8_t* key = (const uint8_t*)(aes->devKey); + whKeyId key_id = WH_DEVCTX_TO_KEYID(aes->devCtx); + uint8_t* iv = (uint8_t*)aes->reg; + uint32_t iv_len = AES_IV_SIZE; + uint8_t* req_in = NULL; + uint8_t* req_key = NULL; + uint8_t* req_iv = NULL; + uint64_t req_len = 0; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO; + uint16_t action = WC_ALGO_TYPE_CIPHER; + uint16_t type = WC_CIPHER_AES_CBC; if (blocks == 0) { /* Nothing to do. */ @@ -816,29 +837,19 @@ int wh_Client_AesCbc(whClientContext* ctx, Aes* aes, int enc, const uint8_t* in, return WH_ERROR_BADARGS; } - uint32_t key_len = aes->keylen; - const uint8_t* key = (const uint8_t*)(aes->devKey); - whKeyId key_id = WH_DEVCTX_TO_KEYID(aes->devCtx); - uint8_t* iv = (uint8_t*)aes->reg; - uint32_t iv_len = AES_IV_SIZE; - - uint16_t group = WH_MESSAGE_GROUP_CRYPTO; - uint16_t action = WC_ALGO_TYPE_CIPHER; - uint16_t type = WC_CIPHER_AES_CBC; - /* Get data buffer */ dataPtr = wh_CommClient_GetDataPtr(ctx->comm); if (dataPtr == NULL) { return WH_ERROR_BADARGS; } /* Setup generic header and get pointer to request data */ - req = (whMessageCrypto_AesCbcRequest*)_createCryptoRequest( - dataPtr, WC_CIPHER_AES_CBC); - uint8_t* req_in = (uint8_t*)(req + 1); - uint8_t* req_key = req_in + len; - uint8_t* req_iv = req_key + key_len; - uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + len + key_len + iv_len; + req = (whMessageCrypto_AesCbcRequest*)_createCryptoRequest( + dataPtr, WC_CIPHER_AES_CBC); + req_in = (uint8_t*)(req + 1); + req_key = req_in + len; + req_iv = req_key + key_len; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + len + key_len + iv_len; WH_DEBUG_CLIENT_VERBOSE("enc:%d keylen:%d ivsz:%d insz:%d reqsz:%u " "blocks:%u\n", @@ -906,14 +917,16 @@ int wh_Client_AesCbcDma(whClientContext* ctx, Aes* aes, int enc, uint8_t* dataPtr = NULL; uintptr_t inAddr = 0; uintptr_t outAddr = 0; + const uint8_t* key = NULL; + uint8_t* iv = (uint8_t*)aes->reg; + uint8_t* req_iv = NULL; + uint8_t* req_key = NULL; + uint16_t req_len = 0; uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; uint16_t action = WC_ALGO_TYPE_CIPHER; uint16_t type = WC_CIPHER_AES_CBC; - const uint8_t* key = NULL; - uint8_t* iv = (uint8_t*)aes->reg; - if (ctx == NULL || aes == NULL || in == NULL || out == NULL) { return WH_ERROR_BADARGS; } @@ -929,12 +942,12 @@ int wh_Client_AesCbcDma(whClientContext* ctx, Aes* aes, int enc, } /* Setup generic header and get pointer to request data */ - req = (whMessageCrypto_AesCbcDmaRequest*)_createCryptoRequest( - dataPtr, WC_CIPHER_AES_CBC); - uint8_t* req_iv = (uint8_t*)req + sizeof(whMessageCrypto_AesCbcDmaRequest); - uint8_t* req_key = req_iv + AES_IV_SIZE; - uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + AES_IV_SIZE; + req = (whMessageCrypto_AesCbcDmaRequest*)_createCryptoRequest( + dataPtr, WC_CIPHER_AES_CBC); + req_iv = (uint8_t*)req + sizeof(whMessageCrypto_AesCbcDmaRequest); + req_key = req_iv + AES_IV_SIZE; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + AES_IV_SIZE; /* Setup request packet */ memset(req, 0, sizeof(*req)); @@ -1036,7 +1049,24 @@ int wh_Client_AesGcm(whClientContext* ctx, Aes* aes, int enc, const uint8_t* in, const uint8_t* dec_tag, uint8_t* enc_tag, uint32_t tag_len, uint8_t* out) { - int ret = WH_ERROR_OK; + int ret = WH_ERROR_OK; + whMessageCrypto_AesGcmRequest* req = NULL; + whMessageCrypto_AesGcmResponse* res = NULL; + uint8_t* dataPtr = NULL; + uint32_t key_len = aes->keylen; + const uint8_t* key = (const uint8_t*)(aes->devKey); + whKeyId key_id = WH_DEVCTX_TO_KEYID(aes->devCtx); + uint8_t* req_in = NULL; + uint8_t* req_key = NULL; + uint8_t* req_iv = NULL; + uint8_t* req_authin = NULL; + uint8_t* req_tag = NULL; + uint64_t req_len = 0; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO; + uint16_t action = WC_ALGO_TYPE_CIPHER; + uint16_t type = WC_CIPHER_AES_GCM; + if ((ctx == NULL) || (aes == NULL) || ((in == NULL) && (len > 0)) || ((iv == NULL) && (iv_len > 0)) || @@ -1045,35 +1075,23 @@ int wh_Client_AesGcm(whClientContext* ctx, Aes* aes, int enc, const uint8_t* in, return WH_ERROR_BADARGS; } - uint16_t group = WH_MESSAGE_GROUP_CRYPTO; - uint16_t action = WC_ALGO_TYPE_CIPHER; - uint16_t type = WC_CIPHER_AES_GCM; - - uint32_t key_len = aes->keylen; - const uint8_t* key = (const uint8_t*)(aes->devKey); - whKeyId key_id = WH_DEVCTX_TO_KEYID(aes->devCtx); - - /* Get data buffer */ - uint8_t* dataPtr = wh_CommClient_GetDataPtr(ctx->comm); + dataPtr = wh_CommClient_GetDataPtr(ctx->comm); if (dataPtr == NULL) { return WH_ERROR_BADARGS; } /* Setup generic header and get pointer to request data */ - whMessageCrypto_AesGcmRequest* req = - (whMessageCrypto_AesGcmRequest*)_createCryptoRequest(dataPtr, - WC_CIPHER_AES_GCM); - - uint8_t* req_in = (uint8_t*)(req + 1); - uint8_t* req_key = req_in + len; - uint8_t* req_iv = req_key + key_len; - uint8_t* req_authin = req_iv + iv_len; - uint8_t* req_tag = req_authin + authin_len; - - uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + len + key_len + iv_len + authin_len + - ((enc == 0) ? tag_len : 0); + req = (whMessageCrypto_AesGcmRequest*)_createCryptoRequest( + dataPtr, WC_CIPHER_AES_GCM); + req_in = (uint8_t*)(req + 1); + req_key = req_in + len; + req_iv = req_key + key_len; + req_authin = req_iv + iv_len; + req_tag = req_authin + authin_len; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + len + key_len + iv_len + authin_len + + ((enc == 0) ? tag_len : 0); WH_DEBUG_CLIENT_VERBOSE("AESGCM: enc:%d keylen:%d ivsz:%d insz:%d authinsz:%d " "authtagsz:%d reqsz:%u\n", @@ -1131,7 +1149,6 @@ int wh_Client_AesGcm(whClientContext* ctx, Aes* aes, int enc, const uint8_t* in, if (ret == WH_ERROR_OK) { /* Get response */ - whMessageCrypto_AesGcmResponse* res; ret = _getCryptoResponse(dataPtr, type, (uint8_t**)&res); /* wolfCrypt allows positive error codes on success in some * scenarios */ @@ -1177,19 +1194,23 @@ int wh_Client_AesGcmDma(whClientContext* ctx, Aes* aes, int enc, uint32_t authin_len, const uint8_t* dec_tag, uint8_t* enc_tag, uint32_t tag_len, uint8_t* out) { - int ret = WH_ERROR_OK; - whMessageCrypto_AesGcmDmaRequest* req = NULL; - uint8_t* dataPtr = NULL; - uintptr_t inAddr = 0; - uintptr_t outAddr = 0; - uintptr_t aadAddr = 0; + int ret = WH_ERROR_OK; + whMessageCrypto_AesGcmDmaRequest* req = NULL; + whMessageCrypto_AesGcmDmaResponse* res = NULL; + uint8_t* dataPtr = NULL; + uintptr_t inAddr = 0; + uintptr_t outAddr = 0; + uintptr_t aadAddr = 0; + const uint8_t* key = NULL; + uint8_t* req_iv = NULL; + uint8_t* req_tag = NULL; + uint8_t* req_key = NULL; + uint64_t req_len = 0; uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; uint16_t action = WC_ALGO_TYPE_CIPHER; uint16_t type = WC_CIPHER_AES_GCM; - const uint8_t* key = NULL; - if (ctx == NULL || aes == NULL) { return WH_ERROR_BADARGS; } @@ -1217,13 +1238,13 @@ int wh_Client_AesGcmDma(whClientContext* ctx, Aes* aes, int enc, } /* Setup generic header and get pointer to request data */ - req = (whMessageCrypto_AesGcmDmaRequest*)_createCryptoRequest( - dataPtr, WC_CIPHER_AES_GCM); - uint8_t* req_iv = (uint8_t*)req + sizeof(whMessageCrypto_AesGcmDmaRequest); - uint8_t* req_tag = req_iv + iv_len; - uint8_t* req_key = req_tag + (enc != 0 ? 0 : tag_len); - uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + iv_len + (enc != 0 ? 0 : tag_len); + req = (whMessageCrypto_AesGcmDmaRequest*)_createCryptoRequest( + dataPtr, WC_CIPHER_AES_GCM); + req_iv = (uint8_t*)req + sizeof(whMessageCrypto_AesGcmDmaRequest); + req_tag = req_iv + iv_len; + req_key = req_tag + (enc != 0 ? 0 : tag_len); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + iv_len + (enc != 0 ? 0 : tag_len); /* Setup request packet */ memset(req, 0, sizeof(*req)); @@ -1306,7 +1327,6 @@ int wh_Client_AesGcmDma(whClientContext* ctx, Aes* aes, int enc, if (ret == WH_ERROR_OK) { /* Get response */ - whMessageCrypto_AesGcmDmaResponse* res; ret = _getCryptoResponse(dataPtr, type, (uint8_t**)&res); /* wolfCrypt allows positive error codes on success in some * scenarios */ @@ -1648,12 +1668,10 @@ int wh_Client_EccSharedSecret(whClientContext* ctx, ecc_key* priv_key, (unsigned int)req->privateKeyId, (unsigned int)req->publicKeyId); if (ret == WH_ERROR_OK) { + uint16_t res_len; /* Server will evict. Reset our flags */ pub_evict = prv_evict = 0; - /* Response Message */ - uint16_t res_len; - /* Recv Response */ do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, @@ -1741,7 +1759,7 @@ int wh_Client_EccSign(whClientContext* ctx, ecc_key* key, const uint8_t* hash, uint16_t group = WH_MESSAGE_GROUP_CRYPTO; uint16_t action = WC_ALGO_TYPE_PK; - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + + uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + hash_len; uint32_t options = 0; @@ -1784,12 +1802,10 @@ int wh_Client_EccSign(whClientContext* ctx, ecc_key* key, const uint8_t* hash, ret = wh_Client_SendRequest(ctx, group, action, req_len, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point. Reset evict */ evict = 0; - /* Response Message */ - uint16_t res_len = 0; - /* Recv Response */ do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, @@ -1883,7 +1899,7 @@ int wh_Client_EccVerify(whClientContext* ctx, ecc_key* key, const uint8_t* sig, uint16_t action = WC_ALGO_TYPE_PK; uint32_t options = 0; - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + + uint32_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(whMessageCrypto_EccVerifyRequest) + sig_len + hash_len; @@ -1939,10 +1955,9 @@ int wh_Client_EccVerify(whClientContext* ctx, ecc_key* key, const uint8_t* sig, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point. Reset evict */ evict = 0; - /* Response Message */ - uint16_t res_len = 0; /* Recv Response */ do { @@ -2454,6 +2469,11 @@ static int _Ed25519MakeKey(whClientContext* ctx, whKeyId* inout_key_id, uint8_t* dataPtr = NULL; whMessageCrypto_Ed25519KeyGenRequest* req = NULL; whMessageCrypto_Ed25519KeyGenResponse* res = NULL; + uint16_t req_len = 0; + uint16_t res_len = 0; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO; + uint16_t action = WC_ALGO_TYPE_PK; if (ctx == NULL || ((label_len != 0) && (label == NULL))) { return WH_ERROR_BADARGS; @@ -2469,12 +2489,9 @@ static int _Ed25519MakeKey(whClientContext* ctx, whKeyId* inout_key_id, } req = (whMessageCrypto_Ed25519KeyGenRequest*)_createCryptoRequest( - dataPtr, WC_PK_TYPE_ED25519_KEYGEN); + dataPtr, WC_PK_TYPE_ED25519_KEYGEN); - uint16_t group = WH_MESSAGE_GROUP_CRYPTO; - uint16_t action = WC_ALGO_TYPE_PK; - uint16_t req_len = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); if (req_len > WOLFHSM_CFG_COMM_DATA_LEN) { return WH_ERROR_BADARGS; @@ -2495,7 +2512,7 @@ static int _Ed25519MakeKey(whClientContext* ctx, whKeyId* inout_key_id, if (ret != WH_ERROR_OK) { return ret; } - uint16_t res_len = 0; + do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, (uint8_t*)dataPtr); @@ -2564,8 +2581,15 @@ int wh_Client_Ed25519Sign(whClientContext* ctx, ed25519_key* key, whMessageCrypto_Ed25519SignResponse* res = NULL; uint8_t* dataPtr = NULL; - whKeyId key_id = WH_DEVCTX_TO_KEYID(key->devCtx); - int evict = 0; + whKeyId key_id = WH_DEVCTX_TO_KEYID(key->devCtx); + int evict = 0; + uint64_t req_len = 0; + uint8_t* req_msg = NULL; + uint8_t* req_ctx = NULL; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO; + uint16_t action = WC_ALGO_TYPE_PK; + uint32_t options = 0; if ((ctx == NULL) || (key == NULL) || ((msg == NULL) && (msgLen > 0)) || ((sig != NULL) && (inout_sig_len == NULL)) || @@ -2584,8 +2608,8 @@ int wh_Client_Ed25519Sign(whClientContext* ctx, ed25519_key* key, return WH_ERROR_BADARGS; } - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + msgLen + contextLen; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + msgLen + contextLen; if (req_len > WOLFHSM_CFG_COMM_DATA_LEN) { return WH_ERROR_BADARGS; } @@ -2602,20 +2626,15 @@ int wh_Client_Ed25519Sign(whClientContext* ctx, ed25519_key* key, } if (ret == WH_ERROR_OK) { - uint16_t group = WH_MESSAGE_GROUP_CRYPTO; - uint16_t action = WC_ALGO_TYPE_PK; - uint32_t options = 0; - dataPtr = wh_CommClient_GetDataPtr(ctx->comm); if (dataPtr == NULL) { return WH_ERROR_BADARGS; } - req = (whMessageCrypto_Ed25519SignRequest*)_createCryptoRequest( - dataPtr, WC_PK_TYPE_ED25519_SIGN); - - uint8_t* req_msg = (uint8_t*)(req + 1); - uint8_t* req_ctx = req_msg + msgLen; + req = (whMessageCrypto_Ed25519SignRequest*)_createCryptoRequest( + dataPtr, WC_PK_TYPE_ED25519_SIGN); + req_msg = (uint8_t*)(req + 1); + req_ctx = req_msg + msgLen; if (evict != 0) { options |= WH_MESSAGE_CRYPTO_ED25519_SIGN_OPTIONS_EVICT; @@ -2637,10 +2656,10 @@ int wh_Client_Ed25519Sign(whClientContext* ctx, ed25519_key* key, ret = wh_Client_SendRequest(ctx, group, action, req_len, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point. Reset evict */ evict = 0; - uint16_t res_len = 0; do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, (uint8_t*)dataPtr); @@ -2699,10 +2718,17 @@ int wh_Client_Ed25519Verify(whClientContext* ctx, ed25519_key* key, whMessageCrypto_Ed25519VerifyRequest* req = NULL; whMessageCrypto_Ed25519VerifyResponse* res = NULL; uint8_t* dataPtr = NULL; + whKeyId key_id = WH_DEVCTX_TO_KEYID(key->devCtx); int evict = 0; - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + sigLen + msgLen + contextLen; + uint8_t* req_sig = NULL; + uint8_t* req_msg = NULL; + uint8_t* req_ctx = NULL; + uint64_t req_len = 0; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO; + uint16_t action = WC_ALGO_TYPE_PK; + uint32_t options = 0; if ((ctx == NULL) || (key == NULL) || (sig == NULL) || (msg == NULL) || (out_res == NULL) || ((context == NULL) && (contextLen > 0))) { @@ -2720,6 +2746,8 @@ int wh_Client_Ed25519Verify(whClientContext* ctx, ed25519_key* key, return WH_ERROR_BADARGS; } + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + sigLen + msgLen + contextLen; if (req_len > WOLFHSM_CFG_COMM_DATA_LEN) { return WH_ERROR_BADARGS; } @@ -2738,21 +2766,16 @@ int wh_Client_Ed25519Verify(whClientContext* ctx, ed25519_key* key, } if (ret == WH_ERROR_OK) { - uint16_t group = WH_MESSAGE_GROUP_CRYPTO; - uint16_t action = WC_ALGO_TYPE_PK; - uint32_t options = 0; - dataPtr = wh_CommClient_GetDataPtr(ctx->comm); if (dataPtr == NULL) { return WH_ERROR_BADARGS; } - req = (whMessageCrypto_Ed25519VerifyRequest*)_createCryptoRequest( - dataPtr, WC_PK_TYPE_ED25519_VERIFY); - - uint8_t* req_sig = (uint8_t*)(req + 1); - uint8_t* req_msg = req_sig + sigLen; - uint8_t* req_ctx = req_msg + msgLen; + req = (whMessageCrypto_Ed25519VerifyRequest*)_createCryptoRequest( + dataPtr, WC_PK_TYPE_ED25519_VERIFY); + req_sig = (uint8_t*)(req + 1); + req_msg = req_sig + sigLen; + req_ctx = req_msg + msgLen; if (evict != 0) { options |= WH_MESSAGE_CRYPTO_ED25519_VERIFY_OPTIONS_EVICT; @@ -2775,10 +2798,10 @@ int wh_Client_Ed25519Verify(whClientContext* ctx, ed25519_key* key, ret = wh_Client_SendRequest(ctx, group, action, req_len, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point. Reset evict */ evict = 0; - uint16_t res_len = 0; do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, (uint8_t*)dataPtr); @@ -2831,6 +2854,12 @@ int wh_Client_Ed25519SignDma(whClientContext* ctx, ed25519_key* key, whKeyId key_id = WH_DEVCTX_TO_KEYID(key->devCtx); int evict = 0; uint32_t inSigLen = (inout_sig_len != NULL) ? *inout_sig_len : 0; + uint64_t req_len = 0; + uint8_t* req_ctx = NULL; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; + uint16_t action = WC_ALGO_TYPE_PK; + uint32_t options = 0; if ((ctx == NULL) || (key == NULL) || ((msg == NULL) && (msgLen > 0)) || (sig == NULL) || (inout_sig_len == NULL) || @@ -2849,8 +2878,8 @@ int wh_Client_Ed25519SignDma(whClientContext* ctx, ed25519_key* key, return WH_ERROR_BADARGS; } - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + contextLen; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + contextLen; if (req_len > WOLFHSM_CFG_COMM_DATA_LEN) { return WH_ERROR_BADARGS; } @@ -2867,19 +2896,14 @@ int wh_Client_Ed25519SignDma(whClientContext* ctx, ed25519_key* key, } if (ret == WH_ERROR_OK) { - uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; - uint16_t action = WC_ALGO_TYPE_PK; - uint32_t options = 0; - dataPtr = wh_CommClient_GetDataPtr(ctx->comm); if (dataPtr == NULL) { return WH_ERROR_BADARGS; } - req = (whMessageCrypto_Ed25519SignDmaRequest*)_createCryptoRequest( - dataPtr, WC_PK_TYPE_ED25519_SIGN); - - uint8_t* req_ctx = (uint8_t*)(req + 1); + req = (whMessageCrypto_Ed25519SignDmaRequest*)_createCryptoRequest( + dataPtr, WC_PK_TYPE_ED25519_SIGN); + req_ctx = (uint8_t*)(req + 1); if (evict != 0) { options |= WH_MESSAGE_CRYPTO_ED25519_SIGN_OPTIONS_EVICT; @@ -2912,9 +2936,9 @@ int wh_Client_Ed25519SignDma(whClientContext* ctx, ed25519_key* key, (uint8_t*)dataPtr); } if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; evict = 0; - uint16_t res_len = 0; do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, (uint8_t*)dataPtr); @@ -2975,10 +2999,15 @@ int wh_Client_Ed25519VerifyDma(whClientContext* ctx, ed25519_key* key, uint8_t* dataPtr = NULL; uintptr_t sigAddr = 0; uintptr_t msgAddr = 0; - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + contextLen; - whKeyId key_id = WH_DEVCTX_TO_KEYID(key->devCtx); - int evict = 0; + + uint64_t req_len = 0; + whKeyId key_id = WH_DEVCTX_TO_KEYID(key->devCtx); + int evict = 0; + uint8_t* req_ctx = NULL; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; + uint16_t action = WC_ALGO_TYPE_PK; + uint32_t options = 0; if ((ctx == NULL) || (key == NULL) || (sig == NULL) || (msg == NULL) || (out_res == NULL) || ((context == NULL) && (contextLen > 0))) { @@ -2996,6 +3025,8 @@ int wh_Client_Ed25519VerifyDma(whClientContext* ctx, ed25519_key* key, return WH_ERROR_BADARGS; } + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + contextLen; if (req_len > WOLFHSM_CFG_COMM_DATA_LEN) { return WH_ERROR_BADARGS; } @@ -3014,19 +3045,14 @@ int wh_Client_Ed25519VerifyDma(whClientContext* ctx, ed25519_key* key, } if (ret == WH_ERROR_OK) { - uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; - uint16_t action = WC_ALGO_TYPE_PK; - uint32_t options = 0; - dataPtr = wh_CommClient_GetDataPtr(ctx->comm); if (dataPtr == NULL) { return WH_ERROR_BADARGS; } - req = (whMessageCrypto_Ed25519VerifyDmaRequest*)_createCryptoRequest( - dataPtr, WC_PK_TYPE_ED25519_VERIFY); - - uint8_t* req_ctx = (uint8_t*)(req + 1); + req = (whMessageCrypto_Ed25519VerifyDmaRequest*)_createCryptoRequest( + dataPtr, WC_PK_TYPE_ED25519_VERIFY); + req_ctx = (uint8_t*)(req + 1); if (evict != 0) { options |= WH_MESSAGE_CRYPTO_ED25519_VERIFY_OPTIONS_EVICT; @@ -3059,9 +3085,9 @@ int wh_Client_Ed25519VerifyDma(whClientContext* ctx, ed25519_key* key, (uint8_t*)dataPtr); } if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; evict = 0; - uint16_t res_len = 0; do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, (uint8_t*)dataPtr); @@ -3201,6 +3227,7 @@ static int _RsaMakeKey(whClientContext* ctx, uint32_t size, uint32_t e, uint16_t group = WH_MESSAGE_GROUP_CRYPTO; uint16_t action = WC_ALGO_TYPE_PK; whKeyId key_id = WH_KEYID_ERASED; + uint16_t req_len = 0; if (ctx == NULL) { return WH_ERROR_BADARGS; @@ -3213,11 +3240,9 @@ static int _RsaMakeKey(whClientContext* ctx, uint32_t size, uint32_t e, } /* Setup generic header and get pointer to request data */ - req = (whMessageCrypto_RsaKeyGenRequest*)_createCryptoRequest( - dataPtr, WC_PK_TYPE_RSA_KEYGEN); - - uint16_t req_len = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req = (whMessageCrypto_RsaKeyGenRequest*)_createCryptoRequest( + dataPtr, WC_PK_TYPE_RSA_KEYGEN); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); /* Use the supplied key id if provided */ if (inout_key_id != NULL) { @@ -3327,8 +3352,14 @@ int wh_Client_RsaFunction(whClientContext* ctx, RsaKey* key, int rsa_type, uint8_t* dataPtr = NULL; /* Transaction state */ - whKeyId key_id; - int evict = 0; + whKeyId key_id = WH_DEVCTX_TO_KEYID(key->devCtx); + int evict = 0; + uint8_t* req_in = NULL; + uint32_t req_len = 0; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO; + uint16_t action = WC_ALGO_TYPE_PK; + uint32_t options = 0; WH_DEBUG_CLIENT_VERBOSE("ctx:%p key:%p, rsa_type:%d in:%p in_len:%u, out:%p " "inout_out_len:%p\n", @@ -3340,8 +3371,6 @@ int wh_Client_RsaFunction(whClientContext* ctx, RsaKey* key, int rsa_type, return WH_ERROR_BADARGS; } - key_id = WH_DEVCTX_TO_KEYID(key->devCtx); - WH_DEBUG_CLIENT_VERBOSE("key_id:%x\n", key_id); /* Import key if necessary */ @@ -3378,16 +3407,11 @@ int wh_Client_RsaFunction(whClientContext* ctx, RsaKey* key, int rsa_type, return WH_ERROR_BADARGS; } - req = (whMessageCrypto_RsaRequest*)_createCryptoRequest(dataPtr, - WC_PK_TYPE_RSA); - - uint16_t group = WH_MESSAGE_GROUP_CRYPTO; - uint16_t action = WC_ALGO_TYPE_PK; - - uint8_t* req_in = (uint8_t*)(req + 1); - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + in_len; - uint32_t options = 0; + req = (whMessageCrypto_RsaRequest*)_createCryptoRequest( + dataPtr, WC_PK_TYPE_RSA); + req_in = (uint8_t*)(req + 1); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + in_len; if (req_len <= WOLFHSM_CFG_COMM_DATA_LEN) { if (evict != 0) { @@ -3409,9 +3433,9 @@ int wh_Client_RsaFunction(whClientContext* ctx, RsaKey* key, int rsa_type, ret = wh_Client_SendRequest(ctx, group, action, req_len, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point. Reset evict */ evict = 0; - uint16_t res_len = 0; /* Recv Response */ do { @@ -3462,8 +3486,8 @@ int wh_Client_RsaGetSize(whClientContext* ctx, const RsaKey* key, int* out_size) int ret = WH_ERROR_OK; /* Transaction state */ - whKeyId key_id; - int evict = 0; + whKeyId key_id = WH_DEVCTX_TO_KEYID(key->devCtx); + int evict = 0; WH_DEBUG_CLIENT_VERBOSE("ctx:%p key:%p, out_size:%p \n", ctx, key, out_size); @@ -3472,8 +3496,6 @@ int wh_Client_RsaGetSize(whClientContext* ctx, const RsaKey* key, int* out_size) return WH_ERROR_BADARGS; } - key_id = WH_DEVCTX_TO_KEYID(key->devCtx); - /* Import key if necessary */ if (WH_KEYID_ISERASED(key_id)) { /* Must import the key to the server and evict it afterwards */ @@ -3521,9 +3543,9 @@ int wh_Client_RsaGetSize(whClientContext* ctx, const RsaKey* key, int* out_size) ret = wh_Client_SendRequest(ctx, group, action, req_len, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point. Reset evict */ evict = 0; - uint16_t res_len = 0; /* Recv Response */ do { @@ -3576,6 +3598,8 @@ static int _HkdfMakeKey(whClientContext* ctx, int hashType, whKeyId keyIdIn, uint16_t group = WH_MESSAGE_GROUP_CRYPTO; uint16_t action = WC_ALGO_TYPE_KDF; whKeyId key_id = WH_KEYID_ERASED; + uint64_t req_len = 0; + uint8_t* req_ptr = NULL; if ((ctx == NULL) || ((inKey == NULL) && (inKeySz != 0))) { return WH_ERROR_BADARGS; @@ -3592,8 +3616,11 @@ static int _HkdfMakeKey(whClientContext* ctx, int hashType, whKeyId keyIdIn, dataPtr, WC_ALGO_TYPE_KDF, WC_KDF_TYPE_HKDF); /* Calculate request length including variable-length data */ - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + inKeySz + saltSz + infoSz; + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + inKeySz + saltSz + infoSz; + if (req_len > WOLFHSM_CFG_COMM_DATA_LEN) { + return WH_ERROR_BADARGS; + } /* Use the supplied key id if provided */ if (inout_key_id != NULL) { @@ -3620,23 +3647,23 @@ static int _HkdfMakeKey(whClientContext* ctx, int hashType, whKeyId keyIdIn, } /* Copy variable-length data after the request structure */ - uint8_t* data_ptr = (uint8_t*)(req + 1); + req_ptr = (uint8_t*)(req + 1); /* Copy input key material */ if ((inKey != NULL) && (inKeySz > 0)) { - memcpy(data_ptr, inKey, inKeySz); - data_ptr += inKeySz; + memcpy(req_ptr, inKey, inKeySz); + req_ptr += inKeySz; } /* Copy salt if provided */ if (salt != NULL && saltSz > 0) { - memcpy(data_ptr, salt, saltSz); - data_ptr += saltSz; + memcpy(req_ptr, salt, saltSz); + req_ptr += saltSz; } /* Copy info if provided */ if (info != NULL && infoSz > 0) { - memcpy(data_ptr, info, infoSz); + memcpy(req_ptr, info, infoSz); } /* Send Request */ @@ -3742,6 +3769,9 @@ static int _CmacKdfMakeKey(whClientContext* ctx, whKeyId saltKeyId, uint16_t group = WH_MESSAGE_GROUP_CRYPTO; uint16_t action = WC_ALGO_TYPE_KDF; whKeyId key_id = WH_KEYID_ERASED; + uint64_t req_len = 0; + uint16_t res_len = 0; + uint8_t* req_ptr = NULL; if ((ctx == NULL) || (outSz == 0)) { return WH_ERROR_BADARGS; @@ -3762,13 +3792,11 @@ static int _CmacKdfMakeKey(whClientContext* ctx, whKeyId saltKeyId, req = (whMessageCrypto_CmacKdfRequest*)_createCryptoRequestWithSubtype( dataPtr, WC_ALGO_TYPE_KDF, WC_KDF_TYPE_TWOSTEP_CMAC); - uint32_t total_len = sizeof(whMessageCrypto_GenericRequestHeader) + - sizeof(*req) + saltSz + zSz + fixedInfoSz; - - if (total_len > WOLFHSM_CFG_COMM_DATA_LEN) { + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + + saltSz + zSz + fixedInfoSz; + if (req_len > WOLFHSM_CFG_COMM_DATA_LEN) { return WH_ERROR_BADARGS; } - uint16_t req_len = (uint16_t)total_len; if (inout_key_id != NULL) { key_id = *inout_key_id; @@ -3791,32 +3819,31 @@ static int _CmacKdfMakeKey(whClientContext* ctx, whKeyId saltKeyId, memcpy(req->label, label, label_len); } - uint8_t* payload = (uint8_t*)(req + 1); + req_ptr = (uint8_t*)(req + 1); if (saltSz > 0 && salt != NULL) { - memcpy(payload, salt, saltSz); - payload += saltSz; + memcpy(req_ptr, salt, saltSz); + req_ptr += saltSz; } if (zSz > 0 && z != NULL) { - memcpy(payload, z, zSz); - payload += zSz; + memcpy(req_ptr, z, zSz); + req_ptr += zSz; } if (fixedInfoSz > 0 && fixedInfo != NULL) { - memcpy(payload, fixedInfo, fixedInfoSz); - payload += fixedInfoSz; + memcpy(req_ptr, fixedInfo, fixedInfoSz); + req_ptr += fixedInfoSz; } /* squash unused warning */ - (void)payload; + (void)req_ptr; ret = wh_Client_SendRequest(ctx, group, action, req_len, dataPtr); if (ret != WH_ERROR_OK) { return ret; } - uint16_t res_len = 0; do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, dataPtr); } while (ret == WH_ERROR_NOTREADY); @@ -3928,14 +3955,18 @@ int wh_Client_Cmac(whClientContext* ctx, Cmac* cmac, CmacType type, whMessageCrypto_CmacAesResponse* res = NULL; uint8_t* dataPtr = NULL; + whKeyId key_id = WH_DEVCTX_TO_KEYID(cmac->devCtx); + uint64_t req_len = 0; + uint8_t* req_in = NULL; + uint8_t* req_key = NULL; + uint32_t hdr_sz = 0; + uint32_t mac_len = + ((outMac == NULL) || (outMacLen == NULL)) ? 0 : *outMacLen; + if (ctx == NULL || cmac == NULL) { return WH_ERROR_BADARGS; } - whKeyId key_id = WH_DEVCTX_TO_KEYID(cmac->devCtx); - uint32_t mac_len = - ((outMac == NULL) || (outMacLen == NULL)) ? 0 : *outMacLen; - /* For non-HSM keys on incremental calls (update/final with no key argument * provided), send the stored key bytes so the server can reconstruct the * CMAC context */ @@ -3964,19 +3995,17 @@ int wh_Client_Cmac(whClientContext* ctx, Cmac* cmac, CmacType type, } /* Setup generic header and get pointer to request data */ - req = (whMessageCrypto_CmacAesRequest*)_createCryptoRequest( - dataPtr, WC_ALGO_TYPE_CMAC); - - uint8_t* req_in = (uint8_t*)(req + 1); - uint8_t* req_key = req_in + inLen; - uint32_t hdr_sz = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req = (whMessageCrypto_CmacAesRequest*)_createCryptoRequest( + dataPtr, WC_ALGO_TYPE_CMAC); + req_in = (uint8_t*)(req + 1); + req_key = req_in + inLen; + hdr_sz = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); if (inLen > WOLFHSM_CFG_COMM_DATA_LEN - hdr_sz || keyLen > WOLFHSM_CFG_COMM_DATA_LEN - hdr_sz - inLen) { return WH_ERROR_BADARGS; } - uint16_t req_len = hdr_sz + inLen + keyLen; + req_len = hdr_sz + inLen + keyLen; /* Setup request packet */ req->inSz = inLen; @@ -3998,6 +4027,7 @@ int wh_Client_Cmac(whClientContext* ctx, Cmac* cmac, CmacType type, /* Send request */ ret = wh_Client_SendRequest(ctx, group, action, req_len, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Update the local type since call succeeded */ cmac->type = type; @@ -4007,8 +4037,6 @@ int wh_Client_Cmac(whClientContext* ctx, Cmac* cmac, CmacType type, cmac->aes.keylen = keyLen; } - - uint16_t res_len = 0; do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, (uint8_t*)dataPtr); @@ -4026,10 +4054,10 @@ int wh_Client_Cmac(whClientContext* ctx, Cmac* cmac, CmacType type, /* Copy out finalized CMAC if present */ if (ret == 0 && outMac != NULL && outMacLen != NULL) { + uint8_t* res_mac = (uint8_t*)(res + 1); if (res->outSz < *outMacLen) { *outMacLen = res->outSz; } - uint8_t* res_mac = (uint8_t*)(res + 1); memcpy(outMac, res_mac, *outMacLen); } } @@ -4052,14 +4080,17 @@ int wh_Client_CmacDma(whClientContext* ctx, Cmac* cmac, CmacType type, uint8_t* dataPtr = NULL; uintptr_t inAddr = 0; + whKeyId key_id = WH_DEVCTX_TO_KEYID(cmac->devCtx); + uint64_t req_len = 0; + uint8_t* req_key = NULL; + uint32_t hdr_sz = 0; + uint32_t mac_len = + ((outMac == NULL) || (outMacLen == NULL)) ? 0 : *outMacLen; + if (ctx == NULL || cmac == NULL) { return WH_ERROR_BADARGS; } - whKeyId key_id = WH_DEVCTX_TO_KEYID(cmac->devCtx); - uint32_t mac_len = - ((outMac == NULL) || (outMacLen == NULL)) ? 0 : *outMacLen; - /* For non-HSM keys on subsequent calls (no key provided), send the * stored key bytes so the server can reconstruct the CMAC context */ if (key == NULL && keyLen == 0 && WH_KEYID_ISERASED(key_id) && @@ -4091,14 +4122,13 @@ int wh_Client_CmacDma(whClientContext* ctx, Cmac* cmac, CmacType type, dataPtr, WC_ALGO_TYPE_CMAC); memset(req, 0, sizeof(*req)); - uint8_t* req_key = (uint8_t*)(req + 1); - uint32_t hdr_sz = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req_key = (uint8_t*)(req + 1); + hdr_sz = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); if (keyLen > WOLFHSM_CFG_COMM_DATA_LEN - hdr_sz) { return WH_ERROR_BADARGS; } - uint16_t req_len = hdr_sz + keyLen; + req_len = hdr_sz + keyLen; /* Setup request fields */ req->outSz = mac_len; @@ -4132,6 +4162,7 @@ int wh_Client_CmacDma(whClientContext* ctx, Cmac* cmac, CmacType type, } if (ret == WH_ERROR_OK) { + uint16_t respSz = 0; /* Update the local type since call succeeded */ cmac->type = type; @@ -4141,7 +4172,6 @@ int wh_Client_CmacDma(whClientContext* ctx, Cmac* cmac, CmacType type, cmac->aes.keylen = keyLen; } - uint16_t respSz = 0; do { ret = wh_Client_RecvResponse(ctx, NULL, NULL, &respSz, (uint8_t*)dataPtr); @@ -4158,10 +4188,10 @@ int wh_Client_CmacDma(whClientContext* ctx, Cmac* cmac, CmacType type, /* Copy out finalized CMAC if present */ if (ret == 0 && outMac != NULL && outMacLen != NULL) { + uint8_t* res_mac = (uint8_t*)(res + 1); if (res->outSz < *outMacLen) { *outMacLen = res->outSz; } - uint8_t* res_mac = (uint8_t*)(res + 1); memcpy(outMac, res_mac, *outMacLen); } } @@ -4194,6 +4224,7 @@ static int _xferSha256BlockAndUpdateDigest(whClientContext* ctx, whMessageCrypto_Sha256Request* req = NULL; whMessageCrypto_Sha2Response* res = NULL; uint8_t* dataPtr = NULL; + uint16_t req_len = 0; /* Get data buffer */ dataPtr = wh_CommClient_GetDataPtr(ctx->comm); @@ -4226,8 +4257,7 @@ static int _xferSha256BlockAndUpdateDigest(whClientContext* ctx, req->resumeState.hiLen = sha256->hiLen; req->resumeState.loLen = sha256->loLen; - uint32_t req_len = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); ret = wh_Client_SendRequest(ctx, group, WC_ALGO_TYPE_HASH, req_len, (uint8_t*)dataPtr); @@ -4481,6 +4511,7 @@ static int _xferSha224BlockAndUpdateDigest(whClientContext* ctx, whMessageCrypto_Sha256Request* req = NULL; whMessageCrypto_Sha2Response* res = NULL; uint8_t* dataPtr = NULL; + uint16_t req_len = 0; /* Get data buffer */ dataPtr = wh_CommClient_GetDataPtr(ctx->comm); @@ -4513,8 +4544,7 @@ static int _xferSha224BlockAndUpdateDigest(whClientContext* ctx, req->resumeState.hiLen = sha224->hiLen; req->resumeState.loLen = sha224->loLen; - uint32_t req_len = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); ret = wh_Client_SendRequest(ctx, group, WC_ALGO_TYPE_HASH, req_len, (uint8_t*)dataPtr); @@ -4762,6 +4792,7 @@ static int _xferSha384BlockAndUpdateDigest(whClientContext* ctx, whMessageCrypto_Sha512Request* req = NULL; whMessageCrypto_Sha2Response* res = NULL; uint8_t* dataPtr = NULL; + uint16_t req_len = 0; /* Get data buffer */ dataPtr = wh_CommClient_GetDataPtr(ctx->comm); @@ -4794,8 +4825,7 @@ static int _xferSha384BlockAndUpdateDigest(whClientContext* ctx, req->resumeState.hiLen = sha384->hiLen; req->resumeState.loLen = sha384->loLen; - uint32_t req_len = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); ret = wh_Client_SendRequest(ctx, group, WC_ALGO_TYPE_HASH, req_len, (uint8_t*)dataPtr); @@ -5044,6 +5074,7 @@ static int _xferSha512BlockAndUpdateDigest(whClientContext* ctx, whMessageCrypto_Sha512Request* req = NULL; whMessageCrypto_Sha2Response* res = NULL; uint8_t* dataPtr = NULL; + uint16_t req_len = 0; /* Get data buffer */ dataPtr = wh_CommClient_GetDataPtr(ctx->comm); @@ -5076,8 +5107,7 @@ static int _xferSha512BlockAndUpdateDigest(whClientContext* ctx, req->resumeState.hiLen = sha512->hiLen; req->resumeState.loLen = sha512->loLen; req->resumeState.hashType = sha512->hashType; - uint32_t req_len = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); ret = wh_Client_SendRequest(ctx, group, WC_ALGO_TYPE_HASH, req_len, (uint8_t*)dataPtr); @@ -5586,7 +5616,7 @@ int wh_Client_MlDsaSign(whClientContext* ctx, const byte* in, word32 in_len, uint16_t group = WH_MESSAGE_GROUP_CRYPTO; uint16_t action = WC_ALGO_TYPE_PK; - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + + uint64_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + in_len; uint32_t options = 0; @@ -5621,12 +5651,10 @@ int wh_Client_MlDsaSign(whClientContext* ctx, const byte* in, word32 in_len, ret = wh_Client_SendRequest(ctx, group, action, req_len, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point. Reset evict */ evict = 0; - /* Response Message */ - uint16_t res_len = 0; - /* Recv Response */ do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, @@ -5714,7 +5742,7 @@ int wh_Client_MlDsaVerify(whClientContext* ctx, const byte* sig, word32 sig_len, uint16_t action = WC_ALGO_TYPE_PK; uint32_t options = 0; - uint16_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + + uint64_t req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req) + sig_len + msg_len; @@ -5757,10 +5785,9 @@ int wh_Client_MlDsaVerify(whClientContext* ctx, const byte* sig, word32 sig_len, (uint8_t*)dataPtr); if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point. Reset evict */ evict = 0; - /* Response Message */ - uint16_t res_len = 0; /* Recv Response */ do { @@ -5875,6 +5902,10 @@ static int _MlDsaMakeKeyDma(whClientContext* ctx, int level, whMessageCrypto_MlDsaKeyGenDmaResponse* res = NULL; uintptr_t keyAddr = 0; uint64_t keyAddrSz = 0; + uint16_t req_len = 0; + + uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; + uint16_t action = WC_ALGO_TYPE_PK; if (ctx == NULL) { return WH_ERROR_BADARGS; @@ -5897,11 +5928,7 @@ static int _MlDsaMakeKeyDma(whClientContext* ctx, int level, } /* Request Message */ - uint16_t group = WH_MESSAGE_GROUP_CRYPTO_DMA; - uint16_t action = WC_ALGO_TYPE_PK; - - uint16_t req_len = - sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); + req_len = sizeof(whMessageCrypto_GenericRequestHeader) + sizeof(*req); if (req_len <= WOLFHSM_CFG_COMM_DATA_LEN) { memset(req, 0, sizeof(*req)); @@ -6083,12 +6110,10 @@ int wh_Client_MlDsaSignDma(whClientContext* ctx, const byte* in, word32 in_len, (uint8_t*)dataPtr); } if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point if requested */ evict = 0; - /* Response Message */ - uint16_t res_len = 0; - /* Recv Response */ do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, @@ -6218,12 +6243,10 @@ int wh_Client_MlDsaVerifyDma(whClientContext* ctx, const byte* sig, (uint8_t*)dataPtr); } if (ret == WH_ERROR_OK) { + uint16_t res_len = 0; /* Server will evict at this point if requested */ evict = 0; - /* Response Message */ - uint16_t res_len = 0; - /* Recv Response */ do { ret = wh_Client_RecvResponse(ctx, &group, &action, &res_len, diff --git a/src/wh_client_keywrap.c b/src/wh_client_keywrap.c index 9b75ba5a5..2c2aec53f 100644 --- a/src/wh_client_keywrap.c +++ b/src/wh_client_keywrap.c @@ -100,12 +100,12 @@ int wh_Client_KeyWrapResponse(whClientContext* ctx, int wh_Client_KeyWrap(whClientContext* ctx, enum wc_CipherType cipherType, uint16_t serverKeyId, void* keyIn, uint16_t keySz, whNvmMetadata* metadataIn, void* wrappedKeyOut, - uint16_t* wrappedKeySz) + uint16_t* wrappedKeyInOutSz) { int ret = WH_ERROR_OK; if (ctx == NULL || keyIn == NULL || metadataIn == NULL || - wrappedKeyOut == NULL || wrappedKeySz == NULL) { + wrappedKeyOut == NULL || wrappedKeyInOutSz == NULL) { return WH_ERROR_BADARGS; } @@ -117,7 +117,7 @@ int wh_Client_KeyWrap(whClientContext* ctx, enum wc_CipherType cipherType, do { ret = wh_Client_KeyWrapResponse(ctx, cipherType, wrappedKeyOut, - wrappedKeySz); + wrappedKeyInOutSz); } while (ret == WH_ERROR_NOTREADY); return ret; diff --git a/src/wh_flash_ramsim.c b/src/wh_flash_ramsim.c index e364be992..ac2f546df 100644 --- a/src/wh_flash_ramsim.c +++ b/src/wh_flash_ramsim.c @@ -226,11 +226,11 @@ uint32_t whFlashRamsim_PartitionSize(void* context) int whFlashRamsim_WriteLock(void* context, uint32_t offset, uint32_t size) { + whFlashRamsimCtx* ctx = (whFlashRamsimCtx*)context; + (void)offset; (void)size; - whFlashRamsimCtx* ctx = (whFlashRamsimCtx*)context; - if (ctx == NULL) { return WH_ERROR_BADARGS; } @@ -243,9 +243,10 @@ int whFlashRamsim_WriteLock(void* context, uint32_t offset, uint32_t size) int whFlashRamsim_WriteUnlock(void* context, uint32_t offset, uint32_t size) { + whFlashRamsimCtx* ctx = (whFlashRamsimCtx*)context; + (void)offset; (void)size; - whFlashRamsimCtx* ctx = (whFlashRamsimCtx*)context; if (ctx == NULL) { return WH_ERROR_BADARGS; diff --git a/src/wh_flash_unit.c b/src/wh_flash_unit.c index 78989bb65..7a65eae3b 100644 --- a/src/wh_flash_unit.c +++ b/src/wh_flash_unit.c @@ -122,6 +122,7 @@ int wh_FlashUnit_BlankCheck(const whFlashCb* cb, void* context, int wh_FlashUnit_Erase(const whFlashCb* cb, void* context, uint32_t offset, uint32_t count) { + int ret = 0; uint32_t byte_offset = offset * WHFU_BYTES_PER_UNIT; uint32_t byte_count = count * WHFU_BYTES_PER_UNIT; @@ -133,7 +134,7 @@ int wh_FlashUnit_Erase(const whFlashCb* cb, void* context, if (count == 0) return 0; - int ret = cb->Erase(context, byte_offset, byte_count); + ret = cb->Erase(context, byte_offset, byte_count); if (ret == 0) { ret = cb->BlankCheck(context, byte_offset, byte_count); @@ -206,9 +207,6 @@ int wh_FlashUnit_ProgramBytes(const whFlashCb* cb, void* context, whFlashUnitBuffer buffer = {0}; uint32_t offset = byte_offset / WHFU_BYTES_PER_UNIT; - /* Unaligned writes are skipped */ - data += byte_offset % WHFU_BYTES_PER_UNIT; - uint32_t count = byte_count / WHFU_BYTES_PER_UNIT; uint32_t rem = byte_count % WHFU_BYTES_PER_UNIT; @@ -216,6 +214,9 @@ int wh_FlashUnit_ProgramBytes(const whFlashCb* cb, void* context, return WH_ERROR_BADARGS; } + /* Unaligned writes are skipped */ + data += byte_offset % WHFU_BYTES_PER_UNIT; + /* Aligned programming */ if(count) { ret = wh_FlashUnit_Program(cb, context, diff --git a/src/wh_log.c b/src/wh_log.c index 1023df0c5..e4135a792 100644 --- a/src/wh_log.c +++ b/src/wh_log.c @@ -51,13 +51,13 @@ const char* wh_Log_LevelToString(whLogLevel level) } void wh_Log_AddMsg(whLogContext* ctx, whLogLevel level, const char* file, - const char* function, uint32_t line, const char* src, - size_t src_len) + const char* function, uint32_t line, const char* msg, + size_t msg_len) { uint64_t timestamp = WH_GETTIME_US(); size_t max_len = (WOLFHSM_CFG_LOG_MSG_MAX > 0) ? (WOLFHSM_CFG_LOG_MSG_MAX - 1) : 0; - size_t copy_len = (src_len < max_len) ? src_len : max_len; + size_t copy_len = (msg_len < max_len) ? msg_len : max_len; whLogEntry entry = {.timestamp = timestamp, .level = level, .file = file, @@ -65,8 +65,8 @@ void wh_Log_AddMsg(whLogContext* ctx, whLogLevel level, const char* file, .line = line, .msg_len = (uint32_t)copy_len}; - if ((src != NULL) && (copy_len > 0)) { - memcpy(entry.msg, src, copy_len); + if ((msg != NULL) && (copy_len > 0)) { + memcpy(entry.msg, msg, copy_len); } /* Zero-pad remainder of message buffer to prevent information leakage */ memset(&entry.msg[copy_len], 0, WOLFHSM_CFG_LOG_MSG_MAX - copy_len); diff --git a/src/wh_log_printf.c b/src/wh_log_printf.c index 73dc835cd..b0530e9be 100644 --- a/src/wh_log_printf.c +++ b/src/wh_log_printf.c @@ -33,41 +33,41 @@ #ifdef WOLFHSM_CFG_LOGGING -int whLogPrintf_Init(void* c, const void* cf) +int whLogPrintf_Init(void* context, const void* config) { - whLogPrintfContext* context = (whLogPrintfContext*)c; - const whLogPrintfConfig* config = (const whLogPrintfConfig*)cf; + whLogPrintfContext* ctx = (whLogPrintfContext*)context; + const whLogPrintfConfig* cfg = (const whLogPrintfConfig*)config; - if (context == NULL) { + if (ctx == NULL) { return WH_ERROR_BADARGS; } /* Initialize context */ - memset(context, 0, sizeof(*context)); + memset(ctx, 0, sizeof(*ctx)); /* Copy config if provided, otherwise use defaults */ - if (config != NULL) { - context->logIfNotDebug = config->logIfNotDebug; + if (cfg != NULL) { + ctx->logIfNotDebug = cfg->logIfNotDebug; } else { - context->logIfNotDebug = 0; + ctx->logIfNotDebug = 0; } - context->initialized = 1; + ctx->initialized = 1; return WH_ERROR_OK; } -int whLogPrintf_AddEntry(void* c, const whLogEntry* entry) +int whLogPrintf_AddEntry(void* context, const whLogEntry* entry) { - whLogPrintfContext* context = (whLogPrintfContext*)c; + whLogPrintfContext* ctx = (whLogPrintfContext*)context; - if ((context == NULL) || (entry == NULL)) { + if ((ctx == NULL) || (entry == NULL)) { return WH_ERROR_BADARGS; } - if (!context->initialized) { + if (!ctx->initialized) { return WH_ERROR_ABORTED; } @@ -76,7 +76,7 @@ int whLogPrintf_AddEntry(void* c, const whLogEntry* entry) * - If logIfNotDebug is false: only log if WOLFHSM_CFG_DEBUG is defined */ #ifndef WOLFHSM_CFG_DEBUG - if (!context->logIfNotDebug) { + if (!ctx->logIfNotDebug) { return WH_ERROR_OK; } #endif diff --git a/src/wh_log_ringbuf.c b/src/wh_log_ringbuf.c index 9a0edc0a3..2e1aa694c 100644 --- a/src/wh_log_ringbuf.c +++ b/src/wh_log_ringbuf.c @@ -31,19 +31,19 @@ #ifdef WOLFHSM_CFG_LOGGING -int whLogRingbuf_Init(void* c, const void* cf) +int whLogRingbuf_Init(void* context, const void* config) { - whLogRingbufContext* context = (whLogRingbufContext*)c; - const whLogRingbufConfig* config = (const whLogRingbufConfig*)cf; + whLogRingbufContext* ctx = (whLogRingbufContext*)context; + const whLogRingbufConfig* cfg = (const whLogRingbufConfig*)config; size_t capacity; - if (context == NULL || config == NULL || config->buffer == NULL || - config->buffer_size < sizeof(whLogEntry)) { + if (ctx == NULL || cfg == NULL || cfg->buffer == NULL || + cfg->buffer_size < sizeof(whLogEntry)) { return WH_ERROR_BADARGS; } /* Calculate capacity (number of complete entries that fit in buffer) */ - capacity = config->buffer_size / sizeof(whLogEntry); + capacity = cfg->buffer_size / sizeof(whLogEntry); /* Capacity must be able to hold at least one log entry, specifically to * prevent divide-by-zeros in the rollover logic */ if (capacity == 0) { @@ -51,26 +51,26 @@ int whLogRingbuf_Init(void* c, const void* cf) } /* Initialize context */ - memset(context, 0, sizeof(*context)); - context->entries = (whLogEntry*)config->buffer; - context->capacity = capacity; - context->count = 0; - context->initialized = 1; + memset(ctx, 0, sizeof(*ctx)); + ctx->entries = (whLogEntry*)cfg->buffer; + ctx->capacity = capacity; + ctx->count = 0; + ctx->initialized = 1; return WH_ERROR_OK; } int whLogRingbuf_Cleanup(void* c) { - whLogRingbufContext* context = (whLogRingbufContext*)c; + whLogRingbufContext* ctx = (whLogRingbufContext*)c; - if (context == NULL) { + if (ctx == NULL) { return WH_ERROR_BADARGS; } - if (context->initialized) { - (void)whLogRingbuf_Clear(context); - context->initialized = 0; + if (ctx->initialized) { + (void)whLogRingbuf_Clear(ctx); + ctx->initialized = 0; } return WH_ERROR_OK; @@ -78,25 +78,25 @@ int whLogRingbuf_Cleanup(void* c) int whLogRingbuf_AddEntry(void* c, const whLogEntry* entry) { - whLogRingbufContext* context = (whLogRingbufContext*)c; + whLogRingbufContext* ctx = (whLogRingbufContext*)c; size_t head; - if ((context == NULL) || (entry == NULL)) { + if ((ctx == NULL) || (entry == NULL)) { return WH_ERROR_BADARGS; } - if (!context->initialized) { + if (!ctx->initialized) { return WH_ERROR_ABORTED; } /* Calculate head position from count */ - head = context->count % context->capacity; + head = ctx->count % ctx->capacity; /* Copy entry to ring buffer at head position */ - memcpy(&context->entries[head], entry, sizeof(whLogEntry)); + memcpy(&ctx->entries[head], entry, sizeof(whLogEntry)); /* Increment count freely to track total messages written */ - context->count++; + ctx->count++; return WH_ERROR_OK; } @@ -110,47 +110,47 @@ int whLogRingbuf_Export(void* c, void* export_arg) int whLogRingbuf_Iterate(void* c, whLogIterateCb iterate_cb, void* iterate_arg) { - whLogRingbufContext* context = (whLogRingbufContext*)c; + whLogRingbufContext* ctx = (whLogRingbufContext*)c; size_t capacity; size_t num_entries; size_t start_idx; size_t i; int ret = 0; - if ((context == NULL) || (iterate_cb == NULL)) { + if ((ctx == NULL) || (iterate_cb == NULL)) { return WH_ERROR_BADARGS; } - if (!context->initialized) { + if (!ctx->initialized) { return WH_ERROR_ABORTED; } /* If buffer is empty, nothing to iterate */ - if (context->count == 0) { + if (ctx->count == 0) { return WH_ERROR_OK; } - capacity = context->capacity; + capacity = ctx->capacity; /* Calculate actual number of entries in buffer (capped at capacity) */ - num_entries = (context->count < capacity) ? context->count : capacity; + num_entries = (ctx->count < capacity) ? ctx->count : capacity; /* Determine starting index for iteration: * - If not full: start at 0 (oldest entry) * - If full: start at head (oldest entry, about to be overwritten) * head = count % capacity */ - if (context->count < capacity) { + if (ctx->count < capacity) { start_idx = 0; } else { - start_idx = context->count % capacity; + start_idx = ctx->count % capacity; } /* Iterate through entries in chronological order */ for (i = 0; i < num_entries; i++) { size_t idx = (start_idx + i) % capacity; - ret = iterate_cb(iterate_arg, &context->entries[idx]); + ret = iterate_cb(iterate_arg, &ctx->entries[idx]); if (ret != 0) { /* User callback requested early termination */ break; @@ -162,17 +162,17 @@ int whLogRingbuf_Iterate(void* c, whLogIterateCb iterate_cb, void* iterate_arg) int whLogRingbuf_Clear(void* c) { - whLogRingbufContext* context = (whLogRingbufContext*)c; + whLogRingbufContext* ctx = (whLogRingbufContext*)c; - if (context == NULL) { + if (ctx == NULL) { return WH_ERROR_BADARGS; } /* Reset ring buffer state */ - context->count = 0; + ctx->count = 0; /* Zero the log entries */ - memset(context->entries, 0, context->capacity * sizeof(whLogEntry)); + memset(ctx->entries, 0, ctx->capacity * sizeof(whLogEntry)); return WH_ERROR_OK; } diff --git a/src/wh_nvm_flash.c b/src/wh_nvm_flash.c index 3d83ab476..a71d56a5f 100644 --- a/src/wh_nvm_flash.c +++ b/src/wh_nvm_flash.c @@ -45,7 +45,7 @@ enum { /* MSW of state variables (nfState) must be set to this pattern when written * to flash to prevent hardware on certain chipsets from confusing zero values * with erased flash */ -static const whFlashUnit BASE_STATE = 0x1234567800000000ull; +static const whFlashUnit BASE_STATE = 0x1234567800000000ULL; /* On-flash layout of the state of an Object or Directory*/ typedef struct { @@ -79,7 +79,7 @@ typedef struct { #define NF_UNITS_PER_DIRECTORY WHFU_BYTES2UNITS(sizeof(nfDirectory)) #define NF_DIRECTORY_OBJECTS_OFFSET WHFU_BYTES2UNITS(offsetof(nfDirectory, objects)) #define NF_DIRECTORY_OBJECT_OFFSET(_n) \ - (NF_DIRECTORY_OBJECTS_OFFSET + (NF_UNITS_PER_OBJECT * _n)) + (NF_DIRECTORY_OBJECTS_OFFSET + (NF_UNITS_PER_OBJECT * (_n))) /* On-flash layout of a Partition */ typedef struct { @@ -438,13 +438,14 @@ static int nfPartition_ProgramCount(whNvmFlashContext* context, static int nfPartition_ProgramInit(whNvmFlashContext* context, int partition) { int ret = 0; + nfMemState init_state; if ((context == NULL) || (context->cb == NULL)) { return WH_ERROR_BADARGS; } /* Valid initial state values for a partition */ - nfMemState init_state = + init_state = (nfMemState) { .status = NF_STATUS_USED, .epoch = 0, @@ -862,6 +863,8 @@ int wh_NvmFlash_Init(void* c, const void* cf) ret = config->cb->Init(config->context, config->config); } if (ret == WH_ERROR_OK) { + nfMemState part_states[2]; + /* Initialize and setup context */ memset(context, 0, sizeof(*context)); context->cb = config->cb; @@ -878,8 +881,6 @@ int wh_NvmFlash_Init(void* c, const void* cf) (void)nfPartition_WriteUnlock(context, 0); (void)nfPartition_WriteUnlock(context, 1); - nfMemState part_states[2]; - /* Recover the partition states to determine which should be active. * No need to check error returns, since output state is initialized * to unknown */ @@ -956,9 +957,6 @@ int wh_NvmFlash_List(void* c, whNvmAccess access, whNvmFlags flags, whNvmId start_id, whNvmId *out_avail_objects, whNvmId *out_id) { - /* TODO: Implement access and flag matching */ - (void)access; (void)flags; - whNvmFlashContext* context = c; int this_entry; int this_count = 0; @@ -969,6 +967,10 @@ int wh_NvmFlash_List(void* c, return WH_ERROR_BADARGS; } + /* TODO: Implement access and flag matching */ + (void)access; + (void)flags; + d = &context->directory; /* Find the starting id */ @@ -1022,10 +1024,12 @@ int wh_NvmFlash_GetAvailable(void* c, uint32_t *out_reclaim_size, whNvmId *out_reclaim_objects) { whNvmFlashContext* context = c; + nfMemDirectory *d; + if (context == NULL) { return WH_ERROR_BADARGS; } - nfMemDirectory *d = &context->directory; + d = &context->directory; if (out_avail_size != NULL) { *out_avail_size = (context->partition_units - NF_PARTITION_DATA_OFFSET - d->next_free_data) * diff --git a/src/wh_nvm_flash_log.c b/src/wh_nvm_flash_log.c index e0ca8d489..19214494b 100644 --- a/src/wh_nvm_flash_log.c +++ b/src/wh_nvm_flash_log.c @@ -137,9 +137,10 @@ static int nfl_FlashEraseHelper(whNvmFlashLogContext* ctx, uint32_t off, static whNvmFlashLogMetadata* nfl_ObjNext(whNvmFlashLogContext* ctx, whNvmFlashLogMetadata* obj) { + uint8_t* next = NULL; if (obj == NULL || ctx == NULL) return NULL; - uint8_t* next = + next = (uint8_t*)obj + sizeof(whNvmFlashLogMetadata) + PAD_SIZE(obj->meta.len); if (next >= ctx->directory.data + ctx->directory.header.size) return NULL; @@ -507,7 +508,8 @@ int wh_NvmFlashLog_Cleanup(void* c) /* List objects */ int wh_NvmFlashLog_List(void* c, whNvmAccess access, whNvmFlags flags, - whNvmId start_id, whNvmId* out_count, whNvmId* out_id) + whNvmId start_id, whNvmId* out_avail_objects, + whNvmId* out_id) { whNvmFlashLogContext* ctx = (whNvmFlashLogContext*)c; whNvmFlashLogMetadata *next_obj = NULL, *start_obj = NULL; @@ -531,16 +533,16 @@ int wh_NvmFlashLog_List(void* c, whNvmAccess access, whNvmFlags flags, } if (next_obj == NULL || next_obj->meta.id == WH_NVM_ID_INVALID) { - if (out_count != NULL) - *out_count = 0; + if (out_avail_objects != NULL) + *out_avail_objects = 0; if (out_id != NULL) *out_id = WH_NVM_ID_INVALID; return WH_ERROR_OK; } count = nfl_ObjectCount(ctx, next_obj); - if (out_count != NULL) - *out_count = count; + if (out_avail_objects != NULL) + *out_avail_objects = count; if (out_id != NULL) *out_id = next_obj->meta.id; diff --git a/src/wh_server.c b/src/wh_server.c index 5098a2da4..701ca24e5 100644 --- a/src/wh_server.c +++ b/src/wh_server.c @@ -176,9 +176,10 @@ static int _wh_Server_HandleCommRequest(whServerContext* server, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { + int rc = 0; + (void)seq; - int rc = 0; switch (action) { case WH_MESSAGE_COMM_ACTION_INIT: { @@ -280,6 +281,8 @@ static int _wh_Server_HandlePkcs11Request(whServerContext* server, uint16_t req_size, const void* req_packet, uint16_t *out_resp_size, void* resp_packet) { + int rc = 0; + (void)server; (void)magic; (void)seq; @@ -287,7 +290,6 @@ static int _wh_Server_HandlePkcs11Request(whServerContext* server, (void)req_packet; (void)resp_packet; - int rc = 0; switch (action) { /* TODO: Add PKCS11 message handling here */ default: @@ -299,6 +301,7 @@ static int _wh_Server_HandlePkcs11Request(whServerContext* server, int wh_Server_HandleRequestMessage(whServerContext* server) { + int rc = 0; uint16_t magic = 0; uint16_t kind = 0; uint16_t group = 0; @@ -321,7 +324,7 @@ int wh_Server_HandleRequestMessage(whServerContext* server) return WH_ERROR_NOTREADY; } - int rc = wh_CommServer_RecvRequest(server->comm, &magic, &kind, &seq, + rc = wh_CommServer_RecvRequest(server->comm, &magic, &kind, &seq, &size, data); /* Got a packet? */ if (rc == WH_ERROR_OK) { diff --git a/src/wh_server_cert.c b/src/wh_server_cert.c index 5cc9b77e3..475ee8196 100644 --- a/src/wh_server_cert.c +++ b/src/wh_server_cert.c @@ -317,6 +317,7 @@ int wh_Server_CertVerifyAcert(whServerContext* server, const uint8_t* cert, uint32_t cert_len, whNvmId trustedRootNvmId) { int rc; + DecodedCert dc; /* Stack-based buffer for root certificate */ uint8_t root_cert[WOLFHSM_CFG_MAX_CERT_SIZE]; @@ -330,7 +331,6 @@ int wh_Server_CertVerifyAcert(whServerContext* server, const uint8_t* cert, } /* Decode and parse the root certificate */ - DecodedCert dc; wc_InitDecodedCert(&dc, root_cert, root_cert_len, NULL); rc = wc_ParseCert(&dc, CERT_TYPE, 0, NULL); if (rc != 0) { @@ -360,10 +360,10 @@ int wh_Server_HandleCertRequest(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)seq; - int rc = 0; + (void)seq; + if ((server == NULL) || (req_packet == NULL) || (resp_packet == NULL) || (out_resp_size == NULL)) { return WH_ERROR_BADARGS; @@ -511,6 +511,8 @@ int wh_Server_HandleCertRequest(whServerContext* server, uint16_t magic, resp.rc = WH_ERROR_ABORTED; } else { + whKeyId keyId; + /* Convert request struct */ wh_MessageCert_TranslateVerifyRequest( magic, (whMessageCert_VerifyRequest*)req_packet, &req); @@ -519,7 +521,7 @@ int wh_Server_HandleCertRequest(whServerContext* server, uint16_t magic, cert_data = (const uint8_t*)req_packet + sizeof(req); /* Map client keyId to server keyId space */ - whKeyId keyId = wh_KeyId_TranslateFromClient( + keyId = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, server->comm->client_id, req.keyId); diff --git a/src/wh_server_crypto.c b/src/wh_server_crypto.c index 56b2a304d..a1da4f0e7 100644 --- a/src/wh_server_crypto.c +++ b/src/wh_server_crypto.c @@ -52,6 +52,7 @@ #include "wolfhsm/wh_utils.h" #include "wolfhsm/wh_server_keystore.h" #include "wolfhsm/wh_server_crypto.h" +#include "wolfhsm/wh_keyid.h" #include "wolfhsm/wh_server.h" @@ -201,7 +202,7 @@ static int _HandleMlDsaCheckPrivKey(whServerContext* ctx, uint16_t magic, int wh_Server_CacheImportRsaKey(whServerContext* ctx, RsaKey* key, whKeyId keyId, whNvmFlags flags, uint32_t label_len, uint8_t* label) { - int ret = 0; + int ret = WH_ERROR_OK; uint8_t* cacheBuf; whNvmMetadata* cacheMeta; uint16_t max_size; @@ -250,7 +251,7 @@ int wh_Server_CacheExportRsaKey(whServerContext* ctx, whKeyId keyId, { uint8_t* cacheBuf; whNvmMetadata* cacheMeta; - int ret = 0; + int ret = WH_ERROR_OK; if ( (ctx == NULL) || (key == NULL) || @@ -271,10 +272,20 @@ static int _HandleRsaKeyGen(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = 0; - RsaKey rsa[1] = {0}; - whMessageCrypto_RsaKeyGenRequest req; + int ret = WH_ERROR_OK; + RsaKey rsa[1] = {0}; + whMessageCrypto_RsaKeyGenRequest req; whMessageCrypto_RsaKeyGenResponse res; + uint32_t key_size = 0; + uint32_t e = 0; + whNvmFlags flags = WH_NVM_FLAGS_NONE; + uint8_t* label = NULL; + uint32_t label_size = WH_NVM_LABEL_LEN; + whKeyId key_id = WH_KEYID_ERASED; + uint8_t* out = NULL; + uint16_t max_size = 0; + uint16_t der_size = 0; + if (inSize < sizeof(whMessageCrypto_RsaKeyGenRequest)) { return WH_ERROR_BADARGS; } @@ -287,29 +298,28 @@ static int _HandleRsaKeyGen(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - int key_size = req.size; - long e = req.e; + key_size = req.size; + e = req.e; + flags = req.flags; + label = req.label; + label_size = WH_NVM_LABEL_LEN; /* Force incoming key_id to have current user/type */ - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - whNvmFlags flags = req.flags; - uint8_t* label = req.label; - uint32_t label_size = WH_NVM_LABEL_LEN; + /* Get pointer to where key data would be stored (after response struct) */ - uint8_t* out = - (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_RsaKeyGenResponse); - uint16_t max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - + out = (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_RsaKeyGenResponse); + max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - ((uint8_t*)out - (uint8_t*)cryptoDataOut)); - uint16_t der_size = 0; /* init the rsa key */ ret = wc_InitRsaKey_ex(rsa, NULL, ctx->crypto->devId); if (ret == 0) { /* make the rsa key with the given params */ ret = wc_MakeRsaKey(rsa, key_size, e, ctx->crypto->rng); - WH_DEBUG_SERVER_VERBOSE("MakeRsaKey: size:%d, e:%ld, ret:%d\n", key_size, e, ret); + WH_DEBUG_SERVER_VERBOSE("MakeRsaKey: size:%d, e:%d, ret:%d\n", key_size, e, ret); if (ret == 0) { /* Check incoming flags */ @@ -368,6 +378,16 @@ static int _HandleRsaFunction( whServerContext* ctx, uint16_t magic, RsaKey rsa[1]; whMessageCrypto_RsaRequest req; + int op_type = 0; + uint32_t options = 0; + int evict = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint32_t in_len = 0; + uint32_t out_len = 0; + uint8_t* in = NULL; + uint8_t* out = NULL; + uint16_t available = 0; + /* Validate minimum size */ if (inSize < sizeof(whMessageCrypto_RsaRequest)) { return WH_ERROR_BADARGS; @@ -381,23 +401,23 @@ static int _HandleRsaFunction( whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - int op_type = (int)(req.opType); - uint32_t options = req.options; - int evict = !!(options & WH_MESSAGE_CRYPTO_RSA_OPTIONS_EVICT); - whKeyId key_id = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - word32 in_len = (word32)(req.inLen); - word32 out_len = (word32)(req.outLen); + op_type = (int)(req.opType); + options = req.options; + evict = !!(options & WH_MESSAGE_CRYPTO_RSA_OPTIONS_EVICT); + key_id = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); + in_len = req.inLen; + out_len = req.outLen; /* Ensure input data fits within request payload */ - uint32_t available = inSize - sizeof(whMessageCrypto_RsaRequest); + available = inSize - sizeof(whMessageCrypto_RsaRequest); if (in_len > available) { return WH_ERROR_BADARGS; } /* in and out are after the fixed size fields */ - byte* in = (uint8_t*)(cryptoDataIn + sizeof(whMessageCrypto_RsaRequest)); - byte* out = (uint8_t*)(cryptoDataOut + sizeof(whMessageCrypto_RsaResponse)); + in = (uint8_t*)(cryptoDataIn + sizeof(whMessageCrypto_RsaRequest)); + out = (uint8_t*)(cryptoDataOut + sizeof(whMessageCrypto_RsaResponse)); WH_DEBUG_SERVER_VERBOSE("HandleRsaFunction opType:%d inLen:%u keyId:%u outLen:%u\n", op_type, in_len, key_id, out_len); @@ -493,11 +513,15 @@ static int _HandleRsaGetSize(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret; + int ret = WH_ERROR_OK; RsaKey rsa[1]; whMessageCrypto_RsaGetSizeRequest req; whMessageCrypto_RsaGetSizeResponse res; int key_size = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint32_t options = 0; + int evict = 0; + if (inSize < sizeof(whMessageCrypto_RsaGetSizeRequest)) { return WH_ERROR_BADARGS; @@ -511,10 +535,10 @@ static int _HandleRsaGetSize(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - uint32_t options = req.options; - int evict = !!(options & WH_MESSAGE_CRYPTO_RSA_GET_SIZE_OPTIONS_EVICT); + options = req.options; + evict = !!(options & WH_MESSAGE_CRYPTO_RSA_GET_SIZE_OPTIONS_EVICT); /* init rsa key */ ret = wc_InitRsaKey_ex(rsa, NULL, ctx->crypto->devId); @@ -558,7 +582,7 @@ int wh_Server_EccKeyCacheImport(whServerContext* ctx, ecc_key* key, uint8_t* cacheBuf; whNvmMetadata* cacheMeta; /* Maximum size of an ecc key der file */ - uint16_t max_size = ECC_BUFSIZE;; + uint16_t max_size = ECC_BUFSIZE; uint16_t der_size; if ( (ctx == NULL) || @@ -676,7 +700,7 @@ int wh_Server_CacheImportCurve25519Key(whServerContext* server, { uint8_t* cacheBuf; whNvmMetadata* cacheMeta; - int ret; + int ret = WH_ERROR_OK; uint8_t der_buf[CURVE25519_MAX_KEY_TO_DER_SZ]; uint16_t keySz = sizeof(der_buf); @@ -712,7 +736,7 @@ int wh_Server_CacheExportCurve25519Key(whServerContext* server, whKeyId keyId, { uint8_t* cacheBuf; whNvmMetadata* cacheMeta; - int ret = 0; + int ret = WH_ERROR_OK; if ( (server == NULL) || (key == NULL) || @@ -807,12 +831,21 @@ static int _HandleEccKeyGen(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)inSize; - int ret = WH_ERROR_OK; ecc_key key[1]; whMessageCrypto_EccKeyGenRequest req; whMessageCrypto_EccKeyGenResponse res; + int key_size = 0; + int curve_id = 0; + whKeyId key_id = WH_KEYID_ERASED; + whNvmFlags flags = WH_NVM_FLAGS_NONE; + uint8_t* label = NULL; + uint16_t label_size = WH_NVM_LABEL_LEN; + uint8_t* res_out = NULL; + uint16_t max_size = 0; + uint16_t res_size = 0; + + (void)inSize; /* Translate request */ ret = wh_MessageCrypto_TranslateEccKeyGenRequest( @@ -822,20 +855,18 @@ static int _HandleEccKeyGen(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - int key_size = req.sz; - int curve_id = req.curveId; - whKeyId key_id = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - whNvmFlags flags = req.flags; - uint8_t* label = req.label; - uint16_t label_size = WH_NVM_LABEL_LEN; + key_size = req.sz; + curve_id = req.curveId; + key_id = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); + flags = req.flags; + label = req.label; /* Response message */ - uint8_t* res_out = - (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_EccKeyGenResponse); - uint16_t max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - - (res_out - (uint8_t*)cryptoDataOut)); - uint16_t res_size = 0; + res_out = + (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_EccKeyGenResponse); + max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - + (res_out - (uint8_t*)cryptoDataOut)); /* init ecc key */ ret = wc_ecc_init_ex(key, NULL, ctx->crypto->devId); @@ -903,12 +934,20 @@ static int _HandleEccSharedSecret(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)inSize; - int ret = WH_ERROR_OK; ecc_key pub_key[1]; ecc_key prv_key[1]; whMessageCrypto_EcdhRequest req; + uint32_t options = 0; + int evict_pub = 0; + int evict_prv = 0; + whKeyId pub_key_id = WH_KEYID_ERASED; + whKeyId prv_key_id = WH_KEYID_ERASED; + byte* res_out = NULL; + word32 max_len = 0; + word32 res_len = 0; + + (void)inSize; /* Translate request */ ret = wh_MessageCrypto_TranslateEcdhRequest( @@ -918,12 +957,12 @@ static int _HandleEccSharedSecret(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - uint32_t options = req.options; - int evict_pub = !!(options & WH_MESSAGE_CRYPTO_ECDH_OPTIONS_EVICTPUB); - int evict_prv = !!(options & WH_MESSAGE_CRYPTO_ECDH_OPTIONS_EVICTPRV); - whKeyId pub_key_id = wh_KeyId_TranslateFromClient( + options = req.options; + evict_pub = !!(options & WH_MESSAGE_CRYPTO_ECDH_OPTIONS_EVICTPUB); + evict_prv = !!(options & WH_MESSAGE_CRYPTO_ECDH_OPTIONS_EVICTPRV); + pub_key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.publicKeyId); - whKeyId prv_key_id = wh_KeyId_TranslateFromClient( + prv_key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.privateKeyId); /* Validate key usage policy for key derivation (private key) */ @@ -936,11 +975,9 @@ static int _HandleEccSharedSecret(whServerContext* ctx, uint16_t magic, } /* Response message */ - byte* res_out = - (byte*)cryptoDataOut + sizeof(whMessageCrypto_EcdhResponse); - word32 max_len = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - - (res_out - (uint8_t*)cryptoDataOut)); - word32 res_len = 0; + res_out = (byte*)cryptoDataOut + sizeof(whMessageCrypto_EcdhResponse); + max_len = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - + (res_out - (uint8_t*)cryptoDataOut)); /* init ecc keys */ ret = wc_ecc_init_ex(pub_key, NULL, ctx->crypto->devId); @@ -993,9 +1030,17 @@ static int _HandleEccSign(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret; + int ret = WH_ERROR_OK; ecc_key key[1]; whMessageCrypto_EccSignRequest req; + uint8_t* in = NULL; + whKeyId key_id = WH_KEYID_ERASED; + word32 in_len = 0; + uint32_t options = 0; + int evict = 0; + byte* res_out = NULL; + word32 max_len = 0; + word32 res_len = 0; /* Validate minimum size */ if (inSize < sizeof(whMessageCrypto_EccSignRequest)) { @@ -1015,13 +1060,12 @@ static int _HandleEccSign(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - uint8_t* in = - (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_EccSignRequest); - whKeyId key_id = wh_KeyId_TranslateFromClient( + in = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_EccSignRequest); + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - word32 in_len = req.sz; - uint32_t options = req.options; - int evict = !!(options & WH_MESSAGE_CRYPTO_ECCSIGN_OPTIONS_EVICT); + in_len = req.sz; + options = req.options; + evict = !!(options & WH_MESSAGE_CRYPTO_ECCSIGN_OPTIONS_EVICT); /* Validate key usage policy for signing */ if (!WH_KEYID_ISERASED(key_id)) { @@ -1033,11 +1077,10 @@ static int _HandleEccSign(whServerContext* ctx, uint16_t magic, } /* Response message */ - byte* res_out = - (byte*)cryptoDataOut + sizeof(whMessageCrypto_EccSignResponse); - word32 max_len = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - - (res_out - (uint8_t*)cryptoDataOut)); - word32 res_len = max_len; + res_out = (byte*)cryptoDataOut + sizeof(whMessageCrypto_EccSignResponse); + max_len = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - + (res_out - (uint8_t*)cryptoDataOut)); + res_len = max_len; /* init private key */ ret = wc_ecc_init_ex(key, NULL, ctx->crypto->devId); @@ -1078,11 +1121,25 @@ static int _HandleEccVerify(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret; + int ret = WH_ERROR_OK; ecc_key key[1]; whMessageCrypto_EccVerifyRequest req; whMessageCrypto_EccVerifyResponse res; + uint32_t available = 0; + uint32_t options = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint32_t hash_len = 0; + uint32_t sig_len = 0; + uint8_t* req_sig = NULL; + uint8_t* req_hash = NULL; + int evict = 0; + int export_pub_key = 0; + byte* res_pub = NULL; + word32 max_size = 0; + uint32_t pub_size = 0; + int result = 0; + /* Validate minimum size */ if (inSize < sizeof(whMessageCrypto_EccVerifyRequest)) { return WH_ERROR_BADARGS; @@ -1096,7 +1153,7 @@ static int _HandleEccVerify(whServerContext* ctx, uint16_t magic, } /* Validate variable-length fields fit within inSize */ - uint32_t available = inSize - sizeof(whMessageCrypto_EccVerifyRequest); + available = inSize - sizeof(whMessageCrypto_EccVerifyRequest); if (req.sigSz > available) { return WH_ERROR_BADARGS; } @@ -1106,16 +1163,16 @@ static int _HandleEccVerify(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - uint32_t options = req.options; - whKeyId key_id = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - uint32_t hash_len = req.hashSz; - uint32_t sig_len = req.sigSz; - uint8_t* req_sig = + options = req.options; + key_id = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); + hash_len = req.hashSz; + sig_len = req.sigSz; + req_sig = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_EccVerifyRequest); - uint8_t* req_hash = req_sig + sig_len; - int evict = !!(options & WH_MESSAGE_CRYPTO_ECCVERIFY_OPTIONS_EVICT); - int export_pub_key = + req_hash = req_sig + sig_len; + evict = !!(options & WH_MESSAGE_CRYPTO_ECCVERIFY_OPTIONS_EVICT); + export_pub_key = !!(options & WH_MESSAGE_CRYPTO_ECCVERIFY_OPTIONS_EXPORTPUB); /* Validate key usage policy for verification */ @@ -1128,12 +1185,10 @@ static int _HandleEccVerify(whServerContext* ctx, uint16_t magic, } /* Response message */ - byte* res_pub = + res_pub = (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_EccVerifyResponse); - word32 max_size = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - - (res_pub - (uint8_t*)cryptoDataOut)); - uint32_t pub_size = 0; - int result = 0; + max_size = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - + (res_pub - (uint8_t*)cryptoDataOut)); /* init public key */ ret = wc_ecc_init_ex(key, NULL, ctx->crypto->devId); @@ -1230,9 +1285,17 @@ static int _HandleRng(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = WH_ERROR_OK; + int ret = WH_ERROR_OK; whMessageCrypto_RngRequest req; whMessageCrypto_RngResponse res; + uint32_t actual_size = 0; + uint8_t* res_out = NULL; + + /* Calculate maximum data size server can respond with (subtract headers) */ + const uint32_t server_max_data = + WOLFHSM_CFG_COMM_DATA_LEN - + sizeof(whMessageCrypto_GenericResponseHeader) - + sizeof(whMessageCrypto_RngResponse); if (inSize < sizeof(whMessageCrypto_RngRequest)) { return WH_ERROR_BADARGS; @@ -1245,19 +1308,11 @@ static int _HandleRng(whServerContext* ctx, uint16_t magic, return ret; } - /* Calculate maximum data size server can respond with (subtract headers) */ - const uint32_t server_max_data = - WOLFHSM_CFG_COMM_DATA_LEN - - sizeof(whMessageCrypto_GenericResponseHeader) - - sizeof(whMessageCrypto_RngResponse); - /* Server responds with minimum of requested size and server max capacity */ - uint32_t actual_size = - (req.sz < server_max_data) ? req.sz : server_max_data; + actual_size = (req.sz < server_max_data) ? req.sz : server_max_data; /* Generate the random data directly into response buffer */ - uint8_t* res_out = - (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_RngResponse); + res_out = (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_RngResponse); ret = wc_RNG_GenerateBlock(ctx->crypto->rng, res_out, actual_size); if (ret != 0) { return ret; @@ -1363,6 +1418,26 @@ static int _HandleHkdf(whServerContext* ctx, uint16_t magic, whMessageCrypto_HkdfRequest req; whMessageCrypto_HkdfResponse res; + int hashType = 0; + uint32_t inKeySz = 0; + uint32_t saltSz = 0; + uint32_t infoSz = 0; + uint32_t outSz = 0; + whKeyId key_id = WH_KEYID_ERASED; + whKeyId keyIdIn = WH_KEYID_ERASED; + whNvmFlags flags = 0; + uint8_t* label = 0; + uint16_t label_size = WH_NVM_LABEL_LEN; + uint32_t available = 0; + + const uint8_t* inKey = NULL; + const uint8_t* salt = NULL; + const uint8_t* info = NULL; + uint8_t* cachedKeyBuf = NULL; + whNvmMetadata* cachedKeyMeta = NULL; + uint8_t* out = NULL; + uint16_t max_size = 0; + /* Validate minimum size */ if (inSize < sizeof(whMessageCrypto_HkdfRequest)) { return WH_ERROR_BADARGS; @@ -1376,21 +1451,20 @@ static int _HandleHkdf(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - int hashType = req.hashType; - uint32_t inKeySz = req.inKeySz; - uint32_t saltSz = req.saltSz; - uint32_t infoSz = req.infoSz; - uint32_t outSz = req.outSz; - whKeyId key_id = wh_KeyId_TranslateFromClient( + hashType = req.hashType; + inKeySz = req.inKeySz; + saltSz = req.saltSz; + infoSz = req.infoSz; + outSz = req.outSz; + flags = req.flags; + label = req.label; + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyIdOut); - whKeyId keyIdIn = wh_KeyId_TranslateFromClient( + keyIdIn = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyIdIn); - whNvmFlags flags = req.flags; - uint8_t* label = req.label; - uint16_t label_size = WH_NVM_LABEL_LEN; /* Validate variable-length fields fit within input buffer */ - uint32_t available = inSize - sizeof(whMessageCrypto_HkdfRequest); + available = inSize - sizeof(whMessageCrypto_HkdfRequest); if (inKeySz > available) { return WH_ERROR_BADARGS; } @@ -1402,14 +1476,9 @@ static int _HandleHkdf(whServerContext* ctx, uint16_t magic, } /* Get pointers to variable-length input data */ - const uint8_t* inKey = - (const uint8_t*)cryptoDataIn + sizeof(whMessageCrypto_HkdfRequest); - const uint8_t* salt = inKey + inKeySz; - const uint8_t* info = salt + saltSz; - - /* Buffer for cached key if needed */ - uint8_t* cachedKeyBuf = NULL; - whNvmMetadata* cachedKeyMeta = NULL; + inKey = (const uint8_t*)cryptoDataIn + sizeof(whMessageCrypto_HkdfRequest); + salt = inKey + inKeySz; + info = salt + saltSz; /* Check if we should use cached key as input */ if (inKeySz == 0 && !WH_KEYID_ISERASED(keyIdIn)) { @@ -1432,10 +1501,9 @@ static int _HandleHkdf(whServerContext* ctx, uint16_t magic, /* Get pointer to where output data would be stored (after response struct) */ - uint8_t* out = - (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_HkdfResponse); - uint16_t max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - - ((uint8_t*)out - (uint8_t*)cryptoDataOut)); + out = (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_HkdfResponse); + max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - + ((uint8_t*)out - (uint8_t*)cryptoDataOut)); /* Check if output size is valid */ if (outSz > max_size) { @@ -1502,6 +1570,28 @@ static int _HandleCmacKdf(whServerContext* ctx, uint16_t magic, whMessageCrypto_CmacKdfRequest req; whMessageCrypto_CmacKdfResponse res; + uint32_t saltSz = 0; + uint32_t zSz = 0; + uint32_t fixedInfoSz = 0; + uint32_t outSz = 0; + whKeyId keyIdOut = WH_KEYID_ERASED; + whKeyId saltKeyId = WH_KEYID_ERASED; + whKeyId zKeyId = WH_KEYID_ERASED; + whNvmFlags flags = WH_NVM_FLAGS_NONE; + uint8_t* label = NULL; + uint16_t label_size = WH_NVM_LABEL_LEN; + uint32_t available = 0; + + const uint8_t* salt = NULL; + const uint8_t* z = NULL; + const uint8_t* fixedInfo = NULL; + uint8_t* cachedSaltBuf = NULL; + whNvmMetadata* cachedSaltMeta = NULL; + uint8_t* cachedZBuf = NULL; + whNvmMetadata* cachedZMeta = NULL; + uint8_t* out = NULL; + uint16_t max_size = 0; + memset(&res, 0, sizeof(res)); /* Validate minimum size */ @@ -1515,22 +1605,22 @@ static int _HandleCmacKdf(whServerContext* ctx, uint16_t magic, return ret; } - uint32_t saltSz = req.saltSz; - uint32_t zSz = req.zSz; - uint32_t fixedInfoSz = req.fixedInfoSz; - uint32_t outSz = req.outSz; - whKeyId keyIdOut = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyIdOut); - whKeyId saltKeyId = wh_KeyId_TranslateFromClient( + saltSz = req.saltSz; + zSz = req.zSz; + fixedInfoSz = req.fixedInfoSz; + outSz = req.outSz; + flags = (whNvmFlags)req.flags; + label = req.label; + keyIdOut = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyIdOut); + saltKeyId = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyIdSalt); - whKeyId zKeyId = wh_KeyId_TranslateFromClient( + zKeyId = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyIdZ); - whNvmFlags flags = (whNvmFlags)req.flags; - uint8_t* label = req.label; - uint16_t label_size = WH_NVM_LABEL_LEN; + /* Validate variable-length fields fit within input buffer */ - uint32_t available = inSize - sizeof(whMessageCrypto_CmacKdfRequest); + available = inSize - sizeof(whMessageCrypto_CmacKdfRequest); if (saltSz > available) { return WH_ERROR_BADARGS; } @@ -1541,15 +1631,10 @@ static int _HandleCmacKdf(whServerContext* ctx, uint16_t magic, return WH_ERROR_BADARGS; } - const uint8_t* salt = - (const uint8_t*)cryptoDataIn + sizeof(whMessageCrypto_CmacKdfRequest); - const uint8_t* z = salt + saltSz; - const uint8_t* fixedInfo = z + zSz; - - uint8_t* cachedSaltBuf = NULL; - whNvmMetadata* cachedSaltMeta = NULL; - uint8_t* cachedZBuf = NULL; - whNvmMetadata* cachedZMeta = NULL; + salt = (const uint8_t*)cryptoDataIn + + sizeof(whMessageCrypto_CmacKdfRequest); + z = salt + saltSz; + fixedInfo = z + zSz; if (saltSz == 0) { if (WH_KEYID_ISERASED(saltKeyId)) { @@ -1593,10 +1678,9 @@ static int _HandleCmacKdf(whServerContext* ctx, uint16_t magic, return WH_ERROR_BADARGS; } - uint8_t* out = - (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_CmacKdfResponse); - uint16_t max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - - ((uint8_t*)out - (uint8_t*)cryptoDataOut)); + out = (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_CmacKdfResponse); + max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - + ((uint8_t*)out - (uint8_t*)cryptoDataOut)); if (outSz > max_size) { return WH_ERROR_BADARGS; @@ -1646,13 +1730,21 @@ static int _HandleCurve25519KeyGen(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)inSize; - int ret = WH_ERROR_OK; curve25519_key key[1]; whMessageCrypto_Curve25519KeyGenRequest req; whMessageCrypto_Curve25519KeyGenResponse res; + int key_size = 0; + whKeyId key_id = WH_KEYID_ERASED; + whNvmFlags flags = WH_NVM_FLAGS_NONE; + uint8_t* label = NULL; + uint16_t label_size = WH_NVM_LABEL_LEN; + uint8_t* out = NULL; + uint16_t ser_size = 0; + + (void)inSize; + /* Translate request */ ret = wh_MessageCrypto_TranslateCurve25519KeyGenRequest( magic, (const whMessageCrypto_Curve25519KeyGenRequest*)cryptoDataIn, @@ -1662,18 +1754,17 @@ static int _HandleCurve25519KeyGen(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - int key_size = req.sz; - whKeyId key_id = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - whNvmFlags flags = req.flags; - uint8_t* label = req.label; - uint16_t label_size = WH_NVM_LABEL_LEN; + key_size = req.sz; + flags = req.flags; + label = req.label; + key_id = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); /* Response Message */ - uint8_t* out = (uint8_t*)cryptoDataOut + - sizeof(whMessageCrypto_Curve25519KeyGenResponse); + out = (uint8_t*)cryptoDataOut + + sizeof(whMessageCrypto_Curve25519KeyGenResponse); /* Initialize the key size to the max size of the buffer */ - uint16_t ser_size = + ser_size = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - (out - (uint8_t*)cryptoDataOut)); /* init key */ @@ -1733,8 +1824,6 @@ static int _HandleCurve25519SharedSecret(whServerContext* ctx, uint16_t magic, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)inSize; - int ret; curve25519_key priv[1] = {0}; curve25519_key pub[1] = {0}; @@ -1742,6 +1831,18 @@ static int _HandleCurve25519SharedSecret(whServerContext* ctx, uint16_t magic, whMessageCrypto_Curve25519Request req; whMessageCrypto_Curve25519Response res; + uint32_t options = 0; + int evict_pub = 0; + int evict_prv = 0; + whKeyId pub_key_id = WH_KEYID_ERASED; + whKeyId prv_key_id = WH_KEYID_ERASED; + int endian = 0; + uint8_t* res_out = NULL; + uint16_t max_len = 0; + word32 res_len = 0; + + (void)inSize; + /* Translate request */ ret = wh_MessageCrypto_TranslateCurve25519Request( magic, (const whMessageCrypto_Curve25519Request*)cryptoDataIn, &req); @@ -1750,14 +1851,14 @@ static int _HandleCurve25519SharedSecret(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - uint32_t options = req.options; - int evict_pub = !!(options & WH_MESSAGE_CRYPTO_CURVE25519_OPTIONS_EVICTPUB); - int evict_prv = !!(options & WH_MESSAGE_CRYPTO_CURVE25519_OPTIONS_EVICTPRV); - whKeyId pub_key_id = wh_KeyId_TranslateFromClient( + options = req.options; + evict_pub = !!(options & WH_MESSAGE_CRYPTO_CURVE25519_OPTIONS_EVICTPUB); + evict_prv = !!(options & WH_MESSAGE_CRYPTO_CURVE25519_OPTIONS_EVICTPRV); + pub_key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.publicKeyId); - whKeyId prv_key_id = wh_KeyId_TranslateFromClient( + prv_key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.privateKeyId); - int endian = req.endian; + endian = req.endian; /* Validate key usage policy for key derivation (private key) */ if (!WH_KEYID_ISERASED(prv_key_id)) { @@ -1769,11 +1870,11 @@ static int _HandleCurve25519SharedSecret(whServerContext* ctx, uint16_t magic, } /* Response message */ - uint8_t* res_out = (uint8_t*)cryptoDataOut + - sizeof(whMessageCrypto_Curve25519Response); - uint16_t max_len = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - - (res_out - (uint8_t*)cryptoDataOut)); - word32 res_len = max_len; + res_out = (uint8_t*)cryptoDataOut + + sizeof(whMessageCrypto_Curve25519Response); + max_len = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - + (res_out - (uint8_t*)cryptoDataOut)); + res_len = max_len; /* init private key */ ret = wc_curve25519_init_ex(priv, NULL, ctx->crypto->devId); @@ -1828,30 +1929,36 @@ static int _HandleEd25519KeyGen(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)inSize; - int ret = WH_ERROR_OK; ed25519_key key[1]; whMessageCrypto_Ed25519KeyGenRequest req; whMessageCrypto_Ed25519KeyGenResponse res; + whKeyId key_id = WH_KEYID_ERASED; + whNvmFlags flags = WH_NVM_FLAGS_NONE; + uint8_t* label = NULL; + uint16_t label_size = WH_NVM_LABEL_LEN; + uint8_t* res_out = NULL; + uint16_t max_size = 0; + uint16_t ser_size = 0; + + (void)inSize; + ret = wh_MessageCrypto_TranslateEd25519KeyGenRequest( magic, (const whMessageCrypto_Ed25519KeyGenRequest*)cryptoDataIn, &req); if (ret != 0) { return ret; } - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - whNvmFlags flags = req.flags; - uint8_t* label = req.label; - uint16_t label_size = WH_NVM_LABEL_LEN; + flags = req.flags; + label = req.label; - uint8_t* res_out = + res_out = (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_Ed25519KeyGenResponse); - uint16_t max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - - (res_out - (uint8_t*)cryptoDataOut)); - uint16_t ser_size = 0; + max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - + (res_out - (uint8_t*)cryptoDataOut)); ret = wc_ed25519_init_ex(key, NULL, ctx->crypto->devId); if (ret == 0) { @@ -1906,6 +2013,14 @@ static int _HandleEd25519Sign(whServerContext* ctx, uint16_t magic, ed25519_key key[1]; whMessageCrypto_Ed25519SignRequest req; uint8_t sig[ED25519_SIG_SIZE]; + word32 sig_len = sizeof(sig); + uint32_t available = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint32_t msg_len = 0; + uint8_t* req_msg = NULL; + uint8_t* req_ctx = NULL; + int evict = 0; + uint8_t* res_sig = NULL; if (inSize < sizeof(req)) { return WH_ERROR_BADARGS; @@ -1917,7 +2032,8 @@ static int _HandleEd25519Sign(whServerContext* ctx, uint16_t magic, return ret; } - uint32_t available = inSize - sizeof(req); + /* Validate variable-length fields fit within input buffer */ + available = inSize - sizeof(whMessageCrypto_Ed25519SignRequest); if (req.msgSz > available) { return WH_ERROR_BADARGS; } @@ -1938,12 +2054,12 @@ static int _HandleEd25519Sign(whServerContext* ctx, uint16_t magic, return WH_ERROR_BADARGS; } - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - uint32_t msg_len = req.msgSz; - uint8_t* req_msg = (uint8_t*)cryptoDataIn + sizeof(req); - uint8_t* req_ctx = req_msg + msg_len; - int evict = !!(req.options & WH_MESSAGE_CRYPTO_ED25519_SIGN_OPTIONS_EVICT); + msg_len = req.msgSz; + req_msg = (uint8_t*)cryptoDataIn + sizeof(req); + req_ctx = req_msg + msg_len; + evict = !!(req.options & WH_MESSAGE_CRYPTO_ED25519_SIGN_OPTIONS_EVICT); if (!WH_KEYID_ISERASED(key_id)) { ret = wh_Server_KeystoreFindEnforceKeyUsage(ctx, key_id, @@ -1953,9 +2069,8 @@ static int _HandleEd25519Sign(whServerContext* ctx, uint16_t magic, } } - uint8_t* res_sig = + res_sig = (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_Ed25519SignResponse); - word32 sig_len = sizeof(sig); ret = wc_ed25519_init_ex(key, NULL, ctx->crypto->devId); if (ret == 0) { @@ -2003,6 +2118,15 @@ static int _HandleEd25519Verify(whServerContext* ctx, uint16_t magic, ed25519_key key[1]; whMessageCrypto_Ed25519VerifyRequest req; whMessageCrypto_Ed25519VerifyResponse res; + uint32_t available = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint32_t sig_len = 0; + uint32_t msg_len = 0; + uint8_t* req_sig = NULL; + uint8_t* req_msg = NULL; + uint8_t* req_ctx = NULL; + int evict = 0; + int verify_res = 0; if (inSize < sizeof(req)) { return WH_ERROR_BADARGS; @@ -2014,7 +2138,8 @@ static int _HandleEd25519Verify(whServerContext* ctx, uint16_t magic, return ret; } - uint32_t available = inSize - sizeof(req); + /* Validate variable-length fields fit within input buffer */ + available = inSize - sizeof(whMessageCrypto_Ed25519VerifyRequest); if (req.sigSz > available) { return WH_ERROR_BADARGS; } @@ -2035,16 +2160,15 @@ static int _HandleEd25519Verify(whServerContext* ctx, uint16_t magic, return WH_ERROR_BADARGS; } - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - uint32_t sig_len = req.sigSz; - uint32_t msg_len = req.msgSz; - uint8_t* req_sig = + sig_len = req.sigSz; + msg_len = req.msgSz; + req_sig = (uint8_t*)cryptoDataIn + sizeof(whMessageCrypto_Ed25519VerifyRequest); - uint8_t* req_msg = req_sig + sig_len; - uint8_t* req_ctx = req_msg + msg_len; - int evict = - !!(req.options & WH_MESSAGE_CRYPTO_ED25519_VERIFY_OPTIONS_EVICT); + req_msg = req_sig + sig_len; + req_ctx = req_msg + msg_len; + evict = !!(req.options & WH_MESSAGE_CRYPTO_ED25519_VERIFY_OPTIONS_EVICT); if (!WH_KEYID_ISERASED(key_id)) { ret = wh_Server_KeystoreFindEnforceKeyUsage(ctx, key_id, @@ -2054,14 +2178,12 @@ static int _HandleEd25519Verify(whServerContext* ctx, uint16_t magic, } } - int result = 0; - ret = wc_ed25519_init_ex(key, NULL, ctx->crypto->devId); if (ret == 0) { ret = wh_Server_CacheExportEd25519Key(ctx, key_id, key); if (ret == WH_ERROR_OK) { ret = wc_ed25519_verify_msg_ex(req_sig, sig_len, req_msg, msg_len, - &result, key, (byte)req.type, + &verify_res, key, (byte)req.type, req_ctx, (byte)req.ctxSz); } wc_ed25519_free(key); @@ -2073,7 +2195,7 @@ static int _HandleEd25519Verify(whServerContext* ctx, uint16_t magic, } if (ret == 0) { - res.res = result; + res.res = verify_res; wh_MessageCrypto_TranslateEd25519VerifyResponse( magic, &res, (whMessageCrypto_Ed25519VerifyResponse*)cryptoDataOut); @@ -2088,13 +2210,17 @@ static int _HandleEd25519SignDma(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = 0; + int ret = WH_ERROR_OK; ed25519_key key[1]; void* msgAddr = NULL; void* sigAddr = NULL; whMessageCrypto_Ed25519SignDmaRequest req; whMessageCrypto_Ed25519SignDmaResponse res; word32 sigLen = 0; + uint32_t available = 0; + uint8_t* req_ctx = NULL; + whKeyId key_id = WH_KEYID_ERASED; + int evict = 0; if (inSize < sizeof(req)) { return WH_ERROR_BADARGS; @@ -2107,23 +2233,24 @@ static int _HandleEd25519SignDma(whServerContext* ctx, uint16_t magic, return ret; } - uint32_t available = inSize - sizeof(req); + /* Validate variable-length fields fit within input buffer */ + available = inSize - sizeof(whMessageCrypto_Ed25519SignDmaRequest); if (req.ctxSz > available) { return WH_ERROR_BADARGS; } if (req.ctxSz > WH_CRYPTO_ED25519_MAX_CTX_LEN) { return WH_ERROR_BADARGS; } - uint8_t* req_ctx = (uint8_t*)cryptoDataIn + sizeof(req); + req_ctx = (uint8_t*)cryptoDataIn + sizeof(req); if ((req.type != (byte)Ed25519) && (req.type != (byte)Ed25519ctx) && (req.type != (byte)Ed25519ph)) { return WH_ERROR_BADARGS; } - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - int evict = !!(req.options & WH_MESSAGE_CRYPTO_ED25519_SIGN_OPTIONS_EVICT); + evict = !!(req.options & WH_MESSAGE_CRYPTO_ED25519_SIGN_OPTIONS_EVICT); if (!WH_KEYID_ISERASED(key_id)) { ret = wh_Server_KeystoreFindEnforceKeyUsage(ctx, key_id, @@ -2195,12 +2322,16 @@ static int _HandleEd25519VerifyDma(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = 0; + int ret = WH_ERROR_OK; ed25519_key key[1]; - void* msgAddr = NULL; - void* sigAddr = NULL; + void* msgAddr = NULL; + void* sigAddr = NULL; whMessageCrypto_Ed25519VerifyDmaRequest req; whMessageCrypto_Ed25519VerifyDmaResponse res; + uint32_t available = 0; + uint8_t* req_ctx = NULL; + whKeyId key_id = WH_KEYID_ERASED; + int evict = 0; if (inSize < sizeof(req)) { return WH_ERROR_BADARGS; @@ -2213,24 +2344,24 @@ static int _HandleEd25519VerifyDma(whServerContext* ctx, uint16_t magic, return ret; } - uint32_t available = inSize - sizeof(req); + /* Validate variable-length fields fit within input buffer */ + available = inSize - sizeof(whMessageCrypto_Ed25519VerifyDmaRequest); if (req.ctxSz > available) { return WH_ERROR_BADARGS; } if (req.ctxSz > WH_CRYPTO_ED25519_MAX_CTX_LEN) { return WH_ERROR_BADARGS; } - uint8_t* req_ctx = (uint8_t*)cryptoDataIn + sizeof(req); + req_ctx = (uint8_t*)cryptoDataIn + sizeof(req); if ((req.type != (byte)Ed25519) && (req.type != (byte)Ed25519ctx) && (req.type != (byte)Ed25519ph)) { return WH_ERROR_BADARGS; } - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - int evict = - !!(req.options & WH_MESSAGE_CRYPTO_ED25519_VERIFY_OPTIONS_EVICT); + evict = !!(req.options & WH_MESSAGE_CRYPTO_ED25519_VERIFY_OPTIONS_EVICT); if (!WH_KEYID_ISERASED(key_id)) { ret = wh_Server_KeystoreFindEnforceKeyUsage(ctx, key_id, @@ -2304,12 +2435,25 @@ static int _HandleAesCtr(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = WH_ERROR_OK; - Aes aes[1] = {0}; + int ret = WH_ERROR_OK; + Aes aes[1] = {0}; whMessageCrypto_AesCtrRequest req; whMessageCrypto_AesCtrResponse res; - uint8_t* cachedKey = NULL; - whNvmMetadata* keyMeta = NULL; + uint8_t* cachedKey = NULL; + whNvmMetadata* keyMeta = NULL; + uint32_t enc = 0; + uint32_t key_len = 0; + uint32_t len = 0; + uint32_t left = 0; + uint64_t needed_size = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint8_t* in = NULL; + uint8_t* key = NULL; + uint8_t* iv = NULL; + uint8_t* tmp = NULL; + uint8_t* out = NULL; + uint8_t* out_reg = NULL; + uint8_t* out_tmp = NULL; if (inSize < sizeof(whMessageCrypto_AesCtrRequest)) { return WH_ERROR_BADARGS; @@ -2321,28 +2465,26 @@ static int _HandleAesCtr(whServerContext* ctx, uint16_t magic, if (ret != WH_ERROR_OK) { return ret; } - uint32_t enc = req.enc; - uint32_t key_len = req.keyLen; - uint32_t len = req.sz; - uint32_t left = req.left; - uint64_t needed_size = sizeof(whMessageCrypto_AesCtrRequest) + len + - key_len + AES_IV_SIZE + AES_BLOCK_SIZE; + enc = req.enc; + key_len = req.keyLen; + len = req.sz; + left = req.left; + needed_size = sizeof(whMessageCrypto_AesCtrRequest) + len + key_len + + AES_IV_SIZE + AES_BLOCK_SIZE; if (needed_size != inSize) { return WH_ERROR_BADARGS; } - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); /* in, key, iv, and out are after fixed size fields */ - uint8_t* in = - (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_AesCtrRequest); - uint8_t* key = in + len; - uint8_t* iv = key + key_len; - uint8_t* tmp = iv + AES_BLOCK_SIZE; - uint8_t* out = - (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_AesCtrResponse); - uint8_t* out_reg = out + len; - uint8_t* out_tmp = out_reg + AES_BLOCK_SIZE; + in = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_AesCtrRequest); + key = in + len; + iv = key + key_len; + tmp = iv + AES_BLOCK_SIZE; + out = (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_AesCtrResponse); + out_reg = out + len; + out_tmp = out_reg + AES_BLOCK_SIZE; /* Debug printouts */ WH_DEBUG_VERBOSE_HEXDUMP("[AesCtr] Input data ", in, len); @@ -2430,14 +2572,22 @@ static int _HandleAesCtrDma(whServerContext* ctx, uint16_t magic, uint16_t seq, whMessageCrypto_AesCtrDmaRequest req; whMessageCrypto_AesCtrDmaResponse res; Aes aes[1] = {0}; - - void* inAddr = NULL; - void* outAddr = NULL; - word32 outSz = 0; - - whKeyId keyId; - uint8_t* cachedKey = NULL; - whNvmMetadata* keyMeta = NULL; + void* inAddr = NULL; + void* outAddr = NULL; + word32 outSz = 0; + whKeyId keyId = WH_KEYID_ERASED; + uint8_t* cachedKey = NULL; + whNvmMetadata* keyMeta = NULL; + uint32_t enc = 0; + uint32_t keyLen = 0; + uint32_t len = 0; + uint32_t left = 0; + uint64_t needed_size = 0; + uint8_t* key = NULL; + uint8_t* iv = NULL; + uint8_t* tmp = NULL; + uint8_t* out_iv = NULL; + uint8_t* out_tmp = NULL; (void)seq; @@ -2452,12 +2602,12 @@ static int _HandleAesCtrDma(whServerContext* ctx, uint16_t magic, uint16_t seq, return ret; } - uint32_t enc = req.enc; - uint32_t keyLen = req.keySz; - uint32_t len = req.input.sz; - uint32_t left = req.left; - uint64_t needed_size = sizeof(whMessageCrypto_AesCtrDmaRequest) + keyLen + - AES_IV_SIZE + AES_BLOCK_SIZE; + enc = req.enc; + keyLen = req.keySz; + len = req.input.sz; + left = req.left; + needed_size = sizeof(whMessageCrypto_AesCtrDmaRequest) + keyLen + + AES_IV_SIZE + AES_BLOCK_SIZE; if (needed_size != inSize) { return WH_ERROR_BADARGS; } @@ -2467,13 +2617,12 @@ static int _HandleAesCtrDma(whServerContext* ctx, uint16_t magic, uint16_t seq, /* iv and tmp are after fixed size fields, key is optional and variable * length */ - uint8_t* key = NULL; - uint8_t* iv = (uint8_t*)(cryptoDataIn) + - sizeof(whMessageCrypto_AesCtrDmaRequest); - uint8_t* tmp = iv + AES_IV_SIZE; - uint8_t* out_iv = (uint8_t*)(cryptoDataOut) + - sizeof(whMessageCrypto_AesCtrDmaResponse); - uint8_t* out_tmp = out_iv + AES_IV_SIZE; + iv = (uint8_t*)(cryptoDataIn) + + sizeof(whMessageCrypto_AesCtrDmaRequest); + tmp = iv + AES_IV_SIZE; + out_iv = (uint8_t*)(cryptoDataOut) + + sizeof(whMessageCrypto_AesCtrDmaResponse); + out_tmp = out_iv + AES_IV_SIZE; memset(&res, 0, sizeof(res)); @@ -2614,12 +2763,20 @@ static int _HandleAesEcb(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = WH_ERROR_OK; - Aes aes[1] = {0}; + int ret = WH_ERROR_OK; + Aes aes[1] = {0}; whMessageCrypto_AesEcbRequest req; whMessageCrypto_AesEcbResponse res; - uint8_t* cachedKey = NULL; - whNvmMetadata* keyMeta = NULL; + uint8_t* cachedKey = NULL; + whNvmMetadata* keyMeta = NULL; + uint32_t enc = 0; + uint32_t key_len = 0; + uint32_t len = 0; + uint64_t needed_size = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint8_t* in = NULL; + uint8_t* key = NULL; + uint8_t* out = NULL; if (inSize < sizeof(whMessageCrypto_AesEcbRequest)) { return WH_ERROR_BADARGS; @@ -2632,25 +2789,21 @@ static int _HandleAesEcb(whServerContext* ctx, uint16_t magic, return ret; } - uint32_t enc = req.enc; - uint32_t key_len = req.keyLen; - uint32_t len = req.sz; - uint64_t needed_size = - sizeof(whMessageCrypto_AesEcbRequest) + len + key_len; + enc = req.enc; + key_len = req.keyLen; + len = req.sz; + needed_size = sizeof(whMessageCrypto_AesEcbRequest) + len + key_len; if (needed_size != inSize) { return WH_ERROR_BADARGS; } - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); /* in, key, and out are after fixed size fields */ - uint8_t* in = - (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_AesEcbRequest); - uint8_t* key = in + len; - - uint8_t* out = - (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_AesEcbResponse); + in = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_AesEcbRequest); + key = in + len; + out = (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_AesEcbResponse); /* Debug printouts */ WH_DEBUG_VERBOSE_HEXDUMP("[AesEcb] Input data", in, len); @@ -2729,14 +2882,16 @@ static int _HandleAesEcbDma(whServerContext* ctx, uint16_t magic, uint16_t seq, whMessageCrypto_AesEcbDmaRequest req; whMessageCrypto_AesEcbDmaResponse res; Aes aes[1] = {0}; - - void* inAddr = NULL; - void* outAddr = NULL; - word32 outSz = 0; - - whKeyId keyId; - uint8_t* cachedKey = NULL; - whNvmMetadata* keyMeta = NULL; + void* inAddr = NULL; + void* outAddr = NULL; + word32 outSz = 0; + whKeyId keyId = WH_KEYID_ERASED; + uint8_t* cachedKey = NULL; + whNvmMetadata* keyMeta = NULL; + uint32_t keyLen = 0; + uint32_t len = 0; + uint64_t needed_size = 0; + uint8_t* key = NULL; (void)seq; @@ -2751,9 +2906,9 @@ static int _HandleAesEcbDma(whServerContext* ctx, uint16_t magic, uint16_t seq, return ret; } - uint32_t keyLen = req.keySz; - uint32_t len = req.input.sz; - uint64_t needed_size = sizeof(whMessageCrypto_AesEcbDmaRequest) + keyLen; + keyLen = req.keySz; + len = req.input.sz; + needed_size = sizeof(whMessageCrypto_AesEcbDmaRequest) + keyLen; if (needed_size != inSize) { return WH_ERROR_BADARGS; } @@ -2761,8 +2916,8 @@ static int _HandleAesEcbDma(whServerContext* ctx, uint16_t magic, uint16_t seq, return WH_ERROR_BADARGS; } - uint8_t* key = (uint8_t*)(cryptoDataIn) + - sizeof(whMessageCrypto_AesEcbDmaRequest); + key = (uint8_t*)(cryptoDataIn) + + sizeof(whMessageCrypto_AesEcbDmaRequest); memset(&res, 0, sizeof(res)); @@ -2893,12 +3048,22 @@ static int _HandleAesCbc(whServerContext* ctx, uint16_t magic, const void* crypt uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = WH_ERROR_OK; - Aes aes[1] = {0}; + int ret = WH_ERROR_OK; + Aes aes[1] = {0}; whMessageCrypto_AesCbcRequest req; whMessageCrypto_AesCbcResponse res; - uint8_t* cachedKey = NULL; - whNvmMetadata* keyMeta = NULL; + uint8_t* cachedKey = NULL; + whNvmMetadata* keyMeta = NULL; + uint32_t enc = 0; + uint32_t key_len = 0; + uint32_t len = 0; + uint64_t needed_size = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint8_t* in = NULL; + uint8_t* key = NULL; + uint8_t* iv = NULL; + uint8_t* out = NULL; + uint8_t* out_iv = NULL; /* Validate minimum size */ if (inSize < sizeof(whMessageCrypto_AesCbcRequest)) { @@ -2913,27 +3078,24 @@ static int _HandleAesCbc(whServerContext* ctx, uint16_t magic, const void* crypt } /* Validate variable-length fields fit within inSize */ - uint32_t enc = req.enc; - uint32_t key_len = req.keyLen; - uint32_t len = req.sz; - uint64_t needed_size = sizeof(whMessageCrypto_AesCbcRequest) + len + - key_len + AES_BLOCK_SIZE; + enc = req.enc; + key_len = req.keyLen; + len = req.sz; + needed_size = sizeof(whMessageCrypto_AesCbcRequest) + len + key_len + + AES_BLOCK_SIZE; if (needed_size != inSize) { return WH_ERROR_BADARGS; } - whKeyId key_id = wh_KeyId_TranslateFromClient( + key_id = wh_KeyId_TranslateFromClient( WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); /* in, key, iv, and out are after fixed size fields */ - uint8_t* in = - (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_AesCbcRequest); - uint8_t* key = in + len; - uint8_t* iv = key + key_len; - - uint8_t* out = - (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_AesCbcResponse); - uint8_t* out_iv = out + len; + in = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_AesCbcRequest); + key = in + len; + iv = key + key_len; + out = (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_AesCbcResponse); + out_iv = out + len; /* Debug printouts */ WH_DEBUG_VERBOSE_HEXDUMP("[AesCbc] Input data", in, len); @@ -3009,18 +3171,23 @@ static int _HandleAesCbcDma(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = WH_ERROR_OK; + int ret = WH_ERROR_OK; whMessageCrypto_AesCbcDmaRequest req; whMessageCrypto_AesCbcDmaResponse res; - Aes aes[1] = {0}; - - void* inAddr = NULL; - void* outAddr = NULL; - word32 outSz = 0; - - whKeyId keyId; - uint8_t* cachedKey = NULL; - whNvmMetadata* keyMeta = NULL; + Aes aes[1] = {0}; + void* inAddr = NULL; + void* outAddr = NULL; + word32 outSz = 0; + whKeyId keyId = WH_KEYID_ERASED; + uint8_t* cachedKey = NULL; + whNvmMetadata* keyMeta = NULL; + uint32_t enc = 0; + uint32_t keyLen = 0; + uint32_t len = 0; + uint64_t needed_size = 0; + uint8_t* key = NULL; + uint8_t* iv = NULL; + uint8_t* out_iv = NULL; (void)seq; @@ -3035,11 +3202,11 @@ static int _HandleAesCbcDma(whServerContext* ctx, uint16_t magic, uint16_t seq, return ret; } - uint32_t enc = req.enc; - uint32_t keyLen = req.keySz; - uint32_t len = req.input.sz; - uint64_t needed_size = sizeof(whMessageCrypto_AesCbcDmaRequest) + keyLen + - AES_IV_SIZE; + enc = req.enc; + keyLen = req.keySz; + len = req.input.sz; + needed_size = sizeof(whMessageCrypto_AesCbcDmaRequest) + keyLen + + AES_IV_SIZE; if (needed_size != inSize) { return WH_ERROR_BADARGS; } @@ -3048,11 +3215,11 @@ static int _HandleAesCbcDma(whServerContext* ctx, uint16_t magic, uint16_t seq, } /* iv is a fixed size field, key is optional and variable length */ - uint8_t* key = NULL; - uint8_t* iv = (uint8_t*)(cryptoDataIn) + - sizeof(whMessageCrypto_AesCbcDmaRequest); - uint8_t* out_iv = (uint8_t*)(cryptoDataOut) + - sizeof(whMessageCrypto_AesCbcDmaResponse); + key = NULL; + iv = (uint8_t*)(cryptoDataIn) + + sizeof(whMessageCrypto_AesCbcDmaRequest); + out_iv = (uint8_t*)(cryptoDataOut) + + sizeof(whMessageCrypto_AesCbcDmaResponse); memset(&res, 0, sizeof(res)); @@ -3184,10 +3351,28 @@ static int _HandleAesGcm(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = WH_ERROR_OK; - Aes aes[1] = {0}; - uint8_t* cachedKey = NULL; - whNvmMetadata* keyMeta = NULL; + int ret = WH_ERROR_OK; + whMessageCrypto_AesGcmRequest req; + whMessageCrypto_AesGcmResponse res; + Aes aes[1] = {0}; + uint8_t* cachedKey = NULL; + whNvmMetadata* keyMeta = NULL; + uint32_t enc = 0; + uint32_t key_len = 0; + uint32_t len = 0; + uint32_t iv_len = 0; + uint32_t authin_len = 0; + uint32_t tag_len = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint64_t needed_size = 0; + uint8_t* in = NULL; + uint8_t* key = NULL; + uint8_t* iv = NULL; + uint8_t* authin = NULL; + uint8_t* tag = NULL; + uint8_t* out = NULL; + uint8_t* out_tag = NULL; + uint32_t res_len = 0; /* Validate minimum size */ if (inSize < sizeof(whMessageCrypto_AesGcmRequest)) { @@ -3195,46 +3380,43 @@ static int _HandleAesGcm(whServerContext* ctx, uint16_t magic, } /* Translate request */ - whMessageCrypto_AesGcmRequest req; ret = wh_MessageCrypto_TranslateAesGcmRequest( magic, (const whMessageCrypto_AesGcmRequest*)cryptoDataIn, &req); if (ret != WH_ERROR_OK) { return ret; } - uint32_t enc = req.enc; - uint32_t key_len = req.keyLen; - uint32_t len = req.sz; - uint32_t iv_len = req.ivSz; - uint32_t authin_len = req.authInSz; - uint32_t tag_len = req.authTagSz; - whKeyId key_id = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - uint64_t needed_size = sizeof(whMessageCrypto_AesGcmRequest) + len + - key_len + iv_len + authin_len + - ((enc == 0) ? tag_len : 0); + enc = req.enc; + key_len = req.keyLen; + len = req.sz; + iv_len = req.ivSz; + authin_len = req.authInSz; + tag_len = req.authTagSz; + key_id = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); + needed_size = sizeof(whMessageCrypto_AesGcmRequest) + len + key_len + + iv_len + authin_len + ((enc == 0) ? tag_len : 0); if (needed_size != inSize) { return WH_ERROR_BADARGS; } /* in, key, iv, authin, tag, and out are after fixed size fields */ - uint8_t* in = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_AesGcmRequest); - uint8_t* key = in + len; - uint8_t* iv = key + key_len; - uint8_t* authin = iv + iv_len; - uint8_t* tag = authin + authin_len; + in = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_AesGcmRequest); + key = in + len; + iv = key + key_len; + authin = iv + iv_len; + tag = authin + authin_len; /* Translate response */ - whMessageCrypto_AesGcmResponse res; res.sz = req.sz; res.authTagSz = (req.enc == 0) ? 0 : req.authTagSz; /* Set up response pointers */ - uint8_t* out = (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_AesGcmResponse); - uint8_t* out_tag = out + len; + out = (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_AesGcmResponse); + out_tag = out + len; - uint32_t res_len = sizeof(whMessageCrypto_AesGcmResponse) + len + - ((enc == 0) ? 0 : tag_len); + res_len = sizeof(whMessageCrypto_AesGcmResponse) + len + + ((enc == 0) ? 0 : tag_len); WH_DEBUG_SERVER_VERBOSE("AESGCM: enc:%d keylen:%d ivsz:%d insz:%d authinsz:%d " "authtagsz:%d reqsz:%u ressz:%u\n", @@ -3332,19 +3514,27 @@ static int _HandleAesGcmDma(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = WH_ERROR_OK; + int ret = WH_ERROR_OK; whMessageCrypto_AesGcmDmaRequest req; whMessageCrypto_AesGcmDmaResponse res; - Aes aes[1] = {0}; - - void* inAddr = NULL; - void* outAddr = NULL; - void* aadAddr = NULL; - word32 outSz = 0; - - whKeyId keyId; - uint8_t* cachedKey = NULL; - whNvmMetadata* keyMeta = NULL; + Aes aes[1] = {0}; + void* inAddr = NULL; + void* outAddr = NULL; + void* aadAddr = NULL; + word32 outSz = 0; + whKeyId keyId = WH_KEYID_ERASED; + uint8_t* cachedKey = NULL; + whNvmMetadata* keyMeta = NULL; + uint32_t enc = 0; + uint32_t keyLen = 0; + uint32_t len = 0; + uint32_t ivLen = 0; + uint32_t tagLen = 0; + uint64_t needed_size = 0; + uint8_t* key = NULL; + uint8_t* iv = NULL; + uint8_t* tag = NULL; + uint8_t* out_tag = NULL; (void)seq; @@ -3359,13 +3549,13 @@ static int _HandleAesGcmDma(whServerContext* ctx, uint16_t magic, uint16_t seq, return ret; } - uint32_t enc = req.enc; - uint32_t keyLen = req.keySz; - uint32_t len = req.input.sz; - uint32_t ivLen = req.ivSz; - uint32_t tagLen = req.authTagSz; - uint64_t needed_size = sizeof(whMessageCrypto_AesGcmDmaRequest) + keyLen + - ivLen + (enc != 0 ? 0 : tagLen); + enc = req.enc; + keyLen = req.keySz; + len = req.input.sz; + ivLen = req.ivSz; + tagLen = req.authTagSz; + needed_size = sizeof(whMessageCrypto_AesGcmDmaRequest) + keyLen + ivLen + + (enc != 0 ? 0 : tagLen); if (needed_size != inSize) { return WH_ERROR_BADARGS; } @@ -3375,12 +3565,12 @@ static int _HandleAesGcmDma(whServerContext* ctx, uint16_t magic, uint16_t seq, /* iv is a fixed size field, key and authTag are optional (key is variable * length) */ - uint8_t* key = NULL; - uint8_t* iv = (uint8_t*)(cryptoDataIn) + - sizeof(whMessageCrypto_AesGcmDmaRequest); - uint8_t* tag = iv + ivLen; - uint8_t* out_tag = (uint8_t*)(cryptoDataOut) + - sizeof(whMessageCrypto_AesGcmDmaResponse); + key = NULL; + iv = (uint8_t*)(cryptoDataIn) + + sizeof(whMessageCrypto_AesGcmDmaRequest); + tag = iv + ivLen; + out_tag = (uint8_t*)(cryptoDataOut) + + sizeof(whMessageCrypto_AesGcmDmaResponse); memset(&res, 0, sizeof(res)); @@ -3578,11 +3768,18 @@ static int _HandleCmac(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)seq; - - int ret; + int ret = WH_ERROR_OK; whMessageCrypto_CmacAesRequest req; whMessageCrypto_CmacAesResponse res; + uint32_t available = 0; + uint8_t tmpKey[AES_256_KEY_SIZE]; + uint32_t tmpKeyLen = sizeof(tmpKey); + Cmac cmac[1] = {0}; + uint8_t* in = NULL; + uint8_t* key = NULL; + uint8_t* out = NULL; + + (void)seq; /* Validate minimum size */ if (inSize < sizeof(whMessageCrypto_CmacAesRequest)) { @@ -3596,7 +3793,7 @@ static int _HandleCmac(whServerContext* ctx, uint16_t magic, uint16_t seq, } /* Validate variable-length fields fit within inSize */ - uint32_t available = inSize - sizeof(whMessageCrypto_CmacAesRequest); + available = inSize - sizeof(whMessageCrypto_CmacAesRequest); if (req.inSz > available) { return WH_ERROR_BADARGS; } @@ -3604,24 +3801,17 @@ static int _HandleCmac(whServerContext* ctx, uint16_t magic, uint16_t seq, if (req.keySz > available) { return WH_ERROR_BADARGS; } - if (req.keySz > AES_MAX_KEY_SIZE) { + if (req.keySz > AES_256_KEY_SIZE) { return WH_ERROR_BADARGS; } - /* Setup fixed size fields */ - uint8_t* in = - (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_CmacAesRequest); - uint8_t* key = in + req.inSz; - uint8_t* out = - (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_CmacAesResponse); + in = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_CmacAesRequest); + key = in + req.inSz; + out = (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_CmacAesResponse); memset(&res, 0, sizeof(res)); - uint8_t tmpKey[AES_MAX_KEY_SIZE]; - uint32_t tmpKeyLen = sizeof(tmpKey); - Cmac cmac[1]; - /* Resolve the key to use */ ret = _CmacResolveKey(ctx, key, req.keySz, req.keyId, tmpKey, &tmpKeyLen); @@ -3769,7 +3959,7 @@ static int _HandleSha224(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = 0; + int ret = WH_ERROR_OK; wc_Sha224 sha224[1]; whMessageCrypto_Sha256Request req; whMessageCrypto_Sha2Response res; @@ -3843,7 +4033,7 @@ static int _HandleSha384(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = 0; + int ret = WH_ERROR_OK; wc_Sha384 sha384[1]; whMessageCrypto_Sha512Request req; whMessageCrypto_Sha2Response res; @@ -3920,7 +4110,7 @@ static int _HandleSha512(whServerContext* ctx, uint16_t magic, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - int ret = 0; + int ret = WH_ERROR_OK; wc_Sha512 sha512[1]; whMessageCrypto_Sha512Request req; whMessageCrypto_Sha2Response res; @@ -4061,12 +4251,21 @@ static int _HandleMlDsaKeyGen(whServerContext* ctx, uint16_t magic, (void)outSize; return WH_ERROR_NOHANDLER; #else - (void)inSize; - - int ret = WH_ERROR_OK; - MlDsaKey key[1]; + int ret = WH_ERROR_OK; + MlDsaKey key[1] = {0}; whMessageCrypto_MlDsaKeyGenRequest req; whMessageCrypto_MlDsaKeyGenResponse res; + int key_size = 0; + whKeyId key_id = WH_KEYID_ERASED; + int level = 0; + whNvmFlags flags = 0; + uint8_t* label = 0; + uint16_t label_size = WH_NVM_LABEL_LEN; + uint8_t* res_out = 0; + uint16_t max_size = 0; + uint16_t res_size = 0; + + (void)inSize; /* Translate the request */ ret = wh_MessageCrypto_TranslateMlDsaKeyGenRequest( @@ -4076,20 +4275,19 @@ static int _HandleMlDsaKeyGen(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - int key_size = req.sz; - whKeyId key_id = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - int level = req.level; - whNvmFlags flags = req.flags; - uint8_t* label = req.label; - uint16_t label_size = WH_NVM_LABEL_LEN; + key_size = req.sz; + key_id = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); + level = req.level; + flags = req.flags; + label = req.label; /* Response message */ - uint8_t* res_out = + res_out = (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_MlDsaKeyGenResponse); - uint16_t max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - - (res_out - (uint8_t*)cryptoDataOut)); - uint16_t res_size = 0; + max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN - + (res_out - (uint8_t*)cryptoDataOut)); + /* TODO key_sz is not used. Should this instead be used as max_size? Figure * out the relation between all three */ @@ -4171,12 +4369,21 @@ static int _HandleMlDsaSign(whServerContext* ctx, uint16_t magic, (void)outSize; return WH_ERROR_NOHANDLER; #else - (void)inSize; - - int ret; - MlDsaKey key[1]; + int ret = WH_ERROR_OK; + MlDsaKey key[1] = {0}; whMessageCrypto_MlDsaSignRequest req; whMessageCrypto_MlDsaSignResponse res; + byte* in = NULL; + whKeyId key_id = WH_KEYID_ERASED; + word32 in_len = 0; + uint32_t options = 0; + int evict = 0; + byte* res_out = NULL; + word32 available_data = 0; + word32 max_len = 0; + word32 res_len = 0; + + (void)inSize; /* Translate the request */ ret = wh_MessageCrypto_TranslateMlDsaSignRequest( @@ -4186,12 +4393,13 @@ static int _HandleMlDsaSign(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - byte* in = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_MlDsaSignRequest); - whKeyId key_id = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - word32 in_len = req.sz; - uint32_t options = req.options; - int evict = !!(options & WH_MESSAGE_CRYPTO_MLDSA_SIGN_OPTIONS_EVICT); + in = (uint8_t*)(cryptoDataIn) + + sizeof(whMessageCrypto_MlDsaSignRequest); + key_id = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); + in_len = req.sz; + options = req.options; + evict = !!(options & WH_MESSAGE_CRYPTO_MLDSA_SIGN_OPTIONS_EVICT); /* Validate key usage policy for signing */ if (!WH_KEYID_ISERASED(key_id)) { @@ -4207,17 +4415,17 @@ static int _HandleMlDsaSign(whServerContext* ctx, uint16_t magic, if (inSize < sizeof(whMessageCrypto_MlDsaSignRequest)) { return WH_ERROR_BADARGS; } - word32 available_data = inSize - sizeof(whMessageCrypto_MlDsaSignRequest); + available_data = inSize - sizeof(whMessageCrypto_MlDsaSignRequest); if (in_len > available_data) { return WH_ERROR_BADARGS; } /* Response message */ - byte* res_out = + res_out = (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_MlDsaSignResponse); - const word32 max_len = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - - (res_out - (uint8_t*)cryptoDataOut)); - word32 res_len = max_len; + max_len = (word32)(WOLFHSM_CFG_COMM_DATA_LEN - + (res_out - (uint8_t*)cryptoDataOut)); + res_len = max_len; /* init private key */ ret = wc_MlDsaKey_Init(key, NULL, ctx->crypto->devId); @@ -4261,12 +4469,22 @@ static int _HandleMlDsaVerify(whServerContext* ctx, uint16_t magic, (void)outSize; return WH_ERROR_NOHANDLER; #else - (void)inSize; - - int ret; - MlDsaKey key[1]; + int ret = WH_ERROR_OK; + MlDsaKey key[1] = {0}; whMessageCrypto_MlDsaVerifyRequest req; whMessageCrypto_MlDsaVerifyResponse res; + uint32_t options = 0; + whKeyId key_id = WH_KEYID_ERASED; + uint32_t hash_len = 0; + uint32_t sig_len = 0; + byte* req_sig = NULL; + int evict = 0; + uint32_t available = 0; + byte* req_hash = NULL; + int verify_res = 0; + + + (void)inSize; /* Translate the request */ ret = wh_MessageCrypto_TranslateMlDsaVerifyRequest( @@ -4276,14 +4494,14 @@ static int _HandleMlDsaVerify(whServerContext* ctx, uint16_t magic, } /* Extract parameters from translated request */ - uint32_t options = req.options; - whKeyId key_id = wh_KeyId_TranslateFromClient( - WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); - uint32_t hash_len = req.hashSz; - uint32_t sig_len = req.sigSz; - byte* req_sig = + options = req.options; + key_id = wh_KeyId_TranslateFromClient( + WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); + hash_len = req.hashSz; + sig_len = req.sigSz; + req_sig = (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_MlDsaVerifyRequest); - int evict = !!(options & WH_MESSAGE_CRYPTO_MLDSA_VERIFY_OPTIONS_EVICT); + evict = !!(options & WH_MESSAGE_CRYPTO_MLDSA_VERIFY_OPTIONS_EVICT); /* Validate key usage policy for verification */ if (!WH_KEYID_ISERASED(key_id)) { @@ -4298,16 +4516,13 @@ static int _HandleMlDsaVerify(whServerContext* ctx, uint16_t magic, if (inSize < sizeof(whMessageCrypto_MlDsaVerifyRequest)) { return WH_ERROR_BADARGS; } - uint32_t available = inSize - sizeof(whMessageCrypto_MlDsaVerifyRequest); + available = inSize - sizeof(whMessageCrypto_MlDsaVerifyRequest); if ((sig_len > available) || (hash_len > available) || (sig_len > (available - hash_len))) { return WH_ERROR_BADARGS; } - byte* req_hash = req_sig + sig_len; - - /* Response message */ - int result = 0; + req_hash = req_sig + sig_len; /* init public key */ ret = wc_MlDsaKey_Init(key, NULL, ctx->crypto->devId); @@ -4317,7 +4532,7 @@ static int _HandleMlDsaVerify(whServerContext* ctx, uint16_t magic, if (ret == WH_ERROR_OK) { /* verify the signature */ ret = wc_MlDsaKey_Verify(key, req_sig, sig_len, req_hash, hash_len, - &result); + &verify_res); } wc_MlDsaKey_Free(key); } @@ -4327,7 +4542,7 @@ static int _HandleMlDsaVerify(whServerContext* ctx, uint16_t magic, (void)wh_Server_KeystoreEvictKey(ctx, key_id); } if (ret == 0) { - res.res = result; + res.res = verify_res; wh_MessageCrypto_TranslateMlDsaVerifyResponse( magic, &res, (whMessageCrypto_MlDsaVerifyResponse*)cryptoDataOut); @@ -4722,14 +4937,14 @@ static int _HandleSha256Dma(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)seq; - - int ret = 0; + int ret = WH_ERROR_OK; whMessageCrypto_Sha2DmaRequest req; whMessageCrypto_Sha2DmaResponse res; wc_Sha256 sha256[1]; int clientDevId; + (void)seq; + if (inSize < sizeof(whMessageCrypto_Sha2DmaRequest)) { return WH_ERROR_BADARGS; } @@ -4844,13 +5059,14 @@ static int _HandleSha224Dma(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)seq; - int ret = 0; + int ret = WH_ERROR_OK; whMessageCrypto_Sha2DmaRequest req; whMessageCrypto_Sha2DmaResponse res; wc_Sha224 sha224[1]; int clientDevId; + (void)seq; + if (inSize < sizeof(whMessageCrypto_Sha2DmaRequest)) { return WH_ERROR_BADARGS; } @@ -4965,13 +5181,14 @@ static int _HandleSha384Dma(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)seq; - int ret = 0; + int ret = WH_ERROR_OK; whMessageCrypto_Sha2DmaRequest req; whMessageCrypto_Sha2DmaResponse res; wc_Sha384 sha384[1]; int clientDevId; + (void)seq; + if (inSize < sizeof(whMessageCrypto_Sha2DmaRequest)) { return WH_ERROR_BADARGS; } @@ -5086,14 +5303,15 @@ static int _HandleSha512Dma(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)seq; - int ret = 0; + int ret = WH_ERROR_OK; whMessageCrypto_Sha2DmaRequest req; whMessageCrypto_Sha2DmaResponse res; wc_Sha512 sha512[1]; int clientDevId; int hashType = WC_HASH_TYPE_SHA512; + (void)seq; + if (inSize < sizeof(whMessageCrypto_Sha2DmaRequest)) { return WH_ERROR_BADARGS; } @@ -5351,14 +5569,17 @@ static int _HandleMlDsaSignDma(whServerContext* ctx, uint16_t magic, (void)outSize; return WH_ERROR_NOHANDLER; #else - int ret = 0; - MlDsaKey key[1]; + int ret = WH_ERROR_OK; + MlDsaKey key[1] = {0}; void* msgAddr = NULL; void* sigAddr = NULL; whMessageCrypto_MlDsaSignDmaRequest req; whMessageCrypto_MlDsaSignDmaResponse res; + whKeyId key_id; + int evict = 0; + if (inSize < sizeof(whMessageCrypto_MlDsaSignDmaRequest)) { return WH_ERROR_BADARGS; } @@ -5370,11 +5591,6 @@ static int _HandleMlDsaSignDma(whServerContext* ctx, uint16_t magic, return ret; } - /* Transaction state */ - whKeyId key_id; - int evict = 0; - - /* Get key ID and evict flag */ key_id = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); @@ -5437,7 +5653,6 @@ static int _HandleMlDsaSignDma(whServerContext* ctx, uint16_t magic, } if (ret == 0) { - /* Translate the response */ (void)wh_MessageCrypto_TranslateMlDsaSignDmaResponse( magic, &res, (whMessageCrypto_MlDsaSignDmaResponse*)cryptoDataOut); @@ -5462,8 +5677,8 @@ static int _HandleMlDsaVerifyDma(whServerContext* ctx, uint16_t magic, (void)outSize; return WH_ERROR_NOHANDLER; #else - int ret = 0; - MlDsaKey key[1]; + int ret = WH_ERROR_OK; + MlDsaKey key[1] = {0}; void* msgAddr = NULL; void* sigAddr = NULL; int verified = 0; @@ -5471,6 +5686,9 @@ static int _HandleMlDsaVerifyDma(whServerContext* ctx, uint16_t magic, whMessageCrypto_MlDsaVerifyDmaRequest req; whMessageCrypto_MlDsaVerifyDmaResponse res; + whKeyId key_id; + int evict = 0; + if (inSize < sizeof(whMessageCrypto_MlDsaVerifyDmaRequest)) { return WH_ERROR_BADARGS; } @@ -5482,10 +5700,6 @@ static int _HandleMlDsaVerifyDma(whServerContext* ctx, uint16_t magic, return ret; } - /* Transaction state */ - whKeyId key_id; - int evict = 0; - /* Get key ID and evict flag */ key_id = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId); @@ -5629,11 +5843,19 @@ static int _HandleCmacDma(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)seq; - - int ret = 0; + int ret = WH_ERROR_OK; whMessageCrypto_CmacAesDmaRequest req; whMessageCrypto_CmacAesDmaResponse res; + void* inAddr = NULL; + uint8_t tmpKey[AES_256_KEY_SIZE]; + uint32_t tmpKeyLen = sizeof(tmpKey); + Cmac cmac[1] = {0}; + uint32_t available = 0; + word32 len = 0; + uint8_t* key = NULL; + uint8_t* out = NULL; + + (void)seq; if (inSize < sizeof(whMessageCrypto_CmacAesDmaRequest)) { return WH_ERROR_BADARGS; @@ -5647,7 +5869,7 @@ static int _HandleCmacDma(whServerContext* ctx, uint16_t magic, uint16_t seq, } /* Validate variable-length fields fit within inSize */ - uint32_t available = inSize - sizeof(whMessageCrypto_CmacAesDmaRequest); + available = inSize - sizeof(whMessageCrypto_CmacAesDmaRequest); if (req.keySz > available) { return WH_ERROR_BADARGS; } @@ -5655,23 +5877,12 @@ static int _HandleCmacDma(whServerContext* ctx, uint16_t magic, uint16_t seq, return WH_ERROR_BADARGS; } - word32 len; - /* Pointers to inline trailing data */ - uint8_t* key = - (uint8_t*)(cryptoDataIn) + sizeof(whMessageCrypto_CmacAesDmaRequest); - uint8_t* out = - (uint8_t*)(cryptoDataOut) + sizeof(whMessageCrypto_CmacAesDmaResponse); + key = (uint8_t*)cryptoDataIn + sizeof(whMessageCrypto_CmacAesDmaRequest); + out = (uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_CmacAesDmaResponse); memset(&res, 0, sizeof(res)); - /* DMA translated address for input */ - void* inAddr = NULL; - - uint8_t tmpKey[AES_MAX_KEY_SIZE]; - uint32_t tmpKeyLen = sizeof(tmpKey); - Cmac cmac[1]; - /* Attempt oneshot if input and output are both present */ if (req.input.sz != 0 && req.outSz != 0) { len = req.outSz; @@ -5798,13 +6009,13 @@ static int _HandleRngDma(whServerContext* ctx, uint16_t magic, uint16_t seq, const void* cryptoDataIn, uint16_t inSize, void* cryptoDataOut, uint16_t* outSize) { - (void)seq; - - int ret = 0; + int ret = WH_ERROR_OK; whMessageCrypto_RngDmaRequest req; whMessageCrypto_RngDmaResponse res; void* outAddr = NULL; + (void)seq; + if (inSize < sizeof(whMessageCrypto_RngDmaRequest)) { return WH_ERROR_BADARGS; } diff --git a/src/wh_server_customcb.c b/src/wh_server_customcb.c index 5e6e3d023..7104d86e2 100644 --- a/src/wh_server_customcb.c +++ b/src/wh_server_customcb.c @@ -55,12 +55,12 @@ int wh_Server_HandleCustomCbRequest(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)seq; - int rc = 0; whMessageCustomCb_Request req = {0}; whMessageCustomCb_Response resp = {0}; + (void)seq; + if (NULL == server || NULL == req_packet || NULL == resp_packet || out_resp_size == NULL) { return WH_ERROR_BADARGS; diff --git a/src/wh_server_img_mgr.c b/src/wh_server_img_mgr.c index 9a32c1093..c3fbc31f6 100644 --- a/src/wh_server_img_mgr.c +++ b/src/wh_server_img_mgr.c @@ -198,11 +198,15 @@ int wh_Server_ImgMgrVerifyMethodEccWithSha256(whServerImgMgrContext* context, const uint8_t* key, size_t keySz, const uint8_t* sig, size_t sigSz) { - int ret = WH_ERROR_OK; - ecc_key eccKey; - uint8_t hash[WC_SHA256_DIGEST_SIZE]; - int verifyResult = 0; - word32 inOutIdx = 0; + int ret = WH_ERROR_OK; + ecc_key eccKey; + uint8_t hash[WC_SHA256_DIGEST_SIZE]; + int verifyResult = 0; + word32 inOutIdx = 0; +#ifdef WOLFHSM_CFG_DMA + whServerContext* server = context->server; + void* serverPtr = NULL; +#endif (void)context; /* Unused parameter */ @@ -226,9 +230,6 @@ int wh_Server_ImgMgrVerifyMethodEccWithSha256(whServerImgMgrContext* context, #ifdef WOLFHSM_CFG_DMA /* For DMA case, we need to access the client memory through server pointer */ - whServerContext* server = context->server; - void* serverPtr = NULL; - ret = wh_Server_DmaProcessClientAddress( server, img->addr, &serverPtr, img->size, WH_DMA_OPER_CLIENT_READ_PRE, (whServerDmaFlags){0}); @@ -284,8 +285,12 @@ int wh_Server_ImgMgrVerifyMethodAesCmac(whServerImgMgrContext* context, const uint8_t* key, size_t keySz, const uint8_t* sig, size_t sigSz) { - int ret = WH_ERROR_OK; - Cmac cmac; + int ret = WH_ERROR_OK; + Cmac cmac; +#ifdef WOLFHSM_CFG_DMA + whServerContext* server = context->server; + void* serverPtr = NULL; +#endif (void)context; /* Unused parameter */ @@ -306,9 +311,6 @@ int wh_Server_ImgMgrVerifyMethodAesCmac(whServerImgMgrContext* context, #ifdef WOLFHSM_CFG_DMA /* For DMA case, we need to access the client memory through server pointer */ - whServerContext* server = context->server; - void* serverPtr = NULL; - ret = wh_Server_DmaProcessClientAddress( server, img->addr, &serverPtr, img->size, WH_DMA_OPER_CLIENT_READ_PRE, (whServerDmaFlags){0}); @@ -347,12 +349,16 @@ int wh_Server_ImgMgrVerifyMethodRsaSslWithSha256( whServerImgMgrContext* context, const whServerImgMgrImg* img, const uint8_t* key, size_t keySz, const uint8_t* sig, size_t sigSz) { - int ret = WH_ERROR_OK; - RsaKey rsaKey; - uint8_t hash[WC_SHA256_DIGEST_SIZE]; - uint8_t decrypted[256]; /* Buffer for decrypted signature */ - word32 decryptedLen = sizeof(decrypted); - word32 inOutIdx = 0; + int ret = WH_ERROR_OK; + RsaKey rsaKey; + uint8_t hash[WC_SHA256_DIGEST_SIZE]; + uint8_t decrypted[256]; /* Buffer for decrypted signature */ + word32 decryptedLen = sizeof(decrypted); + word32 inOutIdx = 0; +#ifdef WOLFHSM_CFG_DMA + whServerContext* server = context->server; + void* serverPtr = NULL; +#endif (void)context; /* Unused parameter */ @@ -376,9 +382,6 @@ int wh_Server_ImgMgrVerifyMethodRsaSslWithSha256( #ifdef WOLFHSM_CFG_DMA /* For DMA case, we need to access the client memory through server pointer */ - whServerContext* server = context->server; - void* serverPtr = NULL; - ret = wh_Server_DmaProcessClientAddress( server, img->addr, &serverPtr, img->size, WH_DMA_OPER_CLIENT_READ_PRE, (whServerDmaFlags){0}); diff --git a/src/wh_server_keystore.c b/src/wh_server_keystore.c index bbf0eca0c..3649fa88d 100644 --- a/src/wh_server_keystore.c +++ b/src/wh_server_keystore.c @@ -1220,8 +1220,8 @@ static int _HandleKeyWrapRequest(whServerContext* server, } /* Translate the server key id passed in from the client */ - serverKeyId = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, - server->comm->client_id, + serverKeyId = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, + server->comm->client_id, req->serverKeyId); /* Store the wrapped key in the response data */ @@ -1287,8 +1287,8 @@ static int _HandleKeyUnwrapAndExportRequest( wrappedKey = reqData; /* Translate the server key id passed in from the client */ - serverKeyId = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, - server->comm->client_id, + serverKeyId = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, + server->comm->client_id, req->serverKeyId); /* Ensure the cipher type in the response matches the request */ @@ -1305,6 +1305,8 @@ static int _HandleKeyUnwrapAndExportRequest( #ifndef NO_AES #ifdef HAVE_AESGCM case WC_CIPHER_AES_GCM: { + uint16_t wrappedKeyUser = 0; + uint16_t wrappedKeyType = 0; uint16_t keySz = req->wrappedKeySz - WH_KEYWRAP_AES_GCM_HEADER_SIZE - sizeof(*metadata); @@ -1328,8 +1330,8 @@ static int _HandleKeyUnwrapAndExportRequest( /* Extract ownership from unwrapped metadata (preserves original * owner) */ - uint16_t wrappedKeyUser = WH_KEYID_USER(metadata->id); - uint16_t wrappedKeyType = WH_KEYID_TYPE(metadata->id); + wrappedKeyUser = WH_KEYID_USER(metadata->id); + wrappedKeyType = WH_KEYID_TYPE(metadata->id); /* Require explicit wrapped-key encoding */ if (wrappedKeyType != WH_KEYTYPE_WRAPPED) { @@ -1375,6 +1377,15 @@ static int _HandleKeyUnwrapAndCacheRequest( whMessageKeystore_KeyUnwrapAndCacheResponse* resp, uint8_t* respData, uint32_t respDataSz) { + int ret; + uint8_t* wrappedKey; + whNvmMetadata metadata = {0}; + uint16_t keySz = 0; + uint8_t key[WOLFHSM_CFG_KEYWRAP_MAX_KEY_SIZE]; + whKeyId serverKeyId; + uint16_t wrappedKeyUser = 0; + uint16_t wrappedKeyType = 0; + /* The server doesn't have any extra response data to send back to the * client */ (void)respData; @@ -1384,13 +1395,6 @@ static int _HandleKeyUnwrapAndCacheRequest( return WH_ERROR_BADARGS; } - int ret; - uint8_t* wrappedKey; - whNvmMetadata metadata = {0}; - uint16_t keySz = 0; - uint8_t key[WOLFHSM_CFG_KEYWRAP_MAX_KEY_SIZE]; - whKeyId serverKeyId; - /* Check if the reqData is big enough to hold the wrapped key */ if (reqDataSz < req->wrappedKeySz) { return WH_ERROR_BUFFER_SIZE; @@ -1400,8 +1404,8 @@ static int _HandleKeyUnwrapAndCacheRequest( wrappedKey = reqData; /* Translate the server key id passed in from the client */ - serverKeyId = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, - server->comm->client_id, + serverKeyId = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, + server->comm->client_id, req->serverKeyId); /* Ensure the cipher type in the response matches the request */ @@ -1444,8 +1448,8 @@ static int _HandleKeyUnwrapAndCacheRequest( } /* Extract ownership from unwrapped metadata (preserves original owner) */ - uint16_t wrappedKeyUser = WH_KEYID_USER(metadata.id); - uint16_t wrappedKeyType = WH_KEYID_TYPE(metadata.id); + wrappedKeyUser = WH_KEYID_USER(metadata.id); + wrappedKeyType = WH_KEYID_TYPE(metadata.id); /* Require explicit wrapped-key encoding */ if (wrappedKeyType != WH_KEYTYPE_WRAPPED) { @@ -1506,8 +1510,8 @@ static int _HandleDataWrapRequest(whServerContext* server, memcpy(data, reqData, req->dataSz); /* Translate the server key id passed in from the client */ - serverKeyId = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, - server->comm->client_id, + serverKeyId = wh_KeyId_TranslateFromClient(WH_KEYTYPE_CRYPTO, + server->comm->client_id, req->serverKeyId); /* Ensure the cipher type in the response matches the request */ @@ -1630,13 +1634,13 @@ int wh_Server_HandleKeyRequest(whServerContext* server, uint16_t magic, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret = WH_ERROR_OK; uint8_t* in; uint8_t* out; whNvmMetadata meta[1] = {{0}}; + (void)req_size; + /* validate args, even though these functions are only supposed to be * called by internal functions */ if ((server == NULL) || (req_packet == NULL) || (out_resp_size == NULL)) { diff --git a/src/wh_server_nvm.c b/src/wh_server_nvm.c index 9c675b62a..18f2c7f49 100644 --- a/src/wh_server_nvm.c +++ b/src/wh_server_nvm.c @@ -84,10 +84,10 @@ int wh_Server_HandleNvmRequest(whServerContext* server, uint16_t req_size, const void* req_packet, uint16_t *out_resp_size, void* resp_packet) { - (void)seq; - int rc = 0; + (void)seq; + if ( (server == NULL) || (req_packet == NULL) || (resp_packet == NULL) || diff --git a/src/wh_server_she.c b/src/wh_server_she.c index cbb7ed680..07f70a1bf 100644 --- a/src/wh_server_she.c +++ b/src/wh_server_she.c @@ -193,13 +193,13 @@ static int _SetUid(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - (void)out_resp_size; - int ret = WH_SHE_ERC_NO_ERROR; whMessageShe_SetUidRequest req; whMessageShe_SetUidResponse resp; + (void)req_size; + (void)out_resp_size; + (void)wh_MessageShe_TranslateSetUidRequest( magic, (whMessageShe_SetUidRequest*)req_packet, &req); @@ -222,14 +222,14 @@ static int _SecureBootInit(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret = 0; uint32_t keySz; uint8_t macKey[WH_SHE_KEY_SZ]; whMessageShe_SecureBootInitRequest req; whMessageShe_SecureBootInitResponse resp; + (void)req_size; + (void)wh_MessageShe_TranslateSecureBootInitRequest(magic, req_packet, &req); /* if we aren't looking for init return error */ @@ -299,13 +299,13 @@ static int _SecureBootUpdate(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret = 0; uint8_t* in; whMessageShe_SecureBootUpdateRequest req; whMessageShe_SecureBootUpdateResponse resp; + (void)req_size; + (void)wh_MessageShe_TranslateSecureBootUpdateRequest(magic, req_packet, &req); @@ -351,9 +351,6 @@ static int _SecureBootFinish(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - (void)req_packet; - int ret = 0; uint32_t keySz; uint32_t field; @@ -362,6 +359,9 @@ static int _SecureBootFinish(whServerContext* server, uint16_t magic, whMessageShe_SecureBootFinishResponse resp; + (void)req_size; + (void)req_packet; + /* if we aren't looking for finish return error */ if (server->she->sbState != WH_SHE_SB_FINISH) { ret = WH_SHE_ERC_SEQUENCE_ERROR; @@ -409,11 +409,11 @@ static int _GetStatus(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { + whMessageShe_GetStatusResponse resp; + (void)req_size; (void)req_packet; - whMessageShe_GetStatusResponse resp; - /* TODO do we care about all the sreg fields? */ resp.sreg = 0; /* SECURE_BOOT */ @@ -446,9 +446,6 @@ static int _LoadKey(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - (void)req_packet; - int ret; int keyRet = 0; uint32_t keySz; @@ -466,6 +463,9 @@ static int _LoadKey(whServerContext* server, uint16_t magic, uint16_t req_size, /* Buffer for counter operations */ uint8_t counter_buffer[WH_SHE_KEY_SZ] = {0}; + (void)req_size; + (void)req_packet; + /* translate the request */ (void)wh_MessageShe_TranslateLoadKeyRequest(magic, req_packet, &req); @@ -671,14 +671,14 @@ static int _LoadPlainKey(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret = 0; whNvmMetadata meta[1] = {{0}}; whMessageShe_LoadPlainKeyRequest req; whMessageShe_LoadPlainKeyResponse resp; + (void)req_size; + (void)wh_MessageShe_TranslateLoadPlainKeyRequest(magic, req_packet, &req); meta->id = WH_MAKE_KEYID(WH_KEYTYPE_SHE, server->comm->client_id, @@ -704,9 +704,6 @@ static int _ExportRamKey(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - (void)req_packet; - int ret = 0; uint32_t keySz; uint32_t field; @@ -717,6 +714,9 @@ static int _ExportRamKey(whServerContext* server, uint16_t magic, uint32_t counter_val; whMessageShe_ExportRamKeyResponse resp; + (void)req_size; + (void)req_packet; + /* check if ram key was loaded by CMD_LOAD_PLAIN_KEY */ if (server->she->ramKeyPlain == 0) { ret = WH_SHE_ERC_KEY_INVALID; @@ -865,9 +865,6 @@ static int _InitRnd(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - (void)req_packet; - int ret = 0; uint32_t keySz; uint8_t kdfInput[WH_SHE_KEY_SZ * 2]; @@ -876,6 +873,9 @@ static int _InitRnd(whServerContext* server, uint16_t magic, uint16_t req_size, whNvmMetadata meta[1] = {0}; whMessageShe_InitRngResponse resp; + (void)req_size; + (void)req_packet; + /* check that init hasn't already been called since startup */ if (server->she->rndInited == 1) { ret = WH_SHE_ERC_SEQUENCE_ERROR; @@ -966,12 +966,12 @@ static int _Rnd(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - (void)req_packet; - int ret = 0; whMessageShe_RndResponse resp; + (void)req_size; + (void)req_packet; + /* check that rng has been inited */ if (server->she->rndInited == 0) { ret = WH_SHE_ERC_RNG_SEED; @@ -1013,8 +1013,6 @@ static int _ExtendSeed(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret = 0; uint32_t keySz; uint8_t kdfInput[WH_SHE_KEY_SZ * 2]; @@ -1022,6 +1020,8 @@ static int _ExtendSeed(whServerContext* server, uint16_t magic, whMessageShe_ExtendSeedRequest req; whMessageShe_ExtendSeedResponse resp; + (void)req_size; + (void)wh_MessageShe_TranslateExtendSeedRequest(magic, req_packet, &req); /* check that rng has been inited */ @@ -1077,8 +1077,6 @@ static int _EncEcb(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret; uint32_t field; uint32_t keySz; @@ -1089,6 +1087,8 @@ static int _EncEcb(whServerContext* server, uint16_t magic, uint16_t req_size, whMessageShe_EncEcbRequest req; whMessageShe_EncEcbResponse resp; + (void)req_size; + /* in and out are after the fixed sized fields */ in = (uint8_t*)req_packet + sizeof(req); out = (uint8_t*)resp_packet + sizeof(resp); @@ -1136,8 +1136,6 @@ static int _EncCbc(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret; uint32_t field; uint32_t keySz; @@ -1147,6 +1145,8 @@ static int _EncCbc(whServerContext* server, uint16_t magic, uint16_t req_size, whMessageShe_EncCbcRequest req; whMessageShe_EncCbcResponse resp; + (void)req_size; + /* in and out are after the fixed sized fields */ in = (uint8_t*)req_packet + sizeof(req); out = (uint8_t*)resp_packet + sizeof(resp); @@ -1201,8 +1201,6 @@ static int _DecEcb(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret; uint32_t field; uint32_t keySz; @@ -1213,6 +1211,8 @@ static int _DecEcb(whServerContext* server, uint16_t magic, uint16_t req_size, whMessageShe_DecEcbRequest req; whMessageShe_DecEcbResponse resp; + (void)req_size; + /* in and out are after the fixed sized fields */ in = (uint8_t*)req_packet + sizeof(req); out = (uint8_t*)resp_packet + sizeof(resp); @@ -1265,8 +1265,6 @@ static int _DecCbc(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret; uint32_t field; uint32_t keySz; @@ -1276,6 +1274,8 @@ static int _DecCbc(whServerContext* server, uint16_t magic, uint16_t req_size, whMessageShe_DecCbcRequest req; whMessageShe_DecCbcResponse resp; + (void)req_size; + /* in and out are after the fixed sized fields */ in = (uint8_t*)req_packet + sizeof(req); out = (uint8_t*)resp_packet + sizeof(resp); @@ -1330,8 +1330,6 @@ static int _GenerateMac(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret; uint32_t field = AES_BLOCK_SIZE; uint32_t keySz; @@ -1340,6 +1338,8 @@ static int _GenerateMac(whServerContext* server, uint16_t magic, whMessageShe_GenMacRequest req; whMessageShe_GenMacResponse resp; + (void)req_size; + /* in and out are after the fixed sized fields */ in = (uint8_t*)req_packet + sizeof(req); @@ -1372,8 +1372,6 @@ static int _VerifyMac(whServerContext* server, uint16_t magic, uint16_t req_size, const void* req_packet, uint16_t* out_resp_size, void* resp_packet) { - (void)req_size; - int ret; uint32_t keySz; uint8_t* message; @@ -1382,6 +1380,7 @@ static int _VerifyMac(whServerContext* server, uint16_t magic, whMessageShe_VerifyMacRequest req; whMessageShe_VerifyMacResponse resp; + (void)req_size; (void)wh_MessageShe_TranslateVerifyMacRequest(magic, req_packet, &req); diff --git a/src/wh_transport_mem.c b/src/wh_transport_mem.c index 92e74d4c2..f0cc37fc4 100644 --- a/src/wh_transport_mem.c +++ b/src/wh_transport_mem.c @@ -38,11 +38,11 @@ int wh_TransportMem_Init(void* c, const void* cf, whCommSetConnectedCb connectcb, void* connectcb_arg) { - (void)connectcb; (void)connectcb_arg; /* Not used */ - whTransportMemContext* context = c; - const whTransportMemConfig* config = cf; + + (void)connectcb; (void)connectcb_arg; /* Not used */ + if ( (context == NULL) || (config == NULL) || (config->req == NULL) || diff --git a/src/wh_utils.c b/src/wh_utils.c index 286224f07..66183a899 100644 --- a/src/wh_utils.c +++ b/src/wh_utils.c @@ -42,22 +42,22 @@ uint16_t wh_Utils_Swap16(uint16_t val) uint32_t wh_Utils_Swap32(uint32_t val) { - return ((val & 0xFF000000ul) >> 24) | - ((val & 0x00FF0000ul) >> 8) | - ((val & 0x0000FF00ul) << 8) | - ((val & 0x000000FFul) << 24); + return ((val & 0xFF000000UL) >> 24) | + ((val & 0x00FF0000UL) >> 8) | + ((val & 0x0000FF00UL) << 8) | + ((val & 0x000000FFUL) << 24); } uint64_t wh_Utils_Swap64(uint64_t val) { - return ((val & 0xFF00000000000000ull) >> 56) | - ((val & 0xFF000000000000ull) >> 40) | - ((val & 0xFF0000000000ull) >> 24) | - ((val & 0xFF00000000ull) >> 8)| - ((val & 0xFF000000ull) << 8) | - ((val & 0xFF0000ull) << 24 ) | - ((val & 0xFF00ull) << 40) | - ((val & 0xFFull) << 56); + return ((val & 0xFF00000000000000ULL) >> 56) | + ((val & 0xFF000000000000ULL) >> 40) | + ((val & 0xFF0000000000ULL) >> 24) | + ((val & 0xFF00000000ULL) >> 8)| + ((val & 0xFF000000ULL) << 8) | + ((val & 0xFF0000ULL) << 24 ) | + ((val & 0xFF00ULL) << 40) | + ((val & 0xFFULL) << 56); } static int isLittleEndian(void) { diff --git a/test/Makefile b/test/Makefile index 259218045..c9a1f3cab 100644 --- a/test/Makefile +++ b/test/Makefile @@ -38,7 +38,7 @@ ARCHFLAGS ?= # Enable extra C compiler warnings CFLAGS_EXTRA = -Werror -Wall -Wextra # Place functions / data into separate sections to allow unused code removal -CFLAGS_EXTRA += -ffunction-sections -fdata-sections +CFLAGS_EXTRA += -ffunction-sections -fdata-sections -Wdeclaration-after-statement # C standard to use (default to c90 if not specified) CSTD ?= -std=c90 diff --git a/test/wh_test_cert.c b/test/wh_test_cert.c index 04250c77c..fa244a056 100644 --- a/test/wh_test_cert.c +++ b/test/wh_test_cert.c @@ -621,9 +621,6 @@ int whTest_CertRamSim(whTestNvmBackendType nvmType) whNvmConfig n_conf[1] = {0}; whNvmContext nvm[1] = {{0}}; - WH_TEST_RETURN_ON_FAIL( - whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); - #ifndef WOLFHSM_CFG_NO_CRYPTO whServerCryptoContext crypto[1] = {{ .devId = INVALID_DEVID, @@ -638,6 +635,9 @@ int whTest_CertRamSim(whTestNvmBackendType nvmType) #endif }}; + WH_TEST_RETURN_ON_FAIL( + whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); + WH_TEST_PRINT("Testing Server Certificate with RAM sim...\n"); /* Initialize NVM */ diff --git a/test/wh_test_clientserver.c b/test/wh_test_clientserver.c index 56107adb7..102c27923 100644 --- a/test/wh_test_clientserver.c +++ b/test/wh_test_clientserver.c @@ -94,12 +94,12 @@ static int _customServerCb(whServerContext* server, const whMessageCustomCb_Request* req, whMessageCustomCb_Response* resp) { - (void)server; - uint8_t* serverPtr = NULL; uint8_t* clientPtr = NULL; size_t copySz = 0; + (void)server; + if (req->type == WH_MESSAGE_CUSTOM_CB_TYPE_DMA64) { clientPtr = (uint8_t*)((uintptr_t)req->data.dma64.client_addr); serverPtr = (uint8_t*)((uintptr_t)req->data.dma64.server_addr); @@ -206,14 +206,14 @@ static int _customServerDmaCb(struct whServerContext_t* server, size_t len, whServerDmaOper oper, whServerDmaFlags flags) { - (void)server; - (void)flags; - /* remapped "client" address, a.k.a. arbitrary "server" buffer */ void* srvTmpBuf = (void*)(clientAddr + (offsetof(TestMemory, srvRemapBufAllow) - offsetof(TestMemory, cliBuf))); + (void)server; + (void)flags; + /* This DMA callback simulates the remapping of client addresses by simply * copying the data between the client address and the "remapped" server * address, which is just an arbitrary server buffer */ @@ -252,10 +252,9 @@ static int _customServerDmaCb(struct whServerContext_t* server, defined(WOLFHSM_CFG_ENABLE_SERVER) static int _testDma(whServerContext* server, whClientContext* client) { - (void)client; - int rc = 0; TestMemory testMem = {0}; + uint8_t tmp[sizeof(testMem.srvRemapBufAllow)]; const whServerDmaAddrAllowList allowList = { .readList = @@ -270,6 +269,8 @@ static int _testDma(whServerContext* server, whClientContext* client) }, }; + (void)client; + /* Register a custom DMA callback */ WH_TEST_RETURN_ON_FAIL(wh_Server_DmaRegisterCb(server, _customServerDmaCb)); @@ -330,7 +331,6 @@ static int _testDma(whServerContext* server, whClientContext* client) /* custom DMA callback uses the tmp server buffer for input data and * should set it to a known pattern on exit */ - uint8_t tmp[sizeof(testMem.srvRemapBufAllow)]; memset(tmp, TEST_MEM_UNMAPPED_BYTE, sizeof(tmp)); WH_TEST_ASSERT_RETURN(0 == memcmp(testMem.srvRemapBufAllow, tmp, sizeof(testMem.srvRemapBufAllow))); @@ -619,9 +619,6 @@ int whTest_ClientServerSequential(whTestNvmBackendType nvmType) whNvmConfig n_conf[1] = {0}; whNvmContext nvm[1] = {{0}}; - WH_TEST_RETURN_ON_FAIL( - whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); - #ifndef WOLFHSM_CFG_NO_CRYPTO whServerCryptoContext crypto[1] = {{ .devId = INVALID_DEVID, @@ -639,33 +636,6 @@ int whTest_ClientServerSequential(whTestNvmBackendType nvmType) whCommConnected server_connected = WH_COMM_DISCONNECTED; - /* Expose the server context to our client connect callback */ - clientServerSequentialTestServerCtx = server; - -#ifndef WOLFHSM_CFG_NO_CRYPTO - WH_TEST_RETURN_ON_FAIL(wolfCrypt_Init()); - WH_TEST_RETURN_ON_FAIL(wc_InitRng_ex(crypto->rng, NULL, crypto->devId)); -#endif - WH_TEST_RETURN_ON_FAIL(wh_Nvm_Init(nvm, n_conf)); - - /* Server API should return NOTREADY until the server is connected */ - WH_TEST_RETURN_ON_FAIL(wh_Server_GetConnected(server, &server_connected)); - WH_TEST_ASSERT_RETURN(WH_COMM_DISCONNECTED == server_connected); - WH_TEST_ASSERT_RETURN(WH_ERROR_NOTREADY == - wh_Server_HandleRequestMessage(server)); - - - /* Init client and server contexts. NOTE: in this test the server MUST be - initialized before the client, as the client init function triggers the - server "connect" via the connect callback, and this will be overwritten (set - to zero) on server init */ - WH_TEST_RETURN_ON_FAIL(wh_Server_Init(server, s_conf)); - WH_TEST_RETURN_ON_FAIL(wh_Client_Init(client, c_conf)); - - /* Ensure server is now "connected" */ - WH_TEST_RETURN_ON_FAIL(wh_Server_GetConnected(server, &server_connected)); - WH_TEST_ASSERT_RETURN(WH_COMM_CONNECTED == server_connected); - int counter = 1; char recv_buffer[WOLFHSM_CFG_COMM_DATA_LEN] = {0}; char send_buffer[WOLFHSM_CFG_COMM_DATA_LEN] = {0}; @@ -696,6 +666,41 @@ int whTest_ClientServerSequential(whTestNvmBackendType nvmType) uint32_t lifecycle_state = 0; uint32_t nvm_state = 0; + whNvmAccess list_access = WH_NVM_ACCESS_ANY; + whNvmFlags list_flags = WH_NVM_FLAGS_NONE; + whNvmId list_id = 0; + whNvmId list_count = 0; + + /* Expose the server context to our client connect callback */ + clientServerSequentialTestServerCtx = server; + + WH_TEST_RETURN_ON_FAIL( + whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); + +#ifndef WOLFHSM_CFG_NO_CRYPTO + WH_TEST_RETURN_ON_FAIL(wolfCrypt_Init()); + WH_TEST_RETURN_ON_FAIL(wc_InitRng_ex(crypto->rng, NULL, crypto->devId)); +#endif + WH_TEST_RETURN_ON_FAIL(wh_Nvm_Init(nvm, n_conf)); + + /* Server API should return NOTREADY until the server is connected */ + WH_TEST_RETURN_ON_FAIL(wh_Server_GetConnected(server, &server_connected)); + WH_TEST_ASSERT_RETURN(WH_COMM_DISCONNECTED == server_connected); + WH_TEST_ASSERT_RETURN(WH_ERROR_NOTREADY == + wh_Server_HandleRequestMessage(server)); + + + /* Init client and server contexts. NOTE: in this test the server MUST be + initialized before the client, as the client init function triggers the + server "connect" via the connect callback, and this will be overwritten (set + to zero) on server init */ + WH_TEST_RETURN_ON_FAIL(wh_Server_Init(server, s_conf)); + WH_TEST_RETURN_ON_FAIL(wh_Client_Init(client, c_conf)); + + /* Ensure server is now "connected" */ + WH_TEST_RETURN_ON_FAIL(wh_Server_GetConnected(server, &server_connected)); + WH_TEST_ASSERT_RETURN(WH_COMM_CONNECTED == server_connected); + /* Check that the server side is ready to recv */ WH_TEST_ASSERT_RETURN(WH_ERROR_NOTREADY == wh_Server_HandleRequestMessage(server)); @@ -750,7 +755,7 @@ int whTest_ClientServerSequential(whTestNvmBackendType nvmType) /* Prepare echo test */ send_len = snprintf(send_buffer, sizeof(send_buffer), "Request:%u", counter); - snprintf(recv_buffer, sizeof(recv_buffer), "NOTHING RECEIVED"); + (void)snprintf(recv_buffer, sizeof(recv_buffer), "NOTHING RECEIVED"); recv_len = 0; WH_TEST_RETURN_ON_FAIL( @@ -891,10 +896,6 @@ int whTest_ClientServerSequential(whTestNvmBackendType nvmType) /* Perform out-of-bounds read tests on first object written */ WH_TEST_RETURN_ON_FAIL(_testOutOfBoundsNvmReads(client, server, 20)); - whNvmAccess list_access = WH_NVM_ACCESS_ANY; - whNvmFlags list_flags = WH_NVM_FLAGS_NONE; - whNvmId list_id = 0; - whNvmId list_count = 0; do { WH_TEST_RETURN_ON_FAIL( wh_Client_NvmListRequest(client, list_access, list_flags, list_id)); @@ -1140,8 +1141,6 @@ int whTest_ClientServerClientConfig(whClientConfig* clientCfg) int ret = 0; whClientContext client[1] = {0}; - WH_TEST_RETURN_ON_FAIL(wh_Client_Init(client, clientCfg)); - int counter = 1; char recv_buffer[WOLFHSM_CFG_COMM_DATA_LEN] = {0}; char send_buffer[WOLFHSM_CFG_COMM_DATA_LEN] = {0}; @@ -1156,6 +1155,13 @@ int whTest_ClientServerClientConfig(whClientConfig* clientCfg) whNvmId avail_objects = 0; whNvmId reclaim_objects = 0; + whNvmAccess list_access = WH_NVM_ACCESS_ANY; + whNvmFlags list_flags = WH_NVM_FLAGS_NONE; + whNvmId list_id = 0; + whNvmId list_count = 0; + + WH_TEST_RETURN_ON_FAIL(wh_Client_Init(client, clientCfg)); + /* Init client/server comms */ WH_TEST_RETURN_ON_FAIL(wh_Client_CommInit(client, &client_id, &server_id)); WH_TEST_ASSERT_RETURN(client_id == client->comm->client_id); @@ -1166,7 +1172,7 @@ int whTest_ClientServerClientConfig(whClientConfig* clientCfg) /* Prepare echo test */ send_len = snprintf(send_buffer, sizeof(send_buffer), "Request:%u", counter); - snprintf(recv_buffer, sizeof(recv_buffer), "NOTHING RECEIVED"); + (void)snprintf(recv_buffer, sizeof(recv_buffer), "NOTHING RECEIVED"); recv_len = 0; WH_TEST_RETURN_ON_FAIL(ret = wh_Client_Echo(client, send_len, send_buffer, &recv_len, recv_buffer)); @@ -1280,10 +1286,6 @@ int whTest_ClientServerClientConfig(whClientConfig* clientCfg) WH_TEST_ASSERT_RETURN(0 == memcmp(send_buffer, recv_buffer, len)); } - whNvmAccess list_access = WH_NVM_ACCESS_ANY; - whNvmFlags list_flags = WH_NVM_FLAGS_NONE; - whNvmId list_id = 0; - whNvmId list_count = 0; do { WH_TEST_RETURN_ON_FAIL( ret = wh_Client_NvmList(client, list_access, list_flags, list_id, @@ -1548,13 +1550,11 @@ static void _whClientServerThreadTest(whClientConfig* c_conf, rc = pthread_create(&cthread, NULL, _whClientTask, c_conf); if (rc == 0) { /* All good. Block on joining */ - - pthread_join(cthread, &retval); - pthread_cancel(sthread); + (void)pthread_join(cthread, &retval); + (void)pthread_cancel(sthread); } else { /* Cancel the server thread */ - pthread_cancel(sthread); - + (void)pthread_cancel(sthread); } } } @@ -1608,9 +1608,6 @@ static int wh_ClientServer_MemThreadTest(whTestNvmBackendType nvmType) whNvmConfig n_conf[1] = {0}; whNvmContext nvm[1] = {{0}}; - WH_TEST_RETURN_ON_FAIL( - whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); - #ifndef WOLFHSM_CFG_NO_CRYPTO /* Crypto context */ whServerCryptoContext crypto[1] = {{ @@ -1628,6 +1625,9 @@ static int wh_ClientServer_MemThreadTest(whTestNvmBackendType nvmType) #endif }}; + WH_TEST_RETURN_ON_FAIL( + whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); + WH_TEST_RETURN_ON_FAIL(wh_Nvm_Init(nvm, n_conf)); #ifndef WOLFHSM_CFG_NO_CRYPTO @@ -1693,9 +1693,6 @@ static int wh_ClientServer_PosixMemMapThreadTest(whTestNvmBackendType nvmType) whNvmConfig n_conf[1] = {0}; whNvmContext nvm[1] = {{0}}; - WH_TEST_RETURN_ON_FAIL( - whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); - #ifndef WOLFHSM_CFG_NO_CRYPTO /* Crypto context */ whServerCryptoContext crypto[1] = {{ @@ -1711,6 +1708,9 @@ static int wh_ClientServer_PosixMemMapThreadTest(whTestNvmBackendType nvmType) #endif }}; + WH_TEST_RETURN_ON_FAIL( + whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); + WH_TEST_RETURN_ON_FAIL(wh_Nvm_Init(nvm, n_conf)); #ifndef WOLFHSM_CFG_NO_CRYPTO diff --git a/test/wh_test_comm.c b/test/wh_test_comm.c index 1a6f5be64..c93e2ea5c 100644 --- a/test/wh_test_comm.c +++ b/test/wh_test_comm.c @@ -97,10 +97,6 @@ int whTest_CommMem(void) }}; whCommServer server[1] = {0}; - /* Init client and server */ - WH_TEST_RETURN_ON_FAIL(wh_CommClient_Init(client, c_conf)); - WH_TEST_RETURN_ON_FAIL(wh_CommServer_Init(server, s_conf, NULL, NULL)); - int counter = 1; uint8_t tx_req[REQ_SIZE] = {0}; @@ -124,6 +120,10 @@ int whTest_CommMem(void) uint16_t rx_resp_type = 0; uint16_t rx_resp_seq = 0; + /* Init client and server */ + WH_TEST_RETURN_ON_FAIL(wh_CommClient_Init(client, c_conf)); + WH_TEST_RETURN_ON_FAIL(wh_CommServer_Init(server, s_conf, NULL, NULL)); + /* Check that neither side is ready to recv */ WH_TEST_ASSERT_RETURN(WH_ERROR_NOTREADY == wh_CommServer_RecvRequest(server, &rx_req_flags, @@ -131,7 +131,7 @@ int whTest_CommMem(void) &rx_req_len, rx_req)); for (counter = 0; counter < REPEAT_COUNT; counter++) { - snprintf((char*)tx_req, sizeof(tx_req), "Request:%u", counter); + (void)snprintf((char*)tx_req, sizeof(tx_req), "Request:%u", counter); tx_req_len = strlen((char*)tx_req); tx_req_type = counter * 2; WH_TEST_RETURN_ON_FAIL( @@ -159,7 +159,7 @@ int whTest_CommMem(void) WH_TEST_DEBUG_PRINT("Server RecvRequest:%d, flags %x, type:%x, seq:%d, len:%d, %s\n", ret, rx_req_flags, rx_req_type, rx_req_seq, rx_req_len, rx_req); - snprintf((char*)tx_resp, sizeof(tx_resp), "Response:%s", rx_req); + (void)snprintf((char*)tx_resp, sizeof(tx_resp), "Response:%s", rx_req); tx_resp_len = strlen((char*)tx_resp); ret = wh_CommServer_SendResponse(server, rx_req_flags, rx_req_type, rx_req_seq, tx_resp_len, tx_resp); @@ -218,7 +218,7 @@ static void* _whCommClientTask(void* cf) WH_TEST_ASSERT_MSG(0 == ret, "Client Init: ret=%d", ret); for (counter = 0; counter < REPEAT_COUNT; counter++) { - snprintf((char*)tx_req, sizeof(tx_req), "Request:%u", counter); + (void)snprintf((char*)tx_req, sizeof(tx_req), "Request:%u", counter); tx_req_len = strlen((char*)tx_req); tx_req_type = counter * 2; do { @@ -271,9 +271,6 @@ static void* _whCommServerTask(void* cf) whCommServer server[1]; int counter = 1; - ret = wh_CommServer_Init(server, config, NULL, NULL); - WH_TEST_ASSERT_MSG(0 == ret, "Server Init: ret=%d", ret); - uint8_t rx_req[REQ_SIZE] = {0}; uint16_t rx_req_len = 0; uint16_t rx_req_flags = 0; @@ -283,6 +280,9 @@ static void* _whCommServerTask(void* cf) uint8_t tx_resp[RESP_SIZE] = {0}; uint16_t tx_resp_len = 0; + ret = wh_CommServer_Init(server, config, NULL, NULL); + WH_TEST_ASSERT_MSG(0 == ret, "Server Init: ret=%d", ret); + for (counter = 0; counter < REPEAT_COUNT; counter++) { do { ret = wh_CommServer_RecvRequest(server, &rx_req_flags, &rx_req_type, @@ -306,7 +306,7 @@ static void* _whCommServerTask(void* cf) } do { - snprintf((char*)tx_resp, sizeof(tx_resp), "Response:%s", rx_req); + (void)snprintf((char*)tx_resp, sizeof(tx_resp), "Response:%s", rx_req); tx_resp_len = strlen((char*)tx_resp); ret = wh_CommServer_SendResponse(server, rx_req_flags, rx_req_type, rx_req_seq, tx_resp_len, tx_resp); @@ -354,14 +354,13 @@ static void _whCommClientServerThreadTest(whCommClientConfig* c_conf, WH_TEST_DEBUG_PRINT("Client thread create:%d\n", rc); if (rc == 0) { /* All good. Block on joining */ - - pthread_join(cthread, &retval); - pthread_join(sthread, &retval); + (void)pthread_join(cthread, &retval); + (void)pthread_join(sthread, &retval); } else { /* Cancel the server thread */ - pthread_cancel(sthread); - pthread_join(sthread, &retval); + (void)pthread_cancel(sthread); + (void)pthread_join(sthread, &retval); } } } @@ -411,12 +410,6 @@ void wh_CommClientServer_ShMemThreadTest(void) .dma_size = BUFFER_SIZE * 4, }}; - /* Make unique name for this test */ - char uniq_name[32] = {0}; - snprintf(uniq_name, sizeof(uniq_name),"/wh_test_comm_shm.%u", - (unsigned) getpid()); - tmcf->name = uniq_name; - /* Client configuration/contexts */ whTransportClientCb tmccb[1] = {POSIX_TRANSPORT_SHM_CLIENT_CB}; posixTransportShmClientContext csc[1] = {0}; @@ -437,6 +430,12 @@ void wh_CommClientServer_ShMemThreadTest(void) .server_id = 0xF, }}; + /* Make unique name for this test */ + char uniq_name[32] = {0}; + (void)snprintf(uniq_name, sizeof(uniq_name),"/wh_test_comm_shm.%u", + (unsigned) getpid()); + tmcf->name = uniq_name; + _whCommClientServerThreadTest(c_conf, s_conf); } diff --git a/test/wh_test_common.c b/test/wh_test_common.c index 2cac0aebb..10bcc4d2d 100644 --- a/test/wh_test_common.c +++ b/test/wh_test_common.c @@ -54,7 +54,9 @@ int whTest_NvmCfgBackend(whTestNvmBackendType type, switch (type) { #if defined(WOLFHSM_CFG_SERVER_NVM_FLASH_LOG) - case WH_NVM_TEST_BACKEND_FLASH_LOG: + case WH_NVM_TEST_BACKEND_FLASH_LOG: { + static whNvmCb nflcb[1] = {WH_NVM_FLASH_LOG_CB}; + nvmSetup->nvmFlashLogCfg.flash_cb = fCb; /* restrict simulated flash partition to nvm_flash_log_partition */ WH_TEST_ASSERT(fCfg->size >= WH_NVM_FLASH_LOG_PARTITION_SIZE * 2); @@ -63,27 +65,28 @@ int whTest_NvmCfgBackend(whTestNvmBackendType type, nvmSetup->nvmFlashLogCfg.flash_ctx = fCtx; memset(&nvmSetup->nvmFlashLogCtx, 0, sizeof(nvmSetup->nvmFlashLogCtx)); - static whNvmCb nflcb[1] = {WH_NVM_FLASH_LOG_CB}; nvmCfg->cb = nflcb; nvmCfg->context = &nvmSetup->nvmFlashLogCtx; nvmCfg->config = &nvmSetup->nvmFlashLogCfg; break; + } #endif - case WH_NVM_TEST_BACKEND_FLASH: + case WH_NVM_TEST_BACKEND_FLASH: { + static whNvmCb nfcb[1] = {WH_NVM_FLASH_CB}; + /* NVM Flash Configuration using RamSim HAL Flash */ nvmSetup->nvmFlashCfg.cb = fCb; nvmSetup->nvmFlashCfg.context = fCtx; nvmSetup->nvmFlashCfg.config = fCfg; memset(&nvmSetup->nvmFlashCtx, 0, sizeof(nvmSetup->nvmFlashCtx)); - static whNvmCb nfcb[1] = {WH_NVM_FLASH_CB}; nvmCfg->cb = nfcb; nvmCfg->context = &nvmSetup->nvmFlashCtx; nvmCfg->config = &nvmSetup->nvmFlashCfg; break; - + } default: return WH_ERROR_BADARGS; } diff --git a/test/wh_test_crypto.c b/test/wh_test_crypto.c index 223809273..7e75bece9 100644 --- a/test/wh_test_crypto.c +++ b/test/wh_test_crypto.c @@ -120,8 +120,6 @@ static int whTest_ShowNvmAvailable(whClientContext* ctx) #ifdef WOLFHSM_CFG_ENABLE_CLIENT static int whTest_CryptoRng(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)ctx; /* Unused */ - #define WH_TEST_RNG_LIL 7 #define WH_TEST_RNG_MED 1024 #define WH_TEST_RNG_BIG (WOLFHSM_CFG_COMM_DATA_LEN * 2) @@ -130,6 +128,8 @@ static int whTest_CryptoRng(whClientContext* ctx, int devId, WC_RNG* rng) uint8_t med[WH_TEST_RNG_MED]; uint8_t big[WH_TEST_RNG_BIG]; + (void)ctx; /* Unused */ + ret = wc_InitRng_ex(rng, NULL, devId); if (ret != 0) { WH_ERROR_PRINT("Failed to wc_InitRng_ex %d\n", ret); @@ -356,9 +356,9 @@ static int whTest_CryptoEcc(whClientContext* ctx, int devId, WC_RNG* rng) } } if (ret == 0) { + word32 sigLen = sizeof(sig); /* Use the shared secret as a random hash */ memcpy(hash, shared_ba, sizeof(hash)); - word32 sigLen = sizeof(sig); ret = wc_ecc_sign_hash((void*)hash, sizeof(hash), (void*)sig, &sigLen, rng, bobKey); @@ -457,8 +457,8 @@ static int whTest_CryptoEcc(whClientContext* ctx, int devId, WC_RNG* rng) } /* Test ECDSA sign/verify with exported keys */ if (ret == 0) { - memcpy(hash, shared_ba, sizeof(hash)); word32 sigLen = sizeof(sig); + memcpy(hash, shared_ba, sizeof(hash)); ret = wc_ecc_sign_hash((void*)hash, sizeof(hash), (void*)sig, &sigLen, rng, bobKey); if (ret != 0) { @@ -590,8 +590,8 @@ static int whTest_CryptoEcc(whClientContext* ctx, int devId, WC_RNG* rng) } /* Test ECDSA sign/verify with cached key */ if (ret == 0) { - memcpy(hash, shared_ba, sizeof(hash)); word32 sigLen = sizeof(sig); + memcpy(hash, shared_ba, sizeof(hash)); ret = wc_ecc_sign_hash((void*)hash, sizeof(hash), (void*)sig, &sigLen, rng, bobKey); if (ret != 0) { @@ -1016,8 +1016,6 @@ static int whTest_Ed25519ImportToServer(whClientContext* ctx, int devId, static int whTest_CryptoEd25519Inline(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)ctx; - int ret = 0; ed25519_key key[1] = {0}; ed25519_key pubKey[1] = {0}; @@ -1029,6 +1027,8 @@ static int whTest_CryptoEd25519Inline(whClientContext* ctx, int devId, byte pubKeyRaw[ED25519_PUB_KEY_SIZE]; word32 pubKeySize = sizeof(pubKeyRaw); + (void)ctx; + ret = wc_ed25519_init_ex(key, NULL, devId); if (ret != 0) { WH_ERROR_PRINT("Failed to initialize Ed25519 key: %d\n", ret); @@ -1479,7 +1479,6 @@ static int whTest_CryptoCurve25519(whClientContext* ctx, int devId, WC_RNG* rng) #ifndef NO_SHA256 static int whTest_CryptoSha256(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)ctx; (void)rng; /* Not currently used */ int ret = WH_ERROR_OK; wc_Sha256 sha256[1]; uint8_t out[WC_SHA256_DIGEST_SIZE]; @@ -1499,6 +1498,8 @@ static int whTest_CryptoSha256(whClientContext* ctx, int devId, WC_RNG* rng) 0x78, 0x1d, 0x94, 0xd6, 0xb0, 0x36, 0x9b, 0x36, 0x56, 0x93, 0x0e, 0xf4, 0x47, 0x9b, 0xae, 0xff, 0xfa, 0x1f, 0x36, 0x38, 0x64}; + (void)ctx; (void)rng; /* Not currently used */ + /* Initialize SHA256 structure */ ret = wc_InitSha256_ex(sha256, NULL, devId); if (ret != 0) { @@ -1593,8 +1594,6 @@ static int whTest_CryptoSha256(whClientContext* ctx, int devId, WC_RNG* rng) #ifdef WOLFSSL_SHA224 static int whTest_CryptoSha224(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)ctx; - (void)rng; /* Not currently used */ int ret = WH_ERROR_OK; wc_Sha224 sha224[1]; uint8_t out[WC_SHA224_DIGEST_SIZE]; @@ -1612,6 +1611,9 @@ static int whTest_CryptoSha224(whClientContext* ctx, int devId, WC_RNG* rng) 0xb4, 0x22, 0xdc, 0xe8, 0xf9, 0x48, 0x8c, 0x4b, 0xc3, 0xef, 0x8e, 0x7d, 0xbe, 0x11, 0xc7, 0x21, 0xba, 0x38, 0xcb, 0x61, 0xf5, 0x6b, 0x7d, 0xc5, 0x30, 0xa7, 0x9c, 0xfd}; + + (void)ctx; (void)rng; /* Not currently used */ + /* Initialize SHA224 structure */ ret = wc_InitSha224_ex(sha224, NULL, devId); if (ret != 0) { @@ -1709,8 +1711,6 @@ static int whTest_CryptoSha224(whClientContext* ctx, int devId, WC_RNG* rng) #ifdef WOLFSSL_SHA384 static int whTest_CryptoSha384(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)ctx; - (void)rng; /* Not currently used */ int ret = WH_ERROR_OK; wc_Sha384 sha384[1]; uint8_t out[WC_SHA384_DIGEST_SIZE]; @@ -1733,6 +1733,9 @@ static int whTest_CryptoSha384(whClientContext* ctx, int devId, WC_RNG* rng) 0x68, 0x49, 0x17, 0xdb, 0x8d, 0x3a, 0x78, 0xab, 0x22, 0xf3, 0xa1, 0x51, 0x70, 0xae, 0x26, 0x80, 0x06, 0x25, 0x99, 0xa5, 0x3d, 0x0f, 0xc3, 0x7a, 0xbd, 0xe1, 0xe2, 0xc6, 0x07, 0xdf, 0xd9, 0x6a, 0x89, 0xa8, 0x2b, 0x99}; + + (void)ctx; (void)rng; /* Not currently used */ + /* Initialize SHA384 structure */ ret = wc_InitSha384_ex(sha384, NULL, devId); if (ret != 0) { @@ -1830,8 +1833,6 @@ static int whTest_CryptoSha384(whClientContext* ctx, int devId, WC_RNG* rng) #ifdef WOLFSSL_SHA512 static int whTest_CryptoSha512(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)ctx; - (void)rng; /* Not currently used */ int ret = WH_ERROR_OK; wc_Sha512 sha512[1]; uint8_t out[WC_SHA512_DIGEST_SIZE]; @@ -1858,6 +1859,9 @@ static int whTest_CryptoSha512(whClientContext* ctx, int devId, WC_RNG* rng) 0xf5, 0x27, 0x9c, 0xe7, 0x80, 0x99, 0x19, 0x9b, 0x91, 0xb3, 0x83, 0x7f, 0x70, 0xaf, 0x8e, 0x02, 0xd9, 0x6d, 0x20, 0xab, 0x1e, 0x72, 0xde, 0x7a, 0x25, 0xa3, 0xe5, 0x60, 0x9e, 0xb0, 0x43}; + + (void)ctx; (void)rng; /* Not currently used */ + /* Initialize SHA512 structure */ ret = wc_InitSha512_ex(sha512, NULL, devId); if (ret != 0) { @@ -1955,8 +1959,6 @@ static int whTest_CryptoSha512(whClientContext* ctx, int devId, WC_RNG* rng) #ifdef HAVE_HKDF static int whTest_CryptoHkdf(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)rng; /* Not currently used */ - int ret = WH_ERROR_OK; #define WH_TEST_HKDF_IKM_SIZE 22 @@ -1984,6 +1986,8 @@ static int whTest_CryptoHkdf(whClientContext* ctx, int devId, WC_RNG* rng) whKeyId key_id = WH_KEYID_ERASED; uint8_t label[] = "HKDF Test Label"; + (void)rng; /* Not currently used */ + /* Test 1: Direct wc_HKDF call (uses crypto callback) */ memset(okm, 0, sizeof(okm)); ret = wc_HKDF_ex(WC_SHA256, ikm, WH_TEST_HKDF_IKM_SIZE, salt, @@ -2164,8 +2168,6 @@ static int whTest_CryptoHkdf(whClientContext* ctx, int devId, WC_RNG* rng) static int whTest_CryptoCmacKdf(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)rng; - int ret = WH_ERROR_OK; /* Test vectors based on wolfSSL CMAC KDF implementation test vectors for @@ -2197,6 +2199,10 @@ static int whTest_CryptoCmacKdf(whClientContext* ctx, int devId, WC_RNG* rng) uint16_t export_len = WH_TEST_CMAC_KDF_OUT_SIZE; whKeyId key_id = WH_KEYID_ERASED; uint8_t keyLabel[] = "CMAC KDF Key"; + whKeyId saltKeyId = WH_KEYID_ERASED; + whKeyId zKeyId = WH_KEYID_ERASED; + + (void)rng; /* 1. Direct wolfCrypt API call that routes through the callback */ memset(out, 0, sizeof(out)); @@ -2267,8 +2273,6 @@ static int whTest_CryptoCmacKdf(whClientContext* ctx, int devId, WC_RNG* rng) } /* 4. Use cached salt and Z inputs */ - whKeyId saltKeyId = WH_KEYID_ERASED; - whKeyId zKeyId = WH_KEYID_ERASED; ret = wh_Client_KeyCache(ctx, WH_NVM_FLAGS_USAGE_DERIVE, NULL, 0, salt, WH_TEST_CMAC_KDF_SALT_SIZE, &saltKeyId); if (ret != 0) { @@ -2409,8 +2413,6 @@ static int whTest_CacheExportKeyDma(whClientContext* ctx, whKeyId* inout_key_id, static int whTest_KeyCache(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)devId; (void)rng; /* Unused */ - #define WH_TEST_KEYCACHE_KEYSIZE 16 int ret; int i; @@ -2421,6 +2423,8 @@ static int whTest_KeyCache(whClientContext* ctx, int devId, WC_RNG* rng) uint8_t labelIn[WH_NVM_LABEL_LEN] = "KeyCache Test Label"; uint8_t labelOut[WH_NVM_LABEL_LEN] = {0}; + (void)devId; (void)rng; /* Unused */ + /* Randomize inputs */ ret = wc_RNG_GenerateBlock(rng, key, sizeof(key)); if (ret != 0) { @@ -2973,9 +2977,6 @@ static int whTest_KeyCache(whClientContext* ctx, int devId, WC_RNG* rng) static int whTest_NonExportableKeystore(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)devId; - (void)rng; - int ret = 0; whKeyId keyId = WH_KEYID_ERASED; uint8_t key[WH_TEST_KEYSTORE_TEST_SZ] = { @@ -2987,6 +2988,8 @@ static int whTest_NonExportableKeystore(whClientContext* ctx, int devId, uint8_t exportedLabel[WH_NVM_LABEL_LEN] = {0}; uint16_t exportedKeySize; + (void)devId; (void)rng; + WH_TEST_PRINT("Testing non-exportable keystore enforcement...\n"); /* Test 1: Cache a key with non-exportable flag and try to export it */ @@ -3129,6 +3132,13 @@ static int whTestCrypto_Aes(whClientContext* ctx, int devId, WC_RNG* rng) whKeyId keyId = WH_KEYID_ERASED; uint8_t labelIn[WH_NVM_LABEL_LEN] = "AES Key Label"; +#ifdef HAVE_AESGCM +#define WH_TEST_AES_AUTHSIZE 16 +#define WH_TEST_AES_TAGSIZE 16 + uint8_t authIn[WH_TEST_AES_AUTHSIZE]; + uint8_t authTag[WH_TEST_AES_TAGSIZE] = { 0 }; +#endif + memset(plainIn, 0xAA, sizeof(plainIn)); /* Randomize inputs */ @@ -3644,11 +3654,6 @@ static int whTestCrypto_Aes(whClientContext* ctx, int devId, WC_RNG* rng) #endif /* HAVE_AES_CBC */ #ifdef HAVE_AESGCM -#define WH_TEST_AES_AUTHSIZE 16 -#define WH_TEST_AES_TAGSIZE 16 - uint8_t authIn[WH_TEST_AES_AUTHSIZE]; - uint8_t authTag[WH_TEST_AES_TAGSIZE] = { 0 }; - /* Generate random auth */ if (ret == 0){ ret = wc_RNG_GenerateBlock(rng, authIn, sizeof(authIn)); @@ -3753,8 +3758,6 @@ static int whTestCrypto_Aes(whClientContext* ctx, int devId, WC_RNG* rng) /* Direct copy of wolfCrypt tests, but using cached keys local to HSM instead */ static int whTestCrypto_Cmac(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)rng; - int ret = 0; Cmac cmac[1]; uint8_t tag[AES_BLOCK_SIZE] = {0}; @@ -3864,6 +3867,8 @@ static int whTestCrypto_Cmac(whClientContext* ctx, int devId, WC_RNG* rng) }; const word32 numCases = sizeof(testCases) / sizeof(testCases[0]); + (void)rng; + for (i = 0; i < numCases && ret == 0; i++) { const CmacTestCase* tc = &testCases[i]; @@ -4077,8 +4082,6 @@ static int whTestCrypto_Cmac(whClientContext* ctx, int devId, WC_RNG* rng) static int whTestCrypto_MlDsaWolfCrypt(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)ctx; - int ret = 0; int verified = 0; @@ -4088,6 +4091,8 @@ static int whTestCrypto_MlDsaWolfCrypt(whClientContext* ctx, int devId, byte sig[DILITHIUM_ML_DSA_44_SIG_SIZE]; word32 sigSz = sizeof(sig); + (void)ctx; + /* Initialize key */ ret = wc_MlDsaKey_Init(&key, NULL, devId); if (ret != 0) { @@ -4166,8 +4171,6 @@ static int whTestCrypto_MlDsaWolfCrypt(whClientContext* ctx, int devId, static int whTestCrypto_MlDsaDmaClient(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)rng; - int ret = 0; MlDsaKey key[1]; MlDsaKey imported_key[1]; @@ -4181,6 +4184,8 @@ static int whTestCrypto_MlDsaDmaClient(whClientContext* ctx, int devId, word32 key_der1_len = sizeof(key_der1); word32 key_der2_len = sizeof(key_der2); + (void)rng; + /* Initialize keys */ ret = wc_MlDsaKey_Init(key, NULL, devId); if (ret != 0) { @@ -4336,8 +4341,6 @@ static int whTestCrypto_MlDsaDmaClient(whClientContext* ctx, int devId, int whTestCrypto_MlDsaVerifyOnlyDma(whClientContext* ctx, int devId, WC_RNG* rng) { - (void)rng; - /* Vectors from wolfCrypt test vectors, but decoupled for isolated usage */ const byte ml_dsa_44_pub_key[] = { 0xd8, 0xac, 0xaf, 0xd8, 0x2e, 0x14, 0x23, 0x78, 0xf7, 0x0d, 0x9a, 0x04, @@ -4702,6 +4705,9 @@ int whTestCrypto_MlDsaVerifyOnlyDma(whClientContext* ctx, int devId, MlDsaKey key[1]; whNvmId keyId = WH_KEYID_ERASED; int evictKey = 0; + int i = 0; + + (void)rng; /* Initialize keys */ ret = wc_MlDsaKey_Init(key, NULL, devId); @@ -4717,7 +4723,6 @@ int whTestCrypto_MlDsaVerifyOnlyDma(whClientContext* ctx, int devId, } /* make dummy msg */ - int i = 0; for (i = 0; i < (int)sizeof(test_msg); i++) { test_msg[i] = (byte)i; } @@ -5883,9 +5888,6 @@ static int wh_ClientServer_MemThreadTest(whTestNvmBackendType nvmType) whNvmConfig n_conf[1] = {0}; whNvmContext nvm[1] = {{0}}; - WH_TEST_RETURN_ON_FAIL( - whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); - /* Crypto context */ whServerCryptoContext crypto[1] = {{ .devId = INVALID_DEVID, @@ -5899,6 +5901,9 @@ static int wh_ClientServer_MemThreadTest(whTestNvmBackendType nvmType) .devId = INVALID_DEVID, }}; + WH_TEST_RETURN_ON_FAIL( + whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); + WH_TEST_RETURN_ON_FAIL(wh_Nvm_Init(nvm, n_conf)); ret = wolfCrypt_Init(); diff --git a/test/wh_test_flash_ramsim.c b/test/wh_test_flash_ramsim.c index fe7ad0d7b..17245e03c 100644 --- a/test/wh_test_flash_ramsim.c +++ b/test/wh_test_flash_ramsim.c @@ -72,6 +72,8 @@ int whTest_Flash_RamSim(void) uint8_t testData[TEST_PAGE_SIZE] = {0}; uint8_t readData[TEST_PAGE_SIZE] = {0}; + uint32_t sector = 0; + uint32_t page = 0; WH_TEST_PRINT("Testing RAM-based flash simulator...\n"); @@ -108,7 +110,6 @@ int whTest_Flash_RamSim(void) return ret; } - uint32_t sector = 0; for (sector = 0; sector < cfg.size / cfg.sectorSize; sector++) { uint32_t sectorOffset = sector * cfg.sectorSize; @@ -131,7 +132,6 @@ int whTest_Flash_RamSim(void) return ret; } - uint32_t page = 0; for (page = 0; page < cfg.sectorSize / cfg.pageSize; page++) { uint32_t pageOffset = sectorOffset + page * cfg.pageSize; diff --git a/test/wh_test_log.c b/test/wh_test_log.c index e58a4ea68..ac4b7864b 100644 --- a/test/wh_test_log.c +++ b/test/wh_test_log.c @@ -889,6 +889,7 @@ static int whTest_LogRingbuf(void) /* Backend storage for ring buffer */ const size_t numLogEntries = 32; whLogEntry ringbuf_buffer[numLogEntries]; + whLogCb ringbufCb = WH_LOG_RINGBUF_CB; /* Setup ring buffer backend */ memset(&logCtx, 0, sizeof(logCtx)); @@ -900,8 +901,6 @@ static int whTest_LogRingbuf(void) ringbufConfig.buffer_size = sizeof(ringbuf_buffer); /* Initialize callback table */ - whLogCb ringbufCb = WH_LOG_RINGBUF_CB; - logConfig.cb = &ringbufCb; logConfig.context = &ringbufCtx; logConfig.config = &ringbufConfig; @@ -1005,6 +1004,8 @@ static int whTest_LogPosixFile(void) const char* test_log_file = "/tmp/wolfhsm_test_log.txt"; int export_count; int iterate_count; + FILE* export_fp = NULL; + char line[2048]; /* Remove any existing test log file */ unlink(test_log_file); @@ -1029,14 +1030,13 @@ static int whTest_LogPosixFile(void) /* Test: Export reads back all entries correctly */ /* For POSIX backend, export to a temp file and count lines */ - FILE* export_fp = tmpfile(); + export_fp = tmpfile(); WH_TEST_ASSERT_RETURN(export_fp != NULL); WH_TEST_RETURN_ON_FAIL(wh_Log_Export(&logCtx, export_fp)); fflush(export_fp); rewind(export_fp); export_count = 0; - char line[2048]; while (fgets(line, sizeof(line), export_fp) != NULL) { export_count++; } @@ -1128,6 +1128,8 @@ static int whTest_LogPosixFileConcurrent(void) pthread_t threads[4]; thread_test_args args[4]; int i; + FILE* verify_fp = NULL; + char line[2048]; /* Remove any existing test log file */ unlink(test_log_file); @@ -1167,7 +1169,7 @@ static int whTest_LogPosixFileConcurrent(void) /* Verify all entries were written */ /* For POSIX backend, export to a temp file and count lines */ - FILE* verify_fp = tmpfile(); + verify_fp = tmpfile(); WH_TEST_ASSERT_RETURN(verify_fp != NULL); WH_TEST_RETURN_ON_FAIL(wh_Log_Export(&logCtx, verify_fp)); fflush(verify_fp); @@ -1175,7 +1177,6 @@ static int whTest_LogPosixFileConcurrent(void) /* Count lines in exported file */ export_count = 0; - char line[2048]; while (fgets(line, sizeof(line), verify_fp) != NULL) { export_count++; } @@ -1311,6 +1312,13 @@ enum { static int _clientServerLogSmokeTest(whClientContext* client) { + /* Basic smoke test: Check that there is at least one log entry in server + * log file */ + + FILE* log_file = NULL; + size_t entry_count = 0; + char line[1024]; + /* Connect to the server, which should trigger an info log entry */ WH_TEST_ASSERT(WH_ERROR_OK == wh_Client_CommInit(client, NULL, NULL)); @@ -1318,14 +1326,9 @@ static int _clientServerLogSmokeTest(whClientContext* client) WH_TEST_RETURN_ON_FAIL(wh_Client_CommClose(client)); /* Now read the log file and verify that the log entries are present */ - FILE* log_file = fopen(WH_LOG_TEST_SERVER_LOG_FILE, "r"); + log_file = fopen(WH_LOG_TEST_SERVER_LOG_FILE, "r"); WH_TEST_ASSERT(log_file != NULL); - /* Basic smoke test: Check that there is at least one log entry in server - * log file */ - size_t entry_count = 0; - char line[1024]; - /* Ensure there are at least 3 log entries and that they are somewhat sanely * ordered */ while (fgets(line, sizeof(line), log_file) != NULL) { @@ -1483,9 +1486,6 @@ static int whTest_LogClientServerMemTransport(void) whNvmConfig n_conf[1] = {0}; whNvmContext nvm[1] = {{0}}; - WH_TEST_RETURN_ON_FAIL(whTest_NvmCfgBackend( - WH_NVM_TEST_BACKEND_FLASH, &nvm_setup, n_conf, fc_conf, fc, fcb)); - #ifndef WOLFHSM_CFG_NO_CRYPTO whServerCryptoContext crypto[1] = {{ .devId = INVALID_DEVID, @@ -1503,8 +1503,6 @@ static int whTest_LogClientServerMemTransport(void) .config = posixCfg, }}; - unlink(WH_LOG_TEST_SERVER_LOG_FILE); - whServerConfig s_conf[1] = {{ .comm_config = cs_conf, .nvm = nvm, @@ -1515,6 +1513,11 @@ static int whTest_LogClientServerMemTransport(void) .logConfig = logConfig, }}; + WH_TEST_RETURN_ON_FAIL(whTest_NvmCfgBackend( + WH_NVM_TEST_BACKEND_FLASH, &nvm_setup, n_conf, fc_conf, fc, fcb)); + + unlink(WH_LOG_TEST_SERVER_LOG_FILE); + WH_TEST_RETURN_ON_FAIL(wh_Nvm_Init(nvm, n_conf)); #ifndef WOLFHSM_CFG_NO_CRYPTO diff --git a/test/wh_test_multiclient.c b/test/wh_test_multiclient.c index 54114cf66..c1b965844 100644 --- a/test/wh_test_multiclient.c +++ b/test/wh_test_multiclient.c @@ -1543,6 +1543,9 @@ static int whTest_MultiClientSequential(void) }}; whServerContext server2[1] = {0}; + uint32_t client_id = 0; + uint32_t server_id = 0; + /* Expose server contexts to connect callbacks */ testServer1 = server1; testServer2 = server2; @@ -1589,9 +1592,6 @@ static int whTest_MultiClientSequential(void) return ret; /* Initialize communication for both clients */ - uint32_t client_id = 0; - uint32_t server_id = 0; - ret = wh_Client_CommInitRequest(client1); if (ret != 0) return ret; diff --git a/test/wh_test_nvm_flash.c b/test/wh_test_nvm_flash.c index 172e0ac45..7b62a63ab 100644 --- a/test/wh_test_nvm_flash.c +++ b/test/wh_test_nvm_flash.c @@ -55,12 +55,12 @@ static void _HexDump(const char* p, size_t data_len) const size_t bytesPerLine = 16; const unsigned char two_digits = 0x10; const unsigned char* u = (const unsigned char*)p; + size_t off = 0; WH_TEST_DEBUG_PRINT(" HD:%p for %lu bytes\n", p, data_len); if ((p == NULL) || (data_len == 0)) return; - size_t off = 0; for (off = 0; off < data_len; off++) { if ((off % bytesPerLine) == 0) WH_TEST_PRINT(" "); @@ -111,9 +111,9 @@ static void _ShowList(const whNvmCb* cb, void* context) id, &listCount, &id); if ((rc == 0) && (listCount > 0)) { + whNvmMetadata myMetadata; WH_TEST_DEBUG_PRINT("Found object id 0x%X (%d) with %d more objects\n", id, id, listCount - 1); - whNvmMetadata myMetadata; memset(&myMetadata, 0, sizeof(myMetadata)); rc = cb->GetMetadata(context, id, &myMetadata); @@ -322,14 +322,6 @@ int whTest_NvmFlashCfg(void* cfg, void* context, const whNvmCb* cb) { int ret = 0; - WH_TEST_RETURN_ON_FAIL(cb->Init(context, cfg)); - -#if defined(WOLFHSM_CFG_DEBUG_VERBOSE) - WH_TEST_DEBUG_PRINT("--Initial NVM contents\n"); - _ShowAvailable(cb, context); - _ShowList(cb, context); -#endif - /* Add 3 new Objects */ unsigned char data1[] = "Data1"; unsigned char data2[] = "Data2"; @@ -347,6 +339,13 @@ int whTest_NvmFlashCfg(void* cfg, void* context, const whNvmCb* cb) whNvmMetadata meta2 = {.id = ids[1], .label = "Label2"}; whNvmMetadata meta3 = {.id = ids[2], .label = "Label3"}; + WH_TEST_RETURN_ON_FAIL(cb->Init(context, cfg)); + + #if defined(WOLFHSM_CFG_DEBUG_VERBOSE) + WH_TEST_DEBUG_PRINT("--Initial NVM contents\n"); + _ShowAvailable(cb, context); + _ShowList(cb, context); + #endif /* Add 3 objects, checking for each object that we can read back what was * written */ @@ -488,8 +487,6 @@ int whTest_NvmFlash_RamSim(void) .memory = memory, }}; - WH_TEST_RETURN_ON_FAIL(whTest_Flash(myCb, myHalFlashCtx, myHalFlashCfg)); - /* NVM Configuration using PosixSim HAL Flash */ whNvmFlashConfig myNvmCfg = { .cb = myCb, @@ -499,9 +496,6 @@ int whTest_NvmFlash_RamSim(void) whNvmFlashContext nvmFlashCtx[1] = {0}; const whNvmCb nvmFlashCb[1] = {WH_NVM_FLASH_CB}; - WH_TEST_RETURN_ON_FAIL( - whTest_NvmFlashCfg(&myNvmCfg, nvmFlashCtx, nvmFlashCb)); - #if defined(WOLFHSM_CFG_SERVER_NVM_FLASH_LOG) whNvmFlashLogConfig myLogCfg = { .flash_cb = myCb, @@ -510,6 +504,14 @@ int whTest_NvmFlash_RamSim(void) }; whNvmFlashLogContext nvmLogCtx[1] = {0}; const whNvmCb nvmLogCb[1] = {WH_NVM_FLASH_LOG_CB}; +#endif /* WOLFHSM_CFG_SERVER_NVM_FLASH_LOG */ + + WH_TEST_RETURN_ON_FAIL(whTest_Flash(myCb, myHalFlashCtx, myHalFlashCfg)); + + WH_TEST_RETURN_ON_FAIL( + whTest_NvmFlashCfg(&myNvmCfg, nvmFlashCtx, nvmFlashCb)); + +#if defined(WOLFHSM_CFG_SERVER_NVM_FLASH_LOG) WH_TEST_RETURN_ON_FAIL(whTest_NvmFlashCfg(&myLogCfg, nvmLogCtx, nvmLogCb)); #endif /* WOLFHSM_CFG_SERVER_NVM_FLASH_LOG */ @@ -636,9 +638,6 @@ int whTest_NvmFlash_PosixFileSim(void) .erased_byte = (~(uint8_t)0), }}; - WH_TEST_RETURN_ON_FAIL(whTest_Flash(myCb, myHalFlashContext, - myHalFlashConfig)); - /* NVM Configuration using PosixSim HAL Flash */ whNvmFlashConfig myNvmCfg = { .cb = myCb, @@ -648,6 +647,19 @@ int whTest_NvmFlash_PosixFileSim(void) whNvmFlashContext nvmFlashCtx[1] = {0}; const whNvmCb nvmFlashCb[1] = {WH_NVM_FLASH_CB}; +#if defined(WOLFHSM_CFG_SERVER_NVM_FLASH_LOG) + whNvmFlashLogConfig myLogCfg = { + .flash_cb = myCb, + .flash_ctx = myHalFlashContext, + .flash_cfg = myHalFlashConfig, + }; + whNvmFlashLogContext nvmLogCtx[1] = {0}; + const whNvmCb nvmLogCb[1] = {WH_NVM_FLASH_LOG_CB}; +#endif /* WOLFHSM_CFG_SERVER_NVM_FLASH_LOG */ + + WH_TEST_RETURN_ON_FAIL(whTest_Flash(myCb, myHalFlashContext, + myHalFlashConfig)); + WH_TEST_ASSERT(0 == whTest_NvmFlashCfg(&myNvmCfg, nvmFlashCtx, nvmFlashCb)); @@ -660,14 +672,6 @@ int whTest_NvmFlash_PosixFileSim(void) memset(myHalFlashContext, 0, sizeof(myHalFlashContext)); - whNvmFlashLogConfig myLogCfg = { - .flash_cb = myCb, - .flash_ctx = myHalFlashContext, - .flash_cfg = myHalFlashConfig, - }; - whNvmFlashLogContext nvmLogCtx[1] = {0}; - const whNvmCb nvmLogCb[1] = {WH_NVM_FLASH_LOG_CB}; - WH_TEST_RETURN_ON_FAIL(whTest_NvmFlashCfg(&myLogCfg, nvmLogCtx, nvmLogCb)); #endif /* WOLFHSM_CFG_SERVER_NVM_FLASH_LOG */ diff --git a/test/wh_test_nvmflags.c b/test/wh_test_nvmflags.c index 00ec332c4..bd644c568 100644 --- a/test/wh_test_nvmflags.c +++ b/test/wh_test_nvmflags.c @@ -48,6 +48,7 @@ static int _testNonExportableNvmAccess(whClientContext* client) uint8_t nvmLabel[WH_NVM_LABEL_LEN] = "NonExportableNvmObj"; int32_t out_rc = 0; whNvmSize out_len = 0; + whNvmId destroyList[] = {nvmId}; WH_TEST_PRINT("Testing non-exportable NVM object access protection...\n"); @@ -77,8 +78,7 @@ static int _testNonExportableNvmAccess(whClientContext* client) WH_TEST_PRINT("Non-exportable NVM object read correctly denied\n"); /* Clean up NVM object */ - whNvmId destroyList[] = {nvmId}; - out_rc = 0; + out_rc = 0; wh_Client_NvmDestroyObjects(client, 1, destroyList, &out_rc); /* Test 2: Verify exportable NVM objects can still be read */ diff --git a/test/wh_test_posix_threadsafe_stress.c b/test/wh_test_posix_threadsafe_stress.c index fb4c6a0fc..e599d434e 100644 --- a/test/wh_test_posix_threadsafe_stress.c +++ b/test/wh_test_posix_threadsafe_stress.c @@ -1947,13 +1947,17 @@ static void* contentionClientThread(void* arg) ClientServerPair* pair = (ClientServerPair*)arg; StressTestContext* ctx = pair->sharedCtx; int rc; - int localIteration; + int localIteration = 0; /* Wait for all threads to start */ pthread_barrier_wait(&ctx->startBarrier); /* Always call barrier first, then check exit flag - prevents deadlock */ while (1) { + ContentionPhase phase; + whKeyId keyId; + ClientRole role; + /* ===== SETUP PHASE (once per phase) ===== */ pthread_barrier_wait(&ctx->setupBarrier); if (ATOMIC_LOAD_INT(&ctx->globalStopFlag)) { @@ -1978,10 +1982,9 @@ static void* contentionClientThread(void* arg) /* ===== STREAMING PHASE (tight loop, no barriers) ===== */ pthread_barrier_wait(&ctx->streamStartBarrier); - ContentionPhase phase = ctx->currentPhase; - whKeyId keyId = ctx->currentKeyId; - ClientRole role = ctx->clientRoles[pair->clientId]; - localIteration = 0; + phase = ctx->currentPhase; + keyId = ctx->currentKeyId; + role = ctx->clientRoles[pair->clientId]; /* Stream requests until phaseRunning becomes 0 */ while (ATOMIC_LOAD_INT(&ctx->phaseRunning)) { @@ -2037,6 +2040,7 @@ static int validatePhaseResult(StressTestContext* ctx, ContentionPhase phase, uint32_t counter = 0; int opACount = 0; int i; + uint32_t expectedMin; /* Count how many threads were doing increments (ROLE_OP_A) */ for (i = 0; i < NUM_CLIENTS; i++) { @@ -2059,7 +2063,7 @@ static int validatePhaseResult(StressTestContext* ctx, ContentionPhase phase, * Account for errors: totalIterations counts all attempts, * but totalErrors counts unacceptable failures that didn't * increment */ - uint32_t expectedMin = totalIterations - totalErrors; + expectedMin = totalIterations - totalErrors; WH_TEST_PRINT(" Counter validation: value=%u, expected_min=%u " "(iters=%d, errors=%d)\n", diff --git a/test/wh_test_server_img_mgr.c b/test/wh_test_server_img_mgr.c index dbd4e1484..624771d6e 100644 --- a/test/wh_test_server_img_mgr.c +++ b/test/wh_test_server_img_mgr.c @@ -210,6 +210,9 @@ static int whTest_ServerImgMgrServerCfgEcc256(whServerConfig* serverCfg) whServerImgMgrImg testImage = {0}; const whNvmId testEccKeyId = 1; const whNvmId testEccSigNvmId = 2; + word32 inOutIdx = 0; + int verifyResult = 0; + uint8_t corruptedSig[128]; /* ECC key and signature variables */ ecc_key eccKey; @@ -221,8 +224,12 @@ static int whTest_ServerImgMgrServerCfgEcc256(whServerConfig* serverCfg) uint8_t pubKeyDer[ECC_BUFSIZE]; word32 pubKeyDerLen = sizeof(pubKeyDer); - /* NVM metadata for signature */ + /* NVM metadata for signature and key */ whNvmMetadata sigMeta = {0}; + whNvmMetadata keyMeta = {0}; + + whServerImgMgrVerifyResult result; + whServerImgMgrVerifyResult results[1]; /* Initialize wolfCrypt */ ret = wc_InitRng(&rng); @@ -239,9 +246,8 @@ static int whTest_ServerImgMgrServerCfgEcc256(whServerConfig* serverCfg) } /* Generate or import the test ECC key */ - word32 inOutIdx = 0; - ret = wc_EccPrivateKeyDecode(testEccPrivKey, &inOutIdx, &eccKey, - sizeof(testEccPrivKey)); + ret= wc_EccPrivateKeyDecode(testEccPrivKey, &inOutIdx, &eccKey, + sizeof(testEccPrivKey)); if (ret != 0) { WH_ERROR_PRINT("Failed to decode ECC private key: %d\n", ret); wc_ecc_free(&eccKey); @@ -298,9 +304,8 @@ static int whTest_ServerImgMgrServerCfgEcc256(whServerConfig* serverCfg) } /* Verify the signature directly to ensure it's correct */ - int verifyResult = 0; - ret = wc_ecc_verify_hash(signature, sigLen, hash, sizeof(hash), - &verifyResult, &eccKey); + ret = wc_ecc_verify_hash(signature, sigLen, hash, sizeof(hash), + &verifyResult, &eccKey); if (ret != 0 || verifyResult != 1) { WH_ERROR_PRINT("Direct signature verification failed: ret=%d, result=%d\n", ret, verifyResult); @@ -360,11 +365,10 @@ static int whTest_ServerImgMgrServerCfgEcc256(whServerConfig* serverCfg) } /* Cache the public key in the keystore */ - whNvmMetadata keyMeta = {0}; - keyMeta.id = testEccKeyId; - keyMeta.access = WH_NVM_ACCESS_ANY; - keyMeta.flags = WH_NVM_FLAGS_NONE; - keyMeta.len = pubKeyDerLen; + keyMeta.id = testEccKeyId; + keyMeta.access = WH_NVM_ACCESS_ANY; + keyMeta.flags = WH_NVM_FLAGS_NONE; + keyMeta.len = pubKeyDerLen; snprintf((char*)keyMeta.label, WH_NVM_LABEL_LEN, "TestKey"); ret = wh_Server_KeystoreCacheKey(server, &keyMeta, pubKeyDer); @@ -389,7 +393,6 @@ static int whTest_ServerImgMgrServerCfgEcc256(whServerConfig* serverCfg) } /* Test image verification */ - whServerImgMgrVerifyResult result; ret = wh_Server_ImgMgrVerifyImg(&imgMgr, &testImage, &result); if (ret != WH_ERROR_OK) { WH_ERROR_PRINT("Image verification failed: %d\n", ret); @@ -454,7 +457,6 @@ static int whTest_ServerImgMgrServerCfgEcc256(whServerConfig* serverCfg) } /* Test verify all */ - whServerImgMgrVerifyResult results[1]; ret = wh_Server_ImgMgrVerifyAll(&imgMgr, results, 1, NULL); if (ret != WH_ERROR_OK) { WH_ERROR_PRINT("Verify all images failed: %d\n", ret); @@ -490,7 +492,6 @@ static int whTest_ServerImgMgrServerCfgEcc256(whServerConfig* serverCfg) /* Negative test: corrupt signature and verify failure */ /* Read current signature from NVM */ - uint8_t corruptedSig[128]; ret = wh_Nvm_Read(serverCfg->nvm, testEccSigNvmId, 0, sigLen, corruptedSig); if (ret != WH_ERROR_OK) { WH_ERROR_PRINT("Failed to read signature for negative test: %d\n", ret); @@ -587,9 +588,14 @@ static int whTest_ServerImgMgrServerCfgAes128Cmac(whServerConfig* serverCfg) Cmac cmac; uint8_t computed_cmac[AES_BLOCK_SIZE]; word32 cmac_size = sizeof(computed_cmac); + uint8_t corruptedCmac[AES_BLOCK_SIZE]; - /* NVM metadata for signature */ + /* NVM metadata for signature and key */ whNvmMetadata sigMeta = {0}; + whNvmMetadata keyMeta = {0}; + + whServerImgMgrVerifyResult result; + whServerImgMgrVerifyResult results[1]; /* Initialize CMAC and compute the expected signature */ ret = wc_InitCmac(&cmac, testAes128Key, sizeof(testAes128Key), WC_CMAC_AES, @@ -652,11 +658,10 @@ static int whTest_ServerImgMgrServerCfgAes128Cmac(whServerConfig* serverCfg) } /* Cache the AES128 key in the keystore */ - whNvmMetadata keyMeta = {0}; - keyMeta.id = testAesCmacKeyId; - keyMeta.access = WH_NVM_ACCESS_ANY; - keyMeta.flags = WH_NVM_FLAGS_NONE; - keyMeta.len = sizeof(testAes128Key); + keyMeta.id = testAesCmacKeyId; + keyMeta.access = WH_NVM_ACCESS_ANY; + keyMeta.flags = WH_NVM_FLAGS_NONE; + keyMeta.len = sizeof(testAes128Key); snprintf((char*)keyMeta.label, WH_NVM_LABEL_LEN, "TestAes128Key"); ret = wh_Server_KeystoreCacheKey(server, &keyMeta, (uint8_t*)testAes128Key); @@ -675,7 +680,6 @@ static int whTest_ServerImgMgrServerCfgAes128Cmac(whServerConfig* serverCfg) } /* Test image verification */ - whServerImgMgrVerifyResult result; ret = wh_Server_ImgMgrVerifyImg(&imgMgr, &testImage, &result); if (ret != WH_ERROR_OK) { WH_ERROR_PRINT("CMAC image verification failed: %d\n", ret); @@ -722,7 +726,6 @@ static int whTest_ServerImgMgrServerCfgAes128Cmac(whServerConfig* serverCfg) } /* Test verify all */ - whServerImgMgrVerifyResult results[1]; ret = wh_Server_ImgMgrVerifyAll(&imgMgr, results, 1, NULL); if (ret != WH_ERROR_OK) { WH_ERROR_PRINT("CMAC verify all images failed: %d\n", ret); @@ -749,7 +752,6 @@ static int whTest_ServerImgMgrServerCfgAes128Cmac(whServerConfig* serverCfg) /* Negative test: corrupt signature and verify failure */ /* Read current signature from NVM */ - uint8_t corruptedCmac[AES_BLOCK_SIZE]; ret = wh_Nvm_Read(serverCfg->nvm, testAesCmacSigNvmId, 0, cmac_size, corruptedCmac); if (ret != WH_ERROR_OK) { @@ -821,6 +823,7 @@ static int whTest_ServerImgMgrServerCfgRsa2048(whServerConfig* serverCfg) whServerImgMgrImg testImage = {0}; const whNvmId testRsaKeyId = 1; const whNvmId testRsaSigNvmId = 2; + word32 inOutIdx = 0; /* RSA key and signature variables */ RsaKey rsaKey; @@ -831,9 +834,16 @@ static int whTest_ServerImgMgrServerCfgRsa2048(whServerConfig* serverCfg) word32 sigLen = sizeof(signature); uint8_t pubKeyDer[512]; /* conservative size for DER encoding */ word32 pubKeyDerLen = sizeof(pubKeyDer); + uint8_t decrypted[256]; + word32 decryptedLen = sizeof(decrypted); + uint8_t corruptedRsaSig[256]; - /* NVM metadata for signature */ + /* NVM metadata for signature and key */ whNvmMetadata sigMeta = {0}; + whNvmMetadata keyMeta = {0}; + + whServerImgMgrVerifyResult result; + whServerImgMgrVerifyResult results[1]; ret = wc_InitRng(&rng); if (ret != 0) { @@ -849,7 +859,6 @@ static int whTest_ServerImgMgrServerCfgRsa2048(whServerConfig* serverCfg) } /* Import the test RSA private key */ - word32 inOutIdx = 0; ret = wc_RsaPrivateKeyDecode(testRsa2048PrivKey, &inOutIdx, &rsaKey, sizeof(testRsa2048PrivKey)); if (ret != 0) { @@ -908,8 +917,6 @@ static int whTest_ServerImgMgrServerCfgRsa2048(whServerConfig* serverCfg) sigLen = (word32)ret; /* Verify the signature directly to ensure it's correct */ - uint8_t decrypted[256]; - word32 decryptedLen = sizeof(decrypted); ret = wc_RsaSSL_Verify(signature, sigLen, decrypted, decryptedLen, &rsaKey); if (ret <= 0) { WH_ERROR_PRINT("Direct signature verification failed: %d\n", ret); @@ -979,11 +986,10 @@ static int whTest_ServerImgMgrServerCfgRsa2048(whServerConfig* serverCfg) } /* Cache the public key in the keystore */ - whNvmMetadata keyMeta = {0}; - keyMeta.id = testRsaKeyId; - keyMeta.access = WH_NVM_ACCESS_ANY; - keyMeta.flags = WH_NVM_FLAGS_NONE; - keyMeta.len = pubKeyDerLen; + keyMeta.id = testRsaKeyId; + keyMeta.access = WH_NVM_ACCESS_ANY; + keyMeta.flags = WH_NVM_FLAGS_NONE; + keyMeta.len = pubKeyDerLen; snprintf((char*)keyMeta.label, WH_NVM_LABEL_LEN, "TestRsaKey"); ret = wh_Server_KeystoreCacheKey(server, &keyMeta, pubKeyDer); @@ -1008,7 +1014,6 @@ static int whTest_ServerImgMgrServerCfgRsa2048(whServerConfig* serverCfg) } /* Test image verification */ - whServerImgMgrVerifyResult result; ret = wh_Server_ImgMgrVerifyImg(&imgMgr, &testImage, &result); if (ret != WH_ERROR_OK) { WH_ERROR_PRINT("RSA image verification failed: %d\n", ret); @@ -1073,7 +1078,6 @@ static int whTest_ServerImgMgrServerCfgRsa2048(whServerConfig* serverCfg) } /* Test verify all */ - whServerImgMgrVerifyResult results[1]; ret = wh_Server_ImgMgrVerifyAll(&imgMgr, results, 1, NULL); if (ret != WH_ERROR_OK) { WH_ERROR_PRINT("RSA verify all images failed: %d\n", ret); @@ -1109,7 +1113,6 @@ static int whTest_ServerImgMgrServerCfgRsa2048(whServerConfig* serverCfg) /* Negative test: corrupt signature and verify failure */ /* Read current signature from NVM */ - uint8_t corruptedRsaSig[256]; ret = wh_Nvm_Read(serverCfg->nvm, testRsaSigNvmId, 0, sigLen, corruptedRsaSig); if (ret != WH_ERROR_OK) { @@ -1233,9 +1236,6 @@ int whTest_ServerImgMgr(whTestNvmBackendType nvmType) whNvmConfig n_conf[1] = {0}; whNvmContext nvm[1] = {{0}}; - WH_TEST_RETURN_ON_FAIL( - whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); - whServerCryptoContext crypto[1] = {{ .devId = INVALID_DEVID, }}; @@ -1246,6 +1246,9 @@ int whTest_ServerImgMgr(whTestNvmBackendType nvmType) .crypto = crypto, }}; + WH_TEST_RETURN_ON_FAIL( + whTest_NvmCfgBackend(nvmType, &nvm_setup, n_conf, fc_conf, fc, fcb)); + /* Initialize NVM */ rc = wh_Nvm_Init(nvm, n_conf); if (rc != 0) { diff --git a/test/wh_test_she.c b/test/wh_test_she.c index ea918fcd9..7e86637e1 100644 --- a/test/wh_test_she.c +++ b/test/wh_test_she.c @@ -568,7 +568,6 @@ static int wh_ClientServer_MemThreadTest(void) }}; whServerSheContext she[1]; - memset(she, 0, sizeof(she)); whServerConfig s_conf[1] = {{ .comm_config = cs_conf, @@ -578,6 +577,8 @@ static int wh_ClientServer_MemThreadTest(void) .devId = INVALID_DEVID, }}; + memset(she, 0, sizeof(she)); + WH_TEST_RETURN_ON_FAIL(wh_Nvm_Init(nvm, n_conf)); WH_TEST_RETURN_ON_FAIL(wolfCrypt_Init());