diff --git a/X9.146/gen_dual_keysig_cert.c b/X9.146/gen_dual_keysig_cert.c index a90428d3c..a9408b722 100644 --- a/X9.146/gen_dual_keysig_cert.c +++ b/X9.146/gen_dual_keysig_cert.c @@ -28,6 +28,7 @@ #include #include #include +#include #if defined(WOLFSSL_DUAL_ALG_CERTS) @@ -121,6 +122,7 @@ static int do_certgen(int argc, char** argv) #endif /* !GEN_ROOT_CERT */ int initPreTBS = 0; ecc_key altCaKey; + int initAltCaKey = 0; word32 idx = 0; #if 0 @@ -241,6 +243,7 @@ static int do_certgen(int argc, char** argv) printf("Decoding the CA alt private key\n"); ret = wc_ecc_init(&altCaKey); if (ret != 0) goto exit; + initAltCaKey = 1; idx = 0; ret = wc_EccPrivateKeyDecode(altPrivBuf, &idx, &altCaKey, @@ -368,12 +371,20 @@ static int do_certgen(int argc, char** argv) printf("SUCCESS!\n"); exit: + wc_ForceZero(caKeyBuf, sizeof(caKeyBuf)); +#ifndef GEN_ROOT_CERT + wc_ForceZero(serverKeyBuf, sizeof(serverKeyBuf)); +#endif + wc_ForceZero(altPrivBuf, sizeof(altPrivBuf)); + if (initCaKey) wc_FreeRsaKey(&caKey); #ifndef GEN_ROOT_CERT if (initServerKey) wc_FreeRsaKey(&serverKey); #endif + if (initAltCaKey) + wc_ecc_free(&altCaKey); if (initPreTBS) wc_FreeDecodedCert(&preTBS); if (initRng) diff --git a/X9.146/gen_ecdsa_mldsa_dual_keysig_cert.c b/X9.146/gen_ecdsa_mldsa_dual_keysig_cert.c index 521f5d229..8f3baa9f7 100644 --- a/X9.146/gen_ecdsa_mldsa_dual_keysig_cert.c +++ b/X9.146/gen_ecdsa_mldsa_dual_keysig_cert.c @@ -28,6 +28,7 @@ #include #include #include +#include #if defined(WOLFSSL_DUAL_ALG_CERTS) && defined(HAVE_DILITHIUM) @@ -153,6 +154,7 @@ static int do_certgen(int argc, char** argv) #endif /* !GEN_ROOT_CERT */ int initPreTBS = 0; dilithium_key altCaKey; + int initAltCaKey = 0; word32 idx = 0; byte level = 0; @@ -257,6 +259,7 @@ static int do_certgen(int argc, char** argv) printf("Decoding the CA alt private key\n"); wc_dilithium_init(&altCaKey); + initAltCaKey = 1; ret = wc_dilithium_set_level(&altCaKey, level); if (ret < 0) goto exit; @@ -445,12 +448,20 @@ static int do_certgen(int argc, char** argv) printf("SUCCESS!\n"); exit: + wc_ForceZero(caKeyBuf, sizeof(caKeyBuf)); +#ifndef GEN_ROOT_CERT + wc_ForceZero(serverKeyBuf, sizeof(serverKeyBuf)); +#endif + wc_ForceZero(altPrivBuf, sizeof(altPrivBuf)); + if (initCaKey) wc_ecc_free(&caKey); #ifndef GEN_ROOT_CERT if (initServerKey) wc_ecc_free(&serverKey); #endif + if (initAltCaKey) + wc_dilithium_free(&altCaKey); if (initPreTBS) wc_FreeDecodedCert(&preTBS); if (initRng) diff --git a/X9.146/gen_rsa_mldsa_dual_keysig_cert.c b/X9.146/gen_rsa_mldsa_dual_keysig_cert.c index 26c2a2bf5..e2f21ab57 100644 --- a/X9.146/gen_rsa_mldsa_dual_keysig_cert.c +++ b/X9.146/gen_rsa_mldsa_dual_keysig_cert.c @@ -28,6 +28,7 @@ #include #include #include +#include #if defined(WOLFSSL_DUAL_ALG_CERTS) && defined(HAVE_DILITHIUM) @@ -138,6 +139,7 @@ static int do_certgen(int argc, char** argv) #endif /* !GEN_ROOT_CERT */ int initPreTBS = 0; dilithium_key altCaKey; + int initAltCaKey = 0; word32 idx = 0; #if 0 @@ -217,6 +219,7 @@ static int do_certgen(int argc, char** argv) printf("Decoding the CA alt private key\n"); wc_dilithium_init(&altCaKey); + initAltCaKey = 1; ret = wc_dilithium_set_level(&altCaKey, 2); if (ret < 0) goto exit; @@ -356,12 +359,20 @@ static int do_certgen(int argc, char** argv) printf("SUCCESS!\n"); exit: + wc_ForceZero(caKeyBuf, sizeof(caKeyBuf)); +#ifndef GEN_ROOT_CERT + wc_ForceZero(serverKeyBuf, sizeof(serverKeyBuf)); +#endif + wc_ForceZero(altPrivBuf, sizeof(altPrivBuf)); + if (initCaKey) wc_FreeRsaKey(&caKey); #ifndef GEN_ROOT_CERT if (initServerKey) wc_FreeRsaKey(&serverKey); #endif + if (initAltCaKey) + wc_dilithium_free(&altCaKey); if (initPreTBS) wc_FreeDecodedCert(&preTBS); if (initRng) diff --git a/btle/ecies/ecc-client.c b/btle/ecies/ecc-client.c index c1cde09a4..adce09481 100644 --- a/btle/ecies/ecc-client.c +++ b/btle/ecies/ecc-client.c @@ -43,6 +43,7 @@ int main(int argc, char** argv) word32 plainSz; ecc_key myKey, peerKey; int type; + int initRng = 0; wolfCrypt_Init(); @@ -70,6 +71,7 @@ int main(int argc, char** argv) printf("wc_InitRng failed! %d\n", ret); goto cleanup; } + initRng = 1; ret = wc_ecc_make_key(&rng, 32, &myKey); if (ret != 0) { @@ -216,6 +218,13 @@ int main(int argc, char** argv) cleanup: + wc_ecc_free(&myKey); + wc_ecc_free(&peerKey); + if (cliCtx != NULL) + wc_ecc_ctx_free(cliCtx); + if (initRng) + wc_FreeRng(&rng); + if (devCtx != NULL) btle_close(devCtx); diff --git a/btle/ecies/ecc-server.c b/btle/ecies/ecc-server.c index 54110b79f..2c6025df5 100644 --- a/btle/ecies/ecc-server.c +++ b/btle/ecies/ecc-server.c @@ -43,6 +43,7 @@ int main(int argc, char** argv) word32 plainSz; ecc_key myKey, peerKey; int type; + int initRng = 0; wolfCrypt_Init(); @@ -71,6 +72,7 @@ int main(int argc, char** argv) printf("wc_InitRng failed! %d\n", ret); goto cleanup; } + initRng = 1; ret = wc_ecc_make_key(&rng, 32, &myKey); if (ret != 0) { @@ -206,6 +208,13 @@ int main(int argc, char** argv) cleanup: + wc_ecc_free(&myKey); + wc_ecc_free(&peerKey); + if (srvCtx != NULL) + wc_ecc_ctx_free(srvCtx); + if (initRng) + wc_FreeRng(&rng); + if (devCtx != NULL) btle_close(devCtx); diff --git a/can-bus/client.c b/can-bus/client.c index 5f729189a..46a218944 100644 --- a/can-bus/client.c +++ b/can-bus/client.c @@ -28,6 +28,7 @@ int main(int argc, char *argv[]) WOLFSSL_CTX *ctx = NULL; WOLFSSL_METHOD* method = NULL; WOLFSSL* ssl = NULL; + char *receive_buffer = NULL; int ret; if (argc != 2) { @@ -40,7 +41,7 @@ int main(int argc, char *argv[]) return ret; } - ret = setup_ssl(SERVICE_TYPE_CLIENT, &ctx, &method, &ssl); + ret = setup_ssl(SERVICE_TYPE_CLIENT, &ctx, &method, &ssl, &receive_buffer); if (ret) { return ret; } @@ -58,7 +59,7 @@ int main(int argc, char *argv[]) free(line); } - close_ssl(ctx, ssl); + close_ssl(ctx, ssl, receive_buffer); return 0; } diff --git a/can-bus/common.c b/can-bus/common.c index 66ccffb0a..b4d650dd0 100644 --- a/can-bus/common.c +++ b/can-bus/common.c @@ -111,6 +111,7 @@ int can_connect(const char *address, uint16_t filter) addr.can_ifindex = ifr.ifr_ifindex; if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("Bind error\n"); + close(sock); return -1; } @@ -122,7 +123,7 @@ void can_close() close(can_con_info.sock); } -void close_ssl(WOLFSSL_CTX *ctx, WOLFSSL *ssl) +void close_ssl(WOLFSSL_CTX *ctx, WOLFSSL *ssl, char *receive_buffer) { if (ssl) { int ret = WOLFSSL_SHUTDOWN_NOT_DONE; @@ -134,11 +135,12 @@ void close_ssl(WOLFSSL_CTX *ctx, WOLFSSL *ssl) int err = wolfSSL_get_error(ssl, ret); fprintf(stderr, "Error shutting down TLS connection: %d, %s", err, wolfSSL_ERR_error_string(err, buffer)); - return; } } can_close(); + free(receive_buffer); + wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); wolfSSL_Cleanup(); @@ -170,13 +172,19 @@ int setup_connection(const char *interface, int local_id, int remote_id) } int setup_ssl(enum service_type type, WOLFSSL_CTX **new_ctx, - WOLFSSL_METHOD **new_method, WOLFSSL **new_ssl) + WOLFSSL_METHOD **new_method, WOLFSSL **new_ssl, + char **new_receive_buffer) { int ret; WOLFSSL_CTX *ctx = NULL; WOLFSSL_METHOD* method = NULL; WOLFSSL* ssl = NULL; char *receive_buffer = malloc(ISOTP_DEFAULT_BUFFER_SIZE); + if (receive_buffer == NULL) { + fprintf(stderr, "Could not allocate receive buffer\n"); + close_ssl(NULL, NULL, NULL); + return -1; + } if (type == SERVICE_TYPE_CLIENT) { method = wolfTLSv1_3_client_method(); @@ -186,13 +194,14 @@ int setup_ssl(enum service_type type, WOLFSSL_CTX **new_ctx, if (!method) { fprintf(stderr, "Could not init wolfSSL method\n"); + close_ssl(NULL, NULL, receive_buffer); return -1; } ctx = wolfSSL_CTX_new(method); if (!ctx) { fprintf(stderr, "Could not init wolfSSL context\n"); - close_ssl(NULL, NULL); + close_ssl(NULL, NULL, receive_buffer); return -1; } @@ -208,7 +217,7 @@ int setup_ssl(enum service_type type, WOLFSSL_CTX **new_ctx, if (ret != WOLFSSL_SUCCESS) { fprintf(stderr, "ERROR: failed to load cert, " "please check the file.\n"); - close_ssl(ctx, NULL); + close_ssl(ctx, NULL, receive_buffer); return -1; } @@ -217,7 +226,7 @@ int setup_ssl(enum service_type type, WOLFSSL_CTX **new_ctx, WOLFSSL_FILETYPE_PEM)) != WOLFSSL_SUCCESS) { fprintf(stderr, "ERROR: failed to load key file, " "please check the file.\n"); - close_ssl(ctx, NULL); + close_ssl(ctx, NULL, receive_buffer); return -1; } } @@ -225,7 +234,7 @@ int setup_ssl(enum service_type type, WOLFSSL_CTX **new_ctx, ssl = wolfSSL_new(ctx); if (!ssl) { fprintf(stderr, "Could not init wolfSSL\n"); - close_ssl(ctx, NULL); + close_ssl(ctx, NULL, receive_buffer); return -1; } @@ -245,12 +254,13 @@ int setup_ssl(enum service_type type, WOLFSSL_CTX **new_ctx, int err = wolfSSL_get_error(ssl, ret); fprintf(stderr, "ERROR: failed to connect using wolfSSL: %d, %s\n", err, wolfSSL_ERR_error_string(err, buffer)); - close_ssl(ctx, ssl); + close_ssl(ctx, ssl, receive_buffer); return -1; } *new_ctx = ctx; *new_method = method; *new_ssl = ssl; + *new_receive_buffer = receive_buffer; printf("SSL handshake done!\n"); diff --git a/can-bus/common.h b/can-bus/common.h index 314c785ff..8c181245e 100644 --- a/can-bus/common.h +++ b/can-bus/common.h @@ -57,8 +57,9 @@ int can_send(struct isotp_can_data *data, void *arg); int can_connect(const char *address, uint16_t filter); void can_close(void); -void close_ssl(WOLFSSL_CTX *ctx, WOLFSSL *ssl); +void close_ssl(WOLFSSL_CTX *ctx, WOLFSSL *ssl, char *receive_buffer); int setup_connection(const char *interface, int local_id, int remote_id); int setup_ssl(enum service_type type, WOLFSSL_CTX **new_ctx, - WOLFSSL_METHOD **new_method, WOLFSSL **new_ssl); + WOLFSSL_METHOD **new_method, WOLFSSL **new_ssl, + char **new_receive_buffer); #endif /* __CANCOMMON_H__ */ diff --git a/can-bus/server.c b/can-bus/server.c index 83ac466cc..b681821db 100644 --- a/can-bus/server.c +++ b/can-bus/server.c @@ -30,6 +30,7 @@ int main(int argc, char *argv[]) WOLFSSL_CTX *ctx = NULL; WOLFSSL_METHOD* method = NULL; WOLFSSL* ssl = NULL; + char *receive_buffer = NULL; int ret; if (argc != 2) { @@ -42,7 +43,7 @@ int main(int argc, char *argv[]) return ret; } - ret = setup_ssl(SERVICE_TYPE_SERVER, &ctx, &method, &ssl); + ret = setup_ssl(SERVICE_TYPE_SERVER, &ctx, &method, &ssl, &receive_buffer); if (ret) { return ret; } @@ -57,7 +58,7 @@ int main(int argc, char *argv[]) } } - close_ssl(ctx, ssl); + close_ssl(ctx, ssl, receive_buffer); return 0; } diff --git a/certfields/extract-pubkey-from-certfile/main.c b/certfields/extract-pubkey-from-certfile/main.c index 9ca2c74a0..b930aa2ba 100644 --- a/certfields/extract-pubkey-from-certfile/main.c +++ b/certfields/extract-pubkey-from-certfile/main.c @@ -36,8 +36,8 @@ int main(void) { int ret = -1; #ifdef OPENSSL_EXTRA - WOLFSSL_X509* x509cert; - WOLFSSL_EVP_PKEY* pubKeyTmp; + WOLFSSL_X509* x509cert = NULL; + WOLFSSL_EVP_PKEY* pubKeyTmp = NULL; RsaKey pubKey; char* certFName = "../../certs/client-cert.pem"; word32 idx = 0; @@ -55,16 +55,27 @@ int main(void) pubKeyTmp = wolfSSL_X509_get_pubkey(x509cert); if (pubKeyTmp == NULL) { printf("Failed to extract public key, abort!\n"); + wolfSSL_X509_free(x509cert); return ret; } printf("Extracted public key successfully\n"); /* setup a key structure to receive the extracted key */ - wc_InitRsaKey(&pubKey, 0); + ret = wc_InitRsaKey(&pubKey, 0); + if (ret != 0) { + printf("Failed to init RSA key, abort!\n"); + wolfSSL_EVP_PKEY_free(pubKeyTmp); + wolfSSL_X509_free(x509cert); + return ret; + } + ret = wc_RsaPublicKeyDecode((byte*)pubKeyTmp->pkey.ptr, &idx, &pubKey, (word32) pubKeyTmp->pkey_sz); if (ret != 0) { printf("Failed to decode public key from pubKeyTmp, abort!\n"); + wc_FreeRsaKey(&pubKey); + wolfSSL_EVP_PKEY_free(pubKeyTmp); + wolfSSL_X509_free(x509cert); return ret; } printf("Successfully decoded public key\n"); @@ -74,10 +85,9 @@ int main(void) printf("%02X", pubKeyTmp->pkey.ptr[i] & 0xFF); } printf("\n"); - + wc_FreeRsaKey(&pubKey); wolfSSL_EVP_PKEY_free(pubKeyTmp); wolfSSL_X509_free(x509cert); - wc_FreeRsaKey(&pubKey); #else printf("Please configure wolfssl with --enable-opensslextra to try using\n" "this example\n"); diff --git a/certgen/certgen_ca_example.c b/certgen/certgen_ca_example.c index 3e2dcdea1..9616cb1bc 100644 --- a/certgen/certgen_ca_example.c +++ b/certgen/certgen_ca_example.c @@ -27,6 +27,7 @@ #include #include #include +#include #if defined(WOLFSSL_CERT_REQ) && defined(WOLFSSL_CERT_GEN) && \ defined(WOLFSSL_KEY_GEN) && defined(HAVE_ECC) @@ -137,6 +138,7 @@ static int do_cagen(int argc, char** argv) fclose(file); printf("Successfully converted the DER to PEM to \"%s\"\n\n", pemKeyOutput); + wc_ForceZero(pemBuf, LARGE_TEMP_SZ); XFREE(pemBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); pemBuf = NULL; #endif @@ -212,7 +214,11 @@ static int do_cagen(int argc, char** argv) exit: + if (derBuf != NULL) + wc_ForceZero(derBuf, LARGE_TEMP_SZ); XFREE(derBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (pemBuf != NULL) + wc_ForceZero(pemBuf, LARGE_TEMP_SZ); XFREE(pemBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (initNewKey) diff --git a/certgen/certgen_example.c b/certgen/certgen_example.c index 0759d64c5..0dd431ee2 100644 --- a/certgen/certgen_example.c +++ b/certgen/certgen_example.c @@ -26,6 +26,7 @@ #include #include #include +#include #if defined(WOLFSSL_CERT_REQ) && defined(WOLFSSL_CERT_GEN) && \ defined(WOLFSSL_KEY_GEN) && defined(HAVE_ECC) @@ -255,6 +256,8 @@ static int do_certgen(int argc, char** argv) XFREE(derBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); XFREE(pemBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (caKeyBuf != NULL) + wc_ForceZero(caKeyBuf, LARGE_TEMP_SZ); XFREE(caKeyBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (initCaKey) diff --git a/certgen/csr_w_ed25519_example.c b/certgen/csr_w_ed25519_example.c index dc010cb4a..65d0ab930 100644 --- a/certgen/csr_w_ed25519_example.c +++ b/certgen/csr_w_ed25519_example.c @@ -23,6 +23,7 @@ #include #include #include +#include #define MAX_TEMP_SIZE 1024 @@ -117,6 +118,8 @@ int main(void) printf("%s", pem); exit: + wc_ForceZero(der, sizeof(der)); + wc_ForceZero(pem, sizeof(pem)); wc_ed25519_free(&key); wc_FreeRng(&rng); diff --git a/certgen/custom_ext.c b/certgen/custom_ext.c index 2716ea6be..b0912ba56 100644 --- a/certgen/custom_ext.c +++ b/certgen/custom_ext.c @@ -224,7 +224,11 @@ static int do_certgen(int argc, char** argv) XFREE(derBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); XFREE(pemBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(caKeyBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (caKeyBuf != NULL) { + /* Zero the CA private key material before releasing the buffer. */ + wc_ForceZero(caKeyBuf, LARGE_TEMP_SZ); + XFREE(caKeyBuf, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + } if (initCaKey) wc_ecc_free(&caKey); diff --git a/crypto/3des/3des-file-encrypt.c b/crypto/3des/3des-file-encrypt.c index aa82d372a..b41692a5e 100644 --- a/crypto/3des/3des-file-encrypt.c +++ b/crypto/3des/3des-file-encrypt.c @@ -23,11 +23,17 @@ #include #include #include +#include +#include #include #include #include #include +#ifndef XPRINTF + #define XPRINTF printf +#endif + #define DES3_BLOCK_SIZE 24 /* size of encryption blocks */ #define SALT_SIZE 8 @@ -61,8 +67,8 @@ int Des3Encrypt(Des3* des3, byte* key, int size, FILE* inFile, FILE* outFile) { WC_RNG rng; byte iv[DES3_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int i = 0; @@ -70,6 +76,8 @@ int Des3Encrypt(Des3* des3, byte* key, int size, FILE* inFile, FILE* outFile) int inputLength; int length; int padCounter = 0; + int rngInit = 0; + int des3Init = 0; fseek(inFile, 0, SEEK_END); inputLength = ftell(inFile); @@ -82,62 +90,99 @@ int Des3Encrypt(Des3* des3, byte* key, int size, FILE* inFile, FILE* outFile) padCounter++; } - input = malloc(length); - output = malloc(length); + input = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1050; + } - ret = wc_InitRng(&rng); - if (ret != 0) { - printf("Failed to initialize random number generator\n"); - return -1030; + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, inputLength, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; - } - for (i = inputLength; i < length; i++) { - /* pads the added characters with the number of pads */ - input[i] = padCounter; + ret = fread(input, 1, inputLength, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + for (i = inputLength; i < length; i++) { + /* pads the added characters with the number of pads */ + input[i] = padCounter; + } + } } - ret = wc_RNG_GenerateBlock(&rng, iv, DES3_BLOCK_SIZE); - if (ret != 0) - return -1020; + if (ret == 0) { + ret = wc_RNG_GenerateBlock(&rng, iv, DES3_BLOCK_SIZE); + if (ret != 0) + ret = -1020; + } /* stretches key to fit size */ - ret = GenerateKey(&rng, key, size, salt, padCounter); - if (ret != 0) - return -1040; + if (ret == 0) { + ret = GenerateKey(&rng, key, size, salt, padCounter); + if (ret != 0) + ret = -1040; + } + + /* inits des3 structure */ + if (ret == 0) { + ret = wc_Des3Init(des3, NULL, INVALID_DEVID); + if (ret != 0) + XPRINTF("Des3Init returned: %d\n", ret); + else + des3Init = 1; + } /* sets key */ - ret = wc_Des3_SetKey(des3, key, iv, DES_ENCRYPTION); - if (ret != 0) - return -1001; + if (ret == 0) { + ret = wc_Des3_SetKey(des3, key, iv, DES_ENCRYPTION); + if (ret != 0) + ret = -1001; + } /* encrypts the message to the output based on input length + padding */ - ret = wc_Des3_CbcEncrypt(des3, output, input, length); - if (ret != 0) - return -1005; + if (ret == 0) { + ret = wc_Des3_CbcEncrypt(des3, output, input, length); + if (ret != 0) + ret = -1005; + } - /* writes to outFile */ - fwrite(salt, 1, SALT_SIZE, outFile); - fwrite(iv, 1, DES3_BLOCK_SIZE, outFile); - fwrite(output, 1, length, outFile); + if (ret == 0) { + /* writes to outFile */ + fwrite(salt, 1, SALT_SIZE, outFile); + fwrite(iv, 1, DES3_BLOCK_SIZE, outFile); + fwrite(output, 1, length, outFile); + } /* closes the opened files and frees the memory*/ - memset(input, 0, length); - memset(output, 0, length); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, length); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, length); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); - wc_FreeRng(&rng); + if (des3Init) + wc_Des3Free(des3); + if (rngInit) + wc_FreeRng(&rng); - return 0; + return ret; } /* @@ -147,81 +192,122 @@ int Des3Decrypt(Des3* des3, byte* key, int size, FILE* inFile, FILE* outFile) { WC_RNG rng; byte iv[DES3_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int i = 0; int ret = 0; int length; int aSize; + int rngInit = 0; + int des3Init = 0; fseek(inFile, 0, SEEK_END); length = ftell(inFile); fseek(inFile, 0, SEEK_SET); aSize = length; - input = malloc(aSize); - output = malloc(aSize); + input = (byte*)XMALLOC(aSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(aSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1051; + } - wc_InitRng(&rng); + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; + } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, length, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; - } - for (i = 0; i < SALT_SIZE; i++) { - /* finds salt from input message */ - salt[i] = input[i]; - } - for (i = SALT_SIZE; i < DES3_BLOCK_SIZE + SALT_SIZE; i++) { - /* finds iv from input message */ - iv[i - SALT_SIZE] = input[i]; + ret = fread(input, 1, length, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + for (i = 0; i < SALT_SIZE; i++) { + /* finds salt from input message */ + salt[i] = input[i]; + } + for (i = SALT_SIZE; i < DES3_BLOCK_SIZE + SALT_SIZE; i++) { + /* finds iv from input message */ + iv[i - SALT_SIZE] = input[i]; + } + } } /* replicates old key if keys match */ - ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, 4096, - size, WC_SHA256); - if (ret != 0) - return -1050; + if (ret == 0) { + ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, + 4096, size, WC_SHA256); + if (ret != 0) + ret = -1050; + } + + /* inits des3 structure */ + if (ret == 0) { + ret = wc_Des3Init(des3, NULL, INVALID_DEVID); + if (ret != 0) + XPRINTF("Des3Init returned: %d\n", ret); + else + des3Init = 1; + } /* sets key */ - ret = wc_Des3_SetKey(des3, key, iv, DES_DECRYPTION); - if (ret != 0) - return -1002; + if (ret == 0) { + ret = wc_Des3_SetKey(des3, key, iv, DES_DECRYPTION); + if (ret != 0) + ret = -1002; + } - /* change length to remove salt/iv block from being decrypted */ - length -= (DES3_BLOCK_SIZE + SALT_SIZE); - for (i = 0; i < length; i++) { - /* shifts message: ignores salt/iv on message*/ - input[i] = input[i + (DES3_BLOCK_SIZE + SALT_SIZE)]; + if (ret == 0) { + /* change length to remove salt/iv block from being decrypted */ + length -= (DES3_BLOCK_SIZE + SALT_SIZE); + for (i = 0; i < length; i++) { + /* shifts message: ignores salt/iv on message*/ + input[i] = input[i + (DES3_BLOCK_SIZE + SALT_SIZE)]; + } + /* decrypts the message to output based on input length + padding */ + ret = wc_Des3_CbcDecrypt(des3, output, input, length); + if (ret != 0) + ret = -1006; } - /* decrypts the message to output based on input length + padding */ - ret = wc_Des3_CbcDecrypt(des3, output, input, length); - if (ret != 0) - return -1006; - if (salt[0] != 0) { - /* reduces length based on number of padded elements */ - length -= output[length-1]; + if (ret == 0) { + if (salt[0] != 0) { + /* reduces length based on number of padded elements */ + length -= output[length-1]; + } + /* writes output to the outFile based on shortened length */ + fwrite(output, 1, length, outFile); } - /* writes output to the outFile based on shortened length */ - fwrite(output, 1, length, outFile); /* closes the opened files and frees the memory*/ - memset(input, 0, aSize); - memset(output, 0, aSize); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, aSize); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, aSize); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); - wc_FreeRng(&rng); + if (des3Init) + wc_Des3Free(des3); + if (rngInit) + wc_FreeRng(&rng); - return 0; + return ret; } /* @@ -229,11 +315,11 @@ int Des3Decrypt(Des3* des3, byte* key, int size, FILE* inFile, FILE* outFile) */ void help() { - printf("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); - printf("Usage: ./3des-encrypt <-option> " + XPRINTF("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); + XPRINTF("Usage: ./3des-encrypt <-option> " "\n\n"); - printf("Options\n"); - printf("-d Decryption\n-e Encryption\n-h Help\n"); + XPRINTF("Options\n"); + XPRINTF("-d Decryption\n-e Encryption\n-h Help\n"); } /* @@ -242,29 +328,36 @@ void help() int NoEcho(char* key, int size) { struct termios oflags, nflags; + int isTTY; - /* disabling echo */ - tcgetattr(fileno(stdin), &oflags); - nflags = oflags; - nflags.c_lflag &= ~ECHO; - nflags.c_lflag |= ECHONL; + isTTY = isatty(fileno(stdin)); - if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { - printf("Error: tcsetattr failed to disable terminal echo\n"); - return -1060; + if (isTTY) { + /* disabling echo */ + tcgetattr(fileno(stdin), &oflags); + nflags = oflags; + nflags.c_lflag &= ~ECHO; + nflags.c_lflag |= ECHONL; + + if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { + XPRINTF("Error: tcsetattr failed to disable terminal echo\n"); + return -1060; + } } - printf("Unique Password: "); + XPRINTF("Unique Password: "); if (fgets(key, size, stdin) == NULL) { - printf("Error: fgets failed to retrieve secure key input\n"); + XPRINTF("Error: fgets failed to retrieve secure key input\n"); return -1070; } key[strlen(key) - 1] = 0; - /* restore terminal */ - if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { - printf("Error: tcsetattr failed to enable terminal echo\n"); - return -1080; + if (isTTY) { + /* restore terminal */ + if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { + XPRINTF("Error: tcsetattr failed to enable terminal echo\n"); + return -1080; + } } return 0; } @@ -275,7 +368,7 @@ int SizeCheck(int size) if (size != 56 && size != 112 && size != 168) { /* if the entered size does not match acceptable size */ - printf("Invalid 3DES key size\n"); + XPRINTF("Invalid 3DES key size\n"); ret = -1080; } @@ -326,7 +419,7 @@ int main(int argc, char** argv) break; case '?': if (optopt) { - printf("Ending Session\n"); + XPRINTF("Ending Session\n"); return -111; } default: @@ -335,20 +428,31 @@ int main(int argc, char** argv) } if (inCheck == 0 || outCheck == 0) { - printf("Must have both input and output file"); - printf(": -i filename -o filename\n"); + XPRINTF("Must have both input and output file"); + XPRINTF(": -i filename -o filename\n"); } else if (ret == 0 && choice != 'n') { - key = malloc(size); /* sets size memory of key */ - ret = NoEcho((char*)key, size); - if (choice == 'e') - Des3Encrypt(&des3, key, size, inFile, outFile); - else if (choice == 'd') - Des3Decrypt(&des3, key, size, inFile, outFile); + key = (byte*)XMALLOC(size, NULL, DYNAMIC_TYPE_TMP_BUFFER); /* sets size memory of key */ + if (key == NULL) { + XPRINTF("Failed to allocate memory for key\n"); + ret = -1050; + } + else { + ret = NoEcho((char*)key, size); + if (ret == 0) { + if (choice == 'e') + ret = Des3Encrypt(&des3, key, size, inFile, outFile); + else if (choice == 'd') + ret = Des3Decrypt(&des3, key, size, inFile, outFile); + } + else { + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + } } else if (choice == 'n') { - printf("Must select either -e[56,112,168] or -d[56,112,168] for \ + XPRINTF("Must select either -e[56,112,168] or -d[56,112,168] for \ encryption and decryption\n"); } diff --git a/crypto/aes/aes-file-encrypt.c b/crypto/aes/aes-file-encrypt.c index 1da8f4ed5..a67500e46 100644 --- a/crypto/aes/aes-file-encrypt.c +++ b/crypto/aes/aes-file-encrypt.c @@ -27,11 +27,17 @@ #include #endif #include +#include +#include #include #include #include #include +#ifndef XPRINTF + #define XPRINTF printf +#endif + #if defined(HAVE_PBKDF2) && !defined(NO_PWDBASED) #define SALT_SIZE 8 @@ -69,8 +75,8 @@ int AesEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) { WC_RNG rng; byte iv[AES_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int i = 0; @@ -78,6 +84,8 @@ int AesEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) int inputLength; int length; int padCounter = 0; + int rngInit = 0; + int aesInit = 0; fseek(inFile, 0, SEEK_END); inputLength = ftell(inFile); @@ -90,69 +98,99 @@ int AesEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) padCounter++; } - input = malloc(length); - output = malloc(length); + input = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1050; + } - ret = wc_InitRng(&rng); - if (ret != 0) { - printf("Failed to initialize random number generator\n"); - return -1030; + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, inputLength, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; - } - for (i = inputLength; i < length; i++) { - /* pads the added characters with the number of pads */ - input[i] = padCounter; + ret = fread(input, 1, inputLength, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + for (i = inputLength; i < length; i++) { + /* pads the added characters with the number of pads */ + input[i] = padCounter; + } + } } - ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); - if (ret != 0) - return -1020; + if (ret == 0) { + ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); + if (ret != 0) + ret = -1020; + } /* stretches key to fit size */ - ret = GenerateKey(&rng, key, size, salt, padCounter); - if (ret != 0) - return -1040; + if (ret == 0) { + ret = GenerateKey(&rng, key, size, salt, padCounter); + if (ret != 0) + ret = -1040; + } /* inits aes structure */ - ret = wc_AesInit(aes, NULL, INVALID_DEVID); - if (ret != 0) { - printf("AesInit returned: %d\n", ret); - return -1001; + if (ret == 0) { + ret = wc_AesInit(aes, NULL, INVALID_DEVID); + if (ret != 0) + XPRINTF("AesInit returned: %d\n", ret); + else + aesInit = 1; } /* sets key */ - ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); - if (ret != 0) { - printf("SetKey returned: %d\n", ret); - return -1001; + if (ret == 0) { + ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); + if (ret != 0) { + XPRINTF("SetKey returned: %d\n", ret); + ret = -1001; + } } /* encrypts the message to the output based on input length + padding */ - ret = wc_AesCbcEncrypt(aes, output, input, length); - if (ret != 0) - return -1005; + if (ret == 0) { + ret = wc_AesCbcEncrypt(aes, output, input, length); + if (ret != 0) + ret = -1005; + } - /* writes to outFile */ - fwrite(salt, 1, SALT_SIZE, outFile); - fwrite(iv, 1, AES_BLOCK_SIZE, outFile); - fwrite(output, 1, length, outFile); + if (ret == 0) { + /* writes to outFile */ + fwrite(salt, 1, SALT_SIZE, outFile); + fwrite(iv, 1, AES_BLOCK_SIZE, outFile); + fwrite(output, 1, length, outFile); + } /* closes the opened files and frees the memory*/ - memset(input, 0, length); - memset(output, 0, length); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, length); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, length); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); - wc_FreeRng(&rng); + if (aesInit) + wc_AesFree(aes); + if (rngInit) + wc_FreeRng(&rng); return ret; } @@ -164,90 +202,125 @@ int AesDecrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) { WC_RNG rng; byte iv[AES_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int i = 0; int ret = 0; int length; int aSize; + int rngInit = 0; + int aesInit = 0; fseek(inFile, 0, SEEK_END); length = ftell(inFile); fseek(inFile, 0, SEEK_SET); aSize = length; - input = malloc(aSize); - output = malloc(aSize); + input = (byte*)XMALLOC(aSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(aSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1051; + } - wc_InitRng(&rng); + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; + } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, length, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; - } - for (i = 0; i < SALT_SIZE; i++) { - /* finds salt from input message */ - salt[i] = input[i]; - } - for (i = SALT_SIZE; i < AES_BLOCK_SIZE + SALT_SIZE; i++) { - /* finds iv from input message */ - iv[i - SALT_SIZE] = input[i]; + ret = fread(input, 1, length, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + for (i = 0; i < SALT_SIZE; i++) { + /* finds salt from input message */ + salt[i] = input[i]; + } + for (i = SALT_SIZE; i < AES_BLOCK_SIZE + SALT_SIZE; i++) { + /* finds iv from input message */ + iv[i - SALT_SIZE] = input[i]; + } + } } /* replicates old key if keys match */ - ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, 4096, - size, WC_SHA256); - if (ret != 0) - return -1050; + if (ret == 0) { + ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, + 4096, size, WC_SHA256); + if (ret != 0) + ret = -1050; + } /* inits aes structure */ - ret = wc_AesInit(aes, NULL, INVALID_DEVID); - if (ret != 0) { - printf("AesInit returned: %d\n", ret); - return -1001; + if (ret == 0) { + ret = wc_AesInit(aes, NULL, INVALID_DEVID); + if (ret != 0) + XPRINTF("AesInit returned: %d\n", ret); + else + aesInit = 1; } /* sets key */ - ret = wc_AesSetKey(aes, key, size, iv, AES_DECRYPTION); - if (ret != 0) { - printf("SetKey returned: %d\n", ret); - return -1002; + if (ret == 0) { + ret = wc_AesSetKey(aes, key, size, iv, AES_DECRYPTION); + if (ret != 0) { + XPRINTF("SetKey returned: %d\n", ret); + ret = -1002; + } } - /* change length to remove salt/iv block from being decrypted */ - length -= (AES_BLOCK_SIZE + SALT_SIZE); - for (i = 0; i < length; i++) { - /* shifts message: ignores salt/iv on message*/ - input[i] = input[i + (AES_BLOCK_SIZE + SALT_SIZE)]; + if (ret == 0) { + /* change length to remove salt/iv block from being decrypted */ + length -= (AES_BLOCK_SIZE + SALT_SIZE); + for (i = 0; i < length; i++) { + /* shifts message: ignores salt/iv on message*/ + input[i] = input[i + (AES_BLOCK_SIZE + SALT_SIZE)]; + } + /* decrypts the message to output based on input length + padding*/ + ret = wc_AesCbcDecrypt(aes, output, input, length); + if (ret != 0) { + ret = -1006; + } } - /* decrypts the message to output based on input length + padding*/ - ret = wc_AesCbcDecrypt(aes, output, input, length); - if (ret != 0) - return -1006; - if (salt[0] != 0) { - /* reduces length based on number of padded elements */ - length -= output[length-1]; + if (ret == 0) { + if (salt[0] != 0) { + /* reduces length based on number of padded elements */ + length -= output[length-1]; + } + /* writes output to the outFile based on shortened length */ + fwrite(output, 1, length, outFile); } - /* writes output to the outFile based on shortened length */ - fwrite(output, 1, length, outFile); /* closes the opened files and frees the memory*/ - memset(input, 0, aSize); - memset(output, 0, aSize); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, aSize); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, aSize); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); - wc_FreeRng(&rng); + if (aesInit) + wc_AesFree(aes); + if (rngInit) + wc_FreeRng(&rng); - return 0; + return ret; } /* @@ -255,11 +328,11 @@ int AesDecrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) */ void help() { - printf("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); - printf("Usage: ./aes-file-encrypt <-option> <-i file.in> " + XPRINTF("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); + XPRINTF("Usage: ./aes-file-encrypt <-option> <-i file.in> " "<-o file.out>\n\n"); - printf("Options\n"); - printf("-d Decryption\n-e Encryption\n-h Help\n"); + XPRINTF("Options\n"); + XPRINTF("-d Decryption\n-e Encryption\n-h Help\n"); } /* @@ -268,30 +341,37 @@ void help() int NoEcho(char* key, int size) { struct termios oflags, nflags; + int isTTY; + + isTTY = isatty(fileno(stdin)); - /* disabling echo */ - tcgetattr(fileno(stdin), &oflags); - nflags = oflags; - nflags.c_lflag &= ~ECHO; - nflags.c_lflag |= ECHONL; + if (isTTY) { + /* disabling echo */ + tcgetattr(fileno(stdin), &oflags); + nflags = oflags; + nflags.c_lflag &= ~ECHO; + nflags.c_lflag |= ECHONL; - if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { - printf("Error: tcsetattr failed to disable terminal echo\n"); - return -1060; + if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { + XPRINTF("Error: tcsetattr failed to disable terminal echo\n"); + return -1060; + } } - printf("Unique Password: "); + XPRINTF("Unique Password: "); if (fgets(key, size, stdin) == NULL) { - printf("Error: fgets failed to retrieve secure key input\n"); + XPRINTF("Error: fgets failed to retrieve secure key input\n"); return -1070; } key[strlen(key) - 1] = 0; - /* restore terminal */ - if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { - printf("Error: tcsetattr failed to enable terminal echo\n"); - return -1080; + if (isTTY) { + /* restore terminal */ + if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { + XPRINTF("Error: tcsetattr failed to enable terminal echo\n"); + return -1080; + } } return 0; } @@ -312,7 +392,7 @@ int SizeCheck(int *size) } else { /* if the entered size does not match acceptable size */ - printf("Invalid AES key size\n"); + XPRINTF("Invalid AES key size\n"); ret = -1080; } @@ -363,7 +443,7 @@ int main(int argc, char** argv) break; case '?': if (optopt) { - printf("Ending Session\n"); + XPRINTF("Ending Session\n"); return -111; } default: @@ -371,19 +451,30 @@ int main(int argc, char** argv) } } if (inCheck == 0 || outCheck == 0) { - printf("Must have both input and output file"); - printf(": -i filename -o filename\n"); + XPRINTF("Must have both input and output file"); + XPRINTF(": -i filename -o filename\n"); } else if (ret == 0 && choice != 'n' && inFile != NULL) { - key = malloc(size); /* sets size memory of key */ - ret = NoEcho((char*)key, size); - if (choice == 'e') - AesEncrypt(&aes, key, size, inFile, outFile); - else if (choice == 'd') - AesDecrypt(&aes, key, size, inFile, outFile); + key = (byte*)XMALLOC(size, NULL, DYNAMIC_TYPE_TMP_BUFFER); /* sets size memory of key */ + if (key == NULL) { + XPRINTF("Failed to allocate memory for key\n"); + ret = -1050; + } + else { + ret = NoEcho((char*)key, size); + if (ret == 0) { + if (choice == 'e') + ret = AesEncrypt(&aes, key, size, inFile, outFile); + else if (choice == 'd') + ret = AesDecrypt(&aes, key, size, inFile, outFile); + } + else { + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + } } else if (choice == 'n') { - printf("Must select either -e[128, 192, 256] or -d[128, 192, 256] \ + XPRINTF("Must select either -e[128, 192, 256] or -d[128, 192, 256] \ for encryption and decryption\n"); ret = -110; } @@ -394,7 +485,7 @@ int main(int argc, char** argv) #else int main() { - printf("pwdbased and HAVE_PBKDF2 not compiled in\n"); + XPRINTF("pwdbased and HAVE_PBKDF2 not compiled in\n"); return 0; } #endif diff --git a/crypto/aes/aescfb-file-encrypt.c b/crypto/aes/aescfb-file-encrypt.c index 5c173687f..bfea3da53 100644 --- a/crypto/aes/aescfb-file-encrypt.c +++ b/crypto/aes/aescfb-file-encrypt.c @@ -23,11 +23,17 @@ #include #include #include +#include +#include #include #include #include #include +#ifndef XPRINTF + #define XPRINTF printf +#endif + #if defined(WOLFSSL_AES_CFB) && defined(HAVE_PBKDF2) && \ !defined(NO_PWDBASED) #define SALT_SIZE 8 @@ -62,8 +68,8 @@ int AesEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) { WC_RNG rng; byte iv[AES_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int i = 0; @@ -71,6 +77,8 @@ int AesEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) int inputLength; int length; int padCounter = 0; + int rngInit = 0; + int aesInit = 0; fseek(inFile, 0, SEEK_END); inputLength = ftell(inFile); @@ -83,69 +91,99 @@ int AesEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) padCounter++; } - input = malloc(length); - output = malloc(length); + input = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1050; + } - ret = wc_InitRng(&rng); - if (ret != 0) { - printf("Failed to initialize random number generator\n"); - return -1030; + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, inputLength, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; - } - for (i = inputLength; i < length; i++) { - /* pads the added characters with the number of pads */ - input[i] = padCounter; + ret = fread(input, 1, inputLength, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + for (i = inputLength; i < length; i++) { + /* pads the added characters with the number of pads */ + input[i] = padCounter; + } + } } - ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); - if (ret != 0) - return -1020; + if (ret == 0) { + ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); + if (ret != 0) + ret = -1020; + } /* stretches key to fit size */ - ret = GenerateKey(&rng, key, size, salt, padCounter); - if (ret != 0) - return -1040; + if (ret == 0) { + ret = GenerateKey(&rng, key, size, salt, padCounter); + if (ret != 0) + ret = -1040; + } /* inits aes structure */ - ret = wc_AesInit(aes, NULL, INVALID_DEVID); - if (ret != 0) { - printf("AesInit returned: %d\n", ret); - return -1001; + if (ret == 0) { + ret = wc_AesInit(aes, NULL, INVALID_DEVID); + if (ret != 0) + XPRINTF("AesInit returned: %d\n", ret); + else + aesInit = 1; } /* sets key */ - ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); - if (ret != 0) { - printf("SetKey returned: %d\n", ret); - return -1001; + if (ret == 0) { + ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); + if (ret != 0) { + XPRINTF("SetKey returned: %d\n", ret); + ret = -1001; + } } /* encrypts the message to the output based on input length + padding */ - ret = wc_AesCfbEncrypt(aes, output, input, length); - if (ret != 0) - return -1005; + if (ret == 0) { + ret = wc_AesCfbEncrypt(aes, output, input, length); + if (ret != 0) + ret = -1005; + } - /* writes to outFile */ - fwrite(salt, 1, SALT_SIZE, outFile); - fwrite(iv, 1, AES_BLOCK_SIZE, outFile); - fwrite(output, 1, length, outFile); + if (ret == 0) { + /* writes to outFile */ + fwrite(salt, 1, SALT_SIZE, outFile); + fwrite(iv, 1, AES_BLOCK_SIZE, outFile); + fwrite(output, 1, length, outFile); + } /* closes the opened files and frees the memory*/ - memset(input, 0, length); - memset(output, 0, length); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, length); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, length); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); - wc_FreeRng(&rng); + if (aesInit) + wc_AesFree(aes); + if (rngInit) + wc_FreeRng(&rng); return ret; } @@ -157,91 +195,125 @@ int AesDecrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) { WC_RNG rng; byte iv[AES_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int i = 0; int ret = 0; int length; int aSize; + int rngInit = 0; + int aesInit = 0; fseek(inFile, 0, SEEK_END); length = ftell(inFile); fseek(inFile, 0, SEEK_SET); aSize = length; - input = malloc(aSize); - output = malloc(aSize); + input = (byte*)XMALLOC(aSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(aSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1051; + } - wc_InitRng(&rng); + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; + } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, length, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; - } - for (i = 0; i < SALT_SIZE; i++) { - /* finds salt from input message */ - salt[i] = input[i]; - } - for (i = SALT_SIZE; i < AES_BLOCK_SIZE + SALT_SIZE; i++) { - /* finds iv from input message */ - iv[i - SALT_SIZE] = input[i]; + ret = fread(input, 1, length, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + for (i = 0; i < SALT_SIZE; i++) { + /* finds salt from input message */ + salt[i] = input[i]; + } + for (i = SALT_SIZE; i < AES_BLOCK_SIZE + SALT_SIZE; i++) { + /* finds iv from input message */ + iv[i - SALT_SIZE] = input[i]; + } + } } /* replicates old key if keys match */ - ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, 4096, - size, WC_SHA256); - if (ret != 0) - return -1050; + if (ret == 0) { + ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, + 4096, size, WC_SHA256); + if (ret != 0) + ret = -1050; + } /* inits aes structure */ - ret = wc_AesInit(aes, NULL, INVALID_DEVID); - if (ret != 0) { - printf("AesInit returned: %d\n", ret); - return -1002; + if (ret == 0) { + ret = wc_AesInit(aes, NULL, INVALID_DEVID); + if (ret != 0) + XPRINTF("AesInit returned: %d\n", ret); + else + aesInit = 1; } /* sets key */ /* decrypt uses AES_ENCRYPTION */ - ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); - if (ret != 0) { - printf("SetKey returned: %d\n", ret); - return -1002; + if (ret == 0) { + ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); + if (ret != 0) { + XPRINTF("SetKey returned: %d\n", ret); + ret = -1002; + } } - /* change length to remove salt/iv block from being decrypted */ - length -= (AES_BLOCK_SIZE + SALT_SIZE); - for (i = 0; i < length; i++) { - /* shifts message: ignores salt/iv on message*/ - input[i] = input[i + (AES_BLOCK_SIZE + SALT_SIZE)]; + if (ret == 0) { + /* change length to remove salt/iv block from being decrypted */ + length -= (AES_BLOCK_SIZE + SALT_SIZE); + for (i = 0; i < length; i++) { + /* shifts message: ignores salt/iv on message*/ + input[i] = input[i + (AES_BLOCK_SIZE + SALT_SIZE)]; + } + /* decrypts the message to output based on input length + padding*/ + ret = wc_AesCfbDecrypt(aes, output, input, length); + if (ret != 0) + ret = -1006; } - /* decrypts the message to output based on input length + padding*/ - ret = wc_AesCfbDecrypt(aes, output, input, length); - if (ret != 0) - return -1006; - if (salt[0] != 0) { - /* reduces length based on number of padded elements */ - length -= output[length-1]; + if (ret == 0) { + if (salt[0] != 0) { + /* reduces length based on number of padded elements */ + length -= output[length-1]; + } + /* writes output to the outFile based on shortened length */ + fwrite(output, 1, length, outFile); } - /* writes output to the outFile based on shortened length */ - fwrite(output, 1, length, outFile); /* closes the opened files and frees the memory*/ - memset(input, 0, aSize); - memset(output, 0, aSize); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, aSize); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, aSize); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); - wc_FreeRng(&rng); + if (aesInit) + wc_AesFree(aes); + if (rngInit) + wc_FreeRng(&rng); - return 0; + return ret; } /* @@ -249,11 +321,11 @@ int AesDecrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) */ void help() { - printf("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); - printf("Usage: ./aes-file-encrypt <-option> <-i file.in> " + XPRINTF("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); + XPRINTF("Usage: ./aes-file-encrypt <-option> <-i file.in> " "<-o file.out>\n\n"); - printf("Options\n"); - printf("-d Decryption\n-e Encryption\n-h Help\n"); + XPRINTF("Options\n"); + XPRINTF("-d Decryption\n-e Encryption\n-h Help\n"); } /* @@ -262,30 +334,37 @@ void help() int NoEcho(char* key, int size) { struct termios oflags, nflags; + int isTTY; + + isTTY = isatty(fileno(stdin)); - /* disabling echo */ - tcgetattr(fileno(stdin), &oflags); - nflags = oflags; - nflags.c_lflag &= ~ECHO; - nflags.c_lflag |= ECHONL; + if (isTTY) { + /* disabling echo */ + tcgetattr(fileno(stdin), &oflags); + nflags = oflags; + nflags.c_lflag &= ~ECHO; + nflags.c_lflag |= ECHONL; - if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { - printf("Error: tcsetattr failed to disable terminal echo\n"); - return -1060; + if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { + XPRINTF("Error: tcsetattr failed to disable terminal echo\n"); + return -1060; + } } - printf("Unique Password: "); + XPRINTF("Unique Password: "); if (fgets(key, size, stdin) == NULL) { - printf("Error: fgets failed to retrieve secure key input\n"); + XPRINTF("Error: fgets failed to retrieve secure key input\n"); return -1070; } key[strlen(key) - 1] = 0; - /* restore terminal */ - if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { - printf("Error: tcsetattr failed to enable terminal echo\n"); - return -1080; + if (isTTY) { + /* restore terminal */ + if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { + XPRINTF("Error: tcsetattr failed to enable terminal echo\n"); + return -1080; + } } return 0; } @@ -306,7 +385,7 @@ int SizeCheck(int *size) } else { /* if the entered size does not match acceptable size */ - printf("Invalid AES key size\n"); + XPRINTF("Invalid AES key size\n"); ret = -1080; } @@ -357,7 +436,7 @@ int main(int argc, char** argv) break; case '?': if (optopt) { - printf("Ending Session\n"); + XPRINTF("Ending Session\n"); return -111; } default: @@ -365,19 +444,30 @@ int main(int argc, char** argv) } } if (inCheck == 0 || outCheck == 0) { - printf("Must have both input and output file"); - printf(": -i filename -o filename\n"); + XPRINTF("Must have both input and output file"); + XPRINTF(": -i filename -o filename\n"); } else if (ret == 0 && choice != 'n' && inFile != NULL) { - key = malloc(size); /* sets size memory of key */ - ret = NoEcho((char*)key, size); - if (choice == 'e') - AesEncrypt(&aes, key, size, inFile, outFile); - else if (choice == 'd') - AesDecrypt(&aes, key, size, inFile, outFile); + key = (byte*)XMALLOC(size, NULL, DYNAMIC_TYPE_TMP_BUFFER); /* sets size memory of key */ + if (key == NULL) { + XPRINTF("Failed to allocate memory for key\n"); + ret = -1050; + } + else { + ret = NoEcho((char*)key, size); + if (ret == 0) { + if (choice == 'e') + ret = AesEncrypt(&aes, key, size, inFile, outFile); + else if (choice == 'd') + ret = AesDecrypt(&aes, key, size, inFile, outFile); + } + else { + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + } } else if (choice == 'n') { - printf("Must select either -e[128, 192, 256] or -d[128, 192, 256] \ + XPRINTF("Must select either -e[128, 192, 256] or -d[128, 192, 256] \ for encryption and decryption\n"); ret = -110; } @@ -388,7 +478,7 @@ int main(int argc, char** argv) #else int main() { - printf("AES-CFB or HAVE_PBKDF2 not compiled in\n"); + XPRINTF("AES-CFB or HAVE_PBKDF2 not compiled in\n"); return 0; } #endif diff --git a/crypto/aes/aesctr-file-encrypt.c b/crypto/aes/aesctr-file-encrypt.c index 366d694eb..18341ff68 100644 --- a/crypto/aes/aesctr-file-encrypt.c +++ b/crypto/aes/aesctr-file-encrypt.c @@ -23,11 +23,17 @@ #include #include #include +#include +#include #include #include #include #include +#ifndef XPRINTF + #define XPRINTF printf +#endif + #if defined(HAVE_PBKDF2) && !defined(NO_PWDBASED) && \ defined(WOLFSSL_AES_COUNTER) #define SALT_SIZE 8 @@ -59,76 +65,107 @@ int AesCtrEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) { WC_RNG rng; byte iv[AES_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int ret = 0; int length; + int rngInit = 0; + int aesInit = 0; fseek(inFile, 0, SEEK_END); length = ftell(inFile); fseek(inFile, 0, SEEK_SET); - input = malloc(length); - output = malloc(length); + input = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1050; + } - ret = wc_InitRng(&rng); - if (ret != 0) { - printf("Failed to initialize random number generator\n"); - return -1030; + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, length, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; + ret = fread(input, 1, length, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else + ret = 0; } - ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); - if (ret != 0) - return -1020; + if (ret == 0) { + ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); + if (ret != 0) + ret = -1020; + } /* stretches key to fit size */ - ret = GenerateKey(&rng, key, size, salt); - if (ret != 0) - return -1040; + if (ret == 0) { + ret = GenerateKey(&rng, key, size, salt); + if (ret != 0) + ret = -1040; + } /* inits aes structure */ - ret = wc_AesInit(aes, NULL, INVALID_DEVID); - if (ret != 0) { - printf("AesInit returned: %d\n", ret); - return -1001; + if (ret == 0) { + ret = wc_AesInit(aes, NULL, INVALID_DEVID); + if (ret != 0) + XPRINTF("AesInit returned: %d\n", ret); + else + aesInit = 1; } /* sets key */ - ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); - if (ret != 0) { - printf("SetKey returned: %d\n", ret); - return -1001; + if (ret == 0) { + ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); + if (ret != 0) { + XPRINTF("SetKey returned: %d\n", ret); + ret = -1001; + } } /* encrypts the message to the output based on input length + padding */ - ret = wc_AesCtrEncrypt(aes, output, input, length); - if (ret != 0) - return -1005; + if (ret == 0) { + ret = wc_AesCtrEncrypt(aes, output, input, length); + if (ret != 0) + ret = -1005; + } - /* writes to outFile */ - fwrite(salt, 1, SALT_SIZE, outFile); - fwrite(iv, 1, AES_BLOCK_SIZE, outFile); - fwrite(output, 1, length, outFile); + if (ret == 0) { + /* writes to outFile */ + fwrite(salt, 1, SALT_SIZE, outFile); + fwrite(iv, 1, AES_BLOCK_SIZE, outFile); + fwrite(output, 1, length, outFile); + } /* closes the opened files and frees the memory*/ - memset(input, 0, length); - memset(output, 0, length); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, length); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, length); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); - wc_FreeRng(&rng); + if (aesInit) + wc_AesFree(aes); + if (rngInit) + wc_FreeRng(&rng); return ret; } @@ -138,74 +175,99 @@ int AesCtrEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) */ int AesCtrDecrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) { - byte* input; - byte* output; - byte* salt; - byte* iv; - byte* c; + byte* input = NULL; + byte* output = NULL; + byte* salt = NULL; + byte* iv = NULL; + byte* c = NULL; int ret = 0; int bufSz; - int cSz; + int cSz = 0; + int aesInit = 0; fseek(inFile, 0, SEEK_END); bufSz = ftell(inFile); fseek(inFile, 0, SEEK_SET); - input = malloc(bufSz); - output = malloc(bufSz); + input = (byte*)XMALLOC(bufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(bufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1051; + } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, bufSz, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; + ret = fread(input, 1, bufSz, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + salt = input; + iv = input + SALT_SIZE; + c = input + SALT_SIZE + AES_BLOCK_SIZE; + cSz = bufSz - SALT_SIZE - AES_BLOCK_SIZE; + } } - salt = input; - iv = input + SALT_SIZE; - c = input + SALT_SIZE + AES_BLOCK_SIZE; - cSz = bufSz - SALT_SIZE - AES_BLOCK_SIZE; - /* replicates old key if keys match */ - ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, 4096, - size, WC_SHA256); - if (ret != 0) - return -1050; + if (ret == 0) { + ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, + 4096, size, WC_SHA256); + if (ret != 0) + ret = -1050; + } /* inits aes structure */ - ret = wc_AesInit(aes, NULL, INVALID_DEVID); - if (ret != 0) { - printf("AesInit returned: %d\n", ret); - return -1002; + if (ret == 0) { + ret = wc_AesInit(aes, NULL, INVALID_DEVID); + if (ret != 0) + XPRINTF("AesInit returned: %d\n", ret); + else + aesInit = 1; } /* sets key */ /* decrypt uses AES_ENCRYPTION */ - ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); - if (ret != 0) { - printf("SetKey returned: %d\n", ret); - return -1002; + if (ret == 0) { + ret = wc_AesSetKey(aes, key, size, iv, AES_ENCRYPTION); + if (ret != 0) { + XPRINTF("SetKey returned: %d\n", ret); + ret = -1002; + } } - ret = wc_AesCtrEncrypt(aes, output, c, cSz); - if (ret != 0) - return -1006; + if (ret == 0) { + ret = wc_AesCtrEncrypt(aes, output, c, cSz); + if (ret != 0) + ret = -1006; + } - /* writes output to the outFile based on shortened length */ - fwrite(output, 1, cSz, outFile); + if (ret == 0) { + /* writes output to the outFile based on shortened length */ + fwrite(output, 1, cSz, outFile); + } /* closes the opened files and frees the memory*/ - memset(input, 0, bufSz); - memset(output, 0, bufSz); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, bufSz); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, bufSz); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); + if (aesInit) + wc_AesFree(aes); - return 0; + return ret; } /* @@ -213,11 +275,11 @@ int AesCtrDecrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) */ void help() { - printf("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); - printf("Usage: ./aesctr-file-encrypt <-option> <-i file.in> " + XPRINTF("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); + XPRINTF("Usage: ./aesctr-file-encrypt <-option> <-i file.in> " "<-o file.out>\n\n"); - printf("Options\n"); - printf("-d Decryption\n-e Encryption\n-h Help\n"); + XPRINTF("Options\n"); + XPRINTF("-d Decryption\n-e Encryption\n-h Help\n"); } /* @@ -226,30 +288,37 @@ void help() int NoEcho(char* key, int size) { struct termios oflags, nflags; + int isTTY; + + isTTY = isatty(fileno(stdin)); - /* disabling echo */ - tcgetattr(fileno(stdin), &oflags); - nflags = oflags; - nflags.c_lflag &= ~ECHO; - nflags.c_lflag |= ECHONL; + if (isTTY) { + /* disabling echo */ + tcgetattr(fileno(stdin), &oflags); + nflags = oflags; + nflags.c_lflag &= ~ECHO; + nflags.c_lflag |= ECHONL; - if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { - printf("Error: tcsetattr failed to disable terminal echo\n"); - return -1060; + if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { + XPRINTF("Error: tcsetattr failed to disable terminal echo\n"); + return -1060; + } } - printf("Unique Password: "); + XPRINTF("Unique Password: "); if (fgets(key, size, stdin) == NULL) { - printf("Error: fgets failed to retrieve secure key input\n"); + XPRINTF("Error: fgets failed to retrieve secure key input\n"); return -1070; } key[strlen(key) - 1] = 0; - /* restore terminal */ - if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { - printf("Error: tcsetattr failed to enable terminal echo\n"); - return -1080; + if (isTTY) { + /* restore terminal */ + if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { + XPRINTF("Error: tcsetattr failed to enable terminal echo\n"); + return -1080; + } } return 0; } @@ -270,7 +339,7 @@ int SizeCheck(int *size) } else { /* if the entered size does not match acceptable size */ - printf("Invalid AES key size\n"); + XPRINTF("Invalid AES key size\n"); ret = -1080; } @@ -321,7 +390,7 @@ int main(int argc, char** argv) break; case '?': if (optopt) { - printf("Ending Session\n"); + XPRINTF("Ending Session\n"); return -111; } default: @@ -329,19 +398,30 @@ int main(int argc, char** argv) } } if (inCheck == 0 || outCheck == 0) { - printf("Must have both input and output file"); - printf(": -i filename -o filename\n"); + XPRINTF("Must have both input and output file"); + XPRINTF(": -i filename -o filename\n"); } else if (ret == 0 && choice != 'n' && inFile != NULL) { - key = malloc(size); /* sets size memory of key */ - ret = NoEcho((char*)key, size); - if (choice == 'e') - AesCtrEncrypt(&aes, key, size, inFile, outFile); - else if (choice == 'd') - AesCtrDecrypt(&aes, key, size, inFile, outFile); + key = (byte*)XMALLOC(size, NULL, DYNAMIC_TYPE_TMP_BUFFER); /* sets size memory of key */ + if (key == NULL) { + XPRINTF("Failed to allocate memory for key\n"); + ret = -1050; + } + else { + ret = NoEcho((char*)key, size); + if (ret == 0) { + if (choice == 'e') + ret = AesCtrEncrypt(&aes, key, size, inFile, outFile); + else if (choice == 'd') + ret = AesCtrDecrypt(&aes, key, size, inFile, outFile); + } + else { + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + } } else if (choice == 'n') { - printf("Must select either -e[128, 192, 256] or -d[128, 192, 256] \ + XPRINTF("Must select either -e[128, 192, 256] or -d[128, 192, 256] \ for encryption and decryption\n"); ret = -110; } @@ -352,7 +432,7 @@ int main(int argc, char** argv) #else int main() { - printf("Missing pwdbased, pbkdf2, or aes-ctr from wolfSSL\n"); + XPRINTF("Missing pwdbased, pbkdf2, or aes-ctr from wolfSSL\n"); return 0; } #endif diff --git a/crypto/camellia/camellia-encrypt.c b/crypto/camellia/camellia-encrypt.c index e638337c0..58ead9bc4 100644 --- a/crypto/camellia/camellia-encrypt.c +++ b/crypto/camellia/camellia-encrypt.c @@ -23,11 +23,17 @@ #include #include #include +#include +#include #include #include #include #include +#ifndef XPRINTF + #define XPRINTF printf +#endif + #define SALT_SIZE 8 /* @@ -61,8 +67,8 @@ int CamelliaEncrypt(Camellia* cam, byte* key, int size, FILE* inFile, { WC_RNG rng; byte iv[CAMELLIA_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int i = 0; @@ -70,6 +76,7 @@ int CamelliaEncrypt(Camellia* cam, byte* key, int size, FILE* inFile, int inputLength; int length; int padCounter = 0; + int rngInit = 0; fseek(inFile, 0, SEEK_END); inputLength = ftell(inFile); @@ -82,60 +89,84 @@ int CamelliaEncrypt(Camellia* cam, byte* key, int size, FILE* inFile, padCounter++; } - input = malloc(length); - output = malloc(length); + input = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1050; + } - ret = wc_InitRng(&rng); - if (ret != 0) { - printf("Failed to initialize random number generator\n"); - return -1030; + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, inputLength, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; - } - for (i = inputLength; i < length; i++) { - /* pads the added characters with the number of pads */ - input[i] = padCounter; + ret = fread(input, 1, inputLength, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + for (i = inputLength; i < length; i++) { + /* pads the added characters with the number of pads */ + input[i] = padCounter; + } + } } - ret = wc_RNG_GenerateBlock(&rng, iv, CAMELLIA_BLOCK_SIZE); - if (ret != 0) - return -1020; + if (ret == 0) { + ret = wc_RNG_GenerateBlock(&rng, iv, CAMELLIA_BLOCK_SIZE); + if (ret != 0) + ret = -1020; + } /* stretches key to fit size */ - ret = GenerateKey(&rng, key, size, salt, padCounter); - if (ret != 0) - return -1040; + if (ret == 0) { + ret = GenerateKey(&rng, key, size, salt, padCounter); + if (ret != 0) + ret = -1040; + } /* sets key */ - ret = wc_CamelliaSetKey(cam, key, CAMELLIA_BLOCK_SIZE, iv); - if (ret != 0) - return -1001; + if (ret == 0) { + ret = wc_CamelliaSetKey(cam, key, CAMELLIA_BLOCK_SIZE, iv); + if (ret != 0) + ret = -1001; + } - /* encrypts the message to the output based on input length + padding */ - wc_CamelliaCbcEncrypt(cam, output, input, length); + if (ret == 0) { + /* encrypts the message to the output based on input length + padding */ + wc_CamelliaCbcEncrypt(cam, output, input, length); - /* writes to outFile */ - fwrite(salt, 1, SALT_SIZE, outFile); - fwrite(iv, 1, CAMELLIA_BLOCK_SIZE, outFile); - fwrite(output, 1, length, outFile); + /* writes to outFile */ + fwrite(salt, 1, SALT_SIZE, outFile); + fwrite(iv, 1, CAMELLIA_BLOCK_SIZE, outFile); + fwrite(output, 1, length, outFile); + } /* closes the opened files and frees the memory*/ - memset(input, 0, length); - memset(output, 0, length); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, length); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, length); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); - wc_FreeRng(&rng); + if (rngInit) + wc_FreeRng(&rng); - return 0; + return ret; } /* @@ -146,78 +177,106 @@ int CamelliaDecrypt(Camellia* cam, byte* key, int size, FILE* inFile, { WC_RNG rng; byte iv[CAMELLIA_BLOCK_SIZE]; - byte* input; - byte* output; + byte* input = NULL; + byte* output = NULL; byte salt[SALT_SIZE] = {0}; int i = 0; int ret = 0; int length; int aSize; + int rngInit = 0; fseek(inFile, 0, SEEK_END); length = ftell(inFile); fseek(inFile, 0, SEEK_SET); aSize = length; - input = malloc(aSize); - output = malloc(aSize); + input = (byte*)XMALLOC(aSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + output = (byte*)XMALLOC(aSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (input == NULL || output == NULL) { + XPRINTF("Failed to allocate memory\n"); + ret = -1051; + } - wc_InitRng(&rng); + if (ret == 0) { + ret = wc_InitRng(&rng); + if (ret != 0) + XPRINTF("Failed to initialize random number generator\n"); + else + rngInit = 1; + } /* reads from inFile and writes whatever is there to the input array */ - ret = fread(input, 1, length, inFile); if (ret == 0) { - printf("Input file does not exist.\n"); - return -1010; - } - for (i = 0; i < SALT_SIZE; i++) { - /* finds salt from input message */ - salt[i] = input[i]; - } - for (i = SALT_SIZE; i < CAMELLIA_BLOCK_SIZE + SALT_SIZE; i++) { - /* finds iv from input message */ - iv[i - SALT_SIZE] = input[i]; + ret = fread(input, 1, length, inFile); + if (ret == 0) { + XPRINTF("Input file does not exist.\n"); + ret = -1010; + } + else { + ret = 0; + for (i = 0; i < SALT_SIZE; i++) { + /* finds salt from input message */ + salt[i] = input[i]; + } + for (i = SALT_SIZE; i < CAMELLIA_BLOCK_SIZE + SALT_SIZE; i++) { + /* finds iv from input message */ + iv[i - SALT_SIZE] = input[i]; + } + } } /* replicates old key if keys match */ - ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, 4096, - size, WC_SHA256); - if (ret != 0) - return -1050; + if (ret == 0) { + ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, + 4096, size, WC_SHA256); + if (ret != 0) + ret = -1050; + } /* sets key */ - ret = wc_CamelliaSetKey(cam, key, CAMELLIA_BLOCK_SIZE, iv); - if (ret != 0) - return -1002; - - /* change length to remove salt/iv block from being decrypted */ - length -= (CAMELLIA_BLOCK_SIZE + SALT_SIZE); - for (i = 0; i < length; i++) { - /* shifts message: ignores salt/iv on message*/ - input[i] = input[i + (CAMELLIA_BLOCK_SIZE + SALT_SIZE)]; + if (ret == 0) { + ret = wc_CamelliaSetKey(cam, key, CAMELLIA_BLOCK_SIZE, iv); + if (ret != 0) + ret = -1002; } - /* decrypts the message to output based on input length + padding */ - wc_CamelliaCbcDecrypt(cam, output, input, length); - if (salt[0] != 0) { - /* reduces length based on number of padded elements */ - length -= output[length-1]; + if (ret == 0) { + /* change length to remove salt/iv block from being decrypted */ + length -= (CAMELLIA_BLOCK_SIZE + SALT_SIZE); + for (i = 0; i < length; i++) { + /* shifts message: ignores salt/iv on message*/ + input[i] = input[i + (CAMELLIA_BLOCK_SIZE + SALT_SIZE)]; + } + /* decrypts the message to output based on input length + padding */ + wc_CamelliaCbcDecrypt(cam, output, input, length); + + if (salt[0] != 0) { + /* reduces length based on number of padded elements */ + length -= output[length-1]; + } + /* writes output to the outFile based on shortened length */ + fwrite(output, 1, length, outFile); } - /* writes output to the outFile based on shortened length */ - fwrite(output, 1, length, outFile); /* closes the opened files and frees the memory*/ - memset(input, 0, aSize); - memset(output, 0, aSize); - memset(key, 0, size); - free(input); - free(output); - free(key); + if (input != NULL) { + wc_ForceZero(input, aSize); + XFREE(input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (output != NULL) { + wc_ForceZero(output, aSize); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + wc_ForceZero(key, size); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); fclose(inFile); fclose(outFile); + if (rngInit) + wc_FreeRng(&rng); - return 0; + return ret; } /* @@ -225,11 +284,11 @@ int CamelliaDecrypt(Camellia* cam, byte* key, int size, FILE* inFile, */ void help() { - printf("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); - printf("Usage: ./camellia-file-encrypt <-option> <-i file.in> " + XPRINTF("\n~~~~~~~~~~~~~~~~~~~~|Help|~~~~~~~~~~~~~~~~~~~~~\n\n"); + XPRINTF("Usage: ./camellia-file-encrypt <-option> <-i file.in> " "<-o file.out>\n\n"); - printf("Options\n"); - printf("-d Decryption\n-e Encryption\n-h Help\n"); + XPRINTF("Options\n"); + XPRINTF("-d Decryption\n-e Encryption\n-h Help\n"); } /* @@ -238,30 +297,37 @@ void help() int NoEcho(char* key, int size) { struct termios oflags, nflags; + int isTTY; + + isTTY = isatty(fileno(stdin)); - /* disabling echo */ - tcgetattr(fileno(stdin), &oflags); - nflags = oflags; - nflags.c_lflag &= ~ECHO; - nflags.c_lflag |= ECHONL; + if (isTTY) { + /* disabling echo */ + tcgetattr(fileno(stdin), &oflags); + nflags = oflags; + nflags.c_lflag &= ~ECHO; + nflags.c_lflag |= ECHONL; - if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { - printf("Error: tcsetattr failed to disable terminal echo\n"); - return -1060; + if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { + XPRINTF("Error: tcsetattr failed to disable terminal echo\n"); + return -1060; + } } - printf("Unique Password: "); + XPRINTF("Unique Password: "); if (fgets(key, size, stdin) == NULL) { - printf("Error: fgets failed to retrieve secure key input\n"); + XPRINTF("Error: fgets failed to retrieve secure key input\n"); return -1070; } key[strlen(key) - 1] = 0; - /* restore terminal */ - if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { - printf("Error: tcsetattr failed to enable terminal echo\n"); - return -1080; + if (isTTY) { + /* restore terminal */ + if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { + XPRINTF("Error: tcsetattr failed to enable terminal echo\n"); + return -1080; + } } return 0; } @@ -272,7 +338,7 @@ int SizeCheck(int size) if (size != 128 && size != 192 && size != 256) { /* if the entered size does not match acceptable size */ - printf("Invalid Camellia key size\n"); + XPRINTF("Invalid Camellia key size\n"); ret = -1080; } @@ -323,7 +389,7 @@ int main(int argc, char** argv) break; case '?': if (optopt) { - printf("Ending Session\n"); + XPRINTF("Ending Session\n"); return -111; } default: @@ -331,20 +397,31 @@ int main(int argc, char** argv) } } if (inCheck == 0 || outCheck == 0) { - printf("Must have both input and output file"); - printf(": -i filename -o filename\n"); + XPRINTF("Must have both input and output file"); + XPRINTF(": -i filename -o filename\n"); } else if (ret == 0 && choice != 'n') { - key = malloc(size); /* sets size memory of key */ - ret = NoEcho((char*)key, size); - if (choice == 'e') - CamelliaEncrypt(&cam, key, size, inFile, outFile); - else if (choice == 'd') - CamelliaDecrypt(&cam, key, size, inFile, outFile); + key = (byte*)XMALLOC(size, NULL, DYNAMIC_TYPE_TMP_BUFFER); /* sets size memory of key */ + if (key == NULL) { + XPRINTF("Failed to allocate memory for key\n"); + ret = -1050; + } + else { + ret = NoEcho((char*)key, size); + if (ret == 0) { + if (choice == 'e') + ret = CamelliaEncrypt(&cam, key, size, inFile, outFile); + else if (choice == 'd') + ret = CamelliaDecrypt(&cam, key, size, inFile, outFile); + } + else { + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + } } else if (choice == 'n') { - printf("Must select either -e[128,192,256] or -d[128,192,256] for \ + XPRINTF("Must select either -e[128,192,256] or -d[128,192,256] for \ encryption and decryption\n"); } diff --git a/custom-io-callbacks/file-client/file-client.c b/custom-io-callbacks/file-client/file-client.c index a61b5a7c1..999d3a449 100644 --- a/custom-io-callbacks/file-client/file-client.c +++ b/custom-io-callbacks/file-client/file-client.c @@ -57,7 +57,7 @@ unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint, int CbIOSend(WOLFSSL *ssl, char *buf, int sz, void *ctx); int CbIORecv(WOLFSSL *ssl, char *buf, int sz, void *ctx); -WOLFSSL* Client(WOLFSSL_CTX* ctx, char* suite, int setSuite, int doVerify); +WOLFSSL* Client(WOLFSSL_CTX** ctx_ptr, char* suite, int setSuite, int doVerify); WOLFSSL_METHOD* SetMethodClient(int i); @@ -118,8 +118,9 @@ int CbIOSend(WOLFSSL *ssl, char *buf, int sz, void *ctx) return ret; } -WOLFSSL* Client(WOLFSSL_CTX* ctx, char* suite, int setSuite, int doVerify) +WOLFSSL* Client(WOLFSSL_CTX** ctx_ptr, char* suite, int setSuite, int doVerify) { + WOLFSSL_CTX* ctx; WOLFSSL* ssl = NULL; int ret; @@ -132,6 +133,7 @@ WOLFSSL* Client(WOLFSSL_CTX* ctx, char* suite, int setSuite, int doVerify) if ((wolfSSL_CTX_load_verify_locations(ctx, peerAuthority, 0)) != SSL_SUCCESS) { printf("Failed to load CA (peer Authority) file\n"); + wolfSSL_CTX_free(ctx); return NULL; } } else { @@ -160,6 +162,7 @@ WOLFSSL* Client(WOLFSSL_CTX* ctx, char* suite, int setSuite, int doVerify) wolfSSL_set_fd(ssl, fpRecv); + if (ctx_ptr) *ctx_ptr = ctx; return ssl; } @@ -186,7 +189,7 @@ int main(int argc, char** argv) /* Example usage */ // sslServ = Server(ctxServ, "ECDHE-RSA-AES128-SHA", 1); - sslCli = Client(ctxCli, "let-wolfssl-decide", 0, 1); + sslCli = Client(&ctxCli, "let-wolfssl-decide", 0, 1); if (sslCli == NULL) { printf("Failed to start client\n"); @@ -205,8 +208,6 @@ int main(int argc, char** argv) if (ret != SSL_SUCCESS) { if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) { - wolfSSL_free(sslCli); - wolfSSL_CTX_free(ctxCli); printf("client ssl connect failed\n"); goto cleanup; } @@ -250,9 +251,13 @@ int main(int argc, char** argv) cleanup: - wolfSSL_shutdown(sslCli); - wolfSSL_free(sslCli); - wolfSSL_CTX_free(ctxCli); + if (sslCli) { + wolfSSL_shutdown(sslCli); + wolfSSL_free(sslCli); + } + if (ctxCli) { + wolfSSL_CTX_free(ctxCli); + } wolfSSL_Cleanup(); /* close the streams so client can reset file contents */ close(fpSend); diff --git a/custom-io-callbacks/file-server/file-server.c b/custom-io-callbacks/file-server/file-server.c index aad2f3bf2..3c4058353 100644 --- a/custom-io-callbacks/file-server/file-server.c +++ b/custom-io-callbacks/file-server/file-server.c @@ -57,7 +57,7 @@ unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identity, int CbIOSend(WOLFSSL *ssl, char *buf, int sz, void *ctx); int CbIORecv(WOLFSSL *ssl, char *buf, int sz, void *ctx); int ConvertHexToBin(const char* h1, byte* b1, word32* b1Sz); -WOLFSSL* Server(WOLFSSL_CTX* ctx, char* suite, int setSuite); +WOLFSSL* Server(WOLFSSL_CTX** ctx_ptr, char* suite, int setSuite); static int fpSend; static int fpRecv; @@ -102,8 +102,9 @@ int CbIOSend(WOLFSSL *ssl, char *buf, int sz, void *ctx) } -WOLFSSL* Server(WOLFSSL_CTX* ctx, char* suite, int setSuite) +WOLFSSL* Server(WOLFSSL_CTX** ctx_ptr, char* suite, int setSuite) { + WOLFSSL_CTX* ctx; WOLFSSL* ssl; int ret = -1; @@ -118,14 +119,16 @@ WOLFSSL* Server(WOLFSSL_CTX* ctx, char* suite, int setSuite) #endif if (wolfSSL_CTX_use_certificate_file(ctx, serverCert, SSL_FILETYPE_PEM) - != SSL_SUCCESS) { + != SSL_SUCCESS) { printf("trouble loading server cert file\n"); + wolfSSL_CTX_free(ctx); return NULL; } if (wolfSSL_CTX_use_PrivateKey_file(ctx, serverKey, SSL_FILETYPE_PEM) - != SSL_SUCCESS) { + != SSL_SUCCESS) { printf("trouble loading server key file\n"); + wolfSSL_CTX_free(ctx); return NULL; } @@ -150,6 +153,7 @@ WOLFSSL* Server(WOLFSSL_CTX* ctx, char* suite, int setSuite) } wolfSSL_set_fd(ssl, fpRecv); + if (ctx_ptr) *ctx_ptr = ctx; return ssl; } @@ -178,8 +182,8 @@ int main(int argc, char** argv) wolfSSL_Init(); /* Example usage */ -// sslServ = Server(ctxServ, "ECDHE-RSA-AES128-SHA", 1); - sslServ = Server(ctxServ, "let-wolfssl-choose", 0); +// sslServ = Server(&ctxServ, "ECDHE-RSA-AES128-SHA", 1); + sslServ = Server(&ctxServ, "let-wolfssl-choose", 0); if (sslServ == NULL) { printf("sslServ NULL\n"); return 0;} ret = SSL_FAILURE; @@ -191,8 +195,6 @@ int main(int argc, char** argv) if (ret != SSL_SUCCESS) { if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) { - wolfSSL_free(sslServ); - wolfSSL_CTX_free(ctxServ); printf("server ssl accept failed ret = %d error = %d wr = %d\n", ret, error, SSL_ERROR_WANT_READ); goto cleanup; @@ -254,9 +256,13 @@ int main(int argc, char** argv) close(open(CR, O_RDWR | O_NOCTTY | O_NDELAY)); close(open(SR, O_RDWR | O_NOCTTY | O_NDELAY)); - wolfSSL_shutdown(sslServ); - wolfSSL_free(sslServ); - wolfSSL_CTX_free(ctxServ); + if (sslServ) { + wolfSSL_shutdown(sslServ); + wolfSSL_free(sslServ); + } + if (ctxServ) { + wolfSSL_CTX_free(ctxServ); + } wolfSSL_Cleanup(); /* Reset the contents of the receive and send files for next run */ fclose(fopen(SR, "wb")); diff --git a/dtls/client-dtls-export.c b/dtls/client-dtls-export.c index 2cdc4b5e1..d60299029 100644 --- a/dtls/client-dtls-export.c +++ b/dtls/client-dtls-export.c @@ -42,9 +42,9 @@ static void Usage(const char* progName) { - printf("Usage: %s [session_file]\n", progName); - printf(" server IP - IP address of the DTLS server\n"); - printf(" session_file - Optional: file to save session (default: %s)\n", + XPRINTF("Usage: %s [session_file]\n", progName); + XPRINTF(" server IP - IP address of the DTLS server\n"); + XPRINTF(" session_file - Optional: file to save session (default: %s)\n", DEFAULT_CLIENT_SESSION_FILE); } @@ -61,6 +61,7 @@ int main(int argc, char** argv) const char* sessionFile = DEFAULT_CLIENT_SESSION_FILE; unsigned char* sessionBuf = NULL; unsigned int sessionSz = 0; + unsigned int sessionBufSz = 0; int n; /* Program argument checking */ @@ -79,7 +80,7 @@ int main(int argc, char** argv) /* Create DTLS 1.2 context */ ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method()); if (ctx == NULL) { - fprintf(stderr, "Error: wolfSSL_CTX_new failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_CTX_new failed\n"); ret = 1; goto cleanup; } @@ -87,7 +88,7 @@ int main(int argc, char** argv) /* Load CA certificates */ ret = wolfSSL_CTX_load_verify_locations(ctx, certs, NULL); if (ret != SSL_SUCCESS) { - fprintf(stderr, "Error: Failed to load CA cert %s\n", certs); + XFPRINTF(stderr, "Error: Failed to load CA cert %s\n", certs); ret = 1; goto cleanup; } @@ -95,7 +96,7 @@ int main(int argc, char** argv) /* Create SSL object */ ssl = wolfSSL_new(ctx); if (ssl == NULL) { - fprintf(stderr, "Error: wolfSSL_new failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_new failed\n"); ret = 1; goto cleanup; } @@ -105,7 +106,7 @@ int main(int argc, char** argv) servAddr.sin_family = AF_INET; servAddr.sin_port = htons(SERV_PORT); if (inet_pton(AF_INET, argv[1], &servAddr.sin_addr) != 1) { - fprintf(stderr, "Error: Invalid IP address: %s\n", argv[1]); + XFPRINTF(stderr, "Error: Invalid IP address: %s\n", argv[1]); ret = 1; goto cleanup; } @@ -116,7 +117,7 @@ int main(int argc, char** argv) /* Create UDP socket */ sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { - fprintf(stderr, "Error: Cannot create socket\n"); + XFPRINTF(stderr, "Error: Cannot create socket\n"); ret = 1; goto cleanup; } @@ -125,80 +126,84 @@ int main(int argc, char** argv) wolfSSL_set_fd(ssl, sockfd); /* Perform DTLS handshake */ - printf("Connecting to server %s:%d...\n", argv[1], SERV_PORT); + XPRINTF("Connecting to server %s:%d...\n", argv[1], SERV_PORT); ret = wolfSSL_connect(ssl); if (ret != SSL_SUCCESS) { int err = wolfSSL_get_error(ssl, ret); - fprintf(stderr, "Error: wolfSSL_connect failed: %d (%s)\n", + XFPRINTF(stderr, "Error: wolfSSL_connect failed: %d (%s)\n", err, wolfSSL_ERR_reason_error_string(err)); ret = 1; goto cleanup; } - printf("DTLS handshake successful!\n"); + XPRINTF("DTLS handshake successful!\n"); /* Export the session */ - printf("Exporting DTLS session...\n"); + XPRINTF("Exporting DTLS session...\n"); /* First call to get required buffer size */ ret = wolfSSL_dtls_export(ssl, NULL, &sessionSz); if (ret != 0 && sessionSz == 0) { - fprintf(stderr, "Error: wolfSSL_dtls_export (get size) failed: %d\n", + XFPRINTF(stderr, "Error: wolfSSL_dtls_export (get size) failed: %d\n", ret); ret = 1; goto cleanup; } /* Allocate buffer for session data */ - sessionBuf = (unsigned char*)malloc(sessionSz); + sessionBuf = (unsigned char*)XMALLOC(sessionSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (sessionBuf == NULL) { - fprintf(stderr, "Error: Memory allocation failed\n"); + XFPRINTF(stderr, "Error: Memory allocation failed\n"); ret = 1; goto cleanup; } + sessionBufSz = sessionSz; /* Export the session */ ret = wolfSSL_dtls_export(ssl, sessionBuf, &sessionSz); if (ret <= 0) { - fprintf(stderr, "Error: wolfSSL_dtls_export failed: %d\n", ret); + XFPRINTF(stderr, "Error: wolfSSL_dtls_export failed: %d\n", ret); ret = 1; goto cleanup; } - printf("Session exported: %d bytes\n", ret); + XPRINTF("Session exported: %d bytes\n", ret); sessionSz = ret; /* Save encrypted session to file */ ret = SaveEncryptedSession(sessionFile, sessionBuf, sessionSz); if (ret != 0) { - fprintf(stderr, "Error: Failed to save encrypted session\n"); + XFPRINTF(stderr, "Error: Failed to save encrypted session\n"); ret = 1; goto cleanup; } /* Send a test message */ - printf("\nEnter message to send (or press Enter to skip): "); + XPRINTF("\nEnter message to send (or press Enter to skip): "); if (fgets(sendLine, MAXLINE, stdin) != NULL && sendLine[0] != '\n') { ret = wolfSSL_write(ssl, sendLine, (int)strlen(sendLine)); if (ret != (int)strlen(sendLine)) { - fprintf(stderr, "Error: wolfSSL_write failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_write failed\n"); } else { - printf("Sent: %s", sendLine); + XPRINTF("Sent: %s", sendLine); /* Read response */ n = wolfSSL_read(ssl, recvLine, sizeof(recvLine) - 1); if (n > 0) { recvLine[n] = '\0'; - printf("Received: %s", recvLine); + XPRINTF("Received: %s", recvLine); } } } - printf("\nSession exported and saved to: %s\n", sessionFile); - printf("You can now use client-dtls-import to resume this session.\n"); + XPRINTF("\nSession exported and saved to: %s\n", sessionFile); + XPRINTF("You can now use client-dtls-import to resume this session.\n"); ret = 0; cleanup: - if (sessionBuf != NULL) free(sessionBuf); + if (sessionBuf != NULL) { + wc_ForceZero(sessionBuf, sessionBufSz); + XFREE(sessionBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } if (ssl != NULL) { wolfSSL_shutdown(ssl); wolfSSL_free(ssl); diff --git a/dtls/client-dtls-import.c b/dtls/client-dtls-import.c index d6ff02699..2009f6dcf 100644 --- a/dtls/client-dtls-import.c +++ b/dtls/client-dtls-import.c @@ -41,9 +41,9 @@ static void Usage(const char* progName) { - printf("Usage: %s [session_file]\n", progName); - printf(" server IP - IP address of the DTLS server\n"); - printf(" session_file - Optional: file to load session from (default: %s)\n", + XPRINTF("Usage: %s [session_file]\n", progName); + XPRINTF(" server IP - IP address of the DTLS server\n"); + XPRINTF(" session_file - Optional: file to load session from (default: %s)\n", DEFAULT_CLIENT_SESSION_FILE); } @@ -59,6 +59,7 @@ int main(int argc, char** argv) const char* sessionFile = DEFAULT_CLIENT_SESSION_FILE; unsigned char* sessionBuf = NULL; unsigned int sessionSz = 0; + unsigned int sessionBufSz = 0; int n; /* Program argument checking */ @@ -77,7 +78,7 @@ int main(int argc, char** argv) /* Create DTLS 1.2 context */ ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method()); if (ctx == NULL) { - fprintf(stderr, "Error: wolfSSL_CTX_new failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_CTX_new failed\n"); ret = 1; goto cleanup; } @@ -85,36 +86,36 @@ int main(int argc, char** argv) /* Create SSL object */ ssl = wolfSSL_new(ctx); if (ssl == NULL) { - fprintf(stderr, "Error: wolfSSL_new failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_new failed\n"); ret = 1; goto cleanup; } /* Load encrypted session from file */ - printf("Loading session from %s...\n", sessionFile); - sessionBuf = LoadEncryptedSession(sessionFile, &sessionSz); + XPRINTF("Loading session from %s...\n", sessionFile); + sessionBuf = LoadEncryptedSession(sessionFile, &sessionSz, &sessionBufSz); if (sessionBuf == NULL) { - fprintf(stderr, "Error: Failed to load session from file\n"); + XFPRINTF(stderr, "Error: Failed to load session from file\n"); ret = 1; goto cleanup; } /* Import the session */ - printf("Importing DTLS session (%u bytes)...\n", sessionSz); + XPRINTF("Importing DTLS session (%u bytes)...\n", sessionSz); ret = wolfSSL_dtls_import(ssl, sessionBuf, sessionSz); if (ret < 0) { - fprintf(stderr, "Error: wolfSSL_dtls_import failed: %d\n", ret); + XFPRINTF(stderr, "Error: wolfSSL_dtls_import failed: %d\n", ret); ret = 1; goto cleanup; } - printf("Session imported successfully!\n"); + XPRINTF("Session imported successfully!\n"); /* Setup server address */ memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(SERV_PORT); if (inet_pton(AF_INET, argv[1], &servAddr.sin_addr) != 1) { - fprintf(stderr, "Error: Invalid IP address: %s\n", argv[1]); + XFPRINTF(stderr, "Error: Invalid IP address: %s\n", argv[1]); ret = 1; goto cleanup; } @@ -125,7 +126,7 @@ int main(int argc, char** argv) /* Create UDP socket */ sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { - fprintf(stderr, "Error: Cannot create socket\n"); + XFPRINTF(stderr, "Error: Cannot create socket\n"); ret = 1; goto cleanup; } @@ -133,11 +134,11 @@ int main(int argc, char** argv) /* Set the socket file descriptor */ wolfSSL_set_fd(ssl, sockfd); - printf("Session restored - no handshake needed!\n"); - printf("Ready to communicate with server %s:%d\n\n", argv[1], SERV_PORT); + XPRINTF("Session restored - no handshake needed!\n"); + XPRINTF("Ready to communicate with server %s:%d\n\n", argv[1], SERV_PORT); /* Send messages using the imported session */ - printf("Enter message to send (or 'quit' to exit):\n"); + XPRINTF("Enter message to send (or 'quit' to exit):\n"); while (fgets(sendLine, MAXLINE, stdin) != NULL) { if (strncmp(sendLine, "quit", 4) == 0) { break; @@ -147,34 +148,37 @@ int main(int argc, char** argv) ret = wolfSSL_write(ssl, sendLine, (int)strlen(sendLine)); if (ret != (int)strlen(sendLine)) { int err = wolfSSL_get_error(ssl, ret); - fprintf(stderr, "Error: wolfSSL_write failed: %d (%s)\n", + XFPRINTF(stderr, "Error: wolfSSL_write failed: %d (%s)\n", err, wolfSSL_ERR_reason_error_string(err)); break; } - printf("Sent: %s", sendLine); + XPRINTF("Sent: %s", sendLine); /* Read response */ n = wolfSSL_read(ssl, recvLine, sizeof(recvLine) - 1); if (n > 0) { recvLine[n] = '\0'; - printf("Received: %s", recvLine); + XPRINTF("Received: %s", recvLine); } else { int err = wolfSSL_get_error(ssl, n); if (err != SSL_ERROR_WANT_READ) { - fprintf(stderr, "Error: wolfSSL_read failed: %d (%s)\n", + XFPRINTF(stderr, "Error: wolfSSL_read failed: %d (%s)\n", err, wolfSSL_ERR_reason_error_string(err)); break; } } - printf("\nEnter message (or 'quit' to exit):\n"); + XPRINTF("\nEnter message (or 'quit' to exit):\n"); } ret = 0; cleanup: - if (sessionBuf != NULL) free(sessionBuf); + if (sessionBuf != NULL) { + wc_ForceZero(sessionBuf, sessionBufSz); + XFREE(sessionBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } if (ssl != NULL) { wolfSSL_shutdown(ssl); wolfSSL_free(ssl); diff --git a/dtls/dtls-export-common.h b/dtls/dtls-export-common.h index 70f0a184c..27647ecae 100644 --- a/dtls/dtls-export-common.h +++ b/dtls/dtls-export-common.h @@ -29,12 +29,21 @@ #include #include +#include +#include #include #include #include #include #include +#ifndef XPRINTF + #define XPRINTF printf +#endif +#ifndef XFPRINTF + #define XFPRINTF fprintf +#endif + /* Default file for session export/import */ #define DEFAULT_CLIENT_SESSION_FILE "dtls_client_session.bin" #define DEFAULT_SERVER_SESSION_FILE "dtls_server_session.bin" @@ -83,7 +92,7 @@ int SaveEncryptedSession(const char* filename, /* Initialize RNG for IV generation */ ret = wc_InitRng(&rng); if (ret != 0) { - printf("Error: wc_InitRng failed: %d\n", ret); + XPRINTF("Error: wc_InitRng failed: %d\n", ret); return -1; } rngInit = 1; @@ -91,15 +100,15 @@ int SaveEncryptedSession(const char* filename, /* Generate random IV */ ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SZ); if (ret != 0) { - printf("Error: Failed to generate IV: %d\n", ret); + XPRINTF("Error: Failed to generate IV: %d\n", ret); goto cleanup; } /* Allocate buffers */ - paddedData = (unsigned char*)malloc(paddedSz); - encryptedData = (unsigned char*)malloc(paddedSz); + paddedData = (unsigned char*)XMALLOC(paddedSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + encryptedData = (unsigned char*)XMALLOC(paddedSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (paddedData == NULL || encryptedData == NULL) { - printf("Error: Memory allocation failed\n"); + XPRINTF("Error: Memory allocation failed\n"); ret = -1; goto cleanup; } @@ -111,7 +120,7 @@ int SaveEncryptedSession(const char* filename, /* Initialize AES */ ret = wc_AesInit(&aes, NULL, INVALID_DEVID); if (ret != 0) { - printf("Error: wc_AesInit failed: %d\n", ret); + XPRINTF("Error: wc_AesInit failed: %d\n", ret); goto cleanup; } aesInit = 1; @@ -119,21 +128,21 @@ int SaveEncryptedSession(const char* filename, /* Set AES key for encryption */ ret = wc_AesSetKey(&aes, AES_KEY, sizeof(AES_KEY), iv, AES_ENCRYPTION); if (ret != 0) { - printf("Error: wc_AesSetKey failed: %d\n", ret); + XPRINTF("Error: wc_AesSetKey failed: %d\n", ret); goto cleanup; } /* Encrypt the data */ ret = wc_AesCbcEncrypt(&aes, encryptedData, paddedData, paddedSz); if (ret != 0) { - printf("Error: wc_AesCbcEncrypt failed: %d\n", ret); + XPRINTF("Error: wc_AesCbcEncrypt failed: %d\n", ret); goto cleanup; } /* Write to file */ fp = fopen(filename, "wb"); if (fp == NULL) { - printf("Error: Cannot open file %s for writing\n", filename); + XPRINTF("Error: Cannot open file %s for writing\n", filename); ret = -1; goto cleanup; } @@ -146,7 +155,7 @@ int SaveEncryptedSession(const char* filename, sizeBuf[2] = (sessionSz >> 8) & 0xFF; sizeBuf[3] = sessionSz & 0xFF; if (fwrite(sizeBuf, 1, 4, fp) != 4) { - printf("Error: Failed to write size to file\n"); + XPRINTF("Error: Failed to write size to file\n"); ret = -1; goto cleanup; } @@ -154,25 +163,31 @@ int SaveEncryptedSession(const char* filename, /* Write IV */ if (fwrite(iv, 1, AES_BLOCK_SZ, fp) != AES_BLOCK_SZ) { - printf("Error: Failed to write IV to file\n"); + XPRINTF("Error: Failed to write IV to file\n"); ret = -1; goto cleanup; } /* Write encrypted data */ if (fwrite(encryptedData, 1, paddedSz, fp) != paddedSz) { - printf("Error: Failed to write encrypted data to file\n"); + XPRINTF("Error: Failed to write encrypted data to file\n"); ret = -1; goto cleanup; } - printf("Session saved to %s (%u bytes encrypted)\n", filename, paddedSz); + XPRINTF("Session saved to %s (%u bytes encrypted)\n", filename, paddedSz); ret = 0; cleanup: if (fp != NULL) fclose(fp); - if (paddedData != NULL) free(paddedData); - if (encryptedData != NULL) free(encryptedData); + if (paddedData != NULL) { + wc_ForceZero(paddedData, paddedSz); + XFREE(paddedData, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (encryptedData != NULL) { + wc_ForceZero(encryptedData, paddedSz); + XFREE(encryptedData, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } if (aesInit) wc_AesFree(&aes); if (rngInit) wc_FreeRng(&rng); @@ -183,9 +198,13 @@ int SaveEncryptedSession(const char* filename, * Load and decrypt session data from file * Returns allocated session data (caller must free), or NULL on error * sessionSz is set to the size of the returned data + * allocSz, if non-NULL, is set to the full allocated size of the returned + * buffer (>= *sessionSz), for callers that need to wc_ForceZero() the + * entire allocation before freeing it */ unsigned char* LoadEncryptedSession(const char* filename, - unsigned int* sessionSz) + unsigned int* sessionSz, + unsigned int* allocSz) { FILE* fp = NULL; Aes aes; @@ -202,7 +221,7 @@ unsigned char* LoadEncryptedSession(const char* filename, /* Open file */ fp = fopen(filename, "rb"); if (fp == NULL) { - printf("Error: Cannot open file %s for reading\n", filename); + XPRINTF("Error: Cannot open file %s for reading\n", filename); return NULL; } @@ -212,14 +231,14 @@ unsigned char* LoadEncryptedSession(const char* filename, fseek(fp, 0, SEEK_SET); if (fileSize < (4 + AES_BLOCK_SZ + AES_BLOCK_SZ)) { - printf("Error: File too small to contain valid session data\n"); + XPRINTF("Error: File too small to contain valid session data\n"); fclose(fp); return NULL; } /* Read original size */ if (fread(sizeBuf, 1, 4, fp) != 4) { - printf("Error: Failed to read size from file\n"); + XPRINTF("Error: Failed to read size from file\n"); fclose(fp); return NULL; } @@ -230,7 +249,7 @@ unsigned char* LoadEncryptedSession(const char* filename, /* Read IV */ if (fread(iv, 1, AES_BLOCK_SZ, fp) != AES_BLOCK_SZ) { - printf("Error: Failed to read IV from file\n"); + XPRINTF("Error: Failed to read IV from file\n"); fclose(fp); return NULL; } @@ -239,16 +258,16 @@ unsigned char* LoadEncryptedSession(const char* filename, encryptedSz = (unsigned int)(fileSize - 4 - AES_BLOCK_SZ); /* Allocate buffers */ - encryptedData = (unsigned char*)malloc(encryptedSz); - decryptedData = (unsigned char*)malloc(encryptedSz); + encryptedData = (unsigned char*)XMALLOC(encryptedSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + decryptedData = (unsigned char*)XMALLOC(encryptedSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (encryptedData == NULL || decryptedData == NULL) { - printf("Error: Memory allocation failed\n"); + XPRINTF("Error: Memory allocation failed\n"); goto cleanup; } /* Read encrypted data */ if (fread(encryptedData, 1, encryptedSz, fp) != encryptedSz) { - printf("Error: Failed to read encrypted data from file\n"); + XPRINTF("Error: Failed to read encrypted data from file\n"); goto cleanup; } fclose(fp); @@ -257,7 +276,7 @@ unsigned char* LoadEncryptedSession(const char* filename, /* Initialize AES */ ret = wc_AesInit(&aes, NULL, INVALID_DEVID); if (ret != 0) { - printf("Error: wc_AesInit failed: %d\n", ret); + XPRINTF("Error: wc_AesInit failed: %d\n", ret); goto cleanup; } aesInit = 1; @@ -265,36 +284,48 @@ unsigned char* LoadEncryptedSession(const char* filename, /* Set AES key for decryption */ ret = wc_AesSetKey(&aes, AES_KEY, sizeof(AES_KEY), iv, AES_DECRYPTION); if (ret != 0) { - printf("Error: wc_AesSetKey failed: %d\n", ret); + XPRINTF("Error: wc_AesSetKey failed: %d\n", ret); goto cleanup; } /* Decrypt the data */ ret = wc_AesCbcDecrypt(&aes, decryptedData, encryptedData, encryptedSz); if (ret != 0) { - printf("Error: wc_AesCbcDecrypt failed: %d\n", ret); + XPRINTF("Error: wc_AesCbcDecrypt failed: %d\n", ret); goto cleanup; } /* Verify padding and original size */ if (originalSz > encryptedSz) { - printf("Error: Invalid original size in file\n"); + XPRINTF("Error: Invalid original size in file\n"); goto cleanup; } *sessionSz = originalSz; - printf("Session loaded from %s (%u bytes)\n", filename, originalSz); + if (allocSz != NULL) { + *allocSz = encryptedSz; + } + XPRINTF("Session loaded from %s (%u bytes)\n", filename, originalSz); /* Clean up and return decrypted data */ - if (encryptedData != NULL) free(encryptedData); + if (encryptedData != NULL) { + wc_ForceZero(encryptedData, encryptedSz); + XFREE(encryptedData, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } if (aesInit) wc_AesFree(&aes); return decryptedData; cleanup: if (fp != NULL) fclose(fp); - if (encryptedData != NULL) free(encryptedData); - if (decryptedData != NULL) free(decryptedData); + if (encryptedData != NULL) { + wc_ForceZero(encryptedData, encryptedSz); + XFREE(encryptedData, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (decryptedData != NULL) { + wc_ForceZero(decryptedData, encryptedSz); + XFREE(decryptedData, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } if (aesInit) wc_AesFree(&aes); return NULL; diff --git a/dtls/server-dtls-export.c b/dtls/server-dtls-export.c index 857e00d98..ee299fac4 100644 --- a/dtls/server-dtls-export.c +++ b/dtls/server-dtls-export.c @@ -51,8 +51,8 @@ static void sig_handler(int sig) static void Usage(const char* progName) { - printf("Usage: %s [session_file]\n", progName); - printf(" session_file - Optional: file to save session (default: %s)\n", + XPRINTF("Usage: %s [session_file]\n", progName); + XPRINTF(" session_file - Optional: file to save session (default: %s)\n", DEFAULT_SERVER_SESSION_FILE); } @@ -76,6 +76,7 @@ int main(int argc, char** argv) const char* sessionFile = DEFAULT_SERVER_SESSION_FILE; unsigned char* sessionBuf = NULL; unsigned int sessionSz = 0; + unsigned int sessionBufSz = 0; /* Program argument checking */ if (argc > 2) { @@ -96,7 +97,7 @@ int main(int argc, char** argv) /* Create DTLS 1.2 context */ ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method()); if (ctx == NULL) { - fprintf(stderr, "Error: wolfSSL_CTX_new failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_CTX_new failed\n"); ret = 1; goto cleanup; } @@ -104,7 +105,7 @@ int main(int argc, char** argv) /* Load CA certificates */ ret = wolfSSL_CTX_load_verify_locations(ctx, caCertLoc, NULL); if (ret != SSL_SUCCESS) { - fprintf(stderr, "Error: Failed to load CA cert %s\n", caCertLoc); + XFPRINTF(stderr, "Error: Failed to load CA cert %s\n", caCertLoc); ret = 1; goto cleanup; } @@ -112,7 +113,7 @@ int main(int argc, char** argv) /* Load server certificate */ ret = wolfSSL_CTX_use_certificate_file(ctx, servCertLoc, SSL_FILETYPE_PEM); if (ret != SSL_SUCCESS) { - fprintf(stderr, "Error: Failed to load server cert %s\n", servCertLoc); + XFPRINTF(stderr, "Error: Failed to load server cert %s\n", servCertLoc); ret = 1; goto cleanup; } @@ -120,7 +121,7 @@ int main(int argc, char** argv) /* Load server private key */ ret = wolfSSL_CTX_use_PrivateKey_file(ctx, servKeyLoc, SSL_FILETYPE_PEM); if (ret != SSL_SUCCESS) { - fprintf(stderr, "Error: Failed to load server key %s\n", servKeyLoc); + XFPRINTF(stderr, "Error: Failed to load server key %s\n", servKeyLoc); ret = 1; goto cleanup; } @@ -128,7 +129,7 @@ int main(int argc, char** argv) /* Create UDP socket */ listenfd = socket(AF_INET, SOCK_DGRAM, 0); if (listenfd < 0) { - fprintf(stderr, "Error: Cannot create socket\n"); + XFPRINTF(stderr, "Error: Cannot create socket\n"); ret = 1; goto cleanup; } @@ -136,7 +137,7 @@ int main(int argc, char** argv) /* Set socket options */ ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, len); if (ret < 0) { - fprintf(stderr, "Error: setsockopt SO_REUSEADDR failed\n"); + XFPRINTF(stderr, "Error: setsockopt SO_REUSEADDR failed\n"); ret = 1; goto cleanup; } @@ -150,20 +151,20 @@ int main(int argc, char** argv) /* Bind socket */ ret = bind(listenfd, (struct sockaddr*)&servAddr, sizeof(servAddr)); if (ret < 0) { - fprintf(stderr, "Error: bind failed\n"); + XFPRINTF(stderr, "Error: bind failed\n"); ret = 1; goto cleanup; } - printf("DTLS server listening on port %d\n", SERV_PORT); - printf("Waiting for client connection...\n"); + XPRINTF("DTLS server listening on port %d\n", SERV_PORT); + XPRINTF("Waiting for client connection...\n"); /* Wait for client connection */ cliLen = sizeof(cliAddr); recvLen = (int)recvfrom(listenfd, buf, sizeof(buf), MSG_PEEK, (struct sockaddr*)&cliAddr, &cliLen); if (recvLen < 0) { - fprintf(stderr, "Error: recvfrom failed\n"); + XFPRINTF(stderr, "Error: recvfrom failed\n"); ret = 1; goto cleanup; } @@ -171,18 +172,18 @@ int main(int argc, char** argv) /* Connect UDP socket to client */ ret = connect(listenfd, (struct sockaddr*)&cliAddr, cliLen); if (ret != 0) { - fprintf(stderr, "Error: UDP connect failed\n"); + XFPRINTF(stderr, "Error: UDP connect failed\n"); ret = 1; goto cleanup; } - printf("Client connected from %s:%d\n", + XPRINTF("Client connected from %s:%d\n", inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port)); /* Create SSL object */ ssl = wolfSSL_new(ctx); if (ssl == NULL) { - fprintf(stderr, "Error: wolfSSL_new failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_new failed\n"); ret = 1; goto cleanup; } @@ -194,82 +195,86 @@ int main(int argc, char** argv) wolfSSL_set_fd(ssl, listenfd); /* Perform DTLS handshake */ - printf("Performing DTLS handshake...\n"); + XPRINTF("Performing DTLS handshake...\n"); ret = wolfSSL_accept(ssl); if (ret != SSL_SUCCESS) { int err = wolfSSL_get_error(ssl, ret); - fprintf(stderr, "Error: wolfSSL_accept failed: %d (%s)\n", + XFPRINTF(stderr, "Error: wolfSSL_accept failed: %d (%s)\n", err, wolfSSL_ERR_reason_error_string(err)); ret = 1; goto cleanup; } - printf("DTLS handshake successful!\n"); + XPRINTF("DTLS handshake successful!\n"); /* Export the session */ - printf("Exporting DTLS session...\n"); + XPRINTF("Exporting DTLS session...\n"); /* First call to get required buffer size */ ret = wolfSSL_dtls_export(ssl, NULL, &sessionSz); if (ret != 0 && sessionSz == 0) { - fprintf(stderr, "Error: wolfSSL_dtls_export (get size) failed: %d\n", + XFPRINTF(stderr, "Error: wolfSSL_dtls_export (get size) failed: %d\n", ret); ret = 1; goto cleanup; } /* Allocate buffer for session data */ - sessionBuf = (unsigned char*)malloc(sessionSz); + sessionBuf = (unsigned char*)XMALLOC(sessionSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (sessionBuf == NULL) { - fprintf(stderr, "Error: Memory allocation failed\n"); + XFPRINTF(stderr, "Error: Memory allocation failed\n"); ret = 1; goto cleanup; } + sessionBufSz = sessionSz; /* Export the session */ ret = wolfSSL_dtls_export(ssl, sessionBuf, &sessionSz); if (ret <= 0) { - fprintf(stderr, "Error: wolfSSL_dtls_export failed: %d\n", ret); + XFPRINTF(stderr, "Error: wolfSSL_dtls_export failed: %d\n", ret); ret = 1; goto cleanup; } - printf("Session exported: %d bytes\n", ret); + XPRINTF("Session exported: %d bytes\n", ret); sessionSz = ret; /* Save encrypted session to file */ ret = SaveEncryptedSession(sessionFile, sessionBuf, sessionSz); if (ret != 0) { - fprintf(stderr, "Error: Failed to save encrypted session\n"); + XFPRINTF(stderr, "Error: Failed to save encrypted session\n"); ret = 1; goto cleanup; } /* Handle one message exchange */ - printf("\nWaiting for message from client...\n"); + XPRINTF("\nWaiting for message from client...\n"); recvLen = wolfSSL_read(ssl, buf, sizeof(buf) - 1); if (recvLen > 0) { buf[recvLen] = '\0'; - printf("Received: %s", (char*)buf); + XPRINTF("Received: %s", (char*)buf); /* Send acknowledgment */ ret = wolfSSL_write(ssl, ack, (int)strlen(ack)); if (ret > 0) { - printf("Sent: %s", ack); + XPRINTF("Sent: %s", ack); } } else { int err = wolfSSL_get_error(ssl, recvLen); if (err != SSL_ERROR_WANT_READ) { - fprintf(stderr, "Warning: wolfSSL_read returned: %d (%s)\n", + XFPRINTF(stderr, "Warning: wolfSSL_read returned: %d (%s)\n", err, wolfSSL_ERR_reason_error_string(err)); } } - printf("\nSession exported and saved to: %s\n", sessionFile); - printf("You can now use server-dtls-import to resume this session.\n"); + XPRINTF("\nSession exported and saved to: %s\n", sessionFile); + XPRINTF("You can now use server-dtls-import to resume this session.\n"); ret = 0; cleanup: - if (sessionBuf != NULL) free(sessionBuf); + if (sessionBuf != NULL) { + wc_ForceZero(sessionBuf, sessionBufSz); + XFREE(sessionBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } if (ssl != NULL) { wolfSSL_shutdown(ssl); wolfSSL_free(ssl); diff --git a/dtls/server-dtls-import.c b/dtls/server-dtls-import.c index f1a83b9c1..fb0f63354 100644 --- a/dtls/server-dtls-import.c +++ b/dtls/server-dtls-import.c @@ -50,8 +50,8 @@ static void sig_handler(int sig) static void Usage(const char* progName) { - printf("Usage: %s [session_file]\n", progName); - printf(" session_file - Optional: file to load session from (default: %s)\n", + XPRINTF("Usage: %s [session_file]\n", progName); + XPRINTF(" session_file - Optional: file to load session from (default: %s)\n", DEFAULT_SERVER_SESSION_FILE); } @@ -72,6 +72,7 @@ int main(int argc, char** argv) const char* sessionFile = DEFAULT_SERVER_SESSION_FILE; unsigned char* sessionBuf = NULL; unsigned int sessionSz = 0; + unsigned int sessionBufSz = 0; /* Program argument checking */ if (argc > 2) { @@ -92,7 +93,7 @@ int main(int argc, char** argv) /* Create DTLS 1.2 context */ ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method()); if (ctx == NULL) { - fprintf(stderr, "Error: wolfSSL_CTX_new failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_CTX_new failed\n"); ret = 1; goto cleanup; } @@ -100,35 +101,35 @@ int main(int argc, char** argv) /* Create SSL object */ ssl = wolfSSL_new(ctx); if (ssl == NULL) { - fprintf(stderr, "Error: wolfSSL_new failed\n"); + XFPRINTF(stderr, "Error: wolfSSL_new failed\n"); ret = 1; goto cleanup; } /* Load encrypted session from file */ - printf("Loading session from %s...\n", sessionFile); - sessionBuf = LoadEncryptedSession(sessionFile, &sessionSz); + XPRINTF("Loading session from %s...\n", sessionFile); + sessionBuf = LoadEncryptedSession(sessionFile, &sessionSz, &sessionBufSz); if (sessionBuf == NULL) { - fprintf(stderr, "Error: Failed to load session from file\n"); + XFPRINTF(stderr, "Error: Failed to load session from file\n"); ret = 1; goto cleanup; } /* Import the session */ - printf("Importing DTLS session (%u bytes)...\n", sessionSz); + XPRINTF("Importing DTLS session (%u bytes)...\n", sessionSz); ret = wolfSSL_dtls_import(ssl, sessionBuf, sessionSz); if (ret < 0) { - fprintf(stderr, "Error: wolfSSL_dtls_import failed: %d\n", ret); - fprintf(stderr, "Make sure wolfSSL was compiled with --enable-sessionexport\n"); + XFPRINTF(stderr, "Error: wolfSSL_dtls_import failed: %d\n", ret); + XFPRINTF(stderr, "Make sure wolfSSL was compiled with --enable-sessionexport\n"); ret = 1; goto cleanup; } - printf("Session imported successfully!\n"); + XPRINTF("Session imported successfully!\n"); /* Create UDP socket */ listenfd = socket(AF_INET, SOCK_DGRAM, 0); if (listenfd < 0) { - fprintf(stderr, "Error: Cannot create socket\n"); + XFPRINTF(stderr, "Error: Cannot create socket\n"); ret = 1; goto cleanup; } @@ -136,7 +137,7 @@ int main(int argc, char** argv) /* Set socket options */ ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, len); if (ret < 0) { - fprintf(stderr, "Error: setsockopt SO_REUSEADDR failed\n"); + XFPRINTF(stderr, "Error: setsockopt SO_REUSEADDR failed\n"); ret = 1; goto cleanup; } @@ -150,21 +151,21 @@ int main(int argc, char** argv) /* Bind socket */ ret = bind(listenfd, (struct sockaddr*)&servAddr, sizeof(servAddr)); if (ret < 0) { - fprintf(stderr, "Error: bind failed\n"); + XFPRINTF(stderr, "Error: bind failed\n"); ret = 1; goto cleanup; } - printf("Session restored - no handshake needed!\n"); - printf("DTLS server listening on port %d\n", SERV_PORT); - printf("Waiting for client messages...\n\n"); + XPRINTF("Session restored - no handshake needed!\n"); + XPRINTF("DTLS server listening on port %d\n", SERV_PORT); + XPRINTF("Waiting for client messages...\n\n"); /* Wait for client connection */ cliLen = sizeof(cliAddr); recvLen = (int)recvfrom(listenfd, buf, sizeof(buf), MSG_PEEK, (struct sockaddr*)&cliAddr, &cliLen); if (recvLen < 0) { - fprintf(stderr, "Error: recvfrom failed\n"); + XFPRINTF(stderr, "Error: recvfrom failed\n"); ret = 1; goto cleanup; } @@ -172,12 +173,12 @@ int main(int argc, char** argv) /* Connect UDP socket to client */ ret = connect(listenfd, (struct sockaddr*)&cliAddr, cliLen); if (ret != 0) { - fprintf(stderr, "Error: UDP connect failed\n"); + XFPRINTF(stderr, "Error: UDP connect failed\n"); ret = 1; goto cleanup; } - printf("Client connected from %s:%d\n", + XPRINTF("Client connected from %s:%d\n", inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port)); /* Set DTLS peer */ @@ -191,16 +192,16 @@ int main(int argc, char** argv) recvLen = wolfSSL_read(ssl, buf, sizeof(buf) - 1); if (recvLen > 0) { buf[recvLen] = '\0'; - printf("Received: %s", (char*)buf); + XPRINTF("Received: %s", (char*)buf); /* Send acknowledgment */ ret = wolfSSL_write(ssl, ack, (int)strlen(ack)); if (ret > 0) { - printf("Sent: %s", ack); + XPRINTF("Sent: %s", ack); } else { int err = wolfSSL_get_error(ssl, ret); - fprintf(stderr, "Error: wolfSSL_write failed: %d (%s)\n", + XFPRINTF(stderr, "Error: wolfSSL_write failed: %d (%s)\n", err, wolfSSL_ERR_reason_error_string(err)); break; } @@ -208,7 +209,7 @@ int main(int argc, char** argv) else { int err = wolfSSL_get_error(ssl, recvLen); if (err != SSL_ERROR_WANT_READ) { - fprintf(stderr, "Error: wolfSSL_read failed: %d (%s)\n", + XFPRINTF(stderr, "Error: wolfSSL_read failed: %d (%s)\n", err, wolfSSL_ERR_reason_error_string(err)); break; } @@ -218,7 +219,10 @@ int main(int argc, char** argv) ret = 0; cleanup: - if (sessionBuf != NULL) free(sessionBuf); + if (sessionBuf != NULL) { + wc_ForceZero(sessionBuf, sessionBufSz); + XFREE(sessionBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } if (ssl != NULL) { wolfSSL_shutdown(ssl); wolfSSL_free(ssl); diff --git a/ecc/ecc-key-export.c b/ecc/ecc-key-export.c index 989b69e6d..a62b85efb 100644 --- a/ecc/ecc-key-export.c +++ b/ecc/ecc-key-export.c @@ -32,6 +32,7 @@ #include #include #include +#include /* Build wolfSSL with: ./configure --enable-ecccustcurves CFLAGS="-DWOLFSSL_DER_TO_PEM -DHAVE_ECC_KOBLITZ" @@ -62,125 +63,159 @@ int main(void) WC_RNG rng; ecc_key key; FILE *fp; + int initRng = 0; + int initKey = 0; + int wolfCryptInit = 0; wolfSSL_Debugging_ON(); ret = wolfCrypt_Init(); if (ret != 0) { printf("wolfCrypt_Init error %s (%d)\n", wc_GetErrorString(ret), ret); - return -1; } - - ret = wc_InitRng(&rng); - if (ret != 0) { - printf("wc_InitRng error %s (%d)\n", wc_GetErrorString(ret), ret); - return -1; + if (ret == 0) { + wolfCryptInit = 1; + ret = wc_InitRng(&rng); + if (ret != 0) { + printf("wc_InitRng error %s (%d)\n", wc_GetErrorString(ret), ret); + } } - - ret = wc_ecc_init(&key); - if (ret != 0) { - printf("wc_ecc_init error %s (%d)\n", wc_GetErrorString(ret), ret); - return -1; + if (ret == 0) { + initRng = 1; + ret = wc_ecc_init(&key); + if (ret != 0) { + printf("wc_ecc_init error %s (%d)\n", wc_GetErrorString(ret), ret); + } } - - ret = wc_ecc_make_key_ex(&rng, TEST_ECC_KEY_SZ, &key, TEST_ECC_KEY_CURVE); - if (ret != 0) { - printf("wc_ecc_make_key_ex error %s (%d)\n", wc_GetErrorString(ret), ret); - return -1; + if (ret == 0) { + initKey = 1; + ret = wc_ecc_make_key_ex(&rng, TEST_ECC_KEY_SZ, &key, TEST_ECC_KEY_CURVE); + if (ret != 0) { + printf("wc_ecc_make_key_ex error %s (%d)\n", wc_GetErrorString(ret), ret); + } } - printf("ECC Key Generated: %d bits, curve %s\n", TEST_ECC_KEY_SZ * 8, XSTRINGIFY(TEST_ECC_KEY_CURVE)); - - memset(der, 0, sizeof(der)); - ret = wc_EccKeyToDer(&key, der, sizeof(der)); - if (ret < 0) { - printf("wc_EccKeyToDer error %s (%d)\n", wc_GetErrorString(ret), ret); - return -1; + if (ret == 0) { + printf("ECC Key Generated: %d bits, curve %s\n", TEST_ECC_KEY_SZ * 8, XSTRINGIFY(TEST_ECC_KEY_CURVE)); + + memset(der, 0, sizeof(der)); + ret = wc_EccKeyToDer(&key, der, sizeof(der)); + if (ret < 0) { + printf("wc_EccKeyToDer error %s (%d)\n", wc_GetErrorString(ret), ret); + } } - derSz = ret; - - fp = fopen("./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".der", "wb"); - if (!fp) { - printf("Error opening %s for write\n", - "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".der"); - return -1; + if (ret >= 0) { + derSz = ret; + + fp = fopen("./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".der", "wb"); + if (!fp) { + printf("Error opening %s for write\n", + "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".der"); + ret = -1; + } + else { + fwrite(der, derSz, 1, fp); + fclose(fp); + + printf("ECC Private Key Exported to %s\n", + "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".der"); + ret = 0; + } } - fwrite(der, derSz, 1, fp); - fclose(fp); - - printf("ECC Private Key Exported to %s\n", - "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".der"); - #ifdef WOLFSSL_DER_TO_PEM - memset(pem, 0, sizeof(pem)); - ret = wc_DerToPem(der, derSz, pem, sizeof(pem), ECC_PRIVATEKEY_TYPE); - if (ret < 0) { - printf("wc_DerToPem error %s (%d)\n", wc_GetErrorString(ret), ret); - return -1; + if (ret == 0) { + memset(pem, 0, sizeof(pem)); + ret = wc_DerToPem(der, derSz, pem, sizeof(pem), ECC_PRIVATEKEY_TYPE); + if (ret < 0) { + printf("wc_DerToPem error %s (%d)\n", wc_GetErrorString(ret), ret); + } } - pemSz = ret; - - fp = fopen("./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".pem", "wb"); - if (!fp) { - printf("Error opening %s for write\n", - "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".pem"); - return -1; + if (ret >= 0) { + pemSz = ret; + + fp = fopen("./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".pem", "wb"); + if (!fp) { + printf("Error opening %s for write\n", + "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".pem"); + ret = -1; + } + else { + fwrite(pem, pemSz, 1, fp); + fclose(fp); + + printf("ECC Private Key Exported to %s\n", + "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".pem"); + ret = 0; + } } - fwrite(pem, pemSz, 1, fp); - fclose(fp); - - printf("ECC Private Key Exported to %s\n", - "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) ".pem"); #endif - memset(der, 0, sizeof(der)); - ret = wc_EccPublicKeyToDer(&key, der, sizeof(der), TEST_ECC_KEY_CURVE); - if (ret < 0) { - printf("wc_EccPublicKeyToDer error %s (%d)\n", wc_GetErrorString(ret), ret); - return -1; + if (ret == 0) { + memset(der, 0, sizeof(der)); + ret = wc_EccPublicKeyToDer(&key, der, sizeof(der), TEST_ECC_KEY_CURVE); + if (ret < 0) { + printf("wc_EccPublicKeyToDer error %s (%d)\n", wc_GetErrorString(ret), ret); + } } - derSz = ret; - - fp = fopen("./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.der", "wb"); - if (!fp) { - printf("Error opening %s for write\n", - "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.der"); - return -1; + if (ret >= 0) { + derSz = ret; + + fp = fopen("./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.der", "wb"); + if (!fp) { + printf("Error opening %s for write\n", + "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.der"); + ret = -1; + } + else { + fwrite(der, derSz, 1, fp); + fclose(fp); + + printf("ECC Public Key Exported to %s\n", + "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.der"); + ret = 0; + } } - fwrite(der, derSz, 1, fp); - fclose(fp); - - printf("ECC Public Key Exported to %s\n", - "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.der"); - #ifdef WOLFSSL_DER_TO_PEM - memset(pem, 0, sizeof(pem)); - ret = wc_DerToPem(der, derSz, pem, sizeof(pem), ECC_PUBLICKEY_TYPE); - if (ret < 0) { - /* try old type */ - ret = wc_DerToPem(der, derSz, pem, sizeof(pem), PUBLICKEY_TYPE); - } - if (ret < 0) { - printf("wc_DerToPem error %s (%d)\n", wc_GetErrorString(ret), ret); - return -1; + if (ret == 0) { + memset(pem, 0, sizeof(pem)); + ret = wc_DerToPem(der, derSz, pem, sizeof(pem), ECC_PUBLICKEY_TYPE); + if (ret < 0) { + /* try old type */ + ret = wc_DerToPem(der, derSz, pem, sizeof(pem), PUBLICKEY_TYPE); + } + if (ret < 0) { + printf("wc_DerToPem error %s (%d)\n", wc_GetErrorString(ret), ret); + } } - pemSz = ret; - - fp = fopen("./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.pem", "wb"); - if (!fp) { - printf("Error opening %s for write\n", - "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.pem"); - return -1; + if (ret >= 0) { + pemSz = ret; + + fp = fopen("./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.pem", "wb"); + if (!fp) { + printf("Error opening %s for write\n", + "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.pem"); + ret = -1; + } + else { + fwrite(pem, pemSz, 1, fp); + fclose(fp); + + printf("ECC Public Key Exported to %s\n", + "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.pem"); + ret = 0; + } } - fwrite(pem, pemSz, 1, fp); - fclose(fp); - - printf("ECC Public Key Exported to %s\n", - "./" XSTRINGIFY(TEST_ECC_KEY_CURVE) "_pub.pem"); #endif - wc_ecc_free(&key); - wc_FreeRng(&rng); - wolfCrypt_Cleanup(); - - return 0; -} \ No newline at end of file + wc_ForceZero(der, sizeof(der)); +#ifdef WOLFSSL_DER_TO_PEM + wc_ForceZero(pem, sizeof(pem)); +#endif + if (initKey) + wc_ecc_free(&key); + if (initRng) + wc_FreeRng(&rng); + if (wolfCryptInit) + wolfCrypt_Cleanup(); + + return ret; +} diff --git a/ecc/ecc-sign.c b/ecc/ecc-sign.c index f70a34017..d22a8ebf6 100644 --- a/ecc/ecc-sign.c +++ b/ecc/ecc-sign.c @@ -123,9 +123,9 @@ static int SignFirmware(byte* hashBuf, word32 hashLen, byte* sigBuf, word32* sig if (gMyKeyInit == 0) { ret = wc_ecc_init(&gMyKey); if (ret == 0) { + gMyKeyInit = 1; ret = wc_ecc_make_key_ex(&rng, ECC_KEY_SIZE, &gMyKey, ECC_KEY_CURVE); if (ret == 0) { - gMyKeyInit = 1; printf("KeyGen Done\n"); } } @@ -181,5 +181,10 @@ int main(void) #endif } + if (gMyKeyInit) { + wc_ecc_free(&gMyKey); + gMyKeyInit = 0; + } + return ret; } diff --git a/ecc/ecc-stack.c b/ecc/ecc-stack.c index 0b609ced6..44936c3c0 100644 --- a/ecc/ecc-stack.c +++ b/ecc/ecc-stack.c @@ -39,17 +39,22 @@ static ecc_key mGenKey; static void* do_it(void* args) { int ret; + int initKey = 0; InitMemoryTracker(); ret = wc_ecc_init(&mGenKey); if (ret == 0) { + initKey = 1; ret = wc_ecc_make_key(&mRng, TEST_KEY_SZ, &mGenKey); } if (ret != 0) { printf("ecc make key failed %d\n", ret); } + if (initKey) + wc_ecc_free(&mGenKey); + ShowMemoryTracker(); CleanupMemoryTracker(); diff --git a/ocsp/responder/ocsp-load-certs.h b/ocsp/responder/ocsp-load-certs.h index d4466f290..959effed9 100644 --- a/ocsp/responder/ocsp-load-certs.h +++ b/ocsp/responder/ocsp-load-certs.h @@ -26,8 +26,10 @@ #include /* WC_MAYBE_UNUSED */ #include /* wc_CertPemToDer, wc_KeyPemToDer */ +#include /* wc_ForceZero */ #include #include +#include /* Load file into malloc'd buffer. Caller must free(*buf). */ static WC_MAYBE_UNUSED byte* LoadFile(const char* path, int* outSz) @@ -76,8 +78,17 @@ static WC_MAYBE_UNUSED byte* LoadKeyDer(const char* path, int* derSz) pem = LoadFile(path, &pemSz); if (!pem) return NULL; der = (byte*)malloc((size_t)pemSz); - if (!der) { free(pem); return NULL; } + if (!der) { + /* Zero the PEM buffer before releasing it, it may hold the + * unencrypted private key material. */ + wc_ForceZero(pem, (word32)pemSz); + free(pem); + return NULL; + } ret = wc_KeyPemToDer(pem, pemSz, der, pemSz, NULL); + /* Zero the PEM buffer before releasing it since it may contain the + * unencrypted private key material. */ + wc_ForceZero(pem, (word32)pemSz); free(pem); if (ret <= 0) { free(der); return NULL; } *derSz = ret; diff --git a/ocsp/responder/ocsp-request-response.c b/ocsp/responder/ocsp-request-response.c index 92ba40086..493548a3b 100644 --- a/ocsp/responder/ocsp-request-response.c +++ b/ocsp/responder/ocsp-request-response.c @@ -37,6 +37,7 @@ #include #include +#include #include #if defined(HAVE_OCSP) && defined(HAVE_OCSP_RESPONDER) && \ @@ -402,7 +403,11 @@ int main(int argc, char** argv) if (caCertInit) wc_FreeDecodedCert(&caCert); free(caCertDer); - free(caKeyDer); + if (caKeyDer) { + /* Zero the CA private key material before releasing the buffer. */ + wc_ForceZero(caKeyDer, (word32)caKeyDerSz); + free(caKeyDer); + } free(serverCertDer); wolfSSL_Cleanup(); diff --git a/ocsp/responder/ocsp-responder-http.c b/ocsp/responder/ocsp-responder-http.c index a0dfdbfd1..2fc249e1a 100644 --- a/ocsp/responder/ocsp-responder-http.c +++ b/ocsp/responder/ocsp-responder-http.c @@ -382,7 +382,11 @@ int main(int argc, char** argv) if (responder) wc_OcspResponder_free(responder); if (caCertInit) wc_FreeDecodedCert(&caCert); free(caCertDer); - free(caKeyDer); + if (caKeyDer) { + /* Zero the CA private key material before releasing the buffer. */ + wc_ForceZero(caKeyDer, (word32)caKeyDerSz); + free(caKeyDer); + } wolfSSL_Cleanup(); return ret; } diff --git a/ocsp/stapling/ocsp-server.c b/ocsp/stapling/ocsp-server.c index d758f936b..e071f798a 100644 --- a/ocsp/stapling/ocsp-server.c +++ b/ocsp/stapling/ocsp-server.c @@ -288,6 +288,11 @@ int main() if (connfd >= 0) close(connfd); if (listenfd >= 0) close(listenfd); if (ctx) wolfSSL_CTX_free(ctx); + if (ocsp_resp) { + XFREE(ocsp_resp, NULL, DYNAMIC_TYPE_OCSP); + ocsp_resp = NULL; + ocsp_resp_sz = 0; + } wolfSSL_Cleanup(); return ret; } diff --git a/pkcs7/authEnvelopedData-kari.c b/pkcs7/authEnvelopedData-kari.c index 849f340e3..151914638 100644 --- a/pkcs7/authEnvelopedData-kari.c +++ b/pkcs7/authEnvelopedData-kari.c @@ -75,6 +75,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/authEnvelopedData-kekri.c b/pkcs7/authEnvelopedData-kekri.c index 44669f93e..af04df5c2 100644 --- a/pkcs7/authEnvelopedData-kekri.c +++ b/pkcs7/authEnvelopedData-kekri.c @@ -58,6 +58,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/authEnvelopedData-ktri.c b/pkcs7/authEnvelopedData-ktri.c index 6f656e098..1f9f9356b 100644 --- a/pkcs7/authEnvelopedData-ktri.c +++ b/pkcs7/authEnvelopedData-ktri.c @@ -71,6 +71,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/authEnvelopedData-ori.c b/pkcs7/authEnvelopedData-ori.c index 6a42d92c6..8b7cde3da 100644 --- a/pkcs7/authEnvelopedData-ori.c +++ b/pkcs7/authEnvelopedData-ori.c @@ -78,6 +78,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/authEnvelopedData-pwri.c b/pkcs7/authEnvelopedData-pwri.c index cebe8d17e..caa38f8d3 100644 --- a/pkcs7/authEnvelopedData-pwri.c +++ b/pkcs7/authEnvelopedData-pwri.c @@ -78,6 +78,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/compressedData.c b/pkcs7/compressedData.c index 41a831fc3..66446e5a3 100644 --- a/pkcs7/compressedData.c +++ b/pkcs7/compressedData.c @@ -48,6 +48,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/encryptedData.c b/pkcs7/encryptedData.c index 0d812b062..c4f58ac2e 100644 --- a/pkcs7/encryptedData.c +++ b/pkcs7/encryptedData.c @@ -52,6 +52,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); @@ -86,6 +87,7 @@ static int encryptedData_encrypt(byte* out, word32 outSz) if (write_file_buffer(encryptedFile, out, ret) != 0) { printf("ERROR: error writing encoded to output file\n"); + wc_PKCS7_Free(pkcs7); return -1; } } diff --git a/pkcs7/envelopedData-kari.c b/pkcs7/envelopedData-kari.c index d34d44205..e97549f1d 100644 --- a/pkcs7/envelopedData-kari.c +++ b/pkcs7/envelopedData-kari.c @@ -75,6 +75,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/envelopedData-kekri.c b/pkcs7/envelopedData-kekri.c index 3646e929d..7763adfa4 100644 --- a/pkcs7/envelopedData-kekri.c +++ b/pkcs7/envelopedData-kekri.c @@ -58,6 +58,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/envelopedData-ktri.c b/pkcs7/envelopedData-ktri.c index b30604706..78306f075 100644 --- a/pkcs7/envelopedData-ktri.c +++ b/pkcs7/envelopedData-ktri.c @@ -71,6 +71,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/envelopedData-ori.c b/pkcs7/envelopedData-ori.c index ed63df9d4..4ead5b496 100644 --- a/pkcs7/envelopedData-ori.c +++ b/pkcs7/envelopedData-ori.c @@ -78,6 +78,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/envelopedData-pwri.c b/pkcs7/envelopedData-pwri.c index 5b2e3b739..b29e40cbc 100644 --- a/pkcs7/envelopedData-pwri.c +++ b/pkcs7/envelopedData-pwri.c @@ -48,6 +48,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/signedData-CompressedFirmwarePkgData.c b/pkcs7/signedData-CompressedFirmwarePkgData.c index fd7afb534..3aa5aac87 100644 --- a/pkcs7/signedData-CompressedFirmwarePkgData.c +++ b/pkcs7/signedData-CompressedFirmwarePkgData.c @@ -86,6 +86,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/signedData-DetachedSignature.c b/pkcs7/signedData-DetachedSignature.c index ad358a63c..be1c42b19 100644 --- a/pkcs7/signedData-DetachedSignature.c +++ b/pkcs7/signedData-DetachedSignature.c @@ -75,6 +75,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); @@ -150,6 +151,8 @@ static int signedData_sign_noattrs(byte* cert, word32 certSz, byte* key, if (write_file_buffer(encodedFileNoAttrs, out, ret) != 0) { printf("ERROR: error writing encoded to output file\n"); + wc_PKCS7_Free(pkcs7); + wc_FreeRng(&rng); return -1; } } @@ -239,6 +242,8 @@ static int signedData_sign_attrs(byte* cert, word32 certSz, byte* key, if (write_file_buffer(encodedFileAttrs, out, ret) != 0) { printf("ERROR: error writing encoded to output file\n"); + wc_PKCS7_Free(pkcs7); + wc_FreeRng(&rng); return -1; } diff --git a/pkcs7/signedData-EncryptedCompressedFirmwarePkgData.c b/pkcs7/signedData-EncryptedCompressedFirmwarePkgData.c index 02510ff8f..8af72656a 100644 --- a/pkcs7/signedData-EncryptedCompressedFirmwarePkgData.c +++ b/pkcs7/signedData-EncryptedCompressedFirmwarePkgData.c @@ -96,6 +96,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/signedData-EncryptedFirmwareCB.c b/pkcs7/signedData-EncryptedFirmwareCB.c index b0d906946..39bbd2d44 100644 --- a/pkcs7/signedData-EncryptedFirmwareCB.c +++ b/pkcs7/signedData-EncryptedFirmwareCB.c @@ -82,6 +82,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); @@ -387,6 +388,7 @@ static int generateBundle(byte* out, word32 *outSz, const byte* encryptKey, *outSz = ret; if (write_file_buffer(fileName, out, ret) != 0) { printf("ERROR: error writing encoded to output file\n"); + wc_PKCS7_Free(pkcs7); return -1; } @@ -438,7 +440,8 @@ static int getFirmwareKey(PKCS7* pkcs7, byte* key, word32 keySz) wc_PKCS7_Init(envPkcs7, NULL, 0); if (wc_PKCS7_SetWrapCEKCb(envPkcs7, myCEKwrapFunc) != 0) { printf("\tIssue setting CEK wrap callback\n"); - return ret; + wc_PKCS7_Free(envPkcs7); + return BAD_FUNC_ARG; } envPkcs7->contentOID = FIRMWARE_PKG_DATA; /* expected content */ ret = wc_PKCS7_DecodeEnvelopedData(envPkcs7, atr, ret, diff --git a/pkcs7/signedData-EncryptedFirmwarePkgData.c b/pkcs7/signedData-EncryptedFirmwarePkgData.c index 5309ea82c..99debcc71 100644 --- a/pkcs7/signedData-EncryptedFirmwarePkgData.c +++ b/pkcs7/signedData-EncryptedFirmwarePkgData.c @@ -90,6 +90,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); @@ -140,6 +141,7 @@ static int signedData_sign_noattrs(byte* cert, word32 certSz, byte* privateKey, if (write_file_buffer(encodedFileNoAttrs, out, ret) != 0) { printf("ERROR: error writing encoded to output file\n"); + wc_PKCS7_Free(pkcs7); return -1; } diff --git a/pkcs7/signedData-FirmwarePkgData.c b/pkcs7/signedData-FirmwarePkgData.c index 3d861a992..672e72ab7 100644 --- a/pkcs7/signedData-FirmwarePkgData.c +++ b/pkcs7/signedData-FirmwarePkgData.c @@ -79,6 +79,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pkcs7/signedData-cryptocb.c b/pkcs7/signedData-cryptocb.c index a811cec4a..fdd18c450 100644 --- a/pkcs7/signedData-cryptocb.c +++ b/pkcs7/signedData-cryptocb.c @@ -124,6 +124,7 @@ static int write_file(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); @@ -244,6 +245,7 @@ static int myCryptoCb(int devIdArg, wc_CryptoInfo* info, void* ctx) ret = wc_InitRsaKey_ex(&rsaPriv, NULL, INVALID_DEVID); if (ret != 0) { + free(der); return ret; } ret = wc_RsaPrivateKeyDecode(der, &idx, &rsaPriv, derSz); @@ -306,6 +308,7 @@ static int myCryptoCb(int devIdArg, wc_CryptoInfo* info, void* ctx) ret = wc_ecc_init_ex(&eccPriv, NULL, INVALID_DEVID); if (ret != 0) { + free(der); return ret; } ret = wc_EccPrivateKeyDecode(der, &idx, &eccPriv, derSz); diff --git a/pkcs7/signedData-stream.c b/pkcs7/signedData-stream.c index 6b89a2a7d..aa428b9dd 100644 --- a/pkcs7/signedData-stream.c +++ b/pkcs7/signedData-stream.c @@ -335,6 +335,11 @@ int main(int argc, char** argv) { FILE* f = fopen(encodedFile, "rb"); + if (f == NULL) { + printf("error opening file %s\n", encodedFile); + ret = -1; + goto out; + } encryptedSz = fread(encrypted, 1, encryptedSz, f); fclose(f); } @@ -347,8 +352,10 @@ int main(int argc, char** argv) decryptedSz = signedData_verify(encrypted, encryptedSz, cert, certSz, key, keySz, decrypted, decryptedSz); - if (decryptedSz < 0) - return -1; + if (decryptedSz < 0) { + ret = -1; + goto out; + } #endif out: diff --git a/pkcs7/signedData.c b/pkcs7/signedData.c index 1ef8580e9..4a05f9cc6 100644 --- a/pkcs7/signedData.c +++ b/pkcs7/signedData.c @@ -71,6 +71,7 @@ static int write_file_buffer(const char* fileName, byte* in, word32 inSz) ret = (int)fwrite(in, 1, inSz, file); if (ret == 0) { printf("ERROR: writing buffer to output file\n"); + fclose(file); return -1; } fclose(file); diff --git a/pq/ml_dsa/ml_dsa.c b/pq/ml_dsa/ml_dsa.c index 22b70ac3e..8bac0691f 100644 --- a/pq/ml_dsa/ml_dsa.c +++ b/pq/ml_dsa/ml_dsa.c @@ -2,12 +2,14 @@ #include #include #include +#include #include /* wolfssl includes */ #include #include #include +#include struct ml_dsa_len_t { uint8_t sec_cat; @@ -50,6 +52,7 @@ main(int argc, int rc = 0; int opt = 0; MlDsaKey key; + int initKey = 0; WC_RNG rng; byte * priv = NULL; byte * pub = NULL; @@ -105,6 +108,7 @@ main(int argc, printf("error: wc_MlDsaKey_Init returned %d\n", rc); goto ml_dsa_exit; } + initKey = 1; rc = wc_MlDsaKey_SetParams(&key, sec_cat); if (rc != 0) { @@ -243,11 +247,18 @@ main(int argc, ml_dsa_exit: - wc_MlDsaKey_Free(&key); + if (initKey) { + wc_MlDsaKey_Free(&key); + } wc_FreeRng(&rng); ml_dsa_free((void *) &sig); ml_dsa_free((void *) &pub); + /* priv holds the secret ML-DSA private key material, zero it before + * releasing the buffer. */ + if (priv != NULL) { + wc_ForceZero(priv, (word32) ml_dsa_priv_len); + } ml_dsa_free((void *) &priv); return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE; diff --git a/pq/ml_kem/ml_kem.c b/pq/ml_kem/ml_kem.c index df3cd9e0f..ae524a89b 100644 --- a/pq/ml_kem/ml_kem.c +++ b/pq/ml_kem/ml_kem.c @@ -26,7 +26,6 @@ #include #endif #include -#include #include #include @@ -54,6 +53,9 @@ int main(int argc, char** argv) MlKemKey BobKey; int ret = 0; WC_RNG rng; + int rngInit = 0; + int aliceKeyInit = 0; + int bobKeyInit = 0; byte alice_pub[WC_ML_KEM_512_PUBLIC_KEY_SIZE]; byte bob_ct[WC_ML_KEM_512_CIPHER_TEXT_SIZE]; byte alice_ss[WC_ML_KEM_SS_SZ]; @@ -62,12 +64,20 @@ int main(int argc, char** argv) printf("Alice creates an ML-KEM-512 key pair\n\n"); ret = wc_InitRng(&rng); - if (ret == 0) + rngInit = 1; + + if (ret == 0) { ret = wc_MlKemKey_Init(&AliceKey, WC_ML_KEM_512, 0, INVALID_DEVID); + if (ret == 0) + aliceKeyInit = 1; + } - if (ret == 0) + if (ret == 0) { ret = wc_MlKemKey_Init(&BobKey, WC_ML_KEM_512, 0, INVALID_DEVID); + if (ret == 0) + bobKeyInit = 1; + } if (ret == 0) ret = wc_MlKemKey_MakeKey(&AliceKey, &rng); @@ -75,8 +85,11 @@ int main(int argc, char** argv) if (ret == 0) ret = wc_MlKemKey_EncodePublicKey(&AliceKey, alice_pub, WC_ML_KEM_512_PUBLIC_KEY_SIZE); - if (ret == 0) - printf("Bob receives public key (size=%d): %s\n\n", WC_ML_KEM_512_PUBLIC_KEY_SIZE, to_hex_string(alice_pub, WC_ML_KEM_512_PUBLIC_KEY_SIZE)); + if (ret == 0) { + char* alice_pub_hex = to_hex_string(alice_pub, WC_ML_KEM_512_PUBLIC_KEY_SIZE); + printf("Bob receives public key (size=%d): %s\n\n", WC_ML_KEM_512_PUBLIC_KEY_SIZE, alice_pub_hex); + free(alice_pub_hex); + } if (ret == 0) ret = wc_MlKemKey_DecodePublicKey(&BobKey, alice_pub, WC_ML_KEM_512_PUBLIC_KEY_SIZE); @@ -84,8 +97,11 @@ int main(int argc, char** argv) if (ret == 0) ret = wc_MlKemKey_Encapsulate(&BobKey, bob_ct, bob_ss, &rng); - if (ret == 0) - printf("Bob Encapsulates secret (Size=%d): %s\n\n", WC_ML_KEM_512_CIPHER_TEXT_SIZE, to_hex_string(bob_ct, WC_ML_KEM_512_CIPHER_TEXT_SIZE)); + if (ret == 0) { + char* bob_ct_hex = to_hex_string(bob_ct, WC_ML_KEM_512_CIPHER_TEXT_SIZE); + printf("Bob Encapsulates secret (Size=%d): %s\n\n", WC_ML_KEM_512_CIPHER_TEXT_SIZE, bob_ct_hex); + free(bob_ct_hex); + } if (ret == 0) printf("Alice receives the ciphertext\n"); @@ -94,15 +110,22 @@ int main(int argc, char** argv) ret = wc_MlKemKey_Decapsulate(&AliceKey, alice_ss, bob_ct, WC_ML_KEM_512_CIPHER_TEXT_SIZE); if (ret == 0) { - printf("Alice's Shared Secret: %s\n\n", to_hex_string(alice_ss, WC_ML_KEM_SS_SZ)); - printf(" Bob's Shared Secret: %s\n\n", to_hex_string(bob_ss, WC_ML_KEM_SS_SZ)); + char* alice_ss_hex = to_hex_string(alice_ss, WC_ML_KEM_SS_SZ); + char* bob_ss_hex = to_hex_string(bob_ss, WC_ML_KEM_SS_SZ); + printf("Alice's Shared Secret: %s\n\n", alice_ss_hex); + printf(" Bob's Shared Secret: %s\n\n", bob_ss_hex); + free(alice_ss_hex); + free(bob_ss_hex); } else { printf("An error occurred\n"); } - wc_MlKemKey_Free(&AliceKey); - wc_MlKemKey_Free(&BobKey); - wc_FreeRng(&rng); + if (aliceKeyInit) + wc_MlKemKey_Free(&AliceKey); + if (bobKeyInit) + wc_MlKemKey_Free(&BobKey); + if (rngInit) + wc_FreeRng(&rng); return ret; } diff --git a/pq/stateful_hash_sig/lms_example.c b/pq/stateful_hash_sig/lms_example.c index 33a40cbc3..50b2c1375 100644 --- a/pq/stateful_hash_sig/lms_example.c +++ b/pq/stateful_hash_sig/lms_example.c @@ -148,8 +148,7 @@ write_key_file(const byte * priv, /* Create the file if it didn't exist. */ file = fopen(filename, "w+"); if (!file) { - fprintf(stderr, "error: fopen(%s, \"w+\") failed: %d\n", filename, - ferror(file)); + fprintf(stderr, "error: fopen(%s, \"w+\") failed\n", filename); return WC_LMS_RC_WRITE_FAIL; } } @@ -159,6 +158,7 @@ write_key_file(const byte * priv, if (n_write != privSz) { fprintf(stderr, "error: wrote %zu, expected %d: %d\n", n_write, privSz, ferror(file)); + fclose(file); return WC_LMS_RC_WRITE_FAIL; } @@ -172,12 +172,14 @@ write_key_file(const byte * priv, if (n_read != n_write) { fprintf(stderr, "error: read %zu, expected %zu: %d\n", n_read, n_write, ferror(file)); + fclose(file); return WC_LMS_RC_WRITE_FAIL; } n_cmp = XMEMCMP(buff, priv, n_write); if (n_cmp != 0) { fprintf(stderr, "error: write data was corrupted: %d\n", n_cmp); + fclose(file); return WC_LMS_RC_WRITE_FAIL; } @@ -217,6 +219,7 @@ read_key_file(byte * priv, if (n_read != privSz) { fprintf(stderr, "error: read %zu, expected %d: %d\n", n_read, privSz, ferror(file)); + fclose(file); return WC_LMS_RC_READ_FAIL; } diff --git a/pq/stateful_hash_sig/xmss_example.c b/pq/stateful_hash_sig/xmss_example.c index 11acd364f..be54659ad 100644 --- a/pq/stateful_hash_sig/xmss_example.c +++ b/pq/stateful_hash_sig/xmss_example.c @@ -116,8 +116,7 @@ write_key_file(const byte * priv, /* Create the file if it didn't exist. */ file = fopen(filename, "w+"); if (!file) { - fprintf(stderr, "error: fopen(%s, \"w+\") failed: %d\n", filename, - ferror(file)); + fprintf(stderr, "error: fopen(%s, \"w+\") failed\n", filename); return WC_XMSS_RC_WRITE_FAIL; } } @@ -127,6 +126,7 @@ write_key_file(const byte * priv, if (n_write != privSz) { fprintf(stderr, "error: wrote %zu, expected %d: %d\n", n_write, privSz, ferror(file)); + fclose(file); return WC_XMSS_RC_WRITE_FAIL; } @@ -140,12 +140,14 @@ write_key_file(const byte * priv, if (n_read != n_write) { fprintf(stderr, "error: read %zu, expected %zu: %d\n", n_read, n_write, ferror(file)); + fclose(file); return WC_XMSS_RC_WRITE_FAIL; } n_cmp = XMEMCMP(read_buf, priv, n_write); if (n_cmp != 0) { fprintf(stderr, "error: write data was corrupted: %d\n", n_cmp); + fclose(file); return WC_XMSS_RC_WRITE_FAIL; } @@ -185,6 +187,7 @@ read_key_file(byte * priv, if (n_read != privSz) { fprintf(stderr, "error: read %zu, expected %d: %d\n", n_read, privSz, ferror(file)); + fclose(file); return WC_XMSS_RC_READ_FAIL; } diff --git a/puf/main.c b/puf/main.c index f81056230..187939356 100644 --- a/puf/main.c +++ b/puf/main.c @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -195,6 +196,8 @@ int main(void) else { printf("FAIL: Identity mismatch!\n"); ret = -1; + wc_ForceZero(key2, sizeof(key2)); + wc_ForceZero(identity2, sizeof(identity2)); goto cleanup; } @@ -202,6 +205,8 @@ int main(void) ret = wc_PufDeriveKey(&ctx, info, sizeof(info), key2, sizeof(key2)); if (ret != 0) { printf("ERROR: wc_PufDeriveKey failed: %d\n", ret); + wc_ForceZero(key2, sizeof(key2)); + wc_ForceZero(identity2, sizeof(identity2)); goto cleanup; } print_hex("Derived key (reconstructed)", key2, WC_PUF_KEY_SZ); @@ -212,6 +217,11 @@ int main(void) else { printf("FAIL: Derived key mismatch!\n"); ret = -1; + } + + wc_ForceZero(key2, sizeof(key2)); + wc_ForceZero(identity2, sizeof(identity2)); + if (ret != 0) { goto cleanup; } } @@ -309,12 +319,16 @@ int main(void) else { printf("FAIL: Identity mismatch after reconstruction!\n"); ret = -1; + wc_ForceZero(key2, sizeof(key2)); + wc_ForceZero(identity2, sizeof(identity2)); goto cleanup; } ret = wc_PufDeriveKey(&ctx, info, sizeof(info), key2, sizeof(key2)); if (ret != 0) { printf("ERROR: wc_PufDeriveKey (reconstruct) failed: %d\n", ret); + wc_ForceZero(key2, sizeof(key2)); + wc_ForceZero(identity2, sizeof(identity2)); goto cleanup; } print_hex("Derived key (reconstructed)", key2, WC_PUF_KEY_SZ); @@ -325,6 +339,11 @@ int main(void) else { printf("FAIL: Derived key mismatch after reconstruction!\n"); ret = -1; + } + + wc_ForceZero(key2, sizeof(key2)); + wc_ForceZero(identity2, sizeof(identity2)); + if (ret != 0) { goto cleanup; } } @@ -334,6 +353,9 @@ int main(void) cleanup: /* Securely zeroize all PUF secrets */ + wc_ForceZero(key, sizeof(key)); + wc_ForceZero(identity, sizeof(identity)); + wc_ForceZero(helperData, sizeof(helperData)); wc_PufZeroize(&ctx); wolfCrypt_Cleanup(); diff --git a/staticmemory/memory-bucket-optimizer/optimizer/memory_bucket_optimizer.c b/staticmemory/memory-bucket-optimizer/optimizer/memory_bucket_optimizer.c index 657ade1b1..066528ae7 100644 --- a/staticmemory/memory-bucket-optimizer/optimizer/memory_bucket_optimizer.c +++ b/staticmemory/memory-bucket-optimizer/optimizer/memory_bucket_optimizer.c @@ -45,6 +45,7 @@ typedef struct AllocationEventNode { struct AllocationEventNode* next; } AllocationEventNode; AllocationEventNode* event_head = NULL; +static AllocationEventNode* event_tail = NULL; /* Linked list node for unique allocation sizes */ typedef struct AllocSizeNode { @@ -94,11 +95,11 @@ void add_allocation_event(AllocationEventNode** list, int size, int timestamp, if (node) { if (*list == NULL) { event_head = node; - *list = node; + *list = node; /* Caller's pointer keeps referencing the head */ } else { - (*list)->next = node; - *list = node; /* Update the list pointer to point to the new node */ + event_tail->next = node; /* Append via the tail, not the head */ } + event_tail = node; } } diff --git a/tls/client-tls-resume.c b/tls/client-tls-resume.c index 07827d246..81f866af5 100644 --- a/tls/client-tls-resume.c +++ b/tls/client-tls-resume.c @@ -180,6 +180,7 @@ int main(int argc, char** argv) wolfSSL_free(ssl); ssl = NULL; close(sockfd); + sockfd = SOCKET_INVALID; /* --------------------------------------- * @@ -275,6 +276,8 @@ int main(int argc, char** argv) /* Cleanup and return */ if (ssl) wolfSSL_free(ssl); /* Free the wolfSSL object */ + if (sslRes) + wolfSSL_free(sslRes); /* Free the resumed wolfSSL object */ if (session) wolfSSL_SESSION_free(session); if (sockfd != SOCKET_INVALID) diff --git a/tls/server-tls-epoll-perf.c b/tls/server-tls-epoll-perf.c index 6f98bbc0a..ccae5059d 100644 --- a/tls/server-tls-epoll-perf.c +++ b/tls/server-tls-epoll-perf.c @@ -475,6 +475,7 @@ static int SSLConn_Accept(SSLConn_CTX* ctx, WOLFSSL_CTX* sslCtx, /* Setup SSL/TLS connection. */ if ((conn->ssl = wolfSSL_new(sslCtx)) == NULL) { + close(conn->sockfd); free(conn); fprintf(stderr, "wolfSSL_new error.\n"); return EXIT_FAILURE; diff --git a/tls/server-tls-epoll-threaded.c b/tls/server-tls-epoll-threaded.c index 714471fce..945834e80 100644 --- a/tls/server-tls-epoll-threaded.c +++ b/tls/server-tls-epoll-threaded.c @@ -583,6 +583,7 @@ static int SSLConn_Accept(ThreadData* threadData, WOLFSSL_CTX* sslCtx, /* Setup SSL/TLS connection. */ if ((conn->ssl = wolfSSL_new(sslCtx)) == NULL) { + close(conn->sockfd); free(conn); fprintf(stderr, "wolfSSL_new error.\n"); return EXIT_FAILURE; diff --git a/tls/server-tls-poll-perf.c b/tls/server-tls-poll-perf.c index 3cd702372..9da6b913e 100644 --- a/tls/server-tls-poll-perf.c +++ b/tls/server-tls-poll-perf.c @@ -471,6 +471,7 @@ static int SSLConn_Accept(SSLConn_CTX* ctx, WOLFSSL_CTX* sslCtx, /* Setup SSL/TLS connection. */ if ((conn->ssl = wolfSSL_new(sslCtx)) == NULL) { + close(conn->sockfd); free(conn); fprintf(stderr, "wolfSSL_new error.\n"); return EXIT_FAILURE; diff --git a/tls/server-tls-threaded.c b/tls/server-tls-threaded.c index 3a9df872d..c06f9f6cb 100644 --- a/tls/server-tls-threaded.c +++ b/tls/server-tls-threaded.c @@ -73,6 +73,7 @@ void* ClientHandler(void* args) /* Create a WOLFSSL object */ if ((ssl = wolfSSL_new(pkg->ctx)) == NULL) { fprintf(stderr, "ERROR: failed to create WOLFSSL object\n"); + close(pkg->connd); pkg->open = 1; pthread_exit(NULL); }