From aea620f85f68ee8653be67097ab69170a2a917cf Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 19 Apr 2023 08:10:32 +0800 Subject: [PATCH 001/391] feat: enable new remote attestation feature by default --- CMakeLists.txt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 89d6041eaff..3aeb485ab27 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -353,6 +353,16 @@ if(NOT WOLFSSL_RNG) list(APPEND WOLFSSL_DEFINITIONS "-DWC_NO_RNG") endif() +# Remote Attestation +# TODO: Make disabled by default. This is for testing only for now. +add_option("WOLFSSL_REMOTE_ATTESTATION" + "Enable wolfSSL remote attestation (default: enabled)" + "yes" "yes;no") + +if(WOLFSSL_REMOTE_ATTESTATION) + list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_REMOTE_ATTESTATION") +endif() + # TODO: - DTLS-SCTP # - DTLS multicast # - OpenSSH From 2d5c75f9a428c1d5f252018eda7dff833c598bf2 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 19 Apr 2023 08:20:05 +0800 Subject: [PATCH 002/391] feat: add 'evidence_request' TLS extension --- wolfssl/internal.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index e98e8080487..a8b879c625b 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2607,6 +2607,9 @@ typedef enum { #ifdef WOLFSSL_QUIC TLSX_KEY_QUIC_TP_PARAMS = 0x0039, /* RFC 9001, ch. 8.2 */ #endif +#endif +#ifdef WOLFSSL_REMOTE_ATTESTATION + TLSX_EVIDENCE_REQUEST = 0xAA00, /* remote attestation, arbitrary number for now */ #endif TLSX_RENEGOTIATION_INFO = 0xff01, #ifdef WOLFSSL_QUIC From 465d710ae34496f8240481344dab7763f8fc7b3b Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 19 Apr 2023 08:21:18 +0800 Subject: [PATCH 003/391] feat: add 'unsupported_evidence' alert --- src/internal.c | 6 ++++++ wolfssl/ssl.h | 1 + 2 files changed, 7 insertions(+) diff --git a/src/internal.c b/src/internal.c index 0fffa2418dd..731705443f1 100644 --- a/src/internal.c +++ b/src/internal.c @@ -18734,6 +18734,12 @@ const char* AlertTypeToString(int type) return bad_certificate_status_response_str; } + case unsupported_evidence: + { + static const char unsupported_evidence_str[] = "unsupported_evidence"; + return unsupported_evidence_str; + } + case no_application_protocol: { static const char no_application_protocol_str[] = diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index f9c20d1f9df..6609ed5e140 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -763,6 +763,7 @@ enum AlertDescription { bad_certificate_status_response = 113, /**< RFC 6066, section 8 */ unknown_psk_identity = 115, /**< RFC 4279, section 2 */ certificate_required = 116, /**< RFC 8446, section 8.2 */ + unsupported_evidence = 118, /**< remote attestation, arbitrary value for now */ no_application_protocol = 120 }; From 8d1f27a6a70c0c432b86ff82cbd51995586c268e Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 19 Apr 2023 08:45:57 +0800 Subject: [PATCH 004/391] feat: add pulic header definitions for 'evidence_request' --- wolfssl/ssl.h | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 6609ed5e140..1f2a216583f 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3666,6 +3666,37 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); /* TLS Extensions */ +#ifdef WOLFSSL_REMOTE_ATTESTATION +// TODO: WIP definitions + +/* + * Evidence Request extension. + * + * For 'client', the data should be: + * 4 bytes Nonce for Evidence Generation + * 1 byte Number of Evidences supported (e.g. 2) + * 1 byte Type Description Length [1st evidence] + * ? bytes Type Description + * 1 byte Type Description Length [2nd evidence] + * ? bytes Type Description + * + * For 'server', the data should be + * 1 byte Type Description Length [e.g. 1st evidence] + * ? bytes Type Description + * 2 bytes Evidence Data Length + * ? bytes Evidence Data + */ +WOLFSSL_API int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev); + +/* + * Returns stored data from the Evidence Request Extension. + * - 'client': data to send to 'server' + * - 'server': data received from 'client' + */ +WOLFSSL_API void *wolfSSL_GetEvidence(WOLFSSL *ssl); + +#endif /* WOLFSSL_REMOTE_ATTESTATION */ + /* Server Name Indication */ #ifdef HAVE_SNI From cbf9039424c50568c8d5afaa9e2244df0debf49a Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 19 Apr 2023 09:07:36 +0800 Subject: [PATCH 005/391] feat: stub implementation to parse 'evidence_request' during Client/Server Hello --- src/tls.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/tls.c b/src/tls.c index 8e2e6655084..3725189d09c 100644 --- a/src/tls.c +++ b/src/tls.c @@ -13667,6 +13667,21 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, ret = ECH_PARSE(ssl, input + offset, size, msgType); break; #endif +#ifdef WOLFSSL_REMOTE_ATTESTATION + case TLSX_EVIDENCE_REQUEST: + WOLFSSL_MSG("Evidence Request extension received"); +#ifdef WOLFSSL_DEBUG_TLS + WOLFSSL_BUFFER(input + offset, size); +#endif + if (msgType != client_hello && msgType != server_hello) { + WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED); + return EXT_NOT_ALLOWED; + } + + // TODO: functions for parsing/writing tlsx data + + break; +#endif /* WOLFSSL_REMOTE_ATTESTATION */ default: WOLFSSL_MSG("Unknown TLS extension type"); } @@ -13675,6 +13690,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, offset += size; } + #ifdef HAVE_EXTENDED_MASTER if (IsAtLeastTLSv1_3(ssl->version) && msgType == hello_retry_request) { /* Don't change EMS status until server_hello received. From 71bdb3fab5bcc8ed12aa4f1b3653e8dd1c92fd0c Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 19 Apr 2023 10:21:53 +0800 Subject: [PATCH 006/391] feat: define data structs for the 'evidence_request' extension --- wolfssl/internal.h | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index a8b879c625b..8cefddc9fb4 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2740,6 +2740,33 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, #endif /* HAVE_TLS_EXTENSIONS */ +#ifdef WOLFSSL_REMOTE_ATTESTATION + +/* Evidence Type */ +typedef struct EV_TYPE { + word8 length; /* Evidence Type Description Length */ + void *description; /* Evidence Type Description */ + struct EV_TYPE *next; /* List Behaviour */ +} EV_TYPE; + +/* Evidence Request from client */ +typedef struct EV_REQUEST_CLIENT { + word32 nonce; /* Nonce for Evidence Generation */ + word8 num_types; /* Number of Evidence Types */ + EV_TYPE *types; /* Evidence Type List */ +} EV_REQUEST_CLIENT; + +/* + * Evidence Request answer from server. + */ +typedef struct EV_REQUEST_SERVER { + EV_TYPE type; /* Evidence Type chosen from client-supported types */ + word16 length; /* Evidence Data Length */ + void *data; /* Evidence Data */ +} EV_REQUEST_SERVER; + +#endif /* WOLFSSL_REMOTE_ATTESTATION */ + /** Server Name Indication - RFC 6066 (session 3) */ #ifdef HAVE_SNI From 0790e0610d959a5cb68d3b2e8d3b77f9d3063ca1 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 19 Apr 2023 10:27:41 +0800 Subject: [PATCH 007/391] feat: implement writing of 'evidence_request' extension to buffer --- src/tls.c | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/src/tls.c b/src/tls.c index 3725189d09c..66a764145f1 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1860,6 +1860,84 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #endif /* HAVE_ALPN */ +/* ****************************************************************************/ +/* Remote Attestation */ +/* ****************************************************************************/ + +/* + * Writes the Evidence Type data into the output buffer. + * Assumes that the output buffer is big enough to hold data. + * + * type The evidence type. + * output The buffer to write into. Advanced by number of bytes written. + * pSz Incremented by the number of bytes written into the buffer. + */ +static void TLSX_EvidenceType_Write(EV_TYPE *type, byte *output, word16 *pSz) { + *output = type->length; + output += OPAQUE8_LEN; + *pSz += OPAQUE8_LEN; + + XMEMCPY(output, type->description, type->length); + output += type->length; + *pSz += type->length; +} + +/* + * Writes the Evidence Request extension data into the output buffer. + * Assumes that the output buffer is big enough to hold data. + * In messages: ClientHello and ServerHello. + * + * data The extension data to write + * output The buffer to write into. + * msgType The type of the message this extension is being written into. + * pSz Incremented by the number of bytes written into the buffer. + * returns Either success (0) or sanity error (SANITY_MSG_E) + */ +static int TLSX_EvidenceRequest_Write(void *data, byte *output, byte msgType, word16 *pSz) { + if (msgType == client_hello) { + EV_REQUEST_CLIENT *req = (EV_REQUEST_CLIENT *) data; + + c32toa(req->nonce, output); + output += OPAQUE32_LEN; + *pSz += OPAQUE32_LEN; + + *output = req->num_types; + output += OPAQUE8_LEN; + *pSz += OPAQUE8_LEN; + + EV_TYPE *type = type = req->types; + // at least one type must be present. + if (type == NULL) { + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + + // write the list of supported evidence types into the buffer + do { + TLSX_EvidenceType_Write(type, output, pSz); + } while ((type = type->next)); + } else if (msgType == server_hello) { + EV_REQUEST_SERVER *req = (EV_REQUEST_SERVER *) data; + + TLSX_EvidenceType_Write(&req->type, output, pSz); + + c16toa(req->length, output); + output += OPAQUE16_LEN; + *pSz += OPAQUE16_LEN; + + XMEMCPY(output, req->data, req->length); + output += req->length; + *pSz += req->length; + } else { + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + + return 0; +} + +#define EV_WRITE TLSX_EvidenceRequest_Write + /******************************************************************************/ /* Server Name Indication */ /******************************************************************************/ @@ -11603,6 +11681,12 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, output + offset, msgType); break; #endif +#ifdef WOLFSSL_REMOTE_ATTESTATION + case TLSX_EVIDENCE_REQUEST: + WOLFSSL_MSG("Evidence Request extension to write"); + ret = EV_WRITE(extension->data, output + offset, msgType, &offset); + break; +#endif #ifdef WOLFSSL_SRTP case TLSX_USE_SRTP: offset += SRTP_WRITE((TlsxSrtp*)extension->data, output+offset); From a493b68cf2916efed276959aa0e4b0d44e2cc91a Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Thu, 20 Apr 2023 12:35:59 +0800 Subject: [PATCH 008/391] feat: simplify 'evidence_request' structs --- src/tls.c | 16 ++++------------ wolfssl/internal.h | 1 - 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/src/tls.c b/src/tls.c index 66a764145f1..fa318bc175a 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1887,13 +1887,13 @@ static void TLSX_EvidenceType_Write(EV_TYPE *type, byte *output, word16 *pSz) { * Assumes that the output buffer is big enough to hold data. * In messages: ClientHello and ServerHello. * - * data The extension data to write + * data The extension data to write. * output The buffer to write into. * msgType The type of the message this extension is being written into. * pSz Incremented by the number of bytes written into the buffer. * returns Either success (0) or sanity error (SANITY_MSG_E) */ -static int TLSX_EvidenceRequest_Write(void *data, byte *output, byte msgType, word16 *pSz) { +static int TLSX_EvidenceRequest_Write(const void *data, byte *output, byte msgType, word16 *pSz) { if (msgType == client_hello) { EV_REQUEST_CLIENT *req = (EV_REQUEST_CLIENT *) data; @@ -1905,17 +1905,9 @@ static int TLSX_EvidenceRequest_Write(void *data, byte *output, byte msgType, wo output += OPAQUE8_LEN; *pSz += OPAQUE8_LEN; - EV_TYPE *type = type = req->types; - // at least one type must be present. - if (type == NULL) { - WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); - return SANITY_MSG_E; + for (int i = 0; i < req->num_types; i++) { + TLSX_EvidenceType_Write(&req->types[i], output, pSz); } - - // write the list of supported evidence types into the buffer - do { - TLSX_EvidenceType_Write(type, output, pSz); - } while ((type = type->next)); } else if (msgType == server_hello) { EV_REQUEST_SERVER *req = (EV_REQUEST_SERVER *) data; diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 8cefddc9fb4..d2d649aabf5 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2746,7 +2746,6 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, typedef struct EV_TYPE { word8 length; /* Evidence Type Description Length */ void *description; /* Evidence Type Description */ - struct EV_TYPE *next; /* List Behaviour */ } EV_TYPE; /* Evidence Request from client */ From 525f7d4098b1c63ab3131441cf0fdbd612f4e026 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Thu, 20 Apr 2023 22:14:39 +0800 Subject: [PATCH 009/391] fix: missing WOLFSSL_REMOTE_ATTESTATION guard --- src/tls.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/tls.c b/src/tls.c index fa318bc175a..0e025828019 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1860,9 +1860,11 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #endif /* HAVE_ALPN */ -/* ****************************************************************************/ +/******************************************************************************/ /* Remote Attestation */ -/* ****************************************************************************/ +/******************************************************************************/ + +#ifdef WOLFSSL_REMOTE_ATTESTATION /* * Writes the Evidence Type data into the output buffer. @@ -1930,6 +1932,8 @@ static int TLSX_EvidenceRequest_Write(const void *data, byte *output, byte msgTy #define EV_WRITE TLSX_EvidenceRequest_Write +#endif /* WOLFSSL_REMOTE_ATTESTATION */ + /******************************************************************************/ /* Server Name Indication */ /******************************************************************************/ From e687470615c185fb79c8e9f063b6b92753063ef8 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sun, 23 Apr 2023 15:21:18 +0800 Subject: [PATCH 010/391] feat: add API for custom evidence verifier/generator --- src/ssl.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ wolfssl/internal.h | 4 ++++ wolfssl/ssl.h | 35 ++++++++++++++++++++++++++++++++--- 3 files changed, 82 insertions(+), 3 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 5077a21f8fc..6d45c710046 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3455,6 +3455,52 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) } +#ifdef WOLFSSL_REMOTE_ATTESTATION + +int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev) { + int ret = TLSX_Push(&ssl->extensions, TLSX_EVIDENCE_REQUEST, ev, ssl->heap); + if (ret != 0) { + return ret; + } + + if (wolfSSL_is_server(ssl)) { + // guaranteed to not be NULL as we just pushed it. + TLSX *ext = TLSX_Find(ssl->extensions, TLSX_EVIDENCE_REQUEST); + ext->resp = 1; + } + + return ret; +} + +/*void *wolfSSL_GetEvidence(WOLFSSL *ssl) { + TLSX *ext = TLSX_Find(ssl->extensions, TLSX_EVIDENCE_REQUEST); + if (ext == NULL) { + return NULL; + } else { + return ext->data; + } +}*/ + +int wolfSSL_SetEvidenceVerifier(WOLFSSL *ssl, int (*evVerifier)(const void *ev)) { + if (wolfSSL_is_server(ssl)) { + return SIDE_ERROR; + } + + ssl->evidenceVerifier = evVerifier; + return 0; +} + +int wolfSSL_SetEvidenceGenerator(WOLFSSL *ssl, int (*evGen)(const void *req)) { + if (!wolfSSL_is_server(ssl)) { + return SIDE_ERROR; + } + + ssl->evidenceGenerator = evGen; + return 0; +} + +#endif /* WOLFSSL_REMOTE_ATTESTATION */ + #ifdef HAVE_SNI WOLFSSL_ABI diff --git a/wolfssl/internal.h b/wolfssl/internal.h index d2d649aabf5..779adc5d2cb 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -5525,6 +5525,10 @@ struct WOLFSSL { #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) WOLFSSL_EchConfig* echConfigs; #endif +#ifdef WOLFSSL_REMOTE_ATTESTATION + int (*evidenceVerifier)(const void *ev); + int (*evidenceGenerator)(const void *req); +#endif /* WOLFSSL_REMOTE_ATTESTATION */ }; /* diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 1f2a216583f..6fb361c98ae 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3690,10 +3690,39 @@ WOLFSSL_API int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev); /* * Returns stored data from the Evidence Request Extension. - * - 'client': data to send to 'server' - * - 'server': data received from 'client' + * + * RETURNS: + * 'client': data to send to 'server' + * 'server': data received from 'client' + */ +// TODO: What about the data the server sent to the client? +// WOLFSSL_API void *wolfSSL_GetEvidence(WOLFSSL *ssl); + +/* + * Sets the callback for evidence verification on 'client' side. + * + * ARGUMENTS: + * ssl The SSL session + * evVerifier The evidence verifier. Takes generated evidence from server as parameter. + * + * RETURNS: + * 'client': 0 + * 'server': SIDE_ERROR + */ +WOLFSSL_API int wolfSSL_SetEvidenceVerifier(WOLFSSL *ssl, int (*evVerifier)(const void *ev)); + +/* + * Sets the callback for evidence generation on 'server' side. + * + * ARGUMENTS: + * ssl The SSL session + * evGen The evidence generator. Takes an evidence request as parameter. + * + * RETURNS: + * 'client': SIDE_ERROR + * 'server': 0 */ -WOLFSSL_API void *wolfSSL_GetEvidence(WOLFSSL *ssl); +WOLFSSL_API int wolfSSL_SetEvidenceGenerator(WOLFSSL *ssl, int (*evGen)(const void *req)); #endif /* WOLFSSL_REMOTE_ATTESTATION */ From a93485e41958eeb9e593bb7d97df646d9beda396 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sun, 23 Apr 2023 15:29:38 +0800 Subject: [PATCH 011/391] feat: create evidence request from server side --- src/tls.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/tls.c b/src/tls.c index 0e025828019..c253c0afa22 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1930,6 +1930,26 @@ static int TLSX_EvidenceRequest_Write(const void *data, byte *output, byte msgTy return 0; } +/* + * Creates a new Evidence Request from Server object. + */ +static EV_REQUEST_SERVER *TLSX_EvidenceRequest_NewServer(const EV_TYPE *type, word16 length, const void *data, void *heap) { + EV_REQUEST_SERVER *req = (EV_REQUEST_SERVER *)XMALLOC(sizeof(EV_REQUEST_SERVER), heap, DYNAMIC_TYPE_TLSX); + + (void)heap; + + if (req) { + req->type.length = type->length; + req->type.description = (void *) XMALLOC(req->type.length, heap, DYNAMIC_TYPE_TLSX); + XMEMCPY(req->type.description, type->description, type->length); + + req->length = length; + XMEMCPY(req->data, data, length); + } + + return req; +} + #define EV_WRITE TLSX_EvidenceRequest_Write #endif /* WOLFSSL_REMOTE_ATTESTATION */ From 6c10c603fda7f158803b807fbd24105cf15c13ef Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sun, 30 Apr 2023 12:04:39 +0800 Subject: [PATCH 012/391] feat: add CMake option for Keying Material Exporter This is enabled by default for now for testing in regards to Remote Attestation --- CMakeLists.txt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3aeb485ab27..1e81bf217fc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -353,6 +353,16 @@ if(NOT WOLFSSL_RNG) list(APPEND WOLFSSL_DEFINITIONS "-DWC_NO_RNG") endif() +# Keying Material Exporter. Used by Remote Attestation +# TODO: Make disabled by default. This is for testing only for now. +add_option("WOLFSSL_KEYING_MATERIAL" + "Enable wolfSSL keying material export (default: enabled)" + "yes" "yes;no") + +if(WOLFSSL_KEYING_MATERIAL) + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_KEYING_MATERIAL") +endif() + # Remote Attestation # TODO: Make disabled by default. This is for testing only for now. add_option("WOLFSSL_REMOTE_ATTESTATION" @@ -360,6 +370,12 @@ add_option("WOLFSSL_REMOTE_ATTESTATION" "yes" "yes;no") if(WOLFSSL_REMOTE_ATTESTATION) + if(NOT WOLFSSL_TLS13) + message(FATAL_ERROR "Remote Attestation supported only for TLSv1.3") + endif() + if(NOT WOLFSSL_KEYING_MATERIAL) + message(FATAL_ERROR "Remote Attestation supported only with Keying Material Exporter") + endif() list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_REMOTE_ATTESTATION") endif() From 4c7303c880f8f022de2a5685e9b50e53d509215c Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Mon, 1 May 2023 15:15:01 +0800 Subject: [PATCH 013/391] fix: annotate documentation --- src/tls.c | 23 ++++++++++++----------- wolfssl/ssl.h | 24 +++++++++--------------- 2 files changed, 21 insertions(+), 26 deletions(-) diff --git a/src/tls.c b/src/tls.c index c253c0afa22..eee008c4ea0 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1866,13 +1866,13 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #ifdef WOLFSSL_REMOTE_ATTESTATION -/* +/** * Writes the Evidence Type data into the output buffer. * Assumes that the output buffer is big enough to hold data. * - * type The evidence type. - * output The buffer to write into. Advanced by number of bytes written. - * pSz Incremented by the number of bytes written into the buffer. + * @param type The evidence type. + * @param output The buffer to write into. Advanced by number of bytes written. + * @param pSz Incremented by the number of bytes written into the buffer. */ static void TLSX_EvidenceType_Write(EV_TYPE *type, byte *output, word16 *pSz) { *output = type->length; @@ -1884,16 +1884,16 @@ static void TLSX_EvidenceType_Write(EV_TYPE *type, byte *output, word16 *pSz) { *pSz += type->length; } -/* +/** * Writes the Evidence Request extension data into the output buffer. * Assumes that the output buffer is big enough to hold data. * In messages: ClientHello and ServerHello. * - * data The extension data to write. - * output The buffer to write into. - * msgType The type of the message this extension is being written into. - * pSz Incremented by the number of bytes written into the buffer. - * returns Either success (0) or sanity error (SANITY_MSG_E) + * @param data The extension data to write. + * @param output The buffer to write into. + * @param msgType The type of the message this extension is being written into. + * @param pSz Incremented by the number of bytes written into the buffer. + * @return Either success (0) or sanity error (SANITY_MSG_E) */ static int TLSX_EvidenceRequest_Write(const void *data, byte *output, byte msgType, word16 *pSz) { if (msgType == client_hello) { @@ -1930,7 +1930,7 @@ static int TLSX_EvidenceRequest_Write(const void *data, byte *output, byte msgTy return 0; } -/* +/** * Creates a new Evidence Request from Server object. */ static EV_REQUEST_SERVER *TLSX_EvidenceRequest_NewServer(const EV_TYPE *type, word16 length, const void *data, void *heap) { @@ -13767,6 +13767,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, ret = ECH_PARSE(ssl, input + offset, size, msgType); break; #endif + #ifdef WOLFSSL_REMOTE_ATTESTATION case TLSX_EVIDENCE_REQUEST: WOLFSSL_MSG("Evidence Request extension received"); diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 6fb361c98ae..8d306760d52 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3698,31 +3698,25 @@ WOLFSSL_API int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev); // TODO: What about the data the server sent to the client? // WOLFSSL_API void *wolfSSL_GetEvidence(WOLFSSL *ssl); -/* +/** * Sets the callback for evidence verification on 'client' side. * - * ARGUMENTS: - * ssl The SSL session - * evVerifier The evidence verifier. Takes generated evidence from server as parameter. + * @param ssl The SSL session + * @param evVerifier The evidence verifier. Takes generated evidence from server as parameter. * - * RETURNS: - * 'client': 0 - * 'server': SIDE_ERROR + * @return 0 if client and SIDE_ERROR if server */ WOLFSSL_API int wolfSSL_SetEvidenceVerifier(WOLFSSL *ssl, int (*evVerifier)(const void *ev)); -/* +/** * Sets the callback for evidence generation on 'server' side. * - * ARGUMENTS: - * ssl The SSL session - * evGen The evidence generator. Takes an evidence request as parameter. + * @param ssl The SSL session + * @param evGen The evidence generator. Takes an evidence request as parameter. * - * RETURNS: - * 'client': SIDE_ERROR - * 'server': 0 + * @return 0 if server and SIDE_ERROR if client */ -WOLFSSL_API int wolfSSL_SetEvidenceGenerator(WOLFSSL *ssl, int (*evGen)(const void *req)); +WOLFSSL_API int wolfSSL_SetEvidenceGenerator(WOLFSSL *ssl, void *(*evGen)(const void *req)); #endif /* WOLFSSL_REMOTE_ATTESTATION */ From 4df0e013b3dd6707d36435f612b2e3afcac94848 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 3 May 2023 14:47:46 +0800 Subject: [PATCH 014/391] feat: change attestation verification/generation callbacks --- src/ssl.c | 15 +++++++++++---- wolfssl/internal.h | 20 ++++++++++++++++++-- wolfssl/ssl.h | 25 +++++++++++++++---------- 3 files changed, 44 insertions(+), 16 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 6d45c710046..268e6d5d0f3 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -20,6 +20,7 @@ */ +#include "wolfssl/wolfcrypt/error-crypt.h" #ifdef HAVE_CONFIG_H #include #endif @@ -3481,21 +3482,27 @@ int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev) { } }*/ -int wolfSSL_SetEvidenceVerifier(WOLFSSL *ssl, int (*evVerifier)(const void *ev)) { +int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const void *att, const byte *c, word16 cLen)) { + if (ssl == NULL || verifyAtt == NULL) { + return BAD_FUNC_ARG; + } if (wolfSSL_is_server(ssl)) { return SIDE_ERROR; } - ssl->evidenceVerifier = evVerifier; + ssl->verifyAttestation = verifyAtt; return 0; } -int wolfSSL_SetEvidenceGenerator(WOLFSSL *ssl, int (*evGen)(const void *req)) { +int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const void *req, const byte *c, word16 cLen, byte *output)) { + if (ssl == NULL || genAtt == NULL) { + return BAD_FUNC_ARG; + } if (!wolfSSL_is_server(ssl)) { return SIDE_ERROR; } - ssl->evidenceGenerator = evGen; + ssl->generateAttestation = genAtt; return 0; } diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 779adc5d2cb..6852697c1ef 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -5526,8 +5526,24 @@ struct WOLFSSL { WOLFSSL_EchConfig* echConfigs; #endif #ifdef WOLFSSL_REMOTE_ATTESTATION - int (*evidenceVerifier)(const void *ev); - int (*evidenceGenerator)(const void *req); + /** For attestation verification. + * + * @param att the attestation data + * @param c the challenge + * @param cLen the challenge length + * @return 0 on success + */ + int (*verifyAttestation)(const void *att, const byte *c, word16 cLen); + /** + * For attestation generation. + * + * @param req the attestation request + * @param c the challenge + * @param cLen the challenge length + * @param output the output buffer for the generated attestation + * @return 0 on success + */ + int (*generateAttestation)(const void *req, const byte *c, word16 cLen, byte *output); #endif /* WOLFSSL_REMOTE_ATTESTATION */ }; diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 8d306760d52..b5152383e06 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3699,24 +3699,29 @@ WOLFSSL_API int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev); // WOLFSSL_API void *wolfSSL_GetEvidence(WOLFSSL *ssl); /** - * Sets the callback for evidence verification on 'client' side. + * Sets the callback for attestation verification on 'client' side. * - * @param ssl The SSL session - * @param evVerifier The evidence verifier. Takes generated evidence from server as parameter. + * @param ssl The SSL session + * @param verifyAtt The attestation verify callback. + * Takes attestation data, a challenge and a challenge length as arguments. + * Must return 0 on success. * - * @return 0 if client and SIDE_ERROR if server + * @return 0 if client, SIDE_ERROR if server, and BAD_FUNC_ARG if any param is NULL. */ -WOLFSSL_API int wolfSSL_SetEvidenceVerifier(WOLFSSL *ssl, int (*evVerifier)(const void *ev)); +WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const void *att, const byte *c, word16 cLen)); /** - * Sets the callback for evidence generation on 'server' side. + * Sets the callback for attestation generation on 'server' side. * - * @param ssl The SSL session - * @param evGen The evidence generator. Takes an evidence request as parameter. + * @param ssl The SSL session + * @param genAtt The attestation generator. + * Takes an attestation request, a challenge, a challenge length and a buffer for generated + * attestation data as arguments. + * Must return 0 on success. * - * @return 0 if server and SIDE_ERROR if client + * @return 0 if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. */ -WOLFSSL_API int wolfSSL_SetEvidenceGenerator(WOLFSSL *ssl, void *(*evGen)(const void *req)); +WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const void *req, const byte *c, word16 cLen, byte *output)); #endif /* WOLFSSL_REMOTE_ATTESTATION */ From 243248ad12e89084a71171c5c8cabc6d3c1194e0 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 3 May 2023 14:59:52 +0800 Subject: [PATCH 015/391] fix: rename evidence to attestation for cohesion --- src/ssl.c | 8 ++++---- src/tls.c | 32 ++++++++++++++++---------------- wolfssl/internal.h | 18 +++++++++--------- wolfssl/ssl.h | 12 ++++++------ 4 files changed, 35 insertions(+), 35 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 268e6d5d0f3..ce93f0c4755 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3458,15 +3458,15 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) #ifdef WOLFSSL_REMOTE_ATTESTATION -int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev) { - int ret = TLSX_Push(&ssl->extensions, TLSX_EVIDENCE_REQUEST, ev, ssl->heap); +int wolfSSL_AttestationRequest(WOLFSSL *ssl, const void *ev) { + int ret = TLSX_Push(&ssl->extensions, TLSX_ATTESTATION_REQUEST, ev, ssl->heap); if (ret != 0) { return ret; } if (wolfSSL_is_server(ssl)) { // guaranteed to not be NULL as we just pushed it. - TLSX *ext = TLSX_Find(ssl->extensions, TLSX_EVIDENCE_REQUEST); + TLSX *ext = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); ext->resp = 1; } @@ -3474,7 +3474,7 @@ int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev) { } /*void *wolfSSL_GetEvidence(WOLFSSL *ssl) { - TLSX *ext = TLSX_Find(ssl->extensions, TLSX_EVIDENCE_REQUEST); + TLSX *ext = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); if (ext == NULL) { return NULL; } else { diff --git a/src/tls.c b/src/tls.c index eee008c4ea0..6b30c9f3a83 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1867,14 +1867,14 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #ifdef WOLFSSL_REMOTE_ATTESTATION /** - * Writes the Evidence Type data into the output buffer. + * Writes the Attestation Type data into the output buffer. * Assumes that the output buffer is big enough to hold data. * - * @param type The evidence type. + * @param type The attestation type. * @param output The buffer to write into. Advanced by number of bytes written. * @param pSz Incremented by the number of bytes written into the buffer. */ -static void TLSX_EvidenceType_Write(EV_TYPE *type, byte *output, word16 *pSz) { +static void TLSX_AttestationType_Write(ATT_TYPE *type, byte *output, word16 *pSz) { *output = type->length; output += OPAQUE8_LEN; *pSz += OPAQUE8_LEN; @@ -1885,7 +1885,7 @@ static void TLSX_EvidenceType_Write(EV_TYPE *type, byte *output, word16 *pSz) { } /** - * Writes the Evidence Request extension data into the output buffer. + * Writes the Attestation Request extension data into the output buffer. * Assumes that the output buffer is big enough to hold data. * In messages: ClientHello and ServerHello. * @@ -1895,9 +1895,9 @@ static void TLSX_EvidenceType_Write(EV_TYPE *type, byte *output, word16 *pSz) { * @param pSz Incremented by the number of bytes written into the buffer. * @return Either success (0) or sanity error (SANITY_MSG_E) */ -static int TLSX_EvidenceRequest_Write(const void *data, byte *output, byte msgType, word16 *pSz) { +static int TLSX_AttestationRequest_Write(const void *data, byte *output, byte msgType, word16 *pSz) { if (msgType == client_hello) { - EV_REQUEST_CLIENT *req = (EV_REQUEST_CLIENT *) data; + ATT_REQUEST_CLIENT *req = (ATT_REQUEST_CLIENT *) data; c32toa(req->nonce, output); output += OPAQUE32_LEN; @@ -1908,12 +1908,12 @@ static int TLSX_EvidenceRequest_Write(const void *data, byte *output, byte msgTy *pSz += OPAQUE8_LEN; for (int i = 0; i < req->num_types; i++) { - TLSX_EvidenceType_Write(&req->types[i], output, pSz); + TLSX_AttestationType_Write(&req->types[i], output, pSz); } } else if (msgType == server_hello) { - EV_REQUEST_SERVER *req = (EV_REQUEST_SERVER *) data; + ATT_REQUEST_SERVER *req = (ATT_REQUEST_SERVER *) data; - TLSX_EvidenceType_Write(&req->type, output, pSz); + TLSX_AttestationType_Write(&req->type, output, pSz); c16toa(req->length, output); output += OPAQUE16_LEN; @@ -1931,10 +1931,10 @@ static int TLSX_EvidenceRequest_Write(const void *data, byte *output, byte msgTy } /** - * Creates a new Evidence Request from Server object. + * Creates a new Attestation Request from Server object. */ -static EV_REQUEST_SERVER *TLSX_EvidenceRequest_NewServer(const EV_TYPE *type, word16 length, const void *data, void *heap) { - EV_REQUEST_SERVER *req = (EV_REQUEST_SERVER *)XMALLOC(sizeof(EV_REQUEST_SERVER), heap, DYNAMIC_TYPE_TLSX); +static ATT_REQUEST_SERVER *TLSX_AttestationRequest_NewServer(const ATT_TYPE *type, word16 length, const void *data, void *heap) { + ATT_REQUEST_SERVER *req = (ATT_REQUEST_SERVER *)XMALLOC(sizeof(ATT_REQUEST_SERVER), heap, DYNAMIC_TYPE_TLSX); (void)heap; @@ -1950,7 +1950,7 @@ static EV_REQUEST_SERVER *TLSX_EvidenceRequest_NewServer(const EV_TYPE *type, wo return req; } -#define EV_WRITE TLSX_EvidenceRequest_Write +#define ATT_WRITE TLSX_AttestationRequest_Write #endif /* WOLFSSL_REMOTE_ATTESTATION */ @@ -11698,9 +11698,9 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, break; #endif #ifdef WOLFSSL_REMOTE_ATTESTATION - case TLSX_EVIDENCE_REQUEST: + case TLSX_ATTESTATION_REQUEST: WOLFSSL_MSG("Evidence Request extension to write"); - ret = EV_WRITE(extension->data, output + offset, msgType, &offset); + ret = ATT_WRITE(extension->data, output + offset, msgType, &offset); break; #endif #ifdef WOLFSSL_SRTP @@ -13769,7 +13769,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, #endif #ifdef WOLFSSL_REMOTE_ATTESTATION - case TLSX_EVIDENCE_REQUEST: + case TLSX_ATTESTATION_REQUEST: WOLFSSL_MSG("Evidence Request extension received"); #ifdef WOLFSSL_DEBUG_TLS WOLFSSL_BUFFER(input + offset, size); diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 6852697c1ef..0d2f3af3835 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2609,7 +2609,7 @@ typedef enum { #endif #endif #ifdef WOLFSSL_REMOTE_ATTESTATION - TLSX_EVIDENCE_REQUEST = 0xAA00, /* remote attestation, arbitrary number for now */ + TLSX_ATTESTATION_REQUEST = 0xAA00, /* remote attestation, arbitrary number for now */ #endif TLSX_RENEGOTIATION_INFO = 0xff01, #ifdef WOLFSSL_QUIC @@ -2743,26 +2743,26 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, #ifdef WOLFSSL_REMOTE_ATTESTATION /* Evidence Type */ -typedef struct EV_TYPE { +typedef struct ATT_TYPE { word8 length; /* Evidence Type Description Length */ void *description; /* Evidence Type Description */ -} EV_TYPE; +} ATT_TYPE; /* Evidence Request from client */ -typedef struct EV_REQUEST_CLIENT { +typedef struct ATT_REQUEST_CLIENT { word32 nonce; /* Nonce for Evidence Generation */ word8 num_types; /* Number of Evidence Types */ - EV_TYPE *types; /* Evidence Type List */ -} EV_REQUEST_CLIENT; + ATT_TYPE *types; /* Evidence Type List */ +} ATT_REQUEST_CLIENT; /* * Evidence Request answer from server. */ -typedef struct EV_REQUEST_SERVER { - EV_TYPE type; /* Evidence Type chosen from client-supported types */ +typedef struct ATT_REQUEST_SERVER { + ATT_TYPE type; /* Evidence Type chosen from client-supported types */ word16 length; /* Evidence Data Length */ void *data; /* Evidence Data */ -} EV_REQUEST_SERVER; +} ATT_REQUEST_SERVER; #endif /* WOLFSSL_REMOTE_ATTESTATION */ diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index b5152383e06..3b37aa78c47 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3670,11 +3670,11 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); // TODO: WIP definitions /* - * Evidence Request extension. + * Attestation Request extension. * * For 'client', the data should be: - * 4 bytes Nonce for Evidence Generation - * 1 byte Number of Evidences supported (e.g. 2) + * 4 bytes Nonce for Attestation Generation + * 1 byte Number of Attestations supported (e.g. 2) * 1 byte Type Description Length [1st evidence] * ? bytes Type Description * 1 byte Type Description Length [2nd evidence] @@ -3683,10 +3683,10 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); * For 'server', the data should be * 1 byte Type Description Length [e.g. 1st evidence] * ? bytes Type Description - * 2 bytes Evidence Data Length - * ? bytes Evidence Data + * 2 bytes Attestation Data Length + * ? bytes Attestation Data */ -WOLFSSL_API int wolfSSL_EvidenceRequest(WOLFSSL *ssl, const void *ev); +WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, const void *ev); /* * Returns stored data from the Evidence Request Extension. From 1522131ee3932d440c8ff6a72cb7319419b9f603 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 3 May 2023 15:02:16 +0800 Subject: [PATCH 016/391] feat: stub implementation for parsing AttestationRequest extension --- src/tls.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/tls.c b/src/tls.c index 6b30c9f3a83..cb809763452 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1950,7 +1950,30 @@ static ATT_REQUEST_SERVER *TLSX_AttestationRequest_NewServer(const ATT_TYPE *typ return req; } +/** + * Parses the Attestation Request extension. + * + * @param ssl The SSL/TLS object. + * @param input The extension data. + * @param length The length of the extension data. + * @param msgType The type of the message this extension is being parsed from. + * @return 0 on success, other values indicate failure. + */ +static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 length, byte msgType) { + if (msgType == client_hello) { + // TODO: parse request and generate attestation here? + } else if (msgType == server_hello) { + // TODO: parse and verify attestation + } else { + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + + return 0; +} + #define ATT_WRITE TLSX_AttestationRequest_Write +#define ATT_PARSE TLSX_AttestationRequest_Parse #endif /* WOLFSSL_REMOTE_ATTESTATION */ @@ -13779,8 +13802,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, return EXT_NOT_ALLOWED; } - // TODO: functions for parsing/writing tlsx data - + ret = ATT_PARSE(ssl, input + offset, size, msgType); break; #endif /* WOLFSSL_REMOTE_ATTESTATION */ default: From 274dede95cfb29a08e093b8065aeb61bde63a864 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Thu, 4 May 2023 16:47:34 +0800 Subject: [PATCH 017/391] simplify attestation request for testing --- src/ssl.c | 10 +++-- src/tls.c | 93 ++++++++++++++-------------------------------- wolfssl/internal.h | 31 ++-------------- wolfssl/ssl.h | 32 +++++++--------- 4 files changed, 51 insertions(+), 115 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index ce93f0c4755..0a80644093b 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3458,8 +3458,10 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) #ifdef WOLFSSL_REMOTE_ATTESTATION -int wolfSSL_AttestationRequest(WOLFSSL *ssl, const void *ev) { - int ret = TLSX_Push(&ssl->extensions, TLSX_ATTESTATION_REQUEST, ev, ssl->heap); +int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { + return 0; + + int ret = TLSX_Push(&ssl->extensions, TLSX_ATTESTATION_REQUEST, req, ssl->heap); if (ret != 0) { return ret; } @@ -3482,7 +3484,7 @@ int wolfSSL_AttestationRequest(WOLFSSL *ssl, const void *ev) { } }*/ -int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const void *att, const byte *c, word16 cLen)) { +int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c, word16 cLen)) { if (ssl == NULL || verifyAtt == NULL) { return BAD_FUNC_ARG; } @@ -3494,7 +3496,7 @@ int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const void *att, return 0; } -int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const void *req, const byte *c, word16 cLen, byte *output)) { +int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output)) { if (ssl == NULL || genAtt == NULL) { return BAD_FUNC_ARG; } diff --git a/src/tls.c b/src/tls.c index cb809763452..84b78e6c737 100644 --- a/src/tls.c +++ b/src/tls.c @@ -21,6 +21,7 @@ +#include "wolfssl/wolfcrypt/error-crypt.h" #ifdef HAVE_CONFIG_H #include #endif @@ -1866,24 +1867,6 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #ifdef WOLFSSL_REMOTE_ATTESTATION -/** - * Writes the Attestation Type data into the output buffer. - * Assumes that the output buffer is big enough to hold data. - * - * @param type The attestation type. - * @param output The buffer to write into. Advanced by number of bytes written. - * @param pSz Incremented by the number of bytes written into the buffer. - */ -static void TLSX_AttestationType_Write(ATT_TYPE *type, byte *output, word16 *pSz) { - *output = type->length; - output += OPAQUE8_LEN; - *pSz += OPAQUE8_LEN; - - XMEMCPY(output, type->description, type->length); - output += type->length; - *pSz += type->length; -} - /** * Writes the Attestation Request extension data into the output buffer. * Assumes that the output buffer is big enough to hold data. @@ -1895,33 +1878,16 @@ static void TLSX_AttestationType_Write(ATT_TYPE *type, byte *output, word16 *pSz * @param pSz Incremented by the number of bytes written into the buffer. * @return Either success (0) or sanity error (SANITY_MSG_E) */ -static int TLSX_AttestationRequest_Write(const void *data, byte *output, byte msgType, word16 *pSz) { - if (msgType == client_hello) { - ATT_REQUEST_CLIENT *req = (ATT_REQUEST_CLIENT *) data; +static int TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output, byte msgType) { + WOLFSSL_ENTER("TLSX_AttestationRequest_Write"); - c32toa(req->nonce, output); - output += OPAQUE32_LEN; - *pSz += OPAQUE32_LEN; - - *output = req->num_types; - output += OPAQUE8_LEN; - *pSz += OPAQUE8_LEN; - - for (int i = 0; i < req->num_types; i++) { - TLSX_AttestationType_Write(&req->types[i], output, pSz); - } - } else if (msgType == server_hello) { - ATT_REQUEST_SERVER *req = (ATT_REQUEST_SERVER *) data; - - TLSX_AttestationType_Write(&req->type, output, pSz); + if (msgType == client_hello || msgType == server_hello) { c16toa(req->length, output); output += OPAQUE16_LEN; - *pSz += OPAQUE16_LEN; - XMEMCPY(output, req->data, req->length); + XMEMCPY(output, req->request, req->length); output += req->length; - *pSz += req->length; } else { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); return SANITY_MSG_E; @@ -1930,26 +1896,6 @@ static int TLSX_AttestationRequest_Write(const void *data, byte *output, byte ms return 0; } -/** - * Creates a new Attestation Request from Server object. - */ -static ATT_REQUEST_SERVER *TLSX_AttestationRequest_NewServer(const ATT_TYPE *type, word16 length, const void *data, void *heap) { - ATT_REQUEST_SERVER *req = (ATT_REQUEST_SERVER *)XMALLOC(sizeof(ATT_REQUEST_SERVER), heap, DYNAMIC_TYPE_TLSX); - - (void)heap; - - if (req) { - req->type.length = type->length; - req->type.description = (void *) XMALLOC(req->type.length, heap, DYNAMIC_TYPE_TLSX); - XMEMCPY(req->type.description, type->description, type->length); - - req->length = length; - XMEMCPY(req->data, data, length); - } - - return req; -} - /** * Parses the Attestation Request extension. * @@ -1960,10 +1906,27 @@ static ATT_REQUEST_SERVER *TLSX_AttestationRequest_NewServer(const ATT_TYPE *typ * @return 0 on success, other values indicate failure. */ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 length, byte msgType) { - if (msgType == client_hello) { - // TODO: parse request and generate attestation here? - } else if (msgType == server_hello) { - // TODO: parse and verify attestation + WOLFSSL_ENTER("TLSX_AttestationRequest_Parse"); + + if (ssl == NULL || input == NULL) { + return BAD_FUNC_ARG; + } + + (void)length; + + if (msgType == client_hello || msgType == server_hello) { + ATT_REQUEST* req = (ATT_REQUEST*)XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); + + if (length < OPAQUE16_LEN + req->length) { + return BUFFER_ERROR; + } + + ato16(input, &req->length); + input += OPAQUE16_LEN; + + req->request = (void *) XMALLOC(req->length, ssl->heap, DYNAMIC_TYPE_TLSX); + XMEMCPY(req->request, input, req->length); + input += req->length; } else { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); return SANITY_MSG_E; @@ -11723,7 +11686,7 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, #ifdef WOLFSSL_REMOTE_ATTESTATION case TLSX_ATTESTATION_REQUEST: WOLFSSL_MSG("Evidence Request extension to write"); - ret = ATT_WRITE(extension->data, output + offset, msgType, &offset); + ret = ATT_WRITE(extension->data, output + offset, msgType); break; #endif #ifdef WOLFSSL_SRTP @@ -13793,7 +13756,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, #ifdef WOLFSSL_REMOTE_ATTESTATION case TLSX_ATTESTATION_REQUEST: - WOLFSSL_MSG("Evidence Request extension received"); + WOLFSSL_MSG("Attestation Request extension received"); #ifdef WOLFSSL_DEBUG_TLS WOLFSSL_BUFFER(input + offset, size); #endif diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 0d2f3af3835..2656588ac9a 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2740,32 +2740,6 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, #endif /* HAVE_TLS_EXTENSIONS */ -#ifdef WOLFSSL_REMOTE_ATTESTATION - -/* Evidence Type */ -typedef struct ATT_TYPE { - word8 length; /* Evidence Type Description Length */ - void *description; /* Evidence Type Description */ -} ATT_TYPE; - -/* Evidence Request from client */ -typedef struct ATT_REQUEST_CLIENT { - word32 nonce; /* Nonce for Evidence Generation */ - word8 num_types; /* Number of Evidence Types */ - ATT_TYPE *types; /* Evidence Type List */ -} ATT_REQUEST_CLIENT; - -/* - * Evidence Request answer from server. - */ -typedef struct ATT_REQUEST_SERVER { - ATT_TYPE type; /* Evidence Type chosen from client-supported types */ - word16 length; /* Evidence Data Length */ - void *data; /* Evidence Data */ -} ATT_REQUEST_SERVER; - -#endif /* WOLFSSL_REMOTE_ATTESTATION */ - /** Server Name Indication - RFC 6066 (session 3) */ #ifdef HAVE_SNI @@ -5533,7 +5507,8 @@ struct WOLFSSL { * @param cLen the challenge length * @return 0 on success */ - int (*verifyAttestation)(const void *att, const byte *c, word16 cLen); + int (*verifyAttestation)(const ATT_REQUEST *att, const byte *c, word16 cLen); + ATT_REQUEST *attestationRequest; /** * For attestation generation. * @@ -5543,7 +5518,7 @@ struct WOLFSSL { * @param output the output buffer for the generated attestation * @return 0 on success */ - int (*generateAttestation)(const void *req, const byte *c, word16 cLen, byte *output); + int (*generateAttestation)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output); #endif /* WOLFSSL_REMOTE_ATTESTATION */ }; diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 3b37aa78c47..a2a1d0068fe 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3669,24 +3669,20 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); #ifdef WOLFSSL_REMOTE_ATTESTATION // TODO: WIP definitions -/* +/** + * Attestation Request + */ +typedef struct ATT_REQUEST { + /** The length of the request data */ + word16 length; + /** The attestation request data */ + void *request; +} ATT_REQUEST; + +/** * Attestation Request extension. - * - * For 'client', the data should be: - * 4 bytes Nonce for Attestation Generation - * 1 byte Number of Attestations supported (e.g. 2) - * 1 byte Type Description Length [1st evidence] - * ? bytes Type Description - * 1 byte Type Description Length [2nd evidence] - * ? bytes Type Description - * - * For 'server', the data should be - * 1 byte Type Description Length [e.g. 1st evidence] - * ? bytes Type Description - * 2 bytes Attestation Data Length - * ? bytes Attestation Data */ -WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, const void *ev); +WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req); /* * Returns stored data from the Evidence Request Extension. @@ -3708,7 +3704,7 @@ WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, const void *ev); * * @return 0 if client, SIDE_ERROR if server, and BAD_FUNC_ARG if any param is NULL. */ -WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const void *att, const byte *c, word16 cLen)); +WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c, word16 cLen)); /** * Sets the callback for attestation generation on 'server' side. @@ -3721,7 +3717,7 @@ WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(cons * * @return 0 if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. */ -WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const void *req, const byte *c, word16 cLen, byte *output)); +WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output)); #endif /* WOLFSSL_REMOTE_ATTESTATION */ From 74e19bc182907c9b901d9759aea7239e5646f1fa Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Thu, 4 May 2023 16:55:41 +0800 Subject: [PATCH 018/391] fix: remove early return and add debug statements --- src/ssl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ssl.c b/src/ssl.c index 0a80644093b..885721a05f4 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -21,6 +21,7 @@ #include "wolfssl/wolfcrypt/error-crypt.h" +#include #ifdef HAVE_CONFIG_H #include #endif @@ -3459,7 +3460,7 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) #ifdef WOLFSSL_REMOTE_ATTESTATION int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { - return 0; + WOLFSSL_ENTER("wolfSSL_AttestationRequest"); int ret = TLSX_Push(&ssl->extensions, TLSX_ATTESTATION_REQUEST, req, ssl->heap); if (ret != 0) { @@ -3472,6 +3473,7 @@ int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { ext->resp = 1; } + WOLFSSL_LEAVE("wolfSSL_AttestationRequest", ret); return ret; } From c4ccbf4bb570572570518a53996586c9b8fe1ccb Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 5 May 2023 13:13:49 +0800 Subject: [PATCH 019/391] feat: add AttestationRequest to ctx object --- src/ssl.c | 19 +++++++++++++++++++ wolfssl/ssl.h | 5 +++++ 2 files changed, 24 insertions(+) diff --git a/src/ssl.c b/src/ssl.c index 885721a05f4..f6980486866 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -20,6 +20,7 @@ */ +#include "wolfssl/ssl.h" #include "wolfssl/wolfcrypt/error-crypt.h" #include #ifdef HAVE_CONFIG_H @@ -3477,6 +3478,24 @@ int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { return ret; } +int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, ATT_REQUEST *req) { + WOLFSSL_ENTER("wolfSSL_CTX_AttestationRequest"); + + int ret = TLSX_Push(&ctx->extensions, TLSX_ATTESTATION_REQUEST, req, ctx->heap); + if (ret != 0) { + return ret; + } + + if (ctx->method->side == WOLFSSL_SERVER_END) { + // guaranteed to not be NULL as we just pushed it. + TLSX *ext = TLSX_Find(ctx->extensions, TLSX_ATTESTATION_REQUEST); + ext->resp = 1; + } + + WOLFSSL_LEAVE("wolfSSL_CTX_AttestationRequest", ret); + return ret; +} + /*void *wolfSSL_GetEvidence(WOLFSSL *ssl) { TLSX *ext = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); if (ext == NULL) { diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index a2a1d0068fe..502edad04ab 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3684,6 +3684,11 @@ typedef struct ATT_REQUEST { */ WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req); +/** + * Attestation Request extension. + */ +WOLFSSL_API int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, ATT_REQUEST *req); + /* * Returns stored data from the Evidence Request Extension. * From 9eef621225fad7da74697934706c4e05b574402d Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 5 May 2023 13:27:35 +0800 Subject: [PATCH 020/391] fix: return written number of bytes for ATT_PARSE --- src/tls.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/tls.c b/src/tls.c index 84b78e6c737..d4e7dd39049 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1881,19 +1881,21 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) static int TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output, byte msgType) { WOLFSSL_ENTER("TLSX_AttestationRequest_Write"); + int i = 0; + if (msgType == client_hello || msgType == server_hello) { c16toa(req->length, output); - output += OPAQUE16_LEN; + i += OPAQUE16_LEN; - XMEMCPY(output, req->request, req->length); - output += req->length; + XMEMCPY(&output[i], req->request, req->length); + i += req->length; } else { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); return SANITY_MSG_E; } - return 0; + return i; } /** @@ -11685,8 +11687,8 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, #endif #ifdef WOLFSSL_REMOTE_ATTESTATION case TLSX_ATTESTATION_REQUEST: - WOLFSSL_MSG("Evidence Request extension to write"); - ret = ATT_WRITE(extension->data, output + offset, msgType); + WOLFSSL_MSG("Attestation Request extension to write"); + offset += ATT_WRITE((const ATT_REQUEST *) extension->data, output + offset, msgType); break; #endif #ifdef WOLFSSL_SRTP From cbe87818ac46aba206124c16282f6164a49548f8 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 5 May 2023 13:40:24 +0800 Subject: [PATCH 021/391] feat: implement GET_SIZE for Attestation Request --- src/tls.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/tls.c b/src/tls.c index d4e7dd39049..c413a4e0dc5 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1937,8 +1937,18 @@ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 return 0; } +static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { + word16 len = 0; + + len += OPAQUE16_LEN; // length field itself + len += req->length; + + return len; +} + #define ATT_WRITE TLSX_AttestationRequest_Write #define ATT_PARSE TLSX_AttestationRequest_Parse +#define ATT_GET_SIZE TLSX_AttestationRequest_GetSize #endif /* WOLFSSL_REMOTE_ATTESTATION */ @@ -11479,6 +11489,11 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType); break; #endif +#ifdef WOLFSSL_REMOTE_ATTESTATION + case TLSX_ATTESTATION_REQUEST: + length += ATT_GET_SIZE((const ATT_REQUEST *) extension->data); + break; +#endif /* WOLFSSL_REMOTE_ATTESTATION */ #ifdef WOLFSSL_SRTP case TLSX_USE_SRTP: length += SRTP_GET_SIZE((TlsxSrtp*)extension->data); From 010a56b5bbf9b22ebd32b5aceb12202e61da2582 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 5 May 2023 13:50:05 +0800 Subject: [PATCH 022/391] feat: implement FREE_ALL for Attestation Request extension --- src/tls.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/tls.c b/src/tls.c index c413a4e0dc5..06f94b8aae9 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1946,9 +1946,15 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { return len; } +static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { + XFREE(req->request, heap, DYNAMIC_TYPE_TLSX); + XFREE(req, heap, DYNAMIC_TYPE_TLSX); +} + #define ATT_WRITE TLSX_AttestationRequest_Write #define ATT_PARSE TLSX_AttestationRequest_Parse #define ATT_GET_SIZE TLSX_AttestationRequest_GetSize +#define ATT_FREE_ALL TLSX_AttestationRequest_FreeAll #endif /* WOLFSSL_REMOTE_ATTESTATION */ @@ -11315,6 +11321,11 @@ void TLSX_FreeAll(TLSX* list, void* heap) KS_FREE_ALL((KeyShareEntry*)extension->data, heap); break; #endif +#ifdef WOLFSSL_REMOTE_ATTESTATION + case TLSX_ATTESTATION_REQUEST: + ATT_FREE_ALL((ATT_REQUEST *) extension->data, heap); + break; +#endif /* WOLFSSL_REMOTE_ATTESTATION */ #ifdef WOLFSSL_SRTP case TLSX_USE_SRTP: SRTP_FREE((TlsxSrtp*)extension->data, heap); From b7a0e6e6ae527600ab1802dcc27d82ab264ad685 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sat, 6 May 2023 18:02:22 +0800 Subject: [PATCH 023/391] fix: add additional checks to attestation request extension --- src/tls.c | 45 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/src/tls.c b/src/tls.c index 06f94b8aae9..1cd49ce3bc4 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1867,6 +1867,28 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #ifdef WOLFSSL_REMOTE_ATTESTATION +int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server) +{ + if (extensions == NULL) { + return BAD_FUNC_ARG; + } + + int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, req, heap); + if (ret != 0) { + return ret; + } + + if (is_server) { + TLSX *ext = TLSX_Find(*extensions, TLSX_ATTESTATION_REQUEST); + if (ext == NULL) { + return BAD_STATE_E; + } + ext->resp = 1; + } + + return WOLFSSL_SUCCESS; +} + /** * Writes the Attestation Request extension data into the output buffer. * Assumes that the output buffer is big enough to hold data. @@ -1878,13 +1900,12 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) * @param pSz Incremented by the number of bytes written into the buffer. * @return Either success (0) or sanity error (SANITY_MSG_E) */ -static int TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output, byte msgType) { +static word16 TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output, byte msgType) { WOLFSSL_ENTER("TLSX_AttestationRequest_Write"); - int i = 0; + word16 i = 0; if (msgType == client_hello || msgType == server_hello) { - c16toa(req->length, output); i += OPAQUE16_LEN; @@ -1914,21 +1935,30 @@ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 return BAD_FUNC_ARG; } - (void)length; + if (length < OPAQUE16_LEN) { + return BUFFER_ERROR; + } if (msgType == client_hello || msgType == server_hello) { ATT_REQUEST* req = (ATT_REQUEST*)XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); - - if (length < OPAQUE16_LEN + req->length) { - return BUFFER_ERROR; + if (req == NULL) { + return MEMORY_ERROR; } ato16(input, &req->length); input += OPAQUE16_LEN; + if (length < OPAQUE16_LEN + req->length) { + return BUFFER_ERROR; + } req->request = (void *) XMALLOC(req->length, ssl->heap, DYNAMIC_TYPE_TLSX); + if (req->request == NULL) { + return MEMORY_ERROR; + } XMEMCPY(req->request, input, req->length); input += req->length; + + ssl->attestationRequest = req; } else { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); return SANITY_MSG_E; @@ -1947,6 +1977,7 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { } static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { + (void)heap; XFREE(req->request, heap, DYNAMIC_TYPE_TLSX); XFREE(req, heap, DYNAMIC_TYPE_TLSX); } From 70d5800c5c36c5ddf741142a963d603756580d75 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sat, 6 May 2023 18:03:27 +0800 Subject: [PATCH 024/391] feat: implement GetAttestationRequest --- src/ssl.c | 30 ++++++++++++++---------------- wolfssl/internal.h | 6 ++++++ wolfssl/ssl.h | 2 ++ 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index f6980486866..03719aa26a2 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3463,16 +3463,11 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { WOLFSSL_ENTER("wolfSSL_AttestationRequest"); - int ret = TLSX_Push(&ssl->extensions, TLSX_ATTESTATION_REQUEST, req, ssl->heap); - if (ret != 0) { - return ret; + if (ssl == NULL) { + return BAD_FUNC_ARG; } - if (wolfSSL_is_server(ssl)) { - // guaranteed to not be NULL as we just pushed it. - TLSX *ext = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); - ext->resp = 1; - } + int ret = TLSX_UseAttestationRequest(&ssl->extensions, req, ssl->heap, wolfSSL_is_server(ssl)); WOLFSSL_LEAVE("wolfSSL_AttestationRequest", ret); return ret; @@ -3481,16 +3476,11 @@ int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, ATT_REQUEST *req) { WOLFSSL_ENTER("wolfSSL_CTX_AttestationRequest"); - int ret = TLSX_Push(&ctx->extensions, TLSX_ATTESTATION_REQUEST, req, ctx->heap); - if (ret != 0) { - return ret; + if (ctx == NULL) { + return BAD_FUNC_ARG; } - if (ctx->method->side == WOLFSSL_SERVER_END) { - // guaranteed to not be NULL as we just pushed it. - TLSX *ext = TLSX_Find(ctx->extensions, TLSX_ATTESTATION_REQUEST); - ext->resp = 1; - } + int ret = TLSX_UseAttestationRequest(&ctx->extensions, req, ctx->heap, ctx->method->side == WOLFSSL_SERVER_END); WOLFSSL_LEAVE("wolfSSL_CTX_AttestationRequest", ret); return ret; @@ -3529,6 +3519,14 @@ int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST return 0; } +const ATT_REQUEST *wolfSSL_GetAttestationRequest(WOLFSSL *ssl) { + if (ssl == NULL) { + return NULL; + } + + return ssl->attestationRequest; +} + #endif /* WOLFSSL_REMOTE_ATTESTATION */ #ifdef HAVE_SNI diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 2656588ac9a..4e14b8ba1cb 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2740,6 +2740,12 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, #endif /* HAVE_TLS_EXTENSIONS */ +#ifdef WOLFSSL_REMOTE_ATTESTATION + +WOLFSSL_LOCAL int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server); + +#endif + /** Server Name Indication - RFC 6066 (session 3) */ #ifdef HAVE_SNI diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 502edad04ab..3643f595c9c 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3724,6 +3724,8 @@ WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(cons */ WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output)); +WOLFSSL_API const ATT_REQUEST *wolfSSL_GetAttestationRequest(WOLFSSL *ssl); + #endif /* WOLFSSL_REMOTE_ATTESTATION */ /* Server Name Indication */ From 64c079bd2cda4f0fe7ee230d025a02b34aa79c24 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sat, 6 May 2023 18:23:54 +0800 Subject: [PATCH 025/391] try to explicitly allocate attestation data inside wolfSSL The extension is NOT written into the ClientHello, even though the extension size is being updated. This results in a handshake failure --- src/tls.c | 42 +++++++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/src/tls.c b/src/tls.c index 1cd49ce3bc4..5d84d105abf 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1867,14 +1867,48 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #ifdef WOLFSSL_REMOTE_ATTESTATION +static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { + (void)heap; + + if (req) { + if (req->request) { + XFREE(req->request, heap, DYNAMIC_TYPE_TLSX); + } + XFREE(req, heap, DYNAMIC_TYPE_TLSX); + } +} + +ATT_REQUEST *TLSX_AttRequest_New(word16 length, void *data, void *heap) { + ATT_REQUEST *req = (ATT_REQUEST *)XMALLOC(sizeof(ATT_REQUEST), heap, DYNAMIC_TYPE_TLSX); + + if (req) { + req->length = length; + req->request = XMALLOC(length, heap, DYNAMIC_TYPE_TLSX); + + if (req->request) { + XMEMCPY(req->request, data, length); + } else { + XFREE(req, heap, DYNAMIC_TYPE_TLSX); + } + } + + return req; +} + int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server) { if (extensions == NULL) { return BAD_FUNC_ARG; } - int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, req, heap); + ATT_REQUEST *req_cpy = TLSX_AttRequest_New(req->length, req->request, heap); + if (req_cpy == NULL) { + return MEMORY_ERROR; + } + + int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, (void *)req_cpy, heap); if (ret != 0) { + TLSX_AttestationRequest_FreeAll(req_cpy, heap); return ret; } @@ -1976,12 +2010,6 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { return len; } -static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { - (void)heap; - XFREE(req->request, heap, DYNAMIC_TYPE_TLSX); - XFREE(req, heap, DYNAMIC_TYPE_TLSX); -} - #define ATT_WRITE TLSX_AttestationRequest_Write #define ATT_PARSE TLSX_AttestationRequest_Parse #define ATT_GET_SIZE TLSX_AttestationRequest_GetSize From 65509f1bc3bb1dd1645eb27413521c3e8747b683 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sun, 7 May 2023 21:13:42 +0800 Subject: [PATCH 026/391] fix: remove unused imports --- src/ssl.c | 3 --- src/tls.c | 1 - 2 files changed, 4 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 03719aa26a2..4582c8a1bc7 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -20,9 +20,6 @@ */ -#include "wolfssl/ssl.h" -#include "wolfssl/wolfcrypt/error-crypt.h" -#include #ifdef HAVE_CONFIG_H #include #endif diff --git a/src/tls.c b/src/tls.c index 5d84d105abf..59afbfcf0a0 100644 --- a/src/tls.c +++ b/src/tls.c @@ -21,7 +21,6 @@ -#include "wolfssl/wolfcrypt/error-crypt.h" #ifdef HAVE_CONFIG_H #include #endif From 2963df187f41c1f05833de42cf11b0542413e2b5 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sat, 13 May 2023 18:07:26 +0800 Subject: [PATCH 027/391] fix: attestation request not being written in ClientHello --- src/tls.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/tls.c b/src/tls.c index 59afbfcf0a0..136eb1a712b 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1911,11 +1911,12 @@ int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* return ret; } - if (is_server) { +// if (is_server) { TLSX *ext = TLSX_Find(*extensions, TLSX_ATTESTATION_REQUEST); if (ext == NULL) { return BAD_STATE_E; } + if (is_server) { ext->resp = 1; } @@ -1946,9 +1947,12 @@ static word16 TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output i += req->length; } else { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + + WOLFSSL_LEAVE("TLSX_AttestationRequest_Write", SANITY_MSG_E); return SANITY_MSG_E; } + WOLFSSL_LEAVE("TLSX_AttestationRequest_Write", i); return i; } @@ -1975,17 +1979,20 @@ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 if (msgType == client_hello || msgType == server_hello) { ATT_REQUEST* req = (ATT_REQUEST*)XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); if (req == NULL) { + WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", MEMORY_ERROR); return MEMORY_ERROR; } ato16(input, &req->length); input += OPAQUE16_LEN; if (length < OPAQUE16_LEN + req->length) { + WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", BUFFER_ERROR); return BUFFER_ERROR; } req->request = (void *) XMALLOC(req->length, ssl->heap, DYNAMIC_TYPE_TLSX); if (req->request == NULL) { + WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", MEMORY_ERROR); return MEMORY_ERROR; } XMEMCPY(req->request, input, req->length); @@ -1994,18 +2001,22 @@ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 ssl->attestationRequest = req; } else { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", SANITY_MSG_E); return SANITY_MSG_E; } + WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", 0); return 0; } static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { + WOLFSSL_ENTER("TLSX_AttestationRequest_GetSize"); word16 len = 0; len += OPAQUE16_LEN; // length field itself len += req->length; + WOLFSSL_LEAVE("TLSX_AttestationRequest_GetSize", len); return len; } @@ -12838,6 +12849,9 @@ int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset) */ TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY)); #endif + #ifdef WOLFSSL_REMOTE_ATTESTATION + TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); + #endif #endif /* WOLFSSL_TLS13 */ #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) From dcae299ee73909d956920beba215fa17f297dafc Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Sun, 14 May 2023 16:19:24 +0800 Subject: [PATCH 028/391] rename remote attestation feature flag To be more concise with other features --- CMakeLists.txt | 2 +- src/ssl.c | 4 ++-- src/tls.c | 20 ++++++++++---------- wolfssl/internal.h | 8 ++++---- wolfssl/ssl.h | 4 ++-- 5 files changed, 19 insertions(+), 19 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e81bf217fc..f16907f3a2a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -376,7 +376,7 @@ if(WOLFSSL_REMOTE_ATTESTATION) if(NOT WOLFSSL_KEYING_MATERIAL) message(FATAL_ERROR "Remote Attestation supported only with Keying Material Exporter") endif() - list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_REMOTE_ATTESTATION") + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_REMOTE_ATTESTATION") endif() # TODO: - DTLS-SCTP diff --git a/src/ssl.c b/src/ssl.c index 4582c8a1bc7..a89bfc33da0 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3455,7 +3455,7 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) } -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { WOLFSSL_ENTER("wolfSSL_AttestationRequest"); @@ -3524,7 +3524,7 @@ const ATT_REQUEST *wolfSSL_GetAttestationRequest(WOLFSSL *ssl) { return ssl->attestationRequest; } -#endif /* WOLFSSL_REMOTE_ATTESTATION */ +#endif /* HAVE_REMOTE_ATTESTATION */ #ifdef HAVE_SNI diff --git a/src/tls.c b/src/tls.c index 136eb1a712b..47a903b3610 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1864,7 +1864,7 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) /* Remote Attestation */ /******************************************************************************/ -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { (void)heap; @@ -2025,7 +2025,7 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { #define ATT_GET_SIZE TLSX_AttestationRequest_GetSize #define ATT_FREE_ALL TLSX_AttestationRequest_FreeAll -#endif /* WOLFSSL_REMOTE_ATTESTATION */ +#endif /* HAVE_REMOTE_ATTESTATION */ /******************************************************************************/ /* Server Name Indication */ @@ -11390,11 +11390,11 @@ void TLSX_FreeAll(TLSX* list, void* heap) KS_FREE_ALL((KeyShareEntry*)extension->data, heap); break; #endif -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION case TLSX_ATTESTATION_REQUEST: ATT_FREE_ALL((ATT_REQUEST *) extension->data, heap); break; -#endif /* WOLFSSL_REMOTE_ATTESTATION */ +#endif /* HAVE_REMOTE_ATTESTATION */ #ifdef WOLFSSL_SRTP case TLSX_USE_SRTP: SRTP_FREE((TlsxSrtp*)extension->data, heap); @@ -11569,11 +11569,11 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType); break; #endif -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION case TLSX_ATTESTATION_REQUEST: length += ATT_GET_SIZE((const ATT_REQUEST *) extension->data); break; -#endif /* WOLFSSL_REMOTE_ATTESTATION */ +#endif /* HAVE_REMOTE_ATTESTATION */ #ifdef WOLFSSL_SRTP case TLSX_USE_SRTP: length += SRTP_GET_SIZE((TlsxSrtp*)extension->data); @@ -11780,7 +11780,7 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, output + offset, msgType); break; #endif -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION case TLSX_ATTESTATION_REQUEST: WOLFSSL_MSG("Attestation Request extension to write"); offset += ATT_WRITE((const ATT_REQUEST *) extension->data, output + offset, msgType); @@ -12849,7 +12849,7 @@ int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset) */ TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY)); #endif - #ifdef WOLFSSL_REMOTE_ATTESTATION + #ifdef HAVE_REMOTE_ATTESTATION TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); #endif #endif /* WOLFSSL_TLS13 */ @@ -13854,7 +13854,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, break; #endif -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION case TLSX_ATTESTATION_REQUEST: WOLFSSL_MSG("Attestation Request extension received"); #ifdef WOLFSSL_DEBUG_TLS @@ -13867,7 +13867,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, ret = ATT_PARSE(ssl, input + offset, size, msgType); break; -#endif /* WOLFSSL_REMOTE_ATTESTATION */ +#endif /* HAVE_REMOTE_ATTESTATION */ default: WOLFSSL_MSG("Unknown TLS extension type"); } diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 4e14b8ba1cb..a6b5b73058c 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2608,7 +2608,7 @@ typedef enum { TLSX_KEY_QUIC_TP_PARAMS = 0x0039, /* RFC 9001, ch. 8.2 */ #endif #endif -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION TLSX_ATTESTATION_REQUEST = 0xAA00, /* remote attestation, arbitrary number for now */ #endif TLSX_RENEGOTIATION_INFO = 0xff01, @@ -2740,7 +2740,7 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, #endif /* HAVE_TLS_EXTENSIONS */ -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION WOLFSSL_LOCAL int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server); @@ -5505,7 +5505,7 @@ struct WOLFSSL { #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) WOLFSSL_EchConfig* echConfigs; #endif -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION /** For attestation verification. * * @param att the attestation data @@ -5525,7 +5525,7 @@ struct WOLFSSL { * @return 0 on success */ int (*generateAttestation)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output); -#endif /* WOLFSSL_REMOTE_ATTESTATION */ +#endif /* HAVE_REMOTE_ATTESTATION */ }; /* diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 3643f595c9c..6fab93edf8f 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3666,7 +3666,7 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); /* TLS Extensions */ -#ifdef WOLFSSL_REMOTE_ATTESTATION +#ifdef HAVE_REMOTE_ATTESTATION // TODO: WIP definitions /** @@ -3726,7 +3726,7 @@ WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const WOLFSSL_API const ATT_REQUEST *wolfSSL_GetAttestationRequest(WOLFSSL *ssl); -#endif /* WOLFSSL_REMOTE_ATTESTATION */ +#endif /* HAVE_REMOTE_ATTESTATION */ /* Server Name Indication */ #ifdef HAVE_SNI From 75d3e45e2e5172cc706ac33a514a611eb46c6c8d Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 24 May 2023 15:42:55 +0800 Subject: [PATCH 029/391] changed attestation request layout, implement generating server response using TLS KME --- CMakeLists.txt | 11 ++- src/internal.c | 7 ++ src/ssl.c | 30 ++++++- src/tls.c | 194 +++++++++++++++++++++++++++++++++++---------- src/tls13.c | 4 + wolfssl/internal.h | 4 +- wolfssl/ssl.h | 38 +++++++-- 7 files changed, 234 insertions(+), 54 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f16907f3a2a..3f52b50a010 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -376,7 +376,16 @@ if(WOLFSSL_REMOTE_ATTESTATION) if(NOT WOLFSSL_KEYING_MATERIAL) message(FATAL_ERROR "Remote Attestation supported only with Keying Material Exporter") endif() - list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_REMOTE_ATTESTATION") + + # TODO: Include proper checks for features. I will hardcode them for now. + list(APPEND WOLFSSL_DEFINITIONS + "-DWOLFSSL_ASN_TEMPLATE" + "-DWOLFSSL_CERT_GEN" + "-DWOLFSSL_KEY_GEN" + "-DWOLFSSL_CUSTOM_OID" + "-DHAVE_OID_ENCODING" + "-DWOLFSSL_CERT_EXT" + "-DHAVE_REMOTE_ATTESTATION") endif() # TODO: - DTLS-SCTP diff --git a/src/internal.c b/src/internal.c index 731705443f1..6ff34739ff5 100644 --- a/src/internal.c +++ b/src/internal.c @@ -21,6 +21,7 @@ +#include "wolfssl/wolfcrypt/error-crypt.h" #ifdef HAVE_CONFIG_H #include #endif @@ -15655,6 +15656,12 @@ static int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, } } +#ifdef HAVE_REMOTE_ATTESTATION + if (type == client_hello) { + + } +#endif /* HAVE_REMOTE_ATTESTATION */ + if (ssl->options.side == WOLFSSL_CLIENT_END) { switch (type) { case certificate: diff --git a/src/ssl.c b/src/ssl.c index a89bfc33da0..f816ca421e4 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3457,7 +3457,33 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) #ifdef HAVE_REMOTE_ATTESTATION -int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { +void wolfSSL_AttestationRequest_print(XFILE fp, const ATT_REQUEST *req) { + return wolfSSL_AttestationRequest_print_ex(fp, req, 0, 0); +} + +void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte typeIsStr, byte dataIsStr) { + if (fp == NULL | req == NULL) { + return; + } + + fprintf(fp, "Attestation Request:\n"); + + fprintf(fp, " Type : %s", typeIsStr ? "" : "0x"); + char *type = req->type; + for (int i = 0; i < req->typeSize; i++) { + fprintf(fp, typeIsStr ? "%c" : "%X", type[i]); + } + fprintf(fp, "\n"); + + fprintf(fp, " Data : %s", dataIsStr ? "" : "0x"); + char *data = req->data; + for (int i = 0; i < req->dataSize; i++) { + fprintf(fp, dataIsStr ? "%c" : "%X", data[i]); + } + fprintf(fp, "\n"); +} + +int wolfSSL_AttestationRequest(WOLFSSL *ssl, const ATT_REQUEST *req) { WOLFSSL_ENTER("wolfSSL_AttestationRequest"); if (ssl == NULL) { @@ -3470,7 +3496,7 @@ int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req) { return ret; } -int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, ATT_REQUEST *req) { +int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUEST *req) { WOLFSSL_ENTER("wolfSSL_CTX_AttestationRequest"); if (ctx == NULL) { diff --git a/src/tls.c b/src/tls.c index 47a903b3610..1060b9041cb 100644 --- a/src/tls.c +++ b/src/tls.c @@ -21,6 +21,7 @@ +#include "wolfssl/wolfcrypt/error-crypt.h" #ifdef HAVE_CONFIG_H #include #endif @@ -1866,32 +1867,50 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #ifdef HAVE_REMOTE_ATTESTATION +#define ATT_CHALLENGE_LABEL "Remote Attestation" +#define ATT_CHALLENGE_LABEL_LEN strlen(ATT_CHALLENGE_LABEL) +#define ATT_BUFFER_SIZE 16384 + static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { (void)heap; if (req) { - if (req->request) { - XFREE(req->request, heap, DYNAMIC_TYPE_TLSX); + if (req->type) { + XFREE(req->type, heap, DYNAMIC_TYPE_TLSX); + } + if (req->data) { + XFREE(req->data, heap, DYNAMIC_TYPE_TLSX); } XFREE(req, heap, DYNAMIC_TYPE_TLSX); } } -ATT_REQUEST *TLSX_AttRequest_New(word16 length, void *data, void *heap) { - ATT_REQUEST *req = (ATT_REQUEST *)XMALLOC(sizeof(ATT_REQUEST), heap, DYNAMIC_TYPE_TLSX); +ATT_REQUEST *TLSX_AttRequest_NewCopy(const ATT_REQUEST *req, void *heap) { + ATT_REQUEST *req_cpy = (ATT_REQUEST *) XMALLOC(sizeof(ATT_REQUEST), heap, DYNAMIC_TYPE_TLSX); if (req) { - req->length = length; - req->request = XMALLOC(length, heap, DYNAMIC_TYPE_TLSX); - - if (req->request) { - XMEMCPY(req->request, data, length); - } else { - XFREE(req, heap, DYNAMIC_TYPE_TLSX); + req_cpy->challengeSize = req->challengeSize; + req_cpy->type = XMALLOC(req->typeSize, heap, DYNAMIC_TYPE_TLSX); + if (req_cpy->type == NULL) { + XFREE(req_cpy, heap, DYNAMIC_TYPE_TLSX); + goto exit; } + req_cpy->data = XMALLOC(req->dataSize, heap, DYNAMIC_TYPE_TLSX); + if (req_cpy->data == NULL) { + XFREE(req_cpy->type, heap, DYNAMIC_TYPE_TLSX); + XFREE(req_cpy, heap, DYNAMIC_TYPE_TLSX); + goto exit; + } + + req_cpy->typeSize = req->typeSize; + XMEMCPY(req_cpy->type, req->type, req_cpy->typeSize); + + req_cpy->dataSize = req->dataSize; + XMEMCPY(req_cpy->data, req->data, req_cpy->dataSize); } - return req; + exit: + return req_cpy; } int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server) @@ -1900,7 +1919,7 @@ int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* return BAD_FUNC_ARG; } - ATT_REQUEST *req_cpy = TLSX_AttRequest_New(req->length, req->request, heap); + ATT_REQUEST *req_cpy = TLSX_AttRequest_NewCopy(req, heap); if (req_cpy == NULL) { return MEMORY_ERROR; } @@ -1911,12 +1930,11 @@ int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* return ret; } -// if (is_server) { + if (is_server) { TLSX *ext = TLSX_Find(*extensions, TLSX_ATTESTATION_REQUEST); if (ext == NULL) { return BAD_STATE_E; } - if (is_server) { ext->resp = 1; } @@ -1939,15 +1957,21 @@ static word16 TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output word16 i = 0; - if (msgType == client_hello || msgType == server_hello) { - c16toa(req->length, output); + if (msgType == client_hello || msgType == encrypted_extensions) { + c16toa(req->challengeSize, &output[i]); + i += OPAQUE16_LEN; + + c16toa(req->typeSize, &output[i]); i += OPAQUE16_LEN; + XMEMCPY(&output[i], req->type, req->typeSize); + i += req->typeSize; - XMEMCPY(&output[i], req->request, req->length); - i += req->length; + c16toa(req->dataSize, &output[i]); + i += OPAQUE16_LEN; + XMEMCPY(&output[i], req->data, req->dataSize); + i += req->dataSize; } else { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); - WOLFSSL_LEAVE("TLSX_AttestationRequest_Write", SANITY_MSG_E); return SANITY_MSG_E; } @@ -1968,58 +1992,142 @@ static word16 TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 length, byte msgType) { WOLFSSL_ENTER("TLSX_AttestationRequest_Parse"); + int ret = 0; + if (ssl == NULL || input == NULL) { - return BAD_FUNC_ARG; + ret = BAD_FUNC_ARG; + goto exit; } - if (length < OPAQUE16_LEN) { - return BUFFER_ERROR; + if (length < 3 * OPAQUE16_LEN) { + ret = BUFFER_ERROR; + goto exit; } - if (msgType == client_hello || msgType == server_hello) { + if (msgType == client_hello || msgType == encrypted_extensions) { ATT_REQUEST* req = (ATT_REQUEST*)XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); if (req == NULL) { - WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", MEMORY_ERROR); - return MEMORY_ERROR; + ret = MEMORY_ERROR; + goto exit; } + // parsing attestation challenge size + ato16(input, &req->challengeSize); + input += OPAQUE16_LEN; - ato16(input, &req->length); + // parsing attestation type + ato16(input, &req->typeSize); input += OPAQUE16_LEN; - if (length < OPAQUE16_LEN + req->length) { - WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", BUFFER_ERROR); - return BUFFER_ERROR; + if (length < OPAQUE16_LEN + req->typeSize) { + ret = BUFFER_ERROR; + goto exit; } - req->request = (void *) XMALLOC(req->length, ssl->heap, DYNAMIC_TYPE_TLSX); - if (req->request == NULL) { - WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", MEMORY_ERROR); - return MEMORY_ERROR; + req->type = (void *) XMALLOC(req->typeSize, ssl->heap, DYNAMIC_TYPE_TLSX); + if (req->type == NULL) { + ret = MEMORY_ERROR; + goto exit; + } + XMEMCPY(req->type, input, req->typeSize); + input += req->typeSize; + + // parsing attestation data + ato16(input, &req->dataSize); + input += OPAQUE16_LEN; + if (length < OPAQUE16_LEN + req->typeSize + req->dataSize) { + ret = BUFFER_ERROR; + goto exit; } - XMEMCPY(req->request, input, req->length); - input += req->length; + + req->data = (void *) XMALLOC(req->dataSize, ssl->heap, DYNAMIC_TYPE_TLSX); + if (req->data == NULL) { + ret = MEMORY_ERROR; + goto exit; + } + XMEMCPY(req->data, input, req->dataSize); + input += req->dataSize; ssl->attestationRequest = req; } else { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); - WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", SANITY_MSG_E); - return SANITY_MSG_E; + ret = SANITY_MSG_E; } - WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", 0); - return 0; + exit: + WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", ret); + return ret; } static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { WOLFSSL_ENTER("TLSX_AttestationRequest_GetSize"); word16 len = 0; - len += OPAQUE16_LEN; // length field itself - len += req->length; + len += OPAQUE16_LEN; // challengeSize field + len += OPAQUE16_LEN; // typeSize field itself + len += req->typeSize; + len += OPAQUE16_LEN; // dataSize field itself + len += req->dataSize; WOLFSSL_LEAVE("TLSX_AttestationRequest_GetSize", len); return len; } +static int CreateAttestationRequestResponse(WOLFSSL *ssl) { + if (ssl == NULL || ssl->attestationRequest == NULL || ssl->generateAttestation == NULL) { + return BAD_FUNC_ARG; + } + + int ret; + unsigned char *c = NULL; + byte *att = NULL; + + // attestation challenge token + const ATT_REQUEST *req = ssl->attestationRequest; + c = XMALLOC(req->challengeSize, ssl->heap, DYNAMIC_TYPE_TLSX); + if (c == NULL) { + ret = MEMORY_ERROR; + goto exit; + } + + ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, NULL, 0, 0); + if (ret != WOLFSSL_SUCCESS) { + goto exit; + } + + // attestation certificate + att = XMALLOC(ATT_BUFFER_SIZE, ssl->heap, DYNAMIC_TYPE_TLSX); + if (att == NULL) { + ret = MEMORY_ERROR; + goto exit; + } + + int attLen = ssl->generateAttestation(ssl->attestationRequest, c, req->challengeSize, att); + if (attLen == 0) { + ret = WOLFSSL_FATAL_ERROR; + goto exit; + } + + ATT_REQUEST att_req_resp = { + .challengeSize = req->challengeSize, + .typeSize = req->typeSize, + .type = req->type, + .dataSize = attLen, + .data = att, + }; + + ret = TLSX_UseAttestationRequest(&ssl->extensions, &att_req_resp, ssl->heap, TRUE); + // extension gets copied, so it's free to clear below buffers now + +exit: + if (c) { + XFREE(c, ssl->heap, DYNAMIC_TYPE_TLSX); + } + if (att) { + XFREE(att, ssl->heap, DYNAMIC_TYPE_TLSX); + } + + return ret; +} + #define ATT_WRITE TLSX_AttestationRequest_Write #define ATT_PARSE TLSX_AttestationRequest_Parse #define ATT_GET_SIZE TLSX_AttestationRequest_GetSize @@ -13860,7 +13968,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, #ifdef WOLFSSL_DEBUG_TLS WOLFSSL_BUFFER(input + offset, size); #endif - if (msgType != client_hello && msgType != server_hello) { + if (msgType != client_hello && msgType != encrypted_extensions) { WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED); return EXT_NOT_ALLOWED; } diff --git a/src/tls13.c b/src/tls13.c index 73714622040..5c248fbabe3 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -7077,6 +7077,10 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) return ret; +#ifdef HAVE_REMOTE_ATTESTATION + +#endif + /* Setup encrypt/decrypt keys for following messages. */ #ifdef WOLFSSL_EARLY_DATA if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index a6b5b73058c..3ea93c5c25f 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2742,6 +2742,8 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, #ifdef HAVE_REMOTE_ATTESTATION +WOLFSSL_LOCAL int GenerateAttestation(WOLFSSL *ssl); + WOLFSSL_LOCAL int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server); #endif @@ -5522,7 +5524,7 @@ struct WOLFSSL { * @param c the challenge * @param cLen the challenge length * @param output the output buffer for the generated attestation - * @return 0 on success + * @return number of written bytes. 0 if unsuccessful. */ int (*generateAttestation)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output); #endif /* HAVE_REMOTE_ATTESTATION */ diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 6fab93edf8f..205c7b225fd 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3673,21 +3673,45 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); * Attestation Request */ typedef struct ATT_REQUEST { - /** The length of the request data */ - word16 length; - /** The attestation request data */ - void *request; + /** The required length for the attestation challenge */ + word16 challengeSize; + /** The attestation type size */ + word16 typeSize; + /** The attestation type */ + void *type; + /** The attestation data size */ + word16 dataSize; + /** The attestation data */ + void *data; } ATT_REQUEST; +/** + * Prints an attestation request to the given file. + * @param fp The FILE pointer to print to + * @param req The attestation request to print + * @see wolfSSL_AttestationRequest_print_ex + */ +WOLFSSL_API void wolfSSL_AttestationRequest_print(XFILE fp, const ATT_REQUEST *req); + +/** + * Prints an attestation request to the given file. + * @param fp The FILE pointer to print to + * @param req The attestation request to print + * @param typeIsStr Whether the attestation type should be printed as a string + * @param dataIsStr Whether the attestation data should be printed as a string + * @see wolfSSL_AttestationRequest_print + */ +WOLFSSL_API void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte typeIsStr, byte dataIsStr); + /** * Attestation Request extension. */ -WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, ATT_REQUEST *req); +WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, const ATT_REQUEST *req); /** * Attestation Request extension. */ -WOLFSSL_API int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, ATT_REQUEST *req); +WOLFSSL_API int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUEST *req); /* * Returns stored data from the Evidence Request Extension. @@ -3718,7 +3742,7 @@ WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(cons * @param genAtt The attestation generator. * Takes an attestation request, a challenge, a challenge length and a buffer for generated * attestation data as arguments. - * Must return 0 on success. + * Must return number of written bytes.0 if unsuccessful. * * @return 0 if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. */ From 5d1c9848e740b3207e3ec78afdda081a940b4a58 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 26 May 2023 15:42:04 +0800 Subject: [PATCH 030/391] remove unused block --- src/internal.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/internal.c b/src/internal.c index 6ff34739ff5..7261b1beb1c 100644 --- a/src/internal.c +++ b/src/internal.c @@ -15656,12 +15656,6 @@ static int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, } } -#ifdef HAVE_REMOTE_ATTESTATION - if (type == client_hello) { - - } -#endif /* HAVE_REMOTE_ATTESTATION */ - if (ssl->options.side == WOLFSSL_CLIENT_END) { switch (type) { case certificate: From 1ce2b096b616e4e2aa170b5e0746b62c6fd0bf6b Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 26 May 2023 15:42:30 +0800 Subject: [PATCH 031/391] reformat --- src/tls.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/tls.c b/src/tls.c index 1060b9041cb..3a29f56d727 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1872,7 +1872,7 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #define ATT_BUFFER_SIZE 16384 static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { - (void)heap; + (void) heap; if (req) { if (req->type) { @@ -1913,8 +1913,7 @@ ATT_REQUEST *TLSX_AttRequest_NewCopy(const ATT_REQUEST *req, void *heap) { return req_cpy; } -int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server) -{ +int TLSX_UseAttestationRequest(TLSX **extensions, const ATT_REQUEST *req, void *heap, byte is_server) { if (extensions == NULL) { return BAD_FUNC_ARG; } @@ -1924,7 +1923,7 @@ int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* return MEMORY_ERROR; } - int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, (void *)req_cpy, heap); + int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, (void *) req_cpy, heap); if (ret != 0) { TLSX_AttestationRequest_FreeAll(req_cpy, heap); return ret; @@ -2005,7 +2004,7 @@ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 } if (msgType == client_hello || msgType == encrypted_extensions) { - ATT_REQUEST* req = (ATT_REQUEST*)XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); + ATT_REQUEST *req = (ATT_REQUEST *) XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); if (req == NULL) { ret = MEMORY_ERROR; goto exit; @@ -2071,7 +2070,8 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { return len; } -static int CreateAttestationRequestResponse(WOLFSSL *ssl) { +int GenerateAttestation(WOLFSSL *ssl) { + WOLFSSL_ENTER("GenerateAttestation"); if (ssl == NULL || ssl->attestationRequest == NULL || ssl->generateAttestation == NULL) { return BAD_FUNC_ARG; } @@ -2125,6 +2125,7 @@ static int CreateAttestationRequestResponse(WOLFSSL *ssl) { XFREE(att, ssl->heap, DYNAMIC_TYPE_TLSX); } + WOLFSSL_LEAVE("GenerateAttestation", ret); return ret; } From 69be54764a692004965bd094cbf18de6cd284b46 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Mon, 29 May 2023 10:44:04 +0800 Subject: [PATCH 032/391] chore: add some documentation, one TODO --- wolfssl/ssl.h | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 205c7b225fd..e62db9ed2f3 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3674,6 +3674,7 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); */ typedef struct ATT_REQUEST { /** The required length for the attestation challenge */ + // TODO: This should be fixed size perhaps word16 challengeSize; /** The attestation type size */ word16 typeSize; @@ -3713,16 +3714,6 @@ WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, const ATT_REQUEST *req) */ WOLFSSL_API int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUEST *req); -/* - * Returns stored data from the Evidence Request Extension. - * - * RETURNS: - * 'client': data to send to 'server' - * 'server': data received from 'client' - */ -// TODO: What about the data the server sent to the client? -// WOLFSSL_API void *wolfSSL_GetEvidence(WOLFSSL *ssl); - /** * Sets the callback for attestation verification on 'client' side. * @@ -3748,6 +3739,13 @@ WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(cons */ WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output)); +/** + * Returns a received attestation request. + * Will be NULL if not received. + * + * @param ssl The SSL session + * @return received attestation request. NULL if not present. + */ WOLFSSL_API const ATT_REQUEST *wolfSSL_GetAttestationRequest(WOLFSSL *ssl); #endif /* HAVE_REMOTE_ATTESTATION */ From 99ab1dc606b1f9f65be7e1db659baadc69b59b9a Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Mon, 29 May 2023 10:45:25 +0800 Subject: [PATCH 033/391] fix: attestation generation --- src/tls.c | 47 ++++++++++++++++++++++++++++++++++++++++------- src/tls13.c | 9 +++++++++ 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/src/tls.c b/src/tls.c index 3a29f56d727..9cd43de8c2b 100644 --- a/src/tls.c +++ b/src/tls.c @@ -2071,15 +2071,16 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { } int GenerateAttestation(WOLFSSL *ssl) { - WOLFSSL_ENTER("GenerateAttestation"); - if (ssl == NULL || ssl->attestationRequest == NULL || ssl->generateAttestation == NULL) { - return BAD_FUNC_ARG; - } - int ret; unsigned char *c = NULL; byte *att = NULL; + WOLFSSL_ENTER("GenerateAttestation"); + if (ssl == NULL || ssl->attestationRequest == NULL || ssl->generateAttestation == NULL || !wolfSSL_is_server(ssl)) { + ret = BAD_FUNC_ARG; + goto exit; + } + // attestation challenge token const ATT_REQUEST *req = ssl->attestationRequest; c = XMALLOC(req->challengeSize, ssl->heap, DYNAMIC_TYPE_TLSX); @@ -2088,8 +2089,18 @@ int GenerateAttestation(WOLFSSL *ssl) { goto exit; } - ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, NULL, 0, 0); - if (ret != WOLFSSL_SUCCESS) { + // generate challenge + if (req->dataSize != 0) { + ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, + req->data, req->dataSize, TRUE); + } else { + ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, + NULL, 0, FALSE); + } + if (ret == WOLFSSL_SUCCESS) { + ret = 0; + } else { + ret = WOLFSSL_FATAL_ERROR; goto exit; } @@ -2102,6 +2113,7 @@ int GenerateAttestation(WOLFSSL *ssl) { int attLen = ssl->generateAttestation(ssl->attestationRequest, c, req->challengeSize, att); if (attLen == 0) { + // TODO: Introduce AttestationError? ret = WOLFSSL_FATAL_ERROR; goto exit; } @@ -2115,6 +2127,11 @@ int GenerateAttestation(WOLFSSL *ssl) { }; ret = TLSX_UseAttestationRequest(&ssl->extensions, &att_req_resp, ssl->heap, TRUE); + if (ret == WOLFSSL_SUCCESS) { + ret = 0; + } else { + ret = WOLFSSL_FATAL_ERROR; + } // extension gets copied, so it's free to clear below buffers now exit: @@ -13138,6 +13155,10 @@ int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength) #ifdef WOLFSSL_DTLS_CID TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID)); #endif /* WOLFSSL_DTLS_CID */ +#ifdef HAVE_REMOTE_ATTESTATION + // TODO: Needed? + TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); +#endif break; #ifdef WOLFSSL_EARLY_DATA @@ -13160,6 +13181,10 @@ int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength) /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, * TLSX_SERVER_CERTIFICATE_TYPE */ +#ifdef HAVE_REMOTE_ATTESTATION + // TODO: Needed? + TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); +#endif break; #endif #endif @@ -13280,6 +13305,10 @@ int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset #ifdef WOLFSSL_DTLS_CID TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID)); #endif /* WOLFSSL_DTLS_CID */ + #ifdef HAVE_REMOTE_ATTESTATION + // TODO: Needed? + TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); + #endif break; #ifdef WOLFSSL_EARLY_DATA @@ -13303,6 +13332,10 @@ int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, * TLSX_SERVER_CERTIFICATE_TYPE */ +#ifdef HAVE_REMOTE_ATTESTATION + // TODO: Needed? + TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); +#endif break; #endif #endif diff --git a/src/tls13.c b/src/tls13.c index 5c248fbabe3..761236fe83b 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -11131,6 +11131,15 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, ret = HashInput(ssl, input + inIdx, size); } +#ifdef HAVE_REMOTE_ATTESTATION + // TODO: Does this belong here? It should be AFTER input hashing and before writing encrypted extensions. + if (ret == 0 && type == client_hello && ssl->attestationRequest) { + if ((ret = GenerateAttestation(ssl)) != 0) { + WOLFSSL_MSG("Attestation Generation failed"); + } + } +#endif /* HAVE_REMOTE_ATTESTATION */ + alertType = TranslateErrorToAlert(ret); if (alertType != invalid_alert) { From fb75812b78b94735bbb28a2aed20d73eda62950c Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Tue, 30 May 2023 16:19:39 +0800 Subject: [PATCH 034/391] feat: add error codes for attestation --- src/internal.c | 6 ++++++ src/tls.c | 4 ++-- wolfssl/error-ssl.h | 6 +++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/internal.c b/src/internal.c index 7261b1beb1c..43620f6d5c3 100644 --- a/src/internal.c +++ b/src/internal.c @@ -23549,6 +23549,12 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) case DUPLICATE_TLS_EXT_E: return "Duplicate TLS extension in message."; + case ATTESTATION_KEYING_E: + return "Keying Binder error in attestation generation"; + + case ATTESTATION_GENERATION_E: + return "Attestation generation error in custom function"; + default : return "unknown error number"; } diff --git a/src/tls.c b/src/tls.c index 9cd43de8c2b..d018f7b0e42 100644 --- a/src/tls.c +++ b/src/tls.c @@ -2100,7 +2100,7 @@ int GenerateAttestation(WOLFSSL *ssl) { if (ret == WOLFSSL_SUCCESS) { ret = 0; } else { - ret = WOLFSSL_FATAL_ERROR; + ret = ATTESTATION_KEYING_E; goto exit; } @@ -2114,7 +2114,7 @@ int GenerateAttestation(WOLFSSL *ssl) { int attLen = ssl->generateAttestation(ssl->attestationRequest, c, req->challengeSize, att); if (attLen == 0) { // TODO: Introduce AttestationError? - ret = WOLFSSL_FATAL_ERROR; + ret = ATTESTATION_GENERATION_E; goto exit; } diff --git a/wolfssl/error-ssl.h b/wolfssl/error-ssl.h index 9a6a9cf2899..b0466dd1f16 100644 --- a/wolfssl/error-ssl.h +++ b/wolfssl/error-ssl.h @@ -191,10 +191,14 @@ enum wolfSSL_ErrorCodes { COMPRESSION_ERROR = -502, /* compression mismatch */ KEY_SHARE_ERROR = -503, /* key share mismatch */ POST_HAND_AUTH_ERROR = -504, /* client won't do post-hand auth */ - HRR_COOKIE_ERROR = -505 /* HRR msg cookie mismatch */ + HRR_COOKIE_ERROR = -505, /* HRR msg cookie mismatch */ /* end negotiation parameter errors only 10 for now */ /* add strings to wolfSSL_ERR_reason_error_string in internal.c !!!!! */ + ATTESTATION_KEYING_E = -606, /* TLS-Exporter error during attestation keying */ + ATTESTATION_GENERATION_E = -607 /* attestation generation error */ + /* add strings to wolfSSL_ERR_reason_error_string in internal.c !!!!! */ + /* no error strings go down here, add above negotiation errors !!!! */ }; From 07af9408d1eafb32c68a84a7c29e6826d37682a8 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Tue, 30 May 2023 16:21:08 +0800 Subject: [PATCH 035/391] fix: move attestation generation call to not error out --- src/tls13.c | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/tls13.c b/src/tls13.c index 761236fe83b..e5ed5dd0bb1 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -7078,8 +7078,14 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) return ret; #ifdef HAVE_REMOTE_ATTESTATION - -#endif + // TODO: Does this belong here? It should be AFTER input hashing and before writing encrypted extensions. + if (ssl->attestationRequest) { + if ((ret = GenerateAttestation(ssl)) != 0) { + WOLFSSL_MSG("Attestation Generation failed"); + return ret; + } + } +#endif /* HAVE_REMOTE_ATTESTATION */ /* Setup encrypt/decrypt keys for following messages. */ #ifdef WOLFSSL_EARLY_DATA @@ -11131,15 +11137,6 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, ret = HashInput(ssl, input + inIdx, size); } -#ifdef HAVE_REMOTE_ATTESTATION - // TODO: Does this belong here? It should be AFTER input hashing and before writing encrypted extensions. - if (ret == 0 && type == client_hello && ssl->attestationRequest) { - if ((ret = GenerateAttestation(ssl)) != 0) { - WOLFSSL_MSG("Attestation Generation failed"); - } - } -#endif /* HAVE_REMOTE_ATTESTATION */ - alertType = TranslateErrorToAlert(ret); if (alertType != invalid_alert) { From a51cf7146a43a3822263c8ac289ae6b4503b5536 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Tue, 30 May 2023 17:01:06 +0800 Subject: [PATCH 036/391] feat: first try at working veryifyAttestation callback --- src/ssl.c | 4 +-- src/tls.c | 61 ++++++++++++++++++++++++++++++++++++++++------ src/tls13.c | 14 ++++++++++- wolfssl/internal.h | 16 ++++++++++++ wolfssl/ssl.h | 4 +-- 5 files changed, 86 insertions(+), 13 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index f816ca421e4..32f8a434b51 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3527,7 +3527,7 @@ int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUES } ssl->verifyAttestation = verifyAtt; - return 0; + return SSL_SUCCESS; } int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output)) { @@ -3539,7 +3539,7 @@ int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST } ssl->generateAttestation = genAtt; - return 0; + return SSL_SUCCESS; } const ATT_REQUEST *wolfSSL_GetAttestationRequest(WOLFSSL *ssl) { diff --git a/src/tls.c b/src/tls.c index d018f7b0e42..2ed44e55ed1 100644 --- a/src/tls.c +++ b/src/tls.c @@ -2118,13 +2118,7 @@ int GenerateAttestation(WOLFSSL *ssl) { goto exit; } - ATT_REQUEST att_req_resp = { - .challengeSize = req->challengeSize, - .typeSize = req->typeSize, - .type = req->type, - .dataSize = attLen, - .data = att, - }; + ATT_REQUEST att_req_resp = {.challengeSize = req->challengeSize, .typeSize = req->typeSize, .type = req->type, .dataSize = attLen, .data = att,}; ret = TLSX_UseAttestationRequest(&ssl->extensions, &att_req_resp, ssl->heap, TRUE); if (ret == WOLFSSL_SUCCESS) { @@ -2134,7 +2128,7 @@ int GenerateAttestation(WOLFSSL *ssl) { } // extension gets copied, so it's free to clear below buffers now -exit: + exit: if (c) { XFREE(c, ssl->heap, DYNAMIC_TYPE_TLSX); } @@ -2146,6 +2140,57 @@ int GenerateAttestation(WOLFSSL *ssl) { return ret; } +/** + * Verifies an attestation certificate from the user-defined callback seeded a challenge created by the TLS-Exporter. + * + * @param ssl The SSL/TLS object + * @return 0 on success. Any other value indicates an error. + * @see WOLFSSL->verifyAttestation() + */ +int VerifyAttestation(WOLFSSL *ssl) { + int ret; + unsigned char *c = NULL; + + WOLFSSL_ENTER("VerifyAttestation"); + if (!ssl || !ssl->attestationRequest || !ssl->verifyAttestation || wolfSSL_is_server(ssl)) { + ret = BAD_FUNC_ARG; + goto exit; + } + + // attestation challenge token + const ATT_REQUEST *req = ssl->attestationRequest; + c = XMALLOC(req->challengeSize, ssl->heap, DYNAMIC_TYPE_TLSX); + if (!c) { + ret = MEMORY_ERROR; + goto exit; + } + + // generate challenge + if (req->dataSize != 0) { + ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, + req->data, req->dataSize, TRUE); + } else { + ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, + NULL, 0, FALSE); + } + if (ret == WOLFSSL_SUCCESS) { + ret = 0; + } else { + ret = ATTESTATION_KEYING_E; + goto exit; + } + + ret = ssl->verifyAttestation(req, c, req->challengeSize); + +exit: + if (c) { + XFREE(c, ssl->heap, DYNAMIC_TYPE_TLSX); + } + + WOLFSSL_LEAVE("VerifyAttestation", ret); + return ret; +} + #define ATT_WRITE TLSX_AttestationRequest_Write #define ATT_PARSE TLSX_AttestationRequest_Parse #define ATT_GET_SIZE TLSX_AttestationRequest_GetSize diff --git a/src/tls13.c b/src/tls13.c index e5ed5dd0bb1..2c40e842914 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -7078,7 +7078,8 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) return ret; #ifdef HAVE_REMOTE_ATTESTATION - // TODO: Does this belong here? It should be AFTER input hashing and before writing encrypted extensions. + // TODO: Does this belong here? It should be AFTER input hashing (for the TLS exporter) + // and before writing encrypted extensions. if (ssl->attestationRequest) { if ((ret = GenerateAttestation(ssl)) != 0) { WOLFSSL_MSG("Attestation Generation failed"); @@ -9162,6 +9163,17 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, } #endif /* !NO_RSA && WC_RSA_PSS */ + #ifdef HAVE_REMOTE_ATTESTATION \ + // TODO: Does this belong here? It should be AFTER input hashing (for the TLS exporter) + // and after receiving encrypted extensions. + if (ssl->attestationRequest && ssl->verifyAttestation) { + ret = VerifyAttestation(ssl); + if (ret != 0) { + goto exit_dcv; + } + } + #endif + /* Advance state and proceed */ ssl->options.asyncState = TLS_ASYNC_FINALIZE; } /* case TLS_ASYNC_VERIFY */ diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 3ea93c5c25f..d39ecdb6fee 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2742,8 +2742,24 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, #ifdef HAVE_REMOTE_ATTESTATION +/** + * Generates an attestation certificate from the user-defined callback seeded by a challenge created by the TLS-Exporter. + * + * @param ssl The SSL/TLS object + * @return 0 on success. Any other value indicates an error. + * @see WOLFSSL->generateAttestation() + */ WOLFSSL_LOCAL int GenerateAttestation(WOLFSSL *ssl); +/** + * Verifies an attestation certificate from the user-defined callback seeded a challenge created by the TLS-Exporter. + * + * @param ssl The SSL/TLS object + * @return 0 on success. Any other value indicates an error. + * @see WOLFSSL->verifyAttestation() + */ +WOLFSSL_LOCAL int VerifyAttestation(WOLFSSL *ssl); + WOLFSSL_LOCAL int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server); #endif diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index e62db9ed2f3..0fee71a1b44 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3722,7 +3722,7 @@ WOLFSSL_API int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUE * Takes attestation data, a challenge and a challenge length as arguments. * Must return 0 on success. * - * @return 0 if client, SIDE_ERROR if server, and BAD_FUNC_ARG if any param is NULL. + * @return SSL_SUCCESS if client, SIDE_ERROR if server, and BAD_FUNC_ARG if any param is NULL. */ WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c, word16 cLen)); @@ -3735,7 +3735,7 @@ WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(cons * attestation data as arguments. * Must return number of written bytes.0 if unsuccessful. * - * @return 0 if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. + * @return SSL_SUCCESS if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. */ WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output)); From 71cb40b39e7d5cad512eaf8216ad696898681b3c Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Tue, 30 May 2023 17:34:56 +0800 Subject: [PATCH 037/391] fix: disable context for attestation challenge generation --- src/tls.c | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/src/tls.c b/src/tls.c index 2ed44e55ed1..a60e34aaaa1 100644 --- a/src/tls.c +++ b/src/tls.c @@ -2090,13 +2090,14 @@ int GenerateAttestation(WOLFSSL *ssl) { } // generate challenge - if (req->dataSize != 0) { - ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, - req->data, req->dataSize, TRUE); - } else { - ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, - NULL, 0, FALSE); - } + // TODO: context data must be explicitly sent inside the attestation_request or saved into the SSL struct +// if (req->dataSize != 0) { +// ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, +// req->data, req->dataSize, TRUE); +// } else { + ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, NULL, + 0, FALSE); +// } if (ret == WOLFSSL_SUCCESS) { ret = 0; } else { @@ -2113,7 +2114,6 @@ int GenerateAttestation(WOLFSSL *ssl) { int attLen = ssl->generateAttestation(ssl->attestationRequest, c, req->challengeSize, att); if (attLen == 0) { - // TODO: Introduce AttestationError? ret = ATTESTATION_GENERATION_E; goto exit; } @@ -2166,13 +2166,14 @@ int VerifyAttestation(WOLFSSL *ssl) { } // generate challenge - if (req->dataSize != 0) { - ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, - req->data, req->dataSize, TRUE); - } else { - ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, - NULL, 0, FALSE); - } + // TODO: context data must be explicitly sent inside the attestation_request or saved into the SSL struct +// if (req->dataSize != 0) { +// ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, +// req->data, req->dataSize, TRUE); +// } else { + ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, NULL, + 0, FALSE); +// } if (ret == WOLFSSL_SUCCESS) { ret = 0; } else { @@ -2182,7 +2183,7 @@ int VerifyAttestation(WOLFSSL *ssl) { ret = ssl->verifyAttestation(req, c, req->challengeSize); -exit: + exit: if (c) { XFREE(c, ssl->heap, DYNAMIC_TYPE_TLSX); } From 59d229fd26b747290e791bcd60fa15ce2012be2d Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Tue, 30 May 2023 18:23:47 +0800 Subject: [PATCH 038/391] fix: print attestation request correctly --- src/ssl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 32f8a434b51..111564e576e 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3469,14 +3469,14 @@ void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte fprintf(fp, "Attestation Request:\n"); fprintf(fp, " Type : %s", typeIsStr ? "" : "0x"); - char *type = req->type; + byte *type = req->type; for (int i = 0; i < req->typeSize; i++) { fprintf(fp, typeIsStr ? "%c" : "%X", type[i]); } fprintf(fp, "\n"); fprintf(fp, " Data : %s", dataIsStr ? "" : "0x"); - char *data = req->data; + byte *data = req->data; for (int i = 0; i < req->dataSize; i++) { fprintf(fp, dataIsStr ? "%c" : "%X", data[i]); } From 6c5973c94e66c9b3dbdb3b3d24b0c2d402b79b9a Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Mon, 5 Jun 2023 15:28:24 +0800 Subject: [PATCH 039/391] feat: new ATT_REQUEST layout --- src/ssl.c | 41 ++++----- src/tls.c | 204 ++++++++++++++++++++------------------------- wolfssl/internal.h | 2 +- wolfssl/ssl.h | 32 +++---- 4 files changed, 131 insertions(+), 148 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 111564e576e..0234682d7b1 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3458,53 +3458,54 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) #ifdef HAVE_REMOTE_ATTESTATION void wolfSSL_AttestationRequest_print(XFILE fp, const ATT_REQUEST *req) { - return wolfSSL_AttestationRequest_print_ex(fp, req, 0, 0); + return wolfSSL_AttestationRequest_print_ex(fp, req, 0); } -void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte typeIsStr, byte dataIsStr) { - if (fp == NULL | req == NULL) { +void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte dataIsStr) { + if (!fp || !req) { return; } fprintf(fp, "Attestation Request:\n"); - - fprintf(fp, " Type : %s", typeIsStr ? "" : "0x"); - byte *type = req->type; - for (int i = 0; i < req->typeSize; i++) { - fprintf(fp, typeIsStr ? "%c" : "%X", type[i]); + fprintf(fp, " Request: %d", req->is_request); + fprintf(fp, " Nonce: 0x%lX\n", req->nonce); + fprintf(fp, " Challenge Size: %d\n", req->challengeSize); + if (req->is_request) { + fprintf(fp, " Type : %s", dataIsStr ? "" : "0x"); + } else { + fprintf(fp, " Attestation : %s", dataIsStr ? "" : "0x"); } - fprintf(fp, "\n"); - - fprintf(fp, " Data : %s", dataIsStr ? "" : "0x"); - byte *data = req->data; - for (int i = 0; i < req->dataSize; i++) { - fprintf(fp, dataIsStr ? "%c" : "%X", data[i]); + byte *type = req->data; + for (int i = 0; i < req->size; i++) { + fprintf(fp, dataIsStr ? "%c" : "%X", type[i]); } fprintf(fp, "\n"); } int wolfSSL_AttestationRequest(WOLFSSL *ssl, const ATT_REQUEST *req) { + int ret; WOLFSSL_ENTER("wolfSSL_AttestationRequest"); if (ssl == NULL) { - return BAD_FUNC_ARG; + ret = BAD_FUNC_ARG; + } else { + ret = TLSX_UseAttestationRequest(&ssl->extensions, req, ssl->heap, wolfSSL_is_server(ssl)); } - int ret = TLSX_UseAttestationRequest(&ssl->extensions, req, ssl->heap, wolfSSL_is_server(ssl)); - WOLFSSL_LEAVE("wolfSSL_AttestationRequest", ret); return ret; } int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUEST *req) { + int ret; WOLFSSL_ENTER("wolfSSL_CTX_AttestationRequest"); if (ctx == NULL) { - return BAD_FUNC_ARG; + ret = BAD_FUNC_ARG; + } else { + ret = TLSX_UseAttestationRequest(&ctx->extensions, req, ctx->heap, ctx->method->side == WOLFSSL_SERVER_END); } - int ret = TLSX_UseAttestationRequest(&ctx->extensions, req, ctx->heap, ctx->method->side == WOLFSSL_SERVER_END); - WOLFSSL_LEAVE("wolfSSL_CTX_AttestationRequest", ret); return ret; } diff --git a/src/tls.c b/src/tls.c index a60e34aaaa1..33523e1ba5f 100644 --- a/src/tls.c +++ b/src/tls.c @@ -22,6 +22,7 @@ #include "wolfssl/wolfcrypt/error-crypt.h" +#include "wolfssl/wolfcrypt/logging.h" #ifdef HAVE_CONFIG_H #include #endif @@ -1875,9 +1876,6 @@ static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { (void) heap; if (req) { - if (req->type) { - XFREE(req->type, heap, DYNAMIC_TYPE_TLSX); - } if (req->data) { XFREE(req->data, heap, DYNAMIC_TYPE_TLSX); } @@ -1888,33 +1886,38 @@ static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { ATT_REQUEST *TLSX_AttRequest_NewCopy(const ATT_REQUEST *req, void *heap) { ATT_REQUEST *req_cpy = (ATT_REQUEST *) XMALLOC(sizeof(ATT_REQUEST), heap, DYNAMIC_TYPE_TLSX); + word8 fail = 0; + if (req) { + req_cpy->is_request = req->is_request; + req_cpy->nonce = req->nonce; req_cpy->challengeSize = req->challengeSize; - req_cpy->type = XMALLOC(req->typeSize, heap, DYNAMIC_TYPE_TLSX); - if (req_cpy->type == NULL) { - XFREE(req_cpy, heap, DYNAMIC_TYPE_TLSX); + req_cpy->size = req->size; + + if (req->size != 0 && !req->data) { + fail = 1; goto exit; } - req_cpy->data = XMALLOC(req->dataSize, heap, DYNAMIC_TYPE_TLSX); - if (req_cpy->data == NULL) { - XFREE(req_cpy->type, heap, DYNAMIC_TYPE_TLSX); - XFREE(req_cpy, heap, DYNAMIC_TYPE_TLSX); + req_cpy->data = XMALLOC(req->size, heap, DYNAMIC_TYPE_TLSX); + if (!req_cpy->data) { + fail = 1; goto exit; } - - req_cpy->typeSize = req->typeSize; - XMEMCPY(req_cpy->type, req->type, req_cpy->typeSize); - - req_cpy->dataSize = req->dataSize; - XMEMCPY(req_cpy->data, req->data, req_cpy->dataSize); + XMEMCPY(req_cpy->data, req->data, req->size); } exit: + if (fail) { + TLSX_AttestationRequest_FreeAll(req_cpy, heap); + } return req_cpy; } int TLSX_UseAttestationRequest(TLSX **extensions, const ATT_REQUEST *req, void *heap, byte is_server) { - if (extensions == NULL) { + if (!extensions || !req) { + return BAD_FUNC_ARG; + } + if (is_server && req->is_request) { return BAD_FUNC_ARG; } @@ -1948,33 +1951,36 @@ int TLSX_UseAttestationRequest(TLSX **extensions, const ATT_REQUEST *req, void * * @param data The extension data to write. * @param output The buffer to write into. * @param msgType The type of the message this extension is being written into. - * @param pSz Incremented by the number of bytes written into the buffer. - * @return Either success (0) or sanity error (SANITY_MSG_E) + * @return 0 on success, other values indicate failure */ static word16 TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output, byte msgType) { WOLFSSL_ENTER("TLSX_AttestationRequest_Write"); word16 i = 0; - if (msgType == client_hello || msgType == encrypted_extensions) { - c16toa(req->challengeSize, &output[i]); - i += OPAQUE16_LEN; - - c16toa(req->typeSize, &output[i]); - i += OPAQUE16_LEN; - XMEMCPY(&output[i], req->type, req->typeSize); - i += req->typeSize; + if (!req) { + WOLFSSL_LEAVE("TLSX_AttestationRequest_Write", BAD_FUNC_ARG); + return BAD_FUNC_ARG; + } - c16toa(req->dataSize, &output[i]); - i += OPAQUE16_LEN; - XMEMCPY(&output[i], req->data, req->dataSize); - i += req->dataSize; - } else { + if (msgType != client_hello && msgType != encrypted_extensions) { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); WOLFSSL_LEAVE("TLSX_AttestationRequest_Write", SANITY_MSG_E); return SANITY_MSG_E; } + c64toa((const w64wrapper *) req->nonce, &output[i]); + i += OPAQUE64_LEN; + + c16toa(req->challengeSize, &output[i]); + i += OPAQUE16_LEN; + + c16toa(req->size, &output[i]); + i += OPAQUE16_LEN; + + XMEMCPY(&output[i], req->data, req->size); + i += req->size; + WOLFSSL_LEAVE("TLSX_AttestationRequest_Write", i); return i; } @@ -1986,70 +1992,62 @@ static word16 TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output * @param input The extension data. * @param length The length of the extension data. * @param msgType The type of the message this extension is being parsed from. - * @return 0 on success, other values indicate failure. + * @return 0 on success, other values indicate failure */ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 length, byte msgType) { WOLFSSL_ENTER("TLSX_AttestationRequest_Parse"); int ret = 0; + int i = 0; if (ssl == NULL || input == NULL) { ret = BAD_FUNC_ARG; goto exit; } - if (length < 3 * OPAQUE16_LEN) { + if (msgType != client_hello && msgType != encrypted_extensions) { + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + ret = SANITY_MSG_E; + goto exit; + } + + // nonce, challengeSize, size fields + if (length < OPAQUE64_LEN + 2 * OPAQUE16_LEN) { ret = BUFFER_ERROR; goto exit; } - if (msgType == client_hello || msgType == encrypted_extensions) { - ATT_REQUEST *req = (ATT_REQUEST *) XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); - if (req == NULL) { - ret = MEMORY_ERROR; - goto exit; - } - // parsing attestation challenge size - ato16(input, &req->challengeSize); - input += OPAQUE16_LEN; + ATT_REQUEST *req = XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); + req->is_request = !wolfSSL_is_server(ssl); - // parsing attestation type - ato16(input, &req->typeSize); - input += OPAQUE16_LEN; - if (length < OPAQUE16_LEN + req->typeSize) { - ret = BUFFER_ERROR; - goto exit; - } + ato64(&input[i], (w64wrapper *) &req->nonce); + i += OPAQUE64_LEN; - req->type = (void *) XMALLOC(req->typeSize, ssl->heap, DYNAMIC_TYPE_TLSX); - if (req->type == NULL) { - ret = MEMORY_ERROR; - goto exit; - } - XMEMCPY(req->type, input, req->typeSize); - input += req->typeSize; + ato16(&input[i], &req->challengeSize); + i += OPAQUE16_LEN; - // parsing attestation data - ato16(input, &req->dataSize); - input += OPAQUE16_LEN; - if (length < OPAQUE16_LEN + req->typeSize + req->dataSize) { - ret = BUFFER_ERROR; - goto exit; - } + ato16(&input[i], &req->size); + i += OPAQUE16_LEN; - req->data = (void *) XMALLOC(req->dataSize, ssl->heap, DYNAMIC_TYPE_TLSX); - if (req->data == NULL) { - ret = MEMORY_ERROR; - goto exit; - } - XMEMCPY(req->data, input, req->dataSize); - input += req->dataSize; + // data field + if (i + req->size < length) { + ret = BUFFER_ERROR; + goto exit; + } + req->data = XMALLOC(req->size, ssl->heap, DYNAMIC_TYPE_TLSX); + if (!req->data) { + ret = MEMORY_ERROR; + goto exit; + } + XMEMCPY(req->data, &input[i], req->size); + i += req->size; - ssl->attestationRequest = req; - } else { +#ifdef DEBUG_WOLFSSL + if (i != length) { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); ret = SANITY_MSG_E; } +#endif exit: WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", ret); @@ -2060,23 +2058,23 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { WOLFSSL_ENTER("TLSX_AttestationRequest_GetSize"); word16 len = 0; + len += OPAQUE64_LEN; // nonce field len += OPAQUE16_LEN; // challengeSize field - len += OPAQUE16_LEN; // typeSize field itself - len += req->typeSize; - len += OPAQUE16_LEN; // dataSize field itself - len += req->dataSize; + len += OPAQUE8_LEN; // size field + len += req->size; // type/attestation data WOLFSSL_LEAVE("TLSX_AttestationRequest_GetSize", len); return len; } int GenerateAttestation(WOLFSSL *ssl) { - int ret; + int ret = 0; unsigned char *c = NULL; byte *att = NULL; WOLFSSL_ENTER("GenerateAttestation"); - if (ssl == NULL || ssl->attestationRequest == NULL || ssl->generateAttestation == NULL || !wolfSSL_is_server(ssl)) { + if (!ssl || !ssl->attestationRequest || !ssl->generateAttestation || !wolfSSL_is_server(ssl) || + !ssl->attestationRequest->is_request) { ret = BAD_FUNC_ARG; goto exit; } @@ -2084,46 +2082,34 @@ int GenerateAttestation(WOLFSSL *ssl) { // attestation challenge token const ATT_REQUEST *req = ssl->attestationRequest; c = XMALLOC(req->challengeSize, ssl->heap, DYNAMIC_TYPE_TLSX); - if (c == NULL) { + if (!c) { ret = MEMORY_ERROR; goto exit; } - // generate challenge - // TODO: context data must be explicitly sent inside the attestation_request or saved into the SSL struct -// if (req->dataSize != 0) { -// ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, -// req->data, req->dataSize, TRUE); -// } else { - ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, NULL, - 0, FALSE); -// } - if (ret == WOLFSSL_SUCCESS) { - ret = 0; - } else { + // generate challenge and convert result + if (wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, + (const unsigned char *) &req->nonce, OPAQUE64_LEN, TRUE) != WOLFSSL_SUCCESS) { ret = ATTESTATION_KEYING_E; goto exit; } // attestation certificate att = XMALLOC(ATT_BUFFER_SIZE, ssl->heap, DYNAMIC_TYPE_TLSX); - if (att == NULL) { + if (!att) { ret = MEMORY_ERROR; goto exit; } - int attLen = ssl->generateAttestation(ssl->attestationRequest, c, req->challengeSize, att); - if (attLen == 0) { + int attSize = ssl->generateAttestation(ssl->attestationRequest, c, req->challengeSize, att); + if (attSize < 0) { ret = ATTESTATION_GENERATION_E; goto exit; } - ATT_REQUEST att_req_resp = {.challengeSize = req->challengeSize, .typeSize = req->typeSize, .type = req->type, .dataSize = attLen, .data = att,}; + ATT_REQUEST response = {.is_request = FALSE, .nonce = req->nonce, .challengeSize = req->challengeSize, .size = attSize, .data = att,}; - ret = TLSX_UseAttestationRequest(&ssl->extensions, &att_req_resp, ssl->heap, TRUE); - if (ret == WOLFSSL_SUCCESS) { - ret = 0; - } else { + if (TLSX_UseAttestationRequest(&ssl->extensions, &response, ssl->heap, TRUE) != WOLFSSL_SUCCESS) { ret = WOLFSSL_FATAL_ERROR; } // extension gets copied, so it's free to clear below buffers now @@ -2148,11 +2134,12 @@ int GenerateAttestation(WOLFSSL *ssl) { * @see WOLFSSL->verifyAttestation() */ int VerifyAttestation(WOLFSSL *ssl) { - int ret; + int ret = 0; unsigned char *c = NULL; WOLFSSL_ENTER("VerifyAttestation"); - if (!ssl || !ssl->attestationRequest || !ssl->verifyAttestation || wolfSSL_is_server(ssl)) { + if (!ssl || !ssl->attestationRequest || !ssl->verifyAttestation || wolfSSL_is_server(ssl) || + ssl->attestationRequest->is_request) { ret = BAD_FUNC_ARG; goto exit; } @@ -2166,17 +2153,8 @@ int VerifyAttestation(WOLFSSL *ssl) { } // generate challenge - // TODO: context data must be explicitly sent inside the attestation_request or saved into the SSL struct -// if (req->dataSize != 0) { -// ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, -// req->data, req->dataSize, TRUE); -// } else { - ret = wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, NULL, - 0, FALSE); -// } - if (ret == WOLFSSL_SUCCESS) { - ret = 0; - } else { + if (wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, + (const unsigned char *) &req->nonce, OPAQUE64_LEN, TRUE) != WOLFSSL_SUCCESS) { ret = ATTESTATION_KEYING_E; goto exit; } diff --git a/wolfssl/internal.h b/wolfssl/internal.h index d39ecdb6fee..b271b5828ee 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -5540,7 +5540,7 @@ struct WOLFSSL { * @param c the challenge * @param cLen the challenge length * @param output the output buffer for the generated attestation - * @return number of written bytes. 0 if unsuccessful. + * @return number of written bytes. Negative number if unsuccessful. */ int (*generateAttestation)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output); #endif /* HAVE_REMOTE_ATTESTATION */ diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 0fee71a1b44..9aacdd48d1b 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3670,19 +3670,24 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); // TODO: WIP definitions /** - * Attestation Request + * Attestation Request data type. */ typedef struct ATT_REQUEST { - /** The required length for the attestation challenge */ - // TODO: This should be fixed size perhaps + /** Is this union a request or a response (from either client or server) */ + word8 is_request; + /** The nonce for challenge generation */ + word64 nonce; + /** The challenge size required for attestation verification */ + // TODO: This could be fixed size if the types are well-defined and have well-defined challenge sizes. + // However, this would need to be managed by IANA, e.g. + // The type can then also be a simple enumeration for further simplicity. word16 challengeSize; - /** The attestation type size */ - word16 typeSize; - /** The attestation type */ - void *type; - /** The attestation data size */ - word16 dataSize; - /** The attestation data */ + /** The .data size */ + word16 size; + /** + * If request: attestation type + * If response: attestation certificate + */ void *data; } ATT_REQUEST; @@ -3698,11 +3703,10 @@ WOLFSSL_API void wolfSSL_AttestationRequest_print(XFILE fp, const ATT_REQUEST *r * Prints an attestation request to the given file. * @param fp The FILE pointer to print to * @param req The attestation request to print - * @param typeIsStr Whether the attestation type should be printed as a string - * @param dataIsStr Whether the attestation data should be printed as a string + * @param dataIsStr Whether the attestation type / certificate should be printed as a string * @see wolfSSL_AttestationRequest_print */ -WOLFSSL_API void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte typeIsStr, byte dataIsStr); +WOLFSSL_API void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte dataIsStr); /** * Attestation Request extension. @@ -3733,7 +3737,7 @@ WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(cons * @param genAtt The attestation generator. * Takes an attestation request, a challenge, a challenge length and a buffer for generated * attestation data as arguments. - * Must return number of written bytes.0 if unsuccessful. + * Must return number of written bytes. Negative number if unsuccessful. * * @return SSL_SUCCESS if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. */ From fff0acbd176fe3ac8fe46a038c12d05d00817f1a Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Mon, 5 Jun 2023 15:55:56 +0800 Subject: [PATCH 040/391] fix: bugs --- src/tls.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/tls.c b/src/tls.c index 33523e1ba5f..2e32669d111 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1958,7 +1958,7 @@ static word16 TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output word16 i = 0; - if (!req) { + if (!req || !req->data) { WOLFSSL_LEAVE("TLSX_AttestationRequest_Write", BAD_FUNC_ARG); return BAD_FUNC_ARG; } @@ -1969,7 +1969,7 @@ static word16 TLSX_AttestationRequest_Write(const ATT_REQUEST *req, byte *output return SANITY_MSG_E; } - c64toa((const w64wrapper *) req->nonce, &output[i]); + c64toa((const w64wrapper *) &req->nonce, &output[i]); i += OPAQUE64_LEN; c16toa(req->challengeSize, &output[i]); @@ -2018,7 +2018,7 @@ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 } ATT_REQUEST *req = XMALLOC(sizeof(ATT_REQUEST), ssl->heap, DYNAMIC_TYPE_TLSX); - req->is_request = !wolfSSL_is_server(ssl); + req->is_request = wolfSSL_is_server(ssl); ato64(&input[i], (w64wrapper *) &req->nonce); i += OPAQUE64_LEN; @@ -2046,9 +2046,12 @@ static int TLSX_AttestationRequest_Parse(WOLFSSL *ssl, const byte *input, word16 if (i != length) { WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); ret = SANITY_MSG_E; + goto exit; } #endif + ssl->attestationRequest = req; + exit: WOLFSSL_LEAVE("TLSX_AttestationRequest_Parse", ret); return ret; @@ -2060,7 +2063,7 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { len += OPAQUE64_LEN; // nonce field len += OPAQUE16_LEN; // challengeSize field - len += OPAQUE8_LEN; // size field + len += OPAQUE16_LEN; // size field len += req->size; // type/attestation data WOLFSSL_LEAVE("TLSX_AttestationRequest_GetSize", len); From 329e4a471adc5c6682c12725e17230d118e6779f Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Wed, 7 Jun 2023 14:41:26 +0800 Subject: [PATCH 041/391] feat: remove superfluous challengeSize parameter It can be inferred from the given ATT_REQUEST struct --- src/ssl.c | 4 ++-- src/tls.c | 28 ++++++++++++++-------------- wolfssl/internal.h | 10 ++++------ wolfssl/ssl.h | 11 ++++++----- 4 files changed, 26 insertions(+), 27 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 0234682d7b1..2a95854cf70 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3519,7 +3519,7 @@ int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUEST *req) { } }*/ -int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c, word16 cLen)) { +int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c)) { if (ssl == NULL || verifyAtt == NULL) { return BAD_FUNC_ARG; } @@ -3531,7 +3531,7 @@ int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUES return SSL_SUCCESS; } -int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output)) { +int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, byte *output)) { if (ssl == NULL || genAtt == NULL) { return BAD_FUNC_ARG; } diff --git a/src/tls.c b/src/tls.c index 2e32669d111..786282f1898 100644 --- a/src/tls.c +++ b/src/tls.c @@ -2073,7 +2073,7 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { int GenerateAttestation(WOLFSSL *ssl) { int ret = 0; unsigned char *c = NULL; - byte *att = NULL; + byte *att_buffer = NULL; WOLFSSL_ENTER("GenerateAttestation"); if (!ssl || !ssl->attestationRequest || !ssl->generateAttestation || !wolfSSL_is_server(ssl) || @@ -2098,19 +2098,19 @@ int GenerateAttestation(WOLFSSL *ssl) { } // attestation certificate - att = XMALLOC(ATT_BUFFER_SIZE, ssl->heap, DYNAMIC_TYPE_TLSX); - if (!att) { + att_buffer = XMALLOC(ATT_BUFFER_SIZE, ssl->heap, DYNAMIC_TYPE_TLSX); + if (!att_buffer) { ret = MEMORY_ERROR; goto exit; } - int attSize = ssl->generateAttestation(ssl->attestationRequest, c, req->challengeSize, att); + int attSize = ssl->generateAttestation(ssl->attestationRequest, c, att_buffer); if (attSize < 0) { ret = ATTESTATION_GENERATION_E; goto exit; } - ATT_REQUEST response = {.is_request = FALSE, .nonce = req->nonce, .challengeSize = req->challengeSize, .size = attSize, .data = att,}; + ATT_REQUEST response = {.is_request = FALSE, .nonce = req->nonce, .challengeSize = req->challengeSize, .size = attSize, .data = att_buffer,}; if (TLSX_UseAttestationRequest(&ssl->extensions, &response, ssl->heap, TRUE) != WOLFSSL_SUCCESS) { ret = WOLFSSL_FATAL_ERROR; @@ -2121,8 +2121,8 @@ int GenerateAttestation(WOLFSSL *ssl) { if (c) { XFREE(c, ssl->heap, DYNAMIC_TYPE_TLSX); } - if (att) { - XFREE(att, ssl->heap, DYNAMIC_TYPE_TLSX); + if (att_buffer) { + XFREE(att_buffer, ssl->heap, DYNAMIC_TYPE_TLSX); } WOLFSSL_LEAVE("GenerateAttestation", ret); @@ -2138,7 +2138,7 @@ int GenerateAttestation(WOLFSSL *ssl) { */ int VerifyAttestation(WOLFSSL *ssl) { int ret = 0; - unsigned char *c = NULL; + unsigned char *challenge_buffer = NULL; WOLFSSL_ENTER("VerifyAttestation"); if (!ssl || !ssl->attestationRequest || !ssl->verifyAttestation || wolfSSL_is_server(ssl) || @@ -2149,24 +2149,24 @@ int VerifyAttestation(WOLFSSL *ssl) { // attestation challenge token const ATT_REQUEST *req = ssl->attestationRequest; - c = XMALLOC(req->challengeSize, ssl->heap, DYNAMIC_TYPE_TLSX); - if (!c) { + challenge_buffer = XMALLOC(req->challengeSize, ssl->heap, DYNAMIC_TYPE_TLSX); + if (!challenge_buffer) { ret = MEMORY_ERROR; goto exit; } // generate challenge - if (wolfSSL_export_keying_material(ssl, c, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, + if (wolfSSL_export_keying_material(ssl, challenge_buffer, req->challengeSize, ATT_CHALLENGE_LABEL, ATT_CHALLENGE_LABEL_LEN, (const unsigned char *) &req->nonce, OPAQUE64_LEN, TRUE) != WOLFSSL_SUCCESS) { ret = ATTESTATION_KEYING_E; goto exit; } - ret = ssl->verifyAttestation(req, c, req->challengeSize); + ret = ssl->verifyAttestation(req, challenge_buffer); exit: - if (c) { - XFREE(c, ssl->heap, DYNAMIC_TYPE_TLSX); + if (challenge_buffer) { + XFREE(challenge_buffer, ssl->heap, DYNAMIC_TYPE_TLSX); } WOLFSSL_LEAVE("VerifyAttestation", ret); diff --git a/wolfssl/internal.h b/wolfssl/internal.h index b271b5828ee..1723a15bdd3 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -5527,22 +5527,20 @@ struct WOLFSSL { /** For attestation verification. * * @param att the attestation data - * @param c the challenge - * @param cLen the challenge length + * @param c the challenge (att.challengeSize) * @return 0 on success */ - int (*verifyAttestation)(const ATT_REQUEST *att, const byte *c, word16 cLen); + int (*verifyAttestation)(const ATT_REQUEST *att, const byte *c); ATT_REQUEST *attestationRequest; /** * For attestation generation. * * @param req the attestation request - * @param c the challenge - * @param cLen the challenge length + * @param c the challenge (att.challengeSize) * @param output the output buffer for the generated attestation * @return number of written bytes. Negative number if unsuccessful. */ - int (*generateAttestation)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output); + int (*generateAttestation)(const ATT_REQUEST *req, const byte *c, byte *output); #endif /* HAVE_REMOTE_ATTESTATION */ }; diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 9aacdd48d1b..29591d17a69 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3723,25 +3723,26 @@ WOLFSSL_API int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUE * * @param ssl The SSL session * @param verifyAtt The attestation verify callback. - * Takes attestation data, a challenge and a challenge length as arguments. + * Takes attestation data and a challenge as arguments. + * The challenge length is inferred by the attestation field `challengeSize`. * Must return 0 on success. * * @return SSL_SUCCESS if client, SIDE_ERROR if server, and BAD_FUNC_ARG if any param is NULL. */ -WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c, word16 cLen)); +WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c)); /** * Sets the callback for attestation generation on 'server' side. * * @param ssl The SSL session * @param genAtt The attestation generator. - * Takes an attestation request, a challenge, a challenge length and a buffer for generated - * attestation data as arguments. + * Takes an attestation request, a challenge, and a buffer for generated attestation data as arguments. + * The challenge length is inferred by the attestation field `challengeSize`. * Must return number of written bytes. Negative number if unsuccessful. * * @return SSL_SUCCESS if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. */ -WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, word16 cLen, byte *output)); +WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, byte *output)); /** * Returns a received attestation request. From d6be87aec91359a31d8af662f5cb7e760a1a1194 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Thu, 8 Jun 2023 11:20:09 +0800 Subject: [PATCH 042/391] fix: missing newline for print --- src/ssl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ssl.c b/src/ssl.c index 2a95854cf70..359621a5047 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3467,7 +3467,7 @@ void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte } fprintf(fp, "Attestation Request:\n"); - fprintf(fp, " Request: %d", req->is_request); + fprintf(fp, " Request: %d\n", req->is_request); fprintf(fp, " Nonce: 0x%lX\n", req->nonce); fprintf(fp, " Challenge Size: %d\n", req->challengeSize); if (req->is_request) { From d743b7cb17c207edc548a23a05d93a70991a4a7e Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Thu, 8 Jun 2023 11:24:56 +0800 Subject: [PATCH 043/391] fix: missing size in print --- src/ssl.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ssl.c b/src/ssl.c index 359621a5047..29e2463c635 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3471,8 +3471,10 @@ void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST *req, byte fprintf(fp, " Nonce: 0x%lX\n", req->nonce); fprintf(fp, " Challenge Size: %d\n", req->challengeSize); if (req->is_request) { + fprintf(fp, " Type Size: %d\n", req->size); fprintf(fp, " Type : %s", dataIsStr ? "" : "0x"); } else { + fprintf(fp, " Attestation Size: %d\n", req->size); fprintf(fp, " Attestation : %s", dataIsStr ? "" : "0x"); } byte *type = req->data; From d41b01ae4264c7a19f0094860996428b2540fe4c Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 9 Jun 2023 15:01:37 +0800 Subject: [PATCH 044/391] misc changes, forgot already --- src/tls.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/tls.c b/src/tls.c index 786282f1898..eb06c28cc6a 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1926,7 +1926,7 @@ int TLSX_UseAttestationRequest(TLSX **extensions, const ATT_REQUEST *req, void * return MEMORY_ERROR; } - int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, (void *) req_cpy, heap); + int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, req_cpy, heap); if (ret != 0) { TLSX_AttestationRequest_FreeAll(req_cpy, heap); return ret; @@ -2072,7 +2072,7 @@ static word16 TLSX_AttestationRequest_GetSize(const ATT_REQUEST *req) { int GenerateAttestation(WOLFSSL *ssl) { int ret = 0; - unsigned char *c = NULL; + byte *c = NULL; byte *att_buffer = NULL; WOLFSSL_ENTER("GenerateAttestation"); @@ -2104,18 +2104,19 @@ int GenerateAttestation(WOLFSSL *ssl) { goto exit; } - int attSize = ssl->generateAttestation(ssl->attestationRequest, c, att_buffer); + const int attSize = ssl->generateAttestation(ssl->attestationRequest, c, att_buffer); if (attSize < 0) { ret = ATTESTATION_GENERATION_E; goto exit; } - ATT_REQUEST response = {.is_request = FALSE, .nonce = req->nonce, .challengeSize = req->challengeSize, .size = attSize, .data = att_buffer,}; + const ATT_REQUEST response = {.is_request = FALSE, .nonce = req->nonce, .challengeSize = req->challengeSize, .size = attSize, .data = att_buffer,}; - if (TLSX_UseAttestationRequest(&ssl->extensions, &response, ssl->heap, TRUE) != WOLFSSL_SUCCESS) { - ret = WOLFSSL_FATAL_ERROR; + if ((ret = wolfSSL_AttestationRequest(ssl, &response)) == WOLFSSL_SUCCESS) { + // reset to 0 as WOLFSSL_SUCCESS is not zero + ret = 0; } - // extension gets copied, so it's free to clear below buffers now + // extension data gets copied, so it's free to clear below buffers now exit: if (c) { From 060efcd426355aac24a1ffaaaa84c48970634c8b Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 16 Jun 2023 12:18:32 +0800 Subject: [PATCH 045/391] chore: refactor function types and constants for RA --- src/ssl.c | 18 ++---------------- src/tls.c | 4 ---- wolfssl/internal.h | 18 ++---------------- wolfssl/ssl.h | 47 ++++++++++++++++++++++++++++------------------ 4 files changed, 33 insertions(+), 54 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 29e2463c635..e8c0275590f 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3498,20 +3498,6 @@ int wolfSSL_AttestationRequest(WOLFSSL *ssl, const ATT_REQUEST *req) { return ret; } -int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUEST *req) { - int ret; - WOLFSSL_ENTER("wolfSSL_CTX_AttestationRequest"); - - if (ctx == NULL) { - ret = BAD_FUNC_ARG; - } else { - ret = TLSX_UseAttestationRequest(&ctx->extensions, req, ctx->heap, ctx->method->side == WOLFSSL_SERVER_END); - } - - WOLFSSL_LEAVE("wolfSSL_CTX_AttestationRequest", ret); - return ret; -} - /*void *wolfSSL_GetEvidence(WOLFSSL *ssl) { TLSX *ext = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); if (ext == NULL) { @@ -3521,7 +3507,7 @@ int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUEST *req) { } }*/ -int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c)) { +int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, VerifyAttCallback verifyAtt) { if (ssl == NULL || verifyAtt == NULL) { return BAD_FUNC_ARG; } @@ -3533,7 +3519,7 @@ int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUES return SSL_SUCCESS; } -int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, byte *output)) { +int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, GenAttCallback genAtt) { if (ssl == NULL || genAtt == NULL) { return BAD_FUNC_ARG; } diff --git a/src/tls.c b/src/tls.c index eb06c28cc6a..ee6d241eaf7 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1868,10 +1868,6 @@ int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz) #ifdef HAVE_REMOTE_ATTESTATION -#define ATT_CHALLENGE_LABEL "Remote Attestation" -#define ATT_CHALLENGE_LABEL_LEN strlen(ATT_CHALLENGE_LABEL) -#define ATT_BUFFER_SIZE 16384 - static void TLSX_AttestationRequest_FreeAll(ATT_REQUEST *req, void *heap) { (void) heap; diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 1723a15bdd3..2b02418bf18 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -5524,23 +5524,9 @@ struct WOLFSSL { WOLFSSL_EchConfig* echConfigs; #endif #ifdef HAVE_REMOTE_ATTESTATION - /** For attestation verification. - * - * @param att the attestation data - * @param c the challenge (att.challengeSize) - * @return 0 on success - */ - int (*verifyAttestation)(const ATT_REQUEST *att, const byte *c); ATT_REQUEST *attestationRequest; - /** - * For attestation generation. - * - * @param req the attestation request - * @param c the challenge (att.challengeSize) - * @param output the output buffer for the generated attestation - * @return number of written bytes. Negative number if unsuccessful. - */ - int (*generateAttestation)(const ATT_REQUEST *req, const byte *c, byte *output); + VerifyAttCallback verifyAttestation; + GenAttCallback generateAttestation; #endif /* HAVE_REMOTE_ATTESTATION */ }; diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 29591d17a69..bda5f22129a 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3669,6 +3669,10 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); #ifdef HAVE_REMOTE_ATTESTATION // TODO: WIP definitions +#define ATT_CHALLENGE_LABEL "Remote Attestation" +#define ATT_CHALLENGE_LABEL_LEN strlen(ATT_CHALLENGE_LABEL) +#define ATT_BUFFER_SIZE 16384 + /** * Attestation Request data type. */ @@ -3691,6 +3695,26 @@ typedef struct ATT_REQUEST { void *data; } ATT_REQUEST; +/** + * The attestation generation callback. + * + * @param req The attestation request to generate data from + * @param c The challenge (from TLS-exporter) to create a fresh attestation certificate. + * Its length can be inferred by the attestation field `challengeSize`. + * @param output The output buffer to store the attestation data. + * Its length is `ATT_BUFFER_SIZE`: + * @return Must be number of written bytes. Negative number if unsuccessful. + */ +typedef int (*GenAttCallback)(const ATT_REQUEST *req, const byte *c, byte *output); +/** + * The attestation verify callback. + * @param att The attestation-/certificate data + * @param c The re-created challenge used for the attestation + * Its length can be inferred by the attestation field `challengeSize`. + * @return Must be 0 on success. + */ +typedef int (*VerifyAttCallback)(const ATT_REQUEST *att, const byte *c); + /** * Prints an attestation request to the given file. * @param fp The FILE pointer to print to @@ -3713,43 +3737,30 @@ WOLFSSL_API void wolfSSL_AttestationRequest_print_ex(XFILE fp, const ATT_REQUEST */ WOLFSSL_API int wolfSSL_AttestationRequest(WOLFSSL *ssl, const ATT_REQUEST *req); -/** - * Attestation Request extension. - */ -WOLFSSL_API int wolfSSL_CTX_AttestationRequest(WOLFSSL_CTX *ctx, const ATT_REQUEST *req); - /** * Sets the callback for attestation verification on 'client' side. * * @param ssl The SSL session * @param verifyAtt The attestation verify callback. - * Takes attestation data and a challenge as arguments. - * The challenge length is inferred by the attestation field `challengeSize`. - * Must return 0 on success. - * - * @return SSL_SUCCESS if client, SIDE_ERROR if server, and BAD_FUNC_ARG if any param is NULL. + * @return SSL_SUCCESS if client, SIDE_ERROR if server, and BAD_FUNC_ARG if any param is NULL. */ -WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, int (*verifyAtt)(const ATT_REQUEST *att, const byte *c)); +WOLFSSL_API int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, VerifyAttCallback verifyAtt); /** * Sets the callback for attestation generation on 'server' side. * * @param ssl The SSL session * @param genAtt The attestation generator. - * Takes an attestation request, a challenge, and a buffer for generated attestation data as arguments. - * The challenge length is inferred by the attestation field `challengeSize`. - * Must return number of written bytes. Negative number if unsuccessful. - * - * @return SSL_SUCCESS if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. + * @return SSL_SUCCESS if server, SIDE_ERROR if client, and BAD_FUNC_ARG if any param is NULL. */ -WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, int (*genAtt)(const ATT_REQUEST *req, const byte *c, byte *output)); +WOLFSSL_API int wolfSSL_SetGenerateAttestation(WOLFSSL *ssl, GenAttCallback genAtt); /** * Returns a received attestation request. * Will be NULL if not received. * * @param ssl The SSL session - * @return received attestation request. NULL if not present. + * @return received attestation request data. NULL if not present. */ WOLFSSL_API const ATT_REQUEST *wolfSSL_GetAttestationRequest(WOLFSSL *ssl); From 166307b33ff9e9a84c97b70c67a139e5c827add9 Mon Sep 17 00:00:00 2001 From: joeftiger <> Date: Fri, 16 Jun 2023 14:25:56 +0800 Subject: [PATCH 046/391] fix: TLS Exporter labels must start with EXPORTER --- wolfssl/ssl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index bda5f22129a..bb4743b764e 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -3669,7 +3669,7 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); #ifdef HAVE_REMOTE_ATTESTATION // TODO: WIP definitions -#define ATT_CHALLENGE_LABEL "Remote Attestation" +#define ATT_CHALLENGE_LABEL "EXPORTER: Remote Attestation" #define ATT_CHALLENGE_LABEL_LEN strlen(ATT_CHALLENGE_LABEL) #define ATT_BUFFER_SIZE 16384 From c24c0cda3d67c68c7ac54c36e66ac91c7ea72c89 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Tue, 20 Jun 2023 14:14:03 +0800 Subject: [PATCH 047/391] chore: remove unneeded includes and code --- src/internal.c | 1 - src/ssl.c | 9 --------- src/tls.c | 2 -- wolfssl/error-ssl.h | 3 ++- 4 files changed, 2 insertions(+), 13 deletions(-) diff --git a/src/internal.c b/src/internal.c index 43620f6d5c3..c1f03e39821 100644 --- a/src/internal.c +++ b/src/internal.c @@ -21,7 +21,6 @@ -#include "wolfssl/wolfcrypt/error-crypt.h" #ifdef HAVE_CONFIG_H #include #endif diff --git a/src/ssl.c b/src/ssl.c index e8c0275590f..1b5059437ec 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -3498,15 +3498,6 @@ int wolfSSL_AttestationRequest(WOLFSSL *ssl, const ATT_REQUEST *req) { return ret; } -/*void *wolfSSL_GetEvidence(WOLFSSL *ssl) { - TLSX *ext = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); - if (ext == NULL) { - return NULL; - } else { - return ext->data; - } -}*/ - int wolfSSL_SetVerifyAttestation(WOLFSSL *ssl, VerifyAttCallback verifyAtt) { if (ssl == NULL || verifyAtt == NULL) { return BAD_FUNC_ARG; diff --git a/src/tls.c b/src/tls.c index ee6d241eaf7..639a06ba12d 100644 --- a/src/tls.c +++ b/src/tls.c @@ -21,8 +21,6 @@ -#include "wolfssl/wolfcrypt/error-crypt.h" -#include "wolfssl/wolfcrypt/logging.h" #ifdef HAVE_CONFIG_H #include #endif diff --git a/wolfssl/error-ssl.h b/wolfssl/error-ssl.h index b0466dd1f16..d8c0a87e583 100644 --- a/wolfssl/error-ssl.h +++ b/wolfssl/error-ssl.h @@ -196,7 +196,8 @@ enum wolfSSL_ErrorCodes { /* add strings to wolfSSL_ERR_reason_error_string in internal.c !!!!! */ ATTESTATION_KEYING_E = -606, /* TLS-Exporter error during attestation keying */ - ATTESTATION_GENERATION_E = -607 /* attestation generation error */ + ATTESTATION_GENERATION_E = -607, /* attestation generation error */ + ATTESTATION_TYPE_SUPPORT_E = -608, /* unsupported attestation type error */ /* add strings to wolfSSL_ERR_reason_error_string in internal.c !!!!! */ /* no error strings go down here, add above negotiation errors !!!! */ From c45670073c8db12047912c716c8f2124ebf6abf7 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Tue, 20 Jun 2023 14:25:47 +0800 Subject: [PATCH 048/391] feat: send alert on unsupported attestation type --- src/internal.c | 9 ++++++--- src/tls.c | 4 ++++ src/tls13.c | 6 +++++- wolfssl/internal.h | 2 +- wolfssl/ssl.h | 6 ++++-- 5 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/internal.c b/src/internal.c index c1f03e39821..696f515ac0f 100644 --- a/src/internal.c +++ b/src/internal.c @@ -18734,9 +18734,9 @@ const char* AlertTypeToString(int type) return bad_certificate_status_response_str; } - case unsupported_evidence: + case unsupported_attestation: { - static const char unsupported_evidence_str[] = "unsupported_evidence"; + static const char unsupported_evidence_str[] = "unsupported_attestation"; return unsupported_evidence_str; } @@ -23552,7 +23552,10 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) return "Keying Binder error in attestation generation"; case ATTESTATION_GENERATION_E: - return "Attestation generation error in custom function"; + return "Attestation generation error in custom VerifyAttCallback"; + + case ATTESTATION_TYPE_SUPPORT_E: + return "Attestation type not supported"; default : return "unknown error number"; diff --git a/src/tls.c b/src/tls.c index 639a06ba12d..08e45a49b8a 100644 --- a/src/tls.c +++ b/src/tls.c @@ -2099,6 +2099,10 @@ int GenerateAttestation(WOLFSSL *ssl) { } const int attSize = ssl->generateAttestation(ssl->attestationRequest, c, att_buffer); + if (attSize == ATTESTATION_TYPE_SUPPORT_E) { + ret = ATTESTATION_TYPE_SUPPORT_E; + goto exit; + } if (attSize < 0) { ret = ATTESTATION_GENERATION_E; goto exit; diff --git a/src/tls13.c b/src/tls13.c index 2c40e842914..3502d9a3659 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -88,6 +88,7 @@ * Default behavior is to return a signed 64-bit value. */ +#include "wolfssl/ssl.h" #ifdef HAVE_CONFIG_H #include #endif @@ -7082,7 +7083,10 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) // and before writing encrypted extensions. if (ssl->attestationRequest) { if ((ret = GenerateAttestation(ssl)) != 0) { - WOLFSSL_MSG("Attestation Generation failed"); + if (ret == ATTESTATION_TYPE_SUPPORT_E) { + SendAlert(ssl, alert_fatal, unsupported_attestation); + WOLFSSL_ERROR_VERBOSE(ATTESTATION_TYPE_SUPPORT_E); + } return ret; } } diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 2b02418bf18..5b949ad8e74 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2746,7 +2746,7 @@ WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type, * Generates an attestation certificate from the user-defined callback seeded by a challenge created by the TLS-Exporter. * * @param ssl The SSL/TLS object - * @return 0 on success. Any other value indicates an error. + * @return 0 on success. ATTESTATION_TYPE_SUPPORT_E on unsupported attestation type. Any other value indicates an error. * @see WOLFSSL->generateAttestation() */ WOLFSSL_LOCAL int GenerateAttestation(WOLFSSL *ssl); diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index bb4743b764e..a6cc8ff5c11 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -763,7 +763,7 @@ enum AlertDescription { bad_certificate_status_response = 113, /**< RFC 6066, section 8 */ unknown_psk_identity = 115, /**< RFC 4279, section 2 */ certificate_required = 116, /**< RFC 8446, section 8.2 */ - unsupported_evidence = 118, /**< remote attestation, arbitrary value for now */ + unsupported_attestation = 118, /**< remote attestation, arbitrary value for now */ no_application_protocol = 120 }; @@ -3703,7 +3703,9 @@ typedef struct ATT_REQUEST { * Its length can be inferred by the attestation field `challengeSize`. * @param output The output buffer to store the attestation data. * Its length is `ATT_BUFFER_SIZE`: - * @return Must be number of written bytes. Negative number if unsuccessful. + * @return Must be number of written bytes. + * ATTESTATION_TYPE_SUPPORT_E if attestation type is unsupported (needed to send alert). + * Any other negative number indicates other failure type */ typedef int (*GenAttCallback)(const ATT_REQUEST *req, const byte *c, byte *output); /** From 9b4a93488913f70764aad71c8ff09632a89fc5ae Mon Sep 17 00:00:00 2001 From: joeftiger Date: Tue, 20 Jun 2023 19:05:48 +0800 Subject: [PATCH 049/391] fix: too high TLSX value leads to segfault in semaphore --- wolfssl/internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 5b949ad8e74..4e5d5055ce5 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2609,7 +2609,7 @@ typedef enum { #endif #endif #ifdef HAVE_REMOTE_ATTESTATION - TLSX_ATTESTATION_REQUEST = 0xAA00, /* remote attestation, arbitrary number for now */ + TLSX_ATTESTATION_REQUEST = 0x0040, /* remote attestation, arbitrary number for now */ #endif TLSX_RENEGOTIATION_INFO = 0xff01, #ifdef WOLFSSL_QUIC From 67130fa082670abe87dddd8413de796885143d50 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Tue, 20 Jun 2023 19:49:09 +0800 Subject: [PATCH 050/391] trying to make ECH work... wolfSSL with their missing documentation certainly doesn't help. --- CMakeLists.txt | 102 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 67 insertions(+), 35 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3f52b50a010..a45f5a8079e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -353,41 +353,6 @@ if(NOT WOLFSSL_RNG) list(APPEND WOLFSSL_DEFINITIONS "-DWC_NO_RNG") endif() -# Keying Material Exporter. Used by Remote Attestation -# TODO: Make disabled by default. This is for testing only for now. -add_option("WOLFSSL_KEYING_MATERIAL" - "Enable wolfSSL keying material export (default: enabled)" - "yes" "yes;no") - -if(WOLFSSL_KEYING_MATERIAL) - list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_KEYING_MATERIAL") -endif() - -# Remote Attestation -# TODO: Make disabled by default. This is for testing only for now. -add_option("WOLFSSL_REMOTE_ATTESTATION" - "Enable wolfSSL remote attestation (default: enabled)" - "yes" "yes;no") - -if(WOLFSSL_REMOTE_ATTESTATION) - if(NOT WOLFSSL_TLS13) - message(FATAL_ERROR "Remote Attestation supported only for TLSv1.3") - endif() - if(NOT WOLFSSL_KEYING_MATERIAL) - message(FATAL_ERROR "Remote Attestation supported only with Keying Material Exporter") - endif() - - # TODO: Include proper checks for features. I will hardcode them for now. - list(APPEND WOLFSSL_DEFINITIONS - "-DWOLFSSL_ASN_TEMPLATE" - "-DWOLFSSL_CERT_GEN" - "-DWOLFSSL_KEY_GEN" - "-DWOLFSSL_CUSTOM_OID" - "-DHAVE_OID_ENCODING" - "-DWOLFSSL_CERT_EXT" - "-DHAVE_REMOTE_ATTESTATION") -endif() - # TODO: - DTLS-SCTP # - DTLS multicast # - OpenSSH @@ -1733,6 +1698,73 @@ if(WOLFSSL_SYS_CA_CERTS) endif() endif() +### START ### Remote Attestation and its dependencies + +# Hybrid Public Key Encryption (RFC9180) +add_option("WOLFSSL_HPKE" + "Enable wolfSSL hybrid public key encryption (default: disabled)" + "no" "yes;no") + +if(WOLFSSL_HPKE) + if(NOT WOLFSSL_ECC) + message(FATAL_ERROR "HPKE supported only with ECC (WOLFSSL_ECC)") + endif() + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_HPKE") +endif() + +# Encrypted Client Hello (ECH) +add_option("WOLFSSL_ECH" + "Enable wolfSSL encrypted client hello (default: disabled)" + "no" "yes;no") + +if(WOLFSSL_ECH) + if(NOT WOLFSSL_HPKE) + message(FATAL_ERROR "ECH supported only with HPKE (WOLFSSL_HPKE)") + endif() + if(NOT WOLFSSL_SNI) + message(FATAL_ERROR "ECH supported only with SNI (WOLFSSL_SNI)") + endif() + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_ECH") +endif() + +# Keying Material Exporter / TLS Exporter +add_option("WOLFSSL_KEYING_MATERIAL" + "Enable wolfSSL keying material export (default: disabled)" + "no" "yes;no") + +if(WOLFSSL_KEYING_MATERIAL) + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_KEYING_MATERIAL") +endif() + +# Remote Attestation +add_option("WOLFSSL_REMOTE_ATTESTATION" + "Enable wolfSSL remote attestation (default: disabled)" + "no" "yes;no") + +if(WOLFSSL_REMOTE_ATTESTATION) + if(NOT WOLFSSL_TLS13) + message(FATAL_ERROR "Remote Attestation supported only for TLSv1.3 (WOLFSSL_TLS13)") + endif() + if(NOT WOLFSSL_KEYING_MATERIAL) + message(FATAL_ERROR "Remote Attestation supported only with Keying Material Exporter (WOLFSSL_KEYING_MATERIAL)") + endif() + if(NOT WOLFSSL_ECH) + message(FATAL_ERROR "Remote Attestation supported only with Encrypted Client Hello (WOLFSSL_ECH)") + endif() + + # TODO: Include proper checks for features. I will hardcode them for now. + list(APPEND WOLFSSL_DEFINITIONS + "-DWOLFSSL_ASN_TEMPLATE" + "-DWOLFSSL_CERT_GEN" + "-DWOLFSSL_KEY_GEN" + "-DWOLFSSL_CUSTOM_OID" + "-DHAVE_OID_ENCODING" + "-DWOLFSSL_CERT_EXT" + "-DHAVE_REMOTE_ATTESTATION") +endif() + +### END ### Remote Attestation and its dependencies + # FLAGS operations if(WOLFSSL_AESCCM) From 9328aace773b45e23244fa276feff4d2f47b2838 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Tue, 20 Jun 2023 20:09:17 +0800 Subject: [PATCH 051/391] fix: remove semaphore calls Apparently it works without issue now (see playground). For whatever reason. --- src/tls.c | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/src/tls.c b/src/tls.c index 08e45a49b8a..54cb210d012 100644 --- a/src/tls.c +++ b/src/tls.c @@ -13001,9 +13001,6 @@ int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset) */ TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY)); #endif - #ifdef HAVE_REMOTE_ATTESTATION - TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); - #endif #endif /* WOLFSSL_TLS13 */ #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) @@ -13181,10 +13178,6 @@ int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength) #ifdef WOLFSSL_DTLS_CID TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID)); #endif /* WOLFSSL_DTLS_CID */ -#ifdef HAVE_REMOTE_ATTESTATION - // TODO: Needed? - TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); -#endif break; #ifdef WOLFSSL_EARLY_DATA @@ -13207,10 +13200,10 @@ int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength) /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, * TLSX_SERVER_CERTIFICATE_TYPE */ -#ifdef HAVE_REMOTE_ATTESTATION - // TODO: Needed? - TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); -#endif +//#ifdef HAVE_REMOTE_ATTESTATION +// // TODO: Needed? +// TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); +//#endif break; #endif #endif @@ -13331,10 +13324,6 @@ int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset #ifdef WOLFSSL_DTLS_CID TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID)); #endif /* WOLFSSL_DTLS_CID */ - #ifdef HAVE_REMOTE_ATTESTATION - // TODO: Needed? - TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); - #endif break; #ifdef WOLFSSL_EARLY_DATA @@ -13358,10 +13347,6 @@ int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, * TLSX_SERVER_CERTIFICATE_TYPE */ -#ifdef HAVE_REMOTE_ATTESTATION - // TODO: Needed? - TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_ATTESTATION_REQUEST)); -#endif break; #endif #endif From c861c71f2759ec6e62eb470a7c1f573f6f06c085 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Fri, 23 Jun 2023 15:31:35 +0800 Subject: [PATCH 052/391] fix: variable name for unsupported attestation --- src/internal.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/internal.c b/src/internal.c index 696f515ac0f..991309f7afe 100644 --- a/src/internal.c +++ b/src/internal.c @@ -18736,8 +18736,8 @@ const char* AlertTypeToString(int type) case unsupported_attestation: { - static const char unsupported_evidence_str[] = "unsupported_attestation"; - return unsupported_evidence_str; + static const char unsupported_attestation_str[] = "unsupported_attestation"; + return unsupported_attestation_str; } case no_application_protocol: From 23be61d8928150b1637dea760331fa332ea1f78a Mon Sep 17 00:00:00 2001 From: joeftiger Date: Fri, 23 Jun 2023 15:35:06 +0800 Subject: [PATCH 053/391] fix: unneeded include and comma --- src/tls13.c | 1 - wolfssl/error-ssl.h | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/tls13.c b/src/tls13.c index 3502d9a3659..15ef748a457 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -88,7 +88,6 @@ * Default behavior is to return a signed 64-bit value. */ -#include "wolfssl/ssl.h" #ifdef HAVE_CONFIG_H #include #endif diff --git a/wolfssl/error-ssl.h b/wolfssl/error-ssl.h index d8c0a87e583..4645de0d4a9 100644 --- a/wolfssl/error-ssl.h +++ b/wolfssl/error-ssl.h @@ -197,7 +197,7 @@ enum wolfSSL_ErrorCodes { ATTESTATION_KEYING_E = -606, /* TLS-Exporter error during attestation keying */ ATTESTATION_GENERATION_E = -607, /* attestation generation error */ - ATTESTATION_TYPE_SUPPORT_E = -608, /* unsupported attestation type error */ + ATTESTATION_TYPE_SUPPORT_E = -608 /* unsupported attestation type error */ /* add strings to wolfSSL_ERR_reason_error_string in internal.c !!!!! */ /* no error strings go down here, add above negotiation errors !!!! */ From 36ddfb19665335f18bdbd40fb622c0dfbdb87a21 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Fri, 23 Jun 2023 15:56:06 +0800 Subject: [PATCH 054/391] fix: change fatal error to warning --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a45f5a8079e..59967d713d3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1749,7 +1749,7 @@ if(WOLFSSL_REMOTE_ATTESTATION) message(FATAL_ERROR "Remote Attestation supported only with Keying Material Exporter (WOLFSSL_KEYING_MATERIAL)") endif() if(NOT WOLFSSL_ECH) - message(FATAL_ERROR "Remote Attestation supported only with Encrypted Client Hello (WOLFSSL_ECH)") + message(WARNING "Remote Attestation recommends Encrypted Client Hello (WOLFSSL_ECH)") endif() # TODO: Include proper checks for features. I will hardcode them for now. From 9afaef8d7fcf991eb31c0adb1f02218bd9d3e684 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Fri, 23 Jun 2023 15:56:21 +0800 Subject: [PATCH 055/391] feat: add Remote Attestation extension to configure file --- configure.ac | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/configure.ac b/configure.ac index 81f75b970f0..698c5e3816a 100644 --- a/configure.ac +++ b/configure.ac @@ -5157,6 +5157,20 @@ then AM_CFLAGS="$AM_CFLAGS -DHAVE_EXTENDED_MASTER" fi +# Remote Attestation Extension +AC_ARG_ENABLE([ra], + [AS_HELP_STRING([--enable-ra],[Enable wolfSSL Remote Attestation (default: disabled)])], + [ ENABLED_RA=$enableval ], + [ ENABLED_RA=no ] + ) +if test "$ENABLED_RA" = "yes" && test "$ENABLED_TLS13" = "yes" && test "$ENABLED_KEYING_MATERIAL" = "yes" +then + ENABLED_RA="yes" + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_REMOTE_ATTESTATION" +else + ENABLED_RA="no" +fi + # TLS Extensions AC_ARG_ENABLE([tlsx], [AS_HELP_STRING([--enable-tlsx],[Enable all TLS Extensions (default: disabled)])], @@ -8967,6 +8981,7 @@ echo " * Renegotiation Indication: $ENABLED_RENEGOTIATION_INDICATION" echo " * Secure Renegotiation: $ENABLED_SECURE_RENEGOTIATION" echo " * Fallback SCSV: $ENABLED_FALLBACK_SCSV" echo " * Keying Material Exporter: $ENABLED_KEYING_MATERIAL" +echo " * Remote Attestation: $ENABLED_RA" echo " * All TLS Extensions: $ENABLED_TLSX" echo " * PKCS#7: $ENABLED_PKCS7" echo " * S/MIME: $ENABLED_SMIME" From 823c8e5b37609d6c9f9774c6b677f55f24197916 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Fri, 23 Jun 2023 16:47:57 +0800 Subject: [PATCH 056/391] fix: compile flag for RA extension --- configure.ac | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index 698c5e3816a..1fa6355b809 100644 --- a/configure.ac +++ b/configure.ac @@ -5165,8 +5165,7 @@ AC_ARG_ENABLE([ra], ) if test "$ENABLED_RA" = "yes" && test "$ENABLED_TLS13" = "yes" && test "$ENABLED_KEYING_MATERIAL" = "yes" then - ENABLED_RA="yes" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_REMOTE_ATTESTATION" + AM_CFLAGS="$AM_CFLAGS -DHAVE_REMOTE_ATTESTATION" else ENABLED_RA="no" fi From 179acda891501e105ec0ec3545393574c930bfec Mon Sep 17 00:00:00 2001 From: joeftiger Date: Fri, 23 Jun 2023 16:53:08 +0800 Subject: [PATCH 057/391] fix: add missing header function --- wolfssl/internal.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 4e5d5055ce5..3d04130155a 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2760,6 +2760,16 @@ WOLFSSL_LOCAL int GenerateAttestation(WOLFSSL *ssl); */ WOLFSSL_LOCAL int VerifyAttestation(WOLFSSL *ssl); +/** + * Creates a copy of the given attestation request. + * (In order to have the memory managed by wolfSSL alone) + * + * @param req The request to clone + * @param heap The heap to use + * @return the pointer to the new clone (if successful) + */ +WOLFSSL_LOCAL ATT_REQUEST *TLSX_AttRequest_NewCopy(const ATT_REQUEST *req, void *heap); + WOLFSSL_LOCAL int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server); #endif From 1cccf660a5b84c0394ddd418cd167fa0163c679b Mon Sep 17 00:00:00 2001 From: Andras Fekete Date: Thu, 22 Jun 2023 10:12:37 -0400 Subject: [PATCH 058/391] Add 'Keying_material' option (cherry picked from commit e1f2c0bb2e79a808d9697a6cd943aa255dd03b3e) --- CMakeLists.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 59967d713d3..ddab15e481e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1810,6 +1810,14 @@ if(WOLFSSL_AESKEYWRAP) ) endif() +# Keying Material Exporter / TLS Exporter +add_option("WOLFSSL_KEYING_MATERIAL" + "Enable wolfSSL keying material export (default: disabled)" + "no" "yes;no") + +if(WOLFSSL_KEYING_MATERIAL) + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_KEYING_MATERIAL") +endif() if(WOLFSSL_KEYGEN) list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_KEY_GEN") From 485d82ad966631b69ee9e5abd5191bf93aa7b1c3 Mon Sep 17 00:00:00 2001 From: Andras Fekete Date: Thu, 22 Jun 2023 10:51:07 -0400 Subject: [PATCH 059/391] Add in CMake flags 'HPKE', 'HKDF', 'ECH' (cherry picked from commit f58ae30b509835140a667ce5a7513fef4e8a40d2) --- CMakeLists.txt | 38 ++++++++++++++++++++++++++++++++++++++ cmake/functions.cmake | 7 +++++++ 2 files changed, 45 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index ddab15e481e..21b5d6d8665 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1810,11 +1810,49 @@ if(WOLFSSL_AESKEYWRAP) ) endif() +# Hybrid Key Derivation Function +add_option("WOLFSSL_HKDF" + "Enable wolfSSL HKDF (HMAC-KDF) support (default: disabled)" + "no" "yes;no") + + +# Hybrid Public Key Encryption (RFC9180) +add_option("WOLFSSL_HPKE" + "Enable wolfSSL hybrid public key encryption (default: disabled)" + "no" "yes;no") + +# Encrypted Client Hello (ECH) +add_option("WOLFSSL_ECH" + "Enable wolfSSL encrypted client hello (default: disabled)" + "no" "yes;no") + # Keying Material Exporter / TLS Exporter add_option("WOLFSSL_KEYING_MATERIAL" "Enable wolfSSL keying material export (default: disabled)" "no" "yes;no") +if(WOLFSSL_HPKE) + if(NOT WOLFSSL_ECC) + message(FATAL_ERROR "HPKE supported only with ECC (WOLFSSL_ECC)") + endif() + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_HPKE") + override_cache(WOLFSSL_HKDF "yes") +endif() + +if(WOLFSSL_HKDF) + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_HKDF") +endif() + +if(WOLFSSL_ECH) + if(NOT WOLFSSL_HPKE) + message(FATAL_ERROR "ECH supported only with HPKE (WOLFSSL_HPKE)") + endif() + if(NOT WOLFSSL_SNI) + message(FATAL_ERROR "ECH supported only with SNI (WOLFSSL_SNI)") + endif() + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_ECH") +endif() + if(WOLFSSL_KEYING_MATERIAL) list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_KEYING_MATERIAL") endif() diff --git a/cmake/functions.cmake b/cmake/functions.cmake index 7b245b57f31..a81e862004d 100644 --- a/cmake/functions.cmake +++ b/cmake/functions.cmake @@ -304,6 +304,9 @@ function(generate_build_flags) if(WOLFSSL_CAAM) set(BUILD_CAAM "yes" PARENT_SCOPE) endif() + if(WOLFSSL_HPKE OR WOLFSSL_USER_SETTINGS) + set(BUILD_HPKE "yes" PARENT_SCOPE) + endif() set(BUILD_FLAGS_GENERATED "yes" PARENT_SCOPE) endfunction() @@ -909,6 +912,10 @@ function(generate_lib_src_list LIB_SOURCES) wolfcrypt/src/port/caam/wolfcaam_hmac.c) endif() + if(BUILD_HPKE) + list(APPEND LIB_SOURCES wolfcrypt/src/hpke.c) + endif() + set(LIB_SOURCES ${LIB_SOURCES} PARENT_SCOPE) endfunction() From b53f44523d92e22571d7acd1940bcee5b85385a3 Mon Sep 17 00:00:00 2001 From: Andras Fekete Date: Thu, 22 Jun 2023 11:03:56 -0400 Subject: [PATCH 060/391] Get around issue with 'uint8_t' undefined (cherry picked from commit 0ee198437ac0c6f502d1c0c7dd1f10998ac5b63a) --- wolfcrypt/test/test.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 82b4244d9d5..72dd9cf5c3a 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -23157,10 +23157,10 @@ static int hpke_test_single(Hpke* hpke) void* receiverKey = NULL; void* ephemeralKey = NULL; #ifdef WOLFSSL_SMALL_STACK - uint8_t *pubKey = NULL; /* public key */ + byte *pubKey = NULL; /* public key */ word16 pubKeySz = (word16)HPKE_Npk_MAX; #else - uint8_t pubKey[HPKE_Npk_MAX]; /* public key */ + byte pubKey[HPKE_Npk_MAX]; /* public key */ word16 pubKeySz = (word16)sizeof(pubKey); #endif @@ -23171,7 +23171,7 @@ static int hpke_test_single(Hpke* hpke) #ifdef WOLFSSL_SMALL_STACK if (ret == 0) { - pubKey = (uint8_t *)XMALLOC(pubKeySz, HEAP_HINT, + pubKey = (byte *)XMALLOC(pubKeySz, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (pubKey == NULL) ret = MEMORY_E; From 44c6009440bf85b84835c3ced1cc34cf55a5b583 Mon Sep 17 00:00:00 2001 From: Andras Fekete Date: Thu, 22 Jun 2023 11:17:34 -0400 Subject: [PATCH 061/391] HKDF already defined (cherry picked from commit 155ce9aecf9f5b14261cd6c238ceb1e6f2aee649) --- CMakeLists.txt | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 21b5d6d8665..2097ec4c998 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1810,12 +1810,6 @@ if(WOLFSSL_AESKEYWRAP) ) endif() -# Hybrid Key Derivation Function -add_option("WOLFSSL_HKDF" - "Enable wolfSSL HKDF (HMAC-KDF) support (default: disabled)" - "no" "yes;no") - - # Hybrid Public Key Encryption (RFC9180) add_option("WOLFSSL_HPKE" "Enable wolfSSL hybrid public key encryption (default: disabled)" @@ -1839,10 +1833,6 @@ if(WOLFSSL_HPKE) override_cache(WOLFSSL_HKDF "yes") endif() -if(WOLFSSL_HKDF) - list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_HKDF") -endif() - if(WOLFSSL_ECH) if(NOT WOLFSSL_HPKE) message(FATAL_ERROR "ECH supported only with HPKE (WOLFSSL_HPKE)") From 2406d3e0afae8340a3d5f44222b143f231c36181 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Thu, 29 Jun 2023 13:48:35 +0200 Subject: [PATCH 062/391] fix: remove custom options --- CMakeLists.txt | 86 +++++++++++--------------------------------------- 1 file changed, 19 insertions(+), 67 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2097ec4c998..4f81464f209 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1698,73 +1698,6 @@ if(WOLFSSL_SYS_CA_CERTS) endif() endif() -### START ### Remote Attestation and its dependencies - -# Hybrid Public Key Encryption (RFC9180) -add_option("WOLFSSL_HPKE" - "Enable wolfSSL hybrid public key encryption (default: disabled)" - "no" "yes;no") - -if(WOLFSSL_HPKE) - if(NOT WOLFSSL_ECC) - message(FATAL_ERROR "HPKE supported only with ECC (WOLFSSL_ECC)") - endif() - list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_HPKE") -endif() - -# Encrypted Client Hello (ECH) -add_option("WOLFSSL_ECH" - "Enable wolfSSL encrypted client hello (default: disabled)" - "no" "yes;no") - -if(WOLFSSL_ECH) - if(NOT WOLFSSL_HPKE) - message(FATAL_ERROR "ECH supported only with HPKE (WOLFSSL_HPKE)") - endif() - if(NOT WOLFSSL_SNI) - message(FATAL_ERROR "ECH supported only with SNI (WOLFSSL_SNI)") - endif() - list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_ECH") -endif() - -# Keying Material Exporter / TLS Exporter -add_option("WOLFSSL_KEYING_MATERIAL" - "Enable wolfSSL keying material export (default: disabled)" - "no" "yes;no") - -if(WOLFSSL_KEYING_MATERIAL) - list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_KEYING_MATERIAL") -endif() - -# Remote Attestation -add_option("WOLFSSL_REMOTE_ATTESTATION" - "Enable wolfSSL remote attestation (default: disabled)" - "no" "yes;no") - -if(WOLFSSL_REMOTE_ATTESTATION) - if(NOT WOLFSSL_TLS13) - message(FATAL_ERROR "Remote Attestation supported only for TLSv1.3 (WOLFSSL_TLS13)") - endif() - if(NOT WOLFSSL_KEYING_MATERIAL) - message(FATAL_ERROR "Remote Attestation supported only with Keying Material Exporter (WOLFSSL_KEYING_MATERIAL)") - endif() - if(NOT WOLFSSL_ECH) - message(WARNING "Remote Attestation recommends Encrypted Client Hello (WOLFSSL_ECH)") - endif() - - # TODO: Include proper checks for features. I will hardcode them for now. - list(APPEND WOLFSSL_DEFINITIONS - "-DWOLFSSL_ASN_TEMPLATE" - "-DWOLFSSL_CERT_GEN" - "-DWOLFSSL_KEY_GEN" - "-DWOLFSSL_CUSTOM_OID" - "-DHAVE_OID_ENCODING" - "-DWOLFSSL_CERT_EXT" - "-DHAVE_REMOTE_ATTESTATION") -endif() - -### END ### Remote Attestation and its dependencies - # FLAGS operations if(WOLFSSL_AESCCM) @@ -1913,6 +1846,25 @@ if (WOLFSSL_CAAM) list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_CAAM") endif() +# Remote Attestation +add_option("WOLFSSL_REMOTE_ATTESTATION" + "Enable wolfSSL remote attestation (default: disabled)" + "no" "yes;no") + +if(WOLFSSL_REMOTE_ATTESTATION) + if(NOT WOLFSSL_TLS13) + message(FATAL_ERROR "Remote Attestation supported only for TLSv1.3 (WOLFSSL_TLS13)") + endif() + if(NOT WOLFSSL_KEYING_MATERIAL) + message(FATAL_ERROR "Remote Attestation supported only with Keying Material Exporter (WOLFSSL_KEYING_MATERIAL)") + endif() + if(NOT WOLFSSL_ECH) + message(WARNING "Remote Attestation recommends Encrypted Client Hello (WOLFSSL_ECH)") + endif() + + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_REMOTE_ATTESTATION") +endif() + # Generates the BUILD_* flags. These control what source files are included in # the library. A series of AM_CONDITIONALs handle this in configure.ac. From 1d3f38ab57487e84292c928e78cf4b7a0df16c8c Mon Sep 17 00:00:00 2001 From: joeftiger Date: Sat, 8 Jul 2023 15:43:06 +0200 Subject: [PATCH 063/391] feat: send RA request only in InnerClientHello when using ECH Current implementation is inefficient as it requires copying the attestation data 4x due to the placement of the inclusion check. It can be done much more efficiently when checking whether to write the extension at all, rather to copy it, remove it from the extension list, calculate TLSX size / write TLSX, and copy it back. Drawback would be, that these things are not in the same place, then. It feels a bit like a design error. --- src/tls.c | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/src/tls.c b/src/tls.c index 54cb210d012..b2b03df8342 100644 --- a/src/tls.c +++ b/src/tls.c @@ -12646,6 +12646,10 @@ static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType, TLSX* echX = NULL; TLSX* serverNameX = NULL; TLSX** extensions = NULL; +#ifdef HAVE_REMOTE_ATTESTATION + TLSX *attReq = NULL; + ATT_REQUEST *tmpAttReq = NULL; +#endif #ifdef WOLFSSL_SMALL_STACK char* tmpServerName = NULL; #else @@ -12705,6 +12709,31 @@ static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType, ret = 0; } +#ifdef HAVE_REMOTE_ATTESTATION + /* if type is outer remove remote attestation request */ + if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) { + if (ssl->extensions) { + attReq = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); + + if (attReq != NULL) + extensions = &ssl->extensions; + } + + if (attReq == NULL && ssl->ctx && ssl->ctx->extensions) { + attReq = TLSX_Find(ssl->ctx->extensions, TLSX_ATTESTATION_REQUEST); + extensions = &ssl->ctx->extensions; + } + + /* store a copy before removing it */ + if (attReq != NULL) { + tmpAttReq = TLSX_AttRequest_NewCopy((ATT_REQUEST *) attReq->data, ssl->heap); + } + + // remove the attestation request + TLSX_Remove(extensions, TLSX_ATTESTATION_REQUEST, ssl->heap); + } +#endif /* HAVE_REMOTE_ATTESTATION */ + if (ret == 0 && ssl->extensions) ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, pLength); @@ -12723,6 +12752,18 @@ static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType, ret = 0; } +#ifdef HAVE_REMOTE_ATTESTATION + if (tmpAttReq != NULL) { + ret = TLSX_UseAttestationRequest(extensions, tmpAttReq, ssl->heap, wolfSSL_is_server(ssl)); + + if (ret == WOLFSSL_SUCCESS) { + ret = 0; + } + + XFREE(tmpAttReq, ssl->heap, DYNAMIC_TYPE_TLSX); + } +#endif /* HAVE_REMOTE_ATTESTATION */ + #ifdef WOLFSSL_SMALL_STACK XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -12841,6 +12882,10 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, TLSX* echX = NULL; TLSX* serverNameX = NULL; TLSX** extensions = NULL; +#ifdef HAVE_REMOTE_ATTESTATION + TLSX *attReq = NULL; + ATT_REQUEST *tmpAttReq = NULL; +#endif #ifdef WOLFSSL_SMALL_STACK char* tmpServerName = NULL; #else @@ -12903,6 +12948,31 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, ret = 0; } +#ifdef HAVE_REMOTE_ATTESTATION + /* if type is outer remove remote attestation request */ + if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) { + if (ssl->extensions) { + attReq = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); + + if (attReq != NULL) + extensions = &ssl->extensions; + } + + if (attReq == NULL && ssl->ctx && ssl->ctx->extensions) { + attReq = TLSX_Find(ssl->ctx->extensions, TLSX_ATTESTATION_REQUEST); + extensions = &ssl->ctx->extensions; + } + + /* store a copy before removing it */ + if (attReq != NULL) { + tmpAttReq = TLSX_AttRequest_NewCopy((ATT_REQUEST *) attReq->data, ssl->heap); + } + + // remove the attestation request + TLSX_Remove(extensions, TLSX_ATTESTATION_REQUEST, ssl->heap); + } +#endif /* HAVE_REMOTE_ATTESTATION */ + if (echX != NULL) { /* turn ech on so it doesn't write, then write it last */ TURN_ON(semaphore, TLSX_ToSemaphore(echX->type)); @@ -12945,6 +13015,18 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, ret = 0; } +#ifdef HAVE_REMOTE_ATTESTATION + if (tmpAttReq != NULL) { + ret = TLSX_UseAttestationRequest(extensions, tmpAttReq, ssl->heap, wolfSSL_is_server(ssl)); + + if (ret == WOLFSSL_SUCCESS) { + ret = 0; + } + + XFREE(tmpAttReq, ssl->heap, DYNAMIC_TYPE_TLSX); + } +#endif /* HAVE_REMOTE_ATTESTATION */ + #ifdef WOLFSSL_SMALL_STACK XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif From 9752d1da3ff494a982eb566c329d5e0e5f559c98 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Wed, 12 Jul 2023 13:12:13 +0200 Subject: [PATCH 064/391] feat: TLSX_RemoveNoFree to remove an extension without freeing its data This is useful to cache extension data in case of ECH, e.g. --- src/tls.c | 76 ++++++++++++++++++++++++++++++++++------------ wolfssl/internal.h | 22 ++++++++++++++ 2 files changed, 79 insertions(+), 19 deletions(-) diff --git a/src/tls.c b/src/tls.c index b2b03df8342..f009c638cdb 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1920,9 +1920,27 @@ int TLSX_UseAttestationRequest(TLSX **extensions, const ATT_REQUEST *req, void * return MEMORY_ERROR; } - int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, req_cpy, heap); - if (ret != 0) { + int ret = TLSX_UseAttestationRequestNoCopy(extensions, req_cpy, heap, is_server); + if (ret != WOLFSSL_SUCCESS) { TLSX_AttestationRequest_FreeAll(req_cpy, heap); + } + + return ret; +} + +int TLSX_UseAttestationRequestNoCopy(TLSX **extensions, const ATT_REQUEST *req, void *heap, byte is_server) { + if (!extensions || !req) { + return BAD_FUNC_ARG; + } + if (is_server && req->is_request) { + return BAD_FUNC_ARG; + } + if (req == NULL) { + return MEMORY_ERROR; + } + + int ret = TLSX_Push(extensions, TLSX_ATTESTATION_REQUEST, req, heap); + if (ret != 0) { return ret; } @@ -10748,6 +10766,32 @@ void TLSX_Remove(TLSX** list, TLSX_Type type, void* heap) } } +/** Remove an extension and returns the data*/ +void *TLSX_RemoveNoFree(TLSX** list, TLSX_Type type) +{ + TLSX* extension; + TLSX** next; + + if (list == NULL) + return NULL; + + extension = *list; + next = list; + + while (extension && extension->type != type) { + next = &extension->next; + extension = extension->next; + } + + if (extension) { + *next = extension->next; + extension->next = NULL; + return extension->data; + } + + return NULL; +} + #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) #define GREASE_ECH_SIZE 160 #define MAX_PUBLIC_NAME_SZ 256 @@ -12647,8 +12691,7 @@ static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType, TLSX* serverNameX = NULL; TLSX** extensions = NULL; #ifdef HAVE_REMOTE_ATTESTATION - TLSX *attReq = NULL; - ATT_REQUEST *tmpAttReq = NULL; + ATT_REQUEST *attReq = NULL; #endif #ifdef WOLFSSL_SMALL_STACK char* tmpServerName = NULL; @@ -12712,25 +12755,22 @@ static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType, #ifdef HAVE_REMOTE_ATTESTATION /* if type is outer remove remote attestation request */ if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) { + // remove extension without freeing the memory to avoid copying if (ssl->extensions) { - attReq = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); + attReq = TLSX_RemoveNoFree(extensions, TLSX_ATTESTATION_REQUEST); - if (attReq != NULL) + if (attReq != NULL) { extensions = &ssl->extensions; + } } if (attReq == NULL && ssl->ctx && ssl->ctx->extensions) { - attReq = TLSX_Find(ssl->ctx->extensions, TLSX_ATTESTATION_REQUEST); - extensions = &ssl->ctx->extensions; - } + attReq = TLSX_RemoveNoFree(&ssl->ctx->extensions, TLSX_ATTESTATION_REQUEST); - /* store a copy before removing it */ - if (attReq != NULL) { - tmpAttReq = TLSX_AttRequest_NewCopy((ATT_REQUEST *) attReq->data, ssl->heap); + if (attReq != NULL) { + extensions = &ssl->ctx->extensions; + } } - - // remove the attestation request - TLSX_Remove(extensions, TLSX_ATTESTATION_REQUEST, ssl->heap); } #endif /* HAVE_REMOTE_ATTESTATION */ @@ -12753,14 +12793,12 @@ static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType, } #ifdef HAVE_REMOTE_ATTESTATION - if (tmpAttReq != NULL) { - ret = TLSX_UseAttestationRequest(extensions, tmpAttReq, ssl->heap, wolfSSL_is_server(ssl)); + if (attReq != NULL) { + ret = TLSX_UseAttestationRequestNoCopy(extensions, attReq, ssl->heap, wolfSSL_is_server(ssl)); if (ret == WOLFSSL_SUCCESS) { ret = 0; } - - XFREE(tmpAttReq, ssl->heap, DYNAMIC_TYPE_TLSX); } #endif /* HAVE_REMOTE_ATTESTATION */ diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 3d04130155a..b5acf7ff867 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -2693,6 +2693,7 @@ struct TLSX { WOLFSSL_LOCAL TLSX* TLSX_Find(TLSX* list, TLSX_Type type); WOLFSSL_LOCAL void TLSX_Remove(TLSX** list, TLSX_Type type, void* heap); +WOLFSSL_LOCAL void *TLSX_RemoveNoFree(TLSX** list, TLSX_Type type); WOLFSSL_LOCAL void TLSX_FreeAll(TLSX* list, void* heap); WOLFSSL_LOCAL int TLSX_SupportExtensions(WOLFSSL* ssl); WOLFSSL_LOCAL int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isRequest); @@ -2770,8 +2771,29 @@ WOLFSSL_LOCAL int VerifyAttestation(WOLFSSL *ssl); */ WOLFSSL_LOCAL ATT_REQUEST *TLSX_AttRequest_NewCopy(const ATT_REQUEST *req, void *heap); +/** + * Adds a new attestation request (copying it beforehand for memory management by wolfSSL). + * @param extensions The extensions list + * @param req The request to add + * @param heap The heap + * @param is_server Whether the extension is from server + * @return WOLFSSL_SUCCESS on success, negative values on error + * @see TLSX_UseAttestationRequestNoCopy + */ WOLFSSL_LOCAL int TLSX_UseAttestationRequest(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server); + +/** + * Adds a new attestation request. + * @param extensions The extensions list + * @param req The request to add + * @param heap The heap + * @param is_server Whether the extension is from server + * @return WOLFSSL_SUCCESS on success, negative values on error + * @see TLSX_UseAttestationRequest + */ +WOLFSSL_LOCAL int TLSX_UseAttestationRequestNoCopy(TLSX** extensions, const ATT_REQUEST *req, void* heap, byte is_server); + #endif /** Server Name Indication - RFC 6066 (session 3) */ From 556d21d6949e6a3f9012e2d454e1ab832d6eefad Mon Sep 17 00:00:00 2001 From: joeftiger Date: Wed, 12 Jul 2023 13:22:26 +0200 Subject: [PATCH 065/391] fix: memory leakage when removing TLSX without free --- src/tls.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/tls.c b/src/tls.c index f009c638cdb..6db25e00cce 100644 --- a/src/tls.c +++ b/src/tls.c @@ -10786,7 +10786,11 @@ void *TLSX_RemoveNoFree(TLSX** list, TLSX_Type type) if (extension) { *next = extension->next; extension->next = NULL; - return extension->data; + + void *data = extension->data; + XFREE(extension, heap, DYNAMIC_TYPE_TLSX); + + return data; } return NULL; From b478d0620efd63c3a5d04d3b3317f085a80e0fc2 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Wed, 12 Jul 2023 13:26:44 +0200 Subject: [PATCH 066/391] fix: cache RA extension when using ECH rather than copying it --- src/tls.c | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/src/tls.c b/src/tls.c index 6db25e00cce..69c7d938e5f 100644 --- a/src/tls.c +++ b/src/tls.c @@ -12925,8 +12925,7 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, TLSX* serverNameX = NULL; TLSX** extensions = NULL; #ifdef HAVE_REMOTE_ATTESTATION - TLSX *attReq = NULL; - ATT_REQUEST *tmpAttReq = NULL; + ATT_REQUEST *attReq = NULL; #endif #ifdef WOLFSSL_SMALL_STACK char* tmpServerName = NULL; @@ -12993,25 +12992,22 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, #ifdef HAVE_REMOTE_ATTESTATION /* if type is outer remove remote attestation request */ if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) { + // remove extension without freeing the memory to avoid copying if (ssl->extensions) { - attReq = TLSX_Find(ssl->extensions, TLSX_ATTESTATION_REQUEST); + attReq = TLSX_RemoveNoFree(extensions, TLSX_ATTESTATION_REQUEST); - if (attReq != NULL) + if (attReq != NULL) { extensions = &ssl->extensions; + } } if (attReq == NULL && ssl->ctx && ssl->ctx->extensions) { - attReq = TLSX_Find(ssl->ctx->extensions, TLSX_ATTESTATION_REQUEST); - extensions = &ssl->ctx->extensions; - } + attReq = TLSX_RemoveNoFree(&ssl->ctx->extensions, TLSX_ATTESTATION_REQUEST); - /* store a copy before removing it */ - if (attReq != NULL) { - tmpAttReq = TLSX_AttRequest_NewCopy((ATT_REQUEST *) attReq->data, ssl->heap); + if (attReq != NULL) { + extensions = &ssl->ctx->extensions; + } } - - // remove the attestation request - TLSX_Remove(extensions, TLSX_ATTESTATION_REQUEST, ssl->heap); } #endif /* HAVE_REMOTE_ATTESTATION */ @@ -13058,14 +13054,12 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, } #ifdef HAVE_REMOTE_ATTESTATION - if (tmpAttReq != NULL) { - ret = TLSX_UseAttestationRequest(extensions, tmpAttReq, ssl->heap, wolfSSL_is_server(ssl)); + if (attReq != NULL) { + ret = TLSX_UseAttestationRequestNoCopy(extensions, attReq, ssl->heap, wolfSSL_is_server(ssl)); if (ret == WOLFSSL_SUCCESS) { ret = 0; } - - XFREE(tmpAttReq, ssl->heap, DYNAMIC_TYPE_TLSX); } #endif /* HAVE_REMOTE_ATTESTATION */ From 1d469e68c0446799074a43d2c45256bf1858e63d Mon Sep 17 00:00:00 2001 From: joeftiger Date: Sat, 2 Sep 2023 12:59:53 +0200 Subject: [PATCH 067/391] benchmark --- src/ssl.c | 4 +++ src/tls.c | 49 ++++++++++++++++++++++++++++++------ src/tls13.c | 39 +++++++++++++++++++++++++++++ wolfssl/internal.h | 1 + wolfssl/ssl.h | 62 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 147 insertions(+), 8 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 1b5059437ec..eb968c2f6cd 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -31224,6 +31224,10 @@ WOLFSSL_CTX* wolfSSL_get_SSL_CTX(WOLFSSL* ssl) return ssl->ctx; } +Benchmark *wolfSSL_GetBenchmark(WOLFSSL *ssl) { + return &ssl->benchmark; +} + #if defined(OPENSSL_ALL) || \ defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \ defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) diff --git a/src/tls.c b/src/tls.c index 69c7d938e5f..6d6e52d457c 100644 --- a/src/tls.c +++ b/src/tls.c @@ -2086,8 +2086,11 @@ int GenerateAttestation(WOLFSSL *ssl) { int ret = 0; byte *c = NULL; byte *att_buffer = NULL; + struct timespec start, c_end, g_end; WOLFSSL_ENTER("GenerateAttestation"); + clock_gettime(CLOCK_MONOTONIC, &start); + if (!ssl || !ssl->attestationRequest || !ssl->generateAttestation || !wolfSSL_is_server(ssl) || !ssl->attestationRequest->is_request) { ret = BAD_FUNC_ARG; @@ -2108,6 +2111,7 @@ int GenerateAttestation(WOLFSSL *ssl) { ret = ATTESTATION_KEYING_E; goto exit; } + clock_gettime(CLOCK_MONOTONIC, &c_end); // attestation certificate att_buffer = XMALLOC(ATT_BUFFER_SIZE, ssl->heap, DYNAMIC_TYPE_TLSX); @@ -2134,6 +2138,10 @@ int GenerateAttestation(WOLFSSL *ssl) { } // extension data gets copied, so it's free to clear below buffers now + clock_gettime(CLOCK_MONOTONIC, &g_end); + timespec_subtract(&start, &c_end, &ssl->benchmark.server_att_request_challenge_generation); + timespec_subtract(&start, &g_end, &ssl->benchmark.server_att_request_generation); + exit: if (c) { XFREE(c, ssl->heap, DYNAMIC_TYPE_TLSX); @@ -2156,8 +2164,11 @@ int GenerateAttestation(WOLFSSL *ssl) { int VerifyAttestation(WOLFSSL *ssl) { int ret = 0; unsigned char *challenge_buffer = NULL; + struct timespec start, c_end, g_end; WOLFSSL_ENTER("VerifyAttestation"); + clock_gettime(CLOCK_MONOTONIC, &start); + if (!ssl || !ssl->attestationRequest || !ssl->verifyAttestation || wolfSSL_is_server(ssl) || ssl->attestationRequest->is_request) { ret = BAD_FUNC_ARG; @@ -2178,6 +2189,7 @@ int VerifyAttestation(WOLFSSL *ssl) { ret = ATTESTATION_KEYING_E; goto exit; } + clock_gettime(CLOCK_MONOTONIC, &c_end); ret = ssl->verifyAttestation(req, challenge_buffer); @@ -2186,6 +2198,10 @@ int VerifyAttestation(WOLFSSL *ssl) { XFREE(challenge_buffer, ssl->heap, DYNAMIC_TYPE_TLSX); } + clock_gettime(CLOCK_MONOTONIC, &g_end); + timespec_subtract(&start, &c_end, &ssl->benchmark.client_certificate_verify_att_request_challenge_generation); + timespec_subtract(&start, &g_end, &ssl->benchmark.client_certificate_verify_att_request); + WOLFSSL_LEAVE("VerifyAttestation", ret); return ret; } @@ -11813,7 +11829,7 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, /** Writes the extensions of a list in a buffer. */ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, - byte msgType, word16* pOffset) + byte msgType, word16* pOffset, WOLFSSL *ssl) { int ret = 0; TLSX* extension; @@ -11822,6 +11838,11 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, byte isRequest = (msgType == client_hello || msgType == certificate_request); + struct timespec start, end; + struct timespec ra_start, ra_end; + + clock_gettime(CLOCK_MONOTONIC, &start); + while ((extension = list)) { list = extension->next; @@ -11983,7 +12004,10 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, #ifdef HAVE_REMOTE_ATTESTATION case TLSX_ATTESTATION_REQUEST: WOLFSSL_MSG("Attestation Request extension to write"); + + clock_gettime(CLOCK_MONOTONIC, &ra_start); offset += ATT_WRITE((const ATT_REQUEST *) extension->data, output + offset, msgType); + clock_gettime(CLOCK_MONOTONIC, &ra_end); break; #endif #ifdef WOLFSSL_SRTP @@ -12030,6 +12054,15 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, *pOffset += offset; + clock_gettime(CLOCK_MONOTONIC, &end); + if (msgType == encrypted_extensions) { + timespec_subtract(&start, &end, &ssl->benchmark.server_extensions); + timespec_subtract(&ra_start, &ra_end, &ssl->benchmark.server_att_request); + } else { + timespec_subtract(&start, &end, &ssl->benchmark.client_extensions); + timespec_subtract(&ra_start, &ra_end, &ssl->benchmark.client_att_request); + } + return ret; } @@ -13018,12 +13051,12 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, if (ret == 0 && ssl->extensions) { ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore, - msgType, pOffset); + msgType, pOffset, ssl); } if (ret == 0 && ssl->ctx && ssl->ctx->extensions) { ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore, - msgType, pOffset); + msgType, pOffset, ssl); } if (echX != NULL) { @@ -13033,12 +13066,12 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, if (ret == 0 && ssl->extensions) { ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore, - msgType, pOffset); + msgType, pOffset, ssl); } if (ret == 0 && ssl->ctx && ssl->ctx->extensions) { ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore, - msgType, pOffset); + msgType, pOffset, ssl); } if (serverNameX != NULL) { @@ -13156,13 +13189,13 @@ int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset) { if (ssl->extensions) { ret = TLSX_Write(ssl->extensions, output + offset, semaphore, - msgType, &offset); + msgType, &offset, ssl); if (ret != 0) return ret; } if (ssl->ctx && ssl->ctx->extensions) { ret = TLSX_Write(ssl->ctx->extensions, output + offset, semaphore, - msgType, &offset); + msgType, &offset, ssl); if (ret != 0) return ret; } @@ -13476,7 +13509,7 @@ int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset offset += OPAQUE16_LEN; /* extensions length */ ret = TLSX_Write(ssl->extensions, output + offset, semaphore, - msgType, &offset); + msgType, &offset, ssl); if (ret != 0) return ret; diff --git a/src/tls13.c b/src/tls13.c index 15ef748a457..e8e2391e904 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -3987,6 +3987,8 @@ int SendTls13ClientHello(WOLFSSL* ssl) WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND); WOLFSSL_ENTER("SendTls13ClientHello"); + struct timespec start, end; + clock_gettime(CLOCK_MONOTONIC, &start); if (ssl == NULL) { return BAD_FUNC_ARG; @@ -4440,6 +4442,9 @@ int SendTls13ClientHello(WOLFSSL* ssl) FreeAsyncCtx(ssl, 0); #endif + clock_gettime(CLOCK_MONOTONIC, &end); + timespec_subtract(&start, &end, &ssl->benchmark.client_hello); + WOLFSSL_LEAVE("SendTls13ClientHello", ret); WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND); @@ -6319,6 +6324,8 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO); WOLFSSL_ENTER("DoTls13ClientHello"); + struct timespec start, end; + clock_gettime(CLOCK_MONOTONIC, &start); #ifdef WOLFSSL_ASYNC_CRYPT if (ssl->async == NULL) { @@ -6798,6 +6805,9 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, exit_dch: + clock_gettime(CLOCK_MONOTONIC, &start); + timespec_subtract(&start, &end, &ssl->benchmark.client_hello); + WOLFSSL_LEAVE("DoTls13ClientHello", ret); #ifdef WOLFSSL_ASYNC_CRYPT @@ -6852,6 +6862,8 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND); WOLFSSL_ENTER("SendTls13ServerHello"); + struct timespec start, end; + clock_gettime(CLOCK_MONOTONIC, &start); /* When ssl->options.dtlsStateful is not set then cookie is calculated in * dtls.c */ @@ -7025,6 +7037,9 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) if (!ssl->options.groupMessages || extMsgType != server_hello) ret = SendBuffered(ssl); + clock_gettime(CLOCK_MONOTONIC, &end); + timespec_subtract(&start, &end, &ssl->benchmark.server_hello); + WOLFSSL_LEAVE("SendTls13ServerHello", ret); WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND); @@ -7047,8 +7062,12 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) word32 idx; int sendSz; + struct timespec ee_start, ee_end; + struct timespec gen_start, gen_end; + WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND); WOLFSSL_ENTER("SendTls13EncryptedExtensions"); + clock_gettime(CLOCK_MONOTONIC, &ee_start); ssl->options.buildingMsg = 1; ssl->keys.encryptionOn = 1; @@ -7081,7 +7100,9 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) // TODO: Does this belong here? It should be AFTER input hashing (for the TLS exporter) // and before writing encrypted extensions. if (ssl->attestationRequest) { + clock_gettime(CLOCK_MONOTONIC, &gen_start); if ((ret = GenerateAttestation(ssl)) != 0) { + clock_gettime(CLOCK_MONOTONIC, &gen_end); if (ret == ATTESTATION_TYPE_SUPPORT_E) { SendAlert(ssl, alert_fatal, unsupported_attestation); WOLFSSL_ERROR_VERBOSE(ATTESTATION_TYPE_SUPPORT_E); @@ -7194,6 +7215,8 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) if (!ssl->options.groupMessages) ret = SendBuffered(ssl); + clock_gettime(CLOCK_MONOTONIC, &ee_end); + timespec_subtract(&ee_start, &ee_end, &ssl->benchmark.server_extensions); WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret); WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND); @@ -8779,6 +8802,8 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO); WOLFSSL_ENTER("DoTls13CertificateVerify"); + struct timespec cv_start, cv_end; + clock_gettime(CLOCK_MONOTONIC, &cv_start); #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13CertificateVerify(ssl, input, inOutIdx, totalSz); @@ -9214,6 +9239,9 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, exit_dcv: + clock_gettime(CLOCK_MONOTONIC, &cv_end); + timespec_subtract(&cv_start, &cv_end, &ssl->benchmark.client_certificate_verify); + WOLFSSL_LEAVE("DoTls13CertificateVerify", ret); WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO); @@ -11419,6 +11447,8 @@ int wolfSSL_connect_TLSv13(WOLFSSL* ssl) int ret = 0; WOLFSSL_ENTER("wolfSSL_connect_TLSv13"); + struct timespec start, end; + clock_gettime(CLOCK_MONOTONIC, &start); #ifdef HAVE_ERRNO_H errno = 0; @@ -11790,6 +11820,9 @@ int wolfSSL_connect_TLSv13(WOLFSSL* ssl) ssl->error = 0; /* clear the error */ + clock_gettime(CLOCK_MONOTONIC, &end); + timespec_subtract(&start, &end, &ssl->benchmark.handshake); + WOLFSSL_LEAVE("wolfSSL_connect_TLSv13", WOLFSSL_SUCCESS); return WOLFSSL_SUCCESS; @@ -12563,7 +12596,10 @@ int wolfSSL_accept_TLSv13(WOLFSSL* ssl) int advanceState; int ret = 0; + struct timespec start, end; + WOLFSSL_ENTER("wolfSSL_accept_TLSv13"); + clock_gettime(CLOCK_MONOTONIC, &start); #ifdef HAVE_ERRNO_H errno = 0; @@ -13049,6 +13085,9 @@ int wolfSSL_accept_TLSv13(WOLFSSL* ssl) ssl->error = 0; /* clear the error */ + clock_gettime(CLOCK_MONOTONIC, &end); + timespec_subtract(&start, &end, &ssl->benchmark.handshake); + WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS); return WOLFSSL_SUCCESS; diff --git a/wolfssl/internal.h b/wolfssl/internal.h index b5acf7ff867..375f137f7ea 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -5560,6 +5560,7 @@ struct WOLFSSL { VerifyAttCallback verifyAttestation; GenAttCallback generateAttestation; #endif /* HAVE_REMOTE_ATTESTATION */ + Benchmark benchmark; }; /* diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index a6cc8ff5c11..cd1cfb78b9e 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -5257,6 +5257,68 @@ WOLFSSL_API int wolfSSL_dtls_cid_get_tx(WOLFSSL* ssl, unsigned char* buffer, #define DTLS1_VERSION 0xFEFF #define DTLS1_2_VERSION 0xFEFD +#include "time.h" + +typedef struct Benchmark { + struct timespec handshake; + struct timespec client_hello; + struct timespec client_extensions; + struct timespec client_att_request; + struct timespec client_certificate_verify; + struct timespec client_certificate_verify_att_request; + struct timespec client_certificate_verify_att_request_challenge_generation; + struct timespec server_hello; + struct timespec server_extensions; + struct timespec server_att_request; + struct timespec server_att_request_generation; + struct timespec server_att_request_challenge_generation; +} Benchmark; + +WOLFSSL_API Benchmark *wolfSSL_GetBenchmark(WOLFSSL *ssl); +WOLFSSL_API static void timespec_subtract(struct timespec *start, struct timespec *end, struct timespec *result) { + /* + if start.ns < end.ns: + result.ns = end.ns - start.ns + result.s = end.s - start.s + else if start.ns > end.ns: + dt = start.ns - end.ns + result.ns = 1'000'000'000 - dt // nanoseconds + result.s = end.s - start.s - 1 // offset due to underflow + else: + result.ns = 0 + result.s = end.s - start.s + */ + + if (start->tv_nsec < end->tv_nsec) { + result->tv_nsec = end->tv_nsec - start->tv_nsec; + result->tv_sec = end->tv_sec - start->tv_sec; + } else if (start->tv_nsec > end->tv_nsec) { + result->tv_nsec = 1000000000L - (start->tv_nsec - end->tv_nsec); // dt in ns + result->tv_sec = end->tv_sec - start->tv_sec - 1; // 1 offset due to underflow + } else { + result->tv_nsec = 0; + result->tv_sec = end->tv_sec - start->tv_sec; + } + + /* + // Perform the carrend for the later subtraction bend updating end. + if (start->tv_nsec < end->tv_nsec) { + __syscall_slong_t nsec = (end->tv_nsec - start->tv_nsec) / 1000000000L + 1; + end->tv_nsec -= 1000000000L * nsec; + end->tv_sec += nsec; + } + if (start->tv_nsec - end->tv_nsec > 1000000000L) { + __syscall_slong_t nsec = (start->tv_nsec - end->tv_nsec) / 1000000000L; + end->tv_nsec += 1000000000L * nsec; + end->tv_sec -= nsec; + } + + // Compute the time remaining to wait. tv_nsec is certainly positive. + result->tv_sec = start->tv_sec - end->tv_sec; + result->tv_nsec = start->tv_nsec - end->tv_nsec; + */ +} + #ifdef __cplusplus } /* extern "C" */ #endif From fec3611701398be6d4be64456dcceb8f7494a272 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 3 Apr 2023 15:49:39 -0500 Subject: [PATCH 068/391] configure.ac: include both -I. and -I$srcdir for "circular dependency" test, so that ${build_pwd}/wolfssl/options.h is found in out-of-tree builds; streamline scripting that dynamically sets $TRIM; linuxkm/module_exports.c.template: include wolfssl/wolfcrypt/wolfmath.h, to bring in wc_GetMathInfo() prototype; src/ssl.c: move "Global pointer to constant BN on" to src/ssl_bn.c; and in wolfSSL_Cleanup(), call the new wolfSSL_BN_free_one() rather than using ad hoc cleanup logic; src/ssl_bn.c: add bn_one and wolfSSL_BN_free_one(); src/ssl_asn1.c: fix bugprone-macro-parentheses in bufLenOrNull(); refactor wolfSSL_ASN1_TIME_diff() to avoid floating point math; use intermediate tm_year variable in wolfssl_asn1_time_to_tm() to avoid target-specific type conflicts on tm->tm_year; use "FALL_THROUGH", not "/* fall-through */", in wolfSSL_ASN1_TYPE_set (clang-diagnostic-implicit-fallthrough); wolfcrypt/src/ecc.c: fix identicalInnerCondition in ecc_mul2add(); wolfcrypt/src/integer.c: refactor OPT_CAST()s in mp_grow() to unconditional casts as elsewhere, to mollify a confused cppcheck-all-intmath; tests/api.c: reformat some overlong lines. --- configure.ac | 18 ++++++------------ linuxkm/module_exports.c.template | 1 + src/ssl.c | 8 +------- src/ssl_asn1.c | 18 +++++++++++------- src/ssl_bn.c | 7 +++++++ tests/api.c | 17 ++++++++++------- wolfcrypt/src/ecc.c | 3 +-- wolfcrypt/src/integer.c | 4 ++-- 8 files changed, 39 insertions(+), 37 deletions(-) diff --git a/configure.ac b/configure.ac index 1fa6355b809..f077f90f620 100644 --- a/configure.ac +++ b/configure.ac @@ -8655,18 +8655,12 @@ echo "#endif" >> $OPTION_FILE echo "" >> $OPTION_FILE # check for supported command to trim option with -which colrm &> /dev/null -RESULT=$? -if test "$RESULT" = "0"; then +if colrm &> /dev/null; then TRIM="colrm 3" +elif cut &> /dev/null; then + TRIM="cut -c1-2" else - which cut &> /dev/null - RESULT=$? - if test "$RESULT" = "0"; then - TRIM="cut -c1-2" - else - AC_MSG_ERROR([Could not find colrm or cut to make options file]) - fi + AC_MSG_ERROR([Could not find colrm or cut to make options file]) fi for option in $CPPFLAGS $AM_CPPFLAGS $CFLAGS $AM_CFLAGS; do @@ -8737,7 +8731,7 @@ done < $OPTION_FILE # switch ifdef protection in cyassl/option.h to CYASSL_OPTONS_H, remove bak sed -i.bak 's/WOLFSSL_OPTIONS_H/CYASSL_OPTIONS_H/g' cyassl/options.h -# workaround for mingw sed that may get "Permission denied" trying to preserver permissions +# workaround for mingw sed that may get "Permission denied" trying to preserve permissions case $host_os in mingw*) chmod u+w cyassl/options.h ;; @@ -8748,7 +8742,7 @@ rm cyassl/options.h.bak if test "$ENABLED_OPENSSLEXTRA" = "yes" && test "$ENABLED_LINUXKM" = "no" then SAVE_CFLAGS=$CFLAGS - CFLAGS="$CFLAGS -I$srcdir" + CFLAGS="$CFLAGS -I. -I$srcdir" if test "$ENABLED_INTEL_QA" = "yes" then CFLAGS="$CFLAGS $QAT_FLAGS" diff --git a/linuxkm/module_exports.c.template b/linuxkm/module_exports.c.template index 5d697e52eda..62d6cf1c57f 100644 --- a/linuxkm/module_exports.c.template +++ b/linuxkm/module_exports.c.template @@ -51,6 +51,7 @@ #include #include #include +#include #include #include #include diff --git a/src/ssl.c b/src/ssl.c index eb968c2f6cd..ab0ac330f9d 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -393,9 +393,6 @@ WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local) #endif #ifdef OPENSSL_EXTRA - /* Global pointer to constant BN on */ - static WOLFSSL_BIGNUM* bn_one = NULL; - /* WOLFSSL_NO_OPENSSL_RAND_CB: Allows way to reduce code size for * OPENSSL_EXTRA where RAND callbacks are not used */ #ifndef WOLFSSL_NO_OPENSSL_RAND_CB @@ -14257,10 +14254,7 @@ int wolfSSL_Cleanup(void) return ret; #ifdef OPENSSL_EXTRA - if (bn_one) { - wolfSSL_BN_free(bn_one); - bn_one = NULL; - } + wolfSSL_BN_free_one(); #endif #ifndef NO_SESSION_CACHE diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 213ccebe08b..51d24ccc55f 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -155,7 +155,7 @@ void wolfSSL_ASN1_item_free(void *items, const WOLFSSL_ASN1_ITEM *tpl) } /* Offset buf if not NULL or NULL. */ -#define bufLenOrNull(buf, len) ((buf != NULL) ? ((buf) + (len)) : NULL) +#define bufLenOrNull(buf, len) (((buf) != NULL) ? ((buf) + (len)) : NULL) /* Encode X509 algorithm as DER. * @@ -3246,7 +3246,7 @@ int wolfSSL_ASN1_TIME_diff(int *days, int *secs, const WOLFSSL_ASN1_TIME *from, *secs = 0; } else if (ret == 1) { - const int SECS_PER_DAY = 24 * 60 * 60; + const long long SECS_PER_DAY = 24 * 60 * 60; long long fromSecs; long long toSecs = 0; @@ -3255,9 +3255,9 @@ int wolfSSL_ASN1_TIME_diff(int *days, int *secs, const WOLFSSL_ASN1_TIME *from, ret = wolfssl_asn1_time_to_secs(to, &toSecs); } if (ret == 1) { - double diffSecs = (double)(toSecs - fromSecs); + long long diffSecs = toSecs - fromSecs; *days = (int) (diffSecs / SECS_PER_DAY); - *secs = (int) (diffSecs - (((double)*days) * SECS_PER_DAY)); + *secs = (int) (diffSecs - ((long long)*days * SECS_PER_DAY)); } } @@ -3672,16 +3672,20 @@ static int wolfssl_asn1_time_to_tm(const WOLFSSL_ASN1_TIME* asnTime, if (asnTime->type == V_ASN1_UTCTIME) { /* Get year from UTC TIME string. */ + int tm_year; if ((ret = wolfssl_utctime_year(asn1TimeBuf, asn1TimeBufLen, - &tm->tm_year)) == 1) { + &tm_year)) == 1) { + tm->tm_year = tm_year; /* Month starts after year - 2 characters. */ i = 2; } } else if (asnTime->type == V_ASN1_GENERALIZEDTIME) { /* Get year from GENERALIZED TIME string. */ + int tm_year; if ((ret = wolfssl_gentime_year(asn1TimeBuf, asn1TimeBufLen, - &tm->tm_year)) == 1) { + &tm_year)) == 1) { + tm->tm_year = tm_year; /* Month starts after year - 4 characters. */ i = 4; } @@ -3998,7 +4002,7 @@ void wolfSSL_ASN1_TYPE_set(WOLFSSL_ASN1_TYPE *a, int type, void *value) WOLFSSL_MSG("NULL tag meant to be always empty!"); /* No way to return error - value will not be used. */ } - /* fall-through */ + FALL_THROUGH; case V_ASN1_OBJECT: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: diff --git a/src/ssl_bn.c b/src/ssl_bn.c index 474259688bf..e301c29e826 100644 --- a/src/ssl_bn.c +++ b/src/ssl_bn.c @@ -306,6 +306,9 @@ void wolfSSL_BN_clear(WOLFSSL_BIGNUM* bn) #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef OPENSSL_EXTRA + +static WOLFSSL_BIGNUM* bn_one = NULL; + /* Return a big number with the value of one. * * @return A big number with the value one on success. @@ -349,6 +352,10 @@ const WOLFSSL_BIGNUM* wolfSSL_BN_value_one(void) return one; } +static void wolfSSL_BN_free_one(void) { + wolfSSL_BN_free(bn_one); + bn_one = NULL; +} /* Create a new big number with the same value as the one passed in. * diff --git a/tests/api.c b/tests/api.c index 70c61b06eeb..aee462d5554 100644 --- a/tests/api.c +++ b/tests/api.c @@ -31070,7 +31070,8 @@ static int test_wolfSSL_d2i_ASN1_INTEGER(void) {positiveDer, sizeof(positiveDer), 65537}, {primeDer, sizeof(primeDer), 0} }; - static const size_t NUM_TEST_VECTORS = sizeof(testVectors)/sizeof(testVectors[0]); + static const size_t NUM_TEST_VECTORS = + sizeof(testVectors)/sizeof(testVectors[0]); /* Check d2i error conditions */ /* NULL pointer to input. */ @@ -32492,8 +32493,8 @@ static int test_wolfSSL_ASN1_TIME_to_tm(void) { int res = TEST_SKIPPED; #if (defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) \ - && !defined(NO_ASN_TIME) + defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ + defined(OPENSSL_ALL)) && !defined(NO_ASN_TIME) ASN1_TIME asnTime; struct tm tm; @@ -32890,11 +32891,13 @@ static int test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS(void) V_ASN1_OBJECT, OBJ_nid2obj(nid)), 1); AssertIntEQ(EC_POINT_point2oct(group, point, 0, NULL, 0, NULL), 0); #ifdef HAVE_COMP_KEY - AssertIntGT((len = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, - NULL, 0, NULL)), 0); + AssertIntGT((len = EC_POINT_point2oct( + group, point, POINT_CONVERSION_COMPRESSED, + NULL, 0, NULL)), 0); #else - AssertIntGT((len = EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, - NULL, 0, NULL)), 0); + AssertIntGT((len = EC_POINT_point2oct( + group, point, POINT_CONVERSION_UNCOMPRESSED, + NULL, 0, NULL)), 0); #endif AssertNotNull(der = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1)); #ifdef HAVE_COMP_KEY diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 26fcf5ef396..5a6ac716241 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -7669,10 +7669,9 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC); if (mu == NULL) err = MEMORY_E; + else #endif - if (err == MP_OKAY) { err = mp_init(mu); - } if (err == MP_OKAY) { err = mp_montgomery_calc_normalization(mu, modulus); diff --git a/wolfcrypt/src/integer.c b/wolfcrypt/src/integer.c index 610512e708d..01f07d295ab 100644 --- a/wolfcrypt/src/integer.c +++ b/wolfcrypt/src/integer.c @@ -423,7 +423,7 @@ int mp_grow (mp_int * a, int size) * in case the operation failed we don't want * to overwrite the dp member of a. */ - tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size, NULL, + tmp = (mp_digit *)XREALLOC (a->dp, sizeof (mp_digit) * size, NULL, DYNAMIC_TYPE_BIGINT); if (tmp == NULL) { /* reallocation failed but "a" is still valid [can be freed] */ @@ -3280,7 +3280,7 @@ int mp_init_size (mp_int * a, int size) size += (MP_PREC * 2) - (size % MP_PREC); /* alloc mem */ - a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size, NULL, + a->dp = (mp_digit *)XMALLOC (sizeof (mp_digit) * size, NULL, DYNAMIC_TYPE_BIGINT); if (a->dp == NULL) { return MP_MEM; From 0aa2a4fea3a12667352c211fd52544d026c8016c Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 3 Apr 2023 16:51:07 +1000 Subject: [PATCH 069/391] cppcheck fixes Fix checking of negative with unsigned variables. Check digestSz for 0 in wc_SSH_KDF() so that no possibility of dividing by zero. Change XMEMCPY to XMEMSET in renesas_sce_util.c. Fix test.c to free prvTmp and pubTmp on read error. Remove unused variables. XFREE checks for NULL so don't check before call. Move variable declarations to reduce scope. --- IDE/Espressif/ESP-IDF/test/test_wolfssl.c | 2 +- examples/benchmark/tls_bench.c | 4 +- examples/client/client.c | 10 +- examples/echoserver/echoserver.c | 3 +- examples/server/server.c | 22 +-- src/bio.c | 10 +- src/conf.c | 5 +- src/internal.c | 45 +++--- src/keys.c | 4 +- src/ocsp.c | 6 +- src/pk.c | 43 ++---- src/ssl.c | 142 +++++++++--------- src/ssl_bn.c | 2 +- src/tls.c | 26 ++-- src/tls13.c | 45 +++--- src/wolfio.c | 5 +- src/x509.c | 11 +- src/x509_str.c | 29 ++-- wolfcrypt/benchmark/benchmark.c | 7 +- wolfcrypt/src/asn.c | 111 +++++++------- wolfcrypt/src/coding.c | 5 +- wolfcrypt/src/curve25519.c | 2 +- wolfcrypt/src/curve448.c | 11 +- wolfcrypt/src/dh.c | 5 +- wolfcrypt/src/evp.c | 70 +++++---- wolfcrypt/src/kdf.c | 2 +- wolfcrypt/src/logging.c | 20 +-- wolfcrypt/src/memory.c | 6 +- wolfcrypt/src/misc.c | 8 +- wolfcrypt/src/port/Renesas/renesas_sce_util.c | 4 +- wolfcrypt/src/port/caam/caam_aes.c | 1 - wolfcrypt/src/port/caam/caam_driver.c | 2 +- wolfcrypt/src/port/cypress/psoc6_crypto.c | 2 - wolfcrypt/src/port/xilinx/xil-sha3.c | 2 + wolfcrypt/src/pwdbased.c | 9 +- wolfcrypt/src/random.c | 9 +- wolfcrypt/src/rsa.c | 10 +- wolfcrypt/src/sha3.c | 9 +- wolfcrypt/src/wolfmath.c | 21 ++- wolfcrypt/test/test.c | 65 ++++---- wolfssl/test.h | 19 +-- 41 files changed, 394 insertions(+), 420 deletions(-) diff --git a/IDE/Espressif/ESP-IDF/test/test_wolfssl.c b/IDE/Espressif/ESP-IDF/test/test_wolfssl.c index c77b7f7eb2e..6b7bbb48311 100644 --- a/IDE/Espressif/ESP-IDF/test/test_wolfssl.c +++ b/IDE/Espressif/ESP-IDF/test/test_wolfssl.c @@ -1125,7 +1125,7 @@ TEST_CASE("wolfssl aes sha256 rsa multi-thread test ", "[wolfssl]") exit_loop = true; /* wait until rsa test finishes */ - while(rsa_elapsedTime<=0){ vTaskDelay(1); } + while(rsa_elapsedTime==0){ vTaskDelay(1); } ESP_LOGI(TAG, "Waiting another %llu s. rsa test would take more time to finish.", (rsa_elapsedTime+3000)/portTICK_PERIOD_MS); diff --git a/examples/benchmark/tls_bench.c b/examples/benchmark/tls_bench.c index 91468bc7794..de384cb214c 100644 --- a/examples/benchmark/tls_bench.c +++ b/examples/benchmark/tls_bench.c @@ -1269,12 +1269,10 @@ static int SocketWaitClient(info_t* info) int connd; struct sockaddr_in clientAddr; socklen_t size = sizeof(clientAddr); -#ifdef WOLFSSL_DTLS - char msg[64]; -#endif #ifdef WOLFSSL_DTLS if (info->doDTLS) { + char msg[64]; #ifdef HAVE_PTHREAD if (!info->clientOrserverOnly) { PTHREAD_CHECK_RET(pthread_mutex_lock(&info->dtls_mutex)); diff --git a/examples/client/client.c b/examples/client/client.c index 01553b82195..058c193ce9c 100644 --- a/examples/client/client.c +++ b/examples/client/client.c @@ -782,8 +782,8 @@ static int ClientBenchmarkThroughput(WOLFSSL_CTX* ctx, char* host, word16 port, err_sys("Client buffer malloc failed"); } doExit: - if (tx_buffer) XFREE(tx_buffer, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (rx_buffer) XFREE(rx_buffer, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(tx_buffer, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(rx_buffer, NULL, DYNAMIC_TYPE_TMP_BUFFER); } else { err_sys("wolfSSL_connect failed"); @@ -953,7 +953,6 @@ static int ClientWrite(WOLFSSL* ssl, const char* msg, int msgSz, const char* str int exitWithRet) { int ret, err; - char buffer[WOLFSSL_MAX_ERROR_SZ]; do { err = 0; /* reset error */ @@ -974,6 +973,7 @@ static int ClientWrite(WOLFSSL* ssl, const char* msg, int msgSz, const char* str #endif ); if (ret != msgSz) { + char buffer[WOLFSSL_MAX_ERROR_SZ]; fprintf(stderr, "SSL_write%s msg error %d, %s\n", str, err, wolfSSL_ERR_error_string(err, buffer)); if (!exitWithRet) { @@ -4311,9 +4311,7 @@ THREAD_RETURN WOLFSSL_THREAD client_test(void* args) #if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \ defined(HAVE_EXT_CACHE)) - if (flatSession) { - XFREE(flatSession, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(flatSession, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif wolfSSL_SESSION_free(session); session = NULL; diff --git a/examples/echoserver/echoserver.c b/examples/echoserver/echoserver.c index 5a01c1226c2..e839f0b0f55 100644 --- a/examples/echoserver/echoserver.c +++ b/examples/echoserver/echoserver.c @@ -298,7 +298,6 @@ THREAD_RETURN CYASSL_THREAD echoserver_test(void* args) CYASSL* ssl = NULL; CYASSL* write_ssl = NULL; /* may have separate w/ HAVE_WRITE_DUP */ char command[SVR_COMMAND_SIZE+1]; - int echoSz = 0; int clientfd; int firstRead = 1; int gotFirstG = 0; @@ -374,6 +373,8 @@ THREAD_RETURN CYASSL_THREAD echoserver_test(void* args) #endif while (1) { + int echoSz; + do { err = 0; /* reset error */ ret = CyaSSL_read(ssl, command, sizeof(command)-1); diff --git a/examples/server/server.c b/examples/server/server.c index 6390dd5547f..9b695a44f9b 100644 --- a/examples/server/server.c +++ b/examples/server/server.c @@ -269,7 +269,6 @@ static int TestEmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx) WOLFSSL_TEST_DTLS_CTX* dtlsCtx = (WOLFSSL_TEST_DTLS_CTX*)ctx; int sd = dtlsCtx->wfd; int sent; - int err; (void)ssl; @@ -291,7 +290,7 @@ static int TestEmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx) sent = TranslateReturnCode(sent, sd); if (sent < 0) { - err = wolfSSL_LastError(); + int err = wolfSSL_LastError(); WOLFSSL_MSG("Embed Send To error"); if (err == SOCKET_EWOULDBLOCK || err == SOCKET_EAGAIN) { @@ -337,8 +336,6 @@ static int NonBlockingSSL_Accept(SSL* ssl) || error == WC_PENDING_E #endif )) { - int currTimeout = 1; - if (error == WOLFSSL_ERROR_WANT_READ) { /* printf("... server would read block\n"); */ } @@ -354,6 +351,8 @@ static int NonBlockingSSL_Accept(SSL* ssl) else #endif { + int currTimeout = 1; + if (error == WOLFSSL_ERROR_WANT_WRITE) { select_ret = tcp_select_tx(sockfd, currTimeout); @@ -408,7 +407,7 @@ int ServerEchoData(SSL* ssl, int clientfd, int echoData, int block, { int ret = 0, err; double start = 0, rx_time = 0, tx_time = 0; - int select_ret, len, rx_pos; + int len, rx_pos; size_t xfer_bytes = 0; char* buffer; @@ -420,7 +419,7 @@ int ServerEchoData(SSL* ssl, int clientfd, int echoData, int block, while ((echoData && throughput == 0) || (!echoData && xfer_bytes < throughput)) { - select_ret = tcp_select(clientfd, 1); /* Timeout=1 second */ + int select_ret = tcp_select(clientfd, 1); /* Timeout=1 second */ if (select_ret == TEST_RECV_READY) { if (throughput) @@ -611,7 +610,6 @@ static void ServerRead(WOLFSSL* ssl, char* input, int inputLen) static void ServerWrite(WOLFSSL* ssl, const char* output, int outputLen) { int ret, err; - char buffer[WOLFSSL_MAX_ERROR_SZ]; int len; #ifdef OPENSSL_ALL @@ -642,6 +640,7 @@ static void ServerWrite(WOLFSSL* ssl, const char* output, int outputLen) } } while (err == WC_PENDING_E || err == WOLFSSL_ERROR_WANT_WRITE); if (ret != outputLen) { + char buffer[WOLFSSL_MAX_ERROR_SZ]; fprintf(stderr, "SSL_write msg error %d, %s\n", err, ERR_error_string(err, buffer)); err_sys_ex(runWithErrors, "SSL_write failed"); @@ -2193,10 +2192,12 @@ THREAD_RETURN WOLFSSL_THREAD server_test(void* args) case 262: { /* Note: this requires TSL1.3 (version >= 4) */ #ifdef HAVE_ECC - int idx = 0; /* ecc curve index */ int j = 0; /* our group index */ #endif if (NULL == myoptarg) { + #ifdef HAVE_ECC + int idx = 0; /* ecc curve index */ + #endif Usage(); if (lng_index == 1) { /* TODO: Need Japanese translation */ @@ -3167,10 +3168,11 @@ THREAD_RETURN WOLFSSL_THREAD server_test(void* args) #if defined(WOLFSSL_DTLS) && defined(USE_WOLFSSL_IO) if (doDTLS && dtlsUDP) { byte b[1500]; - int n; int isClientHello = 0; while (!isClientHello) { + int n; + client_len = sizeof client_addr; /* For DTLS, peek at the next datagram so we can get the @@ -3411,7 +3413,6 @@ THREAD_RETURN WOLFSSL_THREAD server_test(void* args) #if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK) { byte* rnd = NULL; - byte* pt; size_t size; /* get size of buffer then print */ @@ -3438,6 +3439,7 @@ THREAD_RETURN WOLFSSL_THREAD server_test(void* args) } if (rnd) { + byte* pt; printf("Server Random : "); for (pt = rnd; pt < rnd + size; pt++) printf("%02X", *pt); printf("\n"); diff --git a/src/bio.c b/src/bio.c index 03c5ad76218..035835ea443 100644 --- a/src/bio.c +++ b/src/bio.c @@ -2057,11 +2057,10 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_BIO *wolfSSL_BIO_new_connect(const char *str) { WOLFSSL_BIO *bio; - const char* port; WOLFSSL_ENTER("wolfSSL_BIO_new_connect"); bio = wolfSSL_BIO_new(wolfSSL_BIO_s_socket()); if (bio) { - port = XSTRSTR(str, ":"); + const char* port = XSTRSTR(str, ":"); if (port != NULL) bio->port = (word16)XATOI(port + 1); @@ -2261,8 +2260,6 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) void wolfSSL_BIO_ssl_shutdown(WOLFSSL_BIO* b) { - int rc; - WOLFSSL_ENTER("wolfSSL_BIO_ssl_shutdown"); if (b == NULL) { @@ -2279,7 +2276,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } if (b->ptr != NULL) { - rc = wolfSSL_shutdown((WOLFSSL*)b->ptr); + int rc = wolfSSL_shutdown((WOLFSSL*)b->ptr); if (rc == SSL_SHUTDOWN_NOT_DONE) { /* In this case, call again to give us a chance to read the * close notify alert from the other end. */ @@ -2386,7 +2383,6 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) long wolfSSL_BIO_set_conn_hostname(WOLFSSL_BIO* b, char* name) { - size_t currLen = 0; size_t newLen = 0; WOLFSSL_ENTER("wolfSSL_BIO_set_conn_hostname"); @@ -2414,7 +2410,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } } else { - currLen = XSTRLEN(b->ip); + size_t currLen = XSTRLEN(b->ip); if (currLen != newLen) { b->ip = (char*)XREALLOC(b->ip, newLen + 1, b->heap, DYNAMIC_TYPE_OPENSSL); diff --git a/src/conf.c b/src/conf.c index 0a63243c413..4693cbd8c9b 100644 --- a/src/conf.c +++ b/src/conf.c @@ -158,7 +158,6 @@ long wolfSSL_TXT_DB_write(WOLFSSL_BIO *out, WOLFSSL_TXT_DB *db) long totalLen = 0; char buf[512]; /* Should be more than enough for a single row */ char* bufEnd = buf + sizeof(buf); - int sz; int i; WOLFSSL_ENTER("wolfSSL_TXT_DB_write"); @@ -172,6 +171,7 @@ long wolfSSL_TXT_DB_write(WOLFSSL_BIO *out, WOLFSSL_TXT_DB *db) while (data) { char** fields = (char**)data->data.string; char* idx = buf; + int sz; if (!fields) { WOLFSSL_MSG("Missing row"); @@ -1499,10 +1499,9 @@ static const conf_cmd_tbl* wolfssl_conf_find_cmd(WOLFSSL_CONF_CTX* cctx, const char* cmd) { size_t i = 0; - size_t cmdlen = 0; if (cctx->flags & WOLFSSL_CONF_FLAG_CMDLINE) { - cmdlen = XSTRLEN(cmd); + size_t cmdlen = XSTRLEN(cmd); if (cmdlen < 2) { WOLFSSL_MSG("bad cmdline command"); diff --git a/src/internal.c b/src/internal.c index 991309f7afe..b689550d3d7 100644 --- a/src/internal.c +++ b/src/internal.c @@ -1715,7 +1715,6 @@ int wolfSSL_session_import_internal(WOLFSSL* ssl, const unsigned char* buf, int ret = 0; int optSz = 0; int rc; - byte validProto = 0; /* did we find a valid protocol */ WOLFSSL_ENTER("wolfSSL_session_import_internal"); /* check at least enough room for protocol and length */ @@ -1725,6 +1724,8 @@ int wolfSSL_session_import_internal(WOLFSSL* ssl, const unsigned char* buf, /* Check if is TLS export protocol */ if (ret == 0) { + byte validProto = 0; /* did we find a valid protocol */ + if (buf[idx] == (byte)TLS_EXPORT_PRO && (buf[idx + 1] & 0xF0) == ((byte)TLS_EXPORT_PRO & 0xF0)) { validProto = 1; @@ -8902,7 +8903,6 @@ int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket) { int ret = 0; DtlsMsg* pool; - int epochOrder; WOLFSSL_ENTER("DtlsMsgPoolSend"); @@ -8926,6 +8926,8 @@ int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket) } while (pool != NULL) { + int epochOrder; + if (pool->epoch == 0) { DtlsRecordLayerHeader* dtls; @@ -10447,9 +10449,6 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, RecordLayerHeader* rh, word16 *size) { byte tls12minor; -#ifdef WOLFSSL_DTLS - int ret; -#endif /* WOLFSSL_DTLS */ #ifdef OPENSSL_ALL word32 start = *inOutIdx; @@ -10469,7 +10468,7 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, } else { #ifdef WOLFSSL_DTLS - ret = GetDtlsRecordHeader(ssl, inOutIdx, rh, size); + int ret = GetDtlsRecordHeader(ssl, inOutIdx, rh, size); if (ret != 0) return ret; #endif @@ -11418,18 +11417,19 @@ static int BuildFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender) int MatchDomainName(const char* pattern, int len, const char* str) { int ret = 0; - char p, s; if (pattern == NULL || str == NULL || len <= 0) return 0; while (len > 0) { - p = (char)XTOLOWER((unsigned char)*pattern++); + char p = (char)XTOLOWER((unsigned char)*pattern++); if (p == '\0') break; if (p == '*') { + char s; + while (--len > 0 && (p = (char)XTOLOWER((unsigned char)*pattern++)) == '*') { } @@ -16263,14 +16263,14 @@ static WC_INLINE word32 UpdateHighwaterMark(word32 cur, word32 first, * expected sequence number. 0 is special where it is an overflow. */ static void _DtlsUpdateWindowGTSeq(word32 diff, word32* window) { - word32 idx, temp, i; word32 oldWindow[WOLFSSL_DTLS_WINDOW_WORDS]; if (diff == 0 || diff >= DTLS_SEQ_BITS) XMEMSET(window, 0, DTLS_SEQ_SZ); else { - temp = 0; - idx = diff / DTLS_WORD_BITS; + word32 i; + word32 temp = 0; + word32 idx = diff / DTLS_WORD_BITS; diff %= DTLS_WORD_BITS; XMEMCPY(oldWindow, window, sizeof(oldWindow)); @@ -18303,14 +18303,13 @@ static byte MaskPadding(const byte* data, int sz, int macSz) int i; int checkSz = sz - 1; byte paddingSz = data[sz - 1]; - byte mask; byte good = ctMaskGT(paddingSz, sz - 1 - macSz); if (checkSz > TLS_MAX_PAD_SZ) checkSz = TLS_MAX_PAD_SZ; for (i = 0; i < checkSz; i++) { - mask = ctMaskLTE(i, paddingSz); + byte mask = ctMaskLTE(i, paddingSz); good |= mask & (data[sz - 1 - i] ^ paddingSz); } @@ -18775,7 +18774,6 @@ static int DoAlert(WOLFSSL* ssl, byte* input, word32* inOutIdx, int* type) byte level; byte code; word32 dataSz = (word32)ssl->curSize; - int ivExtra = 0; #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA) if (ssl->hsInfoOn) @@ -18793,6 +18791,7 @@ static int DoAlert(WOLFSSL* ssl, byte* input, word32* inOutIdx, int* type) #endif if (IsEncryptionOn(ssl, 0)) { + int ivExtra = 0; #ifndef WOLFSSL_AEAD_ONLY if (ssl->specs.cipher_type == block) { if (ssl->options.tls1_1) @@ -18864,7 +18863,6 @@ static int DoAlert(WOLFSSL* ssl, byte* input, word32* inOutIdx, int* type) static int GetInputData(WOLFSSL *ssl, word32 size) { - int in; int inSz; int maxLength; int usedLength; @@ -18906,7 +18904,7 @@ static int GetInputData(WOLFSSL *ssl, word32 size) /* read data from network */ do { - in = wolfSSLReceive(ssl, + int in = wolfSSLReceive(ssl, ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.length, inSz); @@ -18974,7 +18972,6 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, int content, word32* padSz) { #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY) - int ivExtra = 0; int ret; word32 pad = 0; word32 padByte = 0; @@ -18988,6 +18985,7 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, if (ssl->specs.cipher_type == block) { + int ivExtra = 0; if (ssl->options.tls1_1) ivExtra = ssl->specs.block_size; pad = *(input + msgSz - ivExtra - 1); @@ -23038,10 +23036,8 @@ int RetrySendAlert(WOLFSSL* ssl) /* send alert message */ int SendAlert(WOLFSSL* ssl, int severity, int type) { - int ret; - if (ssl->pendingAlert.level != alert_none) { - ret = RetrySendAlert(ssl); + int ret = RetrySendAlert(ssl); if (ret != 0) { if (ssl->pendingAlert.level == alert_none || (ssl->pendingAlert.level != alert_fatal && @@ -24755,13 +24751,13 @@ int SetCipherList(WOLFSSL_CTX* ctx, Suites* suites, const char* list) #endif /* OPENSSL_EXTRA */ for (i = 0; i < suiteSz; i++) { - int j; - if (XSTRNCMP(name, cipher_names[i].name, sizeof(name)) == 0 #ifndef NO_ERROR_STRINGS || XSTRNCMP(name, cipher_names[i].name_iana, sizeof(name)) == 0 #endif ) { + int j; + #ifdef WOLFSSL_DTLS /* don't allow stream ciphers with DTLS */ if (ctx->method->version.major == DTLS_MAJOR) { @@ -26944,10 +26940,11 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, ssl->options.haveEMS = 0; /* If no extensions, no EMS */ #else { - int allowExt = 0; byte pendingEMS = 0; if ( (i - begin) < helloSz) { + int allowExt = 0; + if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor >= TLSv1_MINOR) { @@ -36683,7 +36680,6 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], { byte *tmpRsa; byte mask; - int i; /* Add the signature length to idx */ args->idx += args->length; @@ -36718,6 +36714,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], ctMaskCopy(~mask, (byte*)&args->output, (byte*)&tmpRsa, sizeof(args->output)); if (args->output != NULL) { + int i; /* Use random secret on error */ for (i = VERSION_SZ; i < SECRET_LEN; i++) { ssl->arrays->preMasterSecret[i] = diff --git a/src/keys.c b/src/keys.c index 8f960ba0e01..8251279363b 100644 --- a/src/keys.c +++ b/src/keys.c @@ -3326,7 +3326,7 @@ int DeriveKeys(WOLFSSL* ssl) int length = 2 * ssl->specs.hash_size + 2 * ssl->specs.key_size + 2 * ssl->specs.iv_size; - int rounds = (length + WC_MD5_DIGEST_SIZE - 1 ) / WC_MD5_DIGEST_SIZE, i; + int rounds = (length + WC_MD5_DIGEST_SIZE - 1 ) / WC_MD5_DIGEST_SIZE; int ret = 0; #ifdef WOLFSSL_SMALL_STACK @@ -3375,6 +3375,8 @@ int DeriveKeys(WOLFSSL* ssl) ret = wc_InitSha(sha); } if (ret == 0) { + int i; + XMEMCPY(md5Input, ssl->arrays->masterSecret, SECRET_LEN); for (i = 0; i < rounds; ++i) { diff --git a/src/ocsp.c b/src/ocsp.c index d3954a68bf9..796b80f55b5 100644 --- a/src/ocsp.c +++ b/src/ocsp.c @@ -1260,9 +1260,6 @@ int wolfSSL_OCSP_id_get0_info(WOLFSSL_ASN1_STRING **name, WOLFSSL_ASN1_OBJECT **pmd, WOLFSSL_ASN1_STRING **keyHash, WOLFSSL_ASN1_INTEGER **serial, WOLFSSL_OCSP_CERTID *cid) { - int i = 0; - WOLFSSL_ASN1_INTEGER* ser; - WOLFSSL_ENTER("wolfSSL_OCSP_id_get0_info"); if (cid == NULL) @@ -1270,6 +1267,9 @@ int wolfSSL_OCSP_id_get0_info(WOLFSSL_ASN1_STRING **name, /* build up ASN1_INTEGER for serial */ if (serial != NULL) { + int i = 0; + WOLFSSL_ASN1_INTEGER* ser; + ser = wolfSSL_ASN1_INTEGER_new(); if (ser == NULL) return 0; diff --git a/src/pk.c b/src/pk.c index 1c371454ea0..e8be5292117 100644 --- a/src/pk.c +++ b/src/pk.c @@ -584,7 +584,6 @@ static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value, int ret = 1; int len; char line[PRINT_NUM_MAX_VALUE_LINE + 1]; - word32 v; /* Get the length of hex encoded value. */ len = mp_unsigned_bin_size(value); @@ -599,7 +598,7 @@ static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value, } if (ret == 1) { /* Get 32-bits of value. */ - v = (word32)value->dp[0]; + word32 v = (word32)value->dp[0]; /* Print the line to the string. */ len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v, v); @@ -2296,7 +2295,6 @@ int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent) int sz = 0; RsaKey* key = NULL; char line[RSA_PRINT_MAX_HEADER_LINE]; - int len; int i = 0; mp_int *num = NULL; /* Header strings. */ @@ -2328,7 +2326,7 @@ int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent) } if (ret == 1) { /* Print header line. */ - len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n", + int len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n", (!mp_iszero(&key->d)) ? "Private-Key" : "Public-Key", sz); if (len >= (int)sizeof(line)) { WOLFSSL_ERROR_MSG("Buffer overflow while formatting key preamble"); @@ -4577,7 +4575,6 @@ int wolfSSL_RSA_blinding_on(WOLFSSL_RSA* rsa, WOLFSSL_BN_CTX* bnCtx) int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent) { int ret = 1; - int pBits; WOLFSSL_ENTER("wolfSSL_DSA_print_fp"); @@ -4586,7 +4583,7 @@ int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent) } if (ret == 1 && dsa->p != NULL) { - pBits = wolfSSL_BN_num_bits(dsa->p); + int pBits = wolfSSL_BN_num_bits(dsa->p); if (pBits == 0) { ret = 0; } @@ -9693,7 +9690,6 @@ char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group, { static const char* hexDigit = "0123456789ABCDEF"; char* hex = NULL; - int id; int i; int sz = 0; int len = 0; @@ -9713,7 +9709,7 @@ char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group, if (!err) { /* Get curve id to look up ordinate size. */ - id = wc_ecc_get_curve_id(group->curve_idx); + int id = wc_ecc_get_curve_id(group->curve_idx); /* Get size of ordinate. */ if ((sz = wc_ecc_get_curve_size_from_id(id)) < 0) { err = 1; @@ -9808,7 +9804,6 @@ int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group, const WOLFSSL_EC_POINT *point, unsigned char *out, unsigned int *len) { int res = 1; - int ret; WOLFSSL_ENTER("wolfSSL_ECPoint_i2d"); @@ -9830,7 +9825,7 @@ int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group, if (res == 1) { /* DER encode point in uncompressed format. */ - ret = wc_ecc_export_point_der(group->curve_idx, + int ret = wc_ecc_export_point_der(group->curve_idx, (ecc_point*)point->internal, out, len); /* Check return. When out is NULL, return will be length only error. */ if ((ret != MP_OKAY) && ((out != NULL) || (ret != LENGTH_ONLY_E))) { @@ -9965,8 +9960,6 @@ size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group, } /* Not infinity. */ else if (!err) { - int ret; - /* Validate format. */ if (form != POINT_CONVERSION_UNCOMPRESSED #ifndef HAVE_SELFTEST @@ -9977,23 +9970,18 @@ size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group, err = 1; } - #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) if (!err) { + int ret; + + #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) /* Encode as compressed or uncompressed. */ ret = wc_ecc_export_point_der_ex(group->curve_idx, (ecc_point*)point->internal, buf, &enc_len, compressed); - /* Check return. When buf is NULL, return will be length only - * error. - */ - if (ret != ((buf != NULL) ? MP_OKAY : LENGTH_ONLY_E)) { - err = 1; - } - } #else - if (!err) { /* Encode uncompressed point in DER format. */ ret = wc_ecc_export_point_der(group->curve_idx, (ecc_point*)point->internal, buf, &enc_len); + #endif /* !HAVE_SELFTEST */ /* Check return. When buf is NULL, return will be length only * error. */ @@ -10001,7 +9989,6 @@ size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group, err = 1; } } - #endif /* !HAVE_SELFTEST */ } /* On error, return encoding length of 0. */ @@ -11747,7 +11734,8 @@ int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *key, unsigned char **out) /* Calculate the length of the private key DER encoding using internal EC * key. */ - if ((!err) && ((len = wc_EccKeyDerSize((ecc_key*)key->internal, 0)) <= 0)) { + if ((!err) && ((int)(len = wc_EccKeyDerSize((ecc_key*)key->internal, 0)) <= + 0)) { WOLFSSL_MSG("wc_EccKeyDerSize error"); err = 1; } @@ -13222,8 +13210,6 @@ WOLFSSL_ECDSA_SIG* wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG** sig, */ int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp) { - word32 rLen; - word32 sLen; word32 len = 0; /* Validate parameter. */ @@ -13233,10 +13219,10 @@ int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp) * top bit set. */ /* Get total length of r including any prepended zero. */ - rLen = mp_leading_bit((mp_int*)sig->r->internal) + + word32 rLen = mp_leading_bit((mp_int*)sig->r->internal) + mp_unsigned_bin_size((mp_int*)sig->r->internal); /* Get total length of s including any prepended zero. */ - sLen = mp_leading_bit((mp_int*)sig->s->internal) + + word32 sLen = mp_leading_bit((mp_int*)sig->s->internal) + mp_unsigned_bin_size((mp_int*)sig->s->internal); /* Calculate length of data in sequence. */ len = 1 + ASN_LEN_SIZE(rLen) + rLen + @@ -13629,7 +13615,6 @@ int wolfSSL_ECDH_compute_key(void *out, size_t outLen, int err = 0; word32 len = 0; ecc_key* key = NULL; - int ret; #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0)) int setGlobalRNG = 0; @@ -13658,6 +13643,8 @@ int wolfSSL_ECDH_compute_key(void *out, size_t outLen, } if (!err) { + int ret; + /* Get the internal key. */ key = (ecc_key*)privKey->internal; /* Set length into variable of type suitable for wolfSSL API. */ diff --git a/src/ssl.c b/src/ssl.c index ab0ac330f9d..e994c461e90 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -1814,14 +1814,13 @@ int wolfSSL_get_ciphers(char* buf, int len) const CipherSuiteInfo* ciphers = GetCipherNames(); int ciphersSz = GetCipherNamesSize(); int i; - int cipherNameSz; if (buf == NULL || len <= 0) return BAD_FUNC_ARG; /* Add each member to the buffer delimited by a : */ for (i = 0; i < ciphersSz; i++) { - cipherNameSz = (int)XSTRLEN(ciphers[i].name); + int cipherNameSz = (int)XSTRLEN(ciphers[i].name); if (cipherNameSz + 1 < len) { XSTRNCPY(buf, ciphers[i].name, len); buf += cipherNameSz; @@ -4637,14 +4636,13 @@ int wolfSSL_want_write(WOLFSSL* ssl) char* wolfSSL_ERR_error_string(unsigned long errNumber, char* data) { - static char tmp[WOLFSSL_MAX_ERROR_SZ] = {0}; - WOLFSSL_ENTER("wolfSSL_ERR_error_string"); if (data) { SetErrorString((int)errNumber, data); return data; } else { + static char tmp[WOLFSSL_MAX_ERROR_SZ] = {0}; SetErrorString((int)errNumber, tmp); return tmp; } @@ -4657,10 +4655,9 @@ void wolfSSL_ERR_error_string_n(unsigned long e, char* buf, unsigned long len) if (len >= WOLFSSL_MAX_ERROR_SZ) wolfSSL_ERR_error_string(e, buf); else { - char tmp[WOLFSSL_MAX_ERROR_SZ]; - WOLFSSL_MSG("Error buffer too short, truncating"); if (len) { + char tmp[WOLFSSL_MAX_ERROR_SZ]; wolfSSL_ERR_error_string(e, tmp); XMEMCPY(buf, tmp, len-1); buf[len-1] = '\0'; @@ -5176,11 +5173,12 @@ WOLFSSL_CERT_MANAGER* wolfSSL_CertManagerNew(void) void wolfSSL_CertManagerFree(WOLFSSL_CERT_MANAGER* cm) { - int doFree = 0; - int ret; WOLFSSL_ENTER("wolfSSL_CertManagerFree"); if (cm) { + int doFree = 0; + int ret; + wolfSSL_RefDec(&cm->ref, &doFree, &ret); #ifdef WOLFSSL_REFCNT_ERROR_RETURN if (ret != 0) { @@ -6569,9 +6567,6 @@ static int ProcessUserChain(WOLFSSL_CTX* ctx, const unsigned char* buff, { int ret = 0; void* heap = wolfSSL_CTX_GetHeap(ctx, ssl); -#ifdef WOLFSSL_TLS13 - int cnt = 0; -#endif if ((type == CA_TYPE) && (ctx == NULL)) { WOLFSSL_MSG("Need context for CA load"); @@ -6591,6 +6586,9 @@ static int ProcessUserChain(WOLFSSL_CTX* ctx, const unsigned char* buff, long consumed = info->consumed; word32 idx = 0; int gotOne = 0; + #ifdef WOLFSSL_TLS13 + int cnt = 0; + #endif /* Calculate max possible size, including max headers */ bufferSz = (word32)(sz - consumed) + (CERT_HEADER_SZ * MAX_CHAIN_DEPTH); @@ -8783,9 +8781,7 @@ int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file, { int ret = WOLFSSL_SUCCESS; #ifndef NO_WOLFSSL_DIR - int fileRet; int successCount = 0; - int failCount = 0; #endif int verify; @@ -8817,6 +8813,8 @@ int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file, if (ret == WOLFSSL_SUCCESS && path) { #ifndef NO_WOLFSSL_DIR char* name = NULL; + int fileRet; + int failCount = 0; #ifdef WOLFSSL_SMALL_STACK ReadDirCtx* readCtx; readCtx = (ReadDirCtx*)XMALLOC(sizeof(ReadDirCtx), ctx->heap, @@ -10173,7 +10171,6 @@ static WOLFSSL_EVP_PKEY* d2iGenericKey(WOLFSSL_EVP_PKEY** out, word32 keyIdx = 0; DhKey* key = NULL; int ret; - int elements; #ifdef WOLFSSL_SMALL_STACK DhKey* dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH); if (dh == NULL) @@ -10221,7 +10218,8 @@ static WOLFSSL_EVP_PKEY* d2iGenericKey(WOLFSSL_EVP_PKEY** out, keyIdx = 0; if (wc_DhKeyDecode(mem, &keyIdx, key, (word32)memSz) == 0) { - elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q | ELEMENT_PUB; + int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q | + ELEMENT_PUB; if (priv) elements |= ELEMENT_PRV; if(SetDhExternal_ex(pkey->dh, elements) @@ -10554,7 +10552,6 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY(WOLFSSL_EVP_PKEY** out, /* helper function to get raw pointer to DER buffer from WOLFSSL_EVP_PKEY */ static int wolfSSL_EVP_PKEY_get_der(const WOLFSSL_EVP_PKEY* key, unsigned char** der) { - unsigned char* pt; int sz; word16 pkcs8HeaderSz; @@ -10568,7 +10565,7 @@ static int wolfSSL_EVP_PKEY_get_der(const WOLFSSL_EVP_PKEY* key, unsigned char** pkcs8HeaderSz = key->pkcs8HeaderSz; sz = key->pkey_sz - pkcs8HeaderSz; if (der) { - pt = (unsigned char*)key->pkey.ptr; + unsigned char* pt = (unsigned char*)key->pkey.ptr; if (*der) { /* since this function signature has no size value passed in it is * assumed that the user has allocated a large enough buffer */ @@ -15085,7 +15082,7 @@ ClientSession* AddSessionToClientCache(int side, int row, int idx, byte* serverI word16 useTicket) { int error = -1; - word32 clientRow = 0, clientIdx = 0, sessionIDHash = 0; + word32 clientRow = 0, clientIdx = 0; (void)useTicket; if (side == WOLFSSL_CLIENT_END && row != INVALID_SESSION_ROW @@ -15117,7 +15114,8 @@ ClientSession* AddSessionToClientCache(int side, int row, int idx, byte* serverI ClientCache[clientRow].Clients[clientIdx].serverIdx = (word16)idx; if (sessionID != NULL) { - sessionIDHash = HashObject(sessionID, ID_LEN, &error); + word32 sessionIDHash = HashObject(sessionID, ID_LEN, + &error); if (error == 0) { ClientCache[clientRow].Clients[clientIdx].sessionIDHash = sessionIDHash; @@ -15548,9 +15546,6 @@ void AddSession(WOLFSSL* ssl) const byte* id = NULL; byte idSz = 0; WOLFSSL_SESSION* session = ssl->session; -#ifdef HAVE_EXT_CACHE - int cbRet = 0; -#endif (void)error; @@ -15663,6 +15658,7 @@ void AddSession(WOLFSSL* ssl) #ifdef HAVE_EXT_CACHE if (error == 0 && ssl->ctx->new_sess_cb != NULL) { + int cbRet = 0; wolfSSL_SESSION_up_ref(session); cbRet = ssl->ctx->new_sess_cb(ssl, session); if (cbRet == 0) @@ -21383,8 +21379,6 @@ WOLFSSL_SESSION* wolfSSL_SESSION_dup(WOLFSSL_SESSION* session) void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) { - int isZero; - session = ClientSessionToSession(session); if (session == NULL) return; @@ -21393,6 +21387,7 @@ void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) if (session->ref.count > 0) { int ret; + int isZero; wolfSSL_RefDec(&session->ref, &isZero, &ret); (void)ret; if (!isZero) { @@ -21922,7 +21917,6 @@ int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher) {NULL, NID_undef} }; - const struct authnid* sa; const char* authStr; char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; @@ -21934,6 +21928,7 @@ int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher) authStr = GetCipherAuthStr(n); if (authStr != NULL) { + const struct authnid* sa; for(sa = authnid_tbl; sa->alg_name != NULL; sa++) { if (XSTRCMP(sa->alg_name, authStr) == 0) { return sa->nid; @@ -21967,7 +21962,6 @@ int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher) {NULL, NID_undef} }; - const struct ciphernid* c; const char* encStr; char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; @@ -21981,6 +21975,7 @@ int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher) encStr = GetCipherEncStr(n); if (encStr != NULL) { + const struct ciphernid* c; for(c = ciphernid_tbl; c->alg_name != NULL; c++) { if (XSTRCMP(c->alg_name, encStr) == 0) { return c->nid; @@ -22006,7 +22001,6 @@ int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher) {NULL, NID_undef} }; - const struct macnid* mc; const char* name; const char* macStr; char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; @@ -22027,6 +22021,7 @@ int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher) macStr = GetCipherMacStr(n); if (macStr != NULL) { + const struct macnid* mc; for(mc = macnid_tbl; mc->alg_name != NULL; mc++) { if (XSTRCMP(mc->alg_name, macStr) == 0) { return mc->nid; @@ -22057,7 +22052,6 @@ int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher) {NULL, NID_undef} }; - const struct kxnid* k; const char* keaStr; char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; @@ -22076,6 +22070,7 @@ int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher) keaStr = GetCipherKeaStr(n); if (keaStr != NULL) { + const struct kxnid* k; for(k = kxnid_table; k->name != NULL; k++) { if (XSTRCMP(k->name, keaStr) == 0) { return k->nid; @@ -22629,7 +22624,7 @@ int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) word32 inOutIdx = 0; #endif word32 pub_derSz = 0; - int ret = 0; + int ret; int key_type = 0; if (key == NULL) { @@ -22638,7 +22633,7 @@ int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) key_type = key->type; if ((key_type != EVP_PKEY_EC) && (key_type != EVP_PKEY_RSA)) { - ret = WOLFSSL_FATAL_ERROR; + return WOLFSSL_FATAL_ERROR; } #ifndef NO_RSA @@ -22654,20 +22649,18 @@ int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) /* We need to get the DER, then convert it to a public key. But what we get * might be a buffered private key so we need to decode it and then encode * the public part. */ - if (ret == 0) { - ret = wolfSSL_EVP_PKEY_get_der(key, &local_der); - if (ret <= 0) { - /* In this case, there was no buffered DER at all. This could be the - * case where the key that was passed in was generated. So now we - * have to create the local DER. */ - local_derSz = wolfSSL_i2d_ECPrivateKey(key->ecc, &local_der); - if (local_derSz == 0) { - ret = WOLFSSL_FATAL_ERROR; - } - } else { - local_derSz = ret; - ret = 0; + ret = wolfSSL_EVP_PKEY_get_der(key, &local_der); + if (ret <= 0) { + /* In this case, there was no buffered DER at all. This could be the + * case where the key that was passed in was generated. So now we + * have to create the local DER. */ + local_derSz = wolfSSL_i2d_ECPrivateKey(key->ecc, &local_der); + if (local_derSz == 0) { + ret = WOLFSSL_FATAL_ERROR; } + } else { + local_derSz = ret; + ret = 0; } if (ret == 0) { @@ -22692,7 +22685,7 @@ int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) if (ret == 0) { pub_derSz = wc_EccPublicKeyDerSize(eccKey, 0); - if (pub_derSz <= 0) { + if ((int)pub_derSz <= 0) { ret = WOLFSSL_FAILURE; } } @@ -22708,7 +22701,7 @@ int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) if (ret == 0) { pub_derSz = wc_EccPublicKeyToDer(eccKey, pub_der, pub_derSz, 0); - if (pub_derSz <= 0) { + if ((int)pub_derSz <= 0) { ret = WOLFSSL_FATAL_ERROR; } } @@ -23305,13 +23298,12 @@ const char* wolfSSL_state_string_long(const WOLFSSL* ssl) */ int wolfSSL_PEM_def_callback(char* name, int num, int w, void* key) { - int sz; (void)w; WOLFSSL_ENTER("wolfSSL_PEM_def_callback"); /* We assume that the user passes a default password as userdata */ if (key) { - sz = (int)XSTRLEN((const char*)key); + int sz = (int)XSTRLEN((const char*)key); sz = (sz > num) ? num : sz; XMEMCPY(name, key, sz); return sz; @@ -23962,11 +23954,9 @@ long wolfSSL_CTX_sess_number(WOLFSSL_CTX* ctx) long wolfSSL_CTX_add_extra_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) { byte* chain = NULL; - long chainSz = 0; int derSz; const byte* der; int ret; - int idx = 0; DerBuffer *derBuffer = NULL; WOLFSSL_ENTER("wolfSSL_CTX_add_extra_chain_cert"); @@ -23994,6 +23984,9 @@ long wolfSSL_CTX_add_extra_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) } } else { + long chainSz = 0; + int idx = 0; + /* TODO: Do this elsewhere. */ ret = AllocDer(&derBuffer, derSz, CERT_TYPE, ctx->heap); if (ret != 0) { @@ -25258,7 +25251,6 @@ int wolfSSL_i2d_SSL_SESSION(WOLFSSL_SESSION* sess, unsigned char** p) #ifdef SESSION_CERTS int i; #endif - unsigned char *data; WOLFSSL_ENTER("wolfSSL_i2d_SSL_SESSION"); @@ -25327,6 +25319,8 @@ int wolfSSL_i2d_SSL_SESSION(WOLFSSL_SESSION* sess, unsigned char** p) #endif if (p != NULL) { + unsigned char *data; + if (*p == NULL) *p = (unsigned char*)XMALLOC(size, NULL, DYNAMIC_TYPE_OPENSSL); if (*p == NULL) @@ -26633,8 +26627,6 @@ int wolfSSL_HMAC_Init(WOLFSSL_HMAC_CTX* ctx, const void* key, int keylen, int wolfSSL_HMAC_Update(WOLFSSL_HMAC_CTX* ctx, const unsigned char* data, int len) { - int hmac_error = 0; - WOLFSSL_MSG("wolfSSL_HMAC_Update"); if (ctx == NULL) { @@ -26643,6 +26635,8 @@ int wolfSSL_HMAC_Update(WOLFSSL_HMAC_CTX* ctx, const unsigned char* data, } if (data) { + int hmac_error = 0; + WOLFSSL_MSG("updating hmac"); hmac_error = wc_HmacUpdate(&ctx->hmac, data, (word32)len); if (hmac_error < 0){ @@ -27463,7 +27457,6 @@ int wolfSSL_get_signature_nid(WOLFSSL *ssl, int* nid) static int populate_groups(int* groups, int max_count, char *list) { char *end; - int len; int count = 0; const WOLF_EC_NIST_NAME* nist_name; @@ -27472,6 +27465,8 @@ static int populate_groups(int* groups, int max_count, char *list) } for (end = list; ; list = ++end) { + int len; + if (count > max_count) { WOLFSSL_MSG("Too many curves in list"); return -1; @@ -27547,7 +27542,6 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* pkey = NULL; DerBuffer* der = NULL; int keyFormat = 0; - int type = -1; WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PrivateKey"); @@ -27557,6 +27551,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, if (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE, &keyFormat, &der) >= 0) { const unsigned char* ptr = der->buffer; + int type = -1; if (keyFormat) { /* keyFormat is Key_Sum enum */ @@ -28489,13 +28484,13 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) WOLFSSL_EVP_PKEY* pkey = NULL; DerBuffer* der = NULL; int keyFormat = 0; - int type = -1; WOLFSSL_ENTER("wolfSSL_PEM_read_PrivateKey"); if (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE, &keyFormat, &der) >= 0) { const unsigned char* ptr = der->buffer; + int type = -1; if (keyFormat) { /* keyFormat is Key_Sum enum */ @@ -28561,7 +28556,6 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) char* nameStr = NULL; int nameLen = 0; char* headerStr = NULL; - int headerLen; int headerFound = 0; unsigned char* der = NULL; word32 derLen = 0; @@ -28599,6 +28593,8 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) ret = WOLFSSL_FAILURE; } if (ret == WOLFSSL_SUCCESS) { + int headerLen; + XSTRNCPY(nameStr, pem + PEM_BEGIN_SZ, nameLen); nameStr[nameLen] = '\0'; @@ -29532,7 +29528,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) int wolfSSL_OBJ_ln2nid(const char *ln) { const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info; - size_t i, lnlen; + size_t lnlen; WOLFSSL_ENTER("wolfSSL_OBJ_ln2nid"); if (ln && (lnlen = XSTRLEN(ln)) > 0) { /* Accept input like "/commonName=" */ @@ -29541,6 +29537,8 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) lnlen--; } if (lnlen) { + size_t i; + if (ln[lnlen-1] == '=') { lnlen--; } @@ -30536,10 +30534,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio, unsigned char* mem = NULL; int memSz = 0; WOLFSSL_EVP_PKEY* key = NULL; - int i = 0, j = 0; unsigned char* extraBioMem = NULL; - int extraBioMemSz = 0; - int derLength = 0; WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_bio"); @@ -30561,6 +30556,9 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio, } if (wolfSSL_BIO_read(bio, (unsigned char*)mem, memSz) == memSz) { + int extraBioMemSz; + int derLength; + /* Determines key type and returns the new private EVP_PKEY object */ if ((key = wolfSSL_d2i_PrivateKey_EVP(NULL, &mem, (long)memSz)) == NULL) { WOLFSSL_MSG("wolfSSL_d2i_PrivateKey_EVP() failure"); @@ -30572,6 +30570,9 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio, derLength = key->pkey_sz; extraBioMemSz = (memSz - derLength); if (extraBioMemSz > 0) { + int i; + int j = 0; + extraBioMem = (unsigned char *)XMALLOC(extraBioMemSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (extraBioMem == NULL) { @@ -30660,7 +30661,6 @@ static void SESSION_ex_data_cache_update(WOLFSSL_SESSION* session, int idx, int i; int error = 0; SessionRow* sessRow = NULL; - WOLFSSL_SESSION* cacheSession = NULL; const byte* id; byte foundCache = 0; @@ -30690,6 +30690,7 @@ static void SESSION_ex_data_cache_update(WOLFSSL_SESSION* session, int idx, } for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) { + WOLFSSL_SESSION* cacheSession; #ifdef SESSION_CACHE_DYNAMIC_MEM cacheSession = sessRow->Sessions[i]; #else @@ -34486,10 +34487,8 @@ int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio, byte* pem = NULL; int pemSz = 0; int type = PKCS8_PRIVATEKEY_TYPE; - int algId; const byte* curveOid; word32 oidSz; - int encAlgId = 0; if (bio == NULL || pkey == NULL) return -1; @@ -34510,6 +34509,7 @@ int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio, WC_RNG rng; ret = wc_InitRng(&rng); if (ret == 0) { + int encAlgId = 0; #ifndef NO_DES3 if (enc == EVP_DES_CBC) encAlgId = DESb; @@ -34540,6 +34540,7 @@ int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio, type = PKCS8_ENC_PRIVATEKEY_TYPE; } if (ret == 0 && enc == NULL) { + int algId; type = PKCS8_PRIVATEKEY_TYPE; #ifdef HAVE_ECC if (pkey->type == EVP_PKEY_EC) { @@ -34702,9 +34703,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey, const byte* der = *pp; word32 idx = 0; int len = 0; - word32 end = 0; int cnt = 0; - int type; word32 algId; word32 keyLen = (word32)length; @@ -34720,7 +34719,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey, */ ret = GetSequence(der, &idx, &len, keyLen); if (ret >= 0) { - end = idx + len; + word32 end = idx + len; while (ret >= 0 && idx < end) { /* Skip type */ idx++; @@ -34739,6 +34738,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey, } if (ret >= 0) { + int type; /* ECC includes version, private[, curve][, public key] */ if (cnt >= 2 && cnt <= 4) type = EVP_PKEY_EC; @@ -35992,7 +35992,6 @@ int wolfSSL_RAND_bytes(unsigned char* buf, int num) WC_RNG tmpRNG[1]; #endif int initTmpRng = 0; - int blockCount = 0; #ifdef HAVE_GLOBAL_RNG int used_global = 0; #endif @@ -36039,7 +36038,7 @@ int wolfSSL_RAND_bytes(unsigned char* buf, int num) } if (rng) { /* handles size greater than RNG_MAX_BLOCK_LEN */ - blockCount = num / RNG_MAX_BLOCK_LEN; + int blockCount = num / RNG_MAX_BLOCK_LEN; while (blockCount--) { ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN); @@ -38162,13 +38161,14 @@ WC_PKCS12* wolfSSL_PKCS12_create(char* pass, char* name, WOLFSSL_EVP_PKEY* pkey, } if (ca != NULL) { - WC_DerCertList* cur; unsigned long numCerts = ca->num; - byte* curDer; - int curDerSz = 0; WOLFSSL_STACK* sk = ca; while (numCerts > 0 && sk != NULL) { + byte* curDer; + WC_DerCertList* cur; + int curDerSz = 0; + cur = (WC_DerCertList*)XMALLOC(sizeof(WC_DerCertList), NULL, DYNAMIC_TYPE_PKCS); if (cur == NULL) { diff --git a/src/ssl_bn.c b/src/ssl_bn.c index e301c29e826..ffc0179e1ff 100644 --- a/src/ssl_bn.c +++ b/src/ssl_bn.c @@ -1280,7 +1280,6 @@ static int wolfssl_bn_add_word_int(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w, int sub) { int ret = 1; - int rc = 0; #if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) #ifdef WOLFSSL_SMALL_STACK mp_int* w_mp = NULL; @@ -1311,6 +1310,7 @@ static int wolfssl_bn_add_word_int(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w, } if (ret == 1) { + int rc = 0; #if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) if (w > (WOLFSSL_BN_ULONG)MP_MASK) { /* Initialize temporary MP integer. */ diff --git a/src/tls.c b/src/tls.c index 6d6e52d457c..18dce34d1c2 100644 --- a/src/tls.c +++ b/src/tls.c @@ -1030,7 +1030,7 @@ static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in, byte dummy[WC_MAX_BLOCK_SIZE] = {0}; int ret; word32 msgSz, blockSz, macSz, padSz, maxSz, realSz; - word32 currSz, offset = 0; + word32 offset = 0; int msgBlocks, blocks, blockBits; int i; @@ -1102,7 +1102,7 @@ static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in, ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ); if (ret == 0) { /* Fill the rest of the block with any available data. */ - currSz = ctMaskLT(msgSz, blockSz) & msgSz; + word32 currSz = ctMaskLT(msgSz, blockSz) & msgSz; currSz |= ctMaskGTE(msgSz, blockSz) & blockSz; currSz -= WOLFSSL_TLS_HMAC_INNER_SZ; currSz &= ~(0 - (currSz >> 31)); @@ -2380,7 +2380,6 @@ static int TLSX_SNI_Parse(WOLFSSL* ssl, const byte* input, word16 length, int cacheOnly = 0; SNI *sni = NULL; byte type; - int matchStat; byte matched; #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) WOLFSSL_ECH* ech = NULL; @@ -2497,6 +2496,7 @@ static int TLSX_SNI_Parse(WOLFSSL* ssl, const byte* input, word16 length, #endif if (matched || sni->options & WOLFSSL_SNI_ANSWER_ON_MISMATCH) { + int matchStat; int r = TLSX_UseSNI(&ssl->extensions, type, input + offset, size, ssl->heap); if (r != WOLFSSL_SUCCESS) @@ -4796,7 +4796,6 @@ int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl) TLSX* ext = NULL; TLSX* extension; SupportedCurve* clientGroup; - SupportedCurve* serverGroup; SupportedCurve* group; int found = 0; @@ -4829,6 +4828,8 @@ int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl) ret = TLSX_PopulateSupportedGroups(ssl, &priority); if (ret == WOLFSSL_SUCCESS) { + SupportedCurve* serverGroup; + ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS); serverGroup = (SupportedCurve*)ext->data; @@ -6286,8 +6287,6 @@ static int TLSX_SupportedVersions_Write(void* data, byte* output, byte msgType, word16* pSz) { WOLFSSL* ssl = (WOLFSSL*)data; - byte major; - byte* cnt; byte tls13minor, tls12minor, tls11minor, isDtls = 0; tls13minor = (byte)TLSv1_3_MINOR; @@ -6308,9 +6307,9 @@ static int TLSX_SupportedVersions_Write(void* data, byte* output, #endif /* WOLFSSL_DTLS13 */ if (msgType == client_hello) { - major = ssl->ctx->method->version.major; + byte major = ssl->ctx->method->version.major; - cnt = output++; + byte* cnt = output++; *cnt = 0; if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13minor) @@ -6402,11 +6401,8 @@ int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl, const byte* input, word16 length, byte msgType, ProtocolVersion* pv, Options* opts, TLSX** exts) { - int i; - int len; /* The client's greatest minor version that we support */ byte clientGreatestMinor = SSLv3_MINOR; - int set = 0; int ret; byte major, minor; byte tls13minor, tls12minor; @@ -6425,6 +6421,10 @@ int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl, const byte* input, #endif /* WOLFSSL_DTLS13 */ if (msgType == client_hello) { + int i; + int len; + int set = 0; + /* Must contain a length and at least one version. */ if (length < OPAQUE8_LEN + OPAQUE16_LEN || (length & 1) != 1) return BUFFER_ERROR; @@ -10008,8 +10008,6 @@ int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions, const byte* input, static int TLSX_PreSharedKey_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType) { - TLSX* extension; - PreSharedKey* list; if (msgType == client_hello) { return TLSX_PreSharedKey_Parse_ClientHello(&ssl->extensions, input, @@ -10018,6 +10016,8 @@ static int TLSX_PreSharedKey_Parse(WOLFSSL* ssl, const byte* input, if (msgType == server_hello) { word16 idx; + PreSharedKey* list; + TLSX* extension; /* Index of identity chosen by server. */ if (length != OPAQUE16_LEN) diff --git a/src/tls13.c b/src/tls13.c index e8e2391e904..cd6d07d9216 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -7739,7 +7739,6 @@ static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo, int ret = 0; byte sigData[MAX_SIG_DATA_SZ]; word16 sigDataSz; - word32 sigSz; ret = CreateSigData(ssl, sigData, &sigDataSz, 1); if (ret != 0) @@ -7747,6 +7746,7 @@ static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo, if (sigAlgo == rsa_pss_sa_algo) { enum wc_HashType hashType = WC_HASH_TYPE_NONE; + word32 sigSz; ret = ConvertHashPss(hashAlgo, &hashType, NULL); if (ret < 0) @@ -9464,7 +9464,6 @@ int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, */ static int SendTls13Finished(WOLFSSL* ssl) { - int sendSz; int finishedSz = ssl->specs.hash_size; byte* input; byte* output; @@ -9572,26 +9571,26 @@ static int SendTls13Finished(WOLFSSL* ssl) } else #endif /* WOLFSSL_DTLS13 */ { - /* This message is always encrypted. */ - sendSz = BuildTls13Message(ssl, output, outputSz, input, - headerSz + finishedSz, handshake, 1, 0, 0); - if (sendSz < 0) { - WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR); - return BUILD_MSG_ERROR; - } - - #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA) - if (ssl->hsInfoOn) AddPacketName(ssl, "Finished"); - if (ssl->toInfoOn) { - ret = AddPacketInfo(ssl, "Finished", handshake, output, sendSz, - WRITE_PROTO, 0, ssl->heap); - if (ret != 0) - return ret; + /* This message is always encrypted. */ + int sendSz = BuildTls13Message(ssl, output, outputSz, input, + headerSz + finishedSz, handshake, 1, 0, 0); + if (sendSz < 0) { + WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR); + return BUILD_MSG_ERROR; } - #endif - ssl->buffers.outputBuffer.length += sendSz; - ssl->options.buildingMsg = 0; + #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA) + if (ssl->hsInfoOn) AddPacketName(ssl, "Finished"); + if (ssl->toInfoOn) { + ret = AddPacketInfo(ssl, "Finished", handshake, output, sendSz, + WRITE_PROTO, 0, ssl->heap); + if (ret != 0) + return ret; + } + #endif + + ssl->buffers.outputBuffer.length += sendSz; + ssl->options.buildingMsg = 0; } if (ssl->options.side == WOLFSSL_SERVER_END) { @@ -9732,7 +9731,6 @@ static int SendTls13Finished(WOLFSSL* ssl) */ static int SendTls13KeyUpdate(WOLFSSL* ssl) { - int sendSz; byte* input; byte* output; int ret; @@ -9786,7 +9784,7 @@ static int SendTls13KeyUpdate(WOLFSSL* ssl) #endif /* WOLFSSL_DTLS13 */ { /* This message is always encrypted. */ - sendSz = BuildTls13Message(ssl, output, outputSz, input, + int sendSz = BuildTls13Message(ssl, output, outputSz, input, headerSz + OPAQUE8_LEN, handshake, 0, 0, 0); if (sendSz < 0) return BUILD_MSG_ERROR; @@ -12593,7 +12591,6 @@ int wolfSSL_accept_TLSv13(WOLFSSL* ssl) #if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) word16 havePSK = 0; #endif - int advanceState; int ret = 0; struct timespec start, end; @@ -12708,7 +12705,7 @@ int wolfSSL_accept_TLSv13(WOLFSSL* ssl) /* fragOffset is non-zero when sending fragments. On the last * fragment, fragOffset is zero again, and the state can be * advanced. */ - advanceState = + int advanceState = (ssl->options.acceptState == TLS13_ACCEPT_CLIENT_HELLO_DONE || ssl->options.acceptState == TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE || diff --git a/src/wolfio.c b/src/wolfio.c index 014f60f9c8c..8c475aea43d 100644 --- a/src/wolfio.c +++ b/src/wolfio.c @@ -2647,13 +2647,12 @@ void wolfSSL_SetIO_Mynewt(WOLFSSL* ssl, struct mn_socket* mnSocket, struct mn_so int uIPSend(WOLFSSL* ssl, char* buf, int sz, void* _ctx) { uip_wolfssl_ctx *ctx = (struct uip_wolfssl_ctx *)_ctx; - int ret; - unsigned int max_sendlen; int total_written = 0; (void)ssl; do { + int ret; unsigned int bytes_left = sz - total_written; - max_sendlen = tcp_socket_max_sendlen(&ctx->conn.tcp); + unsigned int max_sendlen = tcp_socket_max_sendlen(&ctx->conn.tcp); if (bytes_left > max_sendlen) { fprintf(stderr, "uIPSend: Send limited by buffer\r\n"); bytes_left = max_sendlen; diff --git a/src/x509.c b/src/x509.c index efef2954f64..a7a3e8430b8 100644 --- a/src/x509.c +++ b/src/x509.c @@ -12114,7 +12114,6 @@ static int wolfSSL_EscapeString_RFC2253(char* in, word32 inSz, { word32 inIdx = 0; word32 outIdx = 0; - char c = 0; if (in == NULL || out == NULL || inSz == 0 || outSz == 0) { return BAD_FUNC_ARG; @@ -12122,7 +12121,7 @@ static int wolfSSL_EscapeString_RFC2253(char* in, word32 inSz, for (inIdx = 0; inIdx < inSz; inIdx++) { - c = in[inIdx]; + char c = in[inIdx]; if (((inIdx == 0) && (c == ' ' || c == '#')) || ((inIdx == (inSz-1)) && (c == ' ')) || @@ -12169,7 +12168,7 @@ static int wolfSSL_EscapeString_RFC2253(char* in, word32 inSz, int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, int indent, unsigned long flags) { - int i, count = 0, len = 0, tmpSz = 0, nameStrSz = 0, escapeSz = 0; + int i, count = 0, nameStrSz = 0, escapeSz = 0; char* tmp = NULL; char* nameStr = NULL; const char *buf = NULL; @@ -12190,6 +12189,9 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, count = wolfSSL_X509_NAME_entry_count(name); for (i = 0; i < count; i++) { + int len; + int tmpSz; + /* reverse name order for RFC2253 and DN_REV */ if ((flags & XN_FLAG_RFC2253) || (flags & XN_FLAG_DN_REV)) { ne = wolfSSL_X509_NAME_get_entry(name, count - i - 1); @@ -12913,7 +12915,6 @@ int wolfSSL_sk_X509_OBJECT_push(WOLFSSL_STACK* sk, WOLFSSL_X509_OBJECT* obj) int wolfSSL_X509_NAME_copy(WOLFSSL_X509_NAME* from, WOLFSSL_X509_NAME* to) { int i; - WOLFSSL_X509_NAME_ENTRY* ne; WOLFSSL_ENTER("wolfSSL_X509_NAME_copy"); @@ -12943,7 +12944,7 @@ int wolfSSL_X509_NAME_copy(WOLFSSL_X509_NAME* from, WOLFSSL_X509_NAME* to) to->sz = from->sz; for (i = 0; i < MAX_NAME_ENTRIES; i++) { - ne = wolfSSL_X509_NAME_get_entry(from, i); + WOLFSSL_X509_NAME_ENTRY* ne = wolfSSL_X509_NAME_get_entry(from, i); if (ne != NULL) wolfSSL_X509_NAME_add_entry(to, ne, i, 1); } diff --git a/src/x509_str.c b/src/x509_str.c index 0164eb76f1e..52f8c775a1b 100644 --- a/src/x509_str.c +++ b/src/x509_str.c @@ -61,7 +61,6 @@ WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new(void) int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509, WOLF_STACK_OF(WOLFSSL_X509)* sk) { - WOLFSSL_X509* x509_cert; int ret = 0; (void)sk; WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_init"); @@ -83,7 +82,7 @@ int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, ctx->chain = sk; /* Add intermediate certificates from stack to store */ while (sk != NULL) { - x509_cert = sk->data.x509; + WOLFSSL_X509* x509_cert = sk->data.x509; if (x509_cert != NULL && x509_cert->isCa) { ret = wolfSSL_X509_STORE_add_cert(store, x509_cert); if (ret < 0) { @@ -195,22 +194,21 @@ int GetX509Error(int e) */ int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx) { - int ret = 0; - int depth = 0; - int error; -#ifndef NO_ASN_TIME - byte *afterDate, *beforeDate; -#endif - WOLFSSL_ENTER("wolfSSL_X509_verify_cert"); if (ctx != NULL && ctx->store != NULL && ctx->store->cm != NULL && ctx->current_cert != NULL && ctx->current_cert->derCert != NULL) { - ret = wolfSSL_CertManagerVerifyBuffer(ctx->store->cm, - ctx->current_cert->derCert->buffer, - ctx->current_cert->derCert->length, - WOLFSSL_FILETYPE_ASN1); + int ret = 0; + int depth = 0; + int error; + #ifndef NO_ASN_TIME + byte *afterDate, *beforeDate; + #endif + ret = wolfSSL_CertManagerVerifyBuffer(ctx->store->cm, + ctx->current_cert->derCert->buffer, + ctx->current_cert->derCert->length, + WOLFSSL_FILETYPE_ASN1); /* If there was an error, process it and add it to CTX */ if (ret < 0) { /* Get corresponding X509 error */ @@ -1000,7 +998,6 @@ WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, WOLFSSL_CTX* ctx; char *name = NULL; int ret = WOLFSSL_SUCCESS; - int successes = 0; #ifdef WOLFSSL_SMALL_STACK ReadDirCtx* readCtx = NULL; #else @@ -1044,6 +1041,8 @@ WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, /* Load files in dir */ if (dir && ret == WOLFSSL_SUCCESS) { + int successes = 0; + #ifdef WOLFSSL_SMALL_STACK readCtx = (ReadDirCtx*)XMALLOC(sizeof(ReadDirCtx), ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -1094,7 +1093,6 @@ WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, int wolfSSL_X509_CA_num(WOLFSSL_X509_STORE* store) { - int i = 0; int cnt_ret = 0; Signer **table; @@ -1107,6 +1105,7 @@ int wolfSSL_X509_CA_num(WOLFSSL_X509_STORE* store) table = store->cm->caTable; if (table){ if (wc_LockMutex(&store->cm->caLock) == 0){ + int i = 0; for (i = 0; i < CA_TABLE_SIZE; i++) { Signer* signer = table[i]; while (signer) { diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 3c8b0178b41..0b31777b28c 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -1621,10 +1621,9 @@ typedef enum bench_stat_type { void bench_stats_print(void) { int i; - bench_stats_t* bstat; for (i=0; itype == BENCH_STAT_SYM) { printf("%-16s %8.3f %s/s\n", bstat->desc, bstat->perfsec, base2 ? "MB" : "mB"); @@ -6209,7 +6208,7 @@ static void bench_rsaKeyGen_helper(int useDeviceID, int keySz) void bench_rsaKeyGen(int useDeviceID) { - int k, keySz; + int k; #if !defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) const int keySizes[2] = {1024, 2048}; #else @@ -6217,7 +6216,7 @@ void bench_rsaKeyGen(int useDeviceID) #endif for (k = 0; k < (int)(sizeof(keySizes)/sizeof(int)); k++) { - keySz = keySizes[k]; + int keySz = keySizes[k]; bench_rsaKeyGen_helper(useDeviceID, keySz); } } diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index ddae9aff736..a7c72c021ad 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -241,11 +241,13 @@ static word32 BytePrecision(word32 value) */ WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output) { - word32 i = 0, j; + word32 i = 0; if (length < ASN_LONG_LENGTH) output[i++] = (byte)length; else { + word32 j; + output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH); for (j = BytePrecision(length); j; --j) { @@ -2901,7 +2903,6 @@ static int SetASNIntMP(mp_int* n, int maxSz, byte* output) int idx = 0; int leadingBit; int length; - int err; leadingBit = mp_leading_bit(n); length = mp_unsigned_bin_size(n); @@ -2912,7 +2913,7 @@ static int SetASNIntMP(mp_int* n, int maxSz, byte* output) return BUFFER_E; if (output) { - err = mp_to_unsigned_bin(n, output + idx); + int err = mp_to_unsigned_bin(n, output + idx); if (err != MP_OKAY) return MP_TO_E; } @@ -2939,7 +2940,6 @@ static int SetASNIntRSA(void* n, byte* output) int idx = 0; int leadingBit; int length; - int err; leadingBit = wc_Rsa_leading_bit(n); length = wc_Rsa_unsigned_bin_size(n); @@ -2948,7 +2948,7 @@ static int SetASNIntRSA(void* n, byte* output) return BUFFER_E; if (output) { - err = wc_Rsa_to_unsigned_bin(n, output + idx, length); + int err = wc_Rsa_to_unsigned_bin(n, output + idx, length); if (err != MP_OKAY) return MP_TO_E; } @@ -6432,7 +6432,6 @@ int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, #else DECL_ASNGETDATA(dataASN, rsaKeyASN_Length); int ret = 0; - int i; byte version = (byte)-1; #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) word32 algId = 0; @@ -6455,6 +6454,7 @@ int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, key->heap); if (ret == 0) { + int i; /* Register variable to hold version field. */ GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version); /* Setup data to store INTEGER data in mp_int's in RSA object. */ @@ -8065,7 +8065,6 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, int encOidSz = 0; word32 padSz = 0; word32 innerLen = 0; - word32 outerLen = 0; const byte* pbeOidBuf = NULL; word32 pbeOidBufSz = 0; word32 pbeLen = 0; @@ -8119,7 +8118,7 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, if (ret == 0) { /* outerLen = length of PBE encoding + octet string data */ /* Plus 2 for tag and length for pbe */ - outerLen = 2 + pbeLen; + word32 outerLen = 2 + pbeLen; /* Octet string tag, length */ outerLen += 1 + SetLength(keySz + padSz, NULL); /* Octet string bytes */ @@ -8679,13 +8678,14 @@ int ToTraditionalEnc(byte* input, word32 sz, const char* password, #define PKCS8_MIN_BLOCK_SIZE 8 static int Pkcs8Pad(byte* buf, int sz, int blockSz) { - int i, padSz; + int padSz; /* calculate pad size */ padSz = blockSz - (sz & (blockSz - 1)); /* pad with padSz value */ if (buf) { + int i; for (i = 0; i < padSz; i++) { buf[sz+i] = (byte)(padSz & 0xFF); } @@ -8946,9 +8946,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, int version; int id; int blockSz = 0; - byte* pkcs8; word32 pkcs8Sz = 0; - byte cbcIv[MAX_IV_SIZE]; (void)heap; @@ -9017,8 +9015,10 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, } } if (ret == 0) { + byte cbcIv[MAX_IV_SIZE]; /* Store PKCS#8 key in output buffer. */ - pkcs8 = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data; + byte* pkcs8 = + (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data; XMEMCPY(pkcs8, input, inputSz); Pkcs8Pad(pkcs8, inputSz, blockSz); @@ -10254,7 +10254,6 @@ int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key, /* dsaPubKeyASN is longer than dsaPublicKeyASN. */ DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length); int ret = 0; - int i; /* Validated parameters. */ if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) { @@ -10264,6 +10263,8 @@ int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key, ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap); if (ret == 0) { + int i; + /* Clear dynamic data items. */ XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length); /* seq @@ -10450,7 +10451,6 @@ int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key, /* dsaKeyASN is longer than dsaKeyOctASN. */ DECL_ASNGETDATA(dataASN, dsaKeyASN_Length); int ret = 0; - int i; byte version = 0; /* Sanity checks on input */ @@ -10461,6 +10461,8 @@ int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key, CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap); if (ret == 0) { + int i; + /* Try dsaKeyOctASN */ /* Initialize key data and set mp_ints for params */ for (i = 0; i < DSA_INTS - 2; i++) { @@ -10787,9 +10789,9 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, int ints, int includeVersion) { #ifndef WOLFSSL_ASN_TEMPLATE - word32 seqSz = 0, verSz = 0, rawLen, intTotalLen = 0; + word32 seqSz = 0, verSz = 0, intTotalLen = 0; word32 sizes[DSA_INTS]; - int i, j, outLen, ret = 0, mpSz; + int i, j, outLen, ret = 0; byte seq[MAX_SEQ_SZ]; byte ver[MAX_VERSION_SZ]; @@ -10804,9 +10806,10 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, /* write all big ints from key to DER tmps */ for (i = 0; i < ints; i++) { + int mpSz; mp_int* keyInt = GetDsaInt(key, i); + word32 rawLen = mp_unsigned_bin_size(keyInt) + 1; - rawLen = mp_unsigned_bin_size(keyInt) + 1; tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap, DYNAMIC_TYPE_DSA); if (tmps[i] == NULL) { @@ -10861,7 +10864,6 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, #else DECL_ASNSETDATA(dataASN, dsaKeyASN_Length); int ret = 0; - int i; int sz = 0; (void)ints; @@ -10876,6 +10878,8 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap); if (ret == 0) { + int i; + if (includeVersion) { /* Set the version. */ SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0); @@ -13378,8 +13382,6 @@ int GetName(DecodedCert* cert, int nameType, int maxIdx) ASNGetData dataASN[certNameASN_Length]; word32 idx = cert->srcIdx; int ret = 0; - char* full; - byte* hash; WOLFSSL_MSG("Getting Name"); @@ -13389,6 +13391,9 @@ int GetName(DecodedCert* cert, int nameType, int maxIdx) ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0, cert->source, &idx, maxIdx); if (ret == 0) { + char* full; + byte* hash; + /* Store offset of SEQUENCE that is start of name. */ cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset; @@ -13589,7 +13594,7 @@ int GetAsnTimeString(void* currTime, byte* buf, word32 len) XMEMSET(uf_time, 0, sizeof(uf_time)); /* GetFormattedTime returns length with null terminator */ data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time)); - if (data_len <= 0) { + if ((int)data_len <= 0) { return ASN_TIME_E; } /* ensure room to add 2 bytes (ASN type and length) before proceeding */ @@ -13757,7 +13762,6 @@ int wc_ValidateDate(const byte* date, byte format, int dateType) int i = 0; int timeDiff = 0; int diffHH = 0, diffMM = 0; - int diffSign = 0; #if defined(NEED_TMP_TIME) struct tm tmpTimeStorage; @@ -13795,6 +13799,8 @@ int wc_ValidateDate(const byte* date, byte format, int dateType) } if ((date[i] == '+') || (date[i] == '-')) { + int diffSign; + WOLFSSL_MSG("Using time differential, not Zulu") ; diffSign = date[i++] == '+' ? 1 : -1 ; if (GetTime(&diffHH, date, &i) != 0) @@ -13946,7 +13952,6 @@ static int GetDateInfo(const byte* source, word32* idx, const byte** pDate, return 0; #else ASNGetData dataASN[dateASN_Length]; - int i; int ret = 0; if ((source == NULL) || (idx == NULL)) { @@ -13961,8 +13966,8 @@ static int GetDateInfo(const byte* source, word32* idx, const byte** pDate, } if (ret == 0) { /* Determine which tag was seen. */ - i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC - : DATEASN_IDX_GT; + int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC + : DATEASN_IDX_GT; /* Return data from seen item. */ if (pFormat != NULL) { *pFormat = dataASN[i].tag; @@ -17870,7 +17875,6 @@ static int DecodeAuthInfo(const byte* input, int sz, DecodedCert* cert) while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) { ASNGetData dataASN[accessDescASN_Length]; - word32 sz32; /* Clear dynamic data and retrieve OID and name. */ XMEMSET(dataASN, 0, sizeof(dataASN)); @@ -17880,6 +17884,8 @@ static int DecodeAuthInfo(const byte* input, int sz, DecodedCert* cert) ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0, input, &idx, sz); if (ret == 0) { + word32 sz32; + /* Check we have OCSP and URI. */ if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) && (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) { @@ -19874,7 +19880,6 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, DECL_ASNGETDATA(dataASN, x509CertASN_Length); int ret = 0; int badDate = 0; - int i; byte version; word32 idx; word32 serialSz; @@ -19908,6 +19913,8 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, ret = ASN_PARSE_E; } if (ret == 0) { + int i; + /* Set fields extracted from data. */ cert->version = version; cert->serialSz = serialSz; @@ -21263,8 +21270,6 @@ int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm) int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) { int ret = 0; - int checkPathLen = 0; - int decrementMaxPathLen = 0; #ifndef WOLFSSL_ASN_TEMPLATE word32 confirmOID = 0; #ifdef WOLFSSL_CERT_REQ @@ -21631,6 +21636,8 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) */ if (cert->ca && cert->pathLengthSet) { + int checkPathLen = 0; + int decrementMaxPathLen = 0; cert->maxPathLen = cert->pathLength; if (cert->isCA) { WOLFSSL_MSG("\tCA boolean set"); @@ -22514,12 +22521,6 @@ int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer, const char* bufferStart; const char* bufferEnd; char* line; - word32 lineSz; - char* finish; - word32 finishSz; - char* start = NULL; - word32 startSz; - const char* newline = NULL; if (info == NULL || pBuffer == NULL || bufSz == 0) return BAD_FUNC_ARG; @@ -22531,6 +22532,13 @@ int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer, line = XSTRNSTR(bufferStart, kProcTypeHeader, min((word32)bufSz, PEM_LINE_LEN)); if (line != NULL) { + word32 lineSz; + char* finish; + word32 finishSz; + char* start; + word32 startSz; + const char* newline = NULL; + if (line >= bufferEnd) { return BUFFER_E; } @@ -22802,14 +22810,6 @@ int PemToDer(const unsigned char* buff, long longSz, int type, DerBuffer* der; word32 algId = 0; word32 idx; -#if defined(WOLFSSL_ENCRYPTED_KEYS) - #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \ - (!defined(NO_AES) && defined(HAVE_AES_CBC) && \ - defined(HAVE_AES_DECRYPT))) && \ - !defined(NO_WOLFSSL_SKIP_TRAILING_PAD) - int padVal = 0; - #endif -#endif #ifdef OPENSSL_EXTRA char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */ char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */ @@ -22903,11 +22903,12 @@ int PemToDer(const unsigned char* buff, long longSz, int type, if (!headerEnd) { #ifdef OPENSSL_EXTRA if (type == PRIVATEKEY_TYPE) { - const char* beginEnd; - int endLen; /* see if there is a -----BEGIN * PRIVATE KEY----- header */ headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz); if (headerEnd) { + const char* beginEnd; + int endLen; + beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX); if (beginEnd >= (char*)buff + sz) { return BUFFER_E; @@ -23140,6 +23141,13 @@ int PemToDer(const unsigned char* buff, long longSz, int type, ret = NO_PASSWORD; } else { + #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \ + (!defined(NO_AES) && defined(HAVE_AES_CBC) && \ + defined(HAVE_AES_DECRYPT))) && \ + !defined(NO_WOLFSSL_SKIP_TRAILING_PAD) + int padVal = 0; + #endif + ret = wc_BufferKeyDecrypt(info, der->buffer, der->length, (byte*)password, passwordSz, WC_MD5); @@ -23390,9 +23398,7 @@ int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der) byte staticBuffer[FILE_BUFFER_SIZE]; #endif byte* fileBuf = staticBuffer; - int dynamic = 0; int ret = 0; - long sz = 0; XFILE file = NULL; WOLFSSL_ENTER("wc_PemCertToDer"); @@ -23408,6 +23414,9 @@ int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der) } if (ret == 0) { + int dynamic = 0; + long sz = 0; + if (XFSEEK(file, 0, XSEEK_END) != 0) { ret = BUFFER_E; } @@ -30546,7 +30555,7 @@ int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz) /* Encode OID string representation to ITU-T X.690 format */ int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap) { - word32 val, idx = 0, nb_val; + word32 idx = 0, nb_val; char *token, *str, *ptr; word32 len; @@ -30568,7 +30577,7 @@ int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap) token = XSTRTOK(str, ".", &ptr); while (token != NULL) { - val = (word32)XATOI(token); + word32 val = (word32)XATOI(token); if (nb_val == 0) { if (val > 2) { @@ -30592,12 +30601,12 @@ int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap) out[idx++] += (byte)val; } else { - word32 tb = 0, x; + word32 tb = 0; int i = 0; byte oid[MAX_OID_SZ]; while (val >= 128) { - x = val % 128; + word32 x = val % 128; val /= 128; oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x); } diff --git a/wolfcrypt/src/coding.c b/wolfcrypt/src/coding.c index 6247263e188..6d836a0488f 100644 --- a/wolfcrypt/src/coding.c +++ b/wolfcrypt/src/coding.c @@ -558,7 +558,6 @@ int Base16_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) { word32 outIdx = 0; word32 i; - byte hb, lb; if (in == NULL || out == NULL || outLen == NULL) return BAD_FUNC_ARG; @@ -567,8 +566,8 @@ int Base16_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) return BAD_FUNC_ARG; for (i = 0; i < inLen; i++) { - hb = in[i] >> 4; - lb = in[i] & 0x0f; + byte hb = in[i] >> 4; + byte lb = in[i] & 0x0f; /* ASCII value */ hb += '0'; diff --git a/wolfcrypt/src/curve25519.c b/wolfcrypt/src/curve25519.c index 33293560f29..1d36cf8abd2 100644 --- a/wolfcrypt/src/curve25519.c +++ b/wolfcrypt/src/curve25519.c @@ -83,8 +83,8 @@ static WC_INLINE int curve25519_priv_clamp_check(const byte* priv) static WC_INLINE void curve25519_copy_point(byte* out, const byte* point, int endian) { - int i; if (endian == EC25519_BIG_ENDIAN) { + int i; /* put shared secret key in Big Endian format */ for (i = 0; i < CURVE25519_KEYSIZE; i++) { out[i] = point[CURVE25519_KEYSIZE - i -1]; diff --git a/wolfcrypt/src/curve448.c b/wolfcrypt/src/curve448.c index c8bba158d6c..57cc6ac70fd 100644 --- a/wolfcrypt/src/curve448.c +++ b/wolfcrypt/src/curve448.c @@ -236,7 +236,6 @@ int wc_curve448_export_public_ex(curve448_key* key, byte* out, word32* outLen, int endian) { int ret = 0; - int i; if ((key == NULL) || (out == NULL) || (outLen == NULL)) { ret = BAD_FUNC_ARG; @@ -258,6 +257,7 @@ int wc_curve448_export_public_ex(curve448_key* key, byte* out, word32* outLen, if (ret == 0) { *outLen = CURVE448_PUB_KEY_SIZE; if (endian == EC448_BIG_ENDIAN) { + int i; /* read keys in Big Endian format */ for (i = 0; i < CURVE448_PUB_KEY_SIZE; i++) { out[i] = key->p[CURVE448_PUB_KEY_SIZE - i - 1]; @@ -304,7 +304,6 @@ int wc_curve448_import_public_ex(const byte* in, word32 inLen, curve448_key* key, int endian) { int ret = 0; - int i; /* sanity check */ if ((key == NULL) || (in == NULL)) { @@ -318,6 +317,7 @@ int wc_curve448_import_public_ex(const byte* in, word32 inLen, if (ret == 0) { if (endian == EC448_BIG_ENDIAN) { + int i; /* read keys in Big Endian format */ for (i = 0; i < CURVE448_PUB_KEY_SIZE; i++) { key->p[i] = in[CURVE448_PUB_KEY_SIZE - i - 1]; @@ -345,7 +345,6 @@ int wc_curve448_import_public_ex(const byte* in, word32 inLen, int wc_curve448_check_public(const byte* pub, word32 pubSz, int endian) { int ret = 0; - word32 i; if (pub == NULL) { ret = BAD_FUNC_ARG; @@ -362,6 +361,8 @@ int wc_curve448_check_public(const byte* pub, word32 pubSz, int endian) } if (ret == 0) { + word32 i; + if (endian == EC448_LITTLE_ENDIAN) { /* Check for value of zero or one */ for (i = CURVE448_PUB_KEY_SIZE - 1; i > 0; i--) { @@ -465,7 +466,6 @@ int wc_curve448_export_private_raw_ex(curve448_key* key, byte* out, word32* outLen, int endian) { int ret = 0; - int i; /* sanity check */ if ((key == NULL) || (out == NULL) || (outLen == NULL)) { @@ -481,6 +481,7 @@ int wc_curve448_export_private_raw_ex(curve448_key* key, byte* out, *outLen = CURVE448_KEY_SIZE; if (endian == EC448_BIG_ENDIAN) { + int i; /* put the key in Big Endian format */ for (i = 0; i < CURVE448_KEY_SIZE; i++) { out[i] = key->k[CURVE448_KEY_SIZE - i - 1]; @@ -630,7 +631,6 @@ int wc_curve448_import_private_ex(const byte* priv, word32 privSz, curve448_key* key, int endian) { int ret = 0; - int i; /* sanity check */ if ((key == NULL) || (priv == NULL)) { @@ -644,6 +644,7 @@ int wc_curve448_import_private_ex(const byte* priv, word32 privSz, if (ret == 0) { if (endian == EC448_BIG_ENDIAN) { + int i; /* read the key in Big Endian format */ for (i = 0; i < CURVE448_KEY_SIZE; i++) { key->k[i] = priv[CURVE448_KEY_SIZE - i - 1]; diff --git a/wolfcrypt/src/dh.c b/wolfcrypt/src/dh.c index ef65ed15f07..adb13372196 100644 --- a/wolfcrypt/src/dh.c +++ b/wolfcrypt/src/dh.c @@ -2375,14 +2375,13 @@ int wc_DhExportKeyPair(DhKey* key, byte* priv, word32* pPrivSz, byte* pub, word32* pPubSz) { int ret = 0; - word32 pubSz, privSz; if (key == NULL || (priv && pPrivSz == NULL) || (pub && pPubSz == NULL)) { return BAD_FUNC_ARG; } if (priv) { - privSz = mp_unsigned_bin_size(&key->priv); + word32 privSz = mp_unsigned_bin_size(&key->priv); if (privSz > *pPrivSz) { return BUFFER_E; } @@ -2391,7 +2390,7 @@ int wc_DhExportKeyPair(DhKey* key, byte* priv, word32* pPrivSz, } if (pub) { - pubSz = mp_unsigned_bin_size(&key->pub); + word32 pubSz = mp_unsigned_bin_size(&key->pub); if (pubSz > *pPubSz) { return BUFFER_E; } diff --git a/wolfcrypt/src/evp.c b/wolfcrypt/src/evp.c index 9940b22dda6..2a44c4af487 100644 --- a/wolfcrypt/src/evp.c +++ b/wolfcrypt/src/evp.c @@ -438,9 +438,9 @@ int wolfSSL_EVP_DigestInit_ex(WOLFSSL_EVP_MD_CTX* ctx, static int fillBuff(WOLFSSL_EVP_CIPHER_CTX *ctx, const unsigned char *in, int sz) { - int fill; - if (sz > 0) { + int fill; + if ((sz+ctx->bufUsed) > ctx->block_size) { fill = ctx->block_size - ctx->bufUsed; } else { @@ -736,7 +736,6 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, const unsigned char *in, int inl) { int blocks; - int fill; WOLFSSL_ENTER("wolfSSL_EVP_CipherUpdate"); if ((ctx == NULL) || (outl == NULL)) { @@ -820,7 +819,7 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, return WOLFSSL_SUCCESS; } if (ctx->bufUsed > 0) { /* concatenate them if there is anything */ - fill = fillBuff(ctx, in, inl); + int fill = fillBuff(ctx, in, inl); inl -= fill; in += fill; } @@ -946,13 +945,7 @@ static WC_INLINE void IncCtr(byte* ctr, word32 ctrSz) int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { - int fl; int ret = WOLFSSL_SUCCESS; -#if (defined(HAVE_AESGCM) || defined(HAVE_AESCCM)) && \ - ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ - || FIPS_VERSION_GE(2,0)) - byte tmp = 0; -#endif if (!ctx || !outl) return WOLFSSL_FAILURE; @@ -1149,6 +1142,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, ret = WOLFSSL_FAILURE; } else if (ctx->lastUsed) { + int fl; PRINT_BUF(ctx->lastBlock, ctx->block_size); if ((fl = checkPad(ctx, ctx->lastBlock)) >= 0) { XMEMCPY(out, ctx->lastBlock, fl); @@ -1177,6 +1171,8 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, #if (defined(HAVE_AESGCM) || defined(HAVE_AESCCM)) && \ ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) + byte tmp = 0; + /* * This flag needs to retain its value between wolfSSL_EVP_CipherFinal * calls. wolfSSL_EVP_CipherInit will clear it, so we save and restore @@ -1907,7 +1903,6 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ int len; #ifdef HAVE_HKDF enum wc_HashType hkdfHashType; - int hkdfHashSz; #endif WOLFSSL_ENTER("wolfSSL_EVP_PKEY_derive"); @@ -2045,7 +2040,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ return WOLFSSL_FAILURE; } else { - hkdfHashSz = wolfSSL_EVP_MD_size(ctx->pkey->hkdfMd); + int hkdfHashSz = wolfSSL_EVP_MD_size(ctx->pkey->hkdfMd); if (hkdfHashSz <= 0) { WOLFSSL_MSG("Failed to get block size for HKDF hash."); return WOLFSSL_FAILURE; @@ -2502,9 +2497,9 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, switch (ctx->pkey->type) { #if !defined(NO_RSA) && !defined(HAVE_USER_RSA) case EVP_PKEY_RSA: { - int len; unsigned int usiglen = (unsigned int)*siglen; if (!sig) { + int len; if (!ctx->pkey->rsa) return WOLFSSL_FAILURE; len = wc_RsaEncryptSize((RsaKey*)ctx->pkey->rsa->internal); @@ -3418,9 +3413,8 @@ static const struct s_ent { static enum wc_HashType EvpMd2MacType(const WOLFSSL_EVP_MD *md) { - const struct s_ent *ent ; - if (md != NULL) { + const struct s_ent *ent; for (ent = md_tbl; ent->name != NULL; ent++) { if (XSTRCMP((const char *)md, ent->name) == 0) { return ent->macType; @@ -3714,7 +3708,6 @@ static int wolfSSL_evp_digest_pk_init(WOLFSSL_EVP_MD_CTX *ctx, if (pkey->type == EVP_PKEY_HMAC) { int hashType; - const unsigned char* key; #ifndef NO_SHA256 if (XSTRCMP(type, "SHA256") == 0) { @@ -3772,6 +3765,7 @@ static int wolfSSL_evp_digest_pk_init(WOLFSSL_EVP_MD_CTX *ctx, { size_t keySz = 0; + const unsigned char* key; key = wolfSSL_EVP_PKEY_get0_hmac(pkey, &keySz); @@ -5043,11 +5037,11 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) /* returns the NID of message digest used by the ctx */ int wolfSSL_EVP_MD_CTX_type(const WOLFSSL_EVP_MD_CTX *ctx) { - const struct s_ent *ent; - WOLFSSL_ENTER("EVP_MD_CTX_type"); if (ctx) { + const struct s_ent *ent; + if (ctx->isHMAC) { return NID_hmac; } @@ -5084,11 +5078,12 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) static int wolfSSL_EVP_MD_Copy_Hasher(WOLFSSL_EVP_MD_CTX* des, const WOLFSSL_EVP_MD_CTX* src) { - int ret; if (src->isHMAC) { return wolfSSL_HmacCopy(&des->hash.hmac, (Hmac*)&src->hash.hmac); } else { + int ret; + switch (src->macType) { case WC_HASH_TYPE_MD5: #ifndef NO_MD5 @@ -5792,8 +5787,10 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) int arg, void *ptr) { int ret = WOLFSSL_FAILURE; +#if defined(HAVE_AESGCM) || (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) #ifndef WC_NO_RNG WC_RNG rng; +#endif #endif if (ctx == NULL) return WOLFSSL_FAILURE; @@ -9760,8 +9757,6 @@ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, word32 eSz; /* size of public exponent */ const byte* n = NULL; const byte* e = NULL; /* pointer to modulus/exponent */ - int idx; - int wsz; word32 i; unsigned long exponent = 0; #ifdef WOLFSSL_SMALL_STACK @@ -9794,6 +9789,9 @@ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, } do { + int idx; + int wsz; + /* parse key to get modulus and exponent */ if (wc_RsaPublicKeyDecode_ex(pkey, &inOutIdx, pkeySz, &n, &nSz, &e, &eSz) != 0) { @@ -9916,7 +9914,6 @@ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, word32 oidSz = 0; const char* OIDName = NULL; const char* nistCurveName = NULL; - int nid; int idx = 0; int wsz = 0; #ifdef WOLFSSL_SMALL_STACK @@ -9982,7 +9979,7 @@ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, /* get NIST curve name */ if (res == WOLFSSL_SUCCESS) { - nid = EccEnumToNID(curveId); + int nid = EccEnumToNID(curveId); if (nid != -1) { /* look up object name and nist curve name*/ OIDName = wolfSSL_OBJ_nid2sn(nid); @@ -10111,10 +10108,6 @@ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, word32 inOutIdx = 0; word32 oid; byte tagFound; - byte *p = NULL, * q = NULL, * g = NULL, * y = NULL; - int pSz, qSz, gSz, ySz; - int idx; - int wsz; #ifdef WOLFSSL_SMALL_STACK mp_int* a = NULL; #else @@ -10147,6 +10140,11 @@ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, } do { + byte *p = NULL, * q = NULL, * g = NULL, * y = NULL; + int pSz, qSz, gSz, ySz; + int idx; + int wsz; + if (GetSequence(pkey, &inOutIdx, &length, pkeySz) < 0) { break; } @@ -10329,12 +10327,8 @@ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, word32 oid; byte tagFound; byte* prime = NULL; - int primeSz; byte generator; byte* publicKey = NULL; - int publicKeySz; - int idx; - int wsz; word32 outSz; byte outHex[3]; #ifdef WOLFSSL_SMALL_STACK @@ -10369,6 +10363,11 @@ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, } do { + int primeSz; + int publicKeySz; + int idx; + int wsz; + if (GetSequence(pkey, &inOutIdx, (int*)&length, pkeySz) < 0) { break; } @@ -10835,7 +10834,6 @@ void wolfSSL_EVP_EncodeInit(WOLFSSL_EVP_ENCODE_CTX* ctx) int wolfSSL_EVP_EncodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, unsigned char* out, int* outl, const unsigned char* in, int inl) { - int cpysz; int res; word32 outsz = 0; @@ -10850,7 +10848,7 @@ int wolfSSL_EVP_EncodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, * to create a block(48bytes) for encoding */ if (ctx->remaining > 0 && inl > 0) { - cpysz = min((BASE64_ENCODE_BLOCK_SIZE - ctx->remaining), inl); + int cpysz = min((BASE64_ENCODE_BLOCK_SIZE - ctx->remaining), inl); XMEMCPY(ctx->data + ctx->remaining, in, cpysz); ctx->remaining += cpysz; in += cpysz; @@ -10968,7 +10966,6 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, int res; int pad = 0; int i; - int cpySz; unsigned char c; int pad3 = 0; int pad4 = 0; @@ -10996,7 +10993,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, a block(4bytes) for decoding*/ if ( ctx->remaining > 0 && inl > 0) { - cpySz = min((BASE64_DECODE_BLOCK_SIZE - ctx->remaining), inl); + int cpySz = min((BASE64_DECODE_BLOCK_SIZE - ctx->remaining), inl); for ( i = 0; cpySz > 0 && inLen > 0; i++) { if (Base64_SkipNewline(in, &inLen, &j) == ASN_INPUT_E) { @@ -11165,7 +11162,6 @@ int wolfSSL_EVP_DecodeFinal(WOLFSSL_EVP_ENCODE_CTX* ctx, word32 outsz = 0; word32 inLen; word32 j = 0; - int res; WOLFSSL_ENTER("wolfSSL_EVP_DecodeFinal"); @@ -11178,6 +11174,8 @@ int wolfSSL_EVP_DecodeFinal(WOLFSSL_EVP_ENCODE_CTX* ctx, } if (ctx->remaining > 0) { + int res; + inLen = ctx->remaining; if ((res = Base64_SkipNewline(ctx->data, &inLen, &j)) != 0) { *outl = 0; diff --git a/wolfcrypt/src/kdf.c b/wolfcrypt/src/kdf.c index 556ee9ea7e5..480753cb6f0 100644 --- a/wolfcrypt/src/kdf.c +++ b/wolfcrypt/src/kdf.c @@ -767,7 +767,7 @@ int wc_SSH_KDF(byte hashId, byte keyId, byte* key, word32 keySz, } digestSz = wc_HmacSizeByType(enmhashId); - if (digestSz < 0) { + if (digestSz <= 0) { return BAD_FUNC_ARG; } diff --git a/wolfcrypt/src/logging.c b/wolfcrypt/src/logging.c index 7c87925d3e7..939700b57ca 100644 --- a/wolfcrypt/src/logging.c +++ b/wolfcrypt/src/logging.c @@ -358,7 +358,7 @@ void WOLFSSL_MSG(const char* msg) #endif void WOLFSSL_BUFFER(const byte* buffer, word32 length) { - int i, buflen = (int)length, bufidx; + int i, buflen = (int)length; char line[(LINE_LEN * 4) + 3]; /* \t00..0F | chars...chars\0 */ if (!loggingEnabled) { @@ -371,7 +371,7 @@ void WOLFSSL_BUFFER(const byte* buffer, word32 length) } while (buflen > 0) { - bufidx = 0; + int bufidx = 0; XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "\t"); bufidx++; @@ -621,10 +621,10 @@ int wc_AddErrorNode(int error, int line, char* reason, char* file) */ void wc_RemoveErrorNode(int relative_idx) { - int last_idx, abs_idx = get_abs_idx(relative_idx); - size_t move_count; + int abs_idx = get_abs_idx(relative_idx); if (abs_idx >= 0) { + size_t move_count; if (abs_idx >= (int)wc_errors.head_idx) { /* removed entry sits "above" head (or is head), * move entries below it "up" */ @@ -640,7 +640,7 @@ void wc_RemoveErrorNode(int relative_idx) else { /* removed entry sits "below" head (wrap around), * move entries above it "down" */ - last_idx = get_abs_idx(-1); + int last_idx = get_abs_idx(-1); if (last_idx >= abs_idx) { /* this SHOULD always be true */ move_count = (last_idx - abs_idx); if (move_count > 0) { @@ -693,8 +693,6 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, const char **data, int *flags, int (*ignore_err)(int err)) { - int ret = 0; - WOLFSSL_ENTER("wc_PeekErrorNodeLineData"); /* No data or flags stored - error display only in Nginx. */ @@ -706,7 +704,7 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, } while (1) { - ret = wc_PeekErrorNode(0, file, NULL, line); + int ret = wc_PeekErrorNode(0, file, NULL, line); if (ret == BAD_STATE_E) { WOLFSSL_MSG("Issue peeking at error node in queue"); return 0; @@ -757,7 +755,6 @@ unsigned long wc_GetErrorNodeErr(void) void wc_ERR_print_errors_cb(int (*cb)(const char *str, size_t len, void *u), void *u) { - struct wc_error_entry *entry; size_t i; WOLFSSL_ENTER("wc_ERR_print_errors_cb"); @@ -768,7 +765,7 @@ void wc_ERR_print_errors_cb(int (*cb)(const char *str, size_t len, void *u), } for (i = 0; i < wc_errors.count; ++i) { - entry = get_entry((int)i); + struct wc_error_entry *entry = get_entry((int)i); if (entry == NULL) break; cb(entry->reason, XSTRLEN(entry->reason), u); @@ -1200,7 +1197,6 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, const char **data, int *flags, int (*ignore_err)(int err)) { - int ret = 0; int idx; WOLFSSL_ENTER("wc_PeekErrorNodeLineData"); @@ -1220,7 +1216,7 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, idx = getErrorNodeCurrentIdx(); while (1) { - ret = peekErrorNode(idx, file, NULL, line); + int ret = peekErrorNode(idx, file, NULL, line); if (ret == BAD_MUTEX_E || ret == BAD_FUNC_ARG || ret == BAD_STATE_E) { WOLFSSL_MSG("Issue peeking at error node in queue"); return 0; diff --git a/wolfcrypt/src/memory.c b/wolfcrypt/src/memory.c index 39639cc3374..1e0cbf30aff 100644 --- a/wolfcrypt/src/memory.c +++ b/wolfcrypt/src/memory.c @@ -242,7 +242,6 @@ void wc_MemZero_Check(void* addr, size_t len) memZero[i].name, memZero[i].addr, j); fprintf(stderr, "[MEM_ZERO] Checking %p:%ld\n", addr, len); abort(); - break; } } /* Update next index to write to. */ @@ -602,7 +601,6 @@ int wolfSSL_load_static_memory(byte* buffer, word32 sz, int flag, /* divide into chunks of memory and add them to available list */ while (ava >= (heap->sizeList[0] + padSz + memSz)) { - int i; /* creating only IO buffers from memory passed in, max TLS is 16k */ if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) { if ((ret = create_memory_buckets(pt, ava, @@ -622,6 +620,7 @@ int wolfSSL_load_static_memory(byte* buffer, word32 sz, int flag, ava -= ret; } else { + int i; /* start at largest and move to smaller buckets */ for (i = (WOLFMEM_MAX_BUCKETS - 1); i >= 0; i--) { if ((heap->sizeList[i] + padSz + memSz) <= ava) { @@ -1054,7 +1053,6 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) { void* res = 0; wc_Memory* pt = NULL; - word32 prvSz; int i; /* check for testing heap hint was set */ @@ -1120,7 +1118,7 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) res = pt->buffer; /* copy over original information and free ptr */ - prvSz = ((wc_Memory*)((byte*)ptr - padSz - + word32 prvSz = ((wc_Memory*)((byte*)ptr - padSz - sizeof(wc_Memory)))->sz; prvSz = (prvSz > pt->sz)? pt->sz: prvSz; XMEMCPY(pt->buffer, ptr, prvSz); diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index ab4f2fcaa2b..e0cc5b05738 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -181,18 +181,18 @@ WC_MISC_STATIC WC_INLINE word32 ByteReverseWord32(word32 value) WC_MISC_STATIC WC_INLINE void ByteReverseWords(word32* out, const word32* in, word32 byteCount) { - word32 count, i; + word32 i; #ifdef WOLFSSL_USE_ALIGN if ((((size_t)in & 0x3) == 0) && (((size_t)out & 0x3) == 0)) - { #endif - count = byteCount/(word32)sizeof(word32); + { + word32 count = byteCount/(word32)sizeof(word32); for (i = 0; i < count; i++) out[i] = ByteReverseWord32(in[i]); -#ifdef WOLFSSL_USE_ALIGN } +#ifdef WOLFSSL_USE_ALIGN else { byte *in_bytes = (byte *)in; byte *out_bytes = (byte *)out; diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_util.c b/wolfcrypt/src/port/Renesas/renesas_sce_util.c index 1ed11489ecd..f6bd06f56ab 100644 --- a/wolfcrypt/src/port/Renesas/renesas_sce_util.c +++ b/wolfcrypt/src/port/Renesas/renesas_sce_util.c @@ -291,7 +291,7 @@ WOLFSSL_LOCAL int wc_SCE_EccVerify(WOLFSSL* ssl, const uint8_t* sig, return MEMORY_E; } /* initialization */ - XMEMCPY(sigforSCE, 0, HW_SCE_ECDSA_DATA_BYTE_SIZE); + XMEMSET(sigforSCE, 0, HW_SCE_ECDSA_DATA_BYTE_SIZE); /* r */ if (sig[offset] == 0x20) { @@ -945,7 +945,7 @@ WOLFSSL_LOCAL int wc_sce_tls_CertVerify( return MEMORY_E; } /* initialization */ - XMEMCPY(sigforSCE, 0, HW_SCE_ECDSA_DATA_BYTE_SIZE); + XMEMSET(sigforSCE, 0, HW_SCE_ECDSA_DATA_BYTE_SIZE); if (signature[offset] == 0x20) { XMEMCPY(sigforSCE, &signature[offset+1], rs_size); diff --git a/wolfcrypt/src/port/caam/caam_aes.c b/wolfcrypt/src/port/caam/caam_aes.c index 1abcfc717b2..56efdacf10a 100644 --- a/wolfcrypt/src/port/caam/caam_aes.c +++ b/wolfcrypt/src/port/caam/caam_aes.c @@ -58,7 +58,6 @@ int wc_AesSetKey(Aes* aes, const byte* key, word32 len, if (len > 32) { byte out[32]; /* max AES key size */ word32 outSz; - int ret; if (len != 64 && len != 72 && len != 80) { return BAD_FUNC_ARG; diff --git a/wolfcrypt/src/port/caam/caam_driver.c b/wolfcrypt/src/port/caam/caam_driver.c index 17e1d449e88..b78cbdf8127 100644 --- a/wolfcrypt/src/port/caam/caam_driver.c +++ b/wolfcrypt/src/port/caam/caam_driver.c @@ -1163,7 +1163,7 @@ int caamECDSAMake(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) /* create secure partition for private key out */ part = caamFindUnusedPartition(); - if (part < 0) { + if ((int)part < 0) { WOLFSSL_MSG("error finding an unused partition for new key"); return -1; } diff --git a/wolfcrypt/src/port/cypress/psoc6_crypto.c b/wolfcrypt/src/port/cypress/psoc6_crypto.c index 56dc8e8549f..15f3d207ccd 100644 --- a/wolfcrypt/src/port/cypress/psoc6_crypto.c +++ b/wolfcrypt/src/port/cypress/psoc6_crypto.c @@ -101,7 +101,6 @@ int wc_Sha512GetHash(wc_Sha512* sha, byte* hash) int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) { - cy_en_crypto_status_t res; if ((!dst) || (!src)) return BAD_FUNC_ARG; Cy_Crypto_Core_MemCpy(crypto_base, dst, src, sizeof(wc_Sha512)); @@ -158,7 +157,6 @@ int wc_Sha256GetHash(wc_Sha256* sha, byte* hash) int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) { - cy_en_crypto_status_t res; if ((!dst) || (!src)) return BAD_FUNC_ARG; Cy_Crypto_Core_MemCpy(crypto_base, dst, src, sizeof(wc_Sha256)); diff --git a/wolfcrypt/src/port/xilinx/xil-sha3.c b/wolfcrypt/src/port/xilinx/xil-sha3.c index 9ce130af9b4..459e8d6d7de 100644 --- a/wolfcrypt/src/port/xilinx/xil-sha3.c +++ b/wolfcrypt/src/port/xilinx/xil-sha3.c @@ -202,7 +202,9 @@ void wc_Sha3_384_Free(wc_Sha3* sha) */ int wc_Sha3_384_GetHash(wc_Sha3* sha, byte* out) { +#ifdef WOLFSSL_XILINX_CRYPTO_OLD wc_Sha3 s; +#endif if (sha == NULL || out == NULL) { return BAD_FUNC_ARG; diff --git a/wolfcrypt/src/pwdbased.c b/wolfcrypt/src/pwdbased.c index 99afc177653..6b769f65c2c 100644 --- a/wolfcrypt/src/pwdbased.c +++ b/wolfcrypt/src/pwdbased.c @@ -51,7 +51,7 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, { int err; int keyLeft, ivLeft, i; - int digestLeft, store; + int store; int keyOutput = 0; int diestLen; byte digest[WC_MAX_DIGEST_SIZE]; @@ -96,7 +96,7 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, keyLeft = keyLen; ivLeft = ivLen; while (keyOutput < (keyLen + ivLen)) { - digestLeft = diestLen; + int digestLeft = diestLen; /* D_(i - 1) */ if (keyOutput) { /* first time D_0 is empty */ err = wc_HashUpdate(hash, hashT, digest, diestLen); @@ -176,9 +176,8 @@ int wc_PBKDF1(byte* output, const byte* passwd, int pLen, const byte* salt, int wc_PBKDF2_ex(byte* output, const byte* passwd, int pLen, const byte* salt, int sLen, int iterations, int kLen, int hashType, void* heap, int devId) { - word32 i = 1; int hLen; - int j, ret; + int ret; #ifdef WOLFSSL_SMALL_STACK byte* buffer; Hmac* hmac; @@ -213,11 +212,13 @@ int wc_PBKDF2_ex(byte* output, const byte* passwd, int pLen, const byte* salt, ret = wc_HmacInit(hmac, heap, devId); if (ret == 0) { + word32 i = 1; /* use int hashType here, since HMAC FIPS uses the old unique value */ ret = wc_HmacSetKey(hmac, hashType, passwd, pLen); while (ret == 0 && kLen) { int currentLen; + int j; ret = wc_HmacUpdate(hmac, salt, sLen); if (ret != 0) diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index b289dbc929d..1e5c939d26a 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -617,10 +617,9 @@ static int Hash_gen(DRBG_internal* drbg, byte* out, word32 outSz, const byte* V) static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen) { - word16 carry = 0; - if (dLen > 0 && sLen > 0 && dLen >= sLen) { int sIdx, dIdx; + word16 carry = 0; dIdx = dLen - 1; for (sIdx = sLen - 1; sIdx >= 0; sIdx--) { @@ -3164,7 +3163,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #include "nrf_drv_rng.h" int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) { - int remaining = sz, length, pos = 0; + int remaining = sz, pos = 0; word32 err_code; byte available; static byte initialized = 0; @@ -3185,6 +3184,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } while (remaining > 0) { + int length; available = 0; nrf_drv_rng_bytes_available(&available); /* void func */ length = (remaining < available) ? remaining : available; @@ -3798,14 +3798,13 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) int wc_hwrng_generate_block(byte *output, word32 sz) { int fd; - int len; int ret = 0; fd = open("/dev/hwrng", O_RDONLY); if (fd == -1) return OPEN_RAN_E; while(sz) { - len = (int)read(fd, output, sz); + int len = (int)read(fd, output, sz); if (len == -1) { ret = READ_RAN_E; diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index c91599ec088..c15f0004037 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -1888,9 +1888,6 @@ static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen, { int ret = BAD_FUNC_ARG; word16 i; -#ifndef WOLFSSL_RSA_VERIFY_ONLY - byte invalid = 0; -#endif if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) { return BAD_FUNC_ARG; @@ -1923,6 +1920,7 @@ static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen, else { unsigned int j; word16 pastSep = 0; + byte invalid = 0; i = 0; /* Decrypted with private key - unpad must be constant time. */ @@ -3579,11 +3577,6 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen) ret = RSA_BUFFER_E; else if (ret >= 0 && pad != NULL) { -#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \ - !defined(WOLFSSL_NO_MALLOC) - signed char c; -#endif - /* only copy output if not inline */ if (outPtr == NULL) { #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \ @@ -3594,6 +3587,7 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, int start = (int)((size_t)pad - (size_t)key->data); for (j = 0; j < key->dataLen; j++) { + signed char c; out[i] = key->data[j]; c = ctMaskGTE(j, start); c &= ctMaskLT(i, outLen); diff --git a/wolfcrypt/src/sha3.c b/wolfcrypt/src/sha3.c index c9b69c321c2..2710f203b09 100644 --- a/wolfcrypt/src/sha3.c +++ b/wolfcrypt/src/sha3.c @@ -641,12 +641,11 @@ static int InitSha3(wc_Sha3* sha3) static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) { word32 i; - byte l; - byte *t; word32 blocks; if (sha3->i > 0) { - l = p * 8 - sha3->i; + byte *t; + byte l = p * 8 - sha3->i; if (l > len) { l = (byte)len; } @@ -1300,10 +1299,10 @@ int wc_Shake128_Final(wc_Shake* shake, byte* hash, word32 hashLen) int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len) { int ret; - byte hash[1]; ret = Sha3Update(shake, data, len, WC_SHA3_128_COUNT); if (ret == 0) { + byte hash[1]; ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_128_COUNT, 0); } /* No partial data. */ @@ -1429,10 +1428,10 @@ int wc_Shake256_Final(wc_Shake* shake, byte* hash, word32 hashLen) int wc_Shake256_Absorb(wc_Shake* shake, const byte* data, word32 len) { int ret; - byte hash[1]; ret = Sha3Update(shake, data, len, WC_SHA3_256_COUNT); if (ret == 0) { + byte hash[1]; ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_256_COUNT, 0); } /* No partial data. */ diff --git a/wolfcrypt/src/wolfmath.c b/wolfcrypt/src/wolfmath.c index bf2070f34ad..bb86781bd3a 100644 --- a/wolfcrypt/src/wolfmath.c +++ b/wolfcrypt/src/wolfmath.c @@ -76,7 +76,6 @@ void mp_reverse(unsigned char *s, int len) { int ix, iy; - unsigned char t; if (s == NULL) return; @@ -84,7 +83,7 @@ void mp_reverse(unsigned char *s, int len) ix = 0; iy = len - 1; while (ix < iy) { - t = s[ix]; + unsigned char t = s[ix]; s[ix] = s[iy]; s[iy] = t; ++ix; @@ -120,11 +119,6 @@ mp_digit get_digit(const mp_int* a, int n) int mp_cond_copy(mp_int* a, int copy, mp_int* b) { int err = MP_OKAY; -#if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) - unsigned int i; -#else - int i; -#endif #if defined(SP_WORD_SIZE) && SP_WORD_SIZE == 8 unsigned int mask = (unsigned int)0 - copy; #else @@ -138,6 +132,11 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) if (err == MP_OKAY) err = mp_grow(b, a->used + 1); if (err == MP_OKAY) { + #if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) + unsigned int i; + #else + int i; + #endif /* When mask 0, b is unchanged2 * When mask all set, b ^ b ^ a = a */ @@ -173,9 +172,6 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng) { int ret = 0; int cnt = digits * sizeof(mp_digit); -#ifdef USE_INTEGER_HEAP_MATH - int i; -#endif if (rng == NULL) { ret = MISSING_RNG_E; @@ -208,6 +204,7 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng) } if (ret == MP_OKAY) { #ifdef USE_INTEGER_HEAP_MATH + int i; /* Mask down each digit to only bits used */ for (i = 0; i < a->used; i++) { a->dp[i] &= MP_MASK; @@ -374,7 +371,7 @@ void wc_bigint_free(WC_BIGINT* a) int wc_mp_to_bigint_sz(mp_int* src, WC_BIGINT* dst, word32 sz) { int err; - word32 x, y; + word32 x; if (src == NULL || dst == NULL) return BAD_FUNC_ARG; @@ -388,7 +385,7 @@ int wc_mp_to_bigint_sz(mp_int* src, WC_BIGINT* dst, word32 sz) err = wc_bigint_alloc(dst, sz); if (err == MP_OKAY && sz > 0) { /* leading zero pad */ - y = sz - x; + word32 y = sz - x; XMEMSET(dst->buf, 0, y); /* export src as unsigned bin to destination buf */ diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 72dd9cf5c3a..ace477c78c5 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -19981,7 +19981,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) EVP_MD_CTX_cleanup(&md_ctx); if (ret != WOLFSSL_SUCCESS) return WC_TEST_RET_ENC_NC; - if (XMEMCMP(hash, b.output, WC_SHA_DIGEST_SIZE) != 0) + if (XMEMCMP(hash, b.output, b.outLen) != 0) return WC_TEST_RET_ENC_NC; #endif /* NO_SHA */ @@ -20001,8 +20001,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, e.output, WC_SHA224_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, e.output, e.outLen) != 0) { return WC_TEST_RET_ENC_NC; } #endif /* WOLFSSL_SHA224 */ @@ -20023,8 +20022,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, d.output, WC_SHA256_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, d.output, d.outLen) != 0) { return WC_TEST_RET_ENC_NC; } #endif /* !NO_SHA256 */ @@ -20047,8 +20045,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, e.output, WC_SHA384_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, e.output, e.outLen) != 0) { return WC_TEST_RET_ENC_NC; } #endif /* WOLFSSL_SHA384 */ @@ -20072,8 +20069,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, f.output, WC_SHA512_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, f.output, f.outLen) != 0) { return WC_TEST_RET_ENC_NC; } @@ -20095,8 +20091,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, f.output, WC_SHA512_224_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, f.output, f.outLen) != 0) { return WC_TEST_RET_ENC_NC; } #endif /* !WOLFSSL_NOSHA512_224 && !FIPS ... */ @@ -20119,8 +20114,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, f.output, WC_SHA512_256_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, f.output, f.outLen) != 0) { return WC_TEST_RET_ENC_NC; } #endif /* !WOLFSSL_NOSHA512_224 && !FIPS ... */ @@ -20143,8 +20137,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, e.output, WC_SHA3_224_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, e.output, e.outLen) != 0) { return WC_TEST_RET_ENC_NC; } #endif /* WOLFSSL_NOSHA3_224 */ @@ -20166,8 +20159,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, d.output, WC_SHA3_256_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, d.output, d.outLen) != 0) { return WC_TEST_RET_ENC_NC; } #endif /* WOLFSSL_NOSHA3_256 */ @@ -20189,8 +20181,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) ret = EVP_DigestFinal(&md_ctx, hash, 0); } EVP_MD_CTX_cleanup(&md_ctx); - if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, e.output, WC_SHA3_384_DIGEST_SIZE) != 0) { + if (ret != WOLFSSL_SUCCESS || XMEMCMP(hash, e.output, e.outLen) != 0) { return WC_TEST_RET_ENC_NC; } @@ -20214,7 +20205,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) } EVP_MD_CTX_cleanup(&md_ctx); if (ret != WOLFSSL_SUCCESS || - XMEMCMP(hash, f.output, WC_SHA3_512_DIGEST_SIZE) != 0) { + XMEMCMP(hash, f.output, f.outLen) != 0) { return WC_TEST_RET_ENC_NC; } #endif /* WOLFSSL_NOSHA3_512 */ @@ -20239,7 +20230,7 @@ WOLFSSL_TEST_SUBROUTINE int openssl_test(void) #else if (HMAC(EVP_md5(), "JefeJefeJefeJefe", 16, (byte*)c.input, (int)c.inLen, hash, 0) == NULL || - XMEMCMP(hash, c.output, WC_MD5_DIGEST_SIZE) != 0) + XMEMCMP(hash, c.output, c.outLen) != 0) #endif { return WC_TEST_RET_ENC_NC; @@ -21238,8 +21229,11 @@ WOLFSSL_TEST_SUBROUTINE int openssl_pkey0_test(void) } prvBytes = (int)XFREAD(prvTmp, 1, (int)FOURK_BUFF, keyFile); XFCLOSE(keyFile); - if (prvBytes == 0) + if (prvBytes == 0) { + XFREE(prvTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(pubTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); return WC_TEST_RET_ENC_ERRNO; + } keypubFile = XFOPEN(cliKeypub, "rb"); if (!keypubFile) { XFREE(prvTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); @@ -21250,8 +21244,11 @@ WOLFSSL_TEST_SUBROUTINE int openssl_pkey0_test(void) } pubBytes = (int)XFREAD(pubTmp, 1, (int)FOURK_BUFF, keypubFile); XFCLOSE(keypubFile); - if (pubBytes == 0) + if (pubBytes == 0) { + XFREE(prvTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(pubTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); return WC_TEST_RET_ENC_ERRNO; + } #endif /* USE_CERT_BUFFERS */ prvRsa = wolfSSL_RSA_new(); @@ -21657,8 +21654,11 @@ WOLFSSL_TEST_SUBROUTINE int openssl_evpSig_test(void) } prvBytes = (int)XFREAD(prvTmp, 1, (int)FOURK_BUFF, keyFile); XFCLOSE(keyFile); - if (prvBytes == 0) + if (prvBytes == 0) { + XFREE(prvTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(pubTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); return WC_TEST_RET_ENC_ERRNO; + } keypubFile = XFOPEN(cliKeypub, "rb"); if (!keypubFile) { XFREE(pubTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); @@ -21669,8 +21669,11 @@ WOLFSSL_TEST_SUBROUTINE int openssl_evpSig_test(void) } pubBytes = (int)XFREAD(pubTmp, 1, (int)FOURK_BUFF, keypubFile); XFCLOSE(keypubFile); - if (pubBytes == 0) + if (pubBytes == 0) { + XFREE(prvTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(pubTmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); return WC_TEST_RET_ENC_ERRNO; + } #endif /* USE_CERT_BUFFERS */ prvRsa = wolfSSL_RSA_new(); @@ -24737,7 +24740,9 @@ static int ecc_test_curve_size(WC_RNG* rng, int keySize, int testVerifyCount, WC_DECLARE_VAR(exportBuf, byte, ECC_KEY_EXPORT_BUF_SIZE, HEAP_HINT); #endif word32 x = 0; -#if defined(HAVE_ECC_SIGN) && !defined(WOLFSSL_KCAPI_ECC) +#if !defined(ECC_TIMING_RESISTANT) || (defined(ECC_TIMING_RESISTANT) && \ + !defined(WC_NO_RNG) && !defined(WOLFSSL_KCAPI_ECC)) && \ + defined(HAVE_ECC_SIGN) WC_DECLARE_VAR(sig, byte, ECC_SIG_SIZE, HEAP_HINT); WC_DECLARE_VAR(digest, byte, ECC_DIGEST_SIZE, HEAP_HINT); int i; @@ -24771,7 +24776,9 @@ static int ecc_test_curve_size(WC_RNG* rng, int keySize, int testVerifyCount, ERROR_OUT(WC_TEST_RET_ENC_ERRNO, done); #endif -#if defined(HAVE_ECC_SIGN) && !defined(WOLFSSL_KCAPI_ECC) +#if !defined(ECC_TIMING_RESISTANT) || (defined(ECC_TIMING_RESISTANT) && \ + !defined(WC_NO_RNG) && !defined(WOLFSSL_KCAPI_ECC)) && \ + defined(HAVE_ECC_SIGN) if (sig == NULL || digest == NULL) ERROR_OUT(WC_TEST_RET_ENC_ERRNO, done); #endif @@ -44228,11 +44235,13 @@ static int ecc_onlycb_test(myCryptoDevCtx *ctx) #ifdef OPENSSL_EXTRA EVP_PKEY* privKey = NULL; EVP_PKEY* pubKey = NULL; + #ifdef USE_CERT_BUFFERS_256 ecc_key* pkey; + const unsigned char* cp; + #endif EVP_MD_CTX mdCtx; const char testData[] = "Hi There"; size_t checkSz = -1; - const unsigned char* cp; const unsigned char* p; const unsigned char check_v[256] = { 0x30,0x45,0x02,0x20,0x1b,0x5c,0x2a,0xf0,0x18,0x09, diff --git a/wolfssl/test.h b/wolfssl/test.h index 98e0fc9ccc6..0da86d93921 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -1219,7 +1219,6 @@ static WC_INLINE void build_addr(SOCKADDR_IN_T* addr, const char* peer, if ((XSTRCMP(peer, "localhost") != 0) && (XSTRCMP(peer, "127.0.0.1") != 0)) { FILE* fp; - char host_out[100]; char cmd[100]; XSTRNCPY(cmd, "host ", 6); @@ -1227,6 +1226,7 @@ static WC_INLINE void build_addr(SOCKADDR_IN_T* addr, const char* peer, found = 0; fp = popen(cmd, "r"); if (fp != NULL) { + char host_out[100]; while (fgets(host_out, sizeof(host_out), fp) != NULL) { int i; int j = 0; @@ -2455,7 +2455,6 @@ static WC_INLINE int my_psk_use_session_cb(WOLFSSL* ssl, #if defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) int i; - int b = 0x01; WOLFSSL_SESSION* lsess; char buf[256]; const char* cipher_id = "TLS13-AES128-GCM-SHA256"; @@ -2486,8 +2485,9 @@ static WC_INLINE int my_psk_use_session_cb(WOLFSSL* ssl, } if (i != numCiphers) { + int b = 0x01; SSL_SESSION_set_cipher(lsess, cipher); - for (i = 0; i < 32; i++, b += 0x22) { + for (i = 0; i < 32; i++, b += 0x22) { if (b >= 0x100) b = 0x01; local_psk[i] = b; @@ -2857,7 +2857,6 @@ static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) WOLFSSL_BIO* bio = NULL; WOLFSSL_STACK* sk = NULL; X509* x509 = NULL; - int i = 0; #endif #endif @@ -2900,6 +2899,7 @@ static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) #if defined(SHOW_CERTS) && !defined(NO_FILESYSTEM) /* avoid printing duplicate certs */ if (store->depth == 1) { + int i; /* retrieve x509 certs and display them on stdout */ sk = wolfSSL_X509_STORE_GetCerts(store); @@ -3074,10 +3074,10 @@ static WC_INLINE void CaCb(unsigned char* der, int sz, int type) { #if !defined(NO_FILESYSTEM) || defined(FORCE_BUFFER_TEST) && \ !defined(NETOS) - int depth, res; - XFILE keyFile; + int depth; for(depth = 0; depth <= MAX_WOLF_ROOT_DEPTH; depth++) { - keyFile = XFOPEN(dhParamFile, "rb"); + int res; + XFILE keyFile = XFOPEN(dhParamFile, "rb"); if (keyFile != NULL) { fclose(keyFile); return depth; @@ -4814,13 +4814,13 @@ static WC_INLINE int SimulateWantWriteIOSendCb(WOLFSSL *ssl, char *buf, int sz, { static int wantWriteFlag = 1; - int sent; int sd = *(int*)ctx; (void)ssl; if (!wantWriteFlag) { + int sent; wantWriteFlag = 1; sent = wolfIO_Send(sd, buf, sz, 0); @@ -5164,7 +5164,6 @@ static WC_INLINE void EarlyDataStatus(WOLFSSL* ssl) static WC_INLINE int process_handshake_messages(WOLFSSL* ssl, int blocking, int* zero_return) { - int timeout = DEFAULT_TIMEOUT_SEC; char foo[1]; int ret = 0; int dtls; @@ -5177,6 +5176,8 @@ static WC_INLINE int process_handshake_messages(WOLFSSL* ssl, int blocking, *zero_return = 0; if (!blocking) { + int timeout = DEFAULT_TIMEOUT_SEC; + #ifdef WOLFSSL_DTLS if (dtls) { timeout = wolfSSL_dtls_get_current_timeout(ssl); From 6b05ce8af19abc90032d996c009f194afbcc8e98 Mon Sep 17 00:00:00 2001 From: PrinceOfPuppers Date: Wed, 29 Mar 2023 22:22:31 -0400 Subject: [PATCH 070/391] updated zephyr includes --- wolfcrypt/src/random.c | 6 +++--- wolfssl/internal.h | 2 +- wolfssl/test.h | 2 +- wolfssl/wolfcrypt/settings.h | 6 +++--- wolfssl/wolfcrypt/wc_port.h | 6 +++--- wolfssl/wolfio.h | 2 +- zephyr/zephyr_init.c | 2 +- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 1e5c939d26a..c7fb79e89d3 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -3577,11 +3577,11 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #elif defined(WOLFSSL_ZEPHYR) - #include + #include #ifndef _POSIX_C_SOURCE - #include + #include #else - #include + #include #endif int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 375f137f7ea..9ef6764b609 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -194,7 +194,7 @@ #endif #elif defined(WOLFSSL_ZEPHYR) #ifndef SINGLE_THREADED - #include + #include #endif #elif defined(WOLFSSL_TELIT_M2MB) /* do nothing */ diff --git a/wolfssl/test.h b/wolfssl/test.h index 0da86d93921..4739d4e6be5 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -140,7 +140,7 @@ #elif defined(WOLFSSL_ZEPHYR) #include #include - #include + #include #define SOCKET_T int #define SOL_SOCKET 1 #define WOLFSSL_USE_GETADDRINFO diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 82a03fa4abd..bd5438b20da 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1748,9 +1748,9 @@ extern void uITRON4_free(void *p) ; #endif /*(WOLFSSL_APACHE_MYNEWT)*/ #ifdef WOLFSSL_ZEPHYR - #include - #include - #include + #include + #include + #include #include #define WOLFSSL_DH_CONST diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 30493c47b38..78d53208c3a 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -139,7 +139,7 @@ /* do nothing */ #elif defined(WOLFSSL_ZEPHYR) #ifndef SINGLE_THREADED - #include + #include #endif #elif defined(WOLFSSL_TELIT_M2MB) @@ -508,7 +508,7 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFGETS(b,s,f) -2 /* Not ported yet */ #elif defined(WOLFSSL_ZEPHYR) - #include + #include #define XFILE struct fs_file_t* #define STAT struct fs_dirent @@ -913,7 +913,7 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #elif defined(WOLFSSL_ZEPHYR) #ifndef _POSIX_C_SOURCE - #include + #include #else #include #endif diff --git a/wolfssl/wolfio.h b/wolfssl/wolfio.h index f0d9fd5d387..f783fd0395f 100644 --- a/wolfssl/wolfio.h +++ b/wolfssl/wolfio.h @@ -127,7 +127,7 @@ #include #include #elif defined(WOLFSSL_ZEPHYR) - #include + #include #elif defined(MICROCHIP_PIC32) #include #elif defined(HAVE_NETX) diff --git a/zephyr/zephyr_init.c b/zephyr/zephyr_init.c index b0bb4e6affa..9ec82e2d4ed 100644 --- a/zephyr/zephyr_init.c +++ b/zephyr/zephyr_init.c @@ -25,7 +25,7 @@ * Initialize the wolfSSL library. */ -#include +#include #include "user_settings.h" #include "wolfssl/ssl.h" From 41184e3c67e7c36996c3b57dfc46565c7a27bd62 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 24 Mar 2023 16:42:56 +0100 Subject: [PATCH 071/391] Add config option --- configure.ac | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/configure.ac b/configure.ac index f077f90f620..76c04a27462 100644 --- a/configure.ac +++ b/configure.ac @@ -177,6 +177,17 @@ AS_IF([test "$ax_enable_debug" = "yes"], # enabled ENABLED_CERTS="no" +# Implements requirements from RFC9325 +AC_ARG_ENABLE([harden-tls], + [AS_HELP_STRING([--enable-harden-tls],[Enable requirements from RFC9325 (default: disabled)])], + [ ENABLED_HARDEN_TLS=$enableval ], + [ ENABLED_HARDEN_TLS=no ] + ) + +if test "x$ENABLED_HARDEN_TLS" != "xno" +then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS" +fi # Support for forcing 32-bit mode # To force 32-bit instructions use: From ec023b840d8a5d938e69a0f815e1a2498850755e Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 24 Mar 2023 16:43:34 +0100 Subject: [PATCH 072/391] Truncated hmac check --- wolfssl/wolfcrypt/settings.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index bd5438b20da..52a3927b066 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2967,6 +2967,12 @@ extern void uITRON4_free(void *p) ; #error "Dynamic session cache currently does not support persistent session cache." #endif +#ifdef WOLFSSL_HARDEN_TLS + #ifdef HAVE_TRUNCATED_HMAC + #error "Truncated HMAC Extension not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.6" + #endif +#endif + #ifdef __cplusplus } /* extern "C" */ #endif From 35ba0c50f2b5f0c16b39055a0138924e5beba61d Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 24 Mar 2023 16:44:01 +0100 Subject: [PATCH 073/391] No old TLS check --- configure.ac | 2 +- wolfssl/wolfcrypt/settings.h | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index 76c04a27462..1114fbb5125 100644 --- a/configure.ac +++ b/configure.ac @@ -3492,7 +3492,7 @@ AC_ARG_ENABLE([oldtls], [ ENABLED_OLD_TLS=yes ] ) -if test "$ENABLED_CRYPTONLY" = "yes" +if test "$ENABLED_CRYPTONLY" = "yes" || test "x$ENABLED_HARDEN_TLS" != "xno" then ENABLED_OLD_TLS=no fi diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 52a3927b066..5adb5d7cfd8 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2971,6 +2971,9 @@ extern void uITRON4_free(void *p) ; #ifdef HAVE_TRUNCATED_HMAC #error "Truncated HMAC Extension not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.6" #endif + #ifndef NO_OLD_TLS + #error "TLS < 1.2 protocol versions not allowed https://www.rfc-editor.org/rfc/rfc9325#section-3.1.1" + #endif #endif #ifdef __cplusplus From 4d543f654444216190b3f9a4323d702d86229a90 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 24 Mar 2023 16:44:33 +0100 Subject: [PATCH 074/391] Ciphersuite check https://www.rfc-editor.org/rfc/rfc9325#section-4.1 --- wolfssl/internal.h | 73 ++++++++++++++++++++++++++++++------ wolfssl/wolfcrypt/settings.h | 1 + 2 files changed, 62 insertions(+), 12 deletions(-) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 9ef6764b609..0bb07b2da95 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -305,7 +305,9 @@ #endif #ifndef WOLFSSL_AEAD_ONLY - #if !defined(NO_RSA) && !defined(NO_RC4) + #if !defined(NO_RSA) && !defined(NO_RC4) && !defined(WOLFSSL_HARDEN_TLS) + /* MUST NOT negotiate RC4 cipher suites + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #if defined(WOLFSSL_STATIC_RSA) #if !defined(NO_SHA) #define BUILD_SSL_RSA_WITH_RC4_128_SHA @@ -316,7 +318,12 @@ #endif #endif - #if !defined(NO_RSA) && !defined(NO_DES3) + #if !defined(NO_RSA) && !defined(NO_DES3) && !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites that use algorithms offering + * less than 128 bits of security. + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + * Using guidance from section 5.6.1 + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ #if !defined(NO_SHA) #if defined(WOLFSSL_STATIC_RSA) #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA @@ -376,7 +383,10 @@ #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 #endif #endif - #if !defined(NO_DH) + #if !defined(NO_DH) && !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites based on ephemeral + * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" + * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #if !defined(NO_SHA) #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA @@ -458,7 +468,10 @@ #endif #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \ - !defined(NO_RSA) + !defined(NO_RSA) && !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites based on ephemeral + * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" + * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #if !defined(NO_SHA) #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC) @@ -492,7 +505,11 @@ #endif #endif - #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) + #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \ + !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites based on ephemeral + * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" + * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #ifndef NO_SHA256 #if !defined(NO_AES) && defined(WOLFSSL_AES_128) && \ defined(HAVE_AES_CBC) @@ -619,7 +636,9 @@ #endif #endif #endif /* NO_AES */ - #if !defined(NO_RC4) + #if !defined(NO_RC4) && !defined(WOLFSSL_HARDEN_TLS) + /* MUST NOT negotiate RC4 cipher suites + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #if !defined(NO_SHA) #if !defined(NO_RSA) #ifndef WOLFSSL_AEAD_ONLY @@ -692,7 +711,10 @@ #if !defined(NO_RSA) && defined(HAVE_ECC) #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 #endif - #if !defined(NO_DH) && !defined(NO_RSA) + #if !defined(NO_DH) && !defined(NO_RSA) && !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites based on ephemeral + * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" + * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #define BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 #endif #endif /* NO_OLD_POLY1305 */ @@ -702,7 +724,10 @@ defined(HAVE_ED448) #define BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 #endif - #ifndef NO_DH + #ifndef NO_DH && !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites based on ephemeral + * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" + * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #define BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 #endif #endif /* !NO_PSK */ @@ -711,7 +736,10 @@ #endif /* !WOLFSSL_MAX_STRENGTH */ #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \ - !defined(NO_RSA) && defined(HAVE_AESGCM) + !defined(NO_RSA) && defined(HAVE_AESGCM) && !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites based on ephemeral + * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" + * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128) #define BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 @@ -722,7 +750,11 @@ #endif #endif -#if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) +#if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \ + !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites based on ephemeral + * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" + * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #ifndef NO_SHA256 #if defined(HAVE_AESGCM) && defined(WOLFSSL_AES_128) #define BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 @@ -792,7 +824,10 @@ #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 #endif #endif - #if !defined(NO_DH) && !defined(NO_RSA) + #if !defined(NO_DH) && !defined(NO_RSA) && !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites based on ephemeral + * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" + * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #define BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 #endif #endif @@ -912,7 +947,9 @@ #define BUILD_AES #endif -#ifndef NO_RC4 +#if !defined(NO_RC4) && !defined(WOLFSSL_HARDEN_TLS) + /* MUST NOT negotiate RC4 cipher suites + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #undef BUILD_ARC4 #define BUILD_ARC4 #endif @@ -937,6 +974,18 @@ #define HAVE_PFS #endif +#ifdef WOLFSSL_HARDEN_TLS + #ifdef HAVE_NULL_CIPHER + #error "NULL ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1" + #endif + #ifdef WOLFSSL_STATIC_RSA + #error "Static RSA ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1" + #endif + #ifdef WOLFSSL_STATIC_DH + #error "Static DH ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1" + #endif +#endif + /* actual cipher values, 2nd byte */ enum { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x16, diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 5adb5d7cfd8..64ca2da704f 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2974,6 +2974,7 @@ extern void uITRON4_free(void *p) ; #ifndef NO_OLD_TLS #error "TLS < 1.2 protocol versions not allowed https://www.rfc-editor.org/rfc/rfc9325#section-3.1.1" #endif + /* Ciphersuite check done in internal.h */ #endif #ifdef __cplusplus From 1e27d245724b4dd08c6d4b4278c068a4c5f0d2a7 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 24 Mar 2023 18:23:59 +0100 Subject: [PATCH 075/391] Require 128 bits of security for public keys --- wolfssl/internal.h | 50 +++++++++++++++++++++++++++++++++--- wolfssl/wolfcrypt/settings.h | 18 ++++++++++++- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 0bb07b2da95..9e1f958bc8a 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -661,7 +661,12 @@ #endif #endif #endif - #if !defined(NO_DES3) + #if !defined(NO_DES3) && !defined(WOLFSSL_HARDEN_TLS) + /* SHOULD NOT negotiate cipher suites that use algorithms offering + * less than 128 bits of security. + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + * Using guidance from section 5.6.1 + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ #ifndef NO_SHA #if !defined(NO_RSA) #define BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA @@ -724,7 +729,7 @@ defined(HAVE_ED448) #define BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 #endif - #ifndef NO_DH && !defined(WOLFSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(WOLFSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -984,6 +989,9 @@ #ifdef WOLFSSL_STATIC_DH #error "Static DH ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1" #endif + #ifdef HAVE_ANON + #error "At least the server side has to be authenticated" + #endif #endif /* actual cipher values, 2nd byte */ @@ -1172,12 +1180,27 @@ enum { /* set minimum DH key size allowed */ #ifndef WOLFSSL_MIN_DHKEY_BITS - #ifdef WOLFSSL_MAX_STRENGTH + #ifdef WOLFSSL_HARDEN_TLS + /* SHOULD NOT negotiate cipher suites that use algorithms offering + * less than 128 bits of security. + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + * Using guidance from section 5.6.1 + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ + #define WOLFSSL_MIN_DHKEY_BITS 3072 + #elif defined(WOLFSSL_MAX_STRENGTH) #define WOLFSSL_MIN_DHKEY_BITS 2048 #else #define WOLFSSL_MIN_DHKEY_BITS 1024 #endif #endif +#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_DHKEY_BITS < 3072 + /* SHOULD NOT negotiate cipher suites that use algorithms offering + * less than 128 bits of security. + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + * Using guidance from section 5.6.1 + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ + #error "For 128 bits of security DH needs at least 3072 bit keys" +#endif #if (WOLFSSL_MIN_DHKEY_BITS % 8) #error DH minimum bit size must be multiple of 8 #endif @@ -1205,6 +1228,10 @@ enum { #endif #define MAX_DHKEY_SZ (WOLFSSL_MAX_DHKEY_BITS / 8) +#if WOLFSSL_MAX_DHKEY_BITS < WOLFSSL_MIN_DHKEY_BITS +#error "WOLFSSL_MAX_DHKEY_BITS has to be greater than WOLFSSL_MIN_DHKEY_BITS" +#endif + #ifndef MAX_PSK_ID_LEN /* max psk identity/hint supported */ #if defined(WOLFSSL_TLS13) @@ -1800,12 +1827,27 @@ enum Misc { /* set minimum RSA key size allowed */ #ifndef WOLFSSL_MIN_RSA_BITS - #ifdef WOLFSSL_MAX_STRENGTH + #ifdef WOLFSSL_HARDEN_TLS + /* SHOULD NOT negotiate cipher suites that use algorithms offering + * less than 128 bits of security. + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + * Using guidance from section 5.6.1 + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ + #define WOLFSSL_MIN_RSA_BITS 3072 + #elif defined(WOLFSSL_MAX_STRENGTH) #define WOLFSSL_MIN_RSA_BITS 2048 #else #define WOLFSSL_MIN_RSA_BITS 1024 #endif #endif /* WOLFSSL_MIN_RSA_BITS */ +#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_RSA_BITS < 3072 + /* SHOULD NOT negotiate cipher suites that use algorithms offering + * less than 128 bits of security. + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + * Using guidance from section 5.6.1 + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ + #error "For 128 bits of security RSA needs at least 3072 bit keys" +#endif #if (WOLFSSL_MIN_RSA_BITS % 8) /* This is to account for the example case of a min size of 2050 bits but still allows 2049 bit key. So we need the measurement to be in bytes. */ diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 64ca2da704f..610c107253a 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2007,7 +2007,14 @@ extern void uITRON4_free(void *p) ; #ifdef WOLFSSL_MIN_ECC_BITS #define ECC_MIN_KEY_SZ WOLFSSL_MIN_ECC_BITS #else - #if FIPS_VERSION_GE(2,0) + #ifdef WOLFSSL_HARDEN_TLS + /* SHOULD NOT negotiate cipher suites that use algorithms offering + * less than 128 bits of security. + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + * Using guidance from section 5.6.1 + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ + #define ECC_MIN_KEY_SZ 256 + #elif FIPS_VERSION_GE(2,0) /* FIPSv2 and ready (for now) includes 192-bit support */ #define ECC_MIN_KEY_SZ 192 #else @@ -2016,6 +2023,15 @@ extern void uITRON4_free(void *p) ; #endif #endif +#if defined(WOLFSSL_HARDEN_TLS) && ECC_MIN_KEY_SZ < 256 + /* SHOULD NOT negotiate cipher suites that use algorithms offering + * less than 128 bits of security. + * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + * Using guidance from section 5.6.1 + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ + #error "For 128 bits of security ECC needs at least 256 bit keys" +#endif + /* ECC Configs */ #ifdef HAVE_ECC /* By default enable Sign, Verify, DHE, Key Import and Key Export unless From ffde69c1f730679067bfda7bd32cfd366c29145c Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Mon, 27 Mar 2023 15:42:19 +0200 Subject: [PATCH 076/391] Allow user to choose between 112 and 128 bits of security --- configure.ac | 12 ++++++-- wolfssl/internal.h | 55 ++++++++++++++++++------------------ wolfssl/wolfcrypt/settings.h | 25 ++++++++++------ 3 files changed, 53 insertions(+), 39 deletions(-) diff --git a/configure.ac b/configure.ac index 1114fbb5125..f7bfceb0f47 100644 --- a/configure.ac +++ b/configure.ac @@ -179,14 +179,22 @@ ENABLED_CERTS="no" # Implements requirements from RFC9325 AC_ARG_ENABLE([harden-tls], - [AS_HELP_STRING([--enable-harden-tls],[Enable requirements from RFC9325 (default: disabled)])], + [AS_HELP_STRING([--enable-harden-tls],[Enable requirements from RFC9325. Possible values are , <112>, or <128> (default: disabled)])], [ ENABLED_HARDEN_TLS=$enableval ], [ ENABLED_HARDEN_TLS=no ] ) if test "x$ENABLED_HARDEN_TLS" != "xno" then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS" + if test "x$ENABLED_HARDEN_TLS" == "xyes" || test "x$ENABLED_HARDEN_TLS" == "x112" + then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS=112" + elif test "x$ENABLED_HARDEN_TLS" == "x128" + then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS=128" + else + AC_MSG_ERROR([Invalid value for --enable-harden-tls]) + fi fi # Support for forcing 32-bit mode diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 9e1f958bc8a..69b7e855295 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -304,6 +304,9 @@ #undef HAVE_AES_CBC #endif + /* When adding new ciphersuites, make sure that they have appropriate + * guards for WOLFSSL_HARDEN_TLS. */ + #ifndef WOLFSSL_AEAD_ONLY #if !defined(NO_RSA) && !defined(NO_RC4) && !defined(WOLFSSL_HARDEN_TLS) /* MUST NOT negotiate RC4 cipher suites @@ -318,12 +321,7 @@ #endif #endif - #if !defined(NO_RSA) && !defined(NO_DES3) && !defined(WOLFSSL_HARDEN_TLS) - /* SHOULD NOT negotiate cipher suites that use algorithms offering - * less than 128 bits of security. - * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 - * Using guidance from section 5.6.1 - * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ + #if !defined(NO_RSA) && !defined(NO_DES3) #if !defined(NO_SHA) #if defined(WOLFSSL_STATIC_RSA) #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA @@ -661,10 +659,9 @@ #endif #endif #endif - #if !defined(NO_DES3) && !defined(WOLFSSL_HARDEN_TLS) - /* SHOULD NOT negotiate cipher suites that use algorithms offering - * less than 128 bits of security. - * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 + #if !defined(NO_DES3) && !(defined(WOLFSSL_HARDEN_TLS) && \ + WOLFSSL_HARDEN_TLS > 112) + /* 3DES offers only 112 bits of security. * Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ #ifndef NO_SHA @@ -1181,25 +1178,26 @@ enum { /* set minimum DH key size allowed */ #ifndef WOLFSSL_MIN_DHKEY_BITS #ifdef WOLFSSL_HARDEN_TLS - /* SHOULD NOT negotiate cipher suites that use algorithms offering - * less than 128 bits of security. - * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 - * Using guidance from section 5.6.1 + /* Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ - #define WOLFSSL_MIN_DHKEY_BITS 3072 + #if WOLFSSL_HARDEN_TLS >= 128 + #define WOLFSSL_MIN_DHKEY_BITS 3072 + #elif WOLFSSL_HARDEN_TLS >= 112 + #define WOLFSSL_MIN_DHKEY_BITS 2048 + #endif #elif defined(WOLFSSL_MAX_STRENGTH) #define WOLFSSL_MIN_DHKEY_BITS 2048 #else #define WOLFSSL_MIN_DHKEY_BITS 1024 #endif #endif -#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_DHKEY_BITS < 3072 - /* SHOULD NOT negotiate cipher suites that use algorithms offering - * less than 128 bits of security. +#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_DHKEY_BITS < 2048 + /* Implementations MUST NOT negotiate cipher suites offering less than + * 112 bits of security. * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 * Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ - #error "For 128 bits of security DH needs at least 3072 bit keys" + #error "For 112 bits of security DH needs at least 2048 bit keys" #endif #if (WOLFSSL_MIN_DHKEY_BITS % 8) #error DH minimum bit size must be multiple of 8 @@ -1828,25 +1826,26 @@ enum Misc { /* set minimum RSA key size allowed */ #ifndef WOLFSSL_MIN_RSA_BITS #ifdef WOLFSSL_HARDEN_TLS - /* SHOULD NOT negotiate cipher suites that use algorithms offering - * less than 128 bits of security. - * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 - * Using guidance from section 5.6.1 + /* Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ - #define WOLFSSL_MIN_RSA_BITS 3072 + #if WOLFSSL_HARDEN_TLS >= 128 + #define WOLFSSL_MIN_RSA_BITS 3072 + #elif WOLFSSL_HARDEN_TLS >= 112 + #define WOLFSSL_MIN_RSA_BITS 2048 + #endif #elif defined(WOLFSSL_MAX_STRENGTH) #define WOLFSSL_MIN_RSA_BITS 2048 #else #define WOLFSSL_MIN_RSA_BITS 1024 #endif #endif /* WOLFSSL_MIN_RSA_BITS */ -#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_RSA_BITS < 3072 - /* SHOULD NOT negotiate cipher suites that use algorithms offering - * less than 128 bits of security. +#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_RSA_BITS < 2048 + /* Implementations MUST NOT negotiate cipher suites offering less than + * 112 bits of security. * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 * Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ - #error "For 128 bits of security RSA needs at least 3072 bit keys" + #error "For 112 bits of security RSA needs at least 2048 bit keys" #endif #if (WOLFSSL_MIN_RSA_BITS % 8) /* This is to account for the example case of a min size of 2050 bits but diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 610c107253a..ee385eb073f 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -306,6 +306,12 @@ #endif +#ifdef WOLFSSL_HARDEN_TLS + #if WOLFSSL_HARDEN_TLS != 112 && WOLFSSL_HARDEN_TLS != 128 + #error "WOLFSSL_HARDEN_TLS must be defined either to 112 or 128 bits of security." + #endif +#endif + #if defined(_WIN32) && !defined(_M_X64) && \ defined(HAVE_AESGCM) && defined(WOLFSSL_AESNI) @@ -2008,12 +2014,13 @@ extern void uITRON4_free(void *p) ; #define ECC_MIN_KEY_SZ WOLFSSL_MIN_ECC_BITS #else #ifdef WOLFSSL_HARDEN_TLS - /* SHOULD NOT negotiate cipher suites that use algorithms offering - * less than 128 bits of security. - * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 - * Using guidance from section 5.6.1 + /* Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ - #define ECC_MIN_KEY_SZ 256 + #if WOLFSSL_HARDEN_TLS >= 128 + #define ECC_MIN_KEY_SZ 256 + #elif WOLFSSL_HARDEN_TLS >= 112 + #define ECC_MIN_KEY_SZ 224 + #endif #elif FIPS_VERSION_GE(2,0) /* FIPSv2 and ready (for now) includes 192-bit support */ #define ECC_MIN_KEY_SZ 192 @@ -2023,13 +2030,13 @@ extern void uITRON4_free(void *p) ; #endif #endif -#if defined(WOLFSSL_HARDEN_TLS) && ECC_MIN_KEY_SZ < 256 - /* SHOULD NOT negotiate cipher suites that use algorithms offering - * less than 128 bits of security. +#if defined(WOLFSSL_HARDEN_TLS) && ECC_MIN_KEY_SZ < 224 + /* Implementations MUST NOT negotiate cipher suites offering less than + * 112 bits of security. * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 * Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ - #error "For 128 bits of security ECC needs at least 256 bit keys" + #error "For 112 bits of security ECC needs at least 224 bit keys" #endif /* ECC Configs */ From b814971373ac190a4293df8f75139ab7469b54b8 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Mon, 27 Mar 2023 17:20:16 +0200 Subject: [PATCH 077/391] Add harden config to testing --- .github/workflows/os-check.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/os-check.yml b/.github/workflows/os-check.yml index 213cf9d70f6..218e439f3df 100644 --- a/.github/workflows/os-check.yml +++ b/.github/workflows/os-check.yml @@ -14,6 +14,7 @@ jobs: '', '--enable-all --enable-asn=template', '--enable-all --enable-asn=original', + '--enable-harden-tls', ] name: make check runs-on: ${{ matrix.os }} From b7645a22d370656dfee9e5753bb07f61e5df70be Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Mon, 27 Mar 2023 17:53:59 +0200 Subject: [PATCH 078/391] Send secure renegotiation extension by default - Add test for terminating the connection - Add ProcessReplyEx(ssl, 1) to wolfSSL_accept --- configure.ac | 1 + src/internal.c | 18 ++++++++- src/ssl.c | 27 ++++++++++++++ tests/api.c | 72 ++++++++++++++++++++++++++++++++++++ wolfssl/wolfcrypt/settings.h | 7 ++++ 5 files changed, 123 insertions(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index f7bfceb0f47..8c713dd95da 100644 --- a/configure.ac +++ b/configure.ac @@ -195,6 +195,7 @@ then else AC_MSG_ERROR([Invalid value for --enable-harden-tls]) fi + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_EXTRA_ALERTS -DWOLFSSL_CHECK_ALERT_ON_ERR" fi # Support for forcing 32-bit mode diff --git a/src/internal.c b/src/internal.c index b689550d3d7..580379f3942 100644 --- a/src/internal.c +++ b/src/internal.c @@ -7128,11 +7128,13 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) } #endif -#ifdef HAVE_SECURE_RENEGOTIATION +#if defined(HAVE_SECURE_RENEGOTIATION) || \ + defined(HAVE_SERVER_RENEGOTIATION_INFO) if (ssl->options.side == WOLFSSL_CLIENT_END) { int useSecureReneg = ssl->ctx->useSecureReneg; /* use secure renegotiation by default (not recommend) */ - #ifdef WOLFSSL_SECURE_RENEGOTIATION_ON_BY_DEFAULT + #if defined(WOLFSSL_SECURE_RENEGOTIATION_ON_BY_DEFAULT) || \ + (defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_NO_TLS12)) useSecureReneg = 1; #endif if (useSecureReneg) { @@ -27000,6 +27002,18 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } #endif +#ifdef WOLFSSL_HARDEN_TLS + if (ssl->secure_renegotiation == NULL || + !ssl->secure_renegotiation->enabled) { + /* If the server does not acknowledge the extension, the client + * MUST generate a fatal handshake_failure alert prior to + * terminating the connection. + * https://www.rfc-editor.org/rfc/rfc9325#name-renegotiation-in-tls-12 */ + WOLFSSL_MSG("ServerHello did not contain SCR extension"); + return SECURE_RENEGOTIATION_E; + } +#endif + ssl->options.serverState = SERVER_HELLO_COMPLETE; if (IsEncryptionOn(ssl, 0)) { diff --git a/src/ssl.c b/src/ssl.c index e994c461e90..0231a5ee8b0 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -13966,6 +13966,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, case ACCEPT_FIRST_REPLY_DONE : if ( (ssl->error = SendServerHello(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; } @@ -13982,6 +13985,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #ifndef NO_CERTS if (!ssl->options.resuming) if ( (ssl->error = SendCertificate(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; } @@ -13994,6 +14000,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #ifndef NO_CERTS if (!ssl->options.resuming) if ( (ssl->error = SendCertificateStatus(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; } @@ -14010,6 +14019,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #endif if (!ssl->options.resuming) if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; } @@ -14022,6 +14034,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, if (!ssl->options.resuming) { if (ssl->options.verifyPeer) { if ( (ssl->error = SendCertificateRequest(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; } @@ -14039,6 +14054,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, case CERT_REQ_SENT : if (!ssl->options.resuming) if ( (ssl->error = SendServerHelloDone(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; } @@ -14077,6 +14095,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #ifdef HAVE_SESSION_TICKET if (ssl->options.createTicket && !ssl->options.noTicketTls12) { if ( (ssl->error = SendTicket(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_MSG("Thought we need ticket but failed"); WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; @@ -14095,6 +14116,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, } if ( (ssl->error = SendChangeCipher(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; } @@ -14104,6 +14128,9 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, case CHANGE_CIPHER_SENT : if ( (ssl->error = SendFinished(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; } diff --git a/tests/api.c b/tests/api.c index aee462d5554..a6ca181bc84 100644 --- a/tests/api.c +++ b/tests/api.c @@ -64674,6 +64674,77 @@ static int test_extra_alerts_bad_psk(void) return TEST_SKIPPED; } #endif + +#if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_NO_TLS12) && \ + defined(HAVE_IO_TESTS_DEPENDENCIES) +static int test_harden_no_secure_renegotiation_io_cb(WOLFSSL *ssl, char *buf, + int sz, void *ctx) +{ + static int sentServerHello = FALSE; + + if (!sentServerHello) { + byte renegExt[] = { 0xFF, 0x01, 0x00, 0x01, 0x00 }; + size_t i; + + if (sz < (int)sizeof(renegExt)) + return WOLFSSL_CBIO_ERR_GENERAL; + + /* Remove SCR from ServerHello */ + for (i = 0; i < sz - sizeof(renegExt); i++) { + if (XMEMCMP(buf + i, renegExt, sizeof(renegExt)) == 0) { + /* Found the extension. Change it to something unrecognized. */ + buf[i+1] = 0x11; + break; + } + } + sentServerHello = TRUE; + } + + return EmbedSend(ssl, buf, sz, ctx); +} + +static void test_harden_no_secure_renegotiation_ssl_ready(WOLFSSL* ssl) +{ + wolfSSL_SSLSetIOSend(ssl, test_harden_no_secure_renegotiation_io_cb); +} + +static void test_harden_no_secure_renegotiation_on_cleanup(WOLFSSL* ssl) +{ + WOLFSSL_ALERT_HISTORY h; + AssertIntEQ(wolfSSL_get_alert_history(ssl, &h), WOLFSSL_SUCCESS); + AssertIntEQ(h.last_rx.code, handshake_failure); + AssertIntEQ(h.last_rx.level, alert_fatal); +} + +static int test_harden_no_secure_renegotiation(void) +{ + callback_functions client_cbs, server_cbs; + + XMEMSET(&client_cbs, 0, sizeof(client_cbs)); + XMEMSET(&server_cbs, 0, sizeof(server_cbs)); + + client_cbs.method = wolfTLSv1_2_client_method; + server_cbs.method = wolfTLSv1_2_server_method; + + server_cbs.ssl_ready = test_harden_no_secure_renegotiation_ssl_ready; + server_cbs.on_cleanup = test_harden_no_secure_renegotiation_on_cleanup; + test_wolfSSL_client_server_nofail(&client_cbs, &server_cbs); + + AssertIntEQ(client_cbs.return_code, TEST_FAIL); + AssertIntEQ(client_cbs.last_err, SECURE_RENEGOTIATION_E); + AssertIntEQ(server_cbs.return_code, TEST_FAIL); + AssertIntEQ(server_cbs.last_err, SOCKET_ERROR_E); + + return TEST_RES_CHECK(1); +} +#else +static int test_harden_no_secure_renegotiation(void) +{ + return TEST_SKIPPED; +} +#endif + + /*----------------------------------------------------------------------------* | Main *----------------------------------------------------------------------------*/ @@ -65705,6 +65776,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_extra_alerts_wrong_cs), TEST_DECL(test_extra_alerts_skip_hs), TEST_DECL(test_extra_alerts_bad_psk), + TEST_DECL(test_harden_no_secure_renegotiation), /* If at some point a stub get implemented this test should fail indicating * a need to implement a new test case */ diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index ee385eb073f..cc4a66866ff 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2997,6 +2997,13 @@ extern void uITRON4_free(void *p) ; #ifndef NO_OLD_TLS #error "TLS < 1.2 protocol versions not allowed https://www.rfc-editor.org/rfc/rfc9325#section-3.1.1" #endif + #if !defined(WOLFSSL_NO_TLS12) && !defined(HAVE_SECURE_RENEGOTIATION) && \ + !defined(HAVE_SERVER_RENEGOTIATION_INFO) + #error "TLS 1.2 requires at least HAVE_SERVER_RENEGOTIATION_INFO to send the secure renegotiation extension https://www.rfc-editor.org/rfc/rfc9325#section-3.5" + #endif + #if !defined(WOLFSSL_EXTRA_ALERTS) || !defined(WOLFSSL_CHECK_ALERT_ON_ERR) + #error "RFC9325 requires some additional alerts to be sent" + #endif /* Ciphersuite check done in internal.h */ #endif From 2b355b192876c7ab6102629face2cabc1386e7d1 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Tue, 28 Mar 2023 14:14:40 +0200 Subject: [PATCH 079/391] Add comment. --- configure.ac | 2 +- src/internal.c | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index 8c713dd95da..3060536dda0 100644 --- a/configure.ac +++ b/configure.ac @@ -179,7 +179,7 @@ ENABLED_CERTS="no" # Implements requirements from RFC9325 AC_ARG_ENABLE([harden-tls], - [AS_HELP_STRING([--enable-harden-tls],[Enable requirements from RFC9325. Possible values are , <112>, or <128> (default: disabled)])], + [AS_HELP_STRING([--enable-harden-tls],[Enable requirements from RFC9325. Possible values are , <112>, or <128>. is equivalent to <112>. (default: disabled)])], [ ENABLED_HARDEN_TLS=$enableval ], [ ENABLED_HARDEN_TLS=no ] ) diff --git a/src/internal.c b/src/internal.c index 580379f3942..c8228984608 100644 --- a/src/internal.c +++ b/src/internal.c @@ -79,6 +79,10 @@ * by default. * https://www.rfc-editor.org/rfc/rfc8446#section-5.5 * https://www.rfc-editor.org/rfc/rfc9147.html#name-aead-limits + * WOLFSSL_HARDEN_TLS + * Implement the recommendations specified in RFC9325. This macro needs to + * be defined to the desired amount of bits of security. The currently + * implemented values are 112 and 128 bits. */ From f9fb298bc1034f3d55d3d9e852eaefa2d0d8fab4 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 29 Mar 2023 14:22:31 +0200 Subject: [PATCH 080/391] Add flags to disable certain checks --- src/internal.c | 13 +++++++--- wolfssl/internal.h | 48 +++++++++++++++++++++--------------- wolfssl/wolfcrypt/settings.h | 12 +++++---- 3 files changed, 45 insertions(+), 28 deletions(-) diff --git a/src/internal.c b/src/internal.c index c8228984608..b76a4d34bc8 100644 --- a/src/internal.c +++ b/src/internal.c @@ -82,7 +82,13 @@ * WOLFSSL_HARDEN_TLS * Implement the recommendations specified in RFC9325. This macro needs to * be defined to the desired amount of bits of security. The currently - * implemented values are 112 and 128 bits. + * implemented values are 112 and 128 bits. The following macros disable + * certain checks. + * - WOLFSSL_HARDEN_TLS_ALLOW_TRUNCATED_HMAC + * - WOLFSSL_HARDEN_TLS_ALLOW_OLD_TLS + * - WOLFSSL_HARDEN_TLS_NO_SCR_CHECK + * - WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK + * - WOLFSSL_HARDEN_TLS_ALLOW_ALL_CIPHERSUITES */ @@ -7138,7 +7144,8 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) int useSecureReneg = ssl->ctx->useSecureReneg; /* use secure renegotiation by default (not recommend) */ #if defined(WOLFSSL_SECURE_RENEGOTIATION_ON_BY_DEFAULT) || \ - (defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_NO_TLS12)) + (defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_NO_TLS12) && \ + !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK)) useSecureReneg = 1; #endif if (useSecureReneg) { @@ -27006,7 +27013,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } #endif -#ifdef WOLFSSL_HARDEN_TLS +#if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK) if (ssl->secure_renegotiation == NULL || !ssl->secure_renegotiation->enabled) { /* If the server does not acknowledge the extension, the client diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 69b7e855295..34aee973768 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -304,11 +304,15 @@ #undef HAVE_AES_CBC #endif - /* When adding new ciphersuites, make sure that they have appropriate - * guards for WOLFSSL_HARDEN_TLS. */ +/* When adding new ciphersuites, make sure that they have appropriate + * guards for WOLFSSL_HARDEN_TLS. */ +#ifndef WOLFSSL_HARDEN_TLS_ALLOW_ALL_CIPHERSUITES +/* Use a separate define (undef'ed later) to simplify macro logic. */ +#define WSSL_HARDEN_TLS WOLFSSL_HARDEN_TLS +#endif #ifndef WOLFSSL_AEAD_ONLY - #if !defined(NO_RSA) && !defined(NO_RC4) && !defined(WOLFSSL_HARDEN_TLS) + #if !defined(NO_RSA) && !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS) /* MUST NOT negotiate RC4 cipher suites * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #if defined(WOLFSSL_STATIC_RSA) @@ -381,7 +385,7 @@ #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 #endif #endif - #if !defined(NO_DH) && !defined(WOLFSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(WSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -466,7 +470,7 @@ #endif #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \ - !defined(NO_RSA) && !defined(WOLFSSL_HARDEN_TLS) + !defined(NO_RSA) && !defined(WSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -504,7 +508,7 @@ #endif #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \ - !defined(WOLFSSL_HARDEN_TLS) + !defined(WSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -634,7 +638,7 @@ #endif #endif #endif /* NO_AES */ - #if !defined(NO_RC4) && !defined(WOLFSSL_HARDEN_TLS) + #if !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS) /* MUST NOT negotiate RC4 cipher suites * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #if !defined(NO_SHA) @@ -659,8 +663,8 @@ #endif #endif #endif - #if !defined(NO_DES3) && !(defined(WOLFSSL_HARDEN_TLS) && \ - WOLFSSL_HARDEN_TLS > 112) + #if !defined(NO_DES3) && !(defined(WSSL_HARDEN_TLS) && \ + WSSL_HARDEN_TLS > 112) /* 3DES offers only 112 bits of security. * Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ @@ -713,7 +717,7 @@ #if !defined(NO_RSA) && defined(HAVE_ECC) #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 #endif - #if !defined(NO_DH) && !defined(NO_RSA) && !defined(WOLFSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(NO_RSA) && !defined(WSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -726,7 +730,7 @@ defined(HAVE_ED448) #define BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 #endif - #if !defined(NO_DH) && !defined(WOLFSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(WSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -738,7 +742,7 @@ #endif /* !WOLFSSL_MAX_STRENGTH */ #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \ - !defined(NO_RSA) && defined(HAVE_AESGCM) && !defined(WOLFSSL_HARDEN_TLS) + !defined(NO_RSA) && defined(HAVE_AESGCM) && !defined(WSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -753,7 +757,7 @@ #endif #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \ - !defined(WOLFSSL_HARDEN_TLS) + !defined(WSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -826,7 +830,7 @@ #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 #endif #endif - #if !defined(NO_DH) && !defined(NO_RSA) && !defined(WOLFSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(NO_RSA) && !defined(WSSL_HARDEN_TLS) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -949,7 +953,7 @@ #define BUILD_AES #endif -#if !defined(NO_RC4) && !defined(WOLFSSL_HARDEN_TLS) +#if !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS) /* MUST NOT negotiate RC4 cipher suites * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ #undef BUILD_ARC4 @@ -976,7 +980,7 @@ #define HAVE_PFS #endif -#ifdef WOLFSSL_HARDEN_TLS +#ifdef WSSL_HARDEN_TLS #ifdef HAVE_NULL_CIPHER #error "NULL ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1" #endif @@ -991,6 +995,8 @@ #endif #endif +#undef WSSL_HARDEN_TLS + /* actual cipher values, 2nd byte */ enum { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x16, @@ -1177,7 +1183,7 @@ enum { /* set minimum DH key size allowed */ #ifndef WOLFSSL_MIN_DHKEY_BITS - #ifdef WOLFSSL_HARDEN_TLS + #if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK) /* Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ #if WOLFSSL_HARDEN_TLS >= 128 @@ -1191,7 +1197,8 @@ enum { #define WOLFSSL_MIN_DHKEY_BITS 1024 #endif #endif -#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_DHKEY_BITS < 2048 +#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_DHKEY_BITS < 2048 && \ + !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK) /* Implementations MUST NOT negotiate cipher suites offering less than * 112 bits of security. * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 @@ -1825,7 +1832,7 @@ enum Misc { /* set minimum RSA key size allowed */ #ifndef WOLFSSL_MIN_RSA_BITS - #ifdef WOLFSSL_HARDEN_TLS + #if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK) /* Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ #if WOLFSSL_HARDEN_TLS >= 128 @@ -1839,7 +1846,8 @@ enum Misc { #define WOLFSSL_MIN_RSA_BITS 1024 #endif #endif /* WOLFSSL_MIN_RSA_BITS */ -#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_RSA_BITS < 2048 +#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_RSA_BITS < 2048 && \ + !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK) /* Implementations MUST NOT negotiate cipher suites offering less than * 112 bits of security. * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index cc4a66866ff..7afb8d82179 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2013,7 +2013,8 @@ extern void uITRON4_free(void *p) ; #ifdef WOLFSSL_MIN_ECC_BITS #define ECC_MIN_KEY_SZ WOLFSSL_MIN_ECC_BITS #else - #ifdef WOLFSSL_HARDEN_TLS + #if defined(WOLFSSL_HARDEN_TLS) && \ + !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK) /* Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ #if WOLFSSL_HARDEN_TLS >= 128 @@ -2030,7 +2031,8 @@ extern void uITRON4_free(void *p) ; #endif #endif -#if defined(WOLFSSL_HARDEN_TLS) && ECC_MIN_KEY_SZ < 224 +#if defined(WOLFSSL_HARDEN_TLS) && ECC_MIN_KEY_SZ < 224 && \ + !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK) /* Implementations MUST NOT negotiate cipher suites offering less than * 112 bits of security. * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 @@ -2991,14 +2993,14 @@ extern void uITRON4_free(void *p) ; #endif #ifdef WOLFSSL_HARDEN_TLS - #ifdef HAVE_TRUNCATED_HMAC + #if defined(HAVE_TRUNCATED_HMAC) && !defined(WOLFSSL_HARDEN_TLS_ALLOW_TRUNCATED_HMAC) #error "Truncated HMAC Extension not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.6" #endif - #ifndef NO_OLD_TLS + #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_HARDEN_TLS_ALLOW_OLD_TLS) #error "TLS < 1.2 protocol versions not allowed https://www.rfc-editor.org/rfc/rfc9325#section-3.1.1" #endif #if !defined(WOLFSSL_NO_TLS12) && !defined(HAVE_SECURE_RENEGOTIATION) && \ - !defined(HAVE_SERVER_RENEGOTIATION_INFO) + !defined(HAVE_SERVER_RENEGOTIATION_INFO) && !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK) #error "TLS 1.2 requires at least HAVE_SERVER_RENEGOTIATION_INFO to send the secure renegotiation extension https://www.rfc-editor.org/rfc/rfc9325#section-3.5" #endif #if !defined(WOLFSSL_EXTRA_ALERTS) || !defined(WOLFSSL_CHECK_ALERT_ON_ERR) From d28244ed4a0acdea3ed07191a5d73c2895dec396 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Thu, 30 Mar 2023 14:56:31 +0200 Subject: [PATCH 081/391] Add missing define --- wolfssl/internal.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 34aee973768..6e90516d11c 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -306,7 +306,8 @@ /* When adding new ciphersuites, make sure that they have appropriate * guards for WOLFSSL_HARDEN_TLS. */ -#ifndef WOLFSSL_HARDEN_TLS_ALLOW_ALL_CIPHERSUITES +#if defined(WOLFSSL_HARDEN_TLS) && \ + !defined(WOLFSSL_HARDEN_TLS_ALLOW_ALL_CIPHERSUITES) /* Use a separate define (undef'ed later) to simplify macro logic. */ #define WSSL_HARDEN_TLS WOLFSSL_HARDEN_TLS #endif From 925ec8091e287100debad26b857322f466dc8159 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Thu, 30 Mar 2023 15:35:52 +0200 Subject: [PATCH 082/391] Address code review --- src/internal.c | 2 +- wolfssl/internal.h | 17 +++++++++-------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/internal.c b/src/internal.c index b76a4d34bc8..c2c90f5356e 100644 --- a/src/internal.c +++ b/src/internal.c @@ -81,7 +81,7 @@ * https://www.rfc-editor.org/rfc/rfc9147.html#name-aead-limits * WOLFSSL_HARDEN_TLS * Implement the recommendations specified in RFC9325. This macro needs to - * be defined to the desired amount of bits of security. The currently + * be defined to the desired number of bits of security. The currently * implemented values are 112 and 128 bits. The following macros disable * certain checks. * - WOLFSSL_HARDEN_TLS_ALLOW_TRUNCATED_HMAC diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 6e90516d11c..0ade5dc0fb7 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -310,6 +310,7 @@ !defined(WOLFSSL_HARDEN_TLS_ALLOW_ALL_CIPHERSUITES) /* Use a separate define (undef'ed later) to simplify macro logic. */ #define WSSL_HARDEN_TLS WOLFSSL_HARDEN_TLS +#define NO_TLS_DH #endif #ifndef WOLFSSL_AEAD_ONLY @@ -386,7 +387,7 @@ #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 #endif #endif - #if !defined(NO_DH) && !defined(WSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(NO_TLS_DH) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -471,7 +472,7 @@ #endif #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \ - !defined(NO_RSA) && !defined(WSSL_HARDEN_TLS) + !defined(NO_RSA) && !defined(NO_TLS_DH) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -509,7 +510,7 @@ #endif #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \ - !defined(WSSL_HARDEN_TLS) + !defined(NO_TLS_DH) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -718,7 +719,7 @@ #if !defined(NO_RSA) && defined(HAVE_ECC) #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 #endif - #if !defined(NO_DH) && !defined(NO_RSA) && !defined(WSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(NO_RSA) && !defined(NO_TLS_DH) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -731,7 +732,7 @@ defined(HAVE_ED448) #define BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 #endif - #if !defined(NO_DH) && !defined(WSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(NO_TLS_DH) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -743,7 +744,7 @@ #endif /* !WOLFSSL_MAX_STRENGTH */ #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \ - !defined(NO_RSA) && defined(HAVE_AESGCM) && !defined(WSSL_HARDEN_TLS) + !defined(NO_RSA) && defined(HAVE_AESGCM) && !defined(NO_TLS_DH) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -758,7 +759,7 @@ #endif #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \ - !defined(WSSL_HARDEN_TLS) + !defined(NO_TLS_DH) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ @@ -831,7 +832,7 @@ #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 #endif #endif - #if !defined(NO_DH) && !defined(NO_RSA) && !defined(WSSL_HARDEN_TLS) + #if !defined(NO_DH) && !defined(NO_RSA) && !defined(NO_TLS_DH) /* SHOULD NOT negotiate cipher suites based on ephemeral * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*" * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */ From ced54cf9bfb39d05f14efc272df43c7d5b14fba0 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Mon, 3 Apr 2023 18:24:01 +0200 Subject: [PATCH 083/391] Tabs -> spaces --- configure.ac | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/configure.ac b/configure.ac index 3060536dda0..a8d6b805301 100644 --- a/configure.ac +++ b/configure.ac @@ -186,15 +186,15 @@ AC_ARG_ENABLE([harden-tls], if test "x$ENABLED_HARDEN_TLS" != "xno" then - if test "x$ENABLED_HARDEN_TLS" == "xyes" || test "x$ENABLED_HARDEN_TLS" == "x112" - then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS=112" - elif test "x$ENABLED_HARDEN_TLS" == "x128" - then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS=128" + if test "x$ENABLED_HARDEN_TLS" == "xyes" || test "x$ENABLED_HARDEN_TLS" == "x112" + then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS=112" + elif test "x$ENABLED_HARDEN_TLS" == "x128" + then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS=128" else - AC_MSG_ERROR([Invalid value for --enable-harden-tls]) - fi + AC_MSG_ERROR([Invalid value for --enable-harden-tls]) + fi AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_EXTRA_ALERTS -DWOLFSSL_CHECK_ALERT_ON_ERR" fi From c00936e056947f5d077840c649f951ed3db9bef8 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Tue, 4 Apr 2023 16:59:28 +0200 Subject: [PATCH 084/391] Add missing semicolon --- doc/dox_comments/header_files/ssl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/dox_comments/header_files/ssl.h b/doc/dox_comments/header_files/ssl.h index bba56809ad5..6a06cb82e44 100644 --- a/doc/dox_comments/header_files/ssl.h +++ b/doc/dox_comments/header_files/ssl.h @@ -1853,7 +1853,7 @@ int wolfSSL_set_fd(WOLFSSL* ssl, int fd); \sa wolfSSL_SetIOWriteCtx \sa wolfDTLS_SetChGoodCb */ -int wolfSSL_set_dtls_fd_connected(WOLFSSL* ssl, int fd) +int wolfSSL_set_dtls_fd_connected(WOLFSSL* ssl, int fd); /*! \ingroup Setup From 7c53e0c23efcf670be632e0df169957b36d79614 Mon Sep 17 00:00:00 2001 From: Kareem Date: Fri, 31 Mar 2023 17:33:33 -0700 Subject: [PATCH 085/391] Micrium: Add missing XATOI/XSTRTOK definitions, update XMEMMOVE function. --- wolfssl/wolfcrypt/settings.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 7afb8d82179..77f44b816cc 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1582,6 +1582,14 @@ extern void uITRON4_free(void *p) ; #define XSTRNCAT(pstr_dest, pstr_cat, len_max) \ ((CPU_CHAR *)Str_Cat_N((CPU_CHAR *)(pstr_dest), \ (const CPU_CHAR *)(pstr_cat),(CPU_SIZE_T)(len_max))) + #ifndef XATOI /* if custom XATOI is not already defined */ + #define XATOI(s) atoi((s)) + #endif + #if defined(USE_WOLF_STRTOK) + #define XSTRTOK(s1, d, ptr) wc_strtok((s1), (d), (ptr)) + #else + #define XSTRTOK(s1, d, ptr) strtok_r((s1), (d), (ptr)) + #endif #define XMEMSET(pmem, data_val, size) \ ((void)Mem_Set((void *)(pmem), \ (CPU_INT08U) (data_val), \ @@ -1607,7 +1615,8 @@ extern void uITRON4_free(void *p) ; #define XSNPRINTF snprintf #endif - #define XMEMMOVE XMEMCPY + #define XMEMMOVE(pdest, psrc, size) ((void)Mem_Move((void *)(pdest), \ + (void *)(psrc), (CPU_SIZE_T)(size))) #if (OS_CFG_MUTEX_EN == DEF_DISABLED) #define SINGLE_THREADED From 9eeec93426b82480ec996390af75622f5a48ef31 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 20 Feb 2023 12:55:57 -0800 Subject: [PATCH 086/391] IMX6Q CAAM Port --- IDE/QNX/CAAM-DRIVER/.cproject | 529 +++++++++++++++ IDE/QNX/CAAM-DRIVER/.project | 43 ++ IDE/QNX/CAAM-DRIVER/Makefile | 62 +- IDE/QNX/README.md | 13 +- IDE/QNX/include.am | 11 + IDE/QNX/testwolfcrypt/.cproject | 650 ++++++++++++++++++ IDE/QNX/testwolfcrypt/.project | 33 + IDE/QNX/testwolfcrypt/Makefile | 74 +++ IDE/QNX/wolfssl/.cproject | 687 ++++++++++++++++++++ IDE/QNX/wolfssl/.project | 38 ++ IDE/QNX/wolfssl/Makefile | 74 +++ IDE/QNX/wolfssl/user_settings.h | 137 ++++ configure.ac | 61 +- wolfcrypt/benchmark/benchmark.c | 45 +- wolfcrypt/benchmark/benchmark.h | 2 +- wolfcrypt/src/port/caam/caam_driver.c | 57 +- wolfcrypt/src/port/caam/caam_qnx.c | 12 +- wolfcrypt/src/port/caam/wolfcaam_aes.c | 10 +- wolfcrypt/src/port/caam/wolfcaam_cmac.c | 10 +- wolfcrypt/src/port/caam/wolfcaam_ecdsa.c | 8 +- wolfcrypt/src/port/caam/wolfcaam_hash.c | 84 +-- wolfcrypt/src/port/caam/wolfcaam_init.c | 27 +- wolfcrypt/src/port/caam/wolfcaam_qnx.c | 2 + wolfcrypt/src/random.c | 4 +- wolfcrypt/src/wc_port.c | 12 +- wolfcrypt/test/test.c | 2 +- wolfssl/wolfcrypt/port/caam/caam_driver.h | 25 + wolfssl/wolfcrypt/port/caam/caam_qnx.h | 12 - wolfssl/wolfcrypt/port/caam/wolfcaam_hash.h | 3 + wolfssl/wolfcrypt/port/caam/wolfcaam_qnx.h | 6 +- wolfssl/wolfcrypt/settings.h | 87 ++- 31 files changed, 2625 insertions(+), 195 deletions(-) create mode 100644 IDE/QNX/CAAM-DRIVER/.cproject create mode 100644 IDE/QNX/CAAM-DRIVER/.project create mode 100644 IDE/QNX/testwolfcrypt/.cproject create mode 100644 IDE/QNX/testwolfcrypt/.project create mode 100644 IDE/QNX/testwolfcrypt/Makefile create mode 100644 IDE/QNX/wolfssl/.cproject create mode 100644 IDE/QNX/wolfssl/.project create mode 100644 IDE/QNX/wolfssl/Makefile create mode 100644 IDE/QNX/wolfssl/user_settings.h diff --git a/IDE/QNX/CAAM-DRIVER/.cproject b/IDE/QNX/CAAM-DRIVER/.cproject new file mode 100644 index 00000000000..b38dcc000b8 --- /dev/null +++ b/IDE/QNX/CAAM-DRIVER/.cproject @@ -0,0 +1,529 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/IDE/QNX/CAAM-DRIVER/.project b/IDE/QNX/CAAM-DRIVER/.project new file mode 100644 index 00000000000..190891d603e --- /dev/null +++ b/IDE/QNX/CAAM-DRIVER/.project @@ -0,0 +1,43 @@ + + + CAAM-DRIVER + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + + src/caam_driver.c + 1 + $%7BPARENT-3-PROJECT_LOC%7D/wolfcrypt/src/port/caam/caam_driver.c + + + src/caam_error.c + 1 + $%7BPARENT-3-PROJECT_LOC%7D/wolfcrypt/src/port/caam/caam_error.c + + + src/caam_qnx.c + 1 + $%7BPARENT-3-PROJECT_LOC%7D/wolfcrypt/src/port/caam/caam_qnx.c + + + diff --git a/IDE/QNX/CAAM-DRIVER/Makefile b/IDE/QNX/CAAM-DRIVER/Makefile index e483355f029..935a91c76b2 100644 --- a/IDE/QNX/CAAM-DRIVER/Makefile +++ b/IDE/QNX/CAAM-DRIVER/Makefile @@ -1,37 +1,73 @@ ARTIFACT = wolfCrypt #Build architecture/variant string, possible values: x86, armv7le, etc... -PLATFORM = armv7le -OUTPUT_DIR = build -TARGET = $(ARTIFACT) +PLATFORM ?= armv7le + +#Build profile, possible values: release, debug, profile, coverage +BUILD_PROFILE ?= debug + +CONFIG_NAME ?= $(PLATFORM)-$(BUILD_PROFILE) +OUTPUT_DIR = build/$(CONFIG_NAME) +TARGET = $(OUTPUT_DIR)/$(ARTIFACT) + +#Compiler definitions CC ?= qcc -Vgcc_nto$(PLATFORM) -CXX = qcc -lang-c++ -Vgcc_nto$(PLATFORM) +CXX ?= q++ -Vgcc_nto$(PLATFORM)_cxx LD = $(CC) INCLUDES += -I../../../ -I../../../wolfssl/wolfcrypt/port/caam/ CCFLAGS += -O2 -Wall # For debugging print outs build with WOLFSSL_CAAM_PRINT defined -#CCFLAGS += -DWOLFSSL_CAAM_PRINT -O2 -Wall +# CCFLAGS += -DWOLFSSL_CAAM_PRINT -O2 -Wall + +# Setting base address for hardware + +# For IMX6UL devices +# CCFLAGS += -DWOLFSSL_CAAM_IMX6UL -SRCS = \ - ../../../wolfcrypt/src/port/caam/caam_driver.c \ - ../../../wolfcrypt/src/port/caam/caam_error.c \ - ../../../wolfcrypt/src/port/caam/caam_qnx.c \ +# For IMX6Q devices +CCFLAGS += -DWOLFSSL_CAAM_IMX6Q +#Compiler flags for build profiles +CCFLAGS_release += -O2 +CCFLAGS_debug += -g -O0 -fno-builtin +CCFLAGS_coverage += -g -O0 -ftest-coverage -fprofile-arcs -nopipe -Wc,-auxbase-strip,$@ +LDFLAGS_coverage += -ftest-coverage -fprofile-arcs +CCFLAGS_profile += -g -O0 -finstrument-functions +LIBS_profile += -lprofilingS + +#Generic compiler flags (which include build type flags) +CCFLAGS_all += -Wall -fmessage-length=0 +CCFLAGS_all += $(CCFLAGS_$(BUILD_PROFILE)) +LDFLAGS_all += $(LDFLAGS_$(BUILD_PROFILE)) +LIBS_all += $(LIBS_$(BUILD_PROFILE)) +DEPS = -Wp,-MMD,$(OUTPUT_DIR)/$(notdir $(@:%.o=%.d)),-MT,$(OUTPUT_DIR)/$(notdir $@) + +SRCS = ../../../wolfcrypt/src/port/caam/caam_error.c \ + ../../../wolfcrypt/src/port/caam/caam_driver.c \ + ../../../wolfcrypt/src/port/caam/caam_qnx.c + +#Object files list OBJS = $(addprefix $(OUTPUT_DIR)/,$(addsuffix .o, $(basename $(SRCS)))) +#Compiling rule $(OUTPUT_DIR)/%.o: %.c - @mkdir -p $(dir $@) - $(CC) -c -o $@ $(INCLUDES) $(CCFLAGS) $< + @mkdir -p $(dir $(OUTPUT_DIR)/$(notdir $@)) + $(CC) -c $(DEPS) -o $(OUTPUT_DIR)/$(notdir $@) $(INCLUDES) $(CCFLAGS_all) $(CCFLAGS) $< +#Linking rule $(TARGET):$(OBJS) - $(LD) -o $(TARGET) $(LDFLAGS) $(OBJS) $(LIBS) + $(LD) -o $(TARGET) $(LDFLAGS_all) $(LDFLAGS) $(foreach f, $(OBJS), $(OUTPUT_DIR)/$(notdir $(f))) $(LIBS_all) $(LIBS) +#Rules section for default compilation and linking all: $(TARGET) clean: - rm -rf $(OUTPUT_DIR) $(ARTIFACT) + rm -fr $(OUTPUT_DIR) rebuild: clean all + +#Inclusion of dependencies (object files to source and includes) +-include $(OBJS:%.o=%.d) diff --git a/IDE/QNX/README.md b/IDE/QNX/README.md index 800f54cdc0c..2d6694c831b 100644 --- a/IDE/QNX/README.md +++ b/IDE/QNX/README.md @@ -2,6 +2,8 @@ This directory contains; - A Makefile for creating the QNX CAAM driver located at IDE/QNX/CAAM-DRIVER/Makefile +- A Makefile for creating wolfSSL library located at IDE/QNX/wolfssl/Makefile +- A Makefile for creating wolfCrypt unit tests located at IDE/QNX/testwolfcrypt/Makefile - An example TLS server located at IDE/QNX/example-server/ - An example client located at IDE/QNX/example-client - An example CMAC use located at IDE/QNX/example-cmac @@ -15,14 +17,21 @@ source ~/qnx700/qnxsdp-env.sh make ``` -Once the wolfSSL library has been built cd to IDE/QNX/CAAM-DRIVER and run "make". This will produce the wolfCrypt resource manager. It should be started on the device with root permisions. Once wolfCrypt is running on the device with root permisions then any user with access to open a connection to wolfCrypt can make use of the driver. +Once the wolfSSL library has been built cd to IDE/QNX/CAAM-DRIVER and run "make". This will produce the wolfCrypt resource manager. It should be started on the device with root permisions. Once wolfCrypt is running on the device with root permisions then any user with access to open a connection to /dev/wolfCrypt can make use of the driver. +### Momentics +To build in momentics IDE: + +- Switch the workspace to be wolfssl/IDE/QNX/ +- Import the three projects (File->Import->General->Existing Projects into Workspace, in "Select root directory" browse to the directory wolfssl/IDE/QNX/ and select the projects then click "Finish"). +- Build ### Supported Operations By CAAM Driver - ECC black key creation - ECC black key sign / verify / ecdh - Black blob creation and open -- Red blob creation and open +- Red/Black blob creation and open - Cover keys (turn to black key) - CMAC with and without black keys - TRNG used by default to seed Hash DRBG +- AES operations (CTR) diff --git a/IDE/QNX/include.am b/IDE/QNX/include.am index 3236ecd5e29..16dd7e160a2 100644 --- a/IDE/QNX/include.am +++ b/IDE/QNX/include.am @@ -3,7 +3,18 @@ # All paths should be given relative to the root EXTRA_DIST+= IDE/QNX/README.md +EXTRA_DIST+= IDE/QNX/CAAM-DRIVER/.cproject +EXTRA_DIST+= IDE/QNX/CAAM-DRIVER/.project EXTRA_DIST+= IDE/QNX/CAAM-DRIVER/Makefile +EXTRA_DIST+= IDE/QNX/wolfssl/.cproject +EXTRA_DIST+= IDE/QNX/wolfssl/.project +EXTRA_DIST+= IDE/QNX/wolfssl/Makefile +EXTRA_DIST+= IDE/QNX/wolfssl/user_settings.h +EXTRA_DIST+= IDE/QNX/testwolfcrypt/.cproject +EXTRA_DIST+= IDE/QNX/testwolfcrypt/.project +EXTRA_DIST+= IDE/QNX/testwolfcrypt/Makefile + + EXTRA_DIST+= IDE/QNX/example-server/Makefile EXTRA_DIST+= IDE/QNX/example-server/server-tls.c EXTRA_DIST+= IDE/QNX/example-client/Makefile diff --git a/IDE/QNX/testwolfcrypt/.cproject b/IDE/QNX/testwolfcrypt/.cproject new file mode 100644 index 00000000000..e8db384051e --- /dev/null +++ b/IDE/QNX/testwolfcrypt/.cproject @@ -0,0 +1,650 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/IDE/QNX/testwolfcrypt/.project b/IDE/QNX/testwolfcrypt/.project new file mode 100644 index 00000000000..544c652eed6 --- /dev/null +++ b/IDE/QNX/testwolfcrypt/.project @@ -0,0 +1,33 @@ + + + testwolfcrypt + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + + src/test.c + 1 + $%7BPARENT-3-PROJECT_LOC%7D/wolfcrypt/test/test.c + + + diff --git a/IDE/QNX/testwolfcrypt/Makefile b/IDE/QNX/testwolfcrypt/Makefile new file mode 100644 index 00000000000..0afc45f50e1 --- /dev/null +++ b/IDE/QNX/testwolfcrypt/Makefile @@ -0,0 +1,74 @@ +ARTIFACT = testwolfcrypt + +#Build architecture/variant string, possible values: x86, armv7le, etc... +PLATFORM ?= armv7le + +#Build profile, possible values: release, debug, profile, coverage +BUILD_PROFILE ?= debug + +CONFIG_NAME ?= $(PLATFORM)-$(BUILD_PROFILE) +OUTPUT_DIR = build/$(CONFIG_NAME) +TARGET = $(OUTPUT_DIR)/$(ARTIFACT) + +#Compiler definitions + +CC = qcc -Vgcc_nto$(PLATFORM) +CXX = q++ -Vgcc_nto$(PLATFORM)_cxx +LD = $(CC) + +#User defined include/preprocessor flags and libraries + +INCLUDES += -I../wolfssl +INCLUDES += -I../../.. + +#LIBS += -L/path/to/my/lib/$(PLATFORM)/usr/lib -lmylib +LIBS += -L../wolfssl/$(OUTPUT_DIR) -lwolfssl -lm -lsocket + +#Compiler flags for build profiles +CCFLAGS_release += -O2 +CCFLAGS_debug += -g -O0 -fno-builtin +CCFLAGS_coverage += -g -O0 -ftest-coverage -fprofile-arcs -nopipe -Wc,-auxbase-strip,$@ +LDFLAGS_coverage += -ftest-coverage -fprofile-arcs +CCFLAGS_profile += -g -O0 -finstrument-functions +LIBS_profile += -lprofilingS + +#Generic compiler flags (which include build type flags) +CCFLAGS_all += -DWOLFSSL_USER_SETTINGS -Wall -fmessage-length=0 +CCFLAGS_all += $(CCFLAGS_$(BUILD_PROFILE)) +#Shared library has to be compiled with -fPIC +#CCFLAGS_all += -fPIC +LDFLAGS_all += $(LDFLAGS_$(BUILD_PROFILE)) +LIBS_all += $(LIBS_$(BUILD_PROFILE)) +DEPS = -Wp,-MMD,$(OUTPUT_DIR)/$(notdir $(@:%.o=%.d)),-MT,$(OUTPUT_DIR)/$(notdir $@) + +#Macro to expand files recursively: parameters $1 - directory, $2 - extension, i.e. cpp +rwildcard = $(wildcard $(addprefix $1/*.,$2)) $(foreach d,$(wildcard $1/*),$(call rwildcard,$d,$2)) + +#Source list +SRCS = $(call rwildcard, src, c) +SRCS += ../../../wolfcrypt/test/test.c + +#Object files list +OBJS = $(addprefix $(OUTPUT_DIR)/,$(addsuffix .o, $(basename $(SRCS)))) + +#Compiling rule +$(OUTPUT_DIR)/%.o: %.c + @mkdir -p $(dir $(OUTPUT_DIR)/$(notdir $@)) + $(CC) -c $(DEPS) -o $(OUTPUT_DIR)/$(notdir $@) $(INCLUDES) $(CCFLAGS_all) $(CCFLAGS) $< + + +#Linking rule +$(TARGET):$(OBJS) + $(LD) -o $(TARGET) $(LDFLAGS_all) $(LDFLAGS) $(foreach f, $(OBJS), $(OUTPUT_DIR)/$(notdir $(f))) $(LIBS_all) $(LIBS) + + +#Rules section for default compilation and linking +all: $(TARGET) + +clean: + rm -fr $(OUTPUT_DIR) + +rebuild: clean all + +#Inclusion of dependencies (object files to source and includes) +-include $(OBJS:%.o=%.d) diff --git a/IDE/QNX/wolfssl/.cproject b/IDE/QNX/wolfssl/.cproject new file mode 100644 index 00000000000..9d624640e62 --- /dev/null +++ b/IDE/QNX/wolfssl/.cproject @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/IDE/QNX/wolfssl/.project b/IDE/QNX/wolfssl/.project new file mode 100644 index 00000000000..04225c0751c --- /dev/null +++ b/IDE/QNX/wolfssl/.project @@ -0,0 +1,38 @@ + + + wolfssl + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + + src/src + 2 + $%7BPARENT-3-PROJECT_LOC%7D/src + + + src/wolfcrypt + 2 + $%7BPARENT-3-PROJECT_LOC%7D/wolfcrypt/src + + + diff --git a/IDE/QNX/wolfssl/Makefile b/IDE/QNX/wolfssl/Makefile new file mode 100644 index 00000000000..b104d691776 --- /dev/null +++ b/IDE/QNX/wolfssl/Makefile @@ -0,0 +1,74 @@ +ARTIFACT = libwolfssl.so + +#Build architecture/variant string, possible values: x86, armv7le, etc... +PLATFORM ?= armv7le + +#Build profile, possible values: release, debug, profile, coverage +BUILD_PROFILE ?= debug + +CONFIG_NAME ?= $(PLATFORM)-$(BUILD_PROFILE) +OUTPUT_DIR = build/$(CONFIG_NAME) +TARGET = $(OUTPUT_DIR)/$(ARTIFACT) + +#Compiler definitions + +CC = qcc -Vgcc_nto$(PLATFORM) +CXX = q++ -Vgcc_nto$(PLATFORM)_cxx +LD = $(CC) + +#User defined include/preprocessor flags and libraries + +INCLUDES += -I../../.. +INCLUDES += -I./ + +#Compiler flags for build profiles +CCFLAGS_release += -O2 +CCFLAGS_debug += -g -O0 -fno-builtin +CCFLAGS_coverage += -g -O0 -ftest-coverage -fprofile-arcs -nopipe -Wc,-auxbase-strip,$@ +LDFLAGS_coverage += -ftest-coverage -fprofile-arcs +CCFLAGS_profile += -g -O0 -finstrument-functions +LIBS_profile += -lprofilingS + +#Generic compiler flags (which include build type flags) +CCFLAGS_all += -DWOLFSSL_USER_SETTINGS -Wall -fmessage-length=0 +CCFLAGS_all += $(CCFLAGS_$(BUILD_PROFILE)) +#Shared library has to be compiled with -fPIC +CCFLAGS_all += -fPIC +LDFLAGS_all += $(LDFLAGS_$(BUILD_PROFILE)) +LIBS_all += $(LIBS_$(BUILD_PROFILE)) +DEPS = -Wp,-MMD,$(OUTPUT_DIR)/$(notdir $(@:%.o=%.d)),-MT,$(OUTPUT_DIR)/$(notdir $@) + +#Macro to expand files recursively: parameters $1 - directory, $2 - extension, i.e. cpp +rwildcard = $(wildcard $(addprefix $1/*.,$2)) $(foreach d,$(wildcard $1/*),$(call rwildcard,$d,$2)) + +#Source list +SRCS = $(call rwildcard, src, c) +SRCS += $(call rwildcard, ../../../src, c) +SRCS += $(wildcard $(addprefix ../../../wolfcrypt/src/*.,c)) +SRCS += $(wildcard $(addprefix ../../../wolfcrypt/src/port/caam/wolfcaam_*.,c)) + + +#Object files list +OBJS = $(addprefix $(OUTPUT_DIR)/,$(addsuffix .o, $(basename $(SRCS)))) + +#Compiling rule +$(OUTPUT_DIR)/%.o: %.c + @mkdir -p $(dir $(OUTPUT_DIR)/$(notdir $@)) + $(CC) -c $(DEPS) -o $(OUTPUT_DIR)/$(notdir $@) $(INCLUDES) $(CCFLAGS_all) $(CCFLAGS) $< + + +#Linking rule +$(TARGET):$(OBJS) + $(LD) -shared -o $(TARGET) $(LDFLAGS_all) $(LDFLAGS) $(foreach f, $(OBJS), $(OUTPUT_DIR)/$(notdir $(f))) $(LIBS_all) $(LIBS) + + +#Rules section for default compilation and linking +all: $(TARGET) + +clean: + rm -fr $(OUTPUT_DIR) + +rebuild: clean all + +#Inclusion of dependencies (object files to source and includes) +-include $(OBJS:%.o=%.d) diff --git a/IDE/QNX/wolfssl/user_settings.h b/IDE/QNX/wolfssl/user_settings.h new file mode 100644 index 00000000000..3814ecb873f --- /dev/null +++ b/IDE/QNX/wolfssl/user_settings.h @@ -0,0 +1,137 @@ +#ifndef USER_SETTINGS_H +#define USER_SETTINGS_H + +#undef WOLFSSL_SP +#define WOLFSSL_SP + +#undef WOLFSSL_SP_MATH_ALL +#define WOLFSSL_SP_MATH_ALL + +#undef WOLFSSL_SP_ARM32 +#define WOLFSSL_SP_ARM32 + +#undef ECC_TIMING_RESISTANT +#define ECC_TIMING_RESISTANT + +#undef WC_RSA_BLINDING +#define WC_RSA_BLINDING + +#define SIZE_OF_LONG_LONG 8 + +#define NO_MAIN_DRIVER +#define NO_FILESYSTEM + +/* Build CAAM support */ +#undef WOLFSSL_CAAM +#define WOLFSSL_CAAM + +#undef WOLFSSL_QNX_CAAM +#define WOLFSSL_QNX_CAAM + +#undef WOLFSSL_IMX6Q_CAAM +#define WOLFSSL_IMX6Q_CAAM + +#undef WOLFSSL_USE_ALIGN +#define WOLFSSL_USE_ALIGN + +/* Algorithms Enabled */ +#undef HAVE_AESCCM +#define HAVE_AESCCM + +#undef WOLFSSL_SHA512 +#define WOLFSSL_SHA512 + +#undef WOLFSSL_SHA384 +#define WOLFSSL_SHA384 + +#undef HAVE_HKDF +#define HAVE_HKDF + +#undef NO_DSA +#define NO_DSA + +#undef HAVE_ECC +#define HAVE_ECC + +#undef NO_RC4 +#define NO_RC4 + +#undef NO_PSK +#define NO_PSK + +#undef NO_MD4 +#define NO_MD4 + +#undef TFM_ECC256 +#define TFM_ECC256 + +#undef ECC_SHAMIR +#define ECC_SHAMIR + +#undef WC_RSA_PSS +#define WC_RSA_PSS + +#undef WOLFSSL_PSS_LONG_SALT +#define WOLFSSL_PSS_LONG_SALT + +#undef WOLFSSL_ASN_TEMPLATE +#define WOLFSSL_ASN_TEMPLATE + +#undef WOLFSSL_NO_SHAKE128 +#define WOLFSSL_NO_SHAKE128 + +#undef WOLFSSL_NO_SHAKE256 +#define WOLFSSL_NO_SHAKE256 + +#undef HAVE_POLY1305 +#define HAVE_POLY1305 + +#undef HAVE_CHACHA +#define HAVE_CHACHA + +#undef HAVE_HASHDRBG +#define HAVE_HASHDRBG + +#undef NO_FILESYSTEM +#define NO_FILESYSTEM + +#undef HAVE_TLS_EXTENSIONS +#define HAVE_TLS_EXTENSIONS + +#undef HAVE_SUPPORTED_CURVES +#define HAVE_SUPPORTED_CURVES + +#undef HAVE_FFDHE_2048 +#define HAVE_FFDHE_2048 + +#undef HAVE_SUPPORTED_CURVES +#define HAVE_SUPPORTED_CURVES + +#undef WC_NO_ASYNC_THREADING +#define WC_NO_ASYNC_THREADING + +#undef WOLF_CRYPTO_CB +#define WOLF_CRYPTO_CB + +#undef HAVE_DH_DEFAULT_PARAMS +#define HAVE_DH_DEFAULT_PARAMS + +#undef WOLFSSL_AES_COUNTER +#define WOLFSSL_AES_COUNTER + +#undef WOLFSSL_AES_DIRECT +#define WOLFSSL_AES_DIRECT + +#undef NO_DES3 +#define NO_DES3 + +#undef GCM_TABLE_4BIT +#define GCM_TABLE_4BIT + +#undef HAVE_AESGCM +#define HAVE_AESGCM + +#undef HAVE_TLS_EXTENSIONS +#define HAVE_TLS_EXTENSIONS + +#endif diff --git a/configure.ac b/configure.ac index a8d6b805301..7318ec8880c 100644 --- a/configure.ac +++ b/configure.ac @@ -2364,35 +2364,40 @@ AC_ARG_ENABLE([caam], [ ENABLED_CAAM=$enableval ], [ ENABLED_CAAM=no ] ) -if test "$ENABLED_CAAM" = "yes" -then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM -DWOLFSSL_IMX6_CAAM" -fi -if test "$ENABLED_CAAM" = "qnx" +if test "$ENABLED_CAAM" != "no" then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM -DWOLFSSL_IMX6_CAAM -DWOLFSSL_QNX_CAAM" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_ECC" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_CMAC" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_CIPHER" -fi + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM" -if test "$ENABLED_CAAM" = "seco" -then - SECO_DIR=$trylibsecodir - AM_CPPFLAGS="$AM_CPPFLAGS -I$SECO_DIR/include" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM -DWOLFSSL_SECO_CAAM -DWOLFSSL_HASH_KEEP" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_ECC" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_CMAC" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_CIPHER" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_HMAC" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_HASH" - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM_CURVE25519" + for v in `echo $ENABLED_CAAM | tr "," " "` + do + case $v in + qnx) + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_QNX_CAAM" + ENABLED_CAAM_QNX="yes" + ;; - AC_CHECK_LIB([hsm_lib],[hsm_open_session]) - AC_CHECK_LIB([seco_nvm_manager],[seco_nvm_manager]) - LIB_STATIC_ADD="$LIB_STATIC_ADD $SECO_DIR/lib/hsm_lib.a $SECO_DIR/lib/seco_nvm_manager.a" - LIB_ADD="$LIB_ADD -lz" + imx6q) + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_IMX6Q_CAAM" + ;; + + imx6ul) + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_IMX6UL_CAAM" + ;; + + seco) + SECO_DIR=$trylibsecodir + AM_CPPFLAGS="$AM_CPPFLAGS -I$SECO_DIR/include" + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CAAM -DWOLFSSL_SECO_CAAM" + + AC_CHECK_LIB([hsm_lib],[hsm_open_session]) + AC_CHECK_LIB([seco_nvm_manager],[seco_nvm_manager]) + LIB_STATIC_ADD="$LIB_STATIC_ADD $SECO_DIR/lib/hsm_lib.a $SECO_DIR/lib/seco_nvm_manager.a" + LIB_ADD="$LIB_ADD -lz" + ;; + + esac + done fi # INTEL AES-NI @@ -7402,7 +7407,7 @@ AC_ARG_ENABLE([cryptocb], [ ENABLED_CRYPTOCB=no ] ) -if test "x$ENABLED_PKCS11" = "xyes" || test "x$ENABLED_WOLFTPM" = "xyes" || test "$ENABLED_CAAM" = "qnx" || test "$ENABLED_CAAM" = "seco" +if test "x$ENABLED_PKCS11" = "xyes" || test "x$ENABLED_WOLFTPM" = "xyes" || test "$ENABLED_CAAM" != "no" then ENABLED_CRYPTOCB=yes fi @@ -8545,12 +8550,12 @@ AM_CONDITIONAL([BUILD_DES3],[test "x$ENABLED_DES3" = "xyes" || test "x$ENABLED_U AM_CONDITIONAL([BUILD_PKCS7],[test "x$ENABLED_PKCS7" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) AM_CONDITIONAL([BUILD_SMIME],[test "x$ENABLED_SMIME" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) AM_CONDITIONAL([BUILD_HASHFLAGS],[test "x$ENABLED_HASHFLAGS" = "xyes"]) -AM_CONDITIONAL([BUILD_CAAM],[test "x$ENABLED_CAAM" = "xyes" || test "x$ENABLED_CAAM" = "xqnx" || test "x$ENABLED_CAAM" = "xseco"]) AM_CONDITIONAL([BUILD_LINUXKM],[test "$ENABLED_LINUXKM" = "yes"]) AM_CONDITIONAL([BUILD_NO_LIBRARY],[test "$ENABLED_NO_LIBRARY" = "yes"]) AM_CONDITIONAL([BUILD_BENCHMARK],[test "$ENABLED_BENCHMARK" = "yes"]) AM_CONDITIONAL([BUILD_RC2],[test "x$ENABLED_RC2" = "xyes"]) -AM_CONDITIONAL([BUILD_QNXCAAM],[test "x$ENABLED_CAAM" = "xqnx"]) +AM_CONDITIONAL([BUILD_CAAM],[test "x$ENABLED_CAAM" != "xno"]) +AM_CONDITIONAL([BUILD_QNXCAAM],[test "x$ENABLED_CAAM_QNX" = "xyes"]) AM_CONDITIONAL([BUILD_IOTSAFE],[test "x$ENABLED_IOTSAFE" = "xyes"]) AM_CONDITIONAL([BUILD_IOTSAFE_HWRNG],[test "x$ENABLED_IOTSAFE_HWRNG" = "xyes"]) AM_CONDITIONAL([BUILD_SE050],[test "x$ENABLED_SE050" = "xyes"]) diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 0b31777b28c..c1a602f7784 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -1799,10 +1799,16 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, #ifdef HAVE_GET_CYCLES printf("\n\nSymmetric Ciphers:\n\n"); printf("Algorithm," + #ifdef BENCH_DEVID + "HW/SW," + #endif WOLFSSL_FIXED_UNITS_PER_SEC ",Cycles per byte,\n"); #else printf("\n\nSymmetric Ciphers:\n\n"); printf("Algorithm," + #ifdef BENCH_DEVID + "HW/SW," + #endif WOLFSSL_FIXED_UNITS_PER_SEC ", \n"); #endif #endif @@ -1857,10 +1863,13 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, bytes_processed, total, persec, total_cycles); #else (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu,%f,%f,", desc, - BENCH_ASYNC_GET_NAME(useDeviceID), + BENCH_DEVID_GET_NAME(useDeviceID), bytes_processed, total, persec); #endif #endif +#elif defined(BENCH_DEVID) + (void)XSNPRINTF(msg, sizeof(msg), "%s,%s,%f,", desc, + BENCH_DEVID_GET_NAME(useDeviceID), persec); #else (void)XSNPRINTF(msg, sizeof(msg), "%s,%f,", desc, persec); #endif @@ -1887,7 +1896,7 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, (void)XSNPRINTF(msg, sizeof(msg), "%-24s%s %5.0f %s %s %5.3f %s, %8.3f %s/s" ",", - desc, BENCH_ASYNC_GET_NAME(useDeviceID), blocks, blockType, + desc, BENCH_DEVID_GET_NAME(useDeviceID), blocks, blockType, word[0], total, word[1], persec, blockType); #endif /* HAVE_GET_CYCLES */ #else @@ -2027,7 +2036,7 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, (void)XSNPRINTF(msg, sizeof(msg), "%-6s %5d %8s%-2s %s %6d %s %5.3f %s, %s %5.3f ms," " %.3f %s\n", algo, strength, desc, - desc_extra, BENCH_ASYNC_GET_NAME(useDeviceID), + desc_extra, BENCH_DEVID_GET_NAME(useDeviceID), count, word[0], total, word[1], word[2], milliEach, opsSec, word[3]); #endif /* HAVE_GET_CYCLES */ @@ -2252,8 +2261,12 @@ static void* benchmarks_do(void* args) bench_aesofb(); #endif #ifdef WOLFSSL_AES_COUNTER - if (bench_all || (bench_cipher_algs & BENCH_AES_CTR)) - bench_aesctr(); + if (bench_all || (bench_cipher_algs & BENCH_AES_CTR)) { + bench_aesctr(0); + #ifdef BENCH_DEVID + bench_aesctr(1); + #endif + } #endif #ifdef HAVE_AESCCM if (bench_all || (bench_cipher_algs & BENCH_AES_CCM)) { @@ -3903,12 +3916,18 @@ void bench_aesxts(void) #ifdef WOLFSSL_AES_COUNTER static void bench_aesctr_internal(const byte* key, word32 keySz, - const byte* iv, const char* label) + const byte* iv, const char* label, + int useDeviceID) { Aes enc; double start; int i, count, ret = 0; + if ((ret = wc_AesInit(&enc, HEAP_HINT, + useDeviceID ? devId : INVALID_DEVID)) != 0) { + printf("wc_AesInit failed, ret = %d\n", ret); + } + wc_AesSetKeyDirect(&enc, key, keySz, iv, AES_ENCRYPTION); bench_stats_start(&count, &start); @@ -3922,19 +3941,21 @@ static void bench_aesctr_internal(const byte* key, word32 keySz, } count += i; } while (bench_stats_check(start)); - bench_stats_sym_finish(label, 0, count, bench_size, start, ret); + bench_stats_sym_finish(label, useDeviceID, count, bench_size, start, ret); + + wc_AesFree(&enc); } -void bench_aesctr(void) +void bench_aesctr(int useDeviceID) { #ifdef WOLFSSL_AES_128 - bench_aesctr_internal(bench_key, 16, bench_iv, "AES-128-CTR"); + bench_aesctr_internal(bench_key, 16, bench_iv, "AES-128-CTR", useDeviceID); #endif #ifdef WOLFSSL_AES_192 - bench_aesctr_internal(bench_key, 24, bench_iv, "AES-192-CTR"); + bench_aesctr_internal(bench_key, 24, bench_iv, "AES-192-CTR", useDeviceID); #endif #ifdef WOLFSSL_AES_256 - bench_aesctr_internal(bench_key, 32, bench_iv, "AES-256-CTR"); + bench_aesctr_internal(bench_key, 32, bench_iv, "AES-256-CTR", useDeviceID); #endif } #endif /* WOLFSSL_AES_COUNTER */ @@ -5873,7 +5894,7 @@ static void bench_cmac_helper(int keySz, const char* outMsg, int useDeviceID) } count += i; } while (bench_stats_check(start)); - bench_stats_sym_finish(outMsg, 0, count, bench_size, start, ret); + bench_stats_sym_finish(outMsg, useDeviceID, count, bench_size, start, ret); } void bench_cmac(int useDeviceID) diff --git a/wolfcrypt/benchmark/benchmark.h b/wolfcrypt/benchmark/benchmark.h index 1e859e1be21..3cc6aa8d501 100644 --- a/wolfcrypt/benchmark/benchmark.h +++ b/wolfcrypt/benchmark/benchmark.h @@ -55,7 +55,7 @@ void bench_gmac(void); void bench_aesccm(int useDeviceID); void bench_aesecb(int useDeviceID); void bench_aesxts(void); -void bench_aesctr(void); +void bench_aesctr(int useDeviceID); void bench_aescfb(void); void bench_aesofb(void); void bench_aessiv(void); diff --git a/wolfcrypt/src/port/caam/caam_driver.c b/wolfcrypt/src/port/caam/caam_driver.c index b78cbdf8127..dfdc3e99312 100644 --- a/wolfcrypt/src/port/caam/caam_driver.c +++ b/wolfcrypt/src/port/caam/caam_driver.c @@ -571,6 +571,8 @@ Error caamAddJob(DESCSTRUCT* desc) pt = (unsigned int*)caam.ring.VirtualDesc; #if defined(WOLFSSL_CAAM_PRINT) + printf("Number of input ring slots available is %d\n", + CAAM_READ(baseAddr + CAAM_IRSAR_JR)); printf("Doing Job :\n"); #endif for (i = 0; i < desc->idx; i = i + 1) { @@ -606,11 +608,6 @@ Error caamAddJob(DESCSTRUCT* desc) #endif } else { - #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT) - printf("SLOT = 0x%08X, IRJAR0 = 0x%08X\n", CAAM_READ(baseAddr + 0x0014), - CAAM_READ(baseAddr + CAAM_IRJAR0)); - printf("Number of job in done queue = 0x%08X\n", CAAM_READ(baseAddr+ 0x103C)); - #endif CAAM_UNLOCK_MUTEX(&caam.ring.jr_lock); return CAAM_WAITING; } @@ -1758,8 +1755,10 @@ static int SetupJobRing(struct JobRing* r) memset(r->VirtualDesc, 0, CAAM_DESC_MAX * CAAM_JOBRING_SIZE); #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT) - printf("Setting JOB IN 0x%08X\n", (unsigned int)caam.ring.JobIn); - printf("Setting JOB OUT 0x%08X\n", (unsigned int)caam.ring.JobOut); + printf("Setting JOB IN address 0x%08X, size %d\n", + (unsigned int)caam.ring.JobIn, CAAM_JOBRING_SIZE); + printf("Setting JOB OUT address 0x%08X, size %d\n", + (unsigned int)caam.ring.JobOut, CAAM_JOBRING_SIZE); printf("Setting DESC 0x%08X\n", (unsigned int)caam.ring.Desc); #endif @@ -1776,6 +1775,10 @@ static int SetupJobRing(struct JobRing* r) (CAAM_READ(r->BaseAddr + JRINTR_JR) != 0)) { unsigned int reg; + #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT) + printf("Job ring is busy, trying to flush it\n"); + #endif + /* JRCR job ring command register */ CAAM_WRITE(r->BaseAddr + JRCR_JR, 0x2); /* park it */ CAAM_WRITE(r->BaseAddr + JRCR_JR, 0x1); /* flush it */ @@ -1796,28 +1799,52 @@ int InitCAAM(void) Error ret; /* map to memory addresses needed for accessing CAAM */ +#if defined(WOLFSSL_CAAM_PRINT) + printf("Using CAAM_BASE 0x%04X\n", CAAM_BASE); +#endif ret = CAAM_SET_BASEADDR(&caam.baseAddr); if (ret != 0) { return ret; } +#if defined(WOLFSSL_CAAM_PRINT) + printf("Using base address : 0x%04X\n", caam.baseAddr); +#endif ret = SetupJobRing(&caam.ring); if (ret != 0) { WOLFSSL_MSG("Error initializing job ring"); INTERRUPT_Panic(); return ret; } +#if defined(WOLFSSL_CAAM_PRINT) + printf("Using base ring address : 0x%04X\n", caam.ring.BaseAddr); +#endif /* get CHA era */ caam.vrs = CAAM_READ(caam.ring.BaseAddr + CAAM_CHA_CCBVID) >> 24; - #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT) - printf("CAAM version = %04X\n", - CAAM_READ(caam.ring.BaseAddr + CAAM_VERSION_MS) & 0xFFFF); - printf("CAAM era = %d\n", caam.vrs); - printf("RNG revision number = %08X\n", - CAAM_READ(caam.ring.BaseAddr + CAAM_CRNR_LS)); - printSecureMemoryInfo(); - #endif +#if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT) + printf("CAAM version = %04X\n", + CAAM_READ(caam.ring.BaseAddr + CAAM_VERSION_MS) & 0xFFFF); + printf("CAAM era = %d\n", caam.vrs); + printf("RNG revision number = %08X\n", + CAAM_READ(caam.ring.BaseAddr + CAAM_CRNR_LS)); + printSecureMemoryInfo(); + + /* Check if CAAM supports AES-GCM */ + { + unsigned int chaVerLS = + CAAM_READ(caam.ring.BaseAddr + CAAM_CHA_VERSION_LS); + printf("\nCHA support\n"); + printf("CHA Version LS = %04X\n", chaVerLS); + if (!(chaVerLS & CAAM_AES_HIGH_PERFORMANCE)) { + printf("High Performance AES module not supported, NO AES-GCM/XTS\n"); + } + if (chaVerLS & CAAM_AES_LOW_POWER) { + printf("Low Power AES module found\n"); + } + printf("\n"); + } +#endif /* when on i.MX8 with SECO the SECO has control of this */ if (caam.vrs < 9) { diff --git a/wolfcrypt/src/port/caam/caam_qnx.c b/wolfcrypt/src/port/caam/caam_qnx.c index 3ce8e74bc2f..f2c73fa43c4 100644 --- a/wolfcrypt/src/port/caam/caam_qnx.c +++ b/wolfcrypt/src/port/caam/caam_qnx.c @@ -93,8 +93,8 @@ int CAAM_SET_BASEADDR(CAAM_ADDRESS* baseAddr) void* vaddr; /* address range for CAAM is CAAM_BASE plus 0x10000 */ - vaddr = mmap_device_io(0x0000FFFF, CAAM_BASE); - if (vaddr == (uintptr_t)MAP_FAILED) { + vaddr = (void*)mmap_device_io(0x0000FFFF, CAAM_BASE); + if (vaddr == MAP_FAILED) { WOLFSSL_MSG("Unable to map virtual memory"); return -1; } @@ -575,13 +575,15 @@ static int doAEAD(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], { int ret = EOK, i = 0; DESCSTRUCT desc; - CAAM_BUFFER tmp[6] = {0}; + CAAM_BUFFER tmp[6]; iov_t in_iovs[6], out_iovs[2]; int inIdx = 0, outIdx = 0, algo; unsigned char *key = NULL, *iv = NULL, *in = NULL, *out = NULL, *aad = NULL, *tag = NULL; int keySz, ivSz = 0, inSz, outSz, aadSz = 0, tagSz = 0; + memset(tmp, 0, sizeof(tmp)); + /* get key info */ keySz = args[1] & 0xFFFF; /* key size */ key = (unsigned char*)CAAM_ADR_MAP(0, keySz, 0); @@ -737,13 +739,15 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], { int ret = EOK, i = 0; DESCSTRUCT desc; - CAAM_BUFFER tmp[6] = {0}; + CAAM_BUFFER tmp[6]; iov_t in_iovs[6], out_iovs[2]; int inIdx = 0, outIdx = 0; int algo; unsigned char *key = NULL, *iv = NULL, *in = NULL, *out = NULL; int keySz, ivSz = 0, inSz, outSz; + memset(tmp, 0, sizeof(tmp)); + /* get key info */ keySz = args[1] & 0xFFFF; /* key size */ key = (unsigned char*)CAAM_ADR_MAP(0, keySz, 0); diff --git a/wolfcrypt/src/port/caam/wolfcaam_aes.c b/wolfcrypt/src/port/caam/wolfcaam_aes.c index 9f58a54bcc5..73b82426d2e 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_aes.c +++ b/wolfcrypt/src/port/caam/wolfcaam_aes.c @@ -39,6 +39,8 @@ #include #endif +#if (defined(HAVE_AESGCM) && defined(WOLFSSL_CAAM_AESGCM)) || \ + defined(HAVE_AESCCM) /* return 0 on success */ static int wc_CAAM_AesAeadCommon(Aes* aes, const byte* in, byte* out, word32 sz, const byte* nonce, word32 nonceSz, byte* authTag, word32 authTagSz, @@ -89,8 +91,9 @@ static int wc_CAAM_AesAeadCommon(Aes* aes, const byte* in, byte* out, word32 sz, /* authInSz must fit into a short (note that only 16 bits are ava in CAAM * for AAD size anyway) */ - arg[0] = ((authInSz & 0xFFFF) << 16) | dir; - arg[1] = ((nonceSz & 0xFF) << 24) | ((authTagSz & 0xFF) << 16) | keySz; + arg[0] = ((authInSz & 0xFFFF) << 16) | (dir & 0xFFFF); + arg[1] = ((nonceSz & 0xFF) << 24) | ((authTagSz & 0xFF) << 16) | + (keySz & 0xFFFF); arg[2] = sz; arg[3] = aes->blackKey; @@ -101,6 +104,7 @@ static int wc_CAAM_AesAeadCommon(Aes* aes, const byte* in, byte* out, word32 sz, return 0; } +#endif /* HAVE_AESGCM || HAVE_AESCCM */ #if defined(HAVE_AESCCM) @@ -227,6 +231,7 @@ int wc_CAAM_AesCcmDecrypt(Aes* aes, const byte* in, byte* out, word32 sz, #endif /* HAVE_AESCCM */ +#if defined(HAVE_AESGCM) && defined(WOLFSSL_CAAM_AESGCM) int wc_CAAM_AesGcmEncrypt(Aes* aes, const byte* in, byte* out, word32 sz, const byte* nonce, word32 nonceSz, byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) @@ -243,6 +248,7 @@ int wc_CAAM_AesGcmDecrypt(Aes* aes, const byte* in, byte* out, word32 sz, return wc_CAAM_AesAeadCommon(aes, in, out, sz, nonce, nonceSz, (byte*)authTag, authTagSz, authIn, authInSz, CAAM_DEC, CAAM_AESGCM); } +#endif static int wc_CAAM_AesCbcCtrCommon(Aes* aes, byte* out, const byte* in, diff --git a/wolfcrypt/src/port/caam/wolfcaam_cmac.c b/wolfcrypt/src/port/caam/wolfcaam_cmac.c index a06cad29767..4ce43994134 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_cmac.c +++ b/wolfcrypt/src/port/caam/wolfcaam_cmac.c @@ -25,7 +25,7 @@ #include -#if defined(WOLFSSL_CAAM) && defined(WOLFSSL_CMAC) +#if defined(WOLFSSL_CAAM) && defined(WOLFSSL_CMAC) && defined(WOLFSSL_CAAM_CMAC) #include #include @@ -93,7 +93,13 @@ int wc_CAAM_Cmac(Cmac* cmac, const byte* key, word32 keySz, const byte* in, /* first take care of any left overs */ if (cmac->bufferSz > 0) { - word32 add = min(sz, AES_BLOCK_SIZE - cmac->bufferSz); + word32 add; + + if (cmac->bufferSz > AES_BLOCK_SIZE) { + WOLFSSL_MSG("Error with CMAC buffer size"); + return -1; + } + add = min(sz, (int)(AES_BLOCK_SIZE - cmac->bufferSz)); XMEMCPY(&cmac->buffer[cmac->bufferSz], pt, add); cmac->bufferSz += add; diff --git a/wolfcrypt/src/port/caam/wolfcaam_ecdsa.c b/wolfcrypt/src/port/caam/wolfcaam_ecdsa.c index d6548176e6d..bf063e78066 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_ecdsa.c +++ b/wolfcrypt/src/port/caam/wolfcaam_ecdsa.c @@ -25,7 +25,7 @@ #include -#if defined(WOLFSSL_CAAM) && defined(HAVE_ECC) +#if defined(WOLFSSL_CAAM) && defined(HAVE_ECC) && defined(WOLFSSL_CAAM_ECC) #include #include @@ -286,7 +286,7 @@ int wc_CAAM_EccSign(const byte* in, int inlen, byte* out, word32* outlen, { const ecc_set_type* dp; word32 args[4] = {0}; - CAAM_BUFFER buf[9] = {0}; + CAAM_BUFFER buf[9]; int ret, keySz; word32 ecdsel = 0; byte r[MAX_ECC_BYTES] = {0}; @@ -402,7 +402,7 @@ static int wc_CAAM_EccVerify_ex(mp_int* r, mp_int *s, const byte* hash, { const ecc_set_type* dp; word32 args[4] = {0}; - CAAM_BUFFER buf[9] = {0}; + CAAM_BUFFER buf[9]; int ret; int keySz; word32 idx = 0; @@ -528,7 +528,7 @@ int wc_CAAM_Ecdh(ecc_key* private_key, ecc_key* public_key, byte* out, { const ecc_set_type* dp; word32 args[4] = {0}; - CAAM_BUFFER buf[9] = {0}; + CAAM_BUFFER buf[9]; int ret, keySz; word32 ecdsel = 0; /* ecc parameters in hardware */ word32 idx = 0; diff --git a/wolfcrypt/src/port/caam/wolfcaam_hash.c b/wolfcrypt/src/port/caam/wolfcaam_hash.c index 8b3c99ba108..d3155468f0b 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_hash.c +++ b/wolfcrypt/src/port/caam/wolfcaam_hash.c @@ -66,60 +66,29 @@ ****************************************************************************/ #ifndef WOLFSSL_HASH_KEEP -static int _InitSha(byte* ctx, word32 ctxSz, void* heap, int devId, - word32 type) -{ - CAAM_BUFFER buf[1]; - word32 arg[4]; - int ret, idx = 0; - - /* Set buffer for context */ - buf[idx].BufferType = DataBuffer | LastBuffer; - buf[idx].TheAddress = (CAAM_ADDRESS)ctx; - buf[idx].Length = ctxSz + WC_CAAM_CTXLEN; -#if defined(__INTEGRITY) || defined(INTEGRITY) - buf[idx].Transferred = 0; -#endif - idx++; - - arg[0] = CAAM_ALG_INIT; - arg[1] = ctxSz + WC_CAAM_CTXLEN; - arg[2] = (word32)devId; - - if ((ret = wc_caamAddAndWait(buf, idx, arg, type)) != 0) { - WOLFSSL_MSG("Error with CAAM SHA init"); - return ret; - } - - return 0; -} - - -static int _ShaUpdate(wc_Sha* sha, const byte* data, word32 len, word32 digestSz, - word32 type) +static int _ShaUpdate(byte* buffer, word32* buffLen, const byte* ctx, + const byte* data, word32 len, word32 digestSz, word32 type) { CAAM_BUFFER buf[2]; word32 arg[4]; - int ret, idx = 0; - byte* local; + int ret; - if (sha == NULL ||(data == NULL && len > 0)) { + if (buffer == NULL || ctx == NULL || (data == NULL && len > 0)) { return BAD_FUNC_ARG; } if (len == 0) return 0; /* nothing to do */ - local = (byte*)sha->buffer; /* check for filling out existing buffer */ - if (sha->buffLen > 0) { - word32 add = min(len, WC_CAAM_HASH_BLOCK - sha->buffLen); - XMEMCPY(&local[sha->buffLen], data, add); + if (*buffLen > 0) { + word32 add = min(len, WC_CAAM_HASH_BLOCK - *buffLen); + XMEMCPY(&buffer[*buffLen], data, add); - sha->buffLen += add; + *buffLen += add; data += add; len -= add; - if (sha->buffLen == WC_CAAM_HASH_BLOCK) { + if (*buffLen == WC_CAAM_HASH_BLOCK) { /* Set buffer for context */ buf[idx].BufferType = DataBuffer; buf[idx].TheAddress = (CAAM_ADDRESS)sha->ctx; @@ -132,7 +101,7 @@ static int _ShaUpdate(wc_Sha* sha, const byte* data, word32 len, word32 digestSz /* data to update with */ buf[idx].BufferType = DataBuffer | LastBuffer; buf[idx].TheAddress = (CAAM_ADDRESS)sha->buffer; - buf[idx].Length = sha->buffLen; + buf[idx].Length = *buffLen; #if defined(__INTEGRITY) || defined(INTEGRITY) buf[idx].Transferred = 0; #endif @@ -145,7 +114,7 @@ static int _ShaUpdate(wc_Sha* sha, const byte* data, word32 len, word32 digestSz WOLFSSL_MSG("Error with CAAM SHA update"); return ret; } - sha->buffLen = 0; /* cleared out buffer */ + *buffLen = 0; /* cleared out buffer */ } } @@ -187,9 +156,9 @@ static int _ShaUpdate(wc_Sha* sha, const byte* data, word32 len, word32 digestSz /* check for left overs */ if (len > 0) { - word32 add = min(len, WC_CAAM_HASH_BLOCK - sha->buffLen); - XMEMCPY(&local[sha->buffLen], data, add); - sha->buffLen += add; + word32 add = min(len, WC_CAAM_HASH_BLOCK - *buffLen); + XMEMCPY(&buffer[*buffLen], data, add); + *buffLen += add; } return 0; @@ -253,7 +222,8 @@ int wc_CAAM_ShaHash(wc_Sha* sha, const byte* in, word32 inSz, byte* digest) ret = _wc_Hash_Grow(&(sha->msg), &(sha->used), &(sha->len), in, inSz, sha->heap); #else - ret = _ShaUpdate(sha, in, inSz, SHA_DIGEST_SIZE, CAAM_SHA); + ret = _ShaUpdate((byte*)sha->buffer, &sha->buffLen, (byte*)sha->digest, + in, inSz, SHA_DIGEST_SIZE, CAAM_SHA); #endif } @@ -269,7 +239,7 @@ int wc_CAAM_ShaHash(wc_Sha* sha, const byte* in, word32 inSz, byte* digest) wc_InitSha_ex(sha, heap, devId); #else ret = _ShaFinal((byte*)sha->digest, SHA_DIGEST_SIZE, - sha->buffer, sha->bufferLen, digest, CAAM_SHA); + (byte*)sha->buffer, sha->buffLen, digest, CAAM_SHA); #endif } return ret; @@ -291,7 +261,8 @@ int wc_CAAM_Sha224Hash(wc_Sha224* sha224, const byte* in, word32 inSz, #ifdef WOLFSSL_HASH_KEEP ret = wc_Sha224_Grow(sha224, in, inSz); #else - ret = _ShaUpdate(sha224, data, len, SHA224_DIGEST_SIZE, CAAM_SHA224); + ret = _ShaUpdate(sha224->buffer, &sha224->bufferLen, + (byte*)sha224->digest, data, len, SHA224_DIGEST_SIZE, CAAM_SHA224); #endif } @@ -306,7 +277,7 @@ int wc_CAAM_Sha224Hash(wc_Sha224* sha224, const byte* in, word32 inSz, wc_InitSha224_ex(sha224, heap, devId); #else ret = _ShaFinal((byte*)sha224->digest, SHA224_DIGEST_SIZE, - sha224->buffer, sha224->bufferLen, digest, CAAM_SHA224); + (byte*)sha224->buffer, sha224->bufferLen, digest, CAAM_SHA224); #endif } return ret; @@ -328,7 +299,8 @@ int wc_CAAM_Sha256Hash(wc_Sha256* sha256, const byte* in, word32 inSz, #ifdef WOLFSSL_HASH_KEEP ret = wc_Sha256_Grow(sha256, in, inSz); #else - ret = _ShaUpdate(sha256, in, inSz, SHA256_DIGEST_SIZE, CAAM_SHA256); + ret = _ShaUpdate((byte*)sha256->buffer, &sha256->buffLen, + (byte*)sha256->digest, in, inSz, SHA256_DIGEST_SIZE, CAAM_SHA256); #endif } @@ -344,7 +316,7 @@ int wc_CAAM_Sha256Hash(wc_Sha256* sha256, const byte* in, word32 inSz, wc_InitSha256_ex(sha256, heap, devId); #else ret = _ShaFinal((byte*)sha256->digest, SHA256_DIGEST_SIZE, - sha256->buffer, sha256->bufferLen, digest, CAAM_SHA256); + (byte*)sha256->buffer, sha256->buffLen, digest, CAAM_SHA256); #endif } return ret; @@ -366,7 +338,8 @@ int wc_CAAM_Sha384Hash(wc_Sha384* sha384, const byte* in, word32 inSz, #ifdef WOLFSSL_HASH_KEEP ret = wc_Sha384_Grow(sha384, in, inSz); #else - ret = _ShaUpdate(sha384, data, len, SHA384_DIGEST_SIZE, CAAM_SHA384); + ret = _ShaUpdate((byte*)sha384->buffer, &sha384->buffLen, + (byte*)sha384->digest, in, inSz, SHA384_DIGEST_SIZE, CAAM_SHA384); #endif } @@ -381,7 +354,7 @@ int wc_CAAM_Sha384Hash(wc_Sha384* sha384, const byte* in, word32 inSz, wc_InitSha384_ex(sha384, heap, devId); #else ret = _ShaFinal((byte*)sha384->digest, SHA384_DIGEST_SIZE, - sha384->buffer, sha384->bufferLen, digest, CAAM_SHA384); + (byte*)sha384->buffer, sha384->buffLen, digest, CAAM_SHA384); #endif } return ret; @@ -404,7 +377,8 @@ int wc_CAAM_Sha512Hash(wc_Sha512* sha512, const byte* in, word32 inSz, #ifdef WOLFSSL_HASH_KEEP ret = wc_Sha512_Grow(sha512, in, inSz); #else - ret = _ShaUpdate(sha512, data, len, SHA512_DIGEST_SIZE, CAAM_SHA512); + ret = _ShaUpdate((byte*)sha512->buffer, &sha512->buffLen, + (byte*)sha512->digest, in, inSz, SHA512_DIGEST_SIZE, CAAM_SHA512); #endif } @@ -419,7 +393,7 @@ int wc_CAAM_Sha512Hash(wc_Sha512* sha512, const byte* in, word32 inSz, wc_InitSha512_ex(sha512, heap, devId); #else ret = _ShaFinal((byte*)sha512->digest, SHA512_DIGEST_SIZE, - sha512->buffer, sha512->bufferLen, digest, CAAM_SHA512); + (byte*)sha512->buffer, sha512->buffLen, digest, CAAM_SHA512); #endif } return ret; diff --git a/wolfcrypt/src/port/caam/wolfcaam_init.c b/wolfcrypt/src/port/caam/wolfcaam_init.c index a0b868dec36..d6e93cf5a2f 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_init.c +++ b/wolfcrypt/src/port/caam/wolfcaam_init.c @@ -34,14 +34,16 @@ */ #include -#if defined(WOLFSSL_IMX6_CAAM) || defined(WOLFSSL_IMX6_CAAM_RNG) || \ - defined(WOLFSSL_IMX6UL_CAAM) || defined(WOLFSSL_IMX6_CAAM_BLOB) || \ - defined(WOLFSSL_SECO_CAAM) || defined(WOLFSSL_IMXRT1170_CAAM) +#if defined(WOLFSSL_CAAM) #include #include #include +#ifdef DEBUG_WOLFSSL + #include +#endif + /* determine which porting header to include */ #if defined(__INTEGRITY) || defined(INTEGRITY) #ifndef WC_CAAM_PASSWORD @@ -80,6 +82,7 @@ static int wc_CAAM_router(int devId, wc_CryptoInfo* info, void* ctx) int ret = CRYPTOCB_UNAVAILABLE; (void)ctx; + (void)devId; switch (info->algo_type) { case WC_ALGO_TYPE_PK: switch (info->pk.type) { @@ -160,7 +163,7 @@ static int wc_CAAM_router(int devId, wc_CryptoInfo* info, void* ctx) break; case WC_ALGO_TYPE_CMAC: - #ifdef WOLFSSL_CAAM_CMAC + #if defined(WOLFSSL_CMAC) && defined(WOLFSSL_CAAM_CMAC) #ifdef WOLFSSL_SECO_CAAM if (devId != WOLFSSL_SECO_DEVID) break; @@ -180,7 +183,7 @@ static int wc_CAAM_router(int devId, wc_CryptoInfo* info, void* ctx) WOLFSSL_MSG("CMAC not compiled in"); ret = NOT_COMPILED_IN; #endif - #endif /* WOLFSSL_CAAM_CMAC */ + #endif /* WOLFSSL_CMAC && WOLFSSL_CAAM_CMAC */ break; case WC_ALGO_TYPE_HASH: @@ -235,13 +238,13 @@ static int wc_CAAM_router(int devId, wc_CryptoInfo* info, void* ctx) break; case WC_ALGO_TYPE_CIPHER: - #ifdef WOLFSSL_CAAM_CIPHER + #if defined(WOLFSSL_CAAM_CIPHER) #ifdef WOLFSSL_SECO_CAAM if (devId != WOLFSSL_SECO_DEVID) break; /* only call to SECO if using WOLFSSL_SECO_DEVID */ #endif switch (info->cipher.type) { - #if defined(HAVE_AESCCM) + #if defined(HAVE_AESCCM) && defined(WOLFSSL_CAAM_AESCCM) case WC_CIPHER_AES_CCM: if (info->cipher.enc == 1) { ret = wc_CAAM_AesCcmEncrypt( @@ -271,7 +274,7 @@ static int wc_CAAM_router(int devId, wc_CryptoInfo* info, void* ctx) } break; #endif /* HAVE_AESCCM */ - #if defined(HAVE_AESGCM) + #if defined(HAVE_AESGCM) && defined(WOLFSSL_CAAM_AESGCM) case WC_CIPHER_AES_GCM: if (info->cipher.enc == 1) { ret = wc_CAAM_AesGcmEncrypt( @@ -300,7 +303,7 @@ static int wc_CAAM_router(int devId, wc_CryptoInfo* info, void* ctx) info->cipher.aesgcm_dec.authInSz); } break; - #endif /* HAVE_AESGCM */ + #endif /* HAVE_AESGCM && WOLFSSL_CAAM_AESGCM */ case WC_CIPHER_AES_CBC: if (info->cipher.enc == 1) { @@ -517,6 +520,7 @@ int wc_caamAddAndWait(CAAM_BUFFER* buf, int sz, word32 arg[4], word32 type) } +#ifdef WOLFSSL_CAAM_BLOB /* Create a red or black blob * * mod : key modifier, expected 8 bytes for RED key types and 16 for BLACK @@ -688,7 +692,7 @@ int wc_caamOpenBlob(byte* data, word32 dataSz, byte* out, word32* outSz) return wc_caamOpenBlob_ex(data, dataSz, out, outSz, WC_CAAM_BLOB_RED, NULL, 0); } - +#endif /* WOLFSSL_CAAM_BLOB */ /* outSz gets set to key size plus 16 for mac and padding * return 0 on success @@ -831,5 +835,4 @@ int caamReadPartition(CAAM_ADDRESS addr, unsigned char* out, int outSz) return 0; } -#endif /* WOLFSSL_IMX6_CAAM || WOLFSSL_IMX6_CAAM_RNG || - WOLFSSL_IMX6UL_CAAM || WOLFSSL_IMX6_CAAM_BLOB */ +#endif /* WOLFSSL_CAAM */ diff --git a/wolfcrypt/src/port/caam/wolfcaam_qnx.c b/wolfcrypt/src/port/caam/wolfcaam_qnx.c index e9aa82fafca..23db33c9656 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_qnx.c +++ b/wolfcrypt/src/port/caam/wolfcaam_qnx.c @@ -34,6 +34,8 @@ #include #include +#include + /* for devctl use */ int caamFd = -1; static wolfSSL_Mutex caamMutex; diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index c7fb79e89d3..fc5ca784546 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -3315,9 +3315,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) return 0; } -#elif (defined(WOLFSSL_IMX6_CAAM) || defined(WOLFSSL_IMX6_CAAM_RNG) || \ - defined(WOLFSSL_SECO_CAAM) || defined(WOLFSSL_QNX_CAAM) || \ - defined(WOLFSSL_IMXRT1170_CAAM)) +#elif defined(WOLFSSL_CAAM) #include diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index 31eeda136ec..612c2133283 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -81,9 +81,7 @@ #include #endif -#if defined(WOLFSSL_IMX6_CAAM) || defined(WOLFSSL_IMX6_CAAM_RNG) || \ - defined(WOLFSSL_IMX6UL_CAAM) || defined(WOLFSSL_IMX6_CAAM_BLOB) || \ - defined(WOLFSSL_SECO_CAAM) || defined(WOLFSSL_IMXRT1170_CAAM) +#if defined(WOLFSSL_CAAM) #include #endif #if defined(WOLFSSL_DEVCRYPTO) @@ -358,9 +356,7 @@ int wolfCrypt_Init(void) } #endif -#if defined(WOLFSSL_IMX6_CAAM) || defined(WOLFSSL_IMX6_CAAM_RNG) || \ - defined(WOLFSSL_IMX6UL_CAAM) || defined(WOLFSSL_IMX6_CAAM_BLOB) || \ - defined(WOLFSSL_SECO_CAAM) || defined(WOLFSSL_IMXRT1170_CAAM) +#if defined(WOLFSSL_CAAM) if ((ret = wc_caamInit()) != 0) { return ret; } @@ -448,9 +444,7 @@ int wolfCrypt_Cleanup(void) WOLFSSL_SCE_GSCE_HANDLE.p_api->close(WOLFSSL_SCE_GSCE_HANDLE.p_ctrl); #endif - #if defined(WOLFSSL_IMX6_CAAM) || defined(WOLFSSL_IMX6_CAAM_RNG) || \ - defined(WOLFSSL_IMX6_CAAM_BLOB) || \ - defined(WOLFSSL_SECO_CAAM) || defined(WOLFSSL_IMXRT1170_CAAM) + #if defined(WOLFSSL_CAAM) wc_caamFree(); #endif #if defined(WOLFSSL_CRYPTOCELL) diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index ace477c78c5..cd1fb7ccfd6 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -44028,7 +44028,7 @@ WOLFSSL_TEST_SUBROUTINE int blob_test(void) return ret; } -#endif /* WOLFSSL_IMX6_CAAM_BLOB */ +#endif /* WOLFSSL_CAAM_BLOB */ #ifdef WOLF_CRYPTO_CB diff --git a/wolfssl/wolfcrypt/port/caam/caam_driver.h b/wolfssl/wolfcrypt/port/caam/caam_driver.h index 7a99fe791f2..e3e277d5661 100644 --- a/wolfssl/wolfcrypt/port/caam/caam_driver.h +++ b/wolfssl/wolfcrypt/port/caam/caam_driver.h @@ -26,10 +26,28 @@ int InitCAAM(void); #include "caam_qnx.h" #endif + + +#ifndef CAAM_BASE #if (defined(__INTEGRITY) || defined(INTEGRITY)) #define CAAM_BASE 0xf2100000 #define CAAM_PAGE 0xf0100000 +#elif defined(__aarch64__) + /* if on an AArch64 system make assumption that it is an i.MX8 QXP */ + /* use block of memory set aside for job ring 2 */ + #define CAAM_BASE 0x31400000 + #define CAAM_PAGE 0x31800000 +#elif defined(WOLFSSL_CAAM_IMX6Q) + /* IMX6Q */ + #define CAAM_BASE 0x02100000 + #define CAAM_PAGE 0x00100000 +#else + /* IMX6UL */ + #define CAAM_BASE 0x02140000 + #define CAAM_PAGE 0x00100000 #endif +#endif /* !CAAM_BASE */ + #ifdef WOLFSSL_CAAM_PRINT #include @@ -263,6 +281,13 @@ #define CAAM_VERSION_LS 0x0FFC #define CAAM_CHA_CCBVID 0x0FE4 + +/* high performance AES module includes XTS, GCM */ +#define CAAM_AES_HIGH_PERFORMANCE 0x4 + +/* low power AES module includes ECB, CBC, CTR, CCM, CMAC, CBC */ +#define CAAM_AES_LOW_POWER 0x3 + #define CAAM_SM_CMD 0x0BE4 #define CAAM_SM_SMPO 0x0FBC #define CAAM_SMAPR 0x0A04 diff --git a/wolfssl/wolfcrypt/port/caam/caam_qnx.h b/wolfssl/wolfcrypt/port/caam/caam_qnx.h index c48e688d027..d3016f4a6d5 100644 --- a/wolfssl/wolfcrypt/port/caam/caam_qnx.h +++ b/wolfssl/wolfcrypt/port/caam/caam_qnx.h @@ -65,16 +65,4 @@ /* check kernel and yield to same priority threads waiting */ #define CAAM_CPU_CHILL() sched_yield() - -#ifdef __aarch64__ - /* if on an AArch64 system make assumption that it is an i.MX8 QXP */ - /* use block of memory set aside for job ring 2 */ - #define CAAM_BASE 0x31400000 - #define CAAM_PAGE 0x31800000 -#else - /* IMX6UL */ - #define CAAM_BASE 0x02140000 - #define CAAM_PAGE 0x00100000 -#endif - #endif /* CAAM_QNX_H */ diff --git a/wolfssl/wolfcrypt/port/caam/wolfcaam_hash.h b/wolfssl/wolfcrypt/port/caam/wolfcaam_hash.h index 5fca631f3a0..07f176eb517 100644 --- a/wolfssl/wolfcrypt/port/caam/wolfcaam_hash.h +++ b/wolfssl/wolfcrypt/port/caam/wolfcaam_hash.h @@ -58,5 +58,8 @@ WOLFSSL_LOCAL int wc_CAAM_Hmac(Hmac* hmac, int macType, const byte* msg, int msgSz, byte* digest); #endif +#ifndef WC_CAAM_HASH_BLOCK + #define WC_CAAM_HASH_BLOCK 64 +#endif #endif diff --git a/wolfssl/wolfcrypt/port/caam/wolfcaam_qnx.h b/wolfssl/wolfcrypt/port/caam/wolfcaam_qnx.h index d85be684fab..1e329c6639b 100644 --- a/wolfssl/wolfcrypt/port/caam/wolfcaam_qnx.h +++ b/wolfssl/wolfcrypt/port/caam/wolfcaam_qnx.h @@ -51,11 +51,6 @@ } CAAM_BUFFER; #endif - -/* IMX6UL */ -#define CAAM_BASE 0x02140000 -#define CAAM_PAGE 0x00100000 - #define DataBuffer 0 #define LastBuffer 0 #define Success 1 @@ -66,6 +61,7 @@ #include #include #include +#include #include #define ResourceNotAvailable -3 diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 77f44b816cc..a4491746cc7 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1791,29 +1791,86 @@ extern void uITRON4_free(void *p) ; #endif #endif -/* if defined turn on all CAAM support */ -#ifdef WOLFSSL_IMX6_CAAM - #undef WOLFSSL_IMX6_CAAM_RNG - #define WOLFSSL_IMX6_CAAM_RNG +/* Setting supported CAAM algorithms */ +#ifdef WOLFSSL_IMX6Q_CAAM + #undef WOLFSSL_CAAM + #define WOLFSSL_CAAM - #undef WOLFSSL_IMX6_CAAM_BLOB - #define WOLFSSL_IMX6_CAAM_BLOB + /* hardware does not support AES-GCM and ECC + * has the low power AES module only (no high power with GCM) */ + #define WOLFSSL_LP_ONLY_CAAM_AES + #define WOLFSSL_NO_CAAM_ECC +#endif -#if defined(HAVE_AESGCM) || defined(WOLFSSL_AES_XTS) - /* large performance gain with HAVE_AES_ECB defined */ - #undef HAVE_AES_ECB - #define HAVE_AES_ECB +#ifdef WOLFSSL_SECO_CAAM + #define WOLFSSL_CAAM - /* @TODO used for now until plugging in caam aes use with qnx */ - #undef WOLFSSL_AES_DIRECT - #define WOLFSSL_AES_DIRECT -#endif + #define WOLFSSL_HASH_KEEP + #define WOLFSSL_NO_CAAM_BLOB #endif #ifdef WOLFSSL_IMXRT1170_CAAM #define WOLFSSL_CAAM - #define WOLFSSL_CAAM_HASH + + #define WOLFSSL_NO_CAAM_BLOB +#endif + +/* OS specific support so far */ +#ifdef WOLFSSL_QNX_CAAM + /* shim layer for QNX hashing not yet implemented */ + #define WOLFSSL_NO_CAAM_HASH +#endif + +#ifdef WOLFSSL_CAAM + /* switch for all AES type algos */ + #undef WOLFSSL_CAAM_CIPHER #define WOLFSSL_CAAM_CIPHER + #ifdef WOLFSSL_CAAM_CIPHER + #ifndef WOLFSSL_LP_ONLY_CAAM_AES + /* GCM and XTS mode are only available in the high power module */ + #define WOLFSSL_CAAM_AESGCM + #define WOLFSSL_CAAM_AESXTS + #endif + #define WOLFSSL_CAAM_AESCCM + #define WOLFSSL_CAAM_AESCTR + #define WOLFSSL_CAAM_AESCBC + #define WOLFSSL_CAAM_CMAC + #endif /* WOLFSSL_CAAM_CIPHER */ + #if defined(HAVE_AESGCM) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_CMAC) + /* large performance gain with HAVE_AES_ECB defined */ + #undef HAVE_AES_ECB + #define HAVE_AES_ECB + + /* @TODO used for now until plugging in caam aes use with qnx */ + #undef WOLFSSL_AES_DIRECT + #define WOLFSSL_AES_DIRECT + #endif + + /* switch for all hashing algos */ + #ifndef WOLFSSL_NO_CAAM_HASH + #define WOLFSSL_CAAM_HASH + #endif + #if defined(WOLFSSL_DEVCRYPTO_HMAC) + /* HMAC is throught the devcrypto calls */ + #define WOLFSSL_CAAM_HMAC + #endif + + /* public key operations */ + #ifndef WOLFSSL_NO_CAAM_ECC + #undef WOLFSSL_CAAM_ECC + #define WOLFSSL_CAAM_ECC + #endif + + /* so far curve25519 support was only done with the SECO */ + #ifdef WOLFSSL_SECO_CAAM + #define WOLFSSL_CAAM_CURVE25519 + #endif + + /* Blob support */ + #ifndef WOLFSSL_NO_CAAM_BLOB + #define WOLFSSL_CAAM_BLOB + #endif #endif /* If DCP is used without SINGLE_THREADED, enforce WOLFSSL_CRYPT_HW_MUTEX */ From a427f4902fa806931e6663085c58b55c18c1747a Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 1 Mar 2023 15:52:04 -0800 Subject: [PATCH 087/391] cleanup user_settings example file --- IDE/QNX/wolfssl/user_settings.h | 101 ++++++++++++++------------------ 1 file changed, 45 insertions(+), 56 deletions(-) diff --git a/IDE/QNX/wolfssl/user_settings.h b/IDE/QNX/wolfssl/user_settings.h index 3814ecb873f..6015a4e5dbf 100644 --- a/IDE/QNX/wolfssl/user_settings.h +++ b/IDE/QNX/wolfssl/user_settings.h @@ -1,6 +1,7 @@ #ifndef USER_SETTINGS_H #define USER_SETTINGS_H +/* Math library to use */ #undef WOLFSSL_SP #define WOLFSSL_SP @@ -10,17 +11,22 @@ #undef WOLFSSL_SP_ARM32 #define WOLFSSL_SP_ARM32 +/* hardening (timing resistance) */ #undef ECC_TIMING_RESISTANT #define ECC_TIMING_RESISTANT #undef WC_RSA_BLINDING #define WC_RSA_BLINDING +/* hardware size of long long */ #define SIZE_OF_LONG_LONG 8 -#define NO_MAIN_DRIVER +#undef NO_FILESYSTEM #define NO_FILESYSTEM +#undef WOLFSSL_USE_ALIGN +#define WOLFSSL_USE_ALIGN + /* Build CAAM support */ #undef WOLFSSL_CAAM #define WOLFSSL_CAAM @@ -31,9 +37,6 @@ #undef WOLFSSL_IMX6Q_CAAM #define WOLFSSL_IMX6Q_CAAM -#undef WOLFSSL_USE_ALIGN -#define WOLFSSL_USE_ALIGN - /* Algorithms Enabled */ #undef HAVE_AESCCM #define HAVE_AESCCM @@ -47,91 +50,77 @@ #undef HAVE_HKDF #define HAVE_HKDF -#undef NO_DSA -#define NO_DSA - #undef HAVE_ECC #define HAVE_ECC -#undef NO_RC4 -#define NO_RC4 - -#undef NO_PSK -#define NO_PSK - -#undef NO_MD4 -#define NO_MD4 - #undef TFM_ECC256 #define TFM_ECC256 #undef ECC_SHAMIR #define ECC_SHAMIR -#undef WC_RSA_PSS -#define WC_RSA_PSS - -#undef WOLFSSL_PSS_LONG_SALT -#define WOLFSSL_PSS_LONG_SALT +#undef HAVE_HASHDRBG +#define HAVE_HASHDRBG -#undef WOLFSSL_ASN_TEMPLATE -#define WOLFSSL_ASN_TEMPLATE +#undef WOLF_CRYPTO_CB +#define WOLF_CRYPTO_CB -#undef WOLFSSL_NO_SHAKE128 -#define WOLFSSL_NO_SHAKE128 +#undef WOLFSSL_AES_COUNTER +#define WOLFSSL_AES_COUNTER -#undef WOLFSSL_NO_SHAKE256 -#define WOLFSSL_NO_SHAKE256 +#undef WOLFSSL_AES_DIRECT +#define WOLFSSL_AES_DIRECT -#undef HAVE_POLY1305 -#define HAVE_POLY1305 +#undef GCM_TABLE_4BIT +#define GCM_TABLE_4BIT -#undef HAVE_CHACHA -#define HAVE_CHACHA +#undef HAVE_AESGCM +#define HAVE_AESGCM -#undef HAVE_HASHDRBG -#define HAVE_HASHDRBG +#undef WC_RSA_PSS +#define WC_RSA_PSS -#undef NO_FILESYSTEM -#define NO_FILESYSTEM +#undef WOLFSSL_PSS_LONG_SALT +#define WOLFSSL_PSS_LONG_SALT #undef HAVE_TLS_EXTENSIONS #define HAVE_TLS_EXTENSIONS -#undef HAVE_SUPPORTED_CURVES -#define HAVE_SUPPORTED_CURVES - #undef HAVE_FFDHE_2048 #define HAVE_FFDHE_2048 #undef HAVE_SUPPORTED_CURVES #define HAVE_SUPPORTED_CURVES -#undef WC_NO_ASYNC_THREADING -#define WC_NO_ASYNC_THREADING -#undef WOLF_CRYPTO_CB -#define WOLF_CRYPTO_CB +/* Algorithms disabled */ +#undef NO_DSA +#define NO_DSA -#undef HAVE_DH_DEFAULT_PARAMS -#define HAVE_DH_DEFAULT_PARAMS +#undef NO_RC4 +#define NO_RC4 -#undef WOLFSSL_AES_COUNTER -#define WOLFSSL_AES_COUNTER +#undef NO_PSK +#define NO_PSK -#undef WOLFSSL_AES_DIRECT -#define WOLFSSL_AES_DIRECT +#undef NO_MD4 +#define NO_MD4 -#undef NO_DES3 -#define NO_DES3 +#undef WOLFSSL_ASN_TEMPLATE +#define WOLFSSL_ASN_TEMPLATE -#undef GCM_TABLE_4BIT -#define GCM_TABLE_4BIT +#undef WOLFSSL_NO_SHAKE128 +#define WOLFSSL_NO_SHAKE128 -#undef HAVE_AESGCM -#define HAVE_AESGCM +#undef WOLFSSL_NO_SHAKE256 +#define WOLFSSL_NO_SHAKE256 -#undef HAVE_TLS_EXTENSIONS -#define HAVE_TLS_EXTENSIONS +#undef WC_NO_ASYNC_THREADING +#define WC_NO_ASYNC_THREADING +#undef HAVE_DH_DEFAULT_PARAMS +#define HAVE_DH_DEFAULT_PARAMS + +#undef NO_DES3 +#define NO_DES3 #endif From 7b69e65b63c490669077f00720743519c298f57e Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 7 Mar 2023 13:19:33 -0800 Subject: [PATCH 088/391] optimization pass through 2 --- wolfcrypt/src/port/caam/caam_driver.c | 178 +++++++++++++++++++++++--- wolfcrypt/src/port/caam/caam_qnx.c | 35 +++-- 2 files changed, 173 insertions(+), 40 deletions(-) diff --git a/wolfcrypt/src/port/caam/caam_driver.c b/wolfcrypt/src/port/caam/caam_driver.c index dfdc3e99312..20b130c635d 100644 --- a/wolfcrypt/src/port/caam/caam_driver.c +++ b/wolfcrypt/src/port/caam/caam_driver.c @@ -586,14 +586,10 @@ Error caamAddJob(DESCSTRUCT* desc) pt = (unsigned int*)caam.ring.VirtualIn; pt[0] = (unsigned int)caam.ring.Desc; - if (CAAM_ADR_SYNC(caam.ring.VirtualDesc, - desc->idx * sizeof(unsigned int)) != 0) { - CAAM_UNLOCK_MUTEX(&caam.ring.jr_lock); - return -1; - } - + /* Sync both the virtual in and the descriptor */ if (CAAM_ADR_SYNC(caam.ring.VirtualIn, - CAAM_JOBRING_SIZE * sizeof(unsigned int)) != 0) { + (CAAM_JOBRING_SIZE * sizeof(unsigned int)) + + (desc->idx * sizeof(unsigned int))) != 0) { CAAM_UNLOCK_MUTEX(&caam.ring.jr_lock); return -1; } @@ -730,38 +726,52 @@ int caamBlob(DESCSTRUCT* desc) CAAM AES Operations ****************************************************************************/ -static void caamAddFIFOL(DESCSTRUCT* desc, void* in, int inSz, +static void caamAddFIFOLPhy(DESCSTRUCT* desc, unsigned int in, int inSz, unsigned int flush) { /* if size is larger than short type then use extended length option */ if (inSz > 0xFFFF) { desc->desc[desc->idx++] = (CAAM_FIFO_L | flush | FIFOS_EXT | CAAM_CLASS1 | FIFOL_TYPE_MSG); - desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(in, inSz); + desc->desc[desc->idx++] = in; desc->desc[desc->idx++] = inSz; } else { desc->desc[desc->idx++] = (CAAM_FIFO_L | flush | CAAM_CLASS1 | FIFOL_TYPE_MSG) + inSz; - desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(in, inSz); + desc->desc[desc->idx++] = in; } } -static void caamAddFIFOS(DESCSTRUCT* desc, void* out, int outSz) +static void caamAddFIFOL(DESCSTRUCT* desc, void* in, int inSz, + unsigned int flush) +{ + caamAddFIFOLPhy(desc, CAAM_ADR_TO_PHYSICAL(in, inSz), inSz, flush); +} + + +static void caamAddFIFOSPhy(DESCSTRUCT* desc, unsigned int out, int outSz) { /* if size is larger than short type then use extended length option */ if (outSz > 0xFFFF) { desc->desc[desc->idx++] = CAAM_FIFO_S | FIFOS_TYPE_MSG | FIFOS_EXT; - desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(out, outSz); + desc->desc[desc->idx++] = out; desc->desc[desc->idx++] = outSz; } else { desc->desc[desc->idx++] = (CAAM_FIFO_S | FIFOS_TYPE_MSG) + outSz; - desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(out, outSz); + desc->desc[desc->idx++] = out; } } + +static void caamAddFIFOS(DESCSTRUCT* desc, void* out, int outSz) +{ + caamAddFIFOSPhy(desc, CAAM_ADR_TO_PHYSICAL(out, outSz), outSz); +} + + int caamAesCmac(DESCSTRUCT* desc, int sz, unsigned int args[4]) { Error err; @@ -1035,6 +1045,85 @@ int caamAead(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) } +static int caamAesInternal(DESCSTRUCT* desc, + unsigned int keyPhy, int keySz, + unsigned int ivPhy, int ivSz, + unsigned int inPhy, int inSz, + unsigned int outPhy, int outSz) +{ + Value ofst = 0; + Error err; + int state = CAAM_ALG_UPDATE; + + if (desc->state != CAAM_ENC && desc->state != CAAM_DEC) { + return CAAM_ARGS_E; + } + + if (keySz != 16 && keySz != 24 && keySz != 32) { + WOLFSSL_MSG("Bad AES key size found"); + return CAAM_ARGS_E; + } + + /* map and copy over key */ + desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1 | CAAM_NWB) + keySz; + desc->desc[desc->idx++] = keyPhy; + + /* get IV if needed by algorithm */ + switch (desc->type) { + case CAAM_AESECB: + break; + + case CAAM_AESCTR: + ofst = 0x00001000; + /* fall through because states are the same only the offset changes */ + + case CAAM_AESCBC: + { + int maxSz = 16; /* default to CBC/CTR max size */ + + if (ivSz != maxSz) { + WOLFSSL_MSG("Invalid AES-CBC IV size\n"); + return CAAM_ARGS_E; + } + + desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS1 | ofst) + + maxSz; + desc->desc[desc->idx++] = ivPhy; + } + break; + + default: + WOLFSSL_MSG("Mode of AES not implemented"); + return CAAM_ARGS_E; + } + + /* write operation */ + desc->desc[desc->idx++] = CAAM_OP | CAAM_CLASS1 | desc->type | + state | desc->state; + + /* set input/output in descriptor */ + caamAddFIFOLPhy(desc, inPhy, inSz, FIFOL_TYPE_LC1); + caamAddFIFOSPhy(desc, outPhy, outSz); + + /* store updated IV */ + switch (desc->type) { + case CAAM_AESCBC: + case CAAM_AESCTR: + if (ivSz > 0) { + desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS1 | ofst | 16; + desc->desc[desc->idx++] = ivPhy; + } + break; + } + + do { + err = caamDoJob(desc); + } while (err == CAAM_WAITING); + + return err; +} + + /* AES operations follow the buffer sequence of KEY -> (IV) -> Input -> Output */ int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) @@ -1049,6 +1138,8 @@ int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) int idx = 0; int state = CAAM_ALG_UPDATE; + unsigned int keyPhy; + if (desc->state != CAAM_ENC && desc->state != CAAM_DEC) { return CAAM_ARGS_E; } @@ -1061,8 +1152,9 @@ int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) /* map and copy over key */ key = (void*)buf[idx].TheAddress; + keyPhy = CAAM_ADR_TO_PHYSICAL(key, keySz); desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1 | CAAM_NWB) + keySz; - desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(key, keySz); + desc->desc[desc->idx++] = keyPhy; idx++; /* get IV if needed by algorithm */ @@ -1111,7 +1203,7 @@ int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) idx++; /* set input/output in descriptor */ - caamAddFIFOL(desc, in, inSz, FIFOL_TYPE_LC1); + caamAddFIFOLPhy(desc, keyPhy + keySz, inSz, FIFOL_TYPE_LC1); caamAddFIFOS(desc, out, outSz); /* store updated IV */ @@ -1133,6 +1225,52 @@ int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) } +/* When a single buffer is used [key] [in] [iv] [out] for optimization */ +int caamAesCombined(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) +{ + int idx = 0; + unsigned int keyPhy, inPhy, ivPhy, outPhy; + int keySz, inSz, ivSz = 0, outSz; + void* pt; + + keySz = buf[idx].Length; + pt = (void*)buf[idx].TheAddress; + idx++; + + /* get IV if needed by algorithm */ + switch (desc->type) { + case CAAM_AESECB: + break; + + case CAAM_AESCTR: + case CAAM_AESCBC: + { + ivSz = buf[idx].Length; + idx++; + } + break; + + default: + WOLFSSL_MSG("Mode of AES not implemented"); + return CAAM_ARGS_E; + } + + /* get input */ + inSz = buf[idx].Length; + idx++; + + /* set output */ + outSz = buf[idx].Length; + idx++; + + keyPhy = CAAM_ADR_TO_PHYSICAL(pt, keySz + inSz + ivSz + outSz); + + return caamAesInternal(desc, keyPhy, keySz, keyPhy + keySz + inSz,ivSz, + keyPhy + keySz, inSz, + keyPhy + keySz + inSz + ivSz, outSz); +} + + /* ECDSA generate black key * * return Success on success. All other return values are considered a fail @@ -1742,17 +1880,17 @@ static int SetupJobRing(struct JobRing* r) CAAM_SET_JOBRING_ADDR(&r->BaseAddr, &r->JobIn, &r->VirtualIn); /* register the in/out and sizes of job ring */ - r->JobOut = r->JobIn + (CAAM_JOBRING_SIZE * sizeof(unsigned int)); - r->Desc = r->JobOut + (2 * CAAM_JOBRING_SIZE * sizeof(unsigned int)); + r->Desc = r->JobIn + (CAAM_JOBRING_SIZE * sizeof(unsigned int)); + r->JobOut = r->Desc + (CAAM_DESC_MAX * CAAM_JOBRING_SIZE); CAAM_INIT_MUTEX(&caam.ring.jr_lock); - r->VirtualOut = r->VirtualIn + (CAAM_JOBRING_SIZE * sizeof(unsigned int)); - r->VirtualDesc = r->VirtualOut + (2 * CAAM_JOBRING_SIZE * sizeof(unsigned int)); + r->VirtualDesc = r->VirtualIn + (CAAM_JOBRING_SIZE * sizeof(unsigned int)); + r->VirtualOut = r->VirtualDesc + (CAAM_DESC_MAX * CAAM_JOBRING_SIZE); memset(r->VirtualIn, 0, CAAM_JOBRING_SIZE * sizeof(unsigned int)); - memset(r->VirtualOut, 0, 2 * CAAM_JOBRING_SIZE * sizeof(unsigned int)); memset(r->VirtualDesc, 0, CAAM_DESC_MAX * CAAM_JOBRING_SIZE); + memset(r->VirtualOut, 0, 2 * CAAM_JOBRING_SIZE * sizeof(unsigned int)); #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT) printf("Setting JOB IN address 0x%08X, size %d\n", diff --git a/wolfcrypt/src/port/caam/caam_qnx.c b/wolfcrypt/src/port/caam/caam_qnx.c index f2c73fa43c4..fd95bba78de 100644 --- a/wolfcrypt/src/port/caam/caam_qnx.c +++ b/wolfcrypt/src/port/caam/caam_qnx.c @@ -739,18 +739,22 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], { int ret = EOK, i = 0; DESCSTRUCT desc; - CAAM_BUFFER tmp[6]; + CAAM_BUFFER tmp[6] = {0}; iov_t in_iovs[6], out_iovs[2]; int inIdx = 0, outIdx = 0; int algo; unsigned char *key = NULL, *iv = NULL, *in = NULL, *out = NULL; int keySz, ivSz = 0, inSz, outSz; - memset(tmp, 0, sizeof(tmp)); - /* get key info */ keySz = args[1] & 0xFFFF; /* key size */ - key = (unsigned char*)CAAM_ADR_MAP(0, keySz, 0); + inSz = args[2]; /* input size */ + outSz = args[2]; /* output size */ + if (type == WC_CAAM_AESCBC || type == WC_CAAM_AESCTR) { + ivSz = 16; + } + + key = (unsigned char*)CAAM_ADR_MAP(0, keySz + inSz + outSz + ivSz, 0); if (key == NULL) { ret = ECANCELED; } @@ -761,7 +765,7 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], if (ret == EOK) { if (type == WC_CAAM_AESCBC || type == WC_CAAM_AESCTR) { ivSz = 16; - iv = (unsigned char*)CAAM_ADR_MAP(0, ivSz, 0); + iv = key + keySz + inSz; if (iv == NULL) { ret = ECANCELED; } @@ -772,8 +776,7 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], /* get input buffer */ if (ret == EOK) { - inSz = args[2]; /* input size */ - in = (unsigned char*)CAAM_ADR_MAP(0, inSz, 0); + in = key + keySz; if (in == NULL) { ret = ECANCELED; } @@ -783,8 +786,7 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], /* create output buffer to store results */ if (ret == EOK) { - outSz = args[2]; /* output size */ - out = (unsigned char*)CAAM_ADR_MAP(0, outSz, 0); + out = key + keySz + inSz + ivSz; if (out == NULL) { ret = ECANCELED; } @@ -826,19 +828,18 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], tmp[i].TheAddress = (CAAM_ADDRESS)out; caamDescInit(&desc, algo, args, tmp, 6); - if (caamAes(&desc, tmp, args) != Success) { + if (caamAesCombined(&desc, tmp, args) != Success) { ret = ECANCELED; } } /* sync the new IV/MAC and output buffer */ if (ret == EOK) { + CAAM_ADR_SYNC(key, keySz + inSz + ivSz + outSz); if (type == WC_CAAM_AESCBC || type == WC_CAAM_AESCTR) { - CAAM_ADR_SYNC(iv, ivSz); SETIOV(&out_iovs[1], iv, ivSz); outIdx++; } - CAAM_ADR_SYNC(out, outSz); SETIOV(&out_iovs[0], out, outSz); outIdx++; @@ -848,13 +849,7 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], } if (key != NULL) - CAAM_ADR_UNMAP(key, 0, keySz, 0); - if (iv != NULL) - CAAM_ADR_UNMAP(iv, 0, ivSz, 0); - if (in != NULL) - CAAM_ADR_UNMAP(in, 0, inSz, 0); - if (out != NULL) - CAAM_ADR_UNMAP(out, 0, outSz, 0); + CAAM_ADR_UNMAP(key, 0, keySz + inSz + ivSz + outSz, 0); return ret; } @@ -881,7 +876,7 @@ static int doECDSA_KEYPAIR(resmgr_context_t *ctp, io_devctl_t *msg, if (args[0] == CAAM_BLACK_KEY_SM) { privSz = sizeof(unsigned int); } - + /* private key */ tmp[0].Length = privSz; priv = (unsigned char*)CAAM_ADR_MAP(0, privSz, 0); From 4dc6ded8e2d7cd60beb2ef2061138dcb198e2b9d Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 10 Mar 2023 08:34:17 -0800 Subject: [PATCH 089/391] third optimization pass with aes-ctr --- wolfcrypt/src/port/caam/caam_driver.c | 106 +++++++++----------------- wolfcrypt/src/port/caam/caam_qnx.c | 50 ++++++++++-- 2 files changed, 80 insertions(+), 76 deletions(-) diff --git a/wolfcrypt/src/port/caam/caam_driver.c b/wolfcrypt/src/port/caam/caam_driver.c index 20b130c635d..56516237e3d 100644 --- a/wolfcrypt/src/port/caam/caam_driver.c +++ b/wolfcrypt/src/port/caam/caam_driver.c @@ -79,6 +79,7 @@ Error caamAddJob(DESCSTRUCT* desc); Error caamDoJob(DESCSTRUCT* desc); + /****************************************************************************** Internal CAAM Job Ring and partition functions ****************************************************************************/ @@ -1124,37 +1125,22 @@ static int caamAesInternal(DESCSTRUCT* desc, } -/* AES operations follow the buffer sequence of KEY -> (IV) -> Input -> Output +/* Scattered memory, does a mapping for each variable. Less performant than + * caamAesCombined. + * AES operations follow the buffer sequence of KEY -> (IV) -> Input -> Output */ int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) { - Value ofst = 0; - Error err; - int ivSz = 0; void *iv = NULL, *key, *in, *out; - int keySz; - int inSz; - int outSz; + int ivSz = 0, keySz, inSz, outSz; int idx = 0; - int state = CAAM_ALG_UPDATE; - unsigned int keyPhy; - - if (desc->state != CAAM_ENC && desc->state != CAAM_DEC) { - return CAAM_ARGS_E; - } - - keySz = buf[idx].Length; - if (keySz != 16 && keySz != 24 && keySz != 32) { - WOLFSSL_MSG("Bad AES key size found"); - return CAAM_ARGS_E; - } + unsigned int keyPhy = 0, inPhy = 0, outPhy = 0, ivPhy = 0; /* map and copy over key */ - key = (void*)buf[idx].TheAddress; + key = (void*)buf[idx].TheAddress; + keySz = buf[idx].Length; keyPhy = CAAM_ADR_TO_PHYSICAL(key, keySz); - desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1 | CAAM_NWB) + keySz; - desc->desc[desc->idx++] = keyPhy; idx++; /* get IV if needed by algorithm */ @@ -1163,22 +1149,11 @@ int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) break; case CAAM_AESCTR: - ofst = 0x00001000; - /* fall through because states are the same only the offset changes */ - case CAAM_AESCBC: { - int maxSz = 16; /* default to CBC/CTR max size */ - - ivSz = buf[idx].Length; - if (ivSz != maxSz) { - WOLFSSL_MSG("Invalid AES-CBC IV size\n"); - return CAAM_ARGS_E; - } - - iv = (void*)buf[idx].TheAddress; - desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS1 | ofst) + maxSz; - desc->desc[desc->idx++] = (CAAM_ADDRESS)CAAM_ADR_TO_PHYSICAL(iv, ivSz); + ivSz = buf[idx].Length; + iv = (void*)buf[idx].TheAddress; + ivPhy = CAAM_ADR_TO_PHYSICAL(iv, ivSz); idx++; } break; @@ -1188,48 +1163,31 @@ int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) return CAAM_ARGS_E; } - /* write operation */ - desc->desc[desc->idx++] = CAAM_OP | CAAM_CLASS1 | desc->type | - state | desc->state; - /* get input */ - inSz = buf[idx].Length; - in = (void*)buf[idx].TheAddress; + inSz = buf[idx].Length; + in = (void*)buf[idx].TheAddress; + inPhy = CAAM_ADR_TO_PHYSICAL(in, inSz); idx++; /* set output */ - outSz = buf[idx].Length; - out = (void*)buf[idx].TheAddress; + outSz = buf[idx].Length; + out = (void*)buf[idx].TheAddress; + outPhy = CAAM_ADR_TO_PHYSICAL(out, outSz); idx++; - /* set input/output in descriptor */ - caamAddFIFOLPhy(desc, keyPhy + keySz, inSz, FIFOL_TYPE_LC1); - caamAddFIFOS(desc, out, outSz); - - /* store updated IV */ - switch (desc->type) { - case CAAM_AESCBC: - case CAAM_AESCTR: - if (ivSz > 0) { - desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS1 | ofst | 16; - desc->desc[desc->idx++] = (CAAM_ADDRESS)CAAM_ADR_TO_PHYSICAL(iv, ivSz); - } - break; - } - - do { - err = caamDoJob(desc); - } while (err == CAAM_WAITING); - - return err; + return caamAesInternal(desc, keyPhy, keySz, ivPhy, ivSz, inPhy, inSz, + outPhy, outSz); } -/* When a single buffer is used [key] [in] [iv] [out] for optimization */ -int caamAesCombined(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) +/* When a single buffer is used [key] [in] [iv] [out] for optimization + * phyMem is non 0 when the physical memory location is already known + */ +int caamAesCombined(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4], + unsigned int phyMem) { int idx = 0; - unsigned int keyPhy, inPhy, ivPhy, outPhy; + unsigned int keyPhy; int keySz, inSz, ivSz = 0, outSz; void* pt; @@ -1263,11 +1221,17 @@ int caamAesCombined(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4]) outSz = buf[idx].Length; idx++; - keyPhy = CAAM_ADR_TO_PHYSICAL(pt, keySz + inSz + ivSz + outSz); + if (phyMem != 0) { + keyPhy = phyMem; + } + else { + keyPhy = CAAM_ADR_TO_PHYSICAL(pt, keySz + inSz + ivSz + outSz); + } - return caamAesInternal(desc, keyPhy, keySz, keyPhy + keySz + inSz,ivSz, - keyPhy + keySz, inSz, - keyPhy + keySz + inSz + ivSz, outSz); + return caamAesInternal(desc, keyPhy, keySz, + keyPhy + keySz + inSz,ivSz, /* IV */ + keyPhy + keySz, inSz, /* IN buffer */ + keyPhy + keySz + inSz + ivSz, outSz); /* OUT buffer */ } diff --git a/wolfcrypt/src/port/caam/caam_qnx.c b/wolfcrypt/src/port/caam/caam_qnx.c index fd95bba78de..32d7731722c 100644 --- a/wolfcrypt/src/port/caam/caam_qnx.c +++ b/wolfcrypt/src/port/caam/caam_qnx.c @@ -46,10 +46,22 @@ #include #include #include +#include /* virtual address for accessing CAAM addresses */ uintptr_t virtual_base = 0; +static void* localMemory = NULL; +static unsigned int localPhy = 0; +sem_t localMemSem; + +/* Can be overriden, variable for how large of a local buffer to have. + * This allows for large performance gains when avoiding mapping new memory + * for each operation. */ +#ifndef WOLFSSL_CAAM_QNX_MEMORY + #define WOLFSSL_CAAM_QNX_MEMORY 250000 +#endif + /* keep track of which ID memory belongs to so it can be free'd up */ #define MAX_PART 7 pthread_mutex_t sm_mutex; @@ -739,12 +751,16 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], { int ret = EOK, i = 0; DESCSTRUCT desc; - CAAM_BUFFER tmp[6] = {0}; + CAAM_BUFFER tmp[6]; iov_t in_iovs[6], out_iovs[2]; int inIdx = 0, outIdx = 0; int algo; unsigned char *key = NULL, *iv = NULL, *in = NULL, *out = NULL; + unsigned char *pt = NULL; int keySz, ivSz = 0, inSz, outSz; + unsigned int phyMem = 0; + + memset(tmp, 0, sizeof(tmp)); /* get key info */ keySz = args[1] & 0xFFFF; /* key size */ @@ -754,7 +770,19 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], ivSz = 16; } - key = (unsigned char*)CAAM_ADR_MAP(0, keySz + inSz + outSz + ivSz, 0); + if (keySz + inSz + outSz + ivSz < WOLFSSL_CAAM_QNX_MEMORY) { + if (sem_trywait(&localMemSem) == 0) { + key = localMemory; + phyMem = localPhy; + } + } + + /* local pre-mapped memory was not used, try to map some memory now */ + if (key == NULL) { + pt = (unsigned char*)CAAM_ADR_MAP(0, keySz + inSz + outSz + ivSz, 0); + key = pt; + } + if (key == NULL) { ret = ECANCELED; } @@ -828,7 +856,7 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], tmp[i].TheAddress = (CAAM_ADDRESS)out; caamDescInit(&desc, algo, args, tmp, 6); - if (caamAesCombined(&desc, tmp, args) != Success) { + if (caamAesCombined(&desc, tmp, args, phyMem) != Success) { ret = ECANCELED; } } @@ -848,8 +876,13 @@ static int doAES(resmgr_context_t *ctp, io_devctl_t *msg, unsigned int args[4], } } - if (key != NULL) - CAAM_ADR_UNMAP(key, 0, keySz + inSz + ivSz + outSz, 0); + if (pt != NULL) { + CAAM_ADR_UNMAP(pt, 0, keySz + inSz + outSz + ivSz, 0); + } + else { + /* done using local mapped memory */ + sem_post(&localMemSem); + } return ret; } @@ -1686,6 +1719,9 @@ int main(int argc, char *argv[]) WOLFSSL_MSG("unable to start up caam driver!"); exit(1); } + localMemory = (unsigned char*)CAAM_ADR_MAP(0, WOLFSSL_CAAM_QNX_MEMORY, 0); + localPhy = CAAM_ADR_TO_PHYSICAL(localMemory, WOLFSSL_CAAM_QNX_MEMORY); + sem_init(&localMemSem, 1, 1); dpp = dispatch_create(); if (dpp == NULL) { @@ -1729,7 +1765,11 @@ int main(int argc, char *argv[]) } } + sem_destroy(&localMemSem); pthread_mutex_destroy(&sm_mutex); + if (localMemory != NULL) + CAAM_ADR_UNMAP(localMemory, 0, WOLFSSL_CAAM_QNX_MEMORY, 0); + CleanupCAAM(); return 0; } From eff0930fe8861e44bc1d12fcdd934b0f3a96dd4b Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 14 Mar 2023 08:48:43 -0700 Subject: [PATCH 090/391] update README --- IDE/QNX/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/IDE/QNX/README.md b/IDE/QNX/README.md index 2d6694c831b..4ff5c13c9d8 100644 --- a/IDE/QNX/README.md +++ b/IDE/QNX/README.md @@ -35,3 +35,7 @@ To build in momentics IDE: - CMAC with and without black keys - TRNG used by default to seed Hash DRBG - AES operations (CTR) + +### Performance + +Typically on smaller block sizes (~ less than 7k) operations are slower with CAAM than software implementations. There is a tunable macro WOLFSSL_CAAM_QNX_MEMORY which sets the size of an internal buffer used currently with AES operations for performance. By default it is set to 250k but can be defined to smaller or larger values. If the block size being encrypted/decrypted does not fit within the buffer size then there will be a big performance hit. From 5ed9d4e164c0eaebee7e4841b2f609574cf552bc Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 5 Apr 2023 08:02:20 +1000 Subject: [PATCH 091/391] OpenSSL API and cryptonly: fix to compile OBJ_nid2sn not available when compiling for cryptonly - don't compile in call to it in test.h. --- wolfssl/test.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfssl/test.h b/wolfssl/test.h index 4739d4e6be5..e29ad3236a5 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -1129,7 +1129,7 @@ static WC_INLINE void showPeerEx(WOLFSSL* ssl, int lng_index) #ifndef NO_DH int bits; #endif -#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) int nid; #endif #ifdef KEEP_PEER_CERT @@ -1149,7 +1149,7 @@ static WC_INLINE void showPeerEx(WOLFSSL* ssl, int lng_index) cipher = wolfSSL_get_current_cipher(ssl); printf("%s %s\n", words[1], wolfSSL_CIPHER_get_name(cipher)); -#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) if (wolfSSL_get_signature_nid(ssl, &nid) == WOLFSSL_SUCCESS) { printf("%s %s\n", words[2], OBJ_nid2sn(nid)); } From 564f83364d053b9f023b5a06d8d00809ff039dc0 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 5 Apr 2023 10:29:46 +1000 Subject: [PATCH 092/391] ASN.1 testing: restore 0 length BIO failure tests Create a fixed buffer BIO of length 1 and then write one byte into it so that there is 0 length to write into. Test cases removed as setting fixed buffer BIO to length 0 allocated 0 length buffer that is sometimes returning NULL. --- tests/api.c | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/tests/api.c b/tests/api.c index a6ca181bc84..1e352c8330a 100644 --- a/tests/api.c +++ b/tests/api.c @@ -31230,6 +31230,10 @@ static int test_wolfSSL_a2i_ASN1_INTEGER(void) AssertNotNull(fixed = BIO_new(wolfSSL_BIO_s_fixed_mem())); AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(fixed, tmp, 1), 1); + AssertIntEQ(i2a_ASN1_INTEGER(fixed, ai), 0); + AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); AssertIntEQ(i2a_ASN1_INTEGER(fixed, ai), 0); BIO_free(fixed); @@ -31954,7 +31958,9 @@ static int test_wolfSSL_ASN1_STRING_print(void) BIO_free(bio); AssertNotNull(bio = BIO_new(wolfSSL_BIO_s_fixed_mem())); - AssertIntEQ(BIO_set_write_buf_size(bio, 0), 1); + AssertIntEQ(BIO_set_write_buf_size(bio, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(bio, rbuf, 1), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print(bio, asnStr), 0); AssertIntEQ(BIO_set_write_buf_size(bio, 1), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print(bio, asnStr), 0); @@ -32017,6 +32023,10 @@ static int test_wolfSSL_ASN1_STRING_print_ex(void) BIO_read(bio, (void*)rbuf, 15); AssertStrEQ((char*)rbuf, "Hello wolfSSL!"); AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); + AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); AssertIntEQ(BIO_set_write_buf_size(fixed, 14), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); @@ -32029,6 +32039,10 @@ static int test_wolfSSL_ASN1_STRING_print_ex(void) BIO_read(bio, (void*)rbuf, 9); AssertStrEQ((char*)rbuf, "a\\+\\;\\<\\>"); AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); + AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); + AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); AssertIntEQ(BIO_set_write_buf_size(fixed, 8), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); @@ -32041,6 +32055,10 @@ static int test_wolfSSL_ASN1_STRING_print_ex(void) BIO_read(bio, (void*)rbuf, 28); AssertStrEQ((char*)rbuf, "OCTET STRING:Hello wolfSSL!"); AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); + AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); AssertIntEQ(BIO_set_write_buf_size(fixed, 12), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); @@ -32055,6 +32073,10 @@ static int test_wolfSSL_ASN1_STRING_print_ex(void) BIO_read(bio, (void*)rbuf, 31); AssertStrEQ((char*)rbuf, "#48656C6C6F20776F6C6653534C2100"); AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); + AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); AssertIntEQ(BIO_set_write_buf_size(fixed, 30), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); @@ -32067,6 +32089,10 @@ static int test_wolfSSL_ASN1_STRING_print_ex(void) BIO_read(bio, (void*)rbuf, 35); AssertStrEQ((char*)rbuf, "#040F48656C6C6F20776F6C6653534C2100"); AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); + AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); AssertIntEQ(BIO_set_write_buf_size(fixed, 2), 1); AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); @@ -32225,6 +32251,10 @@ static int test_wolfSSL_ASN1_GENERALIZEDTIME_print(void) BIO_free(bio); AssertNotNull(bio = BIO_new(wolfSSL_BIO_s_fixed_mem())); + AssertIntEQ(BIO_set_write_buf_size(bio, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(bio, buf, 1), 1); + AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 0); for (i = 1; i < 20; i++) { AssertIntEQ(BIO_set_write_buf_size(bio, i), 1); AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 0); @@ -32668,6 +32698,10 @@ static int test_wolfSSL_ASN1_TIME_print(void) /* Test BIO_write fails. */ AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + /* Ensure there is 0 bytes avaialble to write into. */ + AssertIntEQ(BIO_write(fixed, buf, 1), 1); + AssertIntEQ(ASN1_TIME_print(fixed, notBefore), 0); + AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); AssertIntEQ(ASN1_TIME_print(fixed, notBefore), 0); AssertIntEQ(BIO_set_write_buf_size(fixed, 23), 1); AssertIntEQ(ASN1_TIME_print(fixed, notBefore), 0); From c6b651e554bb1a42ecd4bf768a2ec68bed3498d0 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 5 Apr 2023 14:23:19 +0200 Subject: [PATCH 093/391] Ignore staticBuffer in test_wolfSSL_dtls_stateless_HashWOLFSSL --- tests/api.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/api.c b/tests/api.c index 1e352c8330a..4d946123147 100644 --- a/tests/api.c +++ b/tests/api.c @@ -60754,10 +60754,16 @@ static word32 test_wolfSSL_dtls_stateless_HashWOLFSSL(const WOLFSSL* ssl) XMEMSET(hashBuf, 0, sizeof(hashBuf)); /* Following fields are not important to compare */ + XMEMSET(sslCopy.buffers.inputBuffer.staticBuffer, 0, STATIC_BUFFER_LEN); sslCopy.buffers.inputBuffer.buffer = NULL; sslCopy.buffers.inputBuffer.bufferSize = 0; sslCopy.buffers.inputBuffer.dynamicFlag = 0; sslCopy.buffers.inputBuffer.offset = 0; + XMEMSET(sslCopy.buffers.outputBuffer.staticBuffer, 0, STATIC_BUFFER_LEN); + sslCopy.buffers.outputBuffer.buffer = NULL; + sslCopy.buffers.outputBuffer.bufferSize = 0; + sslCopy.buffers.outputBuffer.dynamicFlag = 0; + sslCopy.buffers.outputBuffer.offset = 0; sslCopy.error = 0; sslCopy.curSize = 0; sslCopy.keys.curSeq_lo = 0; From ea2bdfb344da0fac608171f1773d3d3c0359668a Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Wed, 5 Apr 2023 15:12:43 -0400 Subject: [PATCH 094/391] Documentation fixup for wolfSSL_get_chain_cert(); --- doc/dox_comments/header_files/ssl.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/dox_comments/header_files/ssl.h b/doc/dox_comments/header_files/ssl.h index 6a06cb82e44..03ddb76e596 100644 --- a/doc/dox_comments/header_files/ssl.h +++ b/doc/dox_comments/header_files/ssl.h @@ -6368,6 +6368,9 @@ unsigned char* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx); memory SESSION_CACHE. \param idx the index of the WOLFSSL_X509 certificate. + Note that it is the user's responsibility to free the returned memory + by calling wolfSSL_FreeX509(). + _Example_ \code WOLFSSL_X509_CHAIN* chain = &session->chain; @@ -6377,9 +6380,10 @@ unsigned char* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx); prt = wolfSSL_get_chain_X509(chain, idx); if(ptr != NULL){ - //ptr contains the cert at the index specified + // ptr contains the cert at the index specified + wolfSSL_FreeX509(ptr); } else { - // ptr is NULL + // ptr is NULL } \endcode From 01725bb1572e677c8d84f7280db934eedc541817 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Wed, 5 Apr 2023 10:39:16 -0400 Subject: [PATCH 095/391] Allow user to override XSTAT --- wolfssl/wolfcrypt/wc_port.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 78d53208c3a..1b0115f8fe7 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -638,13 +638,17 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); && !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) #if defined(USE_WINDOWS_API) #include + #ifndef XSTAT #define XSTAT _stat + #endif #define XS_ISREG(s) (s & _S_IFREG) #define SEPARATOR_CHAR ';' #elif defined(INTIME_RTOS) #include + #ifndef XSTAT #define XSTAT _stat64 + #endif #define XS_ISREG(s) S_ISREG(s) #define SEPARATOR_CHAR ';' #define XWRITE write @@ -652,11 +656,15 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XCLOSE close #elif defined(WOLFSSL_ZEPHYR) + #ifndef XSTAT #define XSTAT fs_stat + #endif #define XS_ISREG(s) (s == FS_DIR_ENTRY_FILE) #define SEPARATOR_CHAR ':' #elif defined(WOLFSSL_TELIT_M2MB) + #ifndef XSTAT #define XSTAT m2mb_fs_stat + #endif #define XS_ISREG(s) (s & M2MB_S_IFREG) #define SEPARATOR_CHAR ':' #else @@ -666,7 +674,9 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XWRITE write #define XREAD read #define XCLOSE close + #ifndef XSTAT #define XSTAT stat + #endif #define XS_ISREG(s) S_ISREG(s) #define SEPARATOR_CHAR ':' #endif From 90130f506b51ee52d0f3bc32b449a6ce992c045f Mon Sep 17 00:00:00 2001 From: Eric Blankenhorn Date: Fri, 24 Mar 2023 10:22:00 -0500 Subject: [PATCH 096/391] Support HAVE_SESSION_TICKET without realloc --- src/ssl.c | 10 ++++++++++ wolfcrypt/test/test.c | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/ssl.c b/src/ssl.c index 0231a5ee8b0..2fb9c3fb07d 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -21234,11 +21234,21 @@ static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, ret = WOLFSSL_FAILURE; } else { +#ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC(input->ticketLen, + output->heap, DYNAMIC_TYPE_SESSION_TICK); + XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); + ticBuff = NULL; +#else tmp = (byte*)XREALLOC(ticBuff, input->ticketLen, output->heap, DYNAMIC_TYPE_SESSION_TICK); +#endif /* WOLFSSL_NO_REALLOC */ if (tmp == NULL) { WOLFSSL_MSG("Failed to allocate memory for ticket"); +#ifndef WOLFSSL_NO_REALLOC XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); + ticBuff = NULL; +#endif /* WOLFSSL_NO_REALLOC */ output->ticket = NULL; output->ticketLen = 0; output->ticketLenAlloc = 0; diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index cd1fb7ccfd6..2653d6abd52 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -13607,10 +13607,10 @@ WOLFSSL_TEST_SUBROUTINE int memory_test(void) #if !defined(USE_FAST_MATH) && !defined(WOLFSSL_NO_MALLOC) && defined(XREALLOC) /* realloc test */ { - byte *c = NULL; byte *b = (byte*)XMALLOC(MEM_TEST_SZ, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); #ifndef WOLFSSL_NO_REALLOC + byte *c = NULL; if (b) { c = (byte*)XREALLOC(b, MEM_TEST_SZ+sizeof(word32), HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); From 87f8af1058883405671e250072d57f97638adfe6 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 5 Apr 2023 13:57:10 +0200 Subject: [PATCH 097/391] Fix intermittent failures in test_wolfSSL_CTX_add_session --- src/ssl.c | 6 +++++- tests/api.c | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/ssl.c b/src/ssl.c index 2fb9c3fb07d..ca484a95065 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -14993,6 +14993,7 @@ int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) session = ClientSessionToSession(session); if (ssl == NULL || session == NULL) { + WOLFSSL_MSG("ssl or session NULL"); return WOLFSSL_FAILURE; } @@ -15033,7 +15034,8 @@ int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) #endif { ret = wolfSSL_DupSession(session, ssl->session, 0); - WOLFSSL_MSG("Session duplicate failed"); + if (ret != WOLFSSL_SUCCESS) + WOLFSSL_MSG("Session duplicate failed"); } } @@ -15246,6 +15248,8 @@ WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session) if (error == 0) { /* Check the session ID hash matches */ error = clientSession->sessionIDHash != sessionIDHash; + if (error != 0) + WOLFSSL_MSG("session ID hash don't match"); } if (error == 0) { /* Hashes match */ diff --git a/tests/api.c b/tests/api.c index 4d946123147..6311b9d586e 100644 --- a/tests/api.c +++ b/tests/api.c @@ -7388,7 +7388,13 @@ static int test_wolfSSL_CTX_add_session(void) test_wolfSSL_CTX_add_session_server_sess = NULL; test_wolfSSL_CTX_add_session_server_ctx = NULL; +#ifdef NO_SESSION_CACHE_REF for (j = 0; j < 5; j++) { +#else + /* The session may be overwritten in this case. Do only one resumption + * to stop this test from failing intermittently. */ + for (j = 0; j < 2; j++) { +#endif #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif From ca16b89415ceed6804592897c12b00cff5afc599 Mon Sep 17 00:00:00 2001 From: Eric Blankenhorn Date: Mon, 20 Mar 2023 16:07:29 -0500 Subject: [PATCH 098/391] RIOT-OS does support writev --- wolfssl/wolfcrypt/settings.h | 1 - 1 file changed, 1 deletion(-) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index a4491746cc7..9448bc789b3 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -677,7 +677,6 @@ #endif #ifdef WOLFSSL_RIOT_OS - #define NO_WRITEV #define TFM_NO_ASM #define NO_FILESYSTEM #define USE_CERT_BUFFERS_2048 From 467e3f0451af9fafb38033006c772e68391884e8 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 5 Apr 2023 20:28:51 -0500 Subject: [PATCH 099/391] eliminate XREWIND() macro, add XSEEK_SET definitions, and refactor all XREWIND()s to XFSEEK()s, to fix clang-tidy-17 bugprone-unsafe-functions warning on rewind(); add BENCH_DEVID_COLUMN_HEADER in wolfcrypt/benchmark/benchmark.c:bench_stats_sym_finish() to resolve clang-diagnostic-embedded-directive. --- src/bio.c | 6 +++-- src/sniffer.c | 5 +++- src/ssl.c | 25 ++++++++++++++++---- src/x509.c | 22 +++++++++++++---- tests/api.c | 24 +++++++++---------- tests/suites.c | 7 +++++- wolfcrypt/benchmark/benchmark.c | 13 +++++----- wolfcrypt/src/asn.c | 42 ++++++++++++++++++++------------- wolfcrypt/src/wc_port.c | 6 ++++- wolfssl/test.h | 4 ++-- wolfssl/wolfcrypt/wc_port.h | 24 +++++++++---------- 11 files changed, 115 insertions(+), 63 deletions(-) diff --git a/src/bio.c b/src/bio.c index 035835ea443..103d7771f2c 100644 --- a/src/bio.c +++ b/src/bio.c @@ -1429,8 +1429,10 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) switch (bio->type) { #ifndef NO_FILESYSTEM case WOLFSSL_BIO_FILE: - XREWIND((XFILE)bio->ptr); - return 0; + if (XFSEEK((XFILE)bio->ptr, 0, XSEEK_SET) != 0) + return WOLFSSL_BIO_ERROR; + else + return 0; #endif case WOLFSSL_BIO_BIO: diff --git a/src/sniffer.c b/src/sniffer.c index a2a134389e5..2b6e98889ca 100644 --- a/src/sniffer.c +++ b/src/sniffer.c @@ -1627,7 +1627,10 @@ static int LoadKeyFile(byte** keyBuf, word32* keyBufSz, XFCLOSE(file); return -1; } - XREWIND(file); + if(XFSEEK(file, 0, XSEEK_SET) != 0) { + XFCLOSE(file); + return -1; + } loadBuf = (byte*)XMALLOC(fileSz, NULL, DYNAMIC_TYPE_FILE); if (loadBuf == NULL) { diff --git a/src/ssl.c b/src/ssl.c index ca484a95065..6065869352d 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -8706,7 +8706,10 @@ int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format, int type, return WOLFSSL_BAD_FILE; } sz = XFTELL(file); - XREWIND(file); + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) { WOLFSSL_MSG("ProcessFile file size error"); @@ -9179,7 +9182,10 @@ int wolfSSL_CertManagerVerify(WOLFSSL_CERT_MANAGER* cm, const char* fname, return WOLFSSL_BAD_FILE; } sz = XFTELL(file); - XREWIND(file); + if(XFSEEK(file, 0, XSEEK_SET) != 0) { + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) { WOLFSSL_MSG("CertManagerVerify file size error"); @@ -9641,7 +9647,10 @@ static int wolfSSL_SetTmpDH_file_wrapper(WOLFSSL_CTX* ctx, WOLFSSL* ssl, return WOLFSSL_BAD_FILE; } sz = XFTELL(file); - XREWIND(file); + if(XFSEEK(file, 0, XSEEK_SET) != 0) { + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) { WOLFSSL_MSG("SetTmpDH file size error"); @@ -12322,7 +12331,10 @@ int CM_RestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const char* fname) return WOLFSSL_BAD_FILE; } memSz = (int)XFTELL(file); - XREWIND(file); + if(XFSEEK(file, 0, XSEEK_SET) != 0) { + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } if (memSz > MAX_WOLFSSL_FILE_SIZE || memSz <= 0) { WOLFSSL_MSG("CM_RestoreCertCache file size error"); @@ -25823,7 +25835,10 @@ int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname) return WOLFSSL_BAD_FILE; } sz = XFTELL(file); - XREWIND(file); + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } if (sz > MAX_WOLFSSL_FILE_SIZE || sz < 0) { WOLFSSL_MSG("cmp_peer_cert_to_file size error"); diff --git a/src/x509.c b/src/x509.c index a7a3e8430b8..b0b2366a8e5 100644 --- a/src/x509.c +++ b/src/x509.c @@ -4647,7 +4647,8 @@ WOLFSSL_X509* wolfSSL_X509_d2i_fp(WOLFSSL_X509** x509, XFILE file) if (XFSEEK(file, 0, XSEEK_END) != 0) return NULL; sz = XFTELL(file); - XREWIND(file); + if (XFSEEK(file, 0, XSEEK_SET) != 0) + return NULL; if (sz > MAX_WOLFSSL_FILE_SIZE || sz < 0) { WOLFSSL_MSG("X509_d2i file size error"); @@ -4706,7 +4707,10 @@ WOLFSSL_X509* wolfSSL_X509_load_certificate_file(const char* fname, int format) return NULL; } sz = XFTELL(file); - XREWIND(file); + if (XFSEEK(file, 0, XSEEK_SET) != 0){ + XFCLOSE(file); + return NULL; + } if (sz > MAX_WOLFSSL_FILE_SIZE || sz < 0) { WOLFSSL_MSG("X509_load_certificate_file size error"); @@ -6624,7 +6628,10 @@ int wolfSSL_X509_LOOKUP_load_file(WOLFSSL_X509_LOOKUP* lookup, return WS_RETURN_CODE(WOLFSSL_BAD_FILE,WOLFSSL_FAILURE); } sz = XFTELL(fp); - XREWIND(fp); + if(XFSEEK(fp, 0, XSEEK_SET) != 0) { + XFCLOSE(fp); + return WS_RETURN_CODE(WOLFSSL_BAD_FILE,WOLFSSL_FAILURE); + } if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) { WOLFSSL_MSG("X509_LOOKUP_load_file size error"); @@ -7181,7 +7188,9 @@ static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type) return NULL; } sz = XFTELL(file); - XREWIND(file); + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + return NULL; + } if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) { WOLFSSL_MSG("d2i_X509_fp_ex file size error"); @@ -7345,7 +7354,10 @@ WOLFSSL_API int wolfSSL_X509_load_cert_crl_file(WOLFSSL_X509_LOOKUP *ctx, } } else { - XREWIND(fp); + if (XFSEEK(fp, 0, XSEEK_SET) != 0) { + WOLFSSL_MSG("XFSEEK error"); + return cnt; + } crl = wolfSSL_PEM_read_X509_CRL(fp, NULL, NULL, NULL); if (crl != NULL) { if (wolfSSL_X509_STORE_add_crl(ctx->store, crl) == diff --git a/tests/api.c b/tests/api.c index 6311b9d586e..f80952aaccb 100644 --- a/tests/api.c +++ b/tests/api.c @@ -601,7 +601,7 @@ static int test_fileAccess(void) AssertTrue((f = XFOPEN(derfile, "rb")) != XBADFILE); AssertTrue(XFSEEK(f, 0, XSEEK_END) == 0); sz = (size_t) XFTELL(f); - XREWIND(f); + AssertTrue(XFSEEK(f, 0, XSEEK_SET) == 0); AssertTrue(sz == sizeof_server_cert_der_2048); AssertTrue((buff = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)) != NULL) ; AssertTrue(XFREAD(buff, 1, sz, f) == sz); @@ -34754,7 +34754,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) AssertTrue((file != XBADFILE)); AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); sz = XFTELL(file); - XREWIND(file); + AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); if (buf) { AssertIntEQ(XFREAD(buf, 1, sz, file), sz); @@ -34781,7 +34781,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) AssertTrue((file != XBADFILE)); AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); sz = XFTELL(file); - XREWIND(file); + AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); if (buf) AssertIntEQ(XFREAD(buf, 1, sz, file), sz); @@ -34828,7 +34828,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) AssertTrue((file != XBADFILE)); AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); sz = XFTELL(file); - XREWIND(file); + AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); if (buf) AssertIntEQ(XFREAD(buf, 1, sz, file), sz); @@ -34867,7 +34867,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) AssertTrue((file != XBADFILE)); AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); sz = XFTELL(file); - XREWIND(file); + AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); if (buf) AssertIntEQ(XFREAD(buf, 1, sz, file), sz); @@ -35473,9 +35473,9 @@ static int test_wolfSSL_PEM_PUBKEY(void) file = XFOPEN(fname, "rb"); AssertTrue((file != XBADFILE)); - AssertIntGE(XFSEEK(file, 0, XSEEK_END), 0); + AssertIntEQ(XFSEEK(file, 0, XSEEK_END), 0); sz = XFTELL(file); - XREWIND(file); + AssertIntEQ(XFSEEK(file, 0, XSEEK_SET), 0); AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); if (buf) AssertIntEQ(XFREAD(buf, 1, sz, file), sz); @@ -44934,7 +44934,7 @@ static int test_wolfSSL_d2i_PrivateKeys_bio(void) AssertTrue((file != XBADFILE)); AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); sz = XFTELL(file); - XREWIND(file); + AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); AssertNotNull(buf = (byte*)XMALLOC(sz, HEAP_HINT, DYNAMIC_TYPE_FILE)); AssertIntEQ(XFREAD(buf, 1, sz, file), sz); XFCLOSE(file); @@ -44962,7 +44962,7 @@ static int test_wolfSSL_d2i_PrivateKeys_bio(void) AssertTrue((file != XBADFILE)); AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); sz = XFTELL(file); - XREWIND(file); + AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); AssertNotNull(buf = (byte*)XMALLOC(sz, HEAP_HINT, DYNAMIC_TYPE_FILE)); AssertIntEQ(XFREAD(buf, 1, sz, file), sz); XFCLOSE(file); @@ -50129,7 +50129,7 @@ static int test_wolfSSL_d2i_and_i2d_DSAparams(void) AssertTrue(f != XBADFILE); AssertTrue(XFSEEK(f, 0, XSEEK_END) == 0); derInLen = (int)XFTELL(f); - XREWIND(f); + AssertTrue(XFSEEK(f, 0, XSEEK_SET) == 0); AssertNotNull(derIn = (byte*)XMALLOC(derInLen, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER)); AssertIntEQ(XFREAD(derIn, 1, derInLen, f), derInLen); @@ -56349,9 +56349,9 @@ static int test_wolfSSL_RSA_verify(void) /* read privete key file */ fp = XFOPEN(svrKeyFile, "rb"); AssertTrue((fp != XBADFILE)); - AssertIntGE(XFSEEK(fp, 0, XSEEK_END), 0); + AssertIntEQ(XFSEEK(fp, 0, XSEEK_END), 0); sz = XFTELL(fp); - XREWIND(fp); + AssertIntEQ(XFSEEK(fp, 0, XSEEK_SET), 0); AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); AssertIntEQ(XFREAD(buf, 1, sz, fp), sz); XFCLOSE(fp); diff --git a/tests/suites.c b/tests/suites.c index 42a85769f8a..f97d7edde37 100644 --- a/tests/suites.c +++ b/tests/suites.c @@ -648,7 +648,12 @@ static void test_harness(void* vargs) args->return_code = 1; return; } - rewind(file); + if (fseek(file, 0, SEEK_SET) < 0) { + fprintf(stderr, "error %d fseeking %s\n", errno, fname); + fclose(file); + args->return_code = 1; + return; + } script = (char*)malloc(sz+1); if (script == 0) { diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index c1a602f7784..8001fd025ce 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -1796,19 +1796,20 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, #endif #else /* normal CSV */ + #ifdef BENCH_DEVID + #define BENCH_DEVID_COLUMN_HEADER "HW/SW," + #else + #define BENCH_DEVID_COLUMN_HEADER + #endif #ifdef HAVE_GET_CYCLES printf("\n\nSymmetric Ciphers:\n\n"); printf("Algorithm," - #ifdef BENCH_DEVID - "HW/SW," - #endif + BENCH_DEVID_COLUMN_HEADER WOLFSSL_FIXED_UNITS_PER_SEC ",Cycles per byte,\n"); #else printf("\n\nSymmetric Ciphers:\n\n"); printf("Algorithm," - #ifdef BENCH_DEVID - "HW/SW," - #endif + BENCH_DEVID_COLUMN_HEADER WOLFSSL_FIXED_UNITS_PER_SEC ", \n"); #endif #endif diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index a7c72c021ad..9875f5d3243 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -23421,9 +23421,14 @@ int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der) ret = BUFFER_E; } sz = XFTELL(file); - XREWIND(file); + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + ret = BUFFER_E; + } - if (sz <= 0) { + if (ret < 0) { + /* intentionally left empty. */ + } + else if (sz <= 0) { ret = BUFFER_E; } else if (sz > (long)sizeof(staticBuffer)) { @@ -23501,9 +23506,14 @@ int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der) if (XFSEEK(file, 0, XSEEK_END) != 0) { ret = BUFFER_E; } + } + if (ret == 0) { sz = XFTELL(file); - XREWIND(file); - + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + ret = BUFFER_E; + } + } + if (ret == 0) { if (sz <= 0) { ret = BUFFER_E; } @@ -23514,22 +23524,22 @@ int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der) else dynamic = 1; } - if (ret == 0) { - if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) { - ret = BUFFER_E; - } - else { - ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der, - 0, NULL, NULL); - } + } + if (ret == 0) { + if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) { + ret = BUFFER_E; } - - XFCLOSE(file); - if (dynamic) { - XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE); + else { + ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der, + 0, NULL, NULL); } } + if (file != XBADFILE) + XFCLOSE(file); + if (dynamic) + XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE); + return ret; } /* load pem public key from file into der buffer, return der size or error */ diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index 612c2133283..c81272ef4f4 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -512,7 +512,11 @@ int wc_FileLoad(const char* fname, unsigned char** buf, size_t* bufLen, return BAD_PATH_ERROR; } fileSz = XFTELL(f); - XREWIND(f); + if (XFSEEK(f, 0, XSEEK_SET) != 0) { + WOLFSSL_MSG("wc_LoadFile file seek error"); + XFCLOSE(f); + return BAD_PATH_ERROR; + } if (fileSz > 0) { *bufLen = fileSz; *buf = (byte*)XMALLOC(*bufLen, heap, DYNAMIC_TYPE_TMP_BUFFER); diff --git a/wolfssl/test.h b/wolfssl/test.h index e29ad3236a5..b39b7d21a61 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -2685,9 +2685,9 @@ static WC_INLINE void OCSPRespFreeCb(void* ioCtx, unsigned char* response) return BAD_PATH_ERROR; } - LIBCALL_CHECK_RET(fseek(lFile, 0, SEEK_END)); + LIBCALL_CHECK_RET(XFSEEK(lFile, 0, XSEEK_END)); fileSz = (int)ftell(lFile); - rewind(lFile); + LIBCALL_CHECK_RET(XFSEEK(lFile, 0, XSEEK_SET)); if (fileSz > 0) { *bufLen = (size_t)fileSz; *buf = (byte*)malloc(*bufLen); diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 1b0115f8fe7..454088823c5 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -427,10 +427,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN(NAME, MODE) vf_open((const char *)NAME, VO_RDONLY, 0) #define XFSEEK ebsnet_fseek #define XFTELL vf_tell - #define XREWIND vf_rewind #define XFREAD(BUF, SZ, AMT, FD) vf_read(FD, BUF, SZ*AMT) #define XFWRITE(BUF, SZ, AMT, FD) vf_write(FD, BUF, SZ*AMT) #define XFCLOSE vf_close + #define XSEEK_SET VSEEK_SET #define XSEEK_END VSEEK_END #define XBADFILE -1 #define XFGETS(b,s,f) -2 /* Not ported yet */ @@ -441,10 +441,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN(NAME, MODE) fs_open((char*)NAME) #define XFSEEK(F, O, W) (void)F #define XFTELL(F) (F)->len - #define XREWIND(F) (void)F #define XFREAD(BUF, SZ, AMT, F) fs_read(F, (char*)BUF, SZ*AMT) #define XFWRITE(BUF, SZ, AMT, F) fs_write(F, (char*)BUF, SZ*AMT) #define XFCLOSE fs_close + #define XSEEK_SET 0 #define XSEEK_END 0 #define XBADFILE NULL #define XFGETS(b,s,f) -2 /* Not ported yet */ @@ -454,10 +454,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN fopen #define XFSEEK fseek #define XFTELL ftell - #define XREWIND(F) fseek(F, 0, IO_SEEK_SET) #define XFREAD fread #define XFWRITE fwrite #define XFCLOSE fclose + #define XSEEK_SET IO_SEEK_SET #define XSEEK_END IO_SEEK_END #define XBADFILE NULL #define XFGETS fgets @@ -471,10 +471,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN fs_fopen #define XFSEEK fs_fseek #define XFTELL fs_ftell - #define XREWIND fs_rewind #define XFREAD fs_fread #define XFWRITE fs_fwrite #define XFCLOSE fs_fclose + #define XSEEK_SET FS_SEEK_SET #define XSEEK_END FS_SEEK_END #define XBADFILE NULL #define XFGETS(b,s,f) -2 /* Not ported yet */ @@ -485,10 +485,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN fopen #define XFSEEK fseek #define XFTELL ftell - #define XREWIND rewind #define XFREAD fread #define XFWRITE fwrite #define XFCLOSE fclose + #define XSEEK_SET PSEEK_SET #define XSEEK_END PSEEK_END #define XBADFILE NULL @@ -499,10 +499,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN mynewt_fopen #define XFSEEK mynewt_fseek #define XFTELL mynewt_ftell - #define XREWIND mynewt_rewind #define XFREAD mynewt_fread #define XFWRITE mynewt_fwrite #define XFCLOSE mynewt_fclose + #define XSEEK_SET 0 #define XSEEK_END 2 #define XBADFILE NULL #define XFGETS(b,s,f) -2 /* Not ported yet */ @@ -521,9 +521,9 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFSEEK fs_seek #define XFTELL fs_tell #define XFREWIND fs_rewind - #define XREWIND(F) fs_seek(F, 0, FS_SEEK_SET) #define XFREAD(P,S,N,F) fs_read(F, P, S*N) #define XFWRITE(P,S,N,F) fs_write(F, P, S*N) + #define XSEEK_SET FS_SEEK_SET #define XSEEK_END FS_SEEK_END #define XBADFILE NULL #define XFGETS(b,s,f) -2 /* Not ported yet */ @@ -533,10 +533,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN(NAME, MODE) m2mb_fs_open((NAME), 0, (MODE)) #define XFSEEK(F, O, W) m2mb_fs_lseek((F), (O), (W)) #define XFTELL(F) m2mb_fs_lseek((F), 0, M2MB_SEEK_END) - #define XREWIND(F) (void)F #define XFREAD(BUF, SZ, AMT, F) m2mb_fs_read((F), (BUF), (SZ)*(AMT)) #define XFWRITE(BUF, SZ, AMT, F) m2mb_fs_write((F), (BUF), (SZ)*(AMT)) #define XFCLOSE m2mb_fs_close + #define XSEEK_SET M2MB_SEEK_SET #define XSEEK_END M2MB_SEEK_END #define XBADFILE -1 #define XFGETS(b,s,f) -2 /* Not ported yet */ @@ -550,10 +550,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN(NAME, MODE) ({ FRESULT res; res = f_open(&curFile, (NAME), (FA_OPEN_ALWAYS | FA_WRITE | FA_READ)); (res == FR_OK) ? &curFile : NULL; }) #define XFSEEK(F, O, W) f_lseek((F), (O)) #define XFTELL(F) f_tell((F)) - #define XREWIND(F) f_rewind((F)) #define XFREAD(BUF, SZ, AMT, F) ({ FRESULT res; UINT br; res = f_read((F), (BUF), (SZ)*(AMT), &br); (void)br; res; }) #define XFWRITE(BUF, SZ, AMT, F) ({ FRESULT res; UINT written; res = f_write((F), (BUF), (SZ)*(AMT), &written); (void)written; res; }) #define XFCLOSE(F) f_close((F)) + #define XSEEK_SET 0 #define XSEEK_END 0 #define XBADFILE NULL #define XFGETS(b,s,f) f_gets((b), (s), (f)) @@ -565,10 +565,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFDOPEN fdopen #define XFSEEK fseek #define XFTELL ftell - #define XREWIND(F) XFSEEK(F, 0, SEEK_SET) #define XFREAD fread #define XFWRITE fwrite #define XFCLOSE fclose + #define XSEEK_END SEEK_SET #define XSEEK_END SEEK_END #define XBADFILE NULL #define XFGETS fgets @@ -585,10 +585,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFOPEN FCL_FOPEN #define XFSEEK FCL_FSEEK #define XFTELL FCL_FTELL - #define XREWIND FCL_REWIND #define XFREAD FCL_FREAD #define XFWRITE FCL_FWRITE #define XFCLOSE FCL_FCLOSE + #define XSEEK_SET SEEK_SET #define XSEEK_END SEEK_END #define XBADFILE NULL #define XFGETS FCL_FGETS @@ -624,10 +624,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFDOPEN fdopen #define XFSEEK fseek #define XFTELL ftell - #define XREWIND rewind #define XFREAD fread #define XFWRITE fwrite #define XFCLOSE fclose + #define XSEEK_SET SEEK_SET #define XSEEK_END SEEK_END #define XBADFILE NULL #define XFGETS fgets From 79bde9f28907e7d8e79e7ba177b1bd8d2b1d6ca0 Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Fri, 31 Mar 2023 15:56:31 +0900 Subject: [PATCH 100/391] fix overwriting serialnum by favouriteDrink --- tests/api.c | 8 ++++++++ wolfssl/wolfcrypt/asn.h | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/api.c b/tests/api.c index f80952aaccb..90e804e09b9 100644 --- a/tests/api.c +++ b/tests/api.c @@ -46890,6 +46890,14 @@ static int test_wolfSSL_make_cert(void) AssertIntEQ(ASN1_STRING_length(entryValue), 2); AssertStrEQ((const char*)ASN1_STRING_data(entryValue), "US"); + /* compare Serial Number */ + AssertIntEQ((idx = X509_NAME_get_index_by_NID(x509name, NID_serialNumber, + -1)), 7); + AssertNotNull(entry = X509_NAME_get_entry(x509name, idx)); + AssertNotNull(entryValue = X509_NAME_ENTRY_get_data(entry)); + AssertIntEQ(ASN1_STRING_length(entryValue), XSTRLEN("wolfSSL12345")); + AssertStrEQ((const char*)ASN1_STRING_data(entryValue), "wolfSSL12345"); + #ifdef WOLFSSL_MULTI_ATTRIB /* get first and second DC and compare result */ AssertIntEQ((idx = X509_NAME_get_index_by_NID(x509name, NID_domainComponent, diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 560d888d0fc..489dcfe5517 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -687,7 +687,7 @@ enum DN_Tags { /* pilot attribute types * OID values of 0.9.2342.19200300.100.1.* */ - ASN_FAVOURITE_DRINK = 0x05, /* favouriteDrink */ + ASN_FAVOURITE_DRINK = 0x13, /* favouriteDrink */ ASN_DOMAIN_COMPONENT = 0x19 /* DC */ }; From ca86b2cb30816f27850873ef245b805fb04341df Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Wed, 5 Apr 2023 07:25:25 +0900 Subject: [PATCH 101/391] fix unitest failure --- tests/api.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/api.c b/tests/api.c index 90e804e09b9..3d948e823cc 100644 --- a/tests/api.c +++ b/tests/api.c @@ -46890,6 +46890,7 @@ static int test_wolfSSL_make_cert(void) AssertIntEQ(ASN1_STRING_length(entryValue), 2); AssertStrEQ((const char*)ASN1_STRING_data(entryValue), "US"); +#ifndef WOLFSSL_MULTI_ATTRIB /* compare Serial Number */ AssertIntEQ((idx = X509_NAME_get_index_by_NID(x509name, NID_serialNumber, -1)), 7); @@ -46897,6 +46898,7 @@ static int test_wolfSSL_make_cert(void) AssertNotNull(entryValue = X509_NAME_ENTRY_get_data(entry)); AssertIntEQ(ASN1_STRING_length(entryValue), XSTRLEN("wolfSSL12345")); AssertStrEQ((const char*)ASN1_STRING_data(entryValue), "wolfSSL12345"); +#endif #ifdef WOLFSSL_MULTI_ATTRIB /* get first and second DC and compare result */ From 004205e7b7b1fe28363696a1a93f691698f06903 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 24 Mar 2023 15:02:15 +1000 Subject: [PATCH 102/391] SP int: improve use of stack Minimize use of stack. Make very large stack allocations dynamic memory allocations unless WOLFSSL_SP_NO_MALLOC. ProcessBufferTryDecode() split up into a function for each type. ProcessBufferTryDecodeRsa() decodes the data and gets key size rather than having or allocating an RsaKey. Added wc_RsaPrivateKeyValidate() that only validates the encoding is an RSA key and returns the key size in bytes. For SP int, only create sp_ints of required size in RSA and ECC implementation. For WOLFSSL_SMALL_STACK, memory is allocated to have just enough bytes and size is set to maximum supported. Otherwise, relies on dynamic stack variables. For ECC, MAX_ECC_BITS_USE used when dynamic stack variables not supported. Significantly reduces memory usage when RSA/DH is also built. Add macros to sp_int.h, tfm.h and integer.h to support declaring, allocating, initializing and freeing mp_ints. For integer.h, mp_int is always static as size is no more than 32 bytes. For tfm.h, WOLFSSL_SMALL_STACK has a full mp_int allocated, otherwise the full mp_int is put on the stack. For sp_int.h with new macros, dynamically allocate sp_int to minimal size when WOLFSSL_SMALL_STACK, or when dynamic stack variables, declare them to be of minimal size or otherwise declare with a fixed max. Added mp_bitsused(), for all implementations, to get the number of bits available based on used. Included for RSA to get the size of the modulus. SP int now always uses dynamic stack variables if possible rather than for builds with WOLFSSL_SP_SMALL. Moved code out into separate functions so that stack allocations don't happen when not going down code path. --- src/ssl.c | 868 +++++++++------ wolfcrypt/src/asn.c | 219 ++-- wolfcrypt/src/ecc.c | 1906 +++++++++++++++++--------------- wolfcrypt/src/rsa.c | 545 +++++---- wolfcrypt/src/sp_int.c | 373 ++++--- wolfssl/internal.h | 2 + wolfssl/wolfcrypt/asn_public.h | 9 +- wolfssl/wolfcrypt/integer.h | 22 + wolfssl/wolfcrypt/rsa.h | 5 + wolfssl/wolfcrypt/settings.h | 3 + wolfssl/wolfcrypt/sp_int.h | 106 +- wolfssl/wolfcrypt/tfm.h | 52 + 12 files changed, 2349 insertions(+), 1761 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 6065869352d..18747276720 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -6718,295 +6718,284 @@ static int ProcessUserChain(WOLFSSL_CTX* ctx, const unsigned char* buff, return ret; } -static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, DerBuffer* der, - int* keySz, word32* idx, int* resetSuites, int* keyFormat, void* heap, int devId) +#ifndef NO_RSA +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION > 2)) +static int ProcessBufferTryDecodeRsa(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, + int devId) { - int ret = 0; + int ret; - (void)heap; (void)devId; - if (ctx == NULL && ssl == NULL) - return BAD_FUNC_ARG; - if (!der || !keySz || !idx || !resetSuites || !keyFormat) - return BAD_FUNC_ARG; + *idx = 0; + ret = wc_RsaPrivateKeyValidate(der->buffer, idx, keySz, der->length); +#ifdef WOLF_PRIVATE_KEY_ID + if ((ret != 0) && (devId != INVALID_DEVID + #ifdef HAVE_PK_CALLBACKS + || wolfSSL_CTX_IsPrivatePkSet(ctx) + #endif + )) { + word32 nSz; -#ifndef NO_RSA - if ((*keyFormat == 0 || *keyFormat == RSAk)) { - /* make sure RSA key can be used */ - #ifdef WOLFSSL_SMALL_STACK - RsaKey* key; + /* if using crypto or PK callbacks, try public key decode */ + *idx = 0; + ret = wc_RsaPublicKeyDecode_ex(der->buffer, idx, der->length, NULL, + &nSz, NULL, NULL); + if (ret == 0) { + *keySz = (int)nSz; + } + } +#endif + if (ret != 0) { + #if !defined(HAVE_ECC) && !defined(HAVE_ED25519) && \ + !defined(HAVE_ED448) && !defined(HAVE_PQC) + WOLFSSL_MSG("RSA decode failed and other algorithms " + "not enabled to try"); + ret = WOLFSSL_BAD_FILE; #else - RsaKey key[1]; + ret = 0; /* continue trying other algorithms */ #endif + } + else { + /* check that the size of the RSA key is enough */ + int minRsaSz = ssl ? ssl->options.minRsaKeySz : ctx->minRsaKeySz; + if (*keySz < minRsaSz) { + ret = RSA_KEY_SIZE_E; + WOLFSSL_MSG("Private Key size too small"); + } - #ifdef WOLFSSL_SMALL_STACK - key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA); - if (key == NULL) - return MEMORY_E; - #endif + if (ssl) { + ssl->buffers.keyType = rsa_sa_algo; + ssl->buffers.keySz = *keySz; + } + else { + ctx->privateKeyType = rsa_sa_algo; + ctx->privateKeySz = *keySz; + } - ret = wc_InitRsaKey_ex(key, heap, devId); - if (ret == 0) { + *keyFormat = RSAk; + + if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { + ssl->options.haveStaticECC = 0; + *resetSuites = 1; + } + } + + return ret; +} +#else +static int ProcessBufferTryDecodeRsa(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, + void* heap, int devId) +{ + int ret; + + /* make sure RSA key can be used */ +#ifdef WOLFSSL_SMALL_STACK + RsaKey* key; +#else + RsaKey key[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA); + if (key == NULL) + return MEMORY_E; +#endif + + ret = wc_InitRsaKey_ex(key, heap, devId); + if (ret == 0) { + *idx = 0; + ret = wc_RsaPrivateKeyDecode(der->buffer, idx, key, der->length); + #ifdef WOLF_PRIVATE_KEY_ID + if (ret != 0 && (devId != INVALID_DEVID + #ifdef HAVE_PK_CALLBACKS + || wolfSSL_CTX_IsPrivatePkSet(ctx) + #endif + )) { + /* if using crypto or PK callbacks, try public key decode */ *idx = 0; - ret = wc_RsaPrivateKeyDecode(der->buffer, idx, key, der->length); - #ifdef WOLF_PRIVATE_KEY_ID - if (ret != 0 && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || wolfSSL_CTX_IsPrivatePkSet(ctx) - #endif - )) { - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_RsaPublicKeyDecode(der->buffer, idx, key, der->length); - } + ret = wc_RsaPublicKeyDecode(der->buffer, idx, key, der->length); + } + #endif + if (ret != 0) { + #if !defined(HAVE_ECC) && !defined(HAVE_ED25519) && \ + !defined(HAVE_ED448) && !defined(HAVE_PQC) + WOLFSSL_MSG("RSA decode failed and other algorithms " + "not enabled to try"); + ret = WOLFSSL_BAD_FILE; + #else + ret = 0; /* continue trying other algorithms */ #endif - if (ret != 0) { - #if !defined(HAVE_ECC) && !defined(HAVE_ED25519) && \ - !defined(HAVE_ED448) && !defined(HAVE_PQC) - WOLFSSL_MSG("RSA decode failed and other algorithms " - "not enabled to try"); - ret = WOLFSSL_BAD_FILE; - #else - ret = 0; /* continue trying other algorithms */ - #endif + } + else { + /* check that the size of the RSA key is enough */ + int minRsaSz = ssl ? ssl->options.minRsaKeySz : ctx->minRsaKeySz; + *keySz = wc_RsaEncryptSize((RsaKey*)key); + if (*keySz < minRsaSz) { + ret = RSA_KEY_SIZE_E; + WOLFSSL_MSG("Private Key size too small"); } - else { - /* check that the size of the RSA key is enough */ - int minRsaSz = ssl ? ssl->options.minRsaKeySz : - ctx->minRsaKeySz; - *keySz = wc_RsaEncryptSize((RsaKey*)key); - if (*keySz < minRsaSz) { - ret = RSA_KEY_SIZE_E; - WOLFSSL_MSG("Private Key size too small"); - } - if (ssl) { - ssl->buffers.keyType = rsa_sa_algo; - ssl->buffers.keySz = *keySz; - } - else { - ctx->privateKeyType = rsa_sa_algo; - ctx->privateKeySz = *keySz; - } + if (ssl) { + ssl->buffers.keyType = rsa_sa_algo; + ssl->buffers.keySz = *keySz; + } + else { + ctx->privateKeyType = rsa_sa_algo; + ctx->privateKeySz = *keySz; + } - *keyFormat = RSAk; + *keyFormat = RSAk; - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - ssl->options.haveStaticECC = 0; - *resetSuites = 1; - } + if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { + ssl->options.haveStaticECC = 0; + *resetSuites = 1; } - - wc_FreeRsaKey(key); } - #ifdef WOLFSSL_SMALL_STACK - XFREE(key, heap, DYNAMIC_TYPE_RSA); - #endif - if (ret != 0) - return ret; + wc_FreeRsaKey(key); } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(key, heap, DYNAMIC_TYPE_RSA); +#endif + + return ret; +} #endif +#endif /* !NO_RSA */ + #ifdef HAVE_ECC - if ((*keyFormat == 0 || *keyFormat == ECDSAk)) { - /* make sure ECC key can be used */ - #ifdef WOLFSSL_SMALL_STACK - ecc_key* key; - #else - ecc_key key[1]; - #endif +static int ProcessBufferTryDecodeEcc(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, + void* heap, int devId) +{ + int ret = 0; + /* make sure ECC key can be used */ +#ifdef WOLFSSL_SMALL_STACK + ecc_key* key; +#else + ecc_key key[1]; +#endif - #ifdef WOLFSSL_SMALL_STACK - key = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, DYNAMIC_TYPE_ECC); - if (key == NULL) - return MEMORY_E; - #endif +#ifdef WOLFSSL_SMALL_STACK + key = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, DYNAMIC_TYPE_ECC); + if (key == NULL) + return MEMORY_E; +#endif - if (wc_ecc_init_ex(key, heap, devId) == 0) { + if (wc_ecc_init_ex(key, heap, devId) == 0) { + *idx = 0; + ret = wc_EccPrivateKeyDecode(der->buffer, idx, key, der->length); + #ifdef WOLF_PRIVATE_KEY_ID + if (ret != 0 && (devId != INVALID_DEVID + #ifdef HAVE_PK_CALLBACKS + || wolfSSL_CTX_IsPrivatePkSet(ctx) + #endif + )) { + /* if using crypto or PK callbacks, try public key decode */ *idx = 0; - ret = wc_EccPrivateKeyDecode(der->buffer, idx, key, der->length); - #ifdef WOLF_PRIVATE_KEY_ID - if (ret != 0 && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || wolfSSL_CTX_IsPrivatePkSet(ctx) - #endif - )) { - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_EccPublicKeyDecode(der->buffer, idx, key, der->length); + ret = wc_EccPublicKeyDecode(der->buffer, idx, key, der->length); + } + #endif + if (ret == 0) { + /* check for minimum ECC key size and then free */ + int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; + *keySz = wc_ecc_size(key); + if (*keySz < minKeySz) { + WOLFSSL_MSG("ECC private key too small"); + ret = ECC_KEY_SIZE_E; } - #endif - if (ret == 0) { - /* check for minimum ECC key size and then free */ - int minKeySz = ssl ? ssl->options.minEccKeySz : - ctx->minEccKeySz; - *keySz = wc_ecc_size(key); - if (*keySz < minKeySz) { - WOLFSSL_MSG("ECC private key too small"); - ret = ECC_KEY_SIZE_E; - } - *keyFormat = ECDSAk; - if (ssl) { - ssl->options.haveStaticECC = 1; - ssl->buffers.keyType = ecc_dsa_sa_algo; - ssl->buffers.keySz = *keySz; - } - else { - ctx->haveStaticECC = 1; - ctx->privateKeyType = ecc_dsa_sa_algo; - ctx->privateKeySz = *keySz; - } - - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } + *keyFormat = ECDSAk; + if (ssl) { + ssl->options.haveStaticECC = 1; + ssl->buffers.keyType = ecc_dsa_sa_algo; + ssl->buffers.keySz = *keySz; } else { - ret = 0; /* continue trying other algorithms */ + ctx->haveStaticECC = 1; + ctx->privateKeyType = ecc_dsa_sa_algo; + ctx->privateKeySz = *keySz; } - wc_ecc_free(key); + if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { + *resetSuites = 1; + } + } + else { + ret = 0; /* continue trying other algorithms */ } - #ifdef WOLFSSL_SMALL_STACK - XFREE(key, heap, DYNAMIC_TYPE_ECC); - #endif - if (ret != 0) - return ret; + wc_ecc_free(key); } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(key, heap, DYNAMIC_TYPE_ECC); +#endif + return ret; +} #endif /* HAVE_ECC */ + #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) - if ((*keyFormat == 0 || *keyFormat == ED25519k)) { - /* make sure Ed25519 key can be used */ - #ifdef WOLFSSL_SMALL_STACK - ed25519_key* key; - #else - ed25519_key key[1]; - #endif +static int ProcessBufferTryDecodeEd25519(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, + void* heap, int devId) +{ + int ret; + /* make sure Ed25519 key can be used */ +#ifdef WOLFSSL_SMALL_STACK + ed25519_key* key; +#else + ed25519_key key[1]; +#endif - #ifdef WOLFSSL_SMALL_STACK - key = (ed25519_key*)XMALLOC(sizeof(ed25519_key), heap, - DYNAMIC_TYPE_ED25519); - if (key == NULL) - return MEMORY_E; - #endif +#ifdef WOLFSSL_SMALL_STACK + key = (ed25519_key*)XMALLOC(sizeof(ed25519_key), heap, + DYNAMIC_TYPE_ED25519); + if (key == NULL) + return MEMORY_E; +#endif - ret = wc_ed25519_init_ex(key, heap, devId); - if (ret == 0) { - *idx = 0; - ret = wc_Ed25519PrivateKeyDecode(der->buffer, idx, key, der->length); - #ifdef WOLF_PRIVATE_KEY_ID - if (ret != 0 && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || wolfSSL_CTX_IsPrivatePkSet(ctx) - #endif - )) { - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_Ed25519PublicKeyDecode(der->buffer, idx, key, - der->length); - } + ret = wc_ed25519_init_ex(key, heap, devId); + if (ret == 0) { + *idx = 0; + ret = wc_Ed25519PrivateKeyDecode(der->buffer, idx, key, der->length); + #ifdef WOLF_PRIVATE_KEY_ID + if (ret != 0 && (devId != INVALID_DEVID + #ifdef HAVE_PK_CALLBACKS + || wolfSSL_CTX_IsPrivatePkSet(ctx) #endif - if (ret == 0) { - /* check for minimum key size and then free */ - int minKeySz = ssl ? ssl->options.minEccKeySz : - ctx->minEccKeySz; - *keySz = ED25519_KEY_SIZE; - if (*keySz < minKeySz) { - WOLFSSL_MSG("ED25519 private key too small"); - ret = ECC_KEY_SIZE_E; - } - if (ret == 0) { - if (ssl) { - ssl->buffers.keyType = ed25519_sa_algo; - ssl->buffers.keySz = *keySz; - } - else if (ctx) { - ctx->privateKeyType = ed25519_sa_algo; - ctx->privateKeySz = *keySz; - } - - *keyFormat = ED25519k; - if (ssl != NULL) { - /* ED25519 requires caching enabled for tracking message - * hash used in EdDSA_Update for signing */ - ssl->options.cacheMessages = 1; - if (ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } - } - } - } - else { - ret = 0; /* continue trying other algorithms */ - } - - wc_ed25519_free(key); + )) { + /* if using crypto or PK callbacks, try public key decode */ + *idx = 0; + ret = wc_Ed25519PublicKeyDecode(der->buffer, idx, key, der->length); } - - #ifdef WOLFSSL_SMALL_STACK - XFREE(key, heap, DYNAMIC_TYPE_ED25519); - #endif - if (ret != 0) - return ret; - } -#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */ -#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) - if ((*keyFormat == 0 || *keyFormat == ED448k)) { - /* make sure Ed448 key can be used */ - #ifdef WOLFSSL_SMALL_STACK - ed448_key* key = NULL; - #else - ed448_key key[1]; #endif - - #ifdef WOLFSSL_SMALL_STACK - key = (ed448_key*)XMALLOC(sizeof(ed448_key), heap, DYNAMIC_TYPE_ED448); - if (key == NULL) - return MEMORY_E; - #endif - - ret = wc_ed448_init(key); if (ret == 0) { - *idx = 0; - ret = wc_Ed448PrivateKeyDecode(der->buffer, idx, key, der->length); - #ifdef WOLF_PRIVATE_KEY_ID - if (ret != 0 && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || wolfSSL_CTX_IsPrivatePkSet(ctx) - #endif - )) { - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_Ed448PublicKeyDecode(der->buffer, idx, key, - der->length); - } - #endif - if (ret == 0) { - /* check for minimum key size and then free */ - int minKeySz = ssl ? ssl->options.minEccKeySz : - ctx->minEccKeySz; - *keySz = ED448_KEY_SIZE; - if (*keySz < minKeySz) { - WOLFSSL_MSG("ED448 private key too small"); - ret = ECC_KEY_SIZE_E; - } + /* check for minimum key size and then free */ + int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; + *keySz = ED25519_KEY_SIZE; + if (*keySz < minKeySz) { + WOLFSSL_MSG("ED25519 private key too small"); + ret = ECC_KEY_SIZE_E; } if (ret == 0) { if (ssl) { - ssl->buffers.keyType = ed448_sa_algo; + ssl->buffers.keyType = ed25519_sa_algo; ssl->buffers.keySz = *keySz; } else if (ctx) { - ctx->privateKeyType = ed448_sa_algo; + ctx->privateKeyType = ed25519_sa_algo; ctx->privateKeySz = *keySz; } - *keyFormat = ED448k; + *keyFormat = ED25519k; if (ssl != NULL) { - /* ED448 requires caching enabled for tracking message + /* ED25519 requires caching enabled for tracking message * hash used in EdDSA_Update for signing */ ssl->options.cacheMessages = 1; if (ssl->options.side == WOLFSSL_SERVER_END) { @@ -7014,161 +7003,316 @@ static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, DerBuffer* der } } } - - wc_ed448_free(key); + } + else { + ret = 0; /* continue trying other algorithms */ } - #ifdef WOLFSSL_SMALL_STACK - XFREE(key, heap, DYNAMIC_TYPE_ED448); - #endif - if (ret != 0) - return ret; + wc_ed25519_free(key); } -#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ -#if defined(HAVE_PQC) -#if defined(HAVE_FALCON) - if (((*keyFormat == 0) || (*keyFormat == FALCON_LEVEL1k) || - (*keyFormat == FALCON_LEVEL5k))) { - /* make sure Falcon key can be used */ - falcon_key* key = (falcon_key*)XMALLOC(sizeof(falcon_key), heap, - DYNAMIC_TYPE_FALCON); - if (key == NULL) { - return MEMORY_E; + +#ifdef WOLFSSL_SMALL_STACK + XFREE(key, heap, DYNAMIC_TYPE_ED25519); +#endif + return ret; +} +#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */ + +#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) +static int ProcessBufferTryDecodeEd448(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, + void* heap, int devId) +{ + int ret; + /* make sure Ed448 key can be used */ +#ifdef WOLFSSL_SMALL_STACK + ed448_key* key = NULL; +#else + ed448_key key[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + key = (ed448_key*)XMALLOC(sizeof(ed448_key), heap, DYNAMIC_TYPE_ED448); + if (key == NULL) + return MEMORY_E; +#endif + + ret = wc_ed448_init_ex(key, heap, devId); + if (ret == 0) { + *idx = 0; + ret = wc_Ed448PrivateKeyDecode(der->buffer, idx, key, der->length); + #ifdef WOLF_PRIVATE_KEY_ID + if (ret != 0 && (devId != INVALID_DEVID + #ifdef HAVE_PK_CALLBACKS + || wolfSSL_CTX_IsPrivatePkSet(ctx) + #endif + )) { + /* if using crypto or PK callbacks, try public key decode */ + *idx = 0; + ret = wc_Ed448PublicKeyDecode(der->buffer, idx, key, der->length); } - ret = wc_falcon_init(key); + #endif if (ret == 0) { - if (*keyFormat == FALCON_LEVEL1k) { - ret = wc_falcon_set_level(key, 1); + /* check for minimum key size and then free */ + int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; + *keySz = ED448_KEY_SIZE; + if (*keySz < minKeySz) { + WOLFSSL_MSG("ED448 private key too small"); + ret = ECC_KEY_SIZE_E; } - else if (*keyFormat == FALCON_LEVEL5k) { - ret = wc_falcon_set_level(key, 5); + } + if (ret == 0) { + if (ssl) { + ssl->buffers.keyType = ed448_sa_algo; + ssl->buffers.keySz = *keySz; } - else { - /* What if *keyformat is 0? We might want to do something more - * graceful here. */ - wc_falcon_free(key); - ret = ALGO_ID_E; + else if (ctx) { + ctx->privateKeyType = ed448_sa_algo; + ctx->privateKeySz = *keySz; + } + + *keyFormat = ED448k; + if (ssl != NULL) { + /* ED448 requires caching enabled for tracking message + * hash used in EdDSA_Update for signing */ + ssl->options.cacheMessages = 1; + if (ssl->options.side == WOLFSSL_SERVER_END) { + *resetSuites = 1; + } } } + wc_ed448_free(key); + } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(key, heap, DYNAMIC_TYPE_ED448); +#endif + return ret; +} +#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ + +#if defined(HAVE_PQC) +#if defined(HAVE_FALCON) +static int ProcessBufferTryDecodeFalcon(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, + void* heap) +{ + int ret; + /* make sure Falcon key can be used */ + falcon_key* key = (falcon_key*)XMALLOC(sizeof(falcon_key), heap, + DYNAMIC_TYPE_FALCON); + if (key == NULL) { + return MEMORY_E; + } + ret = wc_falcon_init(key); + if (ret == 0) { + if (*keyFormat == FALCON_LEVEL1k) { + ret = wc_falcon_set_level(key, 1); + } + else if (*keyFormat == FALCON_LEVEL5k) { + ret = wc_falcon_set_level(key, 5); + } + else { + /* What if *keyformat is 0? We might want to do something more + * graceful here. */ + wc_falcon_free(key); + ret = ALGO_ID_E; + } + } + + if (ret == 0) { + *idx = 0; + ret = wc_falcon_import_private_only(der->buffer, der->length, key); if (ret == 0) { - *idx = 0; - ret = wc_falcon_import_private_only(der->buffer, der->length, key); - if (ret == 0) { - /* check for minimum key size and then free */ - int minKeySz = ssl ? ssl->options.minFalconKeySz : - ctx->minFalconKeySz; - *keySz = FALCON_MAX_KEY_SIZE; - if (*keySz < minKeySz) { - WOLFSSL_MSG("Falcon private key too small"); - ret = FALCON_KEY_SIZE_E; + /* check for minimum key size and then free */ + int minKeySz = ssl ? ssl->options.minFalconKeySz : + ctx->minFalconKeySz; + *keySz = FALCON_MAX_KEY_SIZE; + if (*keySz < minKeySz) { + WOLFSSL_MSG("Falcon private key too small"); + ret = FALCON_KEY_SIZE_E; + } + if (ssl) { + if (*keyFormat == FALCON_LEVEL1k) { + ssl->buffers.keyType = falcon_level1_sa_algo; } - if (ssl) { - if (*keyFormat == FALCON_LEVEL1k) { - ssl->buffers.keyType = falcon_level1_sa_algo; - } - else { - ssl->buffers.keyType = falcon_level5_sa_algo; - } - ssl->buffers.keySz = *keySz; + else { + ssl->buffers.keyType = falcon_level5_sa_algo; + } + ssl->buffers.keySz = *keySz; + } + else { + if (*keyFormat == FALCON_LEVEL1k) { + ctx->privateKeyType = falcon_level1_sa_algo; } else { - if (*keyFormat == FALCON_LEVEL1k) { - ctx->privateKeyType = falcon_level1_sa_algo; - } - else { - ctx->privateKeyType = falcon_level5_sa_algo; - } - ctx->privateKeySz = *keySz; + ctx->privateKeyType = falcon_level5_sa_algo; } + ctx->privateKeySz = *keySz; + } - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } + if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { + *resetSuites = 1; } - wc_falcon_free(key); } - XFREE(key, heap, DYNAMIC_TYPE_FALCON); - if (ret != 0) - return ret; + wc_falcon_free(key); } -#endif /* HAVE_FALCON */ + XFREE(key, heap, DYNAMIC_TYPE_FALCON); + return ret; +} +#endif + #if defined(HAVE_DILITHIUM) - if ((*keyFormat == 0) || - (*keyFormat == DILITHIUM_LEVEL2k) || - (*keyFormat == DILITHIUM_LEVEL3k) || - (*keyFormat == DILITHIUM_LEVEL5k)) { - /* make sure Dilithium key can be used */ - dilithium_key* key = (dilithium_key*)XMALLOC(sizeof(dilithium_key), - heap, - DYNAMIC_TYPE_DILITHIUM); - if (key == NULL) { - return MEMORY_E; +static int ProcessBufferTryDecodeDilithium(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, + void* heap) +{ + int ret; + /* make sure Dilithium key can be used */ + dilithium_key* key = (dilithium_key*)XMALLOC(sizeof(dilithium_key), heap, + DYNAMIC_TYPE_DILITHIUM); + if (key == NULL) { + return MEMORY_E; + } + ret = wc_dilithium_init(key); + if (ret == 0) { + if (*keyFormat == DILITHIUM_LEVEL2k) { + ret = wc_dilithium_set_level(key, 2); + } + else if (*keyFormat == DILITHIUM_LEVEL3k) { + ret = wc_dilithium_set_level(key, 3); + } + else if (*keyFormat == DILITHIUM_LEVEL5k) { + ret = wc_dilithium_set_level(key, 5); + } + else { + /* What if *keyformat is 0? We might want to do something more + * graceful here. */ + wc_dilithium_free(key); + ret = ALGO_ID_E; } - ret = wc_dilithium_init(key); + } + + if (ret == 0) { + *idx = 0; + ret = wc_dilithium_import_private_only(der->buffer, der->length, key); if (ret == 0) { - if (*keyFormat == DILITHIUM_LEVEL2k) { - ret = wc_dilithium_set_level(key, 2); + /* check for minimum key size and then free */ + int minKeySz = ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz; + *keySz = DILITHIUM_MAX_KEY_SIZE; + if (*keySz < minKeySz) { + WOLFSSL_MSG("Dilithium private key too small"); + ret = DILITHIUM_KEY_SIZE_E; } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - ret = wc_dilithium_set_level(key, 3); - } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - ret = wc_dilithium_set_level(key, 5); + if (ssl) { + if (*keyFormat == DILITHIUM_LEVEL2k) { + ssl->buffers.keyType = dilithium_level2_sa_algo; + } + else if (*keyFormat == DILITHIUM_LEVEL3k) { + ssl->buffers.keyType = dilithium_level3_sa_algo; + } + else if (*keyFormat == DILITHIUM_LEVEL5k) { + ssl->buffers.keyType = dilithium_level5_sa_algo; + } + ssl->buffers.keySz = *keySz; } else { - /* What if *keyformat is 0? We might want to do something more - * graceful here. */ - wc_dilithium_free(key); - ret = ALGO_ID_E; - } - } - - if (ret == 0) { - *idx = 0; - ret = wc_dilithium_import_private_only(der->buffer, der->length, - key); - if (ret == 0) { - /* check for minimum key size and then free */ - int minKeySz = ssl ? ssl->options.minDilithiumKeySz : - ctx->minDilithiumKeySz; - *keySz = DILITHIUM_MAX_KEY_SIZE; - if (*keySz < minKeySz) { - WOLFSSL_MSG("Dilithium private key too small"); - ret = DILITHIUM_KEY_SIZE_E; + if (*keyFormat == DILITHIUM_LEVEL2k) { + ctx->privateKeyType = dilithium_level2_sa_algo; } - if (ssl) { - if (*keyFormat == DILITHIUM_LEVEL2k) { - ssl->buffers.keyType = dilithium_level2_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - ssl->buffers.keyType = dilithium_level3_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - ssl->buffers.keyType = dilithium_level5_sa_algo; - } - ssl->buffers.keySz = *keySz; + else if (*keyFormat == DILITHIUM_LEVEL3k) { + ctx->privateKeyType = dilithium_level3_sa_algo; } - else { - if (*keyFormat == DILITHIUM_LEVEL2k) { - ctx->privateKeyType = dilithium_level2_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - ctx->privateKeyType = dilithium_level3_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - ctx->privateKeyType = dilithium_level5_sa_algo; - } - ctx->privateKeySz = *keySz; + else if (*keyFormat == DILITHIUM_LEVEL5k) { + ctx->privateKeyType = dilithium_level5_sa_algo; } + ctx->privateKeySz = *keySz; + } - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } + if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { + *resetSuites = 1; } - wc_dilithium_free(key); } - XFREE(key, heap, DYNAMIC_TYPE_DILITHIUM); + wc_dilithium_free(key); + } + XFREE(key, heap, DYNAMIC_TYPE_DILITHIUM); + + return ret; +} +#endif /* HAVE_DILITHIUM */ +#endif /* HAVE_PQC */ + +static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, + void* heap, int devId) +{ + int ret = 0; + + (void)heap; + (void)devId; + + if (ctx == NULL && ssl == NULL) + return BAD_FUNC_ARG; + if (!der || !keySz || !idx || !resetSuites || !keyFormat) + return BAD_FUNC_ARG; + +#ifndef NO_RSA + if ((*keyFormat == 0 || *keyFormat == RSAk)) { +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION > 2)) + ret = ProcessBufferTryDecodeRsa(ctx, ssl, der, keySz, idx, resetSuites, + keyFormat, devId); +#else + ret = ProcessBufferTryDecodeRsa(ctx, ssl, der, keySz, idx, resetSuites, + keyFormat, heap, devId); +#endif + if (ret != 0) + return ret; + } +#endif +#ifdef HAVE_ECC + if ((*keyFormat == 0 || *keyFormat == ECDSAk)) { + ret = ProcessBufferTryDecodeEcc(ctx, ssl, der, keySz, idx, resetSuites, + keyFormat, heap, devId); + if (ret != 0) + return ret; + } +#endif /* HAVE_ECC */ +#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) + if ((*keyFormat == 0 || *keyFormat == ED25519k)) { + ret = ProcessBufferTryDecodeEd25519(ctx, ssl, der, keySz, idx, + resetSuites, keyFormat, heap, devId); + if (ret != 0) + return ret; + } +#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */ +#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) + if ((*keyFormat == 0 || *keyFormat == ED448k)) { + ret = ProcessBufferTryDecodeEd448(ctx, ssl, der, keySz, idx, + resetSuites, keyFormat, heap, devId); + if (ret != 0) + return ret; + } +#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ +#if defined(HAVE_PQC) +#if defined(HAVE_FALCON) + if (((*keyFormat == 0) || (*keyFormat == FALCON_LEVEL1k) || + (*keyFormat == FALCON_LEVEL5k))) { + ret = ProcessBufferTryDecodeFalcon(ctx, ssl, der, keySz, idx, + resetSuites, keyFormat, heap); + if (ret != 0) + return ret; + } +#endif /* HAVE_FALCON */ +#if defined(HAVE_DILITHIUM) + if ((*keyFormat == 0) || + (*keyFormat == DILITHIUM_LEVEL2k) || + (*keyFormat == DILITHIUM_LEVEL3k) || + (*keyFormat == DILITHIUM_LEVEL5k)) { + ret = ProcessBufferTryDecodeDilithium(ctx, ssl, der, keySz, idx, + resetSuites, keyFormat, heap); if (ret != 0) { return ret; } diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 9875f5d3243..2f16c6265dd 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -3273,8 +3273,6 @@ static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx, #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */ #ifndef WOLFSSL_ASN_TEMPLATE -#if (!defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)) \ - || defined(WOLFSSL_RSA_PUBLIC_ONLY) || (!defined(NO_DSA)) #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA) static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx) { @@ -3291,7 +3289,6 @@ static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx) return 0; } #endif -#endif #endif /* !WOLFSSL_ASN_TEMPLATE */ #ifdef WOLFSSL_ASN_TEMPLATE @@ -6350,9 +6347,12 @@ enum { * @param [in] input Buffer holding BER encoded data. * @param [in, out] inOutIdx On in, start of RSA private key. * On out, start of ASN.1 item after RSA private key. - * @param [in, out] key RSA key object. + * @param [in, out] key RSA key object. May be NULL. + * @param [out] keySz Size of key in bytes. May be NULL. * @param [in] inSz Number of bytes in buffer. * @return 0 on success. + * @return BAD_FUNC_ARG when input or inOutIdx is NULL. + * @return BAD_FUNC_ARG when key and keySz are NULL. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or * is invalid. * @return BUFFER_E when data in buffer is too small. @@ -6361,14 +6361,14 @@ enum { * @return MP_INIT_E when the unable to initialize an mp_int. * @return ASN_GETINT_E when the unable to convert data to an mp_int. */ -int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, - word32 inSz) +static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, + RsaKey* key, int* keySz, word32 inSz) { #ifndef WOLFSSL_ASN_TEMPLATE int version, length; word32 algId = 0; - if (inOutIdx == NULL || input == NULL || key == NULL) { + if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) { return BAD_FUNC_ARG; } @@ -6383,50 +6383,66 @@ int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, if (GetMyVersion(input, inOutIdx, &version, inSz) < 0) return ASN_PARSE_E; - key->type = RSA_PRIVATE; + if (key == NULL) { + int i; -#ifdef WOLFSSL_CHECK_MEM_ZERO - mp_memzero_add("Decode RSA key d", &key->d); - mp_memzero_add("Decode RSA key p", &key->p); - mp_memzero_add("Decode RSA key q", &key->q); -#if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \ - !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) - mp_memzero_add("Decode RSA key dP", &key->dP); - mp_memzero_add("Decode RSA key dQ", &key->dQ); - mp_memzero_add("Decode RSA key u", &key->u); -#endif -#endif + /* Modulus */ + if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) { + return ASN_PARSE_E; + } + *inOutIdx += *keySz; + for (i = 1; i < RSA_INTS; i++) { + if (SkipInt(input, inOutIdx, inSz) < 0) { + return ASN_RSA_KEY_E; + } + } + } + else { + key->type = RSA_PRIVATE; - if (GetInt(&key->n, input, inOutIdx, inSz) < 0 || - GetInt(&key->e, input, inOutIdx, inSz) < 0 || -#ifndef WOLFSSL_RSA_PUBLIC_ONLY - GetInt(&key->d, input, inOutIdx, inSz) < 0 || - GetInt(&key->p, input, inOutIdx, inSz) < 0 || - GetInt(&key->q, input, inOutIdx, inSz) < 0 -#else - SkipInt(input, inOutIdx, inSz) < 0 || - SkipInt(input, inOutIdx, inSz) < 0 || - SkipInt(input, inOutIdx, inSz) < 0 -#endif - ) { - return ASN_RSA_KEY_E; - } -#if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \ - && !defined(WOLFSSL_RSA_PUBLIC_ONLY) - if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 || - GetInt(&key->dQ, input, inOutIdx, inSz) < 0 || - GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E; -#else - if (SkipInt(input, inOutIdx, inSz) < 0 || - SkipInt(input, inOutIdx, inSz) < 0 || - SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E; -#endif + #ifdef WOLFSSL_CHECK_MEM_ZERO + mp_memzero_add("Decode RSA key d", &key->d); + mp_memzero_add("Decode RSA key p", &key->p); + mp_memzero_add("Decode RSA key q", &key->q); + #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \ + !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) + mp_memzero_add("Decode RSA key dP", &key->dP); + mp_memzero_add("Decode RSA key dQ", &key->dQ); + mp_memzero_add("Decode RSA key u", &key->u); + #endif + #endif -#if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL) - if (wc_InitRsaHw(key) != 0) { - return BAD_STATE_E; + if (GetInt(&key->n, input, inOutIdx, inSz) < 0 || + GetInt(&key->e, input, inOutIdx, inSz) < 0 || + #ifndef WOLFSSL_RSA_PUBLIC_ONLY + GetInt(&key->d, input, inOutIdx, inSz) < 0 || + GetInt(&key->p, input, inOutIdx, inSz) < 0 || + GetInt(&key->q, input, inOutIdx, inSz) < 0 + #else + SkipInt(input, inOutIdx, inSz) < 0 || + SkipInt(input, inOutIdx, inSz) < 0 || + SkipInt(input, inOutIdx, inSz) < 0 + #endif + ) { + return ASN_RSA_KEY_E; + } + #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \ + && !defined(WOLFSSL_RSA_PUBLIC_ONLY) + if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 || + GetInt(&key->dQ, input, inOutIdx, inSz) < 0 || + GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E; + #else + if (SkipInt(input, inOutIdx, inSz) < 0 || + SkipInt(input, inOutIdx, inSz) < 0 || + SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E; + #endif + + #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL) + if (wc_InitRsaHw(key) != 0) { + return BAD_STATE_E; + } + #endif } -#endif return 0; #else @@ -6436,12 +6452,20 @@ int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) word32 algId = 0; #endif + void* heap = NULL; + + (void)heap; /* Check validity of parameters. */ - if (inOutIdx == NULL || input == NULL || key == NULL) { + if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) && + (keySz == NULL))) { ret = BAD_FUNC_ARG; } + if ((ret == 0) && (key != NULL)) { + heap = key->heap; + } + #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) if (ret == 0) { /* if has pkcs8 header skip it */ @@ -6451,7 +6475,7 @@ int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, } #endif - CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, key->heap); + CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap); if (ret == 0) { int i; @@ -6459,20 +6483,21 @@ int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version); /* Setup data to store INTEGER data in mp_int's in RSA object. */ #if defined(WOLFSSL_RSA_PUBLIC_ONLY) - /* Extract all public fields. */ - for (i = 0; i < RSA_PUB_INTS; i++) { - GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i)); - } + #define RSA_ASN_INTS RSA_PUB_INTS /* Not extracting all data from BER encoding. */ #define RSA_ASN_COMPLETE 0 #else - /* Extract all private fields. */ - for (i = 0; i < RSA_INTS; i++) { - GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i)); - } + #define RSA_ASN_INTS RSA_INTS /* Extracting all data from BER encoding. */ #define RSA_ASN_COMPLETE 1 #endif + if (key != NULL) { + /* Extract all public fields. */ + for (i = 0; i < RSA_ASN_INTS; i++) { + GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], + GetRsaInt(key, i)); + } + } /* Parse BER encoding for RSA private key. */ ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, RSA_ASN_COMPLETE, input, inOutIdx, inSz); @@ -6484,7 +6509,7 @@ int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, if ((ret == 0) && (version > PKCS1v1)) { ret = ASN_PARSE_E; } - if (ret == 0) { + if ((ret == 0) && (key != NULL)) { #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) /* RSA key object has all private key values. */ key->type = RSA_PRIVATE; @@ -6498,11 +6523,78 @@ int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, ret = BAD_STATE_E; #endif } + else if (ret == 0) { + /* Not filling in key but do want key size. */ + *keySz = dataASN[(byte)RSAKEYASN_IDX_N].length; + /* Check whether first byte of data is 0x00 and drop it. */ + if (input[dataASN[(byte)RSAKEYASN_IDX_E].offset - *keySz] == 0) { + (*keySz)--; + } + } - FREE_ASNGETDATA(dataASN, key->heap); + FREE_ASNGETDATA(dataASN, heap); return ret; #endif /* WOLFSSL_ASN_TEMPLATE */ } + +/* Decode RSA private key. + * + * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey + * + * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields + * being extracted. + * + * @param [in] input Buffer holding BER encoded data. + * @param [in, out] inOutIdx On in, start of RSA private key. + * On out, start of ASN.1 item after RSA private key. + * @param [in, out] key RSA key object. + * @param [in] inSz Number of bytes in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL. + * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or + * is invalid. + * @return BUFFER_E when data in buffer is too small. + * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a + * non-zero length. + * @return MP_INIT_E when the unable to initialize an mp_int. + * @return ASN_GETINT_E when the unable to convert data to an mp_int. + */ +int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, + word32 inSz) +{ + if (key == NULL) { + return BAD_FUNC_ARG; + } + return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz); +} + +/* Valdidate RSA private key ASN.1 encoding. + * + * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey + * + * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields + * being extracted. + * + * @param [in] input Buffer holding BER encoded data. + * @param [in, out] inOutIdx On in, start of RSA private key. + * On out, start of ASN.1 item after RSA private key. + * @param [in] inSz Number of bytes in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL. + * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or + * is invalid. + * @return BUFFER_E when data in buffer is too small. + * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a + * non-zero length. + * @return MP_INIT_E when the unable to initialize an mp_int. + * @return ASN_GETINT_E when the unable to convert data to an mp_int. + */ +int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz, + word32 inSz) +{ + return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz); +} + #endif /* HAVE_USER_RSA */ #endif /* NO_RSA */ @@ -31177,14 +31269,17 @@ static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz, /* Allocate a new parameter set. */ curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap, DYNAMIC_TYPE_ECC_BUFFER); - if (curve == NULL) + if (curve == NULL) { ret = MEMORY_E; + } + else { + /* Clear out parameters and set fields to indicate it is custom. */ + XMEMSET(curve, 0, sizeof(*curve)); + } CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap); if (ret == 0) { - /* Clear out parameters and set fields to indicate it is custom. */ - XMEMSET(curve, 0, sizeof(*curve)); /* Set name to be: "Custom" */ #ifndef WOLFSSL_ECC_CURVE_STATIC curve->name = ecSetCustomName; diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 5a6ac716241..3003443ae5b 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -222,6 +222,15 @@ ECC Curve Sizes: #define HAVE_ECC_MAKE_PUB #endif +#if defined(WOLFSSL_SP_MATH_ALL) && SP_INT_BITS < MAX_ECC_BITS_NEEDED +#define MAX_ECC_BITS_USE SP_INT_BITS +#else +#define MAX_ECC_BITS_USE MAX_ECC_BITS_NEEDED +#endif +#define ECC_KEY_MAX_BITS(key) \ + (((key == NULL) || (key->dp == NULL)) ? MAX_ECC_BITS_USE \ + : (key->dp->size * 8)) + /* forward declarations */ static int wc_ecc_new_point_ex(ecc_point** point, void* heap); static void wc_ecc_del_point_ex(ecc_point* p, void* heap); @@ -1305,8 +1314,12 @@ typedef struct ecc_curve_spec { mp_int order_lcl; mp_int Gx_lcl; mp_int Gy_lcl; +#else +#ifdef WOLFSSL_SP_MATH_ALL + unsigned char* spec_ints; #else mp_int* spec_ints; +#endif word32 spec_count; word32 spec_use; #endif @@ -1390,6 +1403,23 @@ static int xil_mpi_import(mp_int *mpi, #define ALLOC_CURVE_SPECS(intcount, err) #define FREE_CURVE_SPECS() #elif defined(WOLFSSL_SMALL_STACK) +#ifdef WOLFSSL_SP_MATH_ALL + #define DECLARE_CURVE_SPECS(intcount) \ + unsigned char* spec_ints = NULL; \ + ecc_curve_spec curve_lcl; \ + ecc_curve_spec* curve = &curve_lcl; \ + XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \ + curve->spec_count = intcount + + #define ALLOC_CURVE_SPECS(intcount, err) \ + spec_ints = (unsigned char*)XMALLOC(MP_INT_SIZEOF(MP_BITS_CNT( \ + MAX_ECC_BITS_USE)) * (intcount), NULL, \ + DYNAMIC_TYPE_ECC); \ + if (spec_ints == NULL) \ + (err) = MEMORY_E; \ + else \ + curve->spec_ints = spec_ints +#else #define DECLARE_CURVE_SPECS(intcount) \ mp_int* spec_ints = NULL; \ ecc_curve_spec curve_lcl; \ @@ -1404,16 +1434,28 @@ static int xil_mpi_import(mp_int *mpi, (err) = MEMORY_E; \ else \ curve->spec_ints = spec_ints +#endif #define FREE_CURVE_SPECS() \ XFREE(spec_ints, NULL, DYNAMIC_TYPE_ECC) #else - #define DECLARE_CURVE_SPECS(intcount) \ - mp_int spec_ints[(intcount)]; \ - ecc_curve_spec curve_lcl; \ - ecc_curve_spec* curve = &curve_lcl; \ - XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \ - curve->spec_ints = spec_ints; \ +#ifdef WOLFSSL_SP_MATH_ALL + #define DECLARE_CURVE_SPECS(intcount) \ + unsigned char spec_ints[MP_INT_SIZEOF(MP_BITS_CNT( \ + MAX_ECC_BITS_USE)) * intcount]; \ + ecc_curve_spec curve_lcl; \ + ecc_curve_spec* curve = &curve_lcl; \ + XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \ + curve->spec_ints = spec_ints; \ + curve->spec_count = (intcount) +#else + #define DECLARE_CURVE_SPECS(intcount) \ + mp_int spec_ints[(intcount)]; \ + ecc_curve_spec curve_lcl; \ + ecc_curve_spec* curve = &curve_lcl; \ + XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \ + curve->spec_ints = spec_ints; \ curve->spec_count = (intcount) +#endif #define ALLOC_CURVE_SPECS(intcount, err) #define FREE_CURVE_SPECS() #endif /* ECC_CACHE_CURVE */ @@ -1481,10 +1523,19 @@ static int wc_ecc_curve_cache_load_item(ecc_curve_spec* curve, const char* src, WOLFSSL_MSG("Invalid DECLARE_CURVE_SPECS count"); return ECC_BAD_ARG_E; } +#ifdef WOLFSSL_SP_MATH_ALL + *dst = (mp_int*)(curve->spec_ints + MP_INT_SIZEOF(MP_BITS_CNT( + MAX_ECC_BITS_USE)) * curve->spec_use++); +#else *dst = &curve->spec_ints[curve->spec_use++]; #endif +#endif +#ifdef WOLFSSL_SP_MATH_ALL + err = mp_init_size(*dst, MP_BITS_CNT(MAX_ECC_BITS_USE)); +#else err = mp_init(*dst); +#endif if (err == MP_OKAY) { curve->load_mask |= mask; @@ -1725,19 +1776,12 @@ static int _ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R, mp_int* a, mp_int* modulus, mp_digit mp) { #if !defined(WOLFSSL_SP_MATH) -#ifdef WOLFSSL_SMALL_STACK - mp_int* t1 = NULL; - mp_int* t2 = NULL; -#ifdef ALT_ECC_SIZE - mp_int* rx = NULL; - mp_int* ry = NULL; - mp_int* rz = NULL; -#endif -#else - mp_int t1[1], t2[1]; + DECL_MP_INT_SIZE_DYN(t1, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(t2, mp_bitsused(modulus), MAX_ECC_BITS_USE); #ifdef ALT_ECC_SIZE - mp_int rx[1], ry[1], rz[1]; -#endif + DECL_MP_INT_SIZE_DYN(rx, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(ry, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(rz, mp_bitsused(modulus), MAX_ECC_BITS_USE); #endif mp_int *x, *y, *z; int err; @@ -1762,78 +1806,86 @@ static int _ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R, } else #endif /* WOLFSSL_SMALL_STACK_CACHE */ +#endif /* WOLFSSL_SMALL_STACK */ { - t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - if (t1 == NULL || t2 == NULL) { - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - return MEMORY_E; - } + NEW_MP_INT_SIZE(t1, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(t2, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL + if (t1 == NULL || t2 == NULL) { + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + return MEMORY_E; + } + #endif #ifdef ALT_ECC_SIZE - rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - if (rx == NULL || ry == NULL || rz == NULL) { - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - return MEMORY_E; - } + NEW_MP_INT_SIZE(rx, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(ry, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(rz, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL + if (rx == NULL || ry == NULL || rz == NULL) { + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + return MEMORY_E; + } + #endif #endif } -#endif /* WOLFSSL_SMALL_STACK */ - if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { + err = INIT_MP_INT_SIZE(t1, mp_bitsused(modulus)); + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(t2, mp_bitsused(modulus)); + } + if (err != MP_OKAY) { #ifdef WOLFSSL_SMALL_STACK #ifdef WOLFSSL_SMALL_STACK_CACHE - if (R->key == NULL) + if (R->key == NULL) #endif - { - #ifdef ALT_ECC_SIZE - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); - #endif - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - } #endif + { + #ifdef ALT_ECC_SIZE + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); + #endif + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + } return err; } /* should we dbl instead? */ if (err == MP_OKAY) { #ifdef ECC_TIMING_RESISTANT - err = mp_submod_ct(modulus, Q->y, modulus, t1); + err = mp_submod_ct(modulus, Q->y, modulus, t1); #else - err = mp_sub(modulus, Q->y, t1); + err = mp_sub(modulus, Q->y, t1); #endif } if (err == MP_OKAY) { - if ( (mp_cmp(P->x, Q->x) == MP_EQ) && - (get_digit_count(Q->z) && mp_cmp(P->z, Q->z) == MP_EQ) && - (mp_cmp(P->y, Q->y) == MP_EQ || mp_cmp(P->y, t1) == MP_EQ)) { - mp_clear(t1); - mp_clear(t2); - #ifdef WOLFSSL_SMALL_STACK - #ifdef WOLFSSL_SMALL_STACK_CACHE - if (R->key == NULL) - #endif - { - #ifdef ALT_ECC_SIZE - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); - #endif - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - } - #endif - return _ecc_projective_dbl_point(P, R, a, modulus, mp); - } + if ( (mp_cmp(P->x, Q->x) == MP_EQ) && + (get_digit_count(Q->z) && mp_cmp(P->z, Q->z) == MP_EQ) && + (mp_cmp(P->y, Q->y) == MP_EQ || mp_cmp(P->y, t1) == MP_EQ)) { + mp_clear(t1); + mp_clear(t2); + #ifdef WOLFSSL_SMALL_STACK + #ifdef WOLFSSL_SMALL_STACK_CACHE + if (R->key == NULL) + #endif + #endif + { + #ifdef ALT_ECC_SIZE + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); + #endif + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + } + return _ecc_projective_dbl_point(P, R, a, modulus, mp); + } } if (err != MP_OKAY) { @@ -1848,7 +1900,14 @@ static int _ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R, y = ry; z = rz; - if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { + err = INIT_MP_INT_SIZE(x, mp_bitsused(modulus)); + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(y, mp_bitsused(modulus)); + } + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(z, mp_bitsused(modulus)); + } + if (err != MP_OKAY) { goto done; } #else @@ -2020,17 +2079,17 @@ static int _ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R, #ifdef WOLFSSL_SMALL_STACK #ifdef WOLFSSL_SMALL_STACK_CACHE if (R->key == NULL) +#endif #endif { #ifdef ALT_ECC_SIZE - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); #endif - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); } -#endif return err; #else @@ -2111,19 +2170,12 @@ static int _ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, mp_int* modulus, mp_digit mp) { #if !defined(WOLFSSL_SP_MATH) -#ifdef WOLFSSL_SMALL_STACK - mp_int* t1 = NULL; - mp_int* t2 = NULL; -#ifdef ALT_ECC_SIZE - mp_int* rx = NULL; - mp_int* ry = NULL; - mp_int* rz = NULL; -#endif -#else - mp_int t1[1], t2[1]; + DECL_MP_INT_SIZE_DYN(t1, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(t2, mp_bitsused(modulus), MAX_ECC_BITS_USE); #ifdef ALT_ECC_SIZE - mp_int rx[1], ry[1], rz[1]; -#endif + DECL_MP_INT_SIZE_DYN(rx, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(ry, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(rz, mp_bitsused(modulus), MAX_ECC_BITS_USE); #endif mp_int *x, *y, *z; int err; @@ -2141,45 +2193,53 @@ static int _ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, } else #endif /* WOLFSSL_SMALL_STACK_CACHE */ - { - t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - if (t1 == NULL || t2 == NULL) { - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - return MEMORY_E; - } - #ifdef ALT_ECC_SIZE - rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - if (rx == NULL || ry == NULL || rz == NULL) { - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - return MEMORY_E; - } - #endif - } #endif + { + NEW_MP_INT_SIZE(t1, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(t2, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL + if (t1 == NULL || t2 == NULL) { + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + return MEMORY_E; + } + #endif + #ifdef ALT_ECC_SIZE + NEW_MP_INT_SIZE(rx, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(ry, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(rz, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL + if (rx == NULL || ry == NULL || rz == NULL) { + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + return MEMORY_E; + } + #endif + #endif + } - if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { + err = INIT_MP_INT_SIZE(t1, mp_bitsused(modulus)); + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(t2, mp_bitsused(modulus)); + } + if (err != MP_OKAY) { #ifdef WOLFSSL_SMALL_STACK -#ifdef WOLFSSL_SMALL_STACK_CACHE - if (R->key == NULL) -#endif - { - #ifdef ALT_ECC_SIZE - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); - #endif - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - } + #ifdef WOLFSSL_SMALL_STACK_CACHE + if (R->key == NULL) + #endif #endif + { + #ifdef ALT_ECC_SIZE + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); + #endif + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + } return err; } @@ -2191,24 +2251,29 @@ static int _ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, y = ry; z = rz; - if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { - mp_clear(t1); - mp_clear(t2); - #ifdef WOLFSSL_SMALL_STACK - #ifdef WOLFSSL_SMALL_STACK_CACHE - if (R->key == NULL) - #endif - { - #ifdef ALT_ECC_SIZE - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); - #endif - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - } - #endif - return err; + err = INIT_MP_INT_SIZE(x, mp_bitsused(modulus)); + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(y, mp_bitsused(modulus)); + } + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(z, mp_bitsused(modulus)); + } + if (err != MP_OKAY) { +#ifdef WOLFSSL_SMALL_STACK + #ifdef WOLFSSL_SMALL_STACK_CACHE + if (R->key == NULL) + #endif +#endif + { + #ifdef ALT_ECC_SIZE + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); + #endif + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + } + return err; } #else /* Use destination directly */ @@ -2246,7 +2311,7 @@ static int _ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, /* Use a and prime to determine if a == 3 */ err = mp_submod(modulus, a, modulus, t2); } - if (err == MP_OKAY && mp_iszero(t2)) { + if (err == MP_OKAY && mp_iszero((MP_INT_SIZE*)t2)) { /* T2 = X * X */ if (err == MP_OKAY) err = mp_sqr(x, t2); @@ -2378,17 +2443,17 @@ static int _ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, #ifdef WOLFSSL_SMALL_STACK #ifdef WOLFSSL_SMALL_STACK_CACHE if (R->key == NULL) +#endif #endif { #ifdef ALT_ECC_SIZE - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); #endif - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); } -#endif return err; #else @@ -2446,20 +2511,13 @@ int ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) { #if !defined(WOLFSSL_SP_MATH) -#ifdef WOLFSSL_SMALL_STACK - mp_int* t1 = NULL; - mp_int* t2 = NULL; -#ifdef ALT_ECC_SIZE - mp_int* rx = NULL; - mp_int* ry = NULL; - mp_int* rz = NULL; -#endif -#else - mp_int t1[1], t2[1]; + DECL_MP_INT_SIZE_DYN(t1, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(t2, mp_bitsused(modulus), MAX_ECC_BITS_USE); #ifdef ALT_ECC_SIZE - mp_int rx[1], ry[1], rz[1]; + DECL_MP_INT_SIZE_DYN(rx, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(ry, mp_bitsused(modulus), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(rz, mp_bitsused(modulus), MAX_ECC_BITS_USE); #endif -#endif /* WOLFSSL_SMALL_STACK */ mp_int *x, *y, *z; int err; @@ -2491,45 +2549,53 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) } else #endif /* WOLFSSL_SMALL_STACK_CACHE */ - { - t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - if (t1 == NULL || t2 == NULL) { - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - return MEMORY_E; - } -#ifdef ALT_ECC_SIZE - rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); - if (rx == NULL || ry == NULL || rz == NULL) { - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); - return MEMORY_E; - } #endif + { + NEW_MP_INT_SIZE(t1, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(t2, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL + if (t1 == NULL || t2 == NULL) { + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + return MEMORY_E; + } + #endif + #ifdef ALT_ECC_SIZE + NEW_MP_INT_SIZE(rx, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(ry, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(rz, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL + if (rx == NULL || ry == NULL || rz == NULL) { + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); + return MEMORY_E; + } + #endif + #endif } -#endif /* WOLFSSL_SMALL_STACK */ - if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { + err = INIT_MP_INT_SIZE(t1, mp_bitsused(modulus)); + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(t2, mp_bitsused(modulus)); + } + if (err != MP_OKAY) { #ifdef WOLFSSL_SMALL_STACK -#ifdef WOLFSSL_SMALL_STACK_CACHE + #ifdef WOLFSSL_SMALL_STACK_CACHE if (P->key == NULL) + #endif #endif { #ifdef ALT_ECC_SIZE - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); #endif - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); } -#endif return MEMORY_E; } @@ -2539,16 +2605,23 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) y = ry; z = rz; - if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { - goto done; + err = INIT_MP_INT_SIZE(x, mp_bitsused(modulus)); + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(y, mp_bitsused(modulus)); + } + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(z, mp_bitsused(modulus)); + } + if (err != MP_OKAY) { + goto done; } if (err == MP_OKAY) - err = mp_copy(P->x, x); + err = mp_copy(P->x, x); if (err == MP_OKAY) - err = mp_copy(P->y, y); + err = mp_copy(P->y, y); if (err == MP_OKAY) - err = mp_copy(P->z, z); + err = mp_copy(P->z, z); if (err != MP_OKAY) { goto done; @@ -2621,17 +2694,17 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) #ifdef WOLFSSL_SMALL_STACK #ifdef WOLFSSL_SMALL_STACK_CACHE if (P->key == NULL) +#endif #endif { #ifdef ALT_ECC_SIZE - XFREE(rz, NULL, DYNAMIC_TYPE_ECC); - XFREE(ry, NULL, DYNAMIC_TYPE_ECC); - XFREE(rx, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rz, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(ry, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(rx, NULL, DYNAMIC_TYPE_ECC); #endif - XFREE(t2, NULL, DYNAMIC_TYPE_ECC); - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t2, NULL, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(t1, NULL, DYNAMIC_TYPE_ECC); } -#endif return err; #else @@ -2823,24 +2896,20 @@ static int ecc_mulmod(const mp_int* k, ecc_point* tG, ecc_point* R, #else -static int wc_ecc_gen_z(WC_RNG* rng, int size, ecc_point* p, - mp_int* modulus, mp_digit mp, mp_int* tx, mp_int* ty) +static int wc_ecc_gen_z(WC_RNG* rng, int size, ecc_point* p, mp_int* modulus, + mp_digit mp, mp_int* tx, mp_int* ty) { int err = MP_OKAY; -#ifdef WOLFSSL_SMALL_STACK - mp_int* mu = NULL; -#else - mp_int mu[1]; -#endif + DECL_MP_INT_SIZE_DYN(mu, mp_bitsused(modulus), MAX_ECC_BITS_USE); -#ifdef WOLFSSL_SMALL_STACK - mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(mu, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL if (mu == NULL) err = MEMORY_E; #endif if (err == MP_OKAY) - err = mp_init(mu); + err = INIT_MP_INT_SIZE(mu, mp_bitsused(modulus)); if (err == MP_OKAY) err = mp_montgomery_calc_normalization(mu, modulus); /* Generate random value to multiply into p->z. */ @@ -2875,14 +2944,8 @@ static int wc_ecc_gen_z(WC_RNG* rng, int size, ecc_point* p, if (err == MP_OKAY) err = mp_montgomery_reduce(p->y, modulus, mp); -#ifdef WOLFSSL_SMALL_STACK - if (mu != NULL) { - mp_clear(mu); - XFREE(mu, NULL, DYNAMIC_TYPE_ECC); - } -#else mp_clear(mu); -#endif + FREE_MP_INT_SIZE(mu, NULL, DYNAMIC_TYPE_ECC); return err; } @@ -3251,21 +3314,17 @@ static int ecc_point_to_mont(ecc_point* p, ecc_point* r, mp_int* modulus, void* heap) { int err = MP_OKAY; -#ifdef WOLFSSL_SMALL_STACK - mp_int* mu = NULL; -#else - mp_int mu[1]; -#endif + DECL_MP_INT_SIZE_DYN(mu, mp_bitsused(modulus), MAX_ECC_BITS_USE); (void)heap; -#ifdef WOLFSSL_SMALL_STACK - mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(mu, mp_bitsused(modulus), heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL if (mu == NULL) err = MEMORY_E; #endif if (err == MP_OKAY) - err = mp_init(mu); + err = INIT_MP_INT_SIZE(mu, mp_bitsused(modulus)); if (err == MP_OKAY) { err = mp_montgomery_calc_normalization(mu, modulus); @@ -3288,10 +3347,8 @@ static int ecc_point_to_mont(ecc_point* p, ecc_point* r, mp_int* modulus, mp_clear(mu); } -#ifdef WOLFSSL_SMALL_STACK - if (mu != NULL) - XFREE(mu, heap, DYNAMIC_TYPE_ECC); -#endif + + FREE_MP_INT_SIZE(mu, heap, DYNAMIC_TYPE_ECC); return err; } @@ -3504,6 +3561,53 @@ int wc_ecc_mulmod_ex(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, #endif /* !WOLFSSL_SP_MATH || !FP_ECC */ #ifndef FP_ECC +#if !defined(WOLFSSL_SP_MATH) +#ifdef ECC_TIMING_RESISTANT +static int ecc_check_order_minus_1(const mp_int* k, ecc_point* tG, ecc_point* R, + mp_int* modulus, mp_int* order) +{ + int err; + DECL_MP_INT_SIZE_DYN(t, mp_bitsused(order), MAX_ECC_BITS_USE); + + NEW_MP_INT_SIZE(t, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL + if (t == NULL) { + err = MEMORY_E; + } + else +#endif + { + err = INIT_MP_INT_SIZE(t, mp_bitsused(modulus)); + } + if (err == MP_OKAY) { + /* Check for k == order - 1. Result will be 0 point which is not correct + * Calculates order / 2 and adds order / 2 + 1 and gets infinity. + * (with constant time implementation) + */ + err = mp_sub_d(order, 1, t); + if (err == MP_OKAY) { + int kIsMinusOne = (mp_cmp((mp_int*)k, t) == MP_EQ); + err = mp_cond_copy(tG->x, kIsMinusOne, R->x); + if (err == MP_OKAY) { + err = mp_sub(modulus, tG->y, t); + } + if (err == MP_OKAY) { + err = mp_cond_copy(t, kIsMinusOne, R->y); + } + if (err == MP_OKAY) { + err = mp_cond_copy(tG->z, kIsMinusOne, R->z); + } + } + + mp_free(t); + } + + FREE_MP_INT_SIZE(t, NULL, DYNAMIC_TYPE_ECC); + return err; +} +#endif /* ECC_TIMING_RESISTANT */ +#endif + /** Perform a point multiplication k The scalar to multiply by @@ -3515,7 +3619,7 @@ int wc_ecc_mulmod_ex(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, (1==map, 0 == leave in projective) return MP_OKAY on success */ -int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, +int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point* G, ecc_point* R, mp_int* a, mp_int* modulus, mp_int* order, WC_RNG* rng, int map, void* heap) #if !defined(WOLFSSL_SP_MATH) @@ -3529,9 +3633,6 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, ecc_key key; #endif mp_digit mp; -#ifdef ECC_TIMING_RESISTANT - mp_int t; -#endif if (k == NULL || G == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; @@ -3592,37 +3693,12 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, goto exit; } + err = ecc_mulmod(k, tG, R, M, a, modulus, mp, rng); #ifdef ECC_TIMING_RESISTANT - if ((err = mp_init(&t)) != MP_OKAY) - goto exit; - - if (err == MP_OKAY) - err = ecc_mulmod(k, tG, R, M, a, modulus, mp, rng); - - /* Check for k == order - 1. Result will be 0 point which is not correct - * Calculates order / 2 and adds order / 2 + 1 and gets infinity. - * (with constant time implementation) - */ - if (err == MP_OKAY) - err = mp_sub_d(order, 1, &t); if (err == MP_OKAY) { - int kIsMinusOne = (mp_cmp((mp_int*)k, &t) == MP_EQ); - err = mp_cond_copy(tG->x, kIsMinusOne, R->x); - if (err == MP_OKAY) { - err = mp_sub(modulus, tG->y, &t); - } - if (err == MP_OKAY) { - err = mp_cond_copy(&t, kIsMinusOne, R->y); - } - if (err == MP_OKAY) { - err = mp_cond_copy(tG->z, kIsMinusOne, R->z); - } + err = ecc_check_order_minus_1(k, tG, R, modulus, order); } - - mp_free(&t); #else - err = ecc_mulmod(k, tG, R, M, a, modulus, mp, rng); - (void)order; #endif /* map R back from projective space */ @@ -4954,7 +5030,7 @@ static WC_INLINE void wc_ecc_reset(ecc_key* key) /* create the public ECC key from a private key * * key an initialized private key to generate public part from - * curveIn [in]curve for key, can be NULL + * curve [in]curve for key, cannot be NULL * pubOut [out]ecc_point holding the public key, if NULL then public key part * is cached in key instead. * @@ -4966,13 +5042,12 @@ static WC_INLINE void wc_ecc_reset(ecc_key* key) * * returns MP_OKAY on success */ -static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn, +static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, ecc_point* pubOut, WC_RNG* rng) { int err = MP_OKAY; #ifdef HAVE_ECC_MAKE_PUB ecc_point* pub; - DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); #endif /* HAVE_ECC_MAKE_PUB */ (void)rng; @@ -4995,24 +5070,10 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn, key->type = ECC_PRIVATEKEY_ONLY; } - /* avoid loading the curve unless it is not passed in */ - if (curveIn != NULL) { - curve = curveIn; - } - else { - /* load curve info */ - if (err == MP_OKAY) { - ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); - } - if (err == MP_OKAY) { - err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); - } - } - - if ((err == MP_OKAY) && (mp_iszero(&key->k) || mp_isneg(&key->k) || - (mp_cmp(&key->k, curve->order) != MP_LT))) - { - err = ECC_PRIV_KEY_E; + if ((err == MP_OKAY) && (mp_iszero(&key->k) || mp_isneg(&key->k) || + (mp_cmp(&key->k, curve->order) != MP_LT))) + { + err = ECC_PRIV_KEY_E; } if (err == MP_OKAY) { @@ -5125,15 +5186,9 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn, #endif } - /* free up local curve */ - if (curveIn == NULL) { - wc_ecc_curve_free(curve); - FREE_CURVE_SPECS(); - } - #else /* Using hardware crypto, that does not support ecc_make_pub_ex */ - (void)curveIn; + (void)curve; err = NOT_COMPILED_IN; #endif /* HAVE_ECC_MAKE_PUB */ @@ -5161,7 +5216,7 @@ int wc_ecc_make_pub(ecc_key* key, ecc_point* pubOut) { WOLFSSL_ENTER("wc_ecc_make_pub"); - return ecc_make_pub_ex(key, NULL, pubOut, NULL); + return wc_ecc_make_pub_ex(key, pubOut, NULL); } /* create the public ECC key from a private key - mask timing use random z @@ -5175,9 +5230,28 @@ int wc_ecc_make_pub(ecc_key* key, ecc_point* pubOut) */ int wc_ecc_make_pub_ex(ecc_key* key, ecc_point* pubOut, WC_RNG* rng) { + int err = MP_OKAY; + DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); + WOLFSSL_ENTER("wc_ecc_make_pub_ex"); - return ecc_make_pub_ex(key, NULL, pubOut, rng); + if (key == NULL) { + return BAD_FUNC_ARG; + } + + /* load curve info */ + ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); + if (err == MP_OKAY) { + err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); + } + if (err == MP_OKAY) { + err = ecc_make_pub_ex(key, curve, pubOut, rng); + } + + wc_ecc_curve_free(curve); + FREE_CURVE_SPECS(); + + return err; } @@ -5185,9 +5259,6 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id, int flags) { int err = 0; -#if defined(HAVE_ECC_MAKE_PUB) && !defined(WOLFSSL_SP_MATH) - DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); -#endif #if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A) && \ !defined(WOLFSSL_ATECC608A) const CRYS_ECPKI_Domain_t* pDomain; @@ -5449,28 +5520,28 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #endif /* WOLFSSL_SP_384 */ #ifdef WOLFSSL_SP_521 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP521R1) { -#ifndef WC_ECC_NONBLOCK - err = sp_ecc_make_key_521(rng, &key->k, &key->pubkey, key->heap); -#else - if (key->nb_ctx) { - err = sp_ecc_make_key_521_nb(&key->nb_ctx->sp_ctx, rng, &key->k, - &key->pubkey, key->heap); - } - else { - #ifdef WC_ECC_NONBLOCK_ONLY - do { /* perform blocking call to non-blocking function */ - err = sp_ecc_make_key_521_nb(&nb_ctx.sp_ctx, rng, &key->k, - &key->pubkey, key->heap); - } while (err == FP_WOULDBLOCK); - #else + #ifndef WC_ECC_NONBLOCK err = sp_ecc_make_key_521(rng, &key->k, &key->pubkey, key->heap); - #endif /* WC_ECC_NONBLOCK_ONLY */ - } -#endif /* !WC_ECC_NONBLOCK */ + #else + if (key->nb_ctx) { + err = sp_ecc_make_key_521_nb(&key->nb_ctx->sp_ctx, rng, &key->k, + &key->pubkey, key->heap); + } + else { + #ifdef WC_ECC_NONBLOCK_ONLY + do { /* perform blocking call to non-blocking function */ + err = sp_ecc_make_key_521_nb(&nb_ctx.sp_ctx, rng, &key->k, + &key->pubkey, key->heap); + } while (err == FP_WOULDBLOCK); + #else + err = sp_ecc_make_key_521(rng, &key->k, &key->pubkey, key->heap); + #endif /* WC_ECC_NONBLOCK_ONLY */ + } + #endif /* !WC_ECC_NONBLOCK */ - if (err == MP_OKAY) { - key->type = ECC_PRIVATEKEY; - } + if (err == MP_OKAY) { + key->type = ECC_PRIVATEKEY; + } } else #endif /* WOLFSSL_SP_521 */ @@ -5480,6 +5551,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #if defined(WOLFSSL_SP_MATH) err = WC_KEY_SIZE_E; #else + DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); /* setup the key variables */ err = mp_init(&key->k); @@ -6193,13 +6265,9 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, WC_RNG* rng, ecc_key* key) { int err; - #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(WC_ASYNC_ENABLE_ECC) -#ifdef WOLFSSL_SMALL_STACK - mp_int *r = NULL, *s = NULL; -#else - mp_int r[1], s[1]; -#endif + DECL_MP_INT_SIZE_DYN(r, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(s, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); #endif if (in == NULL || out == NULL || outlen == NULL || key == NULL) { @@ -6233,24 +6301,29 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, err = wc_ecc_sign_hash_async(in, inlen, out, outlen, rng, key); #else -#ifdef WOLFSSL_SMALL_STACK - r = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(r, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL if (r == NULL) return MEMORY_E; - s = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); +#endif + NEW_MP_INT_SIZE(s, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL if (s == NULL) { - XFREE(r, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); return MEMORY_E; } #endif - XMEMSET(r, 0, sizeof(mp_int)); - XMEMSET(s, 0, sizeof(mp_int)); - if ((err = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY){ - #ifdef WOLFSSL_SMALL_STACK - XFREE(s, key->heap, DYNAMIC_TYPE_ECC); - XFREE(r, key->heap, DYNAMIC_TYPE_ECC); - #endif + err = INIT_MP_INT_SIZE(r, ECC_KEY_MAX_BITS(key)); + if (err != 0) { + FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); + return err; + } + err = INIT_MP_INT_SIZE(s, ECC_KEY_MAX_BITS(key)); + if (err != 0) { + FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); return err; } @@ -6266,10 +6339,8 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, if (err < 0) { mp_clear(r); mp_clear(s); - #ifdef WOLFSSL_SMALL_STACK - XFREE(s, key->heap, DYNAMIC_TYPE_ECC); - XFREE(r, key->heap, DYNAMIC_TYPE_ECC); - #endif + FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); return err; } @@ -6280,10 +6351,8 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, mp_clear(r); mp_clear(s); -#ifdef WOLFSSL_SMALL_STACK - XFREE(s, key->heap, DYNAMIC_TYPE_ECC); - XFREE(r, key->heap, DYNAMIC_TYPE_ECC); -#endif + FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); #endif /* WOLFSSL_ASYNC_CRYPT */ #else (void)rng; @@ -6376,20 +6445,16 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, { int err = MP_OKAY; int loop_check = 0; -#ifdef WOLFSSL_SMALL_STACK - mp_int* b = NULL; -#else - mp_int b[1]; -#endif + DECL_MP_INT_SIZE_DYN(b, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); -#ifdef WOLFSSL_SMALL_STACK - b = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(b, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL if (b == NULL) err = MEMORY_E; #endif if (err == MP_OKAY) { - err = mp_init(b); + err = INIT_MP_INT_SIZE(b, ECC_KEY_MAX_BITS(key)); } #ifdef WOLFSSL_CUSTOM_CURVES @@ -6540,9 +6605,8 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, mp_forcezero(&pubkey->k); } mp_forcezero(b); -#ifdef WOLFSSL_SMALL_STACK - XFREE(b, key->heap, DYNAMIC_TYPE_ECC); -#elif defined(WOLFSSL_CHECK_MEM_ZERO) + FREE_MP_INT_SIZE(b, key->heap, DYNAMIC_TYPE_ECC); +#if !defined(WOLFSSL_SMALL_STACK) && defined(WOLFSSL_CHECK_MEM_ZERO) mp_memzero_check(b); #endif @@ -6550,96 +6614,10 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, } #endif -/** - Sign a message digest - in The message digest to sign - inlen The length of the digest - key A private ECC key - r [out] The destination for r component of the signature - s [out] The destination for s component of the signature - return MP_OKAY if successful -*/ -int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, - ecc_key* key, mp_int *r, mp_int *s) +#ifdef WOLFSSL_HAVE_SP_ECC +static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, + ecc_key* key, mp_int *r, mp_int *s) { - int err = 0; -#if !defined(WOLFSSL_SP_MATH) - mp_int* e; -#if (!defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)) && \ - !defined(WOLFSSL_SMALL_STACK) - mp_int e_lcl; -#endif - -#if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP) || \ - defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ - defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) || \ - (defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ - (defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA))) - DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); -#else - DECLARE_CURVE_SPECS(1); -#endif -#endif /* !WOLFSSL_SP_MATH */ - - if (in == NULL || r == NULL || s == NULL || key == NULL || rng == NULL) { - return ECC_BAD_ARG_E; - } - - /* is this a private key? */ - if (key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY) { - return ECC_BAD_ARG_E; - } - - /* is the IDX valid ? */ - if (wc_ecc_is_valid_idx(key->idx) == 0 || key->dp == NULL) { - return ECC_BAD_ARG_E; - } - -#if defined(WOLFSSL_SP_MATH) - if (key->idx == ECC_CUSTOM_IDX || (1 - #ifndef WOLFSSL_SP_NO_256 - && ecc_sets[key->idx].id != ECC_SECP256R1 - #endif - #ifdef WOLFSSL_SP_384 - && ecc_sets[key->idx].id != ECC_SECP384R1 - #endif - #ifdef WOLFSSL_SP_521 - && ecc_sets[key->idx].id != ECC_SECP521R1 - #endif - )) { - return WC_KEY_SIZE_E; - } -#endif - -#if defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ - defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) - /* generate deterministic 'k' value to be used either with SP or normal */ - if (key->deterministic == 1) { - if (deterministic_sign_helper(in, inlen, key)) { - WOLFSSL_MSG("Error generating deterministic k to sign"); - return ECC_PRIV_KEY_E; - } - } -#endif - - -#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ - defined(WOLFSSL_ASYNC_CRYPT_SW) - if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { - if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_ECC_SIGN)) { - WC_ASYNC_SW* sw = &key->asyncDev.sw; - sw->eccSign.in = in; - sw->eccSign.inSz = inlen; - sw->eccSign.rng = rng; - sw->eccSign.key = key; - sw->eccSign.r = r; - sw->eccSign.s = s; - return WC_PENDING_E; - } - } -#endif - -#if defined(WOLFSSL_HAVE_SP_ECC) if (key->idx != ECC_CUSTOM_IDX) { #if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP) \ || defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ @@ -6736,156 +6714,254 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, #endif (void)sign_k; } -#else - (void)inlen; + + /* SP doesn't support curve. */ + return WC_KEY_SIZE_E; +} #endif +/** + Sign a message digest + in The message digest to sign + inlen The length of the digest + key A private ECC key + r [out] The destination for r component of the signature + s [out] The destination for s component of the signature + return MP_OKAY if successful +*/ +int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, + ecc_key* key, mp_int *r, mp_int *s) +{ + int err = 0; #if !defined(WOLFSSL_SP_MATH) - -#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V) - err = wc_ecc_alloc_mpint(key, &key->e); - if (err != 0) { - return err; - } - e = key->e; -#elif !defined(WOLFSSL_SMALL_STACK) - e = &e_lcl; -#else - e = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); - if (e == NULL) { - return MEMORY_E; - } + mp_int* e; +#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) + DECL_MP_INT_SIZE_DYN(e_lcl, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); #endif - /* get the hash and load it as a bignum into 'e' */ - /* init the bignums */ - if ((err = mp_init(e)) != MP_OKAY) { - #ifdef WOLFSSL_SMALL_STACK - XFREE(e, key->heap, DYNAMIC_TYPE_ECC); - #endif - return err; - } - - /* load curve info */ #if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP) || \ defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ - defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) - ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); - if (err == MP_OKAY) - err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); + defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) || \ + (defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ + (defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA))) + DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); #else - #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ - (defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)) - if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { - ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); - if (err == MP_OKAY) - err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); - } - else - #endif - { - ALLOC_CURVE_SPECS(1, err); - if (err == MP_OKAY) - err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER); - } + DECLARE_CURVE_SPECS(1); #endif +#endif /* !WOLFSSL_SP_MATH */ - /* load digest into e */ - if (err == MP_OKAY) { - /* we may need to truncate if hash is longer than key size */ - word32 orderBits = mp_count_bits(curve->order); - - /* truncate down to byte size, may be all that's needed */ - if ((WOLFSSL_BIT_SIZE * inlen) > orderBits) - inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE; - err = mp_read_unsigned_bin(e, in, inlen); + if (in == NULL || r == NULL || s == NULL || key == NULL || rng == NULL) { + return ECC_BAD_ARG_E; + } - /* may still need bit truncation too */ - if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * inlen) > orderBits) - mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7)); + /* is this a private key? */ + if (key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY) { + return ECC_BAD_ARG_E; } - /* make up a key and export the public copy */ + /* is the IDX valid ? */ + if (wc_ecc_is_valid_idx(key->idx) == 0 || key->dp == NULL) { + return ECC_BAD_ARG_E; + } + +#if defined(WOLFSSL_SP_MATH) + if (key->idx == ECC_CUSTOM_IDX || (1 + #ifndef WOLFSSL_SP_NO_256 + && ecc_sets[key->idx].id != ECC_SECP256R1 + #endif + #ifdef WOLFSSL_SP_384 + && ecc_sets[key->idx].id != ECC_SECP384R1 + #endif + #ifdef WOLFSSL_SP_521 + && ecc_sets[key->idx].id != ECC_SECP521R1 + #endif + )) { + return WC_KEY_SIZE_E; + } +#endif + +#if defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ + defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) + /* generate deterministic 'k' value to be used either with SP or normal */ + if (key->deterministic == 1) { + if (deterministic_sign_helper(in, inlen, key)) { + WOLFSSL_MSG("Error generating deterministic k to sign"); + return ECC_PRIV_KEY_E; + } + } +#endif + + +#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ + defined(WOLFSSL_ASYNC_CRYPT_SW) + if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { + if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_ECC_SIGN)) { + WC_ASYNC_SW* sw = &key->asyncDev.sw; + sw->eccSign.in = in; + sw->eccSign.inSz = inlen; + sw->eccSign.rng = rng; + sw->eccSign.key = key; + sw->eccSign.r = r; + sw->eccSign.s = s; + return WC_PENDING_E; + } + } +#endif + +#if defined(WOLFSSL_HAVE_SP_ECC) + err = ecc_sign_hash_sp(in, inlen, rng, key, r, s); + if (err != WC_KEY_SIZE_E) { + return err; + } +#else + (void)inlen; +#endif + +#if !defined(WOLFSSL_SP_MATH) + +#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V) + err = wc_ecc_alloc_mpint(key, &key->e); + if (err != 0) { + return err; + } + e = key->e; +#else + NEW_MP_INT_SIZE(e_lcl, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL + if (e_lcl == NULL) { + return MEMORY_E; + } +#endif + e = e_lcl; +#endif + + /* get the hash and load it as a bignum into 'e' */ + /* init the bignums */ + if ((err = INIT_MP_INT_SIZE(e, ECC_KEY_MAX_BITS(key))) != MP_OKAY) { + FREE_MP_INT_SIZE(e_lcl, key->heap, DYNAMIC_TYPE_ECC); + return err; + } + + /* load curve info */ +#if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP) || \ + defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ + defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) + ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); + if (err == MP_OKAY) + err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); +#else + #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ + (defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)) + if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { + ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); + if (err == MP_OKAY) + err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); + } + else + #endif + { + ALLOC_CURVE_SPECS(1, err); + if (err == MP_OKAY) + err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER); + } +#endif + + /* load digest into e */ if (err == MP_OKAY) { - #ifdef WOLFSSL_SMALL_STACK - ecc_key* pubkey; - #else - ecc_key pubkey[1]; - #endif + /* we may need to truncate if hash is longer than key size */ + word32 orderBits = mp_count_bits(curve->order); - #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) - if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { - #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) - #ifdef HAVE_CAVIUM_V - if (NitroxEccIsCurveSupported(key)) - #endif - { - word32 keySz = key->dp->size; - mp_int* k; - #ifdef HAVE_CAVIUM_V - err = wc_ecc_alloc_mpint(key, &key->signK); - if (err != 0) - return err; - k = key->signK; - #else - mp_int k_lcl; - k = &k_lcl; - #endif + /* truncate down to byte size, may be all that's needed */ + if ((WOLFSSL_BIT_SIZE * inlen) > orderBits) + inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE; + err = mp_read_unsigned_bin(e, in, inlen); - err = mp_init(k); + /* may still need bit truncation too */ + if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * inlen) > orderBits) + mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7)); + } - /* make sure r and s are allocated */ - #ifdef HAVE_CAVIUM_V - /* Nitrox V needs single buffer for R and S */ - if (err == MP_OKAY) - err = wc_bigint_alloc(&key->r->raw, NitroxEccGetSize(key)*2); - /* Nitrox V only needs Prime and Order */ - if (err == MP_OKAY) - err = wc_ecc_curve_load(key->dp, &curve, - (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_ORDER)); - #else - if (err == MP_OKAY) - err = wc_bigint_alloc(&key->r->raw, key->dp->size); - if (err == MP_OKAY) - err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); - #endif - if (err == MP_OKAY) - err = wc_bigint_alloc(&key->s->raw, key->dp->size); + /* make up a key and export the public copy */ +#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) + if ((err == MP_OKAY) && (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC)) { + #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) + #ifdef HAVE_CAVIUM_V + if (NitroxEccIsCurveSupported(key)) + #endif + { + word32 keySz = key->dp->size; + mp_int* k; + #ifdef HAVE_CAVIUM_V + err = wc_ecc_alloc_mpint(key, &key->signK); + if (err != 0) + return err; + k = key->signK; + #else + mp_int k_lcl; + k = &k_lcl; + #endif - /* load e and k */ - if (err == MP_OKAY) - err = wc_mp_to_bigint_sz(e, &e->raw, keySz); - if (err == MP_OKAY) - err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz); - if (err == MP_OKAY) - err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order); - if (err == MP_OKAY) - err = wc_mp_to_bigint_sz(k, &k->raw, keySz); + err = mp_init(k); - #ifdef HAVE_CAVIUM_V - if (err == MP_OKAY) - err = NitroxEcdsaSign(key, &e->raw, &key->k.raw, &k->raw, - &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw); - #else - if (err == MP_OKAY) - err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k.raw, - &k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw, - &curve->prime->raw, &curve->order->raw, &curve->Gx->raw, - &curve->Gy->raw); - #endif + /* make sure r and s are allocated */ + #ifdef HAVE_CAVIUM_V + /* Nitrox V needs single buffer for R and S */ + if (err == MP_OKAY) + err = wc_bigint_alloc(&key->r->raw, NitroxEccGetSize(key)*2); + /* Nitrox V only needs Prime and Order */ + if (err == MP_OKAY) + err = wc_ecc_curve_load(key->dp, &curve, + (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_ORDER)); + #else + if (err == MP_OKAY) + err = wc_bigint_alloc(&key->r->raw, key->dp->size); + if (err == MP_OKAY) + err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); + #endif + if (err == MP_OKAY) + err = wc_bigint_alloc(&key->s->raw, key->dp->size); - #ifndef HAVE_CAVIUM_V - mp_clear(e); - mp_clear(k); - #endif - wc_ecc_curve_free(curve); - FREE_CURVE_SPECS(); + /* load e and k */ + if (err == MP_OKAY) + err = wc_mp_to_bigint_sz(e, &e->raw, keySz); + if (err == MP_OKAY) + err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz); + if (err == MP_OKAY) + err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order); + if (err == MP_OKAY) + err = wc_mp_to_bigint_sz(k, &k->raw, keySz); - return err; - } - #endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */ + #ifdef HAVE_CAVIUM_V + if (err == MP_OKAY) + err = NitroxEcdsaSign(key, &e->raw, &key->k.raw, &k->raw, + &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw); + #else + if (err == MP_OKAY) + err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k.raw, + &k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw, + &curve->prime->raw, &curve->order->raw, &curve->Gx->raw, + &curve->Gy->raw); + #endif + + #ifndef HAVE_CAVIUM_V + mp_clear(e); + mp_clear(k); + #endif + wc_ecc_curve_free(curve); + FREE_CURVE_SPECS(); + + return err; } - #endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */ + #endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */ + } +#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */ + + if (err == MP_OKAY) { + #ifdef WOLFSSL_SMALL_STACK + ecc_key* pubkey; + #else + ecc_key pubkey[1]; + #endif #ifdef WOLFSSL_SMALL_STACK pubkey = (ecc_key*)XMALLOC(sizeof(ecc_key), key->heap, DYNAMIC_TYPE_ECC); @@ -6908,9 +6984,7 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, mp_clear(e); wc_ecc_curve_free(curve); -#ifdef WOLFSSL_SMALL_STACK - XFREE(e, key->heap, DYNAMIC_TYPE_ECC); -#endif + FREE_MP_INT_SIZE(e_lcl, key->heap, DYNAMIC_TYPE_ECC); FREE_CURVE_SPECS(); #endif /* !WOLFSSL_SP_MATH */ @@ -7495,6 +7569,51 @@ int ecc_projective_dbl_point_safe(ecc_point *P, ecc_point *R, mp_int* a, !defined(WOLFSSL_KCAPI_ECC) && !defined(WOLF_CRYPTO_CB_ONLY_ECC) #ifdef ECC_SHAMIR +static int ecc_mont_norm_points(ecc_point* A, ecc_point* Am, ecc_point* B, + ecc_point* Bm, mp_int* modulus, void* heap) +{ + int err = MP_OKAY; + DECL_MP_INT_SIZE_DYN(mu, mp_bitsused(modulus), MAX_ECC_BITS_USE); + + (void)heap; + + NEW_MP_INT_SIZE(mu, mp_bitsused(modulus), heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL + if (mu == NULL) + err = MEMORY_E; +#endif + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(mu, mp_bitsused(modulus)); + } + if (err == MP_OKAY) { + err = mp_montgomery_calc_normalization(mu, modulus); + + if (err == MP_OKAY) { + /* copy ones ... */ + err = mp_mulmod(A->x, mu, modulus, Am->x); + } + + if (err == MP_OKAY) + err = mp_mulmod(A->y, mu, modulus, Am->y); + if (err == MP_OKAY) + err = mp_mulmod(A->z, mu, modulus, Am->z); + + if (err == MP_OKAY) + err = mp_mulmod(B->x, mu, modulus, Bm->x); + if (err == MP_OKAY) + err = mp_mulmod(B->y, mu, modulus, Bm->y); + if (err == MP_OKAY) + err = mp_mulmod(B->z, mu, modulus, Bm->z); + + /* done with mu */ + mp_clear(mu); + } + + FREE_MP_INT_SIZE(mu, heap, DYNAMIC_TYPE_ECC); + + return err; +} + /** Computes kA*A + kB*B = C using Shamir's Trick A First point to multiply kA What to multiple A by @@ -7660,45 +7779,7 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { - #ifdef WOLFSSL_SMALL_STACK - mp_int* mu; - #else - mp_int mu[1]; - #endif - #ifdef WOLFSSL_SMALL_STACK - mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC); - if (mu == NULL) - err = MEMORY_E; - else - #endif - err = mp_init(mu); - if (err == MP_OKAY) { - err = mp_montgomery_calc_normalization(mu, modulus); - - if (err == MP_OKAY) - /* copy ones ... */ - err = mp_mulmod(A->x, mu, modulus, precomp[1]->x); - - if (err == MP_OKAY) - err = mp_mulmod(A->y, mu, modulus, precomp[1]->y); - if (err == MP_OKAY) - err = mp_mulmod(A->z, mu, modulus, precomp[1]->z); - - if (err == MP_OKAY) - err = mp_mulmod(B->x, mu, modulus, precomp[1<<2]->x); - if (err == MP_OKAY) - err = mp_mulmod(B->y, mu, modulus, precomp[1<<2]->y); - if (err == MP_OKAY) - err = mp_mulmod(B->z, mu, modulus, precomp[1<<2]->z); - - /* done with mu */ - mp_clear(mu); - } - #ifdef WOLFSSL_SMALL_STACK - if (mu != NULL) { - XFREE(mu, heap, DYNAMIC_TYPE_ECC); - } - #endif + err = ecc_mont_norm_points(A, precomp[1], B, precomp[1<<2], modulus, heap); } if (err == MP_OKAY) { @@ -7870,10 +7951,11 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, { int err; +#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) mp_int *r = NULL, *s = NULL; -#if (!defined(WOLFSSL_ASYNC_CRYPT) || !defined(WC_ASYNC_ENABLE_ECC)) && \ - !defined(WOLFSSL_SMALL_STACK) - mp_int r_lcl, s_lcl; +#else + DECL_MP_INT_SIZE_DYN(r, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(s, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); #endif #ifdef WOLFSSL_ASYNC_CRYPT int isPrivateKeyOnly = 0; @@ -7908,21 +7990,30 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, r = key->r; s = key->s; #else - #ifndef WOLFSSL_SMALL_STACK - r = &r_lcl; - s = &s_lcl; - #else - r = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(r, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL if (r == NULL) return MEMORY_E; - s = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); +#endif + NEW_MP_INT_SIZE(s, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL if (s == NULL) { - XFREE(r, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); return MEMORY_E; } - #endif - XMEMSET(r, 0, sizeof(mp_int)); - XMEMSET(s, 0, sizeof(mp_int)); +#endif + err = INIT_MP_INT_SIZE(r, ECC_KEY_MAX_BITS(key)); + if (err != 0) { + FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); + return err; + } + err = INIT_MP_INT_SIZE(s, ECC_KEY_MAX_BITS(key)); + if (err != 0) { + FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); + return err; + } #endif /* WOLFSSL_ASYNC_CRYPT */ switch (key->state) { @@ -7957,9 +8048,9 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, /* done with R/S */ mp_clear(r); mp_clear(s); - #ifdef WOLFSSL_SMALL_STACK - XFREE(s, key->heap, DYNAMIC_TYPE_ECC); - XFREE(r, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL r = NULL; s = NULL; #endif @@ -7991,11 +8082,9 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, /* cleanup */ #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) wc_ecc_free_async(key); -#elif defined(WOLFSSL_SMALL_STACK) - XFREE(s, key->heap, DYNAMIC_TYPE_ECC); - XFREE(r, key->heap, DYNAMIC_TYPE_ECC); - r = NULL; - s = NULL; +#else + FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); #endif /* make sure required variables are reset */ @@ -8003,10 +8092,6 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, #else (void)siglen; (void)hashlen; - #ifndef WOLFSSL_SMALL_STACK - (void)s_lcl; - (void)r_lcl; - #endif (void)s; (void)r; (void)err; @@ -8048,216 +8133,16 @@ static int wc_ecc_check_r_s_range(ecc_key* key, mp_int* r, mp_int* s) } #endif /* !WOLFSSL_STM32_PKA && !WOLFSSL_PSOC6_CRYPTO */ -/** - Verify an ECC signature - r The signature R component to verify - s The signature S component to verify - hash The hash (message digest) that was signed - hashlen The length of the hash (octets) - res Result of signature, 1==valid, 0==invalid - key The corresponding public ECC key - return MP_OKAY if successful (even if the signature is not valid) - Caller should check the *res value to determine if the signature - is valid or invalid. Other negative values are returned on error. -*/ #ifndef WOLF_CRYPTO_CB_ONLY_ECC -int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, - word32 hashlen, int* res, ecc_key* key) -#if defined(WOLFSSL_STM32_PKA) +static int ecc_verify_hash_sp(mp_int *r, mp_int *s, const byte* hash, + word32 hashlen, int* res, ecc_key* key) { - return stm32_ecc_verify_hash_ex(r, s, hash, hashlen, res, key); -} -#elif defined(WOLFSSL_PSOC6_CRYPTO) -{ - return psoc6_ecc_verify_hash_ex(r, s, hash, hashlen, res, key); -} -#else -{ - int err; - word32 keySz = 0; -#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) - byte sigRS[ATECC_KEY_SIZE*2]; -#elif defined(WOLFSSL_CRYPTOCELL) - byte sigRS[ECC_MAX_CRYPTO_HW_SIZE*2]; - CRYS_ECDSA_VerifyUserContext_t sigCtxTemp; - word32 msgLenInBytes = hashlen; - CRYS_ECPKI_HASH_OpMode_t hash_mode; -#elif defined(WOLFSSL_SILABS_SE_ACCEL) - byte sigRS[ECC_MAX_CRYPTO_HW_SIZE * 2]; -#elif defined(WOLFSSL_KCAPI_ECC) - byte sigRS[MAX_ECC_BYTES*2]; -#elif defined(WOLFSSL_XILINX_CRYPT_VERSAL) - byte sigRS[ECC_MAX_CRYPTO_HW_SIZE * 2]; - byte hashcopy[ECC_MAX_CRYPTO_HW_SIZE] = {0}; -#elif (!defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC)) && \ - !defined(WOLFSSL_SE050) - int did_init = 0; - ecc_point *mG = NULL, *mQ = NULL; - #ifdef WOLFSSL_NO_MALLOC - ecc_point lcl_mG, lcl_mQ; - #endif - #ifdef WOLFSSL_SMALL_STACK - mp_int* v = NULL; - mp_int* w = NULL; - mp_int* u1 = NULL; - mp_int* u2 = NULL; - #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) - mp_int* e_lcl = NULL; - #endif - #else /* WOLFSSL_SMALL_STACK */ - mp_int v[1]; - mp_int w[1]; - mp_int u1[1]; - mp_int u2[1]; - #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) - mp_int e_lcl[1]; - #endif - #endif /* WOLFSSL_SMALL_STACK */ - mp_int* e; - DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); -#endif - - if (r == NULL || s == NULL || hash == NULL || res == NULL || key == NULL) - return ECC_BAD_ARG_E; - - /* default to invalid signature */ - *res = 0; - - /* is the IDX valid ? */ - if (wc_ecc_is_valid_idx(key->idx) == 0 || key->dp == NULL) { - return ECC_BAD_ARG_E; - } - - err = wc_ecc_check_r_s_range(key, r, s); - if (err != MP_OKAY) { - return err; - } - - keySz = key->dp->size; - -#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ - defined(WOLFSSL_ASYNC_CRYPT_SW) - if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { - if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_ECC_VERIFY)) { - WC_ASYNC_SW* sw = &key->asyncDev.sw; - sw->eccVerify.r = r; - sw->eccVerify.s = s; - sw->eccVerify.hash = hash; - sw->eccVerify.hashlen = hashlen; - sw->eccVerify.stat = res; - sw->eccVerify.key = key; - return WC_PENDING_E; - } - } -#endif - -#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) || \ - defined(WOLFSSL_CRYPTOCELL) || defined(WOLFSSL_SILABS_SE_ACCEL) || \ - defined(WOLFSSL_KCAPI_ECC) || defined(WOLFSSL_SE050) || \ - defined(WOLFSSL_XILINX_CRYPT_VERSAL) - -#ifndef WOLFSSL_SE050 - /* Extract R and S with front zero padding (if required), - * SE050 does this in port layer */ - XMEMSET(sigRS, 0, sizeof(sigRS)); - err = mp_to_unsigned_bin(r, sigRS + - (keySz - mp_unsigned_bin_size(r))); - if (err != MP_OKAY) { - return err; - } - err = mp_to_unsigned_bin(s, sigRS + keySz + - (keySz - mp_unsigned_bin_size(s))); - if (err != MP_OKAY) { - return err; - } -#endif /* WOLFSSL_SE050 */ - -#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) - err = atmel_ecc_verify(hash, sigRS, key->pubkey_raw, res); - if (err != 0) { - return err; - } + (void)r; + (void)s; + (void)hash; (void)hashlen; -#elif defined(WOLFSSL_CRYPTOCELL) - - /* truncate if hash is longer than key size */ - if (msgLenInBytes > keySz) { - msgLenInBytes = keySz; - } - hash_mode = cc310_hashModeECC(msgLenInBytes); - if (hash_mode == CRYS_ECPKI_HASH_OpModeLast) { - /* hash_mode = */ cc310_hashModeECC(keySz); - hash_mode = CRYS_ECPKI_HASH_SHA256_mode; - } - - /* verify the signature using the public key */ - err = CRYS_ECDSA_Verify(&sigCtxTemp, - &key->ctx.pubKey, - hash_mode, - &sigRS[0], - keySz*2, - (byte*)hash, - msgLenInBytes); - - if (err == CRYS_ECDSA_VERIFY_INCONSISTENT_VERIFY_ERROR) { - /* signature verification reported invalid signature. */ - *res = 0; /* Redundant, added for code clarity */ - err = MP_OKAY; - } - else if (err != SA_SILIB_RET_OK) { - WOLFSSL_MSG("CRYS_ECDSA_Verify failed"); - return err; - } - else { - /* valid signature. */ - *res = 1; - err = MP_OKAY; - } -#elif defined(WOLFSSL_SILABS_SE_ACCEL) - err = silabs_ecc_verify_hash(&sigRS[0], keySz * 2, - hash, hashlen, - res, key); -#elif defined(WOLFSSL_KCAPI_ECC) - err = KcapiEcc_Verify(key, hash, hashlen, sigRS, keySz * 2); - if (err == 0) { - *res = 1; - } -#elif defined(WOLFSSL_SE050) - err = se050_ecc_verify_hash_ex(hash, hashlen, r, s, key, res); -#elif defined(WOLFSSL_XILINX_CRYPT_VERSAL) - if (hashlen > sizeof(hashcopy)) - return ECC_BAD_ARG_E; - buf_reverse(hashcopy, hash, (hashlen < keySz) ? hashlen : keySz); - mp_reverse(sigRS, keySz); - mp_reverse(sigRS + keySz, keySz); - WOLFSSL_XIL_DCACHE_FLUSH_RANGE(XIL_CAST_U64(hashcopy), keySz); - WOLFSSL_XIL_DCACHE_FLUSH_RANGE(XIL_CAST_U64(key->keyRaw), keySz * 2); - WOLFSSL_XIL_DCACHE_FLUSH_RANGE(XIL_CAST_U64(sigRS), keySz * 2); - - err = XSecure_EllipticVerifySign(&(key->xSec.cinst), - xil_curve_type[key->dp->id], - XIL_CAST_U64(hashcopy), keySz, - XIL_CAST_U64(key->keyRaw), - XIL_CAST_U64(sigRS)); - - if (err != XST_SUCCESS) { - WOLFSSL_XIL_ERROR("Verify ECC signature failed", err); - err = WC_HW_E; - } else { - *res = 1; - } -#endif - -#else - /* checking if private key with no public part */ - if (key->type == ECC_PRIVATEKEY_ONLY) { - WOLFSSL_MSG("Verify called with private key, generating public part"); - err = ecc_make_pub_ex(key, NULL, NULL, NULL); - if (err != MP_OKAY) { - WOLFSSL_MSG("Unable to extract public key"); - return err; - } - } + (void)res; + (void)key; #if defined(WOLFSSL_DSP) && !defined(FREESCALE_LTC_ECC) if (key->handle != -1) { @@ -8384,39 +8269,57 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, } #endif + return 0; +} + #if !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC) - ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); - if (err != 0) { - return err; - } +static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, + word32 hashlen, int* res, ecc_key* key, ecc_curve_spec* curve) +{ + int err; + ecc_point* mG = NULL; + ecc_point* mQ = NULL; +#ifdef WOLFSSL_NO_MALLOC + ecc_point lcl_mG; + ecc_point lcl_mQ; +#endif + DECL_MP_INT_SIZE_DYN(v, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); + DECL_MP_INT_SIZE_DYN(w, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); +#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) + DECL_MP_INT_SIZE_DYN(e_lcl, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); +#endif + mp_int* e; + mp_int* u1 = NULL; /* Will be e. */ + mp_int* u2 = NULL; /* Will be w. */ #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V) err = wc_ecc_alloc_mpint(key, &key->e); if (err != 0) { - FREE_CURVE_SPECS(); return err; } e = key->e; + + err = mp_init(e); #else -#ifdef WOLFSSL_SMALL_STACK - e_lcl = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(e_lcl, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL if (e_lcl == NULL) { - FREE_CURVE_SPECS(); return MEMORY_E; } #endif e = e_lcl; -#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_CAVIUM_V */ - err = mp_init(e); + err = INIT_MP_INT_SIZE(e, ECC_KEY_MAX_BITS(key)); +#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_CAVIUM_V */ if (err != MP_OKAY) { - FREE_CURVE_SPECS(); +#ifdef WOLFSSL_SMALL_STACK + #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) + XFREE(e_lcl, key->heap, DYNAMIC_TYPE_ECC); + #endif +#endif return MEMORY_E; } - /* read in the specs for this curve */ - err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); - /* read hash */ if (err == MP_OKAY) { /* we may need to truncate if hash is longer than key size */ @@ -8460,8 +8363,6 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, #ifndef HAVE_CAVIUM_V mp_clear(e); #endif - wc_ecc_curve_free(curve); - FREE_CURVE_SPECS(); return err; } @@ -8469,36 +8370,27 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, } #endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */ -#ifdef WOLFSSL_SMALL_STACK - if (err == MP_OKAY) { - v = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); - if (v == NULL) - err = MEMORY_E; - } - if (err == MP_OKAY) { - w = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); - if (w == NULL) - err = MEMORY_E; - } - if (err == MP_OKAY) { - u1 = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); - if (u1 == NULL) - err = MEMORY_E; + NEW_MP_INT_SIZE(v, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL + if (v == NULL) { + err = MEMORY_E; } - if (err == MP_OKAY) { - u2 = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); - if (u2 == NULL) - err = MEMORY_E; +#endif + NEW_MP_INT_SIZE(w, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); +#ifdef MP_INT_SIZE_CHECK_NULL + if (w == NULL) { + err = MEMORY_E; } #endif - /* allocate ints */ if (err == MP_OKAY) { - if ((err = mp_init_multi(v, w, u1, u2, NULL, NULL)) != MP_OKAY) { - err = MEMORY_E; - } else { - did_init = 1; - } + u1 = e; + u2 = w; + + err = INIT_MP_INT_SIZE(v, ECC_KEY_MAX_BITS(key)); + } + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(w, ECC_KEY_MAX_BITS(key)); } /* allocate points */ @@ -8556,7 +8448,7 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, { mp_digit mp = 0; - if (!mp_iszero(u1)) { + if (!mp_iszero((MP_INT_SIZE*)u1)) { /* compute u1*mG + u2*mQ = mG */ err = wc_ecc_mulmod_ex(u1, mG, mG, curve->Af, curve->prime, 0, key->heap); @@ -8610,34 +8502,250 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, wc_ecc_del_point_ex(mQ, key->heap); mp_clear(e); - if (did_init) { - mp_clear(v); - mp_clear(w); - mp_clear(u1); - mp_clear(u2); - } -#ifdef WOLFSSL_SMALL_STACK - XFREE(u2, key->heap, DYNAMIC_TYPE_ECC); - XFREE(u1, key->heap, DYNAMIC_TYPE_ECC); - XFREE(w, key->heap, DYNAMIC_TYPE_ECC); - XFREE(v, key->heap, DYNAMIC_TYPE_ECC); + mp_clear(v); + mp_clear(w); + FREE_MP_INT_SIZE(w, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(v, key->heap, DYNAMIC_TYPE_ECC); #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) - XFREE(e_lcl, key->heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(e_lcl, key->heap, DYNAMIC_TYPE_ECC); #endif + + return err; +} +#endif /* !WOLFSSL_SP_MATH || FREESCALE_LTC_ECC */ + +/** + Verify an ECC signature + r The signature R component to verify + s The signature S component to verify + hash The hash (message digest) that was signed + hashlen The length of the hash (octets) + res Result of signature, 1==valid, 0==invalid + key The corresponding public ECC key + return MP_OKAY if successful (even if the signature is not valid) + Caller should check the *res value to determine if the signature + is valid or invalid. Other negative values are returned on error. +*/ +int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, + word32 hashlen, int* res, ecc_key* key) +{ +#if defined(WOLFSSL_STM32_PKA) + return stm32_ecc_verify_hash_ex(r, s, hash, hashlen, res, key); +#elif defined(WOLFSSL_PSOC6_CRYPTO) + return psoc6_ecc_verify_hash_ex(r, s, hash, hashlen, res, key); +#else + int err; + word32 keySz = 0; +#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) + byte sigRS[ATECC_KEY_SIZE*2]; +#elif defined(WOLFSSL_CRYPTOCELL) + byte sigRS[ECC_MAX_CRYPTO_HW_SIZE*2]; + CRYS_ECDSA_VerifyUserContext_t sigCtxTemp; + word32 msgLenInBytes = hashlen; + CRYS_ECPKI_HASH_OpMode_t hash_mode; +#elif defined(WOLFSSL_SILABS_SE_ACCEL) + byte sigRS[ECC_MAX_CRYPTO_HW_SIZE * 2]; +#elif defined(WOLFSSL_KCAPI_ECC) + byte sigRS[MAX_ECC_BYTES*2]; +#elif defined(WOLFSSL_XILINX_CRYPT_VERSAL) + byte sigRS[ECC_MAX_CRYPTO_HW_SIZE * 2]; + byte hashcopy[ECC_MAX_CRYPTO_HW_SIZE] = {0}; +#else + int curveLoaded = 0; + DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); #endif - wc_ecc_curve_free(curve); - FREE_CURVE_SPECS(); + if (r == NULL || s == NULL || hash == NULL || res == NULL || key == NULL) + return ECC_BAD_ARG_E; + + /* default to invalid signature */ + *res = 0; + + /* is the IDX valid ? */ + if (wc_ecc_is_valid_idx(key->idx) == 0 || key->dp == NULL) { + return ECC_BAD_ARG_E; + } + + err = wc_ecc_check_r_s_range(key, r, s); + if (err != MP_OKAY) { + return err; + } + + keySz = key->dp->size; + +#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ + defined(WOLFSSL_ASYNC_CRYPT_SW) + if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { + if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_ECC_VERIFY)) { + WC_ASYNC_SW* sw = &key->asyncDev.sw; + sw->eccVerify.r = r; + sw->eccVerify.s = s; + sw->eccVerify.hash = hash; + sw->eccVerify.hashlen = hashlen; + sw->eccVerify.stat = res; + sw->eccVerify.key = key; + return WC_PENDING_E; + } + } +#endif + +#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) || \ + defined(WOLFSSL_CRYPTOCELL) || defined(WOLFSSL_SILABS_SE_ACCEL) || \ + defined(WOLFSSL_KCAPI_ECC) || defined(WOLFSSL_SE050) || \ + defined(WOLFSSL_XILINX_CRYPT_VERSAL) + +#ifndef WOLFSSL_SE050 + /* Extract R and S with front zero padding (if required), + * SE050 does this in port layer */ + XMEMSET(sigRS, 0, sizeof(sigRS)); + err = mp_to_unsigned_bin(r, sigRS + + (keySz - mp_unsigned_bin_size(r))); + if (err != MP_OKAY) { + return err; + } + err = mp_to_unsigned_bin(s, sigRS + keySz + + (keySz - mp_unsigned_bin_size(s))); + if (err != MP_OKAY) { + return err; + } +#endif /* WOLFSSL_SE050 */ + +#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) + err = atmel_ecc_verify(hash, sigRS, key->pubkey_raw, res); + if (err != 0) { + return err; + } + (void)hashlen; +#elif defined(WOLFSSL_CRYPTOCELL) + + /* truncate if hash is longer than key size */ + if (msgLenInBytes > keySz) { + msgLenInBytes = keySz; + } + hash_mode = cc310_hashModeECC(msgLenInBytes); + if (hash_mode == CRYS_ECPKI_HASH_OpModeLast) { + /* hash_mode = */ cc310_hashModeECC(keySz); + hash_mode = CRYS_ECPKI_HASH_SHA256_mode; + } + + /* verify the signature using the public key */ + err = CRYS_ECDSA_Verify(&sigCtxTemp, + &key->ctx.pubKey, + hash_mode, + &sigRS[0], + keySz*2, + (byte*)hash, + msgLenInBytes); + + if (err == CRYS_ECDSA_VERIFY_INCONSISTENT_VERIFY_ERROR) { + /* signature verification reported invalid signature. */ + *res = 0; /* Redundant, added for code clarity */ + err = MP_OKAY; + } + else if (err != SA_SILIB_RET_OK) { + WOLFSSL_MSG("CRYS_ECDSA_Verify failed"); + return err; + } + else { + /* valid signature. */ + *res = 1; + err = MP_OKAY; + } +#elif defined(WOLFSSL_SILABS_SE_ACCEL) + err = silabs_ecc_verify_hash(&sigRS[0], keySz * 2, + hash, hashlen, + res, key); +#elif defined(WOLFSSL_KCAPI_ECC) + err = KcapiEcc_Verify(key, hash, hashlen, sigRS, keySz * 2); + if (err == 0) { + *res = 1; + } +#elif defined(WOLFSSL_SE050) + err = se050_ecc_verify_hash_ex(hash, hashlen, r, s, key, res); +#elif defined(WOLFSSL_XILINX_CRYPT_VERSAL) + if (hashlen > sizeof(hashcopy)) + return ECC_BAD_ARG_E; + buf_reverse(hashcopy, hash, (hashlen < keySz) ? hashlen : keySz); + mp_reverse(sigRS, keySz); + mp_reverse(sigRS + keySz, keySz); + WOLFSSL_XIL_DCACHE_FLUSH_RANGE(XIL_CAST_U64(hashcopy), keySz); + WOLFSSL_XIL_DCACHE_FLUSH_RANGE(XIL_CAST_U64(key->keyRaw), keySz * 2); + WOLFSSL_XIL_DCACHE_FLUSH_RANGE(XIL_CAST_U64(sigRS), keySz * 2); + + err = XSecure_EllipticVerifySign(&(key->xSec.cinst), + xil_curve_type[key->dp->id], + XIL_CAST_U64(hashcopy), keySz, + XIL_CAST_U64(key->keyRaw), + XIL_CAST_U64(sigRS)); + if (err != XST_SUCCESS) { + WOLFSSL_XIL_ERROR("Verify ECC signature failed", err); + err = WC_HW_E; + } else { + *res = 1; + } +#endif + +#else + /* checking if private key with no public part */ + if (key->type == ECC_PRIVATEKEY_ONLY) { + WOLFSSL_MSG("Verify called with private key, generating public part"); + ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); + if (err != MP_OKAY) { + return err; + } + err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); + if (err != MP_OKAY) { + FREE_CURVE_SPECS(); + return err; + } + err = ecc_make_pub_ex(key, curve, NULL, NULL); + if (err != MP_OKAY) { + WOLFSSL_MSG("Unable to extract public key"); + wc_ecc_curve_free(curve); + FREE_CURVE_SPECS(); + return err; + } + curveLoaded = 1; + } + + err = ecc_verify_hash_sp(r, s, hash, hashlen, res, key); + if (err != 0) { + if (curveLoaded) { + wc_ecc_curve_free(curve); + FREE_CURVE_SPECS(); + } + return err; + } + +#if !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC) + if (!curveLoaded) { + ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); + if (err != 0) { + return err; + } + /* read in the specs for this curve */ + err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); + if (err != 0) { + FREE_CURVE_SPECS(); + return err; + } + } + + err = ecc_verify_hash(r, s, hash, hashlen, res, key, curve); #endif /* !WOLFSSL_SP_MATH || FREESCALE_LTC_ECC */ + + (void)curveLoaded; + wc_ecc_curve_free(curve); + FREE_CURVE_SPECS(); #endif /* WOLFSSL_ATECC508A */ (void)keySz; (void)hashlen; return err; -} #endif /* WOLFSSL_STM32_PKA */ +} #endif /* WOLF_CRYPTO_CB_ONLY_ECC */ #endif /* HAVE_ECC_VERIFY */ diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index c15f0004037..eca9729cc7b 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -764,11 +764,10 @@ static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng) int wc_CheckRsaKey(RsaKey* key) { + DECL_MP_INT_SIZE_DYN(tmp, mp_bitsused(&key->n), RSA_MAX_SIZE); #ifdef WOLFSSL_SMALL_STACK - mp_int *tmp = NULL; WC_RNG *rng = NULL; #else - mp_int tmp[1]; WC_RNG rng[1]; #endif int ret = 0; @@ -782,11 +781,14 @@ int wc_CheckRsaKey(RsaKey* key) #ifdef WOLFSSL_SMALL_STACK rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); - if (rng != NULL) - tmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_RSA); - if (rng == NULL || tmp == NULL) { + if (rng == NULL) { + return MEMORY_E; + } +#endif + NEW_MP_INT_SIZE(tmp, mp_bitsused(&key->n), NULL, DYNAMIC_TYPE_RSA); +#ifdef MP_INT_SIZE_CHECK_NULL + if (tmp == NULL) { XFREE(rng, NULL, DYNAMIC_TYPE_RNG); - XFREE(tmp, NULL, DYNAMIC_TYPE_RSA); return MEMORY_E; } #endif @@ -797,7 +799,7 @@ int wc_CheckRsaKey(RsaKey* key) SAVE_VECTOR_REGISTERS(ret = _svr_ret;); if (ret == 0) { - if (mp_init(tmp) != MP_OKAY) + if (INIT_MP_INT_SIZE(tmp, mp_bitsused(&key->n)) != MP_OKAY) ret = MP_INIT_E; } @@ -916,8 +918,8 @@ int wc_CheckRsaKey(RsaKey* key) RESTORE_VECTOR_REGISTERS(); wc_FreeRng(rng); + FREE_MP_INT_SIZE(tmp, NULL, DYNAMIC_TYPE_RSA); #ifdef WOLFSSL_SMALL_STACK - XFREE(tmp, NULL, DYNAMIC_TYPE_RSA); XFREE(rng, NULL, DYNAMIC_TYPE_RNG); #elif defined(WOLFSSL_CHECK_MEM_ZERO) mp_memzero_check(tmp); @@ -2471,35 +2473,12 @@ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, } #else #ifndef WOLF_CRYPTO_CB_ONLY_RSA -static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, - word32* outLen, int type, RsaKey* key, WC_RNG* rng) +#ifdef WOLFSSL_HAVE_SP_RSA +static int RsaFunction_SP(const byte* in, word32 inLen, byte* out, + word32* outLen, int type, RsaKey* key, WC_RNG* rng) { -#if !defined(WOLFSSL_SP_MATH) -#ifdef WOLFSSL_SMALL_STACK - mp_int* tmp; -#ifdef WC_RSA_BLINDING - mp_int* rnd; - mp_int* rndi; -#endif -#else - mp_int tmp[1]; -#ifdef WC_RSA_BLINDING - mp_int rnd[1], rndi[1]; -#endif -#endif - int ret = 0; -#endif - word32 keyLen = wc_RsaEncryptSize(key); - - if (inLen > keyLen) { - WOLFSSL_MSG("Expected that inLen be no longer RSA key length"); - return BAD_FUNC_ARG; - } + (void)rng; - if (mp_iseven(&key->n)) { - return MP_VAL; - } -#ifdef WOLFSSL_HAVE_SP_RSA #ifndef WOLFSSL_SP_NO_2048 if (mp_count_bits(&key->n) == 2048) { switch(type) { @@ -2593,215 +2572,201 @@ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, } } #endif -#endif /* WOLFSSL_HAVE_SP_RSA */ -#if defined(WOLFSSL_SP_MATH) - (void)rng; - #ifndef WOLFSSL_HAVE_SP_RSA - (void)in; - (void)inLen; - (void)out; - (void)outLen; - (void)type; - (void)key; - #error RSA SP option invalid (enable WOLFSSL_HAVE_SP_RSA or disable WOLFSSL_SP_MATH) - return NOT_COMPILED_IN; - #else - WOLFSSL_MSG("SP Key Size Error"); + /* SP not able to do operation. */ return WC_KEY_SIZE_E; - #endif -#else - (void)rng; +} +#endif -#ifdef WOLFSSL_SMALL_STACK - tmp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA); - if (tmp == NULL) - return MEMORY_E; -#ifdef WC_RSA_BLINDING +#if !defined(WOLFSSL_SP_MATH) #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY) - rnd = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA); - if (rnd == NULL) { - XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA); +static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng) +{ + int ret = 0; +#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG) + DECL_MP_INT_SIZE_DYN(rnd, mp_bitsused(&key->n), RSA_MAX_SIZE); + DECL_MP_INT_SIZE_DYN(rndi, mp_bitsused(&key->n), RSA_MAX_SIZE); +#endif /* WC_RSA_BLINDING && !WC_NO_RNG */ + + (void)rng; + +#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG) + NEW_MP_INT_SIZE(rnd, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA); + NEW_MP_INT_SIZE(rndi, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA); +#ifdef MP_INT_SIZE_CHECK_NULL + if ((rnd == NULL) || (rndi == NULL)) { + FREE_MP_INT_SIZE(rnd, key->heap, DYNAMIC_TYPE_RSA); + FREE_MP_INT_SIZE(rndi, key->heap, DYNAMIC_TYPE_RSA); return MEMORY_E; } - rndi = rnd + 1; -#else - rnd = NULL; - rndi = NULL; #endif -#endif /* WC_RSA_BLINDING */ -#endif /* WOLFSSL_SMALL_STACK */ - if (mp_init(tmp) != MP_OKAY) + if ((INIT_MP_INT_SIZE(rnd, mp_bitsused(&key->n)) != MP_OKAY) || + (INIT_MP_INT_SIZE(rndi, mp_bitsused(&key->n)) != MP_OKAY)) { ret = MP_INIT_E; + } -#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY) -#ifdef WC_RSA_BLINDING if (ret == 0) { - if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) { - if (mp_init_multi(rnd, rndi, NULL, NULL, NULL, NULL) != MP_OKAY) { - mp_clear(tmp); - ret = MP_INIT_E; - } + /* blind */ + ret = mp_rand(rnd, get_digit_count(&key->n), rng); + } + if (ret == 0) { + /* rndi = 1/rnd mod n */ + if (mp_invmod(rnd, &key->n, rndi) != MP_OKAY) { + ret = MP_INVMOD_E; } } -#endif -#endif + if (ret == 0) { + #ifdef WOLFSSL_CHECK_MEM_ZERO + mp_memzero_add("RSA Private rnd", rnd); + mp_memzero_add("RSA Private rndi", rndi); + #endif -#ifndef TEST_UNPAD_CONSTANT_TIME - if (ret == 0 && mp_read_unsigned_bin(tmp, in, inLen) != MP_OKAY) - ret = MP_READ_E; + /* rnd = rnd^e */ + #ifndef WOLFSSL_SP_MATH_ALL + if (mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY) { + ret = MP_EXPTMOD_E; + } + #else + if (mp_exptmod_nct(rnd, &key->e, &key->n, rnd) != MP_OKAY) { + ret = MP_EXPTMOD_E; + } + #endif + } -#ifdef WOLFSSL_CHECK_MEM_ZERO if (ret == 0) { - mp_memzero_add("RSA sync tmp", tmp); + /* tmp = tmp*rnd mod n */ + if (mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY) { + ret = MP_MULMOD_E; + } } -#endif +#endif /* WC_RSA_BLINDING && !WC_NO_RNG */ +#ifdef RSA_LOW_MEM /* half as much memory but twice as slow */ if (ret == 0) { - switch(type) { - #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY) - case RSA_PRIVATE_DECRYPT: - case RSA_PRIVATE_ENCRYPT: - { - #if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG) - /* blind */ - ret = mp_rand(rnd, get_digit_count(&key->n), rng); - if (ret != 0) - break; - /* rndi = 1/rnd mod n */ - if (mp_invmod(rnd, &key->n, rndi) != MP_OKAY) { - ret = MP_INVMOD_E; - break; - } - #ifdef WOLFSSL_CHECK_MEM_ZERO - mp_memzero_add("RSA sync rnd", rnd); - mp_memzero_add("RSA sync rndi", rndi); - #endif + if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) { + ret = MP_EXPTMOD_E; + } + } +#else + if (ret == 0) { + mp_int* tmpa = tmp; +#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG) + mp_int* tmpb = rnd; +#else + DECL_MP_INT_SIZE_DYN(tmpb, mp_bitsused(&key->n), RSA_MAX_SIZE); +#endif - /* rnd = rnd^e */ - #ifndef WOLFSSL_SP_MATH_ALL - if (mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY) { - ret = MP_EXPTMOD_E; - break; - } - #else - if (mp_exptmod_nct(rnd, &key->e, &key->n, rnd) != MP_OKAY) { - ret = MP_EXPTMOD_E; - break; - } - #endif +#if !defined(WC_RSA_BLINDING) || defined(WC_NO_RNG) + NEW_MP_INT_SIZE(tmpb, mp_bitsused(&key->n), key->heap, + DYNAMIC_TYPE_RSA); + #ifdef MP_INT_SIZE_CHECK_NULL + if (tmpb == NULL) { + ret = MEMORY_E; + } + #endif + if ((ret == 0) && INIT_MP_INT_SIZE(tmpb, mp_bitsused(&key->n)) != + MP_OKAY) { + ret = MP_INIT_E; + } +#endif - /* tmp = tmp*rnd mod n */ - if (mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY) { - ret = MP_MULMOD_E; - break; - } - #endif /* WC_RSA_BLINDING && !WC_NO_RNG */ + #ifdef WOLFSSL_CHECK_MEM_ZERO + if (ret == 0) { + mp_memzero_add("RSA Sync tmpb", tmpb); + } + #endif - #ifdef RSA_LOW_MEM /* half as much memory but twice as slow */ - if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) { - ret = MP_EXPTMOD_E; - break; - } - #else - { - #ifdef WOLFSSL_SMALL_STACK - mp_int* tmpa; - mp_int* tmpb = NULL; - #else - mp_int tmpa[1], tmpb[1]; - #endif - int cleara = 0, clearb = 0; + /* tmpb = tmp^dQ mod q */ + if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q, tmpb) != MP_OKAY) + ret = MP_EXPTMOD_E; - #ifdef WOLFSSL_SMALL_STACK - tmpa = (mp_int*)XMALLOC(sizeof(mp_int) * 2, - key->heap, DYNAMIC_TYPE_RSA); - if (tmpa != NULL) - tmpb = tmpa + 1; - else - ret = MEMORY_E; - if (ret == 0) - #endif - { - if (mp_init(tmpa) != MP_OKAY) - ret = MP_INIT_E; - else - cleara = 1; - } + /* tmpa = tmp^dP mod p */ + if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p, tmpa) != MP_OKAY) + ret = MP_EXPTMOD_E; - if (ret == 0) { - if (mp_init(tmpb) != MP_OKAY) - ret = MP_INIT_E; - else - clearb = 1; - } + /* tmp = (tmp - tmpb) * qInv (mod p) */ + #if (defined(WOLFSSL_SP_MATH) || (defined(WOLFSSL_SP_MATH_ALL)) && \ + !defined(WOLFSSL_SP_INT_NEGATIVE)) + if (ret == 0 && mp_submod(tmpa, tmpb, &key->p, tmp) != MP_OKAY) + ret = MP_SUB_E; + #else + if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY) + ret = MP_SUB_E; + #endif - #ifdef WOLFSSL_CHECK_MEM_ZERO - if (ret == 0) { - mp_memzero_add("RSA Sync tmpa", tmpa); - mp_memzero_add("RSA Sync tmpb", tmpb); - } - #endif + if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p, tmp) != MP_OKAY) + ret = MP_MULMOD_E; - /* tmpa = tmp^dP mod p */ - if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p, - tmpa) != MP_OKAY) - ret = MP_EXPTMOD_E; + /* tmp = tmpb + q * tmp */ + if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY) + ret = MP_MUL_E; - /* tmpb = tmp^dQ mod q */ - if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q, - tmpb) != MP_OKAY) - ret = MP_EXPTMOD_E; + if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY) + ret = MP_ADD_E; - /* tmp = (tmpa - tmpb) * qInv (mod p) */ -#if defined(WOLFSSL_SP_MATH) || (defined(WOLFSSL_SP_MATH_ALL) && \ - !defined(WOLFSSL_SP_INT_NEGATIVE)) - if (ret == 0 && mp_submod(tmpa, tmpb, &key->p, tmp) != MP_OKAY) - ret = MP_SUB_E; -#else - if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY) - ret = MP_SUB_E; +#if !defined(WC_RSA_BLINDING) || defined(WC_NO_RNG) + mp_forcezero(tmpb); + FREE_MP_INT_SIZE(tmpb, key->heap, DYNAMIC_TYPE_RSA); + #if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO) + mp_memzero_check(tmpb); + #endif #endif + } +#endif /* RSA_LOW_MEM */ - if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p, - tmp) != MP_OKAY) - ret = MP_MULMOD_E; +#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG) + /* unblind */ + if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY) + ret = MP_MULMOD_E; - /* tmp = tmpb + q * tmp */ - if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY) - ret = MP_MUL_E; + mp_forcezero(rndi); + mp_forcezero(rnd); + FREE_MP_INT_SIZE(rndi, key->heap, DYNAMIC_TYPE_RSA); + FREE_MP_INT_SIZE(rnd, key->heap, DYNAMIC_TYPE_RSA); +#if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO) + mp_memzero_check(rnd); + mp_memzero_check(rndi); +#endif +#endif /* WC_RSA_BLINDING && !WC_NO_RNG */ + return ret; +} +#endif - if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY) - ret = MP_ADD_E; +static int RsaFunctionSync(const byte* in, word32 inLen, byte* out, + word32* outLen, int type, RsaKey* key, WC_RNG* rng) +{ + DECL_MP_INT_SIZE_DYN(tmp, mp_bitsused(&key->n), RSA_MAX_SIZE); + int ret = 0; - #ifdef WOLFSSL_SMALL_STACK - if (tmpa != NULL) - #endif - { - if (cleara) { - mp_forcezero(tmpa); - } - if (clearb) { - mp_forcezero(tmpb); - } - #ifdef WOLFSSL_SMALL_STACK - /* tmpb is allocated after tmpa. */ - XFREE(tmpa, key->heap, DYNAMIC_TYPE_RSA); - #elif defined(WOLFSSL_CHECK_MEM_ZERO) - mp_memzero_check(tmpb); - mp_memzero_check(tmpa); - #endif - } - } /* tmpa/b scope */ - #endif /* RSA_LOW_MEM */ + (void)rng; - #ifdef WC_RSA_BLINDING - /* unblind */ - if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY) - ret = MP_MULMOD_E; - #endif /* WC_RSA_BLINDING */ + NEW_MP_INT_SIZE(tmp, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA); +#ifdef MP_INT_SIZE_CHECK_NULL + if (tmp == NULL) + return MEMORY_E; +#endif + if (INIT_MP_INT_SIZE(tmp, mp_bitsused(&key->n)) != MP_OKAY) + ret = MP_INIT_E; + +#ifndef TEST_UNPAD_CONSTANT_TIME + if (ret == 0 && mp_read_unsigned_bin(tmp, in, inLen) != MP_OKAY) + ret = MP_READ_E; + +#ifdef WOLFSSL_CHECK_MEM_ZERO + if (ret == 0) { + mp_memzero_add("RSA sync tmp", tmp); + } +#endif + + if (ret == 0) { + switch(type) { + #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY) + case RSA_PRIVATE_DECRYPT: + case RSA_PRIVATE_ENCRYPT: + { + ret = RsaFunctionPrivate(tmp, key, rng); break; } #endif @@ -2817,43 +2782,70 @@ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, } if (ret == 0) { - if (keyLen > *outLen) - ret = RSA_BUFFER_E; - } - - if (ret == 0) { - *outLen = keyLen; - if (mp_to_unsigned_bin_len(tmp, out, keyLen) != MP_OKAY) + if (mp_to_unsigned_bin_len(tmp, out, *outLen) != MP_OKAY) ret = MP_TO_E; } #else (void)type; (void)key; XMEMCPY(out, in, inLen); - *outLen = inLen; #endif mp_forcezero(tmp); -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA); -#elif defined(WOLFSSL_CHECK_MEM_ZERO) + FREE_MP_INT_SIZE(tmp, key->heap, DYNAMIC_TYPE_RSA); +#if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO) mp_memzero_check(tmp); #endif -#ifdef WC_RSA_BLINDING - if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) { - mp_forcezero(rndi); - mp_forcezero(rnd); + return ret; +} +#endif /* !WOLFSSL_SP_MATH */ + +static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, + word32* outLen, int type, RsaKey* key, WC_RNG* rng) +{ +#ifdef WOLFSSL_HAVE_SP_RSA + int ret; +#endif + + word32 keyLen = wc_RsaEncryptSize(key); + + if (inLen > keyLen) { + WOLFSSL_MSG("Expected that inLen be no longer RSA key length"); + return BAD_FUNC_ARG; } -#ifdef WOLFSSL_SMALL_STACK - XFREE(rnd, key->heap, DYNAMIC_TYPE_RSA); -#elif defined(WOLFSSL_CHECK_MEM_ZERO) - if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) { - mp_memzero_check(rnd); - mp_memzero_check(rndi); + if (keyLen > *outLen) { + WOLFSSL_MSG("Expected that outLen be no shorter RSA key length"); + return RSA_BUFFER_E; + } + + if (mp_iseven(&key->n)) { + return MP_VAL; } + +#ifdef WOLFSSL_HAVE_SP_RSA + ret = RsaFunction_SP(in, inLen, out, outLen, type, key, rng); + if (ret != WC_KEY_SIZE_E) + return ret; +#endif /* WOLFSSL_HAVE_SP_RSA */ + +#if defined(WOLFSSL_SP_MATH) + (void)rng; +#ifndef WOLFSSL_HAVE_SP_RSA + (void)in; + (void)inLen; + (void)out; + (void)outLen; + (void)type; + (void)key; + #error RSA SP option invalid (enable WOLFSSL_HAVE_SP_RSA or disable WOLFSSL_SP_MATH) + return NOT_COMPILED_IN; +#else + WOLFSSL_MSG("SP Key Size Error"); + return WC_KEY_SIZE_E; #endif -#endif /* WC_RSA_BLINDING */ - return ret; +#else + *outLen = keyLen; + return RsaFunctionSync(in, inLen, out, outLen, type, key, rng); #endif /* WOLFSSL_SP_MATH */ } #endif /* WOLF_CRYPTO_CB_ONLY_RSA */ @@ -3129,6 +3121,53 @@ int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig, } #endif /* WOLFSSL_CRYPTOCELL */ +#ifndef WOLF_CRYPTO_CB_ONLY_RSA +#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(TEST_UNPAD_CONSTANT_TIME) && !defined(NO_RSA_BOUNDS_CHECK) +/* Check that 1 < in < n-1. (Requirement of 800-56B.) */ +static int RsaFunctionCheckIn(const byte* in, word32 inLen, RsaKey* key, + int checkSmallCt) +{ + int ret = 0; + DECL_MP_INT_SIZE_DYN(c, mp_bitsused(&key->n), RSA_MAX_SIZE); + + NEW_MP_INT_SIZE(c, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA); +#ifdef MP_INT_SIZE_CHECK_NULL + if (c == NULL) + ret = MEMORY_E; +#endif + + if (ret == 0 && INIT_MP_INT_SIZE(c, mp_bitsused(&key->n)) != MP_OKAY) { + ret = MP_INIT_E; + } + if (ret == 0) { + if (mp_read_unsigned_bin(c, in, inLen) != 0) + ret = MP_READ_E; + } + if (ret == 0) { + /* check c > 1 */ + if (checkSmallCt && (mp_cmp_d(c, 1) != MP_GT)) + ret = RSA_OUT_OF_RANGE_E; + } + if (ret == 0) { + /* add c+1 */ + if (mp_add_d(c, 1, c) != MP_OKAY) + ret = MP_ADD_E; + } + if (ret == 0) { + /* check c+1 < n */ + if (mp_cmp(c, &key->n) != MP_LT) + ret = RSA_OUT_OF_RANGE_E; + } + mp_clear(c); + + FREE_MP_INT_SIZE(c, key->heap, DYNAMIC_TYPE_RSA); + + return ret; +} +#endif /* !WOLFSSL_RSA_VERIFY_ONLY && !TEST_UNPAD_CONSTANT_TIME && + * !NO_RSA_BOUNDS_CHECK */ +#endif /* WOLF_CRYPTO_CB_ONLY_RSA */ + static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng, int checkSmallCt) @@ -3169,47 +3208,7 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, if (type == RSA_PRIVATE_DECRYPT && key->state == RSA_STATE_DECRYPT_EXPTMOD) { - /* Check that 1 < in < n-1. (Requirement of 800-56B.) */ -#ifdef WOLFSSL_SMALL_STACK - mp_int* c; -#else - mp_int c[1]; -#endif - -#ifdef WOLFSSL_SMALL_STACK - c = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA); - if (c == NULL) - ret = MEMORY_E; -#endif - - if (ret == 0 && mp_init(c) != MP_OKAY) - ret = MP_INIT_E; - if (ret == 0) { - if (mp_read_unsigned_bin(c, in, inLen) != 0) - ret = MP_READ_E; - } - if (ret == 0) { - /* check c > 1 */ - if (checkSmallCt && (mp_cmp_d(c, 1) != MP_GT)) - ret = RSA_OUT_OF_RANGE_E; - } - if (ret == 0) { - /* add c+1 */ - if (mp_add_d(c, 1, c) != MP_OKAY) - ret = MP_ADD_E; - } - if (ret == 0) { - /* check c+1 < n */ - if (mp_cmp(c, &key->n) != MP_LT) - ret = RSA_OUT_OF_RANGE_E; - } - mp_clear(c); - -#ifdef WOLFSSL_SMALL_STACK - if (c != NULL) - XFREE(c, key->heap, DYNAMIC_TYPE_RSA); -#endif - + ret = RsaFunctionCheckIn(in, inLen, key, checkSmallCt); if (ret != 0) { RESTORE_VECTOR_REGISTERS(); return ret; diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index a959a317c51..99cec076012 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -34,6 +34,19 @@ This library provides single precision (SP) integer math functions. #if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) +#if (!defined(WOLFSSL_SMALL_STACK) && !defined(SP_ALLOC)) || \ + defined(WOLFSSL_SP_NO_MALLOC) +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(WOLFSSL_SP_NO_DYN_STACK) +#pragma GCC diagnostic push +/* We are statically declaring a variable smaller than sp_int. + * We track available memory in the 'size' field. + * Disable warnings of sp_int being partly outside array bounds of variable. + */ +#pragma GCC diagnostic ignored "-Warray-bounds" +#endif +#endif + #ifdef NO_INLINE #include #else @@ -89,8 +102,9 @@ This library provides single precision (SP) integer math functions. * WOLFSSL_SP_INT_DIGIT_ALIGN Enable when unaligned access of sp_int_digit * pointer is not allowed. * WOLFSSL_SP_NO_DYN_STACK Disable use of dynamic stack items. - * Used with small code size and not small stack. + * Dynamic arrays used when not small stack. * WOLFSSL_SP_FAST_MODEXP Allow fast mod_exp with small C code + * WOLFSSL_SP_LOW_MEM Use algorithms that use less memory. */ /* TODO: WOLFSSL_SP_SMALL is incompatible with clang-12+ -Os. */ @@ -109,7 +123,7 @@ This library provides single precision (SP) integer math functions. sp_int* n = NULL #else #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_DYN_STACK) + !defined(WOLFSSL_SP_NO_DYN_STACK) /* Declare a variable on the stack with the required data size. */ #define DECL_SP_INT(n, s) \ byte n##d[MP_INT_SIZEOF(s)]; \ @@ -187,16 +201,20 @@ This library provides single precision (SP) integer math functions. #endif +/* Declare a variable that will be assigned a value on XMALLOC. */ +#define DECL_DYN_SP_INT_ARRAY(n, s, c) \ + sp_int* n##d = NULL; \ + sp_int* (n)[c] = { NULL, } + /* DECL_SP_INT_ARRAY: Declare array of 'sp_int'. */ #if (defined(WOLFSSL_SMALL_STACK) || defined(SP_ALLOC)) && \ !defined(WOLFSSL_SP_NO_MALLOC) /* Declare a variable that will be assigned a value on XMALLOC. */ #define DECL_SP_INT_ARRAY(n, s, c) \ - sp_int* n##d = NULL; \ - sp_int* (n)[c] = { NULL, } + DECL_DYN_SP_INT_ARRAY(n, s, c) #else #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_DYN_STACK) + !defined(WOLFSSL_SP_NO_DYN_STACK) /* Declare a variable on the stack with the required data size. */ #define DECL_SP_INT_ARRAY(n, s, c) \ byte n##d[MP_INT_SIZEOF(s) * (c)]; \ @@ -209,38 +227,41 @@ This library provides single precision (SP) integer math functions. #endif #endif -/* ALLOC_SP_INT_ARRAY: Allocate an array of 'sp_int's of required size. */ -#if (defined(WOLFSSL_SMALL_STACK) || defined(SP_ALLOC)) && \ - !defined(WOLFSSL_SP_NO_MALLOC) - /* Dynamically allocate just enough data to support multiple sp_ints of the - * required size. Use pointers into data to make up array and set sizes. - */ - #define ALLOC_SP_INT_ARRAY(n, s, c, err, h) \ - do { \ - if (((err) == MP_OKAY) && ((s) > SP_INT_DIGITS)) { \ - (err) = MP_VAL; \ - } \ - if ((err) == MP_OKAY) { \ - n##d = (sp_int*)XMALLOC(MP_INT_SIZEOF(s) * (c), (h), \ +/* Dynamically allocate just enough data to support multiple sp_ints of the + * required size. Use pointers into data to make up array and set sizes. + */ +#define ALLOC_DYN_SP_INT_ARRAY(n, s, c, err, h) \ +do { \ + if (((err) == MP_OKAY) && ((s) > SP_INT_DIGITS)) { \ + (err) = MP_VAL; \ + } \ + if ((err) == MP_OKAY) { \ + n##d = (sp_int*)XMALLOC(MP_INT_SIZEOF(s) * (c), (h), \ DYNAMIC_TYPE_BIGINT); \ - if (n##d == NULL) { \ - (err) = MP_MEM; \ - } \ - else { \ - int n##ii; \ - (n)[0] = n##d; \ - (n)[0]->size = (s); \ - for (n##ii = 1; n##ii < (c); n##ii++) { \ - (n)[n##ii] = MP_INT_NEXT((n)[n##ii-1], s); \ - (n)[n##ii]->size = (s); \ - } \ + if (n##d == NULL) { \ + (err) = MP_MEM; \ + } \ + else { \ + int n##ii; \ + (n)[0] = n##d; \ + (n)[0]->size = (s); \ + for (n##ii = 1; n##ii < (c); n##ii++) { \ + (n)[n##ii] = MP_INT_NEXT((n)[n##ii-1], s); \ + (n)[n##ii]->size = (s); \ } \ } \ } \ - while (0) +} \ +while (0) + +/* ALLOC_SP_INT_ARRAY: Allocate an array of 'sp_int's of required size. */ +#if (defined(WOLFSSL_SMALL_STACK) || defined(SP_ALLOC)) && \ + !defined(WOLFSSL_SP_NO_MALLOC) + #define ALLOC_SP_INT_ARRAY(n, s, c, err, h) \ + ALLOC_DYN_SP_INT_ARRAY(n, s, c, err, h) #else #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_DYN_STACK) + !defined(WOLFSSL_SP_NO_DYN_STACK) /* Data declared on stack that supports multiple sp_ints of the * required size. Use pointers into data to make up array and set sizes. */ @@ -281,17 +302,20 @@ This library provides single precision (SP) integer math functions. #endif #endif +/* Free data variable that was dynamically allocated. */ +#define FREE_DYN_SP_INT_ARRAY(n, h) \ +do { \ + if (n##d != NULL) { \ + XFREE(n##d, h, DYNAMIC_TYPE_BIGINT); \ + } \ +} \ +while (0) + /* FREE_SP_INT_ARRAY: Free an array of 'sp_int'. */ #if (defined(WOLFSSL_SMALL_STACK) || defined(SP_ALLOC)) && \ !defined(WOLFSSL_SP_NO_MALLOC) - /* Free data variable that was dynamically allocated. */ #define FREE_SP_INT_ARRAY(n, h) \ - do { \ - if (n##d != NULL) { \ - XFREE(n##d, h, DYNAMIC_TYPE_BIGINT); \ - } \ - } \ - while (0) + FREE_DYN_SP_INT_ARRAY(n, h) #else /* Nothing to do as data declared on stack. */ #define FREE_SP_INT_ARRAY(n, h) @@ -8256,13 +8280,18 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) /* Set to temporary when not reusing. */ if (sa == NULL) { sa = td[i++]; + _sp_init_size(sa, a->used + 1); } if (tr == NULL) { tr = td[i]; + _sp_init_size(tr, a->used - d->used + 2); } #else sa = td[2]; tr = td[3]; + + _sp_init_size(sa, a->used + 1); + _sp_init_size(tr, a->used - d->used + 2); #endif sd = td[0]; trial = td[1]; @@ -8270,18 +8299,6 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) /* Initialize sizes to minimal values. */ _sp_init_size(sd, d->used + 1); _sp_init_size(trial, a->used + 1); - #if (defined(WOLFSSL_SMALL_STACK) || defined(SP_ALLOC)) && \ - !defined(WOLFSSL_SP_NO_MALLOC) - if (sa != rem) { - _sp_init_size(sa, a->used + 1); - } - if (tr != r) { - _sp_init_size(tr, a->used - d->used + 2); - } - #else - _sp_init_size(sa, a->used + 1); - _sp_init_size(tr, a->used - d->used + 2); - #endif /* Move divisor to top of word. Adjust dividend as well. */ s = sp_count_bits(d); @@ -8348,6 +8365,7 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ !defined(WOLFSSL_RSA_PUBLIC_ONLY)) #ifndef FREESCALE_LTC_TFM +#ifdef WOLFSSL_SP_INT_NEGATIVE /* Calculate the remainder of dividing a by m: r = a mod m. * * @param [in] a SP integer to reduce. @@ -8355,31 +8373,14 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) * @param [out] r SP integer to store result in. * * @return MP_OKAY on success. - * @return MP_VAL when a, m or r is NULL or m is 0. + * @return MP_MEM when dynamic memory allocation fails. */ -int sp_mod(const sp_int* a, const sp_int* m, sp_int* r) +static int _sp_mod(const sp_int* a, const sp_int* m, sp_int* r) { int err = MP_OKAY; -#ifdef WOLFSSL_SP_INT_NEGATIVE /* Remainder will start as a. */ DECL_SP_INT(t, (a == NULL) ? 1 : a->used + 1); -#endif /* WOLFSSL_SP_INT_NEGATIVE */ - - /* Validate parameters. */ - if ((a == NULL) || (m == NULL) || (r == NULL)) { - err = MP_VAL; - } - /* Ensure a isn't too big a number to operate on. */ - else if (a->used >= SP_INT_DIGITS) { - err = MP_VAL; - } -#ifndef WOLFSSL_SP_INT_NEGATIVE - if (err == MP_OKAY) { - /* Use divide to calculate remainder and don't get quotient. */ - err = sp_div(a, m, NULL, r); - } -#else /* In case remainder is modulus - allocate temporary. */ ALLOC_SP_INT(t, a->used + 1, err, NULL); if (err == MP_OKAY) { @@ -8396,8 +8397,50 @@ int sp_mod(const sp_int* a, const sp_int* m, sp_int* r) err = sp_copy(t, r); } } - FREE_SP_INT(t, NULL); + + return err; +} +#endif + +/* Calculate the remainder of dividing a by m: r = a mod m. + * + * @param [in] a SP integer to reduce. + * @param [in] m SP integer that is the modulus. + * @param [out] r SP integer to store result in. + * + * @return MP_OKAY on success. + * @return MP_VAL when a, m or r is NULL or m is 0. + * @return MP_MEM when dynamic memory allocation fails. + */ +int sp_mod(const sp_int* a, const sp_int* m, sp_int* r) +{ + int err = MP_OKAY; + + /* Validate parameters. */ + if ((a == NULL) || (m == NULL) || (r == NULL)) { + err = MP_VAL; + } + /* Ensure a isn't too big a number to operate on. */ + else if (a->used >= SP_INT_DIGITS) { + err = MP_VAL; + } + +#ifndef WOLFSSL_SP_INT_NEGATIVE + if (err == MP_OKAY) { + /* Use divide to calculate remainder and don't get quotient. */ + err = sp_div(a, m, NULL, r); + } +#else + if ((err == MP_OKAY) && (r != m)) { + err = sp_div(a, m, NULL, r); + if ((!sp_iszero(r)) && (r->sign != m->sign)) { + err = sp_add(r, m, r); + } + } + else if (err == MP_OKAY) { + err = _sp_mod(a, m, r); + } #endif /* WOLFSSL_SP_INT_NEGATIVE */ return err; @@ -8438,14 +8481,14 @@ static int _sp_mul_nxn(const sp_int* a, const sp_int* b, sp_int* r) #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_DYN_STACK) - sp_int_digit t[a->used * 2]; + !defined(WOLFSSL_SP_NO_DYN_STACK) + sp_int_digit t[a->used]; #else - sp_int_digit t[SP_INT_DIGITS]; + sp_int_digit t[SP_INT_DIGITS / 2]; #endif #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * (a->used * 2), NULL, + t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * a->used, NULL, DYNAMIC_TYPE_BIGINT); if (t == NULL) { err = MP_MEM; @@ -8480,14 +8523,14 @@ static int _sp_mul_nxn(const sp_int* a, const sp_int* b, sp_int* r) for (; i < a->used; i++, dp--) { SP_ASM_MUL_ADD(l, h, o, a->dp[i], dp[0]); } - t[k] = l; + r->dp[k] = l; l = h; h = o; o = 0; } - t[k] = l; + r->dp[k] = l; + XMEMCPY(r->dp, t, a->used * sizeof(sp_int_digit)); r->used = k + 1; - XMEMCPY(r->dp, t, r->used * sizeof(sp_int_digit)); sp_clamp(r); } @@ -8517,7 +8560,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_DYN_STACK) + !defined(WOLFSSL_SP_NO_DYN_STACK) sp_int_digit t[a->used + b->used]; #else sp_int_digit t[SP_INT_DIGITS]; @@ -8595,7 +8638,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_DYN_STACK) + !defined(WOLFSSL_SP_NO_DYN_STACK) sp_int_digit t[a->used + b->used]; #else sp_int_digit t[SP_INT_DIGITS]; @@ -8664,7 +8707,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #ifndef WOLFSSL_SP_SMALL #if !defined(WOLFSSL_HAVE_SP_ECC) && defined(HAVE_ECC) -#if SP_WORD_SIZE == 64 +#if (SP_WORD_SIZE == 64 && SP_INT_BITS >= 256) #ifndef SQR_MUL_ASM /* Multiply a by b and store in r: r = a * b * @@ -8852,7 +8895,7 @@ static int _sp_mul_4(const sp_int* a, const sp_int* b, sp_int* r) } #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 64 */ -#if SP_WORD_SIZE == 64 +#if (SP_WORD_SIZE == 64 && SP_INT_BITS >= 384) #ifdef SQR_MUL_ASM /* Multiply a by b and store in r: r = a * b * @@ -8955,7 +8998,7 @@ static int _sp_mul_6(const sp_int* a, const sp_int* b, sp_int* r) } #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 64 */ -#if SP_WORD_SIZE == 32 +#if (SP_WORD_SIZE == 32 && SP_INT_BITS >= 256) #ifdef SQR_MUL_ASM /* Multiply a by b and store in r: r = a * b * @@ -9102,7 +9145,7 @@ static int _sp_mul_8(const sp_int* a, const sp_int* b, sp_int* r) } #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 32 */ -#if SP_WORD_SIZE == 32 +#if (SP_WORD_SIZE == 32 && SP_INT_BITS >= 384) #ifdef SQR_MUL_ASM /* Multiply a by b and store in r: r = a * b * @@ -11307,13 +11350,13 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) else #ifndef WOLFSSL_SP_SMALL #if !defined(WOLFSSL_HAVE_SP_ECC) && defined(HAVE_ECC) -#if SP_WORD_SIZE == 64 +#if (SP_WORD_SIZE == 64 && SP_INT_BITS >= 256) if ((a->used == 4) && (b->used == 4)) { err = _sp_mul_4(a, b, r); } else #endif /* SP_WORD_SIZE == 64 */ -#if SP_WORD_SIZE == 64 +#if (SP_WORD_SIZE == 64 && SP_INT_BITS >= 384) #ifdef SQR_MUL_ASM if ((a->used == 6) && (b->used == 6)) { err = _sp_mul_6(a, b, r); @@ -11321,7 +11364,7 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) else #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 64 */ -#if SP_WORD_SIZE == 32 +#if (SP_WORD_SIZE == 32 && SP_INT_BITS >= 256) #ifdef SQR_MUL_ASM if ((a->used == 8) && (b->used == 8)) { err = _sp_mul_8(a, b, r); @@ -11329,7 +11372,7 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) else #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 32 */ -#if SP_WORD_SIZE == 32 +#if (SP_WORD_SIZE == 32 && SP_INT_BITS >= 384) #ifdef SQR_MUL_ASM if ((a->used == 12) && (b->used == 12)) { err = _sp_mul_12(a, b, r); @@ -11415,6 +11458,32 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #if defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFCRYPT_HAVE_ECCSI) || \ (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) || defined(OPENSSL_ALL) +static int _sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, + sp_int* r) +{ + int err = MP_OKAY; + + /* Create temporary for multiplication result. */ + DECL_SP_INT(t, a->used + b->used); + ALLOC_SP_INT(t, a->used + b->used, err, NULL); + if (err == MP_OKAY) { + err = sp_init_size(t, a->used + b->used); + } + + /* Multiply and reduce. */ + if (err == MP_OKAY) { + err = sp_mul(a, b, t); + } + if (err == MP_OKAY) { + err = sp_mod(t, m, r); + } + + /* Dispose of an allocated SP int. */ + FREE_SP_INT(t, NULL); + + return err; +} + /* Multiply a by b mod m and store in r: r = (a * b) mod m * * @param [in] a SP integer to multiply. @@ -11459,23 +11528,7 @@ int sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) } } else if (err == MP_OKAY) { - /* Create temporary for multiplication result. */ - DECL_SP_INT(t, a->used + b->used); - ALLOC_SP_INT(t, a->used + b->used, err, NULL); - if (err == MP_OKAY) { - err = sp_init_size(t, a->used + b->used); - } - - /* Multiply and reduce. */ - if (err == MP_OKAY) { - err = sp_mul(a, b, t); - } - if (err == MP_OKAY) { - err = sp_mod(t, m, r); - } - - /* Dispose of an allocated SP int. */ - FREE_SP_INT(t, NULL); + _sp_mulmod(a, b, m, r); } #if 0 @@ -11581,7 +11634,8 @@ static int _sp_invmod_bin(const sp_int* a, const sp_int* m, sp_int* u, return err; } -#if !defined(WOLFSSL_SP_SMALL) && (!defined(NO_RSA) || !defined(NO_DH)) +#if !defined(WOLFSSL_SP_LOW_MEM) && !defined(WOLFSSL_SP_SMALL) && \ + (!defined(NO_RSA) || !defined(NO_DH)) /* Calculates the multiplicative inverse in the field. r*a = x*m + 1 * Extended Euclidean Algorithm. NOT constant time. * @@ -11614,20 +11668,17 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, sp_int* y, sp_int* b, sp_int* c, sp_int* inv) { int err = MP_OKAY; - sp_int* d = NULL; - sp_int* r = NULL; sp_int* s; #ifndef WOLFSSL_SP_INT_NEGATIVE int bneg = 0; int cneg = 0; int neg; #endif - DECL_SP_INT_ARRAY(t, m->used + 1, 2); + DECL_SP_INT(d, m->used + 1); - ALLOC_SP_INT_ARRAY(t, m->used + 1, 2, err, NULL); + ALLOC_SP_INT(d, m->used + 1, err, NULL); if (err == MP_OKAY) { - d = t[0]; - r = t[1]; + mp_init(d); /* 1. x = m, y = a, b = 1, c = 0 */ _sp_copy(a, y); @@ -11639,7 +11690,7 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, /* 2. while x > 1 */ while ((err == MP_OKAY) && (!sp_isone(x)) && (!sp_iszero(x))) { /* 2.1. d = x / y, r = x mod y */ - err = sp_div(x, y, d, r); + err = sp_div(x, y, d, x); if (err == MP_OKAY) { /* 2.2. c -= d * b */ if (sp_isone(d)) { @@ -11655,7 +11706,7 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, } } /* 2.3. x = y, y = r */ - s = x; x = y; y = r; r = s; + s = y; y = x; x = s; /* 2.4. s = b, b = c, c = s */ s = b; b = c; c = s; } @@ -11676,7 +11727,7 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, /* 2. while x > 1 */ while ((err == MP_OKAY) && (!sp_isone(x)) && (!sp_iszero(x))) { /* 2.1. d = x / y, r = x mod y */ - err = sp_div(x, y, d, r); + err = sp_div(x, y, d, x); if (err == MP_OKAY) { if (sp_isone(d)) { /* c -= 1 * b */ @@ -11715,7 +11766,7 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, } } /* 2.3. x = y, y = r */ - s = x; x = y; y = r; r = s; + s = y; y = x; x = s; /* 2.4. s = b, b = c, c = s */ s = b; b = c; c = s; neg = bneg; bneg = cneg; cneg = neg; @@ -11736,7 +11787,7 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, } #endif - FREE_SP_INT_ARRAY(t, NULL); + FREE_SP_INT(d, NULL); return err; } #endif @@ -11810,7 +11861,8 @@ static int _sp_invmod(const sp_int* a, const sp_int* m, sp_int* r) if (err == MP_OKAY) { /* Calculate inverse. */ - #if !defined(WOLFSSL_SP_SMALL) && (!defined(NO_RSA) || !defined(NO_DH)) + #if !defined(WOLFSSL_SP_LOW_MEM) && !defined(WOLFSSL_SP_SMALL) && \ + (!defined(NO_RSA) || !defined(NO_DH)) if (sp_count_bits(mm) >= 1024) { err = _sp_invmod_div(ma, mm, u, v, b, c, c); } @@ -11975,8 +12027,13 @@ int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, int s = 0; sp_int* t = NULL; sp_int* e = NULL; +#ifndef WOLFSSL_SP_NO_MALLOC + DECL_DYN_SP_INT_ARRAY(pre, (m == NULL) ? 1 : m->used * 2 + 1, + CT_INV_MOD_PRE_CNT + 2); +#else DECL_SP_INT_ARRAY(pre, (m == NULL) ? 1 : m->used * 2 + 1, CT_INV_MOD_PRE_CNT + 2); +#endif /* Validate parameters. */ if ((a == NULL) || (m == NULL) || (r == NULL)) { @@ -11989,7 +12046,12 @@ int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, err = MP_VAL; } +#ifndef WOLFSSL_SP_NO_MALLOC + ALLOC_DYN_SP_INT_ARRAY(pre, m->used * 2 + 1, CT_INV_MOD_PRE_CNT + 2, err, + NULL); +#else ALLOC_SP_INT_ARRAY(pre, m->used * 2 + 1, CT_INV_MOD_PRE_CNT + 2, err, NULL); +#endif if (err == MP_OKAY) { t = pre[CT_INV_MOD_PRE_CNT + 0]; e = pre[CT_INV_MOD_PRE_CNT + 1]; @@ -12118,7 +12180,11 @@ int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, } } +#ifndef WOLFSSL_SP_NO_MALLOC + FREE_DYN_SP_INT_ARRAY(pre, NULL); +#else FREE_SP_INT_ARRAY(pre, NULL); +#endif return err; } @@ -13084,13 +13150,6 @@ int sp_exptmod(const sp_int* b, const sp_int* e, const sp_int* m, sp_int* r) #if defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_HAVE_SP_DH) #if defined(WOLFSSL_SP_FAST_NCT_EXPTMOD) || !defined(WOLFSSL_SP_SMALL) -/* Always allocate large array of sp_ints unless defined WOLFSSL_SP_NO_MALLOC */ -#ifdef SP_ALLOC -#define SP_ALLOC_PREDEFINED -#else -#define SP_ALLOC -#endif - /* Internal. Exponentiates b to the power of e modulo m into r: r = b ^ e mod m * Creates a window of precalculated exponents with base in Montgomery form. * Sliding window and is NOT constant time. @@ -13141,7 +13200,11 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, sp_int* bm = NULL; sp_int_digit mask; /* Maximum winBits is 6 and preCnt is (1 << (winBits - 1)). */ +#ifndef WOLFSSL_SP_NO_MALLOC + DECL_DYN_SP_INT_ARRAY(t, m->used * 2 + 1, (1 << 5) + 2); +#else DECL_SP_INT_ARRAY(t, m->used * 2 + 1, (1 << 5) + 2); +#endif bits = sp_count_bits(e); @@ -13175,7 +13238,11 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, * - temporary result * - Montgomery form of base */ +#ifndef WOLFSSL_SP_NO_MALLOC + ALLOC_DYN_SP_INT_ARRAY(t, m->used * 2 + 1, preCnt + 2, err, NULL); +#else ALLOC_SP_INT_ARRAY(t, m->used * 2 + 1, preCnt + 2, err, NULL); +#endif if (err == MP_OKAY) { /* Set variables to use allocate memory. */ tr = t[preCnt + 0]; @@ -13393,15 +13460,14 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, err = sp_copy(tr, r); } +#ifndef WOLFSSL_SP_NO_MALLOC + FREE_DYN_SP_INT_ARRAY(t, NULL); +#else FREE_SP_INT_ARRAY(t, NULL); +#endif return err; } -#ifndef SP_ALLOC_PREDEFINED -#undef SP_ALLOC -#undef SP_ALLOC_PREDEFINED -#endif - #else /* Exponentiates b to the power of e modulo m into r: r = b ^ e mod m * Non-constant time implementation. @@ -13796,14 +13862,15 @@ static int _sp_sqr(const sp_int* a, sp_int* r) #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_DYN_STACK) - sp_int_digit t[a->used * 2]; + !defined(WOLFSSL_SP_NO_DYN_STACK) + sp_int_digit t[((a->used + 1) / 2) * 2 + 1]; #else - sp_int_digit t[SP_INT_DIGITS]; + sp_int_digit t[(SP_INT_DIGITS + 1) / 2]; #endif #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * (a->used * 2), NULL, + t = (sp_int_digit*)XMALLOC( + sizeof(sp_int_digit) * (((a->used + 1) / 2) * 2 + 1), NULL, DYNAMIC_TYPE_BIGINT); if (t == NULL) { err = MP_MEM; @@ -13816,13 +13883,14 @@ static int _sp_sqr(const sp_int* a, sp_int* r) h = 0; l = 0; SP_ASM_SQR(h, l, a->dp[0]); - t[0] = h; - t[1] = l; + r->dp[0] = h; + r->dp[1] = l; } else if (err == MP_OKAY) { sp_int_digit l; sp_int_digit h; sp_int_digit o; + sp_int_digit* p = t; h = 0; l = 0; @@ -13858,7 +13926,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) for (; (i < a->used); i++, j--) { SP_ASM_MUL_ADD2(l, h, o, a->dp[i], a->dp[j]); } - t[k * 2 - 1] = l; + p[k * 2 - 1] = l; l = h; h = o; o = 0; @@ -13869,17 +13937,19 @@ static int _sp_sqr(const sp_int* a, sp_int* r) for (; (i < a->used); i++, j--) { SP_ASM_MUL_ADD2(l, h, o, a->dp[i], a->dp[j]); } - t[k * 2] = l; + p[k * 2] = l; l = h; h = o; o = 0; + + p = r->dp; } - t[k * 2 - 1] = l; + r->dp[k * 2 - 1] = l; + XMEMCPY(r->dp, t, (((a->used + 1) / 2) * 2 + 1) * sizeof(sp_int_digit)); } if (err == MP_OKAY) { r->used = a->used * 2; - XMEMCPY(r->dp, t, r->used * sizeof(sp_int_digit)); sp_clamp(r); } @@ -13908,7 +13978,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_DYN_STACK) + !defined(WOLFSSL_SP_NO_DYN_STACK) sp_int_digit t[a->used * 2]; #else sp_int_digit t[SP_INT_DIGITS]; @@ -13996,7 +14066,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) #ifndef WOLFSSL_SP_SMALL #if !defined(WOLFSSL_HAVE_SP_ECC) && defined(HAVE_ECC) -#if SP_WORD_SIZE == 64 +#if (SP_WORD_SIZE == 64 && SP_INT_BITS >= 256) #ifndef SQR_MUL_ASM /* Square a and store in r. r = a * a * @@ -14164,7 +14234,7 @@ static int _sp_sqr_4(const sp_int* a, sp_int* r) } #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 64 */ -#if SP_WORD_SIZE == 64 +#if (SP_WORD_SIZE == 64 && SP_INT_BITS >= 384) #ifdef SQR_MUL_ASM /* Square a and store in r. r = a * a * @@ -14259,7 +14329,7 @@ static int _sp_sqr_6(const sp_int* a, sp_int* r) } #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 64 */ -#if SP_WORD_SIZE == 32 +#if (SP_WORD_SIZE == 32 && SP_INT_BITS >= 256) #ifdef SQR_MUL_ASM /* Square a and store in r. r = a * a * @@ -14389,7 +14459,7 @@ static int _sp_sqr_8(const sp_int* a, sp_int* r) } #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 32 */ -#if SP_WORD_SIZE == 32 +#if (SP_WORD_SIZE == 32 && SP_INT_BITS >= 384) #ifdef SQR_MUL_ASM /* Square a and store in r. r = a * a * @@ -16106,13 +16176,13 @@ int sp_sqr(const sp_int* a, sp_int* r) else #ifndef WOLFSSL_SP_SMALL #if !defined(WOLFSSL_HAVE_SP_ECC) && defined(HAVE_ECC) -#if SP_WORD_SIZE == 64 +#if (SP_WORD_SIZE == 64 && SP_INT_BITS >= 256) if (a->used == 4) { err = _sp_sqr_4(a, r); } else #endif /* SP_WORD_SIZE == 64 */ -#if SP_WORD_SIZE == 64 +#if (SP_WORD_SIZE == 64 && SP_INT_BITS >= 384) #ifdef SQR_MUL_ASM if (a->used == 6) { err = _sp_sqr_6(a, r); @@ -16120,7 +16190,7 @@ int sp_sqr(const sp_int* a, sp_int* r) else #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 64 */ -#if SP_WORD_SIZE == 32 +#if (SP_WORD_SIZE == 32 && SP_INT_BITS >= 256) #ifdef SQR_MUL_ASM if (a->used == 8) { err = _sp_sqr_8(a, r); @@ -16128,7 +16198,7 @@ int sp_sqr(const sp_int* a, sp_int* r) else #endif /* SQR_MUL_ASM */ #endif /* SP_WORD_SIZE == 32 */ -#if SP_WORD_SIZE == 32 +#if (SP_WORD_SIZE == 32 && SP_INT_BITS >= 384) #ifdef SQR_MUL_ASM if (a->used == 12) { err = _sp_sqr_12(a, r); @@ -18577,5 +18647,12 @@ void sp_memzero_check(sp_int* sp) } #endif /* WOLFSSL_CHECK_MEM_ZERO */ +#if (!defined(WOLFSSL_SMALL_STACK) && !defined(SP_ALLOC)) || \ + defined(WOLFSSL_SP_NO_MALLOC) +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(WOLFSSL_SP_NO_DYN_STACK) +#pragma GCC diagnostic pop +#endif +#endif #endif /* WOLFSSL_SP_MATH || WOLFSSL_SP_MATH_ALL */ diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 0ade5dc0fb7..8631841d4e7 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -1235,9 +1235,11 @@ enum { #endif #define MAX_DHKEY_SZ (WOLFSSL_MAX_DHKEY_BITS / 8) +#ifndef NO_DH #if WOLFSSL_MAX_DHKEY_BITS < WOLFSSL_MIN_DHKEY_BITS #error "WOLFSSL_MAX_DHKEY_BITS has to be greater than WOLFSSL_MIN_DHKEY_BITS" #endif +#endif /* NO_DH */ #ifndef MAX_PSK_ID_LEN /* max psk identity/hint supported */ diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index 7ba03c0b757..fb43f974887 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -689,10 +689,17 @@ WOLFSSL_API void wc_FreeDer(DerBuffer** pDer); (! ((HAVE_FIPS_VERSION == 5) && (HAVE_FIPS_VERSION_MINOR == 0))))) WOLFSSL_API int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen); #endif - #endif + #endif /* !HAVE_USER_RSA */ WOLFSSL_API int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header); WOLFSSL_API int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen, int with_header); + + /* For FIPS v1/v2 and selftest rsa.h is replaced. */ + #if defined(HAVE_SELFTEST) || (defined(HAVE_FIPS) && \ + (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION <= 5))) + WOLFSSL_API int wc_RsaPrivateKeyValidate(const byte* input, + word32* inOutIdx, int* keySz, word32 inSz); + #endif #endif #ifndef NO_DSA diff --git a/wolfssl/wolfcrypt/integer.h b/wolfssl/wolfcrypt/integer.h index 712b912569f..8a51b077251 100644 --- a/wolfssl/wolfcrypt/integer.h +++ b/wolfssl/wolfcrypt/integer.h @@ -189,6 +189,26 @@ typedef int mp_err; BITS_PER_DIGIT*2) */ #define MP_WARRAY ((mp_word)1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1)) +/* No point in dynamically allocating mp_int when it is very small. + * The dp field will grow and shrink dynamically. + */ +/* Declare a statically allocated mp_int. */ +#define DECL_MP_INT_SIZE(name, bits) \ + mp_int name[1] +/* Declare statically allocated mp_int. */ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + mp_int name[1] +/* Zero out mp_int of minimal size. */ +#define NEW_MP_INT_SIZE(name, bits, heap, type) \ + XMEMSET(name, 0, sizeof(mp_int)) +/* Dispose of static mp_int. */ +#define FREE_MP_INT_SIZE(name, heap, type) +/* Initialize an mp_int. */ +#define INIT_MP_INT_SIZE(name, bits) \ + mp_init(name) +/* Type to cast to when using size marcos. */ +#define MP_INT_SIZE mp_int + #ifdef HAVE_WOLF_BIGINT /* raw big integer */ typedef struct WC_BIGINT { @@ -237,6 +257,8 @@ typedef int ltm_prime_callback(unsigned char *dst, int len, void *dat); #define mp_isword(a, w) \ ((((a)->used == 1) && ((a)->dp[0] == (w))) || (((w) == 0) && ((a)->used == 0)) \ ? MP_YES : MP_NO) +/* Number of bits used based on used field only. */ +#define mp_bitsused(a) ((a)->used * DIGIT_BIT) /* number of primes */ #ifdef MP_8BIT diff --git a/wolfssl/wolfcrypt/rsa.h b/wolfssl/wolfcrypt/rsa.h index 455ec0162a5..6d31aab558e 100644 --- a/wolfssl/wolfcrypt/rsa.h +++ b/wolfssl/wolfcrypt/rsa.h @@ -352,6 +352,11 @@ WOLFSSL_API int wc_RsaEncryptSize(const RsaKey* key); /* to avoid asn duplicate symbols @wc_fips */ WOLFSSL_API int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, word32 inSz); +#if !defined(HAVE_FIPS) || \ + (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)) +WOLFSSL_API int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, + int* keySz, word32 inSz); +#endif WOLFSSL_API int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, word32 inSz); WOLFSSL_API int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 9448bc789b3..f90ebc67cbc 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1995,6 +1995,9 @@ extern void uITRON4_free(void *p) ; #undef WOLFSSL_SP_INT_DIGIT_ALIGN #define WOLFSSL_SP_INT_DIGIT_ALIGN #endif +#ifdef __APPLE__ + #define WOLFSSL_SP_NO_DYN_STACK +#endif #ifdef __INTEL_COMPILER #pragma warning(disable:2259) /* explicit casts to smaller sizes, disable */ diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index fce3feb4a67..c21224f2c3e 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -658,18 +658,21 @@ typedef struct sp_ecc_ctx { #define sp_setneg(a) ((a)->sign = MP_NEG) #endif +/* Number of bits used based on used field only. */ +#define sp_bitsused(a) ((a)->used * SP_WORD_SIZE) + /* Updates the used count to exclude leading zeros. * * Assumes a is not NULL. * * @param [in] a SP integer to update. */ -#define sp_clamp(a) \ - do { \ - int ii; \ - for (ii = (a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ - } \ - (a)->used = ii + 1; \ +#define sp_clamp(a) \ + do { \ + int ii; \ + for (ii = (a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ + } \ + (a)->used = ii + 1; \ } while (0) /* Check the compiled and linked math implementation are the same. @@ -681,16 +684,6 @@ typedef struct sp_ecc_ctx { #define CheckFastMathSettings() (SP_WORD_SIZE == CheckRunTimeFastMath()) -/* The number of bytes to a sp_int with 'cnt' digits. - * Must have at least one digit. - */ -#define MP_INT_SIZEOF(cnt) \ - (sizeof(sp_int) - (SP_INT_DIGITS - (((cnt) == 0) ? 1 : (cnt))) * \ - sizeof(sp_int_digit)) -/* The address of the next sp_int after one with 'cnt' digits. */ -#define MP_INT_NEXT(t, cnt) \ - (sp_int*)(((byte*)(t)) + MP_INT_SIZEOF(cnt)) - /** * A result of NO. * e.g. Is prime? NO. @@ -747,6 +740,86 @@ typedef struct sp_ecc_ctx { /* Mask of all used bits in word/digit. */ #define MP_MASK SP_MASK +#ifdef MP_LOW_MEM +/* Use algorithms that use less memory. */ +#define WOLFSSL_SP_LOW_MEM +#endif + + +/* The number of bytes to a sp_int with 'cnt' digits. + * Must have at least one digit. + */ +#define MP_INT_SIZEOF(cnt) \ + (sizeof(sp_int) - (SP_INT_DIGITS - (((cnt) == 0) ? 1 : (cnt))) * \ + sizeof(sp_int_digit)) +/* The address of the next sp_int after one with 'cnt' digits. */ +#define MP_INT_NEXT(t, cnt) \ + (sp_int*)(((byte*)(t)) + MP_INT_SIZEOF(cnt)) + + +/* Calculate the number of words required to support a number of bits. */ +#define MP_BITS_CNT(bits) \ + (((bits + SP_WORD_SIZE - 1) / SP_WORD_SIZE) * 2 + 1) + +#ifdef WOLFSSL_SMALL_STACK +/* + * Dynamic memory allocation of mp_int. + */ +/* Declare a dynamically allocated mp_int. */ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + sp_int* name = NULL +/* Declare a dynamically allocated mp_int. */ +#define DECL_MP_INT_SIZE(name, bits) \ + sp_int* name = NULL +/* Allocate an mp_int of minimal size and zero out. */ +#define NEW_MP_INT_SIZE(name, bits, heap, type) \ +do { \ + name = (mp_int*)XMALLOC(MP_INT_SIZEOF(MP_BITS_CNT(bits)), heap, type); \ + if (name != NULL) { \ + XMEMSET(name, 0, MP_INT_SIZEOF(MP_BITS_CNT(bits))); \ + } \ +} \ +while (0) +/* Dispose of dynamically allocated mp_int. */ +#define FREE_MP_INT_SIZE(name, heap, type) \ + XFREE(name, heap, type) +/* Type to cast to when using size marcos. */ +#define MP_INT_SIZE sp_int +/* Must check mp_int pointer for NULL. */ +#define MP_INT_SIZE_CHECK_NULL +#else +/* + * Static allocation of mp_int. + */ +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(WOLFSSL_SP_NO_DYN_STACK) +/* Declare a dynamically allocated mp_int. */ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(bits))]; \ + sp_int* name = (sp_int*)name##d +#else +/* Declare a dynamically allocated mp_int. */ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(max))]; \ + sp_int* name = (sp_int*)name##d +#endif +/* Declare a statically allocated mp_int. */ +#define DECL_MP_INT_SIZE(name, bits) \ + unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(bits))]; \ + sp_int* name = (sp_int*)name##d +/* Zero out mp_int of minimal size. */ +#define NEW_MP_INT_SIZE(name, bits, heap, type) \ + XMEMSET(name, 0, MP_INT_SIZEOF(MP_BITS_CNT(bits))) +/* Dispose of static mp_int. */ +#define FREE_MP_INT_SIZE(name, heap, type) +/* Type to force compiler to not complain about size. */ +#define MP_INT_SIZE sp_int_minimal +#endif + +/* Initialize an mp_int to a specific size. */ +#define INIT_MP_INT_SIZE(name, bits) \ + mp_init_size(name, MP_BITS_CNT(bits)) + #ifdef HAVE_WOLF_BIGINT /* Raw big integer as a big-endian byte array. @@ -992,6 +1065,7 @@ WOLFSSL_LOCAL void sp_memzero_check(sp_int* sp); #define mp_abs sp_abs #define mp_isneg sp_isneg #define mp_setneg sp_setneg +#define mp_bitsused sp_bitsused #define mp_clamp sp_clamp /* One to one mappings. */ diff --git a/wolfssl/wolfcrypt/tfm.h b/wolfssl/wolfcrypt/tfm.h index 8c55535d151..94912a3c97c 100644 --- a/wolfssl/wolfcrypt/tfm.h +++ b/wolfssl/wolfcrypt/tfm.h @@ -317,6 +317,55 @@ #define FP_YES 1 /* yes response */ #define FP_NO 0 /* no response */ + +#ifdef WOLFSSL_SMALL_STACK +/* + * Dynamic memory allocation of mp_int. + */ +/* Declare a dynamically allocated mp_int. */ +#define DECL_MP_INT_SIZE(name, bits) \ + mp_int* name = NULL +/* Declare a dynamically allocated mp_int. */ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + mp_int* name = NULL +/* Allocate an mp_int of minimal size and zero out. */ +#define NEW_MP_INT_SIZE(name, bits, heap, type) \ +do { \ + name = (mp_int*)XMALLOC(sizeof(mp_int), heap, type); \ + if (name != NULL) { \ + XMEMSET(name, 0, sizeof(mp_int)); \ + } \ +} \ +while (0) +/* Dispose of dynamically allocated mp_int. */ +#define FREE_MP_INT_SIZE(name, heap, type) \ + XFREE(name, heap, type) +/* Must check for mp_int pointer for NULL. */ +#define MP_INT_SIZE_CHECK_NULL +#else +/* + * Static allocation of mp_int. + */ +/* Declare a statically allocated mp_int. */ +#define DECL_MP_INT_SIZE(name, bits) \ + mp_int name[1] +/* Declare a statically allocated mp_int. */ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + mp_int name[1] +/* Zero out mp_int of minimal size. */ +#define NEW_MP_INT_SIZE(name, bits, heap, type) \ + XMEMSET(name, 0, sizeof(mp_int)) +/* Dispose of static mp_int. */ +#define FREE_MP_INT_SIZE(name, heap, type) +#endif + +/* Initialize an mp_int. */ +#define INIT_MP_INT_SIZE(name, bits) \ + mp_init(name) +/* Type to cast to when using size marcos. */ +#define MP_INT_SIZE mp_int + + #ifdef HAVE_WOLF_BIGINT /* raw big integer */ typedef struct WC_BIGINT { @@ -448,6 +497,8 @@ MP_API void fp_free(fp_int* a); #define fp_isword(a, w) \ (((((a)->used == 1) && ((a)->dp[0] == (w))) || \ (((w) == 0) && ((a)->used == 0))) ? FP_YES : FP_NO) +/* Number of bits used based on used field only. */ +#define fp_bitsused(a) ((a)->used * DIGIT_BIT) /* set to a small digit */ void fp_set(fp_int *a, fp_digit b); @@ -740,6 +791,7 @@ int fp_sqr_comba64(fp_int *a, fp_int *b); #define mp_isneg(a) fp_isneg(a) #define mp_setneg(a) fp_setneg(a) #define mp_isword(a, w) fp_isword(a, w) +#define mp_bitsused(a) fp_bitsused(a) #define MP_RADIX_BIN 2 #define MP_RADIX_OCT 8 From 377b2a9bd8ced920958b65c745892622fbd70c90 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 6 Apr 2023 14:31:53 -0500 Subject: [PATCH 103/391] wolfcrypt/src/asn.c: * refactor error-checking cascade in wc_PemCertToDer_ex() as in wc_PemPubKeyToDer_ex(), * refactor staticBuffer gating/dynamics in wc_PemPubKeyToDer_ex() as in wc_PemCertToDer_ex(), * and use IO_FAILED_E, not BUFFER_E, for I/O errors on the file handles, in both routines; fix smallstack null pointer dereferences in src/pk.c:wolfSSL_RSA_GenAdd() and src/ssl.c:set_curves_list(). --- src/pk.c | 21 ++++++---- src/ssl.c | 2 +- wolfcrypt/src/asn.c | 93 +++++++++++++++++++++++++-------------------- 3 files changed, 66 insertions(+), 50 deletions(-) diff --git a/src/pk.c b/src/pk.c index e8be5292117..75e239fec92 100644 --- a/src/pk.c +++ b/src/pk.c @@ -4456,12 +4456,7 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) int err; mp_int* t = NULL; #ifdef WOLFSSL_SMALL_STACK - mp_int *tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (tmp == NULL) { - WOLFSSL_ERROR_MSG("Memory allocation failure"); - return -1; - } + mp_int *tmp = NULL; #else mp_int tmp[1]; #endif @@ -4475,6 +4470,17 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) ret = -1; } +#ifdef WOLFSSL_SMALL_STACK + if (ret == 1) { + tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (tmp == NULL) { + WOLFSSL_ERROR_MSG("Memory allocation failure"); + ret = -1; + } + } +#endif + if (ret == 1) { /* Initialize temp MP integer. */ if (mp_init(tmp) != MP_OKAY) { @@ -4523,7 +4529,8 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) mp_clear(t); #ifdef WOLFSSL_SMALL_STACK - XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (tmp != NULL) + XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; diff --git a/src/ssl.c b/src/ssl.c index 18747276720..82bc6510f38 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -33510,7 +33510,7 @@ static int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names) char name[MAX_CURVE_NAME_SZ]; byte groups_len = 0; #ifdef WOLFSSL_SMALL_STACK - void *heap = ssl? ssl->heap : ctx->heap; + void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL; int *groups; #else int groups[WOLFSSL_MAX_GROUP_COUNT]; diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 2f16c6265dd..d3a740432f3 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -23484,14 +23484,14 @@ int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz, #ifdef WOLFSSL_CERT_GEN int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der) { -#ifdef WOLFSSL_SMALL_STACK - byte staticBuffer[1]; /* force XMALLOC */ -#else +#ifndef WOLFSSL_SMALL_STACK byte staticBuffer[FILE_BUFFER_SIZE]; #endif - byte* fileBuf = staticBuffer; + byte* fileBuf; int ret = 0; - XFILE file = NULL; + XFILE file = XBADFILE; + int dynamic = 0; + long sz = 0; WOLFSSL_ENTER("wc_PemCertToDer"); @@ -23501,49 +23501,53 @@ int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der) else { file = XFOPEN(fileName, "rb"); if (file == XBADFILE) { - ret = BUFFER_E; + ret = IO_FAILED_E; } } if (ret == 0) { - int dynamic = 0; - long sz = 0; - if (XFSEEK(file, 0, XSEEK_END) != 0) { - ret = BUFFER_E; + ret = IO_FAILED_E; } + } + if (ret == 0) { sz = XFTELL(file); - if (XFSEEK(file, 0, XSEEK_SET) != 0) { - ret = BUFFER_E; - } - - if (ret < 0) { - /* intentionally left empty. */ + if (sz <= 0) { + ret = IO_FAILED_E; } - else if (sz <= 0) { - ret = BUFFER_E; + } + if (ret == 0) { + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + ret = IO_FAILED_E; } - else if (sz > (long)sizeof(staticBuffer)) { + } + if (ret == 0) { +#ifndef WOLFSSL_SMALL_STACK + if (sz <= (long)sizeof(staticBuffer)) + fileBuf = staticBuffer; + else +#endif + { fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE); if (fileBuf == NULL) ret = MEMORY_E; else dynamic = 1; } - - if (ret == 0) { - if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) { - ret = BUFFER_E; - } - else { - ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL); - } + } + if (ret == 0) { + if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) { + ret = IO_FAILED_E; + } + else { + ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL); } + } + if (file != XBADFILE) XFCLOSE(file); - if (dynamic) - XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE); - } + if (dynamic) + XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE); return ret; } @@ -23571,16 +23575,14 @@ int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz) /* load pem public key from file into der buffer, return der size or error */ int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der) { -#ifdef WOLFSSL_SMALL_STACK - byte staticBuffer[1]; /* force XMALLOC */ -#else +#ifndef WOLFSSL_SMALL_STACK byte staticBuffer[FILE_BUFFER_SIZE]; #endif - byte* fileBuf = staticBuffer; + byte* fileBuf; int dynamic = 0; int ret = 0; long sz = 0; - XFILE file = NULL; + XFILE file = XBADFILE; WOLFSSL_ENTER("wc_PemPubKeyToDer"); @@ -23590,26 +23592,33 @@ int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der) else { file = XFOPEN(fileName, "rb"); if (file == XBADFILE) { - ret = BUFFER_E; + ret = IO_FAILED_E; } } if (ret == 0) { if (XFSEEK(file, 0, XSEEK_END) != 0) { - ret = BUFFER_E; + ret = IO_FAILED_E; } } if (ret == 0) { sz = XFTELL(file); - if (XFSEEK(file, 0, XSEEK_SET) != 0) { - ret = BUFFER_E; + if (sz <= 0) { + ret = IO_FAILED_E; } } if (ret == 0) { - if (sz <= 0) { - ret = BUFFER_E; + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + ret = IO_FAILED_E; } - else if (sz > (long)sizeof(staticBuffer)) { + } + if (ret == 0) { +#ifndef WOLFSSL_SMALL_STACK + if (sz <= (long)sizeof(staticBuffer)) + fileBuf = staticBuffer; + else +#endif + { fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE); if (fileBuf == NULL) ret = MEMORY_E; From 73528436dff7811aec0d0c74811c7b16b59f730c Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 6 Apr 2023 15:15:26 -0500 Subject: [PATCH 104/391] wolfcrypt/src/asn.c: in wc_PemCertToDer_ex() and wc_PemPubKeyToDer_ex(), work around false positive -Wmaybe-uninitialized from scan-build. --- wolfcrypt/src/asn.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index d3a740432f3..d44769da337 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -23487,7 +23487,7 @@ int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der) #ifndef WOLFSSL_SMALL_STACK byte staticBuffer[FILE_BUFFER_SIZE]; #endif - byte* fileBuf; + byte* fileBuf = NULL; int ret = 0; XFILE file = XBADFILE; int dynamic = 0; @@ -23578,7 +23578,7 @@ int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der) #ifndef WOLFSSL_SMALL_STACK byte staticBuffer[FILE_BUFFER_SIZE]; #endif - byte* fileBuf; + byte* fileBuf = NULL; int dynamic = 0; int ret = 0; long sz = 0; From 37bc302772be73691d87d4923e7198f8e206056c Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Wed, 5 Apr 2023 17:10:37 +0200 Subject: [PATCH 105/391] mp_setneg(Z), not mpi --- wolfcrypt/src/port/Espressif/esp32_mp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/port/Espressif/esp32_mp.c b/wolfcrypt/src/port/Espressif/esp32_mp.c index b4efe8cb213..1717a415b03 100644 --- a/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -370,7 +370,7 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) esp_mp_hw_unlock(); if (!mp_iszero(Z) && neg) { - mp_setneg(mpi); + mp_setneg(Z); } return ret; From 409f40ab36ed5c37dcf195b88c81d1ac20d916b1 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Sun, 9 Apr 2023 00:08:01 -0600 Subject: [PATCH 106/391] fix ECC performance regression --- wolfcrypt/src/ecc.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 3003443ae5b..1504a333513 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -8176,6 +8176,7 @@ static int ecc_verify_hash_sp(mp_int *r, mp_int *s, const byte* hash, #if defined(WC_ECC_NONBLOCK) && defined(WC_ECC_NONBLOCK_ONLY) /* perform blocking call to non-blocking function */ ecc_nb_ctx_t nb_ctx; + int err; XMEMSET(&nb_ctx, 0, sizeof(nb_ctx)); err = NOT_COMPILED_IN; /* set default error */ #endif @@ -8269,7 +8270,7 @@ static int ecc_verify_hash_sp(mp_int *r, mp_int *s, const byte* hash, } #endif - return 0; + return NOT_COMPILED_IN; } #if !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC) @@ -8710,7 +8711,7 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, } err = ecc_verify_hash_sp(r, s, hash, hashlen, res, key); - if (err != 0) { + if (err != NOT_COMPILED_IN) { if (curveLoaded) { wc_ecc_curve_free(curve); FREE_CURVE_SPECS(); @@ -8720,6 +8721,7 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, #if !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC) if (!curveLoaded) { + err = 0; /* potential for NOT_COMPILED_IN error from SP attempt */ ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); if (err != 0) { return err; From 7a9137c4328371443d3004c4295dc28c4929e05e Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 10 Apr 2023 12:53:40 -0700 Subject: [PATCH 107/391] fix for ECC sign with nonblocking only --- wolfcrypt/src/ecc.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 1504a333513..208c0c6880c 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -6634,6 +6634,9 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #ifndef WOLFSSL_SP_NO_256 if (ecc_sets[key->idx].id == ECC_SECP256R1) { #ifdef WC_ECC_NONBLOCK + #ifdef WC_ECC_NONBLOCK_ONLY + int err; + #endif if (key->nb_ctx) { return sp_ecc_sign_256_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, &key->k, r, s, sign_k, key->heap); @@ -6661,6 +6664,9 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #ifdef WOLFSSL_SP_384 if (ecc_sets[key->idx].id == ECC_SECP384R1) { #ifdef WC_ECC_NONBLOCK + #ifdef WC_ECC_NONBLOCK_ONLY + int err; + #endif if (key->nb_ctx) { return sp_ecc_sign_384_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, &key->k, r, s, sign_k, key->heap); @@ -6688,6 +6694,9 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #ifdef WOLFSSL_SP_521 if (ecc_sets[key->idx].id == ECC_SECP521R1) { #ifdef WC_ECC_NONBLOCK + #ifdef WC_ECC_NONBLOCK_ONLY + int err; + #endif if (key->nb_ctx) { return sp_ecc_sign_521_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, &key->k, r, s, sign_k, key->heap); From 51d77fc2c75819002b6cec12d9c0220605eb7ee7 Mon Sep 17 00:00:00 2001 From: billphipps <126489738+billphipps@users.noreply.github.com> Date: Mon, 10 Apr 2023 17:08:52 -0400 Subject: [PATCH 108/391] 15451 correct padding for pkcs7 (#6260) * Update to ensure full blocks for crypto in En/DecodeAuthEnvelopedData. * Corrected spacing and comments * Set plain to NULL after free on non-error path. --- wolfcrypt/src/pkcs7.c | 49 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index 298777f6434..57cf90ef024 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -11009,7 +11009,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, { #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) int ret, idx = 0; - int totalSz, encryptedOutSz; + int totalSz, encryptedAllocSz, encryptedOutSz; int contentInfoSeqSz, outerContentTypeSz, outerContentSz; byte contentInfoSeq[MAX_SEQ_SZ]; @@ -11022,6 +11022,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, WC_RNG rng; int blockSz, blockKeySz; + byte* plain; byte* encryptedContent; Pkcs7EncodedRecip* tmpRecip = NULL; @@ -11334,11 +11335,38 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, unauthAttribSet); } - /* allocate encrypted content buffer */ + /* AES-GCM/CCM does NOT require padding for plaintext content or + * AAD inputs RFC 5084 section 3.1 and 3.2, but we must alloc + * full blocks to ensure crypto only gets full blocks */ encryptedOutSz = pkcs7->contentSz; - encryptedContent = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, + encryptedAllocSz = (encryptedOutSz % blockSz) ? + encryptedOutSz + blockSz - + (encryptedOutSz % blockSz) : + encryptedOutSz; + + /* Copy content to plain buffer (zero-padded) to encrypt in full, + * contiguous blocks */ + plain = (byte*)XMALLOC(encryptedAllocSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + if (plain == NULL) { + wc_PKCS7_FreeEncodedRecipientSet(pkcs7); + if (aadBuffer) + XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (flatUnauthAttribs) + XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + if (flatAuthAttribs) + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + return MEMORY_E; + } + + XMEMCPY(plain, pkcs7->content, pkcs7->contentSz); + if ((encryptedAllocSz - encryptedOutSz) > 0) { + XMEMSET(plain + encryptedOutSz, 0, encryptedAllocSz - encryptedOutSz); + } + + encryptedContent = (byte*)XMALLOC(encryptedAllocSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (encryptedContent == NULL) { + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); wc_PKCS7_FreeEncodedRecipientSet(pkcs7); if (aadBuffer) XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -11352,9 +11380,12 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, /* encrypt content */ ret = wc_PKCS7_EncryptContent(pkcs7->encryptOID, pkcs7->cek, pkcs7->cekSz, nonce, nonceSz, aadBuffer, aadBufferSz, authTag, - sizeof(authTag), pkcs7->content, encryptedOutSz, encryptedContent, + sizeof(authTag), plain, encryptedOutSz, encryptedContent, pkcs7->devId, pkcs7->heap); + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + plain = NULL; + if (aadBuffer) { XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); aadBuffer = NULL; @@ -11561,6 +11592,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, byte decryptedKey[MAX_ENCRYPTED_KEY_SZ]; #endif int encryptedContentSz = 0; + int encryptedAllocSz = 0; byte* encryptedContent = NULL; int explicitOctet = 0; @@ -11839,8 +11871,13 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, #endif /* AES-GCM/CCM does NOT require padding for plaintext content or - * AAD inputs RFC 5084 section 3.1 and 3.2 */ - encryptedContent = (byte*)XMALLOC(encryptedContentSz, pkcs7->heap, + * AAD inputs RFC 5084 section 3.1 and 3.2, but we must alloc + * full blocks to ensure crypto only gets full blocks */ + encryptedAllocSz = (encryptedContentSz % expBlockSz) ? + encryptedContentSz + expBlockSz - + (encryptedContentSz % expBlockSz) : + encryptedContentSz; + encryptedContent = (byte*)XMALLOC(encryptedAllocSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (ret == 0 && encryptedContent == NULL) { ret = MEMORY_E; From 264a8108abadc4eceecd00d787ddcef18e25caa5 Mon Sep 17 00:00:00 2001 From: billphipps Date: Thu, 23 Mar 2023 15:46:38 -0400 Subject: [PATCH 109/391] Track SetDigest usage to avoid invalid free under error conditions. --- src/internal.c | 47 +++++++++++++++++++++++++++++++++++++++++----- wolfssl/internal.h | 1 + 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/internal.c b/src/internal.c index c2c90f5356e..9338307a0cf 100644 --- a/src/internal.c +++ b/src/internal.c @@ -4388,24 +4388,28 @@ static void SetDigest(WOLFSSL* ssl, int hashAlgo) switch (hashAlgo) { #ifndef NO_SHA case sha_mac: + ssl->options.dontFreeDigest=1; ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha; ssl->buffers.digest.length = WC_SHA_DIGEST_SIZE; break; #endif /* !NO_SHA */ #ifndef NO_SHA256 case sha256_mac: + ssl->options.dontFreeDigest=1; ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha256; ssl->buffers.digest.length = WC_SHA256_DIGEST_SIZE; break; #endif /* !NO_SHA256 */ #ifdef WOLFSSL_SHA384 case sha384_mac: + ssl->options.dontFreeDigest=1; ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha384; ssl->buffers.digest.length = WC_SHA384_DIGEST_SIZE; break; #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 case sha512_mac: + ssl->options.dontFreeDigest=1; ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha512; ssl->buffers.digest.length = WC_SHA512_DIGEST_SIZE; break; @@ -7544,9 +7548,12 @@ void FreeKeyExchange(WOLFSSL* ssl) /* Cleanup digest buffer */ if (ssl->buffers.digest.buffer) { - XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST); + if(!ssl->options.dontFreeDigest) { + XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST); + } ssl->buffers.digest.buffer = NULL; ssl->buffers.digest.length = 0; + ssl->options.dontFreeDigest=0; } /* Free handshake key */ @@ -26240,6 +26247,14 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, ssl->buffers.digest.length = (unsigned int)digest_sz; /* buffer for hash */ + if(!ssl->buffers.digest.buffer) { + if(!ssl->options.dontFreeDigest) { + XFREE(ssl->buffers.digest.buffer, ssl->heap, + DYNAMIC_TYPE_DIGEST); + } + } + ssl->options.dontFreeDigest=0; + ssl->buffers.digest.buffer = (byte*)XMALLOC(ssl->buffers.digest.length, ssl->heap, DYNAMIC_TYPE_DIGEST); if (ssl->buffers.digest.buffer == NULL) { @@ -30491,8 +30506,16 @@ int SendCertificateVerify(WOLFSSL* ssl) #endif /* WOLFSSL_ASYNC_IO */ /* Digest is not allocated, so do this to prevent free */ + if(ssl->buffers.digest.buffer) { + if(!ssl->options.dontFreeDigest) { + /*This should not happen*/ + XFREE(ssl->buffers.digest.buffer, + ssl->heap, DYNAMIC_TYPE_DIGEST); + } + } ssl->buffers.digest.buffer = NULL; ssl->buffers.digest.length = 0; + ssl->options.dontFreeDigest=0; /* Final cleanup */ #ifdef WOLFSSL_ASYNC_IO @@ -31975,8 +31998,11 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, TypeHash(ssl->options.hashAlgo)); /* Replace sig buffer with new one */ - XFREE(ssl->buffers.digest.buffer, ssl->heap, - DYNAMIC_TYPE_DIGEST); + if(!ssl->options.dontFreeDigest) { + XFREE(ssl->buffers.digest.buffer, + ssl->heap, DYNAMIC_TYPE_DIGEST); + } + ssl->options.dontFreeDigest=0; ssl->buffers.digest.buffer = encodedSig; } @@ -32193,8 +32219,11 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, TypeHash(ssl->options.hashAlgo)); /* Replace sig buffer with new one */ - XFREE(ssl->buffers.digest.buffer, ssl->heap, - DYNAMIC_TYPE_DIGEST); + if(!ssl->options.dontFreeDigest) { + XFREE(ssl->buffers.digest.buffer, + ssl->heap, DYNAMIC_TYPE_DIGEST); + } + ssl->options.dontFreeDigest=0; ssl->buffers.digest.buffer = encodedSig; } break; @@ -34283,8 +34312,16 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, SendAlert(ssl, alert_fatal, bad_certificate); #endif /* Digest is not allocated, so do this to prevent free */ + if(ssl->buffers.digest.buffer) { + if(!ssl->options.dontFreeDigest) { + /*This should not happen*/ + XFREE(ssl->buffers.digest.buffer, + ssl->heap, DYNAMIC_TYPE_DIGEST); + } + } ssl->buffers.digest.buffer = NULL; ssl->buffers.digest.length = 0; + ssl->options.dontFreeDigest=0; #ifdef WOLFSSL_ASYNC_CRYPT /* Cleanup async */ diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 8631841d4e7..4be5b5774ed 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -4473,6 +4473,7 @@ struct Options { word16 saveArrays:1; /* save array Memory for user get keys or psk */ word16 weOwnRng:1; /* will be true unless CTX owns */ + word16 dontFreeDigest:1; /* when true, we used SetDigest */ word16 haveEMS:1; /* using extended master secret */ #ifdef HAVE_POLY1305 word16 oldPoly:1; /* set when to use old rfc way of poly*/ From bc4a1ee784b5e6b0d3bb76d86dfd66df0b4d406d Mon Sep 17 00:00:00 2001 From: Bill Phipps Date: Mon, 10 Apr 2023 17:15:22 +0000 Subject: [PATCH 110/391] Corrected spacing and comments --- src/internal.c | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/src/internal.c b/src/internal.c index 9338307a0cf..d4b083219d9 100644 --- a/src/internal.c +++ b/src/internal.c @@ -4388,28 +4388,28 @@ static void SetDigest(WOLFSSL* ssl, int hashAlgo) switch (hashAlgo) { #ifndef NO_SHA case sha_mac: - ssl->options.dontFreeDigest=1; + ssl->options.dontFreeDigest = 1; ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha; ssl->buffers.digest.length = WC_SHA_DIGEST_SIZE; break; #endif /* !NO_SHA */ #ifndef NO_SHA256 case sha256_mac: - ssl->options.dontFreeDigest=1; + ssl->options.dontFreeDigest = 1; ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha256; ssl->buffers.digest.length = WC_SHA256_DIGEST_SIZE; break; #endif /* !NO_SHA256 */ #ifdef WOLFSSL_SHA384 case sha384_mac: - ssl->options.dontFreeDigest=1; + ssl->options.dontFreeDigest = 1; ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha384; ssl->buffers.digest.length = WC_SHA384_DIGEST_SIZE; break; #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 case sha512_mac: - ssl->options.dontFreeDigest=1; + ssl->options.dontFreeDigest = 1; ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha512; ssl->buffers.digest.length = WC_SHA512_DIGEST_SIZE; break; @@ -7548,12 +7548,13 @@ void FreeKeyExchange(WOLFSSL* ssl) /* Cleanup digest buffer */ if (ssl->buffers.digest.buffer) { - if(!ssl->options.dontFreeDigest) { + /* Only free if digest buffer was not set using SetDigest */ + if (!ssl->options.dontFreeDigest) { XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST); } ssl->buffers.digest.buffer = NULL; ssl->buffers.digest.length = 0; - ssl->options.dontFreeDigest=0; + ssl->options.dontFreeDigest = 0; } /* Free handshake key */ @@ -26247,13 +26248,13 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, ssl->buffers.digest.length = (unsigned int)digest_sz; /* buffer for hash */ - if(!ssl->buffers.digest.buffer) { - if(!ssl->options.dontFreeDigest) { + if (!ssl->buffers.digest.buffer) { + if (!ssl->options.dontFreeDigest) { XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST); } } - ssl->options.dontFreeDigest=0; + ssl->options.dontFreeDigest = 0; ssl->buffers.digest.buffer = (byte*)XMALLOC(ssl->buffers.digest.length, ssl->heap, DYNAMIC_TYPE_DIGEST); @@ -30507,7 +30508,7 @@ int SendCertificateVerify(WOLFSSL* ssl) /* Digest is not allocated, so do this to prevent free */ if(ssl->buffers.digest.buffer) { - if(!ssl->options.dontFreeDigest) { + if (!ssl->options.dontFreeDigest) { /*This should not happen*/ XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST); @@ -30515,7 +30516,7 @@ int SendCertificateVerify(WOLFSSL* ssl) } ssl->buffers.digest.buffer = NULL; ssl->buffers.digest.length = 0; - ssl->options.dontFreeDigest=0; + ssl->options.dontFreeDigest = 0; /* Final cleanup */ #ifdef WOLFSSL_ASYNC_IO @@ -31998,11 +31999,11 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, TypeHash(ssl->options.hashAlgo)); /* Replace sig buffer with new one */ - if(!ssl->options.dontFreeDigest) { + if (!ssl->options.dontFreeDigest) { XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST); } - ssl->options.dontFreeDigest=0; + ssl->options.dontFreeDigest = 0; ssl->buffers.digest.buffer = encodedSig; } @@ -32219,11 +32220,11 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, TypeHash(ssl->options.hashAlgo)); /* Replace sig buffer with new one */ - if(!ssl->options.dontFreeDigest) { + if (!ssl->options.dontFreeDigest) { XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST); } - ssl->options.dontFreeDigest=0; + ssl->options.dontFreeDigest = 0; ssl->buffers.digest.buffer = encodedSig; } break; @@ -34313,7 +34314,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif /* Digest is not allocated, so do this to prevent free */ if(ssl->buffers.digest.buffer) { - if(!ssl->options.dontFreeDigest) { + if (!ssl->options.dontFreeDigest) { /*This should not happen*/ XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST); @@ -34321,7 +34322,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } ssl->buffers.digest.buffer = NULL; ssl->buffers.digest.length = 0; - ssl->options.dontFreeDigest=0; + ssl->options.dontFreeDigest = 0; #ifdef WOLFSSL_ASYNC_CRYPT /* Cleanup async */ From 8106670420890c5d47847442bbbbc82f71781b56 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 27 Mar 2023 11:49:32 -0700 Subject: [PATCH 111/391] Support for STM32H5 --- IDE/STM32Cube/README.md | 5 ++++- IDE/STM32Cube/default_conf.ftl | 6 ++++++ wolfssl/wolfcrypt/port/st/stm32.h | 11 ++++++++--- wolfssl/wolfcrypt/settings.h | 8 ++++++-- 4 files changed, 24 insertions(+), 6 deletions(-) diff --git a/IDE/STM32Cube/README.md b/IDE/STM32Cube/README.md index 010c1546db7..3ba49fc9a54 100644 --- a/IDE/STM32Cube/README.md +++ b/IDE/STM32Cube/README.md @@ -97,16 +97,19 @@ The section for "Hardware platform" may need to be adjusted depending on your pr * To enable STM32L5 support define `WOLFSSL_STM32L5`. * To enable STM32H7 support define `WOLFSSL_STM32H7`. * To enable STM32WB support define `WOLFSSL_STM32WB`. +* To enable STM32U5 support define `WOLFSSL_STM32U5`. +* To enable STM32H5 support define `WOLFSSL_STM32H5`. To use the STM32 Cube HAL support make sure `WOLFSSL_STM32_CUBEMX` is defined. -The PKA acceleration for ECC is avaialble on some U5, L5 and WB55 chips. +The PKA acceleration for ECC is available on some U5, L5 and WB55 chips. This is enabled with `WOLFSSL_STM32_PKA`. You can see some of the benchmarks [here](STM32_Benchmarks.md). To disable hardware crypto acceleration you can define: * `NO_STM32_HASH` * `NO_STM32_CRYPTO` +* `NO_STM32_RNG` To enable the latest Cube HAL support please define `STM32_HAL_V2`. diff --git a/IDE/STM32Cube/default_conf.ftl b/IDE/STM32Cube/default_conf.ftl index 0b0b85cce36..71ba570b2ef 100644 --- a/IDE/STM32Cube/default_conf.ftl +++ b/IDE/STM32Cube/default_conf.ftl @@ -152,6 +152,12 @@ extern ${variable.value} ${variable.name}; #undef NO_STM32_CRYPTO #define WOLFSSL_STM32_PKA #endif +#elif defined(STM32H563xx) + #define WOLFSSL_STM32H5 + #define HAL_CONSOLE_UART huart3 + #define STM32_HAL_V2 + #undef NO_STM32_HASH + #else #warning Please define a hardware platform! /* This means there is not a pre-defined platform for your board/CPU */ diff --git a/wolfssl/wolfcrypt/port/st/stm32.h b/wolfssl/wolfcrypt/port/st/stm32.h index 1ac060dff12..4bd2b69c15c 100644 --- a/wolfssl/wolfcrypt/port/st/stm32.h +++ b/wolfssl/wolfcrypt/port/st/stm32.h @@ -46,8 +46,12 @@ #if !defined(HASH_ALGOMODE_HASH) && defined(HASH_AlgoMode_HASH) #define HASH_ALGOMODE_HASH HASH_AlgoMode_HASH #endif -#if !defined(HASH_DATATYPE_8B) && defined(HASH_DataType_8b) - #define HASH_DATATYPE_8B HASH_DataType_8b +#if !defined(HASH_DATATYPE_8B) + #if defined(HASH_DataType_8b) + #define HASH_DATATYPE_8B HASH_DataType_8b + #elif defined(HASH_BYTE_SWAP) + #define HASH_DATATYPE_8B HASH_BYTE_SWAP + #endif #endif #ifndef HASH_STR_NBW #define HASH_STR_NBW HASH_STR_NBLW @@ -120,7 +124,8 @@ int wc_Stm32_Hash_Final(STM32_HASH_Context* stmCtx, word32 algo, /* Detect newer CubeMX crypto HAL (HAL_CRYP_Encrypt / HAL_CRYP_Decrypt) */ #if !defined(STM32_HAL_V2) && defined(CRYP_AES_GCM) && \ (defined(WOLFSSL_STM32F7) || defined(WOLFSSL_STM32L5) || \ - defined(WOLFSSL_STM32H7) || defined(WOLFSSL_STM32U5)) + defined(WOLFSSL_STM32H7) || defined(WOLFSSL_STM32U5)) || \ + defined(WOLFSSL_STM32H5) #define STM32_HAL_V2 #endif diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index f90ebc67cbc..e4675552ef2 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1361,7 +1361,8 @@ extern void uITRON4_free(void *p) ; defined(WOLFSSL_STM32F7) || defined(WOLFSSL_STM32F1) || \ defined(WOLFSSL_STM32L4) || defined(WOLFSSL_STM32L5) || \ defined(WOLFSSL_STM32WB) || defined(WOLFSSL_STM32H7) || \ - defined(WOLFSSL_STM32G0) || defined(WOLFSSL_STM32U5) + defined(WOLFSSL_STM32G0) || defined(WOLFSSL_STM32U5) || \ + defined(WOLFSSL_STM32H5) #define SIZEOF_LONG_LONG 8 #ifndef CHAR_BIT @@ -1416,6 +1417,8 @@ extern void uITRON4_free(void *p) ; #include "stm32g0xx_hal.h" #elif defined(WOLFSSL_STM32U5) #include "stm32u5xx_hal.h" + #elif defined(WOLFSSL_STM32H5) + #include "stm32h5xx_hal.h" #endif #if defined(WOLFSSL_CUBEMX_USE_LL) && defined(WOLFSSL_STM32L4) #include "stm32l4xx_ll_rng.h" @@ -1467,7 +1470,8 @@ extern void uITRON4_free(void *p) ; #endif /* WOLFSSL_STM32_CUBEMX */ #endif /* WOLFSSL_STM32F2 || WOLFSSL_STM32F4 || WOLFSSL_STM32L4 || WOLFSSL_STM32L5 || WOLFSSL_STM32F7 || WOLFSSL_STMWB || - WOLFSSL_STM32H7 || WOLFSSL_STM32G0 || WOLFSSL_STM32U5 */ + WOLFSSL_STM32H7 || WOLFSSL_STM32G0 || WOLFSSL_STM32U5 || + WOLFSSL_STM32H5 */ #ifdef WOLFSSL_DEOS #include #include From e55b9e229765004fe8dec8c8df0c7f1975a53cf2 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 27 Mar 2023 13:39:29 -0700 Subject: [PATCH 112/391] Added benchmarks for STM32H563ZI. --- IDE/STM32Cube/STM32_Benchmarks.md | 50 +++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/IDE/STM32Cube/STM32_Benchmarks.md b/IDE/STM32Cube/STM32_Benchmarks.md index 4c45a45e02f..ffb63c0b969 100644 --- a/IDE/STM32Cube/STM32_Benchmarks.md +++ b/IDE/STM32Cube/STM32_Benchmarks.md @@ -7,6 +7,7 @@ * [STM32L562E](#stm32l562e) * [STM32F777](#stm32f777) * [STM32U585](#stm32u585) +* [STM32H563ZI](#stm32h563zi) ## STM32H753ZI @@ -708,3 +709,52 @@ ECDSA [ SECP256R1] 256 verify 4 ops took 1.196 sec, avg 299.000 Benchmark complete Benchmark Test: Return code 0 ``` + +## STM32H563ZI + +Cortex-M33 at 150MHz + +### STM32H563ZI (No STM HW Crypto, SP Math ASM Cortex M) + +``` +------------------------------------------------------------------------------ + wolfSSL version 5.6.0 +------------------------------------------------------------------------------ +Running wolfCrypt Benchmarks... +wolfCrypt Benchmark (block bytes 1024, min 1.0 sec each) +RNG 2 MB took 1.011 seconds, 1.950 MB/s +AES-128-CBC-enc 4 MB took 1.000 seconds, 3.686 MB/s +AES-128-CBC-dec 4 MB took 1.004 seconds, 3.723 MB/s +AES-192-CBC-enc 3 MB took 1.004 seconds, 3.187 MB/s +AES-192-CBC-dec 3 MB took 1.000 seconds, 3.046 MB/s +AES-256-CBC-enc 3 MB took 1.000 seconds, 2.816 MB/s +AES-256-CBC-dec 3 MB took 1.004 seconds, 2.728 MB/s +AES-128-GCM-enc 2 MB took 1.000 seconds, 2.048 MB/s +AES-128-GCM-dec 2 MB took 1.004 seconds, 2.091 MB/s +AES-192-GCM-enc 2 MB took 1.008 seconds, 1.879 MB/s +AES-192-GCM-dec 2 MB took 1.011 seconds, 1.874 MB/s +AES-256-GCM-enc 2 MB took 1.000 seconds, 1.741 MB/s +AES-256-GCM-dec 2 MB took 1.012 seconds, 1.745 MB/s +AES-128-GCM-enc-no_AAD 2 MB took 1.008 seconds, 2.057 MB/s +AES-128-GCM-dec-no_AAD 2 MB took 1.008 seconds, 2.108 MB/s +AES-192-GCM-enc-no_AAD 2 MB took 1.000 seconds, 1.894 MB/s +AES-192-GCM-dec-no_AAD 2 MB took 1.000 seconds, 1.894 MB/s +AES-256-GCM-enc-no_AAD 2 MB took 1.004 seconds, 1.759 MB/s +AES-256-GCM-dec-no_AAD 2 MB took 1.004 seconds, 1.759 MB/s +GMAC Table 4-bit 4 MB took 1.000 seconds, 4.400 MB/s +CHACHA 8 MB took 1.000 seconds, 8.448 MB/s +CHA-POLY 6 MB took 1.000 seconds, 5.683 MB/s +POLY1305 26 MB took 1.000 seconds, 25.574 MB/s +SHA-256 5 MB took 1.004 seconds, 4.972 MB/s +HMAC-SHA256 5 MB took 1.000 seconds, 4.941 MB/s +RSA 2048 public 122 ops took 1.000 sec, avg 8.197 ms, 122.000 ops/sec +RSA 2048 private 4 ops took 1.231 sec, avg 307.750 ms, 3.249 ops/sec +DH 2048 key gen 7 ops took 1.000 sec, avg 142.857 ms, 7.000 ops/sec +DH 2048 agree 8 ops took 1.141 sec, avg 142.625 ms, 7.011 ops/sec +ECC [ SECP256R1] 256 key gen 204 ops took 1.000 sec, avg 4.902 ms, 204.000 ops/sec +ECDHE [ SECP256R1] 256 agree 94 ops took 1.007 sec, avg 10.713 ms, 93.347 ops/sec +ECDSA [ SECP256R1] 256 sign 136 ops took 1.012 sec, avg 7.441 ms, 134.387 ops/sec +ECDSA [ SECP256R1] 256 verify 66 ops took 1.012 sec, avg 15.333 ms, 65.217 ops/sec +Benchmark complete +Benchmark Test: Return code 0 +``` From e7d2f05ff389b9e3f3220ee54480d43f49dd17d3 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 28 Mar 2023 16:15:47 -0700 Subject: [PATCH 113/391] Fixes to support larger H5 save/restore and larger digest result (for SHA2-512). --- wolfcrypt/src/port/st/stm32.c | 32 ++++++++++++++++++------------- wolfssl/wolfcrypt/port/st/stm32.h | 11 ++++++++--- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index 39b4417b305..3da7d90ee40 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -164,22 +164,25 @@ static void wc_Stm32_Hash_RestoreContext(STM32_HASH_Context* ctx, int algo) static void wc_Stm32_Hash_GetDigest(byte* hash, int digestSize) { word32 digest[HASH_MAX_DIGEST/sizeof(word32)]; + int i = 0, sz; - /* get digest result */ - digest[0] = HASH->HR[0]; - digest[1] = HASH->HR[1]; - digest[2] = HASH->HR[2]; - digest[3] = HASH->HR[3]; - if (digestSize >= 20) { - digest[4] = HASH->HR[4]; + if (digestSize > HASH_MAX_DIGEST) + digestSize = HASH_MAX_DIGEST; + + sz = digestSize; + while (sz > 0) { + /* first 20 bytes come from instance HR */ + if (i < 5) { + digest[i] = HASH->HR[i]; + } #ifdef HASH_DIGEST - if (digestSize >= 28) { - digest[5] = HASH_DIGEST->HR[5]; - digest[6] = HASH_DIGEST->HR[6]; - if (digestSize == 32) - digest[7] = HASH_DIGEST->HR[7]; + /* reset comes from HASH_DIGEST */ + else { + digest[i] = HASH_DIGEST->HR[i]; } #endif + i++; + sz -= 4; } ByteReverseWords(digest, digest, digestSize); @@ -202,11 +205,14 @@ static int wc_Stm32_Hash_WaitDone(STM32_HASH_Context* stmCtx) int timeout = 0; (void)stmCtx; - /* wait until hash digest is complete */ + /* wait until not busy and hash digest / input block are complete */ while ((HASH->SR & HASH_SR_BUSY) && #ifdef HASH_IMR_DCIE (HASH->SR & HASH_SR_DCIS) == 0 && #endif + #ifdef HASH_IMR_DINIE + (HASH->SR & HASH_SR_DINIS) == 0 && + #endif ++timeout < STM32_HASH_TIMEOUT) { }; diff --git a/wolfssl/wolfcrypt/port/st/stm32.h b/wolfssl/wolfcrypt/port/st/stm32.h index 4bd2b69c15c..05d9d642384 100644 --- a/wolfssl/wolfcrypt/port/st/stm32.h +++ b/wolfssl/wolfcrypt/port/st/stm32.h @@ -35,10 +35,15 @@ #ifdef HASH_DIGEST /* The HASH_DIGEST register indicates SHA224/SHA256 support */ #define STM32_HASH_SHA2 - #define HASH_CR_SIZE 54 - #define HASH_MAX_DIGEST 32 + #if defined(WOLFSSL_STM32H5) + #define HASH_CR_SIZE 103 + #define HASH_MAX_DIGEST 64 /* Up to SHA512 */ + #else + #define HASH_CR_SIZE 54 + #define HASH_MAX_DIGEST 32 + #endif #else - #define HASH_CR_SIZE 50 + #define HASH_CR_SIZE 50 #define HASH_MAX_DIGEST 20 #endif From 7e461e1b392efb1ad74475ee9e2b559183ffa4fc Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 12 Apr 2023 11:39:51 -0700 Subject: [PATCH 114/391] Added STM32G0 benchmarks. --- IDE/STM32Cube/STM32_Benchmarks.md | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/IDE/STM32Cube/STM32_Benchmarks.md b/IDE/STM32Cube/STM32_Benchmarks.md index ffb63c0b969..3f429407b84 100644 --- a/IDE/STM32Cube/STM32_Benchmarks.md +++ b/IDE/STM32Cube/STM32_Benchmarks.md @@ -8,6 +8,7 @@ * [STM32F777](#stm32f777) * [STM32U585](#stm32u585) * [STM32H563ZI](#stm32h563zi) +* [STM32G071RB](#stm32g071rb) ## STM32H753ZI @@ -758,3 +759,49 @@ ECDSA [ SECP256R1] 256 verify 66 ops took 1.012 sec, avg 15.333 Benchmark complete Benchmark Test: Return code 0 ``` + + +## STM32G071RB + +STM32G0 is a Cortex M0+ at up to 64MHz. The STM32G071RB has 128KB Flash and 36KB RAM. + +### STM32G071RB Benchmarks (SP Math Small with ARM Thumb Assembly) + +Build options used: +* `WOLFSSL_HAVE_SP_RSA` +* `WOLFSSL_SP_ARM_THUMB_ASM` +* `WOLFSSL_SP_SMALL` +* `WOLFSSL_SP_MATH` + +``` +------------------------------------------------------------------------------ + wolfSSL version 5.6.0 +------------------------------------------------------------------------------ +Running wolfCrypt Benchmarks... +wolfCrypt Benchmark (block bytes 1024, min 1.0 sec each) +RNG 205 KB took 1.043 seconds, 196.357 KB/s +AES-128-CBC-enc 358 KB took 1.008 seconds, 355.556 KB/s +AES-128-CBC-dec 358 KB took 1.051 seconds, 341.009 KB/s +AES-192-CBC-enc 333 KB took 1.063 seconds, 313.076 KB/s +AES-192-CBC-dec 307 KB took 1.023 seconds, 300.293 KB/s +AES-256-CBC-enc 282 KB took 1.004 seconds, 280.478 KB/s +AES-256-CBC-dec 282 KB took 1.043 seconds, 269.990 KB/s +SHA-256 486 KB took 1.020 seconds, 476.863 KB/s +HMAC-SHA256 486 KB took 1.028 seconds, 473.152 KB/s +RSA 2048 public 12 ops took 1.043 sec, avg 86.917 ms, 11.505 ops/sec +RSA 2048 private 2 ops took 6.482 sec, avg 3241.000 ms, 0.309 ops/sec +ECC [ SECP256R1] 256 key gen 10 ops took 1.122 sec, avg 112.200 ms, 8.913 ops/sec +ECDHE [ SECP256R1] 256 agree 4 ops took 1.000 sec, avg 250.000 ms, 4.000 ops/sec +ECDSA [ SECP256R1] 256 sign 8 ops took 1.227 sec, avg 153.375 ms, 6.520 ops/sec +ECDSA [ SECP256R1] 256 verify 4 ops took 1.396 sec, avg 349.000 ms, 2.865 ops/sec +Benchmark complete +Benchmark Test: Return code 0 +``` + +Without `WOLFSSL_SP_SMALL` (larger version): + +``` +RSA 2048 public 14 ops took 1.016 sec, avg 72.571 ms, 13.780 ops/sec +RSA 2048 private 2 ops took 5.447 sec, avg 2723.500 ms, 0.367 ops/sec +``` + From 3b64e04c5138c6a9720a0b03da52644567986d87 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 12 Apr 2023 13:06:37 -0700 Subject: [PATCH 115/391] Fix PKA build error with SP sign. Fix U5/H5/H7 hashing, which require a workaround to write an extra 32-bit to flush FIFO before save/restore. --- wolfcrypt/src/port/st/stm32.c | 12 +++++++++++- wolfssl/wolfcrypt/port/st/stm32.h | 7 +++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index 3da7d90ee40..c0208127e51 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -312,6 +312,13 @@ int wc_Stm32_Hash_Update(STM32_HASH_Context* stmCtx, word32 algo, } if (wroteToFifo) { + #ifdef STM32_HASH_FIFO_WORKAROUND + /* If we wrote a block send one more 32-bit to FIFO to trigger start. + * The save/restore feature cannot leave 16 deep FIFO filled. */ + wc_Stm32_Hash_Data(stmCtx, 4); + stmCtx->fifoBytes += 4; + #endif + /* make sure hash operation is done */ ret = wc_Stm32_Hash_WaitDone(stmCtx); @@ -868,7 +875,10 @@ int wc_ecc_mulmod_ex(const mp_int *k, ecc_point *G, ecc_point *R, mp_int* a, res = mp_read_unsigned_bin(R->x, Gxbin, size); if (res == MP_OKAY) { res = mp_read_unsigned_bin(R->y, Gybin, size); -#ifndef WOLFSSL_SP_MATH + +#if defined(USE_FAST_MATH) || defined(USE_INTEGER_HEAP_MATH) || \ + ((defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)) && \ + defined(WOLFSSL_SP_INT_NEGATIVE)) /* if k is negative, we compute the multiplication with abs(-k) * with result (x, y) and modify the result to (x, -y) */ diff --git a/wolfssl/wolfcrypt/port/st/stm32.h b/wolfssl/wolfcrypt/port/st/stm32.h index 05d9d642384..f441072e841 100644 --- a/wolfssl/wolfcrypt/port/st/stm32.h +++ b/wolfssl/wolfcrypt/port/st/stm32.h @@ -71,6 +71,13 @@ #define STM32_HASH_REG_SIZE 4 #define STM32_HASH_FIFO_SIZE 16 /* FIFO is 16 deep 32-bits wide */ +#if (defined(WOLFSSL_STM32U5) || defined(WOLFSSL_STM32H5) || \ + defined(WOLFSSL_STM32H7)) && !defined(NO_STM32_HASH_FIFO_WORKAROUND) + /* workaround for hash FIFO to write one extra to finalize */ + #undef STM32_HASH_FIFO_WORKAROUND + #define STM32_HASH_FIFO_WORKAROUND +#endif + /* STM32 Hash Context */ typedef struct { From 105bd3771a706eba3d0661df2e3bb81b9d0bfe20 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 4 Apr 2023 13:46:30 -0700 Subject: [PATCH 116/391] Fixes for implicit casts. Tested with `./configure --disable-asm --enable-32bit --enable-asn=original --enable-cryptonly CFLAGS="-Wconversion -pedantic" && make`. Some progress with ASN template, but not complete. --- wolfcrypt/src/aes.c | 16 +- wolfcrypt/src/asn.c | 522 +++++++++++++++++++------------------ wolfcrypt/src/ecc.c | 93 +++---- wolfcrypt/src/hash.c | 2 +- wolfcrypt/src/misc.c | 49 ++-- wolfcrypt/src/poly1305.c | 2 +- wolfcrypt/src/random.c | 8 +- wolfcrypt/src/sha256.c | 2 +- wolfcrypt/src/signature.c | 10 +- wolfcrypt/src/sp_int.c | 81 +++--- wolfcrypt/src/wolfmath.c | 23 +- wolfssl/wolfcrypt/sp_int.h | 14 +- 12 files changed, 421 insertions(+), 401 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 042331ad42c..2b3b038b35b 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -2893,7 +2893,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( aes->left = 0; #endif - aes->keylen = keylen; + aes->keylen = (int)keylen; aes->rounds = (keylen/4) + 6; #ifdef WOLFSSL_AESNI @@ -4563,7 +4563,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #if (defined(HAVE_AESGCM) && !defined(WC_NO_RNG)) || defined(HAVE_AESCCM) static WC_INLINE void IncCtr(byte* ctr, word32 ctrSz) { - int i; + word32 i; for (i = ctrSz-1; i >= 0; i--) { if (++ctr[i]) break; @@ -4683,12 +4683,12 @@ static void GenerateM0(Aes* aes) #elif defined(GCM_TABLE_4BIT) #if !defined(BIG_ENDIAN_ORDER) && !defined(WC_16BIT_CPU) -static WC_INLINE void Shift4_M0(byte *r8, byte* z8) +static WC_INLINE void Shift4_M0(byte *r8, byte *z8) { int i; for (i = 15; i > 0; i--) - r8[i] = (z8[i-1] << 4) | (z8[i] >> 4); - r8[0] = z8[0] >> 4; + r8[i] = (byte)(z8[i-1] << 4) | (byte)(z8[i] >> 4); + r8[0] = (byte)(z8[0] >> 4); } #endif @@ -7165,7 +7165,7 @@ int WARN_UNUSED_RESULT AES_GCM_decrypt_C( /* ConstantCompare returns the cumulative bitwise or of the bitwise xor of * the pairwise bytes in the strings. */ - res = ConstantCompare(authTag, Tprime, authTagSz); + res = ConstantCompare(authTag, Tprime, (int)authTagSz); /* convert positive retval from ConstantCompare() to all-1s word, in * constant time. */ @@ -8571,7 +8571,7 @@ int wc_AesGcmSetExtIV(Aes* aes, const byte* iv, word32 ivSz) { int ret = 0; - if (aes == NULL || iv == NULL || !CheckAesGcmIvSize(ivSz)) { + if (aes == NULL || iv == NULL || !CheckAesGcmIvSize((int)ivSz)) { ret = BAD_FUNC_ARG; } @@ -8599,7 +8599,7 @@ int wc_AesGcmSetIV(Aes* aes, word32 ivSz, { int ret = 0; - if (aes == NULL || rng == NULL || !CheckAesGcmIvSize(ivSz) || + if (aes == NULL || rng == NULL || !CheckAesGcmIvSize((int)ivSz) || (ivFixed == NULL && ivFixedSz != 0) || (ivFixed != NULL && ivFixedSz != AES_IV_FIXED_SZ)) { diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index d44769da337..16ffce309b2 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -596,7 +596,7 @@ static word32 SizeASN_Num(word32 n, int bits, byte tag) int j; word32 len; - len = 1 + 1 + bits / 8; + len = 1 + 1 + (word32)bits / 8; /* Discover actual size by checking for high zeros. */ for (j = bits - 8; j > 0; j -= 8) { if (n >> j) @@ -696,7 +696,7 @@ int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz) /* Calculate the size of the MP integer data. */ length = mp_unsigned_bin_size(data[i].data.mp); length += mp_leading_bit(data[i].data.mp) ? 1 : 0; - len = SizeASNHeader(length) + length; + len = (word32)SizeASNHeader((word32)length) + (word32)length; break; case ASN_DATA_TYPE_REPLACE_BUFFER: @@ -776,7 +776,7 @@ int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz) #endif } - *encSz = sz; + *encSz = (int)sz; return 0; } @@ -800,7 +800,7 @@ static void SetASN_Num(word32 n, int bits, byte* out, byte tag) idx = 2; /* Set the length of the number based on maximum bit length. */ - len = bits / 8; + len = (byte)(bits / 8); /* Discover actual size by checking for leading zero bytes. */ for (j = bits - 8; j > 0; j -= 8) { if ((n >> j) != 0) { @@ -815,7 +815,7 @@ static void SetASN_Num(word32 n, int bits, byte* out, byte tag) */ if (tag == ASN_BIT_STRING) { byte unusedBits = 0; - byte lastByte = n >> j; + byte lastByte = (byte)(n >> j); /* Quick check last bit. */ if ((lastByte & 0x01) == 0x00) { @@ -840,7 +840,7 @@ static void SetASN_Num(word32 n, int bits, byte* out, byte tag) out[1] = len; /* Place in the required bytes of the number. */ for (; j >= 0; j -= 8) - out[idx++] = n >> j; + out[idx++] = (byte)(n >> j); } /* Creates the DER encoding of the ASN.1 items. @@ -1082,7 +1082,7 @@ static int GetASN_BitString(const byte* input, word32 idx, int length) return ASN_PARSE_E; } /* Ensure unused bits are zero. */ - if ((byte)(input[idx + length - 1] << (8 - input[idx])) != 0) { + if ((byte)(input[idx + (word32)length - 1] << (8 - input[idx])) != 0) { #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x", input[idx], input[idx + length - 1]); @@ -1261,7 +1261,7 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, /* Store data pointer and length for caller. */ data->data.ref.data = input + idx; - data->data.ref.length = len; + data->data.ref.length = (word32)len; break; case ASN_DATA_TYPE_NONE: @@ -1295,7 +1295,7 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, word32 oidIdx = 0; /* Store OID data pointer and length */ data->data.oid.data = input + idx; - data->data.oid.length = len; + data->data.oid.length = (word32)len; /* Get the OID sum. */ err = GetOID(input + idx, &oidIdx, &data->data.oid.sum, data->data.oid.type, len); @@ -1310,7 +1310,7 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, /* Otherwise store data pointer and length. */ data->data.ref.data = input + idx; - data->data.ref.length = len; + data->data.ref.length = (word32)len; break; #ifdef DEBUG_WOLFSSL @@ -1511,9 +1511,9 @@ int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete, return ASN_PARSE_E; } /* Store length of data. */ - data[i].length = len; + data[i].length = (word32)len; /* Note the max length of items under this one. */ - endIdx[depth + 1] = idx + len; + endIdx[depth + 1] = idx + (word32)len; if (choice > 1) { /* Note we found a number choice. */ choiceMet[choice - 2] = 1; @@ -1561,7 +1561,7 @@ int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete, if (asn[i].headerOnly) { /* Store reference to data and length. */ data[i].data.ref.data = input + idx; - data[i].data.ref.length = len; + data[i].data.ref.length = (word32)len; continue; } @@ -1572,7 +1572,7 @@ int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete, } /* Move index to next item. */ - idx += len; + idx += (word32)len; /* When matched numbered choice ... */ if (asn[i].optional > 1) { @@ -1780,7 +1780,7 @@ static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len, ret = ASN_PARSE_E; } /* Check all data used if complete set. */ - if ((ret == 0) && complete && (idx + *len != maxIdx)) { + if ((ret == 0) && complete && (idx + (word32)*len != maxIdx)) { ret = ASN_PARSE_E; } if (ret == 0) { @@ -2112,7 +2112,7 @@ int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx, int check) { int length = 0; - word32 idx = *inOutIdx; + word32 idx = (word32)*inOutIdx; byte b; /* Ensure zero return length on error. */ @@ -2177,7 +2177,7 @@ int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx, } /* When requested, check the buffer has at least length bytes left. */ - if (check && ((idx + length) > maxIdx)) { + if (check && ((idx + (word32)length) > maxIdx)) { WOLFSSL_MSG("GetLength - value exceeds buffer length"); return BUFFER_E; } @@ -2850,7 +2850,7 @@ const char* GetSigName(int oid) { */ int SetASNInt(int len, byte firstByte, byte* output) { - word32 idx = 0; + int idx = 0; if (output) { /* Write out tag. */ @@ -2865,7 +2865,7 @@ int SetASNInt(int len, byte firstByte, byte* output) len++; } /* Encode length - passing NULL for output will not encode. */ - idx += SetLength(len, output ? output + idx : NULL); + idx += SetLength((word32)len, output ? output + idx : NULL); /* Put out pre-pended 0 as well. */ if (firstByte & 0x80) { if (output) { @@ -3088,8 +3088,8 @@ int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx) maxIdx); if (ret == 0) { /* Return number through variable and return value. */ - *number = num; - ret = num; + *number = (int)num; + ret = (int)num; } return ret; #endif @@ -3102,7 +3102,7 @@ int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx) int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx) { word32 idx = *inOutIdx; - word32 len = 0; + int len = 0; int i; byte ar[MAX_LENGTH_SZ]; @@ -3209,7 +3209,7 @@ int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx) if (mp_init(mpi) != MP_OKAY) return MP_INIT_E; - if (mp_read_unsigned_bin(mpi, input + idx, length) != 0) { + if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) { mp_clear(mpi); return ASN_GETINT_E; } @@ -3221,7 +3221,7 @@ int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx) } #endif /* HAVE_WOLF_BIGINT */ - *inOutIdx = idx + length; + *inOutIdx = idx + (word32)length; return 0; #else @@ -3254,7 +3254,7 @@ static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx, if (mp_init(mpi) != MP_OKAY) return MP_INIT_E; - if (mp_read_unsigned_bin(mpi, input + idx, length) != 0) { + if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) { mp_clear(mpi); return ASN_GETINT_E; } @@ -3266,7 +3266,7 @@ static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx, } #endif /* HAVE_WOLF_BIGINT */ - *inOutIdx = idx + length; + *inOutIdx = idx + (word32)length; return 0; } @@ -3355,7 +3355,7 @@ int CheckBitString(const byte* input, word32* inOutIdx, int* len, if (b >= 0x08) return ASN_PARSE_E; if (b != 0) { - if ((byte)(input[idx + length - 1] << (8 - b)) != 0) + if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0) return ASN_PARSE_E; } idx++; @@ -3389,10 +3389,10 @@ int CheckBitString(const byte* input, word32* inOutIdx, int* len, if (ret == 0) { /* Return length of data and unused bits if required. */ if (len != NULL) { - *len = dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length; + *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length; } if (unusedBits != NULL) { - *unusedBits = bits; + *unusedBits = (byte)bits; } } @@ -5572,7 +5572,7 @@ int SetObjectId(int len, byte* output) /* Skip tag. */ idx += ASN_TAG_SZ; /* Encode length - passing NULL for output will not encode. */ - idx += SetLength(len, output ? output + idx : NULL); + idx += SetLength((word32)len, output ? output + idx : NULL); /* Return index after header. */ return idx; @@ -5815,7 +5815,7 @@ static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx) if (ret != 0) return ret; - idx += length; + idx += (word32)length; *inOutIdx = idx; return 0; @@ -6878,7 +6878,7 @@ int ToTraditional_ex(byte* input, word32 sz, word32* algId) if (length < 0) return length; - if (length + inOutIdx > sz) + if ((word32)length + inOutIdx > sz) return BUFFER_E; XMEMMOVE(input, input + inOutIdx, length); @@ -6963,7 +6963,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, /* version Version * no header information just INTEGER */ - sz = SetMyVersion(PKCS8v0, out + keyIdx, 0); + sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0); tmpSz += sz; keyIdx += sz; /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */ sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */ @@ -6972,20 +6972,20 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, sz = SetLength(oidSz, buf); sz += 1; /* plus one for ASN object id */ } - sz = SetAlgoID(algoID, out + keyIdx, oidKeyType, oidSz + sz); + sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz)); tmpSz += sz; keyIdx += sz; /* privateKey PrivateKey * * pkcs8 ecc uses slightly different format. Places curve oid in * buffer */ if (curveOID != NULL && oidSz > 0) { - sz = SetObjectId(oidSz, out + keyIdx); + sz = (word32)SetObjectId((int)oidSz, out + keyIdx); keyIdx += sz; tmpSz += sz; XMEMCPY(out + keyIdx, curveOID, oidSz); keyIdx += oidSz; tmpSz += oidSz; } - sz = SetOctetString(keySz, out + keyIdx); + sz = (word32)SetOctetString(keySz, out + keyIdx); keyIdx += sz; tmpSz += sz; XMEMCPY(out + keyIdx, key, keySz); tmpSz += keySz; @@ -6998,7 +6998,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz); *outSz = tmpSz + sz; - return tmpSz + sz; + return (int)(tmpSz + sz); #else DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length); int sz; @@ -8185,12 +8185,12 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz); } if (ret == 0) { - padSz = (blockSz - (keySz & (blockSz - 1))) & (blockSz - 1); + padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) & (blockSz - 1)); /* inner = OCT salt INT itt */ innerLen = 2 + saltSz + 2 + (itt < 256 ? 1 : 2); if (version != PKCS5v2) { - pbeOidBuf = OidFromId(pbeId, oidPBEType, &pbeOidBufSz); + pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz); /* pbe = OBJ pbse1 SEQ [ inner ] */ pbeLen = 2 + pbeOidBufSz + 2 + innerLen; } @@ -8200,11 +8200,11 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */ kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen; /* enc = OBJ enc_alg OCT iv */ - encLen = 2 + encOidSz + 2 + blockSz; + encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz; /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */ pbeLen = 2 + sizeof(pbes2) + 2 + 2 + kdfLen + 2 + encLen; - ret = wc_RNG_GenerateBlock(rng, cbcIv, blockSz); + ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz); } } if (ret == 0) { @@ -8249,35 +8249,35 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, } } if (ret == 0) { - ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, pbeId, - out + encIdx, keySz, version, cbcIv, 1, 0); + ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId, + out + encIdx, (int)keySz, version, cbcIv, 1, 0); } if (ret == 0) { if (version != PKCS5v2) { /* PBE algorithm */ idx += SetSequence(pbeLen, out + idx); - idx += SetObjectId(pbeOidBufSz, out + idx); + idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx); XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz); idx += pbeOidBufSz; } else { /* PBES2 algorithm identifier */ idx += SetSequence(pbeLen, out + idx); - idx += SetObjectId(pbeOidBufSz, out + idx); + idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx); XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz); idx += pbeOidBufSz; /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */ idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx); /* KDF Algorithm Identifier */ idx += SetSequence(kdfLen, out + idx); - idx += SetObjectId(sizeof(pbkdf2Oid), out + idx); + idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx); XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid)); idx += sizeof(pbkdf2Oid); } idx += SetSequence(innerLen, out + idx); idx += SetOctetString(saltSz, out + idx); XMEMCPY(out + idx, salt, saltSz); idx += saltSz; - ret = SetShortInt(out, &idx, itt, *outSz); + ret = SetShortInt(out, &idx, (word32)itt, *outSz); if (ret > 0) ret = 0; } @@ -8285,19 +8285,19 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, if (version == PKCS5v2) { /* Encryption Algorithm Identifier */ idx += SetSequence(encLen, out + idx); - idx += SetObjectId(encOidSz, out + idx); + idx += (word32)SetObjectId(encOidSz, out + idx); XMEMCPY(out + idx, encOid, encOidSz); - idx += encOidSz; + idx += (word32)encOidSz; /* Encryption Algorithm Parameter: CBC IV */ - idx += SetOctetString(blockSz, out + idx); + idx += SetOctetString((word32)blockSz, out + idx); XMEMCPY(out + idx, cbcIv, blockSz); - idx += blockSz; + idx += (word32)blockSz; } idx += SetOctetString(keySz, out + idx); /* Default PRF - no need to write out OID */ idx += keySz; - ret = idx; + ret = (int)idx; } #ifdef WOLFSSL_SMALL_STACK @@ -8338,11 +8338,11 @@ int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password, * bytes intact. This code calculates the length without the padding * and we return that to the user. */ inOutIdx = 0; - if (GetSequence(input, &inOutIdx, &length, ret) < 0) { + if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) { ret = ASN_PARSE_E; } else { - ret = inOutIdx + length; + ret = (int)inOutIdx + length; } } @@ -8386,7 +8386,7 @@ int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz, ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId, curveOid, curveOidSz); if (ret >= 0) { - pkcs8KeySz = ret; + pkcs8KeySz = (word32)ret; ret = 0; } } @@ -8519,7 +8519,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) } /* Find the end of this SEQUENCE so we can check for the OPTIONAL and * DEFAULT items. */ - seqEnd = inOutIdx + length; + seqEnd = inOutIdx + (word32)length; ret = GetOctetString(input, &inOutIdx, &saltSz, sz); if (ret < 0) @@ -8537,7 +8537,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) #endif XMEMCPY(salt, &input[inOutIdx], saltSz); - inOutIdx += saltSz; + inOutIdx += (word32)saltSz; if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) { ERROR_OUT(ASN_PARSE_E, exit_dc); @@ -8579,7 +8579,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) ERROR_OUT(ASN_PARSE_E, exit_dc); } - if (CheckAlgoV2(oid, &id, NULL) < 0) { + if (CheckAlgoV2((int)oid, &id, NULL) < 0) { ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */ } @@ -8595,7 +8595,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) } XMEMCPY(cbcIv, &input[inOutIdx], length); - inOutIdx += length; + inOutIdx += (word32)length; } if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) { @@ -8611,7 +8611,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) } ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id, - input + inOutIdx, length, version, cbcIv, 0, shaOid); + input + inOutIdx, length, version, cbcIv, 0, (int)shaOid); exit_dc: #ifdef WOLFSSL_SMALL_STACK @@ -8757,7 +8757,7 @@ int ToTraditionalEnc(byte* input, word32 sz, const char* password, ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz); if (ret > 0) { - ret = ToTraditional_ex(input, ret, algId); + ret = ToTraditional_ex(input, (word32)ret, algId); } return ret; @@ -8896,18 +8896,18 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, /* calculate size */ /* size of constructed string at end */ - sz = Pkcs8Pad(NULL, inputSz, blockSz); + sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz); totalSz = ASN_TAG_SZ; totalSz += SetLength(sz, seq); totalSz += sz; /* size of sequence holding object id and sub sequence of salt and itt */ - algoName = OidFromId(id, oidPBEType, &algoSz); + algoName = OidFromId((word32)id, oidPBEType, &algoSz); if (algoName == NULL) { WOLFSSL_MSG("Unknown Algorithm"); return 0; } - innerSz = SetObjectId(algoSz, seq); + innerSz = (word32)SetObjectId((int)algoSz, seq); innerSz += algoSz; /* get subsequence of salt and itt */ @@ -8921,9 +8921,9 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, seqSz += sz; tmpIdx = 0; - ret = SetShortInt(shr, &tmpIdx, itt, maxShr); + ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr); if (ret >= 0) { - seqSz += ret; + seqSz += (word32)ret; } else { return ret; @@ -8941,7 +8941,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, return BUFFER_E; inOutIdx += SetSequence(innerSz, out + inOutIdx); - inOutIdx += SetObjectId(algoSz, out + inOutIdx); + inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx); XMEMCPY(out + inOutIdx, algoName, algoSz); inOutIdx += algoSz; inOutIdx += SetSequence(seqSz, out + inOutIdx); @@ -8975,7 +8975,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, inOutIdx += saltSz; /* place iteration setting in buffer */ - ret = SetShortInt(out, &inOutIdx, itt, *outSz); + ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz); if (ret < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -8992,7 +8992,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0; /* get pad size and verify buffer room */ - sz = Pkcs8Pad(NULL, inputSz, blockSz); + sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz); if (sz + inOutIdx > *outSz) { #ifdef WOLFSSL_SMALL_STACK XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -9003,7 +9003,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, /* copy input to output buffer and pad end */ XMEMCPY(out + inOutIdx, input, inputSz); - sz = Pkcs8Pad(out + inOutIdx, inputSz, blockSz); + sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz); #ifdef WOLFSSL_SMALL_STACK cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER); if (cbcIv == NULL) { @@ -9013,8 +9013,8 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, #endif /* encrypt */ - if ((ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id, - out + inOutIdx, sz, version, cbcIv, 1, 0)) < 0) { + if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id, + out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -9030,7 +9030,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, (void)rng; - return inOutIdx + sz; + return (int)(inOutIdx + sz); #else DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length); int ret = 0; @@ -9343,10 +9343,10 @@ int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz, return ASN_RSA_KEY_E; } if (nSz) - *nSz = length; + *nSz = (word32)length; if (n) *n = &input[*inOutIdx]; - *inOutIdx += length; + *inOutIdx += (word32)length; /* Get exponent */ ret = GetASNInt(input, inOutIdx, &length, inSz); @@ -9354,10 +9354,10 @@ int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz, return ASN_RSA_KEY_E; } if (eSz) - *eSz = length; + *eSz = (word32)length; if (e) *e = &input[*inOutIdx]; - *inOutIdx += length; + *inOutIdx += (word32)length; return ret; #else @@ -9893,8 +9893,8 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) idx += total; /* object dhKeyAgreement 1.2.840.113549.1.3.1 */ - idx += SetObjectId(sizeof(keyDhOid), NULL); - idx += sizeof(keyDhOid); + idx += (word32)SetObjectId(sizeof(keyDhOid), NULL); + idx += (word32)sizeof(keyDhOid); len = idx - keySz; /* sequence - all but pub/priv */ idx += SetSequence(len, NULL); @@ -9926,7 +9926,7 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) /* sequence - all but pub/priv */ idx += SetSequence(len, output + idx); /* object dhKeyAgreement 1.2.840.113549.1.3.1 */ - idx += SetObjectId(sizeof(keyDhOid), output + idx); + idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx); XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid)); idx += sizeof(keyDhOid); @@ -10141,12 +10141,12 @@ int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz, if (length <= (int)*pInOutSz) { XMEMCPY(p, &input[idx], length); - *pInOutSz = length; + *pInOutSz = (word32)length; } else { return BUFFER_E; } - idx += length; + idx += (word32)length; ret = GetASNInt(input, &idx, &length, inSz); if (ret != 0) @@ -10154,7 +10154,7 @@ int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz, if (length <= (int)*gInOutSz) { XMEMCPY(g, &input[idx], length); - *gInOutSz = length; + *gInOutSz = (word32)length; } else { return BUFFER_E; @@ -11231,13 +11231,13 @@ static int GetCertHeader(DecodedCert* cert) return ASN_PARSE_E; /* Reset the max index for the size indicated in the outer wrapper. */ - cert->maxIdx = len + cert->srcIdx; + cert->maxIdx = (word32)len + cert->srcIdx; cert->certBegin = cert->srcIdx; if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0) return ASN_PARSE_E; - cert->sigIndex = len + cert->srcIdx; + cert->sigIndex = (word32)len + cert->srcIdx; if (cert->sigIndex > cert->maxIdx) return ASN_PARSE_E; @@ -11338,19 +11338,19 @@ static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx, return ASN_PARSE_E; pubIdx = *srcIdx; - if (GetSequence(source, srcIdx, &length, pubIdx + pubLen) < 0) + if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0) return ASN_PARSE_E; #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT) cert->sigCtx.CertAtt.pubkey_n_start = cert->sigCtx.CertAtt.pubkey_e_start = pubIdx; #endif - cert->pubKeySize = pubLen; + cert->pubKeySize = (word32)pubLen; cert->publicKey = source + pubIdx; #ifdef WOLFSSL_MAXQ10XX_TLS cert->publicKeyIndex = pubIdx; #endif - *srcIdx += length; + *srcIdx += (word32)length; #ifdef HAVE_OCSP return CalcHashId(cert->publicKey, cert->pubKeySize, cert->subjectKeyHash); @@ -11484,7 +11484,7 @@ static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx, if (ret != 0) return ret; #endif - *srcIdx += length; + *srcIdx += (word32)length; } publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY); @@ -11664,7 +11664,7 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, int pubLen; #endif #if defined(HAVE_ECC) || !defined(NO_DSA) - int pubIdx = srcIdx; + int pubIdx = (int)srcIdx; #endif int ret = 0; int length; @@ -11680,9 +11680,9 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, } #if defined(HAVE_ECC) || !defined(NO_DSA) - pubLen = srcIdx - pubIdx + length; + pubLen = (int)srcIdx - pubIdx + length; #endif - maxIdx = srcIdx + length; + maxIdx = srcIdx + (word32)length; /* Decode the algorithm identifier for the key. */ if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) { @@ -11748,7 +11748,7 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, #ifdef HAVE_ECC case ECDSAk: ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx, - pubLen); + (word32)pubLen); break; #endif /* HAVE_ECC */ #ifdef HAVE_ED25519 @@ -11881,7 +11881,7 @@ static int GetHashId(const byte* id, int length, byte* hash) ret = 0; } else { - ret = CalcHashId(id, length, hash); + ret = CalcHashId(id, (word32)length, hash); } return ret; @@ -12714,7 +12714,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectCN = (char *)&input[srcIdx]; cert->subjectCNLen = strLen; - cert->subjectCNEnc = b; + cert->subjectCNEnc = (char)b; } #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \ defined(WOLFSSL_HAVE_ISSUER_NAMES) @@ -13099,13 +13099,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */ /* last value of OID is the type of pilot attribute */ - id = input[srcIdx + oidSz - 1]; + id = input[srcIdx + (word32)oidSz - 1]; if (id == 0x01) id = ASN_USER_ID; pilot = TRUE; } - srcIdx += oidSz + 1; + srcIdx += (word32)oidSz + 1; if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) { #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ @@ -13200,9 +13200,9 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, } if ((copy != NULL) && !tooBig) { XMEMCPY(&full[idx], copy, copyLen); - idx += copyLen; + idx += (word32)copyLen; XMEMCPY(&full[idx], &input[srcIdx], strLen); - idx += strLen; + idx += (word32)strLen; } #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ !defined(WOLFCRYPT_ONLY) @@ -13227,7 +13227,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, } } #endif /* OPENSSL_EXTRA */ - srcIdx += strLen; + srcIdx += (word32)strLen; } full[idx++] = 0; @@ -13446,30 +13446,30 @@ int GetName(DecodedCert* cert, int nameType, int maxIdx) } localIdx = cert->srcIdx; - if (GetASNTag(cert->source, &localIdx, &tag, maxIdx) < 0) { + if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) { return ASN_PARSE_E; } if (tag == ASN_OBJECT_ID) { WOLFSSL_MSG("Trying optional prefix..."); - if (SkipObjectId(cert->source, &cert->srcIdx, maxIdx) < 0) + if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0) return ASN_PARSE_E; WOLFSSL_MSG("Got optional prefix"); } localIdx = cert->srcIdx; - if (GetASNTag(cert->source, &localIdx, &tag, maxIdx) < 0) { + if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) { return ASN_PARSE_E; } localIdx = cert->srcIdx + 1; - if (GetLength(cert->source, &localIdx, &length, maxIdx) < 0) { + if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) { return ASN_PARSE_E; } length += localIdx - cert->srcIdx; return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx, - cert->srcIdx + length); + cert->srcIdx + (word32)length); #else ASNGetData dataASN[certNameASN_Length]; word32 idx = cert->srcIdx; @@ -14039,7 +14039,7 @@ static int GetDateInfo(const byte* source, word32* idx, const byte** pDate, if (pLength) *pLength = length; - *idx += length; + *idx += (word32)length; return 0; #else @@ -14092,7 +14092,7 @@ static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx) startIdx = cert->srcIdx; ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format, - &length, maxIdx); + &length, (word32)maxIdx); if (ret < 0) return ret; @@ -14100,9 +14100,9 @@ static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx) XMEMCPY(date, datePtr, length); if (dateType == BEFORE) - cert->beforeDateLen = cert->srcIdx - startIdx; + cert->beforeDateLen = (int)(cert->srcIdx - startIdx); else - cert->afterDateLen = cert->srcIdx - startIdx; + cert->afterDateLen = (int)(cert->srcIdx - startIdx); #ifndef NO_ASN_TIME if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE && @@ -14128,10 +14128,10 @@ static int GetValidity(DecodedCert* cert, int verify, int maxIdx) int length; int badDate = 0; - if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0) + if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0) return ASN_PARSE_E; - maxIdx = cert->srcIdx + length; + maxIdx = (int)cert->srcIdx + length; if (GetDate(cert, BEFORE, verify, maxIdx) < 0) badDate = ASN_BEFORE_DATE_E; /* continue parsing */ @@ -14153,7 +14153,7 @@ int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date, int ret; word32 idx = 0; - ret = GetDateInfo(certDate, &idx, date, format, length, certDateSz); + ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz); return ret; } @@ -14206,7 +14206,7 @@ static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx) if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0) return ASN_PARSE_E; - endSeqIdx = cert->srcIdx + length; + endSeqIdx = cert->srcIdx + (word32)length; if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType, maxIdx) < 0) { @@ -14287,16 +14287,16 @@ int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate) WOLFSSL_MSG("Got Algo ID"); - if ( (ret = GetName(cert, ISSUER, cert->sigIndex)) < 0) + if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0) return ret; - if ( (ret = GetValidity(cert, verify, cert->sigIndex)) < 0) + if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0) *badDate = ret; #ifdef WOLFSSL_CERT_REQ } #endif - if ( (ret = GetName(cert, SUBJECT, cert->sigIndex)) < 0) + if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0) return ret; WOLFSSL_MSG("Got Subject Name"); @@ -14388,7 +14388,7 @@ static int GetSignature(DecodedCert* cert) if (ret != 0) return ret; - cert->sigLength = length; + cert->sigLength = (word32)length; cert->signature = &cert->source[cert->srcIdx]; cert->srcIdx += cert->sigLength; @@ -14569,11 +14569,11 @@ static int SetCurve(ecc_key* key, byte* output, size_t outSz) oidSz = key->dp->oidSz; #endif - idx = SetObjectId(oidSz, output); + idx = SetObjectId((int)oidSz, output); /* length only */ if (output == NULL) { - return idx + oidSz; + return idx + (int)oidSz; } /* verify output buffer has room */ @@ -14682,20 +14682,20 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) const byte* algoName = 0; byte ID_Length[1 + MAX_LENGTH_SZ]; byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */ - int length = 0; + word32 length = 0; tagSz = (type == oidHashType || (type == oidSigType && !IsSigAlgoECC(algoOID)) || (type == oidKeyType && algoOID == RSAk)) ? 2 : 0; - algoName = OidFromId(algoOID, type, &algoSz); + algoName = OidFromId((word32)algoOID, (word32)type, &algoSz); if (algoName == NULL) { WOLFSSL_MSG("Unknown Algorithm"); return 0; } - idSz = SetObjectId(algoSz, ID_Length); - seqSz = SetSequence(idSz + algoSz + tagSz + curveSz, seqArray); + idSz = (word32)SetObjectId((int)algoSz, ID_Length); + seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray); /* Copy only algo to output for DSA keys */ if (algoOID == DSAk && output) { @@ -15905,8 +15905,8 @@ static int ConfirmSignature(SignatureCtx* sigCtx, #endif /* HAVE_PK_CALLBACKS */ { ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest, - sigCtx->digestSz, &sigCtx->verify, - sigCtx->key.ecc); + (word32)sigCtx->digestSz, &sigCtx->verify, + sigCtx->key.ecc); } break; } @@ -16038,10 +16038,12 @@ static int ConfirmSignature(SignatureCtx* sigCtx, verifySz = ret; /* make sure we're right justified */ - encodedSigSz = wc_EncodeSignature(encodedSig, - sigCtx->digest, sigCtx->digestSz, sigCtx->typeH); + encodedSigSz = (int)wc_EncodeSignature(encodedSig, + sigCtx->digest, (word32)sigCtx->digestSz, + sigCtx->typeH); if (encodedSigSz == verifySz && sigCtx->out != NULL && - XMEMCMP(sigCtx->out, encodedSig, encodedSigSz) == 0) { + XMEMCMP(sigCtx->out, encodedSig, + (size_t)encodedSigSz) == 0) { ret = 0; } else { @@ -16287,7 +16289,7 @@ static int MatchBaseName(int type, const char* name, int nameSz, } if (type == ASN_DIR_TYPE) - return XMEMCMP(name, base, baseSz) == 0; + return XMEMCMP(name, base, (word32)baseSz) == 0; /* If an email type, handle special cases where the base is only * a domain, or is an email address itself. */ @@ -16957,7 +16959,7 @@ static int DecodeSepHwAltName(DecodedCert* cert, const byte* input, #if !defined(WOLFSSL_ASN_TEMPLATE) /* return 0 on success */ static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input, - word32* idx, int sz, int oid) + word32* idx, word32 sz, int oid) { int ret = 0; int strLen = 0; @@ -17022,7 +17024,7 @@ static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input, if (ret == 0 && dnsEntry != NULL) { dnsEntry->type = ASN_OTHER_TYPE; dnsEntry->len = strLen; - dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap, + dnsEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); #ifdef WOLFSSL_FPKI dnsEntry->oidSum = oid; @@ -17032,14 +17034,14 @@ static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input, ret = MEMORY_E; } else { - XMEMCPY(dnsEntry->name, &input[*idx], strLen); + XMEMCPY(dnsEntry->name, &input[*idx], (word32)strLen); dnsEntry->name[strLen] = '\0'; AddAltName(cert, dnsEntry); } } if (ret == 0) { - *idx += strLen; + *idx += (word32)strLen; } else { XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME); @@ -17063,7 +17065,7 @@ static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input, * @return ASN_UNKNOWN_OID_E when the OID cannot be verified. * @return MEMORY_E when dynamic memory allocation fails. */ -static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) +static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; @@ -17123,7 +17125,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) } dnsEntry->type = ASN_DNS_TYPE; - dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap, + dnsEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (dnsEntry->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17137,7 +17139,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) AddAltName(cert, dnsEntry); length -= strLen; - idx += strLen; + idx += (word32)strLen; } #ifndef IGNORE_NAME_CONSTRAINTS else if (current_byte == @@ -17164,7 +17166,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) } dirEntry->type = ASN_DIR_TYPE; - dirEntry->name = (char*)XMALLOC(strLen + 1, cert->heap, + dirEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (dirEntry->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17178,7 +17180,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) cert->altDirNames = dirEntry; length -= strLen; - idx += strLen; + idx += (word32)strLen; } else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) { DNS_entry* emailEntry; @@ -17198,7 +17200,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) } emailEntry->type = ASN_RFC822_TYPE; - emailEntry->name = (char*)XMALLOC(strLen + 1, cert->heap, + emailEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (emailEntry->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17213,7 +17215,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) cert->altEmailNames = emailEntry; length -= strLen; - idx += strLen; + idx += (word32)strLen; } else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) { DNS_entry* uriEntry; @@ -17228,7 +17230,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) length -= (idx - lenStartIdx); /* check that strLen at index is not past input buffer */ - if (strLen + (int)idx > sz) { + if ((word32)strLen + idx > sz) { return BUFFER_E; } @@ -17241,10 +17243,10 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) hier-part, it must come after the ':' (see RFC 3986 Sec 3). */ { - int i; + word32 i; /* skip past scheme (i.e http,ftp,...) finding first ':' char */ - for (i = 0; i < strLen; i++) { + for (i = 0; i < (word32)strLen; i++) { if (input[idx + i] == ':') { break; } @@ -17256,7 +17258,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) } /* test hier-part is empty */ - if (i == 0 || i == strLen) { + if (i == 0 || i == (word32)strLen) { WOLFSSL_MSG("\tEmpty or malformed URI"); WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E); return ASN_ALT_NAME_E; @@ -17278,7 +17280,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) } uriEntry->type = ASN_URI_TYPE; - uriEntry->name = (char*)XMALLOC(strLen + 1, cert->heap, + uriEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (uriEntry->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17292,7 +17294,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) AddAltName(cert, uriEntry); length -= strLen; - idx += strLen; + idx += (word32)strLen; } #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) { @@ -17318,7 +17320,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) } ipAddr->type = ASN_IP_TYPE; - ipAddr->name = (char*)XMALLOC(strLen + 1, cert->heap, + ipAddr->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (ipAddr->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17340,7 +17342,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) AddAltName(cert, ipAddr); length -= strLen; - idx += strLen; + idx += (word32)strLen; } #endif /* WOLFSSL_QT || OPENSSL_ALL */ #endif /* IGNORE_NAME_CONSTRAINTS */ @@ -17356,7 +17358,7 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) return ASN_PARSE_E; } /* Consume the rest of this sequence. */ - length -= (strLen + idx - lenStartIdx); + length -= (int)(((word32)strLen + idx - lenStartIdx)); if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) { WOLFSSL_MSG("\tbad OID"); @@ -17387,13 +17389,13 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) if (GetLength(input, &idx, &strLen, sz) < 0) { /* check to skip constructed other names too */ if (DecodeConstructedOtherName(cert, input, &idx, sz, - oid) != 0) { + (int)oid) != 0) { WOLFSSL_MSG("\tfail: unsupported other name length"); return ASN_PARSE_E; } } else { - idx += strLen; + idx += (word32)strLen; } } (void)ret; @@ -17408,8 +17410,8 @@ static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert) WOLFSSL_MSG("\tfail: unsupported name length"); return ASN_PARSE_E; } - length -= (strLen + idx - lenStartIdx); - idx += strLen; + length -= (int)((word32)strLen + idx - lenStartIdx); + idx += (word32)strLen; } } @@ -17514,7 +17516,7 @@ static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert) WOLFSSL_ENTER("DecodeBasicCaConstraint"); - if (GetSequence(input, &idx, &length, sz) < 0) { + if (GetSequence(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: bad SEQUENCE"); return ASN_PARSE_E; } @@ -17525,7 +17527,7 @@ static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert) /* If the basic ca constraint is false, this extension may be named, but * left empty. So, if the length is 0, just return. */ - ret = GetBoolean(input, &idx, sz); + ret = GetBoolean(input, &idx, (word32)sz); /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the * pathlen value as if it were the CA Boolean value 7/2/2021 - KH. @@ -17542,7 +17544,7 @@ static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert) return 0; } - ret = GetInteger7Bit(input, &idx, sz); + ret = GetInteger7Bit(input, &idx, (word32)sz); if (ret < 0) return ret; cert->pathLength = (byte)ret; @@ -17605,7 +17607,7 @@ static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert) WOLFSSL_ENTER("DecodePolicyConstraints"); - if (GetSequence(input, &idx, &length, sz) < 0) { + if (GetSequence(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: bad SEQUENCE"); return ASN_PARSE_E; } @@ -17613,7 +17615,7 @@ static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert) if (length == 0) return ASN_PARSE_E; - if (GetASNTag(input, &idx, &tag, sz) < 0) { + if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: bad TAG"); return ASN_PARSE_E; } @@ -17631,7 +17633,7 @@ static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert) return ASN_PARSE_E; } - ret = GetLength(input, &idx, &skipLength, sz); + ret = GetLength(input, &idx, &skipLength, (word32)sz); if (ret < 0) { WOLFSSL_MSG("\tfail: invalid length"); return ret; @@ -17710,7 +17712,7 @@ enum { * is invalid. * @return BUFFER_E when data in buffer is too small. */ -static int DecodeCrlDist(const byte* input, int sz, DecodedCert* cert) +static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0, localIdx; @@ -17720,7 +17722,7 @@ static int DecodeCrlDist(const byte* input, int sz, DecodedCert* cert) WOLFSSL_ENTER("DecodeCrlDist"); cert->extCrlInfoRaw = input; - cert->extCrlInfoRawSz = sz; + cert->extCrlInfoRawSz = (int)sz; /* Unwrap the list of Distribution Points*/ if (GetSequence(input, &idx, &length, sz) < 0) @@ -17759,15 +17761,15 @@ static int DecodeCrlDist(const byte* input, int sz, DecodedCert* cert) cert->extCrlInfoSz = length; cert->extCrlInfo = input + idx; - idx += length; + idx += (word32)length; } else /* This isn't a URI, skip it. */ - idx += length; + idx += (word32)length; } else { /* This isn't a FULLNAME, skip it. */ - idx += length; + idx += (word32)length; } } @@ -17780,7 +17782,7 @@ static int DecodeCrlDist(const byte* input, int sz, DecodedCert* cert) idx++; if (GetLength(input, &idx, &length, sz) < 0) return ASN_PARSE_E; - idx += length; + idx += (word32)length; } /* Check for cRLIssuer */ @@ -17792,7 +17794,7 @@ static int DecodeCrlDist(const byte* input, int sz, DecodedCert* cert) idx++; if (GetLength(input, &idx, &length, sz) < 0) return ASN_PARSE_E; - idx += length; + idx += (word32)length; } if (idx < (word32)sz) @@ -17896,7 +17898,7 @@ enum { * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified. */ -static int DecodeAuthInfo(const byte* input, int sz, DecodedCert* cert) +static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; @@ -17948,7 +17950,7 @@ static int DecodeAuthInfo(const byte* input, int sz, DecodedCert* cert) count++; } #endif - idx += length; + idx += (word32)length; } return 0; @@ -18049,7 +18051,7 @@ enum { * is invalid. * @return BUFFER_E when data in buffer is too small. */ -static int DecodeAuthKeyId(const byte* input, int sz, DecodedCert* cert) +static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; @@ -18142,7 +18144,7 @@ static int DecodeAuthKeyId(const byte* input, int sz, DecodedCert* cert) * invalid. * @return MEMORY_E on dynamic memory allocation failure. */ -static int DecodeSubjKeyId(const byte* input, int sz, DecodedCert* cert) +static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert) { word32 idx = 0; int length = 0; @@ -18197,7 +18199,7 @@ enum { * is invalid. * @return MEMORY_E on dynamic memory allocation failure. */ -static int DecodeKeyUsage(const byte* input, int sz, DecodedCert* cert) +static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; @@ -18259,7 +18261,7 @@ enum { * is invalid. * @return MEMORY_E on dynamic memory allocation failure. */ -static int DecodeExtKeyUsage(const byte* input, int sz, DecodedCert* cert) +static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0, oid; @@ -18527,7 +18529,7 @@ static int DecodeSubtreeGeneralName(const byte* input, int sz, byte tag, * @return MEMORY_E when dynamic memory allocation fails. * @return ASN_PARSE_E when SEQUENCE is not found as expected. */ -static int DecodeSubtree(const byte* input, int sz, Base_entry** head, +static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, void* heap) { #ifndef WOLFSSL_ASN_TEMPLATE @@ -18581,7 +18583,7 @@ static int DecodeSubtree(const byte* input, int sz, Base_entry** head, return MEMORY_E; } - entry->name = (char*)XMALLOC(strLength+1, heap, DYNAMIC_TYPE_ALTNAME); + entry->name = (char*)XMALLOC((word32)strLength+1, heap, DYNAMIC_TYPE_ALTNAME); if (entry->name == NULL) { WOLFSSL_MSG("allocate error"); XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME); @@ -18597,7 +18599,7 @@ static int DecodeSubtree(const byte* input, int sz, Base_entry** head, *head = entry; } - idx += seqLength; + idx += (word32)seqLength; } return ret; @@ -18679,7 +18681,8 @@ enum { * is invalid. * @return MEMORY_E on dynamic memory allocation failure. */ -static int DecodeNameConstraints(const byte* input, int sz, DecodedCert* cert) +static int DecodeNameConstraints(const byte* input, word32 sz, + DecodedCert* cert) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; @@ -18710,12 +18713,13 @@ static int DecodeNameConstraints(const byte* input, int sz, DecodedCert* cert) return ASN_PARSE_E; } - if (DecodeSubtree(input + idx, length, subtree, cert->heap) < 0) { + if (DecodeSubtree(input + idx, (word32)length, subtree, + cert->heap) < 0) { WOLFSSL_MSG("\terror parsing subtree"); return ASN_PARSE_E; } - idx += length; + idx += (word32)length; } return 0; @@ -19327,7 +19331,7 @@ static int DecodeSubjInfoAcc(const byte* input, int sz, DecodedCert* cert) * @return MEMORY_E on dynamic memory allocation failure. * @return Other negative values on error. */ -static int DecodeExtensionType(const byte* input, int length, word32 oid, +static int DecodeExtensionType(const byte* input, word32 length, word32 oid, byte critical, DecodedCert* cert, int *isUnknownExt) { @@ -19342,7 +19346,7 @@ static int DecodeExtensionType(const byte* input, int length, word32 oid, case BASIC_CA_OID: VERIFY_AND_SET_OID(cert->extBasicConstSet); cert->extBasicConstCrit = critical; - if (DecodeBasicCaConstraint(input, length, cert) < 0) { + if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) { ret = ASN_PARSE_E; } break; @@ -19480,7 +19484,7 @@ static int DecodeExtensionType(const byte* input, int length, word32 oid, #ifndef IGNORE_NETSCAPE_CERT_TYPE /* Netscape's certificate type. */ case NETSCAPE_CT_OID: - if (DecodeNsCertType(input, length, cert) < 0) + if (DecodeNsCertType(input, (int)length, cert) < 0) ret = ASN_PARSE_E; break; #endif @@ -19497,7 +19501,7 @@ static int DecodeExtensionType(const byte* input, int length, word32 oid, case POLICY_CONST_OID: VERIFY_AND_SET_OID(cert->extPolicyConstSet); cert->extPolicyConstCrit = critical; - if (DecodePolicyConstraints(&input[idx], length, cert) < 0) + if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0) return ASN_PARSE_E; break; #ifdef WOLFSSL_SUBJ_DIR_ATTR @@ -19594,7 +19598,7 @@ static int DecodeCertExtensions(DecodedCert* cert) #ifndef WOLFSSL_ASN_TEMPLATE int ret = 0; word32 idx = 0; - int sz = cert->extensionsSz; + word32 sz = (word32)cert->extensionsSz; const byte* input = cert->extensions; int length; word32 oid; @@ -19672,15 +19676,15 @@ static int DecodeCertExtensions(DecodedCert* cert) return ret; } - ret = DecodeExtensionType(input + idx, length, oid, critical, cert, - NULL); + ret = DecodeExtensionType(input + idx, (word32)length, oid, critical, + cert, NULL); if (ret == ASN_CRIT_EXT_E) { ret = 0; criticalFail = 1; } if (ret < 0) goto end; - idx += length; + idx += (word32)length; } ret = criticalFail ? ASN_CRIT_EXT_E : 0; @@ -20591,7 +20595,7 @@ int ParseCert(DecodedCert* cert, int type, int verify, void* cm) defined(WOLFSSL_DYN_CERT) /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */ if (cert->subjectCNLen > 0) { - ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap, + ptr = (char*)XMALLOC((word32)cert->subjectCNLen + 1, cert->heap, DYNAMIC_TYPE_SUBJECT_CN); if (ptr == NULL) return MEMORY_E; @@ -20610,7 +20614,7 @@ int ParseCert(DecodedCert* cert, int type, int verify, void* cm) || cert->keyOID == RSAPSSk #endif ) && cert->publicKey != NULL && cert->pubKeySize > 0) { - ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap, + ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY); if (ptr == NULL) return MEMORY_E; @@ -21575,7 +21579,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) /* save extensions */ cert->extensions = &cert->source[cert->srcIdx]; - cert->extensionsSz = cert->sigIndex - cert->srcIdx; + cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx); cert->extensionsIdx = cert->srcIdx; /* for potential later use */ if ((ret = DecodeCertExtensions(cert)) < 0) { @@ -22169,7 +22173,7 @@ int wc_GetSerialNumber(const byte* input, word32* inOutIdx, /* return serial */ XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz); - *inOutIdx += *serialSz; + *inOutIdx += (word32)*serialSz; return result; } @@ -22916,7 +22920,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, /* map header if not found for type */ for (;;) { - headerEnd = XSTRNSTR((char*)buff, header, sz); + headerEnd = XSTRNSTR((char*)buff, header, (word32)sz); if (headerEnd) { break; } @@ -23161,7 +23165,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId); if (ret > 0) { if (keyFormat) - *keyFormat = algId; + *keyFormat = (int)algId; } else { /* ignore failure here and assume key is not pkcs8 wrapped */ @@ -23313,7 +23317,7 @@ int wc_PemToDer(const unsigned char* buff, long longSz, int type, /* if a PKCS8 key header exists remove it */ ret = ToTraditional(der->buffer, der->length); if (ret > 0) { - der->length = ret; + der->length = (word32)ret; } ret = 0; /* ignore error removing PKCS8 header */ } @@ -23380,11 +23384,11 @@ int wc_KeyPemToDer(const unsigned char* pem, int pemSz, } else if (buff == NULL) { WOLFSSL_MSG("Return needed der buff length"); - ret = der->length; + ret = (int)der->length; } else if (der->length <= (word32)buffSz) { XMEMCPY(buff, der->buffer, der->length); - ret = der->length; + ret = (int)der->length; } else { WOLFSSL_MSG("Bad der length"); @@ -23423,7 +23427,7 @@ int wc_CertPemToDer(const unsigned char* pem, int pemSz, else { if (der->length <= (word32)buffSz) { XMEMCPY(buff, der->buffer, der->length); - ret = der->length; + ret = (int)der->length; } else { WOLFSSL_MSG("Bad der length"); @@ -24476,13 +24480,13 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, int with_header, int comp) { #ifndef WOLFSSL_ASN_TEMPLATE - int ret, idx = 0, algoSz, curveSz, bitStringSz; - word32 pubSz; + int ret; + word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz; byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */ byte algo[MAX_ALGO_SZ]; /* 20 */ /* public size */ - pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES; + pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES; if (comp) pubSz = 1 + pubSz; else @@ -24495,13 +24499,15 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, /* headers */ if (with_header) { - curveSz = SetCurve(key, NULL, 0); - if (curveSz <= 0) { - return curveSz; + ret = SetCurve(key, NULL, 0); + if (ret <= 0) { + return ret; } + curveSz = (word32)ret; + ret = 0; /* calculate size */ - algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, curveSz); + algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz); bitStringSz = SetBitString(pubSz, 0, bitString); idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL); @@ -24511,7 +24517,8 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, return BUFFER_E; } - idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, output); + idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, + output); /* algo */ if (output) XMEMCPY(output + idx, algo, algoSz); @@ -24537,7 +24544,7 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, } idx += pubSz; - return idx; + return (int)idx; #else word32 pubSz = 0; int sz = 0; @@ -24664,13 +24671,13 @@ WOLFSSL_ABI int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen, int with_AlgCurve) { - return SetEccPublicKey(output, key, inLen, with_AlgCurve, 0); + return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0); } int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen, int with_AlgCurve, int comp) { - return SetEccPublicKey(output, key, inLen, with_AlgCurve, comp); + return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp); } int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve) @@ -30851,7 +30858,7 @@ int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s) word32 idx = 0; int rSz; /* encoding size */ int sSz; - word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */ + int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */ /* If the leading bit on the INTEGER is a 1, add a leading zero */ int rLeadingZero = mp_leading_bit(r); @@ -30859,23 +30866,24 @@ int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s) int rLen = mp_unsigned_bin_size(r); /* big int size */ int sLen = mp_unsigned_bin_size(s); - if (*outLen < (rLen + rLeadingZero + sLen + sLeadingZero + - headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */ + if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero + + headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */ return BUFFER_E; - idx = SetSequence(rLen + rLeadingZero + sLen+sLeadingZero + headerSz, out); + idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero + + headerSz), out); /* store r */ - rSz = SetASNIntMP(r, *outLen - idx, &out[idx]); + rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]); if (rSz < 0) return rSz; - idx += rSz; + idx += (word32)rSz; /* store s */ - sSz = SetASNIntMP(s, *outLen - idx, &out[idx]); + sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]); if (sSz < 0) return sSz; - idx += sSz; + idx += (word32)sSz; *outLen = idx; @@ -30909,16 +30917,17 @@ int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s) #ifndef WOLFSSL_ASN_TEMPLATE /* determine if leading bit is set */ -static int is_leading_bit_set(const byte* input, word32 sz) +static word32 is_leading_bit_set(const byte* input, word32 sz) { byte c = 0; if (sz > 0) c = input[0]; return (c & 0x80) != 0; } -static int trim_leading_zeros(const byte** input, word32 sz) +static word32 trim_leading_zeros(const byte** input, word32 sz) { - int i, leadingZeroCount = 0; + int i; + word32 leadingZeroCount = 0; const byte* tmp = *input; for (i=0; i<(int)sz; i++) { if (tmp[i] != 0) @@ -30926,7 +30935,7 @@ static int trim_leading_zeros(const byte** input, word32 sz) leadingZeroCount++; } /* catch all zero case */ - if (sz > 0 && leadingZeroCount == (int)sz) { + if (sz > 0 && leadingZeroCount == sz) { leadingZeroCount--; } *input += leadingZeroCount; @@ -30944,7 +30953,7 @@ int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen, int ret; word32 idx; word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */ - int rAddLeadZero, sAddLeadZero; + word32 rAddLeadZero, sAddLeadZero; if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL)) return BAD_FUNC_ARG; @@ -30964,18 +30973,18 @@ int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen, idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out); /* store r */ - ret = SetASNInt(rLen, rAddLeadZero ? 0x80 : 0x00, &out[idx]); + ret = SetASNInt((int)rLen, rAddLeadZero ? 0x80 : 0x00, &out[idx]); if (ret < 0) return ret; - idx += ret; + idx += (word32)ret; XMEMCPY(&out[idx], r, rLen); idx += rLen; /* store s */ - ret = SetASNInt(sLen, sAddLeadZero ? 0x80 : 0x00, &out[idx]); + ret = SetASNInt((int)sLen, sAddLeadZero ? 0x80 : 0x00, &out[idx]); if (ret < 0) return ret; - idx += ret; + idx += (word32)ret; XMEMCPY(&out[idx], s, sLen); idx += sLen; @@ -31039,23 +31048,23 @@ int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen, if (ret != 0) return ret; if (rLen) - *rLen = len; + *rLen = (word32)len; if (r) XMEMCPY(r, (byte*)sig + idx, len); - idx += len; + idx += (word32)len; ret = GetASNInt(sig, &idx, &len, sigLen); if (ret != 0) return ret; if (sLen) - *sLen = len; + *sLen = (word32)len; if (s) XMEMCPY(s, (byte*)sig + idx, len); #ifndef NO_STRICT_ECDSA_LEN /* sanity check that the index has been advanced all the way to the end of * the buffer */ - if (idx + len != sigLen) { + if (idx + (word32)len != sigLen) { ret = ASN_ECC_KEY_E; } #endif @@ -31525,7 +31534,7 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, /* priv key */ XMEMCPY(priv, &input[*inOutIdx], privSz); - *inOutIdx += length; + *inOutIdx += (word32)length; if ((*inOutIdx + 1) < inSz) { /* prefix 0, may have */ @@ -31578,7 +31587,7 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, #endif { XMEMCPY(pub, &input[*inOutIdx], pubSz); - *inOutIdx += length; + *inOutIdx += (word32)length; pubData = pub; } } @@ -31587,8 +31596,8 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, } if (ret == 0) { - ret = wc_ecc_import_private_key_ex(priv, privSz, pubData, pubSz, key, - curve_id); + ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData, + (word32)pubSz, key, curve_id); } #ifdef WOLFSSL_SMALL_STACK @@ -31776,7 +31785,7 @@ int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx, return ASN_PARSE_E; if (length > ECC_MAXSIZE) return BUFFER_E; - *inOutIdx += length; + *inOutIdx += (word32)length; /* Private Curve Header */ if (*inOutIdx >= inSz) @@ -32002,12 +32011,12 @@ int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx, return ret; /* This is the raw point data compressed or uncompressed. */ - if (wc_ecc_import_x963_ex(input + *inOutIdx, length, key, + if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key, curve_id) != 0) { return ASN_ECC_KEY_E; } - *inOutIdx += length; + *inOutIdx += (word32)length; return 0; #else @@ -32100,7 +32109,8 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, byte curve[MAX_ALGO_SZ+2]; byte ver[MAX_VERSION_SZ]; byte seq[MAX_SEQ_SZ]; - int ret, totalSz, curveSz, verSz; + int ret, curveSz, verSz; + word32 totalSz; int privHdrSz = ASN_ECC_HEADER_SZ; int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ; #ifdef WOLFSSL_NO_MALLOC @@ -32126,11 +32136,11 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, return curveSz; /* set computed size */ curve[1] = (byte)curveSz; - curveidx += curveSz; + curveidx += (word32)curveSz; } /* private */ - privSz = key->dp->size; + privSz = (word32)key->dp->size; #ifdef WOLFSSL_QNX_CAAM /* check if is a black key, and add MAC size if needed */ @@ -32140,7 +32150,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, #endif #ifndef WOLFSSL_NO_MALLOC - prv = (byte*)XMALLOC(privSz + privHdrSz + MAX_SEQ_SZ, + prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER); if (prv == NULL) { return MEMORY_E; @@ -32178,7 +32188,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, } #ifndef WOLFSSL_NO_MALLOC - pub = (byte*)XMALLOC(pubSz + pubHdrSz + MAX_SEQ_SZ, + pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER); if (pub == NULL) { XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -32213,9 +32223,9 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, /* make headers */ verSz = SetMyVersion(1, ver, FALSE); - seqSz = SetSequence(verSz + prvidx + pubidx + curveidx, seq); + seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq); - totalSz = prvidx + pubidx + curveidx + verSz + seqSz; + totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz; if (output == NULL) { *inLen = totalSz; #ifndef WOLFSSL_NO_MALLOC @@ -32226,7 +32236,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, #endif return LENGTH_ONLY_E; } - if (inLen != NULL && totalSz > (int)*inLen) { + if (inLen != NULL && totalSz > *inLen) { #ifndef WOLFSSL_NO_MALLOC XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER); if (pubIn) { @@ -32243,7 +32253,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, /* ver */ XMEMCPY(output + idx, ver, verSz); - idx += verSz; + idx += (word32)verSz; /* private */ XMEMCPY(output + idx, prv, prvidx); @@ -32265,7 +32275,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, #endif } - return totalSz; + return (int)totalSz; #else DECL_ASNSETDATA(dataASN, eccKeyASN_Length); word32 privSz, pubSz; @@ -32398,7 +32408,7 @@ int wc_EccKeyDerSize(ecc_key* key, int pub) if (ret != LENGTH_ONLY_E) { return ret; } - return sz; + return (int)sz; } /* Write only private ecc key to DER format, @@ -32422,7 +32432,8 @@ int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen) static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen, int includePublic) { - int ret, tmpDerSz; + int ret; + word32 tmpDerSz; int algoID = 0; word32 oidSz = 0; word32 pkcs8Sz = 0; @@ -32458,7 +32469,7 @@ static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen, #endif return ret; } - tmpDerSz = ret; + tmpDerSz = (word32)ret; /* get pkcs8 expected output size */ ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID, @@ -32499,7 +32510,7 @@ static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen, XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif - *outLen = ret; + *outLen = (word32)ret; return ret; } @@ -35125,13 +35136,14 @@ int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx) WOLFSSL_ENTER("GetNameHash"); dummy = *idx; - if (GetASNTag(source, &dummy, &tag, maxIdx) == 0 && tag == ASN_OBJECT_ID) { + if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 && + tag == ASN_OBJECT_ID) { WOLFSSL_MSG("Trying optional prefix..."); - if (GetLength(source, idx, &length, maxIdx) < 0) + if (GetLength(source, idx, &length, (word32)maxIdx) < 0) return ASN_PARSE_E; - *idx += length; + *idx += (word32)length; WOLFSSL_MSG("Got optional prefix"); } @@ -35139,12 +35151,12 @@ int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx) * calculated over the entire DER encoding of the Name field, including * the tag and length. */ dummy = *idx; - if (GetSequence(source, idx, &length, maxIdx) < 0) + if (GetSequence(source, idx, &length, (word32)maxIdx) < 0) return ASN_PARSE_E; - ret = CalcHashId(source + dummy, length + *idx - dummy, hash); + ret = CalcHashId(source + dummy, (word32)length + *idx - dummy, hash); - *idx += length; + *idx += (word32)length; return ret; #else diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 208c0c6880c..12571276f6b 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -3020,7 +3020,7 @@ static int ecc_mulmod(const mp_int* k, ecc_point* P, ecc_point* Q, err = mp_copy(k, kt); } if (err == MP_OKAY) { - err = mp_grow(kt, modulus->used + 1); + err = mp_grow(kt, (int)modulus->used + 1); } /* Step 2: for j = 1 to t-1 do */ for (i = 1; (err == MP_OKAY) && (i < t); i++) { @@ -3042,11 +3042,11 @@ static int ecc_mulmod(const mp_int* k, ecc_point* P, ecc_point* Q, /* Swap R[0] and R[1] if other index is needed. */ swap ^= b; if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->x, R[1]->x, modulus->used, swap); + err = mp_cond_swap_ct(R[0]->x, R[1]->x, (int)modulus->used, swap); if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->y, R[1]->y, modulus->used, swap); + err = mp_cond_swap_ct(R[0]->y, R[1]->y, (int)modulus->used, swap); if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->z, R[1]->z, modulus->used, swap); + err = mp_cond_swap_ct(R[0]->z, R[1]->z, (int)modulus->used, swap); swap = (int)b; if (err == MP_OKAY) @@ -3062,11 +3062,11 @@ static int ecc_mulmod(const mp_int* k, ecc_point* P, ecc_point* Q, /* Swap back if last bit is 0. */ swap ^= 1; if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->x, R[1]->x, modulus->used, swap); + err = mp_cond_swap_ct(R[0]->x, R[1]->x, (int)modulus->used, swap); if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->y, R[1]->y, modulus->used, swap); + err = mp_cond_swap_ct(R[0]->y, R[1]->y, (int)modulus->used, swap); if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->z, R[1]->z, modulus->used, swap); + err = mp_cond_swap_ct(R[0]->z, R[1]->z, (int)modulus->used, swap); #endif /* Step 5: b = k[0]; R[b] = R[b] - P */ @@ -3085,21 +3085,21 @@ static int ecc_mulmod(const mp_int* k, ecc_point* P, ecc_point* Q, &infinity); #else /* Swap R[0] and R[1], if necessary, to operate on the one we want. */ - err = mp_cond_swap_ct(R[0]->x, R[1]->x, modulus->used, (int)b); + err = mp_cond_swap_ct(R[0]->x, R[1]->x, (int)modulus->used, (int)b); if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->y, R[1]->y, modulus->used, (int)b); + err = mp_cond_swap_ct(R[0]->y, R[1]->y, (int)modulus->used, (int)b); if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->z, R[1]->z, modulus->used, (int)b); + err = mp_cond_swap_ct(R[0]->z, R[1]->z, (int)modulus->used, (int)b); if (err == MP_OKAY) err = ecc_projective_add_point_safe(R[0], R[2], R[0], a, modulus, mp, &infinity); /* Swap back if necessary. */ if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->x, R[1]->x, modulus->used, (int)b); + err = mp_cond_swap_ct(R[0]->x, R[1]->x, (int)modulus->used, (int)b); if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->y, R[1]->y, modulus->used, (int)b); + err = mp_cond_swap_ct(R[0]->y, R[1]->y, (int)modulus->used, (int)b); if (err == MP_OKAY) - err = mp_cond_swap_ct(R[0]->z, R[1]->z, modulus->used, (int)b); + err = mp_cond_swap_ct(R[0]->z, R[1]->z, (int)modulus->used, (int)b); #endif } @@ -4584,7 +4584,7 @@ static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, #ifdef WOLFSSL_NO_MALLOC ecc_point lcl_result; #endif - word32 x = 0; + int x = 0; mp_digit mp = 0; DECLARE_CURVE_SPECS(3); @@ -4644,17 +4644,17 @@ static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, } if (err == MP_OKAY) { x = mp_unsigned_bin_size(curve->prime); - if (*outlen < x || (int)x < mp_unsigned_bin_size(result->x)) { + if (*outlen < (word32)x || x < mp_unsigned_bin_size(result->x)) { err = BUFFER_E; } } if (err == MP_OKAY) { XMEMSET(out, 0, x); - err = mp_to_unsigned_bin(result->x,out + + err = mp_to_unsigned_bin(result->x, out + (x - mp_unsigned_bin_size(result->x))); } - *outlen = x; + *outlen = (word32)x; mp_forcezero(result->x); mp_forcezero(result->y); @@ -4974,7 +4974,7 @@ int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) int err; byte buf[ECC_MAXSIZE_GEN]; - if (rng == NULL || size + 8 > ECC_MAXSIZE_GEN || k == NULL || + if (rng == NULL || size <= 0 || size + 8 > ECC_MAXSIZE_GEN || k == NULL || order == NULL) { return BAD_FUNC_ARG; } @@ -4984,14 +4984,14 @@ int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) size += 8; /* make up random string */ - err = wc_RNG_GenerateBlock(rng, buf, size); + err = wc_RNG_GenerateBlock(rng, buf, (word32)size); #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Add("wc_ecc_gen_k buf", buf, size); #endif /* load random buffer data into k */ if (err == 0) - err = mp_read_unsigned_bin(k, buf, size); + err = mp_read_unsigned_bin(k, buf, (word32)size); /* the key should be smaller than the order of base point */ if (err == MP_OKAY) { @@ -5285,7 +5285,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, return err; } - key->flags = flags; + key->flags = (byte)flags; #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { @@ -5921,7 +5921,7 @@ int wc_ecc_set_flags(ecc_key* key, word32 flags) static int wc_ecc_get_curve_order_bit_count(const ecc_set_type* dp) { int err = MP_OKAY; - word32 orderBits; + int orderBits; DECLARE_CURVE_SPECS(1); ALLOC_CURVE_SPECS(1, err); @@ -5937,7 +5937,7 @@ static int wc_ecc_get_curve_order_bit_count(const ecc_set_type* dp) wc_ecc_curve_free(curve); FREE_CURVE_SPECS(); - return (int)orderBits; + return orderBits; } #ifdef HAVE_ECC_SIGN @@ -6878,7 +6878,7 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, /* load digest into e */ if (err == MP_OKAY) { /* we may need to truncate if hash is longer than key size */ - word32 orderBits = mp_count_bits(curve->order); + word32 orderBits = (word32)mp_count_bits(curve->order); /* truncate down to byte size, may be all that's needed */ if ((WOLFSSL_BIT_SIZE * inlen) > orderBits) @@ -7656,7 +7656,7 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, ecc_point lcl_precomp[SHAMIR_PRECOMP_SZ]; #endif #endif - unsigned bitbufA, bitbufB, lenA, lenB, len, nA, nB, nibble; + unsigned int bitbufA, bitbufB, lenA, lenB, len, nA, nB, nibble; #ifdef WOLFSSL_NO_MALLOC unsigned char tA[ECC_BUFSIZE]; unsigned char tB[ECC_BUFSIZE]; @@ -7750,8 +7750,8 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, #endif /* get sizes */ - lenA = mp_unsigned_bin_size(kA); - lenB = mp_unsigned_bin_size(kB); + lenA = (unsigned int)mp_unsigned_bin_size(kA); + lenB = (unsigned int)mp_unsigned_bin_size(kB); len = MAX(lenA, lenB); /* sanity check */ @@ -7863,7 +7863,7 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, /* if not both zero */ if ((nA != 0) || (nB != 0)) { - int i = nA + (nB<<2); + unsigned int i = nA + (nB<<2); if (first == 1) { /* if first, copy from table */ first = 0; @@ -8581,7 +8581,7 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, return err; } - keySz = key->dp->size; + keySz = (word32)key->dp->size; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_SW) @@ -8837,7 +8837,7 @@ int wc_ecc_import_point_der_ex(const byte* in, word32 inLen, /* read data */ if (err == MP_OKAY) - err = mp_read_unsigned_bin(point->x, in, keysize); + err = mp_read_unsigned_bin(point->x, in, (word32)keysize); #ifdef HAVE_COMP_KEY if (err == MP_OKAY && compressed == 1) { /* build y */ @@ -8980,7 +8980,7 @@ int wc_ecc_import_point_der_ex(const byte* in, word32 inLen, #ifdef HAVE_COMP_KEY if (compressed == 0) #endif - err = mp_read_unsigned_bin(point->y, in + keysize, keysize); + err = mp_read_unsigned_bin(point->y, in + keysize, (word32)keysize); } if (err == MP_OKAY) err = mp_set(point->z, 1); @@ -9034,7 +9034,7 @@ int wc_ecc_export_point_der(const int curve_idx, ecc_point* point, byte* out, if ((curve_idx < 0) || (wc_ecc_is_valid_idx(curve_idx) == 0)) return ECC_BAD_ARG_E; - numlen = ecc_sets[curve_idx].size; + numlen = (word32)ecc_sets[curve_idx].size; /* return length needed only */ if (point != NULL && out == NULL && outLen != NULL) { @@ -9068,7 +9068,7 @@ int wc_ecc_export_point_der(const int curve_idx, ecc_point* point, byte* out, /* pad and store x */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(point->x, buf + - (numlen - mp_unsigned_bin_size(point->x))); + (numlen - (word32)mp_unsigned_bin_size(point->x))); if (ret != MP_OKAY) goto done; XMEMCPY(out+1, buf, numlen); @@ -9076,7 +9076,7 @@ int wc_ecc_export_point_der(const int curve_idx, ecc_point* point, byte* out, /* pad and store y */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(point->y, buf + - (numlen - mp_unsigned_bin_size(point->y))); + (numlen - (word32)mp_unsigned_bin_size(point->y))); if (ret != MP_OKAY) goto done; XMEMCPY(out+1+numlen, buf, numlen); @@ -9177,8 +9177,8 @@ int wc_ecc_export_x963(ecc_key* key, byte* out, word32* outLen) /* return length needed only */ if (key != NULL && out == NULL && outLen != NULL) { /* if key hasn't been setup assume max bytes for size estimation */ - numlen = key->dp ? key->dp->size : MAX_ECC_BYTES; - *outLen = 1 + 2*numlen; + numlen = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES; + *outLen = 1 + 2 * numlen; return LENGTH_ONLY_E; } @@ -9208,7 +9208,7 @@ int wc_ecc_export_x963(ecc_key* key, byte* out, word32* outLen) return ECC_BAD_ARG_E; } - numlen = key->dp->size; + numlen = (word32)key->dp->size; /* verify room in out buffer */ if (*outLen < (1 + 2*numlen)) { @@ -9217,8 +9217,8 @@ int wc_ecc_export_x963(ecc_key* key, byte* out, word32* outLen) } /* verify public key length is less than key size */ - pubxlen = mp_unsigned_bin_size(key->pubkey.x); - pubylen = mp_unsigned_bin_size(key->pubkey.y); + pubxlen = (word32)mp_unsigned_bin_size(key->pubkey.x); + pubylen = (word32)mp_unsigned_bin_size(key->pubkey.y); if ((pubxlen > numlen) || (pubylen > numlen)) { WOLFSSL_MSG("Public key x/y invalid!"); return BUFFER_E; @@ -10056,7 +10056,7 @@ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, /* read data */ if (err == MP_OKAY) - err = mp_read_unsigned_bin(key->pubkey.x, in, keysize); + err = mp_read_unsigned_bin(key->pubkey.x, in, (word32)keysize); #ifdef HAVE_COMP_KEY if (err == MP_OKAY && compressed == 1) { /* build y */ @@ -10192,7 +10192,8 @@ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, if (compressed == 0) #endif { - err = mp_read_unsigned_bin(key->pubkey.y, in + keysize, keysize); + err = mp_read_unsigned_bin(key->pubkey.y, in + keysize, + (word32)keysize); } } if (err == MP_OKAY) @@ -10280,7 +10281,7 @@ int wc_ecc_export_ex(ecc_key* key, byte* qx, word32* qxLen, if (wc_ecc_is_valid_idx(key->idx) == 0 || key->dp == NULL) { return ECC_BAD_ARG_E; } - keySz = key->dp->size; + keySz = (word32)key->dp->size; /* private key, d */ if (d != NULL) { @@ -10437,7 +10438,7 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, wc_ecc_reset(key); /* set key size */ - ret = wc_ecc_set_curve(key, privSz, curve_id); + ret = wc_ecc_set_curve(key, (int)privSz, curve_id); key->type = ECC_PRIVATEKEY_ONLY; } @@ -10771,7 +10772,7 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, err = mp_read_radix(key->pubkey.x, qx, MP_RADIX_HEX); else err = mp_read_unsigned_bin(key->pubkey.x, (const byte*)qx, - key->dp->size); + (word32)key->dp->size); if (mp_isneg(key->pubkey.x)) { WOLFSSL_MSG("Invalid Qx"); @@ -10788,7 +10789,7 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, err = mp_read_radix(key->pubkey.y, qy, MP_RADIX_HEX); else err = mp_read_unsigned_bin(key->pubkey.y, (const byte*)qy, - key->dp->size); + (word32)key->dp->size); if (mp_isneg(key->pubkey.y)) { WOLFSSL_MSG("Invalid Qy"); @@ -10946,7 +10947,7 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, #endif /* WOLFSSL_QNX_CAAM */ { err = mp_read_unsigned_bin(&key->k, (const byte*)d, - key->dp->size); + (word32)key->dp->size); } } #if defined(WOLFSSL_XILINX_CRYPT_VERSAL) diff --git a/wolfcrypt/src/hash.c b/wolfcrypt/src/hash.c index 04de18e2800..ed53d73f56e 100644 --- a/wolfcrypt/src/hash.c +++ b/wolfcrypt/src/hash.c @@ -531,7 +531,7 @@ int wc_Hash(enum wc_HashType hash_type, const byte* data, word32 dig_size; /* Validate hash buffer size */ - dig_size = wc_HashGetDigestSize(hash_type); + dig_size = (word32)wc_HashGetDigestSize(hash_type); if (hash_len < dig_size) { return BUFFER_E; } diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index e0cc5b05738..7ec3871aeca 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -384,25 +384,25 @@ WC_MISC_STATIC WC_INLINE int ConstantCompare(const byte* a, const byte* b, /* converts a 32 bit integer to 24 bit */ WC_MISC_STATIC WC_INLINE void c32to24(word32 in, word24 out) { - out[0] = (in >> 16) & 0xff; - out[1] = (in >> 8) & 0xff; - out[2] = in & 0xff; + out[0] = (byte)((in >> 16) & 0xff); + out[1] = (byte)((in >> 8) & 0xff); + out[2] = (byte)(in & 0xff); } /* convert 16 bit integer to opaque */ WC_MISC_STATIC WC_INLINE void c16toa(word16 wc_u16, byte* c) { - c[0] = (wc_u16 >> 8) & 0xff; - c[1] = wc_u16 & 0xff; + c[0] = (byte)((wc_u16 >> 8) & 0xff); + c[1] = (byte)(wc_u16 & 0xff); } /* convert 32 bit integer to opaque */ WC_MISC_STATIC WC_INLINE void c32toa(word32 wc_u32, byte* c) { - c[0] = (wc_u32 >> 24) & 0xff; - c[1] = (wc_u32 >> 16) & 0xff; - c[2] = (wc_u32 >> 8) & 0xff; - c[3] = wc_u32 & 0xff; + c[0] = (byte)((wc_u32 >> 24) & 0xff); + c[1] = (byte)((wc_u32 >> 16) & 0xff); + c[2] = (byte)((wc_u32 >> 8) & 0xff); + c[3] = (byte)(wc_u32 & 0xff); } #endif @@ -410,14 +410,16 @@ WC_MISC_STATIC WC_INLINE void c32toa(word32 wc_u32, byte* c) /* convert a 24 bit integer into a 32 bit one */ WC_MISC_STATIC WC_INLINE void c24to32(const word24 wc_u24, word32* wc_u32) { - *wc_u32 = ((word32)wc_u24[0] << 16) | (wc_u24[1] << 8) | wc_u24[2]; + *wc_u32 = ((word32)wc_u24[0] << 16) | + ((word32)wc_u24[1] << 8) | + (word32)wc_u24[2]; } /* convert opaque to 24 bit integer */ WC_MISC_STATIC WC_INLINE void ato24(const byte* c, word32* wc_u24) { - *wc_u24 = ((word32)c[0] << 16) | (c[1] << 8) | c[2]; + *wc_u24 = ((word32)c[0] << 16) | ((word32)c[1] << 8) | c[2]; } /* convert opaque to 16 bit integer */ @@ -429,7 +431,10 @@ WC_MISC_STATIC WC_INLINE void ato16(const byte* c, word16* wc_u16) /* convert opaque to 32 bit integer */ WC_MISC_STATIC WC_INLINE void ato32(const byte* c, word32* wc_u32) { - *wc_u32 = ((word32)c[0] << 24) | ((word32)c[1] << 16) | (c[2] << 8) | c[3]; + *wc_u32 = ((word32)c[0] << 24) | + ((word32)c[1] << 16) | + ((word32)c[2] << 8) | + (word32)c[3]; } @@ -474,31 +479,31 @@ WC_MISC_STATIC WC_INLINE int ByteToHexStr(byte in, char* out) /* Constant time - mask set when a > b. */ WC_MISC_STATIC WC_INLINE byte ctMaskGT(int a, int b) { - return (byte)((((word32)a - b - 1) >> 31) - 1); + return (byte)((((word32)a - (word32)b - 1) >> 31) - 1); } /* Constant time - mask set when a >= b. */ WC_MISC_STATIC WC_INLINE byte ctMaskGTE(int a, int b) { - return (byte)((((word32)a - b ) >> 31) - 1); + return (byte)((((word32)a - (word32)b) >> 31) - 1); } /* Constant time - mask set when a >= b. */ WC_MISC_STATIC WC_INLINE int ctMaskIntGTE(int a, int b) { - return (int)((((word32)a - b ) >> 31) - 1); + return (int)((((word32)a - (word32)b) >> 31) - 1); } /* Constant time - mask set when a < b. */ WC_MISC_STATIC WC_INLINE byte ctMaskLT(int a, int b) { - return (byte)((((word32)b - a - 1) >> 31) - 1); + return (byte)((((word32)b - (word32)a - 1) >> 31) - 1); } /* Constant time - mask set when a <= b. */ WC_MISC_STATIC WC_INLINE byte ctMaskLTE(int a, int b) { - return (byte)((((word32)b - a ) >> 31) - 1); + return (byte)((((word32)b - (word32)a) >> 31) - 1); } /* Constant time - mask set when a == b. */ @@ -510,25 +515,25 @@ WC_MISC_STATIC WC_INLINE byte ctMaskEq(int a, int b) /* Constant time - sets 16 bit integer mask when a > b */ WC_MISC_STATIC WC_INLINE word16 ctMask16GT(int a, int b) { - return (word16)((((word32)a - b - 1) >> 31) - 1); + return (word16)((((word32)a - (word32)b - 1) >> 31) - 1); } /* Constant time - sets 16 bit integer mask when a >= b */ WC_MISC_STATIC WC_INLINE word16 ctMask16GTE(int a, int b) { - return (word16)((((word32)a - b ) >> 31) - 1); + return (word16)((((word32)a - (word32)b) >> 31) - 1); } /* Constant time - sets 16 bit integer mask when a < b. */ WC_MISC_STATIC WC_INLINE word16 ctMask16LT(int a, int b) { - return (word16)((((word32)b - a - 1) >> 31) - 1); + return (word16)((((word32)b - (word32)a - 1) >> 31) - 1); } /* Constant time - sets 16 bit integer mask when a <= b. */ WC_MISC_STATIC WC_INLINE word16 ctMask16LTE(int a, int b) { - return (word16)((((word32)b - a ) >> 31) - 1); + return (word16)((((word32)b - (word32)a) >> 31) - 1); } /* Constant time - sets 16 bit integer mask when a == b. */ @@ -559,7 +564,7 @@ WC_MISC_STATIC WC_INLINE int ctMaskSelInt(byte m, int a, int b) /* Constant time - bit set when a <= b. */ WC_MISC_STATIC WC_INLINE byte ctSetLTE(int a, int b) { - return (byte)(((word32)a - b - 1) >> 31); + return (byte)(((word32)a - (word32)b - 1) >> 31); } /* Constant time - conditionally copy size bytes from src to dst if mask is set diff --git a/wolfcrypt/src/poly1305.c b/wolfcrypt/src/poly1305.c index c0ba66afb44..f138b60c1fe 100644 --- a/wolfcrypt/src/poly1305.c +++ b/wolfcrypt/src/poly1305.c @@ -778,7 +778,7 @@ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) /* process full blocks */ if (bytes >= POLY1305_BLOCK_SIZE) { - size_t want = (bytes & ~(POLY1305_BLOCK_SIZE - 1)); + size_t want = ((size_t)bytes & ~(POLY1305_BLOCK_SIZE - 1)); #if !defined(WOLFSSL_ARMASM) || !defined(__aarch64__) int ret; ret = poly1305_blocks(ctx, m, want); diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index fc5ca784546..0631efd9576 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -519,7 +519,7 @@ int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* seed, word32 seedSz) static WC_INLINE void array_add_one(byte* data, word32 dataSz) { - int i; + word32 i; for (i = dataSz - 1; i >= 0; i--) { data[i]++; if (data[i] != 0) break; @@ -618,7 +618,7 @@ static int Hash_gen(DRBG_internal* drbg, byte* out, word32 outSz, const byte* V) static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen) { if (dLen > 0 && sLen > 0 && dLen >= sLen) { - int sIdx, dIdx; + word32 sIdx, dIdx; word16 carry = 0; dIdx = dLen - 1; @@ -779,7 +779,7 @@ int wc_RNG_TestSeed(const byte* seed, word32 seedSz) while (seedIdx < seedSz - SEED_BLOCK_SZ) { if (ConstantCompare(seed + seedIdx, seed + seedIdx + scratchSz, - scratchSz) == 0) { + (int)scratchSz) == 0) { ret = DRBG_CONT_FAILURE; } @@ -3753,7 +3753,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) break; } - sz -= len; + sz -= (word32)len; output += len; if (sz) { diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index b6805a98027..6bf666e7105 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -943,7 +943,7 @@ static int InitSha256(wc_Sha256* sha256) S[i] = sha256->digest[i]; for (i = 0; i < 16; i++) - W[i] = *((const word32*)&data[i*sizeof(word32)]); + W[i] = *((const word32*)&data[i*(int)sizeof(word32)]); for (i = 16; i < WC_SHA256_BLOCK_SIZE; i++) W[i] = Gamma1(W[i-2]) + W[i-7] + Gamma0(W[i-15]) + W[i-16]; diff --git a/wolfcrypt/src/signature.c b/wolfcrypt/src/signature.c index 38a8d98148e..f9c71926be8 100644 --- a/wolfcrypt/src/signature.c +++ b/wolfcrypt/src/signature.c @@ -67,9 +67,9 @@ static int wc_SignatureDerEncode(enum wc_HashType hash_type, byte* hash_data, } oid = ret; - ret = wc_EncodeSignature(hash_data, hash_data, hash_len, oid); + ret = (int)wc_EncodeSignature(hash_data, hash_data, hash_len, oid); if (ret > 0) { - *hash_enc_len = ret; + *hash_enc_len = (word32)ret; ret = 0; } @@ -295,7 +295,7 @@ int wc_SignatureVerify( WOLFSSL_MSG("wc_SignatureVerify: Invalid hash type/len"); return ret; } - hash_enc_len = hash_len = ret; + hash_enc_len = hash_len = (word32)ret; #ifndef NO_RSA if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { @@ -429,7 +429,7 @@ int wc_SignatureGenerateHash_ex( } while (ret == WC_PENDING_E); #endif /* WOLFSSL_CRYPTOCELL */ if (ret >= 0) { - *sig_len = ret; + *sig_len = (word32)ret; ret = 0; /* Success */ } #else @@ -494,7 +494,7 @@ int wc_SignatureGenerate_ex( WOLFSSL_MSG("wc_SignatureGenerate: Invalid hash type/len"); return ret; } - hash_enc_len = hash_len = ret; + hash_enc_len = hash_len = (word32)ret; #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 99cec076012..02543f28ca2 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -178,7 +178,7 @@ This library provides single precision (SP) integer math functions. do { \ ALLOC_SP_INT(n, s, err, h); \ if ((err) == MP_OKAY) { \ - (n)->size = (s); \ + (n)->size = (unsigned int)(s); \ } \ } \ while (0) @@ -4682,7 +4682,7 @@ static void _sp_zero(sp_int* a) * @param [out] a SP integer. * @param [in] size Number of words to say are available. */ -static void _sp_init_size(sp_int* a, int size) +static void _sp_init_size(sp_int* a, unsigned int size) { volatile sp_int_minimal* am = (sp_int_minimal *)a; @@ -4702,7 +4702,7 @@ static void _sp_init_size(sp_int* a, int size) * @return MP_OKAY on success. * @return MP_VAL when a is NULL. */ -int sp_init_size(sp_int* a, int size) +int sp_init_size(sp_int* a, unsigned int size) { int err = MP_OKAY; @@ -4998,8 +4998,8 @@ int sp_exch(sp_int* a, sp_int* b) ALLOC_SP_INT(t, a->used, err, NULL); if (err == MP_OKAY) { /* Cache allocated size of a and b. */ - int asize = a->size; - int bsize = b->size; + unsigned int asize = a->size; + unsigned int bsize = b->size; /* Copy all of SP int: t <= a, a <= b, b <= t. */ XMEMCPY(t, a, MP_INT_SIZEOF(a->used)); XMEMCPY(a, b, MP_INT_SIZEOF(b->used)); @@ -5030,16 +5030,16 @@ int sp_cond_swap_ct(sp_int* a, sp_int* b, int cnt, int swap) { unsigned int i; int err = MP_OKAY; - sp_int_digit mask = (sp_int_digit)0 - swap; + sp_int_digit mask = (sp_int_digit)0 - (sp_int_digit)swap; DECL_SP_INT(t, cnt); /* Allocate temporary to hold masked xor of a and b. */ ALLOC_SP_INT(t, cnt, err, NULL); if (err == MP_OKAY) { /* XOR other fields in sp_int into temp - mask set when swapping. */ - t->used = (int)((a->used ^ b->used) & mask); + t->used = (a->used ^ b->used) & mask; #ifdef WOLFSSL_SP_INT_NEGATIVE - t->sign = (int)((a->sign ^ b->sign) & mask); + t->sign = (a->sign ^ b->sign) & mask; #endif /* XOR requested words into temp - mask set when swapping. */ @@ -5430,13 +5430,13 @@ int sp_cnt_lsb(const sp_int* a) /* Done if not all 4 bits are zero. */ if (cnt != 4) { /* Add checked bits and count in last 4 bits checked. */ - bc += j + cnt; + bc += j + (unsigned int)cnt; break; } } } - return bc; + return (int)bc; } #endif /* WOLFSSL_SP_MATH_ALL || WOLFSSL_HAVE_SP_DH || (HAVE_ECC && FP_ECC) */ @@ -6758,7 +6758,7 @@ static void _sp_div_2(const sp_int* a, sp_int* r) /* Last word only needs to be shifted down. */ r->dp[i] = a->dp[i] >> 1; /* Set used to be all words seen. */ - r->used = i + 1; + r->used = (unsigned int)i + 1; /* Remove leading zeros. */ sp_clamp(r); #ifdef WOLFSSL_SP_INT_NEGATIVE @@ -7267,8 +7267,8 @@ int sp_addmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) { int err = MP_OKAY; /* Calculate used based on digits used in a and b. */ - int used = ((a == NULL) || (b == NULL)) ? 1 : - ((a->used >= b->used) ? a->used + 1 : b->used + 1); + unsigned int used = ((a == NULL) || (b == NULL)) ? 1 : + ((a->used >= b->used) ? a->used + 1 : b->used + 1); DECL_SP_INT(t, used); /* Validate parameters. */ @@ -7780,7 +7780,7 @@ static int sp_lshb(sp_int* a, int n) if (a->used != 0) { /* Calculate number of digits to shift. */ - unsigned int s = n >> SP_WORD_SHIFT; + unsigned int s = (unsigned int)n >> SP_WORD_SHIFT; /* Ensure number has enough digits for result. */ if (a->used + s >= a->size) { @@ -8757,11 +8757,11 @@ static int _sp_mul_4(const sp_int* a, const sp_int* b, sp_int* r) w[14] = (sp_int_word)da[3] * db[2]; w[15] = (sp_int_word)da[3] * db[3]; - r->dp[0] = w[0]; + r->dp[0] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[1]; w[0] += (sp_int_digit)w[2]; - r->dp[1] = w[0]; + r->dp[1] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[1] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[1]; @@ -8770,7 +8770,7 @@ static int _sp_mul_4(const sp_int* a, const sp_int* b, sp_int* r) w[0] += (sp_int_digit)w[3]; w[0] += (sp_int_digit)w[4]; w[0] += (sp_int_digit)w[5]; - r->dp[2] = w[0]; + r->dp[2] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[3] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[3]; @@ -8782,7 +8782,7 @@ static int _sp_mul_4(const sp_int* a, const sp_int* b, sp_int* r) w[0] += (sp_int_digit)w[7]; w[0] += (sp_int_digit)w[8]; w[0] += (sp_int_digit)w[9]; - r->dp[3] = w[0]; + r->dp[3] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[6] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[6]; @@ -8795,7 +8795,7 @@ static int _sp_mul_4(const sp_int* a, const sp_int* b, sp_int* r) w[0] += (sp_int_digit)w[10]; w[0] += (sp_int_digit)w[11]; w[0] += (sp_int_digit)w[12]; - r->dp[4] = w[0]; + r->dp[4] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[10] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[10]; @@ -8805,18 +8805,18 @@ static int _sp_mul_4(const sp_int* a, const sp_int* b, sp_int* r) w[0] += (sp_int_digit)w[12]; w[0] += (sp_int_digit)w[13]; w[0] += (sp_int_digit)w[14]; - r->dp[5] = w[0]; + r->dp[5] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[13] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[13]; w[14] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[14]; w[0] += (sp_int_digit)w[15]; - r->dp[6] = w[0]; + r->dp[6] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[15] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[15]; - r->dp[7] = w[0]; + r->dp[7] = (sp_int_digit)w[0]; r->used = 8; sp_clamp(r); @@ -12094,9 +12094,10 @@ int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, * One or more of the top bits is 1 so count. */ for (i = sp_count_bits(e)-2, j = 1; i >= 0; i--, j++) { - if ((!sp_is_bit_set(e, i)) || (j == CT_INV_MOD_PRE_CNT)) { - break; - } + if ((!sp_is_bit_set(e, (unsigned int)i)) || + (j == CT_INV_MOD_PRE_CNT)) { + break; + } } /* 3. Set tmp to product of leading bits. */ err = sp_copy(pre[j-1], t); @@ -12110,7 +12111,7 @@ int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, */ for (; (err == MP_OKAY) && (i >= 0); i--) { /* 6.1. bit = e[i] */ - int bit = sp_is_bit_set(e, i); + int bit = sp_is_bit_set(e, (unsigned int)i); /* 6.2. j += bit * Update count of consequitive 1 bits. @@ -13231,7 +13232,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, /* Top bit of exponent fixed as 1 for pre-calculated window. */ preCnt = 1 << (winBits - 1); /* Mask for calculating index into pre-computed table. */ - mask = preCnt - 1; + mask = (sp_int_digit)preCnt - 1; /* Allocate sp_ints for: * - pre-computation table @@ -14109,11 +14110,11 @@ static int _sp_sqr_4(const sp_int* a, sp_int* r) w[8] = (sp_int_word)da[2] * da[3]; w[9] = (sp_int_word)da[3] * da[3]; - r->dp[0] = w[0]; + r->dp[0] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[1]; w[0] += (sp_int_digit)w[1]; - r->dp[1] = w[0]; + r->dp[1] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[1] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[1]; @@ -14121,7 +14122,7 @@ static int _sp_sqr_4(const sp_int* a, sp_int* r) w[0] += (sp_int_digit)w[2]; w[0] += (sp_int_digit)w[2]; w[0] += (sp_int_digit)w[3]; - r->dp[2] = w[0]; + r->dp[2] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[2] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[2]; @@ -14132,7 +14133,7 @@ static int _sp_sqr_4(const sp_int* a, sp_int* r) w[0] += (sp_int_digit)w[4]; w[0] += (sp_int_digit)w[5]; w[0] += (sp_int_digit)w[5]; - r->dp[3] = w[0]; + r->dp[3] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[4] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[4]; @@ -14143,7 +14144,7 @@ static int _sp_sqr_4(const sp_int* a, sp_int* r) w[0] += (sp_int_digit)w[6]; w[0] += (sp_int_digit)w[6]; w[0] += (sp_int_digit)w[7]; - r->dp[4] = w[0]; + r->dp[4] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[6] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[6]; @@ -14152,17 +14153,17 @@ static int _sp_sqr_4(const sp_int* a, sp_int* r) w[0] += (sp_int_digit)w[7]; w[0] += (sp_int_digit)w[8]; w[0] += (sp_int_digit)w[8]; - r->dp[5] = w[0]; + r->dp[5] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[8] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[8]; w[0] += (sp_int_digit)w[8]; w[0] += (sp_int_digit)w[9]; - r->dp[6] = w[0]; + r->dp[6] = (sp_int_digit)w[0]; w[0] >>= SP_WORD_SIZE; w[9] >>= SP_WORD_SIZE; w[0] += (sp_int_digit)w[9]; - r->dp[7] = w[0]; + r->dp[7] = (sp_int_digit)w[0]; r->used = 8; sp_clamp(r); @@ -16846,7 +16847,7 @@ static void _sp_mont_setup(const sp_int* m, sp_int_digit* rho) x *= 1 + y; /* rho = -1/m mod d, subtract x (unsigned) from 0, assign negative */ - *rho = (sp_int_digit)((sp_int_digit)0 - (sp_int_sdigit)x); + *rho = (sp_int_digit)((sp_int_sdigit)0 - (sp_int_sdigit)x); } /* Calculate the bottom digit of the inverse of negative m. @@ -16916,7 +16917,7 @@ int sp_mont_norm(sp_int* norm, const sp_int* m) } /* Smallest number greater than m of form 2^n. */ _sp_zero(norm); - err = sp_set_bit(norm, bits); + err = sp_set_bit(norm, (int)bits); } if (err == MP_OKAY) { /* norm = 2^n % m */ @@ -17292,7 +17293,7 @@ static int _sp_read_radix_10(sp_int* a, const char* in) break; } /* Add character value. */ - err = _sp_add_d(a, ch, a); + err = _sp_add_d(a, (sp_int_digit)ch, a); if (err != MP_OKAY) { break; } @@ -17467,7 +17468,7 @@ int sp_tohex(const sp_int* a, char* str) d = a->dp[i]; /* Write out all nibbles of digit. */ for (j = SP_WORD_SIZE - 4; j >= 0; j -= 4) { - *(str++) = (byte)ByteToHex((byte)(d >> j)); + *(str++) = (char)ByteToHex((byte)(d >> j)); } } } @@ -18265,7 +18266,7 @@ int sp_prime_is_prime_ex(const sp_int* a, int trials, int* result, WC_RNG* rng) * give a (1/4)^t chance of a false prime. */ if ((err == MP_OKAY) && (!haveRes)) { int bits = sp_count_bits(a); - word32 baseSz = (bits + 7) / 8; + word32 baseSz = ((word32)bits + 7) / 8; DECL_SP_INT_ARRAY(ds, a->used + 1, 2); DECL_SP_INT_ARRAY(d, a->used * 2 + 1, 2); diff --git a/wolfcrypt/src/wolfmath.c b/wolfcrypt/src/wolfmath.c index bb86781bd3a..b7fe5c7c8d8 100644 --- a/wolfcrypt/src/wolfmath.c +++ b/wolfcrypt/src/wolfmath.c @@ -96,7 +96,7 @@ int get_digit_count(const mp_int* a) if (a == NULL) return 0; - return a->used; + return (int)a->used; } mp_digit get_digit(const mp_int* a, int n) @@ -122,7 +122,7 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) #if defined(SP_WORD_SIZE) && SP_WORD_SIZE == 8 unsigned int mask = (unsigned int)0 - copy; #else - mp_digit mask = (mp_digit)0 - copy; + mp_digit mask = (mp_digit)0 - (mp_digit)copy; #endif if (a == NULL || b == NULL) @@ -130,7 +130,7 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) /* Ensure b has enough space to copy a into */ if (err == MP_OKAY) - err = mp_grow(b, a->used + 1); + err = mp_grow(b, (int)a->used + 1); if (err == MP_OKAY) { #if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) unsigned int i; @@ -144,15 +144,15 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) * get_digit() returns 0 when index greater than available digit. */ for (i = 0; i < a->used; i++) { - b->dp[i] ^= (get_digit(a, i) ^ get_digit(b, i)) & mask; + b->dp[i] ^= (get_digit(a, (int)i) ^ get_digit(b, (int)i)) & mask; } for (; i < b->used; i++) { - b->dp[i] ^= (get_digit(a, i) ^ get_digit(b, i)) & mask; + b->dp[i] ^= (get_digit(a, (int)i) ^ get_digit(b, (int)i)) & mask; } - b->used ^= (a->used ^ b->used) & (int)mask; + b->used ^= (a->used ^ b->used) & (mp_digit)mask; #if (!defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_SP_MATH_ALL)) || \ defined(WOLFSSL_SP_INT_NEGATIVE) - b->sign ^= (a->sign ^ b->sign) & (int)mask; + b->sign ^= (a->sign ^ b->sign) & (mp_digit)mask; #endif } @@ -171,7 +171,7 @@ int get_rand_digit(WC_RNG* rng, mp_digit* d) int mp_rand(mp_int* a, int digits, WC_RNG* rng) { int ret = 0; - int cnt = digits * sizeof(mp_digit); + int cnt = digits * (int)sizeof(mp_digit); if (rng == NULL) { ret = MISSING_RNG_E; @@ -195,12 +195,12 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng) ret = BAD_FUNC_ARG; } if (ret == MP_OKAY) { - a->used = digits; + a->used = (word32)digits; } #endif /* fill the data with random bytes */ if (ret == MP_OKAY) { - ret = wc_RNG_GenerateBlock(rng, (byte*)a->dp, cnt); + ret = wc_RNG_GenerateBlock(rng, (byte*)a->dp, (word32)cnt); } if (ret == MP_OKAY) { #ifdef USE_INTEGER_HEAP_MATH @@ -264,7 +264,8 @@ int wc_export_int(mp_int* mp, byte* buf, word32* len, word32 keySz, } *len = keySz; XMEMSET(buf, 0, *len); - err = mp_to_unsigned_bin(mp, buf + (keySz - mp_unsigned_bin_size(mp))); + err = mp_to_unsigned_bin(mp, buf + + (keySz - (word32)mp_unsigned_bin_size(mp))); } return err; diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index c21224f2c3e..6d36248ffb8 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -667,12 +667,12 @@ typedef struct sp_ecc_ctx { * * @param [in] a SP integer to update. */ -#define sp_clamp(a) \ - do { \ - int ii; \ - for (ii = (a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ - } \ - (a)->used = ii + 1; \ +#define sp_clamp(a) \ + do { \ + unsigned int ii; \ + for (ii = (a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ + } \ + (a)->used = ii + 1; \ } while (0) /* Check the compiled and linked math implementation are the same. @@ -891,7 +891,7 @@ typedef sp_int_digit mp_digit; */ MP_API int sp_init(sp_int* a); -MP_API int sp_init_size(sp_int* a, int size); +MP_API int sp_init_size(sp_int* a, unsigned int size); MP_API int sp_init_multi(sp_int* n1, sp_int* n2, sp_int* n3, sp_int* n4, sp_int* n5, sp_int* n6); MP_API void sp_free(sp_int* a); From 5bc5b12d5c9549e36e901dbcfb0b036280db3419 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 4 Apr 2023 14:08:43 -0700 Subject: [PATCH 117/391] Resolve issue with C89 compliance with "commas at the end of enumerator lists". Tested with `./configure --disable-asm --enable-32bit --enable-asn --enable-cryptonly CFLAGS="-Wall -ansi -pedantic-errors -Wshadow -g" && make` --- wolfssl/wolfcrypt/aes.h | 14 ++--- wolfssl/wolfcrypt/arc4.h | 2 +- wolfssl/wolfcrypt/asn.h | 86 +++++++++++++-------------- wolfssl/wolfcrypt/asn_public.h | 15 ++--- wolfssl/wolfcrypt/chacha.h | 2 +- wolfssl/wolfcrypt/chacha20_poly1305.h | 2 +- wolfssl/wolfcrypt/dh.h | 2 +- wolfssl/wolfcrypt/ecc.h | 8 +-- wolfssl/wolfcrypt/hash.h | 4 +- wolfssl/wolfcrypt/hmac.h | 26 ++++---- wolfssl/wolfcrypt/poly1305.h | 2 +- wolfssl/wolfcrypt/rsa.h | 9 +-- wolfssl/wolfcrypt/signature.h | 2 +- wolfssl/wolfcrypt/types.h | 2 +- 14 files changed, 89 insertions(+), 87 deletions(-) diff --git a/wolfssl/wolfcrypt/aes.h b/wolfssl/wolfcrypt/aes.h index 449220994a2..fdf946d488d 100644 --- a/wolfssl/wolfcrypt/aes.h +++ b/wolfssl/wolfcrypt/aes.h @@ -138,7 +138,7 @@ enum { AES_192_KEY_SIZE = 24, /* for 192 bit */ AES_256_KEY_SIZE = 32, /* for 256 bit */ - AES_IV_SIZE = 16, /* always block size */ + AES_IV_SIZE = 16 /* always block size */ }; #endif @@ -165,20 +165,20 @@ enum { CCM_NONCE_MIN_SZ = 7, CCM_NONCE_MAX_SZ = 13, CTR_SZ = 4, - AES_IV_FIXED_SZ = 4, + AES_IV_FIXED_SZ = 4 #ifdef WOLFSSL_AES_CFB - AES_CFB_MODE = 1, + ,AES_CFB_MODE = 1 #endif #ifdef WOLFSSL_AES_OFB - AES_OFB_MODE = 2, + ,AES_OFB_MODE = 2 #endif #ifdef WOLFSSL_AES_XTS - AES_XTS_MODE = 3, + ,AES_XTS_MODE = 3 #endif #ifdef WOLF_PRIVATE_KEY_ID - AES_MAX_ID_LEN = 32, - AES_MAX_LABEL_LEN = 32, + ,AES_MAX_ID_LEN = 32, + AES_MAX_LABEL_LEN = 32 #endif }; diff --git a/wolfssl/wolfcrypt/arc4.h b/wolfssl/wolfcrypt/arc4.h index ad97921681d..fe58b10ece9 100644 --- a/wolfssl/wolfcrypt/arc4.h +++ b/wolfssl/wolfcrypt/arc4.h @@ -39,7 +39,7 @@ enum { ARC4_ENC_TYPE = 4, /* cipher unique type */ ARC4_STATE_SIZE = 256, - RC4_KEY_SIZE = 16, /* always 128bit */ + RC4_KEY_SIZE = 16 /* always 128bit */ }; /* ARC4 encryption and decryption */ diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 489dcfe5517..3d559cc9af2 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -154,7 +154,7 @@ enum ASN_Tags { /* OneAsymmetricKey Fields */ ASN_ASYMKEY_ATTRS = 0x00, - ASN_ASYMKEY_PUBKEY = 0x01, + ASN_ASYMKEY_PUBKEY = 0x01 }; /* NOTE: If ASN_UTC_TIME_SIZE or ASN_GENERALIZED_TIME_SIZE are ever modified @@ -188,7 +188,7 @@ enum ASNItem_DataType { /* Big number as a positive or negative mp_int. */ ASN_DATA_TYPE_MP_POS_NEG = 9, /* ASN.1 CHOICE. A 0 terminated list of tags that are valid. */ - ASN_DATA_TYPE_CHOICE = 10, + ASN_DATA_TYPE_CHOICE = 10 }; /* A template entry describing an ASN.1 item. */ @@ -831,22 +831,22 @@ enum ECC_TYPES }; #ifdef WOLFSSL_CERT_PIV - enum PIV_Tags { - ASN_PIV_CERT = 0x0A, - ASN_PIV_NONCE = 0x0B, - ASN_PIV_SIGNED_NONCE = 0x0C, - - ASN_PIV_TAG_CERT = 0x70, - ASN_PIV_TAG_CERT_INFO = 0x71, - ASN_PIV_TAG_MSCUID = 0x72, - ASN_PIV_TAG_ERR_DET = 0xFE, - - /* certificate info masks */ - ASN_PIV_CERT_INFO_COMPRESSED = 0x03, - ASN_PIV_CERT_INFO_ISX509 = 0x04, - /* GZIP is 0x01 */ - ASN_PIV_CERT_INFO_GZIP = 0x01, - }; +enum PIV_Tags { + ASN_PIV_CERT = 0x0A, + ASN_PIV_NONCE = 0x0B, + ASN_PIV_SIGNED_NONCE = 0x0C, + + ASN_PIV_TAG_CERT = 0x70, + ASN_PIV_TAG_CERT_INFO = 0x71, + ASN_PIV_TAG_MSCUID = 0x72, + ASN_PIV_TAG_ERR_DET = 0xFE, + + /* certificate info masks */ + ASN_PIV_CERT_INFO_COMPRESSED = 0x03, + ASN_PIV_CERT_INFO_ISX509 = 0x04, + /* GZIP is 0x01 */ + ASN_PIV_CERT_INFO_GZIP = 0x01, +}; #endif /* WOLFSSL_CERT_PIV */ @@ -994,7 +994,7 @@ enum Misc_ASN { PEM_LINE_SZ = 64, /* Length of Base64 encoded line, not including new line */ PEM_LINE_LEN = PEM_LINE_SZ + 12, /* PEM line max + fudge */ - COUNTRY_CODE_LEN = 2, /* RFC 3739 */ + COUNTRY_CODE_LEN = 2 /* RFC 3739 */ }; #ifndef WC_MAX_NAME_ENTRIES @@ -1060,20 +1060,20 @@ enum Block_Sum { #ifdef WOLFSSL_AES_128 AES128CBCb = 414, AES128GCMb = 418, - AES128CCMb = 419, + AES128CCMb = 419 #endif #ifdef WOLFSSL_AES_192 - AES192CBCb = 434, + ,AES192CBCb = 434, AES192GCMb = 438, - AES192CCMb = 439, + AES192CCMb = 439 #endif #ifdef WOLFSSL_AES_256 - AES256CBCb = 454, + ,AES256CBCb = 454, AES256GCMb = 458, - AES256CCMb = 459, + AES256CCMb = 459 #endif #ifndef NO_DES3 - DESb = 69, + ,DESb = 69, DES3b = 652 #endif }; @@ -1101,22 +1101,22 @@ enum Key_Sum { SPHINCS_FAST_LEVEL5k = 282, /* 1 3 9999 6 9 3 */ SPHINCS_SMALL_LEVEL1k = 287, /* 1 3 9999 6 7 10 */ SPHINCS_SMALL_LEVEL3k = 285, /* 1 3 9999 6 8 7 */ - SPHINCS_SMALL_LEVEL5k = 286, /* 1 3 9999 6 9 7 */ + SPHINCS_SMALL_LEVEL5k = 286 /* 1 3 9999 6 9 7 */ }; #if !defined(NO_AES) || defined(HAVE_PKCS7) enum KeyWrap_Sum { #ifdef WOLFSSL_AES_128 - AES128_WRAP = 417, + AES128_WRAP = 417 #endif #ifdef WOLFSSL_AES_192 - AES192_WRAP = 437, + ,AES192_WRAP = 437 #endif #ifdef WOLFSSL_AES_256 - AES256_WRAP = 457, + ,AES256_WRAP = 457 #endif #ifdef HAVE_PKCS7 - PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ + ,PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ #endif }; #endif /* !NO_AES || PKCS7 */ @@ -1126,14 +1126,14 @@ enum Key_Agree { dhSinglePass_stdDH_sha224kdf_scheme = 188, dhSinglePass_stdDH_sha256kdf_scheme = 189, dhSinglePass_stdDH_sha384kdf_scheme = 190, - dhSinglePass_stdDH_sha512kdf_scheme = 191, + dhSinglePass_stdDH_sha512kdf_scheme = 191 }; enum KDF_Sum { PBKDF2_OID = 660, - MGF1_OID = 652, + MGF1_OID = 652 }; @@ -1180,9 +1180,9 @@ enum Extensions_Sum { }; enum CertificatePolicy_Sum { - CP_ANY_OID = 146, /* id-ce 32 0 */ + CP_ANY_OID = 146 /* id-ce 32 0 */ #ifdef WOLFSSL_FPKI - CP_FPKI_COMMON_AUTH_OID = 426, /* 2.16.840.1.101.3.2.1.3.13 */ + ,CP_FPKI_COMMON_AUTH_OID = 426, /* 2.16.840.1.101.3.2.1.3.13 */ CP_FPKI_PIV_AUTH_OID = 453, /* 2.16.840.1.101.3.2.1.3.40 */ CP_FPKI_PIV_AUTH_HW_OID = 454, /* 2.16.840.1.101.3.2.1.3.41 */ CP_FPKI_PIVI_AUTH_OID = 458 /* 2.16.840.1.101.3.2.1.3.45 */ @@ -1195,9 +1195,9 @@ enum SepHardwareName_Sum { enum AuthInfo_Sum { AIA_OCSP_OID = 116, /* 1.3.6.1.5.5.7.48.1, id-ad-ocsp */ - AIA_CA_ISSUER_OID = 117, /* 1.3.6.1.5.5.7.48.2, id-ad-caIssuers */ + AIA_CA_ISSUER_OID = 117 /* 1.3.6.1.5.5.7.48.2, id-ad-caIssuers */ #ifdef WOLFSSL_SUBJ_INFO_ACC - AIA_CA_REPO_OID = 120 /* 1.3.6.1.5.5.7.48.5, id-ad-caRepository */ + ,AIA_CA_REPO_OID = 120 /* 1.3.6.1.5.5.7.48.5, id-ad-caRepository */ #endif /* WOLFSSL_SUBJ_INFO_ACC */ }; @@ -1244,7 +1244,7 @@ enum VerifyType { VERIFY_OCSP = 3, VERIFY_NAME = 4, VERIFY_SKIP_DATE = 5, - VERIFY_OCSP_CERT = 6, + VERIFY_OCSP_CERT = 6 }; #ifdef WOLFSSL_CERT_EXT @@ -1266,7 +1266,7 @@ enum CsrAttrType { INITIALS_OID = 132, SURNAME_OID = 93, NAME_OID = 130, - GIVEN_NAME_OID = 131, + GIVEN_NAME_OID = 131 }; #endif @@ -1349,7 +1349,7 @@ enum SignatureState { SIG_STATE_HASH, SIG_STATE_KEY, SIG_STATE_DO, - SIG_STATE_CHECK, + SIG_STATE_CHECK }; @@ -1459,7 +1459,7 @@ enum CertSignState { CERTSIGN_STATE_BEGIN, CERTSIGN_STATE_DIGEST, CERTSIGN_STATE_ENCODE, - CERTSIGN_STATE_DO, + CERTSIGN_STATE_DO }; struct CertSignCtx { @@ -2242,7 +2242,7 @@ enum cert_enums { SPHINCS_FAST_LEVEL5_KEY = 26, SPHINCS_SMALL_LEVEL1_KEY = 27, SPHINCS_SMALL_LEVEL3_KEY = 28, - SPHINCS_SMALL_LEVEL5_KEY = 29, + SPHINCS_SMALL_LEVEL5_KEY = 29 }; #endif /* WOLFSSL_CERT_GEN */ @@ -2527,7 +2527,7 @@ enum PBESTypes { PBES2 = 13, /* algo ID */ PBES1_MD5_DES = 3, - PBES1_SHA1_DES = 10, + PBES1_SHA1_DES = 10 }; enum PKCSTypes { @@ -2537,7 +2537,7 @@ enum PKCSTypes { PKCS8v0 = 0, /* default PKCS#8 version */ PKCS8v1 = 1, /* PKCS#8 version including public key */ PKCS1v0 = 0, /* default PKCS#1 version */ - PKCS1v1 = 1, /* Multi-prime version */ + PKCS1v1 = 1 /* Multi-prime version */ }; #endif /* !NO_ASN || !NO_PWDBASED */ diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index fb43f974887..7c5401c75be 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -112,7 +112,7 @@ enum Ecc_Sum { ECC_SECP384R1_OID = 210, ECC_BRAINPOOLP384R1_OID = 108, ECC_BRAINPOOLP512R1_OID = 110, - ECC_SECP521R1_OID = 211, + ECC_SECP521R1_OID = 211 }; @@ -154,7 +154,7 @@ enum CertType { SPHINCS_SMALL_LEVEL1_TYPE, SPHINCS_SMALL_LEVEL3_TYPE, SPHINCS_SMALL_LEVEL5_TYPE, - ECC_PARAM_TYPE, + ECC_PARAM_TYPE }; @@ -202,7 +202,7 @@ enum Ctc_SigType { CTC_SPHINCS_FAST_LEVEL5 = 282, CTC_SPHINCS_SMALL_LEVEL1 = 287, CTC_SPHINCS_SMALL_LEVEL3 = 285, - CTC_SPHINCS_SMALL_LEVEL5 = 286, + CTC_SPHINCS_SMALL_LEVEL5 = 286 }; enum Ctc_Encoding { @@ -231,15 +231,16 @@ enum Ctc_Misc { CTC_GEN_SERIAL_SZ = 16, CTC_FILETYPE_ASN1 = 2, CTC_FILETYPE_PEM = 1, - CTC_FILETYPE_DEFAULT = 2, + CTC_FILETYPE_DEFAULT = 2 + #ifdef WOLFSSL_CERT_EXT /* AKID could contains: hash + (Option) AuthCertIssuer,AuthCertSerialNum * We support only hash */ - CTC_MAX_SKID_SIZE = 32, /* SHA256_DIGEST_SIZE */ + ,CTC_MAX_SKID_SIZE = 32, /* SHA256_DIGEST_SIZE */ CTC_MAX_AKID_SIZE = 32, /* SHA256_DIGEST_SIZE */ CTC_MAX_CERTPOL_SZ = 200, /* RFC 5280 Section 4.2.1.4 */ CTC_MAX_CERTPOL_NB = 2, /* Max number of Certificate Policy */ - CTC_MAX_CRLINFO_SZ = WC_CTC_MAX_CRLINFO_SZ, /* Arbitrary size that should be + CTC_MAX_CRLINFO_SZ = WC_CTC_MAX_CRLINFO_SZ /* Arbitrary size that should be * enough for at least two * distribution points. */ #endif /* WOLFSSL_CERT_EXT */ @@ -270,7 +271,7 @@ enum { #endif PEM_PASS_READ = 0, - PEM_PASS_WRITE = 1, + PEM_PASS_WRITE = 1 }; typedef int (wc_pem_password_cb)(char* passwd, int sz, int rw, void* userdata); diff --git a/wolfssl/wolfcrypt/chacha.h b/wolfssl/wolfcrypt/chacha.h index e654972ffb1..7cd73db4e36 100644 --- a/wolfssl/wolfcrypt/chacha.h +++ b/wolfssl/wolfcrypt/chacha.h @@ -72,7 +72,7 @@ Block counter is located at index 12. enum { CHACHA_ENC_TYPE = WC_CIPHER_CHACHA, /* cipher unique type */ - CHACHA_MAX_KEY_SZ = 32, + CHACHA_MAX_KEY_SZ = 32 }; typedef struct ChaCha { diff --git a/wolfssl/wolfcrypt/chacha20_poly1305.h b/wolfssl/wolfcrypt/chacha20_poly1305.h index 7c1ddc97bb1..6c04912a03c 100644 --- a/wolfssl/wolfcrypt/chacha20_poly1305.h +++ b/wolfssl/wolfcrypt/chacha20_poly1305.h @@ -61,7 +61,7 @@ enum { CHACHA20_POLY1305_STATE_INIT = 0, CHACHA20_POLY1305_STATE_READY = 1, CHACHA20_POLY1305_STATE_AAD = 2, - CHACHA20_POLY1305_STATE_DATA = 3, + CHACHA20_POLY1305_STATE_DATA = 3 }; typedef struct ChaChaPoly_Aead { diff --git a/wolfssl/wolfcrypt/dh.h b/wolfssl/wolfcrypt/dh.h index 0b48c5cf74e..e94cb593162 100644 --- a/wolfssl/wolfcrypt/dh.h +++ b/wolfssl/wolfcrypt/dh.h @@ -88,7 +88,7 @@ enum { WC_FFDHE_3072 = 257, WC_FFDHE_4096 = 258, WC_FFDHE_6144 = 259, - WC_FFDHE_8192 = 260, + WC_FFDHE_8192 = 260 }; /* DH Private Key size up to 8192 bit */ diff --git a/wolfssl/wolfcrypt/ecc.h b/wolfssl/wolfcrypt/ecc.h index 72fb2c5b384..2f02c4ad464 100644 --- a/wolfssl/wolfcrypt/ecc.h +++ b/wolfssl/wolfcrypt/ecc.h @@ -189,11 +189,11 @@ enum { ECC_POINT_UNCOMP = 0x04, /* Shamir's dual add constants */ - SHAMIR_PRECOMP_SZ = 16, + SHAMIR_PRECOMP_SZ = 16 #ifdef WOLF_PRIVATE_KEY_ID - ECC_MAX_ID_LEN = 32, - ECC_MAX_LABEL_LEN = 32, + ,ECC_MAX_ID_LEN = 32, + ECC_MAX_LABEL_LEN = 32 #endif }; @@ -413,7 +413,7 @@ typedef struct { enum { WC_ECC_FLAG_NONE = 0x00, WC_ECC_FLAG_COFACTOR = 0x01, - WC_ECC_FLAG_DEC_SIGN = 0x02, + WC_ECC_FLAG_DEC_SIGN = 0x02 }; /* ECC non-blocking */ diff --git a/wolfssl/wolfcrypt/hash.h b/wolfssl/wolfcrypt/hash.h index bf62ca8cf6c..ad3ae2ccbcf 100644 --- a/wolfssl/wolfcrypt/hash.h +++ b/wolfssl/wolfcrypt/hash.h @@ -82,9 +82,9 @@ enum wc_MACAlgorithm { enum wc_HashFlags { WC_HASH_FLAG_NONE = 0x00000000, WC_HASH_FLAG_WILLCOPY = 0x00000001, /* flag to indicate hash will be copied */ - WC_HASH_FLAG_ISCOPY = 0x00000002, /* hash is copy */ + WC_HASH_FLAG_ISCOPY = 0x00000002 /* hash is copy */ #ifdef WOLFSSL_SHA3 - WC_HASH_SHA3_KECCAK256 =0x00010000, /* Older KECCAK256 */ + ,WC_HASH_SHA3_KECCAK256 =0x00010000 /* Older KECCAK256 */ #endif }; diff --git a/wolfssl/wolfcrypt/hmac.h b/wolfssl/wolfcrypt/hmac.h index 86c97ebfbfe..d6db41aa13c 100644 --- a/wolfssl/wolfcrypt/hmac.h +++ b/wolfssl/wolfcrypt/hmac.h @@ -70,42 +70,42 @@ enum { HMAC_FIPS_MIN_KEY = 14, /* 112 bit key length minimum */ IPAD = 0x36, - OPAD = 0x5C, + OPAD = 0x5C /* If any hash is not enabled, add the ID here. */ #ifdef NO_MD5 - WC_MD5 = WC_HASH_TYPE_MD5, + ,WC_MD5 = WC_HASH_TYPE_MD5 #endif #ifdef NO_SHA - WC_SHA = WC_HASH_TYPE_SHA, + ,WC_SHA = WC_HASH_TYPE_SHA #endif #ifdef NO_SHA256 - WC_SHA256 = WC_HASH_TYPE_SHA256, + ,WC_SHA256 = WC_HASH_TYPE_SHA256 #endif #ifndef WOLFSSL_SHA512 - WC_SHA512 = WC_HASH_TYPE_SHA512, + ,WC_SHA512 = WC_HASH_TYPE_SHA512 #ifndef WOLFSSL_NOSHA512_224 - WC_SHA512_224 = WC_HASH_TYPE_SHA512_224, + ,WC_SHA512_224 = WC_HASH_TYPE_SHA512_224 #endif #ifndef WOLFSSL_NOSHA512_256 - WC_SHA512_256 = WC_HASH_TYPE_SHA512_256, + ,WC_SHA512_256 = WC_HASH_TYPE_SHA512_256 #endif #endif #ifndef WOLFSSL_SHA384 - WC_SHA384 = WC_HASH_TYPE_SHA384, + ,WC_SHA384 = WC_HASH_TYPE_SHA384 #endif #ifndef WOLFSSL_SHA224 - WC_SHA224 = WC_HASH_TYPE_SHA224, + ,WC_SHA224 = WC_HASH_TYPE_SHA224 #endif #ifndef WOLFSSL_SHA3 - WC_SHA3_224 = WC_HASH_TYPE_SHA3_224, + ,WC_SHA3_224 = WC_HASH_TYPE_SHA3_224, WC_SHA3_256 = WC_HASH_TYPE_SHA3_256, WC_SHA3_384 = WC_HASH_TYPE_SHA3_384, - WC_SHA3_512 = WC_HASH_TYPE_SHA3_512, + WC_SHA3_512 = WC_HASH_TYPE_SHA3_512 #endif #ifdef WOLF_PRIVATE_KEY_ID - HMAC_MAX_ID_LEN = 32, - HMAC_MAX_LABEL_LEN = 32, + ,HMAC_MAX_ID_LEN = 32, + HMAC_MAX_LABEL_LEN = 32 #endif }; diff --git a/wolfssl/wolfcrypt/poly1305.h b/wolfssl/wolfcrypt/poly1305.h index 0fd9d3c3056..c0a5b8dfc11 100644 --- a/wolfssl/wolfcrypt/poly1305.h +++ b/wolfssl/wolfcrypt/poly1305.h @@ -59,7 +59,7 @@ enum { POLY1305 = 7, POLY1305_BLOCK_SIZE = 16, - POLY1305_DIGEST_SIZE = 16, + POLY1305_DIGEST_SIZE = 16 }; #define WC_POLY1305_PAD_SZ 16 diff --git a/wolfssl/wolfcrypt/rsa.h b/wolfssl/wolfcrypt/rsa.h index 6d31aab558e..2cd78d7fd25 100644 --- a/wolfssl/wolfcrypt/rsa.h +++ b/wolfssl/wolfcrypt/rsa.h @@ -171,14 +171,15 @@ enum { RSA_PSS_PAD_TERM = 0xBC, #endif - RSA_PSS_SALT_LEN_DEFAULT = -1, + RSA_PSS_SALT_LEN_DEFAULT = -1 + #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER - RSA_PSS_SALT_LEN_DISCOVER = -2, + ,RSA_PSS_SALT_LEN_DISCOVER = -2 #endif #ifdef WOLF_PRIVATE_KEY_ID - RSA_MAX_ID_LEN = 32, - RSA_MAX_LABEL_LEN = 32, + ,RSA_MAX_ID_LEN = 32, + RSA_MAX_LABEL_LEN = 32 #endif }; diff --git a/wolfssl/wolfcrypt/signature.h b/wolfssl/wolfcrypt/signature.h index ca641571cae..697e5b598be 100644 --- a/wolfssl/wolfcrypt/signature.h +++ b/wolfssl/wolfcrypt/signature.h @@ -39,7 +39,7 @@ enum wc_SignatureType { WC_SIGNATURE_TYPE_NONE = 0, WC_SIGNATURE_TYPE_ECC = 1, WC_SIGNATURE_TYPE_RSA = 2, - WC_SIGNATURE_TYPE_RSA_W_ENC = 3, /* Adds DER header via wc_EncodeSignature */ + WC_SIGNATURE_TYPE_RSA_W_ENC = 3 /* Adds DER header via wc_EncodeSignature */ }; WOLFSSL_API int wc_SignatureGetSize(enum wc_SignatureType sig_type, diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 8e18d8c6385..6ea779b497a 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -971,7 +971,7 @@ typedef struct w64wrapper { DYNAMIC_TYPE_SNIFFER_PB_BUFFER = 1003, DYNAMIC_TYPE_SNIFFER_TICKET_ID = 1004, DYNAMIC_TYPE_SNIFFER_NAMED_KEY = 1005, - DYNAMIC_TYPE_SNIFFER_KEY = 1006, + DYNAMIC_TYPE_SNIFFER_KEY = 1006 }; /* max error buffer string size */ From 4e850f4773f93f7b1a076be192e7da9e87a1462e Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 4 Apr 2023 14:26:18 -0700 Subject: [PATCH 118/391] Better fixes for pedantic to resolve (`error: comparison of unsigned expression >= 0 is always true`). Also overlong lines. --- wolfcrypt/src/aes.c | 4 ++-- wolfcrypt/src/asn.c | 12 +++++++----- wolfcrypt/src/random.c | 8 ++++---- wolfssl/wolfcrypt/signature.h | 2 +- wolfssl/wolfcrypt/sp_int.h | 2 +- 5 files changed, 15 insertions(+), 13 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 2b3b038b35b..d7d577607b4 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -4563,8 +4563,8 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #if (defined(HAVE_AESGCM) && !defined(WC_NO_RNG)) || defined(HAVE_AESCCM) static WC_INLINE void IncCtr(byte* ctr, word32 ctrSz) { - word32 i; - for (i = ctrSz-1; i >= 0; i--) { + int i; + for (i = (int)ctrSz - 1; i >= 0; i--) { if (++ctr[i]) break; } diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 16ffce309b2..6fa615be842 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -8185,7 +8185,8 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz); } if (ret == 0) { - padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) & (blockSz - 1)); + padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) & + (blockSz - 1)); /* inner = OCT salt INT itt */ innerLen = 2 + saltSz + 2 + (itt < 256 ? 1 : 2); @@ -17309,7 +17310,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) } length -= (idx - lenStartIdx); /* check that strLen at index is not past input buffer */ - if (strLen + (int)idx > sz) { + if (strLen + idx > sz) { return BUFFER_E; } @@ -17444,12 +17445,12 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) cert->weOwnAltNames = 1; - if (length + (int)idx != sz) { + if (length + idx != sz) { ret = ASN_PARSE_E; } } - while ((ret == 0) && ((int)idx < sz)) { + while ((ret == 0) && (idx < sz)) { ASNGetData dataASN[altNameASN_Length]; /* Clear dynamic data items. */ @@ -18583,7 +18584,8 @@ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, return MEMORY_E; } - entry->name = (char*)XMALLOC((word32)strLength+1, heap, DYNAMIC_TYPE_ALTNAME); + entry->name = (char*)XMALLOC((word32)strLength+1, heap, + DYNAMIC_TYPE_ALTNAME); if (entry->name == NULL) { WOLFSSL_MSG("allocate error"); XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME); diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 0631efd9576..ee807d33c90 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -519,8 +519,8 @@ int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* seed, word32 seedSz) static WC_INLINE void array_add_one(byte* data, word32 dataSz) { - word32 i; - for (i = dataSz - 1; i >= 0; i--) { + int i; + for (i = (int)dataSz - 1; i >= 0; i--) { data[i]++; if (data[i] != 0) break; } @@ -618,11 +618,11 @@ static int Hash_gen(DRBG_internal* drbg, byte* out, word32 outSz, const byte* V) static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen) { if (dLen > 0 && sLen > 0 && dLen >= sLen) { - word32 sIdx, dIdx; + int sIdx, dIdx; word16 carry = 0; dIdx = dLen - 1; - for (sIdx = sLen - 1; sIdx >= 0; sIdx--) { + for (sIdx = (int)sLen - 1; sIdx >= 0; sIdx--) { carry += (word16)d[dIdx] + (word16)s[sIdx]; d[dIdx] = (byte)carry; carry >>= 8; diff --git a/wolfssl/wolfcrypt/signature.h b/wolfssl/wolfcrypt/signature.h index 697e5b598be..f712c0478af 100644 --- a/wolfssl/wolfcrypt/signature.h +++ b/wolfssl/wolfcrypt/signature.h @@ -39,7 +39,7 @@ enum wc_SignatureType { WC_SIGNATURE_TYPE_NONE = 0, WC_SIGNATURE_TYPE_ECC = 1, WC_SIGNATURE_TYPE_RSA = 2, - WC_SIGNATURE_TYPE_RSA_W_ENC = 3 /* Adds DER header via wc_EncodeSignature */ + WC_SIGNATURE_TYPE_RSA_W_ENC = 3 /* Adds DER header via wc_EncodeSignature */ }; WOLFSSL_API int wc_SignatureGetSize(enum wc_SignatureType sig_type, diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index 6d36248ffb8..413ad6c824f 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -672,7 +672,7 @@ typedef struct sp_ecc_ctx { unsigned int ii; \ for (ii = (a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ } \ - (a)->used = ii + 1; \ + (a)->used = (unsigned int)ii + 1; \ } while (0) /* Check the compiled and linked math implementation are the same. From e3316a10bd548b34f7bc9fb681d7ebc1ba78967f Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 4 Apr 2023 15:15:04 -0700 Subject: [PATCH 119/391] Fix `enum KeyWrap_Sum` impossible combinations (note: ugly code). --- wolfssl/wolfcrypt/asn.h | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 3d559cc9af2..cda516080db 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -1110,13 +1110,23 @@ enum KeyWrap_Sum { AES128_WRAP = 417 #endif #ifdef WOLFSSL_AES_192 - ,AES192_WRAP = 437 + #ifdef WOLFSSL_AES_128 + , + #endif + AES192_WRAP = 437 #endif #ifdef WOLFSSL_AES_256 - ,AES256_WRAP = 457 + #if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) + , + #endif + AES256_WRAP = 457 #endif #ifdef HAVE_PKCS7 - ,PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ + #if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) || \ + defined(WOLFSSL_AES_256) + , + #endif + PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ #endif }; #endif /* !NO_AES || PKCS7 */ From 786ea6f3b5e2be40c69c9acf5a762aff7303886c Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 10 Apr 2023 17:11:20 -0500 Subject: [PATCH 120/391] more fixes for implicit casts, including asn=template. --- wolfcrypt/benchmark/benchmark.c | 82 +++-- wolfcrypt/benchmark/benchmark.h | 6 +- wolfcrypt/src/asn.c | 594 ++++++++++++++++---------------- wolfcrypt/src/ecc.c | 126 +++---- wolfcrypt/src/hmac.c | 29 +- wolfcrypt/src/kdf.c | 15 +- wolfcrypt/src/misc.c | 9 +- wolfcrypt/src/random.c | 12 +- wolfcrypt/src/rsa.c | 77 +++-- wolfcrypt/src/sp_int.c | 22 +- wolfcrypt/src/wolfmath.c | 4 +- wolfssl/wolfcrypt/kdf.h | 4 +- wolfssl/wolfcrypt/misc.h | 1 + wolfssl/wolfcrypt/sp_int.h | 20 +- 14 files changed, 513 insertions(+), 488 deletions(-) diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 8001fd025ce..5885fa570e1 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -500,19 +500,19 @@ */ static int bench_all = 1; /* Cipher algorithms to benchmark. */ -static int bench_cipher_algs = 0; +static word32 bench_cipher_algs = 0; /* Digest algorithms to benchmark. */ -static int bench_digest_algs = 0; +static word32 bench_digest_algs = 0; /* MAC algorithms to benchmark. */ -static int bench_mac_algs = 0; +static word32 bench_mac_algs = 0; /* Asymmetric algorithms to benchmark. */ -static int bench_asym_algs = 0; +static word32 bench_asym_algs = 0; /* Post-Quantum Asymmetric algorithms to benchmark. */ -static int bench_pq_asym_algs = 0; +static word32 bench_pq_asym_algs = 0; /* Post-Quantum Asymmetric algorithms to benchmark. (Part 2)*/ -static int bench_pq_asym_algs2 = 0; +static word32 bench_pq_asym_algs2 = 0; /* Other cryptographic algorithms to benchmark. */ -static int bench_other_algs = 0; +static word32 bench_other_algs = 0; #if !defined(WOLFSSL_BENCHMARK_ALL) && !defined(NO_MAIN_DRIVER) @@ -907,10 +907,10 @@ static const char* bench_desc_words[][15] = { #define SHOW_INTEL_CYCLES(b, n, s) \ (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), " %s = %6.2f\n", \ bench_result_words1[lng_index][2], \ - count == 0 ? 0 : (float)total_cycles / ((word64)count*(s))) + count == 0 ? 0 : (double)total_cycles / ((word64)count*(s))) #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), "%.6f,\n", \ - count == 0 ? 0 : (float)total_cycles / ((word64)count*(s))) + count == 0 ? 0 : (double)total_cycles / ((word64)count*(s))) #elif defined(LINUX_CYCLE_COUNT) #include #include @@ -1323,15 +1323,15 @@ static const char* bench_result_words2[][5] = { while(options) { if (options & AAD_SIZE_DEFAULT) { aesAuthAddSz = AES_AUTH_ADD_SZ; - options &= ~AAD_SIZE_DEFAULT; + options &= ~(word32)AAD_SIZE_DEFAULT; } else if (options & AAD_SIZE_ZERO) { aesAuthAddSz = 0; - options &= ~AAD_SIZE_ZERO; + options &= ~(word32)AAD_SIZE_ZERO; } else if (options & AAD_SIZE_CUSTOM) { aesAuthAddSz = aes_aad_size; - options &= ~AAD_SIZE_CUSTOM; + options &= ~(word32)AAD_SIZE_CUSTOM; } fn(i); aesAuthAddSz = aesAuthAddSz_orig; @@ -1754,7 +1754,7 @@ static const char* get_blocktype_base10(double* blocks) /* countSz is number of bytes that 1 count represents. Normally bench_size, * except for AES direct that operates on AES_BLOCK_SIZE blocks */ static void bench_stats_sym_finish(const char* desc, int useDeviceID, - int count, int countSz, + int count, word32 countSz, double start, int ret) { double total, persec = 0, blocks = (double)count; @@ -1880,7 +1880,7 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, ESP_LOGV(TAG, "finish total_cycles = %llu", total_cycles); /* implement other cycle counters here */ #else - SHOW_INTEL_CYCLES_CSV(msg, sizeof(msg), countSz); + SHOW_INTEL_CYCLES_CSV(msg, sizeof(msg), (unsigned)countSz); #endif } /* if (csv_format == 1) */ @@ -1913,7 +1913,7 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, /* implement other architecture cycle counters here */ #else - SHOW_INTEL_CYCLES(msg, sizeof(msg), countSz); + SHOW_INTEL_CYCLES(msg, sizeof(msg), (unsigned)countSz); #endif } /* not CSV format */ @@ -3658,7 +3658,7 @@ static void bench_aesecb_internal(int useDeviceID, bench_stats_start(&count, &start); do { - int outer_loop_limit = ((bench_size / benchSz) * 10) + 1; + int outer_loop_limit = (((int)bench_size / benchSz) * 10) + 1; for (times = 0; times < outer_loop_limit /* numBlocks */ || pending > 0; ) { @@ -3700,7 +3700,7 @@ static void bench_aesecb_internal(int useDeviceID, bench_stats_start(&count, &start); do { - int outer_loop_limit = (10 * (bench_size / benchSz)) + 1; + int outer_loop_limit = (10 * ((int)bench_size / benchSz)) + 1; for (times = 0; times < outer_loop_limit || pending > 0; ) { bench_async_poll(&pending); @@ -5835,7 +5835,7 @@ void bench_blake2s(void) #ifdef WOLFSSL_CMAC -static void bench_cmac_helper(int keySz, const char* outMsg, int useDeviceID) +static void bench_cmac_helper(word32 keySz, const char* outMsg, int useDeviceID) { Cmac cmac; byte digest[AES_BLOCK_SIZE]; @@ -6180,7 +6180,7 @@ void bench_siphash(void) #ifndef NO_RSA #if defined(WOLFSSL_KEY_GEN) -static void bench_rsaKeyGen_helper(int useDeviceID, int keySz) +static void bench_rsaKeyGen_helper(int useDeviceID, word32 keySz) { RsaKey genKey[BENCH_MAX_PENDING]; double start; @@ -6207,7 +6207,7 @@ static void bench_rsaKeyGen_helper(int useDeviceID, int keySz) goto exit; } - ret = wc_MakeRsaKey(&genKey[i], keySz, rsa_e_val, &gRng); + ret = wc_MakeRsaKey(&genKey[i], (int)keySz, rsa_e_val, &gRng); if (!bench_async_handle(&ret, BENCH_ASYNC_GET_DEV(&genKey[i]), 0, ×, &pending)) { @@ -6219,7 +6219,7 @@ static void bench_rsaKeyGen_helper(int useDeviceID, int keySz) count += times; } while (bench_stats_check(start)); exit: - bench_stats_asym_finish("RSA", keySz, desc[2], useDeviceID, count, + bench_stats_asym_finish("RSA", (int)keySz, desc[2], useDeviceID, count, start, ret); /* cleanup */ @@ -6232,19 +6232,18 @@ void bench_rsaKeyGen(int useDeviceID) { int k; #if !defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) - const int keySizes[2] = {1024, 2048}; + static const word32 keySizes[2] = {1024, 2048}; #else - const int keySizes[1] = {2048}; + static const word32 keySizes[1] = {2048}; #endif for (k = 0; k < (int)(sizeof(keySizes)/sizeof(int)); k++) { - int keySz = keySizes[k]; - bench_rsaKeyGen_helper(useDeviceID, keySz); + bench_rsaKeyGen_helper(useDeviceID, keySizes[k]); } } -void bench_rsaKeyGen_size(int useDeviceID, int keySz) +void bench_rsaKeyGen_size(int useDeviceID, word32 keySz) { bench_rsaKeyGen_helper(useDeviceID, keySz); } @@ -6358,7 +6357,7 @@ static unsigned char rsa_3072_sig[] = { #endif /* WOLFSSL_RSA_VERIFY_INLINE || WOLFSSL_RSA_PUBLIC_ONLY */ static void bench_rsa_helper(int useDeviceID, RsaKey rsaKey[BENCH_MAX_PENDING], - int rsaKeySz) + word32 rsaKeySz) { int ret = 0, i, times, count = 0, pending = 0; word32 idx = 0; @@ -6437,7 +6436,7 @@ static void bench_rsa_helper(int useDeviceID, RsaKey rsaKey[BENCH_MAX_PENDING], count += times; } while (bench_stats_check(start)); exit_rsa_verify: - bench_stats_asym_finish("RSA", rsaKeySz, desc[0], + bench_stats_asym_finish("RSA", (int)rsaKeySz, desc[0], useDeviceID, count, start, ret); #endif /* !WOLFSSL_RSA_VERIFY_ONLY */ @@ -6473,7 +6472,7 @@ static void bench_rsa_helper(int useDeviceID, RsaKey rsaKey[BENCH_MAX_PENDING], count += times; } while (bench_stats_check(start)); exit_rsa_pub: - bench_stats_asym_finish("RSA", rsaKeySz, desc[1], + bench_stats_asym_finish("RSA", (int)rsaKeySz, desc[1], useDeviceID, count, start, ret); #endif /* !WOLFSSL_RSA_PUBLIC_ONLY */ } @@ -6503,7 +6502,7 @@ static void bench_rsa_helper(int useDeviceID, RsaKey rsaKey[BENCH_MAX_PENDING], count += times; } while (bench_stats_check(start)); exit_rsa_sign: - bench_stats_asym_finish("RSA", rsaKeySz, desc[4], useDeviceID, + bench_stats_asym_finish("RSA", (int)rsaKeySz, desc[4], useDeviceID, count, start, ret); if (ret < 0) { @@ -6560,7 +6559,7 @@ static void bench_rsa_helper(int useDeviceID, RsaKey rsaKey[BENCH_MAX_PENDING], } while (bench_stats_check(start)); exit_rsa_verifyinline: - bench_stats_asym_finish("RSA", rsaKeySz, desc[5], + bench_stats_asym_finish("RSA", (int)rsaKeySz, desc[5], useDeviceID, count, start, ret); } @@ -6580,7 +6579,7 @@ void bench_rsa(int useDeviceID) int i; RsaKey rsaKey[BENCH_MAX_PENDING]; int ret = 0; - int rsaKeySz = 0; + word32 rsaKeySz = 0; const byte* tmp; size_t bytes; #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY) @@ -6675,7 +6674,7 @@ void bench_rsa(int useDeviceID) #ifdef WOLFSSL_KEY_GEN /* bench any size of RSA key */ -void bench_rsa_key(int useDeviceID, int rsaKeySz) +void bench_rsa_key(int useDeviceID, word32 rsaKeySz) { int ret = 0, i, pending = 0; RsaKey rsaKey[BENCH_MAX_PENDING]; @@ -6706,7 +6705,7 @@ void bench_rsa_key(int useDeviceID, int rsaKeySz) } /* create the RSA key */ - ret = wc_MakeRsaKey(&rsaKey[i], rsaKeySz, exp, &gRng); + ret = wc_MakeRsaKey(&rsaKey[i], (int)rsaKeySz, exp, &gRng); if (ret == WC_PENDING_E) { isPending[i] = 1; pending = 1; @@ -7495,7 +7494,7 @@ void bench_eccEncrypt(int curveId) goto exit; for (i = 0; i < (int)sizeof(msg); i++) - msg[i] = i; + msg[i] = (byte)i; bench_stats_start(&count, &start); do { @@ -8931,12 +8930,12 @@ void bench_sphincsKeySign(byte level, byte optim) #endif /* HAVE_GET_CYCLES */ -void benchmark_configure(int block_size) +void benchmark_configure(word32 block_size) { /* must be greater than 0 */ if (block_size > 0) { - numBlocks = numBlocks * bench_size / block_size; - bench_size = (word32)block_size; + numBlocks = (int)((word32)numBlocks * bench_size / block_size); + bench_size = block_size; } } @@ -9065,8 +9064,7 @@ static void Usage(void) */ static int string_matches(const char* arg, const char* str) { - int len = (int)XSTRLEN(str) + 1; - return XSTRNCMP(arg, str, len) == 0; + return XSTRCMP(arg, str) == 0; } #endif /* MAIN_NO_ARGS */ @@ -9156,7 +9154,7 @@ int wolfcrypt_benchmark_main(int argc, char** argv) argc--; argv++; if (argc > 1) { - aes_aad_size = XATOI(argv[1]); + aes_aad_size = (word32)XATOI(argv[1]); aes_aad_options |= AAD_SIZE_CUSTOM; } } @@ -9298,7 +9296,7 @@ int wolfcrypt_benchmark_main(int argc, char** argv) } else { /* parse for block size */ - benchmark_configure(XATOI(argv[1])); + benchmark_configure((word32)XATOI(argv[1])); } argc--; argv++; diff --git a/wolfcrypt/benchmark/benchmark.h b/wolfcrypt/benchmark/benchmark.h index 3cc6aa8d501..a42b133de20 100644 --- a/wolfcrypt/benchmark/benchmark.h +++ b/wolfcrypt/benchmark/benchmark.h @@ -43,7 +43,7 @@ int wolfcrypt_benchmark_main(int argc, char** argv); /* individual benchmarks */ int benchmark_init(void); int benchmark_free(void); -void benchmark_configure(int block_size); +void benchmark_configure(word32 block_size); void bench_des(int useDeviceID); void bench_arc4(int useDeviceID); @@ -92,9 +92,9 @@ void bench_hmac_sha384(int useDeviceID); void bench_hmac_sha512(int useDeviceID); void bench_siphash(void); void bench_rsaKeyGen(int useDeviceID); -void bench_rsaKeyGen_size(int useDeviceID, int keySz); +void bench_rsaKeyGen_size(int useDeviceID, word32 keySz); void bench_rsa(int useDeviceID); -void bench_rsa_key(int useDeviceID, int keySz); +void bench_rsa_key(int useDeviceID, word32 keySz); void bench_dh(int useDeviceID); void bench_kyber(int type); void bench_ecc_curve(int curveId); diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 6fa615be842..73189b3c7c9 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -917,7 +917,7 @@ int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output) /* Add one for leading zero to make encoding a positive num. */ length += mp_leading_bit(data[i].data.mp) ? 1 : 0; /* Write out length. */ - idx += SetASNLength(length, out + idx); + idx += SetASNLength((word32)length, out + idx); /* Write out leading zero to make positive. */ if (mp_leading_bit(data[i].data.mp)) { out[idx++] = 0; @@ -947,7 +947,7 @@ int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output) /* Always one byte of data. */ out[idx++] = 1; /* TRUE = 0xff, FALSE = 0x00 */ - out[idx] = data[i].data.u8 ? -1 : 0; + out[idx] = data[i].data.u8 ? 0xffU : 0x00U; } else if (asn[i].tag == ASN_TAG_NULL) { /* NULL tag is always a zero length item. */ @@ -995,7 +995,7 @@ int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output) } } - return sz; + return (int)sz; } @@ -1142,7 +1142,7 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, *data->data.u16 = 0; for (i = 0; i < len; i++) { *data->data.u16 <<= 8; - *data->data.u16 |= input[idx + i] ; + *data->data.u16 |= input[idx + (word32)i] ; } break; case ASN_DATA_TYPE_WORD32: @@ -1157,7 +1157,7 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, *data->data.u32 = 0; for (i = 0; i < len; i++) { *data->data.u32 <<= 8; - *data->data.u32 |= input[idx + i] ; + *data->data.u32 |= input[idx + (word32)i] ; } break; @@ -1171,8 +1171,8 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, return ASN_PARSE_E; } /* Copy in data and record actual length seen. */ - XMEMCPY(data->data.buffer.data, input + idx, len); - *data->data.buffer.length = len; + XMEMCPY(data->data.buffer.data, input + idx, (size_t)len); + *data->data.buffer.length = (word32)len; break; case ASN_DATA_TYPE_EXP_BUFFER: @@ -1185,7 +1185,7 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, return ASN_PARSE_E; } /* Check data is same as expected. */ - if (XMEMCMP(data->data.ref.data, input + idx, len) != 0) { + if (XMEMCMP(data->data.ref.data, input + idx, (size_t)len) != 0) { #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE WOLFSSL_MSG("Data not as expected"); #endif @@ -1202,7 +1202,7 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, #endif return MP_INIT_E; } - err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx, len); + err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx, (word32)len); if (err != 0) { #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err); @@ -2865,7 +2865,7 @@ int SetASNInt(int len, byte firstByte, byte* output) len++; } /* Encode length - passing NULL for output will not encode. */ - idx += SetLength((word32)len, output ? output + idx : NULL); + idx += (int)SetLength((word32)len, output ? output + idx : NULL); /* Put out pre-pended 0 as well. */ if (firstByte & 0x80) { if (output) { @@ -3487,7 +3487,7 @@ static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx, /* Return tag, length and index after BER item header */ *pTag = tag; - *pLen = len; + *pLen = (word32)len; *idx = i; return 0; } @@ -3557,7 +3557,7 @@ static void IndefItems_AddData(IndefItems* items, word32 length) static void IndefItems_UpdateHeaderLen(IndefItems* items) { items->len[items->idx].headerLen += - SetLength(items->len[items->idx].len, NULL); + (int)SetLength(items->len[items->idx].len, NULL); } /* Go to indefinite parent of current item */ @@ -3583,11 +3583,11 @@ static void IndefItems_CalcLength(IndefItems* items) for (i = idx + 1; i < items->cnt; i++) { if (items->len[i].depth == items->depth) { - items->len[idx].len += items->len[i].headerLen; + items->len[idx].len += (word32)items->len[i].headerLen; items->len[idx].len += items->len[i].len; } } - items->len[idx].headerLen += SetLength(items->len[idx].len, NULL); + items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL); } /* Add more data to indefinite length item */ @@ -3658,7 +3658,7 @@ int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz) tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) && tag != (ASN_SET | ASN_CONSTRUCTED)) { /* Constructed basic type - get repeating tag */ - basic = tag & (~ASN_CONSTRUCTED); + basic = (byte)(tag & (~ASN_CONSTRUCTED)); /* Add up lengths of each item below */ for (; i < berSz; ) { @@ -3751,7 +3751,7 @@ int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz) if (indef) { if (der != NULL) { /* Check enough space for header */ - if (j + IndefItems_HeaderLen(indefItems) > *derSz) { + if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) { ret = BUFFER_E; goto end; } @@ -3760,14 +3760,14 @@ int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz) tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) && tag != (ASN_SET | ASN_CONSTRUCTED)) { /* Remove constructed tag for basic types */ - tag &= ~ASN_CONSTRUCTED; + tag &= (byte)~ASN_CONSTRUCTED; } /* Add tag and length */ der[j] = tag; (void)SetLength(IndefItems_Len(indefItems), der + j + 1); } /* Add header length of indefinite item */ - j += IndefItems_HeaderLen(indefItems); + j += (word32)IndefItems_HeaderLen(indefItems); if ((tag & 0xC0) == 0 && tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) && @@ -5572,7 +5572,7 @@ int SetObjectId(int len, byte* output) /* Skip tag. */ idx += ASN_TAG_SZ; /* Encode length - passing NULL for output will not encode. */ - idx += SetLength((word32)len, output ? output + idx : NULL); + idx += (int)SetLength((word32)len, output ? output + idx : NULL); /* Return index after header. */ return idx; @@ -6287,7 +6287,7 @@ size_t rsaIntOffset[] = { * @return A pointer to an mp_int when valid index. * @return NULL when invalid index. */ -static mp_int* GetRsaInt(RsaKey* key, byte idx) +static mp_int* GetRsaInt(RsaKey* key, int idx) { /* Cast key to byte array to and use offset to get to mp_int field. */ return (mp_int*)(((byte*)key) + rsaIntOffset[idx]); @@ -6525,9 +6525,9 @@ static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, } else if (ret == 0) { /* Not filling in key but do want key size. */ - *keySz = dataASN[(byte)RSAKEYASN_IDX_N].length; + *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length; /* Check whether first byte of data is 0x00 and drop it. */ - if (input[dataASN[(byte)RSAKEYASN_IDX_E].offset - *keySz] == 0) { + if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) { (*keySz)--; } } @@ -6847,7 +6847,7 @@ int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, /* Return index to start of internal key. */ *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input); /* Return value is length of internal key. */ - ret = dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length; + ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length; } FREE_ASNGETDATA(dataASN, NULL); @@ -6881,7 +6881,7 @@ int ToTraditional_ex(byte* input, word32 sz, word32* algId) if ((word32)length + inOutIdx > sz) return BUFFER_E; - XMEMMOVE(input, input + inOutIdx, length); + XMEMMOVE(input, input + inOutIdx, (size_t)length); return length; } @@ -7027,7 +7027,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, /* Only support default PKCS #8 format - v0. */ SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0); /* Set key OID that corresponds to key data. */ - SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], algoID, oidKeyType); + SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID, oidKeyType); if (curveOID != NULL && oidSz > 0) { /* ECC key and curveOID set to write. */ SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], curveOID, oidSz); @@ -7049,7 +7049,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, } if (ret == 0) { /* Always return the calculated size. */ - *outSz = sz; + *outSz = (word32)sz; } /* Check for buffer to encoded into. */ if ((ret == 0) && (out == NULL)) { @@ -8203,7 +8203,7 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, /* enc = OBJ enc_alg OCT iv */ encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz; /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */ - pbeLen = 2 + sizeof(pbes2) + 2 + 2 + kdfLen + 2 + encLen; + pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 + (size_t)encLen); ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz); } @@ -8229,7 +8229,7 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, /* Put Encrypted content in place. */ XMEMCPY(out + encIdx, key, keySz); if (padSz > 0) { - XMEMSET(out + encIdx + keySz, padSz, padSz); + XMEMSET(out + encIdx + keySz, (int)padSz, padSz); keySz += padSz; } @@ -8287,11 +8287,11 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, /* Encryption Algorithm Identifier */ idx += SetSequence(encLen, out + idx); idx += (word32)SetObjectId(encOidSz, out + idx); - XMEMCPY(out + idx, encOid, encOidSz); + XMEMCPY(out + idx, encOid, (size_t)encOidSz); idx += (word32)encOidSz; /* Encryption Algorithm Parameter: CBC IV */ idx += SetOctetString((word32)blockSz, out + idx); - XMEMCPY(out + idx, cbcIv, blockSz); + XMEMCPY(out + idx, cbcIv, (size_t)blockSz); idx += (word32)blockSz; } idx += SetOctetString(keySz, out + idx); @@ -8330,7 +8330,7 @@ int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password, ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password, passwordSz); if (ret > 0) { - XMEMMOVE(input, input + inOutIdx, ret); + XMEMMOVE(input, input + inOutIdx, (size_t)ret); } } @@ -8706,7 +8706,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz); /* Get the digest and encryption algorithm id. */ shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */ - id = dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum; + id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum; /* Convert encryption algorithm to a PBE algorithm if needed. */ CheckAlgoV2(id, &id, NULL); } @@ -8715,13 +8715,13 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) if (ret == 0) { /* Decrypt the key. */ - ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id, - key, keySz, version, cbcIv, 0, shaOid); + ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, (int)iterations, id, + key, (int)keySz, version, cbcIv, 0, (int)shaOid); } if (ret == 0) { /* Copy the decrypted key into the input (inline). */ XMEMMOVE(input, key, keySz); - ret = keySz; + ret = (int)keySz; } FREE_ASNGETDATA(dataASN, NULL); @@ -9067,7 +9067,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, if (ret == 0) { /* Setup data to go into encoding including PBE algorithm, salt, * iteration count, and padded key length. */ - SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], id, oidPBEType); + SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id, oidPBEType); if (salt == NULL || saltSz == 0) { salt = NULL; saltSz = PKCS5_SALT_SZ; @@ -9075,8 +9075,8 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, } SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT], salt, saltSz); - SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER], itt); - pkcs8Sz = Pkcs8Pad(NULL, inputSz, blockSz); + SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER], (word16)itt); + pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz); SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz); /* Calculate size of encoding. */ @@ -9087,7 +9087,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, } /* Return size when no output buffer. */ if ((ret == 0) && (out == NULL)) { - *outSz = sz; + *outSz = (word32)sz; ret = LENGTH_ONLY_E; } /* Check output buffer is big enough for encoded data. */ @@ -9113,11 +9113,11 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, byte* pkcs8 = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data; XMEMCPY(pkcs8, input, inputSz); - Pkcs8Pad(pkcs8, inputSz, blockSz); + Pkcs8Pad(pkcs8, (int)inputSz, blockSz); /* Encrypt PKCS#8 key inline. */ - ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id, pkcs8, - pkcs8Sz, version, cbcIv, 1, 0); + ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id, pkcs8, + (int)pkcs8Sz, version, cbcIv, 1, 0); } if (ret == 0) { /* Returning size on success. */ @@ -9983,7 +9983,7 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) /* Calculate the size of the DH parameters. */ ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz); if (output == NULL) { - *outSz = sz; + *outSz = (word32)sz; ret = LENGTH_ONLY_E; } /* Check buffer is big enough for encoding. */ @@ -9994,7 +9994,7 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) /* Encode the DH parameters into buffer. */ SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output); /* Set the actual encoding size. */ - *outSz = sz; + *outSz = (word32)sz; /* Return the actual encoding size. */ ret = sz; } @@ -10082,7 +10082,7 @@ int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz) ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz); } if ((ret == 0) && (output == NULL)) { - *outSz = sz; + *outSz = (word32)sz; ret = LENGTH_ONLY_E; } /* Check buffer is big enough for encoding. */ @@ -10093,7 +10093,7 @@ int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz) /* Encode the DH parameters into buffer. */ SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output); /* Set the actual encoding size. */ - *outSz = sz; + *outSz = (word32)sz; /* Return count of bytes written. */ ret = sz; } @@ -10408,7 +10408,7 @@ int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key, if (GetSequence(input, inOutIdx, &length, inSz) < 0) return ASN_PARSE_E; - maxIdx = (word32)(*inOutIdx + length); + maxIdx = (word32)(*inOutIdx + (word32)length); if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 || GetInt(&key->q, input, inOutIdx, maxIdx) < 0 || GetInt(&key->g, input, inOutIdx, maxIdx) < 0) @@ -10874,7 +10874,7 @@ int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header) */ int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen) { - return wc_SetDsaPublicKey(output, key, inLen, 1); + return wc_SetDsaPublicKey(output, key, (int)inLen, 1); } #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */ @@ -10993,7 +10993,7 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz); } if ((ret == 0) && (output == NULL)) { - *inLen = sz; + *inLen = (word32)sz; ret = LENGTH_ONLY_E; } /* Check buffer is big enough for encoding. */ @@ -11819,7 +11819,7 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, #ifndef NO_DSA case DSAk: cert->publicKey = source + pubIdx; - cert->pubKeySize = pubLen; + cert->pubKeySize = (word32)pubLen; ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap); break; #endif /* NO_DSA */ @@ -11878,7 +11878,7 @@ static int GetHashId(const byte* id, int length, byte* hash) int ret; if (length == KEYID_SIZE) { - XMEMCPY(hash, id, length); + XMEMCPY(hash, id, (size_t)length); ret = 0; } else { @@ -11904,7 +11904,7 @@ static int GetHashId(const byte* id, int length, byte* hash) *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val) /* Set the string length for a name component into the subject name. */ #define SetCertNameSubjectLen(cert, id, val) \ - *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (val) + *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val) /* Set the encoding for a name component into the subject name. */ #define SetCertNameSubjectEnc(cert, id, val) \ *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val) @@ -12353,7 +12353,7 @@ static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen, } if (ret == 0) { /* Allocate DNS Entry name - length of string plus 1 for NUL. */ - dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap, + dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (dnsEntry->name == NULL) { XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME); @@ -12364,7 +12364,7 @@ static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen, /* Set tag type, name length, name and NUL terminate name. */ dnsEntry->type = type; dnsEntry->len = strLen; - XMEMCPY(dnsEntry->name, str, strLen); + XMEMCPY(dnsEntry->name, str, (size_t)strLen); dnsEntry->name[strLen] = '\0'; #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) @@ -12395,7 +12395,7 @@ static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen, * @param [in] tag BER tag representing encoding of string. * @return 0 on success, negative values on failure. */ -static int SetSubject(DecodedCert* cert, int id, byte* str, word32 strLen, +static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen, byte tag) { int ret = 0; @@ -12403,8 +12403,8 @@ static int SetSubject(DecodedCert* cert, int id, byte* str, word32 strLen, /* Put string and encoding into certificate. */ if (id == ASN_COMMON_NAME) { cert->subjectCN = (char *)str; - cert->subjectCNLen = strLen; - cert->subjectCNEnc = tag; + cert->subjectCNLen = (int)strLen; + cert->subjectCNEnc = (char)tag; } #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) { @@ -12426,12 +12426,12 @@ static int SetSubject(DecodedCert* cert, int id, byte* str, word32 strLen, else if (id == ASN_JURIS_C) { cert->subjectJC = (char*)str; cert->subjectJCLen = strLen; - cert->subjectJCEnc = tag; + cert->subjectJCEnc = (char)tag; } else if (id == ASN_JURIS_ST) { cert->subjectJS = (char*)str; cert->subjectJSLen = strLen; - cert->subjectJSEnc = tag; + cert->subjectJSEnc = (char)tag; } #endif @@ -12556,7 +12556,7 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, if (isSubject) { /* Store subject field components. */ - ret = SetSubject(cert, id, str, strLen, tag); + ret = SetSubject(cert, id, str, (int)strLen, tag); } if (ret == 0) { /* Check there is space for this in the full name string and @@ -13482,7 +13482,7 @@ int GetName(DecodedCert* cert, int nameType, int maxIdx) /* Initialize for data and don't check optional prefix OID. */ GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType); ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0, - cert->source, &idx, maxIdx); + cert->source, &idx, (word32)maxIdx); if (ret == 0) { char* full; byte* hash; @@ -13521,8 +13521,8 @@ static WC_INLINE int GetTime(int* value, const byte* date, int* idx) return ASN_PARSE_E; } - *value += btoi(date[i++]) * 10; - *value += btoi(date[i++]); + *value += (int)btoi(date[i++]) * 10; + *value += (int)btoi(date[i++]); *idx = i; @@ -13677,7 +13677,7 @@ int GetAsnTimeString(void* currTime, byte* buf, word32 len) { byte* data_ptr = buf; byte uf_time[ASN_GENERALIZED_TIME_SIZE]; - word32 data_len = 0; + int data_len = 0; WOLFSSL_ENTER("GetAsnTimeString"); @@ -13687,11 +13687,11 @@ int GetAsnTimeString(void* currTime, byte* buf, word32 len) XMEMSET(uf_time, 0, sizeof(uf_time)); /* GetFormattedTime returns length with null terminator */ data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time)); - if ((int)data_len <= 0) { + if (data_len <= 0) { return ASN_TIME_E; } /* ensure room to add 2 bytes (ASN type and length) before proceeding */ - else if (len < data_len + 2) { + else if (len < (word32)data_len + 2) { return BUFFER_E; } @@ -14069,7 +14069,7 @@ static int GetDateInfo(const byte* source, word32* idx, const byte** pDate, *pDate = dataASN[i].data.ref.data; } if (pLength != NULL) { - *pLength = dataASN[i].data.ref.length; + *pLength = (int)dataASN[i].data.ref.length; } } @@ -14311,7 +14311,7 @@ int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate) ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0); if (ret >= 0) { /* Store current index: public key. */ - cert->srcIdx = ret; + cert->srcIdx = (word32)ret; } return ret; #endif /* WOLFSSL_ASN_TEMPLATE */ @@ -14589,7 +14589,7 @@ static int SetCurve(ecc_key* key, byte* output, size_t outSz) #else XMEMCPY(output+idx, key->dp->oid, oidSz); #endif - idx += oidSz; + idx += (int)oidSz; return idx; } @@ -14604,7 +14604,7 @@ static int SetCurve(ecc_key* key, byte* output, size_t outSz) * @return 1 when algorithm is using ECDSA. * @return 0 otherwise. */ -static WC_INLINE int IsSigAlgoECDSA(int algoOID) +static WC_INLINE int IsSigAlgoECDSA(word32 algoOID) { /* ECDSA sigAlgo must not have ASN1 NULL parameters */ if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA || @@ -14623,7 +14623,7 @@ static WC_INLINE int IsSigAlgoECDSA(int algoOID) * @return 1 when is EC signing algorithm. * @return 0 otherwise. */ -static WC_INLINE int IsSigAlgoECC(int algoOID) +static WC_INLINE int IsSigAlgoECC(word32 algoOID) { (void)algoOID; @@ -14729,16 +14729,16 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL); - algoName = OidFromId(algoOID, type, &algoSz); + algoName = OidFromId((word32)algoOID, (word32)type, &algoSz); if (algoName == NULL) { WOLFSSL_MSG("Unknown Algorithm"); } else { /* Set the OID and OID type to encode. */ - SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], algoOID, type); + SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type); /* Hashes, signatures not ECC and keys not RSA output NULL tag. */ if (!(type == oidHashType || - (type == oidSigType && !IsSigAlgoECC(algoOID)) || + (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) || (type == oidKeyType && algoOID == RSAk))) { /* Don't put out NULL DER item. */ dataASN[ALGOIDASN_IDX_NULL].noOut = 1; @@ -14752,19 +14752,19 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) dataASN[ALGOIDASN_IDX_NULL].noOut = 0; /* Include space for extra data of length curveSz. * Subtract 1 for sequence and 1 for length encoding. */ - SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL, curveSz - 2); + SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL, (word32)curveSz - 2); } /* Calculate size of encoding. */ - ret = SizeASN_Items(algoIdASN + o, dataASN + o, algoIdASN_Length - o, + ret = SizeASN_Items(algoIdASN + o, dataASN + o, (int)algoIdASN_Length - (int)o, &sz); if (ret == 0 && output != NULL) { /* Encode into buffer. */ - SetASN_Items(algoIdASN + o, dataASN + o, algoIdASN_Length - o, + SetASN_Items(algoIdASN + o, dataASN + o, (int)algoIdASN_Length - (int)o, output); if (curveSz > 0) { /* Return size excluding curve data. */ - sz = dataASN[o].offset - dataASN[ALGOIDASN_IDX_NULL].offset; + sz = (int)(dataASN[o].offset - dataASN[ALGOIDASN_IDX_NULL].offset); } } @@ -14779,7 +14779,7 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) } FREE_ASNSETDATA(dataASN, NULL); - return ret; + return (word32)ret; #endif /* WOLFSSL_ASN_TEMPLATE */ } @@ -14845,7 +14845,7 @@ word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz, if (ret == 0) { /* Set hash OID and type. */ - SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], hashOID, oidHashType); + SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID, oidHashType); /* Set digest. */ if (digest == out) { XMEMCPY(dgst, digest, digSz); @@ -14867,7 +14867,7 @@ word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz, } FREE_ASNSETDATA(dataASN, NULL); - return ret; + return (word32)ret; #endif } @@ -15893,7 +15893,7 @@ static int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->pkCbEcc) { ret = sigCtx->pkCbEcc( sig, sigSz, - sigCtx->digest, sigCtx->digestSz, + sigCtx->digest, (unsigned int)sigCtx->digestSz, key, keySz, &sigCtx->verify, sigCtx->pkCtxEcc); } @@ -16596,7 +16596,7 @@ static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert) /* Copy, into cert HW type OID */ XMEMCPY(cert->hwType, dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen); - cert->hwTypeSz = oidLen; + cert->hwTypeSz = (int)oidLen; /* TODO: check this is the HW serial number OID - no test data. */ /* Allocate space for HW serial number. */ @@ -16612,7 +16612,7 @@ static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert) XMEMCPY(cert->hwSerialNum, dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen); cert->hwSerialNum[serialLen] = '\0'; - cert->hwSerialNumSz = serialLen; + cert->hwSerialNumSz = (int)serialLen; } return ret; } @@ -16643,7 +16643,7 @@ static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid) } if (ret == 0) { - ret = SetDNSEntry(cert, buf, bufLen, ASN_OTHER_TYPE, &entry); + ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry); if (ret == 0) { #ifdef WOLFSSL_FPKI entry->oidSum = oid; @@ -16699,7 +16699,7 @@ static int DecodeOtherName(DecodedCert* cert, const byte* input, #endif /* WOLFSSL_FPKI */ case UPN_OID: ret = DecodeOtherHelper(dataASN, cert, - dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum); + (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum); break; default: WOLFSSL_MSG("\tunsupported OID skipping"); @@ -16737,7 +16737,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE, &cert->altNames); if (ret == 0) { - idx += len; + idx += (word32)len; } } #ifndef IGNORE_NAME_CONSTRAINTS @@ -16747,7 +16747,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, word32 idxDir = idx; /* Expecting a SEQUENCE using up all data. */ - if (GetASN_Sequence(input, &idxDir, &strLen, idx + len, 1) < 0) { + if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0) { WOLFSSL_MSG("\tfail: seq length"); return ASN_PARSE_E; } @@ -16755,7 +16755,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen, ASN_DIR_TYPE, &cert->altDirNames); if (ret == 0) { - idx += len; + idx += (word32)len; } } /* GeneralName choice: rfc822Name */ @@ -16763,7 +16763,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_RFC822_TYPE, &cert->altEmailNames); if (ret == 0) { - idx += len; + idx += (word32)len; } } /* GeneralName choice: uniformResourceIdentifier */ @@ -16782,10 +16782,10 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, /* skip past scheme (i.e http,ftp,...) finding first ':' char */ for (i = 0; i < len; i++) { - if (input[idx + i] == ':') { + if (input[idx + (word32)i] == ':') { break; } - if (input[idx + i] == '/') { + if (input[idx + (word32)i] == '/') { i = len; /* error, found relative path since '/' was * encountered before ':'. Returning error * value in next if statement. */ @@ -16800,7 +16800,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, } /* test if scheme is missing */ - if (input[idx + i] != ':') { + if (input[idx + (word32)i] != ':') { WOLFSSL_MSG("\tAlt Name must be absolute URI"); WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E); return ASN_ALT_NAME_E; @@ -16811,7 +16811,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE, &cert->altNames); if (ret == 0) { - idx += len; + idx += (word32)len; } } #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \ @@ -16830,14 +16830,14 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, /* GeneralName choice: otherName */ else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) { /* TODO: test data for code path */ - ret = DecodeOtherName(cert, input, &idx, idx + len); + ret = DecodeOtherName(cert, input, &idx, idx + (word32)len); } #endif /* GeneralName choice: dNSName, x400Address, ediPartyName, * registeredID */ else { WOLFSSL_MSG("\tUnsupported name type, skipping"); - idx += len; + idx += (word32)len; } if (ret == 0) { @@ -17445,7 +17445,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) cert->weOwnAltNames = 1; - if (length + idx != sz) { + if ((word32)length + idx != sz) { ret = ASN_PARSE_E; } } @@ -17462,7 +17462,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) &idx, sz); if (ret == 0) { ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag, - dataASN[ALTNAMEASN_IDX_GN].length, cert); + (int)dataASN[ALTNAMEASN_IDX_GN].length, cert); } } @@ -17568,7 +17568,7 @@ static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert) GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength); ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input, - &idx, sz); + &idx, (word32)sz); } /* Empty SEQUENCE is OK - nothing to store. */ @@ -17587,7 +17587,7 @@ static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert) /* Store CA boolean and whether a path length was seen. */ if (ret == 0) { /* isCA in certificate is a 1 bit of a byte. */ - cert->isCA = isCA; + cert->isCA = isCA ? 1 : 0; cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0); } } @@ -17818,7 +17818,7 @@ static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert) CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap); cert->extCrlInfoRaw = input; - cert->extCrlInfoRawSz = sz; + cert->extCrlInfoRawSz = (int)sz; if (ret == 0) { /* Get the GeneralName choice */ @@ -17833,7 +17833,7 @@ static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert) word32 sz32; GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], &cert->extCrlInfo, &sz32); - cert->extCrlInfoSz = sz32; + cert->extCrlInfoSz = (int)sz32; } #ifdef CRLDP_VALIDATE_DATA @@ -17987,7 +17987,7 @@ static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert) /* Store URI for OCSP lookup. */ GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC], &cert->extAuthInfo, &sz32); - cert->extAuthInfoSz = sz32; + cert->extAuthInfoSz = (int)sz32; #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) count++; #else @@ -18123,7 +18123,7 @@ static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert) /* Get the hash or hash of the hash if wrong size. */ ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data, - dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length, + (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length, cert->extAuthKeyId); } } @@ -18463,7 +18463,7 @@ enum { * @return MEMORY_E when dynamic memory allocation fails. * @return ASN_PARSE_E when SEQUENCE is not found as expected. */ -static int DecodeSubtreeGeneralName(const byte* input, int sz, byte tag, +static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag, Base_entry** head, void* heap) { Base_entry* entry; @@ -18481,7 +18481,7 @@ static int DecodeSubtreeGeneralName(const byte* input, int sz, byte tag, ret = ASN_PARSE_E; } else { - len = strLen; + len = (word32)strLen; ret = 0; } } @@ -18506,7 +18506,7 @@ static int DecodeSubtreeGeneralName(const byte* input, int sz, byte tag, /* Store name, size and tag in object. */ XMEMCPY(entry->name, &input[nameIdx], len); entry->name[len] = '\0'; - entry->nameSz = len; + entry->nameSz = (int)len; entry->type = tag & ASN_TYPE_MASK; /* Put entry at front of linked list. */ @@ -18974,7 +18974,7 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) #endif /* Strip SEQUENCE OF and check using all data. */ - if (GetASN_Sequence(input, &idx, &total_length, sz, 1) < 0) { + if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0) { ret = ASN_PARSE_E; } } @@ -18993,7 +18993,7 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) XMEMSET(dataASN, 0, sizeof(dataASN)); GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType); ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1, - input, &idx, sz); + input, &idx, (word32)sz); if (ret == 0) { /* Get the OID. */ GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length); @@ -19013,7 +19013,7 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) } if (ret == 0) { /* Store device type data and length. */ - cert->deviceTypeSz = length; + cert->deviceTypeSz = (int)length; XMEMCPY(cert->deviceType, data, length); break; } @@ -19347,7 +19347,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, /* Basic Constraints. */ case BASIC_CA_OID: VERIFY_AND_SET_OID(cert->extBasicConstSet); - cert->extBasicConstCrit = critical; + cert->extBasicConstCrit = critical ? 1 : 0; if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) { ret = ASN_PARSE_E; } @@ -19356,7 +19356,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, /* CRL Distribution point. */ case CRL_DIST_OID: VERIFY_AND_SET_OID(cert->extCRLdistSet); - cert->extCRLdistCrit = critical; + cert->extCRLdistCrit = critical ? 1 : 0; if (DecodeCrlDist(input, length, cert) < 0) { ret = ASN_PARSE_E; } @@ -19365,7 +19365,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, /* Authority information access. */ case AUTH_INFO_OID: VERIFY_AND_SET_OID(cert->extAuthInfoSet); - cert->extAuthInfoCrit = critical; + cert->extAuthInfoCrit = critical ? 1 : 0; if (DecodeAuthInfo(input, length, cert) < 0) { ret = ASN_PARSE_E; } @@ -19374,14 +19374,14 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, /* Subject alternative name. */ case ALT_NAMES_OID: VERIFY_AND_SET_OID(cert->extSubjAltNameSet); - cert->extSubjAltNameCrit = critical; + cert->extSubjAltNameCrit = critical ? 1 : 0; ret = DecodeAltNames(input, length, cert); break; /* Authority Key Identifier. */ case AUTH_KEY_OID: VERIFY_AND_SET_OID(cert->extAuthKeyIdSet); - cert->extAuthKeyIdCrit = critical; + cert->extAuthKeyIdCrit = critical ? 1 : 0; #ifndef WOLFSSL_ALLOW_CRIT_SKID /* This check is added due to RFC 5280 section 4.2.1.1 * stating that conforming CA's must mark this extension @@ -19401,7 +19401,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, /* Subject Key Identifier. */ case SUBJ_KEY_OID: VERIFY_AND_SET_OID(cert->extSubjKeyIdSet); - cert->extSubjKeyIdCrit = critical; + cert->extSubjKeyIdCrit = critical ? 1 : 0; #ifndef WOLFSSL_ALLOW_CRIT_SKID /* This check is added due to RFC 5280 section 4.2.1.2 * stating that conforming CA's must mark this extension @@ -19425,12 +19425,12 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, VERIFY_AND_SET_OID(cert->extCertPolicySet); #if defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL) - cert->extCertPolicyCrit = critical; + cert->extCertPolicyCrit = critical ? 1 : 0; #endif #endif #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \ defined(WOLFSSL_QT) - if (DecodeCertPolicy(input, length, cert) < 0) { + if (DecodeCertPolicy(input, (int)length, cert) < 0) { ret = ASN_PARSE_E; } #else @@ -19441,7 +19441,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, /* Key usage. */ case KEY_USAGE_OID: VERIFY_AND_SET_OID(cert->extKeyUsageSet); - cert->extKeyUsageCrit = critical; + cert->extKeyUsageCrit = critical ? 1 : 0; if (DecodeKeyUsage(input, length, cert) < 0) { ret = ASN_PARSE_E; } @@ -19450,7 +19450,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, /* Extended key usage. */ case EXT_KEY_USAGE_OID: VERIFY_AND_SET_OID(cert->extExtKeyUsageSet); - cert->extExtKeyUsageCrit = critical; + cert->extExtKeyUsageCrit = critical ? 1 : 0; if (DecodeExtKeyUsage(input, length, cert) < 0) { ret = ASN_PARSE_E; } @@ -19470,7 +19470,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, } #endif VERIFY_AND_SET_OID(cert->extNameConstraintSet); - cert->extNameConstraintCrit = critical; + cert->extNameConstraintCrit = critical ? 1 : 0; if (DecodeNameConstraints(input, length, cert) < 0) { ret = ASN_PARSE_E; } @@ -19502,7 +19502,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, #endif case POLICY_CONST_OID: VERIFY_AND_SET_OID(cert->extPolicyConstSet); - cert->extPolicyConstCrit = critical; + cert->extPolicyConstCrit = critical ? 1 : 0; if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0) return ASN_PARSE_E; break; @@ -19719,7 +19719,7 @@ static int DecodeCertExtensions(DecodedCert* cert) XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN)); /* Parse extensions header. */ ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset, - certExtHdrASN_Length - offset, 0, input, &idx, sz); + (int)(certExtHdrASN_Length - (size_t)offset), 0, input, &idx, (word32)sz); } /* Parse each extension. */ while ((ret == 0) && (idx < (word32)sz)) { @@ -19734,10 +19734,10 @@ static int DecodeCertExtensions(DecodedCert* cert) GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical); /* Parse extension wrapper. */ ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input, - &idx, sz); + &idx, (word32)sz); if (ret == 0) { word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum; - int length = dataASN[CERTEXTASN_IDX_VAL].length; + word32 length = dataASN[CERTEXTASN_IDX_VAL].length; /* Decode the extension by type. */ ret = DecodeExtensionType(input + idx, length, oid, critical, cert, @@ -20015,7 +20015,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, /* Set fields extracted from data. */ cert->version = version; - cert->serialSz = serialSz; + cert->serialSz = (int)serialSz; cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum; cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum; cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset; @@ -20031,7 +20031,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, } /* Store reference to BEFOREdate. */ cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source); - cert->beforeDateLen = GetASNItem_Length(dataASN[i], cert->source); + cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source); /* Find the item with the AFTER date and check it. */ i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0) @@ -20042,7 +20042,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, } /* Store reference to AFTER date. */ cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source); - cert->afterDateLen = GetASNItem_Length(dataASN[i], cert->source); + cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source); /* Get the issuer name and calculate hash. */ idx = dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset; @@ -20076,7 +20076,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, if (badDateRet != NULL) { *badDateRet = badDate; } - ret = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset; + ret = (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset; done = 1; } } @@ -20176,7 +20176,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, /* Save references to extension data. */ cert->extensions = GetASNItem_Addr( dataASN[X509CERTASN_IDX_TBS_EXT], cert->source); - cert->extensionsSz = GetASNItem_Length( + cert->extensionsSz = (int)GetASNItem_Length( dataASN[X509CERTASN_IDX_TBS_EXT], cert->source); cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset; @@ -20305,7 +20305,7 @@ static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt, cert->contentType = (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data; cert->contentTypeLen = - strDataASN[STRATTRASN_IDX_STR].data.ref.length; + (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length; } break; @@ -20323,7 +20323,7 @@ static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt, /* Store references to password data. */ cert->cPwd = (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data; - cert->cPwdLen = strDataASN[STRATTRASN_IDX_STR].data.ref.length; + cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length; } break; @@ -20342,10 +20342,10 @@ static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt, /* Store references to serial number. */ cert->sNum = (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data; - cert->sNumLen = strDataASN[STRATTRASN_IDX_STR].data.ref.length; + cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length; /* Store serial number if small enough. */ if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) { - XMEMCPY(cert->serial, cert->sNum, cert->sNumLen); + XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen); cert->serialSz = cert->sNumLen; } } @@ -20357,7 +20357,7 @@ static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt, case EXTENSION_REQUEST_OID: /* Store references to all extensions. */ cert->extensions = input; - cert->extensionsSz = maxIdx; + cert->extensionsSz = (int)maxIdx; cert->extensionsIdx = aIdx; /* Decode and validate extensions. */ @@ -20601,7 +20601,7 @@ int ParseCert(DecodedCert* cert, int type, int verify, void* cm) DYNAMIC_TYPE_SUBJECT_CN); if (ptr == NULL) return MEMORY_E; - XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen); + XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen); ptr[cert->subjectCNLen] = '\0'; cert->subjectCN = ptr; cert->subjectCNStored = 1; @@ -22133,7 +22133,7 @@ int SetSerialNumber(const byte* sn, word32 snSz, byte* output, /* write out ASN.1 Integer */ (void)SetASNInt(snSzInt, sn[0], output); - XMEMCPY(output + i, sn, snSzInt); + XMEMCPY(output + i, sn, (size_t)snSzInt); /* compute final length */ i += snSzInt; @@ -22676,7 +22676,7 @@ int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer, /* get cipher name */ if (NAME_SZ < (finish - start)) /* buffer size of info->name */ return BUFFER_E; - if (XMEMCPY(info->name, start, finish - start) == NULL) + if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL) return BUFFER_E; info->name[finish - start] = '\0'; /* null term */ @@ -22735,7 +22735,7 @@ static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo) XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15); XSTRNCAT(dest, kDecInfoHeader, 9); XSTRNCAT(dest, ": ", 3); - XSTRNCAT(dest, cipherInfo, destSz - (int)XSTRLEN(dest) - 1); + XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1); XSTRNCAT(dest, "\n\n", 4); } } @@ -22796,9 +22796,9 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, #endif /* build header and footer based on type */ - XSTRNCPY(header, headerStr, headerLen - 1); + XSTRNCPY(header, headerStr, (size_t)headerLen - 1); header[headerLen - 2] = 0; - XSTRNCPY(footer, footerStr, footerLen - 1); + XSTRNCPY(footer, footerStr, (size_t)footerLen - 1); footer[footerLen - 2] = 0; /* add new line to end */ @@ -22843,7 +22843,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, } /* don't even try if outSz too short */ - if (outSz < headerLen + footerLen + derSz) { + if (outSz < (word32)headerLen + (word32)footerLen + derSz) { #ifdef WOLFSSL_SMALL_STACK XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER); XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -22852,7 +22852,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, } /* header */ - XMEMCPY(output, header, headerLen); + XMEMCPY(output, header, (size_t)headerLen); i = headerLen; #ifdef WOLFSSL_SMALL_STACK @@ -22860,7 +22860,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, #endif /* body */ - outLen = outSz - (headerLen + footerLen); /* input to Base64_Encode */ + outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */ if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -22877,7 +22877,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, #endif return BAD_FUNC_ARG; } - XMEMCPY(output + i, footer, footerLen); + XMEMCPY(output + i, footer, (size_t)footerLen); #ifdef WOLFSSL_SMALL_STACK XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -23105,7 +23105,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, #ifdef WOLFSSL_ENCRYPTED_KEYS if (info) { - ret = wc_EncryptedInfoParse(info, &headerEnd, bufferEnd - headerEnd); + ret = wc_EncryptedInfoParse(info, &headerEnd, (size_t)(bufferEnd - headerEnd)); if (ret < 0) return ret; if (info->set) @@ -23213,7 +23213,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, password, passwordSz); if (ret > 0) { /* update length by decrypted content */ - der->length = ret; + der->length = (word32)ret; idx = 0; /* detect pkcs8 key and get alg type */ /* keep PKCS8 header */ @@ -23221,7 +23221,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, &algId); if (ret >= 0) { if (keyFormat) - *keyFormat = algId; + *keyFormat = (int)algId; ret = 0; } } @@ -23266,7 +23266,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, (der->length % DES_BLOCK_SIZE) != 0) { padVal = der->buffer[der->length-1]; if (padVal < DES_BLOCK_SIZE) { - der->length -= padVal; + der->length -= (word32)padVal; } } } @@ -23277,7 +23277,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, if (der->length > AES_BLOCK_SIZE) { padVal = der->buffer[der->length-1]; if (padVal <= AES_BLOCK_SIZE) { - der->length -= padVal; + der->length -= (word32)padVal; } } } @@ -23290,7 +23290,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, PEMerr(0, PEM_R_BAD_DECRYPT); } #endif - ForceZero(password, passwordSz); + ForceZero(password, (word32)passwordSz); } #ifdef OPENSSL_EXTRA else { @@ -23336,8 +23336,8 @@ static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata) if (userdata == NULL) return 0; - XSTRNCPY(passwd, (char*)userdata, sz); - return min((word32)sz, (word32)XSTRLEN((char*)userdata)); + XSTRNCPY(passwd, (char*)userdata, (size_t)sz); + return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata)); } #endif @@ -23468,11 +23468,11 @@ int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz, } else if (buff == NULL) { WOLFSSL_MSG("Return needed der buff length"); - ret = der->length; + ret = (int)der->length; } else if (der->length <= (word32)buffSz) { XMEMCPY(buff, der->buffer, der->length); - ret = der->length; + ret = (int)der->length; } else { WOLFSSL_MSG("Bad der length"); @@ -23534,7 +23534,7 @@ int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der) else #endif { - fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE); + fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE); if (fileBuf == NULL) ret = MEMORY_E; else @@ -23542,7 +23542,7 @@ int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der) } } if (ret == 0) { - if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) { + if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) { ret = IO_FAILED_E; } else { @@ -23566,7 +23566,7 @@ int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz) if (ret == 0) { if (converted->length < (word32)derSz) { XMEMCPY(derBuf, converted->buffer, converted->length); - ret = converted->length; + ret = (int)converted->length; } else ret = BUFFER_E; @@ -23625,7 +23625,7 @@ int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der) else #endif { - fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE); + fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE); if (fileBuf == NULL) ret = MEMORY_E; else @@ -23633,7 +23633,7 @@ int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der) } } if (ret == 0) { - if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) { + if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) { ret = BUFFER_E; } else { @@ -23659,7 +23659,7 @@ int wc_PemPubKeyToDer(const char* fileName, if (ret == 0) { if (converted->length < (word32)derSz) { XMEMCPY(derBuf, converted->buffer, converted->length); - ret = converted->length; + ret = (int)converted->length; } else ret = BUFFER_E; @@ -23954,7 +23954,7 @@ static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen, #endif /* Calculate size of RSA public key. */ ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o, - rsaPublicKeyASN_Length - o, &sz); + (int)rsaPublicKeyASN_Length - o, &sz); } /* Check output buffer is big enough for encoding. */ if ((ret == 0) && (output != NULL) && (sz > outLen)) { @@ -23963,7 +23963,7 @@ static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen, if ((ret == 0) && (output != NULL)) { /* Encode RSA public key. */ SetASN_Items(rsaPublicKeyASN + o, dataASN + o, - rsaPublicKeyASN_Length - o, output); + (int)rsaPublicKeyASN_Length - o, output); } if (ret == 0) { /* Return size of encoding. */ @@ -24008,7 +24008,7 @@ int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header) */ int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen) { - return SetRsaPublicKey(output, key, inLen, 1); + return SetRsaPublicKey(output, key, (int)inLen, 1); } /* Returns public DER version of the RSA key. If with_header is 0 then only a @@ -24016,7 +24016,7 @@ int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen) int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen, int with_header) { - return SetRsaPublicKey(output, key, inLen, with_header); + return SetRsaPublicKey(output, key, (int)inLen, with_header); } #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA || @@ -24058,7 +24058,7 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) /* write all big ints from key to DER tmps */ for (i = 0; i < RSA_INTS; i++) { - mp_int* keyInt = GetRsaInt(key, (byte)i); + mp_int* keyInt = GetRsaInt(key, i); rawLen = mp_unsigned_bin_size(keyInt) + 1; if (output != NULL) { @@ -24599,7 +24599,7 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, oidKeyType); /* Set the curve OID. */ SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID], - NULL, curveIdSz); + NULL, (word32)curveIdSz); /* Don't try to write out explicit parameters. */ dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1; /* Set size of public point to ensure space is made for it. */ @@ -24618,7 +24618,7 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, output); /* Skip to where public point is to be encoded. */ - output += sz - pubSz; + output += sz - (int)pubSz; /* Cache the location to place the name curve OID. */ curveOid = (byte*) dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data; @@ -24631,12 +24631,12 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, } else { /* Total size is the public point size. */ - sz = pubSz; + sz = (int)pubSz; } if ((ret == 0) && (output != NULL)) { /* Put named curve OID data into encoding. */ - curveIdSz = SetCurve(key, curveOid, curveIdSz); + curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz); if (curveIdSz < 0) { ret = curveIdSz; } @@ -24794,7 +24794,7 @@ int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen, if (ret == 0) { /* Set the OID. */ - SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], keyType, + SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType, oidKeyType); /* Leave space for public point. */ SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen); @@ -24817,7 +24817,7 @@ int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen, ret = BUFFER_E; } else if (ret == 0) { - sz = pubKeyLen; + sz = (int)pubKeyLen; } if ((ret == 0) && (output != NULL)) { @@ -25510,7 +25510,7 @@ static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input) ASNSetData* dataASN; ASNItem* extKuASN = NULL; int asnIdx = 1; - int cnt = 1 + EKU_OID_HI; + size_t cnt = 1 + EKU_OID_HI; int i; int ret = 0; int sz = 0; @@ -25779,7 +25779,7 @@ static int SetCertificatePolicies(byte *output, ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, &piSz); } - if ((ret == 0) && (output != NULL) && (sz + piSz > outputSz)) { + if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) { ret = BUFFER_E; } if (ret == 0) { @@ -25788,12 +25788,12 @@ static int SetCertificatePolicies(byte *output, output); output += piSz; } - sz += piSz; + sz += (word32)piSz; } } if (ret == 0) { - ret = sz; + ret = (int)sz; } return ret; #endif @@ -25873,9 +25873,9 @@ int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names) curName = names; do { - namesSz += curName->len + 2 + + namesSz += (word32)curName->len + 2 + ((curName->len < ASN_LONG_LENGTH) ? 0 - : BytePrecision(curName->len)); + : BytePrecision((word32)curName->len)); curName = curName->next; } while (curName != NULL); @@ -25900,10 +25900,10 @@ int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names) output[idx] |= ASN_CONSTRUCTED; } idx++; - idx += SetLength(curName->len, output + idx); - XMEMCPY(output + idx, curName->name, curName->len); + idx += SetLength((word32)curName->len, output + idx); + XMEMCPY(output + idx, curName->name, (size_t)curName->len); #ifndef WOLFSSL_ALT_NAMES_NO_REV - idx += curName->len; + idx += (word32)curName->len; #endif curName = curName->next; } while (curName != NULL); @@ -25911,7 +25911,7 @@ int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names) #ifdef WOLFSSL_ALT_NAMES_NO_REV idx = namesSz; #endif - return idx; + return (int)idx; } #endif /* WOLFSSL_ALT_NAMES */ @@ -26091,7 +26091,7 @@ static int EncodeName(EncodedName* name, const char* nameStr, int ret = 0; int sz = 0; const byte* oid; - int oidSz; + word32 oidSz; word32 nameSz; /* Validate input parameters. */ @@ -26213,7 +26213,7 @@ int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType, #ifdef WOLFSSL_ASN_TEMPLATE static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid, - int oidSz, byte tag, const byte* data, int sz) + word32 oidSz, byte tag, const byte* data, word32 sz) { XMEMCPY(namesASN, rdnASN, sizeof(rdnASN)); SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz); @@ -26257,7 +26257,7 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, int i; int idx; int ret = 0; - int nameLen[NAME_ENTRIES]; + word32 nameLen[NAME_ENTRIES]; #ifdef WOLFSSL_MULTI_ATTRIB int j; #endif @@ -26265,7 +26265,7 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, for (i = 0; i < NAME_ENTRIES; i++) { /* Keep name length to identify component is to be encoded. */ const char* nameStr = GetOneCertName(name, i); - nameLen[i] = nameStr ? (int)XSTRLEN(nameStr) : 0; + nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0; } idx = nameASN_Length; @@ -26287,10 +26287,10 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, } /* Copy data into dynamic vars. */ SetRdnItems(namesASN + idx, dataASN + idx, dcOid, - sizeof(dcOid), name->name[j].type, - (byte*)name->name[j].value, name->name[j].sz); + sizeof(dcOid), (byte)name->name[j].type, + (byte*)name->name[j].value, (word32)name->name[j].sz); } - idx += rdnASN_Length; + idx += (int)rdnASN_Length; } if (ret != 0) break; @@ -26313,13 +26313,13 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, else if (type == ASN_USER_ID) { /* Copy userID data into dynamic vars. */ SetRdnItems(namesASN + idx, dataASN + idx, uidOid, - sizeof(uidOid), GetNameType(name, i), + sizeof(uidOid), (byte)GetNameType(name, i), (const byte*)GetOneCertName(name, i), nameLen[i]); } else if (type == ASN_FAVOURITE_DRINK) { /* Copy favourite drink data into dynamic vars. */ SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk, - sizeof(fvrtDrk), GetNameType(name, i), + sizeof(fvrtDrk), (byte)GetNameType(name, i), (const byte*)GetOneCertName(name, i), nameLen[i]); } else if (type == ASN_CUSTOM_NAME) { @@ -26332,11 +26332,11 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, else { /* Copy name data into dynamic vars. */ SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i], - NAME_OID_SZ, GetNameType(name, i), + NAME_OID_SZ, (byte)GetNameType(name, i), (const byte*)GetOneCertName(name, i), nameLen[i]); } } - idx += rdnASN_Length; + idx += (int)rdnASN_Length; } #ifdef WOLFSSL_MULTI_ATTRIB @@ -26354,10 +26354,10 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, } /* Copy data into dynamic vars. */ SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i], - NAME_OID_SZ, name->name[j].type, - (byte*)name->name[j].value, name->name[j].sz); + NAME_OID_SZ, (byte)name->name[j].type, + (byte*)name->name[j].value, (word32)name->name[j].sz); } - idx += rdnASN_Length; + idx += (int)rdnASN_Length; } if (ret != 0) break; @@ -26488,14 +26488,14 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) * SEQUENCE, encode SEQUENCE, encode entries into buffer. */ ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */ ASNItem* namesASN = NULL; - int items = 0; + word32 items = 0; int ret = 0; int sz = 0; /* Calculate length of name entries and size for allocating. */ ret = SetNameRdnItems(NULL, NULL, 0, name); if (ret > 0) { - items = ret; + items = (word32)ret; ret = 0; } @@ -26520,8 +26520,8 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) /* Copy in the outer sequence. */ XMEMCPY(namesASN, nameASN, sizeof(nameASN)); - ret = SetNameRdnItems(dataASN, namesASN, items, name); - if (ret == items) + ret = SetNameRdnItems(dataASN, namesASN, (int)items, name); + if (ret == (int)items) ret = 0; else if (ret > 0) { WOLFSSL_MSG("SetNameRdnItems returned different length"); @@ -26530,7 +26530,7 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) } if (ret == 0) { /* Calculate size of encoding. */ - ret = SizeASN_Items(namesASN, dataASN, items, &sz); + ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz); } /* Check buffer size if passed in. */ if (ret == 0 && output != NULL && sz > (int)outputSz) { @@ -26539,7 +26539,7 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) if (ret == 0) { if (output != NULL) { /* Encode Name. */ - ret = SetASN_Items(namesASN, dataASN, items, output); + ret = SetASN_Items(namesASN, dataASN, (int)items, output); } else { /* Return the encoding size. */ @@ -26832,7 +26832,7 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1; } SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR], - cert->altNames, cert->altNamesSz); + cert->altNames, (word32)cert->altNamesSz); } else #endif @@ -26847,7 +26847,7 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID], skidOID, sizeof(skidOID)); SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID], - cert->skid, cert->skidSz); + cert->skid, (word32)cert->skidSz); } else #endif @@ -26873,7 +26873,7 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, #endif { SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID], - cert->akid, cert->akidSz); + cert->akid, (word32)cert->akidSz); } } else @@ -26910,7 +26910,7 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID], ekuOID, sizeof(ekuOID)); SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR], - NULL, sz); + NULL, (word32)sz); } else #endif @@ -26931,7 +26931,7 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, cpOID, sizeof(cpOID)); /* Make space for data. */ SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO], - NULL, sz); + NULL, (word32)sz); } else { ret = CERTPOLICIES_E; @@ -26966,7 +26966,7 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID], crlInfoOID, sizeof(crlInfoOID)); SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR], - cert->crlInfo, cert->crlInfoSz); + cert->crlInfo, (word32)cert->crlInfoSz); } else #endif @@ -27753,11 +27753,11 @@ static int WriteCertBody(DerCert* der, byte* buf) /* Make signature from buffer (sz), write to sig (sigSz) */ -static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, int sz, - byte* sig, int sigSz, RsaKey* rsaKey, ecc_key* eccKey, +static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, + byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey, dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng, - int sigAlgoType, void* heap) + word32 sigAlgoType, void* heap) { int digestSz = 0, typeH = 0, ret = 0; @@ -27807,8 +27807,8 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, int sz, } /* signature */ - certSignCtx->encSigSz = wc_EncodeSignature(certSignCtx->encSig, - certSignCtx->digest, digestSz, typeH); + certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig, + certSignCtx->digest, (word32)digestSz, typeH); } #endif /* !NO_RSA */ FALL_THROUGH; @@ -27820,7 +27820,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, int sz, #ifndef NO_RSA if (rsaKey) { /* signature */ - ret = wc_RsaSSL_Sign(certSignCtx->encSig, certSignCtx->encSigSz, + ret = wc_RsaSSL_Sign(certSignCtx->encSig, (word32)certSignCtx->encSigSz, sig, sigSz, rsaKey, rng); } #endif /* !NO_RSA */ @@ -27829,10 +27829,10 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, int sz, if (!rsaKey && eccKey) { word32 outSz = sigSz; - ret = wc_ecc_sign_hash(certSignCtx->digest, digestSz, + ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz, sig, &outSz, rng, eccKey); if (ret == 0) - ret = outSz; + ret = (int)outSz; } #endif /* HAVE_ECC && HAVE_ECC_SIGN */ @@ -27928,7 +27928,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, int sz, * @return 0 on success. * @return -ve when random number generation failed. */ -static int GenerateInteger(WC_RNG* rng, byte* out, int len) +static int GenerateInteger(WC_RNG* rng, byte* out, word32 len) { int ret; @@ -27941,14 +27941,14 @@ static int GenerateInteger(WC_RNG* rng, byte* out, int len) out[0] &= 0x7f; /* Find first non-zero byte. One zero byte is valid though. */ - for (i = 0; i < len - 1; i++) { + for (i = 0; i < (int)len - 1; i++) { if (out[i] != 0) { break; } } if (i != 0) { /* Remove leading zeros. */ - XMEMMOVE(out, out + i, len - i); + XMEMMOVE(out, out + i, len - (word32)i); } } @@ -28019,12 +28019,12 @@ int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz, /* In place, put body between SEQUENCE and signature. */ if (ret == 0) { /* Set sigature OID and signature data. */ - SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], sigAlgoType, oidSigType); - if (IsSigAlgoECC(sigAlgoType)) { + SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType, oidSigType); + if (IsSigAlgoECC((word32)sigAlgoType)) { /* ECDSA and EdDSA doesn't have NULL tagged item. */ dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1; } - SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, sigSz); + SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz); /* Calculate size of signature data. */ ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ], &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz); @@ -28032,13 +28032,13 @@ int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz, if (ret == 0) { /* Calculate size of outer sequence by calculating size of the encoded * length and adding 1 for tag. */ - seqSz = SizeASNHeader(bodySz + sz); + seqSz = SizeASNHeader((word32)bodySz + (word32)sz); if (buf != NULL) { /* Move body to after sequence. */ - XMEMMOVE(buf + seqSz, buf, bodySz); + XMEMMOVE(buf + seqSz, buf, (size_t)bodySz); } /* Leave space for body in encoding. */ - SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL, bodySz); + SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL, (word32)bodySz); /* Calculate overall size and put in offsets and lengths. */ ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz); @@ -28251,9 +28251,9 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, { /* Calculate issuer name encoding size. If the cert is self-signed * use the subject instead of the issuer. */ - issuerSz = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ? + ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap); - ret = issuerSz; + issuerSz = (word32)ret; } } if (ret >= 0) { @@ -28268,30 +28268,32 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, #endif { /* Calculate subject name encoding size. */ - subjectSz = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, + ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap); - ret = subjectSz; + subjectSz = (word32)ret; } } if (ret >= 0) { /* Calculate public key encoding size. */ - ret = publicKeySz = EncodePublicKey(cert->keyType, NULL, 0, rsaKey, + ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey, eccKey, ed25519Key, ed448Key, dsaKey); + publicKeySz = (word32)ret; } if (ret >= 0) { /* Calculate extensions encoding size - may be 0. */ - ret = extSz = EncodeExtensions(cert, NULL, 0, 0); + ret = EncodeExtensions(cert, NULL, 0, 0); + extSz = (word32)ret; } if (ret >= 0) { /* Don't write out outer sequence - only doing body. */ dataASN[X509CERTASN_IDX_SEQ].noOut = 1; /* Set version, serial number and signature OID */ - SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], cert->version); + SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], (byte)cert->version); SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial, - cert->serialSz); - SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], cert->sigType, + (word32)cert->serialSz); + SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], (word32)cert->sigType, oidSigType); - if (IsSigAlgoECC(cert->sigType)) { + if (IsSigAlgoECC((word32)cert->sigType)) { /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */ dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1; } @@ -28435,7 +28437,7 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, ret = EncodePublicKey(cert->keyType, (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ] .data.buffer.data, - dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ] + (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ] .data.buffer.length, rsaKey, eccKey, ed25519Key, ed448Key, dsaKey); } @@ -29273,22 +29275,24 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, else #endif { - subjectSz = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap); - ret = subjectSz; + ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap); + subjectSz = (word32)ret; } } if (ret >= 0) { /* Determine encode public key size. */ - ret = publicKeySz = EncodePublicKey(cert->keyType, NULL, 0, rsaKey, + ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey, eccKey, ed25519Key, ed448Key, dsaKey); + publicKeySz = (word32)ret; } if (ret >= 0) { /* Determine encode extensions size. */ - ret = extSz = EncodeExtensions(cert, NULL, 0, 1); + ret = EncodeExtensions(cert, NULL, 0, 1); + extSz = (word32)ret; } if (ret >= 0) { /* Set version. */ - SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], cert->version); + SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version); #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) if (sbjRawSz > 0) { /* Put in encoded subject name. */ @@ -29374,7 +29378,7 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, /* Encode public key into space in buffer. */ ret = EncodePublicKey(cert->keyType, (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data, - dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length, + (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length, rsaKey, eccKey, ed25519Key, ed448Key, dsaKey); } if ((ret >= 0 && derBuffer != NULL) && @@ -29501,9 +29505,9 @@ static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz, return MEMORY_E; } - sigSz = MakeSignature(certSignCtx, buf, requestSz, certSignCtx->sig, + sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig, MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key, - falconKey, dilithiumKey, sphincsKey, rng, sType, heap); + falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap); #ifdef WOLFSSL_ASYNC_CRYPT if (sigSz == WC_PENDING_E) { /* Not free'ing certSignCtx->sig here because it could still be in use @@ -29683,11 +29687,11 @@ static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey, /* Compute SKID by hashing public key */ if (kid_type == SKID_TYPE) { - ret = CalcHashId(buf, bufferSz, cert->skid); + ret = CalcHashId(buf, (word32)bufferSz, cert->skid); cert->skidSz = KEYID_SIZE; } else if (kid_type == AKID_TYPE) { - ret = CalcHashId(buf, bufferSz, cert->akid); + ret = CalcHashId(buf, (word32)bufferSz, cert->akid); cert->akidSz = KEYID_SIZE; } else @@ -29825,7 +29829,7 @@ int wc_SetSubjectKeyId(Cert *cert, const char* file) } derSz = MAX_PUBLIC_KEY_SZ; - XMEMSET(der, 0, derSz); + XMEMSET(der, 0, (size_t)derSz); derSz = wc_PemPubKeyToDer(file, der, derSz); if (derSz <= 0) { XFREE(der, cert->heap, DYNAMIC_TYPE_CERT); @@ -29848,7 +29852,7 @@ int wc_SetSubjectKeyId(Cert *cert, const char* file) } idx = 0; - ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, derSz); + ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz); if (ret != 0) #endif { @@ -29876,7 +29880,7 @@ int wc_SetSubjectKeyId(Cert *cert, const char* file) } idx = 0; - ret = wc_EccPublicKeyDecode(der, &idx, eckey, derSz); + ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz); if (ret != 0) { WOLFSSL_MSG("wc_EccPublicKeyDecode failed"); XFREE(der, cert->heap, DYNAMIC_TYPE_CERT); @@ -29942,7 +29946,7 @@ int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); } if (ret >= 0) { @@ -29971,7 +29975,7 @@ int wc_SetAuthKeyId(Cert *cert, const char* file) ret = wc_PemCertToDer_ex(file, &der); if (ret == 0) { - ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, der->length); + ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length); FreeDer(&der); } @@ -30202,7 +30206,7 @@ static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz) return MEMORY_E; #endif - InitDecodedCert(decoded, der, derSz, NULL); + InitDecodedCert(decoded, der, (word32)derSz, NULL); ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0); if (ret < 0) { @@ -30236,8 +30240,8 @@ static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded) ret = -1; } else { - XMEMCPY(cert->beforeDate, decoded->beforeDate, decoded->beforeDateLen); - XMEMCPY(cert->afterDate, decoded->afterDate, decoded->afterDateLen); + XMEMCPY(cert->beforeDate, decoded->beforeDate, (size_t)decoded->beforeDateLen); + XMEMCPY(cert->afterDate, decoded->afterDate, (size_t)decoded->afterDateLen); cert->beforeDateSz = decoded->beforeDateLen; cert->afterDateSz = decoded->afterDateLen; @@ -30255,63 +30259,63 @@ static void SetNameFromDcert(CertName* cn, DecodedCert* decoded) if (decoded->subjectCN) { sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->commonName, decoded->subjectCN, sz); + XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz); cn->commonName[sz] = '\0'; cn->commonNameEnc = decoded->subjectCNEnc; } if (decoded->subjectC) { sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->country, decoded->subjectC, sz); + XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz); cn->country[sz] = '\0'; cn->countryEnc = decoded->subjectCEnc; } if (decoded->subjectST) { sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->state, decoded->subjectST, sz); + XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz); cn->state[sz] = '\0'; cn->stateEnc = decoded->subjectSTEnc; } if (decoded->subjectL) { sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->locality, decoded->subjectL, sz); + XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz); cn->locality[sz] = '\0'; cn->localityEnc = decoded->subjectLEnc; } if (decoded->subjectO) { sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->org, decoded->subjectO, sz); + XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz); cn->org[sz] = '\0'; cn->orgEnc = decoded->subjectOEnc; } if (decoded->subjectOU) { sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->unit, decoded->subjectOU, sz); + XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz); cn->unit[sz] = '\0'; cn->unitEnc = decoded->subjectOUEnc; } if (decoded->subjectSN) { sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->sur, decoded->subjectSN, sz); + XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz); cn->sur[sz] = '\0'; cn->surEnc = decoded->subjectSNEnc; } if (decoded->subjectSND) { sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->serialDev, decoded->subjectSND, sz); + XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz); cn->serialDev[sz] = '\0'; cn->serialDevEnc = decoded->subjectSNDEnc; } if (decoded->subjectUID) { sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->userId, decoded->subjectUID, sz); + XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz); cn->userId[sz] = '\0'; cn->userIdEnc = decoded->subjectUIDEnc; } @@ -30319,21 +30323,21 @@ static void SetNameFromDcert(CertName* cn, DecodedCert* decoded) if (decoded->subjectBC) { sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->busCat, decoded->subjectBC, sz); + XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz); cn->busCat[sz] = '\0'; cn->busCatEnc = decoded->subjectBCEnc; } if (decoded->subjectJC) { sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->joiC, decoded->subjectJC, sz); + XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz); cn->joiC[sz] = '\0'; cn->joiCEnc = decoded->subjectJCEnc; } if (decoded->subjectJS) { sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->joiSt, decoded->subjectJS, sz); + XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz); cn->joiSt[sz] = '\0'; cn->joiStEnc = decoded->subjectJSEnc; } @@ -30341,7 +30345,7 @@ static void SetNameFromDcert(CertName* cn, DecodedCert* decoded) if (decoded->subjectEmail) { sz = (decoded->subjectEmailLen < CTC_NAME_SIZE) ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->email, decoded->subjectEmail, sz); + XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz); cn->email[sz] = '\0'; } #if defined(WOLFSSL_CERT_NAME_ALL) && \ @@ -30349,28 +30353,28 @@ static void SetNameFromDcert(CertName* cn, DecodedCert* decoded) if (decoded->subjectN) { sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->dnName, decoded->subjectN, sz); + XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz); cn->dnName[sz] = '\0'; cn->dnNameEnc = decoded->subjectNEnc; } if (decoded->subjectI) { sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->initials, decoded->subjectI, sz); + XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz); cn->initials[sz] = '\0'; cn->initialsEnc = decoded->subjectIEnc; } if (decoded->subjectGN) { sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->givenName, decoded->subjectGN, sz); + XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz); cn->givenName[sz] = '\0'; cn->givenNameEnc = decoded->subjectGNEnc; } if (decoded->subjectDNQ) { sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen : CTC_NAME_SIZE - 1; - XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, sz); + XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz); cn->dnQualifier[sz] = '\0'; cn->dnQualifierEnc = decoded->subjectDNQEnc; } @@ -30399,7 +30403,7 @@ static int SetNameFromCert(CertName* cn, const byte* der, int derSz) return MEMORY_E; #endif - InitDecodedCert(decoded, der, derSz, NULL); + InitDecodedCert(decoded, der, (word32)derSz, NULL); ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0); if (ret < 0) { @@ -30431,7 +30435,7 @@ int wc_SetIssuer(Cert* cert, const char* issuerFile) ret = wc_PemCertToDer_ex(issuerFile, &der); if (ret == 0) { cert->selfSigned = 0; - ret = SetNameFromCert(&cert->issuer, der->buffer, der->length); + ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length); FreeDer(&der); } @@ -30452,7 +30456,7 @@ int wc_SetSubject(Cert* cert, const char* subjectFile) ret = wc_PemCertToDer_ex(subjectFile, &der); if (ret == 0) { - ret = SetNameFromCert(&cert->subject, der->buffer, der->length); + ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length); FreeDer(&der); } @@ -30475,7 +30479,7 @@ int wc_SetAltNames(Cert* cert, const char* file) ret = wc_PemCertToDer_ex(file, &der); if (ret == 0) { - ret = SetAltNamesFromCert(cert, der->buffer, der->length); + ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length); FreeDer(&der); } @@ -30502,7 +30506,7 @@ int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); } if (ret >= 0) { @@ -30529,7 +30533,7 @@ int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); } if (ret >= 0) { @@ -30556,7 +30560,7 @@ int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); } if (ret >= 0) { @@ -30565,7 +30569,7 @@ int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz) (int)sizeof(CertName))) { XMEMCPY(cert->sbjRaw, ((DecodedCert*)cert->decodedCert)->subjectRaw, - ((DecodedCert*)cert->decodedCert)->subjectRawLen); + (size_t)((DecodedCert*)cert->decodedCert)->subjectRawLen); } #ifndef WOLFSSL_CERT_GEN_CACHE wc_SetCert_Free(cert); @@ -30589,7 +30593,7 @@ int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); } if (ret >= 0) { @@ -30599,7 +30603,7 @@ int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz) /* Copy the subject to the issuer field */ XMEMCPY(cert->issRaw, ((DecodedCert*)cert->decodedCert)->subjectRaw, - ((DecodedCert*)cert->decodedCert)->subjectRawLen); + (size_t)((DecodedCert*)cert->decodedCert)->subjectRawLen); } #ifndef WOLFSSL_CERT_GEN_CACHE wc_SetCert_Free(cert); @@ -30625,7 +30629,7 @@ int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); } if (ret >= 0) { @@ -30652,7 +30656,7 @@ int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); } if (ret >= 0) { @@ -30910,7 +30914,7 @@ int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s) /* Encode DSA signature into buffer. */ SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out); /* Set the actual encoding size. */ - *outLen = sz; + *outLen = (word32)sz; } return ret; @@ -31013,7 +31017,7 @@ int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen, /* Encode DSA signature into buffer. */ SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out); /* Set the actual encoding size. */ - *outLen = sz; + *outLen = (word32)sz; } return ret; @@ -31355,13 +31359,13 @@ static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz, /* Allocate buffer to put hex strings into. */ if (ret == 0) { /* Base X-ordinate */ - ret = DataToHexStringAlloc(base + 1, curve->size, + ret = DataToHexStringAlloc(base + 1, (word32)curve->size, (char**)&curve->Gx, key->heap, DYNAMIC_TYPE_ECC_BUFFER); } if (ret == 0) { /* Base Y-ordinate */ - ret = DataToHexStringAlloc(base + 1 + curve->size, curve->size, + ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size, (char**)&curve->Gy, key->heap, DYNAMIC_TYPE_ECC_BUFFER); } @@ -32299,7 +32303,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, if (ret == 0) { /* Private key size is the curve size. */ - privSz = key->dp->size; + privSz = (word32)key->dp->size; if (pubIn) { /* Get the length of the public key. */ PRIVATE_KEY_UNLOCK(); @@ -32322,7 +32326,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, } /* Curve OID */ SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL, - curveIdSz); + (word32)curveIdSz); /* TODO: add support for SpecifiedECDomain curve. */ dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1; } @@ -32346,7 +32350,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, } /* Return the size if no buffer. */ if ((ret == 0) && (output == NULL)) { - *inLen = sz; + *inLen = (word32)sz; ret = LENGTH_ONLY_E; } /* Check the buffer is big enough. */ @@ -32361,7 +32365,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, /* Put named curve OID data into encoding. */ curveIdSz = SetCurve(key, (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data, - curveIdSz); + (size_t)curveIdSz); if (curveIdSz < 0) { ret = curveIdSz; } @@ -32672,7 +32676,7 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, if (ret == 0) { /* Require OID. */ word32 oidSz; - const byte* oid = OidFromId(keyType, oidKeyType, &oidSz); + const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz); GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz); /* Parse full private key. */ ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input, @@ -32774,7 +32778,7 @@ int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, if (ret == 0) { /* Require OID. */ word32 oidSz; - const byte* oid = OidFromId(keyType, oidKeyType, &oidSz); + const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz); GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz); /* Decode Ed25519 private key. */ @@ -32984,7 +32988,7 @@ int SetAsymKeyDer(const byte* privKey, word32 privKeyLen, /* Set version = 0 */ SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0); /* Set OID. */ - SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], keyType, oidKeyType); + SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType, oidKeyType); /* Leave space for private key. */ SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen); /* Don't write out attributes. */ @@ -35170,7 +35174,7 @@ int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx) GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType); /* Decode certificate name. */ ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx, - maxIdx); + (word32)maxIdx); if (ret == 0) { /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be * calculated over the entire DER encoding of the Name field, including diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 12571276f6b..a139acbe0bc 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -228,8 +228,8 @@ ECC Curve Sizes: #define MAX_ECC_BITS_USE MAX_ECC_BITS_NEEDED #endif #define ECC_KEY_MAX_BITS(key) \ - (((key == NULL) || (key->dp == NULL)) ? MAX_ECC_BITS_USE \ - : (key->dp->size * 8)) + ((((key) == NULL) || ((key)->dp == NULL)) ? MAX_ECC_BITS_USE \ + : (unsigned)((key)->dp->size * 8)) /* forward declarations */ static int wc_ecc_new_point_ex(ecc_point** point, void* heap); @@ -3040,7 +3040,7 @@ static int ecc_mulmod(const mp_int* k, ecc_point* P, ecc_point* Q, } #else /* Swap R[0] and R[1] if other index is needed. */ - swap ^= b; + swap ^= (int)b; if (err == MP_OKAY) err = mp_cond_swap_ct(R[0]->x, R[1]->x, (int)modulus->used, swap); if (err == MP_OKAY) @@ -4650,7 +4650,7 @@ static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, } if (err == MP_OKAY) { - XMEMSET(out, 0, x); + XMEMSET(out, 0, (size_t)x); err = mp_to_unsigned_bin(result->x, out + (x - mp_unsigned_bin_size(result->x))); } @@ -5870,7 +5870,7 @@ int wc_ecc_init_id(ecc_key* key, unsigned char* id, int len, void* heap, if (ret == 0) ret = wc_ecc_init_ex(key, heap, devId); if (ret == 0 && id != NULL && len != 0) { - XMEMCPY(key->id, id, len); + XMEMCPY(key->id, id, (size_t)len); key->idLen = len; #ifdef WOLFSSL_SE050 /* Set SE050 ID from word32, populate ecc_key with public from SE050 */ @@ -5900,7 +5900,7 @@ int wc_ecc_init_label(ecc_key* key, const char* label, void* heap, int devId) if (ret == 0) ret = wc_ecc_init_ex(key, heap, devId); if (ret == 0) { - XMEMCPY(key->label, label, labelLen); + XMEMCPY(key->label, label, (size_t)labelLen); key->labelLen = labelLen; } @@ -7133,7 +7133,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, #endif VSz = KSz = hashSz; - qLen = xSz = h1len = mp_unsigned_bin_size(order); + qLen = xSz = h1len = (word32)mp_unsigned_bin_size(order); /* 3.2 b. Set V = 0x01 0x01 ... */ XMEMSET(V, 0x01, VSz); @@ -7142,7 +7142,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, XMEMSET(K, 0x00, KSz); mp_init(z1); /* always init z1 and free z1 */ - ret = mp_to_unsigned_bin_len(priv, x, qLen); + ret = mp_to_unsigned_bin_len(priv, x, (int)qLen); if (ret == 0) { #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Add("wc_ecc_gen_deterministic_k x", x, qLen); @@ -7176,7 +7176,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, #endif { /* use original hash and keep leading 0's */ - mp_to_unsigned_bin_len(z1, h1, h1len); + mp_to_unsigned_bin_len(z1, h1, (int)h1len); } } mp_free(z1); @@ -7224,9 +7224,9 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, if (ret == 0) { int sz; - sz = MIN(qLen - xSz, VSz); - XMEMCPY(x + xSz, V, sz); - xSz += sz; + sz = (int)MIN(qLen - xSz, (size_t)VSz); + XMEMCPY(x + xSz, V, (size_t)sz); + xSz += (word32)sz; } else { break; /* error case */ @@ -7241,7 +7241,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, if ((ret == 0) && ((int)(xSz * WOLFSSL_BIT_SIZE) != qbits)) { /* handle odd case where shift of 'k' is needed with RFC 6979 * k = bits2int(T) in section 3.2 h.3 */ - mp_rshb(k, (xSz * WOLFSSL_BIT_SIZE) - qbits); + mp_rshb(k, ((int)xSz * WOLFSSL_BIT_SIZE) - qbits); } /* 3.2 step h.3 the key should be smaller than the order of base @@ -7297,7 +7297,7 @@ int wc_ecc_set_deterministic(ecc_key* key, byte flag) return BAD_FUNC_ARG; } - key->deterministic = flag; + key->deterministic = flag ? 1 : 0; return 0; } #endif /* end sign_ex and deterministic sign */ @@ -8110,6 +8110,8 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, } #endif /* !NO_ASN */ +#ifndef WOLF_CRYPTO_CB_ONLY_ECC + #if !defined(WOLFSSL_STM32_PKA) && !defined(WOLFSSL_PSOC6_CRYPTO) && \ !defined(WOLF_CRYPTO_CB_ONLY_ECC) static int wc_ecc_check_r_s_range(ecc_key* key, mp_int* r, mp_int* s) @@ -8142,7 +8144,6 @@ static int wc_ecc_check_r_s_range(ecc_key* key, mp_int* r, mp_int* s) } #endif /* !WOLFSSL_STM32_PKA && !WOLFSSL_PSOC6_CRYPTO */ -#ifndef WOLF_CRYPTO_CB_ONLY_ECC static int ecc_verify_hash_sp(mp_int *r, mp_int *s, const byte* hash, word32 hashlen, int* res, ecc_key* key) { @@ -8333,7 +8334,7 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, /* read hash */ if (err == MP_OKAY) { /* we may need to truncate if hash is longer than key size */ - unsigned int orderBits = mp_count_bits(curve->order); + unsigned int orderBits = (unsigned int)mp_count_bits(curve->order); /* truncate down to byte size, may be all that's needed */ if ( (WOLFSSL_BIT_SIZE * hashlen) > orderBits) @@ -8830,9 +8831,9 @@ int wc_ecc_import_point_der_ex(const byte* in, word32 inLen, /* calculate key size based on inLen / 2 if uncompressed or shortKeySize * is true */ #ifdef HAVE_COMP_KEY - keysize = compressed && !shortKeySize ? inLen : inLen>>1; + keysize = (int)((compressed && !shortKeySize) ? inLen : inLen>>1); #else - keysize = inLen>>1; + keysize = (int)(inLen>>1); #endif /* read data */ @@ -9109,7 +9110,7 @@ int wc_ecc_export_point_der_compressed(const int curve_idx, ecc_point* point, if ((curve_idx < 0) || (wc_ecc_is_valid_idx(curve_idx) == 0)) return ECC_BAD_ARG_E; - numlen = ecc_sets[curve_idx].size; + numlen = (word32)ecc_sets[curve_idx].size; output_len = 1 + numlen; /* y point type + x */ /* return length needed only */ @@ -9145,7 +9146,7 @@ int wc_ecc_export_point_der_compressed(const int curve_idx, ecc_point* point, /* pad and store x */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(point->x, buf + - (numlen - mp_unsigned_bin_size(point->x))); + (numlen - (word32)mp_unsigned_bin_size(point->x))); if (ret != MP_OKAY) goto done; XMEMCPY(out+1, buf, numlen); @@ -10049,7 +10050,7 @@ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, #endif /* determine key size */ - keysize = (inLen>>1); + keysize = (int)(inLen>>1); err = wc_ecc_set_curve(key, keysize, curve_id); key->type = ECC_PUBLICKEY; } @@ -11078,7 +11079,7 @@ static int ecc_public_key_size(ecc_key* key, word32* sz) return BAD_FUNC_ARG; /* 'Uncompressed' | x | y */ - *sz = 1 + 2 * key->dp->size; + *sz = 1 + 2 * (word32)key->dp->size; return 0; } @@ -11725,8 +11726,7 @@ static const struct { /* find a hole and free as required, return -1 if no hole found */ static int find_hole(void) { - unsigned x; - int y, z; + int x, y, z; for (z = -1, y = INT_MAX, x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].lru_count < y && fp_cache[x].lock == 0) { z = x; @@ -11746,7 +11746,7 @@ static int find_hole(void) mp_clear(&fp_cache[z].mu); wc_ecc_del_point(fp_cache[z].g); fp_cache[z].g = NULL; - for (x = 0; x < (1U< mp_unsigned_bin_size(modulus)) { /* find order */ - y = mp_unsigned_bin_size(modulus); + y = (unsigned)mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } @@ -12049,10 +12049,10 @@ static int accel_fp_mul(int idx, const mp_int* k, ecc_point *R, mp_int* a, } /* get bitlen and round up to next multiple of FP_LUT */ - bitlen = mp_unsigned_bin_size(modulus) << 3; + bitlen = (unsigned)mp_unsigned_bin_size(modulus) << 3; x = bitlen % FP_LUT; if (x) { - bitlen += FP_LUT - x; + bitlen += FP_LUT - (unsigned)x; } lut_gap = bitlen / FP_LUT; @@ -12076,7 +12076,7 @@ static int accel_fp_mul(int idx, const mp_int* k, ecc_point *R, mp_int* a, #endif /* let's reverse kb so it's little endian */ x = 0; - y = mp_unsigned_bin_size(tk); + y = (unsigned)mp_unsigned_bin_size(tk); if (y > 0) { y -= 1; } @@ -12088,10 +12088,10 @@ static int accel_fp_mul(int idx, const mp_int* k, ecc_point *R, mp_int* a, /* at this point we can start, yipee */ first = 1; - for (x = lut_gap-1; x >= 0; x--) { + for (x = (int)lut_gap-1; x >= 0; x--) { /* extract FP_LUT bits from kb spread out by lut_gap bits and offset by x bits from the start */ - bitpos = x; + bitpos = (unsigned)x; for (y = z = 0; y < FP_LUT; y++) { z |= ((kb[bitpos>>3] >> (bitpos&7)) & 1) << y; bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid @@ -12206,7 +12206,7 @@ static int accel_fp_mul2add(int idx1, int idx2, /* if it's smaller than modulus we fine */ if (mp_unsigned_bin_size(kA) > mp_unsigned_bin_size(modulus)) { /* find order */ - y = mp_unsigned_bin_size(modulus); + y = (unsigned)mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } @@ -12241,7 +12241,7 @@ static int accel_fp_mul2add(int idx1, int idx2, /* if it's smaller than modulus we fine */ if (mp_unsigned_bin_size(kB) > mp_unsigned_bin_size(modulus)) { /* find order */ - y = mp_unsigned_bin_size(modulus); + y = (unsigned)mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } @@ -12274,10 +12274,10 @@ static int accel_fp_mul2add(int idx1, int idx2, #endif /* get bitlen and round up to next multiple of FP_LUT */ - bitlen = mp_unsigned_bin_size(modulus) << 3; + bitlen = (unsigned)mp_unsigned_bin_size(modulus) << 3; x = bitlen % FP_LUT; if (x) { - bitlen += FP_LUT - x; + bitlen += FP_LUT - (unsigned)x; } lut_gap = bitlen / FP_LUT; @@ -12305,7 +12305,7 @@ static int accel_fp_mul2add(int idx1, int idx2, /* let's reverse kb so it's little endian */ x = 0; - y = mp_unsigned_bin_size(tka); + y = (unsigned)mp_unsigned_bin_size(tka); if (y > 0) { y -= 1; } @@ -12329,7 +12329,7 @@ static int accel_fp_mul2add(int idx1, int idx2, #endif if ((err = mp_to_unsigned_bin(tkb, kb[1])) == MP_OKAY) { x = 0; - y = mp_unsigned_bin_size(tkb); + y = (unsigned)mp_unsigned_bin_size(tkb); if (y > 0) { y -= 1; } @@ -12341,10 +12341,10 @@ static int accel_fp_mul2add(int idx1, int idx2, /* at this point we can start, yipee */ first = 1; - for (x = lut_gap-1; x >= 0; x--) { + for (x = (int)lut_gap-1; x >= 0; x--) { /* extract FP_LUT bits from kb spread out by lut_gap bits and offset by x bits from the start */ - bitpos = x; + bitpos = (unsigned)x; for (y = zA = zB = 0; y < FP_LUT; y++) { zA |= ((kb[0][bitpos>>3] >> (bitpos&7)) & 1) << y; zB |= ((kb[1][bitpos>>3] >> (bitpos&7)) & 1) << y; @@ -13100,7 +13100,7 @@ int wc_ecc_ctx_set_info(ecEncCtx* ctx, const byte* info, int sz) return BAD_FUNC_ARG; ctx->kdfInfo = info; - ctx->kdfInfoSz = sz; + ctx->kdfInfoSz = (word32)sz; return 0; } @@ -13137,9 +13137,9 @@ int wc_ecc_ctx_set_peer_salt(ecEncCtx* ctx, const byte* salt) /* mix half and half */ /* tmp stores 2nd half of client before overwrite */ - XMEMCPY(tmp, ctx->clientSalt + halfSz, halfSz); - XMEMCPY(ctx->clientSalt + halfSz, ctx->serverSalt, halfSz); - XMEMCPY(ctx->serverSalt, tmp, halfSz); + XMEMCPY(tmp, ctx->clientSalt + halfSz, (size_t)halfSz); + XMEMCPY(ctx->clientSalt + halfSz, ctx->serverSalt, (size_t)halfSz); + XMEMCPY(ctx->serverSalt, tmp, (size_t)halfSz); ctx->kdfSalt = ctx->clientSalt; ctx->kdfSaltSz = EXCHANGE_SALT_SZ; @@ -13325,9 +13325,9 @@ static int ecc_get_key_sizes(ecEncCtx* ctx, int* encKeySz, int* ivSz, return BAD_FUNC_ARG; #ifdef WOLFSSL_ECIES_OLD - *keysLen = *encKeySz + *ivSz + *digestSz; + *keysLen = *encKeySz + *ivSz + (int)*digestSz; #else - *keysLen = *encKeySz + *digestSz; + *keysLen = *encKeySz + (int)*digestSz; #endif return 0; @@ -13392,10 +13392,10 @@ int wc_ecc_encrypt_ex(ecc_key* privKey, ecc_key* pubKey, const byte* msg, #ifndef WOLFSSL_ECIES_OLD if (!compressed) { - pubKeySz = 1 + wc_ecc_size(privKey) * 2; + pubKeySz = 1 + (word32)wc_ecc_size(privKey) * 2; } else { - pubKeySz = 1 + wc_ecc_size(privKey); + pubKeySz = 1 + (word32)wc_ecc_size(privKey); } #else (void) compressed; /* avoid unused parameter if WOLFSSL_ECIES_OLD is defined */ @@ -13496,7 +13496,7 @@ int wc_ecc_encrypt_ex(ecc_key* privKey, ecc_key* pubKey, const byte* msg, case ecHKDF_SHA256 : ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt, ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz, - keys, keysLen); + keys, (word32)keysLen); break; default: @@ -13517,7 +13517,7 @@ int wc_ecc_encrypt_ex(ecc_key* privKey, ecc_key* pubKey, const byte* msg, macKey = encKey + encKeySz; ret = wc_RNG_GenerateBlock(privKey->rng, encIv, ivSz); #else - XMEMSET(iv, 0, ivSz); + XMEMSET(iv, 0, (size_t)ivSz); encKey = keys + offset; encIv = iv; macKey = encKey + encKeySz; @@ -13542,7 +13542,7 @@ int wc_ecc_encrypt_ex(ecc_key* privKey, ecc_key* pubKey, const byte* msg, #endif ret = wc_AesInit(aes, NULL, INVALID_DEVID); if (ret == 0) { - ret = wc_AesSetKey(aes, encKey, encKeySz, encIv, + ret = wc_AesSetKey(aes, encKey, (word32)encKeySz, encIv, AES_ENCRYPTION); if (ret == 0) { ret = wc_AesCbcEncrypt(aes, out, msg, msgSz); @@ -13585,7 +13585,7 @@ int wc_ecc_encrypt_ex(ecc_key* privKey, ecc_key* pubKey, const byte* msg, ret = wc_AesInit(aes, NULL, INVALID_DEVID); if (ret == 0) { - ret = wc_AesSetKey(aes, encKey, encKeySz, ctr_iv, + ret = wc_AesSetKey(aes, encKey, (word32)encKeySz, ctr_iv, AES_ENCRYPTION); if (ret == 0) { ret = wc_AesCtrEncrypt(aes, out, msg, msgSz); @@ -13891,7 +13891,7 @@ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, case ecHKDF_SHA256 : ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt, ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz, - keys, keysLen); + keys, (word32)keysLen); break; default: @@ -13912,7 +13912,7 @@ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, msgSz -= ivSz; macKey = encKey + encKeySz; #else - XMEMSET(iv, 0, ivSz); + XMEMSET(iv, 0, (size_t)ivSz); encKey = keys + offset; encIv = iv; macKey = encKey + encKeySz; @@ -13985,7 +13985,7 @@ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, #endif ret = wc_AesInit(aes, NULL, INVALID_DEVID); if (ret == 0) { - ret = wc_AesSetKey(aes, encKey, encKeySz, encIv, + ret = wc_AesSetKey(aes, encKey, (word32)encKeySz, encIv, AES_DECRYPTION); if (ret == 0) { ret = wc_AesCbcDecrypt(aes, out, msg, msgSz-digestSz); @@ -14024,7 +14024,7 @@ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, XMEMCPY(ctr_iv, encIv, WOLFSSL_ECIES_GEN_IV_SIZE); XMEMSET(ctr_iv + WOLFSSL_ECIES_GEN_IV_SIZE, 0, AES_BLOCK_SIZE - WOLFSSL_ECIES_GEN_IV_SIZE); - ret = wc_AesSetKey(aes, encKey, encKeySz, ctr_iv, + ret = wc_AesSetKey(aes, encKey, (word32)encKeySz, ctr_iv, AES_ENCRYPTION); if (ret == 0) { ret = wc_AesCtrEncrypt(aes, out, msg, msgSz-digestSz); @@ -14529,7 +14529,7 @@ static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen return ECC_BAD_ARG_E; } - numlen = key->dp->size; + numlen = (word32)key->dp->size; if (*outLen < (1 + numlen)) { *outLen = 1 + numlen; @@ -14548,7 +14548,7 @@ static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen /* pad and store x */ XMEMSET(out+1, 0, numlen); ret = mp_to_unsigned_bin(key->pubkey.x, - out+1 + (numlen - mp_unsigned_bin_size(key->pubkey.x))); + out+1 + (numlen - (word32)mp_unsigned_bin_size(key->pubkey.x))); *outLen = 1 + numlen; return ret; @@ -14636,8 +14636,7 @@ int wc_X963_KDF(enum wc_HashType type, const byte* secret, word32 secretSz, const byte* sinfo, word32 sinfoSz, byte* out, word32 outSz) { int ret; - int digestSz, copySz; - int remaining = outSz; + word32 digestSz, copySz, remaining = outSz; byte* outIdx; byte counter[4]; byte tmp[WC_MAX_DIGEST_SIZE]; @@ -14657,9 +14656,10 @@ int wc_X963_KDF(enum wc_HashType type, const byte* secret, word32 secretSz, type != WC_HASH_TYPE_SHA512) return BAD_FUNC_ARG; - digestSz = wc_HashGetDigestSize(type); - if (digestSz < 0) - return digestSz; + ret = wc_HashGetDigestSize(type); + if (ret < 0) + return ret; + digestSz = (word32)ret; #ifdef WOLFSSL_SMALL_STACK hash = (wc_HashAlg*)XMALLOC(sizeof(wc_HashAlg), NULL, diff --git a/wolfcrypt/src/hmac.c b/wolfcrypt/src/hmac.c index 11abc58c59c..1c7847335ea 100644 --- a/wolfcrypt/src/hmac.c +++ b/wolfcrypt/src/hmac.c @@ -340,7 +340,7 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) #ifdef WOLF_CRYPTO_CB hmac->keyRaw = key; /* use buffer directly */ - hmac->keyLen = length; + hmac->keyLen = (word16)length; #endif #ifdef WOLFSSL_MAXQ108X @@ -1055,7 +1055,7 @@ int wc_HmacInit_Id(Hmac* hmac, unsigned char* id, int len, void* heap, if (ret == 0) ret = wc_HmacInit(hmac, heap, devId); if (ret == 0) { - XMEMCPY(hmac->id, id, len); + XMEMCPY(hmac->id, id, (size_t)len); hmac->idLen = len; } @@ -1078,7 +1078,7 @@ int wc_HmacInit_Label(Hmac* hmac, const char* label, void* heap, int devId) if (ret == 0) ret = wc_HmacInit(hmac, heap, devId); if (ret == 0) { - XMEMCPY(hmac->label, label, labelLen); + XMEMCPY(hmac->label, label, (size_t)labelLen); hmac->labelLen = labelLen; } @@ -1199,7 +1199,7 @@ int wolfSSL_GetHmacMaxSize(void) #endif int ret; const byte* localSalt; /* either points to user input or tmp */ - int hashSz; + word32 hashSz; ret = wc_HmacSizeByType(type); if (ret < 0) { @@ -1213,7 +1213,7 @@ int wolfSSL_GetHmacMaxSize(void) } #endif - hashSz = ret; + hashSz = (word32)ret; localSalt = salt; if (localSalt == NULL) { XMEMSET(tmp, 0, hashSz); @@ -1259,9 +1259,15 @@ int wolfSSL_GetHmacMaxSize(void) #endif int ret = 0; word32 outIdx = 0; - word32 hashSz = wc_HmacSizeByType(type); + word32 hashSz; byte n = 0x1; + ret = wc_HmacSizeByType(type); + if (ret < 0) { + return ret; + } + hashSz = (word32)ret; + /* RFC 5869 states that the length of output keying material in * octets must be L <= 255*HashLen or N = ceil(L/HashLen) */ @@ -1285,7 +1291,7 @@ int wolfSSL_GetHmacMaxSize(void) } while (outIdx < outSz) { - int tmpSz = (n == 1) ? 0 : hashSz; + word32 tmpSz = (n == 1) ? 0 : hashSz; word32 left = outSz - outIdx; ret = wc_HmacSetKey(myHmac, type, inKey, inKeySz); @@ -1338,11 +1344,14 @@ int wolfSSL_GetHmacMaxSize(void) byte* out, word32 outSz) { byte prk[WC_MAX_DIGEST_SIZE]; - int hashSz = wc_HmacSizeByType(type); + word32 hashSz; int ret; - if (hashSz < 0) - return BAD_FUNC_ARG; + ret = wc_HmacSizeByType(type); + if (ret < 0) { + return ret; + } + hashSz = (word32)ret; ret = wc_HKDF_Extract(type, salt, saltSz, inKey, inKeySz, prk); if (ret != 0) diff --git a/wolfcrypt/src/kdf.c b/wolfcrypt/src/kdf.c index 480753cb6f0..f866dfcc36f 100644 --- a/wolfcrypt/src/kdf.c +++ b/wolfcrypt/src/kdf.c @@ -351,11 +351,11 @@ int wc_PRF_TLS(byte* digest, word32 digLen, const byte* secret, word32 secLen, * digest The type of digest to use. * returns 0 on success, otherwise failure. */ - int wc_Tls13_HKDF_Extract(byte* prk, const byte* salt, int saltLen, - byte* ikm, int ikmLen, int digest) + int wc_Tls13_HKDF_Extract(byte* prk, const byte* salt, word32 saltLen, + byte* ikm, word32 ikmLen, int digest) { int ret; - int len = 0; + word32 len = 0; switch (digest) { #ifndef NO_SHA256 @@ -425,7 +425,7 @@ int wc_PRF_TLS(byte* digest, word32 digLen, const byte* secret, word32 secLen, int digest) { int ret = 0; - int idx = 0; + word32 idx = 0; #ifdef WOLFSSL_SMALL_STACK byte* data; #else @@ -755,7 +755,7 @@ int wc_SSH_KDF(byte hashId, byte keyId, byte* key, word32 keySz, byte kPad = 0; byte pad = 0; byte kSzFlat[LENGTH_SZ]; - int digestSz; + word32 digestSz; int ret; if (key == NULL || keySz == 0 || @@ -766,10 +766,11 @@ int wc_SSH_KDF(byte hashId, byte keyId, byte* key, word32 keySz, return BAD_FUNC_ARG; } - digestSz = wc_HmacSizeByType(enmhashId); - if (digestSz <= 0) { + ret = wc_HmacSizeByType(enmhashId); + if (ret <= 0) { return BAD_FUNC_ARG; } + digestSz = (word32)ret; if (k[0] & 0x80) kPad = 1; c32toa(kSz + kPad, kSzFlat); diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index 7ec3871aeca..de8f4c7e244 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -330,7 +330,7 @@ WC_MISC_STATIC WC_INLINE void ForceZero(void* mem, word32 len) len -= l; while (l--) *z++ = 0; #endif - for (w = (volatile word64*)z; len >= sizeof(*w); len -= sizeof(*w)) + for (w = (volatile word64*)z; len >= sizeof(*w); len -= (word32)sizeof(*w)) *w++ = 0; z = (volatile byte*)w; #endif @@ -561,6 +561,13 @@ WC_MISC_STATIC WC_INLINE int ctMaskSelInt(byte m, int a, int b) (a & ( (signed int)(signed char)m)); } +/* Constant time - select word32 a when mask is set and word32 b otherwise. */ +WC_MISC_STATIC WC_INLINE word32 ctMaskSelWord32(byte m, word32 a, word32 b) +{ + return (((word32)b & (word32)(~(signed int)(signed char)m)) | + ((word32)a & (word32)( (signed int)(signed char)m))); +} + /* Constant time - bit set when a <= b. */ WC_MISC_STATIC WC_INLINE byte ctSetLTE(int a, int b) { diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index ee807d33c90..f25039b5fba 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -370,8 +370,8 @@ static int Hash_df(DRBG_internal* drbg, byte* out, word32 outSz, byte type, { int ret = DRBG_FAILURE; byte ctr; - int i; - int len; + word32 i; + word32 len; word32 bits = (outSz * 8); /* reverse byte order */ #ifdef WOLFSSL_SMALL_STACK_CACHE wc_Sha256* sha = &drbg->sha256; @@ -537,8 +537,8 @@ static int Hash_gen(DRBG_internal* drbg, byte* out, word32 outSz, const byte* V) byte data[DRBG_SEED_LEN]; byte digest[WC_SHA256_DIGEST_SIZE]; #endif - int i; - int len; + word32 i; + word32 len; #ifdef WOLFSSL_SMALL_STACK_CACHE wc_Sha256* sha = &drbg->sha256; #else @@ -621,9 +621,9 @@ static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen int sIdx, dIdx; word16 carry = 0; - dIdx = dLen - 1; + dIdx = (int)dLen - 1; for (sIdx = (int)sLen - 1; sIdx >= 0; sIdx--) { - carry += (word16)d[dIdx] + (word16)s[sIdx]; + carry += (word16)(d[dIdx] + s[sIdx]); d[dIdx] = (byte)carry; carry >>= 8; dIdx--; diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index eca9729cc7b..b638ae6fbe4 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -373,7 +373,7 @@ int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap, if (ret == 0) ret = wc_InitRsaKey_ex(key, heap, devId); if (ret == 0 && id != NULL && len != 0) { - XMEMCPY(key->id, id, len); + XMEMCPY(key->id, id, (size_t)len); key->idLen = len; #ifdef WOLFSSL_SE050 /* Set SE050 ID from word32, populate RsaKey with public from SE050 */ @@ -403,7 +403,7 @@ int wc_InitRsaKey_Label(RsaKey* key, const char* label, void* heap, int devId) if (ret == 0) ret = wc_InitRsaKey_ex(key, heap, devId); if (ret == 0) { - XMEMCPY(key->label, label, labelLen); + XMEMCPY(key->label, label, (size_t)labelLen); key->labelLen = labelLen; } @@ -1141,7 +1141,7 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, void* heap) { int ret; - int hLen; + word32 hLen; int psLen; int i; word32 idx; @@ -1163,10 +1163,11 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, } /* limit of label is the same as limit of hash function which is massive */ - hLen = wc_HashGetDigestSize(hType); - if (hLen < 0) { - return hLen; + ret = wc_HashGetDigestSize(hType); + if (ret < 0) { + return ret; } + hLen = (word32)ret; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER); @@ -1181,7 +1182,7 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, #else /* hLen should never be larger than lHash since size is max digest size, but check before blindly calling wc_Hash */ - if ((word32)hLen > sizeof(lHash)) { + if (hLen > sizeof(lHash)) { WOLFSSL_MSG("OAEP lHash to small for digest!!"); return MEMORY_E; } @@ -1204,7 +1205,7 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, k = RSA key size hLen = hash digest size -- will always be >= 0 at this point */ - if ((word32)(2 * hLen + 2) > pkcsBlockLen) { + if ((2 * hLen + 2) > pkcsBlockLen) { WOLFSSL_MSG("OAEP pad error hash to big for RSA key size"); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); @@ -1224,7 +1225,7 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, /* concatenate lHash || PS || 0x01 || msg */ idx = pkcsBlockLen - 1 - inputLen; - psLen = pkcsBlockLen - inputLen - 2 * hLen - 2; + psLen = (int)pkcsBlockLen - (int)inputLen - 2 * (int)hLen - 2; if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */ #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); @@ -1301,7 +1302,7 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, /* xor created seedMask with seed to make maskedSeed */ i = 0; - while (idx < (word32)(hLen + 1) && i < hLen) { + while (idx < (hLen + 1) && i < (int)hLen) { pkcsBlock[idx] = pkcsBlock[idx] ^ seed[i++]; idx++; } @@ -1635,7 +1636,7 @@ static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen, byte **output, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, void* heap) { - int hLen; + word32 hLen; int ret; byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */ word32 idx; @@ -1653,10 +1654,11 @@ static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen, return BUFFER_E; } - hLen = wc_HashGetDigestSize(hType); - if ((hLen < 0) || (pkcsBlockLen < (2 * (word32)hLen + 2))) { + ret = wc_HashGetDigestSize(hType); + if ((ret < 0) || (pkcsBlockLen < (2 * (word32)ret + 2))) { return BAD_FUNC_ARG; } + hLen = (word32)ret; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER); @@ -1730,16 +1732,16 @@ static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen, these checks. */ ret = 0; - ret |= ConstantCompare(pkcsBlock + hLen + 1, h, hLen); + ret |= ConstantCompare(pkcsBlock + hLen + 1, h, (int)hLen); ret += pkcsBlock[idx++] ^ 0x01; /* separator value is 0x01 */ ret += pkcsBlock[0] ^ 0x00; /* Y, the first value, should be 0 */ /* Return 0 data length on error. */ - idx = ctMaskSelInt(ctMaskEq(ret, 0), idx, pkcsBlockLen); + idx = ctMaskSelWord32(ctMaskEq(ret, 0), idx, pkcsBlockLen); /* adjust pointer to correct location in array and return size of M */ *output = (byte*)(pkcsBlock + idx); - return pkcsBlockLen - idx; + return (int)(pkcsBlockLen - idx); } #endif /* !WC_NO_RSA_OAEP */ @@ -1916,7 +1918,7 @@ static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen, } *output = (byte *)(pkcsBlock + i); - ret = pkcsBlockLen - i; + ret = (int)pkcsBlockLen - i; } #ifndef WOLFSSL_RSA_VERIFY_ONLY else { @@ -1928,21 +1930,21 @@ static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen, /* Decrypted with private key - unpad must be constant time. */ for (j = 2; j < pkcsBlockLen; j++) { /* Update i if not passed the separator and at separator. */ - i |= (~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (j + 1); + i |= (word16)(~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (word16)(j + 1); pastSep |= ctMask16Eq(pkcsBlock[j], 0x00); } /* Minimum of 11 bytes of pre-message data - including leading 0x00. */ invalid |= ctMaskLT(i, RSA_MIN_PAD_SZ); /* Must have seen separator. */ - invalid |= ~pastSep; + invalid |= (byte)~pastSep; /* First byte must be 0x00. */ invalid |= ctMaskNotEq(pkcsBlock[0], 0x00); /* Check against expected block type: padValue */ invalid |= ctMaskNotEq(pkcsBlock[1], padValue); *output = (byte *)(pkcsBlock + i); - ret = ((int)-1 + (int)(invalid >> 7)) & (pkcsBlockLen - i); + ret = ((int)-1 + (int)(invalid >> 7)) & ((int)pkcsBlockLen - i); } #endif @@ -2782,7 +2784,7 @@ static int RsaFunctionSync(const byte* in, word32 inLen, byte* out, } if (ret == 0) { - if (mp_to_unsigned_bin_len(tmp, out, *outLen) != MP_OKAY) + if (mp_to_unsigned_bin_len(tmp, out, (int)*outLen) != MP_OKAY) ret = MP_TO_E; } #else @@ -2803,11 +2805,14 @@ static int RsaFunctionSync(const byte* in, word32 inLen, byte* out, static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { -#ifdef WOLFSSL_HAVE_SP_RSA int ret; -#endif + word32 keyLen; - word32 keyLen = wc_RsaEncryptSize(key); + ret = wc_RsaEncryptSize(key); + if (ret < 0) { + return ret; + } + keyLen = (word32)ret; if (inLen > keyLen) { WOLFSSL_MSG("Expected that inLen be no longer RSA key length"); @@ -3187,8 +3192,7 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, #ifndef WOLF_CRYPTO_CB_ONLY_RSA if (ret != CRYPTOCB_UNAVAILABLE) return ret; - /* fall-through when unavailable */ - ret = 0; /* reset error code and try using software */ + /* fall-through when unavailable and try using software */ #else return ret; #endif @@ -3371,7 +3375,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, #endif /* WOLFSSL_CRYPTOCELL */ key->state = RSA_STATE_ENCRYPT_PAD; - ret = wc_RsaPad_ex(in, inLen, out, sz, pad_value, rng, pad_type, hash, + ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, pad_value, rng, pad_type, hash, mgf, label, labelSz, saltLen, mp_count_bits(&key->n), key->heap); if (ret < 0) { @@ -3384,7 +3388,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, case RSA_STATE_ENCRYPT_EXPTMOD: key->dataLen = outLen; - ret = wc_RsaFunction(out, sz, out, &key->dataLen, rsa_type, key, rng); + ret = wc_RsaFunction(out, (word32)sz, out, &key->dataLen, rsa_type, key, rng); if (ret >= 0 || ret == WC_PENDING_E) { key->state = RSA_STATE_ENCRYPT_RES; @@ -3396,7 +3400,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, FALL_THROUGH; case RSA_STATE_ENCRYPT_RES: - ret = key->dataLen; + ret = (int)key->dataLen; break; default: @@ -3588,8 +3592,8 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, for (j = 0; j < key->dataLen; j++) { signed char c; out[i] = key->data[j]; - c = ctMaskGTE(j, start); - c &= ctMaskLT(i, outLen); + c = (signed char)ctMaskGTE((int)j, start); + c &= (signed char)ctMaskLT((int)i, (int)outLen); /* 0 - no add, -1 add */ i += (word32)((byte)(-c)); } @@ -3597,14 +3601,14 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, else #endif { - XMEMCPY(out, pad, ret); + XMEMCPY(out, pad, (size_t)ret); } } else *outPtr = pad; #if !defined(WOLFSSL_RSA_VERIFY_ONLY) - ret = ctMaskSelInt(ctMaskLTE(ret, outLen), ret, RSA_BUFFER_E); + ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret, RSA_BUFFER_E); #ifndef WOLFSSL_RSA_DECRYPT_TO_0_LEN ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, RSA_BUFFER_E); #endif @@ -4545,7 +4549,7 @@ static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen, /* 4.4,5.5 - Check that prime >= (2^(1/2))(2^((nlen/2)-1)) * This is a comparison against lowerBound */ - ret = mp_read_unsigned_bin(tmp1, lower_bound, nlen/16); + ret = mp_read_unsigned_bin(tmp1, lower_bound, (word32)nlen/16); if (ret != MP_OKAY) goto notOkay; ret = mp_cmp(prime, tmp1); if (ret == MP_LT) goto exit; @@ -4723,7 +4727,8 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) mp_int tmp2_buf, *tmp2 = &tmp2_buf; mp_int tmp3_buf, *tmp3 = &tmp3_buf; #endif /* WOLFSSL_SMALL_STACK */ - int i, failCount, primeSz, isPrime = 0; + int i, failCount, isPrime = 0; + word32 primeSz; byte* buf = NULL; #endif /* !WOLFSSL_CRYPTOCELL && !WOLFSSL_SE050 */ int err; @@ -4826,7 +4831,7 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) /* The failCount value comes from NIST FIPS 186-4, section B.3.3, * process steps 4.7 and 5.8. */ failCount = 5 * (size / 2); - primeSz = size / 16; /* size is the size of n in bits. + primeSz = (word32)size / 16; /* size is the size of n in bits. primeSz is in bytes. */ /* allocate buffer to work with */ diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 02543f28ca2..19dd08ad759 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -245,7 +245,7 @@ do { \ int n##ii; \ (n)[0] = n##d; \ (n)[0]->size = (s); \ - for (n##ii = 1; n##ii < (c); n##ii++) { \ + for (n##ii = 1; n##ii < (int)(c); n##ii++) { \ (n)[n##ii] = MP_INT_NEXT((n)[n##ii-1], s); \ (n)[n##ii]->size = (s); \ } \ @@ -5037,9 +5037,9 @@ int sp_cond_swap_ct(sp_int* a, sp_int* b, int cnt, int swap) ALLOC_SP_INT(t, cnt, err, NULL); if (err == MP_OKAY) { /* XOR other fields in sp_int into temp - mask set when swapping. */ - t->used = (a->used ^ b->used) & mask; + t->used = (a->used ^ b->used) & (unsigned int)mask; #ifdef WOLFSSL_SP_INT_NEGATIVE - t->sign = (a->sign ^ b->sign) & mask; + t->sign = (a->sign ^ b->sign) & (unsigned int)mask; #endif /* XOR requested words into temp - mask set when swapping. */ @@ -7749,7 +7749,7 @@ int sp_lshd(sp_int* a, int s) /* Move up digits. */ XMEMMOVE(a->dp + s, a->dp, a->used * SP_WORD_SIZEOF); /* Back fill with zeros. */ - XMEMSET(a->dp, 0, s * SP_WORD_SIZEOF); + XMEMSET(a->dp, 0, (size_t)s * SP_WORD_SIZEOF); /* Update used. */ a->used += (unsigned int)s; /* Remove leading zeros. */ @@ -8597,7 +8597,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) } for (; k <= (a->used - 1) + (b->used - 1); k++) { j = (int)(b->used - 1); - i = k - j; + i = k - (unsigned int)j; for (; (i < a->used) && (j >= 0); i++, j--) { SP_ASM_MUL_ADD(l, h, o, a->dp[i], b->dp[j]); } @@ -13240,9 +13240,9 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, * - Montgomery form of base */ #ifndef WOLFSSL_SP_NO_MALLOC - ALLOC_DYN_SP_INT_ARRAY(t, m->used * 2 + 1, preCnt + 2, err, NULL); + ALLOC_DYN_SP_INT_ARRAY(t, m->used * 2 + 1, (size_t)preCnt + 2, err, NULL); #else - ALLOC_SP_INT_ARRAY(t, m->used * 2 + 1, preCnt + 2, err, NULL); + ALLOC_SP_INT_ARRAY(t, m->used * 2 + 1, (size_t)preCnt + 2, err, NULL); #endif if (err == MP_OKAY) { /* Set variables to use allocate memory. */ @@ -13412,7 +13412,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, n <<= winBits; c -= winBits; } - y &= mask; + y &= (int)mask; } /* 4.5. Montgomery multiply result by table entry. */ @@ -17751,7 +17751,7 @@ int sp_rand_prime(sp_int* r, int len, WC_RNG* rng, void* heap) } /* Get number of digits required to handle required number of bytes. */ - digits = (len + SP_WORD_SIZEOF - 1) / SP_WORD_SIZEOF; + digits = ((unsigned int)len + SP_WORD_SIZEOF - 1) / SP_WORD_SIZEOF; /* Ensure result has space. */ if (r->size < digits) { err = MP_VAL; @@ -17812,7 +17812,7 @@ int sp_rand_prime(sp_int* r, int len, WC_RNG* rng, void* heap) fflush(stdout); #endif /* SHOW_GEN */ /* Generate bytes into digit array. */ - err = wc_RNG_GenerateBlock(rng, (byte*)r->dp, len); + err = wc_RNG_GenerateBlock(rng, (byte*)r->dp, (word32)len); if (err != 0) { err = MP_VAL; break; @@ -18379,7 +18379,7 @@ static WC_INLINE int _sp_gcd(const sp_int* a, const sp_int* b, sp_int* r) /* Used for swapping sp_ints. */ sp_int* s; /* Determine maximum digit length numbers will reach. */ - int used = (a->used >= b->used) ? a->used + 1 : b->used + 1; + unsigned int used = (a->used >= b->used) ? a->used + 1 : b->used + 1; DECL_SP_INT_ARRAY(d, used, 3); SAVE_VECTOR_REGISTERS(err = _svr_ret;); diff --git a/wolfcrypt/src/wolfmath.c b/wolfcrypt/src/wolfmath.c index b7fe5c7c8d8..11e85cd74b5 100644 --- a/wolfcrypt/src/wolfmath.c +++ b/wolfcrypt/src/wolfmath.c @@ -149,10 +149,10 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) for (; i < b->used; i++) { b->dp[i] ^= (get_digit(a, (int)i) ^ get_digit(b, (int)i)) & mask; } - b->used ^= (a->used ^ b->used) & (mp_digit)mask; + b->used ^= (a->used ^ b->used) & (unsigned int)mask; #if (!defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_SP_MATH_ALL)) || \ defined(WOLFSSL_SP_INT_NEGATIVE) - b->sign ^= (a->sign ^ b->sign) & (mp_digit)mask; + b->sign ^= (a->sign ^ b->sign) & (unsigned int)mask; #endif } diff --git a/wolfssl/wolfcrypt/kdf.h b/wolfssl/wolfcrypt/kdf.h index 76c574e6a18..b1a64fe5d3b 100644 --- a/wolfssl/wolfcrypt/kdf.h +++ b/wolfssl/wolfcrypt/kdf.h @@ -76,8 +76,8 @@ enum { MAX_TLS13_HKDF_LABEL_SZ = 47 + WC_MAX_DIGEST_SIZE }; -WOLFSSL_API int wc_Tls13_HKDF_Extract(byte* prk, const byte* salt, int saltLen, - byte* ikm, int ikmLen, int digest); +WOLFSSL_API int wc_Tls13_HKDF_Extract(byte* prk, const byte* salt, + word32 saltLen, byte* ikm, word32 ikmLen, int digest); WOLFSSL_API int wc_Tls13_HKDF_Expand_Label(byte* okm, word32 okmLen, const byte* prk, word32 prkLen, diff --git a/wolfssl/wolfcrypt/misc.h b/wolfssl/wolfcrypt/misc.h index 0e9ff9869c8..f39352826a5 100644 --- a/wolfssl/wolfcrypt/misc.h +++ b/wolfssl/wolfcrypt/misc.h @@ -128,6 +128,7 @@ WOLFSSL_LOCAL word16 ctMask16Eq(int a, int b); WOLFSSL_LOCAL byte ctMaskNotEq(int a, int b); WOLFSSL_LOCAL byte ctMaskSel(byte m, byte a, byte b); WOLFSSL_LOCAL int ctMaskSelInt(byte m, int a, int b); +WOLFSSL_LOCAL word32 ctMaskSelWord32(byte m, word32 a, word32 b); WOLFSSL_LOCAL byte ctSetLTE(int a, int b); WOLFSSL_LOCAL void ctMaskCopy(byte mask, byte* dst, byte* src, word16 size); WOLFSSL_LOCAL word32 MakeWordFromHash(const byte* hashID); diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index 413ad6c824f..7d70a9c526d 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -669,8 +669,8 @@ typedef struct sp_ecc_ctx { */ #define sp_clamp(a) \ do { \ - unsigned int ii; \ - for (ii = (a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ + int ii; \ + for (ii = (int)(a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ } \ (a)->used = (unsigned int)ii + 1; \ } while (0) @@ -759,7 +759,7 @@ typedef struct sp_ecc_ctx { /* Calculate the number of words required to support a number of bits. */ #define MP_BITS_CNT(bits) \ - (((bits + SP_WORD_SIZE - 1) / SP_WORD_SIZE) * 2 + 1) + ((((bits) + SP_WORD_SIZE - 1) / SP_WORD_SIZE) * 2 + 1) #ifdef WOLFSSL_SMALL_STACK /* @@ -772,13 +772,13 @@ typedef struct sp_ecc_ctx { #define DECL_MP_INT_SIZE(name, bits) \ sp_int* name = NULL /* Allocate an mp_int of minimal size and zero out. */ -#define NEW_MP_INT_SIZE(name, bits, heap, type) \ -do { \ - name = (mp_int*)XMALLOC(MP_INT_SIZEOF(MP_BITS_CNT(bits)), heap, type); \ - if (name != NULL) { \ - XMEMSET(name, 0, MP_INT_SIZEOF(MP_BITS_CNT(bits))); \ - } \ -} \ +#define NEW_MP_INT_SIZE(name, bits, heap, type) \ +do { \ + (name) = (mp_int*)XMALLOC(MP_INT_SIZEOF(MP_BITS_CNT(bits)), heap, type); \ + if ((name) != NULL) { \ + XMEMSET(name, 0, MP_INT_SIZEOF(MP_BITS_CNT(bits))); \ + } \ +} \ while (0) /* Dispose of dynamically allocated mp_int. */ #define FREE_MP_INT_SIZE(name, heap, type) \ From 0652b92fa3a9bb16682a34232c17037116110c3b Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 10 Apr 2023 17:20:39 -0500 Subject: [PATCH 121/391] Revert "Fix `enum KeyWrap_Sum` impossible combinations (note: ugly code)." This reverts commit 2bac48a290e5243337f661c70eb582e55ceb2c39. --- wolfssl/wolfcrypt/asn.h | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index cda516080db..3d559cc9af2 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -1110,23 +1110,13 @@ enum KeyWrap_Sum { AES128_WRAP = 417 #endif #ifdef WOLFSSL_AES_192 - #ifdef WOLFSSL_AES_128 - , - #endif - AES192_WRAP = 437 + ,AES192_WRAP = 437 #endif #ifdef WOLFSSL_AES_256 - #if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) - , - #endif - AES256_WRAP = 457 + ,AES256_WRAP = 457 #endif #ifdef HAVE_PKCS7 - #if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) || \ - defined(WOLFSSL_AES_256) - , - #endif - PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ + ,PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ #endif }; #endif /* !NO_AES || PKCS7 */ From 169abefa35f08ac996c46b430d041d2fca7adf4d Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 10 Apr 2023 17:21:57 -0500 Subject: [PATCH 122/391] Revert "Resolve issue with C89 compliance with "commas at the end of enumerator lists"." This reverts commit 68acfd51dca1e0e11e2e7bd0e6ab956b8def6473. --- wolfssl/wolfcrypt/aes.h | 14 ++--- wolfssl/wolfcrypt/arc4.h | 2 +- wolfssl/wolfcrypt/asn.h | 86 +++++++++++++-------------- wolfssl/wolfcrypt/asn_public.h | 15 +++-- wolfssl/wolfcrypt/chacha.h | 2 +- wolfssl/wolfcrypt/chacha20_poly1305.h | 2 +- wolfssl/wolfcrypt/dh.h | 2 +- wolfssl/wolfcrypt/ecc.h | 8 +-- wolfssl/wolfcrypt/hash.h | 4 +- wolfssl/wolfcrypt/hmac.h | 26 ++++---- wolfssl/wolfcrypt/poly1305.h | 2 +- wolfssl/wolfcrypt/rsa.h | 9 ++- wolfssl/wolfcrypt/signature.h | 2 +- wolfssl/wolfcrypt/types.h | 2 +- 14 files changed, 87 insertions(+), 89 deletions(-) diff --git a/wolfssl/wolfcrypt/aes.h b/wolfssl/wolfcrypt/aes.h index fdf946d488d..449220994a2 100644 --- a/wolfssl/wolfcrypt/aes.h +++ b/wolfssl/wolfcrypt/aes.h @@ -138,7 +138,7 @@ enum { AES_192_KEY_SIZE = 24, /* for 192 bit */ AES_256_KEY_SIZE = 32, /* for 256 bit */ - AES_IV_SIZE = 16 /* always block size */ + AES_IV_SIZE = 16, /* always block size */ }; #endif @@ -165,20 +165,20 @@ enum { CCM_NONCE_MIN_SZ = 7, CCM_NONCE_MAX_SZ = 13, CTR_SZ = 4, - AES_IV_FIXED_SZ = 4 + AES_IV_FIXED_SZ = 4, #ifdef WOLFSSL_AES_CFB - ,AES_CFB_MODE = 1 + AES_CFB_MODE = 1, #endif #ifdef WOLFSSL_AES_OFB - ,AES_OFB_MODE = 2 + AES_OFB_MODE = 2, #endif #ifdef WOLFSSL_AES_XTS - ,AES_XTS_MODE = 3 + AES_XTS_MODE = 3, #endif #ifdef WOLF_PRIVATE_KEY_ID - ,AES_MAX_ID_LEN = 32, - AES_MAX_LABEL_LEN = 32 + AES_MAX_ID_LEN = 32, + AES_MAX_LABEL_LEN = 32, #endif }; diff --git a/wolfssl/wolfcrypt/arc4.h b/wolfssl/wolfcrypt/arc4.h index fe58b10ece9..ad97921681d 100644 --- a/wolfssl/wolfcrypt/arc4.h +++ b/wolfssl/wolfcrypt/arc4.h @@ -39,7 +39,7 @@ enum { ARC4_ENC_TYPE = 4, /* cipher unique type */ ARC4_STATE_SIZE = 256, - RC4_KEY_SIZE = 16 /* always 128bit */ + RC4_KEY_SIZE = 16, /* always 128bit */ }; /* ARC4 encryption and decryption */ diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 3d559cc9af2..489dcfe5517 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -154,7 +154,7 @@ enum ASN_Tags { /* OneAsymmetricKey Fields */ ASN_ASYMKEY_ATTRS = 0x00, - ASN_ASYMKEY_PUBKEY = 0x01 + ASN_ASYMKEY_PUBKEY = 0x01, }; /* NOTE: If ASN_UTC_TIME_SIZE or ASN_GENERALIZED_TIME_SIZE are ever modified @@ -188,7 +188,7 @@ enum ASNItem_DataType { /* Big number as a positive or negative mp_int. */ ASN_DATA_TYPE_MP_POS_NEG = 9, /* ASN.1 CHOICE. A 0 terminated list of tags that are valid. */ - ASN_DATA_TYPE_CHOICE = 10 + ASN_DATA_TYPE_CHOICE = 10, }; /* A template entry describing an ASN.1 item. */ @@ -831,22 +831,22 @@ enum ECC_TYPES }; #ifdef WOLFSSL_CERT_PIV -enum PIV_Tags { - ASN_PIV_CERT = 0x0A, - ASN_PIV_NONCE = 0x0B, - ASN_PIV_SIGNED_NONCE = 0x0C, - - ASN_PIV_TAG_CERT = 0x70, - ASN_PIV_TAG_CERT_INFO = 0x71, - ASN_PIV_TAG_MSCUID = 0x72, - ASN_PIV_TAG_ERR_DET = 0xFE, - - /* certificate info masks */ - ASN_PIV_CERT_INFO_COMPRESSED = 0x03, - ASN_PIV_CERT_INFO_ISX509 = 0x04, - /* GZIP is 0x01 */ - ASN_PIV_CERT_INFO_GZIP = 0x01, -}; + enum PIV_Tags { + ASN_PIV_CERT = 0x0A, + ASN_PIV_NONCE = 0x0B, + ASN_PIV_SIGNED_NONCE = 0x0C, + + ASN_PIV_TAG_CERT = 0x70, + ASN_PIV_TAG_CERT_INFO = 0x71, + ASN_PIV_TAG_MSCUID = 0x72, + ASN_PIV_TAG_ERR_DET = 0xFE, + + /* certificate info masks */ + ASN_PIV_CERT_INFO_COMPRESSED = 0x03, + ASN_PIV_CERT_INFO_ISX509 = 0x04, + /* GZIP is 0x01 */ + ASN_PIV_CERT_INFO_GZIP = 0x01, + }; #endif /* WOLFSSL_CERT_PIV */ @@ -994,7 +994,7 @@ enum Misc_ASN { PEM_LINE_SZ = 64, /* Length of Base64 encoded line, not including new line */ PEM_LINE_LEN = PEM_LINE_SZ + 12, /* PEM line max + fudge */ - COUNTRY_CODE_LEN = 2 /* RFC 3739 */ + COUNTRY_CODE_LEN = 2, /* RFC 3739 */ }; #ifndef WC_MAX_NAME_ENTRIES @@ -1060,20 +1060,20 @@ enum Block_Sum { #ifdef WOLFSSL_AES_128 AES128CBCb = 414, AES128GCMb = 418, - AES128CCMb = 419 + AES128CCMb = 419, #endif #ifdef WOLFSSL_AES_192 - ,AES192CBCb = 434, + AES192CBCb = 434, AES192GCMb = 438, - AES192CCMb = 439 + AES192CCMb = 439, #endif #ifdef WOLFSSL_AES_256 - ,AES256CBCb = 454, + AES256CBCb = 454, AES256GCMb = 458, - AES256CCMb = 459 + AES256CCMb = 459, #endif #ifndef NO_DES3 - ,DESb = 69, + DESb = 69, DES3b = 652 #endif }; @@ -1101,22 +1101,22 @@ enum Key_Sum { SPHINCS_FAST_LEVEL5k = 282, /* 1 3 9999 6 9 3 */ SPHINCS_SMALL_LEVEL1k = 287, /* 1 3 9999 6 7 10 */ SPHINCS_SMALL_LEVEL3k = 285, /* 1 3 9999 6 8 7 */ - SPHINCS_SMALL_LEVEL5k = 286 /* 1 3 9999 6 9 7 */ + SPHINCS_SMALL_LEVEL5k = 286, /* 1 3 9999 6 9 7 */ }; #if !defined(NO_AES) || defined(HAVE_PKCS7) enum KeyWrap_Sum { #ifdef WOLFSSL_AES_128 - AES128_WRAP = 417 + AES128_WRAP = 417, #endif #ifdef WOLFSSL_AES_192 - ,AES192_WRAP = 437 + AES192_WRAP = 437, #endif #ifdef WOLFSSL_AES_256 - ,AES256_WRAP = 457 + AES256_WRAP = 457, #endif #ifdef HAVE_PKCS7 - ,PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ + PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ #endif }; #endif /* !NO_AES || PKCS7 */ @@ -1126,14 +1126,14 @@ enum Key_Agree { dhSinglePass_stdDH_sha224kdf_scheme = 188, dhSinglePass_stdDH_sha256kdf_scheme = 189, dhSinglePass_stdDH_sha384kdf_scheme = 190, - dhSinglePass_stdDH_sha512kdf_scheme = 191 + dhSinglePass_stdDH_sha512kdf_scheme = 191, }; enum KDF_Sum { PBKDF2_OID = 660, - MGF1_OID = 652 + MGF1_OID = 652, }; @@ -1180,9 +1180,9 @@ enum Extensions_Sum { }; enum CertificatePolicy_Sum { - CP_ANY_OID = 146 /* id-ce 32 0 */ + CP_ANY_OID = 146, /* id-ce 32 0 */ #ifdef WOLFSSL_FPKI - ,CP_FPKI_COMMON_AUTH_OID = 426, /* 2.16.840.1.101.3.2.1.3.13 */ + CP_FPKI_COMMON_AUTH_OID = 426, /* 2.16.840.1.101.3.2.1.3.13 */ CP_FPKI_PIV_AUTH_OID = 453, /* 2.16.840.1.101.3.2.1.3.40 */ CP_FPKI_PIV_AUTH_HW_OID = 454, /* 2.16.840.1.101.3.2.1.3.41 */ CP_FPKI_PIVI_AUTH_OID = 458 /* 2.16.840.1.101.3.2.1.3.45 */ @@ -1195,9 +1195,9 @@ enum SepHardwareName_Sum { enum AuthInfo_Sum { AIA_OCSP_OID = 116, /* 1.3.6.1.5.5.7.48.1, id-ad-ocsp */ - AIA_CA_ISSUER_OID = 117 /* 1.3.6.1.5.5.7.48.2, id-ad-caIssuers */ + AIA_CA_ISSUER_OID = 117, /* 1.3.6.1.5.5.7.48.2, id-ad-caIssuers */ #ifdef WOLFSSL_SUBJ_INFO_ACC - ,AIA_CA_REPO_OID = 120 /* 1.3.6.1.5.5.7.48.5, id-ad-caRepository */ + AIA_CA_REPO_OID = 120 /* 1.3.6.1.5.5.7.48.5, id-ad-caRepository */ #endif /* WOLFSSL_SUBJ_INFO_ACC */ }; @@ -1244,7 +1244,7 @@ enum VerifyType { VERIFY_OCSP = 3, VERIFY_NAME = 4, VERIFY_SKIP_DATE = 5, - VERIFY_OCSP_CERT = 6 + VERIFY_OCSP_CERT = 6, }; #ifdef WOLFSSL_CERT_EXT @@ -1266,7 +1266,7 @@ enum CsrAttrType { INITIALS_OID = 132, SURNAME_OID = 93, NAME_OID = 130, - GIVEN_NAME_OID = 131 + GIVEN_NAME_OID = 131, }; #endif @@ -1349,7 +1349,7 @@ enum SignatureState { SIG_STATE_HASH, SIG_STATE_KEY, SIG_STATE_DO, - SIG_STATE_CHECK + SIG_STATE_CHECK, }; @@ -1459,7 +1459,7 @@ enum CertSignState { CERTSIGN_STATE_BEGIN, CERTSIGN_STATE_DIGEST, CERTSIGN_STATE_ENCODE, - CERTSIGN_STATE_DO + CERTSIGN_STATE_DO, }; struct CertSignCtx { @@ -2242,7 +2242,7 @@ enum cert_enums { SPHINCS_FAST_LEVEL5_KEY = 26, SPHINCS_SMALL_LEVEL1_KEY = 27, SPHINCS_SMALL_LEVEL3_KEY = 28, - SPHINCS_SMALL_LEVEL5_KEY = 29 + SPHINCS_SMALL_LEVEL5_KEY = 29, }; #endif /* WOLFSSL_CERT_GEN */ @@ -2527,7 +2527,7 @@ enum PBESTypes { PBES2 = 13, /* algo ID */ PBES1_MD5_DES = 3, - PBES1_SHA1_DES = 10 + PBES1_SHA1_DES = 10, }; enum PKCSTypes { @@ -2537,7 +2537,7 @@ enum PKCSTypes { PKCS8v0 = 0, /* default PKCS#8 version */ PKCS8v1 = 1, /* PKCS#8 version including public key */ PKCS1v0 = 0, /* default PKCS#1 version */ - PKCS1v1 = 1 /* Multi-prime version */ + PKCS1v1 = 1, /* Multi-prime version */ }; #endif /* !NO_ASN || !NO_PWDBASED */ diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index 7c5401c75be..fb43f974887 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -112,7 +112,7 @@ enum Ecc_Sum { ECC_SECP384R1_OID = 210, ECC_BRAINPOOLP384R1_OID = 108, ECC_BRAINPOOLP512R1_OID = 110, - ECC_SECP521R1_OID = 211 + ECC_SECP521R1_OID = 211, }; @@ -154,7 +154,7 @@ enum CertType { SPHINCS_SMALL_LEVEL1_TYPE, SPHINCS_SMALL_LEVEL3_TYPE, SPHINCS_SMALL_LEVEL5_TYPE, - ECC_PARAM_TYPE + ECC_PARAM_TYPE, }; @@ -202,7 +202,7 @@ enum Ctc_SigType { CTC_SPHINCS_FAST_LEVEL5 = 282, CTC_SPHINCS_SMALL_LEVEL1 = 287, CTC_SPHINCS_SMALL_LEVEL3 = 285, - CTC_SPHINCS_SMALL_LEVEL5 = 286 + CTC_SPHINCS_SMALL_LEVEL5 = 286, }; enum Ctc_Encoding { @@ -231,16 +231,15 @@ enum Ctc_Misc { CTC_GEN_SERIAL_SZ = 16, CTC_FILETYPE_ASN1 = 2, CTC_FILETYPE_PEM = 1, - CTC_FILETYPE_DEFAULT = 2 - + CTC_FILETYPE_DEFAULT = 2, #ifdef WOLFSSL_CERT_EXT /* AKID could contains: hash + (Option) AuthCertIssuer,AuthCertSerialNum * We support only hash */ - ,CTC_MAX_SKID_SIZE = 32, /* SHA256_DIGEST_SIZE */ + CTC_MAX_SKID_SIZE = 32, /* SHA256_DIGEST_SIZE */ CTC_MAX_AKID_SIZE = 32, /* SHA256_DIGEST_SIZE */ CTC_MAX_CERTPOL_SZ = 200, /* RFC 5280 Section 4.2.1.4 */ CTC_MAX_CERTPOL_NB = 2, /* Max number of Certificate Policy */ - CTC_MAX_CRLINFO_SZ = WC_CTC_MAX_CRLINFO_SZ /* Arbitrary size that should be + CTC_MAX_CRLINFO_SZ = WC_CTC_MAX_CRLINFO_SZ, /* Arbitrary size that should be * enough for at least two * distribution points. */ #endif /* WOLFSSL_CERT_EXT */ @@ -271,7 +270,7 @@ enum { #endif PEM_PASS_READ = 0, - PEM_PASS_WRITE = 1 + PEM_PASS_WRITE = 1, }; typedef int (wc_pem_password_cb)(char* passwd, int sz, int rw, void* userdata); diff --git a/wolfssl/wolfcrypt/chacha.h b/wolfssl/wolfcrypt/chacha.h index 7cd73db4e36..e654972ffb1 100644 --- a/wolfssl/wolfcrypt/chacha.h +++ b/wolfssl/wolfcrypt/chacha.h @@ -72,7 +72,7 @@ Block counter is located at index 12. enum { CHACHA_ENC_TYPE = WC_CIPHER_CHACHA, /* cipher unique type */ - CHACHA_MAX_KEY_SZ = 32 + CHACHA_MAX_KEY_SZ = 32, }; typedef struct ChaCha { diff --git a/wolfssl/wolfcrypt/chacha20_poly1305.h b/wolfssl/wolfcrypt/chacha20_poly1305.h index 6c04912a03c..7c1ddc97bb1 100644 --- a/wolfssl/wolfcrypt/chacha20_poly1305.h +++ b/wolfssl/wolfcrypt/chacha20_poly1305.h @@ -61,7 +61,7 @@ enum { CHACHA20_POLY1305_STATE_INIT = 0, CHACHA20_POLY1305_STATE_READY = 1, CHACHA20_POLY1305_STATE_AAD = 2, - CHACHA20_POLY1305_STATE_DATA = 3 + CHACHA20_POLY1305_STATE_DATA = 3, }; typedef struct ChaChaPoly_Aead { diff --git a/wolfssl/wolfcrypt/dh.h b/wolfssl/wolfcrypt/dh.h index e94cb593162..0b48c5cf74e 100644 --- a/wolfssl/wolfcrypt/dh.h +++ b/wolfssl/wolfcrypt/dh.h @@ -88,7 +88,7 @@ enum { WC_FFDHE_3072 = 257, WC_FFDHE_4096 = 258, WC_FFDHE_6144 = 259, - WC_FFDHE_8192 = 260 + WC_FFDHE_8192 = 260, }; /* DH Private Key size up to 8192 bit */ diff --git a/wolfssl/wolfcrypt/ecc.h b/wolfssl/wolfcrypt/ecc.h index 2f02c4ad464..72fb2c5b384 100644 --- a/wolfssl/wolfcrypt/ecc.h +++ b/wolfssl/wolfcrypt/ecc.h @@ -189,11 +189,11 @@ enum { ECC_POINT_UNCOMP = 0x04, /* Shamir's dual add constants */ - SHAMIR_PRECOMP_SZ = 16 + SHAMIR_PRECOMP_SZ = 16, #ifdef WOLF_PRIVATE_KEY_ID - ,ECC_MAX_ID_LEN = 32, - ECC_MAX_LABEL_LEN = 32 + ECC_MAX_ID_LEN = 32, + ECC_MAX_LABEL_LEN = 32, #endif }; @@ -413,7 +413,7 @@ typedef struct { enum { WC_ECC_FLAG_NONE = 0x00, WC_ECC_FLAG_COFACTOR = 0x01, - WC_ECC_FLAG_DEC_SIGN = 0x02 + WC_ECC_FLAG_DEC_SIGN = 0x02, }; /* ECC non-blocking */ diff --git a/wolfssl/wolfcrypt/hash.h b/wolfssl/wolfcrypt/hash.h index ad3ae2ccbcf..bf62ca8cf6c 100644 --- a/wolfssl/wolfcrypt/hash.h +++ b/wolfssl/wolfcrypt/hash.h @@ -82,9 +82,9 @@ enum wc_MACAlgorithm { enum wc_HashFlags { WC_HASH_FLAG_NONE = 0x00000000, WC_HASH_FLAG_WILLCOPY = 0x00000001, /* flag to indicate hash will be copied */ - WC_HASH_FLAG_ISCOPY = 0x00000002 /* hash is copy */ + WC_HASH_FLAG_ISCOPY = 0x00000002, /* hash is copy */ #ifdef WOLFSSL_SHA3 - ,WC_HASH_SHA3_KECCAK256 =0x00010000 /* Older KECCAK256 */ + WC_HASH_SHA3_KECCAK256 =0x00010000, /* Older KECCAK256 */ #endif }; diff --git a/wolfssl/wolfcrypt/hmac.h b/wolfssl/wolfcrypt/hmac.h index d6db41aa13c..86c97ebfbfe 100644 --- a/wolfssl/wolfcrypt/hmac.h +++ b/wolfssl/wolfcrypt/hmac.h @@ -70,42 +70,42 @@ enum { HMAC_FIPS_MIN_KEY = 14, /* 112 bit key length minimum */ IPAD = 0x36, - OPAD = 0x5C + OPAD = 0x5C, /* If any hash is not enabled, add the ID here. */ #ifdef NO_MD5 - ,WC_MD5 = WC_HASH_TYPE_MD5 + WC_MD5 = WC_HASH_TYPE_MD5, #endif #ifdef NO_SHA - ,WC_SHA = WC_HASH_TYPE_SHA + WC_SHA = WC_HASH_TYPE_SHA, #endif #ifdef NO_SHA256 - ,WC_SHA256 = WC_HASH_TYPE_SHA256 + WC_SHA256 = WC_HASH_TYPE_SHA256, #endif #ifndef WOLFSSL_SHA512 - ,WC_SHA512 = WC_HASH_TYPE_SHA512 + WC_SHA512 = WC_HASH_TYPE_SHA512, #ifndef WOLFSSL_NOSHA512_224 - ,WC_SHA512_224 = WC_HASH_TYPE_SHA512_224 + WC_SHA512_224 = WC_HASH_TYPE_SHA512_224, #endif #ifndef WOLFSSL_NOSHA512_256 - ,WC_SHA512_256 = WC_HASH_TYPE_SHA512_256 + WC_SHA512_256 = WC_HASH_TYPE_SHA512_256, #endif #endif #ifndef WOLFSSL_SHA384 - ,WC_SHA384 = WC_HASH_TYPE_SHA384 + WC_SHA384 = WC_HASH_TYPE_SHA384, #endif #ifndef WOLFSSL_SHA224 - ,WC_SHA224 = WC_HASH_TYPE_SHA224 + WC_SHA224 = WC_HASH_TYPE_SHA224, #endif #ifndef WOLFSSL_SHA3 - ,WC_SHA3_224 = WC_HASH_TYPE_SHA3_224, + WC_SHA3_224 = WC_HASH_TYPE_SHA3_224, WC_SHA3_256 = WC_HASH_TYPE_SHA3_256, WC_SHA3_384 = WC_HASH_TYPE_SHA3_384, - WC_SHA3_512 = WC_HASH_TYPE_SHA3_512 + WC_SHA3_512 = WC_HASH_TYPE_SHA3_512, #endif #ifdef WOLF_PRIVATE_KEY_ID - ,HMAC_MAX_ID_LEN = 32, - HMAC_MAX_LABEL_LEN = 32 + HMAC_MAX_ID_LEN = 32, + HMAC_MAX_LABEL_LEN = 32, #endif }; diff --git a/wolfssl/wolfcrypt/poly1305.h b/wolfssl/wolfcrypt/poly1305.h index c0a5b8dfc11..0fd9d3c3056 100644 --- a/wolfssl/wolfcrypt/poly1305.h +++ b/wolfssl/wolfcrypt/poly1305.h @@ -59,7 +59,7 @@ enum { POLY1305 = 7, POLY1305_BLOCK_SIZE = 16, - POLY1305_DIGEST_SIZE = 16 + POLY1305_DIGEST_SIZE = 16, }; #define WC_POLY1305_PAD_SZ 16 diff --git a/wolfssl/wolfcrypt/rsa.h b/wolfssl/wolfcrypt/rsa.h index 2cd78d7fd25..6d31aab558e 100644 --- a/wolfssl/wolfcrypt/rsa.h +++ b/wolfssl/wolfcrypt/rsa.h @@ -171,15 +171,14 @@ enum { RSA_PSS_PAD_TERM = 0xBC, #endif - RSA_PSS_SALT_LEN_DEFAULT = -1 - + RSA_PSS_SALT_LEN_DEFAULT = -1, #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER - ,RSA_PSS_SALT_LEN_DISCOVER = -2 + RSA_PSS_SALT_LEN_DISCOVER = -2, #endif #ifdef WOLF_PRIVATE_KEY_ID - ,RSA_MAX_ID_LEN = 32, - RSA_MAX_LABEL_LEN = 32 + RSA_MAX_ID_LEN = 32, + RSA_MAX_LABEL_LEN = 32, #endif }; diff --git a/wolfssl/wolfcrypt/signature.h b/wolfssl/wolfcrypt/signature.h index f712c0478af..ca641571cae 100644 --- a/wolfssl/wolfcrypt/signature.h +++ b/wolfssl/wolfcrypt/signature.h @@ -39,7 +39,7 @@ enum wc_SignatureType { WC_SIGNATURE_TYPE_NONE = 0, WC_SIGNATURE_TYPE_ECC = 1, WC_SIGNATURE_TYPE_RSA = 2, - WC_SIGNATURE_TYPE_RSA_W_ENC = 3 /* Adds DER header via wc_EncodeSignature */ + WC_SIGNATURE_TYPE_RSA_W_ENC = 3, /* Adds DER header via wc_EncodeSignature */ }; WOLFSSL_API int wc_SignatureGetSize(enum wc_SignatureType sig_type, diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 6ea779b497a..8e18d8c6385 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -971,7 +971,7 @@ typedef struct w64wrapper { DYNAMIC_TYPE_SNIFFER_PB_BUFFER = 1003, DYNAMIC_TYPE_SNIFFER_TICKET_ID = 1004, DYNAMIC_TYPE_SNIFFER_NAMED_KEY = 1005, - DYNAMIC_TYPE_SNIFFER_KEY = 1006 + DYNAMIC_TYPE_SNIFFER_KEY = 1006, }; /* max error buffer string size */ From 0163b378a116dd7328a902818de4d170b3133c65 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 10 Apr 2023 18:14:01 -0500 Subject: [PATCH 123/391] wolfcrypt/src/pkcs7.c:wc_PKCS7_DecodeAuthEnvelopedData(): fix clang-analyzer-core.DivideZero (expBlockSz not properly set before use as a denominator in a mod op). --- wolfcrypt/src/pkcs7.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index 57cf90ef024..ceb78ff9a85 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -11718,14 +11718,18 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, ret = ASN_PARSE_E; } - blockKeySz = wc_PKCS7_GetOIDKeySize(encOID); - if (ret == 0 && blockKeySz < 0) { - ret = blockKeySz; + if (ret == 0) { + blockKeySz = wc_PKCS7_GetOIDKeySize(encOID); + if (blockKeySz < 0) { + ret = blockKeySz; + } } - expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID); - if (ret == 0 && expBlockSz < 0) { - ret = expBlockSz; + if (ret == 0) { + expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID); + if (expBlockSz < 0) { + ret = expBlockSz; + } } /* get nonce, stored in OPTIONAL parameter of AlgoID @@ -11868,8 +11872,22 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; encryptedContentSz = pkcs7->stream->expected; + #else + pkiMsgSz = inSz; #endif + if (expBlockSz == 0) { + if (GetAlgoId(pkiMsg, &idx, &encOID, oidBlkType, pkiMsgSz) < 0) { + ret = ASN_PARSE_E; + break; + } + expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID); + if (expBlockSz < 0) { + ret = expBlockSz; + break; + } + } + /* AES-GCM/CCM does NOT require padding for plaintext content or * AAD inputs RFC 5084 section 3.1 and 3.2, but we must alloc * full blocks to ensure crypto only gets full blocks */ From e60dcbba03758b00b27988cae06603851d9f825d Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 10 Apr 2023 19:05:09 -0500 Subject: [PATCH 124/391] fix overlong lines. --- wolfcrypt/benchmark/benchmark.c | 3 +- wolfcrypt/src/asn.c | 100 ++++++++++++++++++++------------ wolfcrypt/src/ecc.c | 7 ++- wolfcrypt/src/misc.c | 8 ++- wolfcrypt/src/pkcs7.c | 3 +- wolfcrypt/src/rsa.c | 12 ++-- 6 files changed, 84 insertions(+), 49 deletions(-) diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 5885fa570e1..68949cbdaa8 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -6207,7 +6207,8 @@ static void bench_rsaKeyGen_helper(int useDeviceID, word32 keySz) goto exit; } - ret = wc_MakeRsaKey(&genKey[i], (int)keySz, rsa_e_val, &gRng); + ret = wc_MakeRsaKey(&genKey[i], (int)keySz, rsa_e_val, + &gRng); if (!bench_async_handle(&ret, BENCH_ASYNC_GET_DEV(&genKey[i]), 0, ×, &pending)) { diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 73189b3c7c9..8802340b4a6 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -1202,7 +1202,8 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, #endif return MP_INIT_E; } - err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx, (word32)len); + err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx, + (word32)len); if (err != 0) { #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err); @@ -7027,7 +7028,8 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, /* Only support default PKCS #8 format - v0. */ SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0); /* Set key OID that corresponds to key data. */ - SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID, oidKeyType); + SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID, + oidKeyType); if (curveOID != NULL && oidSz > 0) { /* ECC key and curveOID set to write. */ SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], curveOID, oidSz); @@ -8203,7 +8205,8 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, /* enc = OBJ enc_alg OCT iv */ encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz; /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */ - pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 + (size_t)encLen); + pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 + + (size_t)encLen); ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz); } @@ -8715,8 +8718,9 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) if (ret == 0) { /* Decrypt the key. */ - ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, (int)iterations, id, - key, (int)keySz, version, cbcIv, 0, (int)shaOid); + ret = wc_CryptKey( + password, passwordSz, salt, (int)saltSz, (int)iterations, id, key, + (int)keySz, version, cbcIv, 0, (int)shaOid); } if (ret == 0) { /* Copy the decrypted key into the input (inline). */ @@ -9067,7 +9071,8 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, if (ret == 0) { /* Setup data to go into encoding including PBE algorithm, salt, * iteration count, and padded key length. */ - SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id, oidPBEType); + SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id, + oidPBEType); if (salt == NULL || saltSz == 0) { salt = NULL; saltSz = PKCS5_SALT_SZ; @@ -9075,7 +9080,8 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, } SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT], salt, saltSz); - SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER], (word16)itt); + SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER], + (word16)itt); pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz); SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz); @@ -9103,7 +9109,8 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, if (salt == NULL) { /* Generate salt into encoding. */ - salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].data.buffer.data; + salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT]. + data.buffer.data; ret = wc_RNG_GenerateBlock(rng, salt, saltSz); } } @@ -9116,8 +9123,8 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, Pkcs8Pad(pkcs8, (int)inputSz, blockSz); /* Encrypt PKCS#8 key inline. */ - ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id, pkcs8, - (int)pkcs8Sz, version, cbcIv, 1, 0); + ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id, + pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0); } if (ret == 0) { /* Returning size on success. */ @@ -14752,19 +14759,21 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) dataASN[ALGOIDASN_IDX_NULL].noOut = 0; /* Include space for extra data of length curveSz. * Subtract 1 for sequence and 1 for length encoding. */ - SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL, (word32)curveSz - 2); + SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL, + (word32)curveSz - 2); } /* Calculate size of encoding. */ - ret = SizeASN_Items(algoIdASN + o, dataASN + o, (int)algoIdASN_Length - (int)o, - &sz); + ret = SizeASN_Items(algoIdASN + o, dataASN + o, + (int)algoIdASN_Length - (int)o, &sz); if (ret == 0 && output != NULL) { /* Encode into buffer. */ - SetASN_Items(algoIdASN + o, dataASN + o, (int)algoIdASN_Length - (int)o, - output); + SetASN_Items(algoIdASN + o, dataASN + o, + (int)algoIdASN_Length - (int)o, output); if (curveSz > 0) { /* Return size excluding curve data. */ - sz = (int)(dataASN[o].offset - dataASN[ALGOIDASN_IDX_NULL].offset); + sz = (int)(dataASN[o].offset - + dataASN[ALGOIDASN_IDX_NULL].offset); } } @@ -14845,7 +14854,8 @@ word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz, if (ret == 0) { /* Set hash OID and type. */ - SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID, oidHashType); + SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID, + oidHashType); /* Set digest. */ if (digest == out) { XMEMCPY(dgst, digest, digSz); @@ -16747,7 +16757,8 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, word32 idxDir = idx; /* Expecting a SEQUENCE using up all data. */ - if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0) { + if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0) + { WOLFSSL_MSG("\tfail: seq length"); return ASN_PARSE_E; } @@ -18970,12 +18981,13 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) if (ret == 0) { #if defined(WOLFSSL_CERT_EXT) - cert->extCertPoliciesNb = 0; + cert->extCertPoliciesNb = 0; #endif /* Strip SEQUENCE OF and check using all data. */ - if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0) { - ret = ASN_PARSE_E; + if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0) + { + ret = ASN_PARSE_E; } } @@ -19719,7 +19731,8 @@ static int DecodeCertExtensions(DecodedCert* cert) XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN)); /* Parse extensions header. */ ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset, - (int)(certExtHdrASN_Length - (size_t)offset), 0, input, &idx, (word32)sz); + (int)(certExtHdrASN_Length - (size_t)offset), 0, + input, &idx, (word32)sz); } /* Parse each extension. */ while ((ret == 0) && (idx < (word32)sz)) { @@ -20323,7 +20336,8 @@ static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt, /* Store references to password data. */ cert->cPwd = (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data; - cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length; + cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR]. + data.ref.length; } break; @@ -20342,7 +20356,8 @@ static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt, /* Store references to serial number. */ cert->sNum = (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data; - cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length; + cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR]. + data.ref.length; /* Store serial number if small enough. */ if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) { XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen); @@ -23105,7 +23120,8 @@ int PemToDer(const unsigned char* buff, long longSz, int type, #ifdef WOLFSSL_ENCRYPTED_KEYS if (info) { - ret = wc_EncryptedInfoParse(info, &headerEnd, (size_t)(bufferEnd - headerEnd)); + ret = wc_EncryptedInfoParse(info, &headerEnd, + (size_t)(bufferEnd - headerEnd)); if (ret < 0) return ret; if (info->set) @@ -26288,7 +26304,8 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, /* Copy data into dynamic vars. */ SetRdnItems(namesASN + idx, dataASN + idx, dcOid, sizeof(dcOid), (byte)name->name[j].type, - (byte*)name->name[j].value, (word32)name->name[j].sz); + (byte*)name->name[j].value, + (word32)name->name[j].sz); } idx += (int)rdnASN_Length; } @@ -27820,7 +27837,8 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, #ifndef NO_RSA if (rsaKey) { /* signature */ - ret = wc_RsaSSL_Sign(certSignCtx->encSig, (word32)certSignCtx->encSigSz, + ret = wc_RsaSSL_Sign(certSignCtx->encSig, + (word32)certSignCtx->encSigSz, sig, sigSz, rsaKey, rng); } #endif /* !NO_RSA */ @@ -28019,7 +28037,8 @@ int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz, /* In place, put body between SEQUENCE and signature. */ if (ret == 0) { /* Set sigature OID and signature data. */ - SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType, oidSigType); + SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType, + oidSigType); if (IsSigAlgoECC((word32)sigAlgoType)) { /* ECDSA and EdDSA doesn't have NULL tagged item. */ dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1; @@ -28038,7 +28057,8 @@ int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz, XMEMMOVE(buf + seqSz, buf, (size_t)bodySz); } /* Leave space for body in encoding. */ - SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL, (word32)bodySz); + SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL, + (word32)bodySz); /* Calculate overall size and put in offsets and lengths. */ ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz); @@ -28288,11 +28308,12 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, /* Don't write out outer sequence - only doing body. */ dataASN[X509CERTASN_IDX_SEQ].noOut = 1; /* Set version, serial number and signature OID */ - SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], (byte)cert->version); + SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], + (byte)cert->version); SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial, (word32)cert->serialSz); - SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], (word32)cert->sigType, - oidSigType); + SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], + (word32)cert->sigType, oidSigType); if (IsSigAlgoECC((word32)cert->sigType)) { /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */ dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1; @@ -30240,8 +30261,10 @@ static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded) ret = -1; } else { - XMEMCPY(cert->beforeDate, decoded->beforeDate, (size_t)decoded->beforeDateLen); - XMEMCPY(cert->afterDate, decoded->afterDate, (size_t)decoded->afterDateLen); + XMEMCPY(cert->beforeDate, decoded->beforeDate, + (size_t)decoded->beforeDateLen); + XMEMCPY(cert->afterDate, decoded->afterDate, + (size_t)decoded->afterDateLen); cert->beforeDateSz = decoded->beforeDateLen; cert->afterDateSz = decoded->afterDateLen; @@ -30569,7 +30592,8 @@ int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz) (int)sizeof(CertName))) { XMEMCPY(cert->sbjRaw, ((DecodedCert*)cert->decodedCert)->subjectRaw, - (size_t)((DecodedCert*)cert->decodedCert)->subjectRawLen); + (size_t)((DecodedCert*)cert->decodedCert)-> + subjectRawLen); } #ifndef WOLFSSL_CERT_GEN_CACHE wc_SetCert_Free(cert); @@ -30603,7 +30627,8 @@ int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz) /* Copy the subject to the issuer field */ XMEMCPY(cert->issRaw, ((DecodedCert*)cert->decodedCert)->subjectRaw, - (size_t)((DecodedCert*)cert->decodedCert)->subjectRawLen); + (size_t)((DecodedCert*)cert->decodedCert)-> + subjectRawLen); } #ifndef WOLFSSL_CERT_GEN_CACHE wc_SetCert_Free(cert); @@ -32988,7 +33013,8 @@ int SetAsymKeyDer(const byte* privKey, word32 privKeyLen, /* Set version = 0 */ SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0); /* Set OID. */ - SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType, oidKeyType); + SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType, + oidKeyType); /* Leave space for private key. */ SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen); /* Don't write out attributes. */ diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index a139acbe0bc..8bb0346298f 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -9146,7 +9146,7 @@ int wc_ecc_export_point_der_compressed(const int curve_idx, ecc_point* point, /* pad and store x */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(point->x, buf + - (numlen - (word32)mp_unsigned_bin_size(point->x))); + (numlen - (word32)mp_unsigned_bin_size(point->x))); if (ret != MP_OKAY) goto done; XMEMCPY(out+1, buf, numlen); @@ -14547,8 +14547,9 @@ static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen /* pad and store x */ XMEMSET(out+1, 0, numlen); - ret = mp_to_unsigned_bin(key->pubkey.x, - out+1 + (numlen - (word32)mp_unsigned_bin_size(key->pubkey.x))); + ret = mp_to_unsigned_bin( + key->pubkey.x, + out+1 + (numlen - (word32)mp_unsigned_bin_size(key->pubkey.x))); *outLen = 1 + numlen; return ret; diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index de8f4c7e244..3c47e517c93 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -330,8 +330,12 @@ WC_MISC_STATIC WC_INLINE void ForceZero(void* mem, word32 len) len -= l; while (l--) *z++ = 0; #endif - for (w = (volatile word64*)z; len >= sizeof(*w); len -= (word32)sizeof(*w)) - *w++ = 0; + for (w = (volatile word64*)z; + len >= sizeof(*w); + len -= (word32)sizeof(*w)) + { + *w++ = 0; + } z = (volatile byte*)w; #endif diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index ceb78ff9a85..e393d5ef311 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -11877,7 +11877,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, #endif if (expBlockSz == 0) { - if (GetAlgoId(pkiMsg, &idx, &encOID, oidBlkType, pkiMsgSz) < 0) { + if (GetAlgoId(pkiMsg, &idx, &encOID, oidBlkType, pkiMsgSz) < 0) + { ret = ASN_PARSE_E; break; } diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index b638ae6fbe4..54503236ea5 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -1930,7 +1930,8 @@ static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen, /* Decrypted with private key - unpad must be constant time. */ for (j = 2; j < pkcsBlockLen; j++) { /* Update i if not passed the separator and at separator. */ - i |= (word16)(~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (word16)(j + 1); + i |= (word16)(~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & + (word16)(j + 1); pastSep |= ctMask16Eq(pkcsBlock[j], 0x00); } @@ -3375,9 +3376,9 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, #endif /* WOLFSSL_CRYPTOCELL */ key->state = RSA_STATE_ENCRYPT_PAD; - ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, pad_value, rng, pad_type, hash, - mgf, label, labelSz, saltLen, mp_count_bits(&key->n), - key->heap); + ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, pad_value, rng, pad_type, + hash, mgf, label, labelSz, saltLen, + mp_count_bits(&key->n), key->heap); if (ret < 0) { break; } @@ -3388,7 +3389,8 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, case RSA_STATE_ENCRYPT_EXPTMOD: key->dataLen = outLen; - ret = wc_RsaFunction(out, (word32)sz, out, &key->dataLen, rsa_type, key, rng); + ret = wc_RsaFunction(out, (word32)sz, out, &key->dataLen, rsa_type, key, + rng); if (ret >= 0 || ret == WC_PENDING_E) { key->state = RSA_STATE_ENCRYPT_RES; From 88f65856079717d5a2760fd07619cb88eee84ad4 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 10 Apr 2023 20:25:46 -0500 Subject: [PATCH 125/391] wolfcrypt/src/ecc.c:fix overstringent arg check in wc_ecc_gen_k(). --- wolfcrypt/src/ecc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 8bb0346298f..d65515520cc 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -4974,7 +4974,7 @@ int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) int err; byte buf[ECC_MAXSIZE_GEN]; - if (rng == NULL || size <= 0 || size + 8 > ECC_MAXSIZE_GEN || k == NULL || + if (rng == NULL || size < 0 || size + 8 > ECC_MAXSIZE_GEN || k == NULL || order == NULL) { return BAD_FUNC_ARG; } From f844aae3daaede5857668f59604ff9b07e673efc Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 12 Apr 2023 02:17:18 -0500 Subject: [PATCH 126/391] more fixes for implicit casts, mostly asn=original. --- wolfcrypt/src/asn.c | 707 ++++++++++++++++++++++-------------------- wolfcrypt/src/hash.c | 10 +- wolfcrypt/src/pkcs7.c | 2 +- wolfcrypt/test/test.c | 2 +- 4 files changed, 385 insertions(+), 336 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 8802340b4a6..c0ca6387226 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -3285,7 +3285,7 @@ static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx) if (ret != 0) return ret; - *inOutIdx = idx + length; + *inOutIdx = idx + (word32)length; return 0; } @@ -3855,7 +3855,7 @@ static word32 SetBitString16Bit(word16 val, byte* output) while (((lastByte >> unusedBits) & 0x01) == 0x00) unusedBits++; - idx = SetBitString(len, unusedBits, output); + idx = SetBitString((word32)len, unusedBits, output); output[idx++] = (byte)val; if (len > 1) output[idx++] = (byte)(val >> 8); @@ -6391,7 +6391,7 @@ static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) { return ASN_PARSE_E; } - *inOutIdx += *keySz; + *inOutIdx += (word32)*keySz; for (i = 1; i < RSA_INTS; i++) { if (SkipInt(input, inOutIdx, inSz) < 0) { return ASN_RSA_KEY_E; @@ -8540,7 +8540,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) } #endif - XMEMCPY(salt, &input[inOutIdx], saltSz); + XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz); inOutIdx += (word32)saltSz; if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) { @@ -8598,7 +8598,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) ERROR_OUT(ASN_PARSE_E, exit_dc); } - XMEMCPY(cbcIv, &input[inOutIdx], length); + XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length); inOutIdx += (word32)length; } @@ -8624,7 +8624,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) #endif if (ret == 0) { - XMEMMOVE(input, input + inOutIdx, length); + XMEMMOVE(input, input + inOutIdx, (size_t)length); ret = length; } @@ -9745,7 +9745,7 @@ int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz) /* the version (0) - private only (for public skip) */ if (GetASNInt(input, inOutIdx, &length, inSz) == 0) { - *inOutIdx += length; + *inOutIdx += (word32)length; } /* Size of dhKeyAgreement section */ @@ -9873,8 +9873,8 @@ int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz) int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) { #ifndef WOLFSSL_ASN_TEMPLATE - int ret, privSz = 0, pubSz = 0, keySz; - word32 idx, len, total; + int ret, privSz = 0, pubSz = 0; + word32 keySz, idx, len, total; if (key == NULL || outSz == NULL) { return BAD_FUNC_ARG; @@ -9884,12 +9884,17 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) if (exportPriv) { /* octect string: priv */ privSz = SetASNIntMP(&key->priv, -1, NULL); - idx = 1 + SetLength(privSz, NULL) + privSz; /* +1 for ASN_OCTET_STRING */ + if (privSz < 0) + return privSz; + idx = 1 + SetLength((word32)privSz, NULL) + + (word32)privSz; /* +1 for ASN_OCTET_STRING */ } else { /* bit string: public */ pubSz = SetASNIntMP(&key->pub, -1, NULL); - idx = SetBitString(pubSz, 0, NULL) + pubSz; + if (pubSz < 0) + return pubSz; + idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz; } keySz = idx; @@ -9929,7 +9934,7 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) idx = SetSequence(total, output); if (exportPriv) { /* version: 0 */ - idx += SetMyVersion(0, output + idx, 0); + idx += (word32)SetMyVersion(0, output + idx, 0); } /* sequence - all but pub/priv */ idx += SetSequence(len, output + idx); @@ -9947,17 +9952,17 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) /* octect string: priv */ if (exportPriv) { - idx += SetOctetString(privSz, output + idx); - idx += SetASNIntMP(&key->priv, -1, output + idx); + idx += (word32)SetOctetString((word32)privSz, output + idx); + idx += (word32)SetASNIntMP(&key->priv, -1, output + idx); } else { /* bit string: public */ - idx += SetBitString(pubSz, 0, output + idx); - idx += SetASNIntMP(&key->pub, -1, output + idx); + idx += (word32)SetBitString((word32)pubSz, 0, output + idx); + idx += (word32)SetASNIntMP(&key->pub, -1, output + idx); } *outSz = idx; - return idx; + return (int)idx; #else ASNSetData dataASN[dhKeyPkcs8ASN_Length]; int ret = 0; @@ -10031,6 +10036,7 @@ int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz) int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz) { #ifndef WOLFSSL_ASN_TEMPLATE + int ret; word32 idx, total; if (key == NULL || outSz == NULL) { @@ -10039,9 +10045,15 @@ int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz) /* determine size */ /* integer - g */ - idx = SetASNIntMP(&key->g, -1, NULL); + ret = SetASNIntMP(&key->g, -1, NULL); + if (ret < 0) + return ret; + idx = (word32)ret; /* integer - p */ - idx += SetASNIntMP(&key->p, -1, NULL); + ret = SetASNIntMP(&key->p, -1, NULL); + if (ret < 0) + return ret; + idx += (word32)ret; total = idx; /* sequence */ idx += SetSequence(idx, NULL); @@ -10060,12 +10072,18 @@ int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz) /* sequence - for P and G only */ idx = SetSequence(total, output); /* integer - p */ - idx += SetASNIntMP(&key->p, -1, output + idx); + ret = SetASNIntMP(&key->p, -1, output + idx); + if (ret < 0) + return ret; + idx += (word32)ret; /* integer - g */ - idx += SetASNIntMP(&key->g, -1, output + idx); + ret = SetASNIntMP(&key->g, -1, output + idx); + if (ret < 0) + return ret; + idx += (word32)ret; *outSz = idx; - return idx; + return (int)idx; #else ASNSetData dataASN[dhParamASN_Length]; int ret = 0; @@ -10148,7 +10166,7 @@ int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz, return ret; if (length <= (int)*pInOutSz) { - XMEMCPY(p, &input[idx], length); + XMEMCPY(p, &input[idx], (size_t)length); *pInOutSz = (word32)length; } else { @@ -10161,7 +10179,7 @@ int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz, return ret; if (length <= (int)*gInOutSz) { - XMEMCPY(g, &input[idx], length); + XMEMCPY(g, &input[idx], (size_t)length); *gInOutSz = (word32)length; } else { @@ -10316,7 +10334,7 @@ int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key, if (GetSequence(input, inOutIdx, &length, inSz) < 0) return ASN_PARSE_E; - maxIdx = (word32)(*inOutIdx + length); + maxIdx = (word32)(*inOutIdx + (word32)length); if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 || GetInt(&key->q, input, inOutIdx, maxIdx) < 0 || GetInt(&key->g, input, inOutIdx, maxIdx) < 0 || @@ -10533,7 +10551,7 @@ int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key, } /* An alternate pass if default certificate fails parsing */ if (ret == ASN_PARSE_E) { - *inOutIdx = temp; + *inOutIdx = (word32)temp; if (GetMyVersion(input, inOutIdx, &version, inSz) < 0) return ASN_PARSE_E; @@ -10645,8 +10663,8 @@ int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header) byte innerSeq[MAX_SEQ_SZ]; byte outerSeq[MAX_SEQ_SZ]; byte bitString[1 + MAX_LENGTH_SZ + 1]; - int idx, pSz, gSz, qSz, ySz, innerSeqSz, outerSeqSz, bitStringSz = 0; - + int pSz, gSz, qSz, ySz; + word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0; WOLFSSL_ENTER("wc_SetDsaPublicKey"); if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) { @@ -10716,7 +10734,7 @@ int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header) } if (with_header) { - int algoSz; + word32 algoSz; #ifdef WOLFSSL_SMALL_STACK byte* algo = NULL; @@ -10731,18 +10749,19 @@ int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header) #else byte algo[MAX_ALGO_SZ]; #endif - innerSeqSz = SetSequence(pSz + qSz + gSz, innerSeq); + innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq); algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0); - bitStringSz = SetBitString(ySz, 0, bitString); - outerSeqSz = SetSequence(algoSz + innerSeqSz + pSz + qSz + gSz, - outerSeq); + bitStringSz = SetBitString((word32)ySz, 0, bitString); + outerSeqSz = SetSequence(algoSz + innerSeqSz + + (word32)(pSz + qSz + gSz), outerSeq); - idx = SetSequence(algoSz + innerSeqSz + pSz + qSz + gSz + bitStringSz + - ySz + outerSeqSz, output); + idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) + + bitStringSz + (word32)ySz + outerSeqSz, output); /* check output size */ - if ((idx + algoSz + bitStringSz + innerSeqSz + pSz + qSz + gSz + ySz) > - outLen) { + if ((idx + algoSz + bitStringSz + innerSeqSz + + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) + { #ifdef WOLFSSL_SMALL_STACK XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER); XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -10764,10 +10783,10 @@ int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header) XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif } else { - innerSeqSz = SetSequence(pSz + qSz + gSz + ySz, innerSeq); + innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq); /* check output size */ - if ((innerSeqSz + pSz + qSz + gSz + ySz) > outLen) { + if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) { #ifdef WOLFSSL_SMALL_STACK XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER); XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -10785,22 +10804,22 @@ int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header) XMEMCPY(output + idx, innerSeq, innerSeqSz); idx += innerSeqSz; /* p */ - XMEMCPY(output + idx, p, pSz); - idx += pSz; + XMEMCPY(output + idx, p, (size_t)pSz); + idx += (word32)pSz; /* q */ - XMEMCPY(output + idx, q, qSz); - idx += qSz; + XMEMCPY(output + idx, q, (size_t)qSz); + idx += (word32)qSz; /* g */ - XMEMCPY(output + idx, g, gSz); - idx += gSz; + XMEMCPY(output + idx, g, (size_t)gSz); + idx += (word32)gSz; /* bit string */ if (bitStringSz > 0) { XMEMCPY(output + idx, bitString, bitStringSz); idx += bitStringSz; } /* y */ - XMEMCPY(output + idx, y, ySz); - idx += ySz; + XMEMCPY(output + idx, y, (size_t)ySz); + idx += (word32)ySz; #ifdef WOLFSSL_SMALL_STACK XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -10808,7 +10827,7 @@ int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header) XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER); XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif - return idx; + return (int)idx; #else DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length); int ret = 0; @@ -10889,9 +10908,9 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, int ints, int includeVersion) { #ifndef WOLFSSL_ASN_TEMPLATE - word32 seqSz = 0, verSz = 0, intTotalLen = 0; + word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j; word32 sizes[DSA_INTS]; - int i, j, outLen, ret = 0; + int i, ret = 0; byte seq[MAX_SEQ_SZ]; byte ver[MAX_VERSION_SZ]; @@ -10908,7 +10927,7 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, for (i = 0; i < ints; i++) { int mpSz; mp_int* keyInt = GetDsaInt(key, i); - word32 rawLen = mp_unsigned_bin_size(keyInt) + 1; + word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1; tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap, DYNAMIC_TYPE_DSA); @@ -10922,7 +10941,8 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, ret = mpSz; break; } - intTotalLen += (sizes[i] = mpSz); + sizes[i] = (word32)mpSz; + intTotalLen += (word32)mpSz; } if (ret != 0) { @@ -10932,7 +10952,7 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, /* make headers */ if (includeVersion) - verSz = SetMyVersion(0, ver, FALSE); + verSz = (word32)SetMyVersion(0, ver, FALSE); seqSz = SetSequence(verSz + intTotalLen, seq); outLen = seqSz + verSz + intTotalLen; @@ -10941,7 +10961,7 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, FreeTmpDsas(tmps, key->heap, ints); return LENGTH_ONLY_E; } - if (outLen > (int)*inLen) { + if (outLen > *inLen) { FreeTmpDsas(tmps, key->heap, ints); return BAD_FUNC_ARG; } @@ -10960,7 +10980,7 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, } FreeTmpDsas(tmps, key->heap, ints); - return outLen; + return (int)outLen; #else DECL_ASNSETDATA(dataASN, dsaKeyASN_Length); int ret = 0; @@ -11488,7 +11508,8 @@ static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx, #endif #ifdef HAVE_OCSP - ret = CalcHashId(source + *srcIdx, length, cert->subjectKeyHash); + ret = CalcHashId(source + *srcIdx, (word32)length, + cert->subjectKeyHash); if (ret != 0) return ret; #endif @@ -11627,7 +11648,7 @@ static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx, if (ret != 0) return ASN_PARSE_E; - *srcIdx += length; + *srcIdx += (word32)length; return 0; #else @@ -12656,7 +12677,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, } #endif - length += srcIdx; + length += (int)srcIdx; idx = 0; while (srcIdx < (word32)length) { @@ -12729,7 +12750,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, else if (nameType == ISSUER) { cert->issuerCN = (char*)&input[srcIdx]; cert->issuerCNLen = strLen; - cert->issuerCNEnc = b; + cert->issuerCNEnc = (char)b; } #endif @@ -12813,13 +12834,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectSN = (char*)&input[srcIdx]; cert->subjectSNLen = strLen; - cert->subjectSNEnc = b; + cert->subjectSNEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) else if (nameType == ISSUER) { cert->issuerSN = (char*)&input[srcIdx]; cert->issuerSNLen = strLen; - cert->issuerSNEnc = b; + cert->issuerSNEnc = (char)b; } #endif /* WOLFSSL_HAVE_ISSUER_NAMES */ #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ @@ -12836,13 +12857,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectC = (char*)&input[srcIdx]; cert->subjectCLen = strLen; - cert->subjectCEnc = b; + cert->subjectCEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) else if (nameType == ISSUER) { cert->issuerC = (char*)&input[srcIdx]; cert->issuerCLen = strLen; - cert->issuerCEnc = b; + cert->issuerCEnc = (char)b; } #endif /* WOLFSSL_HAVE_ISSUER_NAMES */ #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ @@ -12859,13 +12880,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectL = (char*)&input[srcIdx]; cert->subjectLLen = strLen; - cert->subjectLEnc = b; + cert->subjectLEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) else if (nameType == ISSUER) { cert->issuerL = (char*)&input[srcIdx]; cert->issuerLLen = strLen; - cert->issuerLEnc = b; + cert->issuerLEnc = (char)b; } #endif /* WOLFSSL_HAVE_ISSUER_NAMES */ #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ @@ -12882,13 +12903,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectST = (char*)&input[srcIdx]; cert->subjectSTLen = strLen; - cert->subjectSTEnc = b; + cert->subjectSTEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) else if (nameType == ISSUER) { cert->issuerST = (char*)&input[srcIdx]; cert->issuerSTLen = strLen; - cert->issuerSTEnc = b; + cert->issuerSTEnc = (char)b; } #endif /* WOLFSSL_HAVE_ISSUER_NAMES */ #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/ @@ -12905,13 +12926,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectO = (char*)&input[srcIdx]; cert->subjectOLen = strLen; - cert->subjectOEnc = b; + cert->subjectOEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) else if (nameType == ISSUER) { cert->issuerO = (char*)&input[srcIdx]; cert->issuerOLen = strLen; - cert->issuerOEnc = b; + cert->issuerOEnc = (char)b; } #endif /* WOLFSSL_HAVE_ISSUER_NAMES */ #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ @@ -12928,13 +12949,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectOU = (char*)&input[srcIdx]; cert->subjectOULen = strLen; - cert->subjectOUEnc = b; + cert->subjectOUEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) else if (nameType == ISSUER) { cert->issuerOU = (char*)&input[srcIdx]; cert->issuerOULen = strLen; - cert->issuerOUEnc = b; + cert->issuerOUEnc = (char)b; } #endif /* WOLFSSL_HAVE_ISSUER_NAMES */ #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ @@ -12951,13 +12972,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectSND = (char*)&input[srcIdx]; cert->subjectSNDLen = strLen; - cert->subjectSNDEnc = b; + cert->subjectSNDEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) else if (nameType == ISSUER) { cert->issuerSND = (char*)&input[srcIdx]; cert->issuerSNDLen = strLen; - cert->issuerSNDEnc = b; + cert->issuerSNDEnc = (char)b; } #endif /* WOLFSSL_HAVE_ISSUER_NAMES */ #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ @@ -12974,7 +12995,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectUID = (char*)&input[srcIdx]; cert->subjectUIDLen = strLen; - cert->subjectUIDEnc = b; + cert->subjectUIDEnc = (char)b; } #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ #if (defined(OPENSSL_EXTRA) || \ @@ -12991,7 +13012,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectStreet = (char*)&input[srcIdx]; cert->subjectStreetLen = strLen; - cert->subjectStreetEnc = b; + cert->subjectStreetEnc = (char)b; } #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ #if (defined(OPENSSL_EXTRA) || \ @@ -13007,7 +13028,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectBC = (char*)&input[srcIdx]; cert->subjectBCLen = strLen; - cert->subjectBCEnc = b; + cert->subjectBCEnc = (char)b; } #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \ @@ -13022,7 +13043,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectPC = (char*)&input[srcIdx]; cert->subjectPCLen = strLen; - cert->subjectPCEnc = b; + cert->subjectPCEnc = (char)b; } #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/ #if (defined(OPENSSL_EXTRA) || \ @@ -13061,7 +13082,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectJC = (char*)&input[srcIdx]; cert->subjectJCLen = strLen; - cert->subjectJCEnc = b; + cert->subjectJCEnc = (char)b; } #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ #if (defined(OPENSSL_EXTRA) || \ @@ -13079,7 +13100,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (nameType == SUBJECT) { cert->subjectJS = (char*)&input[srcIdx]; cert->subjectJSLen = strLen; - cert->subjectJSEnc = b; + cert->subjectJSEnc = (char)b; } #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ #if (defined(OPENSSL_EXTRA) || \ @@ -13207,9 +13228,9 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, tooBig = TRUE; } if ((copy != NULL) && !tooBig) { - XMEMCPY(&full[idx], copy, copyLen); + XMEMCPY(&full[idx], copy, (size_t)copyLen); idx += (word32)copyLen; - XMEMCPY(&full[idx], &input[srcIdx], strLen); + XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen); idx += (word32)strLen; } #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ @@ -13474,7 +13495,7 @@ int GetName(DecodedCert* cert, int nameType, int maxIdx) if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) { return ASN_PARSE_E; } - length += localIdx - cert->srcIdx; + length += (int)(localIdx - cert->srcIdx); return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx, cert->srcIdx + (word32)length); @@ -14105,7 +14126,7 @@ static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx) return ret; XMEMSET(date, 0, MAX_DATE_SIZE); - XMEMCPY(date, datePtr, length); + XMEMCPY(date, datePtr, (size_t)length); if (dateType == BEFORE) cert->beforeDateLen = (int)(cert->srcIdx - startIdx); @@ -14693,7 +14714,7 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) word32 length = 0; tagSz = (type == oidHashType || - (type == oidSigType && !IsSigAlgoECC(algoOID)) || + (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) || (type == oidKeyType && algoOID == RSAk)) ? 2 : 0; algoName = OidFromId((word32)algoOID, (word32)type, &algoSz); @@ -16300,7 +16321,7 @@ static int MatchBaseName(int type, const char* name, int nameSz, } if (type == ASN_DIR_TYPE) - return XMEMCMP(name, base, (word32)baseSz) == 0; + return XMEMCMP(name, base, (size_t)baseSz) == 0; /* If an email type, handle special cases where the base is only * a domain, or is an email address itself. */ @@ -16891,7 +16912,7 @@ enum { #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE) /* return 0 on success */ static int DecodeSepHwAltName(DecodedCert* cert, const byte* input, - word32* idxIn, int sz) + word32* idxIn, word32 sz) { word32 idx = *idxIn; int strLen; @@ -16931,16 +16952,16 @@ static int DecodeSepHwAltName(DecodedCert* cert, const byte* input, return ret; } - cert->hwType = (byte*)XMALLOC(strLen, cert->heap, + cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap, DYNAMIC_TYPE_X509_EXT); if (cert->hwType == NULL) { WOLFSSL_MSG("\tOut of Memory"); return MEMORY_E; } - XMEMCPY(cert->hwType, &input[idx], strLen); + XMEMCPY(cert->hwType, &input[idx], (size_t)strLen); cert->hwTypeSz = strLen; - idx += strLen; + idx += (word32)strLen; ret = GetOctetString(input, &idx, &strLen, sz); if (ret < 0) { @@ -16949,7 +16970,7 @@ static int DecodeSepHwAltName(DecodedCert* cert, const byte* input, return ret; } - cert->hwSerialNum = (byte*)XMALLOC(strLen + 1, cert->heap, + cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap, DYNAMIC_TYPE_X509_EXT); if (cert->hwSerialNum == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -16958,10 +16979,10 @@ static int DecodeSepHwAltName(DecodedCert* cert, const byte* input, return MEMORY_E; } - XMEMCPY(cert->hwSerialNum, &input[idx], strLen); + XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen); cert->hwSerialNum[strLen] = '\0'; cert->hwSerialNumSz = strLen; - idx += strLen; + idx += (word32)strLen; *idxIn = idx; return 0; @@ -17036,7 +17057,7 @@ static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input, if (ret == 0 && dnsEntry != NULL) { dnsEntry->type = ASN_OTHER_TYPE; dnsEntry->len = strLen; - dnsEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, + dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); #ifdef WOLFSSL_FPKI dnsEntry->oidSum = oid; @@ -17046,7 +17067,7 @@ static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input, ret = MEMORY_E; } else { - XMEMCPY(dnsEntry->name, &input[*idx], (word32)strLen); + XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen); dnsEntry->name[strLen] = '\0'; AddAltName(cert, dnsEntry); } @@ -17128,7 +17149,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) WOLFSSL_MSG("\tfail: str length"); return ASN_PARSE_E; } - length -= (idx - lenStartIdx); + length -= (int)(idx - lenStartIdx); dnsEntry = AltNameNew(cert->heap); if (dnsEntry == NULL) { @@ -17137,7 +17158,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) } dnsEntry->type = ASN_DNS_TYPE; - dnsEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, + dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (dnsEntry->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17145,7 +17166,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) return MEMORY_E; } dnsEntry->len = strLen; - XMEMCPY(dnsEntry->name, &input[idx], strLen); + XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen); dnsEntry->name[strLen] = '\0'; AddAltName(cert, dnsEntry); @@ -17169,7 +17190,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) WOLFSSL_MSG("\tfail: seq length"); return ASN_PARSE_E; } - length -= (idx - lenStartIdx); + length -= (int)(idx - lenStartIdx); dirEntry = AltNameNew(cert->heap); if (dirEntry == NULL) { @@ -17178,7 +17199,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) } dirEntry->type = ASN_DIR_TYPE; - dirEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, + dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (dirEntry->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17186,7 +17207,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) return MEMORY_E; } dirEntry->len = strLen; - XMEMCPY(dirEntry->name, &input[idx], strLen); + XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen); dirEntry->name[strLen] = '\0'; dirEntry->next = cert->altDirNames; cert->altDirNames = dirEntry; @@ -17203,7 +17224,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) WOLFSSL_MSG("\tfail: str length"); return ASN_PARSE_E; } - length -= (idx - lenStartIdx); + length -= (int)(idx - lenStartIdx); emailEntry = AltNameNew(cert->heap); if (emailEntry == NULL) { @@ -17212,7 +17233,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) } emailEntry->type = ASN_RFC822_TYPE; - emailEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, + emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (emailEntry->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17220,7 +17241,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) return MEMORY_E; } emailEntry->len = strLen; - XMEMCPY(emailEntry->name, &input[idx], strLen); + XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen); emailEntry->name[strLen] = '\0'; emailEntry->next = cert->altEmailNames; @@ -17239,7 +17260,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) WOLFSSL_MSG("\tfail: str length"); return ASN_PARSE_E; } - length -= (idx - lenStartIdx); + length -= (int)(idx - lenStartIdx); /* check that strLen at index is not past input buffer */ if ((word32)strLen + idx > sz) { @@ -17292,7 +17313,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) } uriEntry->type = ASN_URI_TYPE; - uriEntry->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, + uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (uriEntry->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17300,7 +17321,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) return MEMORY_E; } uriEntry->len = strLen; - XMEMCPY(uriEntry->name, &input[idx], strLen); + XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen); uriEntry->name[strLen] = '\0'; AddAltName(cert, uriEntry); @@ -17332,7 +17353,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) } ipAddr->type = ASN_IP_TYPE; - ipAddr->name = (char*)XMALLOC((word32)strLen + 1, cert->heap, + ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap, DYNAMIC_TYPE_ALTNAME); if (ipAddr->name == NULL) { WOLFSSL_MSG("\tOut of Memory"); @@ -17549,7 +17570,7 @@ static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert) ret = 0; } - cert->isCA = (byte)ret; + cert->isCA = ret ? 1 : 0; /* If there isn't any more data, return. */ if (idx >= (word32)sz) { @@ -18595,7 +18616,7 @@ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, return MEMORY_E; } - entry->name = (char*)XMALLOC((word32)strLength+1, heap, + entry->name = (char*)XMALLOC((size_t)strLength+1, heap, DYNAMIC_TYPE_ALTNAME); if (entry->name == NULL) { WOLFSSL_MSG("allocate error"); @@ -18603,7 +18624,7 @@ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, return MEMORY_E; } - XMEMCPY(entry->name, &input[nameIdx], strLength); + XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength); entry->name[strLength] = '\0'; entry->nameSz = strLength; entry->type = bType; @@ -18852,7 +18873,7 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) #endif /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */ - static int DecodeCertPolicy(const byte* input, int sz, DecodedCert* cert) + static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; @@ -18885,7 +18906,7 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) } /* Validate total length */ - if (total_length > (sz - (int)idx)) { + if (total_length > (int)(sz - idx)) { WOLFSSL_MSG("\tCertPolicy length mismatch"); return ASN_PARSE_E; } @@ -18903,24 +18924,24 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) ret = GetASNObjectId(input, &idx, &length, sz); if (ret != 0) return ret; - policy_length -= idx - oldIdx; + policy_length -= (int)(idx - oldIdx); if (length > 0) { /* Verify length won't overrun buffer */ - if (length > (sz - (int)idx)) { + if (length > (int)(sz - idx)) { WOLFSSL_MSG("\tCertPolicy length exceeds input buffer"); return ASN_PARSE_E; } #if defined(WOLFSSL_SEP) - cert->deviceType = (byte*)XMALLOC(length, cert->heap, + cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap, DYNAMIC_TYPE_X509_EXT); if (cert->deviceType == NULL) { WOLFSSL_MSG("\tCouldn't alloc memory for deviceType"); return MEMORY_E; } cert->deviceTypeSz = length; - XMEMCPY(cert->deviceType, input + idx, length); + XMEMCPY(cert->deviceType, input + idx, (size_t)length); break; #elif defined(WOLFSSL_CERT_EXT) /* decode cert policy */ @@ -18954,7 +18975,7 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) return 0; #endif } - idx += policy_length; + idx += (word32)policy_length; } while((int)idx < total_length #if defined(WOLFSSL_CERT_EXT) && cert->extCertPoliciesNb < MAX_CERTPOL_NB @@ -19442,7 +19463,7 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, #endif #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \ defined(WOLFSSL_QT) - if (DecodeCertPolicy(input, (int)length, cert) < 0) { + if (DecodeCertPolicy(input, length, cert) < 0) { ret = ASN_PARSE_E; } #else @@ -20612,7 +20633,7 @@ int ParseCert(DecodedCert* cert, int type, int verify, void* cm) defined(WOLFSSL_DYN_CERT) /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */ if (cert->subjectCNLen > 0) { - ptr = (char*)XMALLOC((word32)cert->subjectCNLen + 1, cert->heap, + ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap, DYNAMIC_TYPE_SUBJECT_CN); if (ptr == NULL) return MEMORY_E; @@ -21431,7 +21452,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } if (len) { - word32 attrMaxIdx = cert->srcIdx + len; + word32 attrMaxIdx = cert->srcIdx + (word32)len; word32 oid; byte tag; @@ -21472,7 +21493,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } cert->contentType = (char*)cert->source + cert->srcIdx; cert->contentTypeLen = len; - cert->srcIdx += len; + cert->srcIdx += (word32)len; break; case CHALLENGE_PASSWORD_OID: if (GetHeader(cert->source, &tag, @@ -21487,7 +21508,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } cert->cPwd = (char*)cert->source + cert->srcIdx; cert->cPwdLen = len; - cert->srcIdx += len; + cert->srcIdx += (word32)len; break; case SERIAL_NUMBER_OID: if (GetHeader(cert->source, &tag, @@ -21502,9 +21523,10 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } cert->sNum = (char*)cert->source + cert->srcIdx; cert->sNumLen = len; - cert->srcIdx += len; + cert->srcIdx += (word32)len; if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) { - XMEMCPY(cert->serial, cert->sNum, cert->sNumLen); + XMEMCPY(cert->serial, cert->sNum, + (size_t)cert->sNumLen); cert->serialSz = cert->sNumLen; } break; @@ -21516,7 +21538,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } cert->dnQualifier = (char*)cert->source + cert->srcIdx; cert->dnQualifierLen = len; - cert->srcIdx += len; + cert->srcIdx += (word32)len; break; case INITIALS_OID: if (GetHeader(cert->source, &tag, @@ -21526,7 +21548,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } cert->initials = (char*)cert->source + cert->srcIdx; cert->initialsLen = len; - cert->srcIdx += len; + cert->srcIdx += (word32)len; break; case SURNAME_OID: if (GetHeader(cert->source, &tag, @@ -21536,7 +21558,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } cert->surname = (char*)cert->source + cert->srcIdx; cert->surnameLen = len; - cert->srcIdx += len; + cert->srcIdx += (word32)len; break; case GIVEN_NAME_OID: if (GetHeader(cert->source, &tag, @@ -21546,7 +21568,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } cert->givenName = (char*)cert->source + cert->srcIdx; cert->givenNameLen = len; - cert->srcIdx += len; + cert->srcIdx += (word32)len; break; case UNSTRUCTURED_NAME_OID: if (GetHeader(cert->source, &tag, @@ -21557,7 +21579,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) cert->unstructuredName = (char*)cert->source + cert->srcIdx; cert->unstructuredNameLen = len; - cert->srcIdx += len; + cert->srcIdx += (word32)len; break; case EXTENSION_REQUEST_OID: /* save extensions */ @@ -21573,7 +21595,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) return ret; } } - cert->srcIdx += len; + cert->srcIdx += (word32)len; break; default: WOLFSSL_MSG("Unsupported attribute type"); @@ -23860,7 +23882,8 @@ static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen, int with_header) { #ifndef WOLFSSL_ASN_TEMPLATE - int idx, nSz, eSz, seqSz, headSz = 0, bitStringSz = 0, algoSz = 0; + int nSz, eSz; + word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx; byte seq[MAX_SEQ_SZ]; byte headSeq[MAX_SEQ_SZ]; byte bitString[1 + MAX_LENGTH_SZ + 1]; @@ -23885,22 +23908,23 @@ static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen, #endif if (eSz < 0) return eSz; - seqSz = SetSequence(nSz + eSz, seq); + seqSz = SetSequence((word32)(nSz + eSz), seq); /* headers */ if (with_header) { algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0); - bitStringSz = SetBitString(seqSz + nSz + eSz, 0, bitString); - headSz = SetSequence(nSz + eSz + seqSz + bitStringSz + algoSz, headSeq); + bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString); + headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz, + headSeq); } /* if getting length only */ if (output == NULL) { - return headSz + algoSz + bitStringSz + seqSz + nSz + eSz; + return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz; } /* check output size */ - if ((headSz + algoSz + bitStringSz + seqSz + nSz + eSz) > outLen) { + if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) { return BUFFER_E; } @@ -23927,16 +23951,16 @@ static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen, #else nSz = SetASNIntMP(&key->n, nSz, output + idx); #endif - idx += nSz; + idx += (word32)nSz; /* e */ #ifdef HAVE_USER_RSA eSz = SetASNIntRSA(key->e, output + idx); #else eSz = SetASNIntMP(&key->e, eSz, output + idx); #endif - idx += eSz; + idx += (word32)eSz; - return idx; + return (int)idx; #else DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length); int sz = 0; @@ -24056,8 +24080,8 @@ int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen, int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) { #ifndef WOLFSSL_ASN_TEMPLATE - int ret = 0, i, j, outLen = 0, mpSz; - word32 seqSz = 0, verSz = 0, rawLen, intTotalLen = 0; + int ret = 0, i, mpSz; + word32 j, seqSz = 0, verSz = 0, rawLen, intTotalLen = 0, outLen = 0; word32 sizes[RSA_INTS]; byte seq[MAX_SEQ_SZ]; byte ver[MAX_VERSION_SZ]; @@ -24076,7 +24100,11 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) for (i = 0; i < RSA_INTS; i++) { mp_int* keyInt = GetRsaInt(key, i); - rawLen = mp_unsigned_bin_size(keyInt) + 1; + ret = mp_unsigned_bin_size(keyInt); + if (ret < 0) + return ret; + rawLen = (word32)ret + 1; + ret = 0; if (output != NULL) { tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap, DYNAMIC_TYPE_RSA); @@ -24091,16 +24119,21 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) ret = mpSz; break; } - intTotalLen += (sizes[i] = mpSz); + sizes[i] = (word32)mpSz; + intTotalLen += (word32)mpSz; } if (ret == 0) { /* make headers */ - verSz = SetMyVersion(0, ver, FALSE); - seqSz = SetSequence(verSz + intTotalLen, seq); + ret = SetMyVersion(0, ver, FALSE); + } + if (ret >= 0) { + verSz = (word32)ret; + ret = 0; + seqSz = SetSequence(verSz + intTotalLen, seq); outLen = seqSz + verSz + intTotalLen; - if (output != NULL && outLen > (int)inLen) + if (output != NULL && outLen > inLen) ret = BUFFER_E; } if (ret == 0 && output != NULL) { @@ -24122,7 +24155,7 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) } if (ret == 0) - ret = outLen; + ret = (int)outLen; return ret; #else DECL_ASNSETDATA(dataASN, rsaKeyASN_Length); @@ -24802,7 +24835,7 @@ int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen, } if (ret == 0) { - ret = sz; + ret = (int)sz; } #else if (withHeader) { @@ -24956,18 +24989,19 @@ static void SetTime(struct tm* date, byte* output) /* Copy Dates from cert, return bytes written */ static int CopyValidity(byte* output, Cert* cert) { - int seqSz; + word32 seqSz; WOLFSSL_ENTER("CopyValidity"); /* headers and output */ - seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output); + seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz), + output); if (output) { - XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz); + XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz); XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate, - cert->afterDateSz); + (size_t)cert->afterDateSz); } - return seqSz + cert->beforeDateSz + cert->afterDateSz; + return (int)seqSz + cert->beforeDateSz + cert->afterDateSz; } #endif /* !WOLFSSL_ASN_TEMPLATE */ @@ -25141,18 +25175,18 @@ static int SetExtensions(byte* out, word32 outSz, int *IdxInOut, if (outSz < (word32)(*IdxInOut+extSz)) return BUFFER_E; - XMEMCPY(&out[*IdxInOut], ext, extSz); /* extensions */ + XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */ *IdxInOut += extSz; return *IdxInOut; } /* encode extensions header, return total bytes written */ -static int SetExtensionsHeader(byte* out, word32 outSz, int extSz) +static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz) { byte sequence[MAX_SEQ_SZ]; byte len[MAX_LENGTH_SZ]; - int seqSz, lenSz, idx = 0; + word32 seqSz, lenSz, idx = 0; if (out == NULL) return BAD_FUNC_ARG; @@ -25175,7 +25209,7 @@ static int SetExtensionsHeader(byte* out, word32 outSz, int extSz) XMEMCPY(&out[idx], sequence, seqSz); /* sequence */ idx += seqSz; - return idx; + return (int)idx; } @@ -25254,7 +25288,7 @@ static int SetBC(byte* out, word32 outSz) static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz, byte *in, word32 inSz) { - int idx = 0; + word32 idx = 0; if (out == NULL || oid == NULL || in == NULL) return BAD_FUNC_ARG; @@ -25273,7 +25307,7 @@ static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz, out[idx++] = (byte)inSz; XMEMCPY(out+idx, in, inSz); - return (idx+inSz); + return (int)(idx+inSz); } /* encode Subject Key Identifier, return total bytes written @@ -25282,7 +25316,7 @@ static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length) { byte skid_len[1 + MAX_LENGTH_SZ]; byte skid_enc_len[MAX_LENGTH_SZ]; - int idx = 0, skid_lenSz, skid_enc_lenSz; + word32 idx = 0, skid_lenSz, skid_enc_lenSz; const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 }; if (output == NULL || input == NULL) @@ -25297,8 +25331,8 @@ static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length) if (outSz < 3) return BUFFER_E; - idx = SetSequence(length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz, - output); + idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz + + skid_enc_lenSz, output); if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz) return BUFFER_E; @@ -25319,7 +25353,7 @@ static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length) XMEMCPY(output+idx, input, length); idx += length; - return idx; + return (int)idx; } /* encode Authority Key Identifier, return total bytes written @@ -25327,12 +25361,12 @@ static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length) static int SetAKID(byte* output, word32 outSz, byte *input, word32 length, byte rawAkid) { - int enc_valSz, inSeqSz; + int enc_valSz; byte enc_val_buf[MAX_KID_SZ]; byte* enc_val; const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 }; const byte akid_cs[] = { 0x80 }; - word32 idx; + word32 inSeqSz, idx; (void)rawAkid; @@ -25348,20 +25382,20 @@ static int SetAKID(byte* output, word32 outSz, byte *input, word32 length, #endif { enc_val = enc_val_buf; - enc_valSz = length + 3 + sizeof(akid_cs); + enc_valSz = (int)length + 3 + (int)sizeof(akid_cs); if (enc_valSz > (int)sizeof(enc_val_buf)) return BAD_FUNC_ARG; /* sequence for ContentSpec & value */ - enc_valSz = SetOidValue(enc_val, enc_valSz, akid_cs, sizeof(akid_cs), - input, length); + enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs, + sizeof(akid_cs), input, length); if (enc_valSz <= 0) return enc_valSz; } /* The size of the extension sequence contents */ - inSeqSz = sizeof(akid_oid) + SetOctetString(enc_valSz, NULL) + - enc_valSz; + inSeqSz = (word32)sizeof(akid_oid) + + SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz; if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz) return BAD_FUNC_ARG; @@ -25374,10 +25408,10 @@ static int SetAKID(byte* output, word32 outSz, byte *input, word32 length, idx += sizeof(akid_oid); /* Write out AKID */ - idx += SetOctetString(enc_valSz, output + idx); - XMEMCPY(output + idx, enc_val, enc_valSz); + idx += SetOctetString((word32)enc_valSz, output + idx); + XMEMCPY(output + idx, enc_val, (size_t)enc_valSz); - return idx + enc_valSz; + return (int)idx + enc_valSz; } /* encode Key Usage, return total bytes written @@ -25385,7 +25419,7 @@ static int SetAKID(byte* output, word32 outSz, byte *input, word32 length, static int SetKeyUsage(byte* output, word32 outSz, word16 input) { byte ku[5]; - int idx; + word32 idx; const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04}; if (output == NULL) @@ -25396,14 +25430,14 @@ static int SetKeyUsage(byte* output, word32 outSz, word16 input) ku, idx); } -static int SetOjectIdValue(byte* output, word32 outSz, int* idx, +static int SetOjectIdValue(byte* output, word32 outSz, word32* idx, const byte* oid, word32 oidSz) { /* verify room */ if (*idx + 2 + oidSz >= outSz) return ASN_PARSE_E; - *idx += SetObjectId(oidSz, &output[*idx]); + *idx += (word32)SetObjectId((int)oidSz, &output[*idx]); XMEMCPY(&output[*idx], oid, oidSz); *idx += oidSz; @@ -25446,7 +25480,8 @@ struct { static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input) { #ifndef WOLFSSL_ASN_TEMPLATE - int idx = 0, oidListSz = 0, totalSz, ret = 0; + word32 idx = 0, oidListSz = 0, totalSz; + int ret = 0; const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 }; if (output == NULL) @@ -25519,7 +25554,7 @@ static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input) idx += oidListSz; (void)cert; - return idx; + return (int)idx; #else /* TODO: consider calculating size of OBJECT_IDs, setting length into * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */ @@ -25672,7 +25707,7 @@ static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input) idx += SetBitString(1, unusedBits, &output[idx]); output[idx++] = nsCertType; - return idx; + return (int)idx; } #endif #endif @@ -25689,7 +25724,8 @@ static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input, input == 0 || inSz <= 0) return BAD_FUNC_ARG; - totalSz = sizeof(crlinfo_oid) + SetOctetString(inSz, NULL) + inSz; + totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) + + (word32)inSz; if (SetSequence(totalSz, NULL) + totalSz > outSz) return BAD_FUNC_ARG; @@ -25702,13 +25738,13 @@ static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input, idx += sizeof(crlinfo_oid); /* 3. Octet String */ - idx += SetOctetString(inSz, &output[idx]); + idx += SetOctetString((word32)inSz, &output[idx]); /* 4. CRL Info */ - XMEMCPY(&output[idx], input, inSz); - idx += inSz; + XMEMCPY(&output[idx], input, (size_t)inSz); + idx += (word32)inSz; - return idx; + return (int)idx; } #endif @@ -25762,7 +25798,7 @@ static int SetCertificatePolicies(byte *output, } /* add sequence */ - ret = SetSequence(outSz-2, out); + ret = (int)SetSequence(outSz-2, out); if (ret <= 0) return ret; @@ -25825,10 +25861,9 @@ static int SetAltNames(byte *output, word32 outSz, const byte *input, word32 length, int critical) { byte san_len[1 + MAX_LENGTH_SZ]; - int idx = 0, san_lenSz; const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 }; const byte san_crit[] = { 0x01, 0x01, 0xff }; - word32 seqSz; + word32 seqSz, san_lenSz, idx = 0; if (output == NULL || input == NULL) return BAD_FUNC_ARG; @@ -25842,7 +25877,7 @@ static int SetAltNames(byte *output, word32 outSz, if (outSz < MAX_SEQ_SZ) return BUFFER_E; - seqSz = length + sizeof(san_oid) + san_lenSz; + seqSz = length + (word32)sizeof(san_oid) + san_lenSz; if (critical) seqSz += sizeof(san_crit); idx = SetSequence(seqSz, output); @@ -25867,7 +25902,7 @@ static int SetAltNames(byte *output, word32 outSz, XMEMCPY(output+idx, input, length); idx += length; - return idx; + return (int)idx; } #endif /* WOLFSSL_ASN_TEMPLATE */ @@ -25957,23 +25992,23 @@ static int EncodeName(EncodedName* name, const char* nameStr, byte sequence[MAX_SEQ_SZ]; byte set[MAX_SET_SZ]; - int strLen; - int thisLen; - int firstSz, secondSz, seqSz, setSz; + word32 strLen; + word32 thisLen; + word32 firstSz, secondSz, seqSz, setSz; if (nameStr == NULL) { name->used = 0; return 0; } - thisLen = strLen = (int)XSTRLEN(nameStr); + thisLen = strLen = (word32)XSTRLEN(nameStr); #ifdef WOLFSSL_CUSTOM_OID if (type == ASN_CUSTOM_NAME) { if (cname == NULL || cname->custom.oidSz == 0) { name->used = 0; return 0; } - thisLen = strLen = cname->custom.valSz; + thisLen = strLen = (word32)cname->custom.valSz; } #else (void)cname; @@ -26021,7 +26056,7 @@ static int EncodeName(EncodedName* name, const char* nameStr, firstSz = DN_OID_SZ; } thisLen++; /* id type */ - firstSz = SetObjectId(firstSz, firstLen); + firstSz = (word32)SetObjectId((int)firstSz, firstLen); thisLen += firstSz; seqSz = SetSequence(thisLen, sequence); @@ -26096,10 +26131,10 @@ static int EncodeName(EncodedName* name, const char* nameStr, idx += strLen; name->type = type; - name->totalLen = idx; + name->totalLen = (int)idx; name->used = 1; - return idx; + return (int)idx; #else DECL_ASNSETDATA(dataASN, rdnASN_Length); ASNItem namesASN[rdnASN_Length]; @@ -26391,7 +26426,8 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) { #ifndef WOLFSSL_ASN_TEMPLATE int ret; - int totalBytes = 0, i, idx; + int i; + word32 idx, totalBytes = 0; #ifdef WOLFSSL_SMALL_STACK EncodedName* names = NULL; #else @@ -26418,7 +26454,7 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) for (i = 0; i < NAME_ENTRIES; i++) { const char* nameStr = GetOneCertName(name, i); - ret = EncodeName(&names[i], nameStr, GetNameType(name, i), + ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i), GetCertNameId(i), ASN_IA5_STRING, name); if (ret < 0) { #ifdef WOLFSSL_SMALL_STACK @@ -26427,13 +26463,13 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) WOLFSSL_MSG("EncodeName failed"); return BUFFER_E; } - totalBytes += ret; + totalBytes += (word32)ret; } #ifdef WOLFSSL_MULTI_ATTRIB for (i = 0; i < CTC_MAX_ATTRIB; i++) { if (name->name[i].sz > 0) { ret = EncodeName(&addNames[i], name->name[i].value, - (byte)name->name[i].type, name->name[i].id, + (byte)name->name[i].type, (byte)name->name[i].id, ASN_IA5_STRING, NULL); if (ret < 0) { #ifdef WOLFSSL_SMALL_STACK @@ -26442,7 +26478,7 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) WOLFSSL_MSG("EncodeName on multiple attributes failed"); return BUFFER_E; } - totalBytes += ret; + totalBytes += (word32)ret; } else { addNames[i].used = 0; @@ -26466,7 +26502,7 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) type = GetCertNameId(i); for (j = 0; j < CTC_MAX_ATTRIB; j++) { if (name->name[j].sz > 0 && type == name->name[j].id) { - if (outputSz < (word32)(idx+addNames[j].totalLen)) { + if (outputSz < idx + (word32)addNames[j].totalLen) { #ifdef WOLFSSL_SMALL_STACK XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -26475,22 +26511,22 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) } XMEMCPY(output + idx, addNames[j].encoded, - addNames[j].totalLen); - idx += addNames[j].totalLen; + (size_t)addNames[j].totalLen); + idx += (word32)addNames[j].totalLen; } } #endif /* WOLFSSL_MULTI_ATTRIB */ if (names[i].used) { - if (outputSz < (word32)(idx+names[i].totalLen)) { + if (outputSz < idx + (word32)names[i].totalLen) { #ifdef WOLFSSL_SMALL_STACK XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return BUFFER_E; } - XMEMCPY(output + idx, names[i].encoded, names[i].totalLen); - idx += names[i].totalLen; + XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen); + idx += (word32)names[i].totalLen; } } @@ -26499,7 +26535,7 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) #endif (void)heap; - return totalBytes; + return (int)totalBytes; #else /* TODO: consider calculating size of entries, putting length into * SEQUENCE, encode SEQUENCE, encode entries into buffer. */ @@ -27111,9 +27147,7 @@ static int SetValidity(byte* output, int daysValid) byte before[MAX_DATE_SIZE]; byte after[MAX_DATE_SIZE]; - int beforeSz; - int afterSz; - int seqSz; + word32 beforeSz, afterSz, seqSz; time_t now; time_t then; @@ -27176,7 +27210,7 @@ static int SetValidity(byte* output, int daysValid) XMEMCPY(output + seqSz, before, beforeSz); XMEMCPY(output + seqSz + beforeSz, after, afterSz); - return seqSz + beforeSz + afterSz; + return (int)(seqSz + beforeSz + afterSz); #else (void)output; (void)daysValid; @@ -27272,25 +27306,26 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, XMEMSET(der, 0, sizeof(DerCert)); /* version */ - der->versionSz = SetMyVersion(cert->version, der->version, TRUE); + der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE); /* serial number (must be positive) */ if (cert->serialSz == 0) { /* generate random serial */ cert->serialSz = CTC_GEN_SERIAL_SZ; - ret = wc_RNG_GenerateBlock(rng, cert->serial, cert->serialSz); + ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz); if (ret != 0) return ret; /* Clear the top bit to avoid a negative value */ cert->serial[0] &= 0x7f; } - der->serialSz = SetSerialNumber(cert->serial, cert->serialSz, der->serial, - sizeof(der->serial), CTC_SERIAL_SIZE); + der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz, + der->serial, sizeof(der->serial), + CTC_SERIAL_SIZE); if (der->serialSz < 0) return der->serialSz; /* signature algo */ - der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0); + der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0); if (der->sigAlgoSz <= 0) return ALGO_ID_E; @@ -27403,19 +27438,19 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) if (XSTRLEN((const char*)cert->sbjRaw) > 0) { /* Use the raw subject */ - int idx; + word32 idx; - der->subjectSz = min(sizeof(der->subject), - (word32)XSTRLEN((const char*)cert->sbjRaw)); + der->subjectSz = (int)min((word32)sizeof(der->subject), + (word32)XSTRLEN((const char*)cert->sbjRaw)); /* header */ - idx = SetSequence(der->subjectSz, der->subject); - if (der->subjectSz + idx > (int)sizeof(der->subject)) { + idx = SetSequence((word32)der->subjectSz, der->subject); + if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) { return SUBJECT_E; } XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw, - der->subjectSz); - der->subjectSz += idx; + (size_t)der->subjectSz); + der->subjectSz += (int)idx; } else #endif @@ -27431,20 +27466,20 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) if (XSTRLEN((const char*)cert->issRaw) > 0) { /* Use the raw issuer */ - int idx; + word32 idx; - der->issuerSz = min(sizeof(der->issuer), - (word32)XSTRLEN((const char*)cert->issRaw)); + der->issuerSz = (int)min((word32)sizeof(der->issuer), + (word32)XSTRLEN((const char*)cert->issRaw)); /* header */ - idx = SetSequence(der->issuerSz, der->issuer); - if (der->issuerSz + idx > (int)sizeof(der->issuer)) { + idx = SetSequence((word32)der->issuerSz, der->issuer); + if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) { return ISSUER_E; } XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw, - der->issuerSz); - der->issuerSz += idx; + (size_t)der->issuerSz); + der->issuerSz += (int)idx; } else #endif @@ -27498,7 +27533,7 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, /* Alternative Name */ if (cert->altNamesSz) { der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames), - cert->altNames, cert->altNamesSz, + cert->altNames, (word32)cert->altNamesSz, cert->altNamesCrit); if (der->altNamesSz <= 0) return ALT_NAME_E; @@ -27519,7 +27554,7 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, /* Note: different skid buffers sizes for der (MAX_KID_SZ) and cert (CTC_MAX_SKID_SIZE). */ der->skidSz = SetSKID(der->skid, sizeof(der->skid), - cert->skid, cert->skidSz); + cert->skid, (word32)cert->skidSz); if (der->skidSz <= 0) return SKID_E; @@ -27543,13 +27578,13 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, return AKID_E; der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid, - cert->akidSz, + (word32)cert->akidSz, #ifdef WOLFSSL_AKID_NAME - cert->rawAkid + cert->rawAkid #else - 0 + 0 #endif - ); + ); if (der->akidSz <= 0) return AKID_E; @@ -27629,7 +27664,7 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, /* put the start of extensions sequence (ID, Size) */ der->extensionsSz = SetExtensionsHeader(der->extensions, sizeof(der->extensions), - der->extensionsSz); + (word32)der->extensionsSz); if (der->extensionsSz <= 0) return EXTENSIONS_E; @@ -27732,39 +27767,40 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, /* write DER encoded cert to buffer, size already checked */ static int WriteCertBody(DerCert* der, byte* buf) { - int idx; + word32 idx; /* signed part header */ - idx = SetSequence(der->total, buf); + idx = SetSequence((word32)der->total, buf); /* version */ - XMEMCPY(buf + idx, der->version, der->versionSz); - idx += der->versionSz; + XMEMCPY(buf + idx, der->version, (size_t)der->versionSz); + idx += (word32)der->versionSz; /* serial */ - XMEMCPY(buf + idx, der->serial, der->serialSz); - idx += der->serialSz; + XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz); + idx += (word32)der->serialSz; /* sig algo */ - XMEMCPY(buf + idx, der->sigAlgo, der->sigAlgoSz); - idx += der->sigAlgoSz; + XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz); + idx += (word32)der->sigAlgoSz; /* issuer */ - XMEMCPY(buf + idx, der->issuer, der->issuerSz); - idx += der->issuerSz; + XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz); + idx += (word32)der->issuerSz; /* validity */ - XMEMCPY(buf + idx, der->validity, der->validitySz); - idx += der->validitySz; + XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz); + idx += (word32)der->validitySz; /* subject */ - XMEMCPY(buf + idx, der->subject, der->subjectSz); - idx += der->subjectSz; + XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz); + idx += (word32)der->subjectSz; /* public key */ - XMEMCPY(buf + idx, der->publicKey, der->publicKeySz); - idx += der->publicKeySz; + XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz); + idx += (word32)der->publicKeySz; if (der->extensionsSz) { /* extensions */ - XMEMCPY(buf + idx, der->extensions, min(der->extensionsSz, - (int)sizeof(der->extensions))); - idx += der->extensionsSz; + XMEMCPY(buf + idx, der->extensions, + min((word32)der->extensionsSz, + (word32)sizeof(der->extensions))); + idx += (word32)der->extensionsSz; } - return idx; + return (int)idx; } #endif /* !WOLFSSL_ASN_TEMPLATE */ @@ -27966,7 +28002,7 @@ static int GenerateInteger(WC_RNG* rng, byte* out, word32 len) } if (i != 0) { /* Remove leading zeros. */ - XMEMMOVE(out, out + i, len - (word32)i); + XMEMMOVE(out, out + i, (size_t)len - (size_t)i); } } @@ -28007,16 +28043,21 @@ int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz, { #ifndef WOLFSSL_ASN_TEMPLATE byte seq[MAX_SEQ_SZ]; - int idx = bodySz, seqSz; + word32 idx, seqSz; + + if ((bodySz < 0) || (sigSz < 0)) + return BUFFER_E; + + idx = (word32)bodySz; /* algo */ idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0); /* bit string */ - idx += SetBitString(sigSz, 0, buf ? buf + idx : NULL); + idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL); /* signature */ if (buf) - XMEMCPY(buf + idx, sig, sigSz); - idx += sigSz; + XMEMCPY(buf + idx, sig, (size_t)sigSz); + idx += (word32)sigSz; /* make room for overall header */ seqSz = SetSequence(idx, seq); @@ -28025,7 +28066,7 @@ int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz, XMEMCPY(buf, seq, seqSz); } - return idx + seqSz; + return (int)(idx + seqSz); #else DECL_ASNSETDATA(dataASN, sigASN_Length); word32 seqSz; @@ -28547,18 +28588,19 @@ int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey, /* return size of data set on success * if getting size only then attr and oid should be NULL */ -static int SetReqAttribSingle(byte* output, int* idx, char* attr, int attrSz, - const byte* oid, int oidSz, byte printable, int extSz) -{ - int totalSz = 0; - int seqSz = 0; - int setSz = 0; - int strSz = 0; +static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr, + word32 attrSz, const byte* oid, word32 oidSz, byte printable, + word32 extSz) +{ + word32 totalSz = 0; + word32 seqSz = 0; + word32 setSz = 0; + word32 strSz = 0; byte seq[MAX_SEQ_SZ]; byte set[MAX_SET_SZ]; byte str[MAX_PRSTR_SZ]; - totalSz = SetObjectId(oidSz, NULL); + totalSz = (word32)SetObjectId((int)oidSz, NULL); totalSz += oidSz; if (extSz > 0) { totalSz += setSz = SetSet(extSz, set); @@ -28567,7 +28609,8 @@ static int SetReqAttribSingle(byte* output, int* idx, char* attr, int attrSz, } else { if (printable) { - totalSz += strSz = SetPrintableString(attrSz, str); + strSz = SetPrintableString(attrSz, str); + totalSz += strSz; } else { totalSz += strSz = SetUTF8String(attrSz, str); @@ -28580,7 +28623,7 @@ static int SetReqAttribSingle(byte* output, int* idx, char* attr, int attrSz, if (oid) { XMEMCPY(&output[*idx], seq, seqSz); *idx += seqSz; - *idx += SetObjectId(oidSz, output + *idx); + *idx += (word32)SetObjectId((int)oidSz, output + *idx); XMEMCPY(&output[*idx], oid, oidSz); *idx += oidSz; XMEMCPY(&output[*idx], set, setSz); @@ -28599,24 +28642,24 @@ static int SetReqAttribSingle(byte* output, int* idx, char* attr, int attrSz, -static int SetReqAttrib(byte* output, Cert* cert, int extSz) +static int SetReqAttrib(byte* output, Cert* cert, word32 extSz) { - int sz = 0; /* overall size */ - int setSz = 0; + word32 sz = 0; /* overall size */ + word32 setSz = 0; output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED; sz++; if (cert->challengePw[0]) { setSz += SetReqAttribSingle(output, &sz, NULL, - (int)XSTRLEN(cert->challengePw), NULL, + (word32)XSTRLEN(cert->challengePw), NULL, sizeof(attrChallengePasswordOid), - cert->challengePwPrintableString, 0); + (byte)cert->challengePwPrintableString, 0); } if (cert->unstructuredName[0]) { setSz += SetReqAttribSingle(output, &sz, NULL, - (int)XSTRLEN(cert->unstructuredName), NULL, + (word32)XSTRLEN(cert->unstructuredName), NULL, sizeof(attrUnstructuredNameOid), 1, 0); } @@ -28634,14 +28677,15 @@ static int SetReqAttrib(byte* output, Cert* cert, int extSz) if (cert->challengePw[0]) { SetReqAttribSingle(output, &sz, cert->challengePw, - (int)XSTRLEN(cert->challengePw), &attrChallengePasswordOid[0], + (word32)XSTRLEN(cert->challengePw), + &attrChallengePasswordOid[0], sizeof(attrChallengePasswordOid), - cert->challengePwPrintableString, 0); + (byte)cert->challengePwPrintableString, 0); } if (cert->unstructuredName[0]) { SetReqAttribSingle(output, &sz, cert->unstructuredName, - (int)XSTRLEN(cert->unstructuredName), + (word32)XSTRLEN(cert->unstructuredName), &attrUnstructuredNameOid[0], sizeof(attrUnstructuredNameOid), 1, 0); } @@ -28652,7 +28696,7 @@ static int SetReqAttrib(byte* output, Cert* cert, int extSz) /* The actual extension data will be tacked onto the output later. */ } - return sz; + return (int)sz; } #ifdef WOLFSSL_CUSTOM_OID @@ -28727,7 +28771,7 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, XMEMSET(der, 0, sizeof(DerCert)); /* version */ - der->versionSz = SetMyVersion(cert->version, der->version, FALSE); + der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE); /* subject name */ #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) @@ -28735,16 +28779,16 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, /* Use the raw subject */ int idx; - der->subjectSz = min(sizeof(der->subject), + der->subjectSz = (int)min(sizeof(der->subject), (word32)XSTRLEN((const char*)cert->sbjRaw)); /* header */ - idx = SetSequence(der->subjectSz, der->subject); + idx = (int)SetSequence((word32)der->subjectSz, der->subject); if (der->subjectSz + idx > (int)sizeof(der->subject)) { return SUBJECT_E; } XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw, - der->subjectSz); + (size_t)der->subjectSz); der->subjectSz += idx; } else @@ -28881,7 +28925,7 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, /* Alternative Name */ if (cert->altNamesSz) { der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames), - cert->altNames, cert->altNamesSz, + cert->altNames, (word32)cert->altNamesSz, cert->altNamesCrit); if (der->altNamesSz <= 0) return ALT_NAME_E; @@ -28900,7 +28944,7 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, return SKID_E; der->skidSz = SetSKID(der->skid, sizeof(der->skid), - cert->skid, cert->skidSz); + cert->skid, (word32)cert->skidSz); if (der->skidSz <= 0) return SKID_E; @@ -28949,7 +28993,8 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, /* put extensions */ if (der->extensionsSz > 0) { /* put the start of sequence (ID, Size) */ - der->extensionsSz = SetSequence(der->extensionsSz, der->extensions); + der->extensionsSz = (int)SetSequence((word32)der->extensionsSz, + der->extensions); if (der->extensionsSz <= 0) return EXTENSIONS_E; @@ -29022,7 +29067,7 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, #endif /* WOLFSSL_CERT_EXT */ } - der->attribSz = SetReqAttrib(der->attrib, cert, der->extensionsSz); + der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz); if (der->attribSz <= 0) return REQ_ATTRIBUTE_E; @@ -29039,28 +29084,28 @@ static int WriteCertReqBody(DerCert* der, byte* buf) int idx; /* signed part header */ - idx = SetSequence(der->total, buf); + idx = (int)SetSequence((word32)der->total, buf); /* version */ if (buf) - XMEMCPY(buf + idx, der->version, der->versionSz); + XMEMCPY(buf + idx, der->version, (size_t)der->versionSz); idx += der->versionSz; /* subject */ if (buf) - XMEMCPY(buf + idx, der->subject, der->subjectSz); + XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz); idx += der->subjectSz; /* public key */ if (buf) - XMEMCPY(buf + idx, der->publicKey, der->publicKeySz); + XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz); idx += der->publicKeySz; /* attributes */ if (buf) - XMEMCPY(buf + idx, der->attrib, der->attribSz); + XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz); idx += der->attribSz; /* extensions */ if (der->extensionsSz) { if (buf) - XMEMCPY(buf + idx, der->extensions, min(der->extensionsSz, - (int)sizeof(der->extensions))); + XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz, + sizeof(der->extensions))); idx += der->extensionsSz; } @@ -31081,7 +31126,7 @@ int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen, if (rLen) *rLen = (word32)len; if (r) - XMEMCPY(r, (byte*)sig + idx, len); + XMEMCPY(r, (byte*)sig + idx, (size_t)len); idx += (word32)len; ret = GetASNInt(sig, &idx, &len, sigLen); @@ -31090,7 +31135,7 @@ int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen, if (sLen) *sLen = (word32)len; if (s) - XMEMCPY(s, (byte*)sig + idx, len); + XMEMCPY(s, (byte*)sig + idx, (size_t)len); #ifndef NO_STRICT_ECDSA_LEN /* sanity check that the index has been advanced all the way to the end of @@ -31564,7 +31609,7 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, #endif /* priv key */ - XMEMCPY(priv, &input[*inOutIdx], privSz); + XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz); *inOutIdx += (word32)length; if ((*inOutIdx + 1) < inSz) { @@ -31617,7 +31662,7 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, else #endif { - XMEMCPY(pub, &input[*inOutIdx], pubSz); + XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz); *inOutIdx += (word32)length; pubData = pub; } @@ -31735,16 +31780,16 @@ static int ASNToHexString(const byte* input, word32* inOutIdx, char** out, return ASN_PARSE_E; } - str = (char*)XMALLOC(len * 2 + 1, heap, heapType); + str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType); if (str == NULL) { return MEMORY_E; } for (i=0; i 0) ret = 0; /* reset on success */ - *inOutIdx += len; + *inOutIdx += (word32)len; } } if (ret == 0) { @@ -31947,10 +31992,10 @@ int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx, } if (ret == 0) { #ifndef WOLFSSL_ECC_CURVE_STATIC - curve->Gx = (const char*)XMALLOC(curve->size * 2 + 2, key->heap, - DYNAMIC_TYPE_ECC_BUFFER); - curve->Gy = (const char*)XMALLOC(curve->size * 2 + 2, key->heap, - DYNAMIC_TYPE_ECC_BUFFER); + curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2, + key->heap, DYNAMIC_TYPE_ECC_BUFFER); + curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2, + key->heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Gx == NULL || curve->Gy == NULL) { XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER); ret = MEMORY_E; @@ -31965,9 +32010,9 @@ int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx, if (ret == 0) { char* o = NULL; - XMEMCPY((char*)curve->Gx, point + 2, curve->size * 2); + XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2); XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2, - curve->size * 2); + (size_t)curve->size * 2); ((char*)curve->Gx)[curve->size * 2] = '\0'; ((char*)curve->Gy)[curve->size * 2] = '\0'; XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER); @@ -32283,7 +32328,7 @@ static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, idx = seqSz; /* ver */ - XMEMCPY(output + idx, ver, verSz); + XMEMCPY(output + idx, ver, (size_t)verSz); idx += (word32)verSz; /* private */ @@ -32631,7 +32676,7 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, #ifndef WOLFSSL_ASN_TEMPLATE if (GetSequence(input, inOutIdx, &length, inSz) >= 0) { - endKeyIdx = *inOutIdx + length; + endKeyIdx = (int)*inOutIdx + length; if (GetMyVersion(input, inOutIdx, &version, inSz) < 0) return ASN_PARSE_E; @@ -32652,22 +32697,22 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, return ASN_PARSE_E; priv = input + *inOutIdx; - *inOutIdx += privSz; + *inOutIdx += (word32)privSz; } else { if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0) return ASN_PARSE_E; priv = input + *inOutIdx; - *inOutIdx += privSz; - endKeyIdx = *inOutIdx; + *inOutIdx += (word32)privSz; + endKeyIdx = (int)*inOutIdx; } if ((word32)privSz > *privKeyLen) return BUFFER_E; if (endKeyIdx == (int)*inOutIdx) { - *privKeyLen = privSz; + *privKeyLen = (word32)privSz; XMEMCPY(privKey, priv, *privKeyLen); if (pubKeyLen != NULL) *pubKeyLen = 0; @@ -32686,11 +32731,11 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, return BUFFER_E; pub = input + *inOutIdx; - *inOutIdx += pubSz; + *inOutIdx += (word32)pubSz; - *privKeyLen = privSz; + *privKeyLen = (word32)privSz; XMEMCPY(privKey, priv, *privKeyLen); - *pubKeyLen = pubSz; + *pubKeyLen = (word32)pubSz; if (pubKey != NULL) XMEMCPY(pubKey, pub, *pubKeyLen); } @@ -32793,7 +32838,7 @@ int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, return ASN_PARSE_E; /* This is the raw point data compressed or uncompressed. */ - *pubKeyLen = length; + *pubKeyLen = (word32)length; XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen); #else len = inSz - *inOutIdx; @@ -33003,7 +33048,7 @@ int SetAsymKeyDer(const byte* privKey, word32 privKeyLen, } if (ret == 0) { /* Return size of encoding. */ - ret = sz; + ret = (int)sz; } #else @@ -36428,8 +36473,8 @@ int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers) ret = MEMORY_E; goto error; } - XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr)); - XMEMSET(nextParam, 0, (word32)sizeof(MimeParam)); + XMEMSET(nextHdr, 0, sizeof(MimeHdr)); + XMEMSET(nextParam, 0, sizeof(MimeParam)); curLine = XSTRTOK(in, "\r\n", &ptr); if (curLine == NULL) { @@ -36489,7 +36534,7 @@ int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers) ret = MEMORY_E; goto error; } - XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr)); + XMEMSET(nextHdr, 0, sizeof(MimeHdr)); } else { nextParam->attribute = nameAttr; @@ -36504,7 +36549,7 @@ int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers) ret = MEMORY_E; goto error; } - XMEMSET(nextParam, 0, (word32)sizeof(MimeParam)); + XMEMSET(nextParam, 0, sizeof(MimeParam)); } mimeType = MIME_PARAM; mimeStatus = MIME_NAMEATTR; @@ -36535,7 +36580,7 @@ int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers) ret = MEMORY_E; goto error; } - XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr)); + XMEMSET(nextHdr, 0, sizeof(MimeHdr)); } else { nextParam->attribute = nameAttr; nameAttr = NULL; @@ -36549,7 +36594,7 @@ int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers) ret = MEMORY_E; goto error; } - XMEMSET(nextParam, 0, (word32)sizeof(MimeParam)); + XMEMSET(nextParam, 0, sizeof(MimeParam)); } } diff --git a/wolfcrypt/src/hash.c b/wolfcrypt/src/hash.c index ed53d73f56e..7a146359a28 100644 --- a/wolfcrypt/src/hash.c +++ b/wolfcrypt/src/hash.c @@ -528,11 +528,15 @@ int wc_Hash(enum wc_HashType hash_type, const byte* data, word32 data_len, byte* hash, word32 hash_len) { int ret = HASH_TYPE_E; /* Default to hash type error */ - word32 dig_size; + int dig_size; /* Validate hash buffer size */ - dig_size = (word32)wc_HashGetDigestSize(hash_type); - if (hash_len < dig_size) { + dig_size = wc_HashGetDigestSize(hash_type); + if (dig_size < 0) { + return dig_size; + } + + if (hash_len < (word32)dig_size) { return BUFFER_E; } diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index e393d5ef311..5decdc29c87 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -3820,7 +3820,7 @@ static int wc_PKCS7_VerifyContentMessageDigest(PKCS7* pkcs7, /* compare generated to hash in messageDigest attribute */ if ((innerAttribSz != digestSz) || - (XMEMCMP(attrib->value + idx, digestBuf, (word32)digestSz) != 0)) { + (XMEMCMP(attrib->value + idx, digestBuf, (size_t)digestSz) != 0)) { WOLFSSL_MSG("Content digest does not match messageDigest attrib value"); #ifdef WOLFSSL_SMALL_STACK XFREE(digest, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 2653d6abd52..bfe73f4baee 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -4845,7 +4845,7 @@ WOLFSSL_TEST_SUBROUTINE int hash_test(void) for (i = 0; i < (int)(sizeof(typesHashBad)/sizeof(*typesHashBad)); i++) { ret = wc_Hash(typesHashBad[i], data, sizeof(data), out, sizeof(out)); - if (ret != BAD_FUNC_ARG && ret != BUFFER_E) + if ((ret != BAD_FUNC_ARG) && (ret != BUFFER_E) && (ret != HASH_TYPE_E)) return WC_TEST_RET_ENC_I(i); } From 4220bae976a656a47538b2d1f8cc63ae6cbf09d9 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 12 Apr 2023 16:37:20 -0500 Subject: [PATCH 127/391] wolfcrypt/src/pkcs7.c: correct fix for clang-analyzer-core.DivideZero in wc_PKCS7_DecodeAuthEnvelopedData(). --- wolfcrypt/src/pkcs7.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index 5decdc29c87..e873e0cf379 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -11877,15 +11877,17 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, #endif if (expBlockSz == 0) { - if (GetAlgoId(pkiMsg, &idx, &encOID, oidBlkType, pkiMsgSz) < 0) - { - ret = ASN_PARSE_E; - break; - } - expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID); - if (expBlockSz < 0) { - ret = expBlockSz; - break; + #ifndef NO_PKCS7_STREAM + wc_PKCS7_StreamGetVar(pkcs7, &encOID, NULL, NULL); + #endif + if (encOID == 0) + expBlockSz = 1; + else { + expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID); + if (expBlockSz < 0) { + ret = expBlockSz; + break; + } } } From c23bf0a46b87a2fa1d86dd9a01efa571c2080614 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 12 Apr 2023 13:48:03 -0500 Subject: [PATCH 128/391] wolfssl/wolfcrypt/asn.h: if defined(WOLFSSL_MULTI_ATTRIB), bump predefined WC_ASN_NAME_MAX, to fix rsa_certgen_test() with config --enable-testcert --enable-asn=original CPPFLAGS='-DWOLFSSL_CERT_GEN -DWOLFSSL_MULTI_ATTRIB'. --- wolfssl/wolfcrypt/asn.h | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 489dcfe5517..8e7327219f1 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -858,9 +858,17 @@ enum ECC_TYPES #ifndef WC_ASN_NAME_MAX #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ defined(WOLFSSL_CERT_EXT) - #define WC_ASN_NAME_MAX 330 + #ifdef WOLFSSL_MULTI_ATTRIB + #define WC_ASN_NAME_MAX 360 + #else + #define WC_ASN_NAME_MAX 330 + #endif #else - #define WC_ASN_NAME_MAX 256 + #ifdef WOLFSSL_MULTI_ATTRIB + #define WC_ASN_NAME_MAX 330 + #else + #define WC_ASN_NAME_MAX 256 + #endif #endif #endif From eae56e0d21bdfc6426cdf2c3b363dd442190c5ea Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 11 Apr 2023 13:30:04 -0700 Subject: [PATCH 129/391] fix for creating options.h with cmake and WOLFSSL_USER_SETTINGS --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f81464f209..e29d6cad1a4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1876,8 +1876,8 @@ generate_build_flags() # USER SETTINGS if(WOLFSSL_USER_SETTINGS) # Replace all options and just use WOLFSSL_USER_SETTINGS - set(WOLFSSL_DEFINITIONS "-DWOLFSSL_USER_SETTINGS - -DWOLFSSL_USER_SETTINGS_ASM") + set(WOLFSSL_DEFINITIONS "-DWOLFSSL_USER_SETTINGS") + list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_USER_SETTINGS_ASM") # Create user_settings_asm.h for use in assembly files (e.g. .S files). execute_process(COMMAND $ENV{SHELL} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh From 6d1a48712274b61caa6e267835b07c2ba11a4ef7 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Thu, 13 Apr 2023 10:34:58 -0700 Subject: [PATCH 130/391] fix for wpas build with x509 small --- src/pk.c | 4 ++-- src/ssl_asn1.c | 6 ++++-- wolfcrypt/src/evp.c | 2 +- wolfssl/ssl.h | 4 +++- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/pk.c b/src/pk.c index 75e239fec92..d5e647e9cdf 100644 --- a/src/pk.c +++ b/src/pk.c @@ -1704,7 +1704,7 @@ int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf, #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ -#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) #if !defined(NO_BIO) || !defined(NO_FILESYSTEM) /* Load DER encoded data into WOLFSSL_RSA object. @@ -1748,7 +1748,7 @@ static WOLFSSL_RSA* wolfssl_rsa_d2i(WOLFSSL_RSA** rsa, const unsigned char* in, } #endif -#endif /* OPENSSL_EXTRA */ +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ /* * RSA PEM APIs diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 51d24ccc55f..ee0a5884c91 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -550,6 +550,7 @@ void wolfSSL_ASN1_INTEGER_free(WOLFSSL_ASN1_INTEGER* in) XFREE(in, NULL, DYNAMIC_TYPE_OPENSSL); } +#if defined(OPENSSL_EXTRA) /* Reset the data of ASN.1 INTEGER object back to empty fixed array. * * @param [in] a ASN.1 INTEGER object. @@ -578,6 +579,7 @@ static void wolfssl_asn1_integer_reset_data(WOLFSSL_ASN1_INTEGER* a) /* Set type to positive INTEGER. */ a->type = V_ASN1_INTEGER; } +#endif /* OPENSSL_EXTRA */ /* Setup ASN.1 INTEGER object to handle data of required length. * @@ -1924,7 +1926,7 @@ int wolfSSL_i2a_ASN1_OBJECT(WOLFSSL_BIO *bp, WOLFSSL_ASN1_OBJECT *a) * ASN1_SK_OBJECT APIs ******************************************************************************/ -#if defined(OPENSSL_EXTRA) && !defined(NO_ASN) +#if (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) && !defined(NO_ASN) /* Create a new WOLFSSL_ASN1_OBJECT stack. * * @return New WOLFSSL_ASN1_OBJECT stack on success. @@ -1997,7 +1999,7 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_sk_ASN1_OBJECT_pop( return (WOLFSSL_ASN1_OBJECT*)wolfssl_sk_pop_type(sk, STACK_TYPE_OBJ); } -#endif /* OPENSSL_EXTRA && !NO_ASN */ +#endif /* (OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL) && !NO_ASN */ /******************************************************************************* * ASN1_STRING APIs diff --git a/wolfcrypt/src/evp.c b/wolfcrypt/src/evp.c index 2a44c4af487..8f8f7b86945 100644 --- a/wolfcrypt/src/evp.c +++ b/wolfcrypt/src/evp.c @@ -9598,7 +9598,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) break; #endif /* HAVE_HKDF */ - #if defined(WOLFSSL_CMAC) && !defined(NO_AES) && \ + #if defined(WOLFSSL_CMAC) && defined(OPENSSL_EXTRA) && \ defined(WOLFSSL_AES_DIRECT) case EVP_PKEY_CMAC: if (key->cmacCtx != NULL) { diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index cd1cfb78b9e..39adea3f505 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -228,7 +228,7 @@ typedef struct WOLFSSL_DIST_POINT WOLFSSL_DIST_POINT; typedef struct WOLFSSL_CONF_CTX WOLFSSL_CONF_CTX; -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) struct WOLFSSL_OBJ_NAME { int type; @@ -2863,6 +2863,8 @@ WOLFSSL_API WOLFSSL_X509_NAME* wolfSSL_X509_CRL_get_issuer_name( WOLFSSL_X509_CRL *crl); WOLFSSL_API int wolfSSL_X509_REVOKED_get_serial_number(RevokedCert* rev, byte* in, int* inOutSz); +#endif +#if defined(HAVE_CRL) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) WOLFSSL_API void wolfSSL_X509_CRL_free(WOLFSSL_X509_CRL *crl); #endif From 46df9f32eee9b34e3127e83af194e82825edef4d Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 13 Apr 2023 14:51:29 -0500 Subject: [PATCH 131/391] fix for cppcheck/zerodivcond in wolfcrypt/src/pkcs7.c:wc_PKCS7_DecodeAuthEnvelopedData(); fixes for clang-tidy/bugprone-macro-parentheses in wolfssl/wolfcrypt/sp_int.{c,h} and wolfcrypt/src/ecc.c; fix for clang-analyzer-deadcode.DeadStores in olfcrypt/src/asn.c. --- wolfcrypt/src/asn.c | 3 +-- wolfcrypt/src/ecc.c | 2 +- wolfcrypt/src/pkcs7.c | 3 ++- wolfcrypt/src/sp_int.c | 2 +- wolfssl/wolfcrypt/sp_int.h | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index c0ca6387226..30223ba272d 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -6455,8 +6455,6 @@ static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, #endif void* heap = NULL; - (void)heap; - /* Check validity of parameters. */ if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) && (keySz == NULL))) { @@ -6476,6 +6474,7 @@ static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, } #endif + (void)heap; CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap); if (ret == 0) { diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index d65515520cc..3d237de8eb4 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -1441,7 +1441,7 @@ static int xil_mpi_import(mp_int *mpi, #ifdef WOLFSSL_SP_MATH_ALL #define DECLARE_CURVE_SPECS(intcount) \ unsigned char spec_ints[MP_INT_SIZEOF(MP_BITS_CNT( \ - MAX_ECC_BITS_USE)) * intcount]; \ + MAX_ECC_BITS_USE)) * (intcount)]; \ ecc_curve_spec curve_lcl; \ ecc_curve_spec* curve = &curve_lcl; \ XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \ diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index e873e0cf379..e36f05a9122 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -11887,7 +11887,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, if (expBlockSz < 0) { ret = expBlockSz; break; - } + } else if (expBlockSz == 0) + expBlockSz = 1; } } diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 19dd08ad759..6198e7c7414 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -127,7 +127,7 @@ This library provides single precision (SP) integer math functions. /* Declare a variable on the stack with the required data size. */ #define DECL_SP_INT(n, s) \ byte n##d[MP_INT_SIZEOF(s)]; \ - sp_int* n = (sp_int*)n##d + sp_int* (n) = (sp_int*)n##d #else /* Declare a variable on the stack. */ #define DECL_SP_INT(n, s) \ diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index 7d70a9c526d..90f2e3f7f41 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -796,7 +796,7 @@ while (0) /* Declare a dynamically allocated mp_int. */ #define DECL_MP_INT_SIZE_DYN(name, bits, max) \ unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(bits))]; \ - sp_int* name = (sp_int*)name##d + sp_int* (name) = (sp_int*)name##d #else /* Declare a dynamically allocated mp_int. */ #define DECL_MP_INT_SIZE_DYN(name, bits, max) \ @@ -806,7 +806,7 @@ while (0) /* Declare a statically allocated mp_int. */ #define DECL_MP_INT_SIZE(name, bits) \ unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(bits))]; \ - sp_int* name = (sp_int*)name##d + sp_int* (name) = (sp_int*)name##d /* Zero out mp_int of minimal size. */ #define NEW_MP_INT_SIZE(name, bits, heap, type) \ XMEMSET(name, 0, MP_INT_SIZEOF(MP_BITS_CNT(bits))) From b10473976dc36cf8993b122973c43e2d84388491 Mon Sep 17 00:00:00 2001 From: Eric Blankenhorn Date: Tue, 11 Apr 2023 15:03:48 -0500 Subject: [PATCH 132/391] Allow Micrium to use STM32_RNG --- wolfssl/wolfcrypt/settings.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index e4675552ef2..3c378264728 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1559,7 +1559,8 @@ extern void uITRON4_free(void *p) ; #define NO_WOLFSSL_DIR #define NO_WRITEV - #if ! defined(WOLFSSL_SILABS_SE_ACCEL) && !defined(CUSTOM_RAND_GENERATE) + #if !defined(WOLFSSL_SILABS_SE_ACCEL) && !defined(STM32_RNG) && \ + !defined(CUSTOM_RAND_GENERATE) #define CUSTOM_RAND_TYPE RAND_NBR #define CUSTOM_RAND_GENERATE Math_Rand #endif From e05f257c57c1be2b90c086b827cfa6dfdb7ed537 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 10 Apr 2023 14:44:08 -0700 Subject: [PATCH 133/391] Fix for building with heap math and including integer.h only. Fixes https://github.com/wolfSSL/wolfssl/issues/6280 ``` ./configure --enable-heapmath CFLAGS="-DWOLFSSL_PUBLIC_MP" && make && sudo make install cd ../wolfssl-examples/ecc make clean && make ``` --- wolfssl/wolfcrypt/integer.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/wolfssl/wolfcrypt/integer.h b/wolfssl/wolfcrypt/integer.h index 8a51b077251..3ec64ae6683 100644 --- a/wolfssl/wolfcrypt/integer.h +++ b/wolfssl/wolfcrypt/integer.h @@ -34,9 +34,13 @@ * designs. */ -#include +#ifndef USE_INTEGER_HEAP_MATH + + /* Some platforms (like FIPS) may only include integer.h for math. */ + /* Handle variations of fast math, integer and sp math */ + #include -#ifdef USE_INTEGER_HEAP_MATH +#else #include From f28d9a419340742ad9e308adab7002a348586b6b Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 13 Apr 2023 16:56:38 -0500 Subject: [PATCH 134/391] add WOLF_C89 clauses to the W64LIT() definitions in wolfssl/wolfcrypt/types.h, and wrap several long long numeric literals with W64LIT() in wolfcrypt/src/{aes.c,blake2b.c,siphash.c}; add WOLF_C89 handling to SP_ULONG_BITS and SP_ULLONG_BITS setup in wolfssl/wolfcrypt/sp_int.h. --- wolfcrypt/src/aes.c | 8 ++++---- wolfcrypt/src/blake2b.c | 12 ++++++------ wolfcrypt/src/siphash.c | 10 +++++----- wolfssl/wolfcrypt/sp_int.h | 16 ++++++++++++++-- wolfssl/wolfcrypt/types.h | 20 ++++++++++++++++---- 5 files changed, 45 insertions(+), 21 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index d7d577607b4..40751e45702 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -5398,10 +5398,10 @@ static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE]) a = (z8[1] >> 56) & 0xf; /* Rotate z by 4-bits */ - n3 = z8[1] & 0xf0f0f0f0f0f0f0f0ULL; - n2 = z8[1] & 0x0f0f0f0f0f0f0f0fULL; - n1 = z8[0] & 0xf0f0f0f0f0f0f0f0ULL; - n0 = z8[0] & 0x0f0f0f0f0f0f0f0fULL; + n3 = z8[1] & W64LIT(0xf0f0f0f0f0f0f0f0U); + n2 = z8[1] & W64LIT(0x0f0f0f0f0f0f0f0fU); + n1 = z8[0] & W64LIT(0xf0f0f0f0f0f0f0f0U); + n0 = z8[0] & W64LIT(0x0f0f0f0f0f0f0f0fU); z8[1] = (n3 >> 4) | (n2 << 12) | (n0 >> 52); z8[0] = (n1 >> 4) | (n0 << 12); diff --git a/wolfcrypt/src/blake2b.c b/wolfcrypt/src/blake2b.c index 269e7c404b1..ffd85123b7f 100644 --- a/wolfcrypt/src/blake2b.c +++ b/wolfcrypt/src/blake2b.c @@ -48,10 +48,10 @@ static const word64 blake2b_IV[8] = { - 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, - 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, - 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, - 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL + W64LIT(0x6a09e667f3bcc908U), W64LIT(0xbb67ae8584caa73bU), + W64LIT(0x3c6ef372fe94f82bU), W64LIT(0xa54ff53a5f1d36f1U), + W64LIT(0x510e527fade682d1U), W64LIT(0x9b05688c2b3e6c1fU), + W64LIT(0x1f83d9abfb41bd6bU), W64LIT(0x5be0cd19137e2179U) }; static const byte blake2b_sigma[12][16] = @@ -73,7 +73,7 @@ static const byte blake2b_sigma[12][16] = static WC_INLINE int blake2b_set_lastnode( blake2b_state *S ) { - S->f[1] = ~0ULL; + S->f[1] = ~W64LIT(0U); return 0; } @@ -82,7 +82,7 @@ static WC_INLINE int blake2b_set_lastblock( blake2b_state *S ) { if( S->last_node ) blake2b_set_lastnode( S ); - S->f[0] = ~0ULL; + S->f[0] = ~W64LIT(0U); return 0; } diff --git a/wolfcrypt/src/siphash.c b/wolfcrypt/src/siphash.c index 4494b436c54..a2b031da80f 100644 --- a/wolfcrypt/src/siphash.c +++ b/wolfcrypt/src/siphash.c @@ -165,15 +165,15 @@ int wc_InitSipHash(SipHash* sipHash, const unsigned char* key, word64 k1 = GET_U64(key + 8); /* Initialize state with key. */ - sipHash->v[0] = 0x736f6d6570736575ULL; + sipHash->v[0] = W64LIT(0x736f6d6570736575U); if (outSz == SIPHASH_MAC_SIZE_8) { - sipHash->v[1] = 0x646f72616e646f6dULL; + sipHash->v[1] = W64LIT(0x646f72616e646f6dU); } else { - sipHash->v[1] = 0x646f72616e646f83ULL; + sipHash->v[1] = W64LIT(0x646f72616e646f83U); } - sipHash->v[2] = 0x6c7967656e657261ULL; - sipHash->v[3] = 0x7465646279746573ULL; + sipHash->v[2] = W64LIT(0x6c7967656e657261U); + sipHash->v[3] = W64LIT(0x7465646279746573U); sipHash->v[0] ^= k0; sipHash->v[1] ^= k1; diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index 90f2e3f7f41..7dd679e61c7 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -96,7 +96,12 @@ extern "C" { #error "Size of unsigned int not detected" #endif -#if !defined(NO_64BIT) && ULONG_MAX == 18446744073709551615ULL && \ +#if defined(WOLF_C89) && !defined(NO_64BIT) && ULONG_MAX == 18446744073709551615UL + #define SP_ULONG_BITS 64 + + typedef unsigned long sp_uint64; + typedef long sp_int64; +#elif !defined(WOLF_C89) && !defined(NO_64BIT) && ULONG_MAX == 18446744073709551615ULL && \ 4294967295UL != 18446744073709551615ULL /* verify pre-processor supports * 64-bit ULL types */ #define SP_ULONG_BITS 64 @@ -122,7 +127,14 @@ extern "C" { #endif #ifdef ULLONG_MAX - #if ULLONG_MAX == 18446744073709551615ULL + #if defined(WOLF_C89) && ULLONG_MAX == 18446744073709551615UL + #define SP_ULLONG_BITS 64 + + #if SP_ULLONG_BITS > SP_ULONG_BITS + typedef unsigned long long sp_uint64; + typedef long long sp_int64; + #endif + #elif !defined(WOLF_C89) && ULLONG_MAX == 18446744073709551615ULL #define SP_ULLONG_BITS 64 #if SP_ULLONG_BITS > SP_ULONG_BITS diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 8e18d8c6385..28daab71220 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -174,17 +174,29 @@ decouple library dependencies with standard string, memory and so on. typedef unsigned long long word64; #elif defined(SIZEOF_LONG) && SIZEOF_LONG == 8 #define WORD64_AVAILABLE - #define W64LIT(x) x##LL + #ifdef WOLF_C89 + #define W64LIT(x) x##L + #else + #define W64LIT(x) x##LL + #endif typedef long sword64; typedef unsigned long word64; #elif defined(SIZEOF_LONG_LONG) && SIZEOF_LONG_LONG == 8 #define WORD64_AVAILABLE - #define W64LIT(x) x##LL + #ifdef WOLF_C89 + #define W64LIT(x) x##L + #else + #define W64LIT(x) x##LL + #endif typedef long long sword64; typedef unsigned long long word64; #elif defined(__SIZEOF_LONG_LONG__) && __SIZEOF_LONG_LONG__ == 8 #define WORD64_AVAILABLE - #define W64LIT(x) x##LL + #ifdef WOLF_C89 + #define W64LIT(x) x##L + #else + #define W64LIT(x) x##LL + #endif typedef long long sword64; typedef unsigned long long word64; #endif @@ -971,7 +983,7 @@ typedef struct w64wrapper { DYNAMIC_TYPE_SNIFFER_PB_BUFFER = 1003, DYNAMIC_TYPE_SNIFFER_TICKET_ID = 1004, DYNAMIC_TYPE_SNIFFER_NAMED_KEY = 1005, - DYNAMIC_TYPE_SNIFFER_KEY = 1006, + DYNAMIC_TYPE_SNIFFER_KEY = 1006 }; /* max error buffer string size */ From c775c0dcfa07b84c758faa9f3ec20838b52be800 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 13 Apr 2023 16:57:28 -0500 Subject: [PATCH 135/391] wolfcrypt/src/fe_448.c: fix declaration-after-statement in fe448_mul_8(). --- wolfcrypt/src/fe_448.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/fe_448.c b/wolfcrypt/src/fe_448.c index 0dd439ed7db..e0fde82d363 100644 --- a/wolfcrypt/src/fe_448.c +++ b/wolfcrypt/src/fe_448.c @@ -1836,6 +1836,8 @@ static WC_INLINE void fe448_mul_8(sword32* r, const sword32* a, const sword32* b sword64 t13 = (sword64)a[ 6] * b[ 7]; sword64 t113 = (sword64)a[ 7] * b[ 6]; sword64 t14 = (sword64)a[ 7] * b[ 7]; + sword64 o; + sword64 t15; t1 += t101; t2 += t102; t2 += t202; t3 += t103; t3 += t203; t3 += t303; @@ -1852,8 +1854,8 @@ static WC_INLINE void fe448_mul_8(sword32* r, const sword32* a, const sword32* b t11 += t111; t11 += t211; t11 += t311; t12 += t112; t12 += t212; t13 += t113; - sword64 o = t14 >> 28; - sword64 t15 = o; + o = t14 >> 28; + t15 = o; t14 -= o << 28; o = (t0 >> 28); t1 += o; t = o << 28; t0 -= t; o = (t1 >> 28); t2 += o; t = o << 28; t1 -= t; From e695760acd8184134a97305f4e6a7ee51cc3f819 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Fri, 14 Apr 2023 13:27:20 -0500 Subject: [PATCH 136/391] wolfcrypt/src/sakke.c: fixes for C89 "initializer element is not computable at load time". --- wolfcrypt/src/sakke.c | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/sakke.c b/wolfcrypt/src/sakke.c index c84b9fd6cdc..23161818e2c 100644 --- a/wolfcrypt/src/sakke.c +++ b/wolfcrypt/src/sakke.c @@ -2228,11 +2228,20 @@ static int sakke_pairing(SakkeKey* key, ecc_point* p, ecc_point* q, mp_int* r, mp_proj* t2 = key->tmp.p3; mp_int* t3 = &key->tmp.m2; mp_int* prime = &key->params.prime; - mp_int* t[] = { &key->tmp.m1, t3 }; + mp_int* t[] +#ifndef WOLF_C89 + = { &key->tmp.m1, t3 } +#endif + ; int i; mp_digit mp = 0; SakkeKeyParams* params = &key->params; +#ifdef WOLF_C89 + t[0] = &key->tmp.m1; + t[1] = t3; +#endif + (void)table; (void)len; @@ -2575,16 +2584,35 @@ static int sakke_modexp_loop(SakkeKey* key, mp_int* b, mp_int* e, mp_proj* r, { int err; #ifdef WC_NO_CACHE_RESISTANT - mp_proj* c[2] = { r, key->tmp.p2 }; + mp_proj* c[2] +#ifndef WOLF_C89 + = { r, key->tmp.p2 } +#endif + ; #else - mp_proj* c[3] = { r, key->tmp.p3, key->tmp.p2 }; + mp_proj* c[3] +#ifndef WOLF_C89 + = { r, key->tmp.p3, key->tmp.p2 } #endif + ; +#endif /* WC_NO_CACHE_RESISTANT */ mp_int* t1 = &key->tmp.m1; mp_int* t2 = &key->tmp.m2; mp_int* by = key->tmp.p1->z; mp_int* prime = &key->params.prime; int i; +#ifdef WOLF_C89 +#ifdef WC_NO_CACHE_RESISTANT + c[0] = r; + c[1] = key->tmp.p2; +#else + c[0] = r; + c[1] = key->tmp.p3; + c[2] = key->tmp.p2; +#endif /* WC_NO_CACHE_RESISTANT */ +#endif /* WOLF_C89 */ + /* Set the working value to the base in PF_p[q] */ err = mp_montgomery_calc_normalization(c[0]->x, prime); /* Set c[0] to [mont_one, zero] */ From e89b3b06fe8b6fc15c51217b0e55f1422f060a49 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Fri, 14 Apr 2023 13:47:47 -0500 Subject: [PATCH 137/391] wolfssl/wolfcrypt/types.h: add WOLF_ENUM_DUMMY_LAST_ELEMENT() macro, and disable HAVE_ANONYMOUS_INLINE_AGGREGATES ifdef WOLF_C89. --- wolfssl/wolfcrypt/types.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 28daab71220..64250ce1cf1 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -112,16 +112,22 @@ decouple library dependencies with standard string, memory and so on. /* if a version is available, pivot on the version, otherwise guess it's * allowed, subject to override. */ - #if !defined(__STDC__) \ + #if !defined(WOLF_C89) && (!defined(__STDC__) \ || (!defined(__STDC_VERSION__) && !defined(__cplusplus)) \ || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201101L)) \ - || (defined(__cplusplus) && (__cplusplus >= 201103L)) + || (defined(__cplusplus) && (__cplusplus >= 201103L))) #define HAVE_ANONYMOUS_INLINE_AGGREGATES 1 #else #define HAVE_ANONYMOUS_INLINE_AGGREGATES 0 #endif #endif + #if defined(WOLF_C89) || defined(WOLF_NO_TRAILING_ENUM_COMMAS) + #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) _wolf_ ## prefix ## _enum_dummy_last_element + #else + #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) + #endif + /* helpers for stringifying the expanded value of a macro argument rather * than its literal text: */ From 99ba3c067b899b773a206cfe79aea57da69d2ad1 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Fri, 14 Apr 2023 13:48:03 -0500 Subject: [PATCH 138/391] fix "comma at end of enumerator list" warnings in wolfcrypt for C89 compatibility, mostly by just snipping out unneeded comma, but several using WOLF_ENUM_DUMMY_LAST_ELEMENT() to preserve gated enum values as-is. --- wolfcrypt/src/asn.c | 92 ++++++++++++++------------- wolfcrypt/src/coding.c | 2 +- wolfcrypt/src/ecc.c | 3 +- wolfcrypt/src/pkcs12.c | 2 +- wolfcrypt/src/rsa.c | 2 +- wolfssl/wolfcrypt/aes.h | 4 +- wolfssl/wolfcrypt/arc4.h | 2 +- wolfssl/wolfcrypt/asn.h | 32 +++++----- wolfssl/wolfcrypt/asn_public.h | 9 +-- wolfssl/wolfcrypt/chacha.h | 2 +- wolfssl/wolfcrypt/chacha20_poly1305.h | 2 +- wolfssl/wolfcrypt/des3.h | 2 +- wolfssl/wolfcrypt/dh.h | 2 +- wolfssl/wolfcrypt/dsa.h | 2 +- wolfssl/wolfcrypt/ecc.h | 4 +- wolfssl/wolfcrypt/hash.h | 1 + wolfssl/wolfcrypt/hmac.h | 2 + wolfssl/wolfcrypt/pkcs12.h | 2 +- wolfssl/wolfcrypt/pkcs7.h | 5 +- wolfssl/wolfcrypt/poly1305.h | 2 +- wolfssl/wolfcrypt/rsa.h | 2 + wolfssl/wolfcrypt/signature.h | 2 +- wolfssl/wolfcrypt/siphash.h | 2 +- wolfssl/wolfcrypt/sp_int.h | 8 ++- wolfssl/wolfcrypt/srp.h | 4 +- 25 files changed, 105 insertions(+), 87 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 30223ba272d..28745f4076f 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -6332,6 +6332,7 @@ enum { RSAKEYASN_IDX_DQ, RSAKEYASN_IDX_U, #endif + WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX) }; /* Number of items in ASN.1 template for an RSA private key. */ @@ -6628,6 +6629,7 @@ enum { PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ, #endif PKCS8KEYASN_IDX_PKEY_DATA, + WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX) }; /* Number of items in ASN.1 template for a PKCS #8 key. */ @@ -8060,7 +8062,7 @@ enum { PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL, PBES2PARAMSASN_IDX_ENCS_SEQ, PBES2PARAMSASN_IDX_ENCS_OID, - PBES2PARAMSASN_IDX_ENCS_PARAMS, + PBES2PARAMSASN_IDX_ENCS_PARAMS }; /* Number of items in ASN.1 template for PBES2 parameters. */ @@ -8077,7 +8079,7 @@ static const ASNItem pbes1ParamsASN[] = { }; enum { PBES1PARAMSASN_IDX_SALT = 0, - PBES1PARAMSASN_IDX_ITER, + PBES1PARAMSASN_IDX_ITER }; /* Number of items in ASN.1 template for PBES1 parameters. */ @@ -8444,7 +8446,7 @@ enum { PKCS8DECASN_IDX_ENCALGO_OID, PKCS8DECASN_IDX_ENCALGO_PARAMS, PKCS8DECASN_IDX_ENCCONTENT, - PKCS8DECASN_IDX_ENCDATA, + PKCS8DECASN_IDX_ENCDATA }; /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */ @@ -8815,7 +8817,7 @@ enum { P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ, P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT, P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER, - P8ENCPBES1ASN_IDX_ENCDATA, + P8ENCPBES1ASN_IDX_ENCDATA }; #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem)) @@ -9251,7 +9253,7 @@ enum { RSAPUBLICKEYASN_IDX_PUBKEY, RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ, RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N, - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E, + RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E }; /* Number of items in ASN.1 template for an RSA public key. */ @@ -9619,7 +9621,7 @@ enum { DHPARAMASN_IDX_SEQ = 0, DHPARAMASN_IDX_PRIME, DHPARAMASN_IDX_BASE, - DHPARAMASN_IDX_PRIVLEN, + DHPARAMASN_IDX_PRIVLEN }; /* Number of items in ASN.1 template for DH key. */ @@ -9669,7 +9671,7 @@ enum { DHKEYPKCS8ASN_IDX_PKEY_STR, DHKEYPKCS8ASN_IDX_PKEY_INT, DHKEYPKCS8ASN_IDX_PUBKEY_STR, - DHKEYPKCS8ASN_IDX_PUBKEY_INT, + DHKEYPKCS8ASN_IDX_PUBKEY_INT }; #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem)) @@ -10255,7 +10257,7 @@ enum { DSAKEYASN_IDX_Q, DSAKEYASN_IDX_G, DSAKEYASN_IDX_Y, - DSAKEYASN_IDX_X, + DSAKEYASN_IDX_X }; /* Number of items in ASN.1 template for DSA private key. */ @@ -10291,7 +10293,7 @@ enum { DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q, DSAPUBKEYASN_IDX_ALGOID_PARAMS_G, DSAPUBKEYASN_IDX_PUBKEY_STR, - DSAPUBKEYASN_IDX_PUBKEY_Y, + DSAPUBKEYASN_IDX_PUBKEY_Y }; /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */ @@ -10463,7 +10465,7 @@ enum { DSAKEYOCTASN_IDX_Q, DSAKEYOCTASN_IDX_G, DSAKEYOCTASN_IDX_PKEY_STR, - DSAKEYOCTASN_IDX_X, + DSAKEYOCTASN_IDX_X }; /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */ @@ -11331,7 +11333,7 @@ static const ASNItem rsaCertKeyASN[] = { }; enum { RSACERTKEYASN_IDX_STR = 0, - RSACERTKEYASN_IDX_SEQ, + RSACERTKEYASN_IDX_SEQ }; /* Number of items in ASN.1 template for header before RSA key in cert. */ @@ -11434,7 +11436,7 @@ static const ASNItem eccCertKeyASN[] = { enum { ECCCERTKEYASN_IDX_OID = 0, ECCCERTKEYASN_IDX_PARAMS, - ECCCERTKEYASN_IDX_SUBJPUBKEY, + ECCCERTKEYASN_IDX_SUBJPUBKEY }; /* Number of items in ASN.1 template for header before ECC key in cert. */ @@ -12235,7 +12237,7 @@ enum { RDNASN_IDX_SET = 0, RDNASN_IDX_ATTR_SEQ, RDNASN_IDX_ATTR_TYPE, - RDNASN_IDX_ATTR_VAL, + RDNASN_IDX_ATTR_VAL }; /* Number of items in ASN.1 template for an RDN. */ @@ -13427,7 +13429,7 @@ static const ASNItem certNameASN[] = { }; enum { CERTNAMEASN_IDX_OID = 0, - CERTNAMEASN_IDX_NAME, + CERTNAMEASN_IDX_NAME }; /* Number of items in ASN.1 template for certificate name. */ @@ -14010,7 +14012,7 @@ static const ASNItem dateASN[] = { }; enum { DATEASN_IDX_UTC = 0, - DATEASN_IDX_GT, + DATEASN_IDX_GT }; /* Number of items in ASN.1 template for a date. */ @@ -14831,7 +14833,7 @@ enum { DIGESTINFOASN_IDX_DIGALGO_SEQ, DIGESTINFOASN_IDX_DIGALGO_OID, DIGESTINFOASN_IDX_DIGALGO_NULL, - DIGESTINFOASN_IDX_DIGEST, + DIGESTINFOASN_IDX_DIGEST }; /* Number of items in ASN.1 template for DigestInfo for RSA. */ @@ -16601,7 +16603,7 @@ enum { OTHERNAMEASN_IDX_FASCN, OTHERNAMEASN_IDX_HWN_SEQ, OTHERNAMEASN_IDX_HWN_TYPE, - OTHERNAMEASN_IDX_HWN_NUM, + OTHERNAMEASN_IDX_HWN_NUM }; /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */ @@ -16901,7 +16903,7 @@ static const ASNItem altNameASN[] = { { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 } }; enum { - ALTNAMEASN_IDX_GN = 0, + ALTNAMEASN_IDX_GN = 0 }; /* Number of items in ASN.1 template for GeneralName. */ @@ -17513,7 +17515,7 @@ static const ASNItem basicConsASN[] = { enum { BASICCONSASN_IDX_SEQ = 0, BASICCONSASN_IDX_CA, - BASICCONSASN_IDX_PLEN, + BASICCONSASN_IDX_PLEN }; /* Number of items in ASN.1 template for BasicContraints. */ @@ -17721,7 +17723,7 @@ enum { CRLDISTASN_IDX_DP_DISTPOINT_FN_GN, CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */ CRLDISTASN_IDX_DP_REASONS, - CRLDISTASN_IDX_DP_CRLISSUER, + CRLDISTASN_IDX_DP_CRLISSUER }; /* Number of items in ASN.1 template for CRL distribution points. */ @@ -17908,7 +17910,7 @@ static const ASNItem accessDescASN[] = { enum { ACCESSDESCASN_IDX_SEQ = 0, ACCESSDESCASN_IDX_METH, - ACCESSDESCASN_IDX_LOC, + ACCESSDESCASN_IDX_LOC }; /* Number of items in ASN.1 template for the access description. */ @@ -18063,7 +18065,7 @@ enum { AUTHKEYIDASN_IDX_SEQ = 0, AUTHKEYIDASN_IDX_KEYID, AUTHKEYIDASN_IDX_ISSUER, - AUTHKEYIDASN_IDX_SERIAL, + AUTHKEYIDASN_IDX_SERIAL }; /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */ @@ -18211,7 +18213,7 @@ static const ASNItem keyUsageASN[] = { /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 }, }; enum { - KEYUSAGEASN_IDX_STR = 0, + KEYUSAGEASN_IDX_STR = 0 }; /* Number of items in ASN.1 template for KeyUsage. */ @@ -18273,7 +18275,7 @@ static const ASNItem keyPurposeIdASN[] = { /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }, }; enum { - KEYPURPOSEIDASN_IDX_OID = 0, + KEYPURPOSEIDASN_IDX_OID = 0 }; /* Number of items in ASN.1 template for KeyPurposeId. */ @@ -18475,7 +18477,7 @@ enum { SUBTREEASN_IDX_SEQ = 0, SUBTREEASN_IDX_BASE, SUBTREEASN_IDX_MIN, - SUBTREEASN_IDX_MAX, + SUBTREEASN_IDX_MAX }; /* Number of items in ASN.1 template for GeneralSubtree. */ @@ -18695,7 +18697,7 @@ static const ASNItem nameConstraintsASN[] = { enum { NAMECONSTRAINTSASN_IDX_SEQ = 0, NAMECONSTRAINTSASN_IDX_PERMIT, - NAMECONSTRAINTSASN_IDX_EXCLUDE, + NAMECONSTRAINTSASN_IDX_EXCLUDE }; /* Number of items in ASN.1 template for NameConstraints. */ @@ -18864,7 +18866,7 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) enum { POLICYINFOASN_IDX_SEQ = 0, POLICYINFOASN_IDX_ID, - POLICYINFOASN_IDX_QUALI, + POLICYINFOASN_IDX_QUALI }; /* Number of items in ASN.1 template for PolicyInformation. */ @@ -19581,7 +19583,7 @@ static const ASNItem certExtHdrASN[] = { }; enum { CERTEXTHDRASN_IDX_EXTTAG = 0, - CERTEXTHDRASN_IDX_EXTSEQ, + CERTEXTHDRASN_IDX_EXTSEQ }; /* Number of itesm in ASN.1 template for extensions. */ @@ -19603,7 +19605,7 @@ enum { CERTEXTASN_IDX_SEQ = 0, CERTEXTASN_IDX_OID, CERTEXTASN_IDX_CRIT, - CERTEXTASN_IDX_VAL, + CERTEXTASN_IDX_VAL }; /* Number of items in ASN.1 template for Extension. */ @@ -19934,6 +19936,7 @@ enum { X509CERTASN_IDX_SIGALGO_PARAMS, #endif X509CERTASN_IDX_SIGNATURE, + WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX) }; /* Number of items in ASN template for an X509 certificate. */ @@ -20284,7 +20287,7 @@ static const ASNItem reqAttrASN[] = { enum { REQATTRASN_IDX_SEQ = 0, REQATTRASN_IDX_TYPE, - REQATTRASN_IDX_VALS, + REQATTRASN_IDX_VALS }; /* Number of items in ASN.1 template for certificate request Attribute. */ @@ -20295,7 +20298,7 @@ static const ASNItem strAttrASN[] = { { 0, 0, 0, 0, 0 }, }; enum { - STRATTRASN_IDX_STR = 0, + STRATTRASN_IDX_STR = 0 }; /* Number of items in ASN.1 template for a string choice. */ @@ -20521,7 +20524,7 @@ enum { CERTREQASN_IDX_INFO_SIGALGO_SEQ, CERTREQASN_IDX_INFO_SIGALGO_OID, CERTREQASN_IDX_INFO_SIGALGO_NULL, - CERTREQASN_IDX_INFO_SIGNATURE, + CERTREQASN_IDX_INFO_SIGNATURE }; /* Number of items in ASN.1 template for a certificate request. */ @@ -24501,7 +24504,7 @@ enum { ECCPUBLICKEYASN_IDX_ALGOID_OID, ECCPUBLICKEYASN_IDX_ALGOID_CURVEID, ECCPUBLICKEYASN_IDX_ALGOID_PARAMS, - ECCPUBLICKEYASN_IDX_PUBKEY, + ECCPUBLICKEYASN_IDX_PUBKEY }; /* Number of items in ASN.1 template for ECC public key. */ @@ -24756,7 +24759,7 @@ enum { EDPUBKEYASN_IDX_SEQ = 0, EDPUBKEYASN_IDX_ALGOID_SEQ, EDPUBKEYASN_IDX_ALGOID_OID, - EDPUBKEYASN_IDX_PUBKEY, + EDPUBKEYASN_IDX_PUBKEY }; /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */ @@ -25455,7 +25458,7 @@ static const ASNItem ekuASN[] = { }; enum { EKUASN_IDX_SEQ = 0, - EKUASN_IDX_OID, + EKUASN_IDX_OID }; /* OIDs corresponding to extended key usage. */ @@ -26295,7 +26298,7 @@ static const ASNItem nameASN[] = { { 0, ASN_SEQUENCE, 1, 1, 0 }, }; enum { - NAMEASN_IDX_SEQ = 0, + NAMEASN_IDX_SEQ = 0 }; /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */ @@ -26767,8 +26770,7 @@ enum { CERTEXTSASN_IDX_CUSTOM_SEQ, CERTEXTSASN_IDX_CUSTOM_OID, CERTEXTSASN_IDX_CUSTOM_STR, - CERTEXTSASN_IDX_START_CUSTOM, - + CERTEXTSASN_IDX_START_CUSTOM }; /* Number of items in ASN.1 template for certificate extensions. We multiply @@ -28028,7 +28030,7 @@ enum { SIGASN_IDX_SIGALGO_SEQ, SIGASN_IDX_SIGALGO_OID, SIGASN_IDX_SIGALGO_NULL, - SIGASN_IDX_SIGNATURE, + SIGASN_IDX_SIGNATURE }; /* Number of items in ASN.1 template for a Certificate. */ @@ -29152,7 +29154,7 @@ enum { CERTREQBODYASN_IDX_EXT_SEQ, CERTREQBODYASN_IDX_EXT_OID, CERTREQBODYASN_IDX_EXT_SET, - CERTREQBODYASN_IDX_EXT_BODY, + CERTREQBODYASN_IDX_EXT_BODY }; /* Number of items in ASN.1 template for Certificate Request body. */ @@ -30920,7 +30922,7 @@ static const ASNItem dsaSigASN[] = { enum { DSASIGASN_IDX_SEQ = 0, DSASIGASN_IDX_R, - DSASIGASN_IDX_S, + DSASIGASN_IDX_S }; #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem)) @@ -31334,7 +31336,7 @@ enum { ECCSPECIFIEDASN_IDX_BASE, ECCSPECIFIEDASN_IDX_ORDER, ECCSPECIFIEDASN_IDX_COFACTOR, - ECCSPECIFIEDASN_IDX_HASH_SEQ, + ECCSPECIFIEDASN_IDX_HASH_SEQ }; /* Number of items in ASN.1 template for SpecifiedECDomain. */ @@ -31542,7 +31544,7 @@ enum { ECCKEYASN_IDX_CURVEID, ECCKEYASN_IDX_CURVEPARAMS, ECCKEYASN_IDX_PUBKEY, - ECCKEYASN_IDX_PUBKEY_VAL, + ECCKEYASN_IDX_PUBKEY_VAL }; /* Number of items in ASN.1 template for ECC private key. */ @@ -32638,7 +32640,7 @@ enum { EDKEYASN_IDX_PKEY, EDKEYASN_IDX_PKEY_CURVEPKEY, EDKEYASN_IDX_ATTRS, - EDKEYASN_IDX_PUBKEY, + EDKEYASN_IDX_PUBKEY }; /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */ @@ -35193,7 +35195,7 @@ static const ASNItem nameHashASN[] = { }; enum { NAMEHASHASN_IDX_OID = 0, - NAMEHASHASN_IDX_NAME, + NAMEHASHASN_IDX_NAME }; /* Number of items in ASN.1 template for certificate name hash. */ diff --git a/wolfcrypt/src/coding.c b/wolfcrypt/src/coding.c index 6d836a0488f..a3667da34f8 100644 --- a/wolfcrypt/src/coding.c +++ b/wolfcrypt/src/coding.c @@ -45,7 +45,7 @@ enum { BAD = 0xFF, /* invalid encoding */ PAD = '=', BASE64_MIN = 0x2B, - BASE16_MIN = 0x30, + BASE16_MIN = 0x30 }; diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 3d237de8eb4..1fa6370eea9 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -251,7 +251,7 @@ enum { ECC_STATE_VERIFY_DECODE, ECC_STATE_VERIFY_DO, - ECC_STATE_VERIFY_RES, + ECC_STATE_VERIFY_RES }; @@ -1344,6 +1344,7 @@ enum ecc_curve_load_mask { ECC_CURVE_FIELD_ALL = 0x3B, ECC_CURVE_FIELD_COUNT = 5, #endif + WOLF_ENUM_DUMMY_LAST_ELEMENT(ecc_curve_load_mask) }; #if defined(WOLFSSL_XILINX_CRYPT_VERSAL) diff --git a/wolfcrypt/src/pkcs12.c b/wolfcrypt/src/pkcs12.c index b852c606781..7756d4379e0 100644 --- a/wolfcrypt/src/pkcs12.c +++ b/wolfcrypt/src/pkcs12.c @@ -60,7 +60,7 @@ enum { WC_PKCS12_ENCRYPTED_DATA = 656, WC_PKCS12_DATA_OBJ_SZ = 11, - WC_PKCS12_MAC_SALT_SZ = 8, + WC_PKCS12_MAC_SALT_SZ = 8 }; static const byte WC_PKCS12_ENCRYPTED_OID[] = diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index 54503236ea5..e63ddc96a4f 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -238,7 +238,7 @@ enum { RSA_STATE_DECRYPT_EXPTMOD, RSA_STATE_DECRYPT_UNPAD, - RSA_STATE_DECRYPT_RES, + RSA_STATE_DECRYPT_RES }; diff --git a/wolfssl/wolfcrypt/aes.h b/wolfssl/wolfcrypt/aes.h index 449220994a2..719512cc5af 100644 --- a/wolfssl/wolfcrypt/aes.h +++ b/wolfssl/wolfcrypt/aes.h @@ -138,7 +138,7 @@ enum { AES_192_KEY_SIZE = 24, /* for 192 bit */ AES_256_KEY_SIZE = 32, /* for 256 bit */ - AES_IV_SIZE = 16, /* always block size */ + AES_IV_SIZE = 16 /* always block size */ }; #endif @@ -180,6 +180,8 @@ enum { AES_MAX_ID_LEN = 32, AES_MAX_LABEL_LEN = 32, #endif + + WOLF_ENUM_DUMMY_LAST_ELEMENT(AES) }; diff --git a/wolfssl/wolfcrypt/arc4.h b/wolfssl/wolfcrypt/arc4.h index ad97921681d..fe58b10ece9 100644 --- a/wolfssl/wolfcrypt/arc4.h +++ b/wolfssl/wolfcrypt/arc4.h @@ -39,7 +39,7 @@ enum { ARC4_ENC_TYPE = 4, /* cipher unique type */ ARC4_STATE_SIZE = 256, - RC4_KEY_SIZE = 16, /* always 128bit */ + RC4_KEY_SIZE = 16 /* always 128bit */ }; /* ARC4 encryption and decryption */ diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 8e7327219f1..5de97bd0985 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -154,7 +154,7 @@ enum ASN_Tags { /* OneAsymmetricKey Fields */ ASN_ASYMKEY_ATTRS = 0x00, - ASN_ASYMKEY_PUBKEY = 0x01, + ASN_ASYMKEY_PUBKEY = 0x01 }; /* NOTE: If ASN_UTC_TIME_SIZE or ASN_GENERALIZED_TIME_SIZE are ever modified @@ -188,7 +188,7 @@ enum ASNItem_DataType { /* Big number as a positive or negative mp_int. */ ASN_DATA_TYPE_MP_POS_NEG = 9, /* ASN.1 CHOICE. A 0 terminated list of tags that are valid. */ - ASN_DATA_TYPE_CHOICE = 10, + ASN_DATA_TYPE_CHOICE = 10 }; /* A template entry describing an ASN.1 item. */ @@ -1002,7 +1002,7 @@ enum Misc_ASN { PEM_LINE_SZ = 64, /* Length of Base64 encoded line, not including new line */ PEM_LINE_LEN = PEM_LINE_SZ + 12, /* PEM line max + fudge */ - COUNTRY_CODE_LEN = 2, /* RFC 3739 */ + COUNTRY_CODE_LEN = 2 /* RFC 3739 */ }; #ifndef WC_MAX_NAME_ENTRIES @@ -1109,7 +1109,7 @@ enum Key_Sum { SPHINCS_FAST_LEVEL5k = 282, /* 1 3 9999 6 9 3 */ SPHINCS_SMALL_LEVEL1k = 287, /* 1 3 9999 6 7 10 */ SPHINCS_SMALL_LEVEL3k = 285, /* 1 3 9999 6 8 7 */ - SPHINCS_SMALL_LEVEL5k = 286, /* 1 3 9999 6 9 7 */ + SPHINCS_SMALL_LEVEL5k = 286 /* 1 3 9999 6 9 7 */ }; #if !defined(NO_AES) || defined(HAVE_PKCS7) @@ -1134,14 +1134,14 @@ enum Key_Agree { dhSinglePass_stdDH_sha224kdf_scheme = 188, dhSinglePass_stdDH_sha256kdf_scheme = 189, dhSinglePass_stdDH_sha384kdf_scheme = 190, - dhSinglePass_stdDH_sha512kdf_scheme = 191, + dhSinglePass_stdDH_sha512kdf_scheme = 191 }; enum KDF_Sum { PBKDF2_OID = 660, - MGF1_OID = 652, + MGF1_OID = 652 }; @@ -1193,8 +1193,9 @@ enum CertificatePolicy_Sum { CP_FPKI_COMMON_AUTH_OID = 426, /* 2.16.840.1.101.3.2.1.3.13 */ CP_FPKI_PIV_AUTH_OID = 453, /* 2.16.840.1.101.3.2.1.3.40 */ CP_FPKI_PIV_AUTH_HW_OID = 454, /* 2.16.840.1.101.3.2.1.3.41 */ - CP_FPKI_PIVI_AUTH_OID = 458 /* 2.16.840.1.101.3.2.1.3.45 */ + CP_FPKI_PIVI_AUTH_OID = 458, /* 2.16.840.1.101.3.2.1.3.45 */ #endif /* WOLFSSL_FPKI */ + WOLF_ENUM_DUMMY_LAST_ELEMENT(CertificatePolicy_Sum) }; enum SepHardwareName_Sum { @@ -1205,8 +1206,9 @@ enum AuthInfo_Sum { AIA_OCSP_OID = 116, /* 1.3.6.1.5.5.7.48.1, id-ad-ocsp */ AIA_CA_ISSUER_OID = 117, /* 1.3.6.1.5.5.7.48.2, id-ad-caIssuers */ #ifdef WOLFSSL_SUBJ_INFO_ACC - AIA_CA_REPO_OID = 120 /* 1.3.6.1.5.5.7.48.5, id-ad-caRepository */ + AIA_CA_REPO_OID = 120, /* 1.3.6.1.5.5.7.48.5, id-ad-caRepository */ #endif /* WOLFSSL_SUBJ_INFO_ACC */ + WOLF_ENUM_DUMMY_LAST_ELEMENT(AuthInfo_Sum) }; #define ID_PKIX(num) (67+(num)) /* 1.3.6.1.5.5.7.num, id-pkix num */ @@ -1252,7 +1254,7 @@ enum VerifyType { VERIFY_OCSP = 3, VERIFY_NAME = 4, VERIFY_SKIP_DATE = 5, - VERIFY_OCSP_CERT = 6, + VERIFY_OCSP_CERT = 6 }; #ifdef WOLFSSL_CERT_EXT @@ -1274,7 +1276,7 @@ enum CsrAttrType { INITIALS_OID = 132, SURNAME_OID = 93, NAME_OID = 130, - GIVEN_NAME_OID = 131, + GIVEN_NAME_OID = 131 }; #endif @@ -1357,7 +1359,7 @@ enum SignatureState { SIG_STATE_HASH, SIG_STATE_KEY, SIG_STATE_DO, - SIG_STATE_CHECK, + SIG_STATE_CHECK }; @@ -1467,7 +1469,7 @@ enum CertSignState { CERTSIGN_STATE_BEGIN, CERTSIGN_STATE_DIGEST, CERTSIGN_STATE_ENCODE, - CERTSIGN_STATE_DO, + CERTSIGN_STATE_DO }; struct CertSignCtx { @@ -2250,7 +2252,7 @@ enum cert_enums { SPHINCS_FAST_LEVEL5_KEY = 26, SPHINCS_SMALL_LEVEL1_KEY = 27, SPHINCS_SMALL_LEVEL3_KEY = 28, - SPHINCS_SMALL_LEVEL5_KEY = 29, + SPHINCS_SMALL_LEVEL5_KEY = 29 }; #endif /* WOLFSSL_CERT_GEN */ @@ -2535,7 +2537,7 @@ enum PBESTypes { PBES2 = 13, /* algo ID */ PBES1_MD5_DES = 3, - PBES1_SHA1_DES = 10, + PBES1_SHA1_DES = 10 }; enum PKCSTypes { @@ -2545,7 +2547,7 @@ enum PKCSTypes { PKCS8v0 = 0, /* default PKCS#8 version */ PKCS8v1 = 1, /* PKCS#8 version including public key */ PKCS1v0 = 0, /* default PKCS#1 version */ - PKCS1v1 = 1, /* Multi-prime version */ + PKCS1v1 = 1 /* Multi-prime version */ }; #endif /* !NO_ASN || !NO_PWDBASED */ diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index fb43f974887..0de6a2e6d8a 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -112,7 +112,7 @@ enum Ecc_Sum { ECC_SECP384R1_OID = 210, ECC_BRAINPOOLP384R1_OID = 108, ECC_BRAINPOOLP512R1_OID = 110, - ECC_SECP521R1_OID = 211, + ECC_SECP521R1_OID = 211 }; @@ -154,7 +154,7 @@ enum CertType { SPHINCS_SMALL_LEVEL1_TYPE, SPHINCS_SMALL_LEVEL3_TYPE, SPHINCS_SMALL_LEVEL5_TYPE, - ECC_PARAM_TYPE, + ECC_PARAM_TYPE }; @@ -202,7 +202,7 @@ enum Ctc_SigType { CTC_SPHINCS_FAST_LEVEL5 = 282, CTC_SPHINCS_SMALL_LEVEL1 = 287, CTC_SPHINCS_SMALL_LEVEL3 = 285, - CTC_SPHINCS_SMALL_LEVEL5 = 286, + CTC_SPHINCS_SMALL_LEVEL5 = 286 }; enum Ctc_Encoding { @@ -243,6 +243,7 @@ enum Ctc_Misc { * enough for at least two * distribution points. */ #endif /* WOLFSSL_CERT_EXT */ + WOLF_ENUM_DUMMY_LAST_ELEMENT(Ctc_Misc) }; /* DER buffer */ @@ -270,7 +271,7 @@ enum { #endif PEM_PASS_READ = 0, - PEM_PASS_WRITE = 1, + PEM_PASS_WRITE = 1 }; typedef int (wc_pem_password_cb)(char* passwd, int sz, int rw, void* userdata); diff --git a/wolfssl/wolfcrypt/chacha.h b/wolfssl/wolfcrypt/chacha.h index e654972ffb1..7cd73db4e36 100644 --- a/wolfssl/wolfcrypt/chacha.h +++ b/wolfssl/wolfcrypt/chacha.h @@ -72,7 +72,7 @@ Block counter is located at index 12. enum { CHACHA_ENC_TYPE = WC_CIPHER_CHACHA, /* cipher unique type */ - CHACHA_MAX_KEY_SZ = 32, + CHACHA_MAX_KEY_SZ = 32 }; typedef struct ChaCha { diff --git a/wolfssl/wolfcrypt/chacha20_poly1305.h b/wolfssl/wolfcrypt/chacha20_poly1305.h index 7c1ddc97bb1..6c04912a03c 100644 --- a/wolfssl/wolfcrypt/chacha20_poly1305.h +++ b/wolfssl/wolfcrypt/chacha20_poly1305.h @@ -61,7 +61,7 @@ enum { CHACHA20_POLY1305_STATE_INIT = 0, CHACHA20_POLY1305_STATE_READY = 1, CHACHA20_POLY1305_STATE_AAD = 2, - CHACHA20_POLY1305_STATE_DATA = 3, + CHACHA20_POLY1305_STATE_DATA = 3 }; typedef struct ChaChaPoly_Aead { diff --git a/wolfssl/wolfcrypt/des3.h b/wolfssl/wolfcrypt/des3.h index 94278814f97..96e154dd2a9 100644 --- a/wolfssl/wolfcrypt/des3.h +++ b/wolfssl/wolfcrypt/des3.h @@ -49,7 +49,7 @@ enum { DES_KEY_SIZE = 8, /* des */ DES3_KEY_SIZE = 24, /* 3 des ede */ - DES_IV_SIZE = 8, /* should be the same as DES_BLOCK_SIZE */ + DES_IV_SIZE = 8 /* should be the same as DES_BLOCK_SIZE */ }; diff --git a/wolfssl/wolfcrypt/dh.h b/wolfssl/wolfcrypt/dh.h index 0b48c5cf74e..e94cb593162 100644 --- a/wolfssl/wolfcrypt/dh.h +++ b/wolfssl/wolfcrypt/dh.h @@ -88,7 +88,7 @@ enum { WC_FFDHE_3072 = 257, WC_FFDHE_4096 = 258, WC_FFDHE_6144 = 259, - WC_FFDHE_8192 = 260, + WC_FFDHE_8192 = 260 }; /* DH Private Key size up to 8192 bit */ diff --git a/wolfssl/wolfcrypt/dsa.h b/wolfssl/wolfcrypt/dsa.h index 737dc094db8..c6d0ec19d92 100644 --- a/wolfssl/wolfcrypt/dsa.h +++ b/wolfssl/wolfcrypt/dsa.h @@ -66,7 +66,7 @@ enum { DSA_MIN_SIG_SIZE = DSA_160_SIG_SIZE, DSA_MAX_HALF_SIZE = DSA_256_HALF_SIZE, - DSA_MAX_SIG_SIZE = DSA_256_SIG_SIZE, + DSA_MAX_SIG_SIZE = DSA_256_SIG_SIZE }; /* DSA */ diff --git a/wolfssl/wolfcrypt/ecc.h b/wolfssl/wolfcrypt/ecc.h index 72fb2c5b384..a077df9e4a5 100644 --- a/wolfssl/wolfcrypt/ecc.h +++ b/wolfssl/wolfcrypt/ecc.h @@ -195,6 +195,8 @@ enum { ECC_MAX_ID_LEN = 32, ECC_MAX_LABEL_LEN = 32, #endif + + WOLF_ENUM_DUMMY_LAST_ELEMENT(ECC) }; #endif /* HAVE_ECC */ @@ -413,7 +415,7 @@ typedef struct { enum { WC_ECC_FLAG_NONE = 0x00, WC_ECC_FLAG_COFACTOR = 0x01, - WC_ECC_FLAG_DEC_SIGN = 0x02, + WC_ECC_FLAG_DEC_SIGN = 0x02 }; /* ECC non-blocking */ diff --git a/wolfssl/wolfcrypt/hash.h b/wolfssl/wolfcrypt/hash.h index bf62ca8cf6c..71a21c2e309 100644 --- a/wolfssl/wolfcrypt/hash.h +++ b/wolfssl/wolfcrypt/hash.h @@ -86,6 +86,7 @@ enum wc_HashFlags { #ifdef WOLFSSL_SHA3 WC_HASH_SHA3_KECCAK256 =0x00010000, /* Older KECCAK256 */ #endif + WOLF_ENUM_DUMMY_LAST_ELEMENT(WC_HASH) }; #ifndef NO_HASH_WRAPPER diff --git a/wolfssl/wolfcrypt/hmac.h b/wolfssl/wolfcrypt/hmac.h index 86c97ebfbfe..b17e40f4675 100644 --- a/wolfssl/wolfcrypt/hmac.h +++ b/wolfssl/wolfcrypt/hmac.h @@ -107,6 +107,8 @@ enum { HMAC_MAX_ID_LEN = 32, HMAC_MAX_LABEL_LEN = 32, #endif + + WOLF_ENUM_DUMMY_LAST_ELEMENT(HMAC) }; /* Select the largest available hash for the buffer size. */ diff --git a/wolfssl/wolfcrypt/pkcs12.h b/wolfssl/wolfcrypt/pkcs12.h index 4773966982c..f3023540e44 100644 --- a/wolfssl/wolfcrypt/pkcs12.h +++ b/wolfssl/wolfcrypt/pkcs12.h @@ -43,7 +43,7 @@ typedef struct WC_DerCertList { /* dereferenced in ssl.c */ enum { WC_PKCS12_ITT_DEFAULT = 2048, WC_PKCS12_VERSION_DEFAULT = 3, - WC_PKCS12_MAC_DEFAULT = 1, + WC_PKCS12_MAC_DEFAULT = 1 }; WOLFSSL_API WC_PKCS12* wc_PKCS12_new(void); diff --git a/wolfssl/wolfcrypt/pkcs7.h b/wolfssl/wolfcrypt/pkcs7.h index d260f0155cc..b870666756a 100644 --- a/wolfssl/wolfcrypt/pkcs7.h +++ b/wolfssl/wolfcrypt/pkcs7.h @@ -141,7 +141,7 @@ enum PKCS7_STATE { WC_PKCS7_DECRYPT_PWRI, WC_PKCS7_DECRYPT_ORI, - WC_PKCS7_DECRYPT_DONE, + WC_PKCS7_DECRYPT_DONE }; @@ -158,11 +158,12 @@ enum Pkcs7_Misc { MAX_RECIP_SZ = MAX_VERSION_SZ + MAX_SEQ_SZ + WC_ASN_NAME_MAX + MAX_SN_SZ + MAX_SEQ_SZ + MAX_ALGO_SZ + 1 + MAX_ENCRYPTED_KEY_SZ, + WOLF_ENUM_DUMMY_LAST_ELEMENT(Pkcs7_Misc) }; enum Cms_Options { CMS_SKID = 1, - CMS_ISSUER_AND_SERIAL_NUMBER = 2, + CMS_ISSUER_AND_SERIAL_NUMBER = 2 }; #define DEGENERATE_SID 3 diff --git a/wolfssl/wolfcrypt/poly1305.h b/wolfssl/wolfcrypt/poly1305.h index 0fd9d3c3056..c0a5b8dfc11 100644 --- a/wolfssl/wolfcrypt/poly1305.h +++ b/wolfssl/wolfcrypt/poly1305.h @@ -59,7 +59,7 @@ enum { POLY1305 = 7, POLY1305_BLOCK_SIZE = 16, - POLY1305_DIGEST_SIZE = 16, + POLY1305_DIGEST_SIZE = 16 }; #define WC_POLY1305_PAD_SZ 16 diff --git a/wolfssl/wolfcrypt/rsa.h b/wolfssl/wolfcrypt/rsa.h index 6d31aab558e..3af61899576 100644 --- a/wolfssl/wolfcrypt/rsa.h +++ b/wolfssl/wolfcrypt/rsa.h @@ -180,6 +180,8 @@ enum { RSA_MAX_ID_LEN = 32, RSA_MAX_LABEL_LEN = 32, #endif + + WOLF_ENUM_DUMMY_LAST_ELEMENT(RSA) }; #ifdef WC_RSA_NONBLOCK diff --git a/wolfssl/wolfcrypt/signature.h b/wolfssl/wolfcrypt/signature.h index ca641571cae..f712c0478af 100644 --- a/wolfssl/wolfcrypt/signature.h +++ b/wolfssl/wolfcrypt/signature.h @@ -39,7 +39,7 @@ enum wc_SignatureType { WC_SIGNATURE_TYPE_NONE = 0, WC_SIGNATURE_TYPE_ECC = 1, WC_SIGNATURE_TYPE_RSA = 2, - WC_SIGNATURE_TYPE_RSA_W_ENC = 3, /* Adds DER header via wc_EncodeSignature */ + WC_SIGNATURE_TYPE_RSA_W_ENC = 3 /* Adds DER header via wc_EncodeSignature */ }; WOLFSSL_API int wc_SignatureGetSize(enum wc_SignatureType sig_type, diff --git a/wolfssl/wolfcrypt/siphash.h b/wolfssl/wolfcrypt/siphash.h index 64931c36c50..ebb13024ca2 100644 --- a/wolfssl/wolfcrypt/siphash.h +++ b/wolfssl/wolfcrypt/siphash.h @@ -59,7 +59,7 @@ enum { SIPHASH_KEY_SIZE = 16, /* Key size of SipHash. */ SIPHASH_BLOCK_SIZE = 8, /* Block size of SipHash. */ SIPHASH_MAC_SIZE_8 = 8, /* Output an 8 byte MAC. */ - SIPHASH_MAC_SIZE_16 = 16, /* Output a 16 byte MAC. */ + SIPHASH_MAC_SIZE_16 = 16 /* Output a 16 byte MAC. */ }; typedef struct SipHash SipHash; diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index 7dd679e61c7..5eb845f8983 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -96,14 +96,16 @@ extern "C" { #error "Size of unsigned int not detected" #endif -#if defined(WOLF_C89) && !defined(NO_64BIT) && ULONG_MAX == 18446744073709551615UL +#if defined(WOLF_C89) && !defined(NO_64BIT) && \ + ULONG_MAX == 18446744073709551615UL #define SP_ULONG_BITS 64 typedef unsigned long sp_uint64; typedef long sp_int64; -#elif !defined(WOLF_C89) && !defined(NO_64BIT) && ULONG_MAX == 18446744073709551615ULL && \ +#elif !defined(WOLF_C89) && !defined(NO_64BIT) && \ + ULONG_MAX == 18446744073709551615ULL && \ 4294967295UL != 18446744073709551615ULL /* verify pre-processor supports - * 64-bit ULL types */ + * 64-bit ULL types */ #define SP_ULONG_BITS 64 typedef unsigned long sp_uint64; diff --git a/wolfssl/wolfcrypt/srp.h b/wolfssl/wolfcrypt/srp.h index f589e20aeaf..7832113a7ba 100644 --- a/wolfssl/wolfcrypt/srp.h +++ b/wolfssl/wolfcrypt/srp.h @@ -65,7 +65,7 @@ */ typedef enum { SRP_CLIENT_SIDE = 0, - SRP_SERVER_SIDE = 1, + SRP_SERVER_SIDE = 1 } SrpSide; /** @@ -75,7 +75,7 @@ typedef enum { SRP_TYPE_SHA = 1, SRP_TYPE_SHA256 = 2, SRP_TYPE_SHA384 = 3, - SRP_TYPE_SHA512 = 4, + SRP_TYPE_SHA512 = 4 } SrpType; From a4260ae1555122ae213afd5edfcb0b995401c28a Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Fri, 14 Apr 2023 15:07:05 -0500 Subject: [PATCH 139/391] address peer review: make C89-compatible refactors in sakke_pairing() and sakke_modexp_loop(); add explanatory comment for WOLF_ENUM_DUMMY_LAST_ELEMENT() in types.h. --- wolfcrypt/src/sakke.c | 24 ++++-------------------- wolfssl/wolfcrypt/types.h | 6 ++++++ 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/wolfcrypt/src/sakke.c b/wolfcrypt/src/sakke.c index 23161818e2c..17d61d93af1 100644 --- a/wolfcrypt/src/sakke.c +++ b/wolfcrypt/src/sakke.c @@ -2228,19 +2228,13 @@ static int sakke_pairing(SakkeKey* key, ecc_point* p, ecc_point* q, mp_int* r, mp_proj* t2 = key->tmp.p3; mp_int* t3 = &key->tmp.m2; mp_int* prime = &key->params.prime; - mp_int* t[] -#ifndef WOLF_C89 - = { &key->tmp.m1, t3 } -#endif - ; + mp_int* t[2]; int i; mp_digit mp = 0; SakkeKeyParams* params = &key->params; -#ifdef WOLF_C89 t[0] = &key->tmp.m1; t[1] = t3; -#endif (void)table; (void)len; @@ -2584,25 +2578,16 @@ static int sakke_modexp_loop(SakkeKey* key, mp_int* b, mp_int* e, mp_proj* r, { int err; #ifdef WC_NO_CACHE_RESISTANT - mp_proj* c[2] -#ifndef WOLF_C89 - = { r, key->tmp.p2 } -#endif - ; + mp_proj* c[2]; #else - mp_proj* c[3] -#ifndef WOLF_C89 - = { r, key->tmp.p3, key->tmp.p2 } + mp_proj* c[3]; #endif - ; -#endif /* WC_NO_CACHE_RESISTANT */ mp_int* t1 = &key->tmp.m1; mp_int* t2 = &key->tmp.m2; mp_int* by = key->tmp.p1->z; mp_int* prime = &key->params.prime; int i; -#ifdef WOLF_C89 #ifdef WC_NO_CACHE_RESISTANT c[0] = r; c[1] = key->tmp.p2; @@ -2610,8 +2595,7 @@ static int sakke_modexp_loop(SakkeKey* key, mp_int* b, mp_int* e, mp_proj* r, c[0] = r; c[1] = key->tmp.p3; c[2] = key->tmp.p2; -#endif /* WC_NO_CACHE_RESISTANT */ -#endif /* WOLF_C89 */ +#endif /* Set the working value to the base in PF_p[q] */ err = mp_montgomery_calc_normalization(c[0]->x, prime); diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 64250ce1cf1..4fdc88a82ca 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -122,6 +122,12 @@ decouple library dependencies with standard string, memory and so on. #endif #endif + /* With a true C89-dialect compiler (simulate with gcc -std=c89 -Wall + * -Wextra -pedantic), a trailing comma on the last value in an enum + * definition is a syntax error. We use this macro to accommodate that + * without disrupting clean flow/syntax when some enum values are + * preprocessor-gated. + */ #if defined(WOLF_C89) || defined(WOLF_NO_TRAILING_ENUM_COMMAS) #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) _wolf_ ## prefix ## _enum_dummy_last_element #else From 4f5f87d967c2da62eeed20ae7bae75af1f35c917 Mon Sep 17 00:00:00 2001 From: Chris Conlon Date: Mon, 10 Apr 2023 15:43:31 -0600 Subject: [PATCH 140/391] Only send session ID in resumed ClientHello from SendTls13ClientHello() if ssl->options.resuming --- src/tls13.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/tls13.c b/src/tls13.c index cd6d07d9216..3f99970e5a6 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -4086,7 +4086,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) ssl->options.tls13MiddleBoxCompat = 1; } #else - if (ssl->session->sessionIDSz > 0) + if (ssl->options.resuming && ssl->session->sessionIDSz > 0) args->length += ssl->session->sessionIDSz; #endif @@ -4231,10 +4231,16 @@ int SendTls13ClientHello(WOLFSSL* ssl) if (ssl->session->sessionIDSz > 0) { /* Session resumption for old versions of protocol. */ - args->output[args->idx++] = ID_LEN; - XMEMCPY(args->output + args->idx, ssl->session->sessionID, - ssl->session->sessionIDSz); - args->idx += ID_LEN; + if (ssl->options.resuming) { + args->output[args->idx++] = ID_LEN; + XMEMCPY(args->output + args->idx, ssl->session->sessionID, + ssl->session->sessionIDSz); + args->idx += ID_LEN; + } + else { + /* Not resuming, zero length session ID */ + args->output[args->idx++] = 0; + } } else { #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT From f51a6723f7c51bfcce668663a8982d1bcb8ef084 Mon Sep 17 00:00:00 2001 From: tim-weller-wolfssl Date: Wed, 12 Apr 2023 12:30:42 -0500 Subject: [PATCH 141/391] Update wolfCrypt porting layer for Mynewt OS to provide declarations needed to remove build warning for time API used for XTIME --- wolfssl/wolfcrypt/wc_port.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 454088823c5..c1731a9319a 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -916,6 +916,8 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #elif defined(WOLFSSL_APACHE_MYNEWT) #include "os/os_time.h" + typedef long time_t; + extern time_t mynewt_time(time_t* timer); #define XTIME(t1) mynewt_time((t1)) #define WOLFSSL_GMTIME #define USE_WOLF_TM From 264aa1c104e2ab3c7e4dcaa2e3e0b4cd1f2c6e4c Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 12 Apr 2023 15:33:59 -0700 Subject: [PATCH 142/391] add nomath option for builds without a math library --- configure.ac | 21 ++++++++++++++++++++- wolfssl/wolfcrypt/settings.h | 5 +++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index 7318ec8880c..5586040b550 100644 --- a/configure.ac +++ b/configure.ac @@ -536,6 +536,25 @@ fi # MATH LIBRARY SELECTION + +# no math library +AC_ARG_ENABLE([nomath], + [AS_HELP_STRING([--enable-nomath],[Enable no math library (default: disabled)])], + [ ENABLED_NOMATH=$enableval ], + [ ENABLED_NOMATH="no" ] + ) + +if test "$ENABLED_NOMATH" = "yes" +then + DEF_SP_MATH="no" + DEF_FAST_MATH="no" + ENABLED_SP_MATH_DEFAULT=no + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_NO_MATH" + ENABLED_HEAPMATH="no" + ENABLED_SP="no" + ENABLED_SP_MATH_ALL="no" +fi + # Single Precision maths implementation AC_ARG_ENABLE([sp], [AS_HELP_STRING([--enable-sp],[Enable Single Precision maths implementation (default: disabled)])], @@ -671,7 +690,7 @@ AC_ARG_ENABLE([heapmath], [ ENABLED_HEAPMATH=$enableval ], [ ENABLED_HEAPMATH=no] ) -if test "x$ENABLED_HEAPMATH" = "xyes" || (test "x$ENABLED_SP_MATH_ALL" = "xno" && test "x$ENABLED_FASTMATH" = "xno" && test "x$ENABLED_SP_MATH" = "xno") +if test "x$ENABLED_HEAPMATH" = "xyes" || (test "x$ENABLED_NOMATH" = "xno" && test "x$ENABLED_SP_MATH_ALL" = "xno" && test "x$ENABLED_FASTMATH" = "xno" && test "x$ENABLED_SP_MATH" = "xno") then AM_CFLAGS="$AM_CFLAGS -DUSE_INTEGER_HEAP_MATH" ENABLED_HEAPMATH="yes" diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 3c378264728..7e9e5907b69 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2037,6 +2037,11 @@ extern void uITRON4_free(void *p) ; * Constant time: Not supported * Enable: USE_INTEGER_HEAP_MATH */ + #elif defined(WOLFSSL_NO_MATH) + /* 5) No math library compiled in + * Does not support any public key operations or algorithms that + * require the math library. + */ #else /* default is SP Math. */ #define WOLFSSL_SP_MATH_ALL From 14eab03db9d1334f3da789214cdfbc9dc028d744 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Thu, 13 Apr 2023 14:38:35 -0700 Subject: [PATCH 143/391] do not default to heapmath if no other math libraries found, add NO_BIG_INT as a math option in settings.h --- configure.ac | 24 +++++------------------- wolfssl/wolfcrypt/settings.h | 6 ++---- 2 files changed, 7 insertions(+), 23 deletions(-) diff --git a/configure.ac b/configure.ac index 5586040b550..3d0e34b2dab 100644 --- a/configure.ac +++ b/configure.ac @@ -537,24 +537,6 @@ fi # MATH LIBRARY SELECTION -# no math library -AC_ARG_ENABLE([nomath], - [AS_HELP_STRING([--enable-nomath],[Enable no math library (default: disabled)])], - [ ENABLED_NOMATH=$enableval ], - [ ENABLED_NOMATH="no" ] - ) - -if test "$ENABLED_NOMATH" = "yes" -then - DEF_SP_MATH="no" - DEF_FAST_MATH="no" - ENABLED_SP_MATH_DEFAULT=no - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_NO_MATH" - ENABLED_HEAPMATH="no" - ENABLED_SP="no" - ENABLED_SP_MATH_ALL="no" -fi - # Single Precision maths implementation AC_ARG_ENABLE([sp], [AS_HELP_STRING([--enable-sp],[Enable Single Precision maths implementation (default: disabled)])], @@ -690,7 +672,7 @@ AC_ARG_ENABLE([heapmath], [ ENABLED_HEAPMATH=$enableval ], [ ENABLED_HEAPMATH=no] ) -if test "x$ENABLED_HEAPMATH" = "xyes" || (test "x$ENABLED_NOMATH" = "xno" && test "x$ENABLED_SP_MATH_ALL" = "xno" && test "x$ENABLED_FASTMATH" = "xno" && test "x$ENABLED_SP_MATH" = "xno") +if test "x$ENABLED_HEAPMATH" = "xyes" then AM_CFLAGS="$AM_CFLAGS -DUSE_INTEGER_HEAP_MATH" ENABLED_HEAPMATH="yes" @@ -7959,6 +7941,10 @@ AS_IF([test "x$ENABLED_16BIT" = "xyes" && \ ################################################################################ # Update CFLAGS based on options # ################################################################################ +AS_IF([test "x$ENABLED_SP_MATH_ALL" = "xno" && test "x$ENABLED_FASTMATH" = "xno" && + test "x$ENABLED_HEAPMATH" = "xno"], + [AM_CFLAGS="$AM_CFLAGS -DNO_BIG_INT"]) + AS_IF([test "x$ENABLED_CERTS" = "xno"], [AM_CFLAGS="$AM_CFLAGS -DNO_CERTS"]) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 7e9e5907b69..41569603d8b 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2037,10 +2037,8 @@ extern void uITRON4_free(void *p) ; * Constant time: Not supported * Enable: USE_INTEGER_HEAP_MATH */ - #elif defined(WOLFSSL_NO_MATH) - /* 5) No math library compiled in - * Does not support any public key operations or algorithms that - * require the math library. + #elif defined(NO_BIG_INT) + /* 5) No big integer math libraries */ #else /* default is SP Math. */ From 09d0aea09a8cc074d445deb85027631597bb70dc Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Thu, 13 Apr 2023 16:12:08 -0700 Subject: [PATCH 144/391] fix guard on ECC export --- tests/api.c | 1 + wolfssl/wolfcrypt/settings.h | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/api.c b/tests/api.c index 3d948e823cc..1e31ed6413b 100644 --- a/tests/api.c +++ b/tests/api.c @@ -53065,6 +53065,7 @@ static int test_tls13_apis(void) wolfSSL_CTX_use_PrivateKey_file(serverCtx, ourKey, WOLFSSL_FILETYPE_PEM); #endif serverSsl = wolfSSL_new(serverCtx); + AssertNotNull(serverSsl); #endif #ifdef WOLFSSL_SEND_HRR_COOKIE diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 41569603d8b..2294f79502b 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2143,8 +2143,9 @@ extern void uITRON4_free(void *p) ; #undef HAVE_ECC_KEY_IMPORT #define HAVE_ECC_KEY_IMPORT #endif - /* The ECC key export requires mp_int */ - #if !defined(NO_ECC_KEY_EXPORT) && !defined(NO_BIG_INT) + /* The ECC key export requires mp_int or SP */ + #if (!defined(NO_ECC_KEY_EXPORT) && defined(WOLFSSL_SP_MATH)) || \ + (!defined(NO_ECC_KEY_EXPORT) && !defined(NO_BIG_INT)) #undef HAVE_ECC_KEY_EXPORT #define HAVE_ECC_KEY_EXPORT #endif From 4985d47f7be139fc9ddec984e7a2ef9b4b1475fc Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Fri, 14 Apr 2023 14:52:05 -0600 Subject: [PATCH 145/391] fix configure, compatibility layer needed big int. for BN use --- configure.ac | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/configure.ac b/configure.ac index 3d0e34b2dab..3e260a90e7a 100644 --- a/configure.ac +++ b/configure.ac @@ -3960,11 +3960,6 @@ if test "$ENABLED_ASN" = "no" then AM_CFLAGS="$AM_CFLAGS -DNO_ASN -DNO_ASN_CRYPT" enable_pwdbased=no - if test "$ENABLED_DH" = "no" && test "$ENABLED_ECC" = "no" - then - # DH and ECC need bigint - AM_CFLAGS="$AM_CFLAGS -DNO_BIG_INT" - fi else if test "$ENABLED_ASN" = "template"; then ENABLED_ASN="yes" @@ -4007,10 +4002,11 @@ then AC_MSG_ERROR([please disable ecc if disabling asn.]) fi -# No Big Int (ASN, DSA, RSA, DH and ECC need bigint) +# No Big Int (ASN, DSA, RSA, DH, ECC and compatibility layer need bigint) if test "$ENABLED_ASN" = "no" && test "$ENABLED_DSA" = "no" && \ test "$ENABLED_DH" = "no" && test "$ENABLED_ECC" = "no" && \ - test "$ENABLED_RSA" = "no" + test "$ENABLED_RSA" = "no" && test "$ENABLED_OPENSSLEXTRA" = "no" && \ + test "$ENABLED_OPENSSLALL" ="yes" then ENABLED_SP_MATH_ALL="no" ENABLED_FASTMATH="no" From d94d8f106b3089f67c1520b7ebac210a484b3ecd Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Mon, 17 Apr 2023 18:43:05 +0200 Subject: [PATCH 146/391] hostap/hwsim: use a custom commit to update the expired certs - use 'theirs' merge strategy --- .github/workflows/hostap.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/hostap.yml b/.github/workflows/hostap.yml index 10bc77ccd79..0fa9b5851e5 100644 --- a/.github/workflows/hostap.yml +++ b/.github/workflows/hostap.yml @@ -60,7 +60,7 @@ jobs: config: [ { hostap_ref: hostap_2_10, - hostap_cherry_pick: 698c05da2bd3233b005d45873caa852bc29b32c5, + hostap_cherry_pick: 5679ec5c3dda25a0547a5f66407fd9b0b55fd04a, remove_teap: true, # TLS 1.3 does not work for this version build_id: hostap-build1, @@ -68,6 +68,7 @@ jobs: # Test the dpp patch { hostap_ref: b607d2723e927a3446d89aed813f1aa6068186bb, + hostap_cherry_pick: 5679ec5c3dda25a0547a5f66407fd9b0b55fd04a, osp_ref: ad5b52a49b3cc2a5bfb47ccc1d6a5137132e9446, build_id: hostap-build2 }, @@ -167,7 +168,7 @@ jobs: - if: ${{ matrix.config.hostap_cherry_pick }} name: Cherry pick certificate update working-directory: hostap - run: git cherry-pick -n ${{ matrix.config.hostap_cherry_pick }} + run: git cherry-pick -n -X theirs ${{ matrix.config.hostap_cherry_pick }} - if: ${{ matrix.config.osp_ref }} name: Checkout OSP From d8c62ef7b3ddff91d6a4d558af9ecf28d12ad3a5 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Wed, 8 Mar 2023 13:40:29 -0500 Subject: [PATCH 147/391] Support in the compatibility layer for UPN and SID. --- src/internal.c | 14 +- src/x509.c | 300 ++++++++++++++++++++++++++++++--- tests/api.c | 143 +++++++++++++++- wolfcrypt/src/asn.c | 45 ++++- wolfssl/internal.h | 4 + wolfssl/openssl/asn1.h | 2 + wolfssl/openssl/ssl.h | 31 ++-- wolfssl/openssl/x509v3.h | 1 + wolfssl/ssl.h | 11 ++ wolfssl/wolfcrypt/asn.h | 3 + wolfssl/wolfcrypt/asn_public.h | 22 ++- 11 files changed, 530 insertions(+), 46 deletions(-) diff --git a/src/internal.c b/src/internal.c index d4b083219d9..465496ba6ec 100644 --- a/src/internal.c +++ b/src/internal.c @@ -4238,6 +4238,10 @@ void InitX509(WOLFSSL_X509* x509, int dynamicFlag, void* heap) /* Free wolfSSL X509 type */ void FreeX509(WOLFSSL_X509* x509) { + #if defined(WOLFSSL_CERT_REQ) && defined(OPENSSL_ALL) \ + && defined( WOLFSSL_CUSTOM_OID) + int idx; + #endif /* WOLFSSL_CERT_REQ && OPENSSL_ALL && WOLFSSL_CUSTOM_OID */ if (x509 == NULL) return; @@ -4318,7 +4322,15 @@ void FreeX509(WOLFSSL_X509* x509) if (x509->reqAttributes) { wolfSSL_sk_pop_free(x509->reqAttributes, NULL); } - #endif /* WOLFSSL_CERT_REQ */ + #ifdef WOLFSSL_CUSTOM_OID + for (idx = 0; idx < x509->customExtCount; idx++) { + XFREE(x509->custom_exts[idx].oid, x509->heap, + DYNAMIC_TYPE_X509_EXT); + XFREE(x509->custom_exts[idx].val, x509->heap, + DYNAMIC_TYPE_X509_EXT); + } + #endif /* WOLFSSL_CUSTOM_OID */ + #endif /* WOLFSSL_CERT_REQ && OPENSSL_ALL */ if (x509->altNames) { FreeAltNames(x509->altNames, x509->heap); x509->altNames = NULL; diff --git a/src/x509.c b/src/x509.c index b0b2366a8e5..c8fcebfb2ff 100644 --- a/src/x509.c +++ b/src/x509.c @@ -282,6 +282,55 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_dup(WOLFSSL_X509_EXTENSION* src) return ret; } +WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_create_by_OBJ( + WOLFSSL_X509_EXTENSION* ex, WOLFSSL_ASN1_OBJECT *obj, int crit, + WOLFSSL_ASN1_STRING *data) +{ + int err = 0; + WOLFSSL_X509_EXTENSION *ret = ex; + + WOLFSSL_ENTER("wolfSSL_X509_EXTENSION_create_by_OBJ"); + + if ((obj == NULL) || (data == NULL)) { + return NULL; + } + + if (ret == NULL) { + ret = wolfSSL_X509_EXTENSION_new(); + if (ret == NULL) { + err = 1; + } + } else { + /* Prevent potential memory leaks and dangling pointers. */ + wolfSSL_ASN1_OBJECT_free(ret->obj); + ret->obj = NULL; + wolfSSL_ASN1_STRING_free(&ret->value); + } + + ret->crit = crit; + + if (err == 0) { + ret->obj = wolfSSL_ASN1_OBJECT_dup(obj); + if (ret->obj == NULL) { + err = 1; + } + } + + if (err == 0) { + if (wolfSSL_ASN1_STRING_copy(&ret->value, data) != WOLFSSL_SUCCESS) { + err = 1; + } + } + + if (err == 1) { + if (ret != ex) { + wolfSSL_X509_EXTENSION_free(ret); + } + ret = NULL; + } + return ret; +} + /* Creates and returns a new WOLFSSL_X509_EXTENSION stack. */ WOLFSSL_STACK* wolfSSL_sk_new_x509_ext(void) { @@ -295,7 +344,9 @@ WOLFSSL_STACK* wolfSSL_sk_new_x509_ext(void) return sk; } -/* return 1 on success 0 on fail */ +/* This function does NOT return 1 on success. It returns 0 on fail, and the + * number of items in the stack upon success. This is for compatibility with + * OpenSSL. */ int wolfSSL_sk_X509_EXTENSION_push(WOLFSSL_STACK* sk,WOLFSSL_X509_EXTENSION* ext) { WOLFSSL_STACK* node; @@ -310,7 +361,7 @@ int wolfSSL_sk_X509_EXTENSION_push(WOLFSSL_STACK* sk,WOLFSSL_X509_EXTENSION* ext if (sk->data.ext == NULL) { sk->data.ext = ext; sk->num += 1; - return WOLFSSL_SUCCESS; + return (int)sk->num; } /* stack already has value(s) create a new node and add more */ @@ -330,7 +381,7 @@ int wolfSSL_sk_X509_EXTENSION_push(WOLFSSL_STACK* sk,WOLFSSL_X509_EXTENSION* ext sk->data.ext = ext; sk->num += 1; - return WOLFSSL_SUCCESS; + return (int)sk->num; } /* Free the structure for X509_EXTENSION stack @@ -1133,7 +1184,34 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo WOLFSSL_GENERAL_NAMES* gns = ext->ext_sk; while (gns) { WOLFSSL_GENERAL_NAME* gn = gns->data.gn; - if (!gn || !gn->d.ia5 || + if ((gn != NULL) && (gn->type == ASN_OTHER_TYPE)) { + char *buf = NULL; + int ret = 0; + word32 len = 0; + + len = SetOthername(gn->d.otherName, NULL); + if (len == WOLFSSL_FAILURE) { + return WOLFSSL_FAILURE; + } + + buf = (char*)XMALLOC(len, x509->heap, DYNAMIC_TYPE_X509_EXT); + if (buf == NULL) { + WOLFSSL_MSG("Couldn't allocate memory for othername"); + return WOLFSSL_FAILURE; + } + + /* SetOthername() cannot fail; already passed above. */ + SetOthername(gn->d.otherName, (byte*)buf); + + ret = wolfSSL_X509_add_altname_ex(x509, buf, len, + ASN_OTHER_TYPE); + XFREE(buf, x509->heap, DYNAMIC_TYPE_X509_EXT); + if (ret == WOLFSSL_FAILURE) { + WOLFSSL_MSG("wolfSSL_X509_add_altname_ex() failed"); + return WOLFSSL_FAILURE; + } + } + else if (!gn || !gn->d.ia5 || wolfSSL_X509_add_altname_ex(x509, gn->d.ia5->data, gn->d.ia5->length, gn->type) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Subject alternative name missing extension"); @@ -1163,8 +1241,54 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo } break; default: +#ifdef WOLFSSL_CUSTOM_OID + if ((ext->obj == NULL) || (ext->value.length == 0)) { + WOLFSSL_MSG("Extension has insufficient information."); + return WOLFSSL_FAILURE; + } + + if ((x509->customExtCount < 0) || + (x509->customExtCount >= NUM_CUSTOM_EXT)) { + WOLFSSL_MSG("Bad value for customExtCount."); + return WOLFSSL_FAILURE; + } + + /* This is a viable custom extension. */ + char *oid = XMALLOC(MAX_OID_STRING_SZ, x509->heap, + DYNAMIC_TYPE_X509_EXT); + byte *val = XMALLOC(ext->value.length, x509->heap, + DYNAMIC_TYPE_X509_EXT); + int err = 0; + + if ((oid == NULL) || (val == NULL)) { + WOLFSSL_MSG("Memory allocation failure.\n"); + err = 1; + } + + if (err == 0) { + XMEMCPY(val, ext->value.data, ext->value.length); + if (wolfSSL_OBJ_obj2txt(oid, MAX_OID_STRING_SZ, ext->obj, 1) < 0) { + err = 1; + } + } + + if (err == 1) { + XFREE(val, x509->heap, DYNAMIC_TYPE_X509_EXT); + XFREE(oid, x509->heap, DYNAMIC_TYPE_X509_EXT); + return WOLFSSL_FAILURE; + } + + /* x509->custom_exts now owns the buffers and they must be managed. */ + x509->custom_exts[x509->customExtCount].oid = oid; + x509->custom_exts[x509->customExtCount].crit = ext->crit; + x509->custom_exts[x509->customExtCount].val = val; + x509->custom_exts[x509->customExtCount].valSz = ext->value.length; + x509->customExtCount++; +#else WOLFSSL_MSG("Unsupported extension to add"); return WOLFSSL_FAILURE; +#endif /* WOLFSSL_CUSTOM_OID */ + break; } return WOLFSSL_SUCCESS; @@ -2697,6 +2821,12 @@ WOLFSSL_X509_EXTENSION *wolfSSL_X509V3_EXT_i2d(int nid, int crit, WOLFSSL_MSG("wolfSSL_sk_dup failed"); goto err_cleanup; } + + if (!(ext->obj = wolfSSL_OBJ_nid2obj(nid))) { + WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_new failed"); + goto err_cleanup; + } + break; } case NID_basic_constraints: @@ -3343,6 +3473,7 @@ WOLFSSL_X509* wolfSSL_X509_REQ_d2i(WOLFSSL_X509** x509, return d2i_X509orX509REQ(x509, in, len, 1); } #endif + #endif /* KEEP_PEER_CERT || SESSION_CERTS || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ @@ -4005,6 +4136,7 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_new(void) wolfSSL_GENERAL_NAME_free(gn); return NULL; } + gn->type = GEN_IA5; return gn; } @@ -4024,6 +4156,8 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_dup(WOLFSSL_GENERAL_NAME* gn) return NULL; } + wolfSSL_ASN1_STRING_free(dupl->d.ia5); + dupl->d.ia5 = NULL; switch (gn->type) { /* WOLFSSL_ASN1_STRING types */ case GEN_DNS: @@ -4052,6 +4186,37 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_dup(WOLFSSL_GENERAL_NAME* gn) } break; case GEN_OTHERNAME: + if (gn->d.otherName->value->type != V_ASN1_UTF8STRING) { + WOLFSSL_MSG("Unsupported othername value type"); + goto error; + } + dupl->d.otherName = (WOLFSSL_ASN1_OTHERNAME*)XMALLOC( + sizeof(WOLFSSL_ASN1_OTHERNAME), NULL, DYNAMIC_TYPE_ASN1); + if (dupl->d.otherName == NULL) { + WOLFSSL_MSG("XMALLOC error"); + goto error; + } + dupl->d.otherName->type_id = wolfSSL_ASN1_OBJECT_dup( + gn->d.otherName->type_id); + dupl->d.otherName->value = (WOLFSSL_ASN1_TYPE*)XMALLOC( + sizeof(WOLFSSL_ASN1_TYPE), NULL, DYNAMIC_TYPE_ASN1); + if (dupl->d.otherName->value != NULL) { + dupl->d.otherName->value->type = gn->d.otherName->value->type; + dupl->d.otherName->value->value.utf8string = + wolfSSL_ASN1_STRING_dup( + gn->d.otherName->value->value.utf8string); + } + if ((dupl->d.otherName->type_id == NULL) || + (dupl->d.otherName->value == NULL) || + (dupl->d.otherName->value->value.utf8string == NULL)) { + wolfSSL_ASN1_OBJECT_free(dupl->d.otherName->type_id); + wolfSSL_ASN1_TYPE_free(dupl->d.otherName->value); + XFREE(dupl->d.otherName, NULL, DYNAMIC_TYPE_ASN1); + dupl->d.otherName = NULL; + WOLFSSL_MSG("error duping othername"); + goto error; + } + break; case GEN_X400: case GEN_DIRNAME: case GEN_EDIPARTY: @@ -4070,6 +4235,33 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_dup(WOLFSSL_GENERAL_NAME* gn) return NULL; } +/* Set an Othername in a general name. + * + * @param [out] gen Pointer to the GENERAL_NAME where the othername is set. + * @param [in] oid Object ID (ie UPN). + * @param [in] name The actual name. + * @return WOLFSSL_FAILURE on invalid parameter or memory error, + * WOLFSSL_SUCCESS otherwise. + */ +int wolfSSL_GENERAL_NAME_set0_othername(GENERAL_NAME* gen, ASN1_OBJECT* oid, + ASN1_TYPE* value) { + WOLFSSL_ASN1_OBJECT *x = NULL; + + if ((gen == NULL) || (oid == NULL) || (value == NULL)) { + return WOLFSSL_FAILURE; + } + + x = wolfSSL_ASN1_OBJECT_dup(oid); + if (x == NULL) { + WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_dup() failed"); + return WOLFSSL_FAILURE; + } + + gen->type = GEN_OTHERNAME; + gen->d.otherName->type_id = x; + gen->d.otherName->value = value; + return WOLFSSL_SUCCESS; +} /* return 1 on success 0 on fail */ int wolfSSL_sk_GENERAL_NAME_push(WOLFSSL_GENERAL_NAMES* sk, @@ -4153,6 +4345,19 @@ int wolfSSL_sk_GENERAL_NAME_num(WOLFSSL_STACK* sk) return (int)sk->num; } +/* Allocates an empty GENERAL NAME stack */ +WOLFSSL_STACK* wolfSSL_sk_GENERAL_NAME_new(void *cmpFunc) { + WOLFSSL_STACK* sk = NULL; + (void)cmpFunc; + WOLFSSL_ENTER("wolfSSL_sk_GENERAL_NAME_new"); + + sk = wolfSSL_sk_new_null(); + if (sk != NULL) { + sk->type = STACK_TYPE_GEN_NAME; + } + + return sk; +} #endif /* OPENSSL_EXTRA */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) @@ -4363,34 +4568,52 @@ WOLFSSL_ACCESS_DESCRIPTION* wolfSSL_sk_ACCESS_DESCRIPTION_value( static void wolfSSL_GENERAL_NAME_type_free(WOLFSSL_GENERAL_NAME* name) { if (name != NULL) { - if (name->d.dNSName != NULL) { + switch (name->type) { + case GEN_IA5: + wolfSSL_ASN1_STRING_free(name->d.ia5); + name->d.ia5 = NULL; + break; + case GEN_EMAIL: + wolfSSL_ASN1_STRING_free(name->d.rfc822Name); + name->d.rfc822Name = NULL; + break; + case GEN_DNS: wolfSSL_ASN1_STRING_free(name->d.dNSName); name->d.dNSName = NULL; - } - if (name->d.dirn != NULL) { + break; + case GEN_DIRNAME: wolfSSL_X509_NAME_free(name->d.dirn); name->d.dirn = NULL; - } - if (name->d.uniformResourceIdentifier != NULL) { + break; + case GEN_URI: wolfSSL_ASN1_STRING_free(name->d.uniformResourceIdentifier); name->d.uniformResourceIdentifier = NULL; - } - if (name->d.iPAddress != NULL) { + break; + case GEN_IPADD: wolfSSL_ASN1_STRING_free(name->d.iPAddress); name->d.iPAddress = NULL; - } - if (name->d.registeredID != NULL) { + break; + case GEN_RID: wolfSSL_ASN1_OBJECT_free(name->d.registeredID); name->d.registeredID = NULL; - } - if (name->d.ia5 != NULL) { - wolfSSL_ASN1_STRING_free(name->d.ia5); - name->d.ia5 = NULL; + break; + case GEN_OTHERNAME: + wolfSSL_ASN1_OBJECT_free(name->d.otherName->type_id); + wolfSSL_ASN1_TYPE_free(name->d.otherName->value); + XFREE(name->d.otherName, NULL, DYNAMIC_TYPE_ASN1); + name->d.otherName = NULL; + break; + case GEN_X400: + /* Unsupported: fall through */ + case GEN_EDIPARTY: + /* Unsupported: fall through */ + default: + WOLFSSL_MSG("wolfSSL_GENERAL_NAME_type_free: possible leak"); + break; } } } - /* sets the general name type and free's the existing one * can fail with a memory error if malloc fails or bad arg error * otherwise return WOLFSSL_SUCCESS */ @@ -4409,6 +4632,7 @@ int wolfSSL_GENERAL_NAME_set_type(WOLFSSL_GENERAL_NAME* name, int typ) ret = MEMORY_E; break; default: + name->type = GEN_IA5; name->d.ia5 = wolfSSL_ASN1_STRING_new(); if (name->d.ia5 == NULL) ret = MEMORY_E; @@ -7211,6 +7435,11 @@ static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type) newx509 = (void *)wolfSSL_d2i_X509_CRL(NULL, fileBuffer, (int)sz); } #endif + #ifdef WOLFSSL_CERT_REQ + else if (type == CERTREQ_TYPE) { + newx509 = (void *)wolfSSL_X509_REQ_d2i(NULL, fileBuffer, (int)sz); + } + #endif #if !defined(NO_ASN) && !defined(NO_PWDBASED) && defined(HAVE_PKCS12) else if (type == PKCS12_TYPE) { if ((newx509 = wc_PKCS12_new()) == NULL) { @@ -7249,11 +7478,20 @@ static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type) return newx509; } +#ifdef WOLFSSL_CERT_REQ +WOLFSSL_X509* wolfSSL_d2i_X509_REQ_fp(XFILE fp, WOLFSSL_X509 **req) +{ + return (WOLFSSL_X509 *)wolfSSL_d2i_X509_fp_ex(fp, (void **)req, + CERTREQ_TYPE); +} +#endif /* WOLFSSL_CERT_REQ */ + WOLFSSL_X509 *wolfSSL_d2i_X509_fp(XFILE fp, WOLFSSL_X509 **x509) { WOLFSSL_ENTER("wolfSSL_d2i_X509_fp"); return (WOLFSSL_X509 *)wolfSSL_d2i_X509_fp_ex(fp, (void **)x509, CERT_TYPE); } + /* load certificate or CRL file, and add it to the STORE */ /* @param ctx a pointer to X509_LOOKUP structure */ /* @param file file name to load */ @@ -9228,11 +9466,33 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( } } } + + #ifdef WOLFSSL_CUSTOM_OID + if (ret == WOLFSSL_SUCCESS) { + if ((req->customExtCount < 0) || + (req->customExtCount >= NUM_CUSTOM_EXT)) { + WOLFSSL_MSG("Bad value for customExtCount."); + ret = WOLFSSL_FAILURE; + } + + if (ret == WOLFSSL_SUCCESS) { + for (idx = 0; idx < req->customExtCount; idx++) { + /* Note that ownership is NOT transfered. + * req->custom_exts buffers still need to be cleaned + * up. */ + cert->customCertExt[idx] = req->custom_exts[idx]; + } + cert->customCertExtCount = req->customExtCount; + } + } + #endif /* WOLFSSL_CUSTOM_OID */ #endif /* OPENSSL_ALL */ #ifdef WOLFSSL_ALT_NAMES - cert->altNamesSz = FlattenAltNames(cert->altNames, - sizeof(cert->altNames), req->altNames); + if (ret == WOLFSSL_SUCCESS) { + cert->altNamesSz = FlattenAltNames(cert->altNames, + sizeof(cert->altNames), req->altNames); + } #endif /* WOLFSSL_ALT_NAMES */ } diff --git a/tests/api.c b/tests/api.c index 1e31ed6413b..6aafc64d755 100644 --- a/tests/api.c +++ b/tests/api.c @@ -43264,6 +43264,142 @@ static int test_wolfSSL_X509_NAME_ENTRY(void) return res; } +/* Note the lack of wolfSSL_ prefix...this is a compatability layer test. */ +static int test_GENERAL_NAME_set0_othername(void) { + int res = TEST_SKIPPED; +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ + defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) && \ + defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ALT_NAMES) && \ + defined(WOLFSSL_CERT_EXT) && !defined(NO_FILESYSTEM) + const char * cert_fname = "./certs/server-cert.der"; + const char * key_fname = "./certs/server-key.der"; + X509* x509 = NULL; + GENERAL_NAME* gn = NULL; + GENERAL_NAMES* gns = NULL; + ASN1_OBJECT* upn_oid = NULL; + ASN1_UTF8STRING *utf8str = NULL; + ASN1_TYPE *value = NULL; + X509_EXTENSION * ext = NULL; + + byte* pt = NULL; + byte der[4096]; + int derSz = 0; + EVP_PKEY* priv = NULL; + FILE* f = NULL; + + AssertNotNull(f = fopen(cert_fname, "rb")); + AssertNotNull(x509 = d2i_X509_fp(f, NULL)); + fclose(f); + AssertNotNull(gn = GENERAL_NAME_new()); + AssertNotNull(upn_oid = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1)); + AssertNotNull(utf8str = ASN1_UTF8STRING_new()); + AssertIntEQ(ASN1_STRING_set(utf8str, "othername@wolfssl.com", -1), 1); + AssertNotNull(value = ASN1_TYPE_new()); + ASN1_TYPE_set(value, V_ASN1_UTF8STRING, utf8str); + AssertIntEQ(GENERAL_NAME_set0_othername(gn, upn_oid, value), 1); + AssertNotNull(gns = sk_GENERAL_NAME_new(NULL)); + AssertIntEQ(sk_GENERAL_NAME_push(gns, gn), 1); + AssertNotNull(ext = X509V3_EXT_i2d(NID_subject_alt_name, 0, gns)); + AssertIntEQ(X509_add_ext(x509, ext, -1), 1); + AssertNotNull(f = fopen(key_fname, "rb")); + AssertIntGT(derSz = (int)fread(der, 1, sizeof(der), f), 0); + fclose(f); + pt = der; + AssertNotNull(priv = d2i_PrivateKey(EVP_PKEY_RSA, NULL, + (const unsigned char**)&pt, derSz)); + AssertIntGT(X509_sign(x509, priv, EVP_sha256()), 0); + sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); + ASN1_OBJECT_free(upn_oid); + X509_EXTENSION_free(ext); + X509_free(x509); + EVP_PKEY_free(priv); + res = TEST_RES_CHECK(1); +#endif + return res; +} + +/* Note the lack of wolfSSL_ prefix...this is a compatability layer test. */ +static int test_othername_and_SID_ext(void) { + int res = TEST_SKIPPED; +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ + defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) && \ + defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ALT_NAMES) && \ + defined(WOLFSSL_CERT_EXT) && !defined(NO_FILESYSTEM) + + const char* csr_fname = "./certs/csr.signed.der"; + const char* key_fname = "./certs/server-key.der"; + + byte der[4096]; + int derSz = 0; + X509_REQ* x509 = NULL; + STACK_OF(X509_EXTENSION) *exts = NULL; + + X509_EXTENSION * san_ext = NULL; + GENERAL_NAME* gn = NULL; + GENERAL_NAMES* gns = NULL; + ASN1_OBJECT* upn_oid = NULL; + ASN1_UTF8STRING *utf8str = NULL; + ASN1_TYPE *value = NULL; + + /* SID extension. SID data format explained here: + * https://blog.qdsecurity.se/2022/05/27/manually-injecting-a-sid-in-a-certificate/ + */ + uint8_t SidExtension[] = { + 48, 64, 160, 62, 6, 10, 43, 6, 1, 4, 1, 130, 55, 25, 2, 1, 160, + 48, 4, 46, 83, 45, 49, 45, 53, 45, 50, 49, 45, 50, 56, 52, 51, 57, + 48, 55, 52, 49, 56, 45, 51, 57, 50, 54, 50, 55, 55, 52, 50, 49, 45, + 51, 56, 49, 53, 57, 57, 51, 57, 55, 50, 45, 52, 54, 48, 49}; + X509_EXTENSION *sid_ext = NULL; + ASN1_OBJECT* sid_oid = NULL; + ASN1_OCTET_STRING *sid_data = NULL; + + EVP_PKEY* priv = NULL; + FILE* f = NULL; + byte* pt = NULL; + + AssertNotNull(f = fopen(csr_fname, "rb")); + AssertNotNull(x509 = d2i_X509_REQ_fp(f, NULL)); + fclose(f); + AssertIntEQ(X509_REQ_set_version(x509, 2), 1); + AssertNotNull(gn = GENERAL_NAME_new()); + AssertNotNull(upn_oid = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1)); + AssertNotNull(utf8str = ASN1_UTF8STRING_new()); + AssertIntEQ(ASN1_STRING_set(utf8str, "othername@wolfssl.com", -1), 1); + AssertNotNull(value = ASN1_TYPE_new()); + ASN1_TYPE_set(value, V_ASN1_UTF8STRING, utf8str); + AssertIntEQ(GENERAL_NAME_set0_othername(gn, upn_oid, value), 1); + AssertNotNull(gns = sk_GENERAL_NAME_new(NULL)); + AssertIntEQ(sk_GENERAL_NAME_push(gns, gn), 1); + AssertNotNull(san_ext = X509V3_EXT_i2d(NID_subject_alt_name, 0, gns)); + AssertNotNull(sid_oid = OBJ_txt2obj("1.3.6.1.4.1.311.25.2", 1)); + AssertNotNull(sid_data = ASN1_OCTET_STRING_new()); + ASN1_OCTET_STRING_set(sid_data, SidExtension, sizeof(SidExtension)); + AssertNotNull(sid_ext = X509_EXTENSION_create_by_OBJ(NULL, sid_oid, 0, + sid_data)); + AssertNotNull(exts = sk_X509_EXTENSION_new_null()); + AssertIntEQ(sk_X509_EXTENSION_push(exts, san_ext), 1); + AssertIntEQ(sk_X509_EXTENSION_push(exts, sid_ext), 2); + AssertIntEQ(X509_REQ_add_extensions(x509, exts), 1); + AssertNotNull(f = fopen(key_fname, "rb")); + AssertIntGT(derSz = (int)fread(der, 1, sizeof(der), f), 0); + fclose(f); + pt = der; + AssertNotNull(priv = d2i_PrivateKey(EVP_PKEY_RSA, NULL, + (const unsigned char**)&pt, derSz)); + AssertIntGT(X509_REQ_sign(x509, priv, EVP_sha256()), 0); + pt = der; + AssertIntGT(derSz = i2d_X509_REQ(x509, &pt), 0); + sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); + sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); + ASN1_OBJECT_free(upn_oid); + ASN1_OBJECT_free(sid_oid); + ASN1_OCTET_STRING_free(sid_data); + X509_REQ_free(x509); + EVP_PKEY_free(priv); + res = TEST_RES_CHECK(1); +#endif + return res; +} static int test_wolfSSL_X509_set_name(void) { @@ -45135,7 +45271,6 @@ static int test_wolfSSL_GENERAL_NAME_print(void) const char* x400Str = "X400Name:"; const char* ediStr = "EdiPartyName:"; - /* BIO to output */ AssertNotNull(out = BIO_new(BIO_s_mem())); @@ -45261,6 +45396,8 @@ static int test_wolfSSL_GENERAL_NAME_print(void) AssertIntGT(BIO_read(out, outbuf, sizeof(outbuf)), 0); AssertIntEQ(XSTRNCMP((const char*)outbuf, x400Str, XSTRLEN(x400Str)), 0); + /* Restore to GEN_IA5 (default) to avoid memory leak. */ + gn->type = GEN_IA5; GENERAL_NAME_free(gn); /* test for GEN_EDIPARTY */ @@ -45273,6 +45410,8 @@ static int test_wolfSSL_GENERAL_NAME_print(void) AssertIntGT(BIO_read(out, outbuf, sizeof(outbuf)), 0); AssertIntEQ(XSTRNCMP((const char*)outbuf, ediStr, XSTRLEN(ediStr)), 0); + /* Restore to GEN_IA5 (default) to avoid memory leak. */ + gn->type = GEN_IA5; GENERAL_NAME_free(gn); BIO_free(out); @@ -65153,6 +65292,8 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_OBJ_txt2obj), TEST_DECL(test_wolfSSL_PEM_write_bio_X509), TEST_DECL(test_wolfSSL_X509_NAME_ENTRY), + TEST_DECL(test_GENERAL_NAME_set0_othername), + TEST_DECL(test_othername_and_SID_ext), TEST_DECL(test_wolfSSL_X509_set_name), TEST_DECL(test_wolfSSL_X509_set_notAfter), TEST_DECL(test_wolfSSL_X509_set_notBefore), diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 28745f4076f..440976c0bdd 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -14574,6 +14574,49 @@ word32 SetExplicit(byte number, word32 len, byte* output) output); } +#if defined(OPENSSL_EXTRA) +/* Encode an Othername into DER. + * + * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded. + * @param [out] output Buffer to encode into. If NULL, don't encode. + * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad. + */ +word32 SetOthername(void *name, byte *output) +{ + WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name; + char *nameStr = NULL; + int nameSz = 0; + word32 len = 0; + + if ((nm == NULL) || (nm->value == NULL)) { + WOLFSSL_MSG("otherName value is NULL"); + return WOLFSSL_FAILURE; + } + + nameStr = nm->value->value.utf8string->data; + nameSz = nm->value->value.utf8string->length; + + len = nm->type_id->objSz + + SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) + + SetHeader(CTC_UTF8, nameSz, NULL) + nameSz; + + if (output != NULL) { + /* otherName OID */ + XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz); + output += nm->type_id->objSz; + + output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, + output); + + output += SetHeader(CTC_UTF8, nameSz, output); + + XMEMCPY(output, nameStr, nameSz); + output += nameSz; + } + + return len; +} +#endif /* OPENSSL_EXTRA */ #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) @@ -25949,7 +25992,7 @@ int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names) i = idx; #endif output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type); - if (curName->type == ASN_DIR_TYPE) { + if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) { output[idx] |= ASN_CONSTRUCTED; } idx++; diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 4be5b5774ed..930a6a8b188 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -4861,6 +4861,10 @@ struct WOLFSSL_X509 { byte authKeyIdSet:1; byte authKeyIdCrit:1; byte issuerSet:1; +#ifdef WOLFSSL_CUSTOM_OID + CertExtension custom_exts[NUM_CUSTOM_EXT]; + int customExtCount; +#endif /* WOLFSSL_CUSTOM_OID */ #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef WOLFSSL_CERT_REQ byte isCSR:1; diff --git a/wolfssl/openssl/asn1.h b/wolfssl/openssl/asn1.h index 66fd41f3546..edfa662919e 100644 --- a/wolfssl/openssl/asn1.h +++ b/wolfssl/openssl/asn1.h @@ -185,5 +185,7 @@ WOLFSSL_API int wolfSSL_ASN1_item_i2d(const void *src, byte **dest, #define BN_to_ASN1_INTEGER wolfSSL_BN_to_ASN1_INTEGER #define ASN1_TYPE_set wolfSSL_ASN1_TYPE_set +#define ASN1_TYPE_new wolfSSL_ASN1_TYPE_new +#define ASN1_TYPE_free wolfSSL_ASN1_TYPE_free #endif /* WOLFSSL_ASN1_H_ */ diff --git a/wolfssl/openssl/ssl.h b/wolfssl/openssl/ssl.h index cc31f21d00b..81575908106 100644 --- a/wolfssl/openssl/ssl.h +++ b/wolfssl/openssl/ssl.h @@ -110,7 +110,7 @@ typedef WOLFSSL_ASN1_BIT_STRING ASN1_BIT_STRING; typedef WOLFSSL_dynlock_value CRYPTO_dynlock_value; typedef WOLFSSL_BUF_MEM BUF_MEM; typedef WOLFSSL_GENERAL_NAMES GENERAL_NAMES; -typedef WOLFSSL_GENERAL_NAME GENERAL_NAME; +typedef WOLFSSL_GENERAL_NAME GENERAL_NAME; typedef WOLFSSL_OBJ_NAME OBJ_NAME; typedef WOLFSSL_DIST_POINT_NAME DIST_POINT_NAME; typedef WOLFSSL_DIST_POINT DIST_POINT; @@ -392,16 +392,17 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSL_SESSION_get_max_early_data wolfSSL_SESSION_get_max_early_data #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) - #define SSL_MODE_RELEASE_BUFFERS 0x00000010U - #define ASN1_BOOLEAN WOLFSSL_ASN1_BOOLEAN - #define X509_get_ext wolfSSL_X509_get_ext - #define X509_get_ext_by_OBJ wolfSSL_X509_get_ext_by_OBJ - #define X509_cmp wolfSSL_X509_cmp - #define X509_EXTENSION_get_object wolfSSL_X509_EXTENSION_get_object - #define X509_EXTENSION_get_critical wolfSSL_X509_EXTENSION_get_critical - #define X509_EXTENSION_get_data wolfSSL_X509_EXTENSION_get_data - #define X509_EXTENSION_new wolfSSL_X509_EXTENSION_new - #define X509_EXTENSION_free wolfSSL_X509_EXTENSION_free + #define SSL_MODE_RELEASE_BUFFERS 0x00000010U + #define ASN1_BOOLEAN WOLFSSL_ASN1_BOOLEAN + #define X509_get_ext wolfSSL_X509_get_ext + #define X509_get_ext_by_OBJ wolfSSL_X509_get_ext_by_OBJ + #define X509_cmp wolfSSL_X509_cmp + #define X509_EXTENSION_get_object wolfSSL_X509_EXTENSION_get_object + #define X509_EXTENSION_get_critical wolfSSL_X509_EXTENSION_get_critical + #define X509_EXTENSION_get_data wolfSSL_X509_EXTENSION_get_data + #define X509_EXTENSION_new wolfSSL_X509_EXTENSION_new + #define X509_EXTENSION_free wolfSSL_X509_EXTENSION_free + #define X509_EXTENSION_create_by_OBJ wolfSSL_X509_EXTENSION_create_by_OBJ #endif #define DSA_dup_DH wolfSSL_DSA_dup_DH @@ -415,6 +416,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define i2d_X509_REQ_bio wolfSSL_i2d_X509_REQ_bio #define d2i_X509_bio wolfSSL_d2i_X509_bio #define d2i_X509_REQ_bio wolfSSL_d2i_X509_REQ_bio +#define d2i_X509_REQ_fp wolfSSL_d2i_X509_REQ_fp #define d2i_X509_fp wolfSSL_d2i_X509_fp #define i2d_X509 wolfSSL_i2d_X509 #define d2i_X509 wolfSSL_d2i_X509 @@ -878,6 +880,11 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define ASN1_OCTET_STRING_free wolfSSL_ASN1_STRING_free #define ASN1_OCTET_STRING_set wolfSSL_ASN1_STRING_set +#define ASN1_UTF8STRING WOLFSSL_ASN1_STRING +#define ASN1_UTF8STRING_new wolfSSL_ASN1_STRING_new +#define ASN1_UTF8STRING_free wolfSSL_ASN1_STRING_free +#define ASN1_UTF8STRING_set wolfSSL_ASN1_STRING_set + #define ASN1_PRINTABLE_type(...) V_ASN1_PRINTABLESTRING #define ASN1_UTCTIME_pr wolfSSL_ASN1_UTCTIME_pr @@ -1345,6 +1352,7 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define GENERAL_NAME_free wolfSSL_GENERAL_NAME_free #define GENERAL_NAME_dup wolfSSL_GENERAL_NAME_dup #define GENERAL_NAME_print wolfSSL_GENERAL_NAME_print +#define GENERAL_NAME_set0_othername wolfSSL_GENERAL_NAME_set0_othername #define sk_GENERAL_NAME_push wolfSSL_sk_GENERAL_NAME_push #define sk_GENERAL_NAME_value wolfSSL_sk_GENERAL_NAME_value @@ -1367,6 +1375,7 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define SSL_SESSION_set1_id_context wolfSSL_SESSION_set1_id_context #define SSL_SESSION_print wolfSSL_SESSION_print #define sk_GENERAL_NAME_pop_free wolfSSL_sk_GENERAL_NAME_pop_free +#define sk_GENERAL_NAME_new wolfSSL_sk_GENERAL_NAME_new #define sk_GENERAL_NAME_free wolfSSL_sk_GENERAL_NAME_free #define sk_ASN1_OBJECT_pop_free wolfSSL_sk_ASN1_OBJECT_pop_free #define GENERAL_NAME_free wolfSSL_GENERAL_NAME_free diff --git a/wolfssl/openssl/x509v3.h b/wolfssl/openssl/x509v3.h index 09550edd5f6..30c953936d5 100644 --- a/wolfssl/openssl/x509v3.h +++ b/wolfssl/openssl/x509v3.h @@ -109,6 +109,7 @@ struct WOLFSSL_X509_EXTENSION { #define GEN_URI 6 #define GEN_IPADD 7 #define GEN_RID 8 +#define GEN_IA5 9 #define GENERAL_NAME WOLFSSL_GENERAL_NAME diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 39adea3f505..23053d01c08 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -1558,6 +1558,11 @@ WOLFSSL_API int wolfSSL_GENERAL_NAME_set_type(WOLFSSL_GENERAL_NAME* name, int typ); WOLFSSL_API WOLFSSL_GENERAL_NAMES* wolfSSL_GENERAL_NAMES_dup( WOLFSSL_GENERAL_NAMES* gns); +WOLFSSL_API int wolfSSL_GENERAL_NAME_set0_othername(WOLFSSL_GENERAL_NAME* gen, + WOLFSSL_ASN1_OBJECT* oid, + WOLFSSL_ASN1_TYPE* value); + +WOLFSSL_API WOLFSSL_STACK* wolfSSL_sk_GENERAL_NAME_new(void *cmpFunc); WOLFSSL_API int wolfSSL_sk_GENERAL_NAME_push(WOLFSSL_GENERAL_NAMES* sk, WOLFSSL_GENERAL_NAME* gn); WOLFSSL_API WOLFSSL_GENERAL_NAME* wolfSSL_sk_GENERAL_NAME_value( @@ -4382,6 +4387,9 @@ WOLFSSL_API int wolfSSL_X509_get_ext_by_OBJ(const WOLFSSL_X509 *x, WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x, int loc); WOLFSSL_API int wolfSSL_X509_EXTENSION_get_critical(const WOLFSSL_X509_EXTENSION* ex); WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_new(void); +WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_create_by_OBJ( + WOLFSSL_X509_EXTENSION* ex, WOLFSSL_ASN1_OBJECT *obj, int crit, + WOLFSSL_ASN1_STRING *data); WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_dup( WOLFSSL_X509_EXTENSION* src); WOLFSSL_API int wolfSSL_sk_X509_EXTENSION_push(WOLFSSL_STACK* sk, @@ -4419,6 +4427,9 @@ WOLFSSL_API WOLFSSL_X509* wolfSSL_d2i_X509_bio(WOLFSSL_BIO* bio, #ifdef WOLFSSL_CERT_REQ WOLFSSL_API WOLFSSL_X509* wolfSSL_d2i_X509_REQ_bio(WOLFSSL_BIO* bio, WOLFSSL_X509** x509); +#if !defined(NO_FILESYSTEM) +WOLFSSL_API WOLFSSL_X509* wolfSSL_d2i_X509_REQ_fp(XFILE fp, WOLFSSL_X509 **req); +#endif #endif #endif /* OPENSSL_EXTRA || OPENSSL_ALL */ diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 5de97bd0985..13631843001 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -2166,6 +2166,9 @@ WOLFSSL_LOCAL word32 SetAlgoID(int algoOID,byte* output,int type,int curveSz); WOLFSSL_LOCAL int SetMyVersion(word32 version, byte* output, int header); WOLFSSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output, word32 outputSz, int maxSnSz); +/* name is of type WOLFSSL_ASN1_OTHERNAME; use void* to avoid including ssl.h */ +WOLFSSL_LOCAL word32 SetOthername(void *name, byte *output); + #ifndef WOLFSSL_ASN_TEMPLATE WOLFSSL_LOCAL int wc_GetSerialNumber(const byte* input, word32* inOutIdx, byte* serial, int* serialSz, word32 maxIdx); diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index 0de6a2e6d8a..91b64323f3e 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -351,7 +351,6 @@ typedef struct NameAttrib { #endif /* WOLFSSL_MULTI_ATTRIB */ #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ -#ifdef WOLFSSL_CERT_GEN #ifdef WOLFSSL_CUSTOM_OID typedef struct CertOidField { byte* oid; @@ -362,13 +361,12 @@ typedef struct CertOidField { } CertOidField; typedef struct CertExtension { - const char* oid; - byte crit; - const byte* val; - int valSz; + char* oid; + byte crit; + byte* val; + int valSz; } CertExtension; #endif -#endif /* WOLFSSL_CERT_GEN */ #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) typedef struct CertName { @@ -422,11 +420,8 @@ typedef struct CertName { } CertName; #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL*/ -#ifdef WOLFSSL_CERT_GEN - #ifndef NUM_CUSTOM_EXT #define NUM_CUSTOM_EXT 16 -#endif /* for user to fill for certificate generation */ typedef struct Cert { @@ -434,10 +429,13 @@ typedef struct Cert { byte serial[CTC_SERIAL_SIZE]; /* serial number */ int serialSz; /* serial size */ int sigType; /* signature algo type */ +#if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) \ + || defined(OPENSSL_EXTRA_X509_SMALL) CertName issuer; /* issuer info */ + CertName subject; /* subject info */ +#endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ int daysValid; /* validity days */ int selfSigned; /* self signed flag */ - CertName subject; /* subject info */ int isCA; /* is this going to be a CA */ byte pathLen; /* max depth of valid certification * paths that include this cert */ @@ -492,7 +490,7 @@ typedef struct Cert { char challengePw[CTC_NAME_SIZE]; char unstructuredName[CTC_NAME_SIZE]; int challengePwPrintableString; /* encode as PrintableString */ -#endif +#endif /* WOLFSSL_CERT_REQ */ #ifdef WOLFSSL_CUSTOM_OID /* user oid and value to go in req extensions */ CertOidField extCustom; @@ -500,7 +498,7 @@ typedef struct Cert { /* Extensions to go into X.509 certificates */ CertExtension customCertExt[NUM_CUSTOM_EXT]; int customCertExtCount; -#endif +#endif /* WOLFSSL_CUSTOM_OID */ void* decodedCert; /* internal DecodedCert allocated from heap */ byte* der; /* Pointer to buffer of current DecodedCert cache */ void* heap; /* heap hint */ From 692eed7a6bc5812df6a664a924a38aa857edda60 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Thu, 30 Mar 2023 18:30:23 +0200 Subject: [PATCH 148/391] Write next IV in wolfSSL_DES_ede3_cbc_encrypt --- src/ssl.c | 11 +++++++++++ wolfcrypt/test/test.c | 17 +++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 82bc6510f38..3366c040d5b 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -20030,6 +20030,9 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, WOLFSSL_ENTER("wolfSSL_DES_ede3_cbc_encrypt"); + if (sz <= 0) + return; + XMEMSET(key, 0, sizeof(key)); XMEMCPY(key, *ks1, DES_BLOCK_SIZE); XMEMCPY(&key[DES_BLOCK_SIZE], *ks2, DES_BLOCK_SIZE); @@ -20057,6 +20060,10 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, ret = wc_AsyncWait(ret, &des.asyncDev, WC_ASYNC_FLAG_NONE); #endif (void)ret; /* ignore return codes for processing */ + XMEMCPY(ivec, output+blk*DES_BLOCK_SIZE, DES_BLOCK_SIZE); + } + else { + XMEMCPY(ivec, output+(blk-1)*DES_BLOCK_SIZE, DES_BLOCK_SIZE); } } } @@ -20075,6 +20082,10 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, #endif (void)ret; /* ignore return codes for processing */ XMEMCPY(output+sz-lb_sz, lastblock, lb_sz); + XMEMCPY(ivec, input+sz-lb_sz, DES_BLOCK_SIZE); + } + else { + XMEMCPY(ivec, input+(blk-1)*DES_BLOCK_SIZE, DES_BLOCK_SIZE); } } } diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index bfe73f4baee..11267d9df31 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -7430,6 +7430,9 @@ WOLFSSL_TEST_SUBROUTINE int des3_test(void) }; int ret; +#if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) + size_t i; +#endif ret = wc_Des3Init(&enc, HEAP_HINT, devId); @@ -7466,7 +7469,7 @@ WOLFSSL_TEST_SUBROUTINE int des3_test(void) #if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) /* test the same vectors with using compatibility layer */ - { + for (i = 0; i < sizeof(vector); i += DES_BLOCK_SIZE){ DES_key_schedule ks1; DES_key_schedule ks2; DES_key_schedule ks3; @@ -7475,15 +7478,21 @@ WOLFSSL_TEST_SUBROUTINE int des3_test(void) XMEMCPY(ks1, key3, sizeof(DES_key_schedule)); XMEMCPY(ks2, key3 + 8, sizeof(DES_key_schedule)); XMEMCPY(ks3, key3 + 16, sizeof(DES_key_schedule)); - XMEMCPY(iv4, iv3, sizeof(DES_cblock)); XMEMSET(plain, 0, sizeof(plain)); XMEMSET(cipher, 0, sizeof(cipher)); - DES_ede3_cbc_encrypt(vector, cipher, sizeof(vector), &ks1, &ks2, &ks3, + /* Use i as the splitter */ + XMEMCPY(iv4, iv3, sizeof(DES_cblock)); + DES_ede3_cbc_encrypt(vector, cipher, i, &ks1, &ks2, &ks3, &iv4, DES_ENCRYPT); - DES_ede3_cbc_encrypt(cipher, plain, sizeof(cipher), &ks1, &ks2, &ks3, + DES_ede3_cbc_encrypt(vector + i, cipher + i, sizeof(vector) - i, &ks1, + &ks2, &ks3, &iv4, DES_ENCRYPT); + XMEMCPY(iv4, iv3, sizeof(DES_cblock)); + DES_ede3_cbc_encrypt(cipher, plain, i, &ks1, &ks2, &ks3, &iv4, DES_DECRYPT); + DES_ede3_cbc_encrypt(cipher + i, plain + i, sizeof(cipher) - i, &ks1, + &ks2, &ks3, &iv4, DES_DECRYPT); if (XMEMCMP(plain, vector, sizeof(plain))) return WC_TEST_RET_ENC_NC; From cc397a567461abcfb9b3574497cb2a7efd6811d9 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 31 Mar 2023 11:48:18 +0200 Subject: [PATCH 149/391] Add explicit casts --- wolfcrypt/test/test.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 11267d9df31..223b00d61f8 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -7484,15 +7484,15 @@ WOLFSSL_TEST_SUBROUTINE int des3_test(void) /* Use i as the splitter */ XMEMCPY(iv4, iv3, sizeof(DES_cblock)); - DES_ede3_cbc_encrypt(vector, cipher, i, &ks1, &ks2, &ks3, + DES_ede3_cbc_encrypt(vector, cipher, (long)i, &ks1, &ks2, &ks3, &iv4, DES_ENCRYPT); - DES_ede3_cbc_encrypt(vector + i, cipher + i, sizeof(vector) - i, &ks1, - &ks2, &ks3, &iv4, DES_ENCRYPT); + DES_ede3_cbc_encrypt(vector + i, cipher + i, (long)(sizeof(vector) - i), + &ks1, &ks2, &ks3, &iv4, DES_ENCRYPT); XMEMCPY(iv4, iv3, sizeof(DES_cblock)); - DES_ede3_cbc_encrypt(cipher, plain, i, &ks1, &ks2, &ks3, + DES_ede3_cbc_encrypt(cipher, plain, (long)i, &ks1, &ks2, &ks3, &iv4, DES_DECRYPT); - DES_ede3_cbc_encrypt(cipher + i, plain + i, sizeof(cipher) - i, &ks1, - &ks2, &ks3, &iv4, DES_DECRYPT); + DES_ede3_cbc_encrypt(cipher + i, plain + i, (long)(sizeof(cipher) - i), + &ks1, &ks2, &ks3, &iv4, DES_DECRYPT); if (XMEMCMP(plain, vector, sizeof(plain))) return WC_TEST_RET_ENC_NC; From 17285a5d70ef5d55d5680f685403030c994f9951 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 5 Apr 2023 15:50:51 +0200 Subject: [PATCH 150/391] Add in-place support for DES_ede3_cbc_encrypt --- src/ssl.c | 8 ++++---- wolfcrypt/test/test.c | 14 ++++++++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 3366c040d5b..f0f4f029726 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -20070,6 +20070,10 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, else { if (wc_Des3_SetKey(&des, key, (const byte*)ivec, DES_DECRYPTION) == 0) { + if(lb_sz) + XMEMCPY(ivec, input+sz-lb_sz, DES_BLOCK_SIZE); + else + XMEMCPY(ivec, input+(blk-1)*DES_BLOCK_SIZE, DES_BLOCK_SIZE); ret = wc_Des3_CbcDecrypt(&des, output, input, (word32)blk*DES_BLOCK_SIZE); #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &des.asyncDev, WC_ASYNC_FLAG_NONE); @@ -20082,10 +20086,6 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, #endif (void)ret; /* ignore return codes for processing */ XMEMCPY(output+sz-lb_sz, lastblock, lb_sz); - XMEMCPY(ivec, input+sz-lb_sz, DES_BLOCK_SIZE); - } - else { - XMEMCPY(ivec, input+(blk-1)*DES_BLOCK_SIZE, DES_BLOCK_SIZE); } } } diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 223b00d61f8..dc58a1e488a 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -7474,6 +7474,7 @@ WOLFSSL_TEST_SUBROUTINE int des3_test(void) DES_key_schedule ks2; DES_key_schedule ks3; DES_cblock iv4; + byte tmp[sizeof(vector)]; XMEMCPY(ks1, key3, sizeof(DES_key_schedule)); XMEMCPY(ks2, key3 + 8, sizeof(DES_key_schedule)); @@ -7482,17 +7483,22 @@ WOLFSSL_TEST_SUBROUTINE int des3_test(void) XMEMSET(plain, 0, sizeof(plain)); XMEMSET(cipher, 0, sizeof(cipher)); + /* Test in-place encrypt/decrypt */ + XMEMCPY(tmp, vector, sizeof(vector)); + /* Use i as the splitter */ XMEMCPY(iv4, iv3, sizeof(DES_cblock)); - DES_ede3_cbc_encrypt(vector, cipher, (long)i, &ks1, &ks2, &ks3, + DES_ede3_cbc_encrypt(tmp, tmp, (long)i, &ks1, &ks2, &ks3, &iv4, DES_ENCRYPT); - DES_ede3_cbc_encrypt(vector + i, cipher + i, (long)(sizeof(vector) - i), + DES_ede3_cbc_encrypt(tmp + i, tmp + i, (long)(sizeof(vector) - i), &ks1, &ks2, &ks3, &iv4, DES_ENCRYPT); + XMEMCPY(cipher, tmp, sizeof(cipher)); XMEMCPY(iv4, iv3, sizeof(DES_cblock)); - DES_ede3_cbc_encrypt(cipher, plain, (long)i, &ks1, &ks2, &ks3, + DES_ede3_cbc_encrypt(tmp, tmp, (long)i, &ks1, &ks2, &ks3, &iv4, DES_DECRYPT); - DES_ede3_cbc_encrypt(cipher + i, plain + i, (long)(sizeof(cipher) - i), + DES_ede3_cbc_encrypt(tmp + i, tmp + i, (long)(sizeof(cipher) - i), &ks1, &ks2, &ks3, &iv4, DES_DECRYPT); + XMEMCPY(plain, tmp, sizeof(plain)); if (XMEMCMP(plain, vector, sizeof(plain))) return WC_TEST_RET_ENC_NC; From ae000168ae74a63249071ce7a57b058575f77420 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Tue, 11 Apr 2023 09:41:53 +0200 Subject: [PATCH 151/391] platform-specific VisualGDB test & benchmark projects --- .../wolfssl_benchmark_IDF_v4.4_ESP32.sln | 58 ++++ ...wolfssl_benchmark_IDF_v4.4_ESP32.vgdbproj} | 10 +- .../wolfssl_benchmark_IDF_v5_ESP32.sln | 59 ++++ .../wolfssl_benchmark_IDF_v5_ESP32.vgdbproj | 269 +++++++++++++++++ .../wolfssl_benchmark_IDF_v5_ESP32C3.sln | 63 ++++ .../wolfssl_benchmark_IDF_v5_ESP32C3.vgdbproj | 271 +++++++++++++++++ .../wolfssl_benchmark_IDF_v5_ESP32S3.sln | 54 ++++ .../wolfssl_benchmark_IDF_v5_ESP32S3.vgdbproj | 271 +++++++++++++++++ .../VisualGDB/VisualGDB_wolfssl_test-WIP.sln | 31 -- .../VisualGDB_wolfssl_test_IDF_v5_ESP32S3.sln | 31 -- .../VisualGDB/wolfssl_test-IDF_v5_ESP32.sln} | 12 +- ...roj => wolfssl_test-IDF_v5_ESP32.vgdbproj} | 8 +- .../VisualGDB/wolfssl_test-IDF_v5_ESP32C3.sln | 47 +++ ...j => wolfssl_test-IDF_v5_ESP32C3.vgdbproj} | 10 +- .../VisualGDB/wolfssl_test-IDF_v5_ESP32C6.sln | 47 +++ .../wolfssl_test-IDF_v5_ESP32C6.vgdbproj | 277 ++++++++++++++++++ ...st.sln => wolfssl_test_IDF_v5_ESP32S3.sln} | 36 ++- ...j => wolfssl_test_IDF_v5_ESP32S3.vgdbproj} | 20 +- IDE/Espressif/include.am | 27 +- 19 files changed, 1493 insertions(+), 108 deletions(-) create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.sln rename IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/{VisualGDB_wolfssl_benchmark.vgdbproj => wolfssl_benchmark_IDF_v4.4_ESP32.vgdbproj} (96%) create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.sln create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.vgdbproj create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.sln create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.vgdbproj create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.sln create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.vgdbproj delete mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test-WIP.sln delete mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test_IDF_v5_ESP32S3.sln rename IDE/Espressif/ESP-IDF/examples/{wolfssl_benchmark/VisualGDB/VisualGDB_wolfssl_benchmark.sln => wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.sln} (70%) rename IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/{VisualGDB_wolfssl_test_IDF_v5_ESP32S3.vgdbproj => wolfssl_test-IDF_v5_ESP32.vgdbproj} (94%) create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.sln rename IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/{VisualGDB_wolfssl_test.vgdbproj => wolfssl_test-IDF_v5_ESP32C3.vgdbproj} (95%) create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.sln create mode 100644 IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.vgdbproj rename IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/{VisualGDB_wolfssl_test.sln => wolfssl_test_IDF_v5_ESP32S3.sln} (51%) rename IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/{VisualGDB_wolfssl_test-WIP.vgdbproj => wolfssl_test_IDF_v5_ESP32S3.vgdbproj} (93%) diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.sln new file mode 100644 index 00000000000..5473b15bc6f --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.sln @@ -0,0 +1,58 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.33027.164 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "wolfssl_benchmark", "wolfssl_benchmark_IDF_v4.4_ESP32.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{51FEFEA9-C2BA-43A1-8B36-9140367E5AAF}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.c = ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.c + ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.h = ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.h + ..\sdkconfig.defaults = ..\sdkconfig.defaults + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "wolfssl", "wolfssl", "{E0C1A3C6-D2E2-4E10-890C-3468B1B8834C}" + ProjectSection(SolutionItems) = preProject + ..\components\wolfssl\CMakeLists.txt = ..\components\wolfssl\CMakeLists.txt + ..\components\wolfssl\component.mk = ..\components\wolfssl\component.mk + ..\..\..\..\..\..\wolfcrypt\src\sha.c = ..\..\..\..\..\..\wolfcrypt\src\sha.c + ..\..\..\..\..\..\wolfcrypt\src\sha256.c = ..\..\..\..\..\..\wolfcrypt\src\sha256.c + ..\..\..\..\..\..\wolfcrypt\src\sha3.c = ..\..\..\..\..\..\wolfcrypt\src\sha3.c + ..\..\..\..\..\..\wolfcrypt\src\sha512.c = ..\..\..\..\..\..\wolfcrypt\src\sha512.c + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "include", "include", "{530960D7-4FAB-4683-9C83-35ADE6C00358}" + ProjectSection(SolutionItems) = preProject + ..\components\wolfssl\include\config.h = ..\components\wolfssl\include\config.h + ..\components\wolfssl\include\user_settings.h = ..\components\wolfssl\include\user_settings.h + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|VisualGDB = Debug|VisualGDB + Release|VisualGDB = Release|VisualGDB + Tests (Debug)|VisualGDB = Tests (Debug)|VisualGDB + Tests (Release)|VisualGDB = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.ActiveCfg = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.Build.0 = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.ActiveCfg = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.Build.0 = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.ActiveCfg = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.Build.0 = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.ActiveCfg = Tests (Release)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.Build.0 = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {E0C1A3C6-D2E2-4E10-890C-3468B1B8834C} = {51FEFEA9-C2BA-43A1-8B36-9140367E5AAF} + {530960D7-4FAB-4683-9C83-35ADE6C00358} = {E0C1A3C6-D2E2-4E10-890C-3468B1B8834C} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {668EEFC0-010C-4688-916F-A628190717D4} + EndGlobalSection +EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/VisualGDB_wolfssl_benchmark.vgdbproj b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.vgdbproj similarity index 96% rename from IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/VisualGDB_wolfssl_benchmark.vgdbproj rename to IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.vgdbproj index 911ba6c9aad..aa22dacfdb8 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/VisualGDB_wolfssl_benchmark.vgdbproj +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.vgdbproj @@ -18,9 +18,9 @@ com.visualgdb.xtensa-esp32-elf - 11.2.0 - 9.2.90 - 2 + 8.4.0 + 8.1.0 + 9 .. @@ -67,8 +67,8 @@ true - release/v5.0 - esp-idf/v5.0 + v4.4.1 + esp-idf/v4.4.1 ESPIDF COM20 diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.sln new file mode 100644 index 00000000000..ff33772283d --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.sln @@ -0,0 +1,59 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33516.290 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "wolfssl_benchmark_IDF_v5_ESP32", "wolfssl_benchmark_IDF_v5_ESP32.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "wolfssl", "wolfssl", "{BDD063E3-67C1-437F-9F9B-7175E36EE6EE}" + ProjectSection(SolutionItems) = preProject + ..\components\wolfssl\CMakeLists.txt = ..\components\wolfssl\CMakeLists.txt + ..\components\wolfssl\include\config.h = ..\components\wolfssl\include\config.h + ..\components\wolfssl\Kconfig = ..\components\wolfssl\Kconfig + ..\components\wolfssl\include\user_settings.h = ..\components\wolfssl\include\user_settings.h + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E25A35EF-64B9-48AA-939B-49340C2A4B03}" + ProjectSection(SolutionItems) = preProject + ..\sdkconfig = ..\sdkconfig + ..\build\VisualGDB\Debug\config\sdkconfig.h = ..\build\VisualGDB\Debug\config\sdkconfig.h + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "wolfcrypt", "wolfcrypt", "{68571B42-6509-475F-A79D-FB5F6188753B}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\..\wolfssl\wolfcrypt\port\Espressif\esp32-crypt.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\port\Espressif\esp32-crypt.h + ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_aes.c = ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_aes.c + ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_mp.c = ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_mp.c + ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_sha.c = ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_sha.c + ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_util.c = ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_util.c + ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\README.md = ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\README.md + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|VisualGDB = Debug|VisualGDB + Release|VisualGDB = Release|VisualGDB + Tests (Debug)|VisualGDB = Tests (Debug)|VisualGDB + Tests (Release)|VisualGDB = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.ActiveCfg = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.Build.0 = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.ActiveCfg = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.Build.0 = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.ActiveCfg = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.Build.0 = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.ActiveCfg = Tests (Release)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.Build.0 = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {BDD063E3-67C1-437F-9F9B-7175E36EE6EE} = {E25A35EF-64B9-48AA-939B-49340C2A4B03} + {68571B42-6509-475F-A79D-FB5F6188753B} = {E25A35EF-64B9-48AA-939B-49340C2A4B03} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {DED328BF-3A3C-47F4-A536-4554945B865B} + EndGlobalSection +EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.vgdbproj b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.vgdbproj new file mode 100644 index 00000000000..276a342dee5 --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.vgdbproj @@ -0,0 +1,269 @@ + + + + + + Unknown + + true + + 7bbd1486-d457-4e49-92ba-0cfc9d80849e + true + true + SourceDirs + + + + + + com.visualgdb.xtensa-esp32-elf + + 11.2.0 + 9.2.90 + 2 + + + .. + DEBUG + build/$(PlatformName)/$(ConfigurationName) + + false + $(ToolchainNinja) + $(BuildDir) + + + + false + $(SYSPROGS_CMAKE_PATH) + + + true + false + false + Ninja + false + RemoveBuildDirectory + false + + + true + true + true + false + true + false + true + HideOuterProjectTargets + true + false + true + + + true + eadcc9ab-72b3-4b51-a838-593e5d80ddf7 + + Upper + HeaderDirectoryAndSubdirectories + true + + + release/v5.0 + esp-idf/v5.0 + ESPIDF + + COM20 + false + false + ESP32 + + + + + + + + + + + + + + + Default + + + + COM9 + + 115200 + 8 + None + One + None + + + 0 + false + false + false + ASCII + + + 255 + 0 + 0 + 0 + + + 255 + 169 + 169 + 169 + + + 255 + 211 + 211 + 211 + + + 255 + 144 + 238 + 144 + + + 255 + 169 + 169 + 169 + + + + 16 + true + true + true + true + 0 + + LF + false + false + false + + + + true + + + + + Unknown + + true + true + true + + + + false + + + + + Debug + + + + Release + + + + + + + + + false + false + false + false + false + false + false + false + false + + false + false + false + false + false + false + true + false + None + false + false + app_main + true + false + false + true + 0 + false + 0 + true + false + + + openocd + + -f interface/ftdi/tigard.cfg -c "adapter_khz 15000" -f target/esp32.cfg + + + + false + + 131072 + Enabled + + set remotetimeout 60 + target remote :$$SYS:GDB_PORT$$ + mon gdb_breakpoint_override hard + mon reset halt + load + + false + 0 + 0 + false + + 5000 + 1 + true + + size2MB + freq40M + DIO + + true + + + true + Disabled + 0 + false + false + true + false + false + + _estack + 0 + false + + true + + \ No newline at end of file diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.sln new file mode 100644 index 00000000000..b5157b13912 --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.sln @@ -0,0 +1,63 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.33027.164 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "wolfssl_benchmark_IDF_v5_ESP32C3", "wolfssl_benchmark_IDF_v5_ESP32C3.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{68202294-86F7-471F-BBBF-47F6B3E3137C}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.c = ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.c + ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.h = ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.h + ..\components\wolfssl\include\config.h = ..\components\wolfssl\include\config.h + ..\components\wolfssl\include\user_settings.h = ..\components\wolfssl\include\user_settings.h + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "wolfcrypt", "wolfcrypt", "{35897992-1F28-4AB1-B432-7F7D76D61162}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\..\wolfcrypt\src\sha.c = ..\..\..\..\..\..\wolfcrypt\src\sha.c + ..\..\..\..\..\..\wolfssl\openssl\sha.h = ..\..\..\..\..\..\wolfssl\openssl\sha.h + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha.h + ..\..\..\..\..\..\wolfcrypt\src\sha256.c = ..\..\..\..\..\..\wolfcrypt\src\sha256.c + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha256.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha256.h + ..\..\..\..\..\..\wolfcrypt\src\sha512.c = ..\..\..\..\..\..\wolfcrypt\src\sha512.c + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha512.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha512.h + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Espressif Port", "Espressif Port", "{66DEEB01-9378-4714-9EF7-23A0CA65A996}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\..\wolfssl\wolfcrypt\port\Espressif\esp32-crypt.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\port\Espressif\esp32-crypt.h + ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_sha.c = ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_sha.c + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "config", "config", "{3BA29EA8-68C5-4144-B471-33BA380C323E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|VisualGDB = Debug|VisualGDB + Release|VisualGDB = Release|VisualGDB + Tests (Debug)|VisualGDB = Tests (Debug)|VisualGDB + Tests (Release)|VisualGDB = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.ActiveCfg = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.Build.0 = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.ActiveCfg = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.Build.0 = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.ActiveCfg = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.Build.0 = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.ActiveCfg = Tests (Release)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.Build.0 = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {35897992-1F28-4AB1-B432-7F7D76D61162} = {68202294-86F7-471F-BBBF-47F6B3E3137C} + {66DEEB01-9378-4714-9EF7-23A0CA65A996} = {68202294-86F7-471F-BBBF-47F6B3E3137C} + {3BA29EA8-68C5-4144-B471-33BA380C323E} = {68202294-86F7-471F-BBBF-47F6B3E3137C} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8F3E87F6-73E7-446B-A5B7-ADB94756C9D4} + EndGlobalSection +EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.vgdbproj b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.vgdbproj new file mode 100644 index 00000000000..fa2513a7964 --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.vgdbproj @@ -0,0 +1,271 @@ + + + + + + Unknown + + true + + 7bbd1486-d457-4e49-92ba-0cfc9d80849e + true + true + SourceDirs + + + + + + com.visualgdb.xtensa-esp32-elf + + 11.2.0 + 9.2.90 + 2 + + + .. + DEBUG + build/$(PlatformName)/$(ConfigurationName) + + false + $(ToolchainNinja) + $(BuildDir) + + + + false + $(SYSPROGS_CMAKE_PATH) + + + true + false + false + Ninja + false + RemoveBuildDirectory + false + + + true + true + true + false + true + false + true + HideOuterProjectTargets + true + false + true + + + true + eadcc9ab-72b3-4b51-a838-593e5d80ddf7 + + Upper + HeaderDirectoryAndSubdirectories + true + + + release/v5.0 + esp-idf/v5.0 + ESPIDF + + COM23 + false + false + ESP32C3 + + + + + + + + + + + + + + + Default + + + + COM24 + + 115200 + 8 + None + One + None + + + 0 + false + false + false + ASCII + + + 255 + 0 + 0 + 0 + + + 255 + 169 + 169 + 169 + + + 255 + 211 + 211 + 211 + + + 255 + 144 + 238 + 144 + + + 255 + 169 + 169 + 169 + + + + 16 + true + true + true + true + 0 + + LF + false + false + false + + + + true + + + + + Unknown + + true + true + true + + + + false + + + + + Debug + + + + Release + + + + + + + + + false + true + true + true + true + true + true + true + true + + false + false + false + false + false + false + true + false + Disconnect + false + false + app_main + true + false + false + true + 0 + false + 0 + true + false + + + openocd + esp_usb_jtag + 60:55:F9:BC:29:94 + + -f interface/esp_usb_jtag.cfg -c "adapter_khz 3000" -f target/esp32c3.cfg + + + + false + + 131072 + Enabled + + set remotetimeout 60 + target remote :$$SYS:GDB_PORT$$ + mon gdb_breakpoint_override hard + mon reset halt + load + + false + 0 + 0 + false + + 5000 + 1 + true + + size2MB + freq40M + DIO + + true + + + true + Disabled + 0 + false + false + true + false + false + + _estack + 0 + false + + true + + \ No newline at end of file diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.sln new file mode 100644 index 00000000000..05ad012e75f --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.sln @@ -0,0 +1,54 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.33027.164 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CD9E73EC-27FB-49E4-B3A3-B0502C20A818}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "wolfSSL", "wolfSSL", "{20662F9E-D386-4839-B855-857D7F922C99}" + ProjectSection(SolutionItems) = preProject + ..\components\wolfssl\CMakeLists.txt = ..\components\wolfssl\CMakeLists.txt + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "include", "include", "{89279333-68BD-4E6A-B970-E645967CE5FA}" + ProjectSection(SolutionItems) = preProject + ..\components\wolfssl\include\config.h = ..\components\wolfssl\include\config.h + ..\components\wolfssl\include\user_settings.h = ..\components\wolfssl\include\user_settings.h + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "lib", "lib", "{E9586E44-7821-4956-9F72-A79B988B3211}" + ProjectSection(SolutionItems) = preProject + ..\..\..\user_settings.h = ..\..\..\user_settings.h + EndProjectSection +EndProject +Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "wolfssl_benchmark_IDF_v5_ESP32S3", "wolfssl_benchmark_IDF_v5_ESP32S3.vgdbproj", "{870D7357-61DA-432A-806F-041A23BC8532}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|VisualGDB = Debug|VisualGDB + Release|VisualGDB = Release|VisualGDB + Tests (Debug)|VisualGDB = Tests (Debug)|VisualGDB + Tests (Release)|VisualGDB = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {870D7357-61DA-432A-806F-041A23BC8532}.Debug|VisualGDB.ActiveCfg = Debug|VisualGDB + {870D7357-61DA-432A-806F-041A23BC8532}.Debug|VisualGDB.Build.0 = Debug|VisualGDB + {870D7357-61DA-432A-806F-041A23BC8532}.Release|VisualGDB.ActiveCfg = Release|VisualGDB + {870D7357-61DA-432A-806F-041A23BC8532}.Release|VisualGDB.Build.0 = Release|VisualGDB + {870D7357-61DA-432A-806F-041A23BC8532}.Tests (Debug)|VisualGDB.ActiveCfg = Tests (Debug)|VisualGDB + {870D7357-61DA-432A-806F-041A23BC8532}.Tests (Debug)|VisualGDB.Build.0 = Tests (Debug)|VisualGDB + {870D7357-61DA-432A-806F-041A23BC8532}.Tests (Release)|VisualGDB.ActiveCfg = Tests (Release)|VisualGDB + {870D7357-61DA-432A-806F-041A23BC8532}.Tests (Release)|VisualGDB.Build.0 = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {20662F9E-D386-4839-B855-857D7F922C99} = {CD9E73EC-27FB-49E4-B3A3-B0502C20A818} + {89279333-68BD-4E6A-B970-E645967CE5FA} = {20662F9E-D386-4839-B855-857D7F922C99} + {E9586E44-7821-4956-9F72-A79B988B3211} = {CD9E73EC-27FB-49E4-B3A3-B0502C20A818} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7F8E1DC0-55AD-4DF8-B65A-CD65B60E17F9} + EndGlobalSection +EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.vgdbproj b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.vgdbproj new file mode 100644 index 00000000000..f3bd9b81df8 --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.vgdbproj @@ -0,0 +1,271 @@ + + + + + + Unknown + + true + + 35e5525f-318a-466e-a8c7-36548547d801 + true + true + SourceDirs + + + + + + com.visualgdb.xtensa-esp32-elf + + 11.2.0 + 9.2.90 + 2 + + + .. + DEBUG + build/$(PlatformName)/$(ConfigurationName) + + false + $(ToolchainNinja) + $(BuildDir) + + + + false + $(SYSPROGS_CMAKE_PATH) + + + true + false + false + Ninja + false + RemoveBuildDirectory + false + + + true + true + true + false + true + false + true + HideOuterProjectTargets + true + false + true + + + true + eadcc9ab-72b3-4b51-a838-593e5d80ddf7 + + Upper + HeaderDirectoryAndSubdirectories + true + + + release/v5.0 + esp-idf/v5.0 + ESPIDF + + COM17 + false + false + ESP32S3 + + + + + + + + + + + + + + + Default + + + + COM17 + + 115200 + 8 + None + One + None + + + 0 + false + true + false + ASCII + + + 255 + 0 + 0 + 0 + + + 255 + 169 + 169 + 169 + + + 255 + 211 + 211 + 211 + + + 255 + 144 + 238 + 144 + + + 255 + 169 + 169 + 169 + + + + 16 + true + true + true + true + 0 + + LF + false + false + false + + + + true + + + + + Unknown + + true + true + true + + + + false + + + + + Debug + + + + Release + + + + + + + + + false + false + false + false + false + false + false + false + false + + false + false + false + false + false + false + true + false + None + false + false + app_main + true + false + false + true + 0 + false + 0 + true + false + + + openocd + esp_usb_jtag + 7C:00:00:00:00:00 + + -f interface/esp_usb_jtag.cfg -f target/esp32s3.cfg + + + + false + + 131072 + Enabled + + set remotetimeout 60 + target remote :$$SYS:GDB_PORT$$ + mon gdb_breakpoint_override hard + mon reset halt + load + + false + 0 + 0 + false + + 5000 + 1 + true + + size2MB + freq40M + DIO + + true + + + true + Auto + 0 + false + false + true + false + false + + _estack + 0 + false + + true + + \ No newline at end of file diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test-WIP.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test-WIP.sln deleted file mode 100644 index ac99b57b2d2..00000000000 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test-WIP.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.33027.164 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "VisualGDB_wolfssl_test-WIP", "VisualGDB_wolfssl_test-WIP.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|VisualGDB = Debug|VisualGDB - Release|VisualGDB = Release|VisualGDB - Tests (Debug)|VisualGDB = Tests (Debug)|VisualGDB - Tests (Release)|VisualGDB = Tests (Release)|VisualGDB - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.ActiveCfg = Debug|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.Build.0 = Debug|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.ActiveCfg = Release|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.Build.0 = Release|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.ActiveCfg = Tests (Debug)|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.Build.0 = Tests (Debug)|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.ActiveCfg = Tests (Release)|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.Build.0 = Tests (Release)|VisualGDB - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {C84ED821-3F33-4EBD-94E4-FE860F402B2F} - EndGlobalSection -EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test_IDF_v5_ESP32S3.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test_IDF_v5_ESP32S3.sln deleted file mode 100644 index ff22bd3e3c0..00000000000 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test_IDF_v5_ESP32S3.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.33027.164 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "VisualGDB_wolfssl_test_IDF_v5_ESP32S3", "VisualGDB_wolfssl_test_IDF_v5_ESP32S3.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|VisualGDB = Debug|VisualGDB - Release|VisualGDB = Release|VisualGDB - Tests (Debug)|VisualGDB = Tests (Debug)|VisualGDB - Tests (Release)|VisualGDB = Tests (Release)|VisualGDB - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.ActiveCfg = Debug|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.Build.0 = Debug|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.ActiveCfg = Release|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.Build.0 = Release|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.ActiveCfg = Tests (Debug)|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.Build.0 = Tests (Debug)|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.ActiveCfg = Tests (Release)|VisualGDB - {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.Build.0 = Tests (Release)|VisualGDB - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {7F8E1DC0-55AD-4DF8-B65A-CD65B60E17F9} - EndGlobalSection -EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/VisualGDB_wolfssl_benchmark.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.sln similarity index 70% rename from IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/VisualGDB_wolfssl_benchmark.sln rename to IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.sln index b0d40a1d958..a5a3465afc4 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/VisualGDB_wolfssl_benchmark.sln +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.sln @@ -3,14 +3,12 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.33027.164 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "VisualGDB_wolfssl_benchmark", "VisualGDB_wolfssl_benchmark.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" +Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "wolfssl_test-IDF_v5_ESP32", "wolfssl_test-IDF_v5_ESP32.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{51FEFEA9-C2BA-43A1-8B36-9140367E5AAF}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{760F4DFF-595E-4725-BB3A-EFA5966D0B70}" ProjectSection(SolutionItems) = preProject - ..\..\..\..\..\wolfcrypt\benchmark\benchmark.c = ..\..\..\..\..\wolfcrypt\benchmark\benchmark.c - ..\..\..\..\..\wolfcrypt\benchmark\benchmark.h = ..\..\..\..\..\wolfcrypt\benchmark\benchmark.h - components\wolfssl\CMakeLists.txt = components\wolfssl\CMakeLists.txt - ..\..\..\..\..\include\user_settings.h = ..\..\..\..\..\include\user_settings.h + ..\..\..\..\..\..\wolfcrypt\test\test.c = ..\..\..\..\..\..\wolfcrypt\test\test.c + ..\..\..\..\..\..\include\user_settings.h = ..\..\..\..\..\..\include\user_settings.h EndProjectSection EndProject Global @@ -34,6 +32,6 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {668EEFC0-010C-4688-916F-A628190717D4} + SolutionGuid = {34551780-699D-4BB5-8D19-CB42BE06F361} EndGlobalSection EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test_IDF_v5_ESP32S3.vgdbproj b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.vgdbproj similarity index 94% rename from IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test_IDF_v5_ESP32S3.vgdbproj rename to IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.vgdbproj index bbf7f1c2694..6c3af79883e 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test_IDF_v5_ESP32S3.vgdbproj +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.vgdbproj @@ -1,5 +1,5 @@ - + @@ -71,7 +71,7 @@ esp-idf/v5.0 ESPIDF - COM20 + COM9 false false ESP32 @@ -104,7 +104,7 @@ 0 false - false + true false ASCII @@ -220,7 +220,7 @@ openocd - -f interface/tigard.cfg -c "adapter_khz 3000" -f target/esp32s3.cfg + -f interface/ftdi/tigard.cfg -c "adapter_khz 15000" -f target/esp32.cfg diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.sln new file mode 100644 index 00000000000..e7431acb89f --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.sln @@ -0,0 +1,47 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.33027.164 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "wolfssl_test-IDF_v5_ESP32C3", "wolfssl_test-IDF_v5_ESP32C3.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.h = ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.h + ..\..\..\..\..\..\include\config.h = ..\..\..\..\..\..\include\config.h + ..\..\..\..\..\..\wolfssl\wolfcrypt\port\Espressif\esp32-crypt.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\port\Espressif\esp32-crypt.h + ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_sha.c = ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_sha.c + ..\..\..\..\..\..\wolfcrypt\src\sha.c = ..\..\..\..\..\..\wolfcrypt\src\sha.c + ..\..\..\..\..\..\wolfssl\openssl\sha.h = ..\..\..\..\..\..\wolfssl\openssl\sha.h + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha.h + ..\..\..\..\..\..\wolfcrypt\src\sha256.c = ..\..\..\..\..\..\wolfcrypt\src\sha256.c + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha256.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha256.h + ..\..\..\..\..\..\wolfcrypt\src\sha512.c = ..\..\..\..\..\..\wolfcrypt\src\sha512.c + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha512.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha512.h + ..\..\..\..\..\..\wolfcrypt\test\test.c = ..\..\..\..\..\..\wolfcrypt\test\test.c + ..\..\..\..\..\..\wolfcrypt\test\test.h = ..\..\..\..\..\..\wolfcrypt\test\test.h + ..\..\..\..\..\..\include\user_settings.h = ..\..\..\..\..\..\include\user_settings.h + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|VisualGDB = Debug|VisualGDB + Release|VisualGDB = Release|VisualGDB + Tests (Debug)|VisualGDB = Tests (Debug)|VisualGDB + Tests (Release)|VisualGDB = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.ActiveCfg = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.Build.0 = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.ActiveCfg = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.Build.0 = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.ActiveCfg = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.Build.0 = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.ActiveCfg = Tests (Release)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.Build.0 = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BBD58395-CE14-4ADC-9039-0BB2950C6D59} + EndGlobalSection +EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test.vgdbproj b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.vgdbproj similarity index 95% rename from IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test.vgdbproj rename to IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.vgdbproj index 28bcb2d1dce..9597b4f3401 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test.vgdbproj +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.vgdbproj @@ -71,10 +71,10 @@ esp-idf/v5.0 ESPIDF - COM20 + COM9 false false - ESP32 + ESP32C3 @@ -93,7 +93,7 @@ - COM20 + COM9 115200 8 @@ -104,7 +104,7 @@ 0 false - false + true false ASCII @@ -220,7 +220,7 @@ openocd - -f interface/tigard.cfg -c "adapter_khz 3000" -f target/esp32.cfg + -f interface/esp_usb_jtag.cfg -c "adapter_khz 40000" -f target/esp32c3.cfg diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.sln new file mode 100644 index 00000000000..e0aa28b86c4 --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.sln @@ -0,0 +1,47 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.33027.164 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "wolfssl_test-IDF_v5_ESP32C6", "wolfssl_test-IDF_v5_ESP32C6.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.h = ..\..\..\..\..\..\wolfcrypt\benchmark\benchmark.h + ..\..\..\..\..\..\include\config.h = ..\..\..\..\..\..\include\config.h + ..\..\..\..\..\..\wolfssl\wolfcrypt\port\Espressif\esp32-crypt.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\port\Espressif\esp32-crypt.h + ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_sha.c = ..\..\..\..\..\..\wolfcrypt\src\port\Espressif\esp32_sha.c + ..\..\..\..\..\..\wolfcrypt\src\sha.c = ..\..\..\..\..\..\wolfcrypt\src\sha.c + ..\..\..\..\..\..\wolfssl\openssl\sha.h = ..\..\..\..\..\..\wolfssl\openssl\sha.h + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha.h + ..\..\..\..\..\..\wolfcrypt\src\sha256.c = ..\..\..\..\..\..\wolfcrypt\src\sha256.c + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha256.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha256.h + ..\..\..\..\..\..\wolfcrypt\src\sha512.c = ..\..\..\..\..\..\wolfcrypt\src\sha512.c + ..\..\..\..\..\..\wolfssl\wolfcrypt\sha512.h = ..\..\..\..\..\..\wolfssl\wolfcrypt\sha512.h + ..\..\..\..\..\..\wolfcrypt\test\test.c = ..\..\..\..\..\..\wolfcrypt\test\test.c + ..\..\..\..\..\..\wolfcrypt\test\test.h = ..\..\..\..\..\..\wolfcrypt\test\test.h + ..\..\..\..\..\..\include\user_settings.h = ..\..\..\..\..\..\include\user_settings.h + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|VisualGDB = Debug|VisualGDB + Release|VisualGDB = Release|VisualGDB + Tests (Debug)|VisualGDB = Tests (Debug)|VisualGDB + Tests (Release)|VisualGDB = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.ActiveCfg = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Debug|VisualGDB.Build.0 = Debug|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.ActiveCfg = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Release|VisualGDB.Build.0 = Release|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.ActiveCfg = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Debug)|VisualGDB.Build.0 = Tests (Debug)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.ActiveCfg = Tests (Release)|VisualGDB + {EADCC9AB-72B3-4B51-A838-593E5D80DDF7}.Tests (Release)|VisualGDB.Build.0 = Tests (Release)|VisualGDB + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BBD58395-CE14-4ADC-9039-0BB2950C6D59} + EndGlobalSection +EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.vgdbproj b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.vgdbproj new file mode 100644 index 00000000000..9112ce568c3 --- /dev/null +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.vgdbproj @@ -0,0 +1,277 @@ + + + + + + Unknown + + true + + 35e5525f-318a-466e-a8c7-36548547d801 + true + true + SourceDirs + + + + + + com.visualgdb.xtensa-esp32-elf + + 11.2.0 + 9.2.90 + 2 + + + .. + DEBUG + build/$(PlatformName)/$(ConfigurationName) + + false + $(ToolchainNinja) + $(BuildDir) + + + + false + $(SYSPROGS_CMAKE_PATH) + + + true + false + false + Ninja + false + RemoveBuildDirectory + false + + + true + true + true + false + true + false + true + HideOuterProjectTargets + true + false + true + + + true + eadcc9ab-72b3-4b51-a838-593e5d80ddf7 + + Upper + HeaderDirectoryAndSubdirectories + true + + + master + esp-idf/master + ESPIDF + + COM15 + false + false + ESP32C6 + + + + + + + + + + + + + + + Default + + false + + BuildMachine + BuiltinShortcut + + + + + + + COM9 + + 115200 + 8 + None + One + None + + + 0 + false + true + false + ASCII + + + 255 + 0 + 0 + 0 + + + 255 + 169 + 169 + 169 + + + 255 + 211 + 211 + 211 + + + 255 + 144 + 238 + 144 + + + 255 + 169 + 169 + 169 + + + + 16 + true + true + true + true + 0 + + LF + false + false + false + + + + true + + + + + Unknown + + true + true + true + + + + false + + + + + Debug + + + + Release + + + + + + + + + false + false + false + false + false + false + false + false + false + + false + false + false + false + false + false + true + false + None + false + false + app_main + true + false + false + true + 0 + false + 0 + true + false + + + openocd + + -f interface/esp_usb_jtag_c6.cfg -c "adapter_khz 40000" -f target/esp32c6.cfg + + + + false + + 131072 + Enabled + + set remotetimeout 60 + target remote :$$SYS:GDB_PORT$$ + mon gdb_breakpoint_override hard + mon reset halt + load + + true + 0 + 0 + false + + 5000 + 1 + true + + size2MB + freq40M + DIO + + true + + + true + Disabled + 0 + false + false + true + false + false + + _estack + 0 + false + + true + + \ No newline at end of file diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test.sln b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test_IDF_v5_ESP32S3.sln similarity index 51% rename from IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test.sln rename to IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test_IDF_v5_ESP32S3.sln index 00b1845fc6f..08149805b4c 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test.sln +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test_IDF_v5_ESP32S3.sln @@ -1,21 +1,26 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 -VisualStudioVersion = 16.0.32802.440 +VisualStudioVersion = 16.0.33027.164 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "VisualGDB_wolfssl_test", "VisualGDB_wolfssl_test.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" +Project("{803FD0C6-D64E-4E16-9DC3-1DAEC859A3D2}") = "wolfssl_test_IDF_v5_ESP32S3", "wolfssl_test_IDF_v5_ESP32S3.vgdbproj", "{EADCC9AB-72B3-4B51-A838-593E5D80DDF7}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{35EEC1E7-13AB-4C74-BFCE-22142A10E1C1}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CD9E73EC-27FB-49E4-B3A3-B0502C20A818}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "wolfSSL", "wolfSSL", "{20662F9E-D386-4839-B855-857D7F922C99}" + ProjectSection(SolutionItems) = preProject + ..\components\wolfssl\CMakeLists.txt = ..\components\wolfssl\CMakeLists.txt + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "include", "include", "{89279333-68BD-4E6A-B970-E645967CE5FA}" ProjectSection(SolutionItems) = preProject - ..\..\..\compileAllExamples.sh = ..\..\..\compileAllExamples.sh - README.md = README.md - sdkconfig = sdkconfig - sdkconfig.defaults = sdkconfig.defaults - build\config\sdkconfig.h = build\config\sdkconfig.h - ..\..\..\..\..\wolfcrypt\test\test.c = ..\..\..\..\..\wolfcrypt\test\test.c - ..\..\..\..\..\wolfcrypt\test\test.h = ..\..\..\..\..\wolfcrypt\test\test.h - ..\..\..\..\..\include\user_settings.h = ..\..\..\..\..\include\user_settings.h - ..\..\..\..\..\..\include\user_settings.h = ..\..\..\..\..\..\include\user_settings.h + ..\components\wolfssl\include\config.h = ..\components\wolfssl\include\config.h + ..\components\wolfssl\include\user_settings.h = ..\components\wolfssl\include\user_settings.h + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "lib", "lib", "{E9586E44-7821-4956-9F72-A79B988B3211}" + ProjectSection(SolutionItems) = preProject + ..\..\..\user_settings.h = ..\..\..\user_settings.h EndProjectSection EndProject Global @@ -38,7 +43,12 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {20662F9E-D386-4839-B855-857D7F922C99} = {CD9E73EC-27FB-49E4-B3A3-B0502C20A818} + {89279333-68BD-4E6A-B970-E645967CE5FA} = {20662F9E-D386-4839-B855-857D7F922C99} + {E9586E44-7821-4956-9F72-A79B988B3211} = {CD9E73EC-27FB-49E4-B3A3-B0502C20A818} + EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {A0AC9105-F2CF-44E7-8032-3CD9E77EC9F6} + SolutionGuid = {7F8E1DC0-55AD-4DF8-B65A-CD65B60E17F9} EndGlobalSection EndGlobal diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test-WIP.vgdbproj b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test_IDF_v5_ESP32S3.vgdbproj similarity index 93% rename from IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test-WIP.vgdbproj rename to IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test_IDF_v5_ESP32S3.vgdbproj index 2c1871e9a06..7e49a61dc0a 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test-WIP.vgdbproj +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test_IDF_v5_ESP32S3.vgdbproj @@ -18,9 +18,9 @@ com.visualgdb.xtensa-esp32-elf - 8.4.0 - 8.1.0 - 9 + 11.2.0 + 9.2.90 + 2 .. @@ -67,14 +67,14 @@ true - v4.4.1 - esp-idf/v4.4.1 + release/v5.0 + esp-idf/v5.0 ESPIDF - COM20 + COM17 false false - ESP32 + ESP32S3 @@ -93,7 +93,7 @@ - COM20 + COM17 115200 8 @@ -219,8 +219,10 @@ openocd + esp_usb_jtag + 7C:00:00:00:00:00 - -f interface/tigard.cfg -c "adapter_khz 13000" -f target/esp32.cfg + -f interface/esp_usb_jtag.cfg -f target/esp32s3.cfg diff --git a/IDE/Espressif/include.am b/IDE/Espressif/include.am index 3d0dd43ad6b..bbf104e938e 100644 --- a/IDE/Espressif/include.am +++ b/IDE/Espressif/include.am @@ -17,12 +17,12 @@ EXTRA_DIST+= IDE/Espressif/ESP-IDF/setup_win.bat EXTRA_DIST+= IDE/Espressif/ESP-IDF/UPDATE.md EXTRA_DIST+= IDE/Espressif/ESP-IDF/user_settings.h +# Benchmark EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/main EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/Makefile EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/README.md EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/sdkconfig.defaults -EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/VisualGDB_wolfssl_benchmark.vgdbproj EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/main/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/main/component.mk EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/main/Kconfig.projbuild @@ -31,6 +31,16 @@ EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/main/main.h EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/components/wolfssl/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/components/wolfssl/component.mk +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.sln +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.sln +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.sln +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.sln +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v4.4_ESP32.vgdbproj +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32.vgdbproj +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32C3.vgdbproj +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/VisualGDB/wolfssl_benchmark_IDF_v5_ESP32S3.vgdbproj + +# TLS Client EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_client/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_client/main EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_client/Makefile @@ -46,6 +56,7 @@ EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_client/main/include/wifi_con EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_client/components/wolfssl/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_client/components/wolfssl/component.mk +# TLS Server EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_server/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_server/Makefile EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_server/README.md @@ -59,12 +70,11 @@ EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_server/main/include/wifi_con EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_server/components/wolfssl/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_server/components/wolfssl/component.mk +# wolfSSL Test EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/Makefile EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/README.md EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/sdkconfig.defaults -EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test.vgdbproj -EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/VisualGDB_wolfssl_test_IDF_v5_ESP32S3.vgdbproj EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/main/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/main/component.mk EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/main/Kconfig.projbuild @@ -74,11 +84,22 @@ EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/main/time_helper.h EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/components/wolfssl/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/components/wolfssl/component.mk +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.sln +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.sln +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.sln +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test_IDF_v5_ESP32S3.sln +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32.vgdbproj +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C3.vgdbproj +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test-IDF_v5_ESP32C6.vgdbproj +EXTRA_DIST+= IDE/Espressif/ESP-IDF/examples/wolfssl_test/VisualGDB/wolfssl_test_IDF_v5_ESP32S3.vgdbproj + +# lib files EXTRA_DIST+= IDE/Espressif/ESP-IDF/libs/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/libs/component.mk EXTRA_DIST+= IDE/Espressif/ESP-IDF/libs/README.md EXTRA_DIST+= IDE/Espressif/ESP-IDF/libs/tigard.cfg +# Other test EXTRA_DIST+= IDE/Espressif/ESP-IDF/test/CMakeLists.txt EXTRA_DIST+= IDE/Espressif/ESP-IDF/test/component.mk EXTRA_DIST+= IDE/Espressif/ESP-IDF/test/README.md From 034da7835608a834454a11aa66408dea62de7710 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Tue, 18 Apr 2023 18:41:42 +0200 Subject: [PATCH 152/391] wolfcrypt polish: init, checks, corrections (#6249) * wolfcrypt polish: init, checks, corrections --- wolfcrypt/src/aes.c | 18 ++++++++++++++++++ wolfcrypt/src/asn.c | 8 ++++---- wolfcrypt/src/cmac.c | 8 +++++++- wolfcrypt/src/ed25519.c | 29 +++++++++++++++++++++++------ wolfcrypt/src/md5.c | 7 ++++++- wolfcrypt/src/random.c | 3 +++ wolfcrypt/src/ripemd.c | 6 ++++++ 7 files changed, 67 insertions(+), 12 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 40751e45702..0aebd3bab9b 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -2676,6 +2676,24 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( return BAD_FUNC_ARG; } + #if !defined(WOLFSSL_AES_128) + if (keylen == 16) { + return BAD_FUNC_ARG; + } + #endif + + #if !defined(WOLFSSL_AES_192) + if (keylen == 24) { + return BAD_FUNC_ARG; + } + #endif + + #if !defined(WOLFSSL_AES_256) + if (keylen == 32) { + return BAD_FUNC_ARG; + } + #endif + aes->keylen = keylen; aes->rounds = keylen/4 + 6; diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 440976c0bdd..7d60e5bb0e4 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -19063,7 +19063,7 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) #endif ) { ASNGetData dataASN[policyInfoASN_Length]; - byte* data; + byte* data = NULL; word32 length = 0; /* Clear dynamic data and check OID is a cert policy type. */ @@ -20186,7 +20186,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, /* Check parameters starting with a SEQUENCE. */ else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) { word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum; - word32 sigAlgParamsSz; + word32 sigAlgParamsSz = 0; /* Parameters only with RSA PSS. */ if (oid != CTC_RSASSAPSS) { @@ -29291,9 +29291,9 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, return ret; #else DECL_ASNSETDATA(dataASN, certReqBodyASN_Length); - word32 publicKeySz; + word32 publicKeySz = 0; word32 subjectSz = 0; - word32 extSz; + word32 extSz = 0; int sz = 0; int ret = 0; #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) diff --git a/wolfcrypt/src/cmac.c b/wolfcrypt/src/cmac.c index 24ddcc6355b..db0906c99b5 100644 --- a/wolfcrypt/src/cmac.c +++ b/wolfcrypt/src/cmac.c @@ -216,6 +216,7 @@ int wc_CmacFinal(Cmac* cmac, byte* out, word32* outSz) { int ret; const byte* subKey; + word32 remainder; if (cmac == NULL || out == NULL || outSz == NULL) { return BAD_FUNC_ARG; @@ -237,7 +238,11 @@ int wc_CmacFinal(Cmac* cmac, byte* out, word32* outSz) subKey = cmac->k1; } else { - word32 remainder = AES_BLOCK_SIZE - cmac->bufferSz; + /* ensure we will have a valid remainder value */ + if (cmac->bufferSz > AES_BLOCK_SIZE) { + return BAD_STATE_E; + } + remainder = AES_BLOCK_SIZE - cmac->bufferSz; if (remainder == 0) { remainder = AES_BLOCK_SIZE; @@ -245,6 +250,7 @@ int wc_CmacFinal(Cmac* cmac, byte* out, word32* outSz) if (remainder > 1) { XMEMSET(cmac->buffer + AES_BLOCK_SIZE - remainder, 0, remainder); } + cmac->buffer[AES_BLOCK_SIZE - remainder] = 0x80; subKey = cmac->k2; } diff --git a/wolfcrypt/src/ed25519.c b/wolfcrypt/src/ed25519.c index 5dee270faea..3b9988bc3f2 100644 --- a/wolfcrypt/src/ed25519.c +++ b/wolfcrypt/src/ed25519.c @@ -53,17 +53,29 @@ #endif #if defined(HAVE_ED25519_SIGN) || defined(HAVE_ED25519_VERIFY) -#define ED25519CTX_SIZE 32 + /* Set a static message string for "Sig No Collisions Message SNC". + ** Note this is a static string per spec, see: + ** https://datatracker.ietf.org/doc/rfc8032/ + */ + #define ED25519CTX_SNC_MESSAGE "SigEd25519 no Ed25519 collisions" + #define ED25519CTX_SIZE 32 /* 32 chars: fixed length of SNC Message. */ -static const byte ed25519Ctx[ED25519CTX_SIZE+1] = - "SigEd25519 no Ed25519 collisions"; + /* The 32 bytes of ED25519CTX_SIZE is used elsewhere, but we need one + ** more char for saving the line ending in our ed25519Ctx[] here: */ + static const byte ed25519Ctx[ED25519CTX_SIZE + 1] = ED25519CTX_SNC_MESSAGE; #endif static int ed25519_hash_init(ed25519_key* key, wc_Sha512 *sha) { int ret; +#ifndef WOLFSSL_ED25519_PERSISTENT_SHA + /* when not using persistent SHA, we'll zero the sha param */ + XMEMSET(sha, 0, sizeof(wc_Sha512)); +#endif + ret = wc_InitSha512_ex(sha, key->heap, + #if defined(WOLF_CRYPTO_CB) key->devId #else @@ -334,8 +346,9 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, #else wc_Sha512 sha[1]; ret = ed25519_hash_init(key, sha); - if (ret < 0) + if (ret < 0) { return ret; + } #endif if (type == Ed25519ctx || type == Ed25519ph) { @@ -386,6 +399,7 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, wc_Sha512 *sha = &key->sha; #else wc_Sha512 sha[1]; + ret = ed25519_hash_init(key, sha); if (ret < 0) return ret; @@ -765,9 +779,10 @@ int wc_ed25519_verify_msg_ex(const byte* sig, word32 sigLen, const byte* msg, sha = &key->sha; #else ret = ed25519_hash_init(key, sha); - if (ret < 0) + if (ret < 0) { return ret; -#endif + } +#endif /* WOLFSSL_ED25519_PERSISTENT_SHA */ ret = ed25519_verify_msg_init_with_sha(sig, sigLen, key, sha, type, context, contextLen); @@ -871,7 +886,9 @@ int wc_ed25519_init_ex(ed25519_key* key, void* heap, int devId) if (key == NULL) return BAD_FUNC_ARG; + /* for init, ensure the key is zeroed*/ XMEMSET(key, 0, sizeof(ed25519_key)); + #ifdef WOLF_CRYPTO_CB key->devId = devId; #else diff --git a/wolfcrypt/src/md5.c b/wolfcrypt/src/md5.c index b84ac5d52a9..66296108e9a 100644 --- a/wolfcrypt/src/md5.c +++ b/wolfcrypt/src/md5.c @@ -450,7 +450,12 @@ int wc_Md5Final(wc_Md5* md5, byte* hash) } #endif /* WOLFSSL_ASYNC_CRYPT */ - local = (byte*)md5->buffer; + local = (byte*)md5->buffer; /* buffer allocated in word32 size */ + + /* ensure we have a valid buffer length; (-1 to append a byte to length) */ + if (md5->buffLen > WC_MD5_BLOCK_SIZE - 1) { + return BUFFER_E; + } local[md5->buffLen++] = 0x80; /* add 1 */ diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index f25039b5fba..e445251d17d 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -36,6 +36,9 @@ This library contains implementation for the random number generator. http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=KRNG11I */ +#if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 5 + #include +#endif #if defined(HAVE_FIPS) && \ defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) diff --git a/wolfcrypt/src/ripemd.c b/wolfcrypt/src/ripemd.c index 1fedf67f86e..9402c70beac 100644 --- a/wolfcrypt/src/ripemd.c +++ b/wolfcrypt/src/ripemd.c @@ -324,6 +324,12 @@ int wc_RipeMdFinal(RipeMd* ripemd, byte* hash) AddLength(ripemd, ripemd->buffLen); /* before adding pads */ + /* ensure we have a valid buffer length; */ + if (ripemd->buffLen > RIPEMD_BLOCK_SIZE) { + /* exit with error code if there's a bad buffer size in buffLen */ + return BAD_STATE_E; + } /* buffLen check */ + local[ripemd->buffLen++] = 0x80; /* add 1 */ /* pad with zeros */ From b403a02238dba098337e1304076dc8cf0b45b0cc Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 17 Apr 2023 11:00:37 +1000 Subject: [PATCH 153/391] ECC: wc_ecc_is_point - validate parameters Public API wc_ecc_is_point() needs to validate the parameters. Ensure that the x and y are in range [0, p-1] and z is one (affine ordinates). Made the API a wrapper around existing calculation code. When x-ordinate is a large negative, then it will spend large amounts of time adding the prime to a large negative intermediate value. --- wolfcrypt/src/ecc.c | 64 +++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 1fa6370eea9..3445c40232b 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -4925,22 +4925,6 @@ int wc_ecc_point_is_on_curve(ecc_point *p, int curve_idx) ECC_CURVE_FIELD_BF); } - /* x must be in the range [0, p-1] */ - if (err == MP_OKAY) { - if (mp_cmp(p->x, curve->prime) != MP_LT) - err = ECC_OUT_OF_RANGE_E; - } - /* y must be in the range [0, p-1] */ - if (err == MP_OKAY) { - if (mp_cmp(p->y, curve->prime) != MP_LT) - err = ECC_OUT_OF_RANGE_E; - } - /* z must be 1 */ - if (err == MP_OKAY) { - if (!mp_isone(p->z)) - err = ECC_BAD_ARG_E; - } - if (err == MP_OKAY) { err = wc_ecc_is_point(p, curve->Af, curve->Bf, curve->prime); } @@ -9283,7 +9267,7 @@ int wc_ecc_export_x963_ex(ecc_key* key, byte* out, word32* outLen, !defined(WOLF_CRYPTO_CB_ONLY_ECC) && !defined(WOLFSSL_STM32_PKA) /* is ecc point on curve described by dp ? */ -int wc_ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime) +static int _ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime) { #if !defined(WOLFSSL_SP_MATH) int err; @@ -9419,6 +9403,44 @@ int wc_ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime) #endif } +int wc_ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime) +{ + int err = MP_OKAY; + + /* Validate parameters. */ + if ((ecp == NULL) || (a == NULL) || (b == NULL) || (prime == NULL)) { + err = BAD_FUNC_ARG; + } + + if (err == MP_OKAY) { + /* x must be in the range [0, p-1] */ + if ((mp_cmp(ecp->x, prime) != MP_LT) || mp_isneg(ecp->x)) { + err = ECC_OUT_OF_RANGE_E; + } + } + + if (err == MP_OKAY) { + /* y must be in the range [0, p-1] */ + if ((mp_cmp(ecp->y, prime) != MP_LT) || mp_isneg(ecp->y)) { + err = ECC_OUT_OF_RANGE_E; + } + } + + if (err == MP_OKAY) { + /* z must be one, that is point must be in affine form. */ + if (!mp_isone(ecp->z)) { + err = ECC_BAD_ARG_E; + } + } + + if (err == MP_OKAY) { + /* Check x and y are valid for curve equation. */ + err = _ecc_is_point(ecp, a, b, prime); + } + + return err; +} + #if (FIPS_VERSION_GE(5,0) || defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || \ (defined(WOLFSSL_VALIDATE_ECC_IMPORT) && !defined(WOLFSSL_SP_MATH))) && \ !defined(WOLFSSL_KCAPI_ECC) || defined(WOLFSSL_CAAM) @@ -9889,14 +9911,16 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) /* SP 800-56Ar3, section 5.6.2.3.4, process step 2 */ /* Qx must be in the range [0, p-1] */ if (err == MP_OKAY) { - if (mp_cmp(key->pubkey.x, curve->prime) != MP_LT) { + if ((mp_cmp(key->pubkey.x, curve->prime) != MP_LT) || + mp_isneg(key->pubkey.x)) { err = ECC_OUT_OF_RANGE_E; } } /* Qy must be in the range [0, p-1] */ if (err == MP_OKAY) { - if (mp_cmp(key->pubkey.y, curve->prime) != MP_LT) { + if ((mp_cmp(key->pubkey.y, curve->prime) != MP_LT) || + mp_isneg(key->pubkey.y)) { err = ECC_OUT_OF_RANGE_E; } } @@ -9905,7 +9929,7 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) /* SP 800-56Ar3, section 5.6.2.3.4, process step 3 */ /* make sure point is actually on curve */ if (err == MP_OKAY) - err = wc_ecc_is_point(&key->pubkey, curve->Af, b, curve->prime); + err = _ecc_is_point(&key->pubkey, curve->Af, b, curve->prime); if (!partial) { /* SP 800-56Ar3, section 5.6.2.3.3, process step 4 */ From 3b44f4b1b3b275bd9d0c34622b7dda78c3c2331d Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 17 Apr 2023 11:34:27 +1000 Subject: [PATCH 154/391] ECC, ASN.1: DecodeECC_DSA_Sig didn't handle r and s being initialized New creation of mp_ints r and s to be minimal size must not be re-initialized. Changes to ASN.1 code to handle r and s being initialized and to not initialize again. --- wolfcrypt/src/asn.c | 44 +++++++++++++++++++++++++++++++++-------- wolfcrypt/src/ecc.c | 7 ++++++- wolfssl/wolfcrypt/asn.h | 20 +++++++++++++++++-- 3 files changed, 60 insertions(+), 11 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 7d60e5bb0e4..3268981705a 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -1202,6 +1202,8 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, #endif return MP_INIT_E; } + FALL_THROUGH; + case ASN_DATA_TYPE_MP_INITED: err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx, (word32)len); if (err != 0) { @@ -1532,7 +1534,8 @@ int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete, if (asn[i].tag == ASN_INTEGER) { /* Check validity of first byte. */ err = GetASN_Integer(input, idx, len, - data[i].dataType == ASN_DATA_TYPE_MP); + data[i].dataType == ASN_DATA_TYPE_MP || + data[i].dataType == ASN_DATA_TYPE_MP_INITED); if (err != 0) return err; if (len > 1 && input[idx] == 0) { @@ -1864,6 +1867,17 @@ void GetASN_MP(ASNGetData *dataASN, mp_int* num) dataASN->data.mp = num; } +/* Setup ASN data item to get a number into an mp_int that is initialized. + * + * @param [in] dataASN Dynamic ASN data item. + * @param [in] num Multi-precision number object. + */ +void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num) +{ + dataASN->dataType = ASN_DATA_TYPE_MP_INITED; + dataASN->data.mp = num; +} + /* Setup ASN data item to get a positive or negative number into an mp_int. * * @param [in] dataASN Dynamic ASN data item. @@ -3239,7 +3253,7 @@ int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx) #if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE) static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx, - word32 maxIdx) + word32 maxIdx, int initNum) { word32 idx = *inOutIdx; int ret; @@ -3252,8 +3266,10 @@ static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx, if (((input[idx] & 0x80) == 0x80) && (input[idx - 1] != 0x00)) return MP_INIT_E; - if (mp_init(mpi) != MP_OKAY) - return MP_INIT_E; + if (initNum) { + if (mp_init(mpi) != MP_OKAY) + return MP_INIT_E; + } if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) { mp_clear(mpi); @@ -31206,6 +31222,12 @@ int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen, } int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s) +{ + return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1); +} + +int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s, + int init) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; @@ -31227,11 +31249,11 @@ int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s) } #endif - if (GetIntPositive(r, sig, &idx, sigLen) < 0) { + if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) { return ASN_ECC_KEY_E; } - if (GetIntPositive(s, sig, &idx, sigLen) < 0) { + if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) { mp_clear(r); return ASN_ECC_KEY_E; } @@ -31254,8 +31276,14 @@ int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s) /* Clear dynamic data and set mp_ints to put r and s into. */ XMEMSET(dataASN, 0, sizeof(dataASN)); - GetASN_MP(&dataASN[DSASIGASN_IDX_R], r); - GetASN_MP(&dataASN[DSASIGASN_IDX_S], s); + if (init) { + GetASN_MP(&dataASN[DSASIGASN_IDX_R], r); + GetASN_MP(&dataASN[DSASIGASN_IDX_S], s); + } + else { + GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r); + GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s); + } /* Decode the DSA signature. */ ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx, diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 3445c40232b..3e5341f0a79 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -8018,12 +8018,17 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, /* default to invalid signature */ *res = 0; + /* Decode ASN.1 ECDSA signature. */ + #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) /* Note, DecodeECC_DSA_Sig() calls mp_init() on r and s. * If either of those don't allocate correctly, none of * the rest of this function will execute, and everything * gets cleaned up at the end. */ - /* decode DSA header */ err = DecodeECC_DSA_Sig(sig, siglen, r, s); + #else + /* r and s are initialized. */ + err = DecodeECC_DSA_Sig_Ex(sig, siglen, r, s, 0); + #endif if (err < 0) { break; } diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 13631843001..39a95096bc8 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -185,10 +185,12 @@ enum ASNItem_DataType { ASN_DATA_TYPE_REPLACE_BUFFER = 7, /* Big number as an mp_int. */ ASN_DATA_TYPE_MP = 8, + /* Big number as an mp_int that has already been initialized. */ + ASN_DATA_TYPE_MP_INITED = 9, /* Big number as a positive or negative mp_int. */ - ASN_DATA_TYPE_MP_POS_NEG = 9, + ASN_DATA_TYPE_MP_POS_NEG = 10, /* ASN.1 CHOICE. A 0 terminated list of tags that are valid. */ - ASN_DATA_TYPE_CHOICE = 10 + ASN_DATA_TYPE_CHOICE = 11 }; /* A template entry describing an ASN.1 item. */ @@ -311,6 +313,7 @@ WOLFSSL_LOCAL void GetASN_Buffer(ASNGetData *dataASN, byte* data, WOLFSSL_LOCAL void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length); WOLFSSL_LOCAL void GetASN_MP(ASNGetData *dataASN, mp_int* num); +WOLFSSL_LOCAL void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num); WOLFSSL_LOCAL void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num); WOLFSSL_LOCAL void GetASN_Choice(ASNGetData *dataASN, const byte* options); WOLFSSL_LOCAL void GetASN_Boolean(ASNGetData *dataASN, byte* num); @@ -401,6 +404,17 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); (dataASN)->data.mp = num; \ } while (0) +/* Setup ASN data item to get a number into an mp_int that is initialized. + * + * @param [in] dataASN Dynamic ASN data item. + * @param [in] num Multi-precision number object. + */ +#define GetASN_MP_Inited(dataASN, num) \ + do { \ + (dataASN)->dataType = ASN_DATA_TYPE_MP_INITED; \ + (dataASN)->data.mp = num; \ + } while (0) + /* Setup ASN data item to get a positive or negative number into an mp_int. * * @param [in] dataASN Dynamic ASN data item. @@ -2201,6 +2215,8 @@ WOLFSSL_LOCAL int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr, byte* r, word32* rLen, byte* s, word32* sLen); WOLFSSL_LOCAL int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s); + WOLFSSL_LOCAL int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, + mp_int* r, mp_int* s, int init); #endif #ifndef NO_DSA WOLFSSL_LOCAL int StoreDSAParams(byte*, word32*, const mp_int*, const mp_int*, From 4df4a5d9ab5d87c43fa4a1c4ab304c1b9c9844db Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 17 Apr 2023 11:40:21 +1000 Subject: [PATCH 155/391] SP int: sp_mod check sp_div error before adding and replacing error Fix to not overwrite error when sp_div fails in sp_mod. --- wolfcrypt/src/sp_int.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 6198e7c7414..d07e2720976 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -8434,7 +8434,7 @@ int sp_mod(const sp_int* a, const sp_int* m, sp_int* r) #else if ((err == MP_OKAY) && (r != m)) { err = sp_div(a, m, NULL, r); - if ((!sp_iszero(r)) && (r->sign != m->sign)) { + if ((err == MP_OKAY) && (!sp_iszero(r)) && (r->sign != m->sign)) { err = sp_add(r, m, r); } } From e9e5d5a420bf7e0aadf2cbc2b544fc4dec602eb1 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Tue, 18 Apr 2023 16:51:36 -0400 Subject: [PATCH 156/391] Instructions for GPDMA configuration --- IDE/STM32Cube/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/IDE/STM32Cube/README.md b/IDE/STM32Cube/README.md index 3ba49fc9a54..8689b9e34a8 100644 --- a/IDE/STM32Cube/README.md +++ b/IDE/STM32Cube/README.md @@ -172,6 +172,8 @@ The TLS v1.3 client/server examples over UART are paired with these host-side ap To use this example you will need to use the STM32Cube interface to enable an additional USART and enable DMA for the RX with defaults. Enabling DMA for the USART requires adding the USART RX DMA in the STM32Cube tool. Under Connectivity click on your TLS USART# and goto DMA Settings and "Add" one for USART#_RX with default options. +On some boards, such as U5, there is GPDMA support. In this case when you click on "DMA Settings" you will be given a button to take you to GPDMA1 configuration. Click it. You can then enable a channel (any of the ones from 0 to 11 should be fine.) as "Standard Request Mode" and set the "Request Configuration" section's "Request" to USART#_RX. In the "System Core" tab, find NVIC and click on it. Make sure that the GPDMA1 global interrupt for your channel is enabled as well as USARTx global interrupt. + Then set the TLS_UART macro to the correct `huart#` instance. This USART will be used as a TLS transport. ```c From d677be51803842597a64ab1bc154ccf1db2a0e2f Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Fri, 7 Apr 2023 09:54:59 -0400 Subject: [PATCH 157/391] Add in instructions for compiling with zephyr on STM32. --- zephyr/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/zephyr/CMakeLists.txt b/zephyr/CMakeLists.txt index 586d0673487..cb9bb5c645d 100644 --- a/zephyr/CMakeLists.txt +++ b/zephyr/CMakeLists.txt @@ -110,6 +110,7 @@ if(CONFIG_WOLFSSL) zephyr_library_sources(${ZEPHYR_CURRENT_MODULE_DIR}/wolfcrypt/src/port/psa/psa_aes.c) zephyr_library_sources(${ZEPHYR_CURRENT_MODULE_DIR}/wolfcrypt/src/port/psa/psa_hash.c) zephyr_library_sources(${ZEPHYR_CURRENT_MODULE_DIR}/wolfcrypt/src/port/psa/psa_pkcbs.c) + zephyr_library_sources(${ZEPHYR_CURRENT_MODULE_DIR}/wolfcrypt/src/port/st/stm32.c) zephyr_library_link_libraries(wolfSSL) From 7e0c5f865a0b6a404bf1fa1e64e45bb02311f730 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Sat, 15 Apr 2023 00:29:01 -0500 Subject: [PATCH 158/391] wolfssl/wolfcrypt/asn_public.h: fix version threshold for wc_RsaPrivateKeyValidate() prototype. --- wolfssl/wolfcrypt/asn_public.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index 91b64323f3e..cbe60b8f03c 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -695,7 +695,7 @@ WOLFSSL_API void wc_FreeDer(DerBuffer** pDer); /* For FIPS v1/v2 and selftest rsa.h is replaced. */ #if defined(HAVE_SELFTEST) || (defined(HAVE_FIPS) && \ - (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION <= 5))) + (!defined(HAVE_FIPS_VERSION) || (FIPS_VERSION_LE(5,2)))) WOLFSSL_API int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz, word32 inSz); #endif From 887877939fc7c35cdbaafc0cef76a36da3324981 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Sat, 15 Apr 2023 00:31:17 -0500 Subject: [PATCH 159/391] wolfssl/wolfcrypt/misc.h: add missing argument names in NO_INLINE path. --- wolfssl/wolfcrypt/misc.h | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/wolfssl/wolfcrypt/misc.h b/wolfssl/wolfcrypt/misc.h index f39352826a5..418246787ef 100644 --- a/wolfssl/wolfcrypt/misc.h +++ b/wolfssl/wolfcrypt/misc.h @@ -42,48 +42,48 @@ masking and clearing memory logic. #define WC_MISC_STATIC WOLFSSL_LOCAL -word32 rotlFixed(word32, word32); +word32 rotlFixed(word32 x, word32 y); WOLFSSL_LOCAL -word32 rotrFixed(word32, word32); +word32 rotrFixed(word32 x, word32 y); #ifdef WC_RC2 WOLFSSL_LOCAL -word16 rotlFixed16(word16, word16); +word16 rotlFixed16(word16 x, word16 y); WOLFSSL_LOCAL -word16 rotrFixed16(word16, word16); +word16 rotrFixed16(word16 x, word16 y); #endif WOLFSSL_LOCAL -word32 ByteReverseWord32(word32); +word32 ByteReverseWord32(word32 value); WOLFSSL_LOCAL -void ByteReverseWords(word32*, const word32*, word32); +void ByteReverseWords(word32* out, const word32* in, word32 byteCount); WOLFSSL_LOCAL void XorWordsOut(wolfssl_word* r, const wolfssl_word* a, const wolfssl_word* b, word32 n); WOLFSSL_LOCAL -void xorbufout(void*, const void*, const void*, word32); +void xorbufout(void* out, const void* buf, const void* mask, word32 count); WOLFSSL_LOCAL -void XorWords(wolfssl_word*, const wolfssl_word*, word32); +void XorWords(wolfssl_word* r, const wolfssl_word* a, word32 n); WOLFSSL_LOCAL -void xorbuf(void*, const void*, word32); +void xorbuf(void* buf, const void* mask, word32 count); WOLFSSL_LOCAL -void ForceZero(void*, word32); +void ForceZero(void* mem, word32 len); WOLFSSL_LOCAL -int ConstantCompare(const byte*, const byte*, int); +int ConstantCompare(const byte* a, const byte* b, int length); #ifdef WORD64_AVAILABLE WOLFSSL_LOCAL -word64 rotlFixed64(word64, word64); +word64 rotlFixed64(word64 x, word64 y); WOLFSSL_LOCAL -word64 rotrFixed64(word64, word64); +word64 rotrFixed64(word64 x, word64 y); WOLFSSL_LOCAL -word64 ByteReverseWord64(word64); +word64 ByteReverseWord64(word64 value); WOLFSSL_LOCAL -void ByteReverseWords64(word64*, const word64*, word32); +void ByteReverseWords64(word64* out, const word64* in, word32 byteCount); #endif /* WORD64_AVAILABLE */ #ifndef WOLFSSL_HAVE_MIN From 11e93ee00308f4ffa4a22261b6e24944795d5304 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Sat, 15 Apr 2023 00:33:15 -0500 Subject: [PATCH 160/391] wolfssl/wolfcrypt/sp_int.h: fix a missed bugprone-macro-parentheses in the C89 path. --- wolfssl/wolfcrypt/sp_int.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index 5eb845f8983..57fb901e664 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -815,7 +815,7 @@ while (0) /* Declare a dynamically allocated mp_int. */ #define DECL_MP_INT_SIZE_DYN(name, bits, max) \ unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(max))]; \ - sp_int* name = (sp_int*)name##d + sp_int* (name) = (sp_int*)name##d #endif /* Declare a statically allocated mp_int. */ #define DECL_MP_INT_SIZE(name, bits) \ From 75041f90ccede7675a0ec1badbbbee519deffc19 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Sat, 15 Apr 2023 00:36:22 -0500 Subject: [PATCH 161/391] fix several more C89 "comma at end of enumerator list" spots in 64-bit-only headers, missed in earlier passes; in tests/unit.h, add a WOLF_C89 definition of AssertPtr() without pragmas, to avoid a -Wdeclaration-after-statement. --- tests/unit.h | 12 ++++++++++++ wolfssl/wolfcrypt/ed25519.h | 4 ++-- wolfssl/wolfcrypt/ed448.h | 2 +- wolfssl/wolfcrypt/sha3.h | 2 ++ wolfssl/wolfcrypt/sha512.h | 2 +- 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/tests/unit.h b/tests/unit.h index 24e439771cd..1801df4dd01 100644 --- a/tests/unit.h +++ b/tests/unit.h @@ -88,6 +88,16 @@ #define AssertStrGE(x, y) AssertStr(x, y, >=, <) #define AssertStrLE(x, y) AssertStr(x, y, <=, >) +#ifdef WOLF_C89 + +#define AssertPtr(x, y, op, er) do { \ + void* _x = (void*)(x); \ + void* _y = (void*)(y); \ + Assert(_x op _y, ("%s " #op " %s", #x, #y), ("%p " #er " %p", _x, _y)); \ +} while(0) + +#else + #define AssertPtr(x, y, op, er) do { \ PRAGMA_GCC_DIAG_PUSH; \ /* remarkably, without this inhibition, */ \ @@ -102,6 +112,8 @@ PRAGMA_GCC_DIAG_POP; \ } while(0) +#endif + #define AssertPtrEq(x, y) AssertPtr(x, y, ==, !=) #define AssertPtrNE(x, y) AssertPtr(x, y, !=, ==) #define AssertPtrGT(x, y) AssertPtr(x, y, >, <=) diff --git a/wolfssl/wolfcrypt/ed25519.h b/wolfssl/wolfcrypt/ed25519.h index 298e876bef4..8306f44b17f 100644 --- a/wolfssl/wolfcrypt/ed25519.h +++ b/wolfssl/wolfcrypt/ed25519.h @@ -69,7 +69,7 @@ enum { Ed25519 = -1, Ed25519ctx = 0, - Ed25519ph = 1, + Ed25519ph = 1 }; #ifndef WC_ED25519KEY_TYPE_DEFINED @@ -80,7 +80,7 @@ enum { /* ED25519 Flags */ enum { WC_ED25519_FLAG_NONE = 0x00, - WC_ED25519_FLAG_DEC_SIGN = 0x01, + WC_ED25519_FLAG_DEC_SIGN = 0x01 }; /* An ED25519 Key */ diff --git a/wolfssl/wolfcrypt/ed448.h b/wolfssl/wolfcrypt/ed448.h index b9fa35f6164..a5845fbe3d9 100644 --- a/wolfssl/wolfcrypt/ed448.h +++ b/wolfssl/wolfcrypt/ed448.h @@ -69,7 +69,7 @@ enum { Ed448 = 0, - Ed448ph = 1, + Ed448ph = 1 }; #ifndef WC_ED448KEY_TYPE_DEFINED diff --git a/wolfssl/wolfcrypt/sha3.h b/wolfssl/wolfcrypt/sha3.h index 571aaa0692c..2b9283a03eb 100644 --- a/wolfssl/wolfcrypt/sha3.h +++ b/wolfssl/wolfcrypt/sha3.h @@ -78,6 +78,8 @@ enum { WC_SHA3_384_BLOCK_SIZE = 104, WC_SHA3_512_BLOCK_SIZE = 72, #endif + + WOLF_ENUM_DUMMY_LAST_ELEMENT(WC_SHA3) }; #ifndef NO_OLD_WC_NAMES diff --git a/wolfssl/wolfcrypt/sha512.h b/wolfssl/wolfcrypt/sha512.h index 4011c7df52b..6338700d204 100644 --- a/wolfssl/wolfcrypt/sha512.h +++ b/wolfssl/wolfcrypt/sha512.h @@ -140,7 +140,7 @@ enum { WC_SHA512_256_BLOCK_SIZE = WC_SHA512_BLOCK_SIZE, WC_SHA512_256_DIGEST_SIZE = 32, - WC_SHA512_256_PAD_SIZE = WC_SHA512_PAD_SIZE, + WC_SHA512_256_PAD_SIZE = WC_SHA512_PAD_SIZE }; From 013b67b1cbfc3143965955501bf13acdb838c0ad Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Sat, 15 Apr 2023 02:12:25 -0500 Subject: [PATCH 162/391] another batch of -Wconversion fixes. --- wolfcrypt/src/aes.c | 94 +++++++++++++++++++------------------- wolfcrypt/src/asn.c | 21 +++++---- wolfcrypt/src/cmac.c | 2 +- wolfcrypt/src/des3.c | 2 +- wolfcrypt/src/dh.c | 45 +++++++++--------- wolfcrypt/src/poly1305.c | 18 ++++---- wolfcrypt/src/sha3.c | 4 +- wolfcrypt/src/sha512.c | 4 +- wolfcrypt/src/siphash.c | 4 +- wolfcrypt/src/wc_encrypt.c | 29 ++++++------ wolfcrypt/src/wc_port.c | 17 ++++--- wolfssl/wolfcrypt/sp_int.h | 5 ++ 12 files changed, 131 insertions(+), 114 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 0aebd3bab9b..c40e49bec72 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -4483,7 +4483,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #if defined(HAVE_AES_ECB) && !defined(WOLFSSL_PIC32MZ_CRYPT) && \ !defined(XTRANSFORM_AESCTRBLOCK) if (in != out && sz >= AES_BLOCK_SIZE) { - int blocks = sz / AES_BLOCK_SIZE; + word32 blocks = sz / AES_BLOCK_SIZE; byte* counter = (byte*)aes->reg; byte* c = out; while (blocks--) { @@ -4646,14 +4646,14 @@ static WC_INLINE void FlattenSzInBits(byte* buf, word32 sz) sz <<= 3; /* copy over the words of the sz into the destination buffer */ - buf[0] = (szHi >> 24) & 0xff; - buf[1] = (szHi >> 16) & 0xff; - buf[2] = (szHi >> 8) & 0xff; - buf[3] = szHi & 0xff; - buf[4] = (sz >> 24) & 0xff; - buf[5] = (sz >> 16) & 0xff; - buf[6] = (sz >> 8) & 0xff; - buf[7] = sz & 0xff; + buf[0] = (byte)(szHi >> 24); + buf[1] = (byte)(szHi >> 16); + buf[2] = (byte)(szHi >> 8); + buf[3] = (byte)szHi; + buf[4] = (byte)(sz >> 24); + buf[5] = (byte)(sz >> 16); + buf[6] = (byte)(sz >> 8); + buf[7] = (byte)sz; } @@ -5386,7 +5386,7 @@ static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE]) z8[1] ^= m8[1]; /* Cache top byte for remainder calculations - lost in rotate. */ - a = z8[1] >> 56; + a = (byte)(z8[1] >> 56); /* Rotate Z by 8-bits */ z8[1] = (z8[0] >> 56) | (z8[1] << 8); @@ -8555,7 +8555,7 @@ int wc_AesGcmDecryptFinal(Aes* aes, const byte* authTag, word32 authTagSz) ret = AesGcmFinal_C(aes, calcTag, authTagSz); if (ret == 0) { /* Check calculated tag matches the one passed in. */ - if (ConstantCompare(authTag, calcTag, authTagSz) != 0) { + if (ConstantCompare(authTag, calcTag, (int)authTagSz) != 0) { ret = AES_GCM_AUTH_E; } } @@ -8988,22 +8988,22 @@ static WARN_UNUSED_RESULT int roll_auth( /* encode the length in */ if (inSz <= 0xFEFF) { authLenSz = 2; - out[0] ^= ((inSz & 0xFF00) >> 8); - out[1] ^= (inSz & 0x00FF); + out[0] ^= (byte)(inSz >> 8); + out[1] ^= (byte)inSz; } - else if (inSz <= 0xFFFFFFFF) { + else { authLenSz = 6; - out[0] ^= 0xFF; out[1] ^= 0xFE; - out[2] ^= ((inSz & 0xFF000000) >> 24); - out[3] ^= ((inSz & 0x00FF0000) >> 16); - out[4] ^= ((inSz & 0x0000FF00) >> 8); - out[5] ^= (inSz & 0x000000FF); + out[0] ^= 0xFF; + out[1] ^= 0xFE; + out[2] ^= (byte)(inSz >> 24); + out[3] ^= (byte)(inSz >> 16); + out[4] ^= (byte)(inSz >> 8); + out[5] ^= (byte)inSz; } /* Note, the protocol handles auth data up to 2^64, but we are * using 32-bit sizes right now, so the bigger data isn't handled - * else if (inSz <= 0xFFFFFFFFFFFFFFFF) {} */ - else - return BAD_LENGTH_E; + * else {} + */ /* start fill out the rest of the first block */ remainder = AES_BLOCK_SIZE - authLenSz; @@ -9104,7 +9104,7 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, return BAD_FUNC_ARG; /* sanity check on tag size */ - if (wc_AesCcmCheckTagSize(authTagSz) != 0) { + if (wc_AesCcmCheckTagSize((int)authTagSz) != 0) { return BAD_FUNC_ARG; } @@ -9122,13 +9122,13 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, XMEMSET(A, 0, sizeof(A)); XMEMCPY(B+1, nonce, nonceSz); lenSz = AES_BLOCK_SIZE - 1 - (byte)nonceSz; - B[0] = (authInSz > 0 ? 64 : 0) - + (8 * (((byte)authTagSz - 2) / 2)) - + (lenSz - 1); + B[0] = (byte)((authInSz > 0 ? 64 : 0) + + (8 * (((byte)authTagSz - 2) / 2)) + + (lenSz - 1)); for (i = 0; i < lenSz; i++) { if (mask && i >= wordSz) mask = 0x00; - B[AES_BLOCK_SIZE - 1 - i] = (inSz >> ((8 * i) & mask)) & mask; + B[AES_BLOCK_SIZE - 1 - i] = (byte)((inSz >> ((8 * i) & mask)) & mask); } #ifdef WOLFSSL_CHECK_MEM_ZERO @@ -9283,7 +9283,7 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, return BAD_FUNC_ARG; /* sanity check on tag size */ - if (wc_AesCcmCheckTagSize(authTagSz) != 0) { + if (wc_AesCcmCheckTagSize((int)authTagSz) != 0) { return BAD_FUNC_ARG; } @@ -9385,13 +9385,13 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, o = out; oSz = inSz; - B[0] = (authInSz > 0 ? 64 : 0) - + (8 * (((byte)authTagSz - 2) / 2)) - + (lenSz - 1); + B[0] = (byte)((authInSz > 0 ? 64 : 0) + + (8 * (((byte)authTagSz - 2) / 2)) + + (lenSz - 1)); for (i = 0; i < lenSz; i++) { if (mask && i >= wordSz) mask = 0x00; - B[AES_BLOCK_SIZE - 1 - i] = (inSz >> ((8 * i) & mask)) & mask; + B[AES_BLOCK_SIZE - 1 - i] = (byte)((inSz >> ((8 * i) & mask)) & mask); } ret = wc_AesEncrypt(aes, B, A); @@ -9445,7 +9445,7 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, } xorbuf(A, B, authTagSz); - if (ConstantCompare(A, authTag, authTagSz) != 0) { + if (ConstantCompare(A, authTag, (int)authTagSz) != 0) { /* If the authTag check fails, don't keep the decrypted data. * Unfortunately, you need the decrypted data to calculate the * check value. */ @@ -9626,7 +9626,7 @@ int wc_AesInit_Id(Aes* aes, unsigned char* id, int len, void* heap, int devId) if (ret == 0) ret = wc_AesInit(aes, heap, devId); if (ret == 0) { - XMEMCPY(aes->id, id, len); + XMEMCPY(aes->id, id, (size_t)len); aes->idLen = len; aes->labelLen = 0; } @@ -9637,12 +9637,12 @@ int wc_AesInit_Id(Aes* aes, unsigned char* id, int len, void* heap, int devId) int wc_AesInit_Label(Aes* aes, const char* label, void* heap, int devId) { int ret = 0; - int labelLen = 0; + size_t labelLen = 0; if (aes == NULL || label == NULL) ret = BAD_FUNC_ARG; if (ret == 0) { - labelLen = (int)XSTRLEN(label); + labelLen = XSTRLEN(label); if (labelLen == 0 || labelLen > AES_MAX_LABEL_LEN) ret = BUFFER_E; } @@ -9651,7 +9651,7 @@ int wc_AesInit_Label(Aes* aes, const char* label, void* heap, int devId) ret = wc_AesInit(aes, heap, devId); if (ret == 0) { XMEMCPY(aes->label, label, labelLen); - aes->labelLen = labelLen; + aes->labelLen = (int)labelLen; aes->idLen = 0; } @@ -10032,7 +10032,7 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackDecrypt( #ifdef WOLFSSL_AES_CFB /* check if more input needs copied over to aes->reg */ if (aes->left && sz && mode == AES_CFB_MODE) { - int size = min(aes->left, sz); + word32 size = min(aes->left, sz); XMEMCPY((byte*)aes->reg + AES_BLOCK_SIZE - aes->left, in, size); } #endif @@ -10155,7 +10155,7 @@ static void shiftLeftArray(byte* ary, byte shift) for (i = 0; i < AES_BLOCK_SIZE - 1; i++) { byte carry = ary[i+1] & (0XFF << (WOLFSSL_BIT_SIZE - shift)); carry >>= (WOLFSSL_BIT_SIZE - shift); - ary[i] = (ary[i] << shift) + carry; + ary[i] = (byte)((ary[i] << shift) + carry); } ary[i] = ary[i] << shift; } @@ -10400,11 +10400,11 @@ int wc_AesOfbDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) /* Initialize key wrap counter with value */ static WC_INLINE void InitKeyWrapCounter(byte* inOutCtr, word32 value) { - int i; + word32 i; word32 bytes; bytes = sizeof(word32); - for (i = 0; i < (int)sizeof(word32); i++) { + for (i = 0; i < sizeof(word32); i++) { inOutCtr[i+sizeof(word32)] = (value >> ((bytes - 1) * 8)) & 0xFF; bytes--; } @@ -10495,7 +10495,7 @@ int wc_AesKeyWrap_ex(Aes *aes, const byte* in, word32 inSz, byte* out, /* C[0] = A */ XMEMCPY(out, tmp, KEYWRAP_BLOCK_SIZE); - return inSz + KEYWRAP_BLOCK_SIZE; + return (int)(inSz + KEYWRAP_BLOCK_SIZE); } /* perform AES key wrap (RFC3394), return out sz on success, negative on err */ @@ -10611,7 +10611,7 @@ int wc_AesKeyUnWrap_ex(Aes *aes, const byte* in, word32 inSz, byte* out, if (XMEMCMP(tmp, expIv, KEYWRAP_BLOCK_SIZE) != 0) return BAD_KEYWRAP_IV_E; - return inSz - KEYWRAP_BLOCK_SIZE; + return (int)(inSz - KEYWRAP_BLOCK_SIZE); } int wc_AesKeyUnWrap(const byte* key, word32 keySz, const byte* in, word32 inSz, @@ -10809,7 +10809,7 @@ static WARN_UNUSED_RESULT int _AesXtsHelper( byte tmpC; tmpC = (pt[j] >> 7) & 0x01; - pt[j+AES_BLOCK_SIZE] = ((pt[j] << 1) + carry) & 0xFF; + pt[j+AES_BLOCK_SIZE] = (byte)((pt[j] << 1) + carry); carry = tmpC; } if (carry) { @@ -10912,7 +10912,7 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, byte tmpC; tmpC = (tmp[j] >> 7) & 0x01; - tmp[j] = ((tmp[j] << 1) + carry) & 0xFF; + tmp[j] = (byte)((tmp[j] << 1) + carry); carry = tmpC; } if (carry) { @@ -11049,7 +11049,7 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, byte tmpC; tmpC = (tmp[j] >> 7) & 0x01; - tmp[j] = ((tmp[j] << 1) + carry) & 0xFF; + tmp[j] = (byte)((tmp[j] << 1) + carry); carry = tmpC; } if (carry) { @@ -11073,7 +11073,7 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, byte tmpC; tmpC = (tmp[j] >> 7) & 0x01; - tmp2[j] = ((tmp[j] << 1) + carry) & 0xFF; + tmp2[j] = (byte)((tmp[j] << 1) + carry); carry = tmpC; } if (carry) { diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 3268981705a..d4f03bbeff0 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -11318,21 +11318,23 @@ static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx, ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL); if (ret == 0) { #ifdef HAVE_OCSP - ret = CalcHashId(source + *srcIdx, length, cert->subjectKeyHash); + ret = CalcHashId(source + *srcIdx, (word32)length, + cert->subjectKeyHash); } if (ret == 0) { #endif - publicKey = (byte*)XMALLOC(length, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY); + publicKey = (byte*)XMALLOC((size_t)length, cert->heap, + DYNAMIC_TYPE_PUBLIC_KEY); if (publicKey == NULL) { ret = MEMORY_E; } else { - XMEMCPY(publicKey, &source[*srcIdx], length); + XMEMCPY(publicKey, &source[*srcIdx], (size_t)length); cert->publicKey = publicKey; cert->pubKeyStored = 1; - cert->pubKeySize = length; + cert->pubKeySize = (word32)length; - *srcIdx += length; + *srcIdx += (word32)length; } } @@ -26708,7 +26710,8 @@ static int EncodePublicKey(int keyType, byte* output, int outLen, #endif /* HAVE_ECC */ #ifdef HAVE_ED25519 case ED25519_KEY: - ret = wc_Ed25519PublicKeyToDer(ed25519Key, output, outLen, 1); + ret = wc_Ed25519PublicKeyToDer(ed25519Key, output, + (word32)outLen, 1); if (ret <= 0) { ret = PUBLIC_KEY_E; } @@ -26716,7 +26719,7 @@ static int EncodePublicKey(int keyType, byte* output, int outLen, #endif #ifdef HAVE_ED448 case ED448_KEY: - ret = wc_Ed448PublicKeyToDer(ed448Key, output, outLen, 1); + ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1); if (ret <= 0) { ret = PUBLIC_KEY_E; } @@ -27956,7 +27959,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key); if (ret == 0) - ret = outSz; + ret = (int)outSz; } #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */ @@ -27966,7 +27969,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0); if (ret == 0) - ret = outSz; + ret = (int)outSz; } #endif /* HAVE_ED448 && HAVE_ED448_SIGN */ diff --git a/wolfcrypt/src/cmac.c b/wolfcrypt/src/cmac.c index db0906c99b5..2ceefd7acfc 100644 --- a/wolfcrypt/src/cmac.c +++ b/wolfcrypt/src/cmac.c @@ -342,7 +342,7 @@ int wc_AesCmacVerify(const byte* check, word32 checkSz, XMEMSET(a, 0, aSz); ret = wc_AesCmacGenerate(a, &aSz, in, inSz, key, keySz); - compareRet = ConstantCompare(check, a, min(checkSz, aSz)); + compareRet = ConstantCompare(check, a, (int)min(checkSz, aSz)); if (ret == 0) ret = compareRet ? 1 : 0; diff --git a/wolfcrypt/src/des3.c b/wolfcrypt/src/des3.c index 3699fbe4c33..02cc761125c 100644 --- a/wolfcrypt/src/des3.c +++ b/wolfcrypt/src/des3.c @@ -1486,7 +1486,7 @@ for (j = 0; j < 48; j++) { /* select bits individually */ if (pcr[pc2[j] - 1]) { /* check bit that goes to ks[j] */ l= j % 6; /* mask it in if it's there */ - ks[j/6] |= bytebit[l] >> 2; + ks[j/6] |= (byte)(bytebit[l] >> 2); } } diff --git a/wolfcrypt/src/dh.c b/wolfcrypt/src/dh.c index adb13372196..4dda5672892 100644 --- a/wolfcrypt/src/dh.c +++ b/wolfcrypt/src/dh.c @@ -1039,7 +1039,7 @@ static int _ffc_pairwise_consistency_test(DhKey* key, * modLen - represents L, the size of p in bits * divLen - represents N, the size of q in bits * return 0 on success, -1 on error */ -static int CheckDhLN(int modLen, int divLen) +static int CheckDhLN(word32 modLen, word32 divLen) { int ret = -1; @@ -1076,7 +1076,8 @@ static int CheckDhLN(int modLen, int divLen) static int GeneratePrivateDh186(DhKey* key, WC_RNG* rng, byte* priv, word32* privSz) { - int qSz, pSz, cSz, err; + word32 qSz, pSz, cSz; + int err; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) mp_int* tmpQ = NULL; mp_int* tmpX = NULL; @@ -1093,8 +1094,8 @@ static int GeneratePrivateDh186(DhKey* key, WC_RNG* rng, byte* priv, return BAD_FUNC_ARG; } - qSz = mp_unsigned_bin_size(&key->q); - pSz = mp_unsigned_bin_size(&key->p); + qSz = (word32)mp_unsigned_bin_size(&key->q); + pSz = (word32)mp_unsigned_bin_size(&key->p); /* verify (L,N) pair bit lengths */ /* Trusted primes don't need to be checked. */ @@ -1167,7 +1168,7 @@ static int GeneratePrivateDh186(DhKey* key, WC_RNG* rng, byte* priv, /* tmpQ: M = min(2^N,q) - 1 */ if (err == MP_OKAY) - err = mp_2expt(tmpQ, *privSz * 8); + err = mp_2expt(tmpQ, (int)*privSz * 8); if (err == MP_OKAY) { if (mp_cmp(tmpQ, &key->q) == MP_GT) { @@ -1188,8 +1189,8 @@ static int GeneratePrivateDh186(DhKey* key, WC_RNG* rng, byte* priv, /* copy tmpX into priv */ if (err == MP_OKAY) { - pSz = mp_unsigned_bin_size(tmpX); - if (pSz > (int)*privSz) { + pSz = (word32)mp_unsigned_bin_size(tmpX); + if (pSz > *privSz) { WOLFSSL_MSG("DH private key output buffer too small"); err = BAD_FUNC_ARG; } else { @@ -1235,7 +1236,7 @@ static int GeneratePrivateDh(DhKey* key, WC_RNG* rng, byte* priv, #endif { - sz = mp_unsigned_bin_size(&key->p); + sz = (word32)mp_unsigned_bin_size(&key->p); /* Table of predetermined values from the operation 2 * DiscreteLogWorkFactor(sz * WOLFSSL_BIT_SIZE) / @@ -1348,7 +1349,7 @@ static int GeneratePublicDh(DhKey* key, byte* priv, word32 privSz, ret = MP_TO_E; if (ret == 0) - *pubSz = mp_unsigned_bin_size(y); + *pubSz = (word32)mp_unsigned_bin_size(y); mp_clear(y); mp_clear(x); @@ -2157,7 +2158,7 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, ret = MP_TO_E; if (ret == 0) - *agreeSz = mp_unsigned_bin_size(z); + *agreeSz = (word32)mp_unsigned_bin_size(z); mp_forcezero(z); mp_clear(y); @@ -2381,7 +2382,7 @@ int wc_DhExportKeyPair(DhKey* key, byte* priv, word32* pPrivSz, } if (priv) { - word32 privSz = mp_unsigned_bin_size(&key->priv); + word32 privSz = (word32)mp_unsigned_bin_size(&key->priv); if (privSz > *pPrivSz) { return BUFFER_E; } @@ -2390,7 +2391,7 @@ int wc_DhExportKeyPair(DhKey* key, byte* priv, word32* pPrivSz, } if (pub) { - word32 pubSz = mp_unsigned_bin_size(&key->pub); + word32 pubSz = (word32)mp_unsigned_bin_size(&key->pub); if (pubSz > *pPubSz) { return BUFFER_E; } @@ -2591,7 +2592,7 @@ int wc_DhSetNamedKey(DhKey* key, int name) word32 wc_DhGetNamedKeyMinSize(int name) { - int size; + word32 size; switch (name) { #ifdef HAVE_FFDHE_2048 @@ -2877,9 +2878,9 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) #else mp_int tmp[1], tmp2[2]; #endif - int groupSz = 0, bufSz = 0, - primeCheckCount = 0, - primeCheck = MP_NO, + word32 groupSz = 0, bufSz = 0, + primeCheckCount = 0; + int primeCheck = MP_NO, ret = 0; unsigned char *buf = NULL; @@ -2916,7 +2917,7 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) if (ret == 0) { /* modulus size in bytes */ modSz /= WOLFSSL_BIT_SIZE; - bufSz = modSz - groupSz; + bufSz = (word32)modSz - groupSz; /* allocate ram */ buf = (unsigned char *)XMALLOC(bufSz, @@ -2943,7 +2944,7 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) /* force magnitude */ buf[0] |= 0xC0; /* force even */ - buf[bufSz - 1] &= ~1; + buf[bufSz - 1] &= (byte)~1U; if (mp_init_multi(tmp, tmp2, &dh->p, &dh->q, &dh->g, 0) != MP_OKAY) { @@ -2958,7 +2959,7 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) /* make our prime q */ if (ret == 0) { - if (mp_rand_prime(&dh->q, groupSz, rng, NULL) != MP_OKAY) + if (mp_rand_prime(&dh->q, (int)groupSz, rng, NULL) != MP_OKAY) ret = PRIME_GEN_E; } @@ -3088,9 +3089,9 @@ int wc_DhExportParamsRaw(DhKey* dh, byte* p, word32* pSz, /* get required output buffer sizes */ if (ret == 0) { - pLen = mp_unsigned_bin_size(&dh->p); - qLen = mp_unsigned_bin_size(&dh->q); - gLen = mp_unsigned_bin_size(&dh->g); + pLen = (word32)mp_unsigned_bin_size(&dh->p); + qLen = (word32)mp_unsigned_bin_size(&dh->q); + gLen = (word32)mp_unsigned_bin_size(&dh->g); /* return buffer sizes and LENGTH_ONLY_E if buffers are NULL */ if (p == NULL && q == NULL && g == NULL) { diff --git a/wolfcrypt/src/poly1305.c b/wolfcrypt/src/poly1305.c index f138b60c1fe..f56b3fdadd1 100644 --- a/wolfcrypt/src/poly1305.c +++ b/wolfcrypt/src/poly1305.c @@ -211,14 +211,14 @@ extern void poly1305_final_avx2(Poly1305* ctx, byte* mac); } static void U64TO8(byte* p, word64 v) { - p[0] = (v ) & 0xff; - p[1] = (v >> 8) & 0xff; - p[2] = (v >> 16) & 0xff; - p[3] = (v >> 24) & 0xff; - p[4] = (v >> 32) & 0xff; - p[5] = (v >> 40) & 0xff; - p[6] = (v >> 48) & 0xff; - p[7] = (v >> 56) & 0xff; + p[0] = (byte)v; + p[1] = (byte)(v >> 8); + p[2] = (byte)(v >> 16); + p[3] = (byte)(v >> 24); + p[4] = (byte)(v >> 32); + p[5] = (byte)(v >> 40); + p[6] = (byte)(v >> 48); + p[7] = (byte)(v >> 56); } #endif/* WOLFSSL_ARMASM */ #else /* if not 64 bit then use 32 bit */ @@ -778,7 +778,7 @@ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) /* process full blocks */ if (bytes >= POLY1305_BLOCK_SIZE) { - size_t want = ((size_t)bytes & ~(POLY1305_BLOCK_SIZE - 1)); + size_t want = ((size_t)bytes & ~((size_t)POLY1305_BLOCK_SIZE - 1)); #if !defined(WOLFSSL_ARMASM) || !defined(__aarch64__) int ret; ret = poly1305_blocks(ctx, m, want); diff --git a/wolfcrypt/src/sha3.c b/wolfcrypt/src/sha3.c index 2710f203b09..2baea76548c 100644 --- a/wolfcrypt/src/sha3.c +++ b/wolfcrypt/src/sha3.c @@ -645,7 +645,7 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) if (sha3->i > 0) { byte *t; - byte l = p * 8 - sha3->i; + byte l = (byte)(p * 8 - sha3->i); if (l > len) { l = (byte)len; } @@ -692,7 +692,7 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) data += p * 8; } XMEMCPY(sha3->t, data, len); - sha3->i += len; + sha3->i += (byte)len; return 0; } diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index bffa98501d7..ad2a2494162 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -1073,7 +1073,7 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) #else -static int Sha512FinalRaw(wc_Sha512* sha512, byte* hash, int digestSz) +static int Sha512FinalRaw(wc_Sha512* sha512, byte* hash, size_t digestSz) { #ifdef LITTLE_ENDIAN_ORDER word64 digest[WC_SHA512_DIGEST_SIZE / sizeof(word64)]; @@ -1099,7 +1099,7 @@ int wc_Sha512FinalRaw(wc_Sha512* sha512, byte* hash) return Sha512FinalRaw(sha512, hash, WC_SHA512_DIGEST_SIZE); } -static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, int digestSz, +static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, size_t digestSz, int (*initfp)(wc_Sha512*)) { int ret; diff --git a/wolfcrypt/src/siphash.c b/wolfcrypt/src/siphash.c index a2b031da80f..7e93b0b5a7d 100644 --- a/wolfcrypt/src/siphash.c +++ b/wolfcrypt/src/siphash.c @@ -258,7 +258,7 @@ int wc_SipHashUpdate(SipHash* sipHash, const unsigned char* in, word32 inSz) if (sipHash->cacheCnt > 0) { byte len = SIPHASH_BLOCK_SIZE - sipHash->cacheCnt; if (len > inSz) { - len = inSz; + len = (byte)inSz; } XMEMCPY(sipHash->cache + sipHash->cacheCnt, in, len); in += len; @@ -285,7 +285,7 @@ int wc_SipHashUpdate(SipHash* sipHash, const unsigned char* in, word32 inSz) if (inSz > 0) { /* Cache remaining message bytes less than a block. */ XMEMCPY(sipHash->cache, in, inSz); - sipHash->cacheCnt = inSz; + sipHash->cacheCnt = (byte)inSz; } } diff --git a/wolfcrypt/src/wc_encrypt.c b/wolfcrypt/src/wc_encrypt.c index 2d36f2a82d0..e5be5d60b64 100644 --- a/wolfcrypt/src/wc_encrypt.c +++ b/wolfcrypt/src/wc_encrypt.c @@ -283,7 +283,7 @@ int wc_BufferKeyDecrypt(EncryptedInfo* info, byte* der, word32 derSz, #ifndef NO_PWDBASED if ((ret = wc_PBKDF1(key, password, passwordSz, info->iv, PKCS5_SALT_SZ, 1, - info->keySz, hashType)) != 0) { + (int)info->keySz, hashType)) != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(key, NULL, DYNAMIC_TYPE_SYMMETRIC_KEY); #elif defined(WOLFSSL_CHECK_MEM_ZERO) @@ -349,7 +349,7 @@ int wc_BufferKeyEncrypt(EncryptedInfo* info, byte* der, word32 derSz, #ifndef NO_PWDBASED if ((ret = wc_PBKDF1(key, password, passwordSz, info->iv, PKCS5_SALT_SZ, 1, - info->keySz, hashType)) != 0) { + (int)info->keySz, hashType)) != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(key, NULL, DYNAMIC_TYPE_SYMMETRIC_KEY); #elif defined(WOLFSSL_CHECK_MEM_ZERO) @@ -396,7 +396,7 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, int length, int version, byte* cbcIv, int enc, int shaOid) { int typeH = WC_HASH_TYPE_NONE; - int derivedLen = 0; + word32 derivedLen = 0; int ret = 0; #ifdef WOLFSSL_SMALL_STACK byte* key = NULL; @@ -410,6 +410,9 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, WOLFSSL_ENTER("wc_CryptKey"); + if (length < 0) + ret = BAD_LENGTH_E; + switch (id) { #ifndef NO_DES3 #ifndef NO_MD5 @@ -512,13 +515,13 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, #ifndef NO_HMAC case PKCS5v2: ret = wc_PBKDF2(key, (byte*)password, passwordSz, - salt, saltSz, iterations, derivedLen, typeH); + salt, saltSz, iterations, (int)derivedLen, typeH); break; #endif #ifndef NO_SHA case PKCS5: ret = wc_PBKDF1(key, (byte*)password, passwordSz, - salt, saltSz, iterations, derivedLen, typeH); + salt, saltSz, iterations, (int)derivedLen, typeH); break; #endif #ifdef HAVE_PKCS12 @@ -541,7 +544,7 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, unicodePasswd[idx++] = 0x00; ret = wc_PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz, - iterations, derivedLen, typeH, 1); + iterations, (int)derivedLen, typeH, 1); if (id != PBE_SHA1_RC4_128) { ret += wc_PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz, iterations, 8, typeH, 2); @@ -577,10 +580,10 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, } if (ret == 0) { if (enc) { - wc_Des_CbcEncrypt(&des, input, input, length); + wc_Des_CbcEncrypt(&des, input, input, (word32)length); } else { - wc_Des_CbcDecrypt(&des, input, input, length); + wc_Des_CbcDecrypt(&des, input, input, (word32)length); } } break; @@ -608,10 +611,10 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, } if (ret == 0) { if (enc) { - ret = wc_Des3_CbcEncrypt(&des, input, input, length); + ret = wc_Des3_CbcEncrypt(&des, input, input, (word32)length); } else { - ret = wc_Des3_CbcDecrypt(&des, input, input, length); + ret = wc_Des3_CbcDecrypt(&des, input, input, (word32)length); } } wc_Des3Free(&des); @@ -625,7 +628,7 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, Arc4 dec; wc_Arc4SetKey(&dec, key, derivedLen); - wc_Arc4Process(&dec, input, input, length); + wc_Arc4Process(&dec, input, input, (word32)length); break; } #endif @@ -661,9 +664,9 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, } if (ret == 0) { if (enc) - ret = wc_AesCbcEncrypt(aes, input, input, length); + ret = wc_AesCbcEncrypt(aes, input, input, (word32)length); else - ret = wc_AesCbcDecrypt(aes, input, input, length); + ret = wc_AesCbcDecrypt(aes, input, input, (word32)length); } if (free_aes) wc_AesFree(aes); diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index c81272ef4f4..1a1bcfa3475 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -488,7 +488,7 @@ int wc_FileLoad(const char* fname, unsigned char** buf, size_t* bufLen, void* heap) { int ret; - size_t fileSz; + long int fileSz; XFILE f; if (fname == NULL || buf == NULL || bufLen == NULL) { @@ -512,13 +512,18 @@ int wc_FileLoad(const char* fname, unsigned char** buf, size_t* bufLen, return BAD_PATH_ERROR; } fileSz = XFTELL(f); + if (fileSz < 0) { + WOLFSSL_MSG("wc_LoadFile ftell error"); + XFCLOSE(f); + return BAD_PATH_ERROR; + } if (XFSEEK(f, 0, XSEEK_SET) != 0) { WOLFSSL_MSG("wc_LoadFile file seek error"); XFCLOSE(f); return BAD_PATH_ERROR; } if (fileSz > 0) { - *bufLen = fileSz; + *bufLen = (size_t)fileSz; *buf = (byte*)XMALLOC(*bufLen, heap, DYNAMIC_TYPE_TMP_BUFFER); if (*buf == NULL) { WOLFSSL_MSG("wc_LoadFile memory error"); @@ -727,13 +732,13 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) ret = BAD_PATH_ERROR; break; } - XSTRNCPY(ctx->name, path, pathLen + 1); + XSTRNCPY(ctx->name, path, (size_t)pathLen + 1); ctx->name[pathLen] = '/'; /* Use dnameLen + 1 for GCC 8 warnings of truncating d_name. Because * of earlier check it is known that dnameLen is less than * MAX_FILENAME_SZ - (pathLen + 2) so dnameLen +1 will fit */ - XSTRNCPY(ctx->name + pathLen + 1, ctx->entry->d_name, dnameLen + 1); + XSTRNCPY(ctx->name + pathLen + 1, ctx->entry->d_name, (size_t)dnameLen + 1); if ((ret = wc_FileExists(ctx->name)) == 0) { if (name) *name = ctx->name; @@ -852,12 +857,12 @@ int wc_ReadDirNext(ReadDirCtx* ctx, const char* path, char** name) ret = BAD_PATH_ERROR; break; } - XSTRNCPY(ctx->name, path, pathLen + 1); + XSTRNCPY(ctx->name, path, (size_t)pathLen + 1); ctx->name[pathLen] = '/'; /* Use dnameLen + 1 for GCC 8 warnings of truncating d_name. Because * of earlier check it is known that dnameLen is less than * MAX_FILENAME_SZ - (pathLen + 2) so that dnameLen +1 will fit */ - XSTRNCPY(ctx->name + pathLen + 1, ctx->entry->d_name, dnameLen + 1); + XSTRNCPY(ctx->name + pathLen + 1, ctx->entry->d_name, (size_t)dnameLen + 1); if ((ret = wc_FileExists(ctx->name)) == 0) { if (name) diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index 57fb901e664..033e85f85a8 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -811,6 +811,11 @@ while (0) #define DECL_MP_INT_SIZE_DYN(name, bits, max) \ unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(bits))]; \ sp_int* (name) = (sp_int*)name##d +#elif defined(__cplusplus) +/* C++ doesn't tolerate parentheses around "name" (-Wparentheses) */ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(max))]; \ + sp_int* name = (sp_int*)name##d #else /* Declare a dynamically allocated mp_int. */ #define DECL_MP_INT_SIZE_DYN(name, bits, max) \ From 3698ce8d5d050327d898d677c9f3c10d5b64e406 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 17 Apr 2023 17:43:00 -0500 Subject: [PATCH 163/391] add wc_strcasecmp() and wc_strncasecmp() to wc_port.c, and set up (USE_WOLF_STR[N]CASECMP) in types.h for targets lacking native implementations (including WOLF_C89); define USE_WOLF_STRSEP if defined(WOLF_C89). --- wolfcrypt/src/wc_port.c | 42 +++++++++++++++++++++++++++++++++++++++ wolfssl/wolfcrypt/types.h | 34 +++++++++++++++++++------------ 2 files changed, 63 insertions(+), 13 deletions(-) diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index 1a1bcfa3475..f5bda06abf8 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -1081,6 +1081,48 @@ size_t wc_strlcat(char *dst, const char *src, size_t dstSize) } #endif /* USE_WOLF_STRLCAT */ +#ifdef USE_WOLF_STRCASECMP +int wc_strcasecmp(const char *s1, const char *s2) +{ + char c1, c2; + for (; + ; + ++s1, ++s2) + { + c1 = *s1; + if ((c1 >= 'a') && (c1 <= 'z')) + c1 -= ('a' - 'A'); + c2 = *s2; + if ((c2 >= 'a') && (c2 <= 'z')) + c2 -= ('a' - 'A'); + if ((c1 != c2) || (c1 == 0)) + break; + } + return (c1 - c2); +} +#endif /* USE_WOLF_STRCASECMP */ + +#ifdef USE_WOLF_STRNCASECMP +int wc_strncasecmp(const char *s1, const char *s2, size_t n) +{ + char c1, c2; + for (c1 = 0, c2 = 0; + n > 0; + --n, ++s1, ++s2) + { + c1 = *s1; + if ((c1 >= 'a') && (c1 <= 'z')) + c1 -= ('a' - 'A'); + c2 = *s2; + if ((c2 >= 'a') && (c2 <= 'z')) + c2 -= ('a' - 'A'); + if ((c1 != c2) || (c1 == 0)) + break; + } + return (c1 - c2); +} +#endif /* USE_WOLF_STRNCASECMP */ + #if !defined(SINGLE_THREADED) && !defined(HAVE_C___ATOMIC) void wolfSSL_RefInit(wolfSSL_Ref* ref, int* err) { diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 4fdc88a82ca..28ab2cbc5fe 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -640,7 +640,7 @@ typedef struct w64wrapper { defined(WOLFSSL_TIRTOS) || defined(WOLF_C99)) #define USE_WOLF_STRTOK #endif - #if !defined(USE_WOLF_STRSEP) && (defined(WOLF_C99)) + #if !defined(USE_WOLF_STRSEP) && (defined(WOLF_C89) || defined(WOLF_C99)) #define USE_WOLF_STRSEP #endif #if !defined(XSTRLCPY) && !defined(USE_WOLF_STRLCPY) @@ -684,10 +684,9 @@ typedef struct w64wrapper { #define XSTRCASECMP(s1,s2) strcasecmp((s1),(s2)) #elif defined(MICROCHIP_PIC32) || defined(WOLFSSL_TIRTOS) || \ defined(WOLFSSL_ZEPHYR) - /* XC32 version < 1.0 does not support strcasecmp, so use - * case sensitive one. - */ - #define XSTRCASECMP(s1,s2) strcmp((s1),(s2)) + /* XC32 version < 1.0 does not support strcasecmp. */ + #define USE_WOLF_STRCASECMP + #define XSTRCASECMP(s1,s2) wc_strcasecmp(s1,s2) #elif defined(USE_WINDOWS_API) || defined(FREERTOS_TCP_WINSIM) #define XSTRCASECMP(s1,s2) _stricmp((s1),(s2)) #else @@ -697,8 +696,10 @@ typedef struct w64wrapper { #endif #if defined(WOLFSSL_DEOS) #define XSTRCASECMP(s1,s2) stricmp((s1),(s2)) - #elif defined(WOLFSSL_CMSIS_RTOSv2) || defined(WOLFSSL_AZSPHERE) - #define XSTRCASECMP(s1,s2) strcmp((s1),(s2)) + #elif defined(WOLFSSL_CMSIS_RTOSv2) || defined(WOLFSSL_AZSPHERE) \ + || defined(WOLF_C89) + #define USE_WOLF_STRCASECMP + #define XSTRCASECMP(s1,s2) wc_strcasecmp(s1, s2) #elif defined(WOLF_C89) #define XSTRCASECMP(s1,s2) strcmp((s1),(s2)) #else @@ -713,10 +714,9 @@ typedef struct w64wrapper { #define XSTRNCASECMP(s1,s2,n) strncasecmp((s1),(s2),(n)) #elif defined(MICROCHIP_PIC32) || defined(WOLFSSL_TIRTOS) || \ defined(WOLFSSL_ZEPHYR) - /* XC32 version < 1.0 does not support strncasecmp, so use case - * sensitive one. - */ - #define XSTRNCASECMP(s1,s2,n) strncmp((s1),(s2),(n)) + /* XC32 version < 1.0 does not support strncasecmp. */ + #define USE_WOLF_STRNCASECMP + #define XSTRNCASECMP(s1,s2) wc_strncasecmp(s1,s2) #elif defined(USE_WINDOWS_API) || defined(FREERTOS_TCP_WINSIM) #define XSTRNCASECMP(s1,s2,n) _strnicmp((s1),(s2),(n)) #else @@ -726,8 +726,10 @@ typedef struct w64wrapper { #endif #if defined(WOLFSSL_DEOS) #define XSTRNCASECMP(s1,s2,n) strnicmp((s1),(s2),(n)) - #elif defined(WOLFSSL_CMSIS_RTOSv2) || defined(WOLFSSL_AZSPHERE) - #define XSTRNCASECMP(s1,s2,n) strncmp((s1),(s2),(n)) + #elif defined(WOLFSSL_CMSIS_RTOSv2) || defined(WOLFSSL_AZSPHERE) \ + || defined(WOLF_C89) + #define USE_WOLF_STRNCASECMP + #define XSTRNCASECMP(s1,s2,n) wc_strncasecmp(s1, s2 ,n) #elif defined(WOLF_C89) #define XSTRNCASECMP(s1,s2,n) strncmp((s1),(s2),(n)) #else @@ -855,6 +857,12 @@ typedef struct w64wrapper { WOLFSSL_API size_t wc_strlcat(char *dst, const char *src, size_t dstSize); #define XSTRLCAT(s1,s2,n) wc_strlcat((s1),(s2),(n)) #endif + #ifdef USE_WOLF_STRCASECMP + WOLFSSL_API int wc_strcasecmp(const char *s1, const char *s2); + #endif + #ifdef USE_WOLF_STRNCASECMP + WOLFSSL_API int wc_strncasecmp(const char *s1, const char *s2, size_t n); + #endif #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) #ifndef XGETENV From ce8577b5bc490b46a93f994c14befe366aea6ebb Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 17 Apr 2023 22:51:55 -0500 Subject: [PATCH 164/391] refinements from peer review for #6303. --- wolfcrypt/src/aes.c | 2 +- wolfcrypt/src/dh.c | 2 +- wolfcrypt/src/wc_encrypt.c | 2 +- wolfcrypt/src/wc_port.c | 10 ++-------- 4 files changed, 5 insertions(+), 11 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index c40e49bec72..c44f77bb117 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -10405,7 +10405,7 @@ static WC_INLINE void InitKeyWrapCounter(byte* inOutCtr, word32 value) bytes = sizeof(word32); for (i = 0; i < sizeof(word32); i++) { - inOutCtr[i+sizeof(word32)] = (value >> ((bytes - 1) * 8)) & 0xFF; + inOutCtr[i+sizeof(word32)] = (byte)(value >> ((bytes - 1) * 8)); bytes--; } } diff --git a/wolfcrypt/src/dh.c b/wolfcrypt/src/dh.c index 4dda5672892..4cedcae17dc 100644 --- a/wolfcrypt/src/dh.c +++ b/wolfcrypt/src/dh.c @@ -2944,7 +2944,7 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) /* force magnitude */ buf[0] |= 0xC0; /* force even */ - buf[bufSz - 1] &= (byte)~1U; + buf[bufSz - 1] &= 0xfe; if (mp_init_multi(tmp, tmp2, &dh->p, &dh->q, &dh->g, 0) != MP_OKAY) { diff --git a/wolfcrypt/src/wc_encrypt.c b/wolfcrypt/src/wc_encrypt.c index e5be5d60b64..506ac11e0d2 100644 --- a/wolfcrypt/src/wc_encrypt.c +++ b/wolfcrypt/src/wc_encrypt.c @@ -411,7 +411,7 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, WOLFSSL_ENTER("wc_CryptKey"); if (length < 0) - ret = BAD_LENGTH_E; + return BAD_LENGTH_E; switch (id) { #ifndef NO_DES3 diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index f5bda06abf8..b6c59123f7c 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -1085,10 +1085,7 @@ size_t wc_strlcat(char *dst, const char *src, size_t dstSize) int wc_strcasecmp(const char *s1, const char *s2) { char c1, c2; - for (; - ; - ++s1, ++s2) - { + for (;;++s1, ++s2) { c1 = *s1; if ((c1 >= 'a') && (c1 <= 'z')) c1 -= ('a' - 'A'); @@ -1106,10 +1103,7 @@ int wc_strcasecmp(const char *s1, const char *s2) int wc_strncasecmp(const char *s1, const char *s2, size_t n) { char c1, c2; - for (c1 = 0, c2 = 0; - n > 0; - --n, ++s1, ++s2) - { + for (c1 = 0, c2 = 0; n > 0; --n, ++s1, ++s2) { c1 = *s1; if ((c1 >= 'a') && (c1 <= 'z')) c1 -= ('a' - 'A'); From 1750feb90e01319618a0bdd58ebb30124206a8ae Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Tue, 18 Apr 2023 14:27:52 -0500 Subject: [PATCH 165/391] fix clang-analyzer-deadcode.DeadStores in wolfcrypt/src/asn.c:SetOthername(). --- wolfcrypt/src/asn.c | 1 - 1 file changed, 1 deletion(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index d4f03bbeff0..eaa60c79ec9 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -14629,7 +14629,6 @@ word32 SetOthername(void *name, byte *output) output += SetHeader(CTC_UTF8, nameSz, output); XMEMCPY(output, nameStr, nameSz); - output += nameSz; } return len; From c0c5b471e8370aa19c434870b5b4f81d9ade2c01 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Tue, 18 Apr 2023 14:29:13 -0500 Subject: [PATCH 166/391] fix null pointer deref (found by cppcheck:nullPointerRedundantCheck) in src/x509.c:wolfSSL_X509_EXTENSION_create_by_OBJ(). --- src/x509.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/x509.c b/src/x509.c index c8fcebfb2ff..ca5ffd5a401 100644 --- a/src/x509.c +++ b/src/x509.c @@ -307,7 +307,9 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_create_by_OBJ( wolfSSL_ASN1_STRING_free(&ret->value); } - ret->crit = crit; + if (err == 0) { + ret->crit = crit; + } if (err == 0) { ret->obj = wolfSSL_ASN1_OBJECT_dup(obj); From 411a935ee50999bd554d5ba76d5dde56439ad0bb Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Tue, 18 Apr 2023 14:30:38 -0500 Subject: [PATCH 167/391] wolfcrypt/src/wc_port.c: in wc_FileLoad(), use ssize_t for fileSz, not long int, for portability. --- wolfcrypt/src/wc_port.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index b6c59123f7c..8852e639ed8 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -488,7 +488,7 @@ int wc_FileLoad(const char* fname, unsigned char** buf, size_t* bufLen, void* heap) { int ret; - long int fileSz; + ssize_t fileSz; XFILE f; if (fname == NULL || buf == NULL || bufLen == NULL) { From a14012604f95ce385b300910c4bdabfccb279df9 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Tue, 18 Apr 2023 14:43:41 -0500 Subject: [PATCH 168/391] wolfssl/wolfcrypt/settings.h: add #ifdef _MSC_VER clause to define ssize_t, #ifndef HAVE_SSIZE_T. --- wolfssl/wolfcrypt/settings.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 2294f79502b..0eb3b792b6c 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1877,6 +1877,13 @@ extern void uITRON4_free(void *p) ; #endif #endif +#ifdef _MSC_VER + #ifndef HAVE_SSIZE_T + #include + typedef SSIZE_T ssize_t; + #endif +#endif + /* If DCP is used without SINGLE_THREADED, enforce WOLFSSL_CRYPT_HW_MUTEX */ #if defined(WOLFSSL_IMXRT_DCP) && !defined(SINGLE_THREADED) #undef WOLFSSL_CRYPT_HW_MUTEX From b57b88af27d2c7a087c12d86c6671d80aeac9592 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Wed, 19 Apr 2023 15:10:22 +0200 Subject: [PATCH 169/391] Various Espressif HW crypto, SHA2, AES, MP updates. (#6287) * various Espressif HW crypto, SHA2, AES, MP updates. * code review updates & cleanup * clean trailing whitespace * cleanup per code review * removed additional unused WOLFSSL_USE_ESP32C3_CRYPT_HASH_HW * Code review updates; pack & order WC_ESP32SHA * clean up TAG text for Espressif ESP_LOG() --- .../components/wolfssl/CMakeLists.txt | 3 + .../components/wolfssl/CMakeLists.txt | 2 + .../ESP-IDF/examples/wolfssl_test/main/main.c | 3 +- wolfcrypt/benchmark/benchmark.c | 53 +- wolfcrypt/src/port/Espressif/esp32_aes.c | 265 +++-- wolfcrypt/src/port/Espressif/esp32_mp.c | 406 ++++++- wolfcrypt/src/port/Espressif/esp32_sha.c | 1002 ++++++++++++++--- wolfcrypt/src/port/Espressif/esp32_util.c | 252 ++++- wolfcrypt/src/sha.c | 210 ++-- wolfcrypt/src/sha256.c | 163 +-- wolfcrypt/src/sha512.c | 258 +++-- .../wolfcrypt/port/Espressif/esp32-crypt.h | 117 +- 12 files changed, 2091 insertions(+), 643 deletions(-) diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/components/wolfssl/CMakeLists.txt b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/components/wolfssl/CMakeLists.txt index 2423b802c1c..eff35918387 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/components/wolfssl/CMakeLists.txt +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_benchmark/components/wolfssl/CMakeLists.txt @@ -190,6 +190,8 @@ set(COMPONENT_SRCEXCLUDE "${WOLFSSL_ROOT}/src/conf.c" "${WOLFSSL_ROOT}/src/misc.c" "${WOLFSSL_ROOT}/src/pk.c" + "${WOLFSSL_ROOT}/src/ssl_asn1.c" # included by ssl.c + "${WOLFSSL_ROOT}/src/ssl_bn.c" # included by ssl.c "${WOLFSSL_ROOT}/src/ssl_misc.c" # included by ssl.c "${WOLFSSL_ROOT}/src/x509.c" "${WOLFSSL_ROOT}/src/x509_str.c" @@ -197,6 +199,7 @@ set(COMPONENT_SRCEXCLUDE "${WOLFSSL_ROOT}/wolfcrypt/src/misc.c" "${EXCLUDE_ASM}" ) +set(COMPONENT_PRIV_INCLUDEDIRS ${IDF_PATH}/components/driver/include) register_component() diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/components/wolfssl/CMakeLists.txt b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/components/wolfssl/CMakeLists.txt index 2423b802c1c..a916facabd7 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/components/wolfssl/CMakeLists.txt +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/components/wolfssl/CMakeLists.txt @@ -190,6 +190,8 @@ set(COMPONENT_SRCEXCLUDE "${WOLFSSL_ROOT}/src/conf.c" "${WOLFSSL_ROOT}/src/misc.c" "${WOLFSSL_ROOT}/src/pk.c" + "${WOLFSSL_ROOT}/src/ssl_asn1.c" # included by ssl.c + "${WOLFSSL_ROOT}/src/ssl_bn.c" # included by ssl.c "${WOLFSSL_ROOT}/src/ssl_misc.c" # included by ssl.c "${WOLFSSL_ROOT}/src/x509.c" "${WOLFSSL_ROOT}/src/x509_str.c" diff --git a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/main/main.c b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/main/main.c index 01538f72e32..5adb75300f8 100644 --- a/IDE/Espressif/ESP-IDF/examples/wolfssl_test/main/main.c +++ b/IDE/Espressif/ESP-IDF/examples/wolfssl_test/main/main.c @@ -178,7 +178,8 @@ void app_main(void) #elif defined(CONFIG_IDF_TARGET_ESP32S2) #error "ESP32WROOM32_CRYPT not yet supported on ESP32-S2" #elif defined(CONFIG_IDF_TARGET_ESP32S3) - #error "ESP32WROOM32_CRYPT not yet supported on ESP32-S3" + /* #error "ESP32WROOM32_CRYPT not yet supported on ESP32-S3" */ + ESP_LOGI(TAG, "ESP32WROOM32_CRYPT is enabled for ESP32-S3."); #else ESP_LOGI(TAG, "ESP32WROOM32_CRYPT is enabled."); #endif diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 68949cbdaa8..1c9e1df21aa 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -66,7 +66,21 @@ #include #ifdef WOLFSSL_ESPIDF - #include /* reminder Espressif RISC-V not yet implemented */ + #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + #include "driver/gptimer.h" + static gptimer_handle_t esp_gptimer = NULL; + static gptimer_config_t esp_timer_config = { + .clk_src = GPTIMER_CLK_SRC_DEFAULT, + .direction = GPTIMER_COUNT_UP, + .resolution_hz = CONFIG_XTAL_FREQ * 1000000, + }; + #elif defined(CONFIG_IDF_TARGET_ESP32) || \ + defined(CONFIG_IDF_TARGET_ESP32S2) || \ + defined(CONFIG_IDF_TARGET_ESP32S3) + #include + #else + #error "CONFIG_IDF_TARGET not implemented" + #endif #include #endif @@ -1001,13 +1015,18 @@ static const char* bench_desc_words[][15] = { ** the Espressif `unsigned xthal_get_ccount()` which is known to overflow ** at least once during full benchmark tests. */ - word64 xthal_get_ccount_ex() + uint64_t xthal_get_ccount_ex() { /* reminder: unsigned long long max = 18,446,744,073,709,551,615 */ /* the currently observed clock counter value */ - word64 thisVal = xthal_get_ccount(); - + #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + uint64_t thisVal = 0; + ESP_ERROR_CHECK(gptimer_get_raw_count(esp_gptimer, &thisVal)); + #else + /* reminder unsupported CONFIG_IDF_TARGET captured above */ + uint64_t thisVal = xthal_get_ccount(); + #endif /* if the current value is less than the previous value, ** we likely overflowed at least once. */ @@ -1034,8 +1053,12 @@ static const char* bench_desc_words[][15] = { _xthal_get_ccount_ex += (thisVal - _xthal_get_ccount_last); /* all of this took some time, so reset the "last seen" value */ - _xthal_get_ccount_last = xthal_get_ccount(); - + #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + ESP_ERROR_CHECK(gptimer_get_raw_count(esp_gptimer, + &_xthal_get_ccount_last)); + #else + _xthal_get_ccount_last = xthal_get_ccount(); + #endif return _xthal_get_ccount_ex; } @@ -4992,7 +5015,7 @@ void bench_sha512_224(int useDeviceID) WC_FREE_ARRAY(digest, BENCH_MAX_PENDING, HEAP_HINT); } -#endif +#endif /* WOLFSSL_NOSHA512_224 && !FIPS ... */ #if !defined(WOLFSSL_NOSHA512_256) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST) @@ -5086,10 +5109,9 @@ void bench_sha512_256(int useDeviceID) WC_FREE_ARRAY(digest, BENCH_MAX_PENDING, HEAP_HINT); } +#endif /* WOLFSSL_NOSHA512_256 && !FIPS ... */ -#endif - -#endif +#endif /* WOLFSSL_SHA512 */ #ifdef WOLFSSL_SHA3 @@ -7494,8 +7516,9 @@ void bench_eccEncrypt(int curveId) if (ret != 0) goto exit; - for (i = 0; i < (int)sizeof(msg); i++) + for (i = 0; i < (int)sizeof(msg); i++) { msg[i] = (byte)i; + } bench_stats_start(&count, &start); do { @@ -9095,6 +9118,14 @@ static int string_matches(const char* arg, const char* str) #ifdef WOLFSSL_ESPIDF int argc = construct_argv(); char** argv = (char**)__argv; + + #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + ESP_ERROR_CHECK(gptimer_new_timer(&esp_timer_config, &esp_gptimer)); + ESP_LOGI(TAG, "Enable ESP32-C3 timer "); + ESP_ERROR_CHECK(gptimer_enable(esp_gptimer)); + ESP_ERROR_CHECK(gptimer_start(esp_gptimer)); + #endif + #endif return wolfcrypt_benchmark_main(argc, argv); diff --git a/wolfcrypt/src/port/Espressif/esp32_aes.c b/wolfcrypt/src/port/Espressif/esp32_aes.c index 0603f169e5e..09105a51108 100644 --- a/wolfcrypt/src/port/Espressif/esp32_aes.c +++ b/wolfcrypt/src/port/Espressif/esp32_aes.c @@ -35,10 +35,12 @@ #if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_AES) - +#include "sdkconfig.h" /* programmatically generated from sdkconfig */ #include #include "wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h" +#include +/* breadcrumb tag text for ESP_LOG() */ static const char* TAG = "wolf_hw_aes"; /* mutex */ @@ -67,27 +69,36 @@ static int esp_aes_hw_InUse() } else { ESP_LOGE(TAG, "aes mutex initialization failed."); - return -1; } } else { /* esp aes has already been initialized */ } - /* lock hardware */ - ret = esp_CryptHwMutexLock(&aes_mutex, portMAX_DELAY); - - if(ret != 0) { + if (ret == 0) { + /* lock hardware */ + ret = esp_CryptHwMutexLock(&aes_mutex, portMAX_DELAY); + } + else { ESP_LOGE(TAG, "aes engine lock failed."); - return -1; } - /* Enable AES hardware */ - periph_module_enable(PERIPH_AES_MODULE); + + if (ret == 0) { + /* Enable AES hardware */ + periph_module_enable(PERIPH_AES_MODULE); + + #if CONFIG_IDF_TARGET_ESP32S3 + /* Select working mode. Can be typical or DMA. + * 0 => typical + * 1 => DMA */ + DPORT_REG_WRITE(AES_DMA_ENABLE_REG, 0); + #endif + } ESP_LOGV(TAG, "leave esp_aes_hw_InUse"); return ret; -} +} /* esp_aes_hw_InUse */ /* * release hw engine @@ -102,20 +113,22 @@ static void esp_aes_hw_Leave( void ) esp_CryptHwMutexUnLock(&aes_mutex); ESP_LOGV(TAG, "leave esp_aes_hw_Leave"); -} +} /* esp_aes_hw_Leave */ /* * set key to hardware key registers. + * return 0 on success; -1 if mode isn't supported. */ -static void esp_aes_hw_Set_KeyMode(Aes *ctx, ESP32_AESPROCESS mode) +static int esp_aes_hw_Set_KeyMode(Aes *ctx, ESP32_AESPROCESS mode) { + int ret = 0; word32 i; word32 mode_ = 0; ESP_LOGV(TAG, " enter esp_aes_hw_Set_KeyMode"); /* check mode */ - if(mode == ESP32_AES_UPDATEKEY_ENCRYPT) { + if (mode == ESP32_AES_UPDATEKEY_ENCRYPT) { mode_ = 0; } else { @@ -124,47 +137,89 @@ static void esp_aes_hw_Set_KeyMode(Aes *ctx, ESP32_AESPROCESS mode) } else { ESP_LOGE(TAG, " >> unexpected error."); - return; + ret = BAD_FUNC_ARG; } - } + } /* if mode */ - /* update key */ - for(i=0; i<(ctx->keylen)/sizeof(word32); i++){ - DPORT_REG_WRITE(AES_KEY_BASE + (i*4), *(((word32*)ctx->key) + i)); - } + if (ret == 0) { + + /* update key */ + for (i = 0; i < (ctx->keylen) / sizeof(word32); i++) { + DPORT_REG_WRITE(AES_KEY_BASE + (i * 4), *(((word32*)ctx->key) + i)); + } + + /* + ** ESP32: see table 22-1 in ESP32 Technical Reference + ** ESP32S3: see table 19-2 in ESP32S3 Technical Reference + ** mode Algorithm ESP32 ESP32S3 + ** 0 AES-128 Encryption y y + ** 1 AES-192 Encryption y n + ** 2 AES-256 Encryption y y + ** 4 AES-128 Decryption y y + ** 5 AES-192 Decryption y n + ** 6 AES-256 Decryption y y + */ + switch(ctx->keylen){ + case 24: mode_ += 1; break; + case 32: mode_ += 2; break; + default: break; + } + + #if CONFIG_IDF_TARGET_ESP32S3 + if (mode_ == 1 || mode_ == 5 || mode_ == 7) { + ESP_LOGE(TAG, "esp_aes_hw_Set_KeyMode unsupported mode: %i", mode_); + ret = BAD_FUNC_ARG; + } + #endif - /* mode - * 0 AES-128 Encryption - * 1 AES-192 Encryption - * 2 AES-256 Encryption - * 4 AES-128 Decryption - * 5 AES-192 Decryption - * 6 AES-256 Decryption - */ - switch(ctx->keylen){ - case 24: mode_ += 1; break; - case 32: mode_ += 2; break; - default: break; + if (ret == 0) { + DPORT_REG_WRITE(AES_MODE_REG, mode_); + } + ESP_LOGV(TAG, " leave esp_aes_hw_Setkey"); } - DPORT_REG_WRITE(AES_MODE_REG, mode_); - ESP_LOGV(TAG, " leave esp_aes_hw_Setkey"); -} + return ret; +} /* esp_aes_hw_Set_KeyMode */ /* + * esp_aes_bk * Process a one block of AES + * in: block of 16 bytes (4 x words32) to process + * out: result of processing input bytes. */ static void esp_aes_bk(const byte* in, byte* out) { const word32 *inwords = (const word32 *)in; + #if ESP_IDF_VERSION_MAJOR >= 4 - uint32_t *outwords = (uint32_t *)out; + uint32_t *outwords = (uint32_t *)out; #else word32 *outwords = (word32 *)out; #endif ESP_LOGV(TAG, "enter esp_aes_bk"); +#if CONFIG_IDF_TARGET_ESP32S3 + /* See esp32 - s3 technical reference manual: + ** 19.4.3 Operation process using CPU working mode. + ** The ESP32-S3 also supports a DMA mode. + ** + ** Copy text for encrypting/decrypting blocks: */ + DPORT_REG_WRITE(AES_TEXT_IN_BASE, inwords[0]); + DPORT_REG_WRITE(AES_TEXT_IN_BASE + 4, inwords[1]); + DPORT_REG_WRITE(AES_TEXT_IN_BASE + 8, inwords[2]); + DPORT_REG_WRITE(AES_TEXT_IN_BASE + 12, inwords[3]); + + /* start engine */ + DPORT_REG_WRITE(AES_TRIGGER_REG, 1); + /* wait until finishing the process */ + while (DPORT_REG_READ(AES_STATE_REG) != 0) { + /* wating for the hardware accelerator to complete operation. */ + } + + /* read-out blocks */ + esp_dport_access_read_buffer(outwords, AES_TEXT_OUT_BASE, 4); +#else /* copy text for encrypting/decrypting blocks */ DPORT_REG_WRITE(AES_TEXT_BASE, inwords[0]); DPORT_REG_WRITE(AES_TEXT_BASE + 4, inwords[1]); @@ -175,15 +230,18 @@ static void esp_aes_bk(const byte* in, byte* out) DPORT_REG_WRITE(AES_START_REG, 1); /* wait until finishing the process */ - while(1) { - if(DPORT_REG_READ(AES_IDLE_REG) == 1) + while (1) { + if (DPORT_REG_READ(AES_IDLE_REG) == 1) { break; + } } /* read-out blocks */ esp_dport_access_read_buffer(outwords, AES_TEXT_BASE, 4); +#endif + ESP_LOGV(TAG, "leave esp_aes_bk"); -} +} /* esp_aes_bk */ /* * wc_esp32AesEncrypt @@ -192,20 +250,33 @@ static void esp_aes_bk(const byte* in, byte* out) * @param in : a pointer of the input buffer containing plain text to be encrypted * @param out: a pointer of the output buffer in which to store the cipher text of * the encrypted message +* @return: 0 on success, BAD_FUNC_ARG if the AES algorithm isn't supported. */ int wc_esp32AesEncrypt(Aes *aes, const byte* in, byte* out) { + int ret = 0; + ESP_LOGV(TAG, "enter wc_esp32AesEncrypt"); /* lock the hw engine */ - esp_aes_hw_InUse(); + ret = esp_aes_hw_InUse(); + + if (ret == 0) { + ret = esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_ENCRYPT); + if (ret != 0) { + ESP_LOGE(TAG, "wc_esp32AesEncrypt failed during esp_aes_hw_Set_KeyMode"); + } + } + /* load the key into the register */ - esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_ENCRYPT); - /* process a one block of AES */ - esp_aes_bk(in, out); + if (ret == 0) { + /* process a one block of AES */ + esp_aes_bk(in, out); + } + /* release hw */ esp_aes_hw_Leave(); - return 0; -} + return ret; +} /* wc_esp32AesEncrypt */ /* * wc_esp32AesDecrypt @@ -214,20 +285,33 @@ int wc_esp32AesEncrypt(Aes *aes, const byte* in, byte* out) * @param in : a pointer of the input buffer containing plain text to be decrypted * @param out: a pointer of the output buffer in which to store the cipher text of * the decrypted message +* @return: 0 on success, BAD_FUNC_ARG if the AES algorithm isn't supported. */ int wc_esp32AesDecrypt(Aes *aes, const byte* in, byte* out) { + int ret; + ESP_LOGV(TAG, "enter wc_esp32AesDecrypt"); /* lock the hw engine */ esp_aes_hw_InUse(); /* load the key into the register */ - esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_DECRYPT); - /* process a one block of AES */ - esp_aes_bk(in, out); - /* release hw engine */ - esp_aes_hw_Leave(); - return 0; -} + ret = esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_DECRYPT); + if (ret != 0) { + ESP_LOGE(TAG, "wc_esp32AesDecrypt failed during esp_aes_hw_Set_KeyMode"); + /* release hw */ + esp_aes_hw_Leave(); + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* process a one block of AES */ + esp_aes_bk(in, out); + /* release hw engine */ + esp_aes_hw_Leave(); + } + + return ret; +} /* wc_esp32AesDecrypt */ /* * wc_esp32AesCbcEncrypt @@ -239,9 +323,11 @@ int wc_esp32AesDecrypt(Aes *aes, const byte* in, byte* out) * the encrypted message * @param in : a pointer of the input buffer containing plain text to be encrypted * @param sz : size of input message +* @return: 0 on success, BAD_FUNC_ARG if the AES algorithm isn't supported. */ int wc_esp32AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { + int ret; int i; int offset = 0; word32 blocks = (sz / AES_BLOCK_SIZE); @@ -250,31 +336,40 @@ int wc_esp32AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) ESP_LOGV(TAG, "enter wc_esp32AesCbcEncrypt"); - iv = (byte*)aes->reg; + iv = (byte*)aes->reg; - esp_aes_hw_InUse(); + ret = esp_aes_hw_InUse(); - esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_ENCRYPT); + if (ret == 0) { + ret = esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_ENCRYPT); + if (ret != 0) { + ESP_LOGE(TAG, "wc_esp32AesCbcEncrypt failed HW Set KeyMode"); + } + } /* if set esp_aes_hw_InUse successful */ - while (blocks--) { - XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); + if (ret == 0) { + while (blocks--) { + XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); - /* XOR block with IV for CBC */ - for (i = 0; i < AES_BLOCK_SIZE; i++) - temp_block[i] ^= iv[i]; + /* XOR block with IV for CBC */ + for (i = 0; i < AES_BLOCK_SIZE; i++) { + temp_block[i] ^= iv[i]; + } - esp_aes_bk(temp_block, (out + offset)); + esp_aes_bk(temp_block, (out + offset)); - offset += AES_BLOCK_SIZE; + offset += AES_BLOCK_SIZE; - /* store IV for next block */ - XMEMCPY(iv, out + offset - AES_BLOCK_SIZE, AES_BLOCK_SIZE); - } + /* store IV for next block */ + XMEMCPY(iv, out + offset - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + } /* while (blocks--) */ + } /* if Set Mode successful (ret == 0) */ esp_aes_hw_Leave(); ESP_LOGV(TAG, "leave wc_esp32AesCbcEncrypt"); return 0; -} +} /* wc_esp32AesCbcEncrypt */ + /* * wc_esp32AesCbcDecrypt * @brief: Encrypts a plain text message from the input buffer, and places the @@ -285,9 +380,12 @@ int wc_esp32AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) * the decrypted message * @param in : a pointer of the input buffer containing plain text to be decrypted * @param sz : size of input message +* @return: 0 on success, BAD_FUNC_ARG if the AES algorithm isn't supported. */ int wc_esp32AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) { + int ret; + int i; int offset = 0; word32 blocks = (sz / AES_BLOCK_SIZE); @@ -296,32 +394,39 @@ int wc_esp32AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) ESP_LOGV(TAG, "enter wc_esp32AesCbcDecrypt"); - iv = (byte*)aes->reg; + iv = (byte*)aes->reg; - esp_aes_hw_InUse(); + ret = esp_aes_hw_InUse(); - esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_DECRYPT); + if (ret == 0) { + ret = esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_DECRYPT); + if (ret != 0) { + ESP_LOGE(TAG, "wc_esp32AesCbcDecrypt failed HW Set KeyMode"); + } + } - while (blocks--) { - XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); + if (ret == 0) { + while (blocks--) { + XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); - esp_aes_bk((in + offset), (out + offset)); + esp_aes_bk((in + offset), (out + offset)); - /* XOR block with IV for CBC */ - for (i = 0; i < AES_BLOCK_SIZE; i++) { - (out + offset)[i] ^= iv[i]; - } + /* XOR block with IV for CBC */ + for (i = 0; i < AES_BLOCK_SIZE; i++) { + (out + offset)[i] ^= iv[i]; + } - /* store IV for next block */ - XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); + /* store IV for next block */ + XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); - offset += AES_BLOCK_SIZE; - } + offset += AES_BLOCK_SIZE; + } /* while (blocks--) */ + } /* if Set Mode was successful (ret == 0) */ esp_aes_hw_Leave(); ESP_LOGV(TAG, "leave wc_esp32AesCbcDecrypt"); return 0; -} +} /* wc_esp32AesCbcDecrypt */ #endif /* WOLFSSL_ESP32WROOM32_CRYPT */ #endif /* NO_AES */ diff --git a/wolfcrypt/src/port/Espressif/esp32_mp.c b/wolfcrypt/src/port/Espressif/esp32_mp.c index 1717a415b03..7e57eff4cac 100644 --- a/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -48,6 +48,7 @@ static const char* const TAG = "wolfssl_mp"; #define ESP_HW_RSAMIN_BIT 512 #define BYTE_TO_WORDS(s) (((s+3)>>2)) /* (s+(4-1))/ 4 */ #define BITS_TO_WORDS(s) (((s+31)>>3)>>2) /* (s+(32-1))/ 8/ 4*/ +#define BITS_IN_ONE_WORD 32 #define MP_NG -1 @@ -57,7 +58,7 @@ static const char* const TAG = "wolfssl_mp"; static wolfSSL_Mutex mp_mutex; static int espmp_CryptHwMutexInit = 0; /* -* check if the hw is ready before accessing it +* check if the HW is ready before accessing it * * When the RSA Accelerator is released from reset, the register RSA_CLEAN_REG * reads 0 and an initialization process begins. Hardware initializes the four @@ -66,27 +67,39 @@ static int espmp_CryptHwMutexInit = 0; * after being released from reset, and before writing to any RSA Accelerator * memory blocks or registers for the first time. */ -static int esp_mp_hw_wait_clean() +static int esp_mp_hw_wait_clean(void) { + int ret = MP_OKAY; word32 timeout = 0; - while(!ESP_TIMEOUT(++timeout) && - DPORT_REG_READ(RSA_CLEAN_REG) != 1) { +#if CONFIG_IDF_TARGET_ESP32S3 + + while (!ESP_TIMEOUT(++timeout) && DPORT_REG_READ(RSA_QUERY_CLEAN_REG) != 1) + { + /* wait. expected delay 1 to 2 uS */ + } +#else + /* RSA_CLEAN_REG is now called RSA_QUERY_CLEAN_REG. hwcrypto_reg.h maintains + * RSA_CLEAN_REG for backwards compatibility so this block _might_ be not needed. */ + while(!ESP_TIMEOUT(++timeout) && DPORT_REG_READ(RSA_CLEAN_REG) != 1) { /* wait. expected delay 1 to 2 uS */ } +#endif if (ESP_TIMEOUT(timeout)) { - ESP_LOGE(TAG, "waiting hw ready is timed out."); - return MP_NG; + ESP_LOGE(TAG, "esp_mp_hw_wait_clean waiting HW ready timed out."); + ret = MP_NG; } - return MP_OKAY; + return ret; } /* -* lock hw engine. -* this should be called before using engine. +* esp_mp_hw_lock() +* +* Lock HW engine. +* This should be called before using engine. * -* returns 0 if the hw lock was initialized and mutex lock +* Returns 0 if the HW lock was initialized and mutex lock. * * See Chapter 24: * https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf @@ -116,27 +129,40 @@ static int esp_mp_hw_lock() } else { ESP_LOGE(TAG, "mp mutex initialization failed."); - return MP_NG; } } else { - /* esp aes has already been initialized */ + /* ESP AES has already been initialized */ } - /* lock hardware */ - ret = esp_CryptHwMutexLock(&mp_mutex, portMAX_DELAY); + if (ret == 0) { + /* lock hardware */ + ret = esp_CryptHwMutexLock(&mp_mutex, portMAX_DELAY); + if (ret != 0) { + ESP_LOGE(TAG, "mp engine lock failed."); + ret = MP_NG; + } + } - if (ret != 0) { - ESP_LOGE(TAG, "mp engine lock failed."); - return MP_NG; - } +#if CONFIG_IDF_TARGET_ESP32S3 + /* Activate the RSA accelerator. See 20.3 of ESP32-S3 technical manual. + * periph_module_enable doesn't seem to be documented and in private folder + * with v5 release. Maybe it will be deprecated? */ + if (ret == 0) { + periph_module_enable(PERIPH_RSA_MODULE); + /* clear bit to enable hardware operation; (set to disable) */ + DPORT_REG_CLR_BIT(SYSTEM_RSA_PD_CTRL_REG, SYSTEM_RSA_MEM_PD); + } +#else /* Enable RSA hardware */ - periph_module_enable(PERIPH_RSA_MODULE); + if (ret == 0) { + periph_module_enable(PERIPH_RSA_MODULE); - /* clear bit to enable hardware operation; (set to disable) - */ - DPORT_REG_CLR_BIT(DPORT_RSA_PD_CTRL_REG, DPORT_RSA_PD); + /* clear bit to enable hardware operation; (set to disable) */ + DPORT_REG_CLR_BIT(DPORT_RSA_PD_CTRL_REG, DPORT_RSA_PD); + } +#endif /* reminder: wait until RSA_CLEAN_REG reads 1 * see esp_mp_hw_wait_clean() @@ -145,17 +171,27 @@ static int esp_mp_hw_lock() ESP_LOGV(TAG, "leave esp_mp_hw_lock"); return ret; } + /* -* Release hw engine +* Release HW engine */ static void esp_mp_hw_unlock( void ) { +#if CONFIG_IDF_TARGET_ESP32S3 + /* Deactivate the RSA accelerator. See 20.3 of ESP32-S3 technical manual. + * periph_module_enable doesn't seem to be documented and in private folder + * with v5 release. Maybe it will be deprecated? */ + DPORT_REG_SET_BIT(SYSTEM_RSA_PD_CTRL_REG, SYSTEM_RSA_MEM_PD); + periph_module_disable(PERIPH_RSA_MODULE); + +#else /* set bit to disabled hardware operation; (clear to enable) */ DPORT_REG_SET_BIT(DPORT_RSA_PD_CTRL_REG, DPORT_RSA_PD); /* Disable RSA hardware */ periph_module_disable(PERIPH_RSA_MODULE); +#endif /* unlock */ esp_CryptHwMutexUnLock(&mp_mutex); @@ -189,7 +225,7 @@ static int esp_calc_Mdash(MATH_INT_T *M, word32 k, mp_digit* md) return MP_OKAY; } -/* start hw process */ +/* start HW process */ static void process_start(word32 reg) { /* clear interrupt */ @@ -249,7 +285,8 @@ static void esp_mpint_to_memblock(word32 mem_address, const MATH_INT_T* mp, } } } -/* return needed hw words. + +/* return needed HW words. * supported words length * words : {16 , 32, 48, 64, 80, 96, 112, 128} * bits : {512,1024, 1536, 2048, 2560, 3072, 3584, 4096} @@ -294,7 +331,91 @@ static int esp_get_rinv(MATH_INT_T *rinv, MATH_INT_T *M, word32 exp) int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) { int ret = 0; + +#if CONFIG_IDF_TARGET_ESP32S3 + + int BitsInX = mp_count_bits(X); + int BitsInY = mp_count_bits(Y); + + /* X & Y must be represented by the same number of bits. Must be + * enough to represent the larger one. */ + int MinXYBits = max(BitsInX, BitsInY); + + /* Figure out how many words we need to represent each operand & the result. */ + int WordsForOperand = bits2words(MinXYBits); + int WordsForResult = bits2words(BitsInX + BitsInY); + +#ifdef WOLFSSL_SP_INT_NEGATIVE int neg; + neg = (X->sign == Y->sign) ? MP_ZPOS : MP_NEG; +#endif + /* Make sure we are within capabilities of hardware. */ + if ( (WordsForOperand * BITS_IN_ONE_WORD) > ESP_HW_MULTI_RSAMAX_BITS ) { + ESP_LOGW(TAG, "exceeds max bit length(2048)"); + return MP_VAL; /* Error: value is not able to be used. */ + } + + /* Steps to perform large number multiplication. Calculates Z = X x Y. The number of + * bits in the operands (X, Y) is N. N can be 32x, where x = {1,2,3,...64}, so the + * maximum number of bits in the X and Y is 2048. + * See 20.3.3 of ESP32-S3 technical manual + * 1. Lock the hardware so no-one else uses it and wait until it is ready. + * 2. Enable/disable interrupt that signals completion -- we don't use the interrupt. + * 3. Write number of words required for result to the RSA_MODE_REG (now called RSA_LENGTH_REG). + * Number of words required for the result is 2 * words for operand - 1 + * 4. Load X, Y operands to memory blocks. Note the Y value must be written to + * right aligned. + * 5. Start the operation by writing 1 to RSA_MULT_START_REG, then wait for it + * to complete by monitoring RSA_IDLE_REG (which is now called RSA_QUERY_INTERRUPT_REG). + * 6. Read the result out. + * 7. Release the hardware lock so others can use it. + * x. Clear the interrupt flag, if you used it (we don't). */ + + /* 1. lock HW for use & wait until it is ready. */ + if ( ((ret = esp_mp_hw_lock()) != MP_OKAY) || + ((ret = esp_mp_hw_wait_clean()) != MP_OKAY) ) { + return ret; + } + + /* 2. Disable completion interrupt signal; we don't use. */ + DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); // 0 => no interrupt; 1 => interrupt on completion. + + /* 3. Write number of words required for result. */ + if ( (WordsForOperand * BITS_IN_ONE_WORD * 2) > ESP_HW_RSAMAX_BIT) { + ESP_LOGW(TAG, "result exceeds max bit length"); + return MP_VAL; /* Error: value is not able to be used. */ + } + DPORT_REG_WRITE(RSA_LENGTH_REG, (WordsForOperand * 2 - 1) ); + + /* 4. Load X, Y operands. Maximum is 64 words (64*8*4 = 2048 bits) */ + esp_mpint_to_memblock(RSA_MEM_X_BLOCK_BASE, + X, BitsInX, WordsForOperand); + esp_mpint_to_memblock(RSA_MEM_Z_BLOCK_BASE + WordsForOperand * 4, + Y, BitsInY, WordsForOperand); + + + /* 5. Start operation and wait until it completes. */ + process_start(RSA_MULT_START_REG); + ret = wait_until_done(RSA_QUERY_INTERRUPT_REG); + if (MP_OKAY != ret) { + return ret; + } + + /* 6. read the result form MEM_Z */ + esp_memblock_to_mpint(RSA_MEM_Z_BLOCK_BASE, Z, WordsForResult); + + /* 7. clear and release HW */ + esp_mp_hw_unlock(); + +#ifdef WOLFSSL_SP_INT_NEGATIVE + Z->sign = (Z->used > 0) ? neg : MP_ZPOS; +#endif + + return ret; + /* end if CONFIG_IDF_TARGET_ESP32S3 */ + +#else /* not CONFIG_IDF_TARGET_ESP32S3 */ + /* assumed to be regular Xtensa here */ word32 Xs; word32 Ys; word32 Zs; @@ -302,25 +423,27 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) word32 hwWords_sz; /* neg check - X*Y becomes negative */ +#ifdef WOLFSSL_SP_INT_NEGATIVE neg = mp_isneg(X) != mp_isneg(Y) ? 1 : 0; +#endif /* ask bits number */ Xs = mp_count_bits(X); Ys = mp_count_bits(Y); Zs = Xs + Ys; - /* maximum bits and words for writing to hw */ + /* maximum bits and words for writing to HW */ maxWords_sz = bits2words(max(Xs, Ys)); hwWords_sz = words2hwords(maxWords_sz); /* sanity check */ if((hwWords_sz<<5) > ESP_HW_MULTI_RSAMAX_BITS) { ESP_LOGW(TAG, "exceeds max bit length(2048)"); - return -2; + return MP_VAL; /* Error: value is not able to be used. */ } - /*Steps to use hw in the following order: - * 1. wait until clean hw engine + /*Steps to use HW in the following order: + * 1. wait until clean HW engine * 2. Write(2*N/512bits - 1 + 8) to MULT_MODE_REG * 3. Write X and Y to memory blocks * need to write data to each memory block only according to the length @@ -331,9 +454,9 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) * 6. Write 1 to RSA_INTERRUPT_REG to clear the interrupt. * 7. Read the Z from RSA_Z_MEM * 8. Write 1 to RSA_INTERUPT_REG to clear the interrupt. - * 9. Release the hw engine + * 9. Release the HW engine */ - /* lock hw for use */ + /* lock HW for use */ if ((ret = esp_mp_hw_lock()) != MP_OKAY) { return ret; } @@ -366,14 +489,18 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) /* step.6 read the result form MEM_Z */ esp_memblock_to_mpint(RSA_MEM_Z_BLOCK_BASE, Z, BITS_TO_WORDS(Zs)); - /* step.7 clear and release hw */ + /* step.7 clear and release HW */ esp_mp_hw_unlock(); + +#ifdef WOLFSSL_SP_INT_NEGATIVE if (!mp_iszero(Z) && neg) { mp_setneg(Z); } +#endif return ret; +#endif /* CONFIG_IDF_TARGET_ESP32S3 or not */ } /* Z = X * Y (mod M) */ @@ -392,6 +519,12 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) MATH_INT_T tmpZ; mp_digit mp; + uint32_t Exponent; +#if CONFIG_IDF_TARGET_ESP32S3 + uint32_t OperandBits; + int WordsForOperand; +# endif + /* neg check - X*Y becomes negative */ negcheck = mp_isneg(X) != mp_isneg(Y) ? 1 : 0; @@ -400,27 +533,33 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) Ys = mp_count_bits(Y); Ms = mp_count_bits(M); - /* maximum bits and words for writing to hw */ + /* maximum bits and words for writing to HW */ maxWords_sz = bits2words(max(Xs, max(Ys, Ms))); zwords = bits2words(min(Ms, Xs + Ys)); hwWords_sz = words2hwords(maxWords_sz); if ((hwWords_sz << 5) > ESP_HW_RSAMAX_BIT) { - ESP_LOGE(TAG, "exceeds hw maximum bits"); - return -2; + ESP_LOGE(TAG, "exceeds HW maximum bits"); + return MP_VAL; /* Error: value is not able to be used. */ } /* calculate r_inv = R^2 mode M * where: R = b^n, and b = 2^32 * accordingly R^2 = 2^(n*32*2) */ +#if CONFIG_IDF_TARGET_ESP32S3 + Exponent = maxWords_sz * BITS_IN_ONE_WORD * 2; +#else + Exponent = hwWords_sz << 6; +#endif ret = mp_init_multi(&tmpZ, &r_inv, NULL, NULL, NULL, NULL); - if (ret == 0 && (ret = esp_get_rinv(&r_inv, M, (hwWords_sz << 6))) != MP_OKAY) { + if (ret == 0 && (ret = esp_get_rinv(&r_inv, M, Exponent)) != MP_OKAY) { ESP_LOGE(TAG, "calculate r_inv failed."); mp_clear(&tmpZ); mp_clear(&r_inv); return ret; } - /* lock hw for use */ + + /* lock HW for use */ if ((ret = esp_mp_hw_lock()) != MP_OKAY) { mp_clear(&tmpZ); mp_clear(&r_inv); @@ -431,10 +570,85 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) ESP_LOGE(TAG, "failed to calculate M dash"); mp_clear(&tmpZ); mp_clear(&r_inv); - return -1; + return ret; + } + +#if CONFIG_IDF_TARGET_ESP32S3 + /* Steps to perform large number modular multiplication. Calculates Z = (X x Y) modulo M. + * The number of bits in the operands (X, Y) is N. N can be 32x, where x = {1,2,3,...64}, so the + * maximum number of bits in the X and Y is 2048. We must use the same number of words to represent + * the bits in X, Y and M. + * See 20.3.3 of ESP32-S3 technical manual + * 1. Wait until the hardware is ready. + * 2. Enable/disable interrupt that signals completion -- we don't use the interrupt. + * 3. Write the number of words required to represent the operands to the + * RSA_MODE_REG (now called RSA_LENGTH_REG). + * 4. Write M' value into RSA_M_PRIME_REG (now called RSA_M_DASH_REG). + * 5. Load X, Y, M, r' operands to memory blocks. + * 6. Start the operation by writing 1 to RSA_MOD_MULT_START_REG, then wait for it + * to complete by monitoring RSA_IDLE_REG (which is now called RSA_QUERY_INTERRUPT_REG). + * 7. Read the result out. + * 8. Release the hardware lock so others can use it. + * x. Clear the interrupt flag, if you used it (we don't). */ + + /* 1. Wait until hardware is ready. */ + if ((ret = esp_mp_hw_wait_clean()) != MP_OKAY) { + return ret; } - /*Steps to use hw in the following order: - * 1. wait until clean hw engine + + /* 2. Disable completion interrupt signal; we don't use. */ + DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); // 0 => no interrupt; 1 => interrupt on completion. + + /* 3. Write (N_result_bits/32 - 1) to the RSA_MODE_REG. */ + OperandBits = max(max(Xs, Ys), Ms); + if (OperandBits > ESP_HW_MULTI_RSAMAX_BITS) { + ESP_LOGW(TAG, "result exceeds max bit length"); + return MP_VAL; /* Error: value is not able to be used. */ + } + WordsForOperand = bits2words(OperandBits); + DPORT_REG_WRITE(RSA_LENGTH_REG, WordsForOperand - 1); + + /* 4. Write M' value into RSA_M_PRIME_REG (now called RSA_M_DASH_REG) */ + DPORT_REG_WRITE(RSA_M_DASH_REG, mp); + + /* Select acceleration options. */ + DPORT_REG_WRITE(RSA_CONSTANT_TIME_REG, 0); + + /* 5. Load X, Y, M, r' operands. + * Note RSA_MEM_RB_BLOCK_BASE == RSA_MEM_Z_BLOC_BASE on ESP32s3*/ + esp_mpint_to_memblock(RSA_MEM_X_BLOCK_BASE, X, Xs, hwWords_sz); + esp_mpint_to_memblock(RSA_MEM_Y_BLOCK_BASE, Y, Ys, hwWords_sz); + esp_mpint_to_memblock(RSA_MEM_M_BLOCK_BASE, M, Ms, hwWords_sz); + esp_mpint_to_memblock(RSA_MEM_RB_BLOCK_BASE, &r_inv, mp_count_bits(&r_inv), hwWords_sz); + + /* 6. Start operation and wait until it completes. */ + process_start(RSA_MOD_MULT_START_REG); + ret = wait_until_done(RSA_QUERY_INTERRUPT_REG); + if (MP_OKAY != ret) { + return ret; + } + + /* 7. read the result form MEM_Z */ + esp_memblock_to_mpint(RSA_MEM_Z_BLOCK_BASE, &tmpZ, zwords); + + /* 8. clear and release HW */ + esp_mp_hw_unlock(); + + if (negcheck) { + mp_sub(M, &tmpZ, &tmpZ); + } + + mp_copy(&tmpZ, Z); + mp_clear(&tmpZ); + mp_clear(&r_inv); + + return ret; + /* end if CONFIG_IDF_TARGET_ESP32S3 */ +#else + /* non-S3 Xtensa */ + + /*Steps to use HW in the following order: + * 1. wait until clean HW engine * 2. Write(N/512bits - 1) to MULT_MODE_REG * 3. Write X,M(=G, X, P) to memory blocks * need to write data to each memory block only according to the length @@ -449,10 +663,10 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) * 10. Wait for the second operation to be completed. Poll INTERRUPT_REG until it reads 1. * 11. Read the Z from RSA_Z_MEM * 12. Write 1 to RSA_INTERUPT_REG to clear the interrupt. - * 13. Release the hw engine + * 13. Release the HW engine */ - if ((ret = esp_mp_hw_wait_clean()) != MP_OKAY) { + if ( (ret = esp_mp_hw_wait_clean()) != MP_OKAY ) { return ret; } /* step.1 512 bits => 16 words */ @@ -468,6 +682,7 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) /* step.3 write M' into memory */ DPORT_REG_WRITE(RSA_M_DASH_REG, mp); + /* step.4 start process */ process_start(RSA_MULT_START_REG); @@ -485,7 +700,7 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) /* step.12 read the result from MEM_Z */ esp_memblock_to_mpint(RSA_MEM_Z_BLOCK_BASE, &tmpZ, zwords); - /* step.13 clear and release hw */ + /* step.13 clear and release HW */ esp_mp_hw_unlock(); /* additional steps */ @@ -504,23 +719,25 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) mp_clear(&r_inv); return ret; +#endif } /* Large Number Modular Exponentiation * * Z = X^Y mod M * - * See Chapter 24: - * https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf - * + * See: + * ESP32, Chapter 24, https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf + * ESP32s3, section 20.3.1, https://www.espressif.com/sites/default/files/documentation/esp32-s3_technical_reference_manual_en.pdf * The operation is based on Montgomery multiplication. Aside from the * arguments X, Y , and M, two additional ones are needed —r and M′ .* These arguments are calculated in advance by software. .* .* The RSA Accelerator supports operand lengths of N ∈ {512, 1024, 1536, 2048, -.* 2560, 3072, 3584, 4096} bits. The bit length of arguments Z, X, Y , M, -.* and r can be any one from the N set, but all numbers in a calculation must -.* be of the same length. The bit length of M′ is always 32. +.* 2560, 3072, 3584, 4096} bits on the ESP32 and N ∈ [32, 4096] bits on the ESP32s3. +.* The bit length of arguments Z, X, Y , M, and r can be any one from the N set, +.* but all numbers in a calculation must be of the same length. +.* The bit length of M′ is always 32. .* .* Note some DH references may use: Y = (G ^ X) mod P */ @@ -536,41 +753,111 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, word32 Ys, MATH_INT_T* M, MATH_ MATH_INT_T r_inv; mp_digit mp; +#if CONFIG_IDF_TARGET_ESP32S3 + uint32_t OperandBits; + uint32_t WordsForOperand; +#endif + /* ask bits number */ Xs = mp_count_bits(X); Ms = mp_count_bits(M); - /* maximum bits and words for writing to hw */ + /* maximum bits and words for writing to HW */ maxWords_sz = bits2words(max(Xs, max(Ys, Ms))); hwWords_sz = words2hwords(maxWords_sz); if ((hwWords_sz << 5) > ESP_HW_RSAMAX_BIT) { - ESP_LOGE(TAG, "exceeds hw maximum bits"); - return -2; + ESP_LOGE(TAG, "exceeds HW maximum bits"); + return MP_VAL; /* Error: value is not able to be used. */ } /* calculate r_inv = R^2 mode M * where: R = b^n, and b = 2^32 * accordingly R^2 = 2^(n*32*2) */ ret = mp_init(&r_inv); - if (ret == 0 && (ret = esp_get_rinv(&r_inv, M, (hwWords_sz << 6))) != MP_OKAY) { + if ( (ret == 0) && + ((ret = esp_get_rinv(&r_inv, M, (hwWords_sz << 6))) != MP_OKAY) ) { ESP_LOGE(TAG, "calculate r_inv failed."); mp_clear(&r_inv); return ret; } - /* lock and init the hw */ - if ((ret = esp_mp_hw_lock()) != MP_OKAY) { + /* lock and init the HW */ + if ( (ret = esp_mp_hw_lock()) != MP_OKAY ) { mp_clear(&r_inv); return ret; } /* calc M' */ /* if Pm is odd, uses mp_montgomery_setup() */ - if ((ret = esp_calc_Mdash(M, 32/* bits */, &mp)) != MP_OKAY) { + if ( (ret = esp_calc_Mdash(M, 32/* bits */, &mp)) != MP_OKAY ) { ESP_LOGE(TAG, "failed to calculate M dash"); mp_clear(&r_inv); - return -1; + return ret; + } + +#if CONFIG_IDF_TARGET_ESP32S3 + /* Steps to perform large number modular exponentiation. Calculates Z = (X ^ Y) modulo M. + * The number of bits in the operands (X, Y) is N. N can be 32x, where x = {1,2,3,...64}, so the + * maximum number of bits in the X and Y is 2048. + * See 20.3.3 of ESP32-S3 technical manual + * 1. Wait until the hardware is ready. + * 2. Enable/disable interrupt that signals completion -- we don't use the interrupt. + * 3. Write (N_bits/32 - 1) to the RSA_MODE_REG (now called RSA_LENGTH_REG). + * Here N_bits is the maximum number of bits in X, Y and M. + * 4. Write M' value into RSA_M_PRIME_REG (now called RSA_M_DASH_REG). + * 5. Load X, Y, M, r' operands to memory blocks. + * 6. Start the operation by writing 1 to RSA_MODEXP_START_REG, then wait for it + * to complete by monitoring RSA_IDLE_REG (which is now called RSA_QUERY_INTERRUPT_REG). + * 7. Read the result out. + * 8. Release the hardware lock so others can use it. + * x. Clear the interrupt flag, if you used it (we don't). */ + + /* 1. Wait until hardware is ready. */ + if ((ret = esp_mp_hw_wait_clean()) != MP_OKAY) { + return ret; + } + + /* 2. Disable completion interrupt signal; we don't use. */ + DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); // 0 => no interrupt; 1 => interrupt on completion. + + /* 3. Write (N_result_bits/32 - 1) to the RSA_MODE_REG. */ + OperandBits = max(max(Xs, Ys), Ms); + if (OperandBits > ESP_HW_MULTI_RSAMAX_BITS) { + ESP_LOGW(TAG, "result exceeds max bit length"); + return MP_VAL; /* Error: value is not able to be used. */ } + WordsForOperand = bits2words(OperandBits); + DPORT_REG_WRITE(RSA_LENGTH_REG, WordsForOperand - 1); - /*Steps to use hw in the following order: + /* 4. Write M' value into RSA_M_PRIME_REG (now called RSA_M_DASH_REG) */ + DPORT_REG_WRITE(RSA_M_DASH_REG, mp); + + /* 5. Load X, Y, M, r' operands. */ + esp_mpint_to_memblock(RSA_MEM_X_BLOCK_BASE, X, Xs, hwWords_sz); + esp_mpint_to_memblock(RSA_MEM_Y_BLOCK_BASE, Y, Ys, hwWords_sz); + esp_mpint_to_memblock(RSA_MEM_M_BLOCK_BASE, M, Ms, hwWords_sz); + esp_mpint_to_memblock(RSA_MEM_Z_BLOCK_BASE, &r_inv, + mp_count_bits(&r_inv), hwWords_sz); + + /* 6. Start operation and wait until it completes. */ + process_start(RSA_MODEXP_START_REG); + ret = wait_until_done(RSA_QUERY_INTERRUPT_REG); + if (MP_OKAY != ret) { + return ret; + } + + /* 7. read the result form MEM_Z */ + esp_memblock_to_mpint(RSA_MEM_Z_BLOCK_BASE, Z, BITS_TO_WORDS(Ms)); + + /* 8. clear and release HW */ + esp_mp_hw_unlock(); + + mp_clear(&r_inv); + + return ret; + /* end if CONFIG_IDF_TARGET_ESP32S3 */ +#else + /* non-ESP32S3 Xtensa (regular ESP32) */ + + /* Steps to use HW in the following order: * 1. Write(N/512bits - 1) to MODEXP_MODE_REG * 2. Write X, Y, M and r_inv to memory blocks * need to write data to each memory block only according to the length @@ -605,12 +892,13 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, word32 Ys, MATH_INT_T* M, MATH_ wait_until_done(RSA_INTERRUPT_REG); /* step.6 read a result form memory */ esp_memblock_to_mpint(RSA_MEM_Z_BLOCK_BASE, Z, BITS_TO_WORDS(Ms)); - /* step.7 clear and release hw */ + /* step.7 clear and release HW */ esp_mp_hw_unlock(); mp_clear(&r_inv); return ret; +#endif } #endif /* WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && diff --git a/wolfcrypt/src/port/Espressif/esp32_sha.c b/wolfcrypt/src/port/Espressif/esp32_sha.c index 257a715287c..3f5535ba35a 100644 --- a/wolfcrypt/src/port/Espressif/esp32_sha.c +++ b/wolfcrypt/src/port/Espressif/esp32_sha.c @@ -60,108 +60,569 @@ static const char* TAG = "wolf_hw_sha"; #define WC_SHA_DIGEST_SIZE 20 #endif -/* mutex */ +/* RTOS mutex or just InUse variable */ #if defined(SINGLE_THREADED) static int InUse = 0; #else - static wolfSSL_Mutex sha_mutex; - static int espsha_CryptHwMutexInit = 0; + static wolfSSL_Mutex sha_mutex = NULL; #if defined(DEBUG_WOLFSSL) + /* Only when debugging, we'll keep tracking of block numbers. */ static int this_block_num = 0; #endif #endif -/* - * determine the digest size, depending on SHA type. - * - * See FIPS PUB 180-4, Instruction Section 1. - * - * - enum SHA_TYPE { - SHA1 = 0, - SHA2_256, - SHA2_384, - SHA2_512, - SHA_INVALID = -1, - }; +/* esp_sha_init +** +** ctx: any wolfSSL ctx from any hash algo +** hash_type: the specific wolfSSL enum for hash type +** +** Initializes ctx based on chipset capabilities and current state. +** Active HW states, such as from during a copy operation, are demoted to SW. +** For hash_type not available in HW, set SW mode. +** +** See esp_sha_init_ctx(ctx) */ -static word32 wc_esp_sha_digest_size(enum SHA_TYPE type) +int esp_sha_init(WC_ESP32SHA* ctx, enum wc_HashType hash_type) { - ESP_LOGV(TAG, " esp_sha_digest_size"); + int ret = 0; - switch(type){ - #ifndef NO_SHA - case SHA1: /* typically 20 bytes */ - return WC_SHA_DIGEST_SIZE; - #endif +#if defined(CONFIG_IDF_TARGET_ESP32) || defined(CONFIG_IDF_TARGET_ESP32S3) + switch (hash_type) { /* check each wolfSSL hash type WC_[n] */ + case WC_HASH_TYPE_SHA: + ctx->sha_type = SHA1; /* assign Espressif SHA HW type */ + ret = esp_sha_init_ctx(ctx); + break; - #ifndef NO_SHA256 - case SHA2_256: /* typically 32 bytes */ - return WC_SHA256_DIGEST_SIZE; - #endif + case WC_HASH_TYPE_SHA256: + ctx->sha_type = SHA2_256; /* assign Espressif SHA HW type */ + ret = esp_sha_init_ctx(ctx); + break; - #ifdef WOLFSSL_SHA384 - case SHA2_384: - return WC_SHA384_DIGEST_SIZE; - #endif + #ifdef CONFIG_IDF_TARGET_ESP32S3 + case WC_HASH_TYPE_SHA384: + /* TODO is SHA384 really not supported on -S3? */ + ctx->mode = ESP32_SHA_SW; + ctx->sha_type = SHA2_384; /* Espressif type, but we won't use HW */ + break; + #else + case WC_HASH_TYPE_SHA384: + ctx->sha_type = SHA2_384; /* assign Espressif SHA HW type */ + ret = esp_sha_init_ctx(ctx); + break; + #endif - #ifdef WOLFSSL_SHA512 - case SHA2_512: /* typically 64 bytes */ - return WC_SHA512_DIGEST_SIZE; - #endif + case WC_HASH_TYPE_SHA512: + ctx->sha_type = SHA2_512; /* assign Espressif SHA HW type */ + ret = esp_sha_init_ctx(ctx); + break; + + #ifndef WOLFSSL_NOSHA512_224 + case WC_HASH_TYPE_SHA512_224: + /* Don't call init, always SW as there's no HW. */ + ctx->mode = ESP32_SHA_SW; + ctx->sha_type = SHA2_512; /* Espressif type, but we won't use HW */ + break; + #endif + + #ifndef WOLFSSL_NOSHA512_256 + case WC_HASH_TYPE_SHA512_256: + /* Don't call init, always SW as there's no HW. */ + ctx->mode = ESP32_SHA_SW; + ctx->sha_type = SHA2_512; /* Espressif type, but we won't use HW */ + break; + #endif default: - ESP_LOGE(TAG, "Bad sha type"); - return WC_SHA_DIGEST_SIZE; + ret = esp_sha_init_ctx(ctx); + ESP_LOGW(TAG, "Unexpected hash_type in esp_sha_init"); + break; } - /* we never get here, as all the above switches should have a return */ +#else + /* other chipsets will be implemented here */ +#endif /* defined(CONFIG_IDF_TARGET_ESP32) || defined(CONFIG_IDF_TARGET_ESP32S3) */ + + return ret; } +/* we'll call a separate init as there's only 1 HW acceleration */ +int esp_sha_init_ctx(WC_ESP32SHA* ctx) +{ + if (ctx->initializer == NULL) { + ESP_LOGV(TAG, "regular init of blank WC_ESP32SHA ctx"); + + /* we'll keep track of who initialized this */ + ctx->initializer = ctx; /* save our address in the initializer */ + ctx->mode = ESP32_SHA_INIT; + } + else { + /* things may be more interesting when previously initialized */ + if (ctx->initializer == ctx) { + /* We're likely re-using an existing object previously initialized. + ** There's of course a non-zero probability that garbage data is + ** the same pointer value, but that's highly unlikely; We'd need + ** to discard, then re-init to same memory location for a matching + ** initializer. */ + ESP_LOGV(TAG, "re-using existing WC_ESP32SHA ctx"); + + /* we should never have an unexpected mode in a known ctx */ + switch (ctx->mode) { + case ESP32_SHA_INIT: + case ESP32_SHA_SW: + /* nothing interesting here */ + break; + + case ESP32_SHA_HW: + /* This will be dealt with below: likely demote to SW */ + break; + + case ESP32_SHA_HW_COPY: + /* This is an interesting mode, caller gave HW mode hint */ + ESP_LOGI(TAG, "ALERT: ESP32_SHA_HW_COPY?"); + break; + + default: + /* This should almost occur. We'd need to have an + ** uninitialized ctx that just happens to include the + ** breadcrumb initializer with the same address. */ + ESP_LOGW(TAG, "ALERT: unexpected WC_ESP32SHA ctx mode: " + "%d. ", ctx->mode); + ctx->mode = ESP32_SHA_INIT; + break; + } + /* We don't need to do anything here, + ** this section for diagnostics only. + ** May need to unlock HW, below. */ + } /* ctx->initializer == ctx */ + else { + /* We may end up here with either dirty memory + ** or copied SHA ctx. + ** + ** Any copy function should have already set mode = ESP32_SHA_INIT. + ** + ** In either case, initialize: */ + ctx->initializer = ctx; /* set a new address */ + + /* Always set to ESP32_SHA_INIT, but give debug info as to why: */ + switch (ctx->mode) { + case ESP32_SHA_INIT: + /* if we are already in init mode, nothing to do. */ + break; + + case ESP32_SHA_SW: + /* this should rarely, if ever occur */ + ESP_LOGW(TAG, "ALERT: unexpected SW WC_ESP32SHA ctx mode. " + "Copied? Revert to ESP32_SHA_INIT."); + ctx->mode = ESP32_SHA_INIT; + break; + + case ESP32_SHA_HW: + /* this should rarely, if ever occur. */ + ESP_LOGW(TAG, "ALERT: unexpected HW WC_ESP32SHA ctx mode. " + "Copied?"); + ctx->mode = ESP32_SHA_INIT; + break; + + case ESP32_SHA_HW_COPY: + /* This is an interesting but acceptable situation: + ** an anticipated active HW copy that will demote to SW. */ + ESP_LOGV(TAG, "HW WC_ESP32SHA ctx mode = ESP32_SHA_HW_COPY."); + break; + + default: + /* this will frequently occur during new init */ + ESP_LOGV(TAG, "ALERT: unexpected WC_ESP32SHA ctx mode. " + "Uninitialized?"); + ctx->mode = ESP32_SHA_INIT; + break; + } /* switch */ + } /* ctx->initializer != ctx */ + } /* ctx->initializer != NULL */ + + /* + ** After possibly changing the mode (above) handle current mode: + */ + switch (ctx->mode) { + case ESP32_SHA_INIT: + /* Likely a fresh, new SHA, as desired. */ + ESP_LOGV(TAG, "Normal ESP32_SHA_INIT"); + break; + + case ESP32_SHA_HW: + /* We're already in hardware mode, so release. */ + /* Interesting, but normal. */ + ESP_LOGV(TAG, ">> HW unlock."); + + /* During init is the ONLY TIME we call unlock. + ** If there's a problem, likely some undesired operation + ** outside of wolfSSL. + */ + esp_sha_hw_unlock(ctx); + ctx->mode = ESP32_SHA_INIT; + break; + + case ESP32_SHA_HW_COPY: + /* When we init during a known active HW copy, revert to SW. */ + ESP_LOGV(TAG, "Planned revert to SW during copy."); + ctx->mode = ESP32_SHA_SW; + break; + + case ESP32_SHA_SW: + /* This is an interesting situation: likely a call when + ** another SHA in progress, but copied. */ + ESP_LOGV(TAG, ">> SW Set to init."); + ctx->mode = ESP32_SHA_INIT; + break; + + case ESP32_SHA_FAIL_NEED_UNROLL: + /* Oh, how did we get here? likely uninitialized SHA memory. + ** User code logic may need attention. */ + ESP_LOGW(TAG, "ALERT: \nESP32_SHA_FAIL_NEED_UNROLL\n"); + ctx->mode = ESP32_SHA_INIT; + break; + + default: + /* Most likely corrupted memory. */ + ESP_LOGW(TAG, "ALERT: \nunexpected mode value: " + "%d \n", ctx->mode); + ctx->mode = ESP32_SHA_INIT; + break; + } /* switch (ctx->mode) */ + + /* reminder: always start isfirstblock = 1 (true) when using HW engine */ + /* we're always on the first block at init time (not zero-based!) */ + ctx->isfirstblock = true; + ctx->lockDepth = 0; /* new objects will always start with lock depth = 0 */ + + return 0; /* Always return success. We assume all issues handled, above. */ +} /* esp_sha_init_ctx */ + +/* +** internal SHA ctx copy for ESP HW +*/ +int esp_sha_ctx_copy(struct wc_Sha* src, struct wc_Sha* dst) +{ + int ret; + if (src->ctx.mode == ESP32_SHA_HW) { + /* this is an interesting situation to copy HW digest to SW */ + ESP_LOGV(TAG, "esp_sha_ctx_copy esp_sha_digest_process"); + + /* Get a copy of the HW digest, but don't process it. */ + ret = esp_sha_digest_process(dst, 0); + if (ret == 0) { + /* note we arrived here only because the src is already in HW mode */ + dst->ctx.mode = ESP32_SHA_HW_COPY; /* provide init hint to SW revert */ + + /* initializer will be set during init */ + ret = esp_sha_init(&(dst->ctx), WC_HASH_TYPE_SHA); + if (ret != 0) { + ESP_LOGE(TAG, "Error during esp_sha_ctx_copy in esp_sha_init."); + } + } + else { + ESP_LOGE(TAG, "Error during esp_sha_ctx_copy in esp_sha_digest_process."); + } + + if (dst->ctx.mode == ESP32_SHA_SW) { + /* The normal revert to SW in copy is expected */ + ESP_LOGV(TAG, "Confirmed SHA Copy set to SW"); + } + else { + /* However NOT reverting to SW is not right. + ** This should never happen. */ + ESP_LOGW(TAG, "SHA Copy NOT set to SW"); + } + } /* (src->ctx.mode == ESP32_SHA_HW */ + else { /* src not in HW mode, ok to copy. */ + /* + ** reminder XMEMCOPY, above: dst->ctx = src->ctx; + ** No special HW init needed in SW mode. + ** but we need to set our initializer breadcrumb: */ + dst->ctx.initializer = &(dst->ctx); /* assign new breadcrumb to dst */ + ret = 0; + } + + return ret; +} /* esp_sha_ctx_copy */ + +/* +** internal sha224 ctx copy (no ESP HW) +*/ +int esp_sha224_ctx_copy(struct wc_Sha256* src, struct wc_Sha256* dst) +{ + /* There's no 224 hardware on ESP32 */ + dst->ctx.initializer = &dst->ctx; /* assign the initializer to dst */ + + /* always set to SW, as there's no ESP32 HW for SHA224. + ** TODO: add support for ESP32-S2. ESP32-S3, ESP32-C3 here. + */ + dst->ctx.mode = ESP32_SHA_SW; + return 0; +} /* esp_sha224_ctx_copy */ + +/* +** internal sha256 ctx copy for ESP HW +*/ +int esp_sha256_ctx_copy(struct wc_Sha256* src, struct wc_Sha256* dst) +{ + int ret; + if (src->ctx.mode == ESP32_SHA_HW) { + /* Get a copy of the HW digest, but don't process it. */ + ESP_LOGI(TAG, "esp_sha256_ctx_copy esp_sha512_digest_process"); + ret = esp_sha256_digest_process(dst, 0); + + if (ret == 0) { + /* provide init hint to possibly SW revert */ + dst->ctx.mode = ESP32_SHA_HW_COPY; + + /* initializer breadcrumb will be set during init */ + ret = esp_sha_init(&(dst->ctx), WC_HASH_TYPE_SHA256 ); + } + + if (dst->ctx.mode == ESP32_SHA_SW) { + ESP_LOGV(TAG, "Confirmed wc_Sha256 Copy set to SW"); + } + else { + ESP_LOGW(TAG, "wc_Sha256 Copy NOT set to SW"); + } + } /* (src->ctx.mode == ESP32_SHA_HW) */ + else { + ret = 0; + /* + ** reminder this happened in XMEMCOPY: dst->ctx = src->ctx; + ** No special HW init needed in SW mode. + ** but we need to set our initializer: */ + dst->ctx.initializer = &dst->ctx; /* assign the initializer to dst */ + } /* not (src->ctx.mode == ESP32_SHA_HW) */ + + return ret; +} /* esp_sha256_ctx_copy */ + +/* +** internal sha384 ctx copy for ESP HW +*/ +int esp_sha384_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst) +{ + int ret; + if (src->ctx.mode == ESP32_SHA_HW) { + /* Get a copy of the HW digest, but don't process it. */ + ESP_LOGI(TAG, "esp_sha384_ctx_copy esp_sha512_digest_process"); + ret = esp_sha512_digest_process(dst, 0); + if (ret == 0) { + /* provide init hint to SW revert */ + dst->ctx.mode = ESP32_SHA_HW_COPY; + + /* initializer will be set during init */ + ret = esp_sha_init(&(dst->ctx), WC_HASH_TYPE_SHA384); + if (ret != 0) { + ESP_LOGE(TAG, "Error during esp_sha384_ctx_copy in esp_sha_init."); + } + } + else { + ESP_LOGE(TAG, "Error during esp_sha384_ctx_copy in esp_sha512_digest_process."); + } + + /* just some diagnostic runtime info */ + if (dst->ctx.mode == ESP32_SHA_SW) { + ESP_LOGV(TAG, "Confirmed wc_Sha512 Copy set to SW"); + } + else { + ESP_LOGW(TAG, "wc_Sha512 Copy NOT set to SW"); + } + } /* src->ctx.mode == ESP32_SHA_HW */ + else { + ret = 0; + /* + ** reminder this happened in XMEMCOPY, above: dst->ctx = src->ctx; + ** No special HW init needed in SW mode. + ** but we need to set our initializer: */ + dst->ctx.initializer = &dst->ctx; /* assign the initializer to dst */ + } /* not (src->ctx.mode == ESP32_SHA_HW) */ + + return ret; +} /* esp_sha384_ctx_copy */ + +/* +** Internal sha512 ctx copy for ESP HW. +** If HW already active, fall back to SW for this ctx. +*/ +int esp_sha512_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst) +{ + int ret; + if (src->ctx.mode == ESP32_SHA_HW) { + /* Get a copy of the HW digest, but don't process it. */ + ESP_LOGI(TAG, "esp_sha512_ctx_copy esp_sha512_digest_process"); + ret = esp_sha512_digest_process(dst, 0); + + if (ret == 0) { + /* provide init hint to SW revert */ + dst->ctx.mode = ESP32_SHA_HW_COPY; + + /* initializer will be set during init + ** reminder we should never arrive here for + ** ESP32 SHA512/224 or SHA512/224, as there's no HW */ + ret = esp_sha_init(&(dst->ctx), WC_HASH_TYPE_SHA512); + } + + if (dst->ctx.mode == ESP32_SHA_SW) { + ESP_LOGV(TAG, "Confirmed wc_Sha512 Copy set to SW"); + } + else { + ESP_LOGW(TAG, "wc_Sha512 Copy NOT set to SW"); + } + } /* src->ctx.mode == ESP32_SHA_HW */ + else { + ret = 0; + /* reminder this happened in XMEMCOPY, above: dst->ctx = src->ctx; + ** No special HW init needed when not in active HW mode. + ** but we need to set our initializer breadcrumb: */ + dst->ctx.initializer = &dst->ctx; /*breadcrumb is this ctx address */ + } + + return ret; +} /* esp_sha512_ctx_copy */ + /* -* wait until all engines becomes idle +** determine the digest size, depending on SHA type. +** +** See FIPS PUB 180-4, Instruction Section 1. +** +** see ESP32 shah.h for values: +** +** enum SHA_TYPE { +** SHA1 = 0, +** SHA2_256, +** SHA2_384, +** SHA2_512, +** SHA_INVALID = -1, +** }; +** +** given the SHA_TYPE (see Espressif sha.h) return WC digest size. +** +** Returns zero for bad digest size type request. +** */ -static void wc_esp_wait_until_idle() +static word32 wc_esp_sha_digest_size(enum SHA_TYPE type) { - while((DPORT_REG_READ(SHA_1_BUSY_REG) != 0) || - (DPORT_REG_READ(SHA_256_BUSY_REG) != 0) || - (DPORT_REG_READ(SHA_384_BUSY_REG) != 0) || - (DPORT_REG_READ(SHA_512_BUSY_REG) != 0)) { + int ret = 0; + ESP_LOGV(TAG, " esp_sha_digest_size"); + + switch (type) { + #ifndef NO_SHA + case SHA1: /* typically 20 bytes */ + ret = WC_SHA_DIGEST_SIZE; + break; +#endif + #ifdef WOLFSSL_SHA224 + /* + no SHA224 HW at this time. + case SHA2_224: + ret = WC_SHA224_DIGEST_SIZE; + break; + */ + #endif + #ifndef NO_SHA256 + case SHA2_256: /* typically 32 bytes */ + ret = WC_SHA256_DIGEST_SIZE; + break; +#endif + #ifdef WOLFSSL_SHA384 + case SHA2_384: + ret = WC_SHA384_DIGEST_SIZE; + break; +#endif + #ifdef WOLFSSL_SHA512 + case SHA2_512: /* typically 64 bytes */ + ret = WC_SHA512_DIGEST_SIZE; + break; +#endif + default: + ESP_LOGE(TAG, "Bad SHA type in wc_esp_sha_digest_size"); + ret = 0; + break; + } + + return ret; /* Return value is a size, not an error code. */ +} /* wc_esp_sha_digest_size */ + +/* +** wait until all engines becomes idle +*/ +static int wc_esp_wait_until_idle(void) +{ + int ret = 0; /* assume success */ + +#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + /* ESP32-C3 RISC-V TODO */ +#elif defined(CONFIG_IDF_TARGET_ESP32S3) + while (REG_READ(SHA_BUSY_REG)) { + /* do nothing while waiting. */ + } +#else + while ((DPORT_REG_READ(SHA_1_BUSY_REG) != 0) || + (DPORT_REG_READ(SHA_256_BUSY_REG) != 0) || + (DPORT_REG_READ(SHA_384_BUSY_REG) != 0) || + (DPORT_REG_READ(SHA_512_BUSY_REG) != 0)) { /* do nothing while waiting. */ } -} +#endif + + return ret; +} /* wc_esp_wait_until_idle */ /* - * hack alert. there really should have been something implemented - * in periph_ctrl.c to detect ref_counts[periph] depth. - * - * since there is not at this time, we have this brute-force method. - * - * when trying to unwrap an arbitrary depth of peripheral-enable(s), - * we'll check the register upon *enable* to see if we actually did. - * - * Note that enable / disable only occurs when ref_counts[periph] == 0 - * - * TODO: check if this works with other ESP32 platforms ESP32-C3, ESP32-S3, etc - */ +** hack alert. there really should have been something implemented +** in Espressif periph_ctrl.c to detect ref_counts[periph] depth. +** +** since there is not at this time, we have this brute-force method. +** +** when trying to unwrap an arbitrary depth of peripheral-enable(s), +** we'll check the register upon *enable* to see if we actually did. +** +** Note that enable / disable only occurs when ref_counts[periph] == 0 +** +** TODO: check if this works with other ESP32 platforms ESP32-C3, +** ESP32-S3, etc. (A: generally, no. RISC-V has different HW accelerator.) +*/ int esp_unroll_sha_module_enable(WC_ESP32SHA* ctx) { /* if we end up here, there was a prior unexpected fail and * we need to unroll enables */ int ret = 0; /* assume success unless proven otherwise */ - uint32_t this_sha_mask; /* this is the bit-mask for our SHA CLK_EN_REG */ int actual_unroll_count = 0; int max_unroll_count = 1000; /* never get stuck in a hardware wait loop */ - this_sha_mask = periph_ll_get_clk_en_mask(PERIPH_SHA_MODULE); +#if defined(CONFIG_IDF_TARGET_ESP32) + uint32_t this_sha_mask; /* this is the bit-mask for our SHA CLK_EN_REG */ +#endif + + if (ctx == NULL) { + ESP_LOGE(TAG, "esp_unroll_sha_module_enable called with null ctx."); + return BAD_FUNC_ARG; + } + +#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + /* RISC-V Architecture: TODO */ +#else + /* Xtensa Architecture */ /* unwind prior calls to THIS ctx. decrement ref_counts[periph] */ /* only when ref_counts[periph] == 0 does something actually happen */ /* once the value we read is a 0 in the DPORT_PERI_CLK_EN_REG bit * then we have fully unrolled the enables via ref_counts[periph]==0 */ +#if CONFIG_IDF_TARGET_ESP32S3 + /* once the value we read is a 0 in the DPORT_PERI_CLK_EN_REG bit + * then we have fully unrolled the enables via ref_counts[periph]==0 */ + while (periph_ll_periph_enabled(PERIPH_SHA_MODULE)) { +#else + /* this is the bit-mask for our SHA CLK_EN_REG */ + this_sha_mask = periph_ll_get_clk_en_mask(PERIPH_SHA_MODULE); + asm volatile("memw"); while ((this_sha_mask & *(uint32_t*)DPORT_PERI_CLK_EN_REG) != 0) { +#endif /* CONFIG_IDF_TARGET_ESP32S3 */ periph_module_disable(PERIPH_SHA_MODULE); + asm volatile("memw"); actual_unroll_count++; ESP_LOGI(TAG, "unroll not yet successful. try #%d", actual_unroll_count); @@ -173,38 +634,45 @@ int esp_unroll_sha_module_enable(WC_ESP32SHA* ctx) break; } } - +#endif /* else; not RISC-V */ if (ret == 0) { if (ctx->lockDepth != actual_unroll_count) { /* this could be a warning of wonkiness in RTOS environment. - * we were successful, but not expected depth count*/ - - ESP_LOGV(TAG, "warning lockDepth mismatch."); + ** we were successful, but not expected depth count. + ** + ** This should never happen unless someone else called + ** periph_module_disable() or threading not working properly. + **/ + ESP_LOGW(TAG, "warning lockDepth mismatch."); } ctx->lockDepth = 0; ctx->mode = ESP32_SHA_INIT; } else { + /* This should never occur. Something must have gone seriously + ** wrong. Check for non-wolfSSL outside calls that may have enabled HW. + */ ESP_LOGE(TAG, "Failed to unroll after %d attempts.", - actual_unroll_count); + actual_unroll_count); + ESP_LOGI(TAG, "Setting ctx->mode = ESP32_SHA_SW"); ctx->mode = ESP32_SHA_SW; } return ret; -} +} /* esp_unroll_sha_module_enable */ /* -* lock hw engine. -* this should be called before using engine. +** lock HW engine. +** this should be called before using engine. */ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) { int ret = 0; - ESP_LOGV(TAG, "enter esp_sha_hw_lock"); + ESP_LOGV(TAG, "enter esp_sha_hw_lock %x", (int)ctx->initializer); if (ctx == NULL) { ESP_LOGE(TAG, " esp_sha_try_hw_lock called with NULL ctx"); - return -1; + return BAD_FUNC_ARG; } /* Init mutex @@ -214,8 +682,8 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) * engine being busy or not. **/ #if defined(SINGLE_THREADED) - if(ctx->mode == ESP32_SHA_INIT) { - if(!InUse) { + if (ctx->mode == ESP32_SHA_INIT) { + if (!InUse) { ctx->mode = ESP32_SHA_HW; InUse = 1; } @@ -230,55 +698,70 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) } #else /* not defined(SINGLE_THREADED) */ /* - * there's only one SHA engine for all the hash types - * so when any hash is in use, no others can use it. - * fall back to SW. - **/ + ** there's only one SHA engine for all the hash types + ** so when any hash is in use, no others can use it. + ** fall back to SW. + ** + ** here is some sample code to test the unrolling of SHA enables: + ** - /* - * here is some sample code to test the unrolling of sha enables: - * periph_module_enable(PERIPH_SHA_MODULE); ctx->lockDepth++; periph_module_enable(PERIPH_SHA_MODULE); ctx->lockDepth++; ctx->mode = ESP32_FAIL_NEED_INIT; + ** */ - if (espsha_CryptHwMutexInit == 0) { - ESP_LOGV(TAG, "set esp_CryptHwMutexInit"); + if (sha_mutex == NULL) { + ESP_LOGV(TAG, "Initializing sha_mutex"); + + /* created, but not yet locked */ ret = esp_CryptHwMutexInit(&sha_mutex); if (ret == 0) { - espsha_CryptHwMutexInit = 1; + ESP_LOGV(TAG, "esp_CryptHwMutexInit sha_mutex init success."); } else { - ESP_LOGE(TAG, " mutex initialization failed. revert to software"); + ESP_LOGE(TAG, "esp_CryptHwMutexInit sha_mutex failed."); + sha_mutex = 0; + + ESP_LOGI(TAG, "Revert to ctx->mode = ESP32_SHA_SW."); ctx->mode = ESP32_SHA_SW; - /* espsha_CryptHwMutexInit is still zero */ return 0; /* success, just not using HW */ } } - /* check if this sha has been operated as sw or hw, or not yet init */ + /* check if this SHA has been operated as SW or HW, or not yet init */ if (ctx->mode == ESP32_SHA_INIT) { - /* try to lock the hw engine */ + /* try to lock the HW engine */ ESP_LOGV(TAG, "ESP32_SHA_INIT\n"); /* we don't wait: - * either the engine is free, or we fall back to SW - */ + ** either the engine is free, or we fall back to SW + **/ if (esp_CryptHwMutexLock(&sha_mutex, (TickType_t)0) == 0) { /* check to see if we had a prior fail and need to unroll enables */ ret = esp_unroll_sha_module_enable(ctx); - ESP_LOGV(TAG, "Hardware Mode, lock depth = %d", ctx->lockDepth); + ESP_LOGV(TAG, "Hardware Mode, lock depth = %d, %x", + ctx->lockDepth, (int)ctx->initializer); + + if (ctx->lockDepth > 0) { + /* it is unlikely that this would ever occur, + ** as the mutex should be gate keeping */ + ESP_LOGW(TAG, "WARNING: Hardware Mode " + "interesting lock depth = %d, %x", + ctx->lockDepth, (int)ctx->initializer); + } } else { - ESP_LOGV(TAG, ">>>> Hardware in use; Mode REVERT to ESP32_SHA_SW"); + /* We should have otherwise anticipated this; how did we get here? + ** This code should rarely, ideally never be reached. */ + ESP_LOGI(TAG, "\nHardware in use; Mode REVERT to ESP32_SHA_SW\n"); ctx->mode = ESP32_SHA_SW; return 0; /* success, but revert to SW */ } - } + } /* (ctx->mode == ESP32_SHA_INIT) */ else { /* this should not happen: called during mode != ESP32_SHA_INIT */ ESP_LOGE(TAG, "unexpected error in esp_sha_try_hw_lock."); @@ -286,37 +769,37 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) } #endif /* not defined(SINGLE_THREADED) */ +#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + /* ESP32-C3 RISC-V TODO */ +#else if (ret == 0) { ctx->lockDepth++; /* depth for THIS ctx (there could be others!) */ periph_module_enable(PERIPH_SHA_MODULE); ctx->mode = ESP32_SHA_HW; } else { - ESP_LOGI(TAG, ">>>> Other problem; Mode REVERT to ESP32_SHA_SW"); + ESP_LOGW(TAG, ">>>> Other problem; Mode REVERT to ESP32_SHA_SW"); ctx->mode = ESP32_SHA_SW; } - +#endif ESP_LOGV(TAG, "leave esp_sha_hw_lock"); + return ret; } /* esp_sha_try_hw_lock */ /* -* release hw engine. when we don't have it locked, SHA module is DISABLED +** release HW engine. when we don't have it locked, SHA module is DISABLED */ int esp_sha_hw_unlock(WC_ESP32SHA* ctx) { ESP_LOGV(TAG, "enter esp_sha_hw_unlock"); +#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + /* ESP32-C3 RISC-V TODO */ +#else /* Disable AES hardware */ periph_module_disable(PERIPH_SHA_MODULE); - - #if defined(SINGLE_THREADED) - InUse = 0; - #else - /* unlock hw engine for next use */ - esp_CryptHwMutexUnLock(&sha_mutex); - #endif - +#endif /* we'll keep track of our lock depth. * in case of unexpected results, all the periph_module_disable() calls * and periph_module_disable() need to be unwound. @@ -329,24 +812,86 @@ int esp_sha_hw_unlock(WC_ESP32SHA* ctx) ctx->lockDepth = 0; } - ESP_LOGV(TAG, "leave esp_sha_hw_unlock"); +#if defined(SINGLE_THREADED) + InUse = 0; +#else + /* unlock HW engine for next use */ + esp_CryptHwMutexUnLock(&sha_mutex); +#endif + ESP_LOGV(TAG, "leave esp_sha_hw_unlock, %x", (int)ctx->initializer); return 0; } /* esp_sha_hw_unlock */ /* -* start sha process by using hw engine. -* assumes register already loaded. +* Start SHA process by using HW engine. +* Assumes register already loaded. +* Returns a negative value error code upon failure. */ static int esp_sha_start_process(WC_ESP32SHA* sha) { int ret = 0; +#if defined(CONFIG_IDF_TARGET_ESP32S3) + uint8_t HardwareAlgorithm; +#endif + if (sha == NULL) { - return -1; + return BAD_FUNC_ARG; } ESP_LOGV(TAG, " enter esp_sha_start_process"); - if(sha->isfirstblock){ + #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + /* ESP32-C3 RISC-V TODO */ + #elif defined(CONFIG_IDF_TARGET_ESP32S3) + + /* Translate from Wolf SHA type to hardware algorithm. */ + HardwareAlgorithm = 0; + switch (sha->sha_type) { + case SHA1: + HardwareAlgorithm = 0; + break; + case SHA2_256: + HardwareAlgorithm = 2; + break; + #if defined(WOLFSSL_SHA384) + case SHA2_384: + uHardwareAlgorithm = 3; + break; + #endif + #if defined(WOLFSSL_SHA512) + case SHA2_512: + HardwareAlgorithm = 4; + break; + #endif + default: + /* Unsupported SHA mode. */ + sha->mode = ESP32_SHA_FAIL_NEED_UNROLL; + return -1; + } + + REG_WRITE(SHA_MODE_REG, HardwareAlgorithm); + + if (sha->isfirstblock) { + REG_WRITE(SHA_START_REG, 1); + sha->isfirstblock = false; + + ESP_LOGV(TAG, " set sha->isfirstblock = 0"); + + #if defined(DEBUG_WOLFSSL) + this_block_num = 1; /* one-based counter, just for debug info */ + #endif + } /* first block */ + else { + REG_WRITE(SHA_CONTINUE_REG, 1); + + #if defined(DEBUG_WOLFSSL) + this_block_num++; /* one-based counter */ + ESP_LOGV(TAG, " continue block #%d", this_block_num); + #endif + } /* not first block */ + +#else /* not ESP32S3 */ + if (sha->isfirstblock) { /* start registers for first message block * we don't make any relational memory position assumptions. */ @@ -357,7 +902,7 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) case SHA2_256: DPORT_REG_WRITE(SHA_256_START_REG, 1); - break; + break; #if defined(WOLFSSL_SHA384) case SHA2_384: @@ -368,25 +913,25 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) #if defined(WOLFSSL_SHA512) case SHA2_512: DPORT_REG_WRITE(SHA_512_START_REG, 1); - break; + break; #endif default: sha->mode = ESP32_SHA_FAIL_NEED_UNROLL; ret = -1; break; - } + } - sha->isfirstblock = 0; + sha->isfirstblock = false; ESP_LOGV(TAG, " set sha->isfirstblock = 0"); - #if defined(DEBUG_WOLFSSL) - this_block_num = 1; /* one-based counter, just for debug info */ - #endif + #if defined(DEBUG_WOLFSSL) + this_block_num = 1; /* one-based counter, just for debug info */ + #endif } else { - /* continue */ + /* continue registers for next message block. * we don't make any relational memory position assumptions * for future chip architecture changes. @@ -398,7 +943,7 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) case SHA2_256: DPORT_REG_WRITE(SHA_256_CONTINUE_REG, 1); - break; + break; #if defined(WOLFSSL_SHA384) case SHA2_384: @@ -409,7 +954,7 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) #if defined(WOLFSSL_SHA512) case SHA2_512: DPORT_REG_WRITE(SHA_512_CONTINUE_REG, 1); - break; + break; #endif default: @@ -417,85 +962,154 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) sha->mode = ESP32_SHA_FAIL_NEED_UNROLL; ret = -1; break; - } + } + } + #endif + #if defined(DEBUG_WOLFSSL) this_block_num++; /* one-based counter */ ESP_LOGV(TAG, " continue block #%d", this_block_num); #endif - } - ESP_LOGV(TAG, " leave esp_sha_start_process"); return ret; } /* -* process message block +** process message block */ -static void wc_esp_process_block(WC_ESP32SHA* ctx, /* see ctx->sha_type */ +static int wc_esp_process_block(WC_ESP32SHA* ctx, /* see ctx->sha_type */ const word32* data, word32 len) { + int ret = 0; /* assume success */ + word32 word32_to_save = (len) / (sizeof(word32)); +#ifdef CONFIG_IDF_TARGET_ESP32S3 + uint32_t* MessageSource; + uint32_t* AcceleratorMessage; +#else int i; - int word32_to_save = (len) / (sizeof(word32)); +#endif ESP_LOGV(TAG, " enter esp_process_block"); if (word32_to_save > 0x31) { word32_to_save = 0x31; - ESP_LOGE(TAG, " ERROR esp_process_block len exceeds 0x31 words"); + ESP_LOGE(TAG, " ERROR esp_process_block length exceeds 0x31 words."); } - /* check if there are any busy engine */ - wc_esp_wait_until_idle(); + /* wait until the engine is available */ + ret = wc_esp_wait_until_idle(); + +#if CONFIG_IDF_TARGET_ESP32S3 + MessageSource = (uint32_t*)data; + AcceleratorMessage = (uint32_t*)(SHA_TEXT_BASE); + while (word32_to_save--) { + /* Must swap endianness of data loaded into hardware accelerator to produce + * correct result. Using DPORT_REG_WRITE doesn't avoid this for ESP32s3. + * Note: data sheet claims we also need to swap endianness across 64 byte words + * when doing SHA-512, but the SHA-512 result is not correct if you do that. */ + DPORT_REG_WRITE(AcceleratorMessage, __builtin_bswap32(*MessageSource)); + ++AcceleratorMessage; + ++MessageSource; + } /* (word32_to_save--) */ - /* load [len] words of message data into hw */ +#else + /* load [len] words of message data into HW */ for (i = 0; i < word32_to_save; i++) { /* by using DPORT_REG_WRITE, we avoid the need - * to call __builtin_bswap32 to address endiness + * to call __builtin_bswap32 to address endianness. * * a useful watch array cast to watch at runtime: * ((uint32_t[32]) (*(volatile uint32_t *)(SHA_TEXT_BASE))) * * Write value to DPORT register (does not require protecting) */ + #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + /* ESP32-C3 RISC-V TODO */ + #else DPORT_REG_WRITE(SHA_TEXT_BASE + (i*sizeof(word32)), *(data + i)); + #endif /* memw confirmed auto inserted by compiler here */ } +#endif - /* notify hw to start process + /* notify HW to start process * see ctx->sha_type * reg data does not change until we are ready to read */ - esp_sha_start_process(ctx); + ret = esp_sha_start_process(ctx); ESP_LOGV(TAG, " leave esp_process_block"); -} + return ret; +} /* wc_esp_process_block */ /* - * retrieve sha digest from memory - */ +** retrieve SHA digest from memory +*/ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) { + word32 digestSz; + +#if CONFIG_IDF_TARGET_ESP32S3 + uint64_t* pHash64Buffer; + uint32_t* pHashDestination; + size_t szHashWords; + size_t szHash64Words; +# endif + ESP_LOGV(TAG, "enter esp_digest_state"); - if (ctx == NULL) { - return -1; + if (ctx == NULL) { + return BAD_FUNC_ARG; } /* sanity check */ - if (ctx->sha_type == SHA_INVALID) { + digestSz = wc_esp_sha_digest_size(ctx->sha_type); + if (digestSz == 0) { ctx->mode = ESP32_SHA_FAIL_NEED_UNROLL; ESP_LOGE(TAG, "unexpected error. sha_type is invalid."); return -1; } - - if (ctx == NULL) { - return -1; +#if CONFIG_IDF_TARGET_ESP32S3 + if (ctx->isfirstblock == true) { + /* no hardware use yet. Nothing to do yet */ + return 0; } /* wait until idle */ wc_esp_wait_until_idle(); + /* read hash result into buffer & flip endianness */ + pHashDestination = (uint32_t*)hash; + szHashWords = wc_esp_sha_digest_size(ctx->sha_type) / sizeof(uint32_t); + esp_dport_access_read_buffer(pHashDestination, SHA_H_BASE, szHashWords); + + if (ctx->sha_type == SHA2_512) { + /* Although we don't have to swap endianness on 64-bit words + ** at the input, we do for the output. */ + szHash64Words = szHashWords / 2; + pHash64Buffer = (uint64_t*)pHashDestination; + while (szHash64Words--) { + *pHash64Buffer = __builtin_bswap64(*pHash64Buffer); + ++pHash64Buffer; + } + } /* (ctx->sha_type == SHA2_512) */ + else { + while (szHashWords--) { + *pHashDestination = __builtin_bswap32(*pHashDestination); + ++pHashDestination; + } + } /* not (ctx->sha_type == SHA2_512) */ + + /* end if CONFIG_IDF_TARGET_ESP32S3 */ +#else + /* not CONFIG_IDF_TARGET_ESP32S3 */ + /* wait until idle */ + wc_esp_wait_until_idle(); + /* each sha_type register is at a different location */ +#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + /* ESP32-C3 RISC-V TODO */ +#else switch (ctx->sha_type) { case SHA1: DPORT_REG_WRITE(SHA_1_LOAD_REG, 1); @@ -520,16 +1134,13 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) default: ctx->mode = ESP32_SHA_FAIL_NEED_UNROLL; return -1; - break; } - - if(ctx->isfirstblock == 1){ + if (ctx->isfirstblock == true) { /* no hardware use yet. Nothing to do yet */ return 0; } - /* LOAD final digest */ wc_esp_wait_until_idle(); @@ -549,21 +1160,23 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) * example: * DPORT_SEQUENCE_REG_READ(address + i * 4); */ + esp_dport_access_read_buffer( #if ESP_IDF_VERSION_MAJOR >= 4 - (uint32_t*)(hash), /* the result will be found in hash upon exit */ + (uint32_t*)(hash), /* the result will be found in hash upon exit */ #else - (word32*)(hash), /* the result will be found in hash upon exit */ + (word32*)(hash), /* the result will be found in hash upon exit */ #endif - SHA_TEXT_BASE, /* there's a fixed reg addy for all SHA */ - wc_esp_sha_digest_size(ctx->sha_type) / sizeof(word32) /* # 4-byte */ + SHA_TEXT_BASE, /* there's a fixed reg addr for all SHA */ + digestSz / sizeof(word32) /* # 4-byte */ ); +#endif #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) if (ctx->sha_type == SHA2_384 || ctx->sha_type == SHA2_512) { word32 i; word32* pwrd1 = (word32*)(hash); - /* swap value */ + /* swap 32 bit words in 64 bit values */ for (i = 0; i < WC_SHA512_DIGEST_SIZE / 4; i += 2) { pwrd1[i] ^= pwrd1[i + 1]; pwrd1[i + 1] ^= pwrd1[i]; @@ -571,14 +1184,15 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) } } #endif +#endif /* not CONFIG_IDF_TARGET_ESP32S3 */ ESP_LOGV(TAG, "leave esp_digest_state"); return 0; -} +} /* wc_esp_digest_state */ #ifndef NO_SHA /* -* sha1 process +** sha1 process */ int esp_sha_process(struct wc_Sha* sha, const byte* data) { @@ -589,11 +1203,12 @@ int esp_sha_process(struct wc_Sha* sha, const byte* data) wc_esp_process_block(&sha->ctx, (const word32*)data, WC_SHA_BLOCK_SIZE); ESP_LOGV(TAG, "leave esp_sha_process"); + return ret; -} +} /* esp_sha_process */ /* -* retrieve sha1 digest +** retrieve sha1 digest */ int esp_sha_digest_process(struct wc_Sha* sha, byte blockprocess) { @@ -605,20 +1220,20 @@ int esp_sha_digest_process(struct wc_Sha* sha, byte blockprocess) wc_esp_process_block(&sha->ctx, sha->buffer, WC_SHA_BLOCK_SIZE); } - wc_esp_digest_state(&sha->ctx, (byte*)sha->digest); + ret = wc_esp_digest_state(&sha->ctx, (byte*)sha->digest); ESP_LOGV(TAG, "leave esp_sha_digest_process"); return ret; -} +} /* esp_sha_digest_process */ #endif /* NO_SHA */ #ifndef NO_SHA256 /* -* sha256 process -* -* repeatedly call this for [N] blocks of [WC_SHA256_BLOCK_SIZE] bytes of data +** sha256 process +** +** repeatedly call this for [N] blocks of [WC_SHA256_BLOCK_SIZE] bytes of data */ int esp_sha256_process(struct wc_Sha256* sha, const byte* data) { @@ -628,12 +1243,12 @@ int esp_sha256_process(struct wc_Sha256* sha, const byte* data) if ((&sha->ctx)->sha_type == SHA2_256) { #if defined(DEBUG_WOLFSSL_VERBOSE) - ESP_LOGV(TAG, " confirmed sha type call match"); + ESP_LOGV(TAG, " confirmed SHA type call match"); #endif } else { ret = -1; - ESP_LOGE(TAG, " ERROR sha type call mismatch"); + ESP_LOGE(TAG, " ERROR SHA type call mismatch"); } wc_esp_process_block(&sha->ctx, (const word32*)data, WC_SHA256_BLOCK_SIZE); @@ -641,13 +1256,13 @@ int esp_sha256_process(struct wc_Sha256* sha, const byte* data) ESP_LOGV(TAG, " leave esp_sha256_process"); return ret; -} +} /* esp_sha256_process */ /* -* retrieve sha256 digest -* -* note that wc_Sha256Final() in sha256.c expects to need to reverse byte -* order, even though we could have returned them in the right order. +** retrieve sha256 digest +** +** note that wc_Sha256Final() in sha256.c expects to need to reverse byte +** order, even though we could have returned them in the right order. */ int esp_sha256_digest_process(struct wc_Sha256* sha, byte blockprocess) { @@ -655,8 +1270,7 @@ int esp_sha256_digest_process(struct wc_Sha256* sha, byte blockprocess) ESP_LOGV(TAG, "enter esp_sha256_digest_process"); - if(blockprocess) { - + if (blockprocess) { wc_esp_process_block(&sha->ctx, sha->buffer, WC_SHA256_BLOCK_SIZE); } @@ -664,50 +1278,58 @@ int esp_sha256_digest_process(struct wc_Sha256* sha, byte blockprocess) ESP_LOGV(TAG, "leave esp_sha256_digest_process"); return ret; -} +} /* esp_sha256_digest_process */ #endif /* NO_SHA256 */ #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) /* -* sha512 process. this is used for sha384 too. +** sha512 process. this is used for sha384 too. */ -void esp_sha512_block(struct wc_Sha512* sha, const word32* data, byte isfinal) +int esp_sha512_block(struct wc_Sha512* sha, const word32* data, byte isfinal) { + int ret = 0; /* assume success */ ESP_LOGV(TAG, "enter esp_sha512_block"); /* start register offset */ - if(sha->ctx.mode == ESP32_SHA_SW){ - ByteReverseWords64(sha->buffer, sha->buffer, - WC_SHA512_BLOCK_SIZE); - if(isfinal) { + /* note that in SW mode, wolfSSL uses 64 bit words */ + if (sha->ctx.mode == ESP32_SHA_SW) { + ByteReverseWords64(sha->buffer, + sha->buffer, + WC_SHA512_BLOCK_SIZE); + if (isfinal) { sha->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 2] = sha->hiLen; sha->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 1] = sha->loLen; } - } else { - ByteReverseWords((word32*)sha->buffer, (word32*)sha->buffer, - WC_SHA512_BLOCK_SIZE); - if(isfinal){ + /* when we are in HW mode, Espressif uses 32 bit words */ + ByteReverseWords((word32*)sha->buffer, + (word32*)sha->buffer, + WC_SHA512_BLOCK_SIZE); + + if (isfinal) { sha->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 2] = rotlFixed64(sha->hiLen, 32U); sha->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 1] = rotlFixed64(sha->loLen, 32U); } - wc_esp_process_block(&sha->ctx, data, WC_SHA512_BLOCK_SIZE); + ret = wc_esp_process_block(&sha->ctx, data, WC_SHA512_BLOCK_SIZE); } ESP_LOGV(TAG, "leave esp_sha512_block"); -} + return ret; +} /* esp_sha512_block */ + /* -* sha512 process. this is used for sha384 too. +** sha512 process. this is used for sha384 too. */ int esp_sha512_process(struct wc_Sha512* sha) { + int ret = 0; /* assume success */ word32 *data = (word32*)sha->buffer; ESP_LOGV(TAG, "enter esp_sha512_process"); @@ -715,26 +1337,32 @@ int esp_sha512_process(struct wc_Sha512* sha) esp_sha512_block(sha, data, 0); ESP_LOGV(TAG, "leave esp_sha512_process"); - return 0; + return ret; } + /* -* retrieve sha512 digest. this is used for sha384 too. +** retrieve sha512 digest. this is used for sha384, sha512-224, sha512-256 too. */ int esp_sha512_digest_process(struct wc_Sha512* sha, byte blockproc) { + int ret = 0; ESP_LOGV(TAG, "enter esp_sha512_digest_process"); - if(blockproc) { + if (blockproc) { word32* data = (word32*)sha->buffer; - esp_sha512_block(sha, data, 1); + ret = esp_sha512_block(sha, data, 1); + } + if (sha->ctx.mode == ESP32_SHA_HW) { + ret = wc_esp_digest_state(&sha->ctx, (byte*)sha->digest); + } + else { + ESP_LOGW(TAG, "Call esp_sha512_digest_process in non-HW mode?"); } - if(sha->ctx.mode != ESP32_SHA_SW) - wc_esp_digest_state(&sha->ctx, (byte*)sha->digest); ESP_LOGV(TAG, "leave esp_sha512_digest_process"); - return 0; -} + return ret; +} /* esp_sha512_digest_process */ #endif /* WOLFSSL_SHA512 || WOLFSSL_SHA384 */ #endif /* WOLFSSL_ESP32WROOM32_CRYPT */ #endif /* !defined(NO_SHA) ||... */ diff --git a/wolfcrypt/src/port/Espressif/esp32_util.c b/wolfcrypt/src/port/Espressif/esp32_util.c index 6f2ef11de70..172e661a8bf 100644 --- a/wolfcrypt/src/port/Espressif/esp32_util.c +++ b/wolfcrypt/src/port/Espressif/esp32_util.c @@ -19,6 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ #include +#include #if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ (!defined(NO_AES) || !defined(NO_SHA) || !defined(NO_SHA256) ||\ @@ -27,6 +28,8 @@ #include #include #include + + /* * initialize our mutex used to lock hardware access * @@ -79,25 +82,254 @@ int esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex) { #endif } +/* +** Version / Platform info. +** +** This could evolve into a wolfSSL-wide feature. For now, here only. See: +** https://github.com/wolfSSL/wolfssl/pull/6149 +*/ +#if defined(WOLFSSL_ESPIDF) + #include + #include "sdkconfig.h" + const char* TAG = "Version Info"; + #define WOLFSSL_VERSION_PRINTF(...) ESP_LOGI(TAG, __VA_ARGS__) +#else + #include + #define WOLFSSL_VERSION_PRINTF(...) { printf(__VA_ARGS__); printf("\n"); } +#endif + +/* +******************************************************************************* +** Specific Platforms +******************************************************************************* +*/ + +/* +** Specific platforms: Espressif +*/ +#if defined(WOLFSSL_ESPIDF) +static int ShowExtendedSystemInfo_platform_espressif() +{ +#if defined(CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ) + WOLFSSL_VERSION_PRINTF("CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ: %u MHz", + CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ); +#endif + +#if CONFIG_IDF_TARGET_ESP32 + + WOLFSSL_VERSION_PRINTF("Xthal_have_ccount: %u", + Xthal_have_ccount); + + /* this is the legacy stack size */ +#if defined(CONFIG_MAIN_TASK_STACK_SIZE) + WOLFSSL_VERSION_PRINTF("CONFIG_MAIN_TASK_STACK_SIZE: %d", + CONFIG_MAIN_TASK_STACK_SIZE); +#endif + + /* this is the modern stack size */ +#if defined(CONFIG_ESP_MAIN_TASK_STACK_SIZE) + WOLFSSL_VERSION_PRINTF("CONFIG_ESP_MAIN_TASK_STACK_SIZE: %d", + CONFIG_ESP_MAIN_TASK_STACK_SIZE); +#endif + +#if defined(CONFIG_TIMER_TASK_STACK_SIZE) + WOLFSSL_VERSION_PRINTF("CONFIG_TIMER_TASK_STACK_SIZE: %d", + CONFIG_TIMER_TASK_STACK_SIZE); +#endif + +#if defined(CONFIG_TIMER_TASK_STACK_DEPTH) + WOLFSSL_VERSION_PRINTF("CONFIG_TIMER_TASK_STACK_DEPTH: %d", + CONFIG_TIMER_TASK_STACK_DEPTH); +#endif + +#if defined(SINGLE_THREADED) + /* see also HAVE_STACK_SIZE_VERBOSE */ + char thisHWM = 0; + WOLFSSL_VERSION_PRINTF("Stack HWM: %x", (size_t) &thisHWM); +#else + WOLFSSL_VERSION_PRINTF("Stack HWM: %d", + uxTaskGetStackHighWaterMark(NULL)); +#endif + +#elif CONFIG_IDF_TARGET_ESP32S2 + WOLFSSL_VERSION_PRINTF("Xthal_have_ccount = %u", + Xthal_have_ccount); +#elif CONFIG_IDF_TARGET_ESP32C6 + /* not supported at this time */ +#elif CONFIG_IDF_TARGET_ESP32C3 + /* not supported at this time */ +#elif CONFIG_IDF_TARGET_ESP32S3 + WOLFSSL_VERSION_PRINTF("Xthal_have_ccount = %u", + Xthal_have_ccount); +#elif CONFIG_IDF_TARGET_ESP32H2 + /* not supported at this time */ +#elif CONFIG_IDF_TARGET_ESP32C2 + /* not supported at this time */ +#else + /* not supported at this time */ +#endif + + /* check to see if we are using hardware encryption */ +#if defined(NO_ESP32WROOM32_CRYPT) + WOLFSSL_VERSION_PRINTF("NO_ESP32WROOM32_CRYPT defined! " + "HW acceleration DISABLED."); +#else + /* first show what platform hardware acceleration is enabled + ** (some new platforms may not be supported yet) */ +#if defined(CONFIG_IDF_TARGET_ESP32) + WOLFSSL_VERSION_PRINTF("ESP32WROOM32_CRYPT is enabled for ESP32."); +#elif defined(CONFIG_IDF_TARGET_ESP32S2) + WOLFSSL_VERSION_PRINTF("ESP32WROOM32_CRYPT is enabled for ESP32-S2."); +#elif defined(CONFIG_IDF_TARGET_ESP32S3) + WOLFSSL_VERSION_PRINTF("ESP32WROOM32_CRYPT is enabled for ESP32-S3."); +#else +#error "ESP32WROOM32_CRYPT not yet supported on this IDF TARGET" +#endif + + /* Even though enabled, some specifics may be disabled */ +#if defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) + WOLFSSL_VERSION_PRINTF("NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH is defined!" + "(disabled HW SHA)."); +#endif + +#if defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_AES) + WOLFSSL_VERSION_PRINTF("NO_WOLFSSL_ESP32WROOM32_CRYPT_AES is defined!" + "(disabled HW AES)."); +#endif + +#if defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) + WOLFSSL_VERSION_PRINTF("NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI defined!" + "(disabled HW RSA)"); +#endif +#endif + + return 0; +} +#endif + +/* +******************************************************************************* +** All Platforms +******************************************************************************* +*/ + +/* +** All platforms: git details +*/ +static int ShowExtendedSystemInfo_git() +{ +#if defined(HAVE_WC_INTROSPECTION) && !defined(ALLOW_BINARY_MISMATCH_INTROSPECTION) +#pragma message("WARNING: both HAVE_VERSION_EXTENDED_INFO and " \ + "HAVE_WC_INTROSPECTION are enabled. Some extended " \ + "information details will not be available.") + + WOLFSSL_VERSION_PRINTF("HAVE_WC_INTROSPECTION enabled. " + "Some extended system details not available."); +#else + /* Display some interesting git values that may change, + ** but not desired for introspection which requires object code to be + ** maximally bitwise-invariant. + */ +#if defined(LIBWOLFSSL_VERSION_GIT_ORIGIN) + /* git config --get remote.origin.url */ + WOLFSSL_VERSION_PRINTF("LIBWOLFSSL_VERSION_GIT_ORIGIN = %s", + LIBWOLFSSL_VERSION_GIT_ORIGIN); #endif -#ifdef WOLFSSL_ESP32WROOM32_CRYPT_DEBUG +#if defined(LIBWOLFSSL_VERSION_GIT_BRANCH) + /* git rev-parse --abbrev-ref HEAD */ + WOLFSSL_VERSION_PRINTF("LIBWOLFSSL_VERSION_GIT_BRANCH = %s", + LIBWOLFSSL_VERSION_GIT_BRANCH); +#endif -#include "esp_timer.h" -#include "esp_log.h" +#if defined(LIBWOLFSSL_VERSION_GIT_HASH) + WOLFSSL_VERSION_PRINTF("LIBWOLFSSL_VERSION_GIT_HASH = %s", + LIBWOLFSSL_VERSION_GIT_HASH); +#endif -static uint64_t startTime = 0; +#if defined(LIBWOLFSSL_VERSION_GIT_SHORT_HASH ) + WOLFSSL_VERSION_PRINTF("LIBWOLFSSL_VERSION_GIT_SHORT_HASH = %s", + LIBWOLFSSL_VERSION_GIT_SHORT_HASH); +#endif +#if defined(LIBWOLFSSL_VERSION_GIT_HASH_DATE) + WOLFSSL_VERSION_PRINTF("LIBWOLFSSL_VERSION_GIT_HASH_DATE = %s", + LIBWOLFSSL_VERSION_GIT_HASH_DATE); +#endif -void wc_esp32TimerStart() +#endif /* else not HAVE_WC_INTROSPECTION */ + return 0; +} + +/* +** All platforms: thread details +*/ +static int ShowExtendedSystemInfo_thread() { - startTime = esp_timer_get_time(); + /* all platforms: stack high water mark check */ +#if defined(SINGLE_THREADED) + WOLFSSL_VERSION_PRINTF("SINGLE_THREADED"); +#else + WOLFSSL_VERSION_PRINTF("NOT SINGLE_THREADED"); +#endif + return 0; } -uint64_t wc_esp32elapsedTime() +/* +** All Platforms: platform details +*/ +static int ShowExtendedSystemInfo_platform() { - /* return elapsed time since wc_esp32AesTimeStart() is called in us */ - return esp_timer_get_time() - startTime; +#if defined(WOLFSSL_ESPIDF) +#if defined(CONFIG_IDF_TARGET) + WOLFSSL_VERSION_PRINTF("CONFIG_IDF_TARGET = %s", + CONFIG_IDF_TARGET); + ShowExtendedSystemInfo_platform_espressif(); +#endif +#endif + return 0; +} + +/* +******************************************************************************* +** The public ShowExtendedSystemInfo() +******************************************************************************* +*/ + +int ShowExtendedSystemInfo(void) + { + WOLFSSL_VERSION_PRINTF("Extended Version and Platform Information."); + +#if defined(LIBWOLFSSL_VERSION_STRING) + WOLFSSL_VERSION_PRINTF("LIBWOLFSSL_VERSION_STRING = %s", + LIBWOLFSSL_VERSION_STRING); +#endif + +#if defined(LIBWOLFSSL_VERSION_HEX) + WOLFSSL_VERSION_PRINTF("LIBWOLFSSL_VERSION_HEX = %x", + LIBWOLFSSL_VERSION_HEX); +#endif + +#if defined(WOLFSSL_MULTI_INSTALL_WARNING) + /* CMake may have detected undesired multiple installs, so give warning. */ + WOLFSSL_VERSION_PRINTF(""); + WOLFSSL_VERSION_PRINTF("WARNING: Multiple wolfSSL installs found."); + WOLFSSL_VERSION_PRINTF("Check ESP-IDF and local project [components] directory."); + WOLFSSL_VERSION_PRINTF(""); +#endif + + ShowExtendedSystemInfo_git(); /* may be limited during active introspection */ + ShowExtendedSystemInfo_platform(); + ShowExtendedSystemInfo_thread(); + return 0; + } + + + +int esp_ShowExtendedSystemInfo() +{ + return ShowExtendedSystemInfo(); } -#endif /*WOLFSSL_ESP32WROOM32_CRYPT_DEBUG */ +#endif + diff --git a/wolfcrypt/src/sha.c b/wolfcrypt/src/sha.c index c7d02e10af7..71fae7c8e00 100644 --- a/wolfcrypt/src/sha.c +++ b/wolfcrypt/src/sha.c @@ -26,6 +26,14 @@ #include +#ifdef DEBUG_WOLFSSL_VERBOSE + #if defined(WOLFSSL_ESPIDF) + #include + #else + #include + #endif +#endif + #if !defined(NO_SHA) #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) @@ -50,6 +58,29 @@ #include #endif +#undef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW +#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ + !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) + /* define a single keyword for simplicity & readability + * + * by default the HW acceleration is on for ESP32-WROOM32 + * but individual components can be turned off. + */ + #define WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW + #include "wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h" + + /* Although we have hardware acceleration, + ** we may need to fall back to software */ + #define USE_SHA_SOFTWARE_IMPL + static const char* TAG = "wc_sha"; +#elif defined(WOLFSSL_USE_ESP32C3_CRYPT_HASH_HW) + /* The ESP32C3 is different; HW crypto here. Not yet implemented. + ** We'll be using software for RISC-V at this time */ + static const char* TAG = "wc_sha-c3"; +#else + #undef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW +#endif + /* fips wrapper calls, user can call direct */ #if defined(HAVE_FIPS) && \ (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)) @@ -290,13 +321,11 @@ !defined(WOLFSSL_QNX_CAAM) /* wolfcrypt/src/port/caam/caam_sha.c */ -#elif defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - - #include "wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h" - - #define USE_SHA_SOFTWARE_IMPL +#elif defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) || \ + defined(WOLFSSL_USE_ESP32C3_CRYPT_HASH_HW) + /* This function initializes SHA. + ** This is automatically called by wc_ShaHash */ static int InitSha(wc_Sha* sha) { int ret = 0; @@ -311,19 +340,10 @@ sha->loLen = 0; sha->hiLen = 0; - /* always start firstblock = 1 when using hw engine */ - sha->ctx.isfirstblock = 1; - sha->ctx.sha_type = SHA1; - if(sha->ctx.mode == ESP32_SHA_HW){ - sha->ctx.lockDepth = 0; - /* release hw engine */ - esp_sha_hw_unlock(&(sha->ctx)); - } - /* always set mode as INIT - * whether using HW or SW is determined at first call of update() - */ - sha->ctx.mode = ESP32_SHA_INIT; - sha->ctx.lockDepth = 0; + /* HW needs to be carefully initialized, taking into account soft copy. + ** If already in use; copy may revert to SW as needed. */ + ret = esp_sha_init(&(sha->ctx), WC_HASH_TYPE_SHA); + return ret; } @@ -526,15 +546,20 @@ static WC_INLINE void AddLength(wc_Sha* sha, word32 len) return 0; } -#endif /* !USE_CUSTOM_SHA_TRANSFORM */ +#endif /* XTRANSFORM when USE_SHA_SOFTWARE_IMPL is enabled */ +/* +** wolfCrypt InitSha256 external wrapper. +** +** we'll assume this is ALWAYS for a new, uninitialized sha256 +*/ int wc_InitSha_ex(wc_Sha* sha, void* heap, int devId) { int ret = 0; - - if (sha == NULL) + if (sha == NULL) { return BAD_FUNC_ARG; + } sha->heap = heap; #ifdef WOLF_CRYPTO_CB @@ -542,28 +567,32 @@ int wc_InitSha_ex(wc_Sha* sha, void* heap, int devId) sha->devCtx = NULL; #endif -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) +#ifdef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW + if (sha->ctx.mode != ESP32_SHA_INIT) { + /* it may be interesting to see old values during debugging */ + ESP_LOGV(TAG, "Set ctx mode from prior value: %d", sha->ctx.mode); + } + /* We know this is a fresh, uninitialized item, so set to INIT */ sha->ctx.mode = ESP32_SHA_INIT; - sha->ctx.isfirstblock = 1; - sha->ctx.lockDepth = 0; /* keep track of how many times lock is called */ #endif + ret = InitSha(sha); - if (ret != 0) + if (ret != 0) { return ret; + } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA) ret = wolfAsync_DevCtxInit(&sha->asyncDev, WOLFSSL_ASYNC_MARKER_SHA, sha->heap, devId); #else (void)devId; -#endif /* WOLFSSL_ASYNC_CRYPT */ +# endif /* WOLFSSL_ASYNC_CRYPT */ #ifdef WOLFSSL_IMXRT1170_CAAM ret = wc_CAAM_HashInit(&sha->hndl, &sha->ctx, WC_HASH_TYPE_SHA); #endif return ret; -} +} /* wc_InitSha_ex */ /* do block size increments/updates */ int wc_ShaUpdate(wc_Sha* sha, const byte* data, word32 len) @@ -599,8 +628,9 @@ int wc_ShaUpdate(wc_Sha* sha, const byte* data, word32 len) #endif /* WOLFSSL_ASYNC_CRYPT */ /* check that internal buffLen is valid */ - if (sha->buffLen >= WC_SHA_BLOCK_SIZE) + if (sha->buffLen >= WC_SHA_BLOCK_SIZE) { return BUFFER_E; + } /* add length for final */ AddLength(sha, len); @@ -621,26 +651,32 @@ int wc_ShaUpdate(wc_Sha* sha, const byte* data, word32 len) ByteReverseWords(sha->buffer, sha->buffer, WC_SHA_BLOCK_SIZE); #endif - #if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) + #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) if (sha->ctx.mode == ESP32_SHA_INIT) { + ESP_LOGV(TAG, "wc_ShaUpdate try hardware"); esp_sha_try_hw_lock(&sha->ctx); } if (sha->ctx.mode == ESP32_SHA_SW) { + ESP_LOGI(TAG, "wc_ShaUpdate process software"); ret = XTRANSFORM(sha, (const byte*)local); } else { + ESP_LOGV(TAG, "wc_ShaUpdate process hardware"); esp_sha_process(sha, (const byte*)local); } + #elif defined (WOLFSSL_USE_ESP32C3_CRYPT_HASH_HW) + ESP_LOGI(TAG, "wc_ShaUpdate not implemented for ESP32C3"); + ret = XTRANSFORM(sha, (const byte*)local); #else ret = XTRANSFORM(sha, (const byte*)local); #endif - if (ret != 0) + if (ret != 0) { return ret; + } - sha->buffLen = 0; - } - } + sha->buffLen = 0; /* Nothing left to do, so set to zero. */ + } /* (sha->buffLen == WC_SHA_BLOCK_SIZE) */ + } /* (sha->buffLen > 0) Process any remainder from previous operation. */ /* process blocks */ #ifdef XTRANSFORM_LEN @@ -676,8 +712,7 @@ int wc_ShaUpdate(wc_Sha* sha, const byte* data, word32 len) ByteReverseWords(local32, local32, WC_SHA_BLOCK_SIZE); #endif - #if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) + #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) if (sha->ctx.mode == ESP32_SHA_INIT){ esp_sha_try_hw_lock(&sha->ctx); } @@ -722,6 +757,10 @@ int wc_ShaFinalRaw(wc_Sha* sha, byte* hash) return 0; } +/* +** Finalizes hashing of data. Result is placed into hash. +** Resets state of sha struct. +*/ int wc_ShaFinal(wc_Sha* sha, byte* hash) { int ret; @@ -749,6 +788,13 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) } #endif /* WOLFSSL_ASYNC_CRYPT */ + /* we'll add a 0x80 byte at the end, + ** so make sure we have appropriate buffer length. */ + if (sha->buffLen > WC_SHA_BLOCK_SIZE - 1) { + /* exit with error code if there's a bad buffer size in buffLen */ + return BAD_STATE_E; + } /* buffLen check */ + local[sha->buffLen++] = 0x80; /* add 1 */ /* pad with zeros */ @@ -760,11 +806,13 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) ByteReverseWords(sha->buffer, sha->buffer, WC_SHA_BLOCK_SIZE); #endif - #if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) + #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + /* For a fresh sha.ctx, try to use hardware acceleration */ if (sha->ctx.mode == ESP32_SHA_INIT) { esp_sha_try_hw_lock(&sha->ctx); } + + /* if HW was busy, we may need to fall back to SW. */ if (sha->ctx.mode == ESP32_SHA_SW) { ret = XTRANSFORM(sha, (const byte*)local); } @@ -772,13 +820,19 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) ret = esp_sha_process(sha, (const byte*)local); } #else + /* + ** The #if defined(WOLFSSL_USE_ESP32C3_CRYPT_HASH_HW) also falls + ** though here to SW, as it's not yet implemented for HW. + */ ret = XTRANSFORM(sha, (const byte*)local); #endif - if (ret != 0) + if (ret != 0) { return ret; + } sha->buffLen = 0; - } + } /* (sha->buffLen > WC_SHA_PAD_SIZE) */ + XMEMSET(&local[sha->buffLen], 0, WC_SHA_PAD_SIZE - sha->buffLen); #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) @@ -801,8 +855,7 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) 2 * sizeof(word32)); #endif -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) if (sha->ctx.mode == ESP32_SHA_INIT) { esp_sha_try_hw_lock(&sha->ctx); } @@ -812,6 +865,10 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) else { ret = esp_sha_digest_process(sha, 1); } +/* +** The #if defined(WOLFSSL_USE_ESP32C3_CRYPT_HASH_HW) also falls +** though here to SW, as it's not yet implemented for HW. +*/ #else ret = XTRANSFORM(sha, (const byte*)local); #endif @@ -822,7 +879,7 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) XMEMCPY(hash, (byte *)&sha->digest[0], WC_SHA_DIGEST_SIZE); - (void)InitSha(sha); /* reset state */ + ret = InitSha(sha); /* reset state */ return ret; } @@ -844,12 +901,15 @@ int wc_ShaTransform(wc_Sha* sha, const unsigned char* data) #endif /* USE_SHA_SOFTWARE_IMPL */ - +/* +** This function initializes SHA. This is automatically called by wc_ShaHash. +*/ int wc_InitSha(wc_Sha* sha) { return wc_InitSha_ex(sha, NULL, INVALID_DEVID); } + #if !defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH) void wc_ShaFree(wc_Sha* sha) @@ -882,7 +942,7 @@ void wc_ShaFree(wc_Sha* sha) #endif /* !defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH) */ #endif /* !WOLFSSL_TI_HASH */ -#endif /* HAVE_FIPS */ +#endif /* !HAVE_FIPS ... */ #if !defined(WOLFSSL_TI_HASH) && !defined(WOLFSSL_IMXRT_DCP) @@ -891,36 +951,38 @@ void wc_ShaFree(wc_Sha* sha) #if !defined(WOLFSSL_RENESAS_RX64_HASH) #if !defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH) + +/* wc_ShaGetHash get hash value */ int wc_ShaGetHash(wc_Sha* sha, byte* hash) { int ret; - wc_Sha tmpSha; +#ifdef WOLFSSL_SMALL_STACK + wc_Sha* tmpSha; +#else + wc_Sha tmpSha[1]; +#endif - if (sha == NULL || hash == NULL) + if (sha == NULL || hash == NULL) { return BAD_FUNC_ARG; - -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - if(sha->ctx.mode == ESP32_SHA_INIT){ - esp_sha_try_hw_lock(&sha->ctx); } - if (sha->ctx.mode != ESP32_SHA_SW) { - /* TODO check SW/HW logic */ - esp_sha_digest_process(sha, 0); + +#ifdef WOLFSSL_SMALL_STACK + tmpSha = (wc_Sha*)XMALLOC(sizeof(wc_Sha), NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (tmpSha == NULL) { + return MEMORY_E; } #endif - ret = wc_ShaCopy(sha, &tmpSha); + ret = wc_ShaCopy(sha, tmpSha); if (ret == 0) { - /* if HW failed, use SW */ - ret = wc_ShaFinal(&tmpSha, hash); -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - sha->ctx.mode = ESP32_SHA_SW; -#endif + ret = wc_ShaFinal(tmpSha, hash); + } +#ifdef WOLFSSL_SMALL_STACK + XFREE(tmpSha, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif - } return ret; } @@ -941,27 +1003,29 @@ int wc_ShaCopy(wc_Sha* src, wc_Sha* dst) #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA) ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev); #endif + #ifdef WOLFSSL_PIC32MZ_HASH ret = wc_Pic32HashCopy(&src->cache, &dst->cache); #endif + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); #endif -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - dst->ctx.mode = src->ctx.mode; - dst->ctx.isfirstblock = src->ctx.isfirstblock; - dst->ctx.sha_type = src->ctx.sha_type; + +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + esp_sha_ctx_copy(src, dst); #endif + #ifdef WOLFSSL_HASH_FLAGS - dst->flags |= WC_HASH_FLAG_ISCOPY; + dst->flags |= WC_HASH_FLAG_ISCOPY; #endif return ret; } #endif /* WOLFSSL_RENESAS_RX64_HASH */ -#endif /* defined(WOLFSSL_RENESAS_TSIP_CRYPT) ... */ -#endif /* !WOLFSSL_TI_HASH && !WOLFSSL_IMXRT_DCP */ #endif /* !defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH) */ +#endif /* !defined(WOLFSSL_RENESAS_TSIP_CRYPT) || + defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH) */ +#endif /* !defined(WOLFSSL_TI_HASH) && !defined(WOLFSSL_IMXRT_DCP) */ #ifdef WOLFSSL_HASH_FLAGS int wc_ShaSetFlags(wc_Sha* sha, word32 flags) diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 6bf666e7105..0d9681504ef 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -103,6 +103,14 @@ on the specific device platform. #undef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW #endif +#ifdef WOLFSSL_ESPIDF + /* Define the ESP_LOGx(TAG, "" value for output messages here. + ** + ** Beware of possible conflict in test.c (that one now named TEST_TAG) + */ + static const char* TAG = "wc_sha256"; +#endif + /* fips wrapper calls, user can call direct */ #if defined(HAVE_FIPS) && \ (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)) @@ -731,16 +739,16 @@ static int InitSha256(wc_Sha256* sha256) #define NEED_SOFT_SHA256 /* - * soft SHA needs initialization digest, but HW does not. - */ + ** soft SHA needs initialization digest, but HW does not. + */ static int InitSha256(wc_Sha256* sha256) { int ret = 0; /* zero = success */ - if (sha256 == NULL) + if (sha256 == NULL) { return BAD_FUNC_ARG; + } - XMEMSET(sha256->digest, 0, sizeof(sha256->digest)); sha256->digest[0] = 0x6A09E667L; sha256->digest[1] = 0xBB67AE85L; sha256->digest[2] = 0x3C6EF372L; @@ -754,41 +762,33 @@ static int InitSha256(wc_Sha256* sha256) sha256->loLen = 0; sha256->hiLen = 0; - /* always start firstblock = 1 when using hw engine */ - sha256->ctx.isfirstblock = 1; - sha256->ctx.sha_type = SHA2_256; - if(sha256->ctx.mode == ESP32_SHA_HW) { - /* release hw */ - esp_sha_hw_unlock(&(sha256->ctx)); - } - - /* always set mode as INIT - * whether using HW or SW is determined at first call of update() - */ - sha256->ctx.mode = ESP32_SHA_INIT; + ret = esp_sha_init(&(sha256->ctx), WC_HASH_TYPE_SHA256); return ret; } /* - * wolfCrypt InitSha256 external wrapper - */ + ** wolfCrypt InitSha256 external wrapper. + ** + ** we'll assume this is ALWAYS for a new, uninitialized sha256 + */ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) { - int ret = 0; /* zero = success */ - - if (sha256 == NULL) + (void)devId; + if (sha256 == NULL) { return BAD_FUNC_ARG; + } - XMEMSET(sha256, 0, sizeof(wc_Sha256)); + #ifdef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW + /* We know this is a fresh, uninitialized item, so set to INIT */ + if (sha256->ctx.mode != ESP32_SHA_INIT) { + ESP_LOGV(TAG, "Set ctx mode from prior value: " + "%d", sha256->ctx.mode); + } sha256->ctx.mode = ESP32_SHA_INIT; - sha256->ctx.isfirstblock = 1; - sha256->ctx.lockDepth = 0; /* we'll keep track of our own lock depth */ - (void)devId; - - ret = InitSha256(sha256); + #endif - return ret; + return InitSha256(sha256); } #elif defined(WOLFSSL_RENESAS_TSIP_CRYPT) && \ @@ -1100,15 +1100,17 @@ static int InitSha256(wc_Sha256* sha256) #endif #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) - if (sha256->ctx.mode == ESP32_SHA_INIT || - sha256->ctx.mode == ESP32_SHA_FAIL_NEED_UNROLL) { + if (sha256->ctx.mode == ESP32_SHA_INIT) { + ESP_LOGV(TAG, "Sha256Update try hardware"); esp_sha_try_hw_lock(&sha256->ctx); } if (sha256->ctx.mode == ESP32_SHA_SW) { + ESP_LOGV(TAG, "Sha256Update process software"); ret = XTRANSFORM(sha256, (const byte*)local); } else { + ESP_LOGV(TAG, "Sha256Update process hardware"); esp_sha256_process(sha256, (const byte*)local); } #else @@ -1183,15 +1185,18 @@ static int InitSha256(wc_Sha256* sha256) #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) if (sha256->ctx.mode == ESP32_SHA_INIT){ + ESP_LOGV(TAG, "Sha256Update try hardware loop"); esp_sha_try_hw_lock(&sha256->ctx); } if (sha256->ctx.mode == ESP32_SHA_SW) { + ESP_LOGV(TAG, "Sha256Update process software loop"); ret = XTRANSFORM(sha256, (const byte*)local32); } else { + ESP_LOGV(TAG, "Sha256Update process hardware"); esp_sha256_process(sha256, (const byte*)local32); } -#else + #else ret = XTRANSFORM(sha256, (const byte*)local32); #endif @@ -1255,6 +1260,13 @@ static int InitSha256(wc_Sha256* sha256) return BAD_FUNC_ARG; } + /* we'll add a 0x80 byte at the end, + ** so make sure we have appropriate buffer length. */ + if (sha256->buffLen > WC_SHA256_BLOCK_SIZE - 1) { + /* exit with error code if there's a bad buffer size in buffLen */ + return BAD_STATE_E; + } /* buffLen check */ + local = (byte*)sha256->buffer; local[sha256->buffLen++] = 0x80; /* add 1 */ @@ -1400,8 +1412,9 @@ static int InitSha256(wc_Sha256* sha256) #endif /* WOLFSSL_ASYNC_CRYPT */ ret = Sha256Final(sha256); - if (ret != 0) + if (ret != 0) { return ret; + } #if defined(LITTLE_ENDIAN_ORDER) ByteReverseWords(sha256->digest, sha256->digest, WC_SHA256_DIGEST_SIZE); @@ -1572,6 +1585,10 @@ static int InitSha256(wc_Sha256* sha256) sha224->used = 0; #endif + #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + /* not to be confused with HAS512_224 */ + sha224->ctx.mode = ESP32_SHA_SW; /* no SHA224 HW, so always SW */ + #endif return ret; } @@ -1591,9 +1608,20 @@ static int InitSha256(wc_Sha256* sha256) sha224->W = NULL; #endif + #ifdef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW + /* We know this is a fresh, uninitialized item, so set to INIT */ + if (sha224->ctx.mode != ESP32_SHA_SW) { + ESP_LOGV(TAG, "Set sha224 ctx mode init to ESP32_SHA_SW. " + "Prior value: %d", sha224->ctx.mode); + } + /* no sha224 HW support is available, set to SW */ + sha224->ctx.mode = ESP32_SHA_SW; + #endif + ret = InitSha224(sha224); - if (ret != 0) + if (ret != 0) { return ret; + } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA224) ret = wolfAsync_DevCtxInit(&sha224->asyncDev, @@ -1604,6 +1632,16 @@ static int InitSha256(wc_Sha256* sha256) #ifdef WOLFSSL_IMXRT1170_CAAM ret = wc_CAAM_HashInit(&sha224->hndl, &sha224->ctx, WC_HASH_TYPE_SHA224); #endif + + #ifdef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW + if (sha224->ctx.mode != ESP32_SHA_INIT) { + ESP_LOGV("SHA224", "Set ctx mode from prior value: " + "%d", sha224->ctx.mode); + } + /* We know this is a fresh, uninitialized item, so set to INIT */ + sha224->ctx.mode = ESP32_SHA_INIT; + #endif + return ret; } @@ -1623,6 +1661,10 @@ static int InitSha256(wc_Sha256* sha256) } #endif /* WOLFSSL_ASYNC_CRYPT */ + #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + sha224->ctx.mode = ESP32_SHA_SW; /* no SHA224 HW, so always SW */ + #endif + ret = Sha256Update((wc_Sha256*)sha224, data, len); return ret; @@ -1645,6 +1687,10 @@ static int InitSha256(wc_Sha256* sha256) } #endif /* WOLFSSL_ASYNC_CRYPT */ + #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + sha224->ctx.mode = ESP32_SHA_SW; /* no SHA224 HW, so always SW */ + #endif + ret = Sha256Final((wc_Sha256*)sha224); if (ret != 0) return ret; @@ -1785,11 +1831,11 @@ void wc_Sha256Free(wc_Sha256* sha256) * the unexpected. by the time free is called, the hardware * should have already been released (lockDepth = 0) */ - InitSha256(sha256); /* unlock mutex, set mode to ESP32_SHA_INIT */ - ESP_LOGV("sha256", "Alert: hardware unlock needed in wc_Sha256Free."); + (void)InitSha256(sha256); /* unlock mutex, set mode to ESP32_SHA_INIT */ + ESP_LOGV(TAG, "Alert: hardware unlock needed in wc_Sha256Free."); } else { - ESP_LOGV("sha256", "Hardware unlock not needed in wc_Sha256Free."); + ESP_LOGV(TAG, "Hardware unlock not needed in wc_Sha256Free."); } #endif } @@ -1865,12 +1911,14 @@ int wc_Sha224_Grow(wc_Sha224* sha224, const byte* in, int inSz) int wc_Sha224Copy(wc_Sha224* src, wc_Sha224* dst) { - int ret = 0; + int ret = 0; /* assume success unless proven otherwise */ - if (src == NULL || dst == NULL) + if (src == NULL || dst == NULL) { return BAD_FUNC_ARG; + } XMEMCPY(dst, src, sizeof(wc_Sha224)); + #ifdef WOLFSSL_SMALL_STACK_CACHE dst->W = NULL; #endif @@ -1883,9 +1931,15 @@ int wc_Sha224_Grow(wc_Sha224* sha224, const byte* in, int inSz) #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA224) ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev); #endif + + #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + ret = esp_sha224_ctx_copy(src, dst); + #endif + #ifdef WOLFSSL_HASH_FLAGS dst->flags |= WC_HASH_FLAG_ISCOPY; #endif + #if defined(WOLFSSL_HASH_KEEP) if (src->msg != NULL) { dst->msg = (byte*)XMALLOC(src->len, dst->heap, @@ -1972,32 +2026,13 @@ int wc_Sha256GetHash(wc_Sha256* sha256, byte* hash) } #endif -#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) - /* ESP32 hardware can only handle only 1 active hardware hashing - * at a time. If the mutex lock is acquired the first time then - * that Sha256 instance has exclusive access to hardware. The - * final or free needs to release the mutex. Operations that - * do not get the lock fallback to software based Sha256 */ - - if (sha256->ctx.mode == ESP32_SHA_INIT) { - esp_sha_try_hw_lock(&sha256->ctx); - } - if (sha256->ctx.mode == ESP32_SHA_HW) { - esp_sha256_digest_process(sha256, 0); - } -#endif - ret = wc_Sha256Copy(sha256, tmpSha256); if (ret == 0) { ret = wc_Sha256Final(tmpSha256, hash); - - #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) - sha256->ctx.mode = ESP32_SHA_SW; - #endif - - wc_Sha256Free(tmpSha256); + wc_Sha256Free(tmpSha256); /* TODO move outside brackets? */ } + #ifdef WOLFSSL_SMALL_STACK XFREE(tmpSha256, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -2008,8 +2043,9 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) { int ret = 0; - if (src == NULL || dst == NULL) + if (src == NULL || dst == NULL) { return BAD_FUNC_ARG; + } XMEMCPY(dst, src, sizeof(wc_Sha256)); @@ -2029,20 +2065,19 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA256) ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev); #endif + #ifdef WOLFSSL_PIC32MZ_HASH ret = wc_Pic32HashCopy(&src->cache, &dst->cache); #endif #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) - dst->ctx.mode = src->ctx.mode; - dst->ctx.isfirstblock = src->ctx.isfirstblock; - dst->ctx.sha_type = src->ctx.sha_type; - dst->ctx.lockDepth = src->ctx.lockDepth; + esp_sha256_ctx_copy(src, dst); #endif #ifdef WOLFSSL_HASH_FLAGS dst->flags |= WC_HASH_FLAG_ISCOPY; #endif + #if defined(WOLFSSL_HASH_KEEP) if (src->msg != NULL) { dst->msg = (byte*)XMALLOC(src->len, dst->heap, DYNAMIC_TYPE_TMP_BUFFER); diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index ad2a2494162..5172e60f031 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -28,6 +28,21 @@ #if (defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)) && !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_PSOC6_CRYPTO) +/* determine if we are using Espressif SHA hardware acceleration */ +#undef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW +#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ + !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) + /* define a single keyword for simplicity & readability + * + * by default the HW acceleration is on for ESP32-WROOM32 + * but individual components can be turned off. + */ + #define WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW + static const char* TAG = "wc_sha_512"; +#else + #undef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW +#endif + #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS @@ -279,21 +294,13 @@ static int InitSha512(wc_Sha512* sha512) sha512->loLen = 0; sha512->hiLen = 0; -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) - sha512->ctx.sha_type = SHA2_512; - /* always start firstblock = 1 when using hw engine */ - sha512->ctx.isfirstblock = 1; - if(sha512->ctx.mode == ESP32_SHA_HW) { - /* release hw */ - esp_sha_hw_unlock(&(sha512->ctx)); - } - /* always set mode as INIT - * whether using HW or SW is determined at first call of update() - */ - sha512->ctx.mode = ESP32_SHA_INIT; + /* HW needs to be carefully initialized, taking into account soft copy. + ** If already in use; copy may revert to SW as needed. */ + esp_sha_init(&(sha512->ctx), WC_HASH_TYPE_SHA512); #endif + #ifdef WOLFSSL_HASH_FLAGS sha512->flags = 0; #endif @@ -327,21 +334,15 @@ static int InitSha512_224(wc_Sha512* sha512) sha512->loLen = 0; sha512->hiLen = 0; -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - - sha512->ctx.sha_type = SHA2_512; - /* always start firstblock = 1 when using hw engine */ - sha512->ctx.isfirstblock = 1; - if(sha512->ctx.mode == ESP32_SHA_HW) { - /* release hw */ - esp_sha_hw_unlock(&(sha512->ctx)); - } - /* always set mode as INIT - * whether using HW or SW is determined at first call of update() +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + /* HW needs to be carefully initialized, taking into account soft copy. + ** If already in use; copy may revert to SW as needed. + ** + ** Note for original ESP32, there's no HW for SHA512/224 */ - sha512->ctx.mode = ESP32_SHA_INIT; + esp_sha_init(&(sha512->ctx), WC_HASH_TYPE_SHA512_224); #endif + #ifdef WOLFSSL_HASH_FLAGS sha512->flags = 0; #endif @@ -375,21 +376,15 @@ static int InitSha512_256(wc_Sha512* sha512) sha512->loLen = 0; sha512->hiLen = 0; -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - - sha512->ctx.sha_type = SHA2_512; - /* always start firstblock = 1 when using hw engine */ - sha512->ctx.isfirstblock = 1; - if(sha512->ctx.mode == ESP32_SHA_HW) { - /* release hw */ - esp_sha_hw_unlock(&(sha512->ctx)); - } - /* always set mode as INIT - * whether using HW or SW is determined at first call of update() +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + /* HW needs to be carefully initialized, taking into account soft copy. + ** If already in use; copy may revert to SW as needed. + ** + ** Note for original ESP32, there's no HW for SHA512/2256. */ - sha512->ctx.mode = ESP32_SHA_INIT; + esp_sha_init(&(sha512->ctx), WC_HASH_TYPE_SHA512_256); #endif + #ifdef WOLFSSL_HASH_FLAGS sha512->flags = 0; #endif @@ -578,8 +573,10 @@ static int InitSha512_Family(wc_Sha512* sha512, void* heap, int devId, { int ret = 0; - if (sha512 == NULL) + if (sha512 == NULL) { return BAD_FUNC_ARG; + } + sha512->heap = heap; #ifdef WOLFSSL_SMALL_STACK_CACHE @@ -590,6 +587,7 @@ static int InitSha512_Family(wc_Sha512* sha512, void* heap, int devId, sha512->devCtx = NULL; #endif + /* call the initialization function pointed to by initfp */ ret = initfp(sha512); if (ret != 0) return ret; @@ -614,10 +612,19 @@ static int InitSha512_Family(wc_Sha512* sha512, void* heap, int devId, ret = wc_CAAM_HashInit(&sha512->hndl, &sha512->ctx, WC_HASH_TYPE_SHA512); #endif return ret; -} +} /* InitSha512_Family */ int wc_InitSha512_ex(wc_Sha512* sha512, void* heap, int devId) { +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + if (sha512->ctx.mode != ESP32_SHA_INIT) { + ESP_LOGV(TAG, "Set ctx mode from prior value: " + "%d", sha512->ctx.mode); + } + /* We know this is a fresh, uninitialized item, so set to INIT */ + sha512->ctx.mode = ESP32_SHA_INIT; +#endif + return InitSha512_Family(sha512, heap, devId, InitSha512); } @@ -625,6 +632,10 @@ int wc_InitSha512_ex(wc_Sha512* sha512, void* heap, int devId) (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST) int wc_InitSha512_224_ex(wc_Sha512* sha512, void* heap, int devId) { +#ifdef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW + /* No SHA512/224 HW support is available, set to SW. */ + sha512->ctx.mode = ESP32_SHA_SW; /* no SHA224 HW, so always SW */ +#endif return InitSha512_Family(sha512, heap, devId, InitSha512_224); } #endif /* !WOLFSSL_NOSHA512_224 ... */ @@ -633,6 +644,10 @@ int wc_InitSha512_224_ex(wc_Sha512* sha512, void* heap, int devId) (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST) int wc_InitSha512_256_ex(wc_Sha512* sha512, void* heap, int devId) { +#ifdef WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW + /* No SHA512/256 HW support is available on ESP32, set to SW. */ + sha512->ctx.mode = ESP32_SHA_SW; +#endif return InitSha512_Family(sha512, heap, devId, InitSha512_256); } #endif /* !WOLFSSL_NOSHA512_256 ... */ @@ -836,6 +851,8 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le } ret = esp_sha512_process(sha512); if(ret == 0 && sha512->ctx.mode == ESP32_SHA_SW){ + ByteReverseWords64(sha512->buffer, sha512->buffer, + WC_SHA512_BLOCK_SIZE); ret = Transform_Sha512(sha512); } #endif @@ -903,14 +920,18 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le if(sha512->ctx.mode == ESP32_SHA_INIT) { esp_sha_try_hw_lock(&sha512->ctx); } - ret = esp_sha512_process(sha512); - if(ret == 0 && sha512->ctx.mode == ESP32_SHA_SW){ + if (sha512->ctx.mode == ESP32_SHA_SW) { + ByteReverseWords64(sha512->buffer, sha512->buffer, + WC_SHA512_BLOCK_SIZE); ret = Transform_Sha512(sha512); } + else { + ret = esp_sha512_process(sha512); + } #endif if (ret != 0) break; - } + } /* while (len >= WC_SHA512_BLOCK_SIZE) */ } #endif @@ -962,8 +983,8 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) static WC_INLINE int Sha512Final(wc_Sha512* sha512) { - byte* local; int ret; + byte* local; if (sha512 == NULL) { return BAD_FUNC_ARG; @@ -971,6 +992,12 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) local = (byte*)sha512->buffer; + /* we'll add a 0x80 byte at the end, + ** so make sure we have appropriate buffer length. */ + if (sha512->buffLen > WC_SHA512_BLOCK_SIZE - 1) { + return BAD_STATE_E; + } /* buffLen check */ + local[sha512->buffLen++] = 0x80; /* add 1 */ /* pad with zeros */ @@ -990,24 +1017,29 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) WC_SHA512_BLOCK_SIZE); #endif } + #endif /* LITTLE_ENDIAN_ORDER */ -#if !defined(WOLFSSL_ESP32WROOM32_CRYPT) || \ - defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - ret = Transform_Sha512(sha512); -#else - if(sha512->ctx.mode == ESP32_SHA_INIT) { + #if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + if (sha512->ctx.mode == ESP32_SHA_INIT) { esp_sha_try_hw_lock(&sha512->ctx); - } - ret = esp_sha512_process(sha512); - if(ret == 0 && sha512->ctx.mode == ESP32_SHA_SW){ + } + if (sha512->ctx.mode == ESP32_SHA_SW) { + ByteReverseWords64(sha512->buffer,sha512->buffer, + WC_SHA512_BLOCK_SIZE); ret = Transform_Sha512(sha512); } -#endif + else { + ret = esp_sha512_process(sha512); + } + #else + ret = Transform_Sha512(sha512); + #endif if (ret != 0) return ret; sha512->buffLen = 0; - } + } /* (sha512->buffLen > WC_SHA512_PAD_SIZE) pad with zeros */ + XMEMSET(&local[sha512->buffLen], 0, WC_SHA512_PAD_SIZE - sha512->buffLen); /* put lengths in bits */ @@ -1041,18 +1073,28 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) &(sha512->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 2]), WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE); #endif + #if !defined(WOLFSSL_ESP32WROOM32_CRYPT) || \ defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) ret = Transform_Sha512(sha512); #else if(sha512->ctx.mode == ESP32_SHA_INIT) { + /* typically for tiny block: first = last */ esp_sha_try_hw_lock(&sha512->ctx); } - ret = esp_sha512_digest_process(sha512, 1); - if(ret == 0 && sha512->ctx.mode == ESP32_SHA_SW) { + if (sha512->ctx.mode == ESP32_SHA_SW) { + ByteReverseWords64(sha512->buffer, + sha512->buffer, + WC_SHA512_BLOCK_SIZE); + sha512->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 2] = sha512->hiLen; + sha512->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 1] = sha512->loLen; ret = Transform_Sha512(sha512); } + else { + ret = esp_sha512_digest_process(sha512, 1); + } #endif + if (ret != 0) return ret; @@ -1179,6 +1221,7 @@ void wc_Sha512Free(wc_Sha512* sha512) wolfAsync_DevCtxFree(&sha512->asyncDev, WOLFSSL_ASYNC_MARKER_SHA512); #endif /* WOLFSSL_ASYNC_CRYPT */ } + #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_KCAPI_HASH) /* Apply SHA512 transformation to the data */ /* @param sha a pointer to wc_Sha512 structure */ @@ -1302,24 +1345,16 @@ static int InitSha384(wc_Sha384* sha384) sha384->loLen = 0; sha384->hiLen = 0; -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - sha384->ctx.sha_type = SHA2_384; - /* always start firstblock = 1 when using hw engine */ - sha384->ctx.isfirstblock = 1; - if(sha384->ctx.mode == ESP32_SHA_HW) { - /* release hw */ - esp_sha_hw_unlock(&(sha384->ctx)); - } - /* always set mode as INIT - * whether using HW or SW is determined at first call of update() - */ - sha384->ctx.mode = ESP32_SHA_INIT; - +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + /* HW needs to be carefully initialized, taking into account soft copy. + ** If already in use; copy may revert to SW as needed. */ + esp_sha_init(&(sha384->ctx), WC_HASH_TYPE_SHA384); #endif + #ifdef WOLFSSL_HASH_FLAGS sha384->flags = 0; #endif + #ifdef WOLFSSL_HASH_KEEP sha384->msg = NULL; sha384->len = 0; @@ -1426,10 +1461,19 @@ int wc_InitSha384_ex(wc_Sha384* sha384, void* heap, int devId) sha384->devId = devId; sha384->devCtx = NULL; #endif +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + if (sha384->ctx.mode != ESP32_SHA_INIT) { + ESP_LOGV(TAG, "Set ctx mode from prior value: " + "%d", sha384->ctx.mode); + } + /* We know this is a fresh, uninitialized item, so set to INIT */ + sha384->ctx.mode = ESP32_SHA_INIT; +#endif ret = InitSha384(sha384); - if (ret != 0) + if (ret != 0) { return ret; + } #if defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) @@ -1525,24 +1569,10 @@ static int Sha512_Family_GetHash(wc_Sha512* sha512, byte* hash, } #endif -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - if (sha512->ctx.mode == ESP32_SHA_INIT) { - esp_sha_try_hw_lock(&sha512->ctx); - } - if (sha512->ctx.mode != ESP32_SHA_SW) { - esp_sha512_digest_process(sha512, 0); - } -#endif - + /* copy this sha512 into tmpSha */ ret = wc_Sha512Copy(sha512, tmpSha512); if (ret == 0) { ret = finalfp(tmpSha512, hash); - -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - sha512->ctx.mode = ESP32_SHA_SW;; -#endif wc_Sha512Free(tmpSha512); } @@ -1562,8 +1592,9 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) { int ret = 0; - if (src == NULL || dst == NULL) + if (src == NULL || dst == NULL) { return BAD_FUNC_ARG; + } XMEMCPY(dst, src, sizeof(wc_Sha512)); #ifdef WOLFSSL_SMALL_STACK_CACHE @@ -1578,15 +1609,17 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA512) ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev); #endif -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - dst->ctx.mode = src->ctx.mode; - dst->ctx.isfirstblock = src->ctx.isfirstblock; - dst->ctx.sha_type = src->ctx.sha_type; + +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + if (ret == 0) { + ret = esp_sha512_ctx_copy(src, dst); + } #endif + #ifdef WOLFSSL_HASH_FLAGS dst->flags |= WC_HASH_FLAG_ISCOPY; #endif + #if defined(WOLFSSL_HASH_KEEP) if (src->msg != NULL) { dst->msg = (byte*)XMALLOC(src->len, dst->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -1626,6 +1659,7 @@ int wc_InitSha512_224(wc_Sha512* sha) { return wc_InitSha512_224_ex(sha, NULL, INVALID_DEVID); } + int wc_Sha512_224Update(wc_Sha512* sha, const byte* data, word32 len) { return wc_Sha512Update(sha, data, len); @@ -1640,16 +1674,19 @@ int wc_Sha512_224FinalRaw(wc_Sha512* sha, byte* hash) { return Sha512FinalRaw(sha, hash, WC_SHA512_224_DIGEST_SIZE); } + int wc_Sha512_224Final(wc_Sha512* sha512, byte* hash) { return Sha512_Family_Final(sha512, hash, WC_SHA512_224_DIGEST_SIZE, InitSha512_224); } -#endif +#endif /* else none of the above: WOLFSSL_KCAPI_HASH, WOLFSSL_SE050 */ + void wc_Sha512_224Free(wc_Sha512* sha) { wc_Sha512Free(sha); } + #if defined(WOLFSSL_KCAPI_HASH) /* functions defined in wolfcrypt/src/port/kcapi/kcapi_hash.c */ #elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) @@ -1660,11 +1697,12 @@ int wc_Sha512_224GetHash(wc_Sha512* sha512, byte* hash) { return Sha512_Family_GetHash(sha512, hash, wc_Sha512_224Final); } + int wc_Sha512_224Copy(wc_Sha512* src, wc_Sha512* dst) { return wc_Sha512Copy(src, dst); } -#endif +#endif /* else none of the above: WOLFSSL_KCAPI_HASH, WOLFSSL_SE050 */ #ifdef WOLFSSL_HASH_FLAGS int wc_Sha512_224SetFlags(wc_Sha512* sha, word32 flags) @@ -1694,6 +1732,7 @@ int wc_InitSha512_256(wc_Sha512* sha) { return wc_InitSha512_256_ex(sha, NULL, INVALID_DEVID); } + int wc_Sha512_256Update(wc_Sha512* sha, const byte* data, word32 len) { return wc_Sha512Update(sha, data, len); @@ -1707,16 +1746,19 @@ int wc_Sha512_256FinalRaw(wc_Sha512* sha, byte* hash) { return Sha512FinalRaw(sha, hash, WC_SHA512_256_DIGEST_SIZE); } + int wc_Sha512_256Final(wc_Sha512* sha512, byte* hash) { return Sha512_Family_Final(sha512, hash, WC_SHA512_256_DIGEST_SIZE, InitSha512_256); } #endif + void wc_Sha512_256Free(wc_Sha512* sha) { wc_Sha512Free(sha); } + #if defined(WOLFSSL_KCAPI_HASH) /* functions defined in wolfcrypt/src/port/kcapi/kcapi_hash.c */ @@ -1782,23 +1824,10 @@ int wc_Sha384GetHash(wc_Sha384* sha384, byte* hash) } #endif -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - if (sha384->ctx.mode == ESP32_SHA_INIT) { - esp_sha_try_hw_lock(&sha384->ctx); - } - if (sha384->ctx.mode != ESP32_SHA_SW) { - esp_sha512_digest_process(sha384, 0); - } -#endif + /* copy this sha384 into tmpSha */ ret = wc_Sha384Copy(sha384, tmpSha384); if (ret == 0) { ret = wc_Sha384Final(tmpSha384, hash); - -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - sha384->ctx.mode = ESP32_SHA_SW; -#endif wc_Sha384Free(tmpSha384); } @@ -1818,6 +1847,7 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) } XMEMCPY(dst, src, sizeof(wc_Sha384)); + #ifdef WOLFSSL_SMALL_STACK_CACHE dst->W = NULL; #endif @@ -1830,15 +1860,15 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA384) ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev); #endif -#if defined(WOLFSSL_ESP32WROOM32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) - dst->ctx.mode = src->ctx.mode; - dst->ctx.isfirstblock = src->ctx.isfirstblock; - dst->ctx.sha_type = src->ctx.sha_type; + +#if defined(WOLFSSL_USE_ESP32WROOM32_CRYPT_HASH_HW) + esp_sha384_ctx_copy(src, dst); #endif + #ifdef WOLFSSL_HASH_FLAGS dst->flags |= WC_HASH_FLAG_ISCOPY; #endif + #if defined(WOLFSSL_HASH_KEEP) if (src->msg != NULL) { dst->msg = (byte*)XMALLOC(src->len, dst->heap, DYNAMIC_TYPE_TMP_BUFFER); diff --git a/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h b/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h index 346ca52fdc3..4f61000ae1d 100644 --- a/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h +++ b/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h @@ -28,7 +28,6 @@ #include "esp_idf_version.h" #include "esp_types.h" #include "esp_log.h" -#include "esp_random.h" #ifdef WOLFSSL_ESP32WROOM32_CRYPT_DEBUG #undef LOG_LOCAL_LEVEL @@ -39,31 +38,45 @@ #endif #include -#include "soc/dport_reg.h" -#include "soc/hwcrypto_reg.h" +#if defined(CONFIG_IDF_TARGET_ESP32C3) + /* no includes for ESP32C3 at this time (no HW implemented yet) */ +#elif defined(CONFIG_IDF_TARGET_ESP32S3) + #include "soc/dport_reg.h" + #include "soc/hwcrypto_reg.h" + #if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 5 + #include "esp_private/periph_ctrl.h" + #else + #include "driver/periph_ctrl.h" + #endif +#else + #include "soc/dport_reg.h" + #include "soc/hwcrypto_reg.h" -#if ESP_IDF_VERSION_MAJOR < 5 - #include "soc/cpu.h" -#endif + #if ESP_IDF_VERSION_MAJOR < 5 + #include "soc/cpu.h" + #endif -#if ESP_IDF_VERSION_MAJOR >= 5 - #include "esp_private/periph_ctrl.h" -#else - #include "driver/periph_ctrl.h" -#endif + #if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 5 + #include "esp_private/periph_ctrl.h" + #else + #include "driver/periph_ctrl.h" + #endif + + #if ESP_IDF_VERSION_MAJOR >= 4 + #include + #else + #include + #endif -#if ESP_IDF_VERSION_MAJOR >= 4 - #include -#elif defined(CONFIG_IDF_TARGET_ESP32S3) - #include -#else - #include #endif + #ifdef __cplusplus extern "C" { #endif +int esp_ShowExtendedSystemInfo(void); + int esp_CryptHwMutexInit(wolfSSL_Mutex* mutex); int esp_CryptHwMutexLock(wolfSSL_Mutex* mutex, TickType_t xBloxkTime); int esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex); @@ -72,8 +85,6 @@ int esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex); #if ESP_IDF_VERSION_MAJOR >= 4 #include "esp32/rom/aes.h" - #elif defined(CONFIG_IDF_TARGET_ESP32S3) - #include "esp32s3/rom/aes.h" #else #include "rom/aes.h" #endif @@ -95,14 +106,15 @@ int esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex); #ifdef WOLFSSL_ESP32WROOM32_CRYPT_DEBUG - void wc_esp32TimerStart(); - uint64_t wc_esp32elapsedTime(); + void wc_esp32TimerStart(void); + uint64_t wc_esp32elapsedTime(void); #endif /* WOLFSSL_ESP32WROOM32_CRYPT_DEBUG */ -#if (!defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \ - defined(WOLFSSL_SHA512)) && \ - !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) +#if !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH) && \ + (!defined(NO_SHA) || !defined(NO_SHA256) || \ + defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512) \ + ) /* RAW hash function APIs are not implemented with esp32 hardware acceleration*/ #define WOLFSSL_NO_HASH_RAW @@ -118,50 +130,67 @@ int esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex); #undef SHA_CTX - typedef enum { - ESP32_SHA_INIT = 0, - ESP32_SHA_HW = 1, - ESP32_SHA_SW = 2, + typedef enum + { + ESP32_SHA_INIT = 0, + ESP32_SHA_HW = 1, + ESP32_SHA_SW = 2, + ESP32_SHA_HW_COPY = 3, ESP32_SHA_FAIL_NEED_UNROLL = -1 } ESP32_MODE; - typedef struct { - byte isfirstblock; - - ESP32_MODE mode; /* typically 0 init, 1 HW, 2 SW */ + typedef struct + { + /* pointer to object the initialized HW; to track copies */ + void* initializer; + + /* an ESP32_MODE value; typically: + ** 0 init, + ** 1 HW, + ** 2 SW */ + ESP32_MODE mode; + + /* see esp_rom/include/esp32/rom/sha.h + ** + ** the Espressif type: SHA1, SHA256, etc. + */ + enum SHA_TYPE sha_type; /* we'll keep track of our own locks. - * actual enable/disable only occurs for ref_counts[periph] == 0 */ - int lockDepth; /* see ref_counts[periph] in periph_ctrl.c */ - - /* ESP32S3 defines SHA_TYPE to enum, all other ESP32s define it to - typedef enum. */ - #if defined(CONFIG_IDF_TARGET_ESP32S3) - SHA_TYPE sha_type; - #else - enum SHA_TYPE sha_type; - #endif + ** actual enable/disable only occurs for ref_counts[periph] == 0 + ** + ** see ref_counts[periph] in periph_ctrl.c */ + byte lockDepth:7; /* 7 bits for a small number, pack with below. */ + + /* 0 (false) this is NOT first block. + ** 1 (true ) this is first block. */ + byte isfirstblock:1; /* 1 bit only for true / false */ } WC_ESP32SHA; + int esp_sha_init(WC_ESP32SHA* ctx, enum wc_HashType hash_type); + int esp_sha_init_ctx(WC_ESP32SHA* ctx); int esp_sha_try_hw_lock(WC_ESP32SHA* ctx); int esp_sha_hw_unlock(WC_ESP32SHA* ctx); struct wc_Sha; + int esp_sha_ctx_copy(struct wc_Sha* src, struct wc_Sha* dst); int esp_sha_digest_process(struct wc_Sha* sha, byte blockprocess); int esp_sha_process(struct wc_Sha* sha, const byte* data); #ifndef NO_SHA256 struct wc_Sha256; + int esp_sha224_ctx_copy(struct wc_Sha256* src, struct wc_Sha256* dst); + int esp_sha256_ctx_copy(struct wc_Sha256* src, struct wc_Sha256* dst); int esp_sha256_digest_process(struct wc_Sha256* sha, byte blockprocess); int esp_sha256_process(struct wc_Sha256* sha, const byte* data); int esp32_Transform_Sha256_demo(struct wc_Sha256* sha256, const byte* data); - - #endif /* TODO do we really call esp_sha512_process for WOLFSSL_SHA384 ? */ #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) struct wc_Sha512; + int esp_sha384_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst); + int esp_sha512_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst); int esp_sha512_process(struct wc_Sha512* sha); int esp_sha512_digest_process(struct wc_Sha512* sha, byte blockproc); #endif From 8d7488815c497f625aa98adeb2d8e0a0c6f649db Mon Sep 17 00:00:00 2001 From: TakayukiMatsuo Date: Wed, 19 Apr 2023 04:39:49 +0900 Subject: [PATCH 170/391] Add WOLFSSL_SP_NO_DYN_STACK macro to avoid compilation error in CC-RX compiler --- .../e2studio/RX65N/GR-ROSE/common/user_settings.h | 11 +++++++++++ .../e2studio/RX65N/RSK/wolfssl_demo/user_settings.h | 11 +++++++++++ .../RX72N/EnvisionKit/wolfssl_demo/user_settings.h | 12 ++++++++++++ wolfcrypt/src/port/Renesas/renesas_tsip_util.c | 9 ++++++++- 4 files changed, 42 insertions(+), 1 deletion(-) diff --git a/IDE/Renesas/e2studio/RX65N/GR-ROSE/common/user_settings.h b/IDE/Renesas/e2studio/RX65N/GR-ROSE/common/user_settings.h index b611bf6874f..0c78c5181c0 100644 --- a/IDE/Renesas/e2studio/RX65N/GR-ROSE/common/user_settings.h +++ b/IDE/Renesas/e2studio/RX65N/GR-ROSE/common/user_settings.h @@ -61,6 +61,17 @@ #define SINGLE_THREADED /*#define FREERTOS*/ +/*-- Compiler related definitions --------------------------------------------- + * + * CC-RX is C99 compliant, but may not provide the features wolfSSL requires. + * This section defines macros for such cases to avoid build-time or run-time + * failures. + * + *----------------------------------------------------------------------------*/ + +/* CC-RX does not support variable length array */ +#define WOLFSSL_SP_NO_DYN_STACK + /*-- Cipher related definitions ----------------------------------------------- * diff --git a/IDE/Renesas/e2studio/RX65N/RSK/wolfssl_demo/user_settings.h b/IDE/Renesas/e2studio/RX65N/RSK/wolfssl_demo/user_settings.h index 28343914876..9aeb3e4e59e 100644 --- a/IDE/Renesas/e2studio/RX65N/RSK/wolfssl_demo/user_settings.h +++ b/IDE/Renesas/e2studio/RX65N/RSK/wolfssl_demo/user_settings.h @@ -63,6 +63,17 @@ #define FREERTOS_TCP +/*-- Compiler related definitions --------------------------------------------- + * + * CC-RX is C99 compliant, but may not provide the features wolfSSL requires. + * This section defines macros for such cases to avoid build-time or run-time + * failures. + * + *----------------------------------------------------------------------------*/ + +/* CC-RX does not support variable length array */ +#define WOLFSSL_SP_NO_DYN_STACK + /*-- Cipher related definitions ----------------------------------------------- diff --git a/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/user_settings.h b/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/user_settings.h index 98422cdf933..e5cd3333c75 100644 --- a/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/user_settings.h +++ b/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/user_settings.h @@ -77,6 +77,18 @@ #define WOLFSSL_USER_IO #endif +/*-- Compiler related definitions --------------------------------------------- + * + * CC-RX is C99 compliant, but may not provide the features wolfSSL requires. + * This section defines macros for such cases to avoid build-time or run-time + * failures. + * + *----------------------------------------------------------------------------*/ + +/* CC-RX does not support variable length array */ +#define WOLFSSL_SP_NO_DYN_STACK + + /*-- Cipher related definitions ----------------------------------------------- * * diff --git a/wolfcrypt/src/port/Renesas/renesas_tsip_util.c b/wolfcrypt/src/port/Renesas/renesas_tsip_util.c index b098ed33153..0ebc718cdd5 100644 --- a/wolfcrypt/src/port/Renesas/renesas_tsip_util.c +++ b/wolfcrypt/src/port/Renesas/renesas_tsip_util.c @@ -1913,7 +1913,14 @@ WOLFSSL_LOCAL int tsip_Tls13SendCertVerify(WOLFSSL* ssl) } if (ret == 0) { - ret = tsipImportPublicKey(tuc, tuc->wrappedKeyType); + if (isRsa) { + ret = tsipImportPublicKey(tuc, tuc->wrappedKeyType); + } + else { +#if defined(WOLFSSL_CHECK_SIG_FAULTS) + ret = tsipImportPublicKey(tuc, tuc->wrappedKeyType); +#endif + } } if (ret == 0) { From 999612e99850aca253052ab5512486d850dd07c5 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Tue, 18 Apr 2023 12:27:54 -0400 Subject: [PATCH 171/391] Should not be an error to call wolfSSL_X509_REQ_add_extensions with empty stack. --- src/x509.c | 10 +++++++++- tests/api.c | 2 ++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/x509.c b/src/x509.c index ca5ffd5a401..feb50548ddd 100644 --- a/src/x509.c +++ b/src/x509.c @@ -13618,13 +13618,21 @@ static int regenX509REQDerBuffer(WOLFSSL_X509* x509) int wolfSSL_X509_REQ_add_extensions(WOLFSSL_X509* req, WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* ext_sk) { + WOLFSSL_X509_EXTENSION* ext = NULL; + if (!req || !ext_sk) { WOLFSSL_MSG("Bad parameter"); return WOLFSSL_FAILURE; } + /* It is not an error if the stack is empty. */ + ext = ext_sk->data.ext; + if (ext == NULL) { + return WOLFSSL_SUCCESS; + } + while (ext_sk) { - WOLFSSL_X509_EXTENSION* ext = ext_sk->data.ext; + ext = ext_sk->data.ext; if (wolfSSL_X509_add_ext(req, ext, -1) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("wolfSSL_X509_add_ext error"); diff --git a/tests/api.c b/tests/api.c index 6aafc64d755..a9527d48ac3 100644 --- a/tests/api.c +++ b/tests/api.c @@ -43377,6 +43377,8 @@ static int test_othername_and_SID_ext(void) { AssertNotNull(sid_ext = X509_EXTENSION_create_by_OBJ(NULL, sid_oid, 0, sid_data)); AssertNotNull(exts = sk_X509_EXTENSION_new_null()); + /* Ensure an empty stack doesn't raise an error. */ + AssertIntEQ(X509_REQ_add_extensions(x509, exts), 1); AssertIntEQ(sk_X509_EXTENSION_push(exts, san_ext), 1); AssertIntEQ(sk_X509_EXTENSION_push(exts, sid_ext), 2); AssertIntEQ(X509_REQ_add_extensions(x509, exts), 1); From 0e5fcbf23ccf3e8e96d2cb1fb6a69274b121869e Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 19 Apr 2023 14:17:30 +1000 Subject: [PATCH 172/391] Memory Usage: reduce maximum in use CheckCertSignature Free the dataASN before calling ConfirmSignature. dataASN not needed at this point and ConfirmSignature uses lots of memory. DecodeCertInternal: Free the dataASN before calling DecodeCertExtensions, dataASN not needed at this point and DecodeCertExtensions uses more memory. ecc_verify_hash: v doesn't need to be a new allocated variable - reuse w. v is the modular reduction of x-ordinate to prime calculated at end. --- wolfcrypt/src/asn.c | 39 +++++++++++++++++++++------------------ wolfcrypt/src/ecc.c | 13 ++----------- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index eaa60c79ec9..879061bc569 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -20275,33 +20275,35 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, cert->extensionsSz = (int)GetASNItem_Length( dataASN[X509CERTASN_IDX_TBS_EXT], cert->source); cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset; - - /* Decode the extension data starting at [3]. */ - ret = DecodeCertExtensions(cert); - if (criticalExt != NULL) { - if (ret == ASN_CRIT_EXT_E) { - /* Return critical extension not recognized. */ - *criticalExt = ret; - ret = 0; - } - else { - /* No critical extension error. */ - *criticalExt = 0; - } - } - } - if (ret == 0) { /* Advance past extensions. */ cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset; } } + /* Dispose of memory before allocating for extension decoding. */ + FREE_ASNGETDATA(dataASN, cert->heap); + + if ((ret == 0) && (!done) && (cert->extensions != NULL)) { + /* Decode the extension data starting at [3]. */ + ret = DecodeCertExtensions(cert); + if (criticalExt != NULL) { + if (ret == ASN_CRIT_EXT_E) { + /* Return critical extension not recognized. */ + *criticalExt = ret; + ret = 0; + } + else { + /* No critical extension error. */ + *criticalExt = 0; + } + } + } + if ((ret == 0) && (!done) && (badDate != 0)) { /* Parsed whole certificate fine but return any date errors. */ ret = badDate; } - FREE_ASNGETDATA(dataASN, cert->heap); return ret; } @@ -21408,6 +21410,8 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, } } + FREE_ASNGETDATA(dataASN, heap); + if (ret == 0) { /* Check signature. */ ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz, pubKeyOID, @@ -21422,7 +21426,6 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, if (sigCtx != NULL) XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); #endif - FREE_ASNGETDATA(dataASN, heap); return ret; #endif /* WOLFSSL_ASN_TEMPLATE */ } diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 3e5341f0a79..df3ac4bbc30 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -8284,12 +8284,12 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, ecc_point lcl_mG; ecc_point lcl_mQ; #endif - DECL_MP_INT_SIZE_DYN(v, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); DECL_MP_INT_SIZE_DYN(w, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) DECL_MP_INT_SIZE_DYN(e_lcl, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); #endif mp_int* e; + mp_int* v = NULL; /* Will be w. */ mp_int* u1 = NULL; /* Will be e. */ mp_int* u2 = NULL; /* Will be w. */ @@ -8371,12 +8371,6 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, } #endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */ - NEW_MP_INT_SIZE(v, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); -#ifdef MP_INT_SIZE_CHECK_NULL - if (v == NULL) { - err = MEMORY_E; - } -#endif NEW_MP_INT_SIZE(w, ECC_KEY_MAX_BITS(key), key->heap, DYNAMIC_TYPE_ECC); #ifdef MP_INT_SIZE_CHECK_NULL if (w == NULL) { @@ -8387,8 +8381,7 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, if (err == MP_OKAY) { u1 = e; u2 = w; - - err = INIT_MP_INT_SIZE(v, ECC_KEY_MAX_BITS(key)); + v = w; } if (err == MP_OKAY) { err = INIT_MP_INT_SIZE(w, ECC_KEY_MAX_BITS(key)); @@ -8503,10 +8496,8 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, wc_ecc_del_point_ex(mQ, key->heap); mp_clear(e); - mp_clear(v); mp_clear(w); FREE_MP_INT_SIZE(w, key->heap, DYNAMIC_TYPE_ECC); - FREE_MP_INT_SIZE(v, key->heap, DYNAMIC_TYPE_ECC); #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) FREE_MP_INT_SIZE(e_lcl, key->heap, DYNAMIC_TYPE_ECC); #endif From bbcdae092b53e9bc4a1ebee39fa77feabc3741bf Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Thu, 23 Mar 2023 10:46:09 +0100 Subject: [PATCH 173/391] Try to XOR as many words as possible in xorbuf APIs --- wolfcrypt/src/misc.c | 62 ++++++++++++++++++++++++---------------- wolfssl/wolfcrypt/misc.h | 6 ++-- 2 files changed, 41 insertions(+), 27 deletions(-) diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index 3c47e517c93..d0045a0e575 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -256,42 +256,50 @@ WC_MISC_STATIC WC_INLINE void ByteReverseWords64(word64* out, const word64* in, #ifndef WOLFSSL_NO_XOR_OPS /* This routine performs a bitwise XOR operation of <*r> and <*a> for number of wolfssl_words, placing the result in <*r>. */ -WC_MISC_STATIC WC_INLINE void XorWordsOut(wolfssl_word* r, - const wolfssl_word* a, const wolfssl_word* b, word32 n) +WC_MISC_STATIC WC_INLINE void XorWordsOut(wolfssl_word** r, + const wolfssl_word** a, const wolfssl_word** b, word32 n) { word32 i; - for (i = 0; i < n; i++) r[i] = a[i] ^ b[i]; + for (i = 0; i < n; i++) + *(*r)++ = *(*a)++ ^ *(*b)++; } /* This routine performs a bitwise XOR operation of <*buf> and <*mask> of n counts, placing the result in <*buf>. */ -WC_MISC_STATIC WC_INLINE void xorbufout(void*out, const void* buf, +WC_MISC_STATIC WC_INLINE void xorbufout(void* out, const void* buf, const void* mask, word32 count) { - if (((wc_ptr_t)out | (wc_ptr_t)buf | (wc_ptr_t)mask | count) % - WOLFSSL_WORD_SIZE == 0) - XorWordsOut( (wolfssl_word*)out, (wolfssl_word*)buf, - (const wolfssl_word*)mask, count / WOLFSSL_WORD_SIZE); - else { - word32 i; - byte* o = (byte*)out; - byte* b = (byte*)buf; - const byte* m = (const byte*)mask; + word32 i; + byte* o; + byte* b; + const byte* m; - for (i = 0; i < count; i++) o[i] = b[i] ^ m[i]; + if (((wc_ptr_t)buf | (wc_ptr_t)mask) % WOLFSSL_WORD_SIZE == 0) { + /* Alignment checks out. Possible to XOR words. */ + XorWordsOut( (wolfssl_word**)&out, (const wolfssl_word**)&buf, + (const wolfssl_word**)&mask, count / WOLFSSL_WORD_SIZE); + count %= WOLFSSL_WORD_SIZE; } + + o = (byte*)out; + b = (byte*)buf; + m = (const byte*)mask; + + for (i = 0; i < count; i++) + o[i] = b[i] ^ m[i]; } /* This routine performs a bitwise XOR operation of <*r> and <*a> for number of wolfssl_words, placing the result in <*r>. */ -WC_MISC_STATIC WC_INLINE void XorWords(wolfssl_word* r, const wolfssl_word* a, +WC_MISC_STATIC WC_INLINE void XorWords(wolfssl_word** r, const wolfssl_word** a, word32 n) { word32 i; - for (i = 0; i < n; i++) r[i] ^= a[i]; + for (i = 0; i < n; i++) + *(*r)++ ^= *(*a)++; } /* This routine performs a bitwise XOR operation of <*buf> and <*mask> of n @@ -299,16 +307,22 @@ counts, placing the result in <*buf>. */ WC_MISC_STATIC WC_INLINE void xorbuf(void* buf, const void* mask, word32 count) { - if (((wc_ptr_t)buf | (wc_ptr_t)mask | count) % WOLFSSL_WORD_SIZE == 0) - XorWords( (wolfssl_word*)buf, - (const wolfssl_word*)mask, count / WOLFSSL_WORD_SIZE); - else { - word32 i; - byte* b = (byte*)buf; - const byte* m = (const byte*)mask; + word32 i; + byte* b; + const byte* m; - for (i = 0; i < count; i++) b[i] ^= m[i]; + if (((wc_ptr_t)buf | (wc_ptr_t)mask) % WOLFSSL_WORD_SIZE == 0) { + /* Alignment checks out. Possible to XOR words. */ + XorWords( (wolfssl_word**)&buf, + (const wolfssl_word**)&mask, count / WOLFSSL_WORD_SIZE); + count %= WOLFSSL_WORD_SIZE; } + + b = (byte*)buf; + m = (const byte*)mask; + + for (i = 0; i < count; i++) + b[i] ^= m[i]; } #endif diff --git a/wolfssl/wolfcrypt/misc.h b/wolfssl/wolfcrypt/misc.h index 418246787ef..e433a1a3c70 100644 --- a/wolfssl/wolfcrypt/misc.h +++ b/wolfssl/wolfcrypt/misc.h @@ -59,12 +59,12 @@ WOLFSSL_LOCAL void ByteReverseWords(word32* out, const word32* in, word32 byteCount); WOLFSSL_LOCAL -void XorWordsOut(wolfssl_word* r, const wolfssl_word* a, const wolfssl_word* b, - word32 n); +void XorWordsOut(wolfssl_word** r, const wolfssl_word** a, + const wolfssl_word** b, word32 n); WOLFSSL_LOCAL void xorbufout(void* out, const void* buf, const void* mask, word32 count); WOLFSSL_LOCAL -void XorWords(wolfssl_word* r, const wolfssl_word* a, word32 n); +void XorWords(wolfssl_word** r, const wolfssl_word** a, word32 n); WOLFSSL_LOCAL void xorbuf(void* buf, const void* mask, word32 count); From 817af24a3c8d5475e23b161f59045aeac4d6b4ce Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 22 Mar 2023 18:48:16 +0100 Subject: [PATCH 174/391] Use xorbufout in chacha --- wolfcrypt/src/chacha.c | 70 +++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 42 deletions(-) diff --git a/wolfcrypt/src/chacha.c b/wolfcrypt/src/chacha.c index ae17728f199..4dc9601499e 100644 --- a/wolfcrypt/src/chacha.c +++ b/wolfcrypt/src/chacha.c @@ -202,15 +202,12 @@ int wc_Chacha_SetKey(ChaCha* ctx, const byte* key, word32 keySz) /** * Converts word into bytes with rotations having been done. */ -static WC_INLINE void wc_Chacha_wordtobyte(word32 output[CHACHA_CHUNK_WORDS], - const word32 input[CHACHA_CHUNK_WORDS]) +static WC_INLINE void wc_Chacha_wordtobyte(word32 x[CHACHA_CHUNK_WORDS], + word32 state[CHACHA_CHUNK_WORDS]) { - word32 x[CHACHA_CHUNK_WORDS]; word32 i; - for (i = 0; i < CHACHA_CHUNK_WORDS; i++) { - x[i] = input[i]; - } + XMEMCPY(x, state, CHACHA_CHUNK_BYTES); for (i = (ROUNDS); i > 0; i -= 2) { QUARTERROUND(0, 4, 8, 12) @@ -224,11 +221,8 @@ static WC_INLINE void wc_Chacha_wordtobyte(word32 output[CHACHA_CHUNK_WORDS], } for (i = 0; i < CHACHA_CHUNK_WORDS; i++) { - x[i] = PLUS(x[i], input[i]); - } - - for (i = 0; i < CHACHA_CHUNK_WORDS; i++) { - output[i] = LITTLE32(x[i]); + x[i] = PLUS(x[i], state[i]); + x[i] = LITTLE32(x[i]); } } @@ -334,36 +328,33 @@ extern void chacha_encrypt_avx2(ChaCha* ctx, const byte* m, byte* c, static void wc_Chacha_encrypt_bytes(ChaCha* ctx, const byte* m, byte* c, word32 bytes) { - byte* output; - word32 temp[CHACHA_CHUNK_WORDS]; /* used to make sure aligned */ - word32 i; + union { + byte state[CHACHA_CHUNK_BYTES]; + word32 state32[CHACHA_CHUNK_WORDS]; + wolfssl_word align_word; /* align for xorbufout */ + } tmp; /* handle left overs */ if (bytes > 0 && ctx->left > 0) { - wc_Chacha_wordtobyte(temp, ctx->X); /* recreate the stream */ - output = (byte*)temp + CHACHA_CHUNK_BYTES - ctx->left; - for (i = 0; i < bytes && i < ctx->left; i++) { - c[i] = (byte)(m[i] ^ output[i]); - } - ctx->left -= i; + word32 processed = min(bytes, ctx->left); + wc_Chacha_wordtobyte(tmp.state32, ctx->X); /* recreate the stream */ + xorbufout(c, m, tmp.state + CHACHA_CHUNK_BYTES - ctx->left, processed); + ctx->left -= processed; /* Used up all of the stream that was left, increment the counter */ if (ctx->left == 0) { ctx->X[CHACHA_MATRIX_CNT_IV] = PLUSONE(ctx->X[CHACHA_MATRIX_CNT_IV]); } - bytes -= i; - c += i; - m += i; + bytes -= processed; + c += processed; + m += processed; } - output = (byte*)temp; while (bytes >= CHACHA_CHUNK_BYTES) { - wc_Chacha_wordtobyte(temp, ctx->X); + wc_Chacha_wordtobyte(tmp.state32, ctx->X); ctx->X[CHACHA_MATRIX_CNT_IV] = PLUSONE(ctx->X[CHACHA_MATRIX_CNT_IV]); - for (i = 0; i < CHACHA_CHUNK_BYTES; ++i) { - c[i] = (byte)(m[i] ^ output[i]); - } + xorbufout(c, m, tmp.state, CHACHA_CHUNK_BYTES); bytes -= CHACHA_CHUNK_BYTES; c += CHACHA_CHUNK_BYTES; m += CHACHA_CHUNK_BYTES; @@ -373,11 +364,9 @@ static void wc_Chacha_encrypt_bytes(ChaCha* ctx, const byte* m, byte* c, /* in this case there will always be some left over since bytes is less * than CHACHA_CHUNK_BYTES, so do not increment counter after getting * stream in order for the stream to be recreated on next call */ - wc_Chacha_wordtobyte(temp, ctx->X); - for (i = 0; i < bytes; ++i) { - c[i] = m[i] ^ output[i]; - } - ctx->left = CHACHA_CHUNK_BYTES - i; + wc_Chacha_wordtobyte(tmp.state32, ctx->X); + xorbufout(c, m, tmp.state, bytes); + ctx->left = CHACHA_CHUNK_BYTES - bytes; } } @@ -394,17 +383,14 @@ int wc_Chacha_Process(ChaCha* ctx, byte* output, const byte* input, /* handle left overs */ if (msglen > 0 && ctx->left > 0) { byte* out; - word32 i; + word32 processed = min(msglen, ctx->left); out = (byte*)ctx->over + CHACHA_CHUNK_BYTES - ctx->left; - for (i = 0; i < msglen && i < ctx->left; i++) { - output[i] = (byte)(input[i] ^ out[i]); - } - ctx->left -= i; - - msglen -= i; - output += i; - input += i; + xorbufout(output, input, out, processed); + ctx->left -= processed; + msglen -= processed; + output += processed; + input += processed; } if (msglen == 0) { From f85911d88de57cd1a5271865d68b7c61185cff06 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 29 Mar 2023 15:12:35 +0200 Subject: [PATCH 175/391] Use xorbuf in 3des for FREESCALE_MMCAU --- wolfcrypt/src/des3.c | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/wolfcrypt/src/des3.c b/wolfcrypt/src/des3.c index 02cc761125c..672a8673b88 100644 --- a/wolfcrypt/src/des3.c +++ b/wolfcrypt/src/des3.c @@ -941,8 +941,7 @@ XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); /* XOR block with IV for CBC */ - for (i = 0; i < DES_BLOCK_SIZE; i++) - temp_block[i] ^= iv[i]; + xorbuf(temp_block, iv, DES_BLOCK_SIZE); ret = wolfSSL_CryptHwMutexLock(); if(ret != 0) { @@ -1000,8 +999,7 @@ wolfSSL_CryptHwMutexUnLock(); /* XOR block with IV for CBC */ - for (i = 0; i < DES_BLOCK_SIZE; i++) - (out + offset)[i] ^= iv[i]; + xorbuf(out + offset, iv, DES_BLOCK_SIZE); /* store IV for next block */ XMEMCPY(iv, temp_block, DES_BLOCK_SIZE); @@ -1037,8 +1035,7 @@ XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); /* XOR block with IV for CBC */ - for (i = 0; i < DES_BLOCK_SIZE; i++) - temp_block[i] ^= iv[i]; + xorbuf(temp_block, iv, DES_BLOCK_SIZE); ret = wolfSSL_CryptHwMutexLock(); if(ret != 0) { @@ -1104,8 +1101,7 @@ wolfSSL_CryptHwMutexUnLock(); /* XOR block with IV for CBC */ - for (i = 0; i < DES_BLOCK_SIZE; i++) - (out + offset)[i] ^= iv[i]; + xorbuf(out + offset, iv, DES_BLOCK_SIZE); /* store IV for next block */ XMEMCPY(iv, temp_block, DES_BLOCK_SIZE); From 8c66bb1af5e6543903654b7c7bac90fb5063b06d Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 29 Mar 2023 15:15:23 +0200 Subject: [PATCH 176/391] Simplify ctMaskCopy --- wolfcrypt/src/misc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index d0045a0e575..2d5dfc547db 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -599,7 +599,7 @@ WC_MISC_STATIC WC_INLINE void ctMaskCopy(byte mask, byte* dst, byte* src, { int i; for (i = 0; i < size; ++i) { - *(dst + i) ^= (*(dst + i) ^ *(src + i)) & mask; + dst[i] ^= (dst[i] ^ src[i]) & mask; } } From 496fd88e39fbd1197ffc976c16c219735af21a84 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 29 Mar 2023 15:49:03 +0200 Subject: [PATCH 177/391] pkcs12.c: Ignore param when heap not used --- wolfcrypt/src/pkcs12.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/wolfcrypt/src/pkcs12.c b/wolfcrypt/src/pkcs12.c index 7756d4379e0..b2d837caab6 100644 --- a/wolfcrypt/src/pkcs12.c +++ b/wolfcrypt/src/pkcs12.c @@ -1157,6 +1157,8 @@ static byte* PKCS12_ConcatonateContent(WC_PKCS12* pkcs12,byte* mergedData, byte* oldContent; word32 oldContentSz; + (void)pkcs12; + if (mergedData == NULL || in == NULL) return NULL; From dd375c1855f13b09d7ee21bf2594d7d55826e6c7 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 29 Mar 2023 15:55:48 +0200 Subject: [PATCH 178/391] rsa.c: Use xorbuf when possible --- wolfcrypt/src/rsa.c | 41 +++++++++++------------------------------ 1 file changed, 11 insertions(+), 30 deletions(-) diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index e63ddc96a4f..531302d4c16 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -1143,7 +1143,6 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, int ret; word32 hLen; int psLen; - int i; word32 idx; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) @@ -1235,10 +1234,8 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, } XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen); pkcsBlock[idx--] = 0x01; /* PS and M separator */ - while (psLen > 0 && idx > 0) { - pkcsBlock[idx--] = 0x00; - psLen--; - } + XMEMSET(pkcsBlock + idx - psLen + 1, 0, psLen); + idx -= psLen; idx = idx - hLen + 1; XMEMCPY(pkcsBlock + idx, lHash, hLen); @@ -1277,19 +1274,14 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, return ret; } - i = 0; - idx = hLen + 1; - while (idx < pkcsBlockLen && (word32)i < (pkcsBlockLen - hLen -1)) { - pkcsBlock[idx] = dbMask[i++] ^ pkcsBlock[idx]; - idx++; - } + xorbuf(pkcsBlock + hLen + 1, dbMask,pkcsBlockLen - hLen - 1); + #ifdef WOLFSSL_SMALL_STACK XFREE(dbMask, heap, DYNAMIC_TYPE_RSA); #endif /* create maskedSeed from seedMask */ - idx = 0; - pkcsBlock[idx++] = 0x00; + pkcsBlock[0] = 0x00; /* create seedMask inline */ if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1, pkcsBlock + 1, hLen, heap)) != 0) { @@ -1301,11 +1293,7 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, } /* xor created seedMask with seed to make maskedSeed */ - i = 0; - while (idx < (hLen + 1) && i < (int)hLen) { - pkcsBlock[idx] = pkcsBlock[idx] ^ seed[i++]; - idx++; - } + xorbuf(pkcsBlock + 1, seed, hLen); #ifdef WOLFSSL_CHECK_MEM_ZERO /* Seed must be zeroized now that it has been used. */ wc_MemZero_Add("Pad OAEP seed", seed, hLen); @@ -1349,7 +1337,7 @@ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, int saltLen, int bits, void* heap) { int ret = 0; - int hLen, i, o, maskLen, hiBits; + int hLen, o, maskLen, hiBits; byte* m; byte* s; #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY) @@ -1485,9 +1473,7 @@ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, m = pkcsBlock + maskLen - saltLen - 1; *(m++) ^= 0x01; - for (i = 0; i < saltLen; i++) { - m[i] ^= salt[o + i]; - } + xorbuf(m, salt + o, saltLen); } #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) @@ -1681,9 +1667,7 @@ static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen, } /* xor seedMask value with maskedSeed to get seed value */ - for (idx = 0; idx < (word32)hLen; idx++) { - tmp[idx] = tmp[idx] ^ pkcsBlock[1 + idx]; - } + xorbuf(tmp, pkcsBlock + 1, hLen); /* get dbMask value */ if ((ret = RsaMGF(mgf, tmp, hLen, tmp + hLen, @@ -1698,9 +1682,7 @@ static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen, } /* get DB value by doing maskedDB xor dbMask */ - for (idx = 0; idx < (pkcsBlockLen - hLen - 1); idx++) { - pkcsBlock[hLen + 1 + idx] = pkcsBlock[hLen + 1 + idx] ^ tmp[idx + hLen]; - } + xorbuf(pkcsBlock + hLen + 1, tmp + hLen, pkcsBlockLen - hLen - 1); ForceZero(tmp, pkcsBlockLen); #ifdef WOLFSSL_SMALL_STACK @@ -1873,8 +1855,7 @@ static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen, return PSS_SALTLEN_E; } } - for (i++; i < maskLen; i++) - pkcsBlock[i] ^= tmp[i]; + xorbuf(pkcsBlock + i, tmp + i, maskLen - i); #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); From 5032a9748f3256870d7b09bc2c9582bbd715dbbe Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 29 Mar 2023 16:08:36 +0200 Subject: [PATCH 179/391] xorbuf: fix alignment when possible --- wolfcrypt/src/misc.c | 47 ++++++++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index 2d5dfc547db..477fc5aa6a3 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -262,7 +262,7 @@ WC_MISC_STATIC WC_INLINE void XorWordsOut(wolfssl_word** r, word32 i; for (i = 0; i < n; i++) - *(*r)++ = *(*a)++ ^ *(*b)++; + *((*r)++) = *((*a)++) ^ *((*b)++); } /* This routine performs a bitwise XOR operation of <*buf> and <*mask> of n @@ -276,17 +276,27 @@ WC_MISC_STATIC WC_INLINE void xorbufout(void* out, const void* buf, byte* b; const byte* m; - if (((wc_ptr_t)buf | (wc_ptr_t)mask) % WOLFSSL_WORD_SIZE == 0) { - /* Alignment checks out. Possible to XOR words. */ - XorWordsOut( (wolfssl_word**)&out, (const wolfssl_word**)&buf, - (const wolfssl_word**)&mask, count / WOLFSSL_WORD_SIZE); - count %= WOLFSSL_WORD_SIZE; - } - o = (byte*)out; b = (byte*)buf; m = (const byte*)mask; + + if (((wc_ptr_t)o) % WOLFSSL_WORD_SIZE == + ((wc_ptr_t)b) % WOLFSSL_WORD_SIZE && + ((wc_ptr_t)b) % WOLFSSL_WORD_SIZE == + ((wc_ptr_t)m) % WOLFSSL_WORD_SIZE) { + /* Alignment checks out. Possible to XOR words. */ + /* Move alignment so that it lines up with a + * WOLFSSL_WORD_SIZE boundary */ + while (((wc_ptr_t)b) % WOLFSSL_WORD_SIZE != 0 && count > 0) { + *(o++) = *(b++) ^ *(m++); + count--; + } + XorWordsOut( (wolfssl_word**)&o, (const wolfssl_word**)&b, + (const wolfssl_word**)&m, count / WOLFSSL_WORD_SIZE); + count %= WOLFSSL_WORD_SIZE; + } + for (i = 0; i < count; i++) o[i] = b[i] ^ m[i]; } @@ -299,7 +309,7 @@ WC_MISC_STATIC WC_INLINE void XorWords(wolfssl_word** r, const wolfssl_word** a, word32 i; for (i = 0; i < n; i++) - *(*r)++ ^= *(*a)++; + *((*r)++) ^= *((*a)++); } /* This routine performs a bitwise XOR operation of <*buf> and <*mask> of n @@ -311,16 +321,23 @@ WC_MISC_STATIC WC_INLINE void xorbuf(void* buf, const void* mask, word32 count) byte* b; const byte* m; - if (((wc_ptr_t)buf | (wc_ptr_t)mask) % WOLFSSL_WORD_SIZE == 0) { + b = (byte*)buf; + m = (const byte*)mask; + + if (((wc_ptr_t)b) % WOLFSSL_WORD_SIZE == + ((wc_ptr_t)m) % WOLFSSL_WORD_SIZE) { /* Alignment checks out. Possible to XOR words. */ - XorWords( (wolfssl_word**)&buf, - (const wolfssl_word**)&mask, count / WOLFSSL_WORD_SIZE); + /* Move alignment so that it lines up with a + * WOLFSSL_WORD_SIZE boundary */ + while (((wc_ptr_t)buf) % WOLFSSL_WORD_SIZE != 0 && count > 0) { + *(b++) ^= *(m++); + count--; + } + XorWords( (wolfssl_word**)&b, + (const wolfssl_word**)&m, count / WOLFSSL_WORD_SIZE); count %= WOLFSSL_WORD_SIZE; } - b = (byte*)buf; - m = (const byte*)mask; - for (i = 0; i < count; i++) b[i] ^= m[i]; } From 4bf3e6297d961777ac085e65aa227380e791fb52 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 29 Mar 2023 16:55:50 +0200 Subject: [PATCH 180/391] aes.c: Use xorbufout when possible --- wolfcrypt/src/aes.c | 90 +++++++++++++++++++-------------------------- 1 file changed, 38 insertions(+), 52 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index c44f77bb117..75e57145ea7 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -3829,8 +3829,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); /* XOR block with IV for CBC */ - for (i = 0; i < AES_BLOCK_SIZE; i++) - temp_block[i] ^= iv[i]; + xorbuf(temp_block, iv, AES_BLOCK_SIZE); ret = wc_AesEncrypt(aes, temp_block, out + offset); if (ret != 0) @@ -3869,8 +3868,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) wc_AesDecrypt(aes, in + offset, out + offset); /* XOR block with IV for CBC */ - for (i = 0; i < AES_BLOCK_SIZE; i++) - (out + offset)[i] ^= iv[i]; + xorbuf(out + offset, iv, AES_BLOCK_SIZE); /* store IV for next block */ XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); @@ -4455,9 +4453,9 @@ int wc_AesSetIV(Aes* aes, const byte* iv) /* Software AES - CTR Encrypt */ int wc_AesCtrEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - byte* tmp; byte scratch[AES_BLOCK_SIZE]; int ret; + word32 processed; if (aes == NULL || out == NULL || in == NULL) { return BAD_FUNC_ARG; @@ -4473,12 +4471,13 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #endif /* consume any unused bytes left in aes->tmp */ - tmp = (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left; - while (aes->left && sz) { - *(out++) = *(in++) ^ *(tmp++); - aes->left--; - sz--; - } + processed = min(aes->left, sz); + xorbufout(out, in, (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left, + processed); + out += processed; + in += processed; + aes->left -= processed; + sz -= processed; #if defined(HAVE_AES_ECB) && !defined(WOLFSSL_PIC32MZ_CRYPT) && \ !defined(XTRANSFORM_AESCTRBLOCK) @@ -4545,13 +4544,8 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } IncrementAesCounter((byte*)aes->reg); - aes->left = AES_BLOCK_SIZE; - tmp = (byte*)aes->tmp; - - while (sz--) { - *(out++) = *(in++) ^ *(tmp++); - aes->left--; - } + aes->left = AES_BLOCK_SIZE - sz; + xorbufout(out, in, aes->tmp, sz); } #ifdef WOLFSSL_CHECK_MEM_ZERO @@ -9924,6 +9918,7 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( byte* reg = NULL; #endif int ret = 0; + word32 processed; if (aes == NULL || out == NULL || in == NULL) { return BAD_FUNC_ARG; @@ -9936,18 +9931,17 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( #endif /* consume any unused bytes left in aes->tmp */ - tmp = (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left; - while (aes->left && sz) { - *(out) = *(in++) ^ *(tmp++); - #ifdef WOLFSSL_AES_CFB - if (mode == AES_CFB_MODE) { - *(reg++) = *out; - } - #endif - out++; - aes->left--; - sz--; + processed = min(aes->left, sz); + xorbufout(out, in, (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left, processed); +#ifdef WOLFSSL_AES_CFB + if (mode == AES_CFB_MODE) { + XMEMCPY((byte*)aes->reg + AES_BLOCK_SIZE - aes->left, out, processed); } +#endif + aes->left -= processed; + out += processed; + in += processed; + sz -= processed; SAVE_VECTOR_REGISTERS(return _svr_ret;); @@ -9990,16 +9984,13 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( reg = (byte*)aes->reg; #endif - while (sz--) { - *(out) = *(in++) ^ *(tmp++); - #ifdef WOLFSSL_AES_CFB - if (mode == AES_CFB_MODE) { - *(reg++) = *out; - } - #endif - out++; - aes->left--; + xorbufout(out, in, tmp, sz); + #ifdef WOLFSSL_AES_CFB + if (mode == AES_CFB_MODE) { + XMEMCPY(reg, out, sz); } + #endif + aes->left -= sz; } RESTORE_VECTOR_REGISTERS(); @@ -10022,8 +10013,8 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( static WARN_UNUSED_RESULT int wc_AesFeedbackDecrypt( Aes* aes, byte* out, const byte* in, word32 sz, byte mode) { - byte* tmp; int ret = 0; + word32 processed; if (aes == NULL || out == NULL || in == NULL) { return BAD_FUNC_ARG; @@ -10038,12 +10029,12 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackDecrypt( #endif /* consume any unused bytes left in aes->tmp */ - tmp = (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left; - while (aes->left && sz) { - *(out++) = *(in++) ^ *(tmp++); - aes->left--; - sz--; - } + processed = min(aes->left, sz); + xorbufout(out, in, (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left, processed); + aes->left -= processed; + out += processed; + in += processed; + sz -= processed; SAVE_VECTOR_REGISTERS(return _svr_ret;); @@ -10086,13 +10077,8 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackDecrypt( } #endif - aes->left = AES_BLOCK_SIZE; - tmp = (byte*)aes->tmp; - - while (sz--) { - *(out++) = *(in++) ^ *(tmp++); - aes->left--; - } + aes->left = AES_BLOCK_SIZE - sz; + xorbufout(out, in, aes->tmp, sz); } RESTORE_VECTOR_REGISTERS(); From 3cca8df73ac4c594c81128b18bb8c17b67702025 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 31 Mar 2023 12:18:10 +0200 Subject: [PATCH 181/391] hpke.c: use xorbufout in wc_HpkeContextComputeNonce --- wolfcrypt/src/hpke.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/wolfcrypt/src/hpke.c b/wolfcrypt/src/hpke.c index b9e3c3b2c2f..b0d7dc44113 100644 --- a/wolfcrypt/src/hpke.c +++ b/wolfcrypt/src/hpke.c @@ -43,6 +43,13 @@ #include #include +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + const int hpkeSupportedKem[HPKE_SUPPORTED_KEM_LEN] = { DHKEM_P256_HKDF_SHA256, DHKEM_P384_HKDF_SHA384, @@ -581,7 +588,6 @@ static int wc_HpkeLabeledExpand(Hpke* hpke, byte* suite_id, word32 suite_id_len, static int wc_HpkeContextComputeNonce(Hpke* hpke, HpkeBaseContext* context, byte* out) { - int i; int ret; byte seq_bytes[HPKE_Nn_MAX]; @@ -589,9 +595,7 @@ static int wc_HpkeContextComputeNonce(Hpke* hpke, HpkeBaseContext* context, * nonce */ ret = I2OSP(context->seq, hpke->Nn, seq_bytes); if (ret == 0) { - for (i = 0; i < (int)hpke->Nn; i++) { - out[i] = (context->base_nonce[i] ^ seq_bytes[i]); - } + xorbufout(out, context->base_nonce, seq_bytes, hpke->Nn); } return ret; From a071fa57d9e754839629dc4dd7fb1b755ab1d785 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 31 Mar 2023 12:59:36 +0200 Subject: [PATCH 182/391] sakke.c: use xorbuf --- wolfcrypt/src/sakke.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/wolfcrypt/src/sakke.c b/wolfcrypt/src/sakke.c index 17d61d93af1..3803a4dd57a 100644 --- a/wolfcrypt/src/sakke.c +++ b/wolfcrypt/src/sakke.c @@ -6136,9 +6136,7 @@ static void sakke_xor_in_v(const byte* v, word32 hashSz, byte* out, int idx, i = 0; } o = i; - for (; i < hashSz; i++) { - out[idx + i - o] ^= v[i]; - } + xorbuf(out + idx + i - o, v + i, hashSz - i); } /* From 9dd21b35ce135b064b2dcf44a1b20aa50725706f Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 19 Apr 2023 15:26:05 -0500 Subject: [PATCH 183/391] more -Wconversion fixes, now covering everything inside the 140-3 boundary with default build options, everything in wolfcrypt with default build options, all modes of AES, builds with/without intelasm, all permutations of c89/c99 32/64 bit, and much of the crypto-all-cryptonly boundary; also a gating fix for asn.c:SetShortInt(). --- wolfcrypt/src/aes.c | 100 +++++++-------- wolfcrypt/src/asn.c | 11 +- wolfcrypt/src/blake2b.c | 4 +- wolfcrypt/src/blake2s.c | 8 +- wolfcrypt/src/chacha.c | 4 +- wolfcrypt/src/chacha20_poly1305.c | 4 +- wolfcrypt/src/curve25519.c | 2 +- wolfcrypt/src/curve448.c | 2 +- wolfcrypt/src/ecc.c | 4 +- wolfcrypt/src/pkcs12.c | 194 +++++++++++++++--------------- wolfcrypt/src/pwdbased.c | 66 +++++----- wolfcrypt/src/rsa.c | 57 ++++----- wolfcrypt/src/sha256.c | 2 +- wolfcrypt/src/sha512.c | 4 +- wolfcrypt/src/sp_int.c | 24 ++-- wolfcrypt/src/srp.c | 22 ++-- wolfssl/wolfcrypt/chacha.h | 2 +- 17 files changed, 257 insertions(+), 253 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 75e57145ea7..b314b62dc4d 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -809,7 +809,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits static WARN_UNUSED_RESULT int AES_set_decrypt_key( const unsigned char* userKey, const int bits, Aes* aes) { - int nr; + word32 nr; #ifdef WOLFSSL_SMALL_STACK Aes *temp_key; #else @@ -1795,7 +1795,7 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( XMEMCPY(tmp_align, inBlock, AES_BLOCK_SIZE); AES_ECB_encrypt(tmp_align, tmp_align, AES_BLOCK_SIZE, - (byte*)aes->key, aes->rounds); + (byte*)aes->key, (int)aes->rounds); XMEMCPY(outBlock, tmp_align, AES_BLOCK_SIZE); XFREE(tmp, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); return 0; @@ -1807,7 +1807,7 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( } AES_ECB_encrypt(inBlock, outBlock, AES_BLOCK_SIZE, (byte*)aes->key, - aes->rounds); + (int)aes->rounds); return 0; } @@ -2150,7 +2150,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( if ((const byte*)aes->tmp != inBlock) XMEMCPY(aes->tmp, inBlock, AES_BLOCK_SIZE); AES_ECB_decrypt(inBlock, outBlock, AES_BLOCK_SIZE, (byte*)aes->key, - aes->rounds); + (int)aes->rounds); return 0; } else { @@ -2927,10 +2927,10 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( else XMEMSET(aes->reg, 0, AES_BLOCK_SIZE); if (dir == AES_ENCRYPTION) - return AES_set_encrypt_key(userKey, keylen * 8, aes); + return AES_set_encrypt_key(userKey, (int)keylen * 8, aes); #ifdef HAVE_AES_DECRYPT else - return AES_set_decrypt_key(userKey, keylen * 8, aes); + return AES_set_decrypt_key(userKey, (int)keylen * 8, aes); #endif } #endif /* WOLFSSL_AESNI */ @@ -4073,7 +4073,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) XMEMCPY(tmp_align, in, sz); SAVE_VECTOR_REGISTERS(XFREE(tmp, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); return _svr_ret;); AES_CBC_encrypt(tmp_align, tmp_align, (byte*)aes->reg, sz, - (byte*)aes->key, aes->rounds); + (byte*)aes->key, (int)aes->rounds); RESTORE_VECTOR_REGISTERS(); /* store iv for next call */ XMEMCPY(aes->reg, tmp_align + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); @@ -4090,7 +4090,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) SAVE_VECTOR_REGISTERS(return _svr_ret;); AES_CBC_encrypt(in, out, (byte*)aes->reg, sz, (byte*)aes->key, - aes->rounds); + (int)aes->rounds); RESTORE_VECTOR_REGISTERS(); /* store iv for next call */ XMEMCPY(aes->reg, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); @@ -4205,7 +4205,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) aes->rounds); #else /* WOLFSSL_AESNI_BYx */ AES_CBC_decrypt_by8(in, out, (byte*)aes->reg, sz, (byte*)aes->key, - aes->rounds); + (int)aes->rounds); #endif /* WOLFSSL_AESNI_BYx */ /* store iv for next call */ RESTORE_VECTOR_REGISTERS(); @@ -5305,7 +5305,7 @@ static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE]) z8[0] ^= m8[0]; z8[1] ^= m8[1]; z8[2] ^= m8[2]; z8[3] ^= m8[3]; /* Cache top byte for remainder calculations - lost in rotate. */ - a = z8[3] >> 24; + a = (byte)(z8[3] >> 24); /* Rotate Z by 8-bits */ z8[3] = (z8[2] >> 24) | (z8[3] << 8); @@ -6720,7 +6720,7 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, if (IS_INTEL_AVX2(intel_flags)) { SAVE_VECTOR_REGISTERS(return _svr_ret;); AES_GCM_encrypt_avx2(in, out, authIn, iv, authTag, sz, authInSz, ivSz, - authTagSz, (const byte*)aes->key, aes->rounds); + authTagSz, (const byte*)aes->key, (int)aes->rounds); RESTORE_VECTOR_REGISTERS(); return 0; } @@ -6730,7 +6730,7 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, if (IS_INTEL_AVX1(intel_flags)) { SAVE_VECTOR_REGISTERS(return _svr_ret;); AES_GCM_encrypt_avx1(in, out, authIn, iv, authTag, sz, authInSz, ivSz, - authTagSz, (const byte*)aes->key, aes->rounds); + authTagSz, (const byte*)aes->key, (int)aes->rounds); RESTORE_VECTOR_REGISTERS(); return 0; } @@ -6738,7 +6738,7 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, #endif if (haveAESNI) { AES_GCM_encrypt(in, out, authIn, iv, authTag, sz, authInSz, ivSz, - authTagSz, (const byte*)aes->key, aes->rounds); + authTagSz, (const byte*)aes->key, (int)aes->rounds); return 0; } else @@ -7276,7 +7276,7 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, if (IS_INTEL_AVX2(intel_flags)) { SAVE_VECTOR_REGISTERS(return _svr_ret;); AES_GCM_decrypt_avx2(in, out, authIn, iv, authTag, sz, authInSz, ivSz, - authTagSz, (byte*)aes->key, aes->rounds, &res); + authTagSz, (byte*)aes->key, (int)aes->rounds, &res); RESTORE_VECTOR_REGISTERS(); if (res == 0) return AES_GCM_AUTH_E; @@ -7288,7 +7288,7 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, if (IS_INTEL_AVX1(intel_flags)) { SAVE_VECTOR_REGISTERS(return _svr_ret;); AES_GCM_decrypt_avx1(in, out, authIn, iv, authTag, sz, authInSz, ivSz, - authTagSz, (byte*)aes->key, aes->rounds, &res); + authTagSz, (byte*)aes->key, (int)aes->rounds, &res); RESTORE_VECTOR_REGISTERS(); if (res == 0) return AES_GCM_AUTH_E; @@ -7298,7 +7298,7 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, #endif if (haveAESNI) { AES_GCM_decrypt(in, out, authIn, iv, authTag, sz, authInSz, ivSz, - authTagSz, (byte*)aes->key, aes->rounds, &res); + authTagSz, (byte*)aes->key, (int)aes->rounds, &res); if (res == 0) return AES_GCM_AUTH_E; return 0; @@ -7560,7 +7560,7 @@ static WARN_UNUSED_RESULT int AesGcmInit_aesni( #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { SAVE_VECTOR_REGISTERS(return _svr_ret;); - AES_GCM_init_avx2((byte*)aes->key, aes->rounds, iv, ivSz, aes->H, + AES_GCM_init_avx2((byte*)aes->key, (int)aes->rounds, iv, ivSz, aes->H, AES_COUNTER(aes), AES_INITCTR(aes)); RESTORE_VECTOR_REGISTERS(); } @@ -7569,7 +7569,7 @@ static WARN_UNUSED_RESULT int AesGcmInit_aesni( #ifdef HAVE_INTEL_AVX1 if (IS_INTEL_AVX1(intel_flags)) { SAVE_VECTOR_REGISTERS(return _svr_ret;); - AES_GCM_init_avx1((byte*)aes->key, aes->rounds, iv, ivSz, aes->H, + AES_GCM_init_avx1((byte*)aes->key, (int)aes->rounds, iv, ivSz, aes->H, AES_COUNTER(aes), AES_INITCTR(aes)); RESTORE_VECTOR_REGISTERS(); } @@ -7577,7 +7577,7 @@ static WARN_UNUSED_RESULT int AesGcmInit_aesni( #endif { SAVE_VECTOR_REGISTERS(return _svr_ret;); - AES_GCM_init_aesni((byte*)aes->key, aes->rounds, iv, ivSz, aes->H, + AES_GCM_init_aesni((byte*)aes->key, (int)aes->rounds, iv, ivSz, aes->H, AES_COUNTER(aes), AES_INITCTR(aes)); RESTORE_VECTOR_REGISTERS(); } @@ -7609,7 +7609,7 @@ static WARN_UNUSED_RESULT int AesGcmAadUpdate_aesni( /* Calculate amount we can use - fill up the block. */ byte sz = AES_BLOCK_SIZE - aes->aOver; if (sz > aSz) { - sz = aSz; + sz = (byte)aSz; } /* Copy extra into last GHASH block array and update count. */ XMEMCPY(AES_LASTGBLOCK(aes) + aes->aOver, a, sz); @@ -7670,7 +7670,7 @@ static WARN_UNUSED_RESULT int AesGcmAadUpdate_aesni( } if (partial != 0) { /* Cache the partial block. */ - XMEMCPY(AES_LASTGBLOCK(aes), a, partial); + XMEMCPY(AES_LASTGBLOCK(aes), a, (size_t)partial); aes->aOver = (byte)partial; } } @@ -7735,7 +7735,7 @@ static WARN_UNUSED_RESULT int AesGcmEncryptUpdate_aesni( /* Calculate amount we can use - fill up the block. */ byte sz = AES_BLOCK_SIZE - aes->cOver; if (sz > cSz) { - sz = cSz; + sz = (byte)cSz; } /* Encrypt some of the plaintext. */ xorbuf(AES_LASTGBLOCK(aes) + aes->cOver, p, sz); @@ -7778,23 +7778,23 @@ static WARN_UNUSED_RESULT int AesGcmEncryptUpdate_aesni( /* Encrypt and GHASH full blocks now. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { - AES_GCM_encrypt_update_avx2((byte*)aes->key, aes->rounds, c, p, - blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, + AES_GCM_encrypt_update_avx2((byte*)aes->key, (int)aes->rounds, + c, p, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, AES_COUNTER(aes)); } else #endif #ifdef HAVE_INTEL_AVX1 if (IS_INTEL_AVX1(intel_flags)) { - AES_GCM_encrypt_update_avx1((byte*)aes->key, aes->rounds, c, p, - blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, + AES_GCM_encrypt_update_avx1((byte*)aes->key, (int)aes->rounds, + c, p, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, AES_COUNTER(aes)); } else #endif { - AES_GCM_encrypt_update_aesni((byte*)aes->key, aes->rounds, c, p, - blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, + AES_GCM_encrypt_update_aesni((byte*)aes->key, (int)aes->rounds, + c, p, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, AES_COUNTER(aes)); } /* Skip over to end of blocks. */ @@ -7806,27 +7806,27 @@ static WARN_UNUSED_RESULT int AesGcmEncryptUpdate_aesni( XMEMSET(AES_LASTGBLOCK(aes), 0, AES_BLOCK_SIZE); #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { - AES_GCM_encrypt_block_avx2((byte*)aes->key, aes->rounds, + AES_GCM_encrypt_block_avx2((byte*)aes->key, (int)aes->rounds, AES_LASTGBLOCK(aes), AES_LASTGBLOCK(aes), AES_COUNTER(aes)); } else #endif #ifdef HAVE_INTEL_AVX1 if (IS_INTEL_AVX1(intel_flags)) { - AES_GCM_encrypt_block_avx1((byte*)aes->key, aes->rounds, + AES_GCM_encrypt_block_avx1((byte*)aes->key, (int)aes->rounds, AES_LASTGBLOCK(aes), AES_LASTGBLOCK(aes), AES_COUNTER(aes)); } else #endif { - AES_GCM_encrypt_block_aesni((byte*)aes->key, aes->rounds, + AES_GCM_encrypt_block_aesni((byte*)aes->key, (int)aes->rounds, AES_LASTGBLOCK(aes), AES_LASTGBLOCK(aes), AES_COUNTER(aes)); } /* XOR the remaining plaintext to calculate cipher text. * Keep cipher text for GHASH of last partial block. */ - xorbuf(AES_LASTGBLOCK(aes), p, partial); - XMEMCPY(c, AES_LASTGBLOCK(aes), partial); + xorbuf(AES_LASTGBLOCK(aes), p, (word32)partial); + XMEMCPY(c, AES_LASTGBLOCK(aes), (size_t)partial); /* Update count of the block used. */ aes->cOver = (byte)partial; } @@ -7963,7 +7963,7 @@ static WARN_UNUSED_RESULT int AesGcmDecryptUpdate_aesni( /* Calculate amount we can use - fill up the block. */ byte sz = AES_BLOCK_SIZE - aes->cOver; if (sz > cSz) { - sz = cSz; + sz = (byte)cSz; } /* Keep a copy of the cipher text for GHASH. */ XMEMCPY(AES_LASTBLOCK(aes) + aes->cOver, c, sz); @@ -8008,23 +8008,23 @@ static WARN_UNUSED_RESULT int AesGcmDecryptUpdate_aesni( /* Decrypt and GHASH full blocks now. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { - AES_GCM_decrypt_update_avx2((byte*)aes->key, aes->rounds, p, c, - blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, + AES_GCM_decrypt_update_avx2((byte*)aes->key, (int)aes->rounds, + p, c, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, AES_COUNTER(aes)); } else #endif #ifdef HAVE_INTEL_AVX1 if (IS_INTEL_AVX1(intel_flags)) { - AES_GCM_decrypt_update_avx1((byte*)aes->key, aes->rounds, p, c, - blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, + AES_GCM_decrypt_update_avx1((byte*)aes->key, (int)aes->rounds, + p, c, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, AES_COUNTER(aes)); } else #endif { - AES_GCM_decrypt_update_aesni((byte*)aes->key, aes->rounds, p, c, - blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, + AES_GCM_decrypt_update_aesni((byte*)aes->key, (int)aes->rounds, + p, c, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->H, AES_COUNTER(aes)); } /* Skip over to end of blocks. */ @@ -8036,27 +8036,27 @@ static WARN_UNUSED_RESULT int AesGcmDecryptUpdate_aesni( XMEMSET(AES_LASTGBLOCK(aes), 0, AES_BLOCK_SIZE); #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { - AES_GCM_encrypt_block_avx2((byte*)aes->key, aes->rounds, + AES_GCM_encrypt_block_avx2((byte*)aes->key, (int)aes->rounds, AES_LASTGBLOCK(aes), AES_LASTGBLOCK(aes), AES_COUNTER(aes)); } else #endif #ifdef HAVE_INTEL_AVX1 if (IS_INTEL_AVX1(intel_flags)) { - AES_GCM_encrypt_block_avx1((byte*)aes->key, aes->rounds, + AES_GCM_encrypt_block_avx1((byte*)aes->key, (int)aes->rounds, AES_LASTGBLOCK(aes), AES_LASTGBLOCK(aes), AES_COUNTER(aes)); } else #endif { - AES_GCM_encrypt_block_aesni((byte*)aes->key, aes->rounds, + AES_GCM_encrypt_block_aesni((byte*)aes->key, (int)aes->rounds, AES_LASTGBLOCK(aes), AES_LASTGBLOCK(aes), AES_COUNTER(aes)); } /* Keep cipher text for GHASH of last partial block. */ - XMEMCPY(AES_LASTBLOCK(aes), c, partial); + XMEMCPY(AES_LASTBLOCK(aes), c, (size_t)partial); /* XOR the remaining cipher text to calculate plaintext. */ - xorbuf(AES_LASTGBLOCK(aes), c, partial); - XMEMCPY(p, AES_LASTGBLOCK(aes), partial); + xorbuf(AES_LASTGBLOCK(aes), c, (word32)partial); + XMEMCPY(p, AES_LASTGBLOCK(aes), (size_t)partial); /* Update count of the block used. */ aes->cOver = (byte)partial; } @@ -9190,7 +9190,7 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, AesCcmCtrIncSet4(B, lenSz); AES_ECB_encrypt(B, A, AES_BLOCK_SIZE * 4, (byte*)aes->key, - aes->rounds); + (int)aes->rounds); xorbuf(A, in, AES_BLOCK_SIZE * 4); XMEMCPY(out, A, AES_BLOCK_SIZE * 4); @@ -9315,7 +9315,7 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, AesCcmCtrIncSet4(B, lenSz); AES_ECB_encrypt(B, A, AES_BLOCK_SIZE * 4, (byte*)aes->key, - aes->rounds); + (int)aes->rounds); xorbuf(A, in, AES_BLOCK_SIZE * 4); XMEMCPY(o, A, AES_BLOCK_SIZE * 4); @@ -9815,7 +9815,7 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( #ifdef WOLFSSL_AESNI if (haveAESNI && aes->use_aesni) { SAVE_VECTOR_REGISTERS(return _svr_ret;); - AES_ECB_encrypt(in, out, sz, (byte*)aes->key, aes->rounds); + AES_ECB_encrypt(in, out, sz, (byte*)aes->key, (int)aes->rounds); RESTORE_VECTOR_REGISTERS(); blocks = 0; } @@ -9851,7 +9851,7 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( #ifdef WOLFSSL_AESNI if (haveAESNI && aes->use_aesni) { SAVE_VECTOR_REGISTERS(return _svr_ret;); - AES_ECB_decrypt(in, out, sz, (byte*)aes->key, aes->rounds); + AES_ECB_decrypt(in, out, sz, (byte*)aes->key, (int)aes->rounds); RESTORE_VECTOR_REGISTERS(); blocks = 0; } diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 879061bc569..dfd032aee04 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -3111,7 +3111,8 @@ int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx) } -#if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12) +#if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \ + defined(HAVE_PKCS12) /* Set small integer, 32 bits or less. DER encoding with no leading 0s * returns total amount written including ASN tag and length byte on success */ int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx) @@ -3155,7 +3156,7 @@ int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx) return len + 2; /* size of integer bytes plus ASN TAG and length byte */ } -#endif /* !WOLFSSL_ASN_TEMPLATE */ +#endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */ #endif /* !NO_PWDBASED */ #ifndef WOLFSSL_ASN_TEMPLATE @@ -11762,7 +11763,7 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, } /* Get the pubic key parameters. */ ret = DecodeRsaPssParams(source + seqIdx, - seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen); + (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen); if (ret != 0) { return ASN_PARSE_E; } @@ -11785,7 +11786,7 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, WOLFSSL_MSG("RSA PSS: sig salt length too small"); return ASN_PARSE_E; } - srcIdx += seqLen; + srcIdx += (word32)seqLen; } FALL_THROUGH; #endif /* WC_RSA_PSS */ @@ -16104,7 +16105,7 @@ static int ConfirmSignature(SignatureCtx* sigCtx, sigCtx->saltLen, 0); #else ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest, - sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash, + (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash, sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8, sigCtx->heap); #endif diff --git a/wolfcrypt/src/blake2b.c b/wolfcrypt/src/blake2b.c index ffd85123b7f..02a8d36f51a 100644 --- a/wolfcrypt/src/blake2b.c +++ b/wolfcrypt/src/blake2b.c @@ -219,7 +219,7 @@ static WC_INLINE int blake2b_compress( word64* m, word64* v) { - int i; + word64 i; for( i = 0; i < 16; ++i ) m[i] = load64( block + i * sizeof( m[i] ) ); @@ -339,7 +339,7 @@ int blake2b_final( blake2b_state *S, byte *out, byte outlen ) { int ret = 0; byte buffer[BLAKE2B_OUTBYTES]; - int i; + word64 i; #ifdef WOLFSSL_SMALL_STACK word64* m; word64* v; diff --git a/wolfcrypt/src/blake2s.c b/wolfcrypt/src/blake2s.c index 2e9f26ab364..9efa84f3b80 100644 --- a/wolfcrypt/src/blake2s.c +++ b/wolfcrypt/src/blake2s.c @@ -69,7 +69,7 @@ static const byte blake2s_sigma[10][16] = static WC_INLINE int blake2s_set_lastnode( blake2s_state *S ) { - S->f[1] = ~0; + S->f[1] = ~0U; return 0; } @@ -78,7 +78,7 @@ static WC_INLINE int blake2s_set_lastblock( blake2s_state *S ) { if( S->last_node ) blake2s_set_lastnode( S ); - S->f[0] = ~0; + S->f[0] = ~0U; return 0; } @@ -215,7 +215,7 @@ static WC_INLINE int blake2s_compress( word32* m, word32* v) { - int i; + word32 i; for( i = 0; i < 16; ++i ) m[i] = load32( block + i * sizeof( m[i] ) ); @@ -332,7 +332,7 @@ int blake2s_update( blake2s_state *S, const byte *in, word32 inlen ) int blake2s_final( blake2s_state *S, byte *out, byte outlen ) { int ret = 0; - int i; + word32 i; byte buffer[BLAKE2S_BLOCKBYTES]; #ifdef WOLFSSL_SMALL_STACK word32* m; diff --git a/wolfcrypt/src/chacha.c b/wolfcrypt/src/chacha.c index 4dc9601499e..c6a47726d16 100644 --- a/wolfcrypt/src/chacha.c +++ b/wolfcrypt/src/chacha.c @@ -77,7 +77,7 @@ Public domain. #endif static int cpuidFlagsSet = 0; - static int cpuidFlags = 0; + static word32 cpuidFlags = 0; #endif #ifdef BIG_ENDIAN_ORDER @@ -234,7 +234,7 @@ static WC_INLINE void wc_Chacha_wordtobyte(word32 x[CHACHA_CHUNK_WORDS], * * see https://tools.ietf.org/html/draft-arciszewski-xchacha-03 */ -static WC_INLINE void wc_HChacha_block(ChaCha* ctx, word32 stream[CHACHA_CHUNK_WORDS/2], int nrounds) +static WC_INLINE void wc_HChacha_block(ChaCha* ctx, word32 stream[CHACHA_CHUNK_WORDS/2], word32 nrounds) { word32 x[CHACHA_CHUNK_WORDS]; word32 i; diff --git a/wolfcrypt/src/chacha20_poly1305.c b/wolfcrypt/src/chacha20_poly1305.c index 08507d8d499..e4ebd10165f 100644 --- a/wolfcrypt/src/chacha20_poly1305.c +++ b/wolfcrypt/src/chacha20_poly1305.c @@ -149,7 +149,7 @@ int wc_ChaCha20Poly1305_Init(ChaChaPoly_Aead* aead, /* setup aead context */ XMEMSET(aead, 0, sizeof(ChaChaPoly_Aead)); XMEMSET(authKey, 0, sizeof(authKey)); - aead->isEncrypt = (byte)isEncrypt; + aead->isEncrypt = isEncrypt ? 1 : 0; /* Initialize the ChaCha20 context (key and iv) */ ret = wc_Chacha_SetKey(&aead->chacha, inKey, @@ -340,7 +340,7 @@ int wc_XChaCha20Poly1305_Init( if ((ret = wc_Poly1305_Pad(&aead->poly, (word32)ad_len)) < 0) return ret; - aead->isEncrypt = (byte)isEncrypt; + aead->isEncrypt = isEncrypt ? 1 : 0; aead->state = CHACHA20_POLY1305_STATE_AAD; return 0; diff --git a/wolfcrypt/src/curve25519.c b/wolfcrypt/src/curve25519.c index 1d36cf8abd2..d97a186885e 100644 --- a/wolfcrypt/src/curve25519.c +++ b/wolfcrypt/src/curve25519.c @@ -200,7 +200,7 @@ int wc_curve25519_make_priv(WC_RNG* rng, int keysize, byte* key) return ECC_BAD_ARG_E; /* random number for private key */ - ret = wc_RNG_GenerateBlock(rng, key, keysize); + ret = wc_RNG_GenerateBlock(rng, key, (word32)keysize); if (ret == 0) { /* Clamp the private key */ ret = curve25519_priv_clamp(key); diff --git a/wolfcrypt/src/curve448.c b/wolfcrypt/src/curve448.c index 57cc6ac70fd..dd320a8cc03 100644 --- a/wolfcrypt/src/curve448.c +++ b/wolfcrypt/src/curve448.c @@ -89,7 +89,7 @@ int wc_curve448_make_key(WC_RNG* rng, int keysize, curve448_key* key) if (ret == 0) { /* random number for private key */ - ret = wc_RNG_GenerateBlock(rng, key->k, keysize); + ret = wc_RNG_GenerateBlock(rng, key->k, (word32)keysize); } if (ret == 0) { key->privSet = 1; diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index df3ac4bbc30..99ee7aca214 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -9612,7 +9612,7 @@ static int ecc_check_privkey_gen_helper(ecc_key* key) static int _ecc_pairwise_consistency_test(ecc_key* key, WC_RNG* rng) { int err = 0; - int flags = key->flags; + word32 flags = key->flags; /* If flags not set default to cofactor and dec/sign */ if ((flags & (WC_ECC_FLAG_COFACTOR | WC_ECC_FLAG_DEC_SIGN)) == 0) { @@ -9629,7 +9629,7 @@ static int _ecc_pairwise_consistency_test(ecc_key* key, WC_RNG* rng) word32 sigLen, digestLen; int dynRng = 0, res = 0; - sigLen = wc_ecc_sig_size(key); + sigLen = (word32)wc_ecc_sig_size(key); digestLen = WC_SHA256_DIGEST_SIZE; sig = (byte*)XMALLOC(sigLen + digestLen, NULL, DYNAMIC_TYPE_ECC); if (sig == NULL) diff --git a/wolfcrypt/src/pkcs12.c b/wolfcrypt/src/pkcs12.c index b2d837caab6..612614d7487 100644 --- a/wolfcrypt/src/pkcs12.c +++ b/wolfcrypt/src/pkcs12.c @@ -152,7 +152,7 @@ static void freeSafe(AuthenticatedSafe* safe, void* heap) } /* free content info structs */ - for (i = safe->numCI; i > 0; i--) { + for (i = (int)safe->numCI; i > 0; i--) { ContentInfo* ci = safe->CI; safe->CI = ci->next; XFREE(ci, heap, DYNAMIC_TYPE_PKCS); @@ -207,13 +207,13 @@ void wc_PKCS12_free(WC_PKCS12* pkcs12) /* return 0 on success */ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, - word32* idx, int maxIdx) + word32* idx, word32 maxIdx) { AuthenticatedSafe* safe; word32 oid; word32 localIdx = *idx; int ret; - int size = 0; + word32 size = 0; byte tag; safe = (AuthenticatedSafe*)XMALLOC(sizeof(AuthenticatedSafe), pkcs12->heap, @@ -242,7 +242,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } - if (GetLength(input, &localIdx, &size, maxIdx) <= 0) { + if (GetLength(input, &localIdx, (int *)&size, maxIdx) <= 0) { freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } @@ -265,7 +265,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } - if (GetLength(input, &localIdx, &size, maxIdx) <= 0) { + if (GetLength(input, &localIdx, (int *)&size, maxIdx) <= 0) { freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } @@ -316,15 +316,15 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, * through the ContentInfo's and add them to our * AuthenticatedSafe struct */ { - int CISz; - ret = GetSequence(input, &localIdx, &CISz, size); + word32 CISz; + ret = GetSequence(input, &localIdx, (int *)&CISz, size); if (ret < 0) { freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } CISz += localIdx; - while ((int)localIdx < CISz) { - int curSz = 0; + while (localIdx < CISz) { + word32 curSz = 0; word32 curIdx; ContentInfo* ci = NULL; @@ -332,7 +332,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, printf("\t\tlooking for Content Info.... "); #endif - if ((ret = GetSequence(input, &localIdx, &curSz, size)) < 0) { + if ((ret = GetSequence(input, &localIdx, (int *)&curSz, size)) < 0) { freeSafe(safe, pkcs12->heap); return ret; } @@ -359,7 +359,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, return MEMORY_E; } - ci->type = oid; + ci->type = (int)oid; ci->dataSz = curSz - (localIdx-curIdx); ci->data = (byte*)input + localIdx; localIdx += ci->dataSz; @@ -450,7 +450,7 @@ static int GetSignData(WC_PKCS12* pkcs12, const byte* mem, word32* idx, XFREE(mac, pkcs12->heap, DYNAMIC_TYPE_PKCS); return ASN_PARSE_E; } - mac->digestSz = size; + mac->digestSz = (word32)size; mac->digest = (byte*)XMALLOC(mac->digestSz, pkcs12->heap, DYNAMIC_TYPE_DIGEST); if (mac->digest == NULL || mac->digestSz + curIdx > totalSz) { @@ -483,7 +483,7 @@ static int GetSignData(WC_PKCS12* pkcs12, const byte* mem, word32* idx, if ((ret = GetLength(mem, &curIdx, &size, totalSz)) < 0) { goto exit_gsd; } - mac->saltSz = size; + mac->saltSz = (word32)size; mac->salt = (byte*)XMALLOC(mac->saltSz, pkcs12->heap, DYNAMIC_TYPE_SALT); if (mac->salt == NULL || mac->saltSz + curIdx > totalSz) { ERROR_OUT(MEMORY_E, exit_gsd); @@ -575,7 +575,7 @@ static int wc_PKCS12_create_mac(WC_PKCS12* pkcs12, byte* data, word32 dataSz, unicodePasswd[idx++] = 0x00; /* get hash type used and resulting size of HMAC key */ - hashT = wc_OidGetHash(mac->oid); + hashT = wc_OidGetHash((int)mac->oid); if (hashT == WC_HASH_TYPE_NONE) { ForceZero(unicodePasswd, MAX_UNICODE_SZ); WOLFSSL_MSG("Unsupported hash used"); @@ -590,7 +590,7 @@ static int wc_PKCS12_create_mac(WC_PKCS12* pkcs12, byte* data, word32 dataSz, } /* idx contains size of unicodePasswd */ - ret = wc_PKCS12_PBKDF_ex(key, unicodePasswd, idx, mac->salt, mac->saltSz, + ret = wc_PKCS12_PBKDF_ex(key, unicodePasswd, idx, mac->salt, (int)mac->saltSz, mac->itt, kLen, (int)hashT, id, pkcs12->heap); ForceZero(unicodePasswd, MAX_UNICODE_SZ); if (ret < 0) { @@ -601,7 +601,7 @@ static int wc_PKCS12_create_mac(WC_PKCS12* pkcs12, byte* data, word32 dataSz, if ((ret = wc_HmacInit(&hmac, pkcs12->heap, INVALID_DEVID)) != 0) { return ret; } - ret = wc_HmacSetKey(&hmac, (int)hashT, key, kLen); + ret = wc_HmacSetKey(&hmac, (int)hashT, key, (word32)kLen); if (ret == 0) ret = wc_HmacUpdate(&hmac, data, dataSz); if (ret == 0) @@ -708,7 +708,7 @@ int wc_d2i_PKCS12(const byte* der, word32 derSz, WC_PKCS12* pkcs12) return ASN_PARSE_E; } - pkcs12->der = (byte*)XMALLOC(size, pkcs12->heap, DYNAMIC_TYPE_PKCS); + pkcs12->der = (byte*)XMALLOC((size_t)size, pkcs12->heap, DYNAMIC_TYPE_PKCS); if (pkcs12->der == NULL) return MEMORY_E; ret = wc_BerToDer(der, derSz, pkcs12->der, (word32*)&size); @@ -717,8 +717,8 @@ int wc_d2i_PKCS12(const byte* der, word32 derSz, WC_PKCS12* pkcs12) } der = pkcs12->der; - pkcs12->derSz = size; - totalSz = size; + pkcs12->derSz = (word32)size; + totalSz = (word32)size; idx = 0; if (GetSequence(der, &idx, &size, totalSz) < 0) { @@ -759,7 +759,7 @@ int wc_d2i_PKCS12(const byte* der, word32 derSz, WC_PKCS12* pkcs12) printf("\tSEQUENCE: AuthenticatedSafe size = %d\n", size); #endif - if ((ret = GetSafeContent(pkcs12, der, &idx, size + idx)) < 0) { + if ((ret = GetSafeContent(pkcs12, der, &idx, (word32)size + idx)) < 0) { WOLFSSL_MSG("GetSafeContent error"); return ret; } @@ -895,7 +895,7 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) word32 tmpIdx = 0; /* algo id */ - innerSz += SetAlgoID(mac->oid, ASNALGO, oidHashType, 0); + innerSz += SetAlgoID((int)mac->oid, ASNALGO, oidHashType, 0); /* Octet string holding digest */ innerSz += ASN_TAG_SZ; @@ -908,9 +908,9 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) outerSz += mac->saltSz; /* MAC iterations */ - ret = SetShortInt(ASNSHORT, &tmpIdx, mac->itt, MAX_SHORT_SZ); + ret = SetShortInt(ASNSHORT, &tmpIdx, (word32)mac->itt, MAX_SHORT_SZ); if (ret >= 0) { - outerSz += ret; + outerSz += (word32)ret; ret = 0; } else { @@ -935,7 +935,7 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) { word32 algoIdSz; - algoIdSz = SetAlgoID(mac->oid, &sdBuf[idx], oidHashType, 0); + algoIdSz = SetAlgoID((int)mac->oid, &sdBuf[idx], oidHashType, 0); if (algoIdSz == 0) { ret = ALGO_ID_E; } @@ -963,12 +963,12 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) int tmpSz; word32 tmpIdx = 0; byte ar[MAX_SHORT_SZ]; - tmpSz = SetShortInt(ar, &tmpIdx, mac->itt, MAX_SHORT_SZ); + tmpSz = SetShortInt(ar, &tmpIdx, (word32)mac->itt, MAX_SHORT_SZ); if (tmpSz < 0) { ret = tmpSz; } else { - XMEMCPY(&sdBuf[idx], ar, tmpSz); + XMEMCPY(&sdBuf[idx], ar, (size_t)tmpSz); } } totalSz += sdBufSz; @@ -998,7 +998,7 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) /* check if getting length only */ if (der == NULL && derSz != NULL) { - *derSz = totalSz; + *derSz = (int)totalSz; XFREE(sdBuf, pkcs12->heap, DYNAMIC_TYPE_PKCS); return LENGTH_ONLY_E; } @@ -1040,7 +1040,7 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) idx += seqSz; /* OID */ - idx += SetObjectId(sizeof(WC_PKCS12_DATA_OID), &buf[idx]); + idx += (word32)SetObjectId(sizeof(WC_PKCS12_DATA_OID), &buf[idx]); XMEMCPY(&buf[idx], WC_PKCS12_DATA_OID, sizeof(WC_PKCS12_DATA_OID)); idx += sizeof(WC_PKCS12_DATA_OID); @@ -1068,7 +1068,7 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) } /* Return size of der */ - ret = totalSz; + ret = (int)totalSz; } XFREE(sdBuf, pkcs12->heap, DYNAMIC_TYPE_PKCS); @@ -1206,7 +1206,7 @@ static int PKCS12_CheckConstructedZero(byte* data, word32 dataSz, word32* idx) ret = ASN_PARSE_E; } - *idx += size; + *idx += (word32)size; if (ret == 0 && GetShortInt(data, idx, &number, dataSz) < 0) { ret = ASN_PARSE_E; } @@ -1234,7 +1234,7 @@ static int PKCS12_CoalesceOctetStrings(WC_PKCS12* pkcs12, byte* data, int encryptedContentSz = 0; int originalEncSz = 0; int ret = 0; - int saveIdx; + word32 saveIdx; byte tag; saveIdx = *idx; @@ -1258,14 +1258,14 @@ static int PKCS12_CoalesceOctetStrings(WC_PKCS12* pkcs12, byte* data, } if (ret == 0) { if (mergedData == NULL) { - mergedData = (byte*)XMALLOC(encryptedContentSz, + mergedData = (byte*)XMALLOC((size_t)encryptedContentSz, pkcs12->heap, DYNAMIC_TYPE_PKCS); if (mergedData == NULL) { ret = MEMORY_E; } } mergedData = PKCS12_ConcatonateContent(pkcs12, mergedData, - &mergedSz, &data[*idx], encryptedContentSz); + &mergedSz, &data[*idx], (word32)encryptedContentSz); if (mergedData == NULL) { ret = MEMORY_E; } @@ -1273,7 +1273,7 @@ static int PKCS12_CoalesceOctetStrings(WC_PKCS12* pkcs12, byte* data, if (ret != 0) { break; } - *idx += encryptedContentSz; + *idx += (word32)encryptedContentSz; } *idx = saveIdx; @@ -1335,7 +1335,7 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, /* if there is sign data then verify the MAC */ if (pkcs12->signData != NULL ) { if ((ret = wc_PKCS12_verify(pkcs12, pkcs12->safe->data, - pkcs12->safe->dataSz, (byte*)psw, pswSz)) != 0) { + pkcs12->safe->dataSz, (byte*)psw, (word32)pswSz)) != 0) { WOLFSSL_MSG("PKCS12 Bad MAC on verify"); WOLFSSL_LEAVE("wc_PKCS12_parse verify ", ret); (void)ret; @@ -1397,7 +1397,7 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, #ifdef ASN_BER_TO_DER - curIdx = idx; + curIdx = (int)idx; /* If indefinite length format, ensure it is in the ASN format * the DecryptContent() expects */ if (pkcs12->indefinite && PKCS12_CheckConstructedZero(data, @@ -1409,18 +1409,18 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, goto exit_pk12par; } } - idx = curIdx; + idx = (word32)curIdx; #endif /* decrypted content overwrites input buffer */ - size = ci->dataSz - idx; - buf = (byte*)XMALLOC(size, pkcs12->heap, DYNAMIC_TYPE_PKCS); + size = (int)(ci->dataSz - idx); + buf = (byte*)XMALLOC((size_t)size, pkcs12->heap, DYNAMIC_TYPE_PKCS); if (buf == NULL) { ERROR_OUT(MEMORY_E, exit_pk12par); } - XMEMCPY(buf, data + idx, size); + XMEMCPY(buf, data + idx, (size_t)size); - if ((ret = DecryptContent(buf, size, psw, pswSz)) < 0) { + if ((ret = DecryptContent(buf, (word32)size, psw, pswSz)) < 0) { WOLFSSL_MSG("Decryption failed, algorithm not compiled in?"); goto exit_pk12par; } @@ -1467,14 +1467,14 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, if ((ret = GetSequence(data, &idx, &totalSz, ci->dataSz)) < 0) { goto exit_pk12par; } - totalSz += idx; + totalSz += (int)idx; while ((int)idx < totalSz) { int bagSz; if ((ret = GetSequence(data, &idx, &bagSz, ci->dataSz)) < 0) { goto exit_pk12par; } - bagSz += idx; + bagSz += (int)idx; if ((ret = GetObjectId(data, &idx, &oid, oidIgnoreType, ci->dataSz)) < 0) { @@ -1496,13 +1496,13 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, goto exit_pk12par; } if (*pkey == NULL) { - *pkey = (byte*)XMALLOC(size, pkcs12->heap, + *pkey = (byte*)XMALLOC((size_t)size, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); if (*pkey == NULL) { ERROR_OUT(MEMORY_E, exit_pk12par); } - XMEMCPY(*pkey, data + idx, size); - *pkeySz = ToTraditional_ex(*pkey, size, &algId); + XMEMCPY(*pkey, data + idx, (size_t)size); + *pkeySz = (word32)ToTraditional_ex(*pkey, (word32)size, &algId); } #ifdef WOLFSSL_DEBUG_PKCS12 @@ -1514,7 +1514,7 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, printf("\n"); } #endif - idx += size; + idx += (word32)size; break; case WC_PKCS12_ShroudedKeyBag: /* 668 */ @@ -1533,15 +1533,15 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, goto exit_pk12par; } - k = (byte*)XMALLOC(size, pkcs12->heap, + k = (byte*)XMALLOC((size_t)size, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); if (k == NULL) { ERROR_OUT(MEMORY_E, exit_pk12par); } - XMEMCPY(k, data + idx, size); + XMEMCPY(k, data + idx, (size_t)size); /* overwrites input, be warned */ - if ((ret = ToTraditionalEnc(k, size, psw, pswSz, + if ((ret = ToTraditionalEnc(k, (word32)size, psw, pswSz, &algId)) < 0) { XFREE(k, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); goto exit_pk12par; @@ -1549,13 +1549,13 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, if (ret < size) { /* shrink key buffer */ - byte* tmp = (byte*)XMALLOC(ret, pkcs12->heap, + byte* tmp = (byte*)XMALLOC((size_t)ret, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); if (tmp == NULL) { XFREE(k, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); ERROR_OUT(MEMORY_E, exit_pk12par); } - XMEMCPY(tmp, k, ret); + XMEMCPY(tmp, k, (size_t)ret); XFREE(k, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); k = tmp; } @@ -1563,12 +1563,12 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, if (*pkey == NULL) { *pkey = k; - *pkeySz = size; + *pkeySz = (word32)size; } else { /* only expecting one key */ XFREE(k, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); } - idx += size; + idx += (word32)size; #ifdef WOLFSSL_DEBUG_PKCS12 { @@ -1639,7 +1639,7 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, WOLFSSL_MSG("Unknown PKCS12 cert bag type"); } - if (size + idx > (word32)bagSz) { + if (size + (int)idx > bagSz) { ERROR_OUT(ASN_PARSE_E, exit_pk12par); } @@ -1651,14 +1651,14 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, } XMEMSET(node, 0, sizeof(WC_DerCertList)); - node->buffer = (byte*)XMALLOC(size, pkcs12->heap, + node->buffer = (byte*)XMALLOC((size_t)size, pkcs12->heap, DYNAMIC_TYPE_PKCS); if (node->buffer == NULL) { XFREE(node, pkcs12->heap, DYNAMIC_TYPE_PKCS); ERROR_OUT(MEMORY_E, exit_pk12par); } - XMEMCPY(node->buffer, data + idx, size); - node->bufferSz = size; + XMEMCPY(node->buffer, data + idx, (size_t)size); + node->bufferSz = (word32)size; /* put the new node into the list */ if (certList != NULL) { @@ -1672,7 +1672,7 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, } /* on to next */ - idx += size; + idx += (word32)size; } break; @@ -1694,7 +1694,7 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, /* Attribute, unknown bag or unsupported */ if ((int)idx < bagSz) { - idx = bagSz; /* skip for now */ + idx = (word32)bagSz; /* skip for now */ } } @@ -1826,7 +1826,7 @@ static int wc_PKCS12_shroud_key(WC_PKCS12* pkcs12, WC_RNG* rng, return ret; } - totalSz += ret; + totalSz += (word32)ret; /* out should not be null at this point but check before writing */ if (out == NULL) { @@ -1835,11 +1835,11 @@ static int wc_PKCS12_shroud_key(WC_PKCS12* pkcs12, WC_RNG* rng, /* rewind index and set tag and length */ tmpIdx -= MAX_LENGTH_SZ + 1; - sz = SetExplicit(0, ret, out + tmpIdx); + sz = (word32)SetExplicit(0, (word32)ret, out + tmpIdx); tmpIdx += sz; totalSz += sz; - XMEMMOVE(out + tmpIdx, out + MAX_LENGTH_SZ + 1, ret); + XMEMMOVE(out + tmpIdx, out + MAX_LENGTH_SZ + 1, (size_t)ret); - return totalSz; + return (int)totalSz; } @@ -1919,8 +1919,8 @@ static int wc_PKCS12_create_key_bag(WC_PKCS12* pkcs12, WC_RNG* rng, XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } - length = ret; - XMEMCPY(out + idx, tmp, length); + length = (word32)ret; + XMEMCPY(out + idx, tmp, (size_t)length); XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER); totalSz += length; @@ -1929,7 +1929,7 @@ static int wc_PKCS12_create_key_bag(WC_PKCS12* pkcs12, WC_RNG* rng, XMEMMOVE(out + tmpSz, out + MAX_SEQ_SZ, totalSz); (void)heap; - return totalSz + tmpSz; + return (int)(totalSz + tmpSz); } @@ -1956,16 +1956,16 @@ static int wc_PKCS12_create_cert_bag(WC_PKCS12* pkcs12, word32 tmpSz; if (out == NULL) { - *outSz = MAX_SEQ_SZ + WC_CERTBAG_OBJECT_ID + 1 + MAX_LENGTH_SZ + + *outSz = (word32)(MAX_SEQ_SZ + WC_CERTBAG_OBJECT_ID + 1 + MAX_LENGTH_SZ + MAX_SEQ_SZ + WC_CERTBAG1_OBJECT_ID + 1 + MAX_LENGTH_SZ + 1 + - MAX_LENGTH_SZ + certSz; + MAX_LENGTH_SZ + (int)certSz); return LENGTH_ONLY_E; } /* check buffer size able to handle max size */ - if (*outSz < (MAX_SEQ_SZ + WC_CERTBAG_OBJECT_ID + 1 + MAX_LENGTH_SZ + + if (*outSz < (word32)(MAX_SEQ_SZ + WC_CERTBAG_OBJECT_ID + 1 + MAX_LENGTH_SZ + MAX_SEQ_SZ + WC_CERTBAG1_OBJECT_ID + 1 + MAX_LENGTH_SZ + 1 + - MAX_LENGTH_SZ + certSz)) { + MAX_LENGTH_SZ + (int)certSz)) { return BUFFER_E; } @@ -2031,7 +2031,7 @@ static int wc_PKCS12_create_cert_bag(WC_PKCS12* pkcs12, (void)pkcs12; - return totalSz + tmpSz; + return (int)(totalSz + tmpSz); } @@ -2090,12 +2090,12 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, } /* calculate size */ - totalSz = SetObjectId(sizeof(WC_PKCS12_ENCRYPTED_OID), seq); + totalSz = (word32)SetObjectId(sizeof(WC_PKCS12_ENCRYPTED_OID), seq); totalSz += sizeof(WC_PKCS12_ENCRYPTED_OID); totalSz += ASN_TAG_SZ; - length = SetMyVersion(0, seq, 0); - tmpSz = SetObjectId(sizeof(WC_PKCS12_DATA_OID), seq); + length = (word32)SetMyVersion(0, seq, 0); + tmpSz = (word32)SetObjectId(sizeof(WC_PKCS12_DATA_OID), seq); tmpSz += sizeof(WC_PKCS12_DATA_OID); tmpSz += encSz; length += SetSequence(tmpSz, seq) + tmpSz; @@ -2113,7 +2113,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, idx = 0; idx += SetSequence(totalSz, out + idx); - idx += SetObjectId(sizeof(WC_PKCS12_ENCRYPTED_OID), out + idx); + idx += (word32)SetObjectId(sizeof(WC_PKCS12_ENCRYPTED_OID), out + idx); if (idx + sizeof(WC_PKCS12_ENCRYPTED_OID) > *outSz){ return BUFFER_E; } @@ -2128,7 +2128,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, idx += SetLength(outerSz, out + idx); idx += SetSequence(length, out + idx); - idx += SetMyVersion(0, out + idx, 0); + idx += (word32)SetMyVersion(0, out + idx, 0); tmp = (byte*)XMALLOC(encSz, heap, DYNAMIC_TYPE_TMP_BUFFER); if (tmp == NULL) { return MEMORY_E; @@ -2139,7 +2139,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } - encSz = ret; + encSz = (word32)ret; #ifdef WOLFSSL_DEBUG_PKCS12 { @@ -2153,7 +2153,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, #endif idx += SetSequence(WC_PKCS12_DATA_OBJ_SZ + encSz, out + idx); - idx += SetObjectId(sizeof(WC_PKCS12_DATA_OID), out + idx); + idx += (word32)SetObjectId(sizeof(WC_PKCS12_DATA_OID), out + idx); if (idx + sizeof(WC_PKCS12_DATA_OID) > *outSz){ WOLFSSL_MSG("Buffer not large enough for DATA OID"); XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -2170,7 +2170,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, XMEMCPY(out + idx, tmp, encSz); XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER); idx += encSz; - return idx; + return (int)idx; } /* DATA @@ -2181,7 +2181,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, * sequence containing all bags */ if (type == WC_PKCS12_DATA) { /* calculate size */ - totalSz = SetObjectId(sizeof(WC_PKCS12_DATA_OID), seq); + totalSz = (word32)SetObjectId(sizeof(WC_PKCS12_DATA_OID), seq); totalSz += sizeof(WC_PKCS12_DATA_OID); totalSz += ASN_TAG_SZ; @@ -2202,7 +2202,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, /* place data in output buffer */ idx = 0; idx += SetSequence(totalSz, out); - idx += SetObjectId(sizeof(WC_PKCS12_DATA_OID), out + idx); + idx += (word32)SetObjectId(sizeof(WC_PKCS12_DATA_OID), out + idx); if (idx + sizeof(WC_PKCS12_DATA_OID) > *outSz){ WOLFSSL_MSG("Buffer not large enough for DATA OID"); return BUFFER_E; @@ -2223,7 +2223,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, XMEMCPY(out + idx, content, contentSz); idx += contentSz; - return idx; + return (int)idx; } WOLFSSL_MSG("Unknown/Unsupported content type"); @@ -2273,7 +2273,7 @@ static byte* PKCS12_create_key_content(WC_PKCS12* pkcs12, int nidKey, /* get max size for key bag */ ret = wc_PKCS12_create_key_bag(pkcs12, rng, NULL, &keyBufSz, key, keySz, - algo, iter, pass, passSz); + algo, iter, pass, (int)passSz); if (ret != LENGTH_ONLY_E && ret < 0) { WOLFSSL_MSG("Error getting key bag size"); return NULL; @@ -2288,13 +2288,13 @@ static byte* PKCS12_create_key_content(WC_PKCS12* pkcs12, int nidKey, } ret = wc_PKCS12_create_key_bag(pkcs12, rng, keyBuf + MAX_SEQ_SZ, &keyBufSz, - key, keySz, algo, iter, pass, passSz); + key, keySz, algo, iter, pass, (int)passSz); if (ret < 0) { XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); WOLFSSL_MSG("Error creating key bag"); return NULL; } - keyBufSz = ret; + keyBufSz = (word32)ret; tmpSz = SetSequence(keyBufSz, keyBuf); XMEMMOVE(keyBuf + tmpSz, keyBuf + MAX_SEQ_SZ, keyBufSz); @@ -2310,7 +2310,7 @@ static byte* PKCS12_create_key_content(WC_PKCS12* pkcs12, int nidKey, } #endif ret = wc_PKCS12_encrypt_content(pkcs12, rng, NULL, keyCiSz, - NULL, keyBufSz, algo, pass, passSz, iter, WC_PKCS12_DATA); + NULL, keyBufSz, algo, pass, (int)passSz, iter, WC_PKCS12_DATA); if (ret != LENGTH_ONLY_E) { XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); WOLFSSL_MSG("Error getting key encrypt content size"); @@ -2323,14 +2323,14 @@ static byte* PKCS12_create_key_content(WC_PKCS12* pkcs12, int nidKey, } ret = wc_PKCS12_encrypt_content(pkcs12, rng, keyCi, keyCiSz, - keyBuf, keyBufSz, algo, pass, passSz, iter, WC_PKCS12_DATA); + keyBuf, keyBufSz, algo, pass, (int)passSz, iter, WC_PKCS12_DATA); XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); if (ret < 0 ) { XFREE(keyCi, heap, DYNAMIC_TYPE_TMP_BUFFER); WOLFSSL_MSG("Error creating key encrypt content"); return NULL; } - *keyCiSz = ret; + *keyCiSz = (word32)ret; #ifdef WOLFSSL_DEBUG_PKCS12 { @@ -2435,7 +2435,7 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, XFREE(certBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); return NULL; } - idx += ret; + idx += (word32)ret; if (ca != NULL) { WC_DerCertList* current = ca; @@ -2447,7 +2447,7 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, XFREE(certBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); return NULL; } - idx += ret; + idx += (word32)ret; current = current->next; } } @@ -2459,7 +2459,7 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, /* get buffer size needed for content info */ ret = wc_PKCS12_encrypt_content(pkcs12, rng, NULL, certCiSz, - NULL, certBufSz, algo, pass, passSz, iter, type); + NULL, certBufSz, algo, pass, (int)passSz, iter, type); if (ret != LENGTH_ONLY_E) { XFREE(certBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); WOLFSSL_LEAVE("wc_PKCS12_create()", ret); @@ -2472,14 +2472,14 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, } ret = wc_PKCS12_encrypt_content(pkcs12, rng, certCi, certCiSz, - certBuf, certBufSz, algo, pass, passSz, iter, type); + certBuf, certBufSz, algo, pass, (int)passSz, iter, type); XFREE(certBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); if (ret < 0) { WOLFSSL_LEAVE("wc_PKCS12_create()", ret); XFREE(certCi, heap, DYNAMIC_TYPE_TMP_BUFFER); return NULL; } - *certCiSz = ret; + *certCiSz = (word32)ret; #ifdef WOLFSSL_DEBUG_PKCS12 { @@ -2539,7 +2539,7 @@ static int PKCS12_create_safe(WC_PKCS12* pkcs12, byte* certCi, word32 certCiSz, XMEMCPY(innerData + idx + certCiSz, keyCi, keyCiSz); ret = wc_PKCS12_encrypt_content(pkcs12, rng, safeData, &safeDataSz, - innerData, innerDataSz, 0, pass, passSz, iter, WC_PKCS12_DATA); + innerData, innerDataSz, 0, pass, (int)passSz, iter, WC_PKCS12_DATA); XFREE(innerData, pkcs12->heap, DYNAMIC_TYPE_PKCS); if (ret < 0 ) { WOLFSSL_MSG("Error setting data type for safe contents"); @@ -2713,8 +2713,8 @@ WC_PKCS12* wc_PKCS12_create(char* pass, word32 passSz, char* name, return NULL; } - mac->digestSz = ret; - mac->digest = (byte*)XMALLOC(ret, heap, DYNAMIC_TYPE_PKCS); + mac->digestSz = (word32)ret; + mac->digest = (byte*)XMALLOC((size_t)ret, heap, DYNAMIC_TYPE_PKCS); if (mac->digest == NULL) { WOLFSSL_MSG("Error malloc'ing mac digest buffer"); wc_PKCS12_free(pkcs12); diff --git a/wolfcrypt/src/pwdbased.c b/wolfcrypt/src/pwdbased.c index 6b769f65c2c..e75f5df3319 100644 --- a/wolfcrypt/src/pwdbased.c +++ b/wolfcrypt/src/pwdbased.c @@ -53,7 +53,7 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, int keyLeft, ivLeft, i; int store; int keyOutput = 0; - int diestLen; + int digestLen; byte digest[WC_MAX_DIGEST_SIZE]; #ifdef WOLFSSL_SMALL_STACK wc_HashAlg* hash = NULL; @@ -75,7 +75,7 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, err = wc_HashGetDigestSize(hashT); if (err < 0) return err; - diestLen = err; + digestLen = err; /* initialize hash */ #ifdef WOLFSSL_SMALL_STACK @@ -96,20 +96,20 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, keyLeft = keyLen; ivLeft = ivLen; while (keyOutput < (keyLen + ivLen)) { - int digestLeft = diestLen; + int digestLeft = digestLen; /* D_(i - 1) */ if (keyOutput) { /* first time D_0 is empty */ - err = wc_HashUpdate(hash, hashT, digest, diestLen); + err = wc_HashUpdate(hash, hashT, digest, (word32)digestLen); if (err != 0) break; } /* data */ - err = wc_HashUpdate(hash, hashT, passwd, passwdLen); + err = wc_HashUpdate(hash, hashT, passwd, (word32)passwdLen); if (err != 0) break; /* salt */ if (salt) { - err = wc_HashUpdate(hash, hashT, salt, saltLen); + err = wc_HashUpdate(hash, hashT, salt, (word32)saltLen); if (err != 0) break; } @@ -118,7 +118,7 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, /* count */ for (i = 1; i < iterations; i++) { - err = wc_HashUpdate(hash, hashT, digest, diestLen); + err = wc_HashUpdate(hash, hashT, digest, (word32)digestLen); if (err != 0) break; err = wc_HashFinal(hash, hashT, digest); @@ -128,8 +128,8 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, if (err != 0) break; if (keyLeft) { - store = min(keyLeft, diestLen); - XMEMCPY(&key[keyLen - keyLeft], digest, store); + store = (int)min((word32)keyLeft, (word32)digestLen); + XMEMCPY(&key[keyLen - keyLeft], digest, (size_t)store); keyOutput += store; keyLeft -= store; @@ -137,10 +137,10 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, } if (ivLeft && digestLeft) { - store = min(ivLeft, digestLeft); + store = (int)min((word32)ivLeft, (word32)digestLeft); if (iv != NULL) XMEMCPY(&iv[ivLen - ivLeft], - &digest[diestLen - digestLeft], store); + &digest[digestLen - digestLeft], (size_t)store); keyOutput += store; ivLeft -= store; } @@ -214,13 +214,13 @@ int wc_PBKDF2_ex(byte* output, const byte* passwd, int pLen, const byte* salt, if (ret == 0) { word32 i = 1; /* use int hashType here, since HMAC FIPS uses the old unique value */ - ret = wc_HmacSetKey(hmac, hashType, passwd, pLen); + ret = wc_HmacSetKey(hmac, hashType, passwd, (word32)pLen); while (ret == 0 && kLen) { int currentLen; int j; - ret = wc_HmacUpdate(hmac, salt, sLen); + ret = wc_HmacUpdate(hmac, salt, (word32)sLen); if (ret != 0) break; @@ -241,17 +241,17 @@ int wc_PBKDF2_ex(byte* output, const byte* passwd, int pLen, const byte* salt, if (ret != 0) break; - currentLen = min(kLen, hLen); - XMEMCPY(output, buffer, currentLen); + currentLen = (int)min((word32)kLen, (word32)hLen); + XMEMCPY(output, buffer, (size_t)currentLen); for (j = 1; j < iterations; j++) { - ret = wc_HmacUpdate(hmac, buffer, hLen); + ret = wc_HmacUpdate(hmac, buffer, (word32)hLen); if (ret != 0) break; ret = wc_HmacFinal(hmac, buffer); if (ret != 0) break; - xorbuf(output, buffer, currentLen); + xorbuf(output, buffer, (word32)currentLen); } /* check ret from inside for loop */ @@ -359,7 +359,7 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, word32 u, v, dLen, pLen, iLen, sLen, totalLen; int dynamic = 0; int ret = 0; - int i; + word32 i; byte *D, *S, *P, *I; #ifdef WOLFSSL_SMALL_STACK byte staticBuffer[1]; /* force dynamic usage */ @@ -398,14 +398,14 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, return ret; if (ret == 0) return BAD_STATE_E; - u = ret; + u = (word32)ret; ret = wc_HashGetBlockSize(hashT); if (ret < 0) return ret; if (ret == 0) return BAD_STATE_E; - v = ret; + v = (word32)ret; #ifdef WOLFSSL_SMALL_STACK Ai = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -423,11 +423,11 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, XMEMSET(B, 0, WC_MAX_BLOCK_SIZE); dLen = v; - sLen = v * ((saltLen + v - 1) / v); + sLen = v * (((word32)saltLen + v - 1) / v); /* with passLen checked at the top of the function for >= 0 then passLen * must be 1 or greater here and is always 'true' */ - pLen = v * ((passLen + v - 1) / v); + pLen = v * (((word32)passLen + v - 1) / v); iLen = sLen + pLen; totalLen = dLen + sLen + pLen; @@ -451,10 +451,10 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, XMEMSET(D, id, dLen); - for (i = 0; i < (int)sLen; i++) - S[i] = salt[i % saltLen]; - for (i = 0; i < (int)pLen; i++) - P[i] = passwd[i % passLen]; + for (i = 0; i < sLen; i++) + S[i] = salt[i % (word32)saltLen]; + for (i = 0; i < pLen; i++) + P[i] = passwd[i % (word32)passLen]; #ifdef WOLFSSL_SMALL_STACK if (((B1 = (mp_int *)XMALLOC(sizeof(*B1), heap, DYNAMIC_TYPE_TMP_BUFFER)) @@ -475,8 +475,8 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, if (ret < 0) break; - for (i = 0; i < (int)v; i++) - B[i] = Ai[i % u]; + for (i = 0; i < v; i++) + B[i] = Ai[(word32)i % u]; if (mp_init(B1) != MP_OKAY) ret = MP_INIT_E; @@ -490,7 +490,7 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, break; } - for (i = 0; i < (int)iLen; i += v) { + for (i = 0; i < iLen; i += v) { int outSz; if (mp_init_multi(i1, res, NULL, NULL, NULL, NULL) != MP_OKAY) { @@ -511,8 +511,8 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, XMEMCPY(I + i, tmp + 1, v); } else if (outSz < (int)v) { - XMEMSET(I + i, 0, v - outSz); - ret = mp_to_unsigned_bin(res, I + i + v - outSz); + XMEMSET(I + i, 0, v - (word32)outSz); + ret = mp_to_unsigned_bin(res, I + i + v - (word32)outSz); } else ret = mp_to_unsigned_bin(res, I + i); @@ -528,10 +528,10 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, break; } - currentLen = min(kLen, (int)u); + currentLen = min((word32)kLen, u); XMEMCPY(output, Ai, currentLen); output += currentLen; - kLen -= currentLen; + kLen -= (int)currentLen; mp_clear(B1); } diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index 531302d4c16..fac7e3c1459 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -698,14 +698,17 @@ int wc_FreeRsaKey(RsaKey* key) /* Check the pair-wise consistency of the RSA key. */ static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng) { - const char* msg = "Everyone gets Friday off."; + static const char* msg = "Everyone gets Friday off."; byte* sig; byte* plain; int ret = 0; word32 msgLen, plainLen, sigLen; msgLen = (word32)XSTRLEN(msg); - sigLen = wc_RsaEncryptSize(key); + ret = wc_RsaEncryptSize(key); + if (ret < 0) + return ret; + sigLen = (word32)ret; WOLFSSL_MSG("Doing RSA consistency test"); @@ -1234,8 +1237,8 @@ static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, } XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen); pkcsBlock[idx--] = 0x01; /* PS and M separator */ - XMEMSET(pkcsBlock + idx - psLen + 1, 0, psLen); - idx -= psLen; + XMEMSET(pkcsBlock + idx - psLen + 1, 0, (size_t)psLen); + idx -= (word32)psLen; idx = idx - hLen + 1; XMEMCPY(pkcsBlock + idx, lHash, hLen); @@ -1405,7 +1408,7 @@ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, if ((int)pkcsBlockLen - hLen < saltLen + 2) { return PSS_SALTLEN_E; } - maskLen = pkcsBlockLen - 1 - hLen; + maskLen = (int)pkcsBlockLen - 1 - hLen; #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) @@ -1428,9 +1431,9 @@ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, } } #else - if (pkcsBlockLen < RSA_PSS_PAD_SZ + inputLen + saltLen) { + if ((int)pkcsBlockLen < RSA_PSS_PAD_SZ + (int)inputLen + saltLen) { #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) - msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap, + msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + (word32)saltLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (msg == NULL) { return MEMORY_E; @@ -1448,32 +1451,32 @@ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, m += inputLen; o = 0; if (saltLen > 0) { - ret = wc_RNG_GenerateBlock(rng, salt, saltLen); + ret = wc_RNG_GenerateBlock(rng, salt, (word32)saltLen); if (ret == 0) { - XMEMCPY(m, salt, saltLen); + XMEMCPY(m, salt, (size_t)saltLen); m += saltLen; } } #endif if (ret == 0) { /* Put Hash at end of pkcsBlock - 1 */ - ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, hLen); + ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, (word32)hLen); } if (ret == 0) { /* Set the last eight bits or trailer field to the octet 0xbc */ pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM; - ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, pkcsBlock, maskLen, heap); + ret = RsaMGF(mgf, pkcsBlock + maskLen, (word32)hLen, pkcsBlock, (word32)maskLen, heap); } if (ret == 0) { /* Clear the first high bit when "8emLen - emBits" is non-zero. where emBits = n modBits - 1 */ if (hiBits) - pkcsBlock[0] &= (1 << hiBits) - 1; + pkcsBlock[0] &= (byte)((1 << hiBits) - 1); m = pkcsBlock + maskLen - saltLen - 1; *(m++) ^= 0x01; - xorbuf(m, salt + o, saltLen); + xorbuf(m, salt + o, (word32)saltLen); } #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) @@ -1811,20 +1814,20 @@ static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen, } #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) - tmp = (byte*)XMALLOC(maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER); + tmp = (byte*)XMALLOC((size_t)maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (tmp == NULL) { return MEMORY_E; } #endif - if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, tmp, maskLen, + if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, (word32)hLen, tmp, (word32)maskLen, heap)) != 0) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); return ret; } - tmp[0] &= (1 << bits) - 1; - pkcsBlock[0] &= (1 << bits) - 1; + tmp[0] &= (byte)((1 << bits) - 1); + pkcsBlock[0] &= (byte)((1 << bits) - 1); #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { for (i = 0; i < maskLen - 1; i++) { @@ -1855,7 +1858,7 @@ static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen, return PSS_SALTLEN_E; } } - xorbuf(pkcsBlock + i, tmp + i, maskLen - i); + xorbuf(pkcsBlock + i, tmp + i, (word32)(maskLen - i)); #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); @@ -1981,7 +1984,7 @@ int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out, if (out != NULL) { *out = pkcsBlock; } - ret = pkcsBlockLen; + ret = (int)pkcsBlockLen; } break; #endif /* WC_RSA_NO_PADDING */ @@ -2990,7 +2993,7 @@ int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, case RSA_STATE_ENCRYPT_RES: case RSA_STATE_DECRYPT_RES: - ret = key->dataLen; + ret = (int)key->dataLen; break; default: @@ -3993,7 +3996,7 @@ int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, byte* sig, if (ret == 0) { if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) { - saltLen = inSz; + saltLen = (int)inSz; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) { @@ -4025,7 +4028,7 @@ int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, byte* sig, /* Sig = Salt | Exp Hash */ if (ret == 0) { - if (sigSz != inSz + saltLen) { + if (sigSz != inSz + (word32)saltLen) { ret = PSS_SALTLEN_E; } } @@ -4040,7 +4043,7 @@ int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, byte* sig, } } #else - if (ret == 0 && sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + saltLen)) { + if (ret == 0 && sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + (word32)saltLen)) { ret = BUFFER_E; } #endif @@ -4049,8 +4052,8 @@ int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, byte* sig, if (ret == 0) { XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ); XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz); - XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, saltLen); - ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + saltLen, + XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, (size_t)saltLen); + ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + (word32)saltLen, sigCheck, inSz); } if (ret == 0) { @@ -4114,7 +4117,7 @@ int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out, verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key); if (verify > 0) - ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, verify, + ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, (word32)verify, hash, saltLen, bits); if (ret == 0) ret = verify; @@ -4161,7 +4164,7 @@ int wc_RsaPSS_VerifyCheck(byte* in, word32 inLen, byte* out, word32 outLen, verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf, saltLen, key); if (verify > 0) - ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, verify, + ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, (word32)verify, hash, saltLen, bits); if (ret == 0) ret = verify; diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 0d9681504ef..3286216557c 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -1134,7 +1134,7 @@ static int InitSha256(wc_Sha256* sha256) /* get number of blocks */ /* 64-1 = 0x3F (~ Inverted = 0xFFFFFFC0) */ /* len (masked by 0xFFFFFFC0) returns block aligned length */ - blocksLen = len & ~(WC_SHA256_BLOCK_SIZE-1); + blocksLen = len & ~((word32)WC_SHA256_BLOCK_SIZE-1); if (blocksLen > 0) { /* Byte reversal and alignment handled in function if required */ XTRANSFORM_LEN(sha256, data, blocksLen); diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index 5172e60f031..c742ac1b71b 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -498,7 +498,7 @@ static int InitSha512_256(wc_Sha512* sha512) static int (*Transform_Sha512_p)(wc_Sha512* sha512) = _Transform_Sha512; static int (*Transform_Sha512_Len_p)(wc_Sha512* sha512, word32 len) = NULL; static int transform_check = 0; - static int intel_flags; + static word32 intel_flags; static int Transform_Sha512_is_vectorized = 0; static WC_INLINE int Transform_Sha512(wc_Sha512 *sha512) { @@ -866,7 +866,7 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le #if defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) if (Transform_Sha512_Len_p != NULL) { - word32 blocksLen = len & ~(WC_SHA512_BLOCK_SIZE-1); + word32 blocksLen = len & ~((word32)WC_SHA512_BLOCK_SIZE-1); if (blocksLen > 0) { sha512->data = data; diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index d07e2720976..7c7dd07684e 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -5031,7 +5031,7 @@ int sp_cond_swap_ct(sp_int* a, sp_int* b, int cnt, int swap) unsigned int i; int err = MP_OKAY; sp_int_digit mask = (sp_int_digit)0 - (sp_int_digit)swap; - DECL_SP_INT(t, cnt); + DECL_SP_INT(t, (size_t)cnt); /* Allocate temporary to hold masked xor of a and b. */ ALLOC_SP_INT(t, cnt, err, NULL); @@ -6251,7 +6251,7 @@ static void _sp_div_3(const sp_int* a, sp_int* r, sp_int_digit* rem) /* Sum digits of sum. */ t = (t >> SP_WORD_SIZE) + (t & SP_MASK); /* Get top digit after multipling by (2^SP_WORD_SIZE) / 3. */ - tt = (t * SP_DIV_3_CONST) >> SP_WORD_SIZE; + tt = (sp_int_digit)((t * SP_DIV_3_CONST) >> SP_WORD_SIZE); /* Subtract trial division. */ tr = (sp_int_digit)(t - (sp_int_word)tt * 3); #else @@ -6283,7 +6283,7 @@ static void _sp_div_3(const sp_int* a, sp_int* r, sp_int_digit* rem) /* Combine remainder from last operation with this word. */ t = ((sp_int_word)tr << SP_WORD_SIZE) | a->dp[i]; /* Get top digit after multipling by (2^SP_WORD_SIZE) / 3. */ - tt = (t * SP_DIV_3_CONST) >> SP_WORD_SIZE; + tt = (sp_int_digit)((t * SP_DIV_3_CONST) >> SP_WORD_SIZE); /* Subtract trial division. */ tr = (sp_int_digit)(t - (sp_int_word)tt * 3); #else @@ -6344,7 +6344,7 @@ static void _sp_div_10(const sp_int* a, sp_int* r, sp_int_digit* rem) /* Combine remainder from last operation with this word. */ t = ((sp_int_word)tr << SP_WORD_SIZE) | a->dp[i]; /* Get top digit after multipling by (2^SP_WORD_SIZE) / 10. */ - tt = (t * SP_DIV_10_CONST) >> SP_WORD_SIZE; + tt = (sp_int_digit)((t * SP_DIV_10_CONST) >> SP_WORD_SIZE); /* Subtract trial division. */ tr = (sp_int_digit)(t - (sp_int_word)tt * 10); #else @@ -6370,7 +6370,7 @@ static void _sp_div_10(const sp_int* a, sp_int* r, sp_int_digit* rem) /* Combine remainder from last operation with this word. */ t = ((sp_int_word)tr << SP_WORD_SIZE) | a->dp[i]; /* Get top digit after multipling by (2^SP_WORD_SIZE) / 10. */ - tt = (t * SP_DIV_10_CONST) >> SP_WORD_SIZE; + tt = (sp_int_digit)((t * SP_DIV_10_CONST) >> SP_WORD_SIZE); /* Subtract trial division. */ tr = (sp_int_digit)(t - (sp_int_word)tt * 10); #else @@ -6434,7 +6434,7 @@ static void _sp_div_small(const sp_int* a, sp_int_digit d, sp_int* r, /* Combine remainder from last operation with this word. */ t = ((sp_int_word)tr << SP_WORD_SIZE) | a->dp[i]; /* Get top digit after multipling. */ - tt = (t * m) >> SP_WORD_SIZE; + tt = (sp_int_digit)((t * m) >> SP_WORD_SIZE); /* Subtract trial division. */ tr = (sp_int_digit)t - (sp_int_digit)(tt * d); #else @@ -6461,7 +6461,7 @@ static void _sp_div_small(const sp_int* a, sp_int_digit d, sp_int* r, /* Combine remainder from last operation with this word. */ t = ((sp_int_word)tr << SP_WORD_SIZE) | a->dp[i]; /* Get top digit after multipling. */ - tt = (t * m) >> SP_WORD_SIZE; + tt = (sp_int_digit)((t * m) >> SP_WORD_SIZE); /* Subtract trial division. */ tr = (sp_int_digit)t - (sp_int_digit)(tt * d); #else @@ -8157,8 +8157,8 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) sp_int* tr = NULL; sp_int* trial = NULL; #ifdef WOLFSSL_SP_INT_NEGATIVE - int signA = MP_ZPOS; - int signD = MP_ZPOS; + word32 signA = MP_ZPOS; + word32 signD = MP_ZPOS; #endif /* WOLFSSL_SP_INT_NEGATIVE */ /* Intermediates will always be less than or equal to dividend. */ DECL_SP_INT_ARRAY(td, (a == NULL) ? 1 : a->used + 1, 4); @@ -11320,7 +11320,7 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) { int err = MP_OKAY; #ifdef WOLFSSL_SP_INT_NEGATIVE - int sign = MP_ZPOS; + word32 sign = MP_ZPOS; #endif if ((a == NULL) || (b == NULL) || (r == NULL)) { @@ -17321,7 +17321,7 @@ int sp_read_radix(sp_int* a, const char* in, int radix) { int err = MP_OKAY; #ifdef WOLFSSL_SP_INT_NEGATIVE - int sign = MP_ZPOS; + word32 sign = MP_ZPOS; #endif if ((a == NULL) || (in == NULL)) { @@ -18538,7 +18538,7 @@ int sp_lcm(const sp_int* a, const sp_int* b, sp_int* r) { int err = MP_OKAY; /* Determine maximum digit length numbers will reach. */ - int used = ((a == NULL) || (b == NULL)) ? 1 : + word32 used = ((a == NULL) || (b == NULL)) ? 1 : (a->used >= b->used ? a->used + 1: b->used + 1); DECL_SP_INT_ARRAY(t, used, 2); diff --git a/wolfcrypt/src/srp.c b/wolfcrypt/src/srp.c index 3e46b038c91..e32c35313f4 100644 --- a/wolfcrypt/src/srp.c +++ b/wolfcrypt/src/srp.c @@ -352,8 +352,8 @@ int wc_SrpSetParams(Srp* srp, const byte* N, word32 nSz, byte digest1[SRP_MAX_DIGEST_SIZE]; byte digest2[SRP_MAX_DIGEST_SIZE]; byte pad = 0; - int i, r; - int j = 0; + int r; + word32 i, j = 0; if (!srp || !N || !g || !salt || nSz < gSz) return BAD_FUNC_ARG; @@ -497,7 +497,7 @@ int wc_SrpGetVerifier(Srp* srp, byte* verifier, word32* size) if (!r) r = mp_exptmod(&srp->g, &srp->auth, &srp->N, v); if (!r) r = *size < (word32)mp_unsigned_bin_size(v) ? BUFFER_E : MP_OKAY; if (!r) r = mp_to_unsigned_bin(v, verifier); - if (!r) *size = mp_unsigned_bin_size(v); + if (!r) *size = (word32)mp_unsigned_bin_size(v); mp_clear(v); #ifdef WOLFSSL_SMALL_STACK @@ -579,7 +579,7 @@ int wc_SrpGetPublic(Srp* srp, byte* pub, word32* size) if (mp_iszero(&srp->auth) == MP_YES) return SRP_CALL_ORDER_E; - modulusSz = mp_unsigned_bin_size(&srp->N); + modulusSz = (word32)mp_unsigned_bin_size(&srp->N); if (*size < modulusSz) return BUFFER_E; @@ -640,7 +640,7 @@ int wc_SrpGetPublic(Srp* srp, byte* pub, word32* size) /* extract public key to buffer */ XMEMSET(pub, 0, modulusSz); if (!r) r = mp_to_unsigned_bin(pubkey, pub); - if (!r) *size = mp_unsigned_bin_size(pubkey); + if (!r) *size = (word32)mp_unsigned_bin_size(pubkey); mp_clear(pubkey); #ifdef WOLFSSL_SMALL_STACK @@ -667,10 +667,10 @@ static int wc_SrpSetKey(Srp* srp, byte* secret, word32 size) srp->keySz = 2 * digestSz; for (i = j = 0; j < srp->keySz; i++) { - counter[0] = (i >> 24) & 0xFF; - counter[1] = (i >> 16) & 0xFF; - counter[2] = (i >> 8) & 0xFF; - counter[3] = i & 0xFF; + counter[0] = (byte)(i >> 24); + counter[1] = (byte)(i >> 16); + counter[2] = (byte)(i >> 8); + counter[3] = (byte) i; r = SrpHashInit(&hash, srp->type, srp->heap); if (!r) r = SrpHashUpdate(&hash, secret, size); @@ -761,7 +761,7 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, goto out; digestSz = SrpHashSize(srp->type); - secretSz = mp_unsigned_bin_size(&srp->N); + secretSz = (word32)mp_unsigned_bin_size(&srp->N); if ((secretSz < clientPubKeySz) || (secretSz < serverPubKeySz)) { r = BAD_FUNC_ARG; @@ -879,7 +879,7 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, if ((r = mp_to_unsigned_bin(s, secret))) goto out; - if ((r = srp->keyGenFunc_cb(srp, secret, mp_unsigned_bin_size(s)))) + if ((r = srp->keyGenFunc_cb(srp, secret, (word32)mp_unsigned_bin_size(s)))) goto out; /* updating client proof = H( H(N) ^ H(g) | H(user) | salt | A | B | K) */ diff --git a/wolfssl/wolfcrypt/chacha.h b/wolfssl/wolfcrypt/chacha.h index 7cd73db4e36..848edf68169 100644 --- a/wolfssl/wolfcrypt/chacha.h +++ b/wolfssl/wolfcrypt/chacha.h @@ -61,7 +61,7 @@ Block counter is located at index 12. /* Size of ChaCha chunks */ #define CHACHA_CHUNK_WORDS 16 -#define CHACHA_CHUNK_BYTES (CHACHA_CHUNK_WORDS * sizeof(word32)) +#define CHACHA_CHUNK_BYTES (CHACHA_CHUNK_WORDS * (word32)sizeof(word32)) #ifdef WOLFSSL_X86_64_BUILD #if defined(USE_INTEL_SPEEDUP) && !defined(NO_CHACHA_ASM) From 11b06a2d93b1c598689afaca7ce4a14e67aa51a1 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 19 Apr 2023 15:53:48 -0500 Subject: [PATCH 184/391] fix for retval overwrite (warned by clang-analyzer-deadcode.DeadStores) in sha.c:wc_ShaFinal(); fix for benign clang-analyzer-deadcode.DeadStores in aes.c:wc_AesFeedbackEncrypt(); fix for cppcheck:selfAssignment in chacha.c:wc_Chacha_wordtobyte(). --- wolfcrypt/src/aes.c | 14 +------------- wolfcrypt/src/chacha.c | 2 ++ wolfcrypt/src/sha.c | 6 +++++- 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index b314b62dc4d..184838a6bf3 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -9914,9 +9914,6 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( Aes* aes, byte* out, const byte* in, word32 sz, byte mode) { byte* tmp = NULL; -#ifdef WOLFSSL_AES_CFB - byte* reg = NULL; -#endif int ret = 0; word32 processed; @@ -9924,12 +9921,6 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( return BAD_FUNC_ARG; } -#ifdef WOLFSSL_AES_CFB - if (aes->left && sz) { - reg = (byte*)aes->reg + AES_BLOCK_SIZE - aes->left; - } -#endif - /* consume any unused bytes left in aes->tmp */ processed = min(aes->left, sz); xorbufout(out, in, (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left, processed); @@ -9980,14 +9971,11 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); } #endif - #ifdef WOLFSSL_AES_CFB - reg = (byte*)aes->reg; - #endif xorbufout(out, in, tmp, sz); #ifdef WOLFSSL_AES_CFB if (mode == AES_CFB_MODE) { - XMEMCPY(reg, out, sz); + XMEMCPY(aes->reg, out, sz); } #endif aes->left -= sz; diff --git a/wolfcrypt/src/chacha.c b/wolfcrypt/src/chacha.c index c6a47726d16..91e6bf0e7d9 100644 --- a/wolfcrypt/src/chacha.c +++ b/wolfcrypt/src/chacha.c @@ -222,7 +222,9 @@ static WC_INLINE void wc_Chacha_wordtobyte(word32 x[CHACHA_CHUNK_WORDS], for (i = 0; i < CHACHA_CHUNK_WORDS; i++) { x[i] = PLUS(x[i], state[i]); +#ifdef BIG_ENDIAN_ORDER x[i] = LITTLE32(x[i]); +#endif } } diff --git a/wolfcrypt/src/sha.c b/wolfcrypt/src/sha.c index 71fae7c8e00..1ffd6bd182d 100644 --- a/wolfcrypt/src/sha.c +++ b/wolfcrypt/src/sha.c @@ -879,7 +879,11 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) XMEMCPY(hash, (byte *)&sha->digest[0], WC_SHA_DIGEST_SIZE); - ret = InitSha(sha); /* reset state */ + { + int initret = InitSha(sha); /* reset state */ + if (initret < 0) + ret = initret; + } return ret; } From bf2edfc63c36e48a377ef8a9782ca523c7fec48a Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 19 Apr 2023 17:25:33 -0500 Subject: [PATCH 185/391] revert change in wc_ShaFinal() capturing InitSha() retval, introduced in 510038022f, to (void)ed result. --- wolfcrypt/src/sha.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/wolfcrypt/src/sha.c b/wolfcrypt/src/sha.c index 1ffd6bd182d..549f61b012d 100644 --- a/wolfcrypt/src/sha.c +++ b/wolfcrypt/src/sha.c @@ -879,11 +879,7 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) XMEMCPY(hash, (byte *)&sha->digest[0], WC_SHA_DIGEST_SIZE); - { - int initret = InitSha(sha); /* reset state */ - if (initret < 0) - ret = initret; - } + (void)InitSha(sha); /* reset state */ return ret; } From ef79b1b6bcdb52d6d8296ce0077562817fca7cc6 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 19 Apr 2023 21:22:34 -0500 Subject: [PATCH 186/391] wolfcrypt/src/pkcs12.c: fix non-portable casts; wolfcrypt/src/sp_int.c: use unsigned int, not word32, for sign variables, to match type in header file. --- wolfcrypt/src/pkcs12.c | 30 +++++++++++++++--------------- wolfcrypt/src/sp_int.c | 10 +++++----- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/wolfcrypt/src/pkcs12.c b/wolfcrypt/src/pkcs12.c index 612614d7487..47a583467d4 100644 --- a/wolfcrypt/src/pkcs12.c +++ b/wolfcrypt/src/pkcs12.c @@ -213,7 +213,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, word32 oid; word32 localIdx = *idx; int ret; - word32 size = 0; + int size = 0; byte tag; safe = (AuthenticatedSafe*)XMALLOC(sizeof(AuthenticatedSafe), pkcs12->heap, @@ -242,7 +242,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } - if (GetLength(input, &localIdx, (int *)&size, maxIdx) <= 0) { + if (GetLength(input, &localIdx, &size, maxIdx) <= 0) { freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } @@ -265,7 +265,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } - if (GetLength(input, &localIdx, (int *)&size, maxIdx) <= 0) { + if (GetLength(input, &localIdx, &size, maxIdx) <= 0) { freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } @@ -273,18 +273,18 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, break; } - safe->dataSz = size; - safe->data = (byte*)XMALLOC(size, pkcs12->heap, DYNAMIC_TYPE_PKCS); + safe->dataSz = (word32)size; + safe->data = (byte*)XMALLOC((size_t)size, pkcs12->heap, DYNAMIC_TYPE_PKCS); if (safe->data == NULL) { freeSafe(safe, pkcs12->heap); return MEMORY_E; } - XMEMCPY(safe->data, input + localIdx, size); + XMEMCPY(safe->data, input + localIdx, (size_t)size); *idx = localIdx; localIdx = 0; input = safe->data; - size = safe->dataSz; + size = (int)safe->dataSz; #ifdef ASN_BER_TO_DER if (pkcs12->indefinite) { @@ -316,15 +316,15 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, * through the ContentInfo's and add them to our * AuthenticatedSafe struct */ { - word32 CISz; - ret = GetSequence(input, &localIdx, (int *)&CISz, size); + int CISz; + ret = GetSequence(input, &localIdx, &CISz, (word32)size); if (ret < 0) { freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } - CISz += localIdx; - while (localIdx < CISz) { - word32 curSz = 0; + CISz += (int)localIdx; + while (localIdx < (word32)CISz) { + int curSz = 0; word32 curIdx; ContentInfo* ci = NULL; @@ -332,7 +332,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, printf("\t\tlooking for Content Info.... "); #endif - if ((ret = GetSequence(input, &localIdx, (int *)&curSz, size)) < 0) { + if ((ret = GetSequence(input, &localIdx, &curSz, (word32)size)) < 0) { freeSafe(safe, pkcs12->heap); return ret; } @@ -345,7 +345,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, curIdx = localIdx; if ((ret = GetObjectId(input, &localIdx, &oid, oidIgnoreType, - size)) < 0) { + (word32)size)) < 0) { WOLFSSL_LEAVE("Get object id failed", ret); freeSafe(safe, pkcs12->heap); return ret; @@ -360,7 +360,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, } ci->type = (int)oid; - ci->dataSz = curSz - (localIdx-curIdx); + ci->dataSz = (word32)curSz - (localIdx-curIdx); ci->data = (byte*)input + localIdx; localIdx += ci->dataSz; diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 7c7dd07684e..95de1403e41 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -8157,8 +8157,8 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) sp_int* tr = NULL; sp_int* trial = NULL; #ifdef WOLFSSL_SP_INT_NEGATIVE - word32 signA = MP_ZPOS; - word32 signD = MP_ZPOS; + unsigned int signA = MP_ZPOS; + unsigned int signD = MP_ZPOS; #endif /* WOLFSSL_SP_INT_NEGATIVE */ /* Intermediates will always be less than or equal to dividend. */ DECL_SP_INT_ARRAY(td, (a == NULL) ? 1 : a->used + 1, 4); @@ -11320,7 +11320,7 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) { int err = MP_OKAY; #ifdef WOLFSSL_SP_INT_NEGATIVE - word32 sign = MP_ZPOS; + unsigned int sign = MP_ZPOS; #endif if ((a == NULL) || (b == NULL) || (r == NULL)) { @@ -17321,7 +17321,7 @@ int sp_read_radix(sp_int* a, const char* in, int radix) { int err = MP_OKAY; #ifdef WOLFSSL_SP_INT_NEGATIVE - word32 sign = MP_ZPOS; + unsigned int sign = MP_ZPOS; #endif if ((a == NULL) || (in == NULL)) { @@ -18538,7 +18538,7 @@ int sp_lcm(const sp_int* a, const sp_int* b, sp_int* r) { int err = MP_OKAY; /* Determine maximum digit length numbers will reach. */ - word32 used = ((a == NULL) || (b == NULL)) ? 1 : + unsigned int used = ((a == NULL) || (b == NULL)) ? 1 : (a->used >= b->used ? a->used + 1: b->used + 1); DECL_SP_INT_ARRAY(t, used, 2); From b69c880944fa36f5f998eb39e889da9ec874677e Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 7 Apr 2023 18:10:58 +0200 Subject: [PATCH 187/391] Zephyr port update - Add CONFIG_PTHREAD_IPC when using threads - Add logging config suggestions - test.c: fix undefined `ret` error - Increase stack size for samples - Ignore ASN_BEFORE_DATE_E in examples - wc_port.h: add missing posix thread includes - wc_port.h: move definitions to relevant section - benchmark.c: fix missing `arc` and `argv` errors - benchmark.c: fflush does not work on stdout in Zephyr - Update z_fs_open implementation to support flags --- wolfcrypt/benchmark/benchmark.c | 18 ++++++--- wolfcrypt/src/wc_port.c | 39 ++++++++++++++++++- wolfcrypt/test/test.c | 3 ++ wolfssl/wolfcrypt/wc_port.h | 20 ++++++---- zephyr/samples/wolfssl_benchmark/prj.conf | 3 ++ zephyr/samples/wolfssl_test/prj.conf | 3 ++ zephyr/samples/wolfssl_tls_sock/prj.conf | 5 +++ .../samples/wolfssl_tls_sock/src/tls_sock.c | 29 ++++++++++++-- zephyr/samples/wolfssl_tls_thread/prj.conf | 17 +++++--- .../wolfssl_tls_thread/src/tls_threaded.c | 33 ++++++++++++++-- 10 files changed, 141 insertions(+), 29 deletions(-) diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 1c9e1df21aa..42f12b73d2d 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -97,8 +97,11 @@ #endif #endif -#ifdef NO_STDIO_FILESYSTEM -#define fflush(...) do {} while (0) +#if defined(WOLFSSL_ZEPHYR) || defined(NO_STDIO_FILESYSTEM) || !defined(XFFLUSH) +/* fflush in Zephyr doesn't work on stdout and stderr. Use + * CONFIG_LOG_MODE_IMMEDIATE compilation option instead. */ +#undef XFFLUSH +#define XFFLUSH(...) do {} while (0) #endif /* Macro to disable benchmark */ @@ -359,7 +362,7 @@ printf("%s%s L%d error %d for \"%s\"\n", \ err_prefix, __FILE__, __LINE__, \ errno, #__VA_ARGS__); \ - fflush(stdout); \ + XFFLUSH(stdout); \ _exit(1); \ } \ } while(0) @@ -373,7 +376,7 @@ printf("%s%s L%d error %d for \"%s\"\n", \ err_prefix, __FILE__, __LINE__, \ _pthread_ret, #__VA_ARGS__); \ - fflush(stdout); \ + XFFLUSH(stdout); \ _exit(1); \ } \ } while(0) @@ -1948,7 +1951,7 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, } #ifndef WOLFSSL_SGX - fflush(stdout); + XFFLUSH(stdout); #endif /* Add to thread stats */ @@ -2081,7 +2084,7 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, } #ifndef WOLFSSL_SGX - fflush(stdout); + XFFLUSH(stdout); #endif /* Add to thread stats */ @@ -9125,6 +9128,9 @@ static int string_matches(const char* arg, const char* str) ESP_ERROR_CHECK(gptimer_enable(esp_gptimer)); ESP_ERROR_CHECK(gptimer_start(esp_gptimer)); #endif + #elif defined(MAIN_NO_ARGS) + int argc = 0; + char** argv = NULL; #endif diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index 8852e639ed8..f8629df2d84 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -915,13 +915,48 @@ void wc_ReadDirClose(ReadDirCtx* ctx) #endif /* !NO_FILESYSTEM */ #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_ZEPHYR) -XFILE z_fs_open(const char* filename, const char* perm) +XFILE z_fs_open(const char* filename, const char* mode) { XFILE file; + fs_mode_t flags = 0; + + if (mode == NULL) + return NULL; + + /* Parse mode */ + switch (*mode++) { + case 'r': + flags |= FS_O_READ; + break; + case 'w': + flags |= FS_O_WRITE|FS_O_CREATE; + break; + case 'a': + flags |= FS_O_APPEND|FS_O_CREATE; + break; + default: + return NULL; + } + + /* Ignore binary flag */ + if (*mode == 'b') + mode++; + if (*mode == '+') { + flags |= FS_O_READ; + /* Don't add write flag if already appending */ + if (!(flags & FS_O_APPEND)) + flags |= FS_O_RDWR; + } + /* Ignore binary flag */ + if (*mode == 'b') + mode++; + /* Incorrect mode string */ + if (*mode != '\0') + return NULL; file = (XFILE)XMALLOC(sizeof(*file), NULL, DYNAMIC_TYPE_FILE); if (file != NULL) { - if (fs_open(file, filename) != 0) { + if (fs_open(file, filename, flags) != 0) { XFREE(file, NULL, DYNAMIC_TYPE_FILE); file = NULL; } diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index dc58a1e488a..02ebbdca533 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -43777,6 +43777,9 @@ WOLFSSL_TEST_SUBROUTINE int mutex_test(void) { #ifdef WOLFSSL_PTHREADS wolfSSL_Mutex m; +#endif +#if defined(WOLFSSL_PTHREADS) || (!defined(WOLFSSL_NO_MALLOC) && \ + !defined(WOLFSSL_USER_MUTEX) && defined(WOLFSSL_STATIC_MEMORY)) int ret; #endif #if !defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_USER_MUTEX) diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index c1731a9319a..83d1d86157e 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -139,7 +139,12 @@ /* do nothing */ #elif defined(WOLFSSL_ZEPHYR) #ifndef SINGLE_THREADED + #ifndef CONFIG_PTHREAD_IPC + #error "Need CONFIG_PTHREAD_IPC for threading" + #endif #include + #include + #include #endif #elif defined(WOLFSSL_TELIT_M2MB) @@ -513,11 +518,14 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFILE struct fs_file_t* #define STAT struct fs_dirent - XFILE z_fs_open(const char* filename, const char* perm); + /* These are our wrappers for opening and closing files to + * make the API more POSIX like. */ + XFILE z_fs_open(const char* filename, const char* mode); int z_fs_close(XFILE file); #define XFOPEN z_fs_open #define XFCLOSE z_fs_close + #define XFFLUSH fs_sync #define XFSEEK fs_seek #define XFTELL fs_tell #define XFREWIND fs_rewind @@ -528,6 +536,10 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XBADFILE NULL #define XFGETS(b,s,f) -2 /* Not ported yet */ + #define XSTAT fs_stat + #define XS_ISREG(s) (s == FS_DIR_ENTRY_FILE) + #define SEPARATOR_CHAR ':' + #elif defined(WOLFSSL_TELIT_M2MB) #define XFILE INT32 #define XFOPEN(NAME, MODE) m2mb_fs_open((NAME), 0, (MODE)) @@ -655,12 +667,6 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XREAD read #define XCLOSE close - #elif defined(WOLFSSL_ZEPHYR) - #ifndef XSTAT - #define XSTAT fs_stat - #endif - #define XS_ISREG(s) (s == FS_DIR_ENTRY_FILE) - #define SEPARATOR_CHAR ':' #elif defined(WOLFSSL_TELIT_M2MB) #ifndef XSTAT #define XSTAT m2mb_fs_stat diff --git a/zephyr/samples/wolfssl_benchmark/prj.conf b/zephyr/samples/wolfssl_benchmark/prj.conf index 4dd23691ff3..2cf2714081c 100644 --- a/zephyr/samples/wolfssl_benchmark/prj.conf +++ b/zephyr/samples/wolfssl_benchmark/prj.conf @@ -3,6 +3,9 @@ CONFIG_MAIN_STACK_SIZE=32768 CONFIG_MINIMAL_LIBC_MALLOC_ARENA_SIZE=16384 +# Pthreads +CONFIG_PTHREAD_IPC=y + # Clock for time() CONFIG_POSIX_CLOCK=y diff --git a/zephyr/samples/wolfssl_test/prj.conf b/zephyr/samples/wolfssl_test/prj.conf index 624674315df..c2f997430dc 100644 --- a/zephyr/samples/wolfssl_test/prj.conf +++ b/zephyr/samples/wolfssl_test/prj.conf @@ -3,6 +3,9 @@ CONFIG_MAIN_STACK_SIZE=32768 CONFIG_MINIMAL_LIBC_MALLOC_ARENA_SIZE=16384 +# Pthreads +CONFIG_PTHREAD_IPC=y + # Clock for time() CONFIG_POSIX_CLOCK=y diff --git a/zephyr/samples/wolfssl_tls_sock/prj.conf b/zephyr/samples/wolfssl_tls_sock/prj.conf index f06afac26ce..9ca0cef9bd0 100644 --- a/zephyr/samples/wolfssl_tls_sock/prj.conf +++ b/zephyr/samples/wolfssl_tls_sock/prj.conf @@ -7,6 +7,9 @@ CONFIG_MINIMAL_LIBC_MALLOC_ARENA_SIZE=8192 # General config CONFIG_NEWLIB_LIBC=y +# Pthreads +CONFIG_PTHREAD_IPC=y + # Clock for time() CONFIG_POSIX_CLOCK=y @@ -43,6 +46,8 @@ CONFIG_NET_PKT_TX_COUNT=10 # Logging CONFIG_PRINTK=y #CONFIG_WOLFSSL_DEBUG=y +#CONFIG_LOG=y +#CONFIG_LOG_MODE_IMMEDIATE=y # TLS configuration CONFIG_WOLFSSL=y diff --git a/zephyr/samples/wolfssl_tls_sock/src/tls_sock.c b/zephyr/samples/wolfssl_tls_sock/src/tls_sock.c index 59cf271b58f..489591ec8cf 100644 --- a/zephyr/samples/wolfssl_tls_sock/src/tls_sock.c +++ b/zephyr/samples/wolfssl_tls_sock/src/tls_sock.c @@ -30,8 +30,8 @@ #endif #define BUFFER_SIZE 2048 -#define STATIC_MEM_SIZE (96*1024) -#define THREAD_STACK_SIZE (12*1024) +#define STATIC_MEM_SIZE (192*1024) +#define THREAD_STACK_SIZE (24*1024) #define MAX_SEND_SIZE 256 /* The stack to use in the server's thread. */ @@ -64,6 +64,15 @@ static const char msgHTTPIndex[] = "\n" "\n"; +/* DO NOT use this in production. You should implement a way + * to get the current date. */ +static int verifyIgnoreDateError(int preverify, WOLFSSL_X509_STORE_CTX* store) +{ + if (store->error == ASN_BEFORE_DATE_E) + return 1; /* override error */ + else + return preverify; +} /* Create a new wolfSSL client with a server CA certificate. */ static int wolfssl_client_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl) @@ -81,8 +90,11 @@ static int wolfssl_client_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl) if (ret == 0) { /* Load client certificates into WOLFSSL_CTX */ - if (wolfSSL_CTX_load_verify_buffer(client_ctx, ca_cert_der_2048, - sizeof_ca_cert_der_2048, WOLFSSL_FILETYPE_ASN1) != + if (wolfSSL_CTX_load_verify_buffer_ex(client_ctx, ca_cert_der_2048, + sizeof_ca_cert_der_2048, WOLFSSL_FILETYPE_ASN1, 0, + /* DO NOT use this in production. You should + * implement a way to get the current date. */ + WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY) != WOLFSSL_SUCCESS) { printf("ERROR: failed to load CA certificate\n"); ret = -1; @@ -97,6 +109,11 @@ static int wolfssl_client_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl) } } + if (ret == 0) + wolfSSL_set_verify(client_ssl, + WOLFSSL_VERIFY_PEER|WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT, + verifyIgnoreDateError); + if (ret == 0) { /* Return newly created wolfSSL context and object */ *ctx = client_ctx; @@ -170,6 +187,10 @@ static int wolfssl_server_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl) } } + if (ret == 0) + wolfSSL_set_verify(server_ssl, WOLFSSL_VERIFY_PEER, + verifyIgnoreDateError); + if (ret == 0) { /* Return newly created wolfSSL context and object */ *ctx = server_ctx; diff --git a/zephyr/samples/wolfssl_tls_thread/prj.conf b/zephyr/samples/wolfssl_tls_thread/prj.conf index 5cf80edf39d..e675b38a5eb 100644 --- a/zephyr/samples/wolfssl_tls_thread/prj.conf +++ b/zephyr/samples/wolfssl_tls_thread/prj.conf @@ -4,6 +4,9 @@ CONFIG_ENTROPY_GENERATOR=y CONFIG_INIT_STACKS=y CONFIG_MINIMAL_LIBC_MALLOC_ARENA_SIZE=65536 +# Pthreads +CONFIG_PTHREAD_IPC=y + # Clock for time() CONFIG_POSIX_CLOCK=y @@ -16,16 +19,18 @@ CONFIG_NET_SOCKETS=y CONFIG_DNS_RESOLVER=y # Logging -# Enable logging using RTT and UART CONFIG_PRINTK=y -CONFIG_CBPRINTF_LIBC_SUBSTS=y -CONFIG_CBPRINTF_FP_SUPPORT=y -CONFIG_CONSOLE=y CONFIG_LOG=y -CONFIG_LOG_BACKEND_UART=y -CONFIG_LOG_BUFFER_SIZE=15360 +CONFIG_LOG_MODE_IMMEDIATE=y #CONFIG_WOLFSSL_DEBUG=y +# Enable logging using RTT and UART +#CONFIG_CBPRINTF_LIBC_SUBSTS=y +#CONFIG_CBPRINTF_FP_SUPPORT=y +#CONFIG_CONSOLE=y +#CONFIG_LOG_BACKEND_UART=y +#CONFIG_LOG_BUFFER_SIZE=15360 + # TLS configuration CONFIG_WOLFSSL=y CONFIG_WOLFSSL_BUILTIN=y diff --git a/zephyr/samples/wolfssl_tls_thread/src/tls_threaded.c b/zephyr/samples/wolfssl_tls_thread/src/tls_threaded.c index ae148886071..57990ab99d1 100644 --- a/zephyr/samples/wolfssl_tls_thread/src/tls_threaded.c +++ b/zephyr/samples/wolfssl_tls_thread/src/tls_threaded.c @@ -43,8 +43,8 @@ #endif #define BUFFER_SIZE 2048 -#define STATIC_MEM_SIZE (96*1024) -#define THREAD_STACK_SIZE (13*1024) +#define STATIC_MEM_SIZE (192*1024) +#define THREAD_STACK_SIZE (24*1024) /* The stack to use in the server's thread. */ K_THREAD_STACK_DEFINE(server_stack, THREAD_STACK_SIZE); @@ -173,6 +173,16 @@ static int send_server(WOLFSSL* ssl, char* buff, int sz, void* ctx) return sz; } +/* DO NOT use this in production. You should implement a way + * to get the current date. */ +static int verifyIgnoreDateError(int preverify, WOLFSSL_X509_STORE_CTX* store) +{ + if (store->error == ASN_BEFORE_DATE_E) + return 1; /* override error */ + else + return preverify; +} + /* Create a new wolfSSL client with a server CA certificate. */ static int wolfssl_client_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl) { @@ -189,8 +199,11 @@ static int wolfssl_client_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl) if (ret == 0) { /* Load client certificates into WOLFSSL_CTX */ - if (wolfSSL_CTX_load_verify_buffer(client_ctx, ca_ecc_cert_der_256, - sizeof_ca_ecc_cert_der_256, WOLFSSL_FILETYPE_ASN1) != + if (wolfSSL_CTX_load_verify_buffer_ex(client_ctx, ca_ecc_cert_der_256, + sizeof_ca_ecc_cert_der_256, WOLFSSL_FILETYPE_ASN1, 0, + /* DO NOT use this in production. You should + * implement a way to get the current date. */ + WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY) != WOLFSSL_SUCCESS) { printf("ERROR: failed to load CA certificate\n"); ret = -1; @@ -218,6 +231,11 @@ static int wolfssl_client_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl) } } + if (ret == 0) + wolfSSL_set_verify(client_ssl, + WOLFSSL_VERIFY_PEER|WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT, + verifyIgnoreDateError); + #if defined(WOLFSSL_HAVE_PSA) && defined(HAVE_PK_CALLBACKS) if (ret == 0) { XMEMSET(&client_psa_ctx, 0, sizeof(client_psa_ctx)); @@ -378,6 +396,10 @@ static int wolfssl_server_new(WOLFSSL_CTX** ctx, WOLFSSL** ssl) } } + if (ret == 0) + wolfSSL_set_verify(server_ssl, WOLFSSL_VERIFY_PEER, + verifyIgnoreDateError); + #if defined(WOLFSSL_HAVE_PSA) && defined(HAVE_PK_CALLBACKS) if (ret == 0) { if (wolfSSL_set_psa_ctx(server_ssl, &server_psa_ctx) @@ -543,6 +565,7 @@ void server_thread(void* arg1, void* arg2, void* arg3) ret = wolfssl_send(server_ssl, msgHTTPIndex); printf("Server Return: %d\n", ret); + printf("Server Error: %d\n", wolfSSL_get_error(server_ssl, ret)); #ifdef WOLFSSL_STATIC_MEMORY printf("Server Memory Stats\n"); @@ -618,6 +641,8 @@ int main() ret = 0; printf("Client Return: %d\n", ret); + printf("Client Error: %d\n", wolfSSL_get_error(client_ssl, ret)); + join_thread(serverThread); From 7cf0b33cce241605f245f518f60d779302b39362 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 20 Apr 2023 12:42:51 +1000 Subject: [PATCH 188/391] SP C: fix handling of oversized arrays For mul and sqr implementation efficiency the fixed array has extra digits beyond what is needed. When encoding, only put in the useful digits. --- wolfcrypt/src/sp_c32.c | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/wolfcrypt/src/sp_c32.c b/wolfcrypt/src/sp_c32.c index c9821829dac..cd226658c9a 100644 --- a/wolfcrypt/src/sp_c32.c +++ b/wolfcrypt/src/sp_c32.c @@ -236,7 +236,7 @@ static void sp_2048_to_bin_72(sp_digit* r, byte* a) } j = 2055 / 8 - 1; a[j] = 0; - for (i=0; i<72 && j>=0; i++) { + for (i=0; i<71 && j>=0; i++) { b = 0; /* lint allow cast of mismatch sp_digit and int */ a[j--] |= (byte)(r[i] << s); /*lint !e9033*/ @@ -4130,8 +4130,8 @@ static int sp_2048_to_mp(const sp_digit* a, mp_int* r) err = mp_grow(r, (2048 + DIGIT_BIT - 1) / DIGIT_BIT); if (err == MP_OKAY) { /*lint !e774 case where err is always MP_OKAY*/ #if DIGIT_BIT == 29 - XMEMCPY(r->dp, a, sizeof(sp_digit) * 72); - r->used = 72; + XMEMCPY(r->dp, a, sizeof(sp_digit) * 71); + r->used = 71; mp_clamp(r); #elif DIGIT_BIT < 29 int i; @@ -4139,7 +4139,7 @@ static int sp_2048_to_mp(const sp_digit* a, mp_int* r) int s = 0; r->dp[0] = 0; - for (i = 0; i < 72; i++) { + for (i = 0; i < 71; i++) { r->dp[j] |= (mp_digit)(a[i] << s); r->dp[j] &= ((sp_digit)1 << DIGIT_BIT) - 1; s = DIGIT_BIT - s; @@ -4164,7 +4164,7 @@ static int sp_2048_to_mp(const sp_digit* a, mp_int* r) int s = 0; r->dp[0] = 0; - for (i = 0; i < 72; i++) { + for (i = 0; i < 71; i++) { r->dp[j] |= ((mp_digit)a[i]) << s; if (s + 29 >= DIGIT_BIT) { #if DIGIT_BIT != 32 && DIGIT_BIT != 64 @@ -8302,7 +8302,7 @@ static void sp_3072_to_bin_112(sp_digit* r, byte* a) } j = 3079 / 8 - 1; a[j] = 0; - for (i=0; i<112 && j>=0; i++) { + for (i=0; i<110 && j>=0; i++) { b = 0; /* lint allow cast of mismatch sp_digit and int */ a[j--] |= (byte)(r[i] << s); /*lint !e9033*/ @@ -11706,8 +11706,8 @@ static int sp_3072_to_mp(const sp_digit* a, mp_int* r) err = mp_grow(r, (3072 + DIGIT_BIT - 1) / DIGIT_BIT); if (err == MP_OKAY) { /*lint !e774 case where err is always MP_OKAY*/ #if DIGIT_BIT == 28 - XMEMCPY(r->dp, a, sizeof(sp_digit) * 112); - r->used = 112; + XMEMCPY(r->dp, a, sizeof(sp_digit) * 110); + r->used = 110; mp_clamp(r); #elif DIGIT_BIT < 28 int i; @@ -11715,7 +11715,7 @@ static int sp_3072_to_mp(const sp_digit* a, mp_int* r) int s = 0; r->dp[0] = 0; - for (i = 0; i < 112; i++) { + for (i = 0; i < 110; i++) { r->dp[j] |= (mp_digit)(a[i] << s); r->dp[j] &= ((sp_digit)1 << DIGIT_BIT) - 1; s = DIGIT_BIT - s; @@ -11740,7 +11740,7 @@ static int sp_3072_to_mp(const sp_digit* a, mp_int* r) int s = 0; r->dp[0] = 0; - for (i = 0; i < 112; i++) { + for (i = 0; i < 110; i++) { r->dp[j] |= ((mp_digit)a[i]) << s; if (s + 28 >= DIGIT_BIT) { #if DIGIT_BIT != 32 && DIGIT_BIT != 64 @@ -15818,7 +15818,7 @@ static void sp_4096_to_bin_162(sp_digit* r, byte* a) } j = 4103 / 8 - 1; a[j] = 0; - for (i=0; i<162 && j>=0; i++) { + for (i=0; i<158 && j>=0; i++) { b = 0; /* lint allow cast of mismatch sp_digit and int */ a[j--] |= (byte)(r[i] << s); /*lint !e9033*/ @@ -19231,8 +19231,8 @@ static int sp_4096_to_mp(const sp_digit* a, mp_int* r) err = mp_grow(r, (4096 + DIGIT_BIT - 1) / DIGIT_BIT); if (err == MP_OKAY) { /*lint !e774 case where err is always MP_OKAY*/ #if DIGIT_BIT == 26 - XMEMCPY(r->dp, a, sizeof(sp_digit) * 162); - r->used = 162; + XMEMCPY(r->dp, a, sizeof(sp_digit) * 158); + r->used = 158; mp_clamp(r); #elif DIGIT_BIT < 26 int i; @@ -19240,7 +19240,7 @@ static int sp_4096_to_mp(const sp_digit* a, mp_int* r) int s = 0; r->dp[0] = 0; - for (i = 0; i < 162; i++) { + for (i = 0; i < 158; i++) { r->dp[j] |= (mp_digit)(a[i] << s); r->dp[j] &= ((sp_digit)1 << DIGIT_BIT) - 1; s = DIGIT_BIT - s; @@ -19265,7 +19265,7 @@ static int sp_4096_to_mp(const sp_digit* a, mp_int* r) int s = 0; r->dp[0] = 0; - for (i = 0; i < 162; i++) { + for (i = 0; i < 158; i++) { r->dp[j] |= ((mp_digit)a[i]) << s; if (s + 26 >= DIGIT_BIT) { #if DIGIT_BIT != 32 && DIGIT_BIT != 64 @@ -44528,8 +44528,8 @@ static int sp_1024_to_mp(const sp_digit* a, mp_int* r) err = mp_grow(r, (1024 + DIGIT_BIT - 1) / DIGIT_BIT); if (err == MP_OKAY) { /*lint !e774 case where err is always MP_OKAY*/ #if DIGIT_BIT == 25 - XMEMCPY(r->dp, a, sizeof(sp_digit) * 42); - r->used = 42; + XMEMCPY(r->dp, a, sizeof(sp_digit) * 41); + r->used = 41; mp_clamp(r); #elif DIGIT_BIT < 25 int i; @@ -44537,7 +44537,7 @@ static int sp_1024_to_mp(const sp_digit* a, mp_int* r) int s = 0; r->dp[0] = 0; - for (i = 0; i < 42; i++) { + for (i = 0; i < 41; i++) { r->dp[j] |= (mp_digit)(a[i] << s); r->dp[j] &= ((sp_digit)1 << DIGIT_BIT) - 1; s = DIGIT_BIT - s; @@ -44562,7 +44562,7 @@ static int sp_1024_to_mp(const sp_digit* a, mp_int* r) int s = 0; r->dp[0] = 0; - for (i = 0; i < 42; i++) { + for (i = 0; i < 41; i++) { r->dp[j] |= ((mp_digit)a[i]) << s; if (s + 25 >= DIGIT_BIT) { #if DIGIT_BIT != 32 && DIGIT_BIT != 64 From 40ff84bb63d8ebb7a970d496ab2ede674eb48dfc Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 20 Apr 2023 15:13:54 +1000 Subject: [PATCH 189/391] SP int: ARM Thumb ASM don't use r7 on debug When DEBUG is defined, use versions of assembly code that don't use register r7. --- wolfcrypt/src/sp_int.c | 276 ++++++++++++++++++++++++++++++++--------- 1 file changed, 219 insertions(+), 57 deletions(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 95de1403e41..571e3a897a5 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -1490,8 +1490,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "uxth %[l], %[b] \n\t" \ "muls %[l], r6 \n\t" \ /* al * bh */ \ - "lsrs r7, %[b], #16 \n\t" \ - "muls r6, r7 \n\t" \ + "lsrs r5, %[b], #16 \n\t" \ + "muls r6, r5 \n\t" \ "lsrs %[h], r6, #16 \n\t" \ "lsls r6, r6, #16 \n\t" \ "adds %[l], %[l], r6 \n\t" \ @@ -1499,20 +1499,20 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "adcs %[h], %[o] \n\t" \ /* ah * bh */ \ "lsrs r6, %[a], #16 \n\t" \ - "muls r7, r6 \n\t" \ - "adds %[h], %[h], r7 \n\t" \ + "muls r5, r6 \n\t" \ + "adds %[h], %[h], r5 \n\t" \ /* ah * bl */ \ - "uxth r7, %[b] \n\t" \ - "muls r6, r7 \n\t" \ - "lsrs r7, r6, #16 \n\t" \ + "uxth r5, %[b] \n\t" \ + "muls r6, r5 \n\t" \ + "lsrs r5, r6, #16 \n\t" \ "lsls r6, r6, #16 \n\t" \ "adds %[l], %[l], r6 \n\t" \ - "adcs %[h], r7 \n\t" \ + "adcs %[h], r5 \n\t" \ : [l] "+l" (vl), [h] "+l" (vh), [o] "+l" (vo) \ : [a] "l" (va), [b] "l" (vb) \ - : "r6", "r7", "cc" \ + : "r5", "r6", "cc" \ ) -#ifndef WOLFSSL_SP_SMALL +#if !defined(WOLFSSL_SP_SMALL) && !defined(DEBUG) /* Multiply va by vb and add double size result into: vo | vh | vl */ #define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ __asm__ __volatile__ ( \ @@ -1625,7 +1625,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "l" (va), [b] "l" (vb) \ : "r4", "r5", "r6", "cc" \ ) -#ifndef WOLFSSL_SP_SMALL +#if !defined(WOLFSSL_SP_SMALL) && !defined(DEBUG) /* Multiply va by vb and add double size result twice into: vo | vh | vl */ #define SP_ASM_MUL_ADD2(vl, vh, vo, va, vb) \ __asm__ __volatile__ ( \ @@ -1728,6 +1728,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : "r5", "r6", "r8", "cc" \ ) #endif +#ifndef DEBUG /* Multiply va by vb and add double size result twice into: vo | vh | vl * Assumes first add will not overflow vh | vl */ @@ -1775,6 +1776,59 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "l" (va), [b] "l" (vb) \ : "r5", "r6", "r7", "cc" \ ) +#else +/* Multiply va by vb and add double size result twice into: vo | vh | vl + * Assumes first add will not overflow vh | vl + */ +#define SP_ASM_MUL_ADD2_NO(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "movs r8, %[a] \n\t" \ + /* al * bl */ \ + "uxth r5, %[a] \n\t" \ + "uxth r6, %[b] \n\t" \ + "muls r6, r5 \n\t" \ + "adds %[l], %[l], r6 \n\t" \ + "movs %[a], #0 \n\t" \ + "adcs %[h], %[a] \n\t" \ + "adds %[l], %[l], r6 \n\t" \ + "adcs %[h], %[a] \n\t" \ + /* al * bh */ \ + "lsrs r6, %[b], #16 \n\t" \ + "muls r5, r6 \n\t" \ + "lsrs r6, r5, #16 \n\t" \ + "lsls r5, r5, #16 \n\t" \ + "adds %[l], %[l], r5 \n\t" \ + "adcs %[h], r6 \n\t" \ + "adds %[l], %[l], r5 \n\t" \ + "adcs %[h], r6 \n\t" \ + "adcs %[o], %[a] \n\t" \ + /* ah * bh */ \ + "movs %[a], r8 \n\t" \ + "lsrs r5, %[a], #16 \n\t" \ + "lsrs r6, %[b], #16 \n\t" \ + "muls r6, r5 \n\t" \ + "movs %[a], #0 \n\t" \ + "adds %[h], %[h], r6 \n\t" \ + "adcs %[o], %[a] \n\t" \ + "adds %[h], %[h], r6 \n\t" \ + "adcs %[o], %[a] \n\t" \ + /* ah * bl */ \ + "uxth r6, %[b] \n\t" \ + "muls r5, r6 \n\t" \ + "lsrs r6, r5, #16 \n\t" \ + "lsls r5, r5, #16 \n\t" \ + "adds %[l], %[l], r5 \n\t" \ + "adcs %[h], r6 \n\t" \ + "adcs %[o], %[a] \n\t" \ + "adds %[l], %[l], r5 \n\t" \ + "adcs %[h], r6 \n\t" \ + "adcs %[o], %[a] \n\t" \ + "movs %[a], r8 \n\t" \ + : [l] "+l" (vl), [h] "+l" (vh), [o] "+l" (vo) \ + : [a] "l" (va), [b] "l" (vb) \ + : "r5", "r6", "r8", "cc" \ + ) +#endif /* Square va and store double size result in: vh | vl */ #define SP_ASM_SQR(vl, vh, va) \ __asm__ __volatile__ ( \ @@ -1825,25 +1879,25 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, /* Square va and add double size result into: vh | vl */ #define SP_ASM_SQR_ADD_NO(vl, vh, va) \ __asm__ __volatile__ ( \ - "lsrs r7, %[a], #16 \n\t" \ + "lsrs r6, %[a], #16 \n\t" \ "uxth r6, %[a] \n\t" \ /* al * al */ \ "muls r6, r6 \n\t" \ /* ah * ah */ \ - "muls r7, r7 \n\t" \ + "muls r6, r6 \n\t" \ "adds %[l], %[l], r6 \n\t" \ - "adcs %[h], r7 \n\t" \ - "lsrs r7, %[a], #16 \n\t" \ + "adcs %[h], r6 \n\t" \ + "lsrs r6, %[a], #16 \n\t" \ "uxth r6, %[a] \n\t" \ /* 2 * al * ah */ \ - "muls r6, r7 \n\t" \ - "lsrs r7, r6, #15 \n\t" \ + "muls r6, r6 \n\t" \ + "lsrs r6, r6, #15 \n\t" \ "lsls r6, r6, #17 \n\t" \ "adds %[l], %[l], r6 \n\t" \ - "adcs %[h], r7 \n\t" \ + "adcs %[h], r6 \n\t" \ : [l] "+l" (vl), [h] "+l" (vh) \ : [a] "l" (va) \ - : "r6", "r7", "cc" \ + : "r5", "r6", "cc" \ ) /* Add va into: vh | vl */ #define SP_ASM_ADDC(vl, vh, va) \ @@ -1919,8 +1973,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "uxth %[l], %[b] \n\t" \ "muls %[l], r6, %[l] \n\t" \ /* al * bh */ \ - "lsrs r7, %[b], #16 \n\t" \ - "muls r6, r7, r6 \n\t" \ + "lsrs r5, %[b], #16 \n\t" \ + "muls r6, r5, r6 \n\t" \ "lsrs %[h], r6, #16 \n\t" \ "lsls r6, r6, #16 \n\t" \ "adds %[l], %[l], r6 \n\t" \ @@ -1928,20 +1982,20 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "adcs %[h], %[h], %[o] \n\t" \ /* ah * bh */ \ "lsrs r6, %[a], #16 \n\t" \ - "muls r7, r6, r7 \n\t" \ - "adds %[h], %[h], r7 \n\t" \ + "muls r5, r6, r5 \n\t" \ + "adds %[h], %[h], r5 \n\t" \ /* ah * bl */ \ - "uxth r7, %[b] \n\t" \ - "muls r6, r7, r6 \n\t" \ - "lsrs r7, r6, #16 \n\t" \ + "uxth r5, %[b] \n\t" \ + "muls r6, r5, r6 \n\t" \ + "lsrs r5, r6, #16 \n\t" \ "lsls r6, r6, #16 \n\t" \ "adds %[l], %[l], r6 \n\t" \ - "adcs %[h], %[h], r7 \n\t" \ + "adcs %[h], %[h], r5 \n\t" \ : [l] "+l" (vl), [h] "+l" (vh), [o] "+l" (vo) \ : [a] "l" (va), [b] "l" (vb) \ - : "r6", "r7", "cc" \ + : "r5", "r6", "cc" \ ) -#ifndef WOLFSSL_SP_SMALL +#if !defined(WOLFSSL_SP_SMALL) && !defined(DEBUG) /* Multiply va by vb and add double size result into: vo | vh | vl */ #define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ __asm__ __volatile__ ( \ @@ -2053,7 +2107,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "l" (va), [b] "l" (vb) \ : "r4", "r5", "r6", "cc" \ ) -#ifndef WOLFSSL_SP_SMALL +#if !defined(WOLFSSL_SP_SMALL) && !defined(DEBUG) /* Multiply va by vb and add double size result twice into: vo | vh | vl */ #define SP_ASM_MUL_ADD2(vl, vh, vo, va, vb) \ __asm__ __volatile__ ( \ @@ -2156,6 +2210,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : "r5", "r6", "r8", "cc" \ ) #endif +#ifndef DEBUG /* Multiply va by vb and add double size result twice into: vo | vh | vl * Assumes first add will not overflow vh | vl */ @@ -2203,6 +2258,59 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "l" (va), [b] "l" (vb) \ : "r5", "r6", "r7", "cc" \ ) +#else +/* Multiply va by vb and add double size result twice into: vo | vh | vl + * Assumes first add will not overflow vh | vl + */ +#define SP_ASM_MUL_ADD2_NO(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "movs r8, %[a] \n\t" \ + /* al * bl */ \ + "uxth r5, %[a] \n\t" \ + "uxth r6, %[b] \n\t" \ + "muls r6, r5, r6 \n\t" \ + "adds %[l], %[l], r6 \n\t" \ + "movs %[a], #0 \n\t" \ + "adcs %[h], %[h], %[a] \n\t" \ + "adds %[l], %[l], r6 \n\t" \ + "adcs %[h], %[h], %[a] \n\t" \ + /* al * bh */ \ + "lsrs r6, %[b], #16 \n\t" \ + "muls r5, r6, r5 \n\t" \ + "lsrs r6, r5, #16 \n\t" \ + "lsls r5, r5, #16 \n\t" \ + "adds %[l], %[l], r5 \n\t" \ + "adcs %[h], %[h], r6 \n\t" \ + "adds %[l], %[l], r5 \n\t" \ + "adcs %[h], %[h], r6 \n\t" \ + "adcs %[o], %[o], %[a] \n\t" \ + /* ah * bh */ \ + "movs %[a], r8 \n\t" \ + "lsrs r5, %[a], #16 \n\t" \ + "lsrs r6, %[b], #16 \n\t" \ + "muls r6, r5, r6 \n\t" \ + "movs %[a], #0 \n\t" \ + "adds %[h], %[h], r6 \n\t" \ + "adcs %[o], %[o], %[a] \n\t" \ + "adds %[h], %[h], r6 \n\t" \ + "adcs %[o], %[o], %[a] \n\t" \ + /* ah * bl */ \ + "uxth r6, %[b] \n\t" \ + "muls r5, r6, r5 \n\t" \ + "lsrs r6, r5, #16 \n\t" \ + "lsls r5, r5, #16 \n\t" \ + "adds %[l], %[l], r5 \n\t" \ + "adcs %[h], %[h], r6 \n\t" \ + "adcs %[o], %[o], %[a] \n\t" \ + "adds %[l], %[l], r5 \n\t" \ + "adcs %[h], %[h], r6 \n\t" \ + "adcs %[o], %[o], %[a] \n\t" \ + "movs %[a], r8 \n\t" \ + : [l] "+l" (vl), [h] "+l" (vh), [o] "+l" (vo) \ + : [a] "l" (va), [b] "l" (vb) \ + : "r5", "r6", "r8", "cc" \ + ) +#endif /* Square va and store double size result in: vh | vl */ #define SP_ASM_SQR(vl, vh, va) \ __asm__ __volatile__ ( \ @@ -2253,25 +2361,25 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, /* Square va and add double size result into: vh | vl */ #define SP_ASM_SQR_ADD_NO(vl, vh, va) \ __asm__ __volatile__ ( \ - "lsrs r7, %[a], #16 \n\t" \ + "lsrs r5, %[a], #16 \n\t" \ "uxth r6, %[a] \n\t" \ /* al * al */ \ "muls r6, r6, r6 \n\t" \ /* ah * ah */ \ - "muls r7, r7, r7 \n\t" \ + "muls r5, r5, r5 \n\t" \ "adds %[l], %[l], r6 \n\t" \ - "adcs %[h], %[h], r7 \n\t" \ - "lsrs r7, %[a], #16 \n\t" \ + "adcs %[h], %[h], r5 \n\t" \ + "lsrs r5, %[a], #16 \n\t" \ "uxth r6, %[a] \n\t" \ /* 2 * al * ah */ \ - "muls r6, r7, r6 \n\t" \ - "lsrs r7, r6, #15 \n\t" \ + "muls r6, r5, r6 \n\t" \ + "lsrs r5, r6, #15 \n\t" \ "lsls r6, r6, #17 \n\t" \ "adds %[l], %[l], r6 \n\t" \ - "adcs %[h], %[h], r7 \n\t" \ + "adcs %[h], %[h], r5 \n\t" \ : [l] "+l" (vl), [h] "+l" (vh) \ : [a] "l" (va) \ - : "r6", "r7", "cc" \ + : "r5", "r6", "cc" \ ) /* Add va into: vh | vl */ #define SP_ASM_ADDC(vl, vh, va) \ @@ -2347,8 +2455,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "uxth %[l], %[b] \n\t" \ "mul %[l], r6 \n\t" \ /* al * bh */ \ - "lsr r7, %[b], #16 \n\t" \ - "mul r6, r7 \n\t" \ + "lsr r5, %[b], #16 \n\t" \ + "mul r6, r5 \n\t" \ "lsr %[h], r6, #16 \n\t" \ "lsl r6, r6, #16 \n\t" \ "add %[l], %[l], r6 \n\t" \ @@ -2356,20 +2464,20 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "adc %[h], %[o] \n\t" \ /* ah * bh */ \ "lsr r6, %[a], #16 \n\t" \ - "mul r7, r6 \n\t" \ - "add %[h], %[h], r7 \n\t" \ + "mul r5, r6 \n\t" \ + "add %[h], %[h], r5 \n\t" \ /* ah * bl */ \ - "uxth r7, %[b] \n\t" \ - "mul r6, r7 \n\t" \ - "lsr r7, r6, #16 \n\t" \ + "uxth r5, %[b] \n\t" \ + "mul r6, r5 \n\t" \ + "lsr r5, r6, #16 \n\t" \ "lsl r6, r6, #16 \n\t" \ "add %[l], %[l], r6 \n\t" \ - "adc %[h], r7 \n\t" \ + "adc %[h], r5 \n\t" \ : [l] "+l" (vl), [h] "+l" (vh), [o] "+l" (vo) \ : [a] "l" (va), [b] "l" (vb) \ - : "r6", "r7", "cc" \ + : "r5", "r6", "cc" \ ) -#ifndef WOLFSSL_SP_SMALL +#if !defined(WOLFSSL_SP_SMALL) && !defined(DEBUG) /* Multiply va by vb and add double size result into: vo | vh | vl */ #define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ __asm__ __volatile__ ( \ @@ -2482,7 +2590,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "l" (va), [b] "l" (vb) \ : "r4", "r5", "r6", "cc" \ ) -#ifndef WOLFSSL_SP_SMALL +#if !defined(WOLFSSL_SP_SMALL) && !defined(DEBUG) /* Multiply va by vb and add double size result twice into: vo | vh | vl */ #define SP_ASM_MUL_ADD2(vl, vh, vo, va, vb) \ __asm__ __volatile__ ( \ @@ -2585,6 +2693,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : "r5", "r6", "r8", "cc" \ ) #endif +#ifndef DEBUG /* Multiply va by vb and add double size result twice into: vo | vh | vl * Assumes first add will not overflow vh | vl */ @@ -2632,6 +2741,59 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "l" (va), [b] "l" (vb) \ : "r5", "r6", "r7", "cc" \ ) +#else +/* Multiply va by vb and add double size result twice into: vo | vh | vl + * Assumes first add will not overflow vh | vl + */ +#define SP_ASM_MUL_ADD2_NO(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mov r8, %[a] \n\t" \ + /* al * bl */ \ + "uxth r5, %[a] \n\t" \ + "uxth r6, %[b] \n\t" \ + "mul r6, r5 \n\t" \ + "add %[l], %[l], r6 \n\t" \ + "mov %[a], #0 \n\t" \ + "adc %[h], %[a] \n\t" \ + "add %[l], %[l], r6 \n\t" \ + "adc %[h], %[a] \n\t" \ + /* al * bh */ \ + "lsr r6, %[b], #16 \n\t" \ + "mul r5, r6 \n\t" \ + "lsr r6, r5, #16 \n\t" \ + "lsl r5, r5, #16 \n\t" \ + "add %[l], %[l], r5 \n\t" \ + "adc %[h], r6 \n\t" \ + "add %[l], %[l], r5 \n\t" \ + "adc %[h], r6 \n\t" \ + "adc %[o], %[a] \n\t" \ + /* ah * bh */ \ + "mov %[a], r8 \n\t" \ + "lsr r5, %[a], #16 \n\t" \ + "lsr r6, %[b], #16 \n\t" \ + "mul r6, r5 \n\t" \ + "mov %[a], #0 \n\t" \ + "add %[h], %[h], r6 \n\t" \ + "adc %[o], %[a] \n\t" \ + "add %[h], %[h], r6 \n\t" \ + "adc %[o], %[a] \n\t" \ + /* ah * bl */ \ + "uxth r6, %[b] \n\t" \ + "mul r5, r6 \n\t" \ + "lsr r6, r5, #16 \n\t" \ + "lsl r5, r5, #16 \n\t" \ + "add %[l], %[l], r5 \n\t" \ + "adc %[h], r6 \n\t" \ + "adc %[o], %[a] \n\t" \ + "add %[l], %[l], r5 \n\t" \ + "adc %[h], r6 \n\t" \ + "adc %[o], %[a] \n\t" \ + "mov %[a], r8 \n\t" \ + : [l] "+l" (vl), [h] "+l" (vh), [o] "+l" (vo) \ + : [a] "l" (va), [b] "l" (vb) \ + : "r5", "r6", "r8", "cc" \ + ) +#endif /* Square va and store double size result in: vh | vl */ #define SP_ASM_SQR(vl, vh, va) \ __asm__ __volatile__ ( \ @@ -2682,25 +2844,25 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, /* Square va and add double size result into: vh | vl */ #define SP_ASM_SQR_ADD_NO(vl, vh, va) \ __asm__ __volatile__ ( \ - "lsr r7, %[a], #16 \n\t" \ + "lsr r5, %[a], #16 \n\t" \ "uxth r6, %[a] \n\t" \ /* al * al */ \ "mul r6, r6 \n\t" \ /* ah * ah */ \ - "mul r7, r7 \n\t" \ + "mul r5, r5 \n\t" \ "add %[l], %[l], r6 \n\t" \ - "adc %[h], r7 \n\t" \ - "lsr r7, %[a], #16 \n\t" \ + "adc %[h], r5 \n\t" \ + "lsr r5, %[a], #16 \n\t" \ "uxth r6, %[a] \n\t" \ /* 2 * al * ah */ \ - "mul r6, r7 \n\t" \ - "lsr r7, r6, #15 \n\t" \ + "mul r6, r5 \n\t" \ + "lsr r5, r6, #15 \n\t" \ "lsl r6, r6, #17 \n\t" \ "add %[l], %[l], r6 \n\t" \ - "adc %[h], r7 \n\t" \ + "adc %[h], r5 \n\t" \ : [l] "+l" (vl), [h] "+l" (vh) \ : [a] "l" (va) \ - : "r6", "r7", "cc" \ + : "r5", "r6", "cc" \ ) /* Add va into: vh | vl */ #define SP_ASM_ADDC(vl, vh, va) \ From 2f6a604ebf2fe650cf7db20a3dc05e5794eaf446 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Thu, 9 Mar 2023 16:41:48 -0700 Subject: [PATCH 190/391] Adding NO_ASN_TIME_CHECK build option --- wolfcrypt/src/asn.c | 15 +++++++++------ wolfssl/wolfcrypt/settings.h | 5 +++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index dfd032aee04..72647aa2b1f 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -42,6 +42,8 @@ /* ASN Options: + * NO_ASN_TIME_CHECK: Disables ASN time checks (avoiding the ASN_BEFORE_DATE_E + * and ASN_AFTER_DATE_E errors). * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC or wishing to save space. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks. @@ -14153,7 +14155,7 @@ static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx) else cert->afterDateLen = (int)(cert->srcIdx - startIdx); -#ifndef NO_ASN_TIME +#ifndef NO_ASN_TIME_CHECK if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE && !XVALIDATE_DATE(date, format, dateType)) { if (dateType == BEFORE) { @@ -20028,7 +20030,7 @@ static int CheckDate(ASNGetData *dataASN, int dateType) ret = ASN_DATE_SZ_E; } -#ifndef NO_ASN_TIME +#ifndef NO_ASN_TIME_CHECK /* Check date is a valid string and BEFORE or AFTER now. */ if ((ret == 0) && (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) { @@ -33631,7 +33633,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, &single->status->thisDateFormat, size) < 0) return ASN_PARSE_E; -#ifndef NO_ASN_TIME +#ifndef NO_ASN_TIME_CHECK #ifndef WOLFSSL_NO_OCSP_DATE_CHECK if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE)) return ASN_BEFORE_DATE_E; @@ -33667,7 +33669,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, &single->status->nextDateFormat, size) < 0) return ASN_PARSE_E; -#ifndef NO_ASN_TIME +#ifndef NO_ASN_TIME_CHECK #ifndef WOLFSSL_NO_OCSP_DATE_CHECK if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER)) return ASN_AFTER_DATE_E; @@ -33764,7 +33766,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, /* Store the thisDate format - only one possible. */ cs->thisDateFormat = ASN_GENERALIZED_TIME; - #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK) + #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK) /* Check date is a valid string and BEFORE now. */ if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) { ret = ASN_BEFORE_DATE_E; @@ -33787,7 +33789,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) { /* Store the nextDate format - only one possible. */ cs->nextDateFormat = ASN_GENERALIZED_TIME; - #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK) + #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK) /* Check date is a valid string and AFTER now. */ if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) { ret = ASN_AFTER_DATE_E; @@ -36319,6 +36321,7 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, ret = PaseCRL_CheckSignature(dcrl, buff, cm); } + (void)verify; FREE_ASNGETDATA(dataASN, dcrl->heap); return ret; #endif /* WOLFSSL_ASN_TEMPLATE */ diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 0eb3b792b6c..c2b63f6433b 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2607,6 +2607,11 @@ extern void uITRON4_free(void *p) ; #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 #endif +/* Disable time checking if no timer */ +#if defined(NO_ASN_TIME) + #define NO_ASN_TIME_CHECK +#endif + /* both CURVE and ED small math should be enabled */ #ifdef CURVED25519_SMALL #define CURVE25519_SMALL From b8a3bf320f30074074f7e534a1860b9a6459ff3f Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Thu, 20 Apr 2023 14:36:22 -0600 Subject: [PATCH 191/391] Add more comments for alternatives and security risk --- wolfcrypt/src/asn.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 72647aa2b1f..8b0f62c9614 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -43,7 +43,11 @@ /* ASN Options: * NO_ASN_TIME_CHECK: Disables ASN time checks (avoiding the ASN_BEFORE_DATE_E - * and ASN_AFTER_DATE_E errors). + * and ASN_AFTER_DATE_E errors). Safer ways to avoid date errors would be to + * set the WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY flag when calling the _ex versions of + * cert loading functions or to define the WOLFSSL_NO_OCSP_DATE_CHECK macro to + * skip OCSP date errors. Defining NO_ASN_TIME_CHECK will skip ALL date checks + * and could pose a security risk. * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC or wishing to save space. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks. From 10f6586d8a2606d0d9ebdc53fe8f4fedaebd1bf2 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Thu, 20 Apr 2023 16:45:53 -0600 Subject: [PATCH 192/391] Remove duplicate line --- wolfcrypt/src/asn.c | 1 - 1 file changed, 1 deletion(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 8b0f62c9614..c758399c3d2 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -36325,7 +36325,6 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, ret = PaseCRL_CheckSignature(dcrl, buff, cm); } - (void)verify; FREE_ASNGETDATA(dataASN, dcrl->heap); return ret; #endif /* WOLFSSL_ASN_TEMPLATE */ From 5638b38c290c0d18fe4666b5e71d29564fe4f26d Mon Sep 17 00:00:00 2001 From: tmael Date: Fri, 21 Apr 2023 06:46:08 -0700 Subject: [PATCH 193/391] TLS v1.3: Support a stateful ticket and test HAVE_EXT_CACHE (#5960) * Add TLSv1.3 stateful support Fix internal and external session cache * session cache fixes * Refactor - implement wolfSSL_CTX_flush_sessions - use wolfSSL_CTX_flush_sessions to make test_wolfSSL_CTX_add_session_ext deterministic - add dtls to test_wolfSSL_CTX_add_session_ext - DoClientTicket_ex does not modify ssl object - only call session remove callback on: - timeout - session is being overwritten/removed from the cache * Session fixes - restore bogus ID on session duplicate - don't evict on overwrite - use memmove instead on memcpy as `ssl->session == session` is possible - ignore ClientSession parameter in AddSessionToCache on NO_SESSION_CACHE_REF - use sessionID when altSessionID not present * Session fixes - DoClientTicketFinalize: always copy in the ID as teh altSessionID - don't overwrite ex_data when overwriting cacheSession and cacheSession owns it * Callback wants to retain a copy * wolfSSL_GetSessionClient: ssl->ctx->get_sess_cb does not apply here * test_wolfSSL_CTX_add_session_ext gate expected results on WOLFSSL_DTLS_NO_HVR_ON_RESUME * TlsSessionIdIsValid: copy return can't be ignored * Silence unused parameter * test_wolfSSL_CTX_add_session_ext: handle async case * Gate wolfSSL_SSL_CTX_remove_session on NO_SESSION_CACHE * ssl.c: style fixes * Add twcase_get_sessionCb_cleanup to free external cache * Remove hard tab * Correct build error in wolfSSL_CTX_flush_sessions * Jenkins fixes: - altSessionID only available with WOLFSSL_TICKET_HAVE_ID - slim out psk_sess_free_cb_ctx * Stateful dtls case has 2 accesses. Stateless just one. * Add version numbering to hostap logs * Import internal.h for test_wolfSSL_SESSION_get_ex_new_index * wolfSSL_SetSession: don't check SslSessionCacheOff for session setting * wolfSSL_SetSession: fully set expired session for OpenSSL compatibility * wolfSSL_SetSession: check if setting same object * AddSession: always populate the session object to allow re-use * Add logging to wolfSSL_NewSession and wolfSSL_FreeSession * Always setup session object * Check if session has been setup before setting it * Print errors in async test * Make SetupSession available outside NO_SESSION_CACHE * Review comments * Fix ticBuf leak and TlsSessionIdIsValid logic * Fix unmatched curly brackets * TlsSessionIdIsValid: always need to check copy var * TlsResumptionIsValid: set resume to FALSE default * wolfSSL_SetSession: remove now variable since only used in one place * Move internalCacheLookupOff into HAVE_EXT_CACHE block --------- Co-authored-by: Juliusz Sosinowicz --- .github/workflows/async.yml | 6 + .github/workflows/hostap.yml | 11 +- .github/workflows/os-check.yml | 4 + src/dtls.c | 59 ++-- src/internal.c | 219 ++++++++++-- src/sniffer.c | 2 + src/ssl.c | 554 +++++++++++++++++------------- src/tls13.c | 72 ++-- tests/api.c | 601 ++++++++++++++++++++++++++++++++- wolfssl/internal.h | 41 ++- wolfssl/ssl.h | 7 +- 11 files changed, 1237 insertions(+), 339 deletions(-) diff --git a/.github/workflows/async.yml b/.github/workflows/async.yml index cb0407538ee..5696b2a306a 100644 --- a/.github/workflows/async.yml +++ b/.github/workflows/async.yml @@ -23,3 +23,9 @@ jobs: ./configure ${{ matrix.config }} make check + - name: Print errors + if: ${{ failure() }} + run: | + if [ -f test-suite.log ] ; then + cat test-suite.log + fi diff --git a/.github/workflows/hostap.yml b/.github/workflows/hostap.yml index 0fa9b5851e5..ffa270cb934 100644 --- a/.github/workflows/hostap.yml +++ b/.github/workflows/hostap.yml @@ -99,6 +99,15 @@ jobs: ${{ toJSON(matrix) }} EOF + - name: Print computed job run ID + run: | + SHA_SUM=$(sha256sum << 'END_OF_HEREDOC' | cut -d " " -f 1 + ${{ toJSON(github) }} + END_OF_HEREDOC + ) + echo "our_job_run_id=$SHA_SUM" >> $GITHUB_ENV + echo Our job run ID is $SHA_SUM + - name: Checkout wolfSSL uses: actions/checkout@v3 with: @@ -264,7 +273,7 @@ jobs: if: ${{ failure() && steps.testing.outcome == 'failure' }} uses: actions/upload-artifact@v3 with: - name: hostap-logs + name: hostap-logs-${{ env.our_job_run_id }} path: hostap/tests/hwsim/logs.zip retention-days: 5 diff --git a/.github/workflows/os-check.yml b/.github/workflows/os-check.yml index 218e439f3df..6a8c34fd08f 100644 --- a/.github/workflows/os-check.yml +++ b/.github/workflows/os-check.yml @@ -15,6 +15,10 @@ jobs: '--enable-all --enable-asn=template', '--enable-all --enable-asn=original', '--enable-harden-tls', + '--enable-tls13 --enable-session-ticket --enable-dtls --enable-dtls13 + --enable-opensslextra --enable-sessioncerts + CPPFLAGS=''-DWOLFSSL_DTLS_NO_HVR_ON_RESUME -DHAVE_EXT_CACHE + -DWOLFSSL_TICKET_HAVE_ID -DHAVE_EX_DATA -DSESSION_CACHE_DYNAMIC_MEM'' ', ] name: make check runs-on: ${{ matrix.os }} diff --git a/src/dtls.c b/src/dtls.c index 513b6991edb..11de01541bf 100644 --- a/src/dtls.c +++ b/src/dtls.c @@ -335,6 +335,8 @@ static int TlsTicketIsValid(const WOLFSSL* ssl, WolfSSL_ConstVector exts, int ret = 0; int tlsxFound; + *resume = FALSE; + ret = FindExtByType(&tlsxSessionTicket, TLSX_SESSION_TICKET, exts, &tlsxFound); if (ret != 0) @@ -359,42 +361,45 @@ static int TlsTicketIsValid(const WOLFSSL* ssl, WolfSSL_ConstVector exts, static int TlsSessionIdIsValid(const WOLFSSL* ssl, WolfSSL_ConstVector sessionID, int* resume) { - WOLFSSL_SESSION* sess; + const WOLFSSL_SESSION* sess; word32 sessRow; int ret; +#ifdef HAVE_EXT_CACHE + int copy; +#endif + *resume = FALSE; + if (ssl->options.sessionCacheOff) return 0; if (sessionID.size != ID_LEN) return 0; -#ifdef HAVE_EXT_CACHE - { - if (ssl->ctx->get_sess_cb != NULL) { - int unused; - sess = - ssl->ctx->get_sess_cb((WOLFSSL*)ssl, sessionID.elements, ID_LEN, - &unused); - if (sess != NULL) { +#ifdef HAVE_EXT_CACHE + if (ssl->ctx->get_sess_cb != NULL) { + WOLFSSL_SESSION* extSess = + ssl->ctx->get_sess_cb((WOLFSSL*)ssl, sessionID.elements, ID_LEN, + ©); + if (extSess != NULL) { #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - /* This logic is only for TLS <= 1.2 tickets. Don't accept - * TLS 1.3. */ - if (IsAtLeastTLSv1_3(sess->version)) - wolfSSL_FreeSession(ssl->ctx, sess); - else + defined(HAVE_SESSION_TICKET)) + /* This logic is only for TLS <= 1.2 tickets. Don't accept + * TLS 1.3. */ + if (!IsAtLeastTLSv1_3(extSess->version)) #endif - { - *resume = 1; - wolfSSL_FreeSession(ssl->ctx, sess); - return 0; - } - } + *resume = TRUE; + if (!copy) + wolfSSL_FreeSession(ssl->ctx, extSess); + if (*resume) + return 0; } - if (ssl->ctx->internalCacheLookupOff) - return 0; } + if (ssl->ctx->internalCacheLookupOff) + return 0; #endif - ret = TlsSessionCacheGetAndLock(sessionID.elements, &sess, &sessRow, 1); + + + ret = TlsSessionCacheGetAndRdLock(sessionID.elements, &sess, &sessRow, + ssl->options.side); if (ret == 0 && sess != NULL) { #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ defined(HAVE_SESSION_TICKET)) @@ -402,9 +407,7 @@ static int TlsSessionIdIsValid(const WOLFSSL* ssl, WolfSSL_ConstVector sessionID * TLS 1.3. */ if (!IsAtLeastTLSv1_3(sess->version)) #endif - { - *resume = 1; - } + *resume = TRUE; TlsSessionCacheUnlockRow(sessRow); } @@ -480,7 +483,7 @@ static void FindPskSuiteFromExt(const WOLFSSL* ssl, TLSX* extensions, /* Decode the identity. */ switch (current->decryptRet) { case PSK_DECRYPT_NONE: - ret = DoClientTicket_ex(ssl, current); + ret = DoClientTicket_ex(ssl, current, 0); break; case PSK_DECRYPT_OK: ret = WOLFSSL_TICKET_RET_OK; diff --git a/src/internal.c b/src/internal.c index 465496ba6ec..b7039beb74a 100644 --- a/src/internal.c +++ b/src/internal.c @@ -21307,8 +21307,9 @@ int SendFinished(WOLFSSL* ssl) return BUILD_MSG_ERROR; if (!ssl->options.resuming) { + SetupSession(ssl); #ifndef NO_SESSION_CACHE - AddSession(ssl); /* just try */ + AddSession(ssl); #endif if (ssl->options.side == WOLFSSL_SERVER_END) { #ifdef OPENSSL_EXTRA @@ -30637,6 +30638,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, *inOutIdx += length; if (length > 0) { ssl->timeout = lifetime; + SetupSession(ssl); #ifndef NO_SESSION_CACHE AddSession(ssl); #endif @@ -34848,18 +34850,35 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif /* WOLFSSL_SLT13 */ - void DoClientTicketFinalize(WOLFSSL* ssl, InternalTicket* it) + void DoClientTicketFinalize(WOLFSSL* ssl, InternalTicket* it, + const WOLFSSL_SESSION* sess) { #ifdef WOLFSSL_TICKET_HAVE_ID ssl->session->haveAltSessionID = 1; XMEMCPY(ssl->session->altSessionID, it->id, ID_LEN); - if (wolfSSL_GetSession(ssl, NULL, 1) != NULL) { - WOLFSSL_MSG("Found session matching the session id" - " found in the ticket"); +#endif + if (sess != NULL) { + byte bogusID[ID_LEN]; + byte bogusIDSz = ssl->session->sessionIDSz; + XMEMCPY(bogusID, ssl->session->sessionID, ID_LEN); + /* Failure here should not interupt the resumption. We already have + * all the cipher material we need in `it` */ + WOLFSSL_MSG("Copying in session from passed in arg"); + (void)wolfSSL_DupSession(sess, ssl->session, 1); + /* Restore the fake ID */ + XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN); + ssl->session->sessionIDSz= bogusIDSz; } +#ifdef WOLFSSL_TICKET_HAVE_ID else { - WOLFSSL_MSG("Can't find session matching the session id" - " found in the ticket"); + if (wolfSSL_GetSession(ssl, NULL, 1) != NULL) { + WOLFSSL_MSG("Found session matching the session id" + " found in the ticket"); + } + else { + WOLFSSL_MSG("Can't find session matching the session id" + " found in the ticket"); + } } #endif @@ -34922,18 +34941,139 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #if defined(WOLFSSL_TLS13) + static void PopulateInternalTicketFromSession(const WOLFSSL_SESSION* sess, + InternalTicket* it) + { +#ifdef WOLFSSL_32BIT_MILLI_TIME + word32 milliBornOn = sess->bornOn; +#else + sword64 milliBornOn = (sword64)sess->bornOn; +#endif + /* Convert to milliseconds */ + milliBornOn *= 1000; + it->pv = sess->version; + it->suite[0] = sess->cipherSuite0; + it->suite[1] = sess->cipherSuite; + XMEMCPY(it->msecret, sess->masterSecret, SECRET_LEN); +#ifdef WOLFSSL_32BIT_MILLI_TIME + c32toa(milliBornOn, it->timestamp); +#else + c32toa((word32)(milliBornOn >> 32), it->timestamp); + c32toa((word32)milliBornOn , it->timestamp + OPAQUE32_LEN); +#endif + it->haveEMS = (byte)sess->haveEMS; + c32toa(sess->ticketAdd, it->ageAdd); + c16toa(sess->namedGroup, it->namedGroup); + if (sess->ticketNonce.len <= MAX_TICKET_NONCE_STATIC_SZ) { + it->ticketNonceLen = sess->ticketNonce.len; + XMEMCPY(it->ticketNonce, sess->ticketNonce.data, + sess->ticketNonce.len); + } +#ifdef WOLFSSL_EARLY_DATA + c32toa(sess->maxEarlyDataSz, it->maxEarlyDataSz); +#endif +#ifdef WOLFSSL_TICKET_HAVE_ID + if (sess->haveAltSessionID) + XMEMCPY(it->id, sess->altSessionID, ID_LEN); + else + XMEMCPY(it->id, sess->sessionID, ID_LEN); +#endif + } + + + static const WOLFSSL_SESSION* GetSesionFromCacheOrExt(const WOLFSSL* ssl, + const byte* id, psk_sess_free_cb_ctx* freeCtx) + { + const WOLFSSL_SESSION* sess = NULL; + int ret; + XMEMSET(freeCtx, 0, sizeof(*freeCtx)); +#ifdef HAVE_EXT_CACHE + if (ssl->ctx->get_sess_cb != NULL) { + int copy = 0; + sess = ssl->ctx->get_sess_cb((WOLFSSL*)ssl, + id, ID_LEN, ©); + if (sess != NULL) { + freeCtx->extCache = 1; + /* If copy not set then free immediately */ + if (!copy) + freeCtx->freeSess = 1; + } + } +#endif + if (sess == NULL) { + ret = TlsSessionCacheGetAndRdLock(id, &sess, &freeCtx->row, + ssl->options.side); + if (ret != 0) + sess = NULL; + } + return sess; + } + + static void FreeSessionFromCacheOrExt(const WOLFSSL* ssl, + const WOLFSSL_SESSION* sess, psk_sess_free_cb_ctx* freeCtx) + { + (void)ssl; + (void)sess; +#ifdef HAVE_EXT_CACHE + if (freeCtx->extCache) { + if (freeCtx->freeSess) + /* In this case sess is not longer const and the external cache + * wants us to free it. */ + wolfSSL_FreeSession(ssl->ctx, (WOLFSSL_SESSION*)sess); + } + else +#endif + TlsSessionCacheUnlockRow(freeCtx->row); + } + /* Parse ticket sent by client, returns callback return value. Doesn't * modify ssl and stores the InternalTicket inside psk */ - int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk) + int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk, int retainSess) { - int decryptRet; int ret; + int decryptRet = WOLFSSL_TICKET_RET_REJECT; WOLFSSL_START(WC_FUNC_TICKET_DO); WOLFSSL_ENTER("DoClientTicket_ex"); - decryptRet = DoDecryptTicket(ssl, psk->identity, psk->identityLen, - &psk->it); + if (psk->identityLen == ID_LEN && IsAtLeastTLSv1_3(ssl->version)) { + /* This is a stateful ticket. We can be sure about this because + * stateless tickets are much longer. */ + const WOLFSSL_SESSION* sess = NULL; + sess = GetSesionFromCacheOrExt(ssl, psk->identity, + &psk->sess_free_cb_ctx); + if (sess != NULL) { + /* Session found in cache. Copy in relevant info to psk */ + byte* tmp; + WOLFSSL_MSG("Found session matching the session id" + " found in the ticket"); + /* Allocate and populate an InternalTicket */ + tmp = (byte*)XREALLOC(psk->identity, sizeof(InternalTicket), + ssl->heap, DYNAMIC_TYPE_TLSX); + if (tmp != NULL) { + XMEMSET(tmp, 0, sizeof(InternalTicket)); + psk->identity = tmp; + psk->identityLen = sizeof(InternalTicket); + psk->it = (InternalTicket*)tmp; + PopulateInternalTicketFromSession(sess, psk->it); + decryptRet = WOLFSSL_TICKET_RET_OK; + if (retainSess) { + psk->sess = sess; + psk->sess_free_cb = FreeSessionFromCacheOrExt; + } + } + if (psk->sess == NULL) { + FreeSessionFromCacheOrExt(ssl, sess, + &psk->sess_free_cb_ctx); + XMEMSET(&psk->sess_free_cb_ctx, 0, + sizeof(psk_sess_free_cb_ctx)); + } + } + } + else { + decryptRet = DoDecryptTicket(ssl, psk->identity, psk->identityLen, + &psk->it); + } switch (decryptRet) { case WOLFSSL_TICKET_RET_OK: psk->decryptRet = PSK_DECRYPT_OK; @@ -34945,11 +35085,11 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, psk->decryptRet = PSK_DECRYPT_FAIL; return decryptRet; } - #ifdef WOLFSSL_CHECK_MEM_ZERO +#ifdef WOLFSSL_CHECK_MEM_ZERO /* Internal ticket successfully decrypted. */ wc_MemZero_Add("Do Client Ticket internal", psk->it, sizeof(InternalTicket)); - #endif +#endif ret = DoClientTicketCheckVersion(ssl, psk->it); if (ret != 0) { @@ -34967,17 +35107,41 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* Parse ticket sent by client, returns callback return value */ int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len) { - int decryptRet; + int decryptRet = WOLFSSL_TICKET_RET_REJECT; int ret; - InternalTicket* it + InternalTicket* it; +#ifdef WOLFSSL_TLS13 + InternalTicket staticIt; + const WOLFSSL_SESSION* sess = NULL; + psk_sess_free_cb_ctx freeCtx; + + XMEMSET(&freeCtx, 0, sizeof(psk_sess_free_cb_ctx)); +#endif WOLFSSL_START(WC_FUNC_TICKET_DO); WOLFSSL_ENTER("DoClientTicket"); - decryptRet = DoDecryptTicket(ssl, input, len, &it); +#ifdef WOLFSSL_TLS13 + if (len == ID_LEN && IsAtLeastTLSv1_3(ssl->version)) { + /* This is a stateful ticket. We can be sure about this because + * stateless tickets are much longer. */ + sess = GetSesionFromCacheOrExt(ssl, input, &freeCtx); + if (sess != NULL) { + it = &staticIt; + XMEMSET(it, 0, sizeof(InternalTicket)); + PopulateInternalTicketFromSession(sess, it); + decryptRet = WOLFSSL_TICKET_RET_OK; + } + } + else +#endif + decryptRet = DoDecryptTicket(ssl, input, len, &it); + if (decryptRet != WOLFSSL_TICKET_RET_OK && - decryptRet != WOLFSSL_TICKET_RET_CREATE) - return decryptRet; + decryptRet != WOLFSSL_TICKET_RET_CREATE) { + it = NULL; + goto cleanup; + } #ifdef WOLFSSL_CHECK_MEM_ZERO /* Internal ticket successfully decrypted. */ wc_MemZero_Add("Do Client Ticket internal", it, sizeof(InternalTicket)); @@ -34985,20 +35149,23 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ret = DoClientTicketCheckVersion(ssl, it); if (ret != 0) { + decryptRet = ret; + goto cleanup; + } + + DoClientTicketFinalize(ssl, it, NULL); + +cleanup: + if (it != NULL) { ForceZero(it, sizeof(*it)); #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Check(it, sizeof(InternalTicket)); #endif - return ret; } - - DoClientTicketFinalize(ssl, it); - - ForceZero(it, sizeof(*it)); -#ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Check(it, sizeof(InternalTicket)); +#ifdef WOLFSSL_TLS13 + if (sess != NULL) + FreeSessionFromCacheOrExt(ssl, sess, &freeCtx); #endif - return decryptRet; } diff --git a/src/sniffer.c b/src/sniffer.c index 2b6e98889ca..cbd17ae94ec 100644 --- a/src/sniffer.c +++ b/src/sniffer.c @@ -3418,6 +3418,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, WOLFSSL_SESSION* sess = wolfSSL_GetSession(session->sslServer, NULL, 0); if (sess == NULL) { + SetupSession(session->sslServer); AddSession(session->sslServer); /* don't re add */ #ifdef WOLFSSL_SNIFFER_STATS INC_STAT(SnifferStats.sslResumptionInserts); @@ -4345,6 +4346,7 @@ static int ProcessFinished(const byte* input, int size, int* sslBytes, #ifndef NO_SESSION_CACHE WOLFSSL_SESSION* sess = wolfSSL_GetSession(session->sslServer, NULL, 0); if (sess == NULL) { + SetupSession(session->sslServer); AddSession(session->sslServer); /* don't re add */ #ifdef WOLFSSL_SNIFFER_STATS INC_STAT(SnifferStats.sslResumptionInserts); diff --git a/src/ssl.c b/src/ssl.c index f0f4f029726..d54015916de 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -6413,6 +6413,35 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) static WOLFSSL_GLOBAL int clisession_mutex_valid = 0; #endif /* !NO_CLIENT_CACHE */ + void EvictSessionFromCache(WOLFSSL_SESSION* session) + { +#ifdef HAVE_EX_DATA + int save_ownExData = session->ownExData; + session->ownExData = 1; /* Make sure ex_data access doesn't lead back + * into the cache. */ +#endif +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + if (session->rem_sess_cb != NULL) { + session->rem_sess_cb(NULL, session); + session->rem_sess_cb = NULL; + } +#endif + ForceZero(session->masterSecret, SECRET_LEN); + XMEMSET(session->sessionID, 0, ID_LEN); + session->sessionIDSz = 0; +#ifdef HAVE_SESSION_TICKET + if (session->ticketLenAlloc > 0) { + XFREE(session->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK); + session->ticket = session->staticTicket; + session->ticketLen = 0; + session->ticketLenAlloc = 0; + } +#endif +#ifdef HAVE_EX_DATA + session->ownExData = save_ownExData; +#endif + } + #endif /* !NO_SESSION_CACHE */ #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB) @@ -14523,6 +14552,47 @@ int wolfSSL_Cleanup(void) return ret; } +void SetupSession(WOLFSSL* ssl) +{ + WOLFSSL_SESSION* session = ssl->session; + + WOLFSSL_ENTER("SetupSession"); + + if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL && + !session->haveAltSessionID) { + /* Make sure the session ID is available when the user calls any + * get_session API */ + XMEMCPY(session->sessionID, ssl->arrays->sessionID, ID_LEN); + session->sessionIDSz = ssl->arrays->sessionIDSz; + } + session->side = (byte)ssl->options.side; + if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) + XMEMCPY(session->masterSecret, ssl->arrays->masterSecret, SECRET_LEN); + session->haveEMS = ssl->options.haveEMS; +#ifdef OPENSSL_EXTRA + /* If using compatibility layer then check for and copy over session context + * id. */ + if (ssl->sessionCtxSz > 0 && ssl->sessionCtxSz < ID_LEN) { + XMEMCPY(ssl->session->sessionCtx, ssl->sessionCtx, ssl->sessionCtxSz); + session->sessionCtxSz = ssl->sessionCtxSz; + } +#endif + session->timeout = ssl->timeout; + session->bornOn = LowResTimer(); +#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ + defined(HAVE_SESSION_TICKET)) + session->version = ssl->version; +#endif +#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) + session->cipherSuite0 = ssl->options.cipherSuite0; + session->cipherSuite = ssl->options.cipherSuite; +#endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + session->peerVerifyRet = (byte)ssl->peerVerifyRet; +#endif + session->isSetup = 1; +} #ifndef NO_SESSION_CACHE @@ -14534,6 +14604,44 @@ void wolfSSL_flush_sessions(WOLFSSL_CTX* ctx, long tm) (void)tm; } +void wolfSSL_CTX_flush_sessions(WOLFSSL_CTX* ctx, long tm) +{ + int i, j; + byte id[ID_LEN]; + + (void)ctx; + XMEMSET(id, 0, ID_LEN); + WOLFSSL_ENTER("wolfSSL_flush_sessions"); + for (i = 0; i < SESSION_ROWS; ++i) { + if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) { + WOLFSSL_MSG("Session cache mutex lock failed"); + return; + } + for (j = 0; j < SESSIONS_PER_ROW; j++) { +#ifdef SESSION_CACHE_DYNAMIC_MEM + WOLFSSL_SESSION* s = SessionCache[i].Sessions[j]; +#else + WOLFSSL_SESSION* s = &SessionCache[i].Sessions[j]; +#endif + if ( +#ifdef SESSION_CACHE_DYNAMIC_MEM + s != NULL && +#endif + XMEMCMP(s->sessionID, id, ID_LEN) != 0 && + s->bornOn + s->timeout < (word32)tm + ) + { + EvictSessionFromCache(s); +#ifdef SESSION_CACHE_DYNAMIC_MEM + XFREE(s, s->heap, DYNAMIC_TYPE_SESSION); + SessionCache[i].Sessions[j] = NULL; +#endif + } + } + SESSION_ROW_UNLOCK(&SessionCache[i]); + } +} + /* set ssl session timeout in seconds */ WOLFSSL_ABI @@ -14636,23 +14744,8 @@ WOLFSSL_SESSION* wolfSSL_GetSessionClient(WOLFSSL* ssl, const byte* id, int len) len = min(SERVER_ID_LEN, (word32)len); -#ifdef HAVE_EXT_CACHE - if (ssl->ctx->get_sess_cb != NULL) { - int copy = 0; - WOLFSSL_MSG("Calling external session cache"); - ret = ssl->ctx->get_sess_cb(ssl, (byte*)id, len, ©); - if (ret != NULL) { - WOLFSSL_MSG("Session found in external cache"); - return ret; - } - WOLFSSL_MSG("Session not found in external cache"); - } - - if (ssl->ctx->internalCacheLookupOff) { - WOLFSSL_MSG("Internal cache turned off"); - return NULL; - } -#endif + /* Do not access ssl->ctx->get_sess_cb from here. It is using a different + * set of ID's */ row = HashObject(id, len, &error) % CLIENT_SESSION_ROWS; if (error != 0) { @@ -14725,9 +14818,6 @@ static int SslSessionCacheOff(const WOLFSSL* ssl, const WOLFSSL_SESSION* session return ssl->options.sessionCacheOff #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_FORCE_CACHE_ON_TICKET) && session->ticketLen == 0 - #endif - #ifdef OPENSSL_EXTRA - && ssl->options.side != WOLFSSL_CLIENT_END #endif ; } @@ -14776,11 +14866,13 @@ void TlsSessionCacheUnlockRow(word32 row) SESSION_ROW_UNLOCK(sessRow); } -int TlsSessionCacheGetAndLock(const byte *id, WOLFSSL_SESSION **sess, - word32 *lockedRow, byte readOnly) +/* Don't use this function directly. Use TlsSessionCacheGetAndRdLock and + * TlsSessionCacheGetAndWrLock to fully utilize compiler const support. */ +static int TlsSessionCacheGetAndLock(const byte *id, + const WOLFSSL_SESSION **sess, word32 *lockedRow, byte readOnly, byte side) { SessionRow *sessRow; - WOLFSSL_SESSION *s; + const WOLFSSL_SESSION *s; word32 row; int count; int error; @@ -14810,7 +14902,7 @@ int TlsSessionCacheGetAndLock(const byte *id, WOLFSSL_SESSION **sess, #else s = &sessRow->Sessions[idx]; #endif - if (s && XMEMCMP(s->sessionID, id, ID_LEN) == 0) { + if (s && XMEMCMP(s->sessionID, id, ID_LEN) == 0 && s->side == side) { *sess = s; break; } @@ -14826,9 +14918,22 @@ int TlsSessionCacheGetAndLock(const byte *id, WOLFSSL_SESSION **sess, return 0; } +int TlsSessionCacheGetAndRdLock(const byte *id, const WOLFSSL_SESSION **sess, + word32 *lockedRow, byte side) +{ + return TlsSessionCacheGetAndLock(id, sess, lockedRow, 1, side); +} + +int TlsSessionCacheGetAndWrLock(const byte *id, WOLFSSL_SESSION **sess, + word32 *lockedRow, byte side) +{ + return TlsSessionCacheGetAndLock(id, (const WOLFSSL_SESSION**)sess, + lockedRow, 0, side); +} + int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) { - WOLFSSL_SESSION* sess = NULL; + const WOLFSSL_SESSION* sess = NULL; const byte* id = NULL; word32 row; int error = 0; @@ -14887,23 +14992,25 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) #ifdef HAVE_EXT_CACHE if (ssl->ctx->get_sess_cb != NULL) { int copy = 0; + WOLFSSL_SESSION* extSess; /* Attempt to retrieve the session from the external cache. */ WOLFSSL_MSG("Calling external session cache"); - sess = ssl->ctx->get_sess_cb(ssl, (byte*)id, ID_LEN, ©); - if ((sess != NULL) + extSess = ssl->ctx->get_sess_cb(ssl, (byte*)id, ID_LEN, ©); + if ((extSess != NULL) #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) && (IsAtLeastTLSv1_3(ssl->version) == - IsAtLeastTLSv1_3(sess->version)) + IsAtLeastTLSv1_3(extSess->version)) #endif ) { WOLFSSL_MSG("Session found in external cache"); - error = wolfSSL_DupSession(sess, output, 0); + error = wolfSSL_DupSession(extSess, output, 0); #ifdef HAVE_EX_DATA - output->ownExData = 1; + extSess->ownExData = 1; + output->ownExData = 0; #endif /* If copy not set then free immediately */ if (!copy) - wolfSSL_FreeSession(ssl->ctx, sess); + wolfSSL_FreeSession(ssl->ctx, extSess); /* We want to restore the bogus ID for TLS compatibility */ if (ssl->session->haveAltSessionID && output == ssl->session) { @@ -14974,7 +15081,7 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) /* init to avoid clang static analyzer false positive */ row = 0; - error = TlsSessionCacheGetAndLock(id, &sess, &row, 1); + error = TlsSessionCacheGetAndRdLock(id, &sess, &row, (byte)ssl->options.side); error = (error == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; if (error != WOLFSSL_SUCCESS || sess == NULL) { WOLFSSL_MSG("Get Session from cache failed"); @@ -15006,21 +15113,23 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) error = WOLFSSL_FAILURE; } else if (LowResTimer() >= (sess->bornOn + sess->timeout)) { + WOLFSSL_SESSION* wrSess = NULL; WOLFSSL_MSG("Invalid session: timed out"); + sess = NULL; TlsSessionCacheUnlockRow(row); + /* Attempt to get a write lock */ + error = TlsSessionCacheGetAndWrLock(id, &wrSess, &row, + ssl->options.side); + if (error == 0 && wrSess != NULL) { + EvictSessionFromCache(wrSess); + TlsSessionCacheUnlockRow(row); + } error = WOLFSSL_FAILURE; } #endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 */ } if (error == WOLFSSL_SUCCESS) { -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - /* We don't want the peer member. We will free it at the end. */ - if (sess->peer != NULL) { - peer = sess->peer; - sess->peer = NULL; - } -#endif #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) error = wolfSSL_DupSessionEx(sess, output, 1, preallocNonce, &preallocNonceLen, &preallocNonceUsed); @@ -15028,7 +15137,7 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) error = wolfSSL_DupSession(sess, output, 1); #endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 */ #ifdef HAVE_EX_DATA - output->ownExData = 0; /* Session cache owns external data */ + output->ownExData = !sess->ownExData; /* Session may own ex_data */ #endif TlsSessionCacheUnlockRow(row); } @@ -15148,11 +15257,12 @@ int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) session = ClientSessionToSession(session); - if (ssl == NULL || session == NULL) { - WOLFSSL_MSG("ssl or session NULL"); + if (ssl == NULL || session == NULL || !session->isSetup) { + WOLFSSL_MSG("ssl or session NULL or not set up"); return WOLFSSL_FAILURE; } + /* We need to lock the session as the first step if its in the cache */ if (session->type == WOLFSSL_SESSION_TYPE_CACHE) { if (session->cacheRow < SESSION_ROWS) { sessRow = &SessionCache[session->cacheRow]; @@ -15163,11 +15273,6 @@ int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) } } - if (ret == WOLFSSL_SUCCESS && SslSessionCacheOff(ssl, session)) { - WOLFSSL_MSG("Session cache off"); - ret = WOLFSSL_FAILURE; - } - if (ret == WOLFSSL_SUCCESS && ssl->options.side != WOLFSSL_NEITHER_END && (byte)ssl->options.side != session->side) { WOLFSSL_MSG("Setting session for wrong role"); @@ -15175,12 +15280,16 @@ int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) } if (ret == WOLFSSL_SUCCESS) { + if (ssl->session == session) { + WOLFSSL_MSG("ssl->session and session same"); + } + else #ifdef HAVE_STUNNEL /* stunnel depends on the ex_data not being duplicated. Copy OpenSSL * behaviour for now. */ if (session->type != WOLFSSL_SESSION_TYPE_CACHE) { if (wolfSSL_SESSION_up_ref(session) == WOLFSSL_SUCCESS) { - wolfSSL_SESSION_free(ssl->session); + wolfSSL_FreeSession(ssl->ctx, ssl->session); ssl->session = session; } else @@ -15196,7 +15305,8 @@ int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) } /* Let's copy over the altSessionID for local cache purposes */ - if (ret == WOLFSSL_SUCCESS && session->haveAltSessionID) { + if (ret == WOLFSSL_SUCCESS && session->haveAltSessionID && + ssl->session != session) { ssl->session->haveAltSessionID = 1; XMEMCPY(ssl->session->altSessionID, session->altSessionID, ID_LEN); } @@ -15223,36 +15333,33 @@ int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) } #endif /* OPENSSL_EXTRA */ - if (LowResTimer() < (ssl->session->bornOn + ssl->session->timeout)) { - ssl->options.resuming = 1; - ssl->options.haveEMS = ssl->session->haveEMS; + if (LowResTimer() >= (ssl->session->bornOn + ssl->session->timeout)) { +#if !defined(OPENSSL_EXTRA) || !defined(WOLFSSL_ERROR_CODE_OPENSSL) + return WOLFSSL_FAILURE; /* session timed out */ +#else /* defined(OPENSSL_EXTRA) && defined(WOLFSSL_ERROR_CODE_OPENSSL) */ + WOLFSSL_MSG("Session is expired but return success for " + "OpenSSL compatibility"); +#endif + } + ssl->options.resuming = 1; + ssl->options.haveEMS = ssl->session->haveEMS; #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - ssl->version = ssl->session->version; - if (IsAtLeastTLSv1_3(ssl->version)) - ssl->options.tls1_3 = 1; + defined(HAVE_SESSION_TICKET)) + ssl->version = ssl->session->version; + if (IsAtLeastTLSv1_3(ssl->version)) + ssl->options.tls1_3 = 1; #endif #if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) - ssl->options.cipherSuite0 = ssl->session->cipherSuite0; - ssl->options.cipherSuite = ssl->session->cipherSuite; + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) + ssl->options.cipherSuite0 = ssl->session->cipherSuite0; + ssl->options.cipherSuite = ssl->session->cipherSuite; #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - ssl->peerVerifyRet = (unsigned long)ssl->session->peerVerifyRet; + ssl->peerVerifyRet = (unsigned long)ssl->session->peerVerifyRet; #endif - ret = WOLFSSL_SUCCESS; - } - else { -#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_ERROR_CODE_OPENSSL) - WOLFSSL_MSG("Session is expired but return success for " - "OpenSSL compatibility"); - ret = WOLFSSL_SUCCESS; -#else - ret = WOLFSSL_FAILURE; /* session timed out */ -#endif /* OPENSSL_EXTRA && WOLFSSL_ERROR_CODE_OPENSSL */ - } - return ret; + + return WOLFSSL_SUCCESS; } @@ -15456,7 +15563,6 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, int row; int i; int overwrite = 0; - (void)ctx; (void)sessionIndex; (void)useTicket; @@ -15556,34 +15662,47 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, #ifdef SESSION_CACHE_DYNAMIC_MEM cacheSession = sessRow->Sessions[idx]; - if (cacheSession) { - XFREE(cacheSession, sessRow->heap, DYNAMIC_TYPE_SESSION); - cacheSession = NULL; - } - cacheSession = (WOLFSSL_SESSION*) XMALLOC(sizeof(WOLFSSL_SESSION), sessRow->heap, - DYNAMIC_TYPE_SESSION); if (cacheSession == NULL) { - return MEMORY_E; + cacheSession = (WOLFSSL_SESSION*) XMALLOC(sizeof(WOLFSSL_SESSION), + sessRow->heap, DYNAMIC_TYPE_SESSION); + if (cacheSession == NULL) { + #ifdef HAVE_SESSION_TICKET + XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); + #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKE_NONCE_MALLOC) + if (preallocNonce != NULL) + XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + #endif + #endif + SESSION_ROW_UNLOCK(sessRow); + return MEMORY_E; + } + XMEMSET(cacheSession, 0, sizeof(WOLFSSL_SESSION)); + sessRow->Sessions[idx] = cacheSession; } - XMEMSET(cacheSession, 0, sizeof(WOLFSSL_SESSION)); - sessRow->Sessions[idx] = cacheSession; #else cacheSession = &sessRow->Sessions[idx]; #endif #ifdef HAVE_EX_DATA - if (cacheSession->ownExData) { + if (overwrite) { + /* Figure out who owns the ex_data */ + if (cacheSession->ownExData) { + /* Prioritize cacheSession copy */ + XMEMCPY(&addSession->ex_data, &cacheSession->ex_data, + sizeof(WOLFSSL_CRYPTO_EX_DATA)); + } + /* else will be copied in wolfSSL_DupSession call */ + } + else if (cacheSession->ownExData) { crypto_ex_cb_free_data(cacheSession, crypto_ex_cb_ctx_session, &cacheSession->ex_data); - if (cacheSession->rem_sess_cb) { - cacheSession->rem_sess_cb(NULL, cacheSession); - /* Make sure not to call remove functions again */ - cacheSession->ownExData = 0; - cacheSession->rem_sess_cb = NULL; - } + cacheSession->ownExData = 0; } #endif + if (!overwrite) + EvictSessionFromCache(cacheSession); + cacheSession->type = WOLFSSL_SESSION_TYPE_CACHE; cacheSession->cacheRow = row; @@ -15650,22 +15769,26 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, #endif if (ret == 0) { - /* Increment the totalCount and the nextIdx */ - if (sessRow->totalCount < SESSIONS_PER_ROW) - sessRow->totalCount++; - sessRow->nextIdx = (sessRow->nextIdx + 1) % SESSIONS_PER_ROW; + if (!overwrite) { + /* Increment the totalCount and the nextIdx */ + if (sessRow->totalCount < SESSIONS_PER_ROW) + sessRow->totalCount++; + sessRow->nextIdx = (sessRow->nextIdx + 1) % SESSIONS_PER_ROW; + } if (id != addSession->sessionID) { /* ssl->session->sessionID may contain the bogus ID or we want the * ID from the arrays object */ XMEMCPY(cacheSession->sessionID, id, ID_LEN); cacheSession->sessionIDSz = ID_LEN; } -#ifdef HAVE_EX_DATA - if (ctx->rem_sess_cb != NULL) { - addSession->ownExData = 0; - cacheSession->ownExData = 1; +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + if (ctx->rem_sess_cb != NULL) cacheSession->rem_sess_cb = ctx->rem_sess_cb; - } +#endif +#ifdef HAVE_EX_DATA + /* The session in cache now owns the ex_data */ + addSession->ownExData = 0; + cacheSession->ownExData = 1; #endif #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ @@ -15687,7 +15810,6 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, cacheSession->ticketLen = 0; } #endif - SESSION_ROW_UNLOCK(sessRow); cacheSession = NULL; /* Can't access after unlocked */ @@ -15724,9 +15846,6 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, return ret; } -#ifndef NO_CLIENT_CACHE -#endif - void AddSession(WOLFSSL* ssl) { int error = 0; @@ -15743,63 +15862,16 @@ void AddSession(WOLFSSL* ssl) return; } - if (ssl->options.haveSessionId == 0) { - WOLFSSL_MSG("Don't have session id"); - return; - } - -#if defined(HAVE_SESSION_TICKET) && !defined(OPENSSL_EXTRA) - /* For the compat layer generate a session object to use */ - if (ssl->options.side == WOLFSSL_SERVER_END && ssl->options.useTicket == 1) { - WOLFSSL_MSG("Using tickets instead of cache"); - return; - } -#endif - if (session->haveAltSessionID) { id = session->altSessionID; idSz = ID_LEN; } else { - if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) { - /* Make sure the session ID is available when the user calls any - * get_session API */ - XMEMCPY(session->sessionID, ssl->arrays->sessionID, ID_LEN); - session->sessionIDSz = ssl->arrays->sessionIDSz; - } id = session->sessionID; idSz = session->sessionIDSz; } - session->timeout = ssl->timeout; - session->side = (byte)ssl->options.side; - if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) - XMEMCPY(session->masterSecret, ssl->arrays->masterSecret, SECRET_LEN); - session->haveEMS = ssl->options.haveEMS; -#ifdef OPENSSL_EXTRA - /* If using compatibility layer then check for and copy over session context - * id. */ - if (ssl->sessionCtxSz > 0 && ssl->sessionCtxSz < ID_LEN) { - XMEMCPY(ssl->session->sessionCtx, ssl->sessionCtx, ssl->sessionCtxSz); - session->sessionCtxSz = ssl->sessionCtxSz; - } -#endif - session->timeout = ssl->timeout; - session->bornOn = LowResTimer(); -#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - session->version = ssl->version; -#endif -#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) - session->cipherSuite0 = ssl->options.cipherSuite0; - session->cipherSuite = ssl->options.cipherSuite; -#endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - session->peerVerifyRet = (byte)ssl->peerVerifyRet; -#endif - /* Do this last so that if it fails, the rest of the session is setup. Do - * this only for the client because if the server doesn't have an ID at + /* Do this only for the client because if the server doesn't have an ID at * this point, it won't on resumption. */ if (idSz == 0 && ssl->options.side == WOLFSSL_CLIENT_END) { WC_RNG* rng = NULL; @@ -15817,31 +15889,28 @@ void AddSession(WOLFSSL* ssl) id = ssl->session->altSessionID; idSz = ID_LEN; } - /* Setup done */ - if (ssl->options.side == WOLFSSL_SERVER_END /* No point in adding a - * client session */ -#ifdef HAVE_EXT_CACHE - && !ssl->options.internalCacheOff -#endif - ) - { - /* Try to add the session to cache. Its ok if we don't succeed. */ - (void)AddSessionToCache(ssl->ctx, session, id, idSz, + /* Try to add the session to internal cache or external cache + if a new_sess_cb is set. Its ok if we don't succeed. */ + (void)AddSessionToCache(ssl->ctx, session, id, idSz, #ifdef SESSION_INDEX - &ssl->sessionIndex, + &ssl->sessionIndex, #else - NULL, + NULL, #endif - ssl->options.side, + ssl->options.side, #ifdef HAVE_SESSION_TICKET - ssl->options.useTicket, + ssl->options.useTicket, +#else + 0, +#endif +#ifdef NO_SESSION_CACHE_REF + NULL #else - 0, + (ssl->options.side == WOLFSSL_CLIENT_END) ? + &ssl->clientSession : NULL #endif - NULL - ); - } + ); #ifdef HAVE_EXT_CACHE if (error == 0 && ssl->ctx->new_sess_cb != NULL) { @@ -17795,8 +17864,16 @@ int wolfSSL_set_compression(WOLFSSL* ssl) if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { ctx->noTicketTls12 = 1; } + /* This code is here for documentation purpose. You must not turn off + * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3. + * Because we need to support both stateful and stateless tickets. + #ifdef WOLFSSL_TLS13 + if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { + ctx->noTicketTls13 = 1; + } + #endif + */ #endif - return ctx->mask; } @@ -20178,7 +20255,7 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, if (!ssl->options.handShakeDone) { /* Only reset the session if we didn't complete a handshake */ - wolfSSL_SESSION_free(ssl->session); + wolfSSL_FreeSession(ssl->ctx, ssl->session); ssl->session = wolfSSL_NewSession(ssl->heap); if (ssl->session == NULL) { return WOLFSSL_FAILURE; @@ -21207,6 +21284,8 @@ WOLFSSL_SESSION* wolfSSL_NewSession(void* heap) { WOLFSSL_SESSION* ret = NULL; + WOLFSSL_ENTER("wolfSSL_NewSession"); + ret = (WOLFSSL_SESSION*)XMALLOC(sizeof(WOLFSSL_SESSION), heap, DYNAMIC_TYPE_SESSION); if (ret != NULL) { @@ -21238,12 +21317,12 @@ WOLFSSL_SESSION* wolfSSL_NewSession(void* heap) ret->ticketNonce.data = ret->ticketNonce.dataStatic; #endif #endif -#ifdef HAVE_EX_DATA - crypto_ex_cb_setup_new_data(ret, crypto_ex_cb_ctx_session, - &ret->ex_data); -#endif #ifdef HAVE_EX_DATA ret->ownExData = 1; + if (crypto_ex_cb_ctx_session != NULL) { + crypto_ex_cb_setup_new_data(ret, crypto_ex_cb_ctx_session, + &ret->ex_data); + } #endif } return ret; @@ -21593,6 +21672,8 @@ void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) (void)ctx; + WOLFSSL_ENTER("wolfSSL_FreeSession"); + if (session->ref.count > 0) { int ret; int isZero; @@ -21604,23 +21685,14 @@ void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) wolfSSL_RefFree(&session->ref); } -#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + WOLFSSL_MSG("wolfSSL_FreeSession full free"); + #ifdef HAVE_EX_DATA if (session->ownExData) { crypto_ex_cb_free_data(session, crypto_ex_cb_ctx_session, &session->ex_data); } #endif - if (ctx != NULL && ctx->rem_sess_cb -#ifdef HAVE_EX_DATA - && session->ownExData /* This will be true if we are not using the - * internal cache so it will get called for - * externally cached sessions as well. */ -#endif - ) { - ctx->rem_sess_cb(ctx, session); - } -#endif #ifdef HAVE_EX_DATA_CLEANUP_HOOKS wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data); @@ -21660,6 +21732,8 @@ void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) } } +/* DO NOT use this API internally. Use wolfSSL_FreeSession directly instead + * and pass in the ctx parameter if possible (like from ssl->ctx). */ void wolfSSL_SESSION_free(WOLFSSL_SESSION* session) { session = ClientSessionToSession(session); @@ -21682,12 +21756,14 @@ int wolfSSL_CTX_add_session(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) /* Session cache is global */ (void)ctx; - id = session->sessionID; - idSz = session->sessionIDSz; if (session->haveAltSessionID) { id = session->altSessionID; idSz = ID_LEN; } + else { + id = session->sessionID; + idSz = session->sessionIDSz; + } error = AddSessionToCache(ctx, session, id, idSz, NULL, session->side, @@ -25877,11 +25953,13 @@ WOLFSSL_SESSION* wolfSSL_d2i_SSL_SESSION(WOLFSSL_SESSION** sess, *sess = s; } + s->isSetup = 1; + *p += idx; end: if (ret != 0 && (sess == NULL || *sess != s)) { - wolfSSL_SESSION_free(s); + wolfSSL_FreeSession(NULL, s); s = NULL; } #endif /* HAVE_EXT_CACHE */ @@ -31417,6 +31495,8 @@ int wolfSSL_version(WOLFSSL* ssl) return DTLS1_VERSION; case DTLSv1_2_MINOR : return DTLS1_2_VERSION; + case DTLSv1_3_MINOR: + return DTLS1_3_VERSION; default: return WOLFSSL_FAILURE; } @@ -32720,10 +32800,13 @@ int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh) return WOLFSSL_SUCCESS; } #endif - -/* Assumes that the session passed in is from the cache. */ +#ifndef NO_SESSION_CACHE int wolfSSL_SSL_CTX_remove_session(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *s) { +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + int rem_called = FALSE; +#endif + WOLFSSL_ENTER("wolfSSL_SSL_CTX_remove_session"); s = ClientSessionToSession(s); @@ -32734,77 +32817,64 @@ int wolfSSL_SSL_CTX_remove_session(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *s) if (!ctx->internalCacheOff) #endif { - /* Don't remove session just timeout session. */ - s->timeout = 0; -#ifndef NO_SESSION_CACHE - /* Clear the timeout in the cache */ - { - int row; - int i; - SessionRow* sessRow = NULL; - WOLFSSL_SESSION *cacheSession; - const byte* id; - int ret = 0; + const byte* id; + WOLFSSL_SESSION *sess = NULL; + word32 row = 0; + int ret; - id = s->sessionID; - if (s->haveAltSessionID) - id = s->altSessionID; + id = s->sessionID; + if (s->haveAltSessionID) + id = s->altSessionID; - row = (int)(HashObject(id, ID_LEN, &ret) % SESSION_ROWS); - if (ret != 0) { - WOLFSSL_MSG("Hash session failed"); - return ret; - } - - sessRow = &SessionCache[row]; - if (SESSION_ROW_WR_LOCK(sessRow) != 0) { - WOLFSSL_MSG("Session row lock failed"); - return BAD_MUTEX_E; + ret = TlsSessionCacheGetAndWrLock(id, &sess, &row, ctx->method->side); + if (ret == 0 && sess != NULL) { +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + if (sess->rem_sess_cb != NULL) { + rem_called = TRUE; } - - for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) { -#ifdef SESSION_CACHE_DYNAMIC_MEM - cacheSession = sessRow->Sessions[i]; -#else - cacheSession = &sessRow->Sessions[i]; #endif - if (cacheSession && - XMEMCMP(id, cacheSession->sessionID, ID_LEN) == 0) { - if (ctx->method->side != cacheSession->side) - continue; - cacheSession->timeout = 0; + /* Call this before changing ownExData so that calls to ex_data + * don't try to access the SessionCache again. */ + EvictSessionFromCache(sess); #ifdef HAVE_EX_DATA - if (cacheSession->ownExData) { - /* Most recent version of ex data is in cache. Copy it - * over so the user can free it. */ - XMEMCPY(&s->ex_data, &cacheSession->ex_data, - sizeof(WOLFSSL_CRYPTO_EX_DATA)); - } - cacheSession->ownExData = 0; /* We clear below */ - s->ownExData = 1; + if (sess->ownExData) { + /* Most recent version of ex data is in cache. Copy it + * over so the user can free it. */ + XMEMCPY(&s->ex_data, &sess->ex_data, + sizeof(WOLFSSL_CRYPTO_EX_DATA)); + s->ownExData = 1; + sess->ownExData = 0; + } #endif - #ifdef SESSION_CACHE_DYNAMIC_MEM - XFREE(cacheSession, sessRow->heap, DYNAMIC_TYPE_SESSION); - sessRow->Sessions[i] = NULL; -#endif - break; + { + /* Find and clear entry. Row is locked so we are good to go. */ + int idx; + for (idx = 0; idx < SESSIONS_PER_ROW; idx++) { + if (sess == SessionCache[row].Sessions[idx]) { + XFREE(sess, sess->heap, DYNAMIC_TYPE_SESSION); + SessionCache[row].Sessions[idx] = NULL; + break; + } } } - SESSION_ROW_UNLOCK(sessRow); - } #endif + TlsSessionCacheUnlockRow(row); + } } #if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) - if (ctx->rem_sess_cb != NULL) { + if (ctx->rem_sess_cb != NULL && !rem_called) { ctx->rem_sess_cb(ctx, s); } #endif + /* s cannot be resumed at this point */ + s->timeout = 0; + return 0; } - +#endif /* !NO_SESSION_CACHE */ #ifndef NO_BIO BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s) { diff --git a/src/tls13.c b/src/tls13.c index 3f99970e5a6..2db8e76b2fd 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -5672,7 +5672,8 @@ static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz, /* Decode the identity. */ switch (current->decryptRet) { case PSK_DECRYPT_NONE: - ret = DoClientTicket_ex(ssl, current); + ret = DoClientTicket_ex(ssl, current, 1); + /* psk->sess may be set. Need to clean up later. */ break; case PSK_DECRYPT_OK: ret = WOLFSSL_TICKET_RET_OK; @@ -5690,12 +5691,27 @@ static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz, return ret; #endif + if (ret != WOLFSSL_TICKET_RET_OK && current->sess_free_cb != NULL) { + current->sess_free_cb(ssl, current->sess, + ¤t->sess_free_cb_ctx); + current->sess = NULL; + XMEMSET(¤t->sess_free_cb_ctx, 0, + sizeof(psk_sess_free_cb_ctx)); + } if (ret == WOLFSSL_TICKET_RET_OK) { - if (DoClientTicketCheck(ssl, current, ssl->timeout, suite) != 0) + ret = DoClientTicketCheck(ssl, current, ssl->timeout, suite); + if (ret == 0) + DoClientTicketFinalize(ssl, current->it, current->sess); + if (current->sess_free_cb != NULL) { + current->sess_free_cb(ssl, current->sess, + ¤t->sess_free_cb_ctx); + current->sess = NULL; + XMEMSET(¤t->sess_free_cb_ctx, 0, + sizeof(psk_sess_free_cb_ctx)); + } + if (ret != 0) continue; - DoClientTicketFinalize(ssl, current->it); - /* SERVER: using secret in session ticket for peer auth. */ ssl->options.peerAuthGood = 1; @@ -10076,10 +10092,6 @@ static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input, #endif const byte* nonce; byte nonceLength; -#ifndef NO_SESSION_CACHE - const byte* id; - byte idSz; -#endif WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_DO); WOLFSSL_ENTER("DoTls13NewSessionTicket"); @@ -10175,16 +10187,9 @@ static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input, #endif *inOutIdx += length; + SetupSession(ssl); #ifndef NO_SESSION_CACHE - AddSession(ssl); - id = ssl->session->sessionID; - idSz = ssl->session->sessionIDSz; - if (ssl->session->haveAltSessionID) { - id = ssl->session->altSessionID; - idSz = ID_LEN; - } - AddSessionToCache(ssl->ctx, ssl->session, id, idSz, NULL, - ssl->session->side, 1, &ssl->clientSession); + AddSession(ssl); #endif /* Always encrypted. */ @@ -10369,12 +10374,15 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) #else extSz = EXTS_SZ; #endif - - /* Lifetime | Age Add | Ticket | Extensions */ - length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ + - ssl->session->ticketLen + extSz; + /* Lifetime | Age Add | Ticket session ID | Extensions */ + length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ; + if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0) + length += ID_LEN + extSz; + else + length += ssl->session->ticketLen + extSz; /* Nonce */ length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ; + sendSz = idx + length + MAX_MSG_EXTRA; /* Check buffers are big enough and grow if needed. */ @@ -10399,11 +10407,26 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) output[idx++] = ssl->session->ticketNonce.data[0]; /* length */ - c16toa(ssl->session->ticketLen, output + idx); + if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0) { + c16toa(ID_LEN, output + idx); + } + else { + c16toa(ssl->session->ticketLen, output + idx); + } + idx += LENGTH_SZ; /* ticket */ - XMEMCPY(output + idx, ssl->session->ticket, ssl->session->ticketLen); - idx += ssl->session->ticketLen; + if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0) { + if (ssl->session->haveAltSessionID) + XMEMCPY(output + idx, ssl->session->altSessionID, ID_LEN); + else + XMEMCPY(output + idx, ssl->session->sessionID, ID_LEN); + idx += ID_LEN; + } + else { + XMEMCPY(output + idx, ssl->session->ticket, ssl->session->ticketLen); + idx += ssl->session->ticketLen; + } #ifdef WOLFSSL_EARLY_DATA extSz = 0; @@ -10419,6 +10442,7 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) ssl->options.haveSessionId = 1; + SetupSession(ssl); /* Only add to cache when support built in and when the ticket contains * an ID. Otherwise we have no way to actually retrieve the ticket from the * cache. */ diff --git a/tests/api.c b/tests/api.c index a9527d48ac3..e66dbc5517b 100644 --- a/tests/api.c +++ b/tests/api.c @@ -342,7 +342,7 @@ defined(HAVE_SESSION_TICKET) || (defined(OPENSSL_EXTRA) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)) || \ defined(WOLFSSL_TEST_STATIC_BUILD) || defined(WOLFSSL_DTLS) || \ - defined(HAVE_ECH) + defined(HAVE_ECH) || defined(HAVE_EX_DATA) /* for testing SSL_get_peer_cert_chain, or SESSION_TICKET_HINT_DEFAULT, * for setting authKeyIdSrc in WOLFSSL_X509, or testing DTLS sequence * number tracking */ @@ -7447,6 +7447,592 @@ static int test_wolfSSL_CTX_add_session(void) return res; } +#if defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_EXT_CACHE) && \ + !defined(SINGLE_THREADED) && defined(WOLFSSL_TLS13) && \ + !defined(NO_SESSION_CACHE) && defined(OPENSSL_EXTRA) && \ + defined(SESSION_CERTS) && defined(HAVE_SESSION_TICKET) && \ + !defined(TITAN_SESSION_CACHE) && \ + !defined(HUGE_SESSION_CACHE) && \ + !defined(BIG_SESSION_CACHE) && \ + !defined(MEDIUM_SESSION_CACHE) + +/* twcase - prefix for test_wolfSSL_CTX_add_session_ext */ +/* Sessions to restore/store */ +static WOLFSSL_SESSION* twcase_server_first_session_ptr; +static WOLFSSL_SESSION* twcase_client_first_session_ptr; +static WOLFSSL_CTX* twcase_server_current_ctx_ptr; +static int twcase_new_session_called = 0; +static int twcase_remove_session_called = 0; +static int twcase_get_session_called = 0; + +/* Test default, SESSIONS_PER_ROW*SESSION_ROWS = 3*11, see ssl.c */ +#define SESSION_CACHE_SIZE 33 + +typedef struct { + const byte* key; /* key, altSessionID, session ID, NULL if empty */ + WOLFSSL_SESSION* value; +} hashTable_entry; + +typedef struct { + hashTable_entry entries[SESSION_CACHE_SIZE]; /* hash slots */ + size_t capacity; /* size of entries */ + size_t length; /* number of items in the hash table */ + wolfSSL_Mutex htLock; /* lock */ +}hashTable; + +static hashTable server_sessionCache; + +static int twcase_new_sessionCb(WOLFSSL *ssl, WOLFSSL_SESSION *sess) +{ + int i; + (void)ssl; + /* + * This example uses a hash table. + * Steps you should take for a non-demo code: + * - acquire a lock for the file named according to the session id + * - open the file + * - encrypt and write the SSL_SESSION object to the file + * - release the lock + * + * Return: + * 0: The callback does not wish to hold a reference of the sess + * 1: The callback wants to hold a reference of the sess. The callback is + * now also responsible for calling wolfSSL_SESSION_free() on sess. + */ + if (sess == NULL) + return 0; + + if (wc_LockMutex(&server_sessionCache.htLock) != 0) { + return 0; + } + for (i = 0; i < SESSION_CACHE_SIZE; i++) { + if (server_sessionCache.entries[i].value == NULL) { + if (sess->haveAltSessionID == 1) + server_sessionCache.entries[i].key = sess->altSessionID; + else + server_sessionCache.entries[i].key = sess->sessionID; + + server_sessionCache.entries[i].value = sess; + server_sessionCache.length++; + break; + } + } + ++twcase_new_session_called; + wc_UnLockMutex(&server_sessionCache.htLock); + fprintf(stderr, "\t\ttwcase_new_session_called %d\n", + twcase_new_session_called); + return 1; +} + +static void twcase_remove_sessionCb(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *sess) +{ + int i; + (void)ctx; + (void)sess; + + if (sess == NULL) + return; + /* + * This example uses a hash table. + * Steps you should take for a non-demo code: + * - acquire a lock for the file named according to the session id + * - remove the file + * - release the lock + */ + if (wc_LockMutex(&server_sessionCache.htLock) != 0) { + return; + } + for (i = 0; i < SESSION_CACHE_SIZE; i++) { + if (server_sessionCache.entries[i].key != NULL && + XMEMCMP(server_sessionCache.entries[i].key, + sess->sessionID, SSL_MAX_SSL_SESSION_ID_LENGTH) == 0) { + wolfSSL_SESSION_free(server_sessionCache.entries[i].value); + server_sessionCache.entries[i].value = NULL; + server_sessionCache.entries[i].key = NULL; + server_sessionCache.length--; + break; + } + } + ++twcase_remove_session_called; + wc_UnLockMutex(&server_sessionCache.htLock); + fprintf(stderr, "\t\ttwcase_remove_session_called %d\n", + twcase_remove_session_called); +} + +static WOLFSSL_SESSION *twcase_get_sessionCb(WOLFSSL *ssl, + const unsigned char *id, int len, int *ref) +{ + int i; + (void)ssl; + (void)id; + (void)len; + + /* + * This example uses a hash table. + * Steps you should take for a non-demo code: + * - acquire a lock for the file named according to the session id in the + * 2nd arg + * - read and decrypt contents of file and create a new SSL_SESSION + * - object release the lock + * - return the new session object + */ + fprintf(stderr, "\t\ttwcase_get_session_called %d\n", + ++twcase_get_session_called); + /* This callback want to retain a copy of the object. If we want wolfSSL to + * be responsible for the pointer then set to 0. */ + *ref = 1; + + for (i = 0; i < SESSION_CACHE_SIZE; i++) { + if (server_sessionCache.entries[i].key != NULL && + XMEMCMP(server_sessionCache.entries[i].key, id, + SSL_MAX_SSL_SESSION_ID_LENGTH) == 0) { + return server_sessionCache.entries[i].value; + } + } + return NULL; +} +static void twcase_get_sessionCb_cleanup(void) +{ + int i; + int cnt = 0; + + /* If twcase_get_sessionCb sets *ref = 1, the application is responsible + * for freeing sessions */ + + for (i = 0; i < SESSION_CACHE_SIZE; i++) { + if (server_sessionCache.entries[i].value != NULL) { + wolfSSL_SESSION_free(server_sessionCache.entries[i].value); + cnt++; + } + } + + fprintf(stderr, "\t\ttwcase_get_sessionCb_cleanup freed %d sessions\n", + cnt); +} + +static void twcase_cache_intOff_extOff(WOLFSSL_CTX* ctx) +{ + /* off - Disable internal cache */ + AssertIntEQ(wolfSSL_CTX_set_session_cache_mode(ctx, + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE), WOLFSSL_SUCCESS); +#ifdef OPENSSL_EXTRA + AssertIntEQ(wolfSSL_CTX_get_session_cache_mode(ctx) & + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE, + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE); +#endif + /* off - Donot setup external cache */ + + /* Require both peers to provide certs */ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); +} + +static void twcase_cache_intOn_extOff(WOLFSSL_CTX* ctx) +{ + /* on - internal cache is on by default*/ + /* off - Donot setup external cache */ + /* Require both peers to provide certs */ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); +} + +static void twcase_cache_intOff_extOn(WOLFSSL_CTX* ctx) +{ + /* off - Disable internal cache */ + AssertIntEQ(wolfSSL_CTX_set_session_cache_mode(ctx, + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE), WOLFSSL_SUCCESS); +#ifdef OPENSSL_EXTRA + AssertIntEQ(wolfSSL_CTX_get_session_cache_mode(ctx) & + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE, + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE); +#endif + /* on - Enable external cache */ + wolfSSL_CTX_sess_set_new_cb(ctx, twcase_new_sessionCb); + wolfSSL_CTX_sess_set_remove_cb(ctx, twcase_remove_sessionCb); + wolfSSL_CTX_sess_set_get_cb(ctx, twcase_get_sessionCb); + + /* Require both peers to provide certs */ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); +} + +static void twcase_cache_intOn_extOn(WOLFSSL_CTX* ctx) +{ + /* on - internal cache is on by default */ + /* on - Enable external cache */ + wolfSSL_CTX_sess_set_new_cb(ctx, twcase_new_sessionCb); + wolfSSL_CTX_sess_set_remove_cb(ctx, twcase_remove_sessionCb); + wolfSSL_CTX_sess_set_get_cb(ctx, twcase_get_sessionCb); + + /* Require both peers to provide certs */ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); +} +static void twcase_cache_intOn_extOn_noTicket(WOLFSSL_CTX* ctx) +{ + /* on - internal cache is on by default */ + /* on - Enable external cache */ + wolfSSL_CTX_sess_set_new_cb(ctx, twcase_new_sessionCb); + wolfSSL_CTX_sess_set_remove_cb(ctx, twcase_remove_sessionCb); + wolfSSL_CTX_sess_set_get_cb(ctx, twcase_get_sessionCb); + + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TICKET); + /* Require both peers to provide certs */ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); +} +static void twcase_server_sess_ctx_pre_shutdown(WOLFSSL* ssl) +{ + WOLFSSL_SESSION** sess; + if (wolfSSL_is_server(ssl)) + sess = &twcase_server_first_session_ptr; + else + return; + + if (*sess == NULL) { + AssertNotNull(*sess = wolfSSL_get1_session(ssl)); + /* Now save the session in the internal store to make it available + * for lookup. For TLS 1.3, we can't save the session without + * WOLFSSL_TICKET_HAVE_ID because there is no way to retrieve the + * session from cache. */ + if (wolfSSL_is_server(ssl) +#ifndef WOLFSSL_TICKET_HAVE_ID + && wolfSSL_version(ssl) != TLS1_3_VERSION + && wolfSSL_version(ssl) != DTLS1_3_VERSION +#endif + ) { + AssertIntEQ(wolfSSL_CTX_add_session(wolfSSL_get_SSL_CTX(ssl), + *sess), WOLFSSL_SUCCESS); + } + } + /* Save CTX to be able to decrypt tickets */ + if (twcase_server_current_ctx_ptr == NULL) { + AssertNotNull(twcase_server_current_ctx_ptr = wolfSSL_get_SSL_CTX(ssl)); + AssertIntEQ(wolfSSL_CTX_up_ref(wolfSSL_get_SSL_CTX(ssl)), + WOLFSSL_SUCCESS); + } +#ifdef SESSION_CERTS +#ifndef WOLFSSL_TICKET_HAVE_ID + if (wolfSSL_version(ssl) != TLS1_3_VERSION && + wolfSSL_session_reused(ssl)) +#endif + { + /* With WOLFSSL_TICKET_HAVE_ID the peer certs should be available + * for all connections. TLS 1.3 only has tickets so if we don't + * include the session id in the ticket then the certificates + * will not be available on resumption. */ + WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl); + AssertNotNull(peer); + wolfSSL_X509_free(peer); + AssertNotNull(wolfSSL_SESSION_get_peer_chain(*sess)); + } +#endif +} + +static void twcase_client_sess_ctx_pre_shutdown(WOLFSSL* ssl) +{ + WOLFSSL_SESSION** sess; + sess = &twcase_client_first_session_ptr; + if (*sess == NULL) { + AssertNotNull(*sess = wolfSSL_get1_session(ssl)); + } + else { + /* If we have a session retrieved then remaining connections should be + * resuming on that session */ + AssertIntEQ(wolfSSL_session_reused(ssl), 1); + } + +#ifdef SESSION_CERTS +#ifndef WOLFSSL_TICKET_HAVE_ID + if (wolfSSL_version(ssl) != TLS1_3_VERSION && + wolfSSL_session_reused(ssl)) +#endif + { + + WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl); + AssertNotNull(peer); + wolfSSL_X509_free(peer); + AssertNotNull(wolfSSL_SESSION_get_peer_chain(*sess)); +#ifdef OPENSSL_EXTRA + AssertNotNull(wolfSSL_SESSION_get0_peer(*sess)); +#endif + } +#endif +} +static void twcase_client_set_sess_ssl_ready(WOLFSSL* ssl) +{ + /* Set the session to reuse for the client */ + AssertNotNull(ssl); + AssertNotNull(twcase_client_first_session_ptr); + AssertIntEQ(wolfSSL_set_session(ssl,twcase_client_first_session_ptr), + WOLFSSL_SUCCESS); +} +#endif + +static int test_wolfSSL_CTX_add_session_ext(void) +{ + int res = TEST_SKIPPED; +#if defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_EXT_CACHE) && \ + !defined(SINGLE_THREADED) && defined(WOLFSSL_TLS13) && \ + !defined(NO_SESSION_CACHE) && defined(OPENSSL_EXTRA) && \ + defined(SESSION_CERTS) && defined(HAVE_SESSION_TICKET) && \ + !defined(TITAN_SESSION_CACHE) && \ + !defined(HUGE_SESSION_CACHE) && \ + !defined(BIG_SESSION_CACHE) && \ + !defined(MEDIUM_SESSION_CACHE) + /* Test the default 33 sessions */ + + struct test_params { + method_provider client_meth; + method_provider server_meth; + const char* tls_version; + } params[] = { +#if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && \ + defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TICKET_HAVE_ID) + { wolfTLSv1_3_client_method, wolfTLSv1_3_server_method, "TLSv1_3" }, +#ifdef WOLFSSL_DTLS13 + { wolfDTLSv1_3_client_method, wolfDTLSv1_3_server_method, "DTLSv1_3" }, +#endif +#endif +#ifndef WOLFSSL_NO_TLS12 + { wolfTLSv1_2_client_method, wolfTLSv1_2_server_method, "TLSv1_2" }, +#ifdef WOLFSSL_DTLS + { wolfDTLSv1_2_client_method, wolfDTLSv1_2_server_method, "DTLSv1_2" }, +#endif +#endif +#if !defined(NO_OLD_TLS) && ((!defined(NO_AES) && !defined(NO_AES_CBC)) || \ + !defined(NO_DES3)) + { wolfTLSv1_1_client_method, wolfTLSv1_1_server_method, "TLSv1_1" }, +#ifdef WOLFSSL_DTLS + { wolfDTLSv1_client_method, wolfDTLSv1_server_method, "DTLSv1_0" }, +#endif +#endif + }; + + const int paramsLen = sizeof(params)/sizeof(*params); + int i, j; + + /* Clear cache before starting */ + wolfSSL_CTX_flush_sessions(NULL, -1); + + XMEMSET(&server_sessionCache, 0, sizeof(hashTable)); + if (wc_InitMutex(&server_sessionCache.htLock) != 0) + return BAD_MUTEX_E; + server_sessionCache.capacity = SESSION_CACHE_SIZE; + + for (i = 0; i < paramsLen; i++) { + fprintf(stderr, "\tBegin %s\n", params[i].tls_version); + for (j = 0; j < 5; j++) { + int tls13 = XSTRSTR(params[i].tls_version, "TLSv1_3") != NULL; + int dtls = XSTRSTR(params[i].tls_version, "DTLS") != NULL; + callback_functions client_cb; + callback_functions server_cb; + + (void)dtls; + + /* Test five cache configurations */ + twcase_client_first_session_ptr = NULL; + twcase_server_first_session_ptr = NULL; + twcase_server_current_ctx_ptr = NULL; + twcase_new_session_called = 0; + twcase_remove_session_called = 0; + twcase_get_session_called = 0; + + /* connection 1 - first connection */ + fprintf(stderr, "\tconnect: %s: j=%d, methodsLen=%d\n", + params[i].tls_version, j, paramsLen); + + XMEMSET(&client_cb, 0, sizeof(callback_functions)); + XMEMSET(&server_cb, 0, sizeof(callback_functions)); + client_cb.method = params[i].client_meth; + server_cb.method = params[i].server_meth; + + if (dtls) + client_cb.doUdp = server_cb.doUdp = 1; + + /* Setup internal and external cache */ + switch (j) { + case 0: + /* SSL_OP_NO_TICKET stateful ticket case */ + server_cb.ctx_ready = twcase_cache_intOn_extOn_noTicket; + break; + case 1: + server_cb.ctx_ready = twcase_cache_intOn_extOn; + break; + case 2: + server_cb.ctx_ready = twcase_cache_intOff_extOn; + break; + case 3: + server_cb.ctx_ready = twcase_cache_intOn_extOff; + break; + case 4: + server_cb.ctx_ready = twcase_cache_intOff_extOff; + break; + } + client_cb.ctx_ready = twcase_cache_intOff_extOff; + + /* Add session to internal cache and save SSL session for testing */ + server_cb.on_result = twcase_server_sess_ctx_pre_shutdown; + /* Save client SSL session for testing */ + client_cb.on_result = twcase_client_sess_ctx_pre_shutdown; + server_cb.ticNoInit = 1; /* Use default builtin */ + /* Don't free/release ctx */ + server_cb.ctx = twcase_server_current_ctx_ptr; + server_cb.isSharedCtx = 1; + + test_wolfSSL_client_server_nofail(&client_cb, &server_cb); + + AssertTrue(client_cb.return_code); + AssertTrue(server_cb.return_code); + AssertIntEQ(twcase_get_session_called, 0); + switch (j) { + case 0: + case 1: + case 2: + /* cache cannot be searched with out a connection */ + /* Add a new session */ + AssertIntEQ(twcase_new_session_called, 1); + /* In twcase_server_sess_ctx_pre_shutdown + * wolfSSL_CTX_add_session which evicts the existing session + * in cache and adds it back in */ + AssertIntLE(twcase_remove_session_called, 1); + break; + case 3: + case 4: + /* no external cache */ + AssertIntEQ(twcase_new_session_called, 0); + AssertIntEQ(twcase_remove_session_called, 0); + break; + } + + /* connection 2 - session resume */ + fprintf(stderr, "\tresume: %s: j=%d, methodsLen=%d\n", + params[i].tls_version, j, paramsLen); + twcase_new_session_called = 0; + twcase_remove_session_called = 0; + twcase_get_session_called = 0; + server_cb.on_result = 0; + client_cb.on_result = 0; + server_cb.ticNoInit = 1; /* Use default builtin */ + + server_cb.ctx = twcase_server_current_ctx_ptr; + + /* try session resumption */ + client_cb.ssl_ready = twcase_client_set_sess_ssl_ready; + + test_wolfSSL_client_server_nofail(&client_cb, &server_cb); + + AssertTrue(client_cb.return_code); + AssertTrue(server_cb.return_code); + + /* Clear cache before checking */ + wolfSSL_CTX_flush_sessions(NULL, -1); + + switch (j) { + case 0: + if (tls13) { + /* (D)TLSv1.3 stateful case */ + /* cache hit */ + /* DTLS accesses cache once for stateless parsing and + * once for stateful parsing */ + AssertIntEQ(twcase_get_session_called, !dtls ? 1 : 2); + + /* (D)TLSv1.3 creates a new ticket, + * updates both internal and external cache */ + AssertIntEQ(twcase_new_session_called, 1); + AssertIntEQ(twcase_remove_session_called, 1); + + } + else { + /* non (D)TLSv1.3 case, no update */ + /* DTLS accesses cache once for stateless parsing and + * once for stateful parsing */ +#ifdef WOLFSSL_DTLS_NO_HVR_ON_RESUME + AssertIntEQ(twcase_get_session_called, !dtls ? 1 : 2); +#else + AssertIntEQ(twcase_get_session_called, 1); +#endif + AssertIntEQ(twcase_new_session_called, 0); + /* Called on session added in + * twcase_server_sess_ctx_pre_shutdown */ + AssertIntEQ(twcase_remove_session_called, 1); + } + break; + case 1: + if (tls13) { + /* (D)TLSv1.3 case */ + /* cache hit */ + AssertIntEQ(twcase_get_session_called, 1); + /* (D)TLSv1.3 creates a new ticket, + * updates both internal and external cache */ + AssertIntEQ(twcase_new_session_called, 1); + /* Called on session added in + * twcase_server_sess_ctx_pre_shutdown and by wolfSSL */ + AssertIntEQ(twcase_remove_session_called, 1); + } + else { + /* non (D)TLSv1.3 case */ + /* cache hit */ + /* DTLS accesses cache once for stateless parsing and + * once for stateful parsing */ +#ifdef WOLFSSL_DTLS_NO_HVR_ON_RESUME + AssertIntEQ(twcase_get_session_called, !dtls ? 1 : 2); +#else + AssertIntEQ(twcase_get_session_called, 1); +#endif + AssertIntEQ(twcase_new_session_called, 0); + /* Called on session added in + * twcase_server_sess_ctx_pre_shutdown */ + AssertIntEQ(twcase_remove_session_called, 1); + } + break; + case 2: + if (tls13) { + /* (D)TLSv1.3 case */ + /* cache hit */ + AssertIntEQ(twcase_get_session_called, 1); + /* (D)TLSv1.3 creates a new ticket, + * updates both internal and external cache */ + AssertIntEQ(twcase_new_session_called, 1); + /* Called on session added in + * twcase_server_sess_ctx_pre_shutdown and by wolfSSL */ + AssertIntEQ(twcase_remove_session_called, 1); + } + else { + /* non (D)TLSv1.3 case */ + /* cache hit */ + /* DTLS accesses cache once for stateless parsing and + * once for stateful parsing */ +#ifdef WOLFSSL_DTLS_NO_HVR_ON_RESUME + AssertIntEQ(twcase_get_session_called, !dtls ? 1 : 2); +#else + AssertIntEQ(twcase_get_session_called, 1); +#endif + AssertIntEQ(twcase_new_session_called, 0); + /* Called on session added in + * twcase_server_sess_ctx_pre_shutdown */ + AssertIntEQ(twcase_remove_session_called, 1); + } + break; + case 3: + case 4: + /* no external cache */ + AssertIntEQ(twcase_get_session_called, 0); + AssertIntEQ(twcase_new_session_called, 0); + AssertIntEQ(twcase_remove_session_called, 0); + break; + } + wolfSSL_SESSION_free(twcase_client_first_session_ptr); + wolfSSL_SESSION_free(twcase_server_first_session_ptr); + wolfSSL_CTX_free(twcase_server_current_ctx_ptr); + } + twcase_get_sessionCb_cleanup(); + XMEMSET(&server_sessionCache.entries, 0, + sizeof(server_sessionCache.entries)); + fprintf(stderr, "\tEnd %s\n", params[i].tls_version); + } + wc_FreeMutex(&server_sessionCache.htLock); + res = TEST_RES_CHECK(1); +#endif + + return res; +} + #if defined(WOLFSSL_DTLS) && defined(WOLFSSL_SESSION_EXPORT) /* canned export of a session using older version 3 */ @@ -44888,14 +45474,10 @@ static int test_wolfSSL_CTX_sess_set_remove_cb(void) /* Both should have been allocated */ AssertIntEQ(clientSessRemCountMalloc, 1); AssertIntEQ(serverSessRemCountMalloc, 1); -#if (!defined(WOLFSSL_TLS13) || !defined(HAVE_SESSION_TICKET)) && \ - defined(NO_SESSION_CACHE_REF) - /* Client session should not be added to cache so this should be free'd when - * the SSL object was being free'd */ - AssertIntEQ(clientSessRemCountFree, 1); -#else - /* Client session is in cache due to requiring a persistent reference */ + /* This should not be called yet. Session wasn't evicted from cache yet. */ AssertIntEQ(clientSessRemCountFree, 0); +#if (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) || \ + !defined(NO_SESSION_CACHE_REF) /* Force a cache lookup */ AssertNotNull(SSL_SESSION_get_ex_data(clientSess, serverSessRemIdx)); /* Force a cache update */ @@ -62297,6 +62879,8 @@ static int test_wolfSSL_SESSION_get_ex_new_index(void) SSL_SESSION_free(d); AssertIntEQ(test_wolfSSL_SESSION_get_ex_new_index_free_cb_called, 2); + crypto_ex_cb_free(crypto_ex_cb_ctx_session); + crypto_ex_cb_ctx_session = NULL; return TEST_RES_CHECK(1); } #else @@ -64972,6 +65556,7 @@ TEST_CASE testCases[] = { #ifdef HAVE_IO_TESTS_DEPENDENCIES TEST_DECL(test_wolfSSL_get_finished), TEST_DECL(test_wolfSSL_CTX_add_session), + TEST_DECL(test_wolfSSL_CTX_add_session_ext), #endif TEST_DECL(test_SSL_CIPHER_get_xxx), TEST_DECL(test_wolfSSL_ERR_strings), diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 930a6a8b188..f6f28123042 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -3271,6 +3271,18 @@ enum PskDecryptReturn { PSK_DECRYPT_FAIL, }; +#ifdef HAVE_SESSION_TICKET +typedef struct psk_sess_free_cb_ctx { + word32 row; +#ifdef HAVE_EXT_CACHE + int extCache; + int freeSess; +#endif +} psk_sess_free_cb_ctx; +typedef void (psk_sess_free_cb)(const WOLFSSL* ssl, const WOLFSSL_SESSION* sess, + psk_sess_free_cb_ctx* freeCtx); +#endif + /* The PreSharedKey extension information - entry in a linked list. */ typedef struct PreSharedKey { word16 identityLen; /* Length of identity */ @@ -3283,6 +3295,11 @@ typedef struct PreSharedKey { byte hmac; /* HMAC algorithm */ #ifdef HAVE_SESSION_TICKET InternalTicket* it; /* ptr to ticket */ + const WOLFSSL_SESSION* sess; /* ptr to session either from external cache or + * into SessionCache. Work around so that we + * don't call into the cache more than once */ + psk_sess_free_cb* sess_free_cb; /* callback to free sess */ + psk_sess_free_cb_ctx sess_free_cb_ctx; /* info for sess_free_cb */ #endif byte resumption:1; /* Resumption PSK */ byte chosen:1; /* Server's choice */ @@ -4122,6 +4139,8 @@ struct WOLFSSL_SESSION { byte haveAltSessionID:1; #ifdef HAVE_EX_DATA byte ownExData:1; +#endif +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) Rem_Sess_Cb rem_sess_cb; #endif void* heap; @@ -4197,6 +4216,7 @@ struct WOLFSSL_SESSION { #ifdef HAVE_EX_DATA WOLFSSL_CRYPTO_EX_DATA ex_data; #endif + byte isSetup:1; }; #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) && \ @@ -4211,9 +4231,10 @@ WOLFSSL_LOCAL int wolfSSL_RAND_Init(void); WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_NewSession(void* heap); WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_GetSession( WOLFSSL* ssl, byte* masterSecret, byte restoreSessionCerts); +WOLFSSL_LOCAL void SetupSession(WOLFSSL* ssl); WOLFSSL_LOCAL void AddSession(WOLFSSL* ssl); /* use wolfSSL_API visibility to be able to test in tests/api.c */ -WOLFSSL_API int AddSessionToCache(WOLFSSL_CTX* ssl, +WOLFSSL_API int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, const byte* id, byte idSz, int* sessionIndex, int side, word16 useTicket, ClientSession** clientCacheEntry); #ifndef NO_CLIENT_CACHE @@ -4224,8 +4245,11 @@ WOLFSSL_LOCAL ClientSession* AddSessionToClientCache(int side, int row, int idx, WOLFSSL_LOCAL WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session); WOLFSSL_LOCAL void TlsSessionCacheUnlockRow(word32 row); -WOLFSSL_LOCAL int TlsSessionCacheGetAndLock(const byte *id, - WOLFSSL_SESSION **sess, word32 *lockedRow, byte readOnly); +WOLFSSL_LOCAL int TlsSessionCacheGetAndRdLock(const byte *id, + const WOLFSSL_SESSION **sess, word32 *lockedRow, byte side); +WOLFSSL_LOCAL int TlsSessionCacheGetAndWrLock(const byte *id, + WOLFSSL_SESSION **sess, word32 *lockedRow, byte side); +WOLFSSL_LOCAL void EvictSessionFromCache(WOLFSSL_SESSION* session); /* WOLFSSL_API to test it in tests/api.c */ WOLFSSL_API int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output); WOLFSSL_LOCAL int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session); @@ -5832,13 +5856,15 @@ WOLFSSL_LOCAL int SendTicket(WOLFSSL* ssl); WOLFSSL_LOCAL int DoDecryptTicket(const WOLFSSL* ssl, const byte* input, word32 len, InternalTicket **it); /* Return 0 when check successful. <0 on failure. */ -WOLFSSL_LOCAL void DoClientTicketFinalize(WOLFSSL* ssl, InternalTicket* it); +WOLFSSL_LOCAL void DoClientTicketFinalize(WOLFSSL* ssl, InternalTicket* it, + const WOLFSSL_SESSION* sess); #ifdef WOLFSSL_TLS13 WOLFSSL_LOCAL int DoClientTicketCheck(const WOLFSSL* ssl, const PreSharedKey* psk, sword64 timeout, const byte* suite); WOLFSSL_LOCAL void CleanupClientTickets(PreSharedKey* psk); -WOLFSSL_LOCAL int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk); +WOLFSSL_LOCAL int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk, + int retainSess); #endif WOLFSSL_LOCAL int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len); @@ -6357,8 +6383,9 @@ typedef struct CRYPTO_EX_cb_ctx { WOLFSSL_CRYPTO_EX_dup* dup_func; struct CRYPTO_EX_cb_ctx* next; } CRYPTO_EX_cb_ctx; -extern CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session; -WOLFSSL_LOCAL void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx); +/* use wolfSSL_API visibility to be able to clear in tests/api.c */ +WOLFSSL_API extern CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session; +WOLFSSL_API void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx); WOLFSSL_LOCAL void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx, WOLFSSL_CRYPTO_EX_DATA* ex_data); WOLFSSL_LOCAL void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx, diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 23053d01c08..611a79462dc 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -1236,6 +1236,7 @@ WOLFSSL_ABI WOLFSSL_API int wolfSSL_set_session(WOLFSSL* ssl, WOLFSSL_SESSION* WOLFSSL_API long wolfSSL_SSL_SESSION_set_timeout(WOLFSSL_SESSION* ses, long t); WOLFSSL_ABI WOLFSSL_API WOLFSSL_SESSION* wolfSSL_get_session(WOLFSSL* ssl); WOLFSSL_ABI WOLFSSL_API void wolfSSL_flush_sessions(WOLFSSL_CTX* ctx, long tm); +WOLFSSL_API void wolfSSL_CTX_flush_sessions(WOLFSSL_CTX* ctx, long tm); WOLFSSL_API int wolfSSL_SetServerID(WOLFSSL* ssl, const unsigned char* id, int len, int newSession); #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \ @@ -4984,9 +4985,6 @@ WOLFSSL_API long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx); WOLFSSL_API long wolfSSL_get_timeout(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh); -WOLFSSL_API int wolfSSL_SSL_CTX_remove_session(WOLFSSL_CTX* ctx, - WOLFSSL_SESSION *c); - WOLFSSL_API WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s); WOLFSSL_API WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s); WOLFSSL_API int wolfSSL_SSL_do_handshake(WOLFSSL *s); @@ -5002,6 +5000,8 @@ WOLFSSL_API int wolfSSL_SSL_in_init(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl); #ifndef NO_SESSION_CACHE + WOLFSSL_API int wolfSSL_SSL_CTX_remove_session(WOLFSSL_CTX* ctx, + WOLFSSL_SESSION *c); WOLFSSL_API WOLFSSL_SESSION *wolfSSL_SSL_get0_session(const WOLFSSL *s); #endif @@ -5269,6 +5269,7 @@ WOLFSSL_API int wolfSSL_dtls_cid_get_tx(WOLFSSL* ssl, unsigned char* buffer, #define TLS1_3_VERSION 0x0304 #define DTLS1_VERSION 0xFEFF #define DTLS1_2_VERSION 0xFEFD +#define DTLS1_3_VERSION 0xFEFC #include "time.h" From 34c441b121e39195f3f52e4f314e84406cfee0e8 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 20 Apr 2023 17:52:08 +1000 Subject: [PATCH 194/391] Memory Usage fixes Ed25519CheckPubKey/Ed448CheckPubKey: get the public key from certificate in a new function, wc_CertGetPubKey, that uses less memory. Set the ENCRYPT_BASE_BITS to minimal values when Curve448/Curve25519 are the largest public key algorithms. --- src/internal.c | 40 ++++------------ wolfcrypt/src/asn.c | 103 ++++++++++++++++++++++++++++++++++++++++ wolfssl/internal.h | 4 ++ wolfssl/wolfcrypt/asn.h | 5 ++ 4 files changed, 122 insertions(+), 30 deletions(-) diff --git a/src/internal.c b/src/internal.c index b7039beb74a..ae0db056cfc 100644 --- a/src/internal.c +++ b/src/internal.c @@ -5221,23 +5221,13 @@ int Ed25519CheckPubKey(WOLFSSL* ssl) /* Public key required for signing. */ if (key != NULL && !key->pubKeySet) { - DerBuffer* leaf = ssl->buffers.certificate; - DecodedCert* cert = (DecodedCert*)XMALLOC(sizeof(*cert), - ssl->heap, DYNAMIC_TYPE_DCERT); - if (cert == NULL) - ret = MEMORY_E; + const unsigned char* pubKey; + word32 pubKeySz; + ret = wc_CertGetPubKey(ssl->buffers.certificate->buffer, + ssl->buffers.certificate->length, &pubKey, &pubKeySz); if (ret == 0) { - InitDecodedCert(cert, leaf->buffer, leaf->length, ssl->heap); - ret = DecodeToKey(cert, 0); - } - if (ret == 0) { - ret = wc_ed25519_import_public(cert->publicKey, cert->pubKeySize, - key); - } - if (cert != NULL) { - FreeDecodedCert(cert); - XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT); + ret = wc_ed25519_import_public(pubKey, pubKeySz, key); } } @@ -5555,23 +5545,13 @@ int Ed448CheckPubKey(WOLFSSL* ssl) /* Public key required for signing. */ if (key != NULL && !key->pubKeySet) { - DerBuffer* leaf = ssl->buffers.certificate; - DecodedCert* cert = (DecodedCert*)XMALLOC(sizeof(*cert), ssl->heap, - DYNAMIC_TYPE_DCERT); - if (cert == NULL) - ret = MEMORY_E; + const unsigned char* pubKey; + word32 pubKeySz; + ret = wc_CertGetPubKey(ssl->buffers.certificate->buffer, + ssl->buffers.certificate->length, &pubKey, &pubKeySz); if (ret == 0) { - InitDecodedCert(cert, leaf->buffer, leaf->length, ssl->heap); - ret = DecodeToKey(cert, 0); - } - if (ret == 0) { - ret = wc_ed448_import_public(cert->publicKey, cert->pubKeySize, - key); - } - if (cert != NULL) { - FreeDecodedCert(cert); - XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT); + ret = wc_ed448_import_public(pubKey, pubKeySz, key); } } diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index c758399c3d2..974f8df7eca 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -21473,6 +21473,109 @@ int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm) #endif /* WOLFSSL_SMALL_CERT_VERIFY */ #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */ +#if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \ + (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT))) +/* ASN.1 DER decode instruction. */ +typedef struct DecodeInstr { + /* Tag expected. */ + byte tag; + /* Operation to perform: step in or go over */ + byte op:1; + /* ASN.1 item is optional. */ + byte optional:1; +} DecodeInstr; + +/* Step into ASN.1 item. */ +#define DECODE_INSTR_IN 0 +/* Step over ASN.1 item. */ +#define DECODE_INSTR_OVER 1 + +/* Get the public key data from the DER encoded X.509 certificate. + * + * Assumes data has previously been parsed for complete validity. + * + * @param [in] cert DER encoded X.509 certificate data. + * @param [in] certSz Length of DER encoding. + * @param [out] pubKey Public key data. (From the BIT_STRING.) + * @param [out] pubKeySz Length of public key data in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL. + * @return ASN_PARSE_E when certificate encoding is invalid. + */ +int wc_CertGetPubKey(const byte* cert, word32 certSz, + const unsigned char** pubKey, word32* pubKeySz) +{ + int ret = 0; + int l; + word32 o = 0; + int i; + static DecodeInstr ops[] = { + /* Outer SEQ */ + { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 }, + /* TBSCertificate: SEQ */ + { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 }, + /* Version: [0] */ + { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION, + DECODE_INSTR_OVER, 1 }, + /* CertificateSerialNumber: INT */ + { ASN_INTEGER, DECODE_INSTR_OVER, 0 }, + /* AlgorithmIdentifier: SEQ */ + { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 }, + /* issuer: SEQ */ + { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 }, + /* Validity: SEQ */ + { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 }, + /* subject: SEQ */ + { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 }, + /* subjectPublicKeyInfo SEQ */ + { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 }, + /* AlgorithmIdentifier: SEQ */ + { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 }, + /* PublicKey: BIT_STRING */ + { ASN_BIT_STRING, DECODE_INSTR_IN , 0 }, + }; + + /* Validate parameters. */ + if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) { + ret = BAD_FUNC_ARG; + } + + /* Process each instruction to take us to public key data. */ + for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) { + DecodeInstr op = ops[i]; + + /* Check the current ASN.1 item has the expected tag. */ + if (cert[o] != op.tag) { + /* If not optional then error, otherwise skip op. */ + if (!op.optional) { + ret = ASN_PARSE_E; + } + } + else { + /* Move past tag. */ + o++; + /* Get the length of ASN.1 item and move past length encoding. */ + if (GetLength(cert, &o, &l, certSz) < 0) { + ret = ASN_PARSE_E; + } + /* Skip data if required. */ + else if (op.op == DECODE_INSTR_OVER) { + o += l; + } + } + } + + if (ret == 0) { + /* Return the public key data and length. + * Skip first byte of BIT_STRING data: unused bits. */ + *pubKey = cert + o + 1; + *pubKeySz = l - 1; + } + + return ret; +} +#endif + int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) { int ret = 0; diff --git a/wolfssl/internal.h b/wolfssl/internal.h index f6f28123042..28ecf5111ae 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -1337,6 +1337,10 @@ enum { /* Integer/heap maths - support 4096-bit. */ #define ENCRYPT_BASE_BITS 4096 #endif +#elif defined(HAVE_CURVE448) + #define ENCRYPT_BASE_BITS (456 * 2) +#elif defined(HAVE_CURVE25519) + #define ENCRYPT_BASE_BITS (256 * 2) #else /* No secret from public key operation but PSK key plus length used. */ #define ENCRYPT_BASE_BITS ((MAX_PSK_ID_LEN + 2) * 8) diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 39a95096bc8..5b9e7b4f884 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -2045,6 +2045,11 @@ WOLFSSL_API int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap, const byte* pubKey, word32 pubKeySz, int pubKeyOID); #endif +#if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \ + (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT))) +WOLFSSL_LOCAL int wc_CertGetPubKey(const byte* cert, word32 certSz, + const unsigned char** pubKey, word32* pubKeySz); +#endif #ifdef WOLFSSL_CERT_REQ WOLFSSL_LOCAL int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, From 3f7aa7a3866aef17862e9404705832230db12fed Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 21 Apr 2023 11:23:47 +1000 Subject: [PATCH 195/391] ECC: max bits for a key must handle order as well The order may be 1 bit larger than prime for some curves. Handle this in calculation of maximum size of curve. SP int _sp_mont_red(): ensure m->used is never 0 when doing default implementaion. --- wolfcrypt/src/ecc.c | 12 ++++++++++-- wolfcrypt/src/sp_int.c | 4 ++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 99ee7aca214..53eaff4d746 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -227,9 +227,17 @@ ECC Curve Sizes: #else #define MAX_ECC_BITS_USE MAX_ECC_BITS_NEEDED #endif +#if !defined(WOLFSSL_CUSTOM_CURVES) && (ECC_MIN_KEY_SZ > 160) && \ + (!defined(HAVE_ECC_KOBLITZ) || (ECC_MIN_KEY_SZ > 224)) #define ECC_KEY_MAX_BITS(key) \ - ((((key) == NULL) || ((key)->dp == NULL)) ? MAX_ECC_BITS_USE \ - : (unsigned)((key)->dp->size * 8)) + ((((key) == NULL) || ((key)->dp == NULL)) ? MAX_ECC_BITS_USE : \ + ((unsigned)((key)->dp->size * 8))) +#else +/* Add one bit for cases when order is a bit greater than prime. */ +#define ECC_KEY_MAX_BITS(key) \ + ((((key) == NULL) || ((key)->dp == NULL)) ? MAX_ECC_BITS_USE : \ + ((unsigned)((key)->dp->size * 8 + 1))) +#endif /* forward declarations */ static int wc_ecc_new_point_ex(ecc_point** point, void* heap); diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 571e3a897a5..fac64425bb8 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -16552,8 +16552,8 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp) a->dp[i] = 0; } - /* Special case when modulus is 1 digit. */ - if (m->used == 1) { + /* Special case when modulus is 1 digit or less. */ + if (m->used <= 1) { /* mu = (mp * DigitMask(a, i)) & WORD_MASK */ mu = mp * a->dp[0]; /* a += mu * m */ From 44e92018b36cb51f28ff3e69bbd221f7fa7a8b9e Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 17 Apr 2023 10:09:02 +1000 Subject: [PATCH 196/391] SP int: sp_radix_size when radix 10 fix temp size SP int should be able to calculate size of encoded number for a radix of 10 when mp_int has all digits used. sp_radix_size declared a temporary mp_int of 1 greater than input. Don't need it 1 greater. Stack declaration of maximum plus one caused address sanitizer error. Changed temporary mp_int to be same size as input mp_int. --- wolfcrypt/src/sp_int.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index fac64425bb8..0ef613244a5 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -17825,12 +17825,12 @@ int sp_radix_size(const sp_int* a, int radix, int* size) *size = 1 + 1; } else { - DECL_SP_INT(t, a->used + 1); + DECL_SP_INT(t, a->used); /* Temporary to be divided by 10. */ - ALLOC_SP_INT(t, a->used + 1, err, NULL); + ALLOC_SP_INT(t, a->used, err, NULL); if (err == MP_OKAY) { - t->size = a->used + 1; + t->size = a->used; err = sp_copy(a, t); } From 5bad129c37c81fdd80d7d01cb376cef12164a22e Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 20 Apr 2023 10:59:20 +1000 Subject: [PATCH 197/391] SP int: ensure declaration of sp_ints are with valid values Move declaration of sp_ints until after checks of valid parameters. In particular, whether used field of input/s are valid. Pull implementations of algorithms out into separate functions as a pattern to fix. --- wolfcrypt/src/sp_int.c | 908 +++++++++++++++++++++++++---------------- 1 file changed, 557 insertions(+), 351 deletions(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 0ef613244a5..e10db3985e5 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -5145,7 +5145,6 @@ int sp_init_copy(sp_int* r, const sp_int* a) int sp_exch(sp_int* a, sp_int* b) { int err = MP_OKAY; - DECL_SP_INT(t, (a != NULL) ? a->used : 1); /* Validate parameters. */ if ((a == NULL) || (b == NULL)) { @@ -5156,22 +5155,28 @@ int sp_exch(sp_int* a, sp_int* b) err = MP_VAL; } - /* Create temporary for swapping. */ - ALLOC_SP_INT(t, a->used, err, NULL); if (err == MP_OKAY) { - /* Cache allocated size of a and b. */ - unsigned int asize = a->size; - unsigned int bsize = b->size; - /* Copy all of SP int: t <= a, a <= b, b <= t. */ - XMEMCPY(t, a, MP_INT_SIZEOF(a->used)); - XMEMCPY(a, b, MP_INT_SIZEOF(b->used)); - XMEMCPY(b, t, MP_INT_SIZEOF(t->used)); - /* Put back size of a and b. */ - a->size = asize; - b->size = bsize; + /* Declare temporary for swapping. */ + DECL_SP_INT(t, a->used); + + /* Create temporary for swapping. */ + ALLOC_SP_INT(t, a->used, err, NULL); + if (err == MP_OKAY) { + /* Cache allocated size of a and b. */ + unsigned int asize = a->size; + unsigned int bsize = b->size; + /* Copy all of SP int: t <- a, a <- b, b <- t. */ + XMEMCPY(t, a, MP_INT_SIZEOF(a->used)); + XMEMCPY(a, b, MP_INT_SIZEOF(b->used)); + XMEMCPY(b, t, MP_INT_SIZEOF(t->used)); + /* Put back size of a and b. */ + a->size = asize; + b->size = bsize; + } + + FREE_SP_INT(t, NULL); } - FREE_SP_INT(t, NULL); return err; } #endif /* (WOLFSSL_SP_MATH_ALL && !WOLFSSL_RSA_VERIFY_ONLY) || !NO_DH || @@ -7422,24 +7427,60 @@ int sp_sub(const sp_int* a, const sp_int* b, sp_int* r) * @param [out] r SP integer to hold result. * * @return MP_OKAY on success. - * @return MP_VAL when a, b, m or r is NULL. * @return MP_MEM when dynamic memory allocation fails. */ -int sp_addmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) +static int _sp_addmod(const sp_int* a, const sp_int* b, const sp_int* m, + sp_int* r) { int err = MP_OKAY; /* Calculate used based on digits used in a and b. */ - unsigned int used = ((a == NULL) || (b == NULL)) ? 1 : - ((a->used >= b->used) ? a->used + 1 : b->used + 1); + unsigned int used = ((a->used >= b->used) ? a->used + 1 : b->used + 1); DECL_SP_INT(t, used); + /* Allocate a temporary SP int to hold sum. */ + ALLOC_SP_INT_SIZE(t, used, err, NULL); + + if (err == MP_OKAY) { + /* Do sum. */ + err = sp_add(a, b, t); + } + if (err == MP_OKAY) { + /* Mod result. */ + err = sp_mod(t, m, r); + } + + FREE_SP_INT(t, NULL); + return err; +} + +/* Add two value and reduce: r = (a + b) % m + * + * @param [in] a SP integer to add. + * @param [in] b SP integer to add with. + * @param [in] m SP integer that is the modulus. + * @param [out] r SP integer to hold result. + * + * @return MP_OKAY on success. + * @return MP_VAL when a, b, m or r is NULL. + * @return MP_MEM when dynamic memory allocation fails. + */ +int sp_addmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) +{ + int err = MP_OKAY; + /* Validate parameters. */ if ((a == NULL) || (b == NULL) || (m == NULL) || (r == NULL)) { err = MP_VAL; } + /* Ensure a and b aren't too big a number to operate on. */ + else if (a->used >= SP_INT_DIGITS) { + err = MP_VAL; + } + else if (b->used >= SP_INT_DIGITS) { + err = MP_VAL; + } + - /* Allocate a temporary SP int to hold sum. */ - ALLOC_SP_INT_SIZE(t, used, err, NULL); #if 0 if (err == MP_OKAY) { sp_print(a, "a"); @@ -7447,23 +7488,16 @@ int sp_addmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) sp_print(m, "m"); } #endif - if (err == MP_OKAY) { - /* Do sum. */ - err = sp_add(a, b, t); + /* Do add and modular reduction. */ + err = _sp_addmod(a, b, m, r); } - if (err == MP_OKAY) { - /* Mod result. */ - err = sp_mod(t, m, r); - } - #if 0 if (err == MP_OKAY) { sp_print(r, "rma"); } #endif - FREE_SP_INT(t, NULL); return err; } #endif /* WOLFSSL_SP_MATH_ALL || WOLFSSL_CUSTOM_CURVES) || @@ -7480,32 +7514,18 @@ int sp_addmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) * @param [out] r SP integer to hold result. * * @return MP_OKAY on success. - * @return MP_VAL when a, b, m or r is NULL. * @return MP_MEM when dynamic memory allocation fails. */ -int sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) +static int _sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, + sp_int* r) { -#ifndef WOLFSSL_SP_INT_NEGATIVE int err = MP_OKAY; - unsigned int used = ((a == NULL) || (b == NULL) || (m == NULL)) ? 1 : - ((a->used >= m->used) ? - ((a->used >= b->used) ? (a->used + 1) : (b->used + 1)) : +#ifndef WOLFSSL_SP_INT_NEGATIVE + unsigned int used = ((a->used >= m->used) ? + ((a->used >= b->used) ? (a->used + 1) : (b->used + 1)) : ((b->used >= m->used)) ? (b->used + 1) : (m->used + 1)); DECL_SP_INT_ARRAY(t, used, 2); - /* Validate parameters. */ - if ((a == NULL) || (b == NULL) || (m == NULL) || (r == NULL)) { - err = MP_VAL; - } - -#if 0 - if (err == MP_OKAY) { - sp_print(a, "a"); - sp_print(b, "b"); - sp_print(m, "m"); - } -#endif - ALLOC_SP_INT_ARRAY(t, used, 2, err, NULL); if (err == MP_OKAY) { /* Reduce a to less than m. */ @@ -7533,26 +7553,55 @@ int sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) err = sp_sub(a, b, r); } -#if 0 + FREE_SP_INT_ARRAY(t, NULL); +#else /* WOLFSSL_SP_INT_NEGATIVE */ + unsigned int used = ((a->used >= b->used) ? a->used + 1 : b->used + 1); + DECL_SP_INT(t, used); + + ALLOC_SP_INT_SIZE(t, used, err, NULL); + /* Subtract b from a into temporary. */ if (err == MP_OKAY) { - sp_print(r, "rms"); + err = sp_sub(a, b, t); } -#endif + if (err == MP_OKAY) { + /* Reduce result mod m into result. */ + err = sp_mod(t, m, r); + } + FREE_SP_INT(t, NULL); +#endif /* WOLFSSL_SP_INT_NEGATIVE */ - FREE_SP_INT_ARRAY(t, NULL); return err; +} -#else /* WOLFSSL_SP_INT_NEGATIVE */ - +/* Sub b from a and reduce: r = (a - b) % m + * Result is always positive. + * + * @param [in] a SP integer to subtract from + * @param [in] b SP integer to subtract. + * @param [in] m SP integer that is the modulus. + * @param [out] r SP integer to hold result. + * + * @return MP_OKAY on success. + * @return MP_VAL when a, b, m or r is NULL. + * @return MP_MEM when dynamic memory allocation fails. + */ +int sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) +{ int err = MP_OKAY; - unsigned int used = ((a == NULL) || (b == NULL)) ? 1 : - ((a->used >= b->used) ? a->used + 1 : b->used + 1); - DECL_SP_INT(t, used); - /* Validate parameters. */ if ((a == NULL) || (b == NULL) || (m == NULL) || (r == NULL)) { err = MP_VAL; } + /* Ensure a, b and m aren't too big a number to operate on. */ + else if (a->used >= SP_INT_DIGITS) { + err = MP_VAL; + } + else if (b->used >= SP_INT_DIGITS) { + err = MP_VAL; + } + else if (m->used >= SP_INT_DIGITS) { + err = MP_VAL; + } #if 0 if (err == MP_OKAY) { @@ -7561,26 +7610,17 @@ int sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) sp_print(m, "m"); } #endif - - ALLOC_SP_INT_SIZE(t, used, err, NULL); - /* Subtract b from a into temporary. */ if (err == MP_OKAY) { - err = sp_sub(a, b, t); + /* Do submod. */ + err = _sp_submod(a, b, m, r); } - if (err == MP_OKAY) { - /* Reduce result mod m into result. */ - err = sp_mod(t, m, r); - } - #if 0 if (err == MP_OKAY) { sp_print(r, "rms"); } #endif - FREE_SP_INT(t, NULL); return err; -#endif /* WOLFSSL_SP_INT_NEGATIVE */ } #endif /* WOLFSSL_SP_MATH_ALL */ @@ -8126,7 +8166,7 @@ static void _sp_div_same_size(sp_int* a, const sp_int* d, sp_int* r) * @return MP_OKAY on success. * @return MP_VAL when operation fails - only when compiling small code. */ -static int _sp_div(sp_int* a, const sp_int* d, sp_int* r, sp_int* trial) +static int _sp_div_impl(sp_int* a, const sp_int* d, sp_int* r, sp_int* trial) { int err = MP_OKAY; unsigned int i; @@ -8299,16 +8339,17 @@ static int _sp_div(sp_int* a, const sp_int* d, sp_int* r, sp_int* trial) /* Divide a by d and return the quotient in r and the remainder in rem. * r = a / d; rem = a % d * - * @param [in] a SP integer to be divided. - * @param [in] d SP integer to divide by. - * @param [out] r SP integer that is the quotient. - * @param [out] rem SP integer that is the remainder. + * @param [in] a SP integer to be divided. + * @param [in] d SP integer to divide by. + * @param [out] r SP integer that is the quotient. + * @param [out] rem SP integer that is the remainder. + * @param [in] used Number of digits in temporaries to use. * * @return MP_OKAY on success. - * @return MP_VAL when a or d is NULL, r and rem are NULL, or d is 0. * @return MP_MEM when dynamic memory allocation fails. */ -int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) +static int _sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem, + unsigned int used) { int err = MP_OKAY; int ret; @@ -8323,94 +8364,55 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) unsigned int signD = MP_ZPOS; #endif /* WOLFSSL_SP_INT_NEGATIVE */ /* Intermediates will always be less than or equal to dividend. */ - DECL_SP_INT_ARRAY(td, (a == NULL) ? 1 : a->used + 1, 4); + DECL_SP_INT_ARRAY(td, used, 4); - /* Validate parameters. */ - if ((a == NULL) || (d == NULL) || ((r == NULL) && (rem == NULL))) { - err = MP_VAL; - } - /* a / 0 = infinity. */ - if ((err == MP_OKAY) && sp_iszero(d)) { - err = MP_VAL; - } - /* Ensure quotient result has enough memory. */ - if ((err == MP_OKAY) && (r != NULL) && (r->size < a->used - d->used + 2)) { - err = MP_VAL; - } - if ((err == MP_OKAY) && (rem != NULL)) { - /* Ensure remainder has enough memory. */ - if ((a->used <= d->used) && (rem->size < a->used + 1)) { - err = MP_VAL; +#ifdef WOLFSSL_SP_INT_NEGATIVE + /* Cache sign for results. */ + signA = a->sign; + signD = d->sign; +#endif /* WOLFSSL_SP_INT_NEGATIVE */ + + /* Handle simple case of: dividend < divisor. */ + ret = _sp_cmp_abs(a, d); + if (ret == MP_LT) { + /* a = 0 * d + a */ + if (rem != NULL) { + _sp_copy(a, rem); } - else if ((a->used > d->used) && (rem->size < d->used + 1)) { - err = MP_VAL; + if (r != NULL) { + _sp_set(r, 0); } + done = 1; } - /* May need to shift number being divided left into a new word. */ - if ((err == MP_OKAY) && (a->used == SP_INT_DIGITS)) { - int bits = SP_WORD_SIZE - (sp_count_bits(d) % SP_WORD_SIZE); - if ((bits != SP_WORD_SIZE) && - (sp_count_bits(a) + bits > SP_INT_DIGITS * SP_WORD_SIZE)) { - err = MP_VAL; + /* Handle simple case of: dividend == divisor. */ + else if (ret == MP_EQ) { + /* a = 1 * d + 0 */ + if (rem != NULL) { + _sp_set(rem, 0); } - } - -#if 0 - if (err == MP_OKAY) { - sp_print(a, "a"); - sp_print(d, "b"); - } -#endif - - if (err == MP_OKAY) { - #ifdef WOLFSSL_SP_INT_NEGATIVE - /* Cache sign for results. */ - signA = a->sign; - signD = d->sign; - #endif /* WOLFSSL_SP_INT_NEGATIVE */ - - /* Handle simple case of: dividend < divisor. */ - ret = _sp_cmp_abs(a, d); - if (ret == MP_LT) { - /* a = 0 * d + a */ - if (rem != NULL) { - _sp_copy(a, rem); - } - if (r != NULL) { - _sp_set(r, 0); - } - done = 1; + if (r != NULL) { + _sp_set(r, 1); + #ifdef WOLFSSL_SP_INT_NEGATIVE + r->sign = (signA == signD) ? MP_ZPOS : MP_NEG; + #endif /* WOLFSSL_SP_INT_NEGATIVE */ } - /* Handle simple case of: dividend == divisor. */ - else if (ret == MP_EQ) { - /* a = 1 * d + 0 */ - if (rem != NULL) { - _sp_set(rem, 0); - } - if (r != NULL) { - _sp_set(r, 1); - #ifdef WOLFSSL_SP_INT_NEGATIVE - r->sign = (signA == signD) ? MP_ZPOS : MP_NEG; - #endif /* WOLFSSL_SP_INT_NEGATIVE */ - } - done = 1; + done = 1; + } + else if (sp_count_bits(a) == sp_count_bits(d)) { + /* a is greater than d but same bit length - subtract. */ + if (rem != NULL) { + _sp_sub_off(a, d, rem, 0); + #ifdef WOLFSSL_SP_INT_NEGATIVE + rem->sign = signA; + #endif } - else if (sp_count_bits(a) == sp_count_bits(d)) { - /* a is greater than d but same bit length - subtract. */ - if (rem != NULL) { - _sp_sub_off(a, d, rem, 0); - #ifdef WOLFSSL_SP_INT_NEGATIVE - rem->sign = signA; - #endif - } - if (r != NULL) { - _sp_set(r, 1); - #ifdef WOLFSSL_SP_INT_NEGATIVE - r->sign = (signA == signD) ? MP_ZPOS : MP_NEG; - #endif /* WOLFSSL_SP_INT_NEGATIVE */ - } - done = 1; + if (r != NULL) { + _sp_set(r, 1); + #ifdef WOLFSSL_SP_INT_NEGATIVE + r->sign = (signA == signD) ? MP_ZPOS : MP_NEG; + #endif /* WOLFSSL_SP_INT_NEGATIVE */ } + done = 1; } /* Allocate temporary 'sp_int's and assign. */ @@ -8429,9 +8431,9 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) cnt--; } /* Macro always has code associated with it and checks err first. */ - ALLOC_SP_INT_ARRAY(td, a->used + 1, cnt, err, NULL); + ALLOC_SP_INT_ARRAY(td, used, cnt, err, NULL); #else - ALLOC_SP_INT_ARRAY(td, a->used + 1, 4, err, NULL); + ALLOC_SP_INT_ARRAY(td, used, 4, err, NULL); #endif } if ((!done) && (err == MP_OKAY)) { @@ -8442,7 +8444,7 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) /* Set to temporary when not reusing. */ if (sa == NULL) { sa = td[i++]; - _sp_init_size(sa, a->used + 1); + _sp_init_size(sa, used); } if (tr == NULL) { tr = td[i]; @@ -8452,7 +8454,7 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) sa = td[2]; tr = td[3]; - _sp_init_size(sa, a->used + 1); + _sp_init_size(sa, used); _sp_init_size(tr, a->used - d->used + 2); #endif sd = td[0]; @@ -8460,7 +8462,7 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) /* Initialize sizes to minimal values. */ _sp_init_size(sd, d->used + 1); - _sp_init_size(trial, a->used + 1); + _sp_init_size(trial, used); /* Move divisor to top of word. Adjust dividend as well. */ s = sp_count_bits(d); @@ -8478,7 +8480,7 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) } if ((!done) && (err == MP_OKAY) && (d->used > 0)) { /* Do division: tr = sa / d, sa = sa % d. */ - err = _sp_div(sa, d, tr, trial); + err = _sp_div_impl(sa, d, tr, trial); /* Return the remainder if required. */ if ((err == MP_OKAY) && (rem != NULL)) { /* Move result back down if moved up for divisor value. */ @@ -8506,18 +8508,84 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) } } -#if 0 + FREE_SP_INT_ARRAY(td, NULL); + return err; +} + +/* Divide a by d and return the quotient in r and the remainder in rem. + * r = a / d; rem = a % d + * + * @param [in] a SP integer to be divided. + * @param [in] d SP integer to divide by. + * @param [out] r SP integer that is the quotient. + * @param [out] rem SP integer that is the remainder. + * + * @return MP_OKAY on success. + * @return MP_VAL when a or d is NULL, r and rem are NULL, or d is 0. + * @return MP_MEM when dynamic memory allocation fails. + */ +int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) +{ + int err = MP_OKAY; + unsigned int used = 1; + + /* Validate parameters. */ + if ((a == NULL) || (d == NULL) || ((r == NULL) && (rem == NULL))) { + err = MP_VAL; + } + /* a / 0 = infinity. */ + if ((err == MP_OKAY) && sp_iszero(d)) { + err = MP_VAL; + } + /* Ensure quotient result has enough memory. */ + if ((err == MP_OKAY) && (r != NULL) && (r->size < a->used - d->used + 2)) { + err = MP_VAL; + } + if ((err == MP_OKAY) && (rem != NULL)) { + /* Ensure remainder has enough memory. */ + if ((a->used <= d->used) && (rem->size < a->used + 1)) { + err = MP_VAL; + } + else if ((a->used > d->used) && (rem->size < d->used + 1)) { + err = MP_VAL; + } + } if (err == MP_OKAY) { - if (rem != NULL) { - sp_print(rem, "rdr"); + if (a->used == SP_INT_DIGITS) { + /* May need to shift number being divided left into a new word. */ + int bits = SP_WORD_SIZE - (sp_count_bits(d) % SP_WORD_SIZE); + if ((bits != SP_WORD_SIZE) && + (sp_count_bits(a) + bits > SP_INT_DIGITS * SP_WORD_SIZE)) { + err = MP_VAL; + } + else { + used = SP_INT_DIGITS; + } } - if (r != NULL) { - sp_print(r, "rdw"); + else { + used = a->used + 1; } } -#endif - FREE_SP_INT_ARRAY(td, NULL); + if (err == MP_OKAY) { + #if 0 + sp_print(a, "a"); + sp_print(d, "b"); + #endif + /* Do operation. */ + err = _sp_div(a, d, r, rem, used); + #if 0 + if (err == MP_OKAY) { + if (rem != NULL) { + sp_print(rem, "rdr"); + } + if (r != NULL) { + sp_print(r, "rdw"); + } + } + #endif + } + return err; } #endif /* WOLFSSL_SP_MATH_ALL || !NO_DH || HAVE_ECC || \ @@ -8528,7 +8596,7 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) !defined(WOLFSSL_RSA_PUBLIC_ONLY)) #ifndef FREESCALE_LTC_TFM #ifdef WOLFSSL_SP_INT_NEGATIVE -/* Calculate the remainder of dividing a by m: r = a mod m. +/* Calculate the remainder of dividing a by m: r = a mod m. r is m. * * @param [in] a SP integer to reduce. * @param [in] m SP integer that is the modulus. @@ -11620,13 +11688,23 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #if defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFCRYPT_HAVE_ECCSI) || \ (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) || defined(OPENSSL_ALL) +/* Multiply a by b mod m and store in r: r = (a * b) mod m + * + * @param [in] a SP integer to multiply. + * @param [in] b SP integer to multiply. + * @param [in] m SP integer that is the modulus. + * @param [out] r SP integer result. + * + * @return MP_OKAY on success. + * @return MP_MEM when dynamic memory allocation fails. + */ static int _sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) { int err = MP_OKAY; - /* Create temporary for multiplication result. */ DECL_SP_INT(t, a->used + b->used); + ALLOC_SP_INT(t, a->used + b->used, err, NULL); if (err == MP_OKAY) { err = sp_init_size(t, a->used + b->used); @@ -11690,6 +11768,7 @@ int sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) } } else if (err == MP_OKAY) { + /* Do operation using temporary. */ _sp_mulmod(a, b, m, r); } @@ -11973,8 +12052,8 @@ static int _sp_invmod(const sp_int* a, const sp_int* m, sp_int* r) sp_int* u = NULL; sp_int* v = NULL; sp_int* b = NULL; - DECL_SP_INT_ARRAY(t, (m == NULL) ? 1 : (m->used + 1), 3); - DECL_SP_INT(c, (m == NULL) ? 1 : (2 * m->used + 1)); + DECL_SP_INT_ARRAY(t, m->used + 1, 3); + DECL_SP_INT(c, 2 * m->used + 1); /* Allocate SP ints: * - x3 one word larger than modulus @@ -12177,36 +12256,22 @@ int sp_invmod(const sp_int* a, const sp_int* m, sp_int* r) * @param [in] mp SP integer digit that is the bottom digit of inv(-m). * * @return MP_OKAY on success. - * @return MP_VAL when a, m or r is NULL; a is 0 or m is less than 3. * @return MP_MEM when dynamic memory allocation fails. */ -int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, +static int _sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, sp_int_digit mp) { int err = MP_OKAY; int i; int j = 0; - int s = 0; - sp_int* t = NULL; - sp_int* e = NULL; -#ifndef WOLFSSL_SP_NO_MALLOC - DECL_DYN_SP_INT_ARRAY(pre, (m == NULL) ? 1 : m->used * 2 + 1, - CT_INV_MOD_PRE_CNT + 2); -#else - DECL_SP_INT_ARRAY(pre, (m == NULL) ? 1 : m->used * 2 + 1, - CT_INV_MOD_PRE_CNT + 2); -#endif - - /* Validate parameters. */ - if ((a == NULL) || (m == NULL) || (r == NULL)) { - err = MP_VAL; - } - - /* 0 != n*m + 1 (+ve m), r*a mod 0 is always 0 (never 1) */ - if ((err == MP_OKAY) && (sp_iszero(a) || sp_iszero(m) || - ((m->used == 1) && (m->dp[0] < 3)))) { - err = MP_VAL; - } + int s = 0; + sp_int* t = NULL; + sp_int* e = NULL; +#ifndef WOLFSSL_SP_NO_MALLOC + DECL_DYN_SP_INT_ARRAY(pre, m->used * 2 + 1, CT_INV_MOD_PRE_CNT + 2); +#else + DECL_SP_INT_ARRAY(pre, m->used * 2 + 1, CT_INV_MOD_PRE_CNT + 2); +#endif #ifndef WOLFSSL_SP_NO_MALLOC ALLOC_DYN_SP_INT_ARRAY(pre, m->used * 2 + 1, CT_INV_MOD_PRE_CNT + 2, err, @@ -12351,6 +12416,48 @@ int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, return err; } +/* Calculates the multiplicative inverse in the field - constant time. + * + * Modulus (m) must be a prime and greater than 2. + * For prime m, inv = a ^ (m-2) mod m as 1 = a ^ (m-1) mod m. + * + * @param [in] a SP integer, Montgomery form, to find inverse of. + * @param [in] m SP integer this is the modulus. + * @param [out] r SP integer to hold result. + * @param [in] mp SP integer digit that is the bottom digit of inv(-m). + * + * @return MP_OKAY on success. + * @return MP_VAL when a, m or r is NULL; a is 0 or m is less than 3. + * @return MP_MEM when dynamic memory allocation fails. + */ +int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, + sp_int_digit mp) +{ + int err = MP_OKAY; + + /* Validate parameters. */ + if ((a == NULL) || (m == NULL) || (r == NULL)) { + err = MP_VAL; + } + /* Ensure m is not too big. */ + else if (m->used * 2 >= SP_INT_DIGITS) { + err = MP_VAL; + } + + /* 0 != n*m + 1 (+ve m), r*a mod 0 is always 0 (never 1) */ + if ((err == MP_OKAY) && (sp_iszero(a) || sp_iszero(m) || + ((m->used == 1) && (m->dp[0] < 3)))) { + err = MP_VAL; + } + + if (err == MP_OKAY) { + /* Do operation. */ + err = _sp_invmod_mont_ct(a, m, r, mp); + } + + return err; +} + #endif /* WOLFSSL_SP_INVMOD_MONT_CT */ @@ -13131,6 +13238,10 @@ int sp_exptmod_ex(const sp_int* b, const sp_int* e, int digits, const sp_int* m, (digits < 0)) { err = MP_VAL; } + /* Ensure m is not too big. */ + else if (m->used * 2 >= SP_INT_DIGITS) { + err = MP_VAL; + } #if 0 if (err == MP_OKAY) { @@ -13753,6 +13864,7 @@ int sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, sp_int* r) { int err = MP_OKAY; + /* Validate parameters. */ if ((b == NULL) || (e == NULL) || (m == NULL) || (r == NULL)) { err = MP_VAL; } @@ -13776,12 +13888,15 @@ int sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, sp_int* r) err = MP_VAL; } #endif + /* x mod 1 is always 0. */ else if (sp_isone(m)) { _sp_set(r, 0); } + /* b^0 mod m = 1 mod m = 1. */ else if (sp_iszero(e)) { _sp_set(r, 1); } + /* 0^x mod m = 0 mod m = 0. */ else if (sp_iszero(b)) { _sp_set(r, 0); } @@ -16442,6 +16557,39 @@ int sp_sqr(const sp_int* a, sp_int* r) #if defined(WOLFSSL_SP_MATH_ALL) || \ (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || !defined(NO_DH) || defined(HAVE_ECC) +/* Square a mod m and store in r: r = (a * a) mod m + * + * @param [in] a SP integer to square. + * @param [in] m SP integer that is the modulus. + * @param [out] r SP integer result. + * + * @return MP_OKAY on success. + * @return MP_MEM when dynamic memory allocation fails. + */ +static int _sp_sqrmod(const sp_int* a, const sp_int* m, sp_int* r) +{ + int err = MP_OKAY; + /* Create temporary for multiplication result. */ + DECL_SP_INT(t, a->used * 2); + + ALLOC_SP_INT(t, a->used * 2, err, NULL); + if (err == MP_OKAY) { + err = sp_init_size(t, a->used * 2); + } + + /* Square and reduce. */ + if (err == MP_OKAY) { + err = sp_sqr(a, t); + } + if (err == MP_OKAY) { + err = sp_mod(t, m, r); + } + + /* Dispose of an allocated SP int. */ + FREE_SP_INT(t, NULL); + return err; +} + /* Square a mod m and store in r: r = (a * a) mod m * * @param [in] a SP integer to square. @@ -16465,6 +16613,10 @@ int sp_sqrmod(const sp_int* a, const sp_int* m, sp_int* r) if ((err == MP_OKAY) && (r != m) && (a->used * 2 > r->size)) { err = MP_VAL; } + /* Ensure a is not too big. */ + if ((err == MP_OKAY) && (r == m) && (a->used * 2 > SP_INT_DIGITS)) { + err = MP_VAL; + } /* Use r as intermediate result if not same as pointer m which is needed * after first intermediate result. @@ -16477,23 +16629,8 @@ int sp_sqrmod(const sp_int* a, const sp_int* m, sp_int* r) } } else if (err == MP_OKAY) { - /* Create temporary for multiplication result. */ - DECL_SP_INT(t, a->used * 2); - ALLOC_SP_INT(t, a->used * 2, err, NULL); - if (err == MP_OKAY) { - err = sp_init_size(t, a->used * 2); - } - - /* Square and reduce. */ - if (err == MP_OKAY) { - err = sp_sqr(a, t); - } - if (err == MP_OKAY) { - err = sp_mod(t, m, r); - } - - /* Dispose of an allocated SP int. */ - FREE_SP_INT(t, NULL); + /* Do operation with temporary. */ + err = _sp_sqrmod(a, m, r); } return err; @@ -17673,6 +17810,9 @@ int sp_todecimal(const sp_int* a, char* str) *str++ = '0'; *str = '\0'; } + else if (a->used >= SP_INT_DIGITS) { + err = MP_VAL; + } else { /* Temporary that is divided by 10. */ DECL_SP_INT(t, a->used + 1); @@ -18267,6 +18407,58 @@ static WC_INLINE int sp_div_primes(const sp_int* a, int* haveRes, int* result) return err; } +/* Check whether a is prime by checking t iterations of Miller-Rabin. + * + * @param [in] a SP integer to check. + * @param [in] trials Number of trials of Miller-Rabin test to perform. + * @param [out] result MP_YES when number is prime. + * MP_NO otherwise. + * + * @return MP_OKAY on success. + * @return MP_MEM when dynamic memory allocation fails. + */ +static int _sp_prime_trials(const sp_int* a, int trials, int* result) +{ + int err = MP_OKAY; + int i; + sp_int* n1; + sp_int* r; + DECL_SP_INT_ARRAY(t, a->used + 1, 2); + DECL_SP_INT(b, a->used * 2 + 1); + + ALLOC_SP_INT_ARRAY(t, a->used + 1, 2, err, NULL); + /* Allocate number that will hold modular exponentiation result. */ + ALLOC_SP_INT(b, a->used * 2 + 1, err, NULL); + if (err == MP_OKAY) { + n1 = t[0]; + r = t[1]; + + _sp_init_size(n1, a->used + 1); + _sp_init_size(r, a->used + 1); + _sp_init_size(b, a->used * 2 + 1); + + /* Do requested number of trials of Miller-Rabin test. */ + for (i = 0; i < trials; i++) { + /* Miller-Rabin test with known small prime. */ + _sp_set(b, sp_primes[i]); + err = sp_prime_miller_rabin(a, b, result, n1, r); + if ((err != MP_OKAY) || (*result == MP_NO)) { + break; + } + } + + /* Clear temporary values. */ + sp_clear(n1); + sp_clear(r); + sp_clear(b); + } + + /* Free allocated temporary. */ + FREE_SP_INT(b, NULL); + FREE_SP_INT_ARRAY(t, NULL); + return err; +} + /* Check whether a is prime. * Checks against a number of small primes and does t iterations of * Miller-Rabin. @@ -18283,7 +18475,6 @@ static WC_INLINE int sp_div_primes(const sp_int* a, int* haveRes, int* result) int sp_prime_is_prime(const sp_int* a, int trials, int* result) { int err = MP_OKAY; - int i; int haveRes = 0; /* Validate parameters. */ @@ -18293,6 +18484,9 @@ int sp_prime_is_prime(const sp_int* a, int trials, int* result) } err = MP_VAL; } + else if (a->used * 2 >= SP_INT_DIGITS) { + err = MP_VAL; + } /* Check validity of Miller-Rabin iterations count. * Must do at least one and need a unique pre-computed prime for each * iteration. @@ -18321,48 +18515,106 @@ int sp_prime_is_prime(const sp_int* a, int trials, int* result) err = sp_div_primes(a, &haveRes, result); } + /* Check a number of iterations of Miller-Rabin with small primes. */ if ((err == MP_OKAY) && (!haveRes)) { - sp_int* n1; - sp_int* r; - DECL_SP_INT_ARRAY(t, a->used + 1, 2); - DECL_SP_INT(b, a->used * 2 + 1); - - ALLOC_SP_INT_ARRAY(t, a->used + 1, 2, err, NULL); - /* Allocate number that will hold modular exponentiation result. */ - ALLOC_SP_INT(b, a->used * 2 + 1, err, NULL); - if (err == MP_OKAY) { - n1 = t[0]; - r = t[1]; - - _sp_init_size(n1, a->used + 1); - _sp_init_size(r, a->used + 1); - _sp_init_size(b, a->used * 2 + 1); - - /* Do requested number of trials of Miller-Rabin test. */ - for (i = 0; i < trials; i++) { - /* Miller-Rabin test with known small prime. */ - _sp_set(b, sp_primes[i]); - err = sp_prime_miller_rabin(a, b, result, n1, r); - if ((err != MP_OKAY) || (*result == MP_NO)) { - break; - } + err = _sp_prime_trials(a, trials, result); + } + + RESTORE_VECTOR_REGISTERS(); + + return err; +} + +#ifndef WC_NO_RNG +/* Check whether a is prime by doing t iterations of Miller-Rabin. + * + * t random numbers should give a (1/4)^t chance of a false prime. + * + * @param [in] a SP integer to check. + * @param [in] trials Number of iterations of Miller-Rabin test to perform. + * @param [out] result MP_YES when number is prime. + * MP_NO otherwise. + * @param [in] rng Random number generator for Miller-Rabin testing. + * + * @return MP_OKAY on success. + * @return MP_VAL when a, result or rng is NULL. + * @return MP_MEM when dynamic memory allocation fails. + */ +static int _sp_prime_random_trials(const sp_int* a, int trials, int* result, + WC_RNG* rng) +{ + int err = MP_OKAY; + int bits = sp_count_bits(a); + word32 baseSz = ((word32)bits + 7) / 8; + DECL_SP_INT_ARRAY(ds, a->used + 1, 2); + DECL_SP_INT_ARRAY(d, a->used * 2 + 1, 2); + + ALLOC_SP_INT_ARRAY(ds, a->used + 1, 2, err, NULL); + ALLOC_SP_INT_ARRAY(d, a->used * 2 + 1, 2, err, NULL); + if (err == MP_OKAY) { + sp_int* c = ds[0]; + sp_int* n1 = ds[1]; + sp_int* b = d[0]; + sp_int* r = d[1]; + + _sp_init_size(c , a->used + 1); + _sp_init_size(n1, a->used + 1); + _sp_init_size(b , a->used * 2 + 1); + _sp_init_size(r , a->used * 2 + 1); + + _sp_sub_d(a, 2, c); + + bits &= SP_WORD_MASK; + + /* Keep trying random numbers until all trials complete. */ + while (trials > 0) { + /* Generate random trial number. */ + err = wc_RNG_GenerateBlock(rng, (byte*)b->dp, baseSz); + if (err != MP_OKAY) { + break; + } + b->used = a->used; + #ifdef BIG_ENDIAN_ORDER + /* Fix top digit if fewer bytes than a full digit generated. */ + if (((baseSz * 8) & SP_WORD_MASK) != 0) { + b->dp[b->used-1] >>= + SP_WORD_SIZE - ((baseSz * 8) & SP_WORD_MASK); } + #endif /* BIG_ENDIAN_ORDER */ - /* Clear temporary values. */ - sp_clear(n1); - sp_clear(r); - sp_clear(b); - } + /* Ensure the top word has no more bits than necessary. */ + if (bits > 0) { + b->dp[b->used - 1] &= ((sp_int_digit)1 << bits) - 1; + sp_clamp(b); + } - /* Free allocated temporary. */ - FREE_SP_INT(b, NULL); - FREE_SP_INT_ARRAY(t, NULL); - } + /* Can't use random value it is: 0, 1, a-2, a-1, >= a */ + if ((sp_cmp_d(b, 2) != MP_GT) || (_sp_cmp(b, c) != MP_LT)) { + continue; + } - RESTORE_VECTOR_REGISTERS(); + /* Perform Miller-Rabin test with random value. */ + err = sp_prime_miller_rabin(a, b, result, n1, r); + if ((err != MP_OKAY) || (*result == MP_NO)) { + break; + } + + /* Trial complete. */ + trials--; + } - return err; + /* Zeroize temporary values used when generating private prime. */ + sp_forcezero(n1); + sp_forcezero(r); + sp_forcezero(b); + sp_forcezero(c); + } + + FREE_SP_INT_ARRAY(d, NULL); + FREE_SP_INT_ARRAY(ds, NULL); + return err; } +#endif /*!WC_NO_RNG */ /* Check whether a is prime. * Checks against a number of small primes and does t iterations of @@ -18383,16 +18635,15 @@ int sp_prime_is_prime_ex(const sp_int* a, int trials, int* result, WC_RNG* rng) int err = MP_OKAY; int ret = MP_YES; int haveRes = 0; -#ifndef WC_NO_RNG - sp_int *b = NULL; - sp_int *c = NULL; - sp_int *n1 = NULL; - sp_int *r = NULL; -#endif /* WC_NO_RNG */ if ((a == NULL) || (result == NULL) || (rng == NULL)) { err = MP_VAL; } +#ifndef WC_NO_RNG + if ((err == MP_OKAY) && (a->used * 2 >= SP_INT_DIGITS)) { + err = MP_VAL; + } +#endif #ifdef WOLFSSL_SP_INT_NEGATIVE if ((err == MP_OKAY) && (a->sign == MP_NEG)) { err = MP_VAL; @@ -18424,77 +18675,9 @@ int sp_prime_is_prime_ex(const sp_int* a, int trials, int* result, WC_RNG* rng) } #ifndef WC_NO_RNG - /* now do a miller rabin with up to t random numbers, this should - * give a (1/4)^t chance of a false prime. */ + /* Check a number of iterations of Miller-Rabin with random large values. */ if ((err == MP_OKAY) && (!haveRes)) { - int bits = sp_count_bits(a); - word32 baseSz = ((word32)bits + 7) / 8; - DECL_SP_INT_ARRAY(ds, a->used + 1, 2); - DECL_SP_INT_ARRAY(d, a->used * 2 + 1, 2); - - ALLOC_SP_INT_ARRAY(ds, a->used + 1, 2, err, NULL); - ALLOC_SP_INT_ARRAY(d, a->used * 2 + 1, 2, err, NULL); - if (err == MP_OKAY) { - c = ds[0]; - n1 = ds[1]; - b = d[0]; - r = d[1]; - - _sp_init_size(c , a->used + 1); - _sp_init_size(n1, a->used + 1); - _sp_init_size(b , a->used * 2 + 1); - _sp_init_size(r , a->used * 2 + 1); - - _sp_sub_d(a, 2, c); - - bits &= SP_WORD_MASK; - - /* Keep trying random numbers until all trials complete. */ - while (trials > 0) { - /* Generate random trial number. */ - err = wc_RNG_GenerateBlock(rng, (byte*)b->dp, baseSz); - if (err != MP_OKAY) { - break; - } - b->used = a->used; - #ifdef BIG_ENDIAN_ORDER - /* Fix top digit if fewer bytes than a full digit generated. */ - if (((baseSz * 8) & SP_WORD_MASK) != 0) { - b->dp[b->used-1] >>= - SP_WORD_SIZE - ((baseSz * 8) & SP_WORD_MASK); - } - #endif /* BIG_ENDIAN_ORDER */ - - /* Ensure the top word has no more bits than necessary. */ - if (bits > 0) { - b->dp[b->used - 1] &= ((sp_int_digit)1 << bits) - 1; - sp_clamp(b); - } - - /* Can't use random value it is: 0, 1, a-2, a-1, >= a */ - if ((sp_cmp_d(b, 2) != MP_GT) || (_sp_cmp(b, c) != MP_LT)) { - continue; - } - - /* Perform Miller-Rabin test with random value. */ - err = sp_prime_miller_rabin(a, b, &ret, n1, r); - if ((err != MP_OKAY) || (ret == MP_NO)) { - break; - } - - /* Trial complete. */ - trials--; - } - - /* Zeroize temporary values used when generating private prime. */ - sp_forcezero(n1); - sp_forcezero(r); - sp_forcezero(b); - sp_forcezero(c); - } - - FREE_SP_INT_ARRAY(d, NULL); - FREE_SP_INT_ARRAY(ds, NULL); + err = _sp_prime_random_trials(a, trials, &ret, rng); } #else (void)trials; @@ -18693,39 +18876,15 @@ int sp_gcd(const sp_int* a, const sp_int* b, sp_int* r) * @param [out] r SP integer to hold result. * * @return MP_OKAY on success. - * @return MP_VAL when a, b or r is NULL; or a or b is zero. * @return MP_MEM when dynamic memory allocation fails. */ -int sp_lcm(const sp_int* a, const sp_int* b, sp_int* r) +static int _sp_lcm(const sp_int* a, const sp_int* b, sp_int* r) { int err = MP_OKAY; /* Determine maximum digit length numbers will reach. */ - unsigned int used = ((a == NULL) || (b == NULL)) ? 1 : - (a->used >= b->used ? a->used + 1: b->used + 1); + unsigned int used = ((a->used >= b->used) ? a->used + 1: b->used + 1); DECL_SP_INT_ARRAY(t, used, 2); - /* Validate parameters. */ - if ((a == NULL) || (b == NULL) || (r == NULL)) { - err = MP_VAL; - } -#ifdef WOLFSSL_SP_INT_NEGATIVE - /* Ensure a and b are positive. */ - else if ((a->sign == MP_NEG) || (b->sign >= MP_NEG)) { - err = MP_VAL; - } -#endif - /* Ensure r has space for maximumal result. */ - else if (r->size < a->used + b->used) { - err = MP_VAL; - } - - /* LCM of 0 and any number is undefined as 0 is not in the set of values - * being used. - */ - if ((err == MP_OKAY) && (mp_iszero(a) || mp_iszero(b))) { - err = MP_VAL; - } - ALLOC_SP_INT_ARRAY(t, used, 2, err, NULL); if (err == MP_OKAY) { _sp_init_size(t[0], used); @@ -18769,6 +18928,53 @@ int sp_lcm(const sp_int* a, const sp_int* b, sp_int* r) return err; } +/* Calculates the Lowest Common Multiple (LCM) of a and b and stores in r. + * Smallest number divisible by both numbers. + * + * a and b are positive integers. + * + * @param [in] a SP integer of first operand. + * @param [in] b SP integer of second operand. + * @param [out] r SP integer to hold result. + * + * @return MP_OKAY on success. + * @return MP_VAL when a, b or r is NULL; or a or b is zero. + * @return MP_MEM when dynamic memory allocation fails. + */ +int sp_lcm(const sp_int* a, const sp_int* b, sp_int* r) +{ + int err = MP_OKAY; + + /* Validate parameters. */ + if ((a == NULL) || (b == NULL) || (r == NULL)) { + err = MP_VAL; + } +#ifdef WOLFSSL_SP_INT_NEGATIVE + /* Ensure a and b are positive. */ + else if ((a->sign == MP_NEG) || (b->sign >= MP_NEG)) { + err = MP_VAL; + } +#endif + /* Ensure r has space for maximumal result. */ + else if (r->size < a->used + b->used) { + err = MP_VAL; + } + + /* LCM of 0 and any number is undefined as 0 is not in the set of values + * being used. + */ + if ((err == MP_OKAY) && (mp_iszero(a) || mp_iszero(b))) { + err = MP_VAL; + } + + if (err == MP_OKAY) { + /* Do operation. */ + err = _sp_lcm(a, b, r); + } + + return err; +} + #endif /* WOLFSSL_SP_MATH_ALL && !NO_RSA && WOLFSSL_KEY_GEN */ /* Returns the run time settings. From af408e629709a66ab845baa0ad5567959d9e8ed1 Mon Sep 17 00:00:00 2001 From: jordan Date: Tue, 18 Apr 2023 10:51:38 -0500 Subject: [PATCH 198/391] Fix out-of-bounds write in fp_mod_2d. --- wolfcrypt/src/tfm.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/wolfcrypt/src/tfm.c b/wolfcrypt/src/tfm.c index aa4b441d8ab..fe8f5bffe9a 100644 --- a/wolfcrypt/src/tfm.c +++ b/wolfcrypt/src/tfm.c @@ -1010,6 +1010,13 @@ void fp_mod_2d(fp_int *a, int b, fp_int *c) } bmax = ((unsigned int)b + DIGIT_BIT - 1) / DIGIT_BIT; + + /* If a is negative and bmax is larger than FP_SIZE, then the + * result can't fit within c. Just return. */ + if (c->sign == FP_NEG && bmax > FP_SIZE) { + return; + } + /* zero digits above the last digit of the modulus */ for (x = bmax; x < (unsigned int)c->used; x++) { c->dp[x] = 0; From cc3988bcc5bcd5bd02097b5cb5ec9a86721234ec Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 24 Apr 2023 09:15:31 +1000 Subject: [PATCH 199/391] BN_to_ASN1_INTEGER: fix handling of padding Incorrect calculation of when padding byte needed and consequently adding byte manually when properly handled by SetASNInt(). --- src/ssl_asn1.c | 9 +------- tests/api.c | 63 ++++++++++++++++++++++++++++++-------------------- 2 files changed, 39 insertions(+), 33 deletions(-) diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index ee0a5884c91..5a09e2742b2 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -1333,15 +1333,11 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_BN_to_ASN1_INTEGER(const WOLFSSL_BIGNUM *bn, /* Get length in bits of encoded number. */ numBits = wolfSSL_BN_num_bits(bn); /* Leading zero required if most-significant byte has top bit set. */ - if ((numBits % 8) == 7) { + if ((numBits > 0) && (numBits % 8) == 0) { firstByte = 0x80; } /* Get length of header based on length of number. */ length = SetASNInt(len, firstByte, NULL); - if (firstByte != 0) { - /* Add one for leading zero. */ - length++; - } /* Add number of bytes to encode number. */ length += len; @@ -1359,9 +1355,6 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_BN_to_ASN1_INTEGER(const WOLFSSL_BIGNUM *bn, a->data[idx] = 0; } else { - if (firstByte != 0) { - a->data[idx++] = 0; - } /* Add encoded number. */ len = wolfSSL_BN_bn2bin(bn, a->data + idx); if (len < 0) { diff --git a/tests/api.c b/tests/api.c index e66dbc5517b..585d8c9cdec 100644 --- a/tests/api.c +++ b/tests/api.c @@ -31421,22 +31421,25 @@ static int test_wolfSSL_ASN1_INTEGER_BN(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) ASN1_INTEGER* ai; - ASN1_INTEGER* a2; - BIGNUM* a; + ASN1_INTEGER* ai2; + BIGNUM* bn; + BIGNUM* bn2; ai = ASN1_INTEGER_new(); AssertNotNull(ai); + bn2 = BN_new(); + AssertNotNull(bn2); /* Invalid parameter testing. */ - AssertNull(a = ASN1_INTEGER_to_BN(NULL, NULL)); - AssertNull(a2 = BN_to_ASN1_INTEGER(NULL, NULL)); + AssertNull(bn = ASN1_INTEGER_to_BN(NULL, NULL)); + AssertNull(ai2 = BN_to_ASN1_INTEGER(NULL, NULL)); /* at the moment hard setting since no set function */ ai->data[0] = 0xff; /* No DER encoding. */ ai->length = 1; #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY) - AssertNotNull(a = ASN1_INTEGER_to_BN(ai, NULL)); - BN_free(a); + AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); + BN_free(bn); #else AssertNull(ASN1_INTEGER_to_BN(ai, NULL)); #endif @@ -31447,8 +31450,8 @@ static int test_wolfSSL_ASN1_INTEGER_BN(void) ai->length = 3; #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY) /* Interpreted as a number 0x020403. */ - AssertNotNull(a = ASN1_INTEGER_to_BN(ai, NULL)); - BN_free(a); + AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); + BN_free(bn); #else AssertNull(ASN1_INTEGER_to_BN(ai, NULL)); #endif @@ -31457,37 +31460,47 @@ static int test_wolfSSL_ASN1_INTEGER_BN(void) ai->data[1] = 0x01; /* length of integer */ ai->data[2] = 0x03; ai->length = 3; - AssertNotNull(a = ASN1_INTEGER_to_BN(ai, NULL)); - AssertNotNull(a2 = BN_to_ASN1_INTEGER(a, NULL)); - AssertIntEQ(ASN1_INTEGER_cmp(ai, a2), 0); + AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); + AssertNotNull(ai2 = BN_to_ASN1_INTEGER(bn, NULL)); + AssertIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); + AssertNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); + AssertIntEQ(BN_cmp(bn, bn2), 0); ai->data[0] = 0x02; /* tag for ASN_INTEGER */ - ai->data[1] = 0x01; /* length of integer */ - ai->data[2] = 0xff; - ai->length = 3; - AssertNotNull(a = ASN1_INTEGER_to_BN(ai, a)); - AssertNotNull(a2 = BN_to_ASN1_INTEGER(a, a2)); - AssertIntEQ(ASN1_INTEGER_cmp(ai, a2), 0); + ai->data[1] = 0x02; /* length of integer */ + ai->data[2] = 0x00; /* padding byte to ensure positive */ + ai->data[3] = 0xff; + ai->length = 4; + AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); + AssertNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); + AssertIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); + AssertNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); + AssertIntEQ(BN_cmp(bn, bn2), 0); ai->data[0] = 0x02; /* tag for ASN_INTEGER */ ai->data[1] = 0x01; /* length of integer */ ai->data[2] = 0x00; ai->length = 3; - AssertNotNull(a = ASN1_INTEGER_to_BN(ai, a)); - AssertNotNull(a2 = BN_to_ASN1_INTEGER(a, a2)); - AssertIntEQ(ASN1_INTEGER_cmp(ai, a2), 0); + AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); + AssertNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); + AssertIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); + AssertNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); + AssertIntEQ(BN_cmp(bn, bn2), 0); ai->data[0] = 0x02; /* tag for ASN_INTEGER */ ai->data[1] = 0x01; /* length of integer */ ai->data[2] = 0x01; ai->length = 3; ai->negative = 1; - AssertNotNull(a = ASN1_INTEGER_to_BN(ai, a)); - AssertNotNull(a2 = BN_to_ASN1_INTEGER(a, a2)); - AssertIntEQ(ASN1_INTEGER_cmp(ai, a2), 0); + AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); + AssertNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); + AssertIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); + AssertNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); + AssertIntEQ(BN_cmp(bn, bn2), 0); - BN_free(a); - ASN1_INTEGER_free(a2); + BN_free(bn2); + BN_free(bn); + ASN1_INTEGER_free(ai2); ASN1_INTEGER_free(ai); res = TEST_RES_CHECK(1); From 725a7578f7c34e5c7a211b8eef0cee7bfce700a6 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 20 Apr 2023 08:27:44 +1000 Subject: [PATCH 200/391] SP int: missing brace Missing a brace in sp_exptmod_ex(). --- wolfcrypt/src/sp_int.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index e10db3985e5..5c2f7d1c8bf 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -13341,7 +13341,7 @@ int sp_exptmod_ex(const sp_int* b, const sp_int* e, int digits, const sp_int* m, #if defined(WOLFSSL_SP_MATH_ALL) || !defined(NO_DH) || defined(OPENSSL_ALL) #if (defined(WOLFSSL_RSA_VERIFY_ONLY) || defined(WOLFSSL_RSA_PUBLIC_ONLY)) && \ defined(NO_DH) - if ((!done) && (err == MP_OKAY)) + if ((!done) && (err == MP_OKAY)) { /* Use non-constant time version - fastest. */ err = sp_exptmod_nct(b, e, m, r); } From e47007e73794a6d8ef061582ba11aebb8328a3be Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Fri, 21 Apr 2023 16:05:20 -0500 Subject: [PATCH 201/391] remove buggy+bug-prone WOLFSSL_NO_XOR_OPS setup in settings.h. --- wolfssl/wolfcrypt/settings.h | 6 ------ 1 file changed, 6 deletions(-) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index c2b63f6433b..9953ff6d2f0 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2735,12 +2735,6 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_HAVE_PRF #endif -#if defined(NO_AES) && defined(NO_DES3) && !defined(HAVE_CAMELLIA) && \ - !defined(WOLFSSL_HAVE_PRF) && defined(NO_PWDBASED) - #undef WOLFSSL_NO_XOR_OPS - #define WOLFSSL_NO_XOR_OPS -#endif - #if defined(NO_ASN) && defined(WOLFCRYPT_ONLY) && !defined(WOLFSSL_WOLFSSH) #undef WOLFSSL_NO_INT_ENCODE #define WOLFSSL_NO_INT_ENCODE From ccd4d5b3d493b20e866b014f6bc79ffa56c2149e Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Fri, 21 Apr 2023 16:05:43 -0500 Subject: [PATCH 202/391] fix typos in configure.ac (from shellcheck --severity=warning). --- configure.ac | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/configure.ac b/configure.ac index 3e260a90e7a..1c87cf180e2 100644 --- a/configure.ac +++ b/configure.ac @@ -186,10 +186,10 @@ AC_ARG_ENABLE([harden-tls], if test "x$ENABLED_HARDEN_TLS" != "xno" then - if test "x$ENABLED_HARDEN_TLS" == "xyes" || test "x$ENABLED_HARDEN_TLS" == "x112" + if test "x$ENABLED_HARDEN_TLS" = "xyes" || test "x$ENABLED_HARDEN_TLS" = "x112" then AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS=112" - elif test "x$ENABLED_HARDEN_TLS" == "x128" + elif test "x$ENABLED_HARDEN_TLS" = "x128" then AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HARDEN_TLS=128" else @@ -1616,7 +1616,7 @@ then fi if test "x$ENABLED_PSA" != "xyes" && \ - (test "x$PSA_LIB"! = "x" || test "x$PSA_INCLUDE" != "x" || test "x$PSA_LIB_NAME" != "x" ) + (test "x$PSA_LIB" != "x" || test "x$PSA_INCLUDE" != "x" || test "x$PSA_LIB_NAME" != "x" ) then AC_MSG_ERROR([to use PSA you need to enable it with --enable-psa]) fi @@ -4006,7 +4006,7 @@ fi if test "$ENABLED_ASN" = "no" && test "$ENABLED_DSA" = "no" && \ test "$ENABLED_DH" = "no" && test "$ENABLED_ECC" = "no" && \ test "$ENABLED_RSA" = "no" && test "$ENABLED_OPENSSLEXTRA" = "no" && \ - test "$ENABLED_OPENSSLALL" ="yes" + test "$ENABLED_OPENSSLALL" = "yes" then ENABLED_SP_MATH_ALL="no" ENABLED_FASTMATH="no" @@ -4068,7 +4068,7 @@ then then AC_MSG_ERROR([You need to enable both DTLS and TLSv1.3 to use DTLSv1.3]) fi - if test "x$ENABLED_SEND_HRR_COOKIE" == "xundefined" + if test "x$ENABLED_SEND_HRR_COOKIE" = "xundefined" then AC_MSG_NOTICE([DTLSv1.3 is enabled, enabling HRR cookie]) AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_SEND_HRR_COOKIE" @@ -5234,7 +5234,7 @@ then fi if test "$ENABLED_TLS13_EARLY_DATA" = "yes" then - if test "x$ENABLED_TLS13" = "xno" && test "X$ENABLED_ALL" = "xno" + if test "x$ENABLED_TLS13" = "xno" && test "x$ENABLED_ALL" = "xno" then AC_MSG_ERROR([cannot enable earlydata without enabling tls13.]) fi @@ -6085,7 +6085,7 @@ then AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_ALT_CERT_CHAINS" fi - if test "xENABLE_IP_ALT_NAME" = "xno" + if test "x$ENABLE_IP_ALT_NAME" = "xno" then ENABLE_IP_ALT_NAME="yes" AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_IP_ALT_NAME" @@ -7538,7 +7538,7 @@ fi if test -n "$MPI_MAX_KEY_BITS" -o -n "$WITH_MAX_ECC_BITS"; then if test -n "$MAX_MPI_KEY_BITS" -a -n "$WITH_MAX_ECC_BITS"; then - if test -n "$MAX_MPI_KEY_BITS" -lt "$WITH_MAX_ECC_BITS"; then + if test "$MAX_MPI_KEY_BITS" -lt "$WITH_MAX_ECC_BITS"; then MPI_MAX_KEY_BITS="$WITH_MAX_ECC_BITS" fi elif test -n "$WITH_MAX_ECC_BITS"; then @@ -8681,9 +8681,9 @@ echo "#endif" >> $OPTION_FILE echo "" >> $OPTION_FILE # check for supported command to trim option with -if colrm &> /dev/null; then +if colrm >/dev/null 2>&1 /dev/null; then +elif cut >/dev/null 2>&1 Date: Mon, 24 Apr 2023 14:51:55 -0600 Subject: [PATCH 203/391] Async sniffer: don't retry if seeing non-pending error (#6220) * Async sniffer: don't retry if seeing non-pending error * Print error messages when decrypting from queue * Zeroize the SessionTable in ssl_FreeSniffer() --------- Co-authored-by: Lealem Amedie --- src/sniffer.c | 2 ++ sslSniffer/sslSnifferTest/snifftest.c | 10 +++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/sniffer.c b/src/sniffer.c index cbd17ae94ec..37dd73fa6e0 100644 --- a/src/sniffer.c +++ b/src/sniffer.c @@ -831,6 +831,7 @@ static void FreeSnifferSession(SnifferSession* session) #endif } XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION); + XMEMSET(session, 0, sizeof(SnifferSession)); } @@ -855,6 +856,7 @@ void ssl_FreeSniffer(void) FreeSnifferSession(removeSession); } } + XMEMSET(SessionTable, 0, sizeof(SessionTable)); SessionCount = 0; /* Then server (wolfSSL_CTX) */ diff --git a/sslSniffer/sslSnifferTest/snifftest.c b/sslSniffer/sslSnifferTest/snifftest.c index 060e86aa4ee..d3ba59d6966 100644 --- a/sslSniffer/sslSnifferTest/snifftest.c +++ b/sslSniffer/sslSnifferTest/snifftest.c @@ -572,12 +572,16 @@ static int SnifferAsyncPollQueue(byte** data, char* err, SSLInfo* sslInfo, ret = ssl_DecodePacketAsync(asyncQueue[i].packet, asyncQueue[i].length, 0, data, err, sslInfo, NULL); asyncQueue[i].lastRet = ret; - if (ret >= 0) { + if (ret != WC_PENDING_E) { + if (ret < 0) { + printf("ssl_Decode ret = %d, %s on packet number %d\n", + ret, err, asyncQueue[i].packetNumber); + } /* done, so free and break to process below */ XFREE(asyncQueue[i].packet, NULL, DYNAMIC_TYPE_TMP_BUFFER); asyncQueue[i].packet = NULL; - if (ret > 0) { - /* decrypted some data, so return */ + if (ret != 0) { + /* decrypted some data or found error, so return */ break; } } From 88efa717a2bf96451af55c9c12c7d71b1db47d8c Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 21 Apr 2023 13:04:42 +1000 Subject: [PATCH 204/391] Memory usage improvements TLS 1.3 Server: don't cache the messages for Ed25519/Ed448 when doing TLS 1.3. ASN DecodeCertInternal: Call GetCertName for issuer and subject after freeing the dataASN. --- src/tls13.c | 24 +++++++ wolfcrypt/src/asn.c | 163 ++++++++++++++++++++++++++------------------ 2 files changed, 122 insertions(+), 65 deletions(-) diff --git a/src/tls13.c b/src/tls13.c index 2db8e76b2fd..9ef9c283855 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -11116,6 +11116,30 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, echInOutIdx = *inOutIdx; #endif ret = DoTls13ClientHello(ssl, input, inOutIdx, size); + #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \ + ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \ + (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH))) + if ((ssl->options.resuming || !ssl->options.verifyPeer || + !IsAtLeastTLSv1_2(ssl) || IsAtLeastTLSv1_3(ssl->version)) + #ifdef WOLFSSL_DTLS13 + && (!ssl->options.dtls) + #endif + ) { + #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) + if (ret != WC_PENDING_E && ret != OCSP_WANT_READ) + #endif + { + ssl->options.cacheMessages = 0; + if ((ssl->hsHashes != NULL) && + (ssl->hsHashes->messages != NULL)) { + ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length); + XFREE(ssl->hsHashes->messages, ssl->heap, + DYNAMIC_TYPE_HASHES); + ssl->hsHashes->messages = NULL; + } + } + } + #endif #if defined(HAVE_ECH) if (ret == 0) { echX = TLSX_Find(ssl->extensions, TLSX_ECH); diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 974f8df7eca..dfe9817a78b 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -20084,6 +20084,12 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, byte version; word32 idx; word32 serialSz; + const unsigned char* issuer = NULL; + word32 issuerSz = 0; + const unsigned char* subject = NULL; + word32 subjectSz = 0; + word32 pubKeyOffset = 0; + word32 pubKeyEnd = 0; int done = 0; CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap); @@ -20116,6 +20122,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, if (ret == 0) { int i; + pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset; /* Set fields extracted from data. */ cert->version = version; cert->serialSz = (int)serialSz; @@ -20147,41 +20154,26 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source); cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source); - /* Get the issuer name and calculate hash. */ - idx = dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset; - ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, - cert->source, &idx, - dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset); + /* Get the issuer name. */ + issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset; + issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset - + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset; } if (ret == 0) { - /* Get the subject name and calculate hash. */ - idx = dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset; - ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT, - cert->source, &idx, - dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset); + /* Get the subject name. */ + subject = cert->source + + dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset; + subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset - + dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset; } - if (ret == 0) { - /* Determine if self signed by comparing issuer and subject hashes. */ - #ifdef WOLFSSL_CERT_REQ - if (cert->isCSR) - cert->selfSigned = 1; - else - #endif - { - cert->selfSigned = XMEMCMP(cert->issuerHash, cert->subjectHash, - KEYID_SIZE) == 0 ? 1 : 0; - } - - if (stopAtPubKey) { - /* Return any bad date error through badDateRet and return offset of - * subjectPublicKeyInfo. - */ - if (badDateRet != NULL) { - *badDateRet = badDate; - } - ret = (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset; - done = 1; + if ((ret == 0) && (stopAtPubKey)) { + /* Return any bad date error through badDateRet and return offset of + * subjectPublicKeyInfo. + */ + if (badDateRet != NULL) { + *badDateRet = badDate; } + done = 1; } if ((ret == 0) && (!done)) { @@ -20251,11 +20243,8 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, #endif } if ((ret == 0) && (!done)) { - /* Parse the public key. */ - idx = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset; - ret = GetCertKey(cert, cert->source, &idx, - dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset); - if ((ret == 0) && stopAfterPubKey) { + pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset; + if (stopAfterPubKey) { /* Return any bad date error through badDateRed and return offset * after subjectPublicKeyInfo. */ @@ -20290,7 +20279,42 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, /* Dispose of memory before allocating for extension decoding. */ FREE_ASNGETDATA(dataASN, cert->heap); - if ((ret == 0) && (!done) && (cert->extensions != NULL)) { + if ((ret == 0) && (issuer != NULL)) { + idx = 0; + /* Put issuer into cert and calculate hash. */ + ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer, + &idx, issuerSz); + } + if ((ret == 0) && (subject != NULL)) { + idx = 0; + /* Put subject into cert and calculate hash. */ + ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT, + subject, &idx, subjectSz); + } + if (ret == 0) { + /* Determine if self signed by comparing issuer and subject hashes. */ + #ifdef WOLFSSL_CERT_REQ + if (cert->isCSR) { + cert->selfSigned = 1; + } + else + #endif + { + cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash, + KEYID_SIZE) == 0); + } + if (stopAtPubKey) { + ret = pubKeyOffset; + } + } + + if ((ret == 0) && (!stopAtPubKey)) { + /* Parse the public key. */ + idx = pubKeyOffset; + ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd); + } + if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) && + (cert->extensions != NULL)) { /* Decode the extension data starting at [3]. */ ret = DecodeCertExtensions(cert); if (criticalExt != NULL) { @@ -21260,6 +21284,10 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, word32 sigParamsSz = 0; const byte* caName = NULL; word32 caNameLen = 0; +#ifndef NO_SKID + const byte* akiData = NULL; + word32 akiLen = 0; +#endif (void)req; (void)heap; @@ -21269,17 +21297,6 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, } ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap); -#ifdef WOLFSSL_SMALL_STACK - if (ret == 0) { - sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, - DYNAMIC_TYPE_SIGNATURE); - if (sigCtx == NULL) { - ret = MEMORY_E; - } - } -#endif - - InitSignatureCtx(sigCtx, heap, INVALID_DEVID); if ((ret == 0) && (!req)) { /* Clear dynamic data for certificate items. */ @@ -21379,16 +21396,22 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, #endif } +#ifndef NO_SKID + if ((ret == 0) && (pubKey == NULL) && !req) { + akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data; + akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length; + } +#endif + + FREE_ASNGETDATA(dataASN, heap); + /* If no public passed, then find the CA. */ if ((ret == 0) && (pubKey == NULL)) { #ifndef NO_SKID /* Find the AKI extension in list of extensions and get hash. */ - if ((!req) && - (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) { + if ((!req) && (akiData != NULL)) { /* TODO: test case */ - ret = GetAKIHash(dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data, - dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length, - hash, &extAuthKeyIdSet, heap); + ret = GetAKIHash(akiData, akiLen, hash, &extAuthKeyIdSet, heap); } /* Get the CA by hash one was found. */ @@ -21417,22 +21440,32 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, } } - FREE_ASNGETDATA(dataASN, heap); - if (ret == 0) { - /* Check signature. */ - ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz, pubKeyOID, - sig, sigSz, sigOID, sigParams, sigParamsSz, NULL); - if (ret != 0) { - WOLFSSL_MSG("Confirm signature failed"); + #ifdef WOLFSSL_SMALL_STACK + sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, + DYNAMIC_TYPE_SIGNATURE); + if (sigCtx == NULL) { + ret = MEMORY_E; + } + if (ret == 0) + #endif + { + InitSignatureCtx(sigCtx, heap, INVALID_DEVID); + + /* Check signature. */ + ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz, + pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz, NULL); + if (ret != 0) { + WOLFSSL_MSG("Confirm signature failed"); + } + + FreeSignatureCtx(sigCtx); + #ifdef WOLFSSL_SMALL_STACK + XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); + #endif } } - FreeSignatureCtx(sigCtx); -#ifdef WOLFSSL_SMALL_STACK - if (sigCtx != NULL) - XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); -#endif return ret; #endif /* WOLFSSL_ASN_TEMPLATE */ } From 27e8276f0bec4bc30a8ad0adc415981483d9f002 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Wed, 19 Apr 2023 17:20:33 -0600 Subject: [PATCH 205/391] Remove shellscript dependency from CMake with WOLFSSL_USER_SETTINGS --- CMakeLists.txt | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e29d6cad1a4..46e9a95f857 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1660,6 +1660,10 @@ add_option("WOLFSSL_USER_SETTINGS" "Use your own user_settings.h and do not add Makefile CFLAGS (default: disabled)" "no" "yes;no") +add_option("WOLFSSL_USER_SETTINGS_ASM" + "Enable use of user_settings_asm.h in assembly files (default: disabled)" + "no" "yes;no") + add_option("WOLFSSL_OPTFLAGS" "Enable default optimization CFLAGS for the compiler (default: enabled)" "yes" "yes;no") @@ -1877,14 +1881,23 @@ generate_build_flags() if(WOLFSSL_USER_SETTINGS) # Replace all options and just use WOLFSSL_USER_SETTINGS set(WOLFSSL_DEFINITIONS "-DWOLFSSL_USER_SETTINGS") - list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_USER_SETTINGS_ASM") - - # Create user_settings_asm.h for use in assembly files (e.g. .S files). - execute_process(COMMAND $ENV{SHELL} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh - "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}" - RESULT_VARIABLE USER_SETTINGS_ASM_RET) - if (NOT USER_SETTINGS_ASM_RET EQUAL 0) - message(FATAL_ERROR "${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh failed.") +endif() + +if(WOLFSSL_USER_SETTINGS_ASM) + if(WOLFSSL_USER_SETTINGS) + list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_USER_SETTINGS_ASM") + # Create user_settings_asm.h for use in assembly files (e.g. .S files). + execute_process(COMMAND + $ENV{SHELL} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh + "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}" + RESULT_VARIABLE USER_SETTINGS_ASM_RET) + if (NOT USER_SETTINGS_ASM_RET EQUAL 0) + message(FATAL_ERROR + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh failed.") + endif() + else() + message(FATAL_ERROR + "Must have WOLFSSL_USER_SETTINGS to enable WOLFSSL_USER_SETTINGS_ASM.") endif() endif() From 941ee049eaa6704d9b2ff1bc553583e1a39e3977 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Wed, 19 Apr 2023 18:13:57 -0600 Subject: [PATCH 206/391] Let hashbang decide which shell to run with instead of default shell --- CMakeLists.txt | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 46e9a95f857..7628354a591 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1887,10 +1887,17 @@ if(WOLFSSL_USER_SETTINGS_ASM) if(WOLFSSL_USER_SETTINGS) list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_USER_SETTINGS_ASM") # Create user_settings_asm.h for use in assembly files (e.g. .S files). - execute_process(COMMAND - $ENV{SHELL} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh - "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}" - RESULT_VARIABLE USER_SETTINGS_ASM_RET) + if(WIN32) + execute_process(COMMAND + $ENV{SHELL} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh + "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}" + RESULT_VARIABLE USER_SETTINGS_ASM_RET) + else() + execute_process(COMMAND + ${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh + "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}" + RESULT_VARIABLE USER_SETTINGS_ASM_RET) + endif() if (NOT USER_SETTINGS_ASM_RET EQUAL 0) message(FATAL_ERROR "${CMAKE_CURRENT_SOURCE_DIR}/scripts/user_settings_asm.sh failed.") From 7202557bc99774bfeb7db8a6b83e3cc8f65542fa Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 24 Apr 2023 16:29:22 -0700 Subject: [PATCH 207/391] add guard for random with CAAM + MQX --- wolfcrypt/src/random.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index e445251d17d..885d973d521 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -2858,8 +2858,9 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) return RAN_BLOCK_E; } -#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) || \ - defined(FREESCALE_KSDK_BM) || defined(FREESCALE_FREE_RTOS) +#elif !defined(WOLFSSL_CAAM) && \ + (defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) || \ + defined(FREESCALE_KSDK_BM) || defined(FREESCALE_FREE_RTOS)) /* * Fallback to USE_TEST_GENSEED if a FREESCALE platform did not match any * of the TRNG/RNGA/RNGB support From 3478d0e375c74f8bf9d3795179d47e58212d39db Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 24 Apr 2023 17:59:32 +1000 Subject: [PATCH 208/391] OpenSSL EC API: fix setting private key wolfSSL_EC_KEY_set_private_key() should fail on obvious bad private key values. --- src/pk.c | 9 ++++++++- tests/api.c | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/pk.c b/src/pk.c index d5e647e9cdf..8ac6a8271fd 100644 --- a/src/pk.c +++ b/src/pk.c @@ -12753,7 +12753,7 @@ WOLFSSL_BIGNUM *wolfSSL_EC_KEY_get0_private_key(const WOLFSSL_EC_KEY *key) * @return 0 on failure. */ int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key, - const WOLFSSL_BIGNUM *priv_key) + const WOLFSSL_BIGNUM *priv_key) { int ret = 1; @@ -12765,6 +12765,13 @@ int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key, ret = 0; } + /* Check for obvious invalid values. */ + if (wolfSSL_BN_is_negative(priv_key) || wolfSSL_BN_is_zero(priv_key) || + wolfSSL_BN_is_one(priv_key)) { + WOLFSSL_MSG("Invalid private key value"); + ret = 0; + } + if (ret == 1) { /* Free key if previously set. */ if (key->priv_key != NULL) { diff --git a/tests/api.c b/tests/api.c index 585d8c9cdec..1a3e47fddb4 100644 --- a/tests/api.c +++ b/tests/api.c @@ -59993,8 +59993,8 @@ static int test_wolfSSL_EC_KEY_private_key(void) AssertNotNull(key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)); AssertNotNull(priv = wolfSSL_BN_new()); AssertNotNull(priv2 = wolfSSL_BN_new()); - AssertIntNE(BN_set_word(priv, 1), 0); - AssertIntNE(BN_set_word(priv2, 1), 0); + AssertIntNE(BN_set_word(priv, 2), 0); + AssertIntNE(BN_set_word(priv2, 2), 0); AssertNull(wolfSSL_EC_KEY_get0_private_key(NULL)); /* No private key set. */ From 68726a233213b4fc36a5c9c649b4a2968fd8a29e Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 25 Apr 2023 08:30:33 -0700 Subject: [PATCH 209/391] add sanity check on PKCS7 index value --- wolfcrypt/src/pkcs7.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index e36f05a9122..4373277123c 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -9733,6 +9733,10 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, *idx += (dateLen + 1); } + if (*idx > pkiMsgSz) { + return ASN_PARSE_E; + } + /* may have OPTIONAL OtherKeyAttribute */ localIdx = *idx; if ((*idx < kekIdSz) && GetASNTag(pkiMsg, &localIdx, &tag, @@ -9745,6 +9749,10 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, *idx += length; } + if (*idx > pkiMsgSz) { + return ASN_PARSE_E; + } + /* get KeyEncryptionAlgorithmIdentifier */ if (GetAlgoId(pkiMsg, idx, &keyWrapOID, oidKeyWrapType, pkiMsgSz) < 0) return ASN_PARSE_E; From e969db55d0d13386088c92fe9e3b1f1095ad8e1c Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 11 Apr 2023 09:06:39 -0700 Subject: [PATCH 210/391] avoid callback buffer overwrite with sha512_224 and remove min from wolfcaam_cmac --- wolfcrypt/src/port/caam/wolfcaam_cmac.c | 3 ++- wolfcrypt/src/sha512.c | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/port/caam/wolfcaam_cmac.c b/wolfcrypt/src/port/caam/wolfcaam_cmac.c index 4ce43994134..737f19da012 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_cmac.c +++ b/wolfcrypt/src/port/caam/wolfcaam_cmac.c @@ -99,7 +99,8 @@ int wc_CAAM_Cmac(Cmac* cmac, const byte* key, word32 keySz, const byte* in, WOLFSSL_MSG("Error with CMAC buffer size"); return -1; } - add = min(sz, (int)(AES_BLOCK_SIZE - cmac->bufferSz)); + add = (sz < ((int)(AES_BLOCK_SIZE - cmac->bufferSz))) ? sz : + (int)(AES_BLOCK_SIZE - cmac->bufferSz); XMEMCPY(&cmac->buffer[cmac->bufferSz], pt, add); cmac->bufferSz += add; diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index c742ac1b71b..224fe2e99fc 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -1152,9 +1152,12 @@ static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, size_t digestSz, #ifdef WOLF_CRYPTO_CB if (sha512->devId != INVALID_DEVID) { - ret = wc_CryptoCb_Sha512Hash(sha512, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) + byte localHash[WC_SHA512_DIGEST_SIZE]; + ret = wc_CryptoCb_Sha512Hash(sha512, NULL, 0, localHash); + if (ret != CRYPTOCB_UNAVAILABLE) { + XMEMCPY(hash, localHash, digestSz); return ret; + } /* fall-through when unavailable */ } #endif From 0514824577813f75bfe95fd79f15ccef76f1f033 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Wed, 15 Mar 2023 15:43:35 -0600 Subject: [PATCH 211/391] add messageDigest attribute if adding any custom signed attributes --- wolfcrypt/src/pkcs7.c | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index 4373277123c..3b1f45ecfa1 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -1975,16 +1975,27 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, /* add custom signed attributes if set */ if (pkcs7->signedAttribsSz > 0 && pkcs7->signedAttribs != NULL) { + /* Signed messageDigest must be present if any signed attributes are + * RFC 5652 section 11.2 */ + if (pkcs7->skipDefaultSignedAttribs != 0) { + hashSz = wc_HashGetDigestSize(esd->hashType); + if (hashSz < 0) + return hashSz; + + cannedAttribs[0].oid = messageDigestOid; + cannedAttribs[0].oidSz = messageDigestOidSz; + cannedAttribs[0].value = esd->contentDigest; + cannedAttribs[0].valueSz = hashSz + 2; /* ASN.1 heading */ + esd->signedAttribsCount++; + esd->signedAttribsSz += EncodeAttributes( + &esd->signedAttribs[atrIdx], 1, cannedAttribs, 1); + atrIdx++; + } + esd->signedAttribsCount += pkcs7->signedAttribsSz; - #ifdef NO_ASN_TIME esd->signedAttribsSz += EncodeAttributes(&esd->signedAttribs[atrIdx], esd->signedAttribsCount, pkcs7->signedAttribs, pkcs7->signedAttribsSz); - #else - esd->signedAttribsSz += EncodeAttributes(&esd->signedAttribs[atrIdx], - esd->signedAttribsCount, - pkcs7->signedAttribs, pkcs7->signedAttribsSz); - #endif } #ifdef NO_ASN_TIME From 4e2d283a6b96ae1ca8cb0f7916480958b62236bf Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 10 Apr 2023 15:41:54 -0700 Subject: [PATCH 212/391] add function to control default pkcs7 signer attributes --- wolfcrypt/src/pkcs7.c | 98 +++++++++++++++++++++++++-------------- wolfssl/wolfcrypt/pkcs7.h | 9 +++- 2 files changed, 71 insertions(+), 36 deletions(-) diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index 3b1f45ecfa1..d92c3fb0745 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -1929,7 +1929,7 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, return BAD_FUNC_ARG; } - if (pkcs7->skipDefaultSignedAttribs == 0) { + if (pkcs7->defaultSignedAttribs != WOLFSSL_NO_ATTRIBUTES) { hashSz = wc_HashGetDigestSize(esd->hashType); if (hashSz < 0) return hashSz; @@ -1946,23 +1946,34 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, cannedAttribsCount = sizeof(cannedAttribs)/sizeof(PKCS7Attrib); - cannedAttribs[idx].oid = contentTypeOid; - cannedAttribs[idx].oidSz = contentTypeOidSz; - cannedAttribs[idx].value = contentType; - cannedAttribs[idx].valueSz = contentTypeSz; - idx++; + if ((pkcs7->defaultSignedAttribs & WOLFSSL_CONTENT_ATTRIBUTE) || + pkcs7->defaultSignedAttribs == 0) { + cannedAttribs[idx].oid = contentTypeOid; + cannedAttribs[idx].oidSz = contentTypeOidSz; + cannedAttribs[idx].value = contentType; + cannedAttribs[idx].valueSz = contentTypeSz; + idx++; + } + #ifndef NO_ASN_TIME - cannedAttribs[idx].oid = signingTimeOid; - cannedAttribs[idx].oidSz = signingTimeOidSz; - cannedAttribs[idx].value = signingTime; - cannedAttribs[idx].valueSz = timeSz; - idx++; + if ((pkcs7->defaultSignedAttribs & WOLFSSL_TIME_ATTRIBUTE) || + pkcs7->defaultSignedAttribs == 0) { + cannedAttribs[idx].oid = signingTimeOid; + cannedAttribs[idx].oidSz = signingTimeOidSz; + cannedAttribs[idx].value = signingTime; + cannedAttribs[idx].valueSz = timeSz; + idx++; + } #endif - cannedAttribs[idx].oid = messageDigestOid; - cannedAttribs[idx].oidSz = messageDigestOidSz; - cannedAttribs[idx].value = esd->contentDigest; - cannedAttribs[idx].valueSz = hashSz + 2; /* ASN.1 heading */ - idx++; + + if ((pkcs7->defaultSignedAttribs & WOLFSSL_MESSAGE_DIGEST_ATTRIBUTE) || + pkcs7->defaultSignedAttribs == 0) { + cannedAttribs[idx].oid = messageDigestOid; + cannedAttribs[idx].oidSz = messageDigestOidSz; + cannedAttribs[idx].value = esd->contentDigest; + cannedAttribs[idx].valueSz = hashSz + 2; /* ASN.1 heading */ + idx++; + } esd->signedAttribsCount += cannedAttribsCount; esd->signedAttribsSz += EncodeAttributes(&esd->signedAttribs[atrIdx], @@ -1975,23 +1986,6 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, /* add custom signed attributes if set */ if (pkcs7->signedAttribsSz > 0 && pkcs7->signedAttribs != NULL) { - /* Signed messageDigest must be present if any signed attributes are - * RFC 5652 section 11.2 */ - if (pkcs7->skipDefaultSignedAttribs != 0) { - hashSz = wc_HashGetDigestSize(esd->hashType); - if (hashSz < 0) - return hashSz; - - cannedAttribs[0].oid = messageDigestOid; - cannedAttribs[0].oidSz = messageDigestOidSz; - cannedAttribs[0].value = esd->contentDigest; - cannedAttribs[0].valueSz = hashSz + 2; /* ASN.1 heading */ - esd->signedAttribsCount++; - esd->signedAttribsSz += EncodeAttributes( - &esd->signedAttribs[atrIdx], 1, cannedAttribs, 1); - atrIdx++; - } - esd->signedAttribsCount += pkcs7->signedAttribsSz; esd->signedAttribsSz += EncodeAttributes(&esd->signedAttribs[atrIdx], esd->signedAttribsCount, @@ -2850,14 +2844,48 @@ int wc_PKCS7_SetDetached(PKCS7* pkcs7, word16 flag) * Returns 0 on success, negative upon error. */ int wc_PKCS7_NoDefaultSignedAttribs(PKCS7* pkcs7) { - if (pkcs7 == NULL) + return wc_PKCS7_SetDefaultSignedAttribs(pkcs7, WOLFSSL_NO_ATTRIBUTES); +} + + +/* By default, SignedData bundles have the following signed attributes attached: + * contentType (1.2.840.113549.1.9.3) + * signingTime (1.2.840.113549.1.9.5) + * messageDigest (1.2.840.113549.1.9.4) + * + * Calling this API before wc_PKCS7_EncodeSignedData() allows control over which + * default attributes are added. + * + * pkcs7 - pointer to initialized PKCS7 structure + * + * Returns 0 on success, negative upon error. */ +int wc_PKCS7_SetDefaultSignedAttribs(PKCS7* pkcs7, word16 flag) +{ + if (pkcs7 == NULL) { return BAD_FUNC_ARG; + } + + if (flag & WOLFSSL_NO_ATTRIBUTES) { + if (flag ^ WOLFSSL_NO_ATTRIBUTES) { + WOLFSSL_MSG("Error, can not have additional flags with no " + "attributes flag set"); + return BAD_FUNC_ARG; + } + pkcs7->defaultSignedAttribs = 0; + } - pkcs7->skipDefaultSignedAttribs = 1; + /* check for unknown flags */ + if (flag & ~(WOLFSSL_CONTENT_ATTRIBUTE | WOLFSSL_TIME_ATTRIBUTE | + WOLFSSL_MESSAGE_DIGEST_ATTRIBUTE | WOLFSSL_NO_ATTRIBUTES)) { + WOLFSSL_MSG("Unknown attribute flags found"); + return BAD_FUNC_ARG; + } + pkcs7->defaultSignedAttribs |= flag; return 0; } + /* return codes: >0: Size of signed PKCS7 output buffer, negative: error */ int wc_PKCS7_EncodeSignedData(PKCS7* pkcs7, byte* output, word32 outputSz) { diff --git a/wolfssl/wolfcrypt/pkcs7.h b/wolfssl/wolfcrypt/pkcs7.h index b870666756a..da0a53f33b2 100644 --- a/wolfssl/wolfcrypt/pkcs7.h +++ b/wolfssl/wolfcrypt/pkcs7.h @@ -75,6 +75,12 @@ #define MAX_UNAUTH_ATTRIBS_SZ 7 #endif +/* bitmap flag for attributes */ +#define WOLFSSL_NO_ATTRIBUTES 0x1 +#define WOLFSSL_CONTENT_ATTRIBUTE 0x2 +#define WOLFSSL_TIME_ATTRIBUTE 0x4 +#define WOLFSSL_MESSAGE_DIGEST_ATTRIBUTE 0x8 + /* PKCS#7 content types, ref RFC 2315 (Section 14) */ enum PKCS7_TYPES { PKCS7_MSG = 650, /* 1.2.840.113549.1.7 */ @@ -312,7 +318,7 @@ struct PKCS7 { #endif word32 state; - word16 skipDefaultSignedAttribs:1; /* skip adding default signed attribs */ + word16 defaultSignedAttribs; /* set which default signed attribs */ byte version; /* 1 for RFC 2315 and 3 for RFC 4108 */ PKCS7SignerInfo* signerInfo; @@ -361,6 +367,7 @@ WOLFSSL_API int wc_PKCS7_EncodeData(PKCS7* pkcs7, byte* output, /* CMS/PKCS#7 SignedData */ WOLFSSL_API int wc_PKCS7_SetDetached(PKCS7* pkcs7, word16 flag); WOLFSSL_API int wc_PKCS7_NoDefaultSignedAttribs(PKCS7* pkcs7); +WOLFSSL_API int wc_PKCS7_SetDefaultSignedAttribs(PKCS7* pkcs7, word16 flag); WOLFSSL_API int wc_PKCS7_EncodeSignedData(PKCS7* pkcs7, byte* output, word32 outputSz); WOLFSSL_API int wc_PKCS7_EncodeSignedData_ex(PKCS7* pkcs7, const byte* hashBuf, From 935b679cbb94aed2c90eada45a3042482a6e721b Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Tue, 25 Apr 2023 13:56:29 -0600 Subject: [PATCH 213/391] more specific naming for attribute types --- wolfcrypt/src/pkcs7.c | 9 +++++---- wolfssl/wolfcrypt/pkcs7.h | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index d92c3fb0745..b5ec1d82f0e 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -1946,7 +1946,7 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, cannedAttribsCount = sizeof(cannedAttribs)/sizeof(PKCS7Attrib); - if ((pkcs7->defaultSignedAttribs & WOLFSSL_CONTENT_ATTRIBUTE) || + if ((pkcs7->defaultSignedAttribs & WOLFSSL_CONTENT_TYPE_ATTRIBUTE) || pkcs7->defaultSignedAttribs == 0) { cannedAttribs[idx].oid = contentTypeOid; cannedAttribs[idx].oidSz = contentTypeOidSz; @@ -1956,7 +1956,7 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, } #ifndef NO_ASN_TIME - if ((pkcs7->defaultSignedAttribs & WOLFSSL_TIME_ATTRIBUTE) || + if ((pkcs7->defaultSignedAttribs & WOLFSSL_SIGNING_TIME_ATTRIBUTE) || pkcs7->defaultSignedAttribs == 0) { cannedAttribs[idx].oid = signingTimeOid; cannedAttribs[idx].oidSz = signingTimeOidSz; @@ -2875,8 +2875,9 @@ int wc_PKCS7_SetDefaultSignedAttribs(PKCS7* pkcs7, word16 flag) } /* check for unknown flags */ - if (flag & ~(WOLFSSL_CONTENT_ATTRIBUTE | WOLFSSL_TIME_ATTRIBUTE | - WOLFSSL_MESSAGE_DIGEST_ATTRIBUTE | WOLFSSL_NO_ATTRIBUTES)) { + if (flag & ~(WOLFSSL_CONTENT_TYPE_ATTRIBUTE | + WOLFSSL_SIGNING_TIME_ATTRIBUTE | + WOLFSSL_MESSAGE_DIGEST_ATTRIBUTE | WOLFSSL_NO_ATTRIBUTES)) { WOLFSSL_MSG("Unknown attribute flags found"); return BAD_FUNC_ARG; } diff --git a/wolfssl/wolfcrypt/pkcs7.h b/wolfssl/wolfcrypt/pkcs7.h index da0a53f33b2..8f28fdbae21 100644 --- a/wolfssl/wolfcrypt/pkcs7.h +++ b/wolfssl/wolfcrypt/pkcs7.h @@ -77,8 +77,8 @@ /* bitmap flag for attributes */ #define WOLFSSL_NO_ATTRIBUTES 0x1 -#define WOLFSSL_CONTENT_ATTRIBUTE 0x2 -#define WOLFSSL_TIME_ATTRIBUTE 0x4 +#define WOLFSSL_CONTENT_TYPE_ATTRIBUTE 0x2 +#define WOLFSSL_SIGNING_TIME_ATTRIBUTE 0x4 #define WOLFSSL_MESSAGE_DIGEST_ATTRIBUTE 0x8 /* PKCS#7 content types, ref RFC 2315 (Section 14) */ From 3b256f20b342ab54533a880937a38a3bf81d28bf Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 26 Apr 2023 00:05:37 -0500 Subject: [PATCH 214/391] wolfcrypt/src/asn.c: add to DecodeCertInternal() a workaround for an apparent clang-tidy bug, gated on WOLFSSL_CLANG_TIDY, and add a missing cast to mollify -Wconversion; wolfssl/wolfcrypt/sp_int.h: refactor MP_INT_SIZEOF() using sizeof(sp_int_minimal) and addition, rather than sizeof(sp_int) and subtraction, for clarity and analyzer mollification. --- wolfcrypt/src/asn.c | 8 +++++++- wolfssl/wolfcrypt/sp_int.h | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index dfe9817a78b..7f84841283c 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -20112,6 +20112,12 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, /* Parse the X509 certificate. */ ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert->source, &cert->srcIdx, cert->maxIdx); +#ifdef WOLFSSL_CLANG_TIDY + /* work around clang-tidy false positive re cert->source. */ + if ((ret == 0) && (cert->source == NULL)) { + ret = ASN_PARSE_E; + } +#endif } /* Check version is valid/supported - can't be negative. */ if ((ret == 0) && (version > MAX_X509_VERSION)) { @@ -20304,7 +20310,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, KEYID_SIZE) == 0); } if (stopAtPubKey) { - ret = pubKeyOffset; + ret = (int)pubKeyOffset; } } diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index 033e85f85a8..d96c7480eba 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -764,7 +764,7 @@ typedef struct sp_ecc_ctx { * Must have at least one digit. */ #define MP_INT_SIZEOF(cnt) \ - (sizeof(sp_int) - (SP_INT_DIGITS - (((cnt) == 0) ? 1 : (cnt))) * \ + (sizeof(sp_int_minimal) + (((cnt) <= 1) ? 0 : ((cnt) - 1)) * \ sizeof(sp_int_digit)) /* The address of the next sp_int after one with 'cnt' digits. */ #define MP_INT_NEXT(t, cnt) \ From ecfb7327d952386049b8c6682cc3738ccc0de28a Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Tue, 25 Apr 2023 09:16:39 -0600 Subject: [PATCH 215/391] Remove XMEMSET after XFREE in sniffer.c --- src/sniffer.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/sniffer.c b/src/sniffer.c index 37dd73fa6e0..3a85d525494 100644 --- a/src/sniffer.c +++ b/src/sniffer.c @@ -831,7 +831,6 @@ static void FreeSnifferSession(SnifferSession* session) #endif } XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION); - XMEMSET(session, 0, sizeof(SnifferSession)); } From 8f3be5413fed3532b100b63d1c30ba651de439ed Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 25 Apr 2023 13:32:19 -0700 Subject: [PATCH 216/391] revert WOLFSSL_NO_ASN_STRICT macro guard --- wolfcrypt/src/asn.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 7f84841283c..29211f240ed 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -16555,9 +16555,10 @@ static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert) } break; case ASN_DIR_TYPE: + #ifndef WOLFSSL_NO_ASN_STRICT name = cert->altDirNames; + #endif - #ifndef WOLFSSL_NO_ASN_STRICT /* RFC 5280 section 4.2.1.10 "Restrictions of the form directoryName MUST be applied to the subject field .... and to any names @@ -16570,7 +16571,6 @@ static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert) subjectDnsName.len = cert->subjectRawLen; subjectDnsName.name = (char *)cert->subjectRaw; } - #endif break; default: /* Other types of names are ignored for now. From 46512083717b7ae1f9613aaf1b3f26504ecef610 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 26 Apr 2023 12:19:00 -0600 Subject: [PATCH 217/391] set dev ID with signature check (#6318) * set dev ID with signature check * refactor devId use and add API to set devId in WOLFSSL_CERT_MANAGER structure * add api.c call to set devid with WOLFSSL_CERT_MANAGER * resolving devID CRL issue and CM pointer * add device find callback * add simple test case --- src/ssl.c | 7 ++- wolfcrypt/src/asn.c | 59 +++++++++++++------- wolfcrypt/src/cryptocb.c | 105 +++++++++++++++++++++++------------ wolfcrypt/test/test.c | 19 ++++++- wolfssl/wolfcrypt/asn.h | 2 + wolfssl/wolfcrypt/cryptocb.h | 3 + 6 files changed, 135 insertions(+), 60 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index d54015916de..b001b86de3a 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -7667,7 +7667,7 @@ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, #endif WOLFSSL_MSG("Checking cert signature type"); - InitDecodedCert(cert, der->buffer, der->length, heap); + InitDecodedCert_ex(cert, der->buffer, der->length, heap, devId); if (DecodeToKey(cert, 0) < 0) { WOLFSSL_MSG("Decode to key failed"); @@ -9908,7 +9908,7 @@ static int check_cert_key(DerBuffer* cert, DerBuffer* key, void* heap, size = cert->length; buff = cert->buffer; - InitDecodedCert(der, buff, size, heap); + InitDecodedCert_ex(der, buff, size, heap, devId); if (ParseCertRelative(der, CERT_TYPE, NO_VERIFY, NULL) != 0) { FreeDecodedCert(der); #ifdef WOLFSSL_SMALL_STACK @@ -20696,7 +20696,8 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, ret = wolfSSL_X509_dup(&ssl->peerCert); #ifdef SESSION_CERTS else if (ssl->session->chain.count > 0) { - if (DecodeToX509(&ssl->peerCert, ssl->session->chain.certs[0].buffer, + if (DecodeToX509(&ssl->peerCert, + ssl->session->chain.certs[0].buffer, ssl->session->chain.certs[0].length) == 0) { ret = wolfSSL_X509_dup(&ssl->peerCert); } diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 29211f240ed..29c9bb2a808 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -11117,6 +11117,21 @@ int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen) */ void InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz, void* heap) +{ + InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID); +} + + +/* Initialize decoded certificate object with buffer of DER encoding. + * + * @param [in, out] cert Decoded certificate object. + * @param [in] source Buffer containing DER encoded certificate. + * @param [in] inSz Size of DER data in buffer in bytes. + * @param [in] heap Dynamic memory hint. + * @param [in] devId Crypto callback ID to use. + */ +void InitDecodedCert_ex(DecodedCert* cert, + const byte* source, word32 inSz, void* heap, int devId) { if (cert != NULL) { XMEMSET(cert, 0, sizeof(DecodedCert)); @@ -11152,7 +11167,7 @@ void InitDecodedCert(DecodedCert* cert, #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ #ifndef NO_CERTS - InitSignatureCtx(&cert->sigCtx, heap, INVALID_DEVID); + InitSignatureCtx(&cert->sigCtx, heap, devId); #endif } } @@ -20958,6 +20973,7 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, if (sigCtx == NULL) return MEMORY_E; #endif + InitSignatureCtx(sigCtx, heap, INVALID_DEVID); /* Certificate SEQUENCE */ @@ -24653,7 +24669,8 @@ void wc_SetCert_Free(Cert* cert) } } -static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz) +static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz, + int devId) { int ret; @@ -24671,8 +24688,8 @@ static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz) else { XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert)); - InitDecodedCert((DecodedCert*)cert->decodedCert, der, derSz, - cert->heap); + InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz, + cert->heap, devId); ret = ParseCertRelative((DecodedCert*)cert->decodedCert, CERT_TYPE, 0, NULL); if (ret >= 0) { @@ -30226,7 +30243,7 @@ int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID); } if (ret >= 0) { @@ -30467,7 +30484,8 @@ static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded) #ifndef NO_FILESYSTEM /* Set Alt Names from der cert, return 0 on success */ -static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz) +static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz, + int devId) { int ret; #ifdef WOLFSSL_SMALL_STACK @@ -30486,7 +30504,7 @@ static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz) return MEMORY_E; #endif - InitDecodedCert(decoded, der, (word32)derSz, NULL); + InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId); ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0); if (ret < 0) { @@ -30666,7 +30684,7 @@ static void SetNameFromDcert(CertName* cn, DecodedCert* decoded) #ifndef NO_FILESYSTEM /* Set cn name from der buffer, return 0 on success */ -static int SetNameFromCert(CertName* cn, const byte* der, int derSz) +static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId) { int ret; #ifdef WOLFSSL_SMALL_STACK @@ -30685,7 +30703,7 @@ static int SetNameFromCert(CertName* cn, const byte* der, int derSz) return MEMORY_E; #endif - InitDecodedCert(decoded, der, (word32)derSz, NULL); + InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId); ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0); if (ret < 0) { @@ -30717,7 +30735,8 @@ int wc_SetIssuer(Cert* cert, const char* issuerFile) ret = wc_PemCertToDer_ex(issuerFile, &der); if (ret == 0) { cert->selfSigned = 0; - ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length); + ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length, + INVALID_DEVID); FreeDer(&der); } @@ -30738,7 +30757,8 @@ int wc_SetSubject(Cert* cert, const char* subjectFile) ret = wc_PemCertToDer_ex(subjectFile, &der); if (ret == 0) { - ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length); + ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length, + INVALID_DEVID); FreeDer(&der); } @@ -30761,7 +30781,8 @@ int wc_SetAltNames(Cert* cert, const char* file) ret = wc_PemCertToDer_ex(file, &der); if (ret == 0) { - ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length); + ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length, + INVALID_DEVID); FreeDer(&der); } @@ -30788,7 +30809,7 @@ int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID); } if (ret >= 0) { @@ -30815,7 +30836,7 @@ int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID); } if (ret >= 0) { @@ -30842,7 +30863,7 @@ int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID); } if (ret >= 0) { @@ -30876,7 +30897,7 @@ int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID); } if (ret >= 0) { @@ -30913,7 +30934,7 @@ int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID); } if (ret >= 0) { @@ -30940,7 +30961,7 @@ int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz) /* Check if decodedCert is cached */ if (cert->der != der) { /* Allocate cache for the decoded cert */ - ret = wc_SetCert_LoadDer(cert, der, (word32)derSz); + ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID); } if (ret >= 0) { @@ -34440,7 +34461,6 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, int sigLength; const byte* sigParams = NULL; word32 sigParamsSz = 0; - WOLFSSL_ENTER("DecodeBasicOcspResponse"); (void)heap; @@ -34708,6 +34728,7 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, #endif if (ca) { SignatureCtx sigCtx; + /* Initialize he signature context. */ InitSignatureCtx(&sigCtx, heap, INVALID_DEVID); diff --git a/wolfcrypt/src/cryptocb.c b/wolfcrypt/src/cryptocb.c index 38f5af42c2e..8d3a683566f 100644 --- a/wolfcrypt/src/cryptocb.c +++ b/wolfcrypt/src/cryptocb.c @@ -34,6 +34,9 @@ #include #include +#ifdef WOLFSSL_CAAM + #include +#endif /* TODO: Consider linked list with mutex */ #ifndef MAX_CRYPTO_DEVID_CALLBACKS @@ -46,6 +49,7 @@ typedef struct CryptoCb { void* ctx; } CryptoCb; static WOLFSSL_GLOBAL CryptoCb gCryptoDev[MAX_CRYPTO_DEVID_CALLBACKS]; +static CryptoDevCallbackFind CryptoCb_FindCb = NULL; #ifdef DEBUG_CRYPTOCB @@ -165,15 +169,32 @@ WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info) } #endif /* DEBUG_CRYPTOCB */ -static CryptoCb* wc_CryptoCb_FindDevice(int devId) +/* Search through listed devices and return the first matching device ID + * found. */ +static CryptoCb* wc_CryptoCb_GetDevice(int devId) { int i; - for (i=0; idevId = INVALID_DEVID; @@ -248,7 +279,7 @@ int wc_CryptoCb_Rsa(const byte* in, word32 inLen, byte* out, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -278,7 +309,7 @@ int wc_CryptoCb_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -306,7 +337,7 @@ int wc_CryptoCb_RsaCheckPrivKey(RsaKey* key, const byte* pubKey, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -333,7 +364,7 @@ int wc_CryptoCb_MakeEccKey(WC_RNG* rng, int keySize, ecc_key* key, int curveId) return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -360,7 +391,7 @@ int wc_CryptoCb_Ecdh(ecc_key* private_key, ecc_key* public_key, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(private_key->devId); + dev = wc_CryptoCb_FindDevice(private_key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -387,7 +418,7 @@ int wc_CryptoCb_EccSign(const byte* in, word32 inlen, byte* out, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -416,7 +447,7 @@ int wc_CryptoCb_EccVerify(const byte* sig, word32 siglen, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -445,7 +476,7 @@ int wc_CryptoCb_EccCheckPrivKey(ecc_key* key, const byte* pubKey, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -473,7 +504,7 @@ int wc_CryptoCb_Curve25519Gen(WC_RNG* rng, int keySize, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -499,7 +530,7 @@ int wc_CryptoCb_Curve25519(curve25519_key* private_key, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(private_key->devId); + dev = wc_CryptoCb_FindDevice(private_key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -529,7 +560,7 @@ int wc_CryptoCb_Ed25519Gen(WC_RNG* rng, int keySize, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -556,7 +587,7 @@ int wc_CryptoCb_Ed25519Sign(const byte* in, word32 inLen, byte* out, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -588,7 +619,7 @@ int wc_CryptoCb_Ed25519Verify(const byte* sig, word32 sigLen, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(key->devId); + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -624,7 +655,7 @@ int wc_CryptoCb_AesGcmEncrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -665,7 +696,7 @@ int wc_CryptoCb_AesGcmDecrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -708,7 +739,7 @@ int wc_CryptoCb_AesCcmEncrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -749,7 +780,7 @@ int wc_CryptoCb_AesCcmDecrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -789,7 +820,7 @@ int wc_CryptoCb_AesCbcEncrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -821,7 +852,7 @@ int wc_CryptoCb_AesCbcDecrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -854,7 +885,7 @@ int wc_CryptoCb_AesCtrEncrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -887,7 +918,7 @@ int wc_CryptoCb_AesEcbEncrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -919,7 +950,7 @@ int wc_CryptoCb_AesEcbDecrypt(Aes* aes, byte* out, /* locate registered callback */ if (aes) { - dev = wc_CryptoCb_FindDevice(aes->devId); + dev = wc_CryptoCb_FindDevice(aes->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -954,7 +985,7 @@ int wc_CryptoCb_Des3Encrypt(Des3* des3, byte* out, /* locate registered callback */ if (des3) { - dev = wc_CryptoCb_FindDevice(des3->devId); + dev = wc_CryptoCb_FindDevice(des3->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -986,7 +1017,7 @@ int wc_CryptoCb_Des3Decrypt(Des3* des3, byte* out, /* locate registered callback */ if (des3) { - dev = wc_CryptoCb_FindDevice(des3->devId); + dev = wc_CryptoCb_FindDevice(des3->devId, WC_ALGO_TYPE_CIPHER); } else { /* locate first callback and try using it */ @@ -1020,7 +1051,7 @@ int wc_CryptoCb_ShaHash(wc_Sha* sha, const byte* in, /* locate registered callback */ if (sha) { - dev = wc_CryptoCb_FindDevice(sha->devId); + dev = wc_CryptoCb_FindDevice(sha->devId, WC_ALGO_TYPE_HASH); } else { /* locate first callback and try using it */ @@ -1053,7 +1084,7 @@ int wc_CryptoCb_Sha256Hash(wc_Sha256* sha256, const byte* in, /* locate registered callback */ if (sha256) { - dev = wc_CryptoCb_FindDevice(sha256->devId); + dev = wc_CryptoCb_FindDevice(sha256->devId, WC_ALGO_TYPE_HASH); } else { /* locate first callback and try using it */ @@ -1087,7 +1118,7 @@ int wc_CryptoCb_Sha384Hash(wc_Sha384* sha384, const byte* in, /* locate registered callback */ #ifndef NO_SHA2_CRYPTO_CB if (sha384) { - dev = wc_CryptoCb_FindDevice(sha384->devId); + dev = wc_CryptoCb_FindDevice(sha384->devId, WC_ALGO_TYPE_HASH); } else #endif @@ -1123,7 +1154,7 @@ int wc_CryptoCb_Sha512Hash(wc_Sha512* sha512, const byte* in, /* locate registered callback */ #ifndef NO_SHA2_CRYPTO_CB if (sha512) { - dev = wc_CryptoCb_FindDevice(sha512->devId); + dev = wc_CryptoCb_FindDevice(sha512->devId, WC_ALGO_TYPE_HASH); } else #endif @@ -1160,7 +1191,7 @@ int wc_CryptoCb_Hmac(Hmac* hmac, int macType, const byte* in, word32 inSz, return ret; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(hmac->devId); + dev = wc_CryptoCb_FindDevice(hmac->devId, WC_ALGO_TYPE_HMAC); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -1186,7 +1217,7 @@ int wc_CryptoCb_RandomBlock(WC_RNG* rng, byte* out, word32 sz) /* locate registered callback */ if (rng) { - dev = wc_CryptoCb_FindDevice(rng->devId); + dev = wc_CryptoCb_FindDevice(rng->devId, WC_ALGO_TYPE_RNG); } else { /* locate first callback and try using it */ @@ -1213,7 +1244,7 @@ int wc_CryptoCb_RandomSeed(OS_Seed* os, byte* seed, word32 sz) CryptoCb* dev; /* locate registered callback */ - dev = wc_CryptoCb_FindDevice(os->devId); + dev = wc_CryptoCb_FindDevice(os->devId, WC_ALGO_TYPE_SEED); if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -1238,7 +1269,7 @@ int wc_CryptoCb_Cmac(Cmac* cmac, const byte* key, word32 keySz, /* locate registered callback */ if (cmac) { - dev = wc_CryptoCb_FindDevice(cmac->devId); + dev = wc_CryptoCb_FindDevice(cmac->devId, WC_ALGO_TYPE_CMAC); } else { /* locate first callback and try using it */ diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 02ebbdca533..a01982714ad 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -45138,6 +45138,23 @@ static int myCryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) return ret; } + +static int myCryptoCbFind(int currentId, int algoType) +{ + /* can have algo specific overrides here + switch (algoType) { + + } + */ + (void)algoType; + + if (currentId == INVALID_DEVID) { + return 1; /* override invalid devid found with 1 */ + } + return currentId; +} + + WOLFSSL_TEST_SUBROUTINE int cryptocb_test(void) { int ret = 0; @@ -45149,7 +45166,7 @@ WOLFSSL_TEST_SUBROUTINE int cryptocb_test(void) /* set devId to something other than INVALID_DEVID */ devId = 1; ret = wc_CryptoCb_RegisterDevice(devId, myCryptoDevCb, &myCtx); - + wc_CryptoCb_SetDeviceFindCb(myCryptoCbFind); #ifndef WC_NO_RNG if (ret == 0) ret = random_test(); diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 5b9e7b4f884..3794acde637 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -2023,6 +2023,8 @@ WOLFSSL_ASN_API DNS_entry* AltNameNew(void* heap); #endif /* IGNORE_NAME_CONSTRAINTS */ WOLFSSL_ASN_API void InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz, void* heap); +WOLFSSL_LOCAL void InitDecodedCert_ex(DecodedCert* cert, const byte* source, + word32 inSz, void* heap, int devId); WOLFSSL_ASN_API void FreeDecodedCert(DecodedCert* cert); WOLFSSL_ASN_API int ParseCert(DecodedCert* cert, int type, int verify, void* cm); diff --git a/wolfssl/wolfcrypt/cryptocb.h b/wolfssl/wolfcrypt/cryptocb.h index 287e10941a9..1b11cf3e4de 100644 --- a/wolfssl/wolfcrypt/cryptocb.h +++ b/wolfssl/wolfcrypt/cryptocb.h @@ -366,6 +366,9 @@ WOLFSSL_API int wc_CryptoCb_RegisterDevice(int devId, CryptoDevCallbackFunc cb, WOLFSSL_API void wc_CryptoCb_UnRegisterDevice(int devId); WOLFSSL_API int wc_CryptoCb_DefaultDevID(void); +typedef int (*CryptoDevCallbackFind)(int devId, int algoType); +WOLFSSL_API void wc_CryptoCb_SetDeviceFindCb(CryptoDevCallbackFind cb); + #ifdef DEBUG_CRYPTOCB WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info); #endif From 48e58d583efbfd9cf73e0cad585f6b211bb54563 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 26 Apr 2023 09:03:08 +1000 Subject: [PATCH 218/391] ASN original, OCSP: fix maximum size calc to GetDateInfo GetDateInfo called with a local index (reset to 0) but size is of original buffer. Subtract the index into original buffer from size to get size available for parsing. --- wolfcrypt/src/asn.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 29c9bb2a808..a26c12f7451 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -33786,7 +33786,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, localIdx = 0; if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL, (byte*)&single->status->thisDateParsed.type, - &single->status->thisDateParsed.length, size) < 0) + &single->status->thisDateParsed.length, size - idx) < 0) return ASN_PARSE_E; if (idx + localIdx >= size) @@ -33822,7 +33822,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, localIdx = 0; if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL, (byte*)&single->status->nextDateParsed.type, - &single->status->nextDateParsed.length, size) < 0) + &single->status->nextDateParsed.length, size - idx) < 0) return ASN_PARSE_E; if (idx + localIdx >= size) From 4fbe3ecbac10bc4cde586d434ff0889de8e705a5 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 26 Apr 2023 11:05:07 +1000 Subject: [PATCH 219/391] Minor fixes EncryptContent() - id not initialized sp_int.c: cast count to int to ensure same type comparison with i. --- wolfcrypt/src/asn.c | 2 +- wolfcrypt/src/sp_int.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index a26c12f7451..2ddcbb17d0d 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -9065,7 +9065,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, int ret = 0; int sz = 0; int version; - int id; + int id = -1; int blockSz = 0; word32 pkcs8Sz = 0; diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 5c2f7d1c8bf..6b8a1e7b5aa 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -274,7 +274,7 @@ while (0) int n##ii; \ (n)[0] = (sp_int*)n##d; \ ((sp_int_minimal*)(n)[0])->size = (s); \ - for (n##ii = 1; n##ii < (c); n##ii++) { \ + for (n##ii = 1; n##ii < (int)(c); n##ii++) { \ (n)[n##ii] = MP_INT_NEXT((n)[n##ii-1], s); \ ((sp_int_minimal*)(n)[n##ii])->size = (s); \ } \ @@ -292,7 +292,7 @@ while (0) } \ if ((err) == MP_OKAY) { \ int n##ii; \ - for (n##ii = 0; n##ii < (c); n##ii++) { \ + for (n##ii = 0; n##ii < (int)(c); n##ii++) { \ (n)[n##ii] = &n##d[n##ii]; \ (n)[n##ii]->size = (s); \ } \ From ac091a31434b2ec30cc16d113260b70dd4e715c6 Mon Sep 17 00:00:00 2001 From: Kareem Date: Wed, 26 Apr 2023 15:00:59 -0700 Subject: [PATCH 220/391] Fix getting key size in stm32_ecc_sign_hash_ex. --- wolfcrypt/src/port/st/stm32.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index c0208127e51..f72d1872f64 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -1012,7 +1012,7 @@ int stm32_ecc_sign_hash_ex(const byte* hash, word32 hashlen, WC_RNG* rng, mp_init(&gen_k); mp_init(&order_mp); - size = mp_unsigned_bin_size(key->pubkey.x); + size = wc_ecc_size(key); status = stm32_get_from_mp_int(Keybin, &key->k, size); if (status != MP_OKAY) From 588d005056b4dced2fdfaf057d5aeb5bd2920645 Mon Sep 17 00:00:00 2001 From: TakayukiMatsuo Date: Mon, 17 Apr 2023 07:49:42 +0900 Subject: [PATCH 221/391] Update Japanese comments --- doc/dox_comments/header_files-ja/aes.h | 24 ++++++++++- doc/dox_comments/header_files-ja/ed25519.h | 49 ++++++++++++++++++---- doc/dox_comments/header_files-ja/ssl.h | 36 +++++++++++++++- 3 files changed, 99 insertions(+), 10 deletions(-) diff --git a/doc/dox_comments/header_files-ja/aes.h b/doc/dox_comments/header_files-ja/aes.h index daf2234396c..9db335ed408 100644 --- a/doc/dox_comments/header_files-ja/aes.h +++ b/doc/dox_comments/header_files-ja/aes.h @@ -610,7 +610,7 @@ int wc_AesXtsFree(XtsAes* aes); /*! \ingroup AES - \brief AES構造を初期化します。ASYNCハードウェアで使用するためのヒープヒントとIDを設定する + \brief Aes構造体を初期化します。ヒープヒントを設定し、ASYNCハードウェアを使用する場合のIDも設定します。Aes構造体の使用が終了した際にwc_AesFreeを呼び出すのはユーザーに任されています。 \return 0 成功 \param aes 初期化にはAES構造 \param heap 必要に応じてmalloc / freeに使用するヒントヒント @@ -622,13 +622,33 @@ int wc_AesXtsFree(XtsAes* aes); //heap hint could be set here if used - wc_AesInit(&aes, hint, devId); + wc_AesInit(&enc, hint, devId); \endcode \sa wc_AesSetKey \sa wc_AesSetIV */ int wc_AesInit(Aes* aes, void* heap, int devId); +/*! + \ingroup AES + \brief Aes構造体に関連つけられたリソースを可能なら解放する。 + 内部的にはノーオペレーションとなることもありますが、ベストプラクティスとしてどのケースでもこの関数を呼び出すことを推奨します。 + \return 戻り値なし + \param aes FreeすべきAes構造体へのポインター + _Example_ + \code + Aes enc; + void* hint = NULL; + int devId = INVALID_DEVID; //if not using async INVALID_DEVID is default + //heap hint could be set here if used + wc_AesInit(&enc, hint, devId); + // ... do some interesting things ... + wc_AesFree(&enc); + \endcode + \sa wc_AesInit +*/ +int wc_AesFree(Aes* aes); + /*! \ingroup AES \brief CFBモードを持つAES。 diff --git a/doc/dox_comments/header_files-ja/ed25519.h b/doc/dox_comments/header_files-ja/ed25519.h index c843411c6aa..57f5adb4276 100644 --- a/doc/dox_comments/header_files-ja/ed25519.h +++ b/doc/dox_comments/header_files-ja/ed25519.h @@ -436,7 +436,7 @@ int wc_ed25519_import_public(const byte* in, word32 inLen, ed25519_key* key); \ingroup ED25519 \brief この関数は、ed25519秘密鍵をバッファからのみインポートします。 \return 0 ED25519キーのインポートに成功しました。 - \return BAD_FUNC_ARG INまたはKEYがNULLに評価された場合、またはPRIVSZがED25519_KEY_SIZEよりも小さい場合に返されます。 + \return BAD_FUNC_ARG privまたはkeyがNULLに評価された場合、またはprivSzがED25519_KEY_SIZEと異なる場合に返されます。 \param [in] 秘密鍵を含むバッファへのPRIVポインタ。 \param [in] 秘密鍵のPrivsz長さ。 \param [in] 公開鍵を含むバッファへのPubポインタ。 @@ -465,7 +465,7 @@ int wc_ed25519_import_private_only(const byte* priv, word32 privSz, \ingroup ED25519 \brief この関数は、一対のバッファからパブリック/プライベートED25519キーペアをインポートします。この関数は圧縮キーと非圧縮キーの両方を処理します。 \return 0 ED25519_KEYのインポートに成功しました。 - \return BAD_FUNC_ARG INまたはKEYがNULLに評価された場合、またはいずれかのPROVSZがED25519_SEY_SIZEまたはPUBSZよりも小さい場合は、ED25519_PUB_KEY_SIZEよりも小さい場合に返されます。 + \return BAD_FUNC_ARG privまたはkeyがNULLに評価された場合、privSzがED25519_KEY_SIZEと異なるあるいはED25519_PRV_KEY_SIZEとも異なる場合、pubSzがED25519_PUB_KEY_SIZEよりも小さい場合に返されます。 \param [in] 秘密鍵を含むバッファへのPRIVポインタ。 \param [in] 秘密鍵のPrivsz長さ。 \param [in] 公開鍵を含むバッファへのPubポインタ。 @@ -492,6 +492,40 @@ int wc_ed25519_import_private_only(const byte* priv, word32 privSz, int wc_ed25519_import_private_key(const byte* priv, word32 privSz, const byte* pub, word32 pubSz, ed25519_key* key); +/*! + \ingroup ED25519 + \brief この関数は一対のバッファからEd25519公開鍵/秘密鍵ペアをインポートします。この関数は圧縮キーと非圧縮キーの両方を処理します。公開鍵はtrusted引数により信頼されていないとされた場合には秘密鍵に対して検証されます。 + \return 0 ed25519_keyのインポートに成功しました。 + \return BAD_FUNC_ARG Returned if privあるいはkeyがNULLに評価された場合、privSzがED25519_KEY_SIZEともED25519_PRV_KEY_SIZEとも異なる場合、pubSzがED25519_PUB_KEY_SIZEより小さい場合に返されます。 + \param [in] priv 秘密鍵を保持するバッファへのポインター + \param [in] privSz 秘密鍵バッファのサイズ + \param [in] pub 公開鍵を保持するバッファへのポインター + \param [in] pubSz 公開鍵バッファのサイズ + \param [in,out] key インポートされた公開鍵/秘密鍵を保持するed25519_keyオブジェクトへのポインター + \param [in] trusted 公開鍵が信頼できるか否か。 + _Example_ + \code + int ret; + byte priv[] = { initialize with 32 byte private key }; + byte pub[] = { initialize with the corresponding public key }; + ed25519_key key; + wc_ed25519_init_key(&key); + ret = wc_ed25519_import_private_key(priv, sizeof(priv), pub, sizeof(pub), + &key, 1); + if (ret != 0) { + // error importing key + } + \endcode + \sa wc_ed25519_import_public + \sa wc_ed25519_import_public_ex + \sa wc_ed25519_import_private_only + \sa wc_ed25519_import_private_key + \sa wc_ed25519_export_private +*/ + +int wc_ed25519_import_private_key_ex(const byte* priv, word32 privSz, + const byte* pub, word32 pubSz, ed25519_key* key, int trusted); + /*! \ingroup ED25519 \brief この関数は、秘密鍵をED25519_Key構造体からエクスポートします。公開鍵をバッファアウトに格納し、ounterenでこのバッファに書き込まれたバイトを設定します。 @@ -524,7 +558,7 @@ int wc_ed25519_export_public(ed25519_key* key, byte* out, word32* outLen); \ingroup ED25519 \brief この関数は、ED25519_Key構造体からの秘密鍵のみをエクスポートします。秘密鍵をバッファアウトに格納し、outlenにこのバッファに書き込まれたバイトを設定します。 \return 0 秘密鍵のエクスポートに成功したら返されます。 - \return ECC_BAD_ARG_E いずれかの入力値がNULLに評価された場合に返されます。 + \return BAD_FUNC_ARG いずれかの入力値がNULLに評価された場合に返されます。 \return BUFFER_E 提供されたバッファーが秘密鍵を保存するのに十分な大きさでない場合に返されます。 \param [in] 秘密鍵をエクスポートするためのED25519_Key構造体へのキーポインタ。 \param [out] 秘密鍵を保存するバッファへのポインタ。 @@ -551,7 +585,7 @@ int wc_ed25519_export_private_only(ed25519_key* key, byte* out, word32* outLen); \ingroup ED25519 \brief この関数は、ED25519_Key構造体からキーペアをエクスポートします。キーペアをバッファOUTに格納し、ounterenでこのバッファに書き込まれたバイトを設定します。 \return 0 キーペアのエクスポートに成功したら返されます。 - \return ECC_BAD_ARG_E いずれかの入力値がNULLに評価された場合に返されます。 + \return BAD_FUNC_ARG いずれかの入力値がNULLに評価された場合に返されます。 \return BUFFER_E 提供されているバッファーがキーペアを保存するのに十分な大きさでない場合に返されます。 \param [in] キーペアをエクスポートするためのED25519_Key構造体へのキーポインタ。 \param [out] キーペアを保存するバッファへのポインタ。 @@ -582,7 +616,7 @@ int wc_ed25519_export_private(ed25519_key* key, byte* out, word32* outLen); \ingroup ED25519 \brief この関数は、ED25519_KEY構造体とは別にプライベートキーと公開鍵をエクスポートします。秘密鍵をバッファーPrivに格納し、PRIVSZでこのバッファに書き込まれたバイトを設定します。公開鍵をバッファPUBに格納し、Pubszでこのバッファに書き込まれたバイトを設定します。 \return 0 キーペアのエクスポートに成功したら返されます。 - \return ECC_BAD_ARG_E いずれかの入力値がNULLに評価された場合に返されます。 + \return BAD_FUNC_ARG いずれかの入力値がNULLに評価された場合に返されます。 \return BUFFER_E 提供されているバッファーがキーペアを保存するのに十分な大きさでない場合に返されます。 \param [in] キーペアをエクスポートするためのED25519_Key構造体へのキーポインタ。 \param [out] 秘密鍵を保存するバッファへのPRIVポインタ。 @@ -616,7 +650,8 @@ int wc_ed25519_export_key(ed25519_key* key, \ingroup ED25519 \brief この関数は、ED25519_KEY構造体の公開鍵をチェックします。 \return 0 プライベートキーと公開鍵が一致した場合に返されます。 - \return BAD_FUNC_ARGS 与えられたキーがNULLの場合に返されます。 + \return BAD_FUNC_ARG 与えられた鍵がNULLの場合に返されます。 + \return PUBLIC_KEY_E 公開鍵が参照できないか無効の場合に返されます。 _Example_ \code int ret; @@ -640,7 +675,7 @@ int wc_ed25519_check_key(ed25519_key* key); \ingroup ED25519 \brief この関数は、ED25519 - 32バイトのサイズを返します。 \return ED25519_KEY_SIZE 有効な秘密鍵のサイズ(32バイト)。 - \return BAD_FUNC_ARGS 与えられたキーがNULLの場合に返されます。 + \return BAD_FUNC_ARG 与えられたキーがNULLの場合に返されます。 _Example_ \code int keySz; diff --git a/doc/dox_comments/header_files-ja/ssl.h b/doc/dox_comments/header_files-ja/ssl.h index 1c41d9da878..b403ba57740 100644 --- a/doc/dox_comments/header_files-ja/ssl.h +++ b/doc/dox_comments/header_files-ja/ssl.h @@ -1054,6 +1054,37 @@ WOLFSSL* wolfSSL_new(WOLFSSL_CTX*); */ int wolfSSL_set_fd (WOLFSSL* ssl, int fd); +/*! + \ingroup Setup + \brief この関数はファイルディスクリプタ(fd)をSSLコネクションの入出力手段として設定します。 + 通常はソケットファイルディスクリプタが指定されます。この関数はDTLS専用のAPIであり、ソケットは接続済みとマークされます。 + したがって、与えられたfdに対するrecvfromとsendto呼び出しでのaddrとaddr_lenはNULLに設定されます。 + \return SSL_SUCCESS 成功時に返されます。 + \return Bad_FUNC_ARG 失敗時に返されます。 + \param ssl wolfSSL_new()で生成されたSSLセッションへのポインタ。 + \param fd SSL/TLSコネクションに使用するファイルディスクリプタ。 + _Example_ + \code + int sockfd; + WOLFSSL* ssl = 0; + ... + if (connect(sockfd, peer_addr, peer_addr_len) != 0) { + // handle connect error + } + ... + ret = wolfSSL_set_dtls_fd_connected(ssl, sockfd); + if (ret != SSL_SUCCESS) { + // failed to set SSL file descriptor + } + \endcode + \sa wolfSSL_CTX_SetIOSend + \sa wolfSSL_CTX_SetIORecv + \sa wolfSSL_SetIOReadCtx + \sa wolfSSL_SetIOWriteCtx + \sa wolfDTLS_SetChGoodCb +*/ +int wolfSSL_set_dtls_fd_connected(WOLFSSL* ssl, int fd); + /*! \ingroup IO \brief 渡された優先順位の暗号の名前を取得します。 @@ -4006,8 +4037,11 @@ unsigned char* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx); /*! \ingroup CertsKeys \brief この関数は、証明書のチェーンからのピアのwolfssl_x509_209_Certificateをインデックス(IDX)で取得します。 - \return pointer wolfssl_x509構造へのポインタを返します。 + \return pointer WOLFSSL_X509構造体へのポインタを返します。 \param chain 動的メモリsession_cacheの場合に使用されるWOLFSSL_X509_CHAINへのポインタ。 + + 注意:本関数から返された構造体をwolfSSL_FreeX509()を呼び出して解放するのはユーザーの責任です。 + _Example_ \code WOLFSSL_X509_CHAIN* chain = &session->chain; From 70b0b134e6f8d7ec4701e028c4cbed1d320f8567 Mon Sep 17 00:00:00 2001 From: TakayukiMatsuo Date: Mon, 17 Apr 2023 09:34:55 +0900 Subject: [PATCH 222/391] Fix example code in wolfSSL_get_chain_X509 --- doc/dox_comments/header_files-ja/ssl.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/dox_comments/header_files-ja/ssl.h b/doc/dox_comments/header_files-ja/ssl.h index b403ba57740..16923ae60e8 100644 --- a/doc/dox_comments/header_files-ja/ssl.h +++ b/doc/dox_comments/header_files-ja/ssl.h @@ -4036,7 +4036,7 @@ unsigned char* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx); /*! \ingroup CertsKeys - \brief この関数は、証明書のチェーンからのピアのwolfssl_x509_209_Certificateをインデックス(IDX)で取得します。 + \brief この関数は、証明書のチェーンからのピアのWOLFSSL_X509構造体をインデックス(IDX)で取得します。 \return pointer WOLFSSL_X509構造体へのポインタを返します。 \param chain 動的メモリsession_cacheの場合に使用されるWOLFSSL_X509_CHAINへのポインタ。 @@ -4047,11 +4047,12 @@ unsigned char* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx); WOLFSSL_X509_CHAIN* chain = &session->chain; int idx = 999; // set idx ... - WOLFSSL_X509_CHAIN ptr; + WOLFSSL_X509* ptr; prt = wolfSSL_get_chain_X509(chain, idx); if(ptr != NULL){ //ptr contains the cert at the index specified + wolfSSL_FreeX509(ptr); } else { // ptr is NULL } From 8187937bc0360651712624eb43bb7bd9eaef0744 Mon Sep 17 00:00:00 2001 From: Kareem Date: Fri, 24 Mar 2023 15:44:55 -0700 Subject: [PATCH 223/391] Fix PowerPC inline assembly on old GNU as. It does not like an empty clobbered register line, so simply omit the line. --- wolfcrypt/src/sp_int.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 6b8a1e7b5aa..503a8988ac0 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -3638,7 +3638,6 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "li %[o], 0 \n\t" \ : [l] "+r" (vl), [h] "+r" (vh), [o] "=r" (vo) \ : [a] "r" (va), [b] "r" (vb) \ - : \ ) /* Multiply va by vb and add double size result into: vo | vh | vl */ #define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ @@ -3764,7 +3763,6 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "cntlzw %[n], %[a] \n\t" \ : [n] "=r" (vn) \ : [a] "r" (va) \ - : \ ) #define SP_INT_ASM_AVAILABLE From f650a7d980e079846e86fb557035c30f4cc75206 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 27 Apr 2023 17:38:29 -0500 Subject: [PATCH 224/391] configure.ac: escape backslashes when generating preprocessor directives for .build_params; delete backslashes and process parenthesized arguments correctly when generating options.h. --- configure.ac | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/configure.ac b/configure.ac index 1c87cf180e2..7622c2226c6 100644 --- a/configure.ac +++ b/configure.ac @@ -8647,8 +8647,8 @@ fi if test "$ENABLED_REPRODUCIBLE_BUILD" != "yes" then - echo "#define LIBWOLFSSL_CONFIGURE_ARGS \"$ac_configure_args\"" > "${output_objdir}/.build_params" && - echo "#define LIBWOLFSSL_GLOBAL_CFLAGS \"$CPPFLAGS $AM_CPPFLAGS $CFLAGS $AM_CFLAGS\" LIBWOLFSSL_GLOBAL_EXTRA_CFLAGS" >> "${output_objdir}/.build_params" || + echo "#define LIBWOLFSSL_CONFIGURE_ARGS \"$ac_configure_args\"" | sed 's/\\/\\\\/g' > "${output_objdir}/.build_params" && + echo "#define LIBWOLFSSL_GLOBAL_CFLAGS \"$CPPFLAGS $AM_CPPFLAGS $CFLAGS $AM_CFLAGS\" LIBWOLFSSL_GLOBAL_EXTRA_CFLAGS" | sed 's/\\/\\\\/g' >> "${output_objdir}/.build_params" || AC_MSG_ERROR([Couldn't create ${output_objdir}/.build_params.]) else rm -f "${output_objdir}/.build_params" @@ -8693,8 +8693,9 @@ for option in $CPPFLAGS $AM_CPPFLAGS $CFLAGS $AM_CFLAGS; do opt_type=$(echo $option | $TRIM ) case "$opt_type" in -D) - RHS_only=$(echo $option | sed 's/^-D//') - noequalsign=$(echo $RHS_only | sed 's/=/ /') + option=$(echo "$option" | tr -d '\\') + RHS_only=$(echo "$option" | sed 's/^-D//') + noequalsign=$(echo "$RHS_only" | tr '=' ' ') if test "$noequalsign" = "NDEBUG" || test "$noequalsign" = "DEBUG" then if test "$verbose" = "yes"; then @@ -8710,7 +8711,9 @@ for option in $CPPFLAGS $AM_CPPFLAGS $CFLAGS $AM_CFLAGS; do echo "#ifndef WOLFSSL_OPTIONS_IGNORE_SYS" >> $OPTION_FILE fi - noarg=$(echo "$RHS_only" | sed 's/=.*//') + # note need to use both autotools-style [] quoting and shell-style '' + # quoting for sed script with [] character set expression here. + noarg=$(echo "$RHS_only" | sed ['s/\(([^=)]*)\)\{0,1\}=.*//']) echo "#undef $noarg" >> $OPTION_FILE echo "#define $noequalsign" >> $OPTION_FILE From b7bceac3ae5c36d1b797456e9e34300effa107b8 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 27 Apr 2023 17:46:56 -0500 Subject: [PATCH 225/391] wolfcrypt/test/test.c: add TEST_FAIL() macro (counterpart to incumbent TEST_PASS()), by default same as incumbent functionality, but #ifdef TEST_ALWAYS_RUN_TO_END, print errors as they occur but continue to end. --- wolfcrypt/test/test.c | 210 ++++++++++++++++++++++-------------------- 1 file changed, 112 insertions(+), 98 deletions(-) diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index a01982714ad..4b8d11d145a 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -789,6 +789,12 @@ static int wolfssl_pb_print(const char* msg, ...) } #endif +#ifdef TEST_ALWAYS_RUN_TO_END + #define TEST_FAIL(msg, retval) do { last_failed_test_ret = (retval); render_error_message(msg, retval); } while (0) +#elif !defined(TEST_FAIL) + #define TEST_FAIL(msg, retval) return err_sys(msg, retval) +#endif + #ifdef HAVE_STACK_SIZE THREAD_RETURN WOLFSSL_THREAD wolfcrypt_test(void* args) #else @@ -798,6 +804,9 @@ int wolfcrypt_test(void* args) int ret; #ifdef WOLFSSL_TRACK_MEMORY_VERBOSE long heap_baselineAllocs, heap_baselineBytes; +#endif +#ifdef TEST_ALWAYS_RUN_TO_END + int last_failed_test_ret = 0; #endif STACK_SIZE_INIT(); @@ -918,29 +927,29 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifdef HAVE_SELFTEST if ( (ret = wolfCrypt_SelfTest()) != 0) - return err_sys("CAVP selftest failed!\n", ret); + TEST_FAIL("CAVP selftest failed!\n", ret); else TEST_PASS("CAVP selftest passed!\n"); #endif if ( (ret = error_test()) != 0) - return err_sys("error test failed!\n", ret); + TEST_FAIL("error test failed!\n", ret); else TEST_PASS("error test passed!\n"); if ( (ret = memory_test()) != 0) - return err_sys("MEMORY test failed!\n", ret); + TEST_FAIL("MEMORY test failed!\n", ret); else TEST_PASS("MEMORY test passed!\n"); #ifndef NO_CODING if ( (ret = base64_test()) != 0) - return err_sys("base64 test failed!\n", ret); + TEST_FAIL("base64 test failed!\n", ret); else TEST_PASS("base64 test passed!\n"); #ifdef WOLFSSL_BASE16 if ( (ret = base16_test()) != 0) - return err_sys("base16 test failed!\n", ret); + TEST_FAIL("base16 test failed!\n", ret); else TEST_PASS("base16 test passed!\n"); #endif @@ -948,70 +957,70 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifndef NO_ASN if ( (ret = asn_test()) != 0) - return err_sys("asn test failed!\n", ret); + TEST_FAIL("asn test failed!\n", ret); else TEST_PASS("asn test passed!\n"); #endif #ifndef WC_NO_RNG if ( (ret = random_test()) != 0) - return err_sys("RANDOM test failed!\n", ret); + TEST_FAIL("RANDOM test failed!\n", ret); else TEST_PASS("RANDOM test passed!\n"); #endif /* WC_NO_RNG */ #ifndef NO_MD5 if ( (ret = md5_test()) != 0) - return err_sys("MD5 test failed!\n", ret); + TEST_FAIL("MD5 test failed!\n", ret); else TEST_PASS("MD5 test passed!\n"); #endif #ifdef WOLFSSL_MD2 if ( (ret = md2_test()) != 0) - return err_sys("MD2 test failed!\n", ret); + TEST_FAIL("MD2 test failed!\n", ret); else TEST_PASS("MD2 test passed!\n"); #endif #ifndef NO_MD4 if ( (ret = md4_test()) != 0) - return err_sys("MD4 test failed!\n", ret); + TEST_FAIL("MD4 test failed!\n", ret); else TEST_PASS("MD4 test passed!\n"); #endif #ifndef NO_SHA if ( (ret = sha_test()) != 0) - return err_sys("SHA test failed!\n", ret); + TEST_FAIL("SHA test failed!\n", ret); else TEST_PASS("SHA test passed!\n"); #endif #ifdef WOLFSSL_SHA224 if ( (ret = sha224_test()) != 0) - return err_sys("SHA-224 test failed!\n", ret); + TEST_FAIL("SHA-224 test failed!\n", ret); else TEST_PASS("SHA-224 test passed!\n"); #endif #ifndef NO_SHA256 if ( (ret = sha256_test()) != 0) - return err_sys("SHA-256 test failed!\n", ret); + TEST_FAIL("SHA-256 test failed!\n", ret); else TEST_PASS("SHA-256 test passed!\n"); #endif #ifdef WOLFSSL_SHA384 if ( (ret = sha384_test()) != 0) - return err_sys("SHA-384 test failed!\n", ret); + TEST_FAIL("SHA-384 test failed!\n", ret); else TEST_PASS("SHA-384 test passed!\n"); #endif #ifdef WOLFSSL_SHA512 if ((ret = sha512_test()) != 0) { - return err_sys("SHA-512 test failed!\n", ret); + TEST_FAIL("SHA-512 test failed!\n", ret); } else { TEST_PASS("SHA-512 test passed!\n"); @@ -1020,7 +1029,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if !defined(WOLFSSL_NOSHA512_224) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST) if ((ret = sha512_224_test()) != 0) { - return err_sys("SHA-512/224 test failed!\n", ret); + TEST_FAIL("SHA-512/224 test failed!\n", ret); } else TEST_PASS("SHA-512/224 test passed!\n"); @@ -1029,7 +1038,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if !defined(WOLFSSL_NOSHA512_256) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST) if ((ret = sha512_256_test()) != 0) { - return err_sys("SHA-512/256 test failed!\n", ret); + TEST_FAIL("SHA-512/256 test failed!\n", ret); } else TEST_PASS("SHA-512/256 test passed!\n"); @@ -1039,48 +1048,48 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifdef WOLFSSL_SHA3 if ( (ret = sha3_test()) != 0) - return err_sys("SHA-3 test failed!\n", ret); + TEST_FAIL("SHA-3 test failed!\n", ret); else TEST_PASS("SHA-3 test passed!\n"); #endif #ifdef WOLFSSL_SHAKE128 if ( (ret = shake128_test()) != 0) - return err_sys("SHAKE128 test failed!\n", ret); + TEST_FAIL("SHAKE128 test failed!\n", ret); else TEST_PASS("SHAKE128 test passed!\n"); #endif #ifdef WOLFSSL_SHAKE256 if ( (ret = shake256_test()) != 0) - return err_sys("SHAKE256 test failed!\n", ret); + TEST_FAIL("SHAKE256 test failed!\n", ret); else TEST_PASS("SHAKE256 test passed!\n"); #endif #ifndef NO_HASH_WRAPPER if ( (ret = hash_test()) != 0) - return err_sys("Hash test failed!\n", ret); + TEST_FAIL("Hash test failed!\n", ret); else TEST_PASS("Hash test passed!\n"); #endif #ifdef WOLFSSL_RIPEMD if ( (ret = ripemd_test()) != 0) - return err_sys("RIPEMD test failed!\n", ret); + TEST_FAIL("RIPEMD test failed!\n", ret); else TEST_PASS("RIPEMD test passed!\n"); #endif #ifdef HAVE_BLAKE2 if ( (ret = blake2b_test()) != 0) - return err_sys("BLAKE2b test failed!\n", ret); + TEST_FAIL("BLAKE2b test failed!\n", ret); else TEST_PASS("BLAKE2b test passed!\n"); #endif #ifdef HAVE_BLAKE2S if ( (ret = blake2s_test()) != 0) - return err_sys("BLAKE2s test failed!\n", ret); + TEST_FAIL("BLAKE2s test failed!\n", ret); else TEST_PASS("BLAKE2s test passed!\n"); #endif @@ -1089,42 +1098,42 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if !defined(NO_MD5) && !(defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) \ && (HAVE_FIPS_VERSION >= 5)) if ( (ret = hmac_md5_test()) != 0) - return err_sys("HMAC-MD5 test failed!\n", ret); + TEST_FAIL("HMAC-MD5 test failed!\n", ret); else TEST_PASS("HMAC-MD5 test passed!\n"); #endif #ifndef NO_SHA if ( (ret = hmac_sha_test()) != 0) - return err_sys("HMAC-SHA test failed!\n", ret); + TEST_FAIL("HMAC-SHA test failed!\n", ret); else TEST_PASS("HMAC-SHA test passed!\n"); #endif #ifdef WOLFSSL_SHA224 if ( (ret = hmac_sha224_test()) != 0) - return err_sys("HMAC-SHA224 test failed!\n", ret); + TEST_FAIL("HMAC-SHA224 test failed!\n", ret); else TEST_PASS("HMAC-SHA224 test passed!\n"); #endif #ifndef NO_SHA256 if ( (ret = hmac_sha256_test()) != 0) - return err_sys("HMAC-SHA256 test failed!\n", ret); + TEST_FAIL("HMAC-SHA256 test failed!\n", ret); else TEST_PASS("HMAC-SHA256 test passed!\n"); #endif #ifdef WOLFSSL_SHA384 if ( (ret = hmac_sha384_test()) != 0) - return err_sys("HMAC-SHA384 test failed!\n", ret); + TEST_FAIL("HMAC-SHA384 test failed!\n", ret); else TEST_PASS("HMAC-SHA384 test passed!\n"); #endif #ifdef WOLFSSL_SHA512 if ( (ret = hmac_sha512_test()) != 0) - return err_sys("HMAC-SHA512 test failed!\n", ret); + TEST_FAIL("HMAC-SHA512 test failed!\n", ret); else TEST_PASS("HMAC-SHA512 test passed!\n"); #endif @@ -1133,7 +1142,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ !defined(WOLFSSL_NOSHA3_224) && !defined(WOLFSSL_NOSHA3_256) && \ !defined(WOLFSSL_NOSHA3_384) && !defined(WOLFSSL_NOSHA3_512) if ( (ret = hmac_sha3_test()) != 0) - return err_sys("HMAC-SHA3 test failed!\n", ret); + TEST_FAIL("HMAC-SHA3 test failed!\n", ret); else TEST_PASS("HMAC-SHA3 test passed!\n"); #endif @@ -1141,7 +1150,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(HAVE_HKDF) && !defined(NO_HMAC) PRIVATE_KEY_UNLOCK(); if ( (ret = hkdf_test()) != 0) - return err_sys("HMAC-KDF test failed!\n", ret); + TEST_FAIL("HMAC-KDF test failed!\n", ret); else TEST_PASS("HMAC-KDF test passed!\n"); PRIVATE_KEY_LOCK(); @@ -1151,7 +1160,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifdef WOLFSSL_WOLFSSH PRIVATE_KEY_UNLOCK(); if ( (ret = sshkdf_test()) != 0) - return err_sys("SSH-KDF test failed!\n", ret); + TEST_FAIL("SSH-KDF test failed!\n", ret); else TEST_PASS("SSH-KDF test passed!\n"); PRIVATE_KEY_LOCK(); @@ -1160,7 +1169,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifdef WOLFSSL_TLS13 PRIVATE_KEY_UNLOCK(); if ( (ret = tls13_kdf_test()) != 0) - return err_sys("TLSv1.3 KDF test failed!\n", ret); + TEST_FAIL("TLSv1.3 KDF test failed!\n", ret); else TEST_PASS("TLSv1.3 KDF test passed!\n"); PRIVATE_KEY_LOCK(); @@ -1168,14 +1177,14 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(HAVE_X963_KDF) && defined(HAVE_ECC) if ( (ret = x963kdf_test()) != 0) - return err_sys("X963-KDF test failed!\n", ret); + TEST_FAIL("X963-KDF test failed!\n", ret); else TEST_PASS("X963-KDF test passed!\n"); #endif #if defined(HAVE_HPKE) && defined(HAVE_ECC) && defined(HAVE_AESGCM) if ( (ret = hpke_test()) != 0) - return err_sys("HPKE test failed!\n", ret); + TEST_FAIL("HPKE test failed!\n", ret); else TEST_PASS("HPKE test passed!\n"); #endif @@ -1183,97 +1192,97 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(HAVE_AESGCM) && defined(WOLFSSL_AES_128) && \ !defined(WOLFSSL_AFALG_XILINX_AES) && !defined(WOLFSSL_XILINX_CRYPT) if ( (ret = gmac_test()) != 0) - return err_sys("GMAC test failed!\n", ret); + TEST_FAIL("GMAC test failed!\n", ret); else TEST_PASS("GMAC test passed!\n"); #endif #ifdef WC_RC2 if ( (ret = rc2_test()) != 0) - return err_sys("RC2 test failed!\n", ret); + TEST_FAIL("RC2 test failed!\n", ret); else TEST_PASS("RC2 test passed!\n"); #endif #ifndef NO_RC4 if ( (ret = arc4_test()) != 0) - return err_sys("ARC4 test failed!\n", ret); + TEST_FAIL("ARC4 test failed!\n", ret); else TEST_PASS("ARC4 test passed!\n"); #endif #ifdef HAVE_CHACHA if ( (ret = chacha_test()) != 0) - return err_sys("Chacha test failed!\n", ret); + TEST_FAIL("Chacha test failed!\n", ret); else TEST_PASS("Chacha test passed!\n"); #endif #ifdef HAVE_XCHACHA if ( (ret = XChaCha_test()) != 0) - return err_sys("XChacha test failed!\n", ret); + TEST_FAIL("XChacha test failed!\n", ret); else TEST_PASS("XChacha test passed!\n"); #endif #ifdef HAVE_POLY1305 if ( (ret = poly1305_test()) != 0) - return err_sys("POLY1305 test failed!\n", ret); + TEST_FAIL("POLY1305 test failed!\n", ret); else TEST_PASS("POLY1305 test passed!\n"); #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) if ( (ret = chacha20_poly1305_aead_test()) != 0) - return err_sys("ChaCha20-Poly1305 AEAD test failed!\n", ret); + TEST_FAIL("ChaCha20-Poly1305 AEAD test failed!\n", ret); else TEST_PASS("ChaCha20-Poly1305 AEAD test passed!\n"); #endif #if defined(HAVE_XCHACHA) && defined(HAVE_POLY1305) if ( (ret = XChaCha20Poly1305_test()) != 0) - return err_sys("XChaCha20-Poly1305 AEAD test failed!\n", ret); + TEST_FAIL("XChaCha20-Poly1305 AEAD test failed!\n", ret); else TEST_PASS("XChaCha20-Poly1305 AEAD test passed!\n"); #endif #ifndef NO_DES3 if ( (ret = des_test()) != 0) - return err_sys("DES test failed!\n", ret); + TEST_FAIL("DES test failed!\n", ret); else TEST_PASS("DES test passed!\n"); #endif #ifndef NO_DES3 if ( (ret = des3_test()) != 0) - return err_sys("DES3 test failed!\n", ret); + TEST_FAIL("DES3 test failed!\n", ret); else TEST_PASS("DES3 test passed!\n"); #endif #ifndef NO_AES if ( (ret = aes_test()) != 0) - return err_sys("AES test failed!\n", ret); + TEST_FAIL("AES test failed!\n", ret); else TEST_PASS("AES test passed!\n"); #ifdef WOLFSSL_AES_192 if ( (ret = aes192_test()) != 0) - return err_sys("AES192 test failed!\n", ret); + TEST_FAIL("AES192 test failed!\n", ret); else TEST_PASS("AES192 test passed!\n"); #endif #ifdef WOLFSSL_AES_256 if ( (ret = aes256_test()) != 0) - return err_sys("AES256 test failed!\n", ret); + TEST_FAIL("AES256 test failed!\n", ret); else TEST_PASS("AES256 test passed!\n"); #endif #ifdef WOLFSSL_AES_OFB if ( (ret = aesofb_test()) != 0) - return err_sys("AES-OFB test failed!\n", ret); + TEST_FAIL("AES-OFB test failed!\n", ret); else TEST_PASS("AESOFB test passed!\n"); #endif @@ -1281,13 +1290,13 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifdef HAVE_AESGCM #if !defined(WOLFSSL_AFALG) && !defined(WOLFSSL_DEVCRYPTO) if ( (ret = aesgcm_test()) != 0) - return err_sys("AES-GCM test failed!\n", ret); + TEST_FAIL("AES-GCM test failed!\n", ret); #endif #if !defined(WOLFSSL_AFALG_XILINX_AES) && !defined(WOLFSSL_XILINX_CRYPT) && \ !defined(WOLFSSL_KCAPI_AES) && !(defined(WOLF_CRYPTO_CB) && \ (defined(HAVE_INTEL_QA_SYNC) || defined(HAVE_CAVIUM_OCTEON_SYNC))) if ((ret = aesgcm_default_test()) != 0) { - return err_sys("AES-GCM test failed!\n", ret); + TEST_FAIL("AES-GCM test failed!\n", ret); } #endif if (ret == 0) { @@ -1297,19 +1306,19 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(HAVE_AESCCM) && defined(WOLFSSL_AES_128) if ( (ret = aesccm_test()) != 0) - return err_sys("AES-CCM test failed!\n", ret); + TEST_FAIL("AES-CCM test failed!\n", ret); else TEST_PASS("AES-CCM test passed!\n"); #endif #ifdef HAVE_AES_KEYWRAP if ( (ret = aeskeywrap_test()) != 0) - return err_sys("AES Key Wrap test failed!\n", ret); + TEST_FAIL("AES Key Wrap test failed!\n", ret); else TEST_PASS("AES Key Wrap test passed!\n"); #endif #ifdef WOLFSSL_AES_SIV if ( (ret = aes_siv_test()) != 0) - return err_sys("AES-SIV test failed!\n", ret); + TEST_FAIL("AES-SIV test failed!\n", ret); else TEST_PASS("AES-SIV test passed!\n"); #endif @@ -1317,7 +1326,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifdef HAVE_CAMELLIA if ( (ret = camellia_test()) != 0) - return err_sys("CAMELLIA test failed!\n", ret); + TEST_FAIL("CAMELLIA test failed!\n", ret); else TEST_PASS("CAMELLIA test passed!\n"); #endif @@ -1325,12 +1334,12 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if !defined(NO_RSA) #ifdef WC_RSA_NO_PADDING if ( (ret = rsa_no_pad_test()) != 0) - return err_sys("RSA NOPAD test failed!\n", ret); + TEST_FAIL("RSA NOPAD test failed!\n", ret); else TEST_PASS("RSA NOPAD test passed!\n"); #endif if ( (ret = rsa_test()) != 0) - return err_sys("RSA test failed!\n", ret); + TEST_FAIL("RSA test failed!\n", ret); else TEST_PASS("RSA test passed!\n"); #endif @@ -1338,7 +1347,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifndef NO_DH PRIVATE_KEY_UNLOCK(); if ( (ret = dh_test()) != 0) - return err_sys("DH test failed!\n", ret); + TEST_FAIL("DH test failed!\n", ret); else TEST_PASS("DH test passed!\n"); PRIVATE_KEY_LOCK(); @@ -1346,49 +1355,49 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifndef NO_DSA if ( (ret = dsa_test()) != 0) - return err_sys("DSA test failed!\n", ret); + TEST_FAIL("DSA test failed!\n", ret); else TEST_PASS("DSA test passed!\n"); #endif #ifdef WOLFCRYPT_HAVE_SRP if ( (ret = srp_test()) != 0) - return err_sys("SRP test failed!\n", ret); + TEST_FAIL("SRP test failed!\n", ret); else TEST_PASS("SRP test passed!\n"); #endif #ifndef NO_PWDBASED if ( (ret = pwdbased_test()) != 0) - return err_sys("PWDBASED test failed!\n", ret); + TEST_FAIL("PWDBASED test failed!\n", ret); else TEST_PASS("PWDBASED test passed!\n"); #endif #if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) if ( (ret = openssl_test()) != 0) - return err_sys("OPENSSL test failed!\n", ret); + TEST_FAIL("OPENSSL test failed!\n", ret); else TEST_PASS("OPENSSL test passed!\n"); if ( (ret = openSSL_evpMD_test()) != 0) - return err_sys("OPENSSL (EVP MD) test failed!\n", ret); + TEST_FAIL("OPENSSL (EVP MD) test failed!\n", ret); else TEST_PASS("OPENSSL (EVP MD) passed!\n"); if ( (ret = openssl_pkey0_test()) != 0) - return err_sys("OPENSSL (PKEY0) test failed!\n", ret); + TEST_FAIL("OPENSSL (PKEY0) test failed!\n", ret); else TEST_PASS("OPENSSL (PKEY0) passed!\n"); if ( (ret = openssl_pkey1_test()) != 0) - return err_sys("OPENSSL (PKEY1) test failed!\n", ret); + TEST_FAIL("OPENSSL (PKEY1) test failed!\n", ret); else TEST_PASS("OPENSSL (PKEY1) passed!\n"); #if !defined(WOLF_CRYPTO_CB_ONLY_RSA) && !defined(WOLF_CRYPTO_CB_ONLY_ECC) if ( (ret = openssl_evpSig_test()) != 0) - return err_sys("OPENSSL (EVP Sign/Verify) test failed!\n", ret); + TEST_FAIL("OPENSSL (EVP Sign/Verify) test failed!\n", ret); else TEST_PASS("OPENSSL (EVP Sign/Verify) passed!\n"); #endif @@ -1397,14 +1406,14 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(HAVE_ECC) PRIVATE_KEY_UNLOCK(); if ( (ret = ecc_test()) != 0) - return err_sys("ECC test failed!\n", ret); + TEST_FAIL("ECC test failed!\n", ret); else TEST_PASS("ECC test passed!\n"); PRIVATE_KEY_LOCK(); #if defined(HAVE_ECC_ENCRYPT) && defined(HAVE_AES_CBC) && \ (defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_256)) if ( (ret = ecc_encrypt_test()) != 0) - return err_sys("ECC Enc test failed!\n", ret); + TEST_FAIL("ECC Enc test failed!\n", ret); else TEST_PASS("ECC Enc test passed!\n"); #endif @@ -1414,7 +1423,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ !defined(WOLF_CRYPTO_CB_ONLY_ECC) /* skip for ATECC508/608A, cannot import private key buffers */ if ( (ret = ecc_test_buffers()) != 0) - return err_sys("ECC buffer test failed!\n", ret); + TEST_FAIL("ECC buffer test failed!\n", ret); else TEST_PASS("ECC buffer test passed!\n"); #endif @@ -1423,7 +1432,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if !defined(NO_ASN_TIME) && !defined(NO_RSA) && defined(WOLFSSL_TEST_CERT) && \ !defined(NO_FILESYSTEM) if ( (ret = cert_test()) != 0) - return err_sys("CERT test failed!\n", ret); + TEST_FAIL("CERT test failed!\n", ret); else TEST_PASS("CERT test passed!\n"); #endif @@ -1431,7 +1440,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_TEST_CERT) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && defined(WOLFSSL_GEN_CERT) if ( (ret = certext_test()) != 0) - return err_sys("CERT EXT test failed!\n", ret); + TEST_FAIL("CERT EXT test failed!\n", ret); else TEST_PASS("CERT EXT test passed!\n"); #endif @@ -1439,76 +1448,76 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(WOLFSSL_CERT_GEN_CACHE) && defined(WOLFSSL_TEST_CERT) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN) if ( (ret = decodedCertCache_test()) != 0) - return err_sys("DECODED CERT CACHE test failed!\n", ret); + TEST_FAIL("DECODED CERT CACHE test failed!\n", ret); else TEST_PASS("DECODED CERT CACHE test passed!\n"); #endif #ifdef HAVE_CURVE25519 if ( (ret = curve25519_test()) != 0) - return err_sys("CURVE25519 test failed!\n", ret); + TEST_FAIL("CURVE25519 test failed!\n", ret); else TEST_PASS("CURVE25519 test passed!\n"); #endif #ifdef HAVE_ED25519 if ( (ret = ed25519_test()) != 0) - return err_sys("ED25519 test failed!\n", ret); + TEST_FAIL("ED25519 test failed!\n", ret); else TEST_PASS("ED25519 test passed!\n"); #endif #ifdef HAVE_CURVE448 if ( (ret = curve448_test()) != 0) - return err_sys("CURVE448 test failed!\n", ret); + TEST_FAIL("CURVE448 test failed!\n", ret); else TEST_PASS("CURVE448 test passed!\n"); #endif #ifdef HAVE_ED448 if ( (ret = ed448_test()) != 0) - return err_sys("ED448 test failed!\n", ret); + TEST_FAIL("ED448 test failed!\n", ret); else TEST_PASS("ED448 test passed!\n"); #endif #ifdef WOLFSSL_HAVE_KYBER if ( (ret = kyber_test()) != 0) - return err_sys("KYBER test failed!\n", ret); + TEST_FAIL("KYBER test failed!\n", ret); else TEST_PASS("KYBER test passed!\n"); #endif #ifdef WOLFCRYPT_HAVE_ECCSI if ( (ret = eccsi_test()) != 0) - return err_sys("ECCSI test failed!\n", ret); + TEST_FAIL("ECCSI test failed!\n", ret); else TEST_PASS("ECCSI test passed!\n"); #endif #ifdef WOLFCRYPT_HAVE_SAKKE if ( (ret = sakke_test()) != 0) - return err_sys("SAKKE test failed!\n", ret); + TEST_FAIL("SAKKE test failed!\n", ret); else TEST_PASS("SAKKE test passed!\n"); #endif #if defined(WOLFSSL_CMAC) && !defined(NO_AES) if ( (ret = cmac_test()) != 0) - return err_sys("CMAC test failed!\n", ret); + TEST_FAIL("CMAC test failed!\n", ret); else TEST_PASS("CMAC test passed!\n"); #endif #if defined(WOLFSSL_SIPHASH) if ( (ret = siphash_test()) != 0) - return err_sys("SipHash test failed!\n", ret); + TEST_FAIL("SipHash test failed!\n", ret); else TEST_PASS("SipHash test passed!\n"); #endif #ifdef HAVE_LIBZ if ( (ret = compress_test()) != 0) - return err_sys("COMPRESS test failed!\n", ret); + TEST_FAIL("COMPRESS test failed!\n", ret); else TEST_PASS("COMPRESS test passed!\n"); #endif @@ -1516,29 +1525,29 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #ifdef HAVE_PKCS7 #ifndef NO_PKCS7_ENCRYPTED_DATA if ( (ret = pkcs7encrypted_test()) != 0) - return err_sys("PKCS7encrypted test failed!\n", ret); + TEST_FAIL("PKCS7encrypted test failed!\n", ret); else TEST_PASS("PKCS7encrypted test passed!\n"); #endif #if defined(HAVE_LIBZ) && !defined(NO_PKCS7_COMPRESSED_DATA) if ( (ret = pkcs7compressed_test()) != 0) - return err_sys("PKCS7compressed test failed!\n", ret); + TEST_FAIL("PKCS7compressed test failed!\n", ret); else TEST_PASS("PKCS7compressed test passed!\n"); #endif if ( (ret = pkcs7signed_test()) != 0) - return err_sys("PKCS7signed test failed!\n", ret); + TEST_FAIL("PKCS7signed test failed!\n", ret); else TEST_PASS("PKCS7signed test passed!\n"); if ( (ret = pkcs7enveloped_test()) != 0) - return err_sys("PKCS7enveloped test failed!\n", ret); + TEST_FAIL("PKCS7enveloped test failed!\n", ret); else TEST_PASS("PKCS7enveloped test passed!\n"); #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) if ( (ret = pkcs7authenveloped_test()) != 0) - return err_sys("PKCS7authenveloped test failed!\n", ret); + TEST_FAIL("PKCS7authenveloped test failed!\n", ret); else TEST_PASS("PKCS7authenveloped test passed!\n"); #endif @@ -1547,14 +1556,14 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(WOLFSSL_PUBLIC_MP) && \ (defined(WOLFSSL_SP_MATH_ALL) || defined(USE_FAST_MATH)) if ( (ret = mp_test()) != 0) - return err_sys("mp test failed!\n", ret); + TEST_FAIL("mp test failed!\n", ret); else TEST_PASS("mp test passed!\n"); #endif #if defined(WOLFSSL_PUBLIC_MP) && defined(WOLFSSL_KEY_GEN) if ( (ret = prime_test()) != 0) - return err_sys("prime test failed!\n", ret); + TEST_FAIL("prime test failed!\n", ret); else TEST_PASS("prime test passed!\n"); #endif @@ -1563,19 +1572,19 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ (defined(WOLFSSL_TEST_CERT) || defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) if ( (ret = berder_test()) != 0) - return err_sys("ber-der test failed!\n", ret); + TEST_FAIL("ber-der test failed!\n", ret); else TEST_PASS("ber-der test passed!\n"); #endif if ( (ret = logging_test()) != 0) - return err_sys("logging test failed!\n", ret); + TEST_FAIL("logging test failed!\n", ret); else TEST_PASS("logging test passed!\n"); #if !defined(NO_ASN) && !defined(NO_ASN_TIME) if ( (ret = time_test()) != 0) - return err_sys("time test failed!\n", ret); + TEST_FAIL("time test failed!\n", ret); else TEST_PASS("time test passed!\n"); #endif @@ -1585,20 +1594,20 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #else if ((ret = mutex_test()) != 0) #endif - return err_sys("mutex test failed!\n", ret); + TEST_FAIL("mutex test failed!\n", ret); else TEST_PASS("mutex test passed!\n"); #if defined(USE_WOLFSSL_MEMORY) && !defined(FREERTOS) if ( (ret = memcb_test()) != 0) - return err_sys("memcb test failed!\n", ret); + TEST_FAIL("memcb test failed!\n", ret); else TEST_PASS("memcb test passed!\n"); #endif #ifdef WOLFSSL_CAAM_BLOB if ( (ret = blob_test()) != 0) - return err_sys("blob test failed!\n", ret); + TEST_FAIL("blob test failed!\n", ret); else TEST_PASS("blob test passed!\n"); #endif @@ -1607,14 +1616,14 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ !(defined(HAVE_INTEL_QAT_SYNC) || defined(HAVE_CAVIUM_OCTEON_SYNC) || \ defined(WOLFSSL_QNX_CAAM)) if ( (ret = cryptocb_test()) != 0) - return err_sys("crypto callback test failed!\n", ret); + TEST_FAIL("crypto callback test failed!\n", ret); else TEST_PASS("crypto callback test passed!\n"); #endif #ifdef WOLFSSL_CERT_PIV if ( (ret = certpiv_test()) != 0) - return err_sys("cert piv test failed!\n", ret); + TEST_FAIL("cert piv test failed!\n", ret); else TEST_PASS("cert piv test passed!\n"); #endif @@ -1637,6 +1646,11 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ wc_ecc_fp_free(); #endif +#ifdef TEST_ALWAYS_RUN_TO_END + if (last_failed_test_ret != 0) + ret = last_failed_test_ret; +#endif + if (args) ((func_args*)args)->return_code = ret; From c5e7cdec2e91786e42975a1c3f1abdf4f3411c14 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 27 Apr 2023 17:48:32 -0500 Subject: [PATCH 226/391] linuxkm: in {save,restore}_vector_registers_x86(), check if vector register file has already been saved and invalidated, and if so, inhibit the kernel_fpu_{begin,end}() wrap and instead just use preempt_{disable,enable}() wraps. --- linuxkm/linuxkm_memory.c | 53 +++++++++++++++++++++++++++++++--------- wolfcrypt/src/memory.c | 4 +++ 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/linuxkm/linuxkm_memory.c b/linuxkm/linuxkm_memory.c index 660f9fbaa28..facee2af268 100644 --- a/linuxkm/linuxkm_memory.c +++ b/linuxkm/linuxkm_memory.c @@ -30,6 +30,8 @@ #endif #else static unsigned int *wolfcrypt_linuxkm_fpu_states = NULL; + #define WC_FPU_COUNT_MASK 0x7fffffffU + #define WC_FPU_SAVED_MASK 0x80000000U #endif static WARN_UNUSED_RESULT inline int am_in_hard_interrupt_handler(void) @@ -223,8 +225,10 @@ */ ((unsigned char *)wolfcrypt_linuxkm_fpu_states[processor_id])[PAGE_SIZE-1] = 1; #else /* !LINUXKM_SIMD_IRQ */ - if (wolfcrypt_linuxkm_fpu_states[processor_id] != 0) { - if (wolfcrypt_linuxkm_fpu_states[processor_id] == ~0U) { + if (wolfcrypt_linuxkm_fpu_states[processor_id] != 0U) { + if ((wolfcrypt_linuxkm_fpu_states[processor_id] & WC_FPU_COUNT_MASK) + == WC_FPU_COUNT_MASK) + { preempt_enable(); pr_err("save_vector_registers_x86 recursion register overflow for " "cpu id %d.\n", processor_id); @@ -234,11 +238,28 @@ return 0; } } - kernel_fpu_begin(); - preempt_enable(); /* kernel_fpu_begin() does its own - * preempt_disable(). decrement ours. - */ - wolfcrypt_linuxkm_fpu_states[processor_id] = 1; + + /* if kernel_fpu_begin() won't actually save the reg file (because + * it was already saved and invalidated, or because we're in a + * kernel thread), don't call kernel_fpu_begin() here, nor call + * kernel_fpu_end() in cleanup. this avoids pointless overhead. in + * kernels >=5.17.12 (from changes to irq_fpu_usable() in linux + * commit 59f5ede3bc0f, backported somewhere >5.17.5), this also + * fixes register corruption. + */ + if ((current->flags & PF_KTHREAD) || + test_thread_flag(TIF_NEED_FPU_LOAD)) + { + wolfcrypt_linuxkm_fpu_states[processor_id] = + WC_FPU_SAVED_MASK + 1U; /* set msb 1 to inhibit kernel_fpu_end() at cleanup. */ + /* keep preempt_disable()d from above. */ + } else { + kernel_fpu_begin(); + preempt_enable(); /* kernel_fpu_begin() does its own + * preempt_disable(). decrement ours. + */ + wolfcrypt_linuxkm_fpu_states[processor_id] = 1U; /* set msb 0 to trigger kernel_fpu_end() at cleanup. */ + } #endif /* !LINUXKM_SIMD_IRQ */ return 0; @@ -287,19 +308,29 @@ kernel_fpu_end(); } #else /* !LINUXKM_SIMD_IRQ */ - if (wolfcrypt_linuxkm_fpu_states[processor_id] == 0) + if ((wolfcrypt_linuxkm_fpu_states[processor_id] & WC_FPU_COUNT_MASK) == 0U) { pr_err("restore_vector_registers_x86 called for cpu id %d " "without saved context.\n", processor_id); return; } - if (--wolfcrypt_linuxkm_fpu_states[processor_id] > 0) { - preempt_enable(); /* preempt_disable count will still be nonzero after this decrement. */ + if ((--wolfcrypt_linuxkm_fpu_states[processor_id] & WC_FPU_COUNT_MASK) > 0U) { + preempt_enable(); /* preempt_disable count may still be nonzero + * after this decrement, but any remaining + * count(s) aren't ours. + */ return; } - kernel_fpu_end(); + if (wolfcrypt_linuxkm_fpu_states[processor_id] == 0U) { + kernel_fpu_end(); + } else { + preempt_enable(); /* preempt_disable count will still be nonzero + * after this decrement. + */ + wolfcrypt_linuxkm_fpu_states[processor_id] = 0U; + } #endif /* !LINUXKM_SIMD_IRQ */ return; diff --git a/wolfcrypt/src/memory.c b/wolfcrypt/src/memory.c index 1e0cbf30aff..83a23ad7928 100644 --- a/wolfcrypt/src/memory.c +++ b/wolfcrypt/src/memory.c @@ -24,6 +24,10 @@ #include #endif +#ifdef WOLFSSL_LINUXKM + #define WOLFSSL_NEED_LINUX_CURRENT +#endif + #include /* check old macros @wc_fips */ From 5278a3a6b92af5b3d7dad3ddfbb8f3ccf2d52021 Mon Sep 17 00:00:00 2001 From: TakayukiMatsuo Date: Wed, 26 Apr 2023 17:12:14 +0900 Subject: [PATCH 227/391] Fix issues in test_wolfSSL_dtls_fragments --- tests/api.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/api.c b/tests/api.c index 1a3e47fddb4..05974a84a54 100644 --- a/tests/api.c +++ b/tests/api.c @@ -60917,6 +60917,7 @@ static void test_wolfSSL_dtls12_fragments_spammer(WOLFSSL* ssl) #ifdef WOLFSSL_DTLS13 static void test_wolfSSL_dtls13_fragments_spammer(WOLFSSL* ssl) { + const word16 sendCountMax = 100; byte b[150]; /* buffer for the messages to send */ size_t idx = 0; size_t msg_offset = 0; @@ -60944,7 +60945,7 @@ static void test_wolfSSL_dtls13_fragments_spammer(WOLFSSL* ssl) /* fragment contents */ idx += 100; - for (; ret > 0; msg_number++) { + for (; ret > 0 && msg_number < sendCountMax; msg_number++) { byte sendBuf[150]; int sendSz = sizeof(sendBuf); struct timespec delay; @@ -60993,9 +60994,10 @@ static int test_wolfSSL_dtls_fragments(void) AssertFalse(func_cb_server.return_code); /* The socket should be closed by the server resulting in a - * socket error or reading a close notify alert */ + * socket error, fatal error or reading a close notify alert */ if (func_cb_client.last_err != SOCKET_ERROR_E && - func_cb_client.last_err != WOLFSSL_ERROR_ZERO_RETURN) { + func_cb_client.last_err != WOLFSSL_ERROR_ZERO_RETURN && + func_cb_client.last_err != FATAL_ERROR) { AssertIntEQ(func_cb_client.last_err, SOCKET_ERROR_E); } /* Check the server returned an error indicating the msg buffer From 1ec0adece9e6b308d8f51b01bb8ff654977fbfd0 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 27 Apr 2023 09:41:31 +1000 Subject: [PATCH 228/391] SP int ARMv6: clz not available, correct #if Checking for architecture less than 7 to use clz instruction when clz is only guaranteed to be available in 7 or more. Reverse logic. --- wolfcrypt/src/sp_int.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 503a8988ac0..c95512b32f7 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -1245,7 +1245,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "r" (va), [b] "r" (vb), [c] "r" (vc) \ : "cc" \ ) -#if defined(WOLFSSL_SP_ARM_ARCH) && (WOLFSSL_SP_ARM_ARCH < 7) +#if defined(WOLFSSL_SP_ARM_ARCH) && (WOLFSSL_SP_ARM_ARCH >= 7) /* Count leading zeros - instruction only available on ARMv7 and newer. */ #define SP_ASM_LZCNT(va, vn) \ __asm__ __volatile__ ( \ From cddecd6ca0891a56b7cb4b7e968806417b2debb0 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz <49391366+julek-wolfssl@users.noreply.github.com> Date: Fri, 28 Apr 2023 19:00:24 +0200 Subject: [PATCH 229/391] Zephyr misc fixes for TLS (#6353) * zephyr wolfssl_tls_sock: fix project name * zephyr tls_sock.c: don't include options.h when using user settings * zephyr: define XSTAT_TYPE for use with XSTAT --- wolfssl/wolfcrypt/wc_port.h | 2 +- zephyr/samples/wolfssl_tls_sock/CMakeLists.txt | 2 +- zephyr/samples/wolfssl_tls_sock/src/tls_sock.c | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 83d1d86157e..98606204b51 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -516,7 +516,6 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #include #define XFILE struct fs_file_t* - #define STAT struct fs_dirent /* These are our wrappers for opening and closing files to * make the API more POSIX like. */ @@ -537,6 +536,7 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFGETS(b,s,f) -2 /* Not ported yet */ #define XSTAT fs_stat + #define XSTAT_TYPE struct fs_dirent #define XS_ISREG(s) (s == FS_DIR_ENTRY_FILE) #define SEPARATOR_CHAR ':' diff --git a/zephyr/samples/wolfssl_tls_sock/CMakeLists.txt b/zephyr/samples/wolfssl_tls_sock/CMakeLists.txt index 512a0006fc2..a1208f50293 100644 --- a/zephyr/samples/wolfssl_tls_sock/CMakeLists.txt +++ b/zephyr/samples/wolfssl_tls_sock/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.13.1) include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE) -project(wolfssl_tls_threaded) +project(wolfssl_tls_sock) FILE(GLOB app_sources src/*.c) target_sources(app PRIVATE ${app_sources}) diff --git a/zephyr/samples/wolfssl_tls_sock/src/tls_sock.c b/zephyr/samples/wolfssl_tls_sock/src/tls_sock.c index 489591ec8cf..8e71527db72 100644 --- a/zephyr/samples/wolfssl_tls_sock/src/tls_sock.c +++ b/zephyr/samples/wolfssl_tls_sock/src/tls_sock.c @@ -19,7 +19,9 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#include +#ifndef WOLFSSL_USER_SETTINGS + #include +#endif #include #define USE_CERT_BUFFERS_2048 #include From 73c25fccb89dd0346fca659c4dc5d905773c47a7 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 21 Apr 2023 09:42:57 +0200 Subject: [PATCH 230/391] Allow cert callback to override skipAddCA --- src/internal.c | 17 +++++--- tests/api.c | 109 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 6 deletions(-) diff --git a/src/internal.c b/src/internal.c index ae0db056cfc..65444527d3c 100644 --- a/src/internal.c +++ b/src/internal.c @@ -13695,10 +13695,10 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, ssl->peerVerifyRet = 0; #endif args->verifyErr = 0; - } - /* do not add to certificate manager */ - skipAddCA = 1; + /* do not add to certificate manager */ + skipAddCA = 1; + } } #endif /* WOLFSSL_ALT_CERT_CHAINS */ @@ -13711,7 +13711,12 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, ret = ssl->error = 0; } - + #ifdef WOLFSSL_ALT_CERT_CHAINS + if (ret != 0 && args->dCert->isCA) { + /* do not add to certificate manager */ + skipAddCA = 1; + } + #endif /* If valid CA then add to Certificate Manager */ if (ret == 0 && args->dCert->isCA && @@ -13745,13 +13750,13 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, } /* Handle error codes */ + ssl->error = ret; /* Report SSL error or clear error if + * callback overrides. */ if (ret != 0) { if (!ssl->options.verifyNone) { WOLFSSL_ERROR_VERBOSE(ret); DoCertFatalAlert(ssl, ret); } - ssl->error = ret; /* Report SSL error */ - if (args->lastErr == 0) { args->lastErr = ret; /* save error from last time */ ret = 0; /* reset error */ diff --git a/tests/api.c b/tests/api.c index 05974a84a54..0bea13ed9b4 100644 --- a/tests/api.c +++ b/tests/api.c @@ -65541,6 +65541,114 @@ static int test_harden_no_secure_renegotiation(void) } #endif +#if defined(HAVE_OCSP) && defined(HAVE_IO_TESTS_DEPENDENCIES) +static int test_override_alt_cert_chain_cert_cb(int preverify, + WOLFSSL_X509_STORE_CTX* store) +{ + printf("preverify: %d\n", preverify); + printf("store->error: %d\n", store->error); + printf("error reason: %s\n", wolfSSL_ERR_reason_error_string(store->error)); + if (store->error == OCSP_INVALID_STATUS) { + printf("Overriding OCSP error\n"); + return 1; + } +#ifndef WOLFSSL_ALT_CERT_CHAINS + else if ((store->error == ASN_NO_SIGNER_E || + store->error == ASN_SELF_SIGNED_E +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(HAVE_WEBSERVER) + || store->error == WOLFSSL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY +#endif + ) && store->error_depth == store->totalCerts - 1) { + printf("Overriding no signer error only for root cert\n"); + return 1; + } +#endif + else + return preverify; +} + +static int test_override_alt_cert_chain_ocsp_cb(void* ioCtx, const char* url, + int urlSz, unsigned char* request, int requestSz, + unsigned char** response) +{ + (void)ioCtx; + (void)url; + (void)urlSz; + (void)request; + (void)requestSz; + (void)response; + return -1; +} + +static void test_override_alt_cert_chain_client_ctx_ready(WOLFSSL_CTX* ctx) +{ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, + test_override_alt_cert_chain_cert_cb); + AssertIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_CHECKALL | + WOLFSSL_OCSP_URL_OVERRIDE), WOLFSSL_SUCCESS); + AssertIntEQ(wolfSSL_CTX_SetOCSP_Cb(ctx, + test_override_alt_cert_chain_ocsp_cb, NULL, NULL), WOLFSSL_SUCCESS); + AssertIntEQ(wolfSSL_CTX_SetOCSP_OverrideURL(ctx, "not a url"), + WOLFSSL_SUCCESS); +} + +static void test_override_alt_cert_chain_client_ctx_ready2(WOLFSSL_CTX* ctx) +{ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + AssertIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_CHECKALL | + WOLFSSL_OCSP_URL_OVERRIDE), WOLFSSL_SUCCESS); + AssertIntEQ(wolfSSL_CTX_SetOCSP_Cb(ctx, + test_override_alt_cert_chain_ocsp_cb, NULL, NULL), WOLFSSL_SUCCESS); + AssertIntEQ(wolfSSL_CTX_SetOCSP_OverrideURL(ctx, "not a url"), + WOLFSSL_SUCCESS); +} + +static void test_override_alt_cert_chain_server_ctx_ready(WOLFSSL_CTX* ctx) +{ + AssertIntEQ(wolfSSL_CTX_use_certificate_chain_file(ctx, + "./certs/intermediate/server-chain-alt.pem"), WOLFSSL_SUCCESS); +} + +static int test_override_alt_cert_chain(void) +{ + size_t i; + struct test_params { + ctx_callback client_ctx_cb; + ctx_callback server_ctx_cb; + int result; + } params[] = { + {test_override_alt_cert_chain_client_ctx_ready, + test_override_alt_cert_chain_server_ctx_ready, TEST_SUCCESS}, + {test_override_alt_cert_chain_client_ctx_ready2, + test_override_alt_cert_chain_server_ctx_ready, TEST_FAIL}, + }; + + for (i = 0; i < sizeof(params)/sizeof(*params); i++) { + callback_functions client_cbs, server_cbs; + XMEMSET(&client_cbs, 0, sizeof(client_cbs)); + XMEMSET(&server_cbs, 0, sizeof(server_cbs)); + + printf("test config: %d\n", (int)i); + + client_cbs.ctx_ready = params[i].client_ctx_cb; + server_cbs.ctx_ready = params[i].server_ctx_cb; + + test_wolfSSL_client_server_nofail(&client_cbs, &server_cbs); + + AssertIntEQ(client_cbs.return_code, params[i].result); + AssertIntEQ(server_cbs.return_code, params[i].result); + } + + return TEST_RES_CHECK(1); +} +#else +static int test_override_alt_cert_chain(void) +{ + return TEST_SKIPPED; +} +#endif + /*----------------------------------------------------------------------------* | Main @@ -66577,6 +66685,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_extra_alerts_skip_hs), TEST_DECL(test_extra_alerts_bad_psk), TEST_DECL(test_harden_no_secure_renegotiation), + TEST_DECL(test_override_alt_cert_chain), /* If at some point a stub get implemented this test should fail indicating * a need to implement a new test case */ From ad2df520b70b079c5096a299100890abcbe107c4 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Fri, 28 Apr 2023 13:58:29 -0600 Subject: [PATCH 231/391] Fix uninitialized variable compiler warning --- src/internal.c | 2 +- src/ssl.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/internal.c b/src/internal.c index 65444527d3c..6cbcc9d1457 100644 --- a/src/internal.c +++ b/src/internal.c @@ -10461,7 +10461,7 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, RecordLayerHeader* rh, word16 *size) { - byte tls12minor; + byte tls12minor = 0; #ifdef OPENSSL_ALL word32 start = *inOutIdx; diff --git a/src/ssl.c b/src/ssl.c index b001b86de3a..4bce5d240c5 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -7471,7 +7471,7 @@ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, ret = ProcessUserChain(ctx, buff, sz, format, type, ssl, used, info, verify); if (ret == ASN_NO_PEM_HEADER) { /* Additional chain is optional */ - unsigned long pemErr; + unsigned long pemErr = 0; CLEAR_ASN_NO_PEM_HEADER_ERROR(pemErr); ret = 0; } @@ -9015,7 +9015,7 @@ int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file, (ret == ASN_NO_PEM_HEADER))) { /* Do not fail here if a certificate fails to load, continue to next file */ - unsigned long err; + unsigned long err = 0; CLEAR_ASN_NO_PEM_HEADER_ERROR(err); #if defined(WOLFSSL_QT) ret = WOLFSSL_SUCCESS; From 9e4071a03526bdb15638425d5a4bd4596cabaeeb Mon Sep 17 00:00:00 2001 From: Andras Fekete Date: Fri, 28 Apr 2023 14:08:15 -0400 Subject: [PATCH 232/391] Should only move the index by the amount we wrote --- src/internal.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/internal.c b/src/internal.c index 6cbcc9d1457..c99585cf860 100644 --- a/src/internal.c +++ b/src/internal.c @@ -20919,7 +20919,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, if (args->ivSz > 0) { XMEMCPY(output + args->idx, args->iv, min(args->ivSz, MAX_IV_SZ)); - args->idx += args->ivSz; + args->idx += min(args->ivSz, MAX_IV_SZ); } XMEMCPY(output + args->idx, input, inSz); args->idx += inSz; From 80382a6cfd79c8fa9c478ef8ca7933440100d507 Mon Sep 17 00:00:00 2001 From: Kareem Date: Fri, 28 Apr 2023 16:35:49 -0700 Subject: [PATCH 233/391] Fix wc_PeekErrorNodeLineData not unlocking error queue on error. --- wolfcrypt/src/logging.c | 1 + 1 file changed, 1 insertion(+) diff --git a/wolfcrypt/src/logging.c b/wolfcrypt/src/logging.c index 939700b57ca..04d218d1741 100644 --- a/wolfcrypt/src/logging.c +++ b/wolfcrypt/src/logging.c @@ -1218,6 +1218,7 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, while (1) { int ret = peekErrorNode(idx, file, NULL, line); if (ret == BAD_MUTEX_E || ret == BAD_FUNC_ARG || ret == BAD_STATE_E) { + ERRQ_UNLOCK(); WOLFSSL_MSG("Issue peeking at error node in queue"); return 0; } From b7fe5884c5176824a48a067269a3a09301fdfbd1 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 1 May 2023 11:31:58 -0700 Subject: [PATCH 234/391] Improved fix for STM32 hashing on U5 --- wolfcrypt/src/port/st/stm32.c | 50 +++++++++++++++++-------------- wolfssl/wolfcrypt/port/st/stm32.h | 16 +++++++++- 2 files changed, 43 insertions(+), 23 deletions(-) diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index f72d1872f64..82408dc5879 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -234,7 +234,7 @@ static void wc_Stm32_Hash_Data(STM32_HASH_Context* stmCtx, word32 len) if (len > stmCtx->buffLen) len = stmCtx->buffLen; - /* calculate number of 32-bit blocks */ + /* calculate number of 32-bit blocks - round up */ blocks = ((len + STM32_HASH_REG_SIZE-1) / STM32_HASH_REG_SIZE); #ifdef DEBUG_STM32_HASH printf("STM DIN %d blocks\n", blocks); @@ -268,17 +268,16 @@ int wc_Stm32_Hash_Update(STM32_HASH_Context* stmCtx, word32 algo, byte* local = (byte*)stmCtx->buffer; int wroteToFifo = 0; const word32 fifoSz = (STM32_HASH_FIFO_SIZE * STM32_HASH_REG_SIZE); - - if (blockSize > fifoSz) - blockSize = fifoSz; + word32 chunkSz; #ifdef DEBUG_STM32_HASH printf("STM Hash Update: algo %x, len %d, blockSz %d\n", algo, len, blockSize); #endif + (void)blockSize; /* check that internal buffLen is valid */ - if (stmCtx->buffLen > blockSize) { + if (stmCtx->buffLen > (word32)sizeof(stmCtx->buffer)) { return BUFFER_E; } @@ -288,37 +287,44 @@ int wc_Stm32_Hash_Update(STM32_HASH_Context* stmCtx, word32 algo, /* restore hash context or init as new hash */ wc_Stm32_Hash_RestoreContext(stmCtx, algo); + chunkSz = fifoSz; +#ifdef STM32_HASH_FIFO_WORKAROUND + /* if FIFO already has bytes written then fill remainder first */ + if (stmCtx->fifoBytes > 0) { + chunkSz -= stmCtx->fifoBytes; + stmCtx->fifoBytes = 0; + } +#endif + /* write blocks to FIFO */ while (len) { - word32 fillBlockSz = blockSize, add; - - /* if FIFO already has bytes written then fill remainder first */ - if (stmCtx->fifoBytes > 0) { - fillBlockSz -= stmCtx->fifoBytes; - stmCtx->fifoBytes = 0; - } - - add = min(len, fillBlockSz - stmCtx->buffLen); + word32 add = min(len, chunkSz - stmCtx->buffLen); XMEMCPY(&local[stmCtx->buffLen], data, add); stmCtx->buffLen += add; data += add; len -= add; - if (len > 0 && stmCtx->buffLen == fillBlockSz) { + #ifdef STM32_HASH_FIFO_WORKAROUND + /* We cannot leave the FIFO full and do save/restore + * the last must be large enough to flush block from FIFO */ + if (stmCtx->buffLen + len <= fifoSz * 2) { + chunkSz = fifoSz + STM32_HASH_REG_SIZE; + } + #endif + + if (len >= 0 && stmCtx->buffLen == chunkSz) { wc_Stm32_Hash_Data(stmCtx, stmCtx->buffLen); wroteToFifo = 1; + #ifdef STM32_HASH_FIFO_WORKAROUND + if (chunkSz > fifoSz) + stmCtx->fifoBytes = chunkSz - fifoSz; + chunkSz = fifoSz; + #endif } } if (wroteToFifo) { - #ifdef STM32_HASH_FIFO_WORKAROUND - /* If we wrote a block send one more 32-bit to FIFO to trigger start. - * The save/restore feature cannot leave 16 deep FIFO filled. */ - wc_Stm32_Hash_Data(stmCtx, 4); - stmCtx->fifoBytes += 4; - #endif - /* make sure hash operation is done */ ret = wc_Stm32_Hash_WaitDone(stmCtx); diff --git a/wolfssl/wolfcrypt/port/st/stm32.h b/wolfssl/wolfcrypt/port/st/stm32.h index f441072e841..1bcb7749f1a 100644 --- a/wolfssl/wolfcrypt/port/st/stm32.h +++ b/wolfssl/wolfcrypt/port/st/stm32.h @@ -74,10 +74,22 @@ #if (defined(WOLFSSL_STM32U5) || defined(WOLFSSL_STM32H5) || \ defined(WOLFSSL_STM32H7)) && !defined(NO_STM32_HASH_FIFO_WORKAROUND) /* workaround for hash FIFO to write one extra to finalize */ + /* RM: Message Data Feeding: Data are entered into the HASH + * one 32-bit word at a time, by writing them into the HASH_DIN register. + * The current contents of the HASH_DIN register are transferred to the + * 16 words input FIFO each time the register is written with new data. + * Hence HASH_DIN and the FIFO form a seventeen 32-bit words length FIFO. */ + #undef STM32_HASH_BUFFER_SIZE + #define STM32_HASH_BUFFER_SIZE 17 + #undef STM32_HASH_FIFO_WORKAROUND #define STM32_HASH_FIFO_WORKAROUND #endif +#ifndef STM32_HASH_BUFFER_SIZE +#define STM32_HASH_BUFFER_SIZE STM32_HASH_FIFO_SIZE +#endif + /* STM32 Hash Context */ typedef struct { @@ -88,11 +100,13 @@ typedef struct { uint32_t HASH_CSR[HASH_CR_SIZE]; /* Hash state / buffers */ - word32 buffer[STM32_HASH_FIFO_SIZE]; /* partial word buffer */ + word32 buffer[STM32_HASH_BUFFER_SIZE]; /* partial word buffer */ word32 buffLen; /* partial word remain */ word32 loLen; /* total update bytes (only lsb 6-bits is used for nbr valid bytes in last word) */ +#ifdef STM32_HASH_FIFO_WORKAROUND int fifoBytes; /* number of currently filled FIFO bytes */ +#endif } STM32_HASH_Context; From 3e1373e4bd44cfd4c57833b06b78204a8c906b10 Mon Sep 17 00:00:00 2001 From: Andras Fekete Date: Mon, 1 May 2023 15:28:39 -0400 Subject: [PATCH 235/391] Changes to make it possible to use a different base container --- Docker/wolfCLU/Dockerfile | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Docker/wolfCLU/Dockerfile b/Docker/wolfCLU/Dockerfile index 4333c13db4f..deb388d8e9a 100644 --- a/Docker/wolfCLU/Dockerfile +++ b/Docker/wolfCLU/Dockerfile @@ -1,3 +1,4 @@ +ARG DOCKER_BASE_IMAGE=ubuntu FROM ubuntu as BUILDER ARG DEPS_WOLFSSL="build-essential autoconf libtool zlib1g-dev libuv1-dev libpam0g-dev git libpcap-dev libcurl4-openssl-dev bsdmainutils netcat iputils-ping bubblewrap" @@ -15,8 +16,11 @@ RUN DUMMY=${DUMMY} git clone --depth=1 --single-branch --branch=master http://gi # install wolfCLU RUN git clone --depth=1 --single-branch --branch=main http://github.com/wolfssl/wolfCLU && cd wolfCLU && ./autogen.sh && ./configure && make -j $NUM_CPU && make install -FROM ubuntu +FROM ${DOCKER_BASE_IMAGE} +USER root COPY --from=BUILDER /usr/local/lib/libwolfssl.so /usr/local/lib/ COPY --from=BUILDER /usr/local/bin/wolfssl* /usr/local/bin/ RUN ldconfig -ENTRYPOINT ["/usr/local/bin/wolfssl"] +CMD ["/usr/local/bin/wolfssl"] +LABEL org.opencontainers.image.source=https://github.com/wolfssl/wolfssl +LABEL org.opencontainers.image.description="Simple wolfCLU in a container" From 243cc368042451e9f13dcbffdc39ecb109771570 Mon Sep 17 00:00:00 2001 From: Andras Fekete Date: Wed, 5 Apr 2023 14:39:44 -0400 Subject: [PATCH 236/391] Missing 'tcpdump' utility --- Docker/Dockerfile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Docker/Dockerfile b/Docker/Dockerfile index e30efaa907f..60c69247d51 100644 --- a/Docker/Dockerfile +++ b/Docker/Dockerfile @@ -5,7 +5,7 @@ USER root ARG DEPS_WOLFSSL="build-essential autoconf libtool clang clang-tools zlib1g-dev libuv1-dev libpam0g-dev valgrind git linux-headers-generic gcc-multilib g++-multilib libpcap-dev bubblewrap gdb iputils-ping lldb bsdmainutils netcat binutils-arm-linux-gnueabi binutils-aarch64-linux-gnu" ARG DEPS_LIBOQS="astyle cmake gcc ninja-build libssl-dev python3-pytest python3-pytest-xdist unzip xsltproc doxygen graphviz python3-yaml valgrind git" -ARG DEPS_TESTS="abi-dumper libcurl4-openssl-dev" +ARG DEPS_TESTS="abi-dumper libcurl4-openssl-dev tcpdump" RUN DEBIAN_FRONTEND=noninteractive apt update && apt install -y apt-utils \ && apt install -y ${DEPS_WOLFSSL} ${DEPS_LIBOQS} ${DEPS_TESTS} \ && apt clean -y && rm -rf /var/lib/apt/lists/* @@ -19,4 +19,7 @@ RUN groupadd -f -g ${GID} docker && ( getent passwd ${UID} || useradd -ms /bin/b RUN git clone --single-branch https://github.com/open-quantum-safe/liboqs.git && cd liboqs && git checkout af76ca3b1f2fbc1f4f0967595f3bb07692fb3d82 \ && mkdir build && cd build && cmake -DOQS_DIST_BUILD=ON -DOQS_USE_CPUFEATURE_INSTRUCTIONS=OFF -DOQS_USE_OPENSSL=0 .. && make -j8 all && make install && cd ../.. && rm -rf liboqs +# Allow non-root to use tcpdump (will need NET_RAW and NET_ADMIN capability when running the container) +RUN setcap 'CAP_NET_RAW+eip CAP_NET_ADMIN+eip' /usr/bin/tcpdump + USER ${UID}:${GID} \ No newline at end of file From f77b541be134c69fccd9946596ed75cd8f824720 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 4 Apr 2023 14:17:57 -0700 Subject: [PATCH 237/391] Fix for async ECC shared secret. ZD 15938 --- .github/workflows/async.yml | 1 + wolfcrypt/src/ecc.c | 15 +++++++-------- wolfssl/wolfcrypt/ecc.h | 5 +++++ 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/.github/workflows/async.yml b/.github/workflows/async.yml index 5696b2a306a..8ded7695063 100644 --- a/.github/workflows/async.yml +++ b/.github/workflows/async.yml @@ -10,6 +10,7 @@ jobs: config: [ # Add new configs here '--enable-asynccrypt --enable-all --enable-dtls13', + '--enable-asynccrypt-sw', ] name: make check runs-on: ubuntu-latest diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 53eaff4d746..bfa69d564ce 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -4455,7 +4455,7 @@ int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out, !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_KCAPI_ECC) && \ !defined(WOLF_CRYPTO_CB_ONLY_ECC) -static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, +int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, byte* out, word32* outlen) { int err = MP_OKAY; @@ -4749,11 +4749,6 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, private_key->dp->cofactor); #endif - - if (err == WC_PENDING_E) { - /* advance state, next call will handle return code processing */ - private_key->state++; - } } else #elif defined(WOLFSSL_ASYNC_CRYPT_SW) @@ -4772,6 +4767,10 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, err = wc_ecc_shared_secret_gen_sync(private_key, point, out, outlen); } + if (err == WC_PENDING_E) { + private_key->state++; + } + #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) wc_ecc_curve_free(curve); FREE_CURVE_SPECS(); @@ -4826,8 +4825,7 @@ int wc_ecc_shared_secret_ex(ecc_key* private_key, ecc_point* point, err = wc_ecc_shared_secret_gen_async(private_key, point, out, outlen); if (err == 0) { - /* advance state and exit early */ - private_key->state++; + /* exit early */ RESTORE_VECTOR_REGISTERS(); return err; } @@ -8352,6 +8350,7 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, if (NitroxEccIsCurveSupported(key)) #endif { + word32 keySz = (word32)key->dp->size; err = wc_mp_to_bigint_sz(e, &e->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(key->pubkey.x, &key->pubkey.x->raw, keySz); diff --git a/wolfssl/wolfcrypt/ecc.h b/wolfssl/wolfcrypt/ecc.h index a077df9e4a5..80141bdd801 100644 --- a/wolfssl/wolfcrypt/ecc.h +++ b/wolfssl/wolfcrypt/ecc.h @@ -604,6 +604,11 @@ WOLFSSL_API int wc_ecc_shared_secret_ex(ecc_key* private_key, ecc_point* point, byte* out, word32 *outlen); +/* Internal API for blocking ECDHE call */ +WOLFSSL_LOCAL +int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, + ecc_point* point, byte* out, word32* outlen); + #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) || \ defined(PLUTON_CRYPTO_ECC) || defined(WOLFSSL_CRYPTOCELL) #define wc_ecc_shared_secret_ssh wc_ecc_shared_secret From f9a6260b597eff5bdb84cf9dd87556b45e02354d Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 1 May 2023 15:47:21 -0700 Subject: [PATCH 238/391] Add option to support disabling thread local `--disable-threadlocal`. Useful for cross-compile situation where thread local storage is not desired. ZD 16062 --- configure.ac | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index 7622c2226c6..2f4bc3e6d88 100644 --- a/configure.ac +++ b/configure.ac @@ -159,9 +159,20 @@ then output_objdir=. fi + # Thread local storage -AX_TLS([thread_ls_on=yes],[thread_ls_on=no]) -AS_IF([test "x$thread_ls_on" = "xyes"],[AM_CFLAGS="$AM_CFLAGS -DHAVE_THREAD_LS"]) +thread_ls_on="no" +AC_ARG_ENABLE([threadlocal], + [AS_HELP_STRING([--enable-threadlocal],[Enable thread local support (default: enabled)])], + [ ENABLED_THREADLOCAL=$enableval ], + [ ENABLED_THREADLOCAL=yes ] + ) +if test "$ENABLED_THREADLOCAL" = "yes" +then + AX_TLS([thread_ls_on=yes],[thread_ls_on=no]) + AS_IF([test "x$thread_ls_on" = "xyes"],[AM_CFLAGS="$AM_CFLAGS -DHAVE_THREAD_LS"]) +fi + # DEBUG AX_DEBUG From b0aab5d520abe1ee4327ececf071c339b8f686f4 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 19 Apr 2023 14:51:36 -0700 Subject: [PATCH 239/391] smaller sized build with curl --- src/ssl.c | 18 +++++++++++----- wolfcrypt/src/evp.c | 43 +++++++++++++++++++++++++++----------- wolfcrypt/src/md5.c | 2 +- wolfcrypt/src/sha.c | 2 +- wolfcrypt/src/sha256.c | 2 +- wolfcrypt/src/sha512.c | 8 +++---- wolfssl/internal.h | 10 ++++++--- wolfssl/openssl/ssl.h | 2 +- wolfssl/ssl.h | 11 +++++----- wolfssl/wolfcrypt/md5.h | 2 +- wolfssl/wolfcrypt/sha.h | 2 +- wolfssl/wolfcrypt/sha256.h | 2 +- wolfssl/wolfcrypt/sha512.h | 6 +++--- 13 files changed, 71 insertions(+), 39 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 4bce5d240c5..1271304a32e 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -19060,8 +19060,10 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, return wolfSSL_OpenSSL_version(); #endif } +#endif /* OPENSSL_EXTRA */ +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) #ifndef NO_MD5 int wolfSSL_MD5_Init(WOLFSSL_MD5_CTX* md5) { @@ -19858,6 +19860,9 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, } #endif /* WOLFSSL_NOSHA3_512 */ #endif /* WOLFSSL_SHA3 */ +#endif + +#ifdef OPENSSL_EXTRA unsigned char* wolfSSL_HMAC(const WOLFSSL_EVP_MD* evp_md, const void* key, int key_len, const unsigned char* d, int n, @@ -20236,11 +20241,14 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, #endif /* OPENSSL_EXTRA */ -#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) +#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \ + defined(HAVE_CURL) void wolfSSL_ERR_clear_error(void) { WOLFSSL_ENTER("wolfSSL_ERR_clear_error"); + #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) wc_ClearErrorNodes(); + #endif } #endif @@ -33573,16 +33581,15 @@ void wolfSSL_get0_next_proto_negotiated(const WOLFSSL *s, const unsigned char ** #endif /* WOLFSSL_NGINX / WOLFSSL_HAPROXY */ -#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) int wolfSSL_curve_is_disabled(const WOLFSSL* ssl, word16 curve_id) { return (curve_id <= WOLFSSL_ECC_MAX && ssl->disabledCurves && ssl->disabledCurves & (1 << curve_id)); } -#endif -#if defined(OPENSSL_EXTRA) && (defined(HAVE_ECC) || \ +#if (defined(HAVE_ECC) || \ defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) static int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names) { @@ -33759,7 +33766,8 @@ int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names) } return set_curves_list(ssl, NULL, names); } -#endif /* OPENSSL_EXTRA && (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */ +#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */ +#endif /* OPENSSL_EXTRA || HAVE_CURL */ #ifdef OPENSSL_EXTRA /* Sets a callback for when sending and receiving protocol messages. diff --git a/wolfcrypt/src/evp.c b/wolfcrypt/src/evp.c index 8f8f7b86945..1df7edacb7e 100644 --- a/wolfcrypt/src/evp.c +++ b/wolfcrypt/src/evp.c @@ -33,7 +33,7 @@ #elif defined(WOLFCRYPT_ONLY) #else -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) #if !defined(HAVE_PKCS7) && \ ((defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \ @@ -47,6 +47,8 @@ #include #include +#ifdef OPENSSL_EXTRA + #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 @@ -419,16 +421,6 @@ int wolfSSL_EVP_DecryptFinal_ex(WOLFSSL_EVP_CIPHER_CTX *ctx, } } - -int wolfSSL_EVP_DigestInit_ex(WOLFSSL_EVP_MD_CTX* ctx, - const WOLFSSL_EVP_MD* type, - WOLFSSL_ENGINE *impl) -{ - (void) impl; - WOLFSSL_ENTER("wolfSSL_EVP_DigestInit_ex"); - return wolfSSL_EVP_DigestInit(ctx, type); -} - #ifdef DEBUG_WOLFSSL_EVP #define PRINT_BUF(b, sz) { int _i; for(_i=0; _i<(sz); _i++) { \ printf("%02x(%c),", (b)[_i], (b)[_i]); if ((_i+1)%8==0)printf("\n");}} @@ -3342,6 +3334,7 @@ int wolfSSL_EVP_SignUpdate(WOLFSSL_EVP_MD_CTX *ctx, const void *data, size_t len WOLFSSL_ENTER("EVP_SignUpdate("); return wolfSSL_EVP_DigestUpdate(ctx, data, len); } +#endif /* OPENSSL_EXTRA */ static const struct s_ent { const enum wc_HashType macType; @@ -3424,6 +3417,7 @@ static enum wc_HashType EvpMd2MacType(const WOLFSSL_EVP_MD *md) return WC_HASH_TYPE_NONE; } +#ifdef OPENSSL_EXTRA static const WOLFSSL_EVP_MD* wolfSSL_macType2EVP_md(enum wc_HashType type) { const struct s_ent *ent ; @@ -4039,6 +4033,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, ForceZero(digest, sizeof(digest)); return ret; } + int wolfSSL_EVP_DigestVerifyInit(WOLFSSL_EVP_MD_CTX *ctx, WOLFSSL_EVP_PKEY_CTX **pctx, const WOLFSSL_EVP_MD *type, @@ -4734,6 +4729,17 @@ void wolfSSL_EVP_init(void) /* Does nothing. */ } +#endif /* OPENSSL_EXTRA */ + +int wolfSSL_EVP_DigestInit_ex(WOLFSSL_EVP_MD_CTX* ctx, + const WOLFSSL_EVP_MD* type, + WOLFSSL_ENGINE *impl) +{ + (void) impl; + WOLFSSL_ENTER("wolfSSL_EVP_DigestInit_ex"); + return wolfSSL_EVP_DigestInit(ctx, type); +} + /* this function makes the assumption that out buffer is big enough for digest*/ int wolfSSL_EVP_Digest(const unsigned char* in, int inSz, unsigned char* out, unsigned int* outSz, const WOLFSSL_EVP_MD* evp, @@ -5058,11 +5064,13 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } +#ifdef OPENSSL_EXTRA /* returns WOLFSSL_SUCCESS on success */ int wolfSSL_EVP_MD_CTX_copy(WOLFSSL_EVP_MD_CTX *out, const WOLFSSL_EVP_MD_CTX *in) { return wolfSSL_EVP_MD_CTX_copy_ex(out, in); } +#endif /* returns digest size */ int wolfSSL_EVP_MD_CTX_size(const WOLFSSL_EVP_MD_CTX *ctx) { @@ -5073,6 +5081,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) return(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(ctx))); } +#ifdef OPENSSL_EXTRA /* Deep copy of EVP_MD hasher * return WOLFSSL_SUCCESS on success */ static int wolfSSL_EVP_MD_Copy_Hasher(WOLFSSL_EVP_MD_CTX* des, @@ -5223,6 +5232,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } return wolfSSL_EVP_MD_Copy_Hasher(out, (WOLFSSL_EVP_MD_CTX*)in); } +#endif void wolfSSL_EVP_MD_CTX_init(WOLFSSL_EVP_MD_CTX* ctx) { @@ -5351,6 +5361,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } } +#ifdef OPENSSL_EXTRA #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) @@ -5666,13 +5677,16 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) WOLFSSL_ENTER("wolfSSL_EVP_enc_null"); return EVP_NULL; } +#endif int wolfSSL_EVP_MD_CTX_cleanup(WOLFSSL_EVP_MD_CTX* ctx) { int ret = WOLFSSL_SUCCESS; WOLFSSL_ENTER("wolfSSL_EVP_MD_CTX_cleanup"); + #ifdef OPENSSL_EXTRA if (ctx->pctx != NULL) wolfSSL_EVP_PKEY_CTX_free(ctx->pctx); + #endif if (ctx->isHMAC) { wc_HmacFree(&ctx->hash.hmac); @@ -5770,6 +5784,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) return ret; } +#ifdef OPENSSL_EXTRA void wolfSSL_EVP_CIPHER_CTX_init(WOLFSSL_EVP_CIPHER_CTX* ctx) { WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_init"); @@ -7776,7 +7791,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) WOLFSSL_MSG("wolfSSL_EVP_Cipher success"); return ret; } - +#endif /* WOLFSSL_SUCCESS on ok */ int wolfSSL_EVP_DigestInit(WOLFSSL_EVP_MD_CTX* ctx, const WOLFSSL_EVP_MD* md) @@ -8158,6 +8173,7 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_get_digestbynid(int id) return NULL; } +#ifdef OPENSSL_EXTRA static void clearEVPPkeyKeys(WOLFSSL_EVP_PKEY *pkey) { if(pkey == NULL) @@ -8874,6 +8890,7 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_ripemd160(void) #endif +#endif int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) { WOLFSSL_MSG("wolfSSL_EVP_MD_block_size"); @@ -9024,6 +9041,7 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) return BAD_FUNC_ARG; } +#ifdef OPENSSL_EXTRA int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) { int ret = BAD_FUNC_ARG; @@ -9465,6 +9483,7 @@ int wolfSSL_EVP_PKEY_assign_DH(EVP_PKEY* pkey, WOLFSSL_DH* key) +#endif /* OPENSSL_EXTRA */ #endif /* OPENSSL_EXTRA */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) diff --git a/wolfcrypt/src/md5.c b/wolfcrypt/src/md5.c index 66296108e9a..1f61302646d 100644 --- a/wolfcrypt/src/md5.c +++ b/wolfcrypt/src/md5.c @@ -557,7 +557,7 @@ int wc_Md5Copy(wc_Md5* src, wc_Md5* dst) return ret; } -#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) /* Apply MD5 transformation to the data */ /* @param md5 a pointer to wc_MD5 structure */ /* @param data data to be applied MD5 transformation */ diff --git a/wolfcrypt/src/sha.c b/wolfcrypt/src/sha.c index 549f61b012d..4c560cc4bd3 100644 --- a/wolfcrypt/src/sha.c +++ b/wolfcrypt/src/sha.c @@ -884,7 +884,7 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) return ret; } -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) /* Apply SHA1 transformation to the data */ /* @param sha a pointer to wc_Sha structure */ /* @param data data to be applied SHA1 transformation */ diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 3286216557c..94bdc265395 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -1424,7 +1424,7 @@ static int InitSha256(wc_Sha256* sha256) return InitSha256(sha256); /* reset state */ } -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) /* Apply SHA256 transformation to the data */ /* @param sha a pointer to wc_Sha256 structure */ /* @param data data to be applied SHA256 transformation */ diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index 224fe2e99fc..f4e77ccc270 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -1224,8 +1224,8 @@ void wc_Sha512Free(wc_Sha512* sha512) wolfAsync_DevCtxFree(&sha512->asyncDev, WOLFSSL_ASYNC_MARKER_SHA512); #endif /* WOLFSSL_ASYNC_CRYPT */ } - -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_KCAPI_HASH) +#if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) \ + && !defined(WOLFSSL_KCAPI_HASH) /* Apply SHA512 transformation to the data */ /* @param sha a pointer to wc_Sha512 structure */ /* @param data data to be applied SHA512 transformation */ @@ -1718,7 +1718,7 @@ int wc_Sha512_224GetFlags(wc_Sha512* sha, word32* flags) } #endif /* WOLFSSL_HASH_FLAGS */ -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) int wc_Sha512_224Transform(wc_Sha512* sha, const unsigned char* data) { return wc_Sha512Transform(sha, data); @@ -1787,7 +1787,7 @@ int wc_Sha512_256GetFlags(wc_Sha512* sha, word32* flags) } #endif /* WOLFSSL_HASH_FLAGS */ -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) int wc_Sha512_256Transform(wc_Sha512* sha, const unsigned char* data) { return wc_Sha512Transform(sha, data); diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 28ecf5111ae..a8ed9f36714 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -3555,9 +3555,11 @@ struct WOLFSSL_CTX { short minDilithiumKeySz;/* minimum Dilithium key size */ #endif unsigned long mask; /* store SSL_OP_ flags */ +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) + word32 disabledCurves; /* curves disabled by user */ +#endif #ifdef OPENSSL_EXTRA byte sessionCtx[ID_LEN]; /* app session context ID */ - word32 disabledCurves; /* curves disabled by user */ const unsigned char *alpn_cli_protos;/* ALPN client protocol list */ unsigned int alpn_cli_protos_len; byte sessionCtxSz; @@ -5311,7 +5313,9 @@ struct WOLFSSL { WOLFSSL_BIO* biowr; /* socket bio write to free/close */ byte sessionCtx[ID_LEN]; /* app session context ID */ WOLFSSL_X509_VERIFY_PARAM* param; /* verification parameters*/ - word32 disabledCurves; /* curves disabled by user */ +#endif +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) + word32 disabledCurves; /* curves disabled by user */ #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) unsigned long peerVerifyRet; @@ -5935,7 +5939,7 @@ WOLFSSL_LOCAL int SetECKeyInternal(WOLFSSL_EC_KEY* eckey); WOLFSSL_LOCAL int SetECKeyExternal(WOLFSSL_EC_KEY* eckey); #endif -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) WOLFSSL_LOCAL int wolfSSL_curve_is_disabled(const WOLFSSL* ssl, word16 named_curve); #else diff --git a/wolfssl/openssl/ssl.h b/wolfssl/openssl/ssl.h index 81575908106..d9ada762b40 100644 --- a/wolfssl/openssl/ssl.h +++ b/wolfssl/openssl/ssl.h @@ -1564,7 +1564,7 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || WOLFSSL_MYSQL_COMPATIBLE || OPENSSL_ALL || HAVE_LIGHTY */ -#if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) +#if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) && defined(HAVE_ECC) #define SSL_CTX_set1_curves_list wolfSSL_CTX_set1_curves_list #define SSL_set1_curves_list wolfSSL_set1_curves_list #endif diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 611a79462dc..28f4515dde9 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -228,7 +228,7 @@ typedef struct WOLFSSL_DIST_POINT WOLFSSL_DIST_POINT; typedef struct WOLFSSL_CONF_CTX WOLFSSL_CONF_CTX; -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || defined(HAVE_CURL) struct WOLFSSL_OBJ_NAME { int type; @@ -2630,11 +2630,12 @@ enum { /* ssl Constants */ /* extra begins */ -#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) enum { /* ERR Constants */ ERR_TXT_STRING = 1 }; - +#endif +#ifdef OPENSSL_EXTRA /* bio misc */ enum { WOLFSSL_BIO_ERROR = -1, @@ -4864,10 +4865,10 @@ WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_X509_OBJECT_get0_X509_CRL(WOLFSSL_X509_OBJ WOLFSSL_API void wolfSSL_sk_X509_pop_free(WOLF_STACK_OF(WOLFSSL_X509)* sk, void (*f) (WOLFSSL_X509*)); #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ -#if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) +#if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) && defined(HAVE_ECC) WOLFSSL_API int wolfSSL_CTX_set1_curves_list(WOLFSSL_CTX* ctx, const char* names); WOLFSSL_API int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names); -#endif /* OPENSSL_EXTRA && HAVE_ECC */ +#endif /* (OPENSSL_EXTRA || HAVE_CURL) && HAVE_ECC */ #if defined(OPENSSL_ALL) || \ defined(HAVE_STUNNEL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ diff --git a/wolfssl/wolfcrypt/md5.h b/wolfssl/wolfcrypt/md5.h index f7312908566..6506be98947 100644 --- a/wolfssl/wolfcrypt/md5.h +++ b/wolfssl/wolfcrypt/md5.h @@ -112,7 +112,7 @@ WOLFSSL_API int wc_InitMd5_ex(wc_Md5* md5, void* heap, int devId); WOLFSSL_API int wc_Md5Update(wc_Md5* md5, const byte* data, word32 len); WOLFSSL_API int wc_Md5Final(wc_Md5* md5, byte* hash); WOLFSSL_API void wc_Md5Free(wc_Md5* md5); -#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) WOLFSSL_API int wc_Md5Transform(wc_Md5* md5, const byte* data); #endif diff --git a/wolfssl/wolfcrypt/sha.h b/wolfssl/wolfcrypt/sha.h index a6362660f17..1b181f52594 100644 --- a/wolfssl/wolfcrypt/sha.h +++ b/wolfssl/wolfcrypt/sha.h @@ -201,7 +201,7 @@ WOLFSSL_API void wc_ShaFree(wc_Sha* sha); WOLFSSL_API int wc_ShaGetHash(wc_Sha* sha, byte* hash); WOLFSSL_API int wc_ShaCopy(wc_Sha* src, wc_Sha* dst); -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) WOLFSSL_API int wc_ShaTransform(wc_Sha* sha, const unsigned char* data); #endif diff --git a/wolfssl/wolfcrypt/sha256.h b/wolfssl/wolfcrypt/sha256.h index ccdee8540a7..c6665c90b5e 100644 --- a/wolfssl/wolfcrypt/sha256.h +++ b/wolfssl/wolfcrypt/sha256.h @@ -254,7 +254,7 @@ WOLFSSL_API int wc_Sha256Update(wc_Sha256* sha, const byte* data, word32 len); WOLFSSL_API int wc_Sha256FinalRaw(wc_Sha256* sha256, byte* hash); WOLFSSL_API int wc_Sha256Final(wc_Sha256* sha256, byte* hash); WOLFSSL_API void wc_Sha256Free(wc_Sha256* sha256); -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) WOLFSSL_API int wc_Sha256Transform(wc_Sha256* sha, const unsigned char* data); #endif #if defined(WOLFSSL_HASH_KEEP) diff --git a/wolfssl/wolfcrypt/sha512.h b/wolfssl/wolfcrypt/sha512.h index 6338700d204..07411b01d54 100644 --- a/wolfssl/wolfcrypt/sha512.h +++ b/wolfssl/wolfcrypt/sha512.h @@ -236,7 +236,7 @@ WOLFSSL_API int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst); WOLFSSL_API int wc_Sha512GetFlags(wc_Sha512* sha512, word32* flags); #endif -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) WOLFSSL_API int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data); #endif @@ -255,7 +255,7 @@ WOLFSSL_API int wc_Sha512_224Copy(wc_Sha512* src, wc_Sha512* dst); WOLFSSL_API int wc_Sha512_224GetFlags(wc_Sha512* sha512, word32* flags); #endif -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) WOLFSSL_API int wc_Sha512_224Transform(wc_Sha512* sha, const unsigned char* data); #endif /* OPENSSL_EXTRA */ @@ -276,7 +276,7 @@ WOLFSSL_API int wc_Sha512_256Copy(wc_Sha512* src, wc_Sha512* dst); WOLFSSL_API int wc_Sha512_256GetFlags(wc_Sha512* sha512, word32* flags); #endif -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) WOLFSSL_API int wc_Sha512_256Transform(wc_Sha512* sha, const unsigned char* data); #endif /* OPENSSL_EXTRA */ From 7ace26cc62b1759a6e98c912dbcba404d3b90aa0 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 1 May 2023 13:23:48 -0700 Subject: [PATCH 240/391] refactor evp.c to group all MD digest functions togther --- wolfcrypt/src/evp.c | 6728 +++++++++++++++++++++---------------------- 1 file changed, 3356 insertions(+), 3372 deletions(-) diff --git a/wolfcrypt/src/evp.c b/wolfcrypt/src/evp.c index 1df7edacb7e..0316b34f840 100644 --- a/wolfcrypt/src/evp.c +++ b/wolfcrypt/src/evp.c @@ -47,7 +47,77 @@ #include #include -#ifdef OPENSSL_EXTRA + +static const struct s_ent { + const enum wc_HashType macType; + const int nid; + const char *name; +} md_tbl[] = { +#ifndef NO_MD4 + {WC_HASH_TYPE_MD4, NID_md4, "MD4"}, +#endif /* NO_MD4 */ + +#ifndef NO_MD5 + {WC_HASH_TYPE_MD5, NID_md5, "MD5"}, +#endif /* NO_MD5 */ + +#ifndef NO_SHA + {WC_HASH_TYPE_SHA, NID_sha1, "SHA1"}, + {WC_HASH_TYPE_SHA, NID_sha1, "SHA"}, /* Leave for backwards compatibility */ +#endif /* NO_SHA */ + +#ifdef WOLFSSL_SHA224 + {WC_HASH_TYPE_SHA224, NID_sha224, "SHA224"}, +#endif /* WOLFSSL_SHA224 */ +#ifndef NO_SHA256 + {WC_HASH_TYPE_SHA256, NID_sha256, "SHA256"}, +#endif + +#ifdef WOLFSSL_SHA384 + {WC_HASH_TYPE_SHA384, NID_sha384, "SHA384"}, +#endif /* WOLFSSL_SHA384 */ + +#ifdef WOLFSSL_SHA512 + {WC_HASH_TYPE_SHA512, NID_sha512, "SHA512"}, +#endif /* WOLFSSL_SHA512 */ + +#if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) + {WC_HASH_TYPE_SHA512_224, NID_sha512_224, "SHA512_224"}, +#endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_224 */ + +#if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) + {WC_HASH_TYPE_SHA512_256, NID_sha512_256, "SHA512_256"}, +#endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_256 */ + +#ifndef WOLFSSL_NOSHA3_224 + {WC_HASH_TYPE_SHA3_224, NID_sha3_224, "SHA3_224"}, +#endif +#ifndef WOLFSSL_NOSHA3_256 + {WC_HASH_TYPE_SHA3_256, NID_sha3_256, "SHA3_256"}, +#endif +#ifndef WOLFSSL_NOSHA3_384 + {WC_HASH_TYPE_SHA3_384, NID_sha3_384, "SHA3_384"}, +#endif +#ifndef WOLFSSL_NOSHA3_512 + {WC_HASH_TYPE_SHA3_512, NID_sha3_512, "SHA3_512"}, +#endif +#ifdef HAVE_BLAKE2 + {WC_HASH_TYPE_BLAKE2B, NID_blake2b512, "BLAKE2B512"}, +#endif +#ifdef HAVE_BLAKE2S + {WC_HASH_TYPE_BLAKE2S, NID_blake2s256, "BLAKE2S256"}, +#endif +#ifdef WOLFSSL_SHAKE128 + {WC_HASH_TYPE_SHAKE128, NID_shake128, "SHAKE128"}, +#endif +#ifdef WOLFSSL_SHAKE256 + {WC_HASH_TYPE_SHAKE256, NID_shake256, "SHAKE256"}, +#endif + {WC_HASH_TYPE_NONE, 0, NULL} +}; +#endif /* OPENSSL_EXTRA || HAVE_CURL */ + +#if defined(OPENSSL_EXTRA) #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) @@ -3334,90 +3404,6 @@ int wolfSSL_EVP_SignUpdate(WOLFSSL_EVP_MD_CTX *ctx, const void *data, size_t len WOLFSSL_ENTER("EVP_SignUpdate("); return wolfSSL_EVP_DigestUpdate(ctx, data, len); } -#endif /* OPENSSL_EXTRA */ - -static const struct s_ent { - const enum wc_HashType macType; - const int nid; - const char *name; -} md_tbl[] = { -#ifndef NO_MD4 - {WC_HASH_TYPE_MD4, NID_md4, "MD4"}, -#endif /* NO_MD4 */ - -#ifndef NO_MD5 - {WC_HASH_TYPE_MD5, NID_md5, "MD5"}, -#endif /* NO_MD5 */ - -#ifndef NO_SHA - {WC_HASH_TYPE_SHA, NID_sha1, "SHA1"}, - {WC_HASH_TYPE_SHA, NID_sha1, "SHA"}, /* Leave for backwards compatibility */ -#endif /* NO_SHA */ - -#ifdef WOLFSSL_SHA224 - {WC_HASH_TYPE_SHA224, NID_sha224, "SHA224"}, -#endif /* WOLFSSL_SHA224 */ -#ifndef NO_SHA256 - {WC_HASH_TYPE_SHA256, NID_sha256, "SHA256"}, -#endif - -#ifdef WOLFSSL_SHA384 - {WC_HASH_TYPE_SHA384, NID_sha384, "SHA384"}, -#endif /* WOLFSSL_SHA384 */ - -#ifdef WOLFSSL_SHA512 - {WC_HASH_TYPE_SHA512, NID_sha512, "SHA512"}, -#endif /* WOLFSSL_SHA512 */ - -#if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - {WC_HASH_TYPE_SHA512_224, NID_sha512_224, "SHA512_224"}, -#endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_224 */ - -#if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - {WC_HASH_TYPE_SHA512_256, NID_sha512_256, "SHA512_256"}, -#endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_256 */ - -#ifndef WOLFSSL_NOSHA3_224 - {WC_HASH_TYPE_SHA3_224, NID_sha3_224, "SHA3_224"}, -#endif -#ifndef WOLFSSL_NOSHA3_256 - {WC_HASH_TYPE_SHA3_256, NID_sha3_256, "SHA3_256"}, -#endif -#ifndef WOLFSSL_NOSHA3_384 - {WC_HASH_TYPE_SHA3_384, NID_sha3_384, "SHA3_384"}, -#endif -#ifndef WOLFSSL_NOSHA3_512 - {WC_HASH_TYPE_SHA3_512, NID_sha3_512, "SHA3_512"}, -#endif -#ifdef HAVE_BLAKE2 - {WC_HASH_TYPE_BLAKE2B, NID_blake2b512, "BLAKE2B512"}, -#endif -#ifdef HAVE_BLAKE2S - {WC_HASH_TYPE_BLAKE2S, NID_blake2s256, "BLAKE2S256"}, -#endif -#ifdef WOLFSSL_SHAKE128 - {WC_HASH_TYPE_SHAKE128, NID_shake128, "SHAKE128"}, -#endif -#ifdef WOLFSSL_SHAKE256 - {WC_HASH_TYPE_SHAKE256, NID_shake256, "SHAKE256"}, -#endif - {WC_HASH_TYPE_NONE, 0, NULL} -}; - -static enum wc_HashType EvpMd2MacType(const WOLFSSL_EVP_MD *md) -{ - if (md != NULL) { - const struct s_ent *ent; - for (ent = md_tbl; ent->name != NULL; ent++) { - if (XSTRCMP((const char *)md, ent->name) == 0) { - return ent->macType; - } - } - } - return WC_HASH_TYPE_NONE; -} - -#ifdef OPENSSL_EXTRA static const WOLFSSL_EVP_MD* wolfSSL_macType2EVP_md(enum wc_HashType type) { const struct s_ent *ent ; @@ -4729,2081 +4715,1495 @@ void wolfSSL_EVP_init(void) /* Does nothing. */ } -#endif /* OPENSSL_EXTRA */ - -int wolfSSL_EVP_DigestInit_ex(WOLFSSL_EVP_MD_CTX* ctx, - const WOLFSSL_EVP_MD* type, - WOLFSSL_ENGINE *impl) -{ - (void) impl; - WOLFSSL_ENTER("wolfSSL_EVP_DigestInit_ex"); - return wolfSSL_EVP_DigestInit(ctx, type); -} - -/* this function makes the assumption that out buffer is big enough for digest*/ -int wolfSSL_EVP_Digest(const unsigned char* in, int inSz, unsigned char* out, - unsigned int* outSz, const WOLFSSL_EVP_MD* evp, - WOLFSSL_ENGINE* eng) -{ - int err; - int hashType = WC_HASH_TYPE_NONE; - int hashSz; - - WOLFSSL_ENTER("wolfSSL_EVP_Digest"); - if (in == NULL || out == NULL || evp == NULL) { - WOLFSSL_MSG("Null argument passed in"); - return WOLFSSL_FAILURE; - } - - err = wolfSSL_EVP_get_hashinfo(evp, &hashType, &hashSz); - if (err != WOLFSSL_SUCCESS) - return err; - - if (wc_Hash((enum wc_HashType)hashType, in, inSz, out, hashSz) != 0) { - return WOLFSSL_FAILURE; - } - - if (outSz != NULL) - *outSz = hashSz; - - (void)eng; - return WOLFSSL_SUCCESS; -} - -static const struct alias { - const char *name; - const char *alias; -} digest_alias_tbl[] = -{ - {"MD4", "ssl3-md4"}, - {"MD5", "ssl3-md5"}, - {"SHA1", "ssl3-sha1"}, - {"SHA1", "SHA"}, - { NULL, NULL} -}; - -const WOLFSSL_EVP_MD *wolfSSL_EVP_get_digestbyname(const char *name) -{ - char nameUpper[15]; /* 15 bytes should be enough for any name */ - size_t i; - - const struct alias *al; - const struct s_ent *ent; - - for (i = 0; i < sizeof(nameUpper) && name[i] != '\0'; i++) { - nameUpper[i] = (char)XTOUPPER((unsigned char) name[i]); + /* returns WOLFSSL_SUCCESS on success */ + int wolfSSL_EVP_MD_CTX_copy(WOLFSSL_EVP_MD_CTX *out, const WOLFSSL_EVP_MD_CTX *in) + { + return wolfSSL_EVP_MD_CTX_copy_ex(out, in); } - if (i < sizeof(nameUpper)) - nameUpper[i] = '\0'; - else - return NULL; - - name = nameUpper; - for (al = digest_alias_tbl; al->name != NULL; al++) - if(XSTRCMP(name, al->alias) == 0) { - name = al->name; - break; - } - - for (ent = md_tbl; ent->name != NULL; ent++) - if(XSTRCMP(name, ent->name) == 0) { - return (EVP_MD *)ent->name; + /* Deep copy of EVP_MD hasher + * return WOLFSSL_SUCCESS on success */ + static int wolfSSL_EVP_MD_Copy_Hasher(WOLFSSL_EVP_MD_CTX* des, + const WOLFSSL_EVP_MD_CTX* src) + { + if (src->isHMAC) { + return wolfSSL_HmacCopy(&des->hash.hmac, (Hmac*)&src->hash.hmac); } - return NULL; -} - -/* Returns the NID of the WOLFSSL_EVP_MD passed in. - * - * type - pointer to WOLFSSL_EVP_MD for which to return NID value - * - * Returns NID on success, or NID_undef if none exists. - */ -int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) -{ - const struct s_ent *ent ; - WOLFSSL_ENTER("EVP_MD_type"); + else { + int ret; - if (type == NULL) { - WOLFSSL_MSG("MD type arg is NULL"); - return NID_undef; + switch (src->macType) { + case WC_HASH_TYPE_MD5: + #ifndef NO_MD5 + ret = wc_Md5Copy((wc_Md5*)&src->hash.digest, + (wc_Md5*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif /* !NO_MD5 */ + break; + case WC_HASH_TYPE_SHA: + #ifndef NO_SHA + ret = wc_ShaCopy((wc_Sha*)&src->hash.digest, + (wc_Sha*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif /* !NO_SHA */ + break; + case WC_HASH_TYPE_SHA224: + #ifdef WOLFSSL_SHA224 + ret = wc_Sha224Copy((wc_Sha224*)&src->hash.digest, + (wc_Sha224*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif /* WOLFSSL_SHA224 */ + break; + case WC_HASH_TYPE_SHA256: + #ifndef NO_SHA256 + ret = wc_Sha256Copy((wc_Sha256*)&src->hash.digest, + (wc_Sha256*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif /* !NO_SHA256 */ + break; + case WC_HASH_TYPE_SHA384: + #ifdef WOLFSSL_SHA384 + ret = wc_Sha384Copy((wc_Sha384*)&src->hash.digest, + (wc_Sha384*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif /* WOLFSSL_SHA384 */ + break; + case WC_HASH_TYPE_SHA512: + #ifdef WOLFSSL_SHA512 + ret = wc_Sha512Copy((wc_Sha512*)&src->hash.digest, + (wc_Sha512*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif /* WOLFSSL_SHA512 */ + break; + #ifndef WOLFSSL_NOSHA512_224 + case WC_HASH_TYPE_SHA512_224: + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) + ret = wc_Sha512_224Copy((wc_Sha512*)&src->hash.digest, + (wc_Sha512*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif + break; + #endif /* !WOLFSSL_NOSHA512_224 */ + #ifndef WOLFSSL_NOSHA512_256 + case WC_HASH_TYPE_SHA512_256: + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) + ret = wc_Sha512_256Copy((wc_Sha512*)&src->hash.digest, + (wc_Sha512*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif + break; + #endif /* !WOLFSSL_NOSHA512_256 */ + case WC_HASH_TYPE_SHA3_224: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) + ret = wc_Sha3_224_Copy((wc_Sha3*)&src->hash.digest, + (wc_Sha3*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif + break; + case WC_HASH_TYPE_SHA3_256: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) + ret = wc_Sha3_256_Copy((wc_Sha3*)&src->hash.digest, + (wc_Sha3*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif + break; + case WC_HASH_TYPE_SHA3_384: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) + ret = wc_Sha3_384_Copy((wc_Sha3*)&src->hash.digest, + (wc_Sha3*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif + break; + case WC_HASH_TYPE_SHA3_512: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) + ret = wc_Sha3_512_Copy((wc_Sha3*)&src->hash.digest, + (wc_Sha3*)&des->hash.digest); + #else + ret = NOT_COMPILED_IN; + #endif + break; + case WC_HASH_TYPE_NONE: + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD4: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) + case WC_HASH_TYPE_SHAKE128: + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) + case WC_HASH_TYPE_SHAKE256: + #endif + default: + ret = BAD_FUNC_ARG; + break; + } + return ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; + } } - for( ent = md_tbl; ent->name != NULL; ent++){ - if(XSTRCMP((const char *)type, ent->name) == 0) { - return ent->nid; + /* copies structure in to the structure out + * + * returns WOLFSSL_SUCCESS on success */ + int wolfSSL_EVP_MD_CTX_copy_ex(WOLFSSL_EVP_MD_CTX *out, const WOLFSSL_EVP_MD_CTX *in) + { + if ((out == NULL) || (in == NULL)) return WOLFSSL_FAILURE; + WOLFSSL_ENTER("EVP_CIPHER_MD_CTX_copy_ex"); + wolfSSL_EVP_MD_CTX_cleanup(out); + XMEMCPY(out, in, sizeof(WOLFSSL_EVP_MD_CTX)); + if (in->pctx != NULL) { + out->pctx = wolfSSL_EVP_PKEY_CTX_new(in->pctx->pkey, NULL); + if (out->pctx == NULL) + return WOLFSSL_FAILURE; } + return wolfSSL_EVP_MD_Copy_Hasher(out, (WOLFSSL_EVP_MD_CTX*)in); } - return NID_undef; -} - -#ifndef NO_MD4 + #ifndef NO_AES - /* return a pointer to MD4 EVP type */ - const WOLFSSL_EVP_MD* wolfSSL_EVP_md4(void) + #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cbc(void) { - WOLFSSL_ENTER("EVP_md4"); - return EVP_get_digestbyname("MD4"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cbc"); + return EVP_AES_128_CBC; } + #endif /* WOLFSSL_AES_128 */ -#endif /* !NO_MD4 */ - - -#ifndef NO_MD5 - const WOLFSSL_EVP_MD* wolfSSL_EVP_md5(void) + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_cbc(void) { - WOLFSSL_ENTER("EVP_md5"); - return EVP_get_digestbyname("MD5"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cbc"); + return EVP_AES_192_CBC; } + #endif /* WOLFSSL_AES_192 */ -#endif /* !NO_MD5 */ -#ifdef HAVE_BLAKE2 - /* return EVP_MD - * @param none - * @return "blake2b512" - */ - const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2b512(void) + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_cbc(void) { - WOLFSSL_ENTER("EVP_blake2b512"); - return EVP_get_digestbyname("BLAKE2b512"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cbc"); + return EVP_AES_256_CBC; } + #endif /* WOLFSSL_AES_256 */ + #endif /* HAVE_AES_CBC */ -#endif - -#ifdef HAVE_BLAKE2S - /* return EVP_MD - * @param none - * @return "blake2s256" - */ - const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2s256(void) + #ifdef WOLFSSL_AES_CFB +#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb1(void) { - WOLFSSL_ENTER("EVP_blake2s256"); - return EVP_get_digestbyname("BLAKE2s256"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb1"); + return EVP_AES_128_CFB1; } + #endif /* WOLFSSL_AES_128 */ -#endif - - -#ifndef NO_WOLFSSL_STUB - void wolfSSL_EVP_set_pw_prompt(const char *prompt) + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_cfb1(void) { - (void)prompt; - WOLFSSL_STUB("EVP_set_pw_prompt"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb1"); + return EVP_AES_192_CFB1; } -#endif + #endif /* WOLFSSL_AES_192 */ -#ifndef NO_WOLFSSL_STUB - const WOLFSSL_EVP_MD* wolfSSL_EVP_mdc2(void) + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_cfb1(void) { - WOLFSSL_STUB("EVP_mdc2"); - return NULL; + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb1"); + return EVP_AES_256_CFB1; } -#endif + #endif /* WOLFSSL_AES_256 */ -#ifndef NO_SHA - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha1(void) + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb8(void) { - WOLFSSL_ENTER("EVP_sha1"); - return EVP_get_digestbyname("SHA1"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb8"); + return EVP_AES_128_CFB8; } -#endif /* NO_SHA */ - -#ifdef WOLFSSL_SHA224 + #endif /* WOLFSSL_AES_128 */ - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha224(void) + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_cfb8(void) { - WOLFSSL_ENTER("EVP_sha224"); - return EVP_get_digestbyname("SHA224"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb8"); + return EVP_AES_192_CFB8; } + #endif /* WOLFSSL_AES_192 */ -#endif /* WOLFSSL_SHA224 */ - - - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha256(void) + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_cfb8(void) { - WOLFSSL_ENTER("EVP_sha256"); - return EVP_get_digestbyname("SHA256"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb8"); + return EVP_AES_256_CFB8; } + #endif /* WOLFSSL_AES_256 */ +#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ -#ifdef WOLFSSL_SHA384 - - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha384(void) + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb128(void) { - WOLFSSL_ENTER("EVP_sha384"); - return EVP_get_digestbyname("SHA384"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb128"); + return EVP_AES_128_CFB128; } + #endif /* WOLFSSL_AES_128 */ -#endif /* WOLFSSL_SHA384 */ - -#ifdef WOLFSSL_SHA512 - - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512(void) + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_cfb128(void) { - WOLFSSL_ENTER("EVP_sha512"); - return EVP_get_digestbyname("SHA512"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb128"); + return EVP_AES_192_CFB128; } + #endif /* WOLFSSL_AES_192 */ -#ifndef WOLFSSL_NOSHA512_224 + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_cfb128(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb128"); + return EVP_AES_256_CFB128; + } + #endif /* WOLFSSL_AES_256 */ + #endif /* WOLFSSL_AES_CFB */ - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_224(void) + #ifdef WOLFSSL_AES_OFB + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ofb(void) { - WOLFSSL_ENTER("EVP_sha512_224"); - return EVP_get_digestbyname("SHA512_224"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ofb"); + return EVP_AES_128_OFB; } + #endif /* WOLFSSL_AES_128 */ -#endif /* !WOLFSSL_NOSHA512_224 */ + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_ofb(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ofb"); + return EVP_AES_192_OFB; + } + #endif /* WOLFSSL_AES_192 */ -#ifndef WOLFSSL_NOSHA512_256 - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_256(void) + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_ofb(void) { - WOLFSSL_ENTER("EVP_sha512_256"); - return EVP_get_digestbyname("SHA512_256"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ofb"); + return EVP_AES_256_OFB; } + #endif /* WOLFSSL_AES_256 */ + #endif /* WOLFSSL_AES_OFB */ -#endif /* !WOLFSSL_NOSHA512_224 */ + #ifdef WOLFSSL_AES_XTS + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_xts(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_xts"); + return EVP_AES_128_XTS; + } + #endif /* WOLFSSL_AES_128 */ -#endif /* WOLFSSL_SHA512 */ + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_xts(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_xts"); + return EVP_AES_256_XTS; + } + #endif /* WOLFSSL_AES_256 */ + #endif /* WOLFSSL_AES_XTS */ -#ifdef WOLFSSL_SHA3 -#ifndef WOLFSSL_NOSHA3_224 - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_224(void) + #ifdef HAVE_AESGCM + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_gcm(void) { - WOLFSSL_ENTER("EVP_sha3_224"); - return EVP_get_digestbyname("SHA3_224"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_gcm"); + return EVP_AES_128_GCM; } -#endif /* WOLFSSL_NOSHA3_224 */ + #endif /* WOLFSSL_GCM_128 */ + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_gcm(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_gcm"); + return EVP_AES_192_GCM; + } + #endif /* WOLFSSL_AES_192 */ -#ifndef WOLFSSL_NOSHA3_256 - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_256(void) + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_gcm(void) { - WOLFSSL_ENTER("EVP_sha3_256"); - return EVP_get_digestbyname("SHA3_256"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_gcm"); + return EVP_AES_256_GCM; } -#endif /* WOLFSSL_NOSHA3_256 */ + #endif /* WOLFSSL_AES_256 */ + #endif /* HAVE_AESGCM */ -#ifndef WOLFSSL_NOSHA3_384 - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_384(void) + #ifdef HAVE_AESCCM + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ccm(void) { - WOLFSSL_ENTER("EVP_sha3_384"); - return EVP_get_digestbyname("SHA3_384"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ccm"); + return EVP_AES_128_CCM; } -#endif /* WOLFSSL_NOSHA3_384 */ + #endif /* WOLFSSL_CCM_128 */ -#ifndef WOLFSSL_NOSHA3_512 - const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_512(void) + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_ccm(void) { - WOLFSSL_ENTER("EVP_sha3_512"); - return EVP_get_digestbyname("SHA3_512"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ccm"); + return EVP_AES_192_CCM; } -#endif /* WOLFSSL_NOSHA3_512 */ + #endif /* WOLFSSL_AES_192 */ -#ifdef WOLFSSL_SHAKE128 - const WOLFSSL_EVP_MD* wolfSSL_EVP_shake128(void) + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_ccm(void) { - WOLFSSL_ENTER("EVP_shake128"); - return EVP_get_digestbyname("SHAKE128"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ccm"); + return EVP_AES_256_CCM; } -#endif /* WOLFSSL_SHAKE128 */ + #endif /* WOLFSSL_AES_256 */ + #endif /* HAVE_AESCCM */ -#ifdef WOLFSSL_SHAKE256 - const WOLFSSL_EVP_MD* wolfSSL_EVP_shake256(void) + #ifdef WOLFSSL_AES_COUNTER + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ctr(void) { - WOLFSSL_ENTER("EVP_shake256"); - return EVP_get_digestbyname("SHAKE256"); + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ctr"); + return EVP_AES_128_CTR; } -#endif /* WOLFSSL_SHAKE256 */ + #endif /* WOLFSSL_AES_2128 */ -#endif /* WOLFSSL_SHA3 */ + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_ctr(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ctr"); + return EVP_AES_192_CTR; + } + #endif /* WOLFSSL_AES_192 */ - WOLFSSL_EVP_MD_CTX *wolfSSL_EVP_MD_CTX_new(void) + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_ctr(void) { - WOLFSSL_EVP_MD_CTX* ctx; - WOLFSSL_ENTER("EVP_MD_CTX_new"); - ctx = (WOLFSSL_EVP_MD_CTX*)XMALLOC(sizeof *ctx, NULL, - DYNAMIC_TYPE_OPENSSL); - if (ctx){ - wolfSSL_EVP_MD_CTX_init(ctx); - } - return ctx; + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ctr"); + return EVP_AES_256_CTR; } + #endif /* WOLFSSL_AES_256 */ + #endif /* WOLFSSL_AES_COUNTER */ - void wolfSSL_EVP_MD_CTX_free(WOLFSSL_EVP_MD_CTX *ctx) + #ifdef HAVE_AES_ECB + #ifdef WOLFSSL_AES_128 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ecb(void) { - if (ctx) { - WOLFSSL_ENTER("EVP_MD_CTX_free"); - wolfSSL_EVP_MD_CTX_cleanup(ctx); - XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL); - } + WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ecb"); + return EVP_AES_128_ECB; } + #endif /* WOLFSSL_AES_128 */ - /* returns the NID of message digest used by the ctx */ - int wolfSSL_EVP_MD_CTX_type(const WOLFSSL_EVP_MD_CTX *ctx) - { - WOLFSSL_ENTER("EVP_MD_CTX_type"); - if (ctx) { - const struct s_ent *ent; + #ifdef WOLFSSL_AES_192 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_ecb(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ecb"); + return EVP_AES_192_ECB; + } + #endif /* WOLFSSL_AES_192*/ - if (ctx->isHMAC) { - return NID_hmac; - } - for(ent = md_tbl; ent->name != NULL; ent++) { - if (ctx->macType == ent->macType) { - return ent->nid; - } - } - /* Return whatever we got */ - return ctx->macType; - } - return 0; + #ifdef WOLFSSL_AES_256 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_ecb(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ecb"); + return EVP_AES_256_ECB; } + #endif /* WOLFSSL_AES_256 */ + #endif /* HAVE_AES_ECB */ + #endif /* NO_AES */ - -#ifdef OPENSSL_EXTRA - /* returns WOLFSSL_SUCCESS on success */ - int wolfSSL_EVP_MD_CTX_copy(WOLFSSL_EVP_MD_CTX *out, const WOLFSSL_EVP_MD_CTX *in) +#ifndef NO_DES3 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_des_cbc(void) { - return wolfSSL_EVP_MD_CTX_copy_ex(out, in); + WOLFSSL_ENTER("wolfSSL_EVP_des_cbc"); + return EVP_DES_CBC; + } +#ifdef WOLFSSL_DES_ECB + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_des_ecb(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_des_ecb"); + return EVP_DES_ECB; } #endif - - /* returns digest size */ - int wolfSSL_EVP_MD_CTX_size(const WOLFSSL_EVP_MD_CTX *ctx) { - return(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(ctx))); + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_des_ede3_cbc(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_des_ede3_cbc"); + return EVP_DES_EDE3_CBC; } - /* returns block size */ - int wolfSSL_EVP_MD_CTX_block_size(const WOLFSSL_EVP_MD_CTX *ctx) { - return(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(ctx))); +#ifdef WOLFSSL_DES_ECB + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_des_ede3_ecb(void) + { + WOLFSSL_ENTER("wolfSSL_EVP_des_ede3_ecb"); + return EVP_DES_EDE3_ECB; } +#endif +#endif /* NO_DES3 */ -#ifdef OPENSSL_EXTRA - /* Deep copy of EVP_MD hasher - * return WOLFSSL_SUCCESS on success */ - static int wolfSSL_EVP_MD_Copy_Hasher(WOLFSSL_EVP_MD_CTX* des, - const WOLFSSL_EVP_MD_CTX* src) +#ifndef NO_RC4 + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_rc4(void) { - if (src->isHMAC) { - return wolfSSL_HmacCopy(&des->hash.hmac, (Hmac*)&src->hash.hmac); - } - else { - int ret; - - switch (src->macType) { - case WC_HASH_TYPE_MD5: - #ifndef NO_MD5 - ret = wc_Md5Copy((wc_Md5*)&src->hash.digest, - (wc_Md5*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif /* !NO_MD5 */ - break; - case WC_HASH_TYPE_SHA: - #ifndef NO_SHA - ret = wc_ShaCopy((wc_Sha*)&src->hash.digest, - (wc_Sha*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif /* !NO_SHA */ - break; - case WC_HASH_TYPE_SHA224: - #ifdef WOLFSSL_SHA224 - ret = wc_Sha224Copy((wc_Sha224*)&src->hash.digest, - (wc_Sha224*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif /* WOLFSSL_SHA224 */ - break; - case WC_HASH_TYPE_SHA256: - #ifndef NO_SHA256 - ret = wc_Sha256Copy((wc_Sha256*)&src->hash.digest, - (wc_Sha256*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif /* !NO_SHA256 */ - break; - case WC_HASH_TYPE_SHA384: - #ifdef WOLFSSL_SHA384 - ret = wc_Sha384Copy((wc_Sha384*)&src->hash.digest, - (wc_Sha384*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif /* WOLFSSL_SHA384 */ - break; - case WC_HASH_TYPE_SHA512: - #ifdef WOLFSSL_SHA512 - ret = wc_Sha512Copy((wc_Sha512*)&src->hash.digest, - (wc_Sha512*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif /* WOLFSSL_SHA512 */ - break; - #ifndef WOLFSSL_NOSHA512_224 - case WC_HASH_TYPE_SHA512_224: - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) - ret = wc_Sha512_224Copy((wc_Sha512*)&src->hash.digest, - (wc_Sha512*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif - break; - #endif /* !WOLFSSL_NOSHA512_224 */ - #ifndef WOLFSSL_NOSHA512_256 - case WC_HASH_TYPE_SHA512_256: - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) - ret = wc_Sha512_256Copy((wc_Sha512*)&src->hash.digest, - (wc_Sha512*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif - break; - #endif /* !WOLFSSL_NOSHA512_256 */ - case WC_HASH_TYPE_SHA3_224: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wc_Sha3_224_Copy((wc_Sha3*)&src->hash.digest, - (wc_Sha3*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif - break; - case WC_HASH_TYPE_SHA3_256: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wc_Sha3_256_Copy((wc_Sha3*)&src->hash.digest, - (wc_Sha3*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif - break; - case WC_HASH_TYPE_SHA3_384: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wc_Sha3_384_Copy((wc_Sha3*)&src->hash.digest, - (wc_Sha3*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif - break; - case WC_HASH_TYPE_SHA3_512: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wc_Sha3_512_Copy((wc_Sha3*)&src->hash.digest, - (wc_Sha3*)&des->hash.digest); - #else - ret = NOT_COMPILED_IN; - #endif - break; - case WC_HASH_TYPE_NONE: - case WC_HASH_TYPE_MD2: - case WC_HASH_TYPE_MD4: - case WC_HASH_TYPE_MD5_SHA: - case WC_HASH_TYPE_BLAKE2B: - case WC_HASH_TYPE_BLAKE2S: - #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) - case WC_HASH_TYPE_SHAKE128: - #endif - #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) - case WC_HASH_TYPE_SHAKE256: - #endif - default: - ret = BAD_FUNC_ARG; - break; - } - return ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; - } - } - - /* copies structure in to the structure out - * - * returns WOLFSSL_SUCCESS on success */ - int wolfSSL_EVP_MD_CTX_copy_ex(WOLFSSL_EVP_MD_CTX *out, const WOLFSSL_EVP_MD_CTX *in) - { - if ((out == NULL) || (in == NULL)) return WOLFSSL_FAILURE; - WOLFSSL_ENTER("EVP_CIPHER_MD_CTX_copy_ex"); - wolfSSL_EVP_MD_CTX_cleanup(out); - XMEMCPY(out, in, sizeof(WOLFSSL_EVP_MD_CTX)); - if (in->pctx != NULL) { - out->pctx = wolfSSL_EVP_PKEY_CTX_new(in->pctx->pkey, NULL); - if (out->pctx == NULL) - return WOLFSSL_FAILURE; - } - return wolfSSL_EVP_MD_Copy_Hasher(out, (WOLFSSL_EVP_MD_CTX*)in); + WOLFSSL_ENTER("wolfSSL_EVP_rc4"); + return EVP_ARC4; } #endif - void wolfSSL_EVP_MD_CTX_init(WOLFSSL_EVP_MD_CTX* ctx) +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_chacha20_poly1305(void) { - WOLFSSL_ENTER("EVP_CIPHER_MD_CTX_init"); - XMEMSET(ctx, 0, sizeof(WOLFSSL_EVP_MD_CTX)); + WOLFSSL_ENTER("wolfSSL_EVP_chacha20_poly1305"); + return EVP_CHACHA20_POLY1305; } +#endif - const WOLFSSL_EVP_MD *wolfSSL_EVP_MD_CTX_md(const WOLFSSL_EVP_MD_CTX *ctx) +#ifdef HAVE_CHACHA + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_chacha20(void) { - const struct s_ent *ent; - if (ctx == NULL) - return NULL; - WOLFSSL_ENTER("EVP_MD_CTX_md"); - if (ctx->isHMAC) { - return "HMAC"; - } - for(ent = md_tbl; ent->name != NULL; ent++) { - if(ctx->macType == ent->macType) { - return (const WOLFSSL_EVP_MD *)ent->name; - } - } - return (WOLFSSL_EVP_MD *)NULL; + WOLFSSL_ENTER("wolfSSL_EVP_chacha20"); + return EVP_CHACHA20; } +#endif - /* return alias name if has - * @param n message digest type name - * @return alias name, otherwise NULL - */ - static const char* hasAliasName(const char* n) + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_enc_null(void) { - - const char* aliasnm = NULL; - const struct alias *al; - - for (al = digest_alias_tbl; al->name != NULL; al++) - if(XSTRCMP(n, al->name) == 0) { - aliasnm = al->alias; - break; - } - - return aliasnm; + WOLFSSL_ENTER("wolfSSL_EVP_enc_null"); + return EVP_NULL; } - - - struct do_all_md { - void *arg; - void (*fn) (const WOLFSSL_EVP_MD *m, - const char* from, const char* to, void *arg); - }; - - /* do all md algorithm - * @param nm a pointer to WOLFSSL_OBJ_NAME - * @param arg arguments to pass to the callback - * @return none - */ - static void md_do_all_func(const WOLFSSL_OBJ_NAME* nm, void* arg) + void wolfSSL_EVP_CIPHER_CTX_init(WOLFSSL_EVP_CIPHER_CTX* ctx) { - struct do_all_md *md = (struct do_all_md*)arg; - - const struct s_ent *ent; - - /* sanity check */ - if (md == NULL || nm == NULL || md->fn == NULL || - nm->type != WOLFSSL_OBJ_NAME_TYPE_MD_METH) - return; - - /* loop all md */ - for (ent = md_tbl; ent->name != NULL; ent++){ - /* check if the md has alias */ - if(hasAliasName(ent->name) != NULL) { - md->fn(NULL, ent->name, ent->name, md->arg); - } - else { - md->fn(ent->name, ent->name, NULL, md->arg); - } + WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_init"); + if (ctx) { + XMEMSET(ctx, 0, sizeof(WOLFSSL_EVP_CIPHER_CTX)); + ctx->cipherType = WOLFSSL_EVP_CIPH_TYPE_INIT; /* not yet initialized */ + ctx->keyLen = 0; + ctx->enc = 1; /* start in encrypt mode */ } } - /* call md_do_all function to do all md algorithm via a callback function - * @param fn a callback function to be called with all 'md' - * @param args arguments to pass to the callback - * @return none - */ - void wolfSSL_EVP_MD_do_all(void (*fn) (const WOLFSSL_EVP_MD *m, - const char* from, const char* to, void* xx), void* args) + /* This function allows cipher specific parameters to be + determined and set. */ + int wolfSSL_EVP_CIPHER_CTX_ctrl(WOLFSSL_EVP_CIPHER_CTX *ctx, int type, \ + int arg, void *ptr) { - struct do_all_md md; + int ret = WOLFSSL_FAILURE; +#if defined(HAVE_AESGCM) || (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) +#ifndef WC_NO_RNG + WC_RNG rng; +#endif +#endif + if (ctx == NULL) + return WOLFSSL_FAILURE; - md.fn = fn; - md.arg = args; + (void)arg; + (void)ptr; - wolfSSL_OBJ_NAME_do_all(WOLFSSL_OBJ_NAME_TYPE_MD_METH, - md_do_all_func, &md); - } - - /* call "fn" based on OBJ_NAME type - * @param type OBJ_NAME type - * @param fn a callback function - * @param args arguments to pass to the callback - * @return none - */ - void wolfSSL_OBJ_NAME_do_all(int type, - void (*fn)(const WOLFSSL_OBJ_NAME*, void* arg), void* arg) - { - WOLFSSL_OBJ_NAME objnm; - - /* sanity check */ - if (!fn) - return; - - objnm.type = type; + WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_ctrl"); switch(type) { - case WOLFSSL_OBJ_NAME_TYPE_MD_METH: - fn(&objnm, arg); + case EVP_CTRL_INIT: + wolfSSL_EVP_CIPHER_CTX_init(ctx); + if(ctx) + ret = WOLFSSL_SUCCESS; break; - case WOLFSSL_OBJ_NAME_TYPE_CIPHER_METH: - case WOLFSSL_OBJ_NAME_TYPE_PKEY_METH: - case WOLFSSL_OBJ_NAME_TYPE_COMP_METH: - case WOLFSSL_OBJ_NAME_TYPE_NUM: - WOLFSSL_MSG("not implemented"); - FALL_THROUGH; - case WOLFSSL_OBJ_NAME_TYPE_UNDEF: - default: + case EVP_CTRL_SET_KEY_LENGTH: + ret = wolfSSL_EVP_CIPHER_CTX_set_key_length(ctx, arg); + break; +#if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || \ + (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) + case EVP_CTRL_AEAD_SET_IVLEN: + if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) + break; + #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (arg != CHACHA20_POLY1305_AEAD_IV_SIZE) { + break; + } + } + else + #endif /* HAVE_CHACHA && HAVE_POLY1305 */ + { + if (arg <= 0 || arg > AES_BLOCK_SIZE) + break; + } + ret = wolfSSL_EVP_CIPHER_CTX_set_iv_length(ctx, arg); break; - } - } - -#ifdef OPENSSL_EXTRA - #ifndef NO_AES - - #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cbc(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cbc"); - return EVP_AES_128_CBC; - } - #endif /* WOLFSSL_AES_128 */ +#if defined(HAVE_AESGCM) || (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) + case EVP_CTRL_AEAD_SET_IV_FIXED: + if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) + break; + if (arg == -1) { + /* arg == -1 copies ctx->ivSz from ptr */ + ret = wolfSSL_EVP_CIPHER_CTX_set_iv(ctx, (byte*)ptr, ctx->ivSz); + } +#ifndef WC_NO_RNG + else { + /* + * Fixed field must be at least 4 bytes and invocation + * field at least 8. + */ + if ((arg < 4) || (ctx->ivSz - arg) < 8) { + WOLFSSL_MSG("Fixed field or invocation field too short"); + break; + } + /* arg is 4...(ctx->ivSz - 8) */ + XMEMCPY(ctx->iv, ptr, arg); + if (wc_InitRng(&rng) != 0) { + WOLFSSL_MSG("wc_InitRng failed"); + break; + } + if (wc_RNG_GenerateBlock(&rng, ctx->iv + arg, + ctx->ivSz - arg) == 0) { + ret = WOLFSSL_SUCCESS; + } else { + /* rng is freed immediately after if block so no need + * to do it here + */ + WOLFSSL_MSG("wc_RNG_GenerateBlock failed"); + } + if (wc_FreeRng(&rng) != 0) { + WOLFSSL_MSG("wc_FreeRng failed"); + ret = WOLFSSL_FAILURE; + break; + } + } + #ifdef HAVE_AESGCM + if (ret == WOLFSSL_SUCCESS) { + /* + * OpenSSL requires that a EVP_CTRL_AEAD_SET_IV_FIXED + * command be issued before a EVP_CTRL_GCM_IV_GEN command. + * This flag is used to enforce that. + */ + ctx->authIvGenEnable = 1; + } + #endif +#endif /* !WC_NO_RNG */ + break; +#endif /* HAVE_AESGCM || (HAVE_CHACHA && HAVE_POLY1305) */ +#if defined(HAVE_AESGCM) && !defined(_WIN32) && !defined(HAVE_SELFTEST) && \ + (!defined(HAVE_FIPS) || FIPS_VERSION_GE(2,0)) + /* + * Using EVP_CTRL_GCM_IV_GEN is a way to do AES-GCM encrypt/decrypt + * multiple times with EVP_Cipher without having to call + * EVP_CipherInit between each iteration. The IV is incremented for + * each subsequent EVP_Cipher call to prevent IV reuse. + */ + case EVP_CTRL_GCM_IV_GEN: + if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) + break; + if (!ctx->authIvGenEnable) { + WOLFSSL_MSG("Must use EVP_CTRL_AEAD_SET_IV_FIXED before " + "EVP_CTRL_GCM_IV_GEN"); + break; + } + if (ctx->cipher.aes.keylen == 0 || ctx->ivSz == 0) { + WOLFSSL_MSG("Key or IV not set"); + break; + } + if (ptr == NULL) { + WOLFSSL_MSG("Destination buffer for IV bytes NULL."); + break; + } + if (arg <= 0 || arg > ctx->ivSz) { + XMEMCPY(ptr, ctx->iv, ctx->ivSz); + } + else { + /* + * Copy the last "arg" bytes of ctx->iv into the buffer at + * "ptr." Not sure why OpenSSL does this, but it does. + */ + XMEMCPY(ptr, ctx->iv + ctx->ivSz - arg, arg); + } - #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_cbc(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cbc"); - return EVP_AES_192_CBC; - } - #endif /* WOLFSSL_AES_192 */ + /* + * The gcmIncIV flag indicates that the IV should be incremented + * after the next cipher operation. + */ + ctx->authIncIv = 1; + ret = WOLFSSL_SUCCESS; + break; +#endif /* HAVE_AESGCM && !_WIN32 && !HAVE_SELFTEST && (!HAVE_FIPS || + * FIPS_VERSION >= 2)*/ + case EVP_CTRL_AEAD_SET_TAG: + if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) + break; +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (arg != CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE) { + break; + } + ctx->authTagSz = arg; + ret = WOLFSSL_SUCCESS; + if (ptr != NULL) { + XMEMCPY(ctx->authTag, ptr, arg); + } + break; + } + else +#endif /* HAVE_CHACHA && HAVE_POLY1305 */ + { + if(arg <= 0 || arg > 16 || (ptr == NULL)) + break; + XMEMCPY(ctx->authTag, ptr, arg); + ctx->authTagSz = arg; + ret = WOLFSSL_SUCCESS; + break; + } + case EVP_CTRL_AEAD_GET_TAG: + if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) + break; - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_cbc(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cbc"); - return EVP_AES_256_CBC; - } - #endif /* WOLFSSL_AES_256 */ - #endif /* HAVE_AES_CBC */ +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (arg != CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE) { + break; + } + } + else +#endif /* HAVE_CHACHA && HAVE_POLY1305 */ + { + if (arg <= 0 || arg > AES_BLOCK_SIZE) + break; + } - #ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb1(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb1"); - return EVP_AES_128_CFB1; + if (ptr != NULL) { + XMEMCPY(ptr, ctx->authTag, arg); + ret = WOLFSSL_SUCCESS; + } + break; +#endif /* HAVE_AESGCM || HAVE_AESCCM || (HAVE_CHACHA && HAVE_POLY1305) */ + default: + WOLFSSL_MSG("EVP_CIPHER_CTX_ctrl operation not yet handled"); + break; + } + return ret; } - #endif /* WOLFSSL_AES_128 */ - #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_cfb1(void) + /* WOLFSSL_SUCCESS on ok */ + int wolfSSL_EVP_CIPHER_CTX_cleanup(WOLFSSL_EVP_CIPHER_CTX* ctx) { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb1"); - return EVP_AES_192_CFB1; - } - #endif /* WOLFSSL_AES_192 */ + WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_cleanup"); + if (ctx) { +#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ + (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) +#if (defined(HAVE_AESGCM) && defined(WOLFSSL_AESGCM_STREAM)) || \ + defined(HAVE_AESCCM) || \ + defined(HAVE_AESCBC) || \ + defined(WOLFSSL_AES_COUNTER) || \ + defined(HAVE_AES_ECB) || \ + defined(HAVE_AES_CFB) || \ + defined(HAVE_AES_OFB) || \ + defined(WOLFSSL_AES_XTS) - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_cfb1(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb1"); - return EVP_AES_256_CFB1; - } - #endif /* WOLFSSL_AES_256 */ - - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb8(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb8"); - return EVP_AES_128_CFB8; - } - #endif /* WOLFSSL_AES_128 */ + switch (ctx->cipherType) { + #if defined(HAVE_AESGCM) && defined(WOLFSSL_AESGCM_STREAM) + case AES_128_GCM_TYPE: + case AES_192_GCM_TYPE: + case AES_256_GCM_TYPE: + #endif /* HAVE_AESGCM && WOLFSSL_AESGCM_STREAM */ + #if defined(HAVE_AESCCM) + case AES_128_CCM_TYPE: + case AES_192_CCM_TYPE: + case AES_256_CCM_TYPE: + #endif /* HAVE_AESCCM */ + #ifdef HAVE_AESCBC + case AES_128_CBC_TYPE: + case AES_192_CBC_TYPE: + case AES_256_CBC_TYPE: + #endif + #ifdef WOLFSSL_AES_COUNTER + case AES_128_CTR_TYPE: + case AES_192_CTR_TYPE: + case AES_256_CTR_TYPE: + #endif + #ifdef HAVE_AES_ECB + case AES_128_ECB_TYPE: + case AES_192_ECB_TYPE: + case AES_256_ECB_TYPE: + #endif + #ifdef HAVE_AES_CFB + case AES_128_CFB1_TYPE: + case AES_192_CFB1_TYPE: + case AES_256_CFB1_TYPE: + case AES_128_CFB8_TYPE: + case AES_192_CFB8_TYPE: + case AES_256_CFB8_TYPE: + case AES_128_CFB128_TYPE: + case AES_192_CFB128_TYPE: + case AES_256_CFB128_TYPE: + #endif + #ifdef HAVE_AES_OFB + case AES_128_OFB_TYPE: + case AES_192_OFB_TYPE: + case AES_256_OFB_TYPE: + #endif + #ifdef WOLFSSL_AES_XTS + case AES_128_XTS_TYPE: + case AES_256_XTS_TYPE: + #endif + wc_AesFree(&ctx->cipher.aes); + } - #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_cfb8(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb8"); - return EVP_AES_192_CFB8; - } - #endif /* WOLFSSL_AES_192 */ +#endif /* AES */ +#endif /* not FIPS or FIPS v2+ */ - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_cfb8(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb8"); - return EVP_AES_256_CFB8; - } - #endif /* WOLFSSL_AES_256 */ -#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ + ctx->cipherType = WOLFSSL_EVP_CIPH_TYPE_INIT; /* not yet initialized */ +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + if (ctx->key) { + ForceZero(ctx->key, ctx->keyLen); + XFREE(ctx->key, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->key = NULL; + } +#endif + ctx->keyLen = 0; +#if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) + if (ctx->authBuffer) { + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; + } + ctx->authBufferLen = 0; + if (ctx->authIn) { + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + ctx->authInSz = 0; + ctx->authIvGenEnable = 0; + ctx->authIncIv = 0; +#endif + } - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb128(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb128"); - return EVP_AES_128_CFB128; + return WOLFSSL_SUCCESS; } - #endif /* WOLFSSL_AES_128 */ - #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_cfb128(void) + /* Permanent stub for Qt compilation. */ + #if defined(WOLFSSL_QT) && !defined(NO_WOLFSSL_STUB) + const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_rc2_cbc(void) { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb128"); - return EVP_AES_192_CFB128; + WOLFSSL_ENTER("wolfSSL_EVP_rc2_cbc"); + WOLFSSL_STUB("EVP_rc2_cbc"); + return NULL; } - #endif /* WOLFSSL_AES_192 */ + #endif - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_cfb128(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb128"); - return EVP_AES_256_CFB128; - } - #endif /* WOLFSSL_AES_256 */ - #endif /* WOLFSSL_AES_CFB */ +#if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED) - #ifdef WOLFSSL_AES_OFB - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ofb(void) + int wolfSSL_EVP_BytesToKey(const WOLFSSL_EVP_CIPHER* type, + const WOLFSSL_EVP_MD* md, const byte* salt, + const byte* data, int sz, int count, byte* key, byte* iv) { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ofb"); - return EVP_AES_128_OFB; - } - #endif /* WOLFSSL_AES_128 */ + int ret; + int hashType = WC_HASH_TYPE_NONE; + #ifdef WOLFSSL_SMALL_STACK + EncryptedInfo* info; + #else + EncryptedInfo info[1]; + #endif - #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_ofb(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ofb"); - return EVP_AES_192_OFB; - } - #endif /* WOLFSSL_AES_192 */ + #ifdef WOLFSSL_SMALL_STACK + info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL, + DYNAMIC_TYPE_ENCRYPTEDINFO); + if (info == NULL) { + WOLFSSL_MSG("malloc failed"); + return WOLFSSL_FAILURE; + } + #endif - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_ofb(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ofb"); - return EVP_AES_256_OFB; - } - #endif /* WOLFSSL_AES_256 */ - #endif /* WOLFSSL_AES_OFB */ + XMEMSET(info, 0, sizeof(EncryptedInfo)); - #ifdef WOLFSSL_AES_XTS - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_xts(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_xts"); - return EVP_AES_128_XTS; - } - #endif /* WOLFSSL_AES_128 */ + ret = wc_EncryptedInfoGet(info, type); + if (ret < 0) + goto end; - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_xts(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_xts"); - return EVP_AES_256_XTS; - } - #endif /* WOLFSSL_AES_256 */ - #endif /* WOLFSSL_AES_XTS */ + if (data == NULL) { + ret = info->keySz; + goto end; + } - #ifdef HAVE_AESGCM - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_gcm(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_gcm"); - return EVP_AES_128_GCM; - } - #endif /* WOLFSSL_GCM_128 */ + ret = wolfSSL_EVP_get_hashinfo(md, &hashType, NULL); + if (ret == WOLFSSL_FAILURE) + goto end; - #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_gcm(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_gcm"); - return EVP_AES_192_GCM; - } - #endif /* WOLFSSL_AES_192 */ + ret = wc_PBKDF1_ex(key, info->keySz, iv, info->ivSz, data, sz, salt, + EVP_SALT_SIZE, count, hashType, NULL); + if (ret == 0) + ret = info->keySz; - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_gcm(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_gcm"); - return EVP_AES_256_GCM; - } - #endif /* WOLFSSL_AES_256 */ - #endif /* HAVE_AESGCM */ + end: + #ifdef WOLFSSL_SMALL_STACK + XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); + #endif + if (ret < 0) + return 0; /* failure - for compatibility */ - #ifdef HAVE_AESCCM - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ccm(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ccm"); - return EVP_AES_128_CCM; + return ret; } - #endif /* WOLFSSL_CCM_128 */ - #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_ccm(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ccm"); - return EVP_AES_192_CCM; - } - #endif /* WOLFSSL_AES_192 */ +#endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */ - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_ccm(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ccm"); - return EVP_AES_256_CCM; - } - #endif /* WOLFSSL_AES_256 */ - #endif /* HAVE_AESCCM */ - #ifdef WOLFSSL_AES_COUNTER - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ctr(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ctr"); - return EVP_AES_128_CTR; - } - #endif /* WOLFSSL_AES_2128 */ +#ifndef NO_AES +#if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) || \ + defined(WOLFSSL_AES_256) + #define AES_SIZE_ANY +#endif +#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_COUNTER) || \ + defined(HAVE_AES_ECB) || defined(WOLFSSL_AES_CFB) || \ + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_DIRECT) + #define AES_SET_KEY +#endif - #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_ctr(void) +#if defined(AES_SIZE_ANY) && defined(AES_SET_KEY) + static int AesSetKey_ex(Aes* aes, const byte* key, word32 len, + const byte* iv, int dir, int direct) { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ctr"); - return EVP_AES_192_CTR; + int ret; + /* wc_AesSetKey clear aes.reg if iv == NULL. + Keep IV for openSSL compatibility */ + if (iv == NULL) + XMEMCPY((byte *)aes->tmp, (byte *)aes->reg, AES_BLOCK_SIZE); + if (direct) { + #if defined(WOLFSSL_AES_DIRECT) + ret = wc_AesSetKeyDirect(aes, key, len, iv, dir); + #else + ret = NOT_COMPILED_IN; + #endif + } + else { + ret = wc_AesSetKey(aes, key, len, iv, dir); + } + if (iv == NULL) + XMEMCPY((byte *)aes->reg, (byte *)aes->tmp, AES_BLOCK_SIZE); + return ret; } - #endif /* WOLFSSL_AES_192 */ - +#endif /* AES_ANY_SIZE && AES_SET_KEY */ +#endif /* NO_AES */ - #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_ctr(void) +#if defined(HAVE_AESGCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ + || FIPS_VERSION_GE(2,0)) + static int EvpCipherInitAesGCM(WOLFSSL_EVP_CIPHER_CTX* ctx, + const WOLFSSL_EVP_CIPHER* type, + const byte* key, const byte* iv, int enc) { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ctr"); - return EVP_AES_256_CTR; - } - #endif /* WOLFSSL_AES_256 */ - #endif /* WOLFSSL_AES_COUNTER */ + int ret = WOLFSSL_SUCCESS; - #ifdef HAVE_AES_ECB - #ifdef WOLFSSL_AES_128 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ecb(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ecb"); - return EVP_AES_128_ECB; - } - #endif /* WOLFSSL_AES_128 */ + if (ctx->authIn) { + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + ctx->authInSz = 0; + ctx->block_size = AES_BLOCK_SIZE; + ctx->authTagSz = AES_BLOCK_SIZE; + if (ctx->ivSz == 0) { + ctx->ivSz = GCM_NONCE_MID_SZ; + } + ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_GCM_MODE | + WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; + if (enc == 0 || enc == 1) { + ctx->enc = enc ? 1 : 0; + } + #ifdef WOLFSSL_AES_128 + if (ctx->cipherType == AES_128_GCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_GCM))) { + WOLFSSL_MSG("EVP_AES_128_GCM"); + ctx->cipherType = AES_128_GCM_TYPE; + ctx->keyLen = AES_128_KEY_SIZE; + } + #endif #ifdef WOLFSSL_AES_192 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_192_ecb(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ecb"); - return EVP_AES_192_ECB; - } - #endif /* WOLFSSL_AES_192*/ - - + if (ctx->cipherType == AES_192_GCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_GCM))) { + WOLFSSL_MSG("EVP_AES_192_GCM"); + ctx->cipherType = AES_192_GCM_TYPE; + ctx->keyLen = AES_192_KEY_SIZE; + } + #endif #ifdef WOLFSSL_AES_256 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_256_ecb(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ecb"); - return EVP_AES_256_ECB; - } - #endif /* WOLFSSL_AES_256 */ - #endif /* HAVE_AES_ECB */ - #endif /* NO_AES */ - -#ifndef NO_DES3 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_des_cbc(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_des_cbc"); - return EVP_DES_CBC; - } -#ifdef WOLFSSL_DES_ECB - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_des_ecb(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_des_ecb"); - return EVP_DES_ECB; - } -#endif - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_des_ede3_cbc(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_des_ede3_cbc"); - return EVP_DES_EDE3_CBC; - } -#ifdef WOLFSSL_DES_ECB - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_des_ede3_ecb(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_des_ede3_ecb"); - return EVP_DES_EDE3_ECB; - } -#endif -#endif /* NO_DES3 */ - -#ifndef NO_RC4 - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_rc4(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_rc4"); - return EVP_ARC4; - } -#endif + if (ctx->cipherType == AES_256_GCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_GCM))) { + WOLFSSL_MSG("EVP_AES_256_GCM"); + ctx->cipherType = AES_256_GCM_TYPE; + ctx->keyLen = AES_256_KEY_SIZE; + } + #endif -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_chacha20_poly1305(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_chacha20_poly1305"); - return EVP_CHACHA20_POLY1305; - } -#endif + #ifndef WOLFSSL_AESGCM_STREAM + if (ret == WOLFSSL_SUCCESS && key && + wc_AesGcmSetKey(&ctx->cipher.aes, key, ctx->keyLen)) { + WOLFSSL_MSG("wc_AesGcmSetKey() failed"); + ret = WOLFSSL_FAILURE; + } + #endif /* !WOLFSSL_AESGCM_STREAM */ + if (ret == WOLFSSL_SUCCESS && iv && + wc_AesGcmSetExtIV(&ctx->cipher.aes, iv, ctx->ivSz)) { + WOLFSSL_MSG("wc_AesGcmSetExtIV() failed"); + ret = WOLFSSL_FAILURE; + } + #ifdef WOLFSSL_AESGCM_STREAM + /* + * Initialize with key and IV if available. wc_AesGcmInit will fail + * if called with IV only and no key has been set. + */ + if (ret == WOLFSSL_SUCCESS && + (key || (iv && ctx->cipher.aes.gcmKeySet)) && + wc_AesGcmInit(&ctx->cipher.aes, key, + (key == NULL) ? 0 : ctx->keyLen, iv, + (iv == NULL) ? 0 : ctx->ivSz) != 0) { + WOLFSSL_MSG("wc_AesGcmInit() failed"); + ret = WOLFSSL_FAILURE; + } + #endif /* WOLFSSL_AESGCM_STREAM */ -#ifdef HAVE_CHACHA - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_chacha20(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_chacha20"); - return EVP_CHACHA20; - } -#endif + /* + * OpenSSL clears this flag, which permits subsequent use of + * EVP_CTRL_GCM_IV_GEN, when EVP_CipherInit is called with no key. + * If a key is provided, the flag retains its value. + */ + if (ret == WOLFSSL_SUCCESS && key == NULL) { + ctx->authIvGenEnable = 0; + } - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_enc_null(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_enc_null"); - return EVP_NULL; + return ret; } -#endif - int wolfSSL_EVP_MD_CTX_cleanup(WOLFSSL_EVP_MD_CTX* ctx) + static int EvpCipherAesGCM(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, + byte* src, word32 len) { - int ret = WOLFSSL_SUCCESS; - WOLFSSL_ENTER("wolfSSL_EVP_MD_CTX_cleanup"); - #ifdef OPENSSL_EXTRA - if (ctx->pctx != NULL) - wolfSSL_EVP_PKEY_CTX_free(ctx->pctx); - #endif + int ret = WOLFSSL_FAILURE; - if (ctx->isHMAC) { - wc_HmacFree(&ctx->hash.hmac); + #ifndef WOLFSSL_AESGCM_STREAM + /* No destination means only AAD. */ + if (src != NULL && dst == NULL) { + ret = wolfSSL_EVP_CipherUpdate_GCM_AAD(ctx, src, len); } - else { - switch (ctx->macType) { - case WC_HASH_TYPE_MD5: - #ifndef NO_MD5 - wc_Md5Free((wc_Md5*)&ctx->hash.digest); - #endif /* !NO_MD5 */ - break; - case WC_HASH_TYPE_SHA: - #ifndef NO_SHA - wc_ShaFree((wc_Sha*)&ctx->hash.digest); - #endif /* !NO_SHA */ - break; - case WC_HASH_TYPE_SHA224: - #ifdef WOLFSSL_SHA224 - wc_Sha224Free((wc_Sha224*)&ctx->hash.digest); - #endif /* WOLFSSL_SHA224 */ - break; - case WC_HASH_TYPE_SHA256: - #ifndef NO_SHA256 - wc_Sha256Free((wc_Sha256*)&ctx->hash.digest); - #endif /* !NO_SHA256 */ - break; - case WC_HASH_TYPE_SHA384: - #ifdef WOLFSSL_SHA384 - wc_Sha384Free((wc_Sha384*)&ctx->hash.digest); - #endif /* WOLFSSL_SHA384 */ - break; - case WC_HASH_TYPE_SHA512: - #ifdef WOLFSSL_SHA512 - wc_Sha512Free((wc_Sha512*)&ctx->hash.digest); - #endif /* WOLFSSL_SHA512 */ - break; - #ifndef WOLFSSL_NOSHA512_224 - case WC_HASH_TYPE_SHA512_224: - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) - wc_Sha512_224Free((wc_Sha512*)&ctx->hash.digest); - #endif - break; - #endif /* !WOLFSSL_NOSHA512_224 */ - #ifndef WOLFSSL_NOSHA512_256 - case WC_HASH_TYPE_SHA512_256: - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) - wc_Sha512_256Free((wc_Sha512*)&ctx->hash.digest); - #endif - break; - #endif /* !WOLFSSL_NOSHA512_256 */ - case WC_HASH_TYPE_SHA3_224: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - wc_Sha3_224_Free((wc_Sha3*)&ctx->hash.digest); - #endif - break; - case WC_HASH_TYPE_SHA3_256: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - wc_Sha3_256_Free((wc_Sha3*)&ctx->hash.digest); - #endif - break; - case WC_HASH_TYPE_SHA3_384: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - wc_Sha3_384_Free((wc_Sha3*)&ctx->hash.digest); - #endif - break; - case WC_HASH_TYPE_SHA3_512: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - wc_Sha3_512_Free((wc_Sha3*)&ctx->hash.digest); - #endif - break; - case WC_HASH_TYPE_NONE: - /* Not an error since an unused struct could be free'd or - * reset. */ - break; - case WC_HASH_TYPE_MD2: - case WC_HASH_TYPE_MD4: - case WC_HASH_TYPE_MD5_SHA: - case WC_HASH_TYPE_BLAKE2B: - case WC_HASH_TYPE_BLAKE2S: - #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) - case WC_HASH_TYPE_SHAKE128: - #endif - #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) - case WC_HASH_TYPE_SHAKE256: - #endif - default: - ret = WOLFSSL_FAILURE; - break; + else if (src != NULL && dst != NULL) { + if (ctx->enc) { + ret = wc_AesGcmEncrypt(&ctx->cipher.aes, dst, src, + len, ctx->iv, ctx->ivSz, ctx->authTag, + ctx->authTagSz, ctx->authIn, + ctx->authInSz); + } + else { + ret = wc_AesGcmDecrypt(&ctx->cipher.aes, dst, src, + len, ctx->iv, ctx->ivSz, ctx->authTag, + ctx->authTagSz, ctx->authIn, + ctx->authInSz); + } + if (ctx->authIncIv) { + IncCtr((byte*)ctx->cipher.aes.reg, + ctx->cipher.aes.nonceSz); + ctx->authIncIv = 0; } } - ForceZero(ctx, sizeof(*ctx)); - ctx->macType = WC_HASH_TYPE_NONE; + #else + /* + * No need to call wc_AesGcmInit. Should have been called by + * wolfSSL_EVP_CipherInit. + */ + /* NULL dst and non-NULL src means only AAD. */ + if (src != NULL && dst == NULL) { + if (ctx->enc) { + ret = wc_AesGcmEncryptUpdate(&ctx->cipher.aes, NULL, + NULL, 0, src, len); + } + else { + ret = wc_AesGcmDecryptUpdate(&ctx->cipher.aes, NULL, + NULL, 0, src, len); + } + } + /* Only plain/cipher text. */ + else if (src != NULL && dst != NULL) { + if (ctx->enc) { + ret = wc_AesGcmEncryptUpdate(&ctx->cipher.aes, dst, src, + len, NULL, 0); + } + else { + ret = wc_AesGcmDecryptUpdate(&ctx->cipher.aes, dst, src, + len, NULL, 0); + } + } + /* + * src == NULL is analogous to other "final"-type functions + * (e.g. EVP_CipherFinal). Calculates tag on encrypt + * and checks tag on decrypt. + */ + else { + if (ctx->enc) { + /* Calculate authentication tag. */ + ret = wc_AesGcmEncryptFinal(&ctx->cipher.aes, + ctx->authTag, ctx->authTagSz); + /* + * wc_AesGcmEncryptFinal increments the IV in + * ctx->cipher.aes.reg, so we don't call IncCtr here. + */ + } + else { + /* Calculate authentication tag and compare. */ + ret = wc_AesGcmDecryptFinal(&ctx->cipher.aes, + ctx->authTag, ctx->authTagSz); + if (ctx->authIncIv) { + IncCtr((byte*)ctx->cipher.aes.reg, + ctx->cipher.aes.nonceSz); + } + } + /* Reinitialize for subsequent wolfSSL_EVP_Cipher calls. */ + if (wc_AesGcmInit(&ctx->cipher.aes, NULL, 0, + (byte*)ctx->cipher.aes.reg, + ctx->ivSz) != 0) { + WOLFSSL_MSG("wc_AesGcmInit failed"); + return WOLFSSL_FATAL_ERROR; + } + ctx->authIncIv = 0; + } + #endif /* WOLFSSL_AESGCM_STREAM */ + if (src == NULL) { + /* + * Clear any leftover AAD on final (final is when src is + * NULL). + */ + if (ctx->authIn != NULL) { + XMEMSET(ctx->authIn, 0, ctx->authInSz); + } + ctx->authInSz = 0; + } + if (ret == 0) { + ret = len; + } + return ret; } +#endif /* HAVE_AESGCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || + * HAVE_FIPS_VERSION >= 2 */ -#ifdef OPENSSL_EXTRA - void wolfSSL_EVP_CIPHER_CTX_init(WOLFSSL_EVP_CIPHER_CTX* ctx) + /* return WOLFSSL_SUCCESS on ok, 0 on failure to match API compatibility */ +#if defined(HAVE_AESCCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ + || FIPS_VERSION_GE(2,0)) + static int EvpCipherInitAesCCM(WOLFSSL_EVP_CIPHER_CTX* ctx, + const WOLFSSL_EVP_CIPHER* type, + const byte* key, const byte* iv, int enc) { - WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_init"); - if (ctx) { - XMEMSET(ctx, 0, sizeof(WOLFSSL_EVP_CIPHER_CTX)); - ctx->cipherType = WOLFSSL_EVP_CIPH_TYPE_INIT; /* not yet initialized */ - ctx->keyLen = 0; - ctx->enc = 1; /* start in encrypt mode */ + int ret = WOLFSSL_SUCCESS; + + if (ctx->authIn) { + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + ctx->authInSz = 0; + + ctx->block_size = AES_BLOCK_SIZE; + ctx->authTagSz = AES_BLOCK_SIZE; + if (ctx->ivSz == 0) { + ctx->ivSz = GCM_NONCE_MID_SZ; + } + ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_CCM_MODE | + WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; + if (enc == 0 || enc == 1) { + ctx->enc = enc ? 1 : 0; + } + + #ifdef WOLFSSL_AES_128 + if (ctx->cipherType == AES_128_CCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CCM))) { + WOLFSSL_MSG("EVP_AES_128_CCM"); + ctx->cipherType = AES_128_CCM_TYPE; + ctx->keyLen = AES_128_KEY_SIZE; + } + #endif + #ifdef WOLFSSL_AES_192 + if (ctx->cipherType == AES_192_CCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CCM))) { + WOLFSSL_MSG("EVP_AES_192_CCM"); + ctx->cipherType = AES_192_CCM_TYPE; + ctx->keyLen = AES_192_KEY_SIZE; + } + #endif + #ifdef WOLFSSL_AES_256 + if (ctx->cipherType == AES_256_CCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CCM))) { + WOLFSSL_MSG("EVP_AES_256_CCM"); + ctx->cipherType = AES_256_CCM_TYPE; + ctx->keyLen = AES_256_KEY_SIZE; + } + #endif + + if (ret == WOLFSSL_SUCCESS && key && + wc_AesCcmSetKey(&ctx->cipher.aes, key, ctx->keyLen)) { + WOLFSSL_MSG("wc_AesCcmSetKey() failed"); + ret = WOLFSSL_FAILURE; + } + if (ret == WOLFSSL_SUCCESS && iv && + wc_AesCcmSetNonce(&ctx->cipher.aes, iv, ctx->ivSz)) { + WOLFSSL_MSG("wc_AesCcmSetNonce() failed"); + ret = WOLFSSL_FAILURE; + } + + /* + * OpenSSL clears this flag, which permits subsequent use of + * EVP_CTRL_CCM_IV_GEN, when EVP_CipherInit is called with no key. + * If a key is provided, the flag retains its value. + */ + if (ret == WOLFSSL_SUCCESS && key == NULL) { + ctx->authIvGenEnable = 0; } + + return ret; } - /* This function allows cipher specific parameters to be - determined and set. */ - int wolfSSL_EVP_CIPHER_CTX_ctrl(WOLFSSL_EVP_CIPHER_CTX *ctx, int type, \ - int arg, void *ptr) + static int EvpCipherAesCCM(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, + byte* src, word32 len) { int ret = WOLFSSL_FAILURE; -#if defined(HAVE_AESGCM) || (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) -#ifndef WC_NO_RNG - WC_RNG rng; -#endif -#endif - if (ctx == NULL) - return WOLFSSL_FAILURE; - - (void)arg; - (void)ptr; - - WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_ctrl"); - switch(type) { - case EVP_CTRL_INIT: - wolfSSL_EVP_CIPHER_CTX_init(ctx); - if(ctx) - ret = WOLFSSL_SUCCESS; - break; - case EVP_CTRL_SET_KEY_LENGTH: - ret = wolfSSL_EVP_CIPHER_CTX_set_key_length(ctx, arg); - break; -#if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || \ - (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) - case EVP_CTRL_AEAD_SET_IVLEN: - if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) - break; - #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { - if (arg != CHACHA20_POLY1305_AEAD_IV_SIZE) { - break; - } - } - else - #endif /* HAVE_CHACHA && HAVE_POLY1305 */ - { - if (arg <= 0 || arg > AES_BLOCK_SIZE) - break; - } - ret = wolfSSL_EVP_CIPHER_CTX_set_iv_length(ctx, arg); - break; - -#if defined(HAVE_AESGCM) || (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) - case EVP_CTRL_AEAD_SET_IV_FIXED: - if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) - break; - if (arg == -1) { - /* arg == -1 copies ctx->ivSz from ptr */ - ret = wolfSSL_EVP_CIPHER_CTX_set_iv(ctx, (byte*)ptr, ctx->ivSz); - } -#ifndef WC_NO_RNG - else { - /* - * Fixed field must be at least 4 bytes and invocation - * field at least 8. - */ - if ((arg < 4) || (ctx->ivSz - arg) < 8) { - WOLFSSL_MSG("Fixed field or invocation field too short"); - break; - } - /* arg is 4...(ctx->ivSz - 8) */ - XMEMCPY(ctx->iv, ptr, arg); - if (wc_InitRng(&rng) != 0) { - WOLFSSL_MSG("wc_InitRng failed"); - break; - } - if (wc_RNG_GenerateBlock(&rng, ctx->iv + arg, - ctx->ivSz - arg) == 0) { - ret = WOLFSSL_SUCCESS; - } else { - /* rng is freed immediately after if block so no need - * to do it here - */ - WOLFSSL_MSG("wc_RNG_GenerateBlock failed"); - } - if (wc_FreeRng(&rng) != 0) { - WOLFSSL_MSG("wc_FreeRng failed"); - ret = WOLFSSL_FAILURE; - break; - } - } - #ifdef HAVE_AESGCM - if (ret == WOLFSSL_SUCCESS) { - /* - * OpenSSL requires that a EVP_CTRL_AEAD_SET_IV_FIXED - * command be issued before a EVP_CTRL_GCM_IV_GEN command. - * This flag is used to enforce that. - */ - ctx->authIvGenEnable = 1; - } - #endif -#endif /* !WC_NO_RNG */ - break; -#endif /* HAVE_AESGCM || (HAVE_CHACHA && HAVE_POLY1305) */ -#if defined(HAVE_AESGCM) && !defined(_WIN32) && !defined(HAVE_SELFTEST) && \ - (!defined(HAVE_FIPS) || FIPS_VERSION_GE(2,0)) + /* No destination means only AAD. */ + if (src != NULL && dst == NULL) { + ret = wolfSSL_EVP_CipherUpdate_CCM_AAD(ctx, src, len); + } + else if (src != NULL && dst != NULL) { + if (ctx->enc) { + ret = wc_AesCcmEncrypt(&ctx->cipher.aes, dst, src, + len, ctx->iv, ctx->ivSz, ctx->authTag, + ctx->authTagSz, ctx->authIn, + ctx->authInSz); + } + else { + ret = wc_AesCcmDecrypt(&ctx->cipher.aes, dst, src, + len, ctx->iv, ctx->ivSz, ctx->authTag, + ctx->authTagSz, ctx->authIn, + ctx->authInSz); + } + if (ctx->authIncIv) { + IncCtr((byte*)ctx->cipher.aes.reg, + ctx->cipher.aes.nonceSz); + ctx->authIncIv = 0; + } + } + if (src == NULL) { /* - * Using EVP_CTRL_GCM_IV_GEN is a way to do AES-GCM encrypt/decrypt - * multiple times with EVP_Cipher without having to call - * EVP_CipherInit between each iteration. The IV is incremented for - * each subsequent EVP_Cipher call to prevent IV reuse. + * Clear any leftover AAD on final (final is when src is + * NULL). */ - case EVP_CTRL_GCM_IV_GEN: - if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) - break; - if (!ctx->authIvGenEnable) { - WOLFSSL_MSG("Must use EVP_CTRL_AEAD_SET_IV_FIXED before " - "EVP_CTRL_GCM_IV_GEN"); - break; - } - if (ctx->cipher.aes.keylen == 0 || ctx->ivSz == 0) { - WOLFSSL_MSG("Key or IV not set"); - break; - } - if (ptr == NULL) { - WOLFSSL_MSG("Destination buffer for IV bytes NULL."); - break; - } - if (arg <= 0 || arg > ctx->ivSz) { - XMEMCPY(ptr, ctx->iv, ctx->ivSz); - } - else { - /* - * Copy the last "arg" bytes of ctx->iv into the buffer at - * "ptr." Not sure why OpenSSL does this, but it does. - */ - XMEMCPY(ptr, ctx->iv + ctx->ivSz - arg, arg); - } + if (ctx->authIn != NULL) { + XMEMSET(ctx->authIn, 0, ctx->authInSz); + } + ctx->authInSz = 0; + } + if (ret == 0) { + ret = len; + } - /* - * The gcmIncIV flag indicates that the IV should be incremented - * after the next cipher operation. - */ - ctx->authIncIv = 1; - ret = WOLFSSL_SUCCESS; - break; -#endif /* HAVE_AESGCM && !_WIN32 && !HAVE_SELFTEST && (!HAVE_FIPS || - * FIPS_VERSION >= 2)*/ - case EVP_CTRL_AEAD_SET_TAG: - if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) - break; -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { - if (arg != CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE) { - break; - } - ctx->authTagSz = arg; - ret = WOLFSSL_SUCCESS; - if (ptr != NULL) { - XMEMCPY(ctx->authTag, ptr, arg); - } - break; - } - else -#endif /* HAVE_CHACHA && HAVE_POLY1305 */ - { - if(arg <= 0 || arg > 16 || (ptr == NULL)) - break; + return ret; + } +#endif /* HAVE_AESCCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || + * HAVE_FIPS_VERSION >= 2 */ - XMEMCPY(ctx->authTag, ptr, arg); - ctx->authTagSz = arg; - ret = WOLFSSL_SUCCESS; - break; - } - case EVP_CTRL_AEAD_GET_TAG: - if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) - break; + /* return WOLFSSL_SUCCESS on ok, 0 on failure to match API compatibility */ + int wolfSSL_EVP_CipherInit(WOLFSSL_EVP_CIPHER_CTX* ctx, + const WOLFSSL_EVP_CIPHER* type, const byte* key, + const byte* iv, int enc) + { + int ret = 0; + (void)key; + (void)iv; + (void)enc; -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { - if (arg != CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE) { - break; - } - } - else -#endif /* HAVE_CHACHA && HAVE_POLY1305 */ - { - if (arg <= 0 || arg > AES_BLOCK_SIZE) - break; - } + WOLFSSL_ENTER("wolfSSL_EVP_CipherInit"); + if (ctx == NULL) { + WOLFSSL_MSG("no ctx"); + return WOLFSSL_FAILURE; + } - if (ptr != NULL) { - XMEMCPY(ptr, ctx->authTag, arg); - ret = WOLFSSL_SUCCESS; - } - break; -#endif /* HAVE_AESGCM || HAVE_AESCCM || (HAVE_CHACHA && HAVE_POLY1305) */ - default: - WOLFSSL_MSG("EVP_CIPHER_CTX_ctrl operation not yet handled"); - break; + if (type == NULL && ctx->cipherType == WOLFSSL_EVP_CIPH_TYPE_INIT) { + WOLFSSL_MSG("no type set"); + return WOLFSSL_FAILURE; } - return ret; - } + if (ctx->cipherType == WOLFSSL_EVP_CIPH_TYPE_INIT){ + /* only first EVP_CipherInit invoke. ctx->cipherType is set below */ + XMEMSET(&ctx->cipher, 0, sizeof(ctx->cipher)); + ctx->flags = 0; + } + /* always clear buffer state */ + ctx->bufUsed = 0; + ctx->lastUsed = 0; - /* WOLFSSL_SUCCESS on ok */ - int wolfSSL_EVP_CIPHER_CTX_cleanup(WOLFSSL_EVP_CIPHER_CTX* ctx) - { - WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_cleanup"); - if (ctx) { -#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ - (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) -#if (defined(HAVE_AESGCM) && defined(WOLFSSL_AESGCM_STREAM)) || \ - defined(HAVE_AESCCM) || \ - defined(HAVE_AESCBC) || \ - defined(WOLFSSL_AES_COUNTER) || \ - defined(HAVE_AES_ECB) || \ - defined(HAVE_AES_CFB) || \ - defined(HAVE_AES_OFB) || \ - defined(WOLFSSL_AES_XTS) +#ifdef HAVE_WOLFSSL_EVP_CIPHER_CTX_IV + if (!iv && ctx->ivSz) { + iv = ctx->iv; + } +#endif - switch (ctx->cipherType) { - #if defined(HAVE_AESGCM) && defined(WOLFSSL_AESGCM_STREAM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: - #endif /* HAVE_AESGCM && WOLFSSL_AESGCM_STREAM */ - #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: - #endif /* HAVE_AESCCM */ - #ifdef HAVE_AESCBC - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: - #endif - #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: - #endif - #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: - #endif - #ifdef HAVE_AES_CFB - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: - #endif - #ifdef HAVE_AES_OFB - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: - #endif - #ifdef WOLFSSL_AES_XTS - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: - #endif - wc_AesFree(&ctx->cipher.aes); +#ifndef NO_AES + #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + #ifdef WOLFSSL_AES_128 + if (ctx->cipherType == AES_128_CBC_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CBC))) { + WOLFSSL_MSG("EVP_AES_128_CBC"); + ctx->cipherType = AES_128_CBC_TYPE; + ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; + ctx->keyLen = 16; + ctx->block_size = AES_BLOCK_SIZE; + ctx->ivSz = AES_BLOCK_SIZE; + if (enc == 0 || enc == 1) + ctx->enc = enc ? 1 : 0; + if (key) { + ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, + ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 0); + if (ret != 0) + return WOLFSSL_FAILURE; } - -#endif /* AES */ -#endif /* not FIPS or FIPS v2+ */ - - ctx->cipherType = WOLFSSL_EVP_CIPH_TYPE_INIT; /* not yet initialized */ -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->key) { - ForceZero(ctx->key, ctx->keyLen); - XFREE(ctx->key, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->key = NULL; + if (iv && key == NULL) { + ret = wc_AesSetIV(&ctx->cipher.aes, iv); + if (ret != 0) + return WOLFSSL_FAILURE; } -#endif - ctx->keyLen = 0; -#if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) - if (ctx->authBuffer) { - XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authBuffer = NULL; + } + #endif /* WOLFSSL_AES_128 */ + #ifdef WOLFSSL_AES_192 + if (ctx->cipherType == AES_192_CBC_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CBC))) { + WOLFSSL_MSG("EVP_AES_192_CBC"); + ctx->cipherType = AES_192_CBC_TYPE; + ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; + ctx->keyLen = 24; + ctx->block_size = AES_BLOCK_SIZE; + ctx->ivSz = AES_BLOCK_SIZE; + if (enc == 0 || enc == 1) + ctx->enc = enc ? 1 : 0; + if (key) { + ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, + ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 0); + if (ret != 0) + return WOLFSSL_FAILURE; } - ctx->authBufferLen = 0; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; + if (iv && key == NULL) { + ret = wc_AesSetIV(&ctx->cipher.aes, iv); + if (ret != 0) + return WOLFSSL_FAILURE; } - ctx->authInSz = 0; - ctx->authIvGenEnable = 0; - ctx->authIncIv = 0; -#endif - } - - return WOLFSSL_SUCCESS; - } - - /* Permanent stub for Qt compilation. */ - #if defined(WOLFSSL_QT) && !defined(NO_WOLFSSL_STUB) - const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_rc2_cbc(void) - { - WOLFSSL_ENTER("wolfSSL_EVP_rc2_cbc"); - WOLFSSL_STUB("EVP_rc2_cbc"); - return NULL; - } - #endif - -#if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED) - - int wolfSSL_EVP_BytesToKey(const WOLFSSL_EVP_CIPHER* type, - const WOLFSSL_EVP_MD* md, const byte* salt, - const byte* data, int sz, int count, byte* key, byte* iv) - { - int ret; - int hashType = WC_HASH_TYPE_NONE; - #ifdef WOLFSSL_SMALL_STACK - EncryptedInfo* info; - #else - EncryptedInfo info[1]; - #endif - - #ifdef WOLFSSL_SMALL_STACK - info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL, - DYNAMIC_TYPE_ENCRYPTEDINFO); - if (info == NULL) { - WOLFSSL_MSG("malloc failed"); - return WOLFSSL_FAILURE; } - #endif - - XMEMSET(info, 0, sizeof(EncryptedInfo)); - - ret = wc_EncryptedInfoGet(info, type); - if (ret < 0) - goto end; - - if (data == NULL) { - ret = info->keySz; - goto end; + #endif /* WOLFSSL_AES_192 */ + #ifdef WOLFSSL_AES_256 + if (ctx->cipherType == AES_256_CBC_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CBC))) { + WOLFSSL_MSG("EVP_AES_256_CBC"); + ctx->cipherType = AES_256_CBC_TYPE; + ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; + ctx->keyLen = 32; + ctx->block_size = AES_BLOCK_SIZE; + ctx->ivSz = AES_BLOCK_SIZE; + if (enc == 0 || enc == 1) + ctx->enc = enc ? 1 : 0; + if (key) { + ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, + ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 0); + if (ret != 0){ + WOLFSSL_MSG("AesSetKey() failed"); + return WOLFSSL_FAILURE; + } + } + if (iv && key == NULL) { + ret = wc_AesSetIV(&ctx->cipher.aes, iv); + if (ret != 0){ + WOLFSSL_MSG("wc_AesSetIV() failed"); + return WOLFSSL_FAILURE; + } + } } - - ret = wolfSSL_EVP_get_hashinfo(md, &hashType, NULL); - if (ret == WOLFSSL_FAILURE) - goto end; - - ret = wc_PBKDF1_ex(key, info->keySz, iv, info->ivSz, data, sz, salt, - EVP_SALT_SIZE, count, hashType, NULL); - if (ret == 0) - ret = info->keySz; - - end: - #ifdef WOLFSSL_SMALL_STACK - XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); - #endif - if (ret < 0) - return 0; /* failure - for compatibility */ - - return ret; - } - -#endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */ - - -#ifndef NO_AES -#if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) || \ - defined(WOLFSSL_AES_256) - #define AES_SIZE_ANY -#endif - -#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_COUNTER) || \ - defined(HAVE_AES_ECB) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_DIRECT) - #define AES_SET_KEY -#endif - -#if defined(AES_SIZE_ANY) && defined(AES_SET_KEY) - static int AesSetKey_ex(Aes* aes, const byte* key, word32 len, - const byte* iv, int dir, int direct) - { - int ret; - /* wc_AesSetKey clear aes.reg if iv == NULL. - Keep IV for openSSL compatibility */ - if (iv == NULL) - XMEMCPY((byte *)aes->tmp, (byte *)aes->reg, AES_BLOCK_SIZE); - if (direct) { - #if defined(WOLFSSL_AES_DIRECT) - ret = wc_AesSetKeyDirect(aes, key, len, iv, dir); - #else - ret = NOT_COMPILED_IN; + #endif /* WOLFSSL_AES_256 */ + #endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ + #if defined(HAVE_AESGCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ + || FIPS_VERSION_GE(2,0)) + if (FALSE + #ifdef WOLFSSL_AES_128 + || ctx->cipherType == AES_128_GCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_GCM)) #endif + #ifdef WOLFSSL_AES_192 + || ctx->cipherType == AES_192_GCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_GCM)) + #endif + #ifdef WOLFSSL_AES_256 + || ctx->cipherType == AES_256_GCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_GCM)) + #endif + ) { + if (EvpCipherInitAesGCM(ctx, type, key, iv, enc) + != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } } - else { - ret = wc_AesSetKey(aes, key, len, iv, dir); - } - if (iv == NULL) - XMEMCPY((byte *)aes->reg, (byte *)aes->tmp, AES_BLOCK_SIZE); - return ret; - } -#endif /* AES_ANY_SIZE && AES_SET_KEY */ -#endif /* NO_AES */ - -#if defined(HAVE_AESGCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ - || FIPS_VERSION_GE(2,0)) - static int EvpCipherInitAesGCM(WOLFSSL_EVP_CIPHER_CTX* ctx, - const WOLFSSL_EVP_CIPHER* type, - const byte* key, const byte* iv, int enc) - { - int ret = WOLFSSL_SUCCESS; - - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } - ctx->authInSz = 0; - - ctx->block_size = AES_BLOCK_SIZE; - ctx->authTagSz = AES_BLOCK_SIZE; - if (ctx->ivSz == 0) { - ctx->ivSz = GCM_NONCE_MID_SZ; - } - ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_GCM_MODE | - WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; - if (enc == 0 || enc == 1) { - ctx->enc = enc ? 1 : 0; - } - - #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_GCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_GCM))) { - WOLFSSL_MSG("EVP_AES_128_GCM"); - ctx->cipherType = AES_128_GCM_TYPE; - ctx->keyLen = AES_128_KEY_SIZE; - } - #endif - #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_GCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_GCM))) { - WOLFSSL_MSG("EVP_AES_192_GCM"); - ctx->cipherType = AES_192_GCM_TYPE; - ctx->keyLen = AES_192_KEY_SIZE; - } - #endif - #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_GCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_GCM))) { - WOLFSSL_MSG("EVP_AES_256_GCM"); - ctx->cipherType = AES_256_GCM_TYPE; - ctx->keyLen = AES_256_KEY_SIZE; - } - #endif - - #ifndef WOLFSSL_AESGCM_STREAM - if (ret == WOLFSSL_SUCCESS && key && - wc_AesGcmSetKey(&ctx->cipher.aes, key, ctx->keyLen)) { - WOLFSSL_MSG("wc_AesGcmSetKey() failed"); - ret = WOLFSSL_FAILURE; - } - #endif /* !WOLFSSL_AESGCM_STREAM */ - if (ret == WOLFSSL_SUCCESS && iv && - wc_AesGcmSetExtIV(&ctx->cipher.aes, iv, ctx->ivSz)) { - WOLFSSL_MSG("wc_AesGcmSetExtIV() failed"); - ret = WOLFSSL_FAILURE; - } - #ifdef WOLFSSL_AESGCM_STREAM - /* - * Initialize with key and IV if available. wc_AesGcmInit will fail - * if called with IV only and no key has been set. - */ - if (ret == WOLFSSL_SUCCESS && - (key || (iv && ctx->cipher.aes.gcmKeySet)) && - wc_AesGcmInit(&ctx->cipher.aes, key, - (key == NULL) ? 0 : ctx->keyLen, iv, - (iv == NULL) ? 0 : ctx->ivSz) != 0) { - WOLFSSL_MSG("wc_AesGcmInit() failed"); - ret = WOLFSSL_FAILURE; - } - #endif /* WOLFSSL_AESGCM_STREAM */ - - /* - * OpenSSL clears this flag, which permits subsequent use of - * EVP_CTRL_GCM_IV_GEN, when EVP_CipherInit is called with no key. - * If a key is provided, the flag retains its value. - */ - if (ret == WOLFSSL_SUCCESS && key == NULL) { - ctx->authIvGenEnable = 0; - } - - return ret; - } - - static int EvpCipherAesGCM(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, - byte* src, word32 len) - { - int ret = WOLFSSL_FAILURE; - - #ifndef WOLFSSL_AESGCM_STREAM - /* No destination means only AAD. */ - if (src != NULL && dst == NULL) { - ret = wolfSSL_EVP_CipherUpdate_GCM_AAD(ctx, src, len); - } - else if (src != NULL && dst != NULL) { - if (ctx->enc) { - ret = wc_AesGcmEncrypt(&ctx->cipher.aes, dst, src, - len, ctx->iv, ctx->ivSz, ctx->authTag, - ctx->authTagSz, ctx->authIn, - ctx->authInSz); + #endif /* HAVE_AESGCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || + * HAVE_FIPS_VERSION >= 2 */ + #if defined(HAVE_AESCCM) && \ + ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ + || FIPS_VERSION_GE(2,0)) + if (FALSE + #ifdef WOLFSSL_AES_128 + || ctx->cipherType == AES_128_CCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CCM)) + #endif + #ifdef WOLFSSL_AES_192 + || ctx->cipherType == AES_192_CCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CCM)) + #endif + #ifdef WOLFSSL_AES_256 + || ctx->cipherType == AES_256_CCM_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CCM)) + #endif + ) { + if (EvpCipherInitAesCCM(ctx, type, key, iv, enc) + != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; } - else { - ret = wc_AesGcmDecrypt(&ctx->cipher.aes, dst, src, - len, ctx->iv, ctx->ivSz, ctx->authTag, - ctx->authTagSz, ctx->authIn, - ctx->authInSz); + } + #endif /* HAVE_AESCCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || + * HAVE_FIPS_VERSION >= 2 */ +#ifdef WOLFSSL_AES_COUNTER + #ifdef WOLFSSL_AES_128 + if (ctx->cipherType == AES_128_CTR_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CTR))) { + WOLFSSL_MSG("EVP_AES_128_CTR"); + ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; + ctx->cipherType = AES_128_CTR_TYPE; + ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; + ctx->keyLen = 16; + ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->ivSz = AES_BLOCK_SIZE; +#if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) + ctx->cipher.aes.left = 0; +#endif + if (enc == 0 || enc == 1) + ctx->enc = enc ? 1 : 0; + if (key) { + ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, + AES_ENCRYPTION, 1); + if (ret != 0) + return WOLFSSL_FAILURE; } - if (ctx->authIncIv) { - IncCtr((byte*)ctx->cipher.aes.reg, - ctx->cipher.aes.nonceSz); - ctx->authIncIv = 0; + if (iv && key == NULL) { + ret = wc_AesSetIV(&ctx->cipher.aes, iv); + if (ret != 0) + return WOLFSSL_FAILURE; } } - #else - /* - * No need to call wc_AesGcmInit. Should have been called by - * wolfSSL_EVP_CipherInit. - */ - /* NULL dst and non-NULL src means only AAD. */ - if (src != NULL && dst == NULL) { - if (ctx->enc) { - ret = wc_AesGcmEncryptUpdate(&ctx->cipher.aes, NULL, - NULL, 0, src, len); + #endif /* WOLFSSL_AES_128 */ + #ifdef WOLFSSL_AES_192 + if (ctx->cipherType == AES_192_CTR_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CTR))) { + WOLFSSL_MSG("EVP_AES_192_CTR"); + ctx->cipherType = AES_192_CTR_TYPE; + ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; + ctx->keyLen = 24; + ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->ivSz = AES_BLOCK_SIZE; +#if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) + ctx->cipher.aes.left = 0; +#endif + if (enc == 0 || enc == 1) + ctx->enc = enc ? 1 : 0; + if (key) { + ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, + AES_ENCRYPTION, 1); + if (ret != 0) + return WOLFSSL_FAILURE; } - else { - ret = wc_AesGcmDecryptUpdate(&ctx->cipher.aes, NULL, - NULL, 0, src, len); + if (iv && key == NULL) { + ret = wc_AesSetIV(&ctx->cipher.aes, iv); + if (ret != 0) + return WOLFSSL_FAILURE; } } - /* Only plain/cipher text. */ - else if (src != NULL && dst != NULL) { - if (ctx->enc) { - ret = wc_AesGcmEncryptUpdate(&ctx->cipher.aes, dst, src, - len, NULL, 0); + #endif /* WOLFSSL_AES_192 */ + #ifdef WOLFSSL_AES_256 + if (ctx->cipherType == AES_256_CTR_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CTR))) { + WOLFSSL_MSG("EVP_AES_256_CTR"); + ctx->cipherType = AES_256_CTR_TYPE; + ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; + ctx->keyLen = 32; + ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->ivSz = AES_BLOCK_SIZE; +#if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) + ctx->cipher.aes.left = 0; +#endif + if (enc == 0 || enc == 1) + ctx->enc = enc ? 1 : 0; + if (key) { + ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, + AES_ENCRYPTION, 1); + if (ret != 0) + return WOLFSSL_FAILURE; } - else { - ret = wc_AesGcmDecryptUpdate(&ctx->cipher.aes, dst, src, - len, NULL, 0); + if (iv && key == NULL) { + ret = wc_AesSetIV(&ctx->cipher.aes, iv); + if (ret != 0) + return WOLFSSL_FAILURE; } } - /* - * src == NULL is analogous to other "final"-type functions - * (e.g. EVP_CipherFinal). Calculates tag on encrypt - * and checks tag on decrypt. - */ - else { - if (ctx->enc) { - /* Calculate authentication tag. */ - ret = wc_AesGcmEncryptFinal(&ctx->cipher.aes, - ctx->authTag, ctx->authTagSz); - /* - * wc_AesGcmEncryptFinal increments the IV in - * ctx->cipher.aes.reg, so we don't call IncCtr here. - */ - } - else { - /* Calculate authentication tag and compare. */ - ret = wc_AesGcmDecryptFinal(&ctx->cipher.aes, - ctx->authTag, ctx->authTagSz); - if (ctx->authIncIv) { - IncCtr((byte*)ctx->cipher.aes.reg, - ctx->cipher.aes.nonceSz); - } - } - /* Reinitialize for subsequent wolfSSL_EVP_Cipher calls. */ - if (wc_AesGcmInit(&ctx->cipher.aes, NULL, 0, - (byte*)ctx->cipher.aes.reg, - ctx->ivSz) != 0) { - WOLFSSL_MSG("wc_AesGcmInit failed"); - return WOLFSSL_FATAL_ERROR; - } - ctx->authIncIv = 0; - } - #endif /* WOLFSSL_AESGCM_STREAM */ - if (src == NULL) { - /* - * Clear any leftover AAD on final (final is when src is - * NULL). - */ - if (ctx->authIn != NULL) { - XMEMSET(ctx->authIn, 0, ctx->authInSz); - } - ctx->authInSz = 0; - } - if (ret == 0) { - ret = len; - } - - return ret; - } -#endif /* HAVE_AESGCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || - * HAVE_FIPS_VERSION >= 2 */ - - /* return WOLFSSL_SUCCESS on ok, 0 on failure to match API compatibility */ -#if defined(HAVE_AESCCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ - || FIPS_VERSION_GE(2,0)) - static int EvpCipherInitAesCCM(WOLFSSL_EVP_CIPHER_CTX* ctx, - const WOLFSSL_EVP_CIPHER* type, - const byte* key, const byte* iv, int enc) - { - int ret = WOLFSSL_SUCCESS; - - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } - ctx->authInSz = 0; - - ctx->block_size = AES_BLOCK_SIZE; - ctx->authTagSz = AES_BLOCK_SIZE; - if (ctx->ivSz == 0) { - ctx->ivSz = GCM_NONCE_MID_SZ; - } - ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_CCM_MODE | - WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; - if (enc == 0 || enc == 1) { - ctx->enc = enc ? 1 : 0; - } - - #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CCM))) { - WOLFSSL_MSG("EVP_AES_128_CCM"); - ctx->cipherType = AES_128_CCM_TYPE; - ctx->keyLen = AES_128_KEY_SIZE; - } - #endif - #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CCM))) { - WOLFSSL_MSG("EVP_AES_192_CCM"); - ctx->cipherType = AES_192_CCM_TYPE; - ctx->keyLen = AES_192_KEY_SIZE; - } - #endif - #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CCM))) { - WOLFSSL_MSG("EVP_AES_256_CCM"); - ctx->cipherType = AES_256_CCM_TYPE; - ctx->keyLen = AES_256_KEY_SIZE; - } - #endif - - if (ret == WOLFSSL_SUCCESS && key && - wc_AesCcmSetKey(&ctx->cipher.aes, key, ctx->keyLen)) { - WOLFSSL_MSG("wc_AesCcmSetKey() failed"); - ret = WOLFSSL_FAILURE; - } - if (ret == WOLFSSL_SUCCESS && iv && - wc_AesCcmSetNonce(&ctx->cipher.aes, iv, ctx->ivSz)) { - WOLFSSL_MSG("wc_AesCcmSetNonce() failed"); - ret = WOLFSSL_FAILURE; - } - - /* - * OpenSSL clears this flag, which permits subsequent use of - * EVP_CTRL_CCM_IV_GEN, when EVP_CipherInit is called with no key. - * If a key is provided, the flag retains its value. - */ - if (ret == WOLFSSL_SUCCESS && key == NULL) { - ctx->authIvGenEnable = 0; - } - - return ret; - } - - static int EvpCipherAesCCM(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, - byte* src, word32 len) - { - int ret = WOLFSSL_FAILURE; - - /* No destination means only AAD. */ - if (src != NULL && dst == NULL) { - ret = wolfSSL_EVP_CipherUpdate_CCM_AAD(ctx, src, len); - } - else if (src != NULL && dst != NULL) { - if (ctx->enc) { - ret = wc_AesCcmEncrypt(&ctx->cipher.aes, dst, src, - len, ctx->iv, ctx->ivSz, ctx->authTag, - ctx->authTagSz, ctx->authIn, - ctx->authInSz); - } - else { - ret = wc_AesCcmDecrypt(&ctx->cipher.aes, dst, src, - len, ctx->iv, ctx->ivSz, ctx->authTag, - ctx->authTagSz, ctx->authIn, - ctx->authInSz); - } - if (ctx->authIncIv) { - IncCtr((byte*)ctx->cipher.aes.reg, - ctx->cipher.aes.nonceSz); - ctx->authIncIv = 0; - } - } - if (src == NULL) { - /* - * Clear any leftover AAD on final (final is when src is - * NULL). - */ - if (ctx->authIn != NULL) { - XMEMSET(ctx->authIn, 0, ctx->authInSz); - } - ctx->authInSz = 0; - } - if (ret == 0) { - ret = len; - } - - return ret; - } -#endif /* HAVE_AESCCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || - * HAVE_FIPS_VERSION >= 2 */ - - /* return WOLFSSL_SUCCESS on ok, 0 on failure to match API compatibility */ - int wolfSSL_EVP_CipherInit(WOLFSSL_EVP_CIPHER_CTX* ctx, - const WOLFSSL_EVP_CIPHER* type, const byte* key, - const byte* iv, int enc) - { - int ret = 0; - (void)key; - (void)iv; - (void)enc; - - WOLFSSL_ENTER("wolfSSL_EVP_CipherInit"); - if (ctx == NULL) { - WOLFSSL_MSG("no ctx"); - return WOLFSSL_FAILURE; - } - - if (type == NULL && ctx->cipherType == WOLFSSL_EVP_CIPH_TYPE_INIT) { - WOLFSSL_MSG("no type set"); - return WOLFSSL_FAILURE; - } - if (ctx->cipherType == WOLFSSL_EVP_CIPH_TYPE_INIT){ - /* only first EVP_CipherInit invoke. ctx->cipherType is set below */ - XMEMSET(&ctx->cipher, 0, sizeof(ctx->cipher)); - ctx->flags = 0; - } - /* always clear buffer state */ - ctx->bufUsed = 0; - ctx->lastUsed = 0; - -#ifdef HAVE_WOLFSSL_EVP_CIPHER_CTX_IV - if (!iv && ctx->ivSz) { - iv = ctx->iv; - } -#endif - -#ifndef NO_AES - #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + #endif /* WOLFSSL_AES_256 */ +#endif /* WOLFSSL_AES_COUNTER */ + #ifdef HAVE_AES_ECB #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CBC_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CBC))) { - WOLFSSL_MSG("EVP_AES_128_CBC"); - ctx->cipherType = AES_128_CBC_TYPE; + if (ctx->cipherType == AES_128_ECB_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_ECB))) { + WOLFSSL_MSG("EVP_AES_128_ECB"); + ctx->cipherType = AES_128_ECB_TYPE; ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 16; ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (key) { - ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, - ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 0); - if (ret != 0) - return WOLFSSL_FAILURE; - } - if (iv && key == NULL) { - ret = wc_AesSetIV(&ctx->cipher.aes, iv); - if (ret != 0) - return WOLFSSL_FAILURE; + ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, NULL, + ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 1); } + if (ret != 0) + return WOLFSSL_FAILURE; } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CBC_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CBC))) { - WOLFSSL_MSG("EVP_AES_192_CBC"); - ctx->cipherType = AES_192_CBC_TYPE; + if (ctx->cipherType == AES_192_ECB_TYPE || + (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_ECB))) { + WOLFSSL_MSG("EVP_AES_192_ECB"); + ctx->cipherType = AES_192_ECB_TYPE; ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; + ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 24; ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (key) { - ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, - ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 0); - if (ret != 0) - return WOLFSSL_FAILURE; - } - if (iv && key == NULL) { - ret = wc_AesSetIV(&ctx->cipher.aes, iv); - if (ret != 0) - return WOLFSSL_FAILURE; + ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, NULL, + ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 1); } - } - #endif /* WOLFSSL_AES_192 */ - #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CBC_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CBC))) { - WOLFSSL_MSG("EVP_AES_256_CBC"); - ctx->cipherType = AES_256_CBC_TYPE; - ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; - ctx->keyLen = 32; - ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; - if (enc == 0 || enc == 1) - ctx->enc = enc ? 1 : 0; - if (key) { - ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, - ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 0); - if (ret != 0){ - WOLFSSL_MSG("AesSetKey() failed"); - return WOLFSSL_FAILURE; - } - } - if (iv && key == NULL) { - ret = wc_AesSetIV(&ctx->cipher.aes, iv); - if (ret != 0){ - WOLFSSL_MSG("wc_AesSetIV() failed"); - return WOLFSSL_FAILURE; - } - } - } - #endif /* WOLFSSL_AES_256 */ - #endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ - #if defined(HAVE_AESGCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ - || FIPS_VERSION_GE(2,0)) - if (FALSE - #ifdef WOLFSSL_AES_128 - || ctx->cipherType == AES_128_GCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_GCM)) - #endif - #ifdef WOLFSSL_AES_192 - || ctx->cipherType == AES_192_GCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_GCM)) - #endif - #ifdef WOLFSSL_AES_256 - || ctx->cipherType == AES_256_GCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_GCM)) - #endif - ) { - if (EvpCipherInitAesGCM(ctx, type, key, iv, enc) - != WOLFSSL_SUCCESS) { - return WOLFSSL_FAILURE; - } - } - #endif /* HAVE_AESGCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || - * HAVE_FIPS_VERSION >= 2 */ - #if defined(HAVE_AESCCM) && \ - ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ - || FIPS_VERSION_GE(2,0)) - if (FALSE - #ifdef WOLFSSL_AES_128 - || ctx->cipherType == AES_128_CCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CCM)) - #endif - #ifdef WOLFSSL_AES_192 - || ctx->cipherType == AES_192_CCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CCM)) - #endif - #ifdef WOLFSSL_AES_256 - || ctx->cipherType == AES_256_CCM_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CCM)) - #endif - ) { - if (EvpCipherInitAesCCM(ctx, type, key, iv, enc) - != WOLFSSL_SUCCESS) { - return WOLFSSL_FAILURE; - } - } - #endif /* HAVE_AESCCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || - * HAVE_FIPS_VERSION >= 2 */ -#ifdef WOLFSSL_AES_COUNTER - #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CTR_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CTR))) { - WOLFSSL_MSG("EVP_AES_128_CTR"); - ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->cipherType = AES_128_CTR_TYPE; - ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; - ctx->keyLen = 16; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; -#if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) - ctx->cipher.aes.left = 0; -#endif - if (enc == 0 || enc == 1) - ctx->enc = enc ? 1 : 0; - if (key) { - ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, - AES_ENCRYPTION, 1); - if (ret != 0) - return WOLFSSL_FAILURE; - } - if (iv && key == NULL) { - ret = wc_AesSetIV(&ctx->cipher.aes, iv); - if (ret != 0) - return WOLFSSL_FAILURE; - } - } - #endif /* WOLFSSL_AES_128 */ - #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CTR_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CTR))) { - WOLFSSL_MSG("EVP_AES_192_CTR"); - ctx->cipherType = AES_192_CTR_TYPE; - ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; - ctx->keyLen = 24; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; -#if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) - ctx->cipher.aes.left = 0; -#endif - if (enc == 0 || enc == 1) - ctx->enc = enc ? 1 : 0; - if (key) { - ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, - AES_ENCRYPTION, 1); - if (ret != 0) - return WOLFSSL_FAILURE; - } - if (iv && key == NULL) { - ret = wc_AesSetIV(&ctx->cipher.aes, iv); - if (ret != 0) - return WOLFSSL_FAILURE; - } - } - #endif /* WOLFSSL_AES_192 */ - #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CTR_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CTR))) { - WOLFSSL_MSG("EVP_AES_256_CTR"); - ctx->cipherType = AES_256_CTR_TYPE; - ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; - ctx->keyLen = 32; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; -#if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) - ctx->cipher.aes.left = 0; -#endif - if (enc == 0 || enc == 1) - ctx->enc = enc ? 1 : 0; - if (key) { - ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, iv, - AES_ENCRYPTION, 1); - if (ret != 0) - return WOLFSSL_FAILURE; - } - if (iv && key == NULL) { - ret = wc_AesSetIV(&ctx->cipher.aes, iv); - if (ret != 0) - return WOLFSSL_FAILURE; - } - } - #endif /* WOLFSSL_AES_256 */ -#endif /* WOLFSSL_AES_COUNTER */ - #ifdef HAVE_AES_ECB - #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_ECB_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_ECB))) { - WOLFSSL_MSG("EVP_AES_128_ECB"); - ctx->cipherType = AES_128_ECB_TYPE; - ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; - ctx->keyLen = 16; - ctx->block_size = AES_BLOCK_SIZE; - if (enc == 0 || enc == 1) - ctx->enc = enc ? 1 : 0; - if (key) { - ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, NULL, - ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 1); - } - if (ret != 0) - return WOLFSSL_FAILURE; - } - #endif /* WOLFSSL_AES_128 */ - #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_ECB_TYPE || - (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_ECB))) { - WOLFSSL_MSG("EVP_AES_192_ECB"); - ctx->cipherType = AES_192_ECB_TYPE; - ctx->flags &= ~WOLFSSL_EVP_CIPH_MODE; - ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; - ctx->keyLen = 24; - ctx->block_size = AES_BLOCK_SIZE; - if (enc == 0 || enc == 1) - ctx->enc = enc ? 1 : 0; - if (key) { - ret = AesSetKey_ex(&ctx->cipher.aes, key, ctx->keyLen, NULL, - ctx->enc ? AES_ENCRYPTION : AES_DECRYPTION, 1); - } - if (ret != 0) - return WOLFSSL_FAILURE; + if (ret != 0) + return WOLFSSL_FAILURE; } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 @@ -7791,1700 +7191,2284 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) WOLFSSL_MSG("wolfSSL_EVP_Cipher success"); return ret; } + +static void clearEVPPkeyKeys(WOLFSSL_EVP_PKEY *pkey) +{ + if(pkey == NULL) + return; + WOLFSSL_ENTER("clearEVPPkeyKeys"); +#ifndef NO_RSA + if (pkey->rsa != NULL && pkey->ownRsa == 1) { + wolfSSL_RSA_free(pkey->rsa); + pkey->rsa = NULL; + } + pkey->ownRsa = 0; +#endif +#ifndef NO_DSA + if (pkey->dsa != NULL && pkey->ownDsa == 1) { + wolfSSL_DSA_free(pkey->dsa); + pkey->dsa = NULL; + } + pkey->ownDsa = 0; #endif - /* WOLFSSL_SUCCESS on ok */ - int wolfSSL_EVP_DigestInit(WOLFSSL_EVP_MD_CTX* ctx, - const WOLFSSL_EVP_MD* md) - { - int ret = WOLFSSL_SUCCESS; +#ifndef NO_DH + if (pkey->dh != NULL && pkey->ownDh == 1) { + wolfSSL_DH_free(pkey->dh); + pkey->dh = NULL; + } + pkey->ownDh = 0; +#endif +#ifdef HAVE_ECC + if (pkey->ecc != NULL && pkey->ownEcc == 1) { + wolfSSL_EC_KEY_free(pkey->ecc); + pkey->ecc = NULL; + } + pkey->ownEcc = 0; +#endif +} - WOLFSSL_ENTER("EVP_DigestInit"); +#ifndef NO_RSA +#if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) +static int PopulateRSAEvpPkeyDer(WOLFSSL_EVP_PKEY *pkey) +{ + int ret = 0; + int derSz = 0; + word32 pkcs8Sz = 0; + byte* derBuf = NULL; + RsaKey* rsa = NULL; + WOLFSSL_RSA *key = NULL; - if (ctx == NULL) { - return BAD_FUNC_ARG; - } + if (pkey == NULL || pkey->rsa == NULL || pkey->rsa->internal == NULL) { + WOLFSSL_MSG("bad parameter"); + return WOLFSSL_FAILURE; + } + key = pkey->rsa; + rsa = (RsaKey*)pkey->rsa->internal; - #ifdef WOLFSSL_ASYNC_CRYPT - /* compile-time validation of ASYNC_CTX_SIZE */ - typedef char async_test[WC_ASYNC_DEV_SIZE >= sizeof(WC_ASYNC_DEV) ? - 1 : -1]; - (void)sizeof(async_test); - #endif + /* Get DER size */ + if (rsa->type == RSA_PRIVATE) { + ret = wc_RsaKeyToDer(rsa, NULL, 0); + if (ret > 0) { + derSz = ret; + #ifdef HAVE_PKCS8 + if (key->pkcs8HeaderSz) { + ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, NULL, derSz, + RSAk, NULL, 0); + if (ret == LENGTH_ONLY_E) + ret = 0; + } + #endif + } + } + else { + ret = wc_RsaKeyToPublicDer(rsa, NULL, 0); + if (ret > 0) + derSz = ret; + } - /* Set to 0 if no match */ - ctx->macType = EvpMd2MacType(md); - if (md == NULL) { - XMEMSET(&ctx->hash.digest, 0, sizeof(WOLFSSL_Hasher)); - } else - #ifndef NO_SHA - if ((XSTRCMP(md, "SHA") == 0) || (XSTRCMP(md, "SHA1") == 0)) { - ret = wolfSSL_SHA_Init(&(ctx->hash.digest.sha)); - } else - #endif - #ifndef NO_SHA256 - if (XSTRCMP(md, "SHA256") == 0) { - ret = wolfSSL_SHA256_Init(&(ctx->hash.digest.sha256)); - } else - #endif - #ifdef WOLFSSL_SHA224 - if (XSTRCMP(md, "SHA224") == 0) { - ret = wolfSSL_SHA224_Init(&(ctx->hash.digest.sha224)); - } else - #endif - #ifdef WOLFSSL_SHA384 - if (XSTRCMP(md, "SHA384") == 0) { - ret = wolfSSL_SHA384_Init(&(ctx->hash.digest.sha384)); - } else - #endif - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - if (XSTRCMP(md, "SHA512_224") == 0) { - ret = wolfSSL_SHA512_224_Init(&(ctx->hash.digest.sha512)); - } else - #endif - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - if (XSTRCMP(md, "SHA512_256") == 0) { - ret = wolfSSL_SHA512_256_Init(&(ctx->hash.digest.sha512)); - } else - #endif - #ifdef WOLFSSL_SHA512 - if (XSTRCMP(md, "SHA512") == 0) { - ret = wolfSSL_SHA512_Init(&(ctx->hash.digest.sha512)); - } else - #endif - #ifndef NO_MD4 - if (XSTRCMP(md, "MD4") == 0) { - wolfSSL_MD4_Init(&(ctx->hash.digest.md4)); - } else - #endif - #ifndef NO_MD5 - if (XSTRCMP(md, "MD5") == 0) { - ret = wolfSSL_MD5_Init(&(ctx->hash.digest.md5)); - } else - #endif -#ifdef WOLFSSL_SHA3 - #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(md, "SHA3_224") == 0) { - ret = wolfSSL_SHA3_224_Init(&(ctx->hash.digest.sha3_224)); - } else - #endif - #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(md, "SHA3_256") == 0) { - ret = wolfSSL_SHA3_256_Init(&(ctx->hash.digest.sha3_256)); - } else - #endif - #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(md, "SHA3_384") == 0) { - ret = wolfSSL_SHA3_384_Init(&(ctx->hash.digest.sha3_384)); - } else - #endif - #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(md, "SHA3_512") == 0) { - ret = wolfSSL_SHA3_512_Init(&(ctx->hash.digest.sha3_512)); - } else - #endif + if (derSz == 0 || ret < 0) { + WOLFSSL_MSG("Error getting RSA DER size"); + return WOLFSSL_FAILURE; + } + +#ifdef WOLFSSL_NO_REALLOC + derBuf = (byte*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_DER); + if (derBuf != NULL) { + XMEMCPY(derBuf, pkey->pkey.ptr, pkey->pkey_sz); + XFREE(pkey->pkey.ptr, pkey->heap, DYNAMIC_TYPE_DER); + pkey->pkey.ptr = NULL; + } +#else + derBuf = (byte*)XREALLOC(pkey->pkey.ptr, derSz, + pkey->heap, DYNAMIC_TYPE_DER); #endif - { - ctx->macType = WC_HASH_TYPE_NONE; - return BAD_FUNC_ARG; + if (derBuf == NULL) { + WOLFSSL_MSG("PopulateRSAEvpPkeyDer malloc failed"); + return WOLFSSL_FAILURE; + } + + /* Old pointer is invalid from this point on */ + pkey->pkey.ptr = (char*)derBuf; + + if (rsa->type == RSA_PRIVATE) { + ret = wc_RsaKeyToDer(rsa, derBuf, derSz); + if (ret > 0) { + derSz = ret; + #ifdef HAVE_PKCS8 + if (key->pkcs8HeaderSz) { + byte* keyBuf = derBuf; + int keySz = derSz; + derSz = pkcs8Sz; + /* Need new buffer for PKCS8 since we can't + * do this in-place */ + derBuf = (byte*)XMALLOC(pkcs8Sz, pkey->heap, + DYNAMIC_TYPE_DER); + if (derBuf != NULL) { + ret = wc_CreatePKCS8Key(derBuf, (word32*)&derSz, keyBuf, + keySz, RSAk, NULL, 0); + XFREE(keyBuf, pkey->heap, DYNAMIC_TYPE_DER); + pkey->pkey.ptr = (char*)derBuf; + } + else + ret = MEMORY_E; + } + #endif } + } + else { + /* Public key to DER */ + ret = wc_RsaKeyToPublicDer(rsa, derBuf, derSz); + if (ret > 0) + derSz = ret; + } - return ret; + if (ret < 0) { + WOLFSSL_MSG("PopulateRSAEvpPkeyDer failed"); + return WOLFSSL_FAILURE; + } + else { + pkey->pkey_sz = derSz; + return WOLFSSL_SUCCESS; } +} +#endif - /* WOLFSSL_SUCCESS on ok, WOLFSSL_FAILURE on failure */ - int wolfSSL_EVP_DigestUpdate(WOLFSSL_EVP_MD_CTX* ctx, const void* data, - size_t sz) - { - int ret = WOLFSSL_FAILURE; - enum wc_HashType macType; +WOLFSSL_RSA* wolfSSL_EVP_PKEY_get0_RSA(WOLFSSL_EVP_PKEY *pkey) +{ + WOLFSSL_MSG("wolfSSL_EVP_PKEY_get0_RSA"); - WOLFSSL_ENTER("EVP_DigestUpdate"); + if (pkey == NULL) + return NULL; - macType = EvpMd2MacType(EVP_MD_CTX_md(ctx)); - switch (macType) { - case WC_HASH_TYPE_MD4: - #ifndef NO_MD4 - wolfSSL_MD4_Update((MD4_CTX*)&ctx->hash, data, - (unsigned long)sz); - ret = WOLFSSL_SUCCESS; - #endif - break; - case WC_HASH_TYPE_MD5: - #ifndef NO_MD5 - ret = wolfSSL_MD5_Update((MD5_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - case WC_HASH_TYPE_SHA: - #ifndef NO_SHA - ret = wolfSSL_SHA_Update((SHA_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - case WC_HASH_TYPE_SHA224: - #ifdef WOLFSSL_SHA224 - ret = wolfSSL_SHA224_Update((SHA224_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - case WC_HASH_TYPE_SHA256: - #ifndef NO_SHA256 - ret = wolfSSL_SHA256_Update((SHA256_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif /* !NO_SHA256 */ - break; - case WC_HASH_TYPE_SHA384: - #ifdef WOLFSSL_SHA384 - ret = wolfSSL_SHA384_Update((SHA384_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - case WC_HASH_TYPE_SHA512: - #ifdef WOLFSSL_SHA512 - ret = wolfSSL_SHA512_Update((SHA512_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif /* WOLFSSL_SHA512 */ - break; + return pkey->rsa; +} - #ifndef WOLFSSL_NOSHA512_224 - case WC_HASH_TYPE_SHA512_224: - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_224_Update((SHA512_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - #endif /* !WOLFSSL_NOSHA512_224 */ +WOLFSSL_RSA* wolfSSL_EVP_PKEY_get1_RSA(WOLFSSL_EVP_PKEY* pkey) +{ + WOLFSSL_MSG("wolfSSL_EVP_PKEY_get1_RSA"); - #ifndef WOLFSSL_NOSHA512_256 - case WC_HASH_TYPE_SHA512_256: - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_256_Update((SHA512_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif /* WOLFSSL_SHA512 */ - break; - #endif /* !WOLFSSL_NOSHA512_256 */ + if (pkey == NULL || pkey->rsa == NULL) + return NULL; - case WC_HASH_TYPE_SHA3_224: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wolfSSL_SHA3_224_Update((SHA3_224_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - case WC_HASH_TYPE_SHA3_256: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wolfSSL_SHA3_256_Update((SHA3_256_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - case WC_HASH_TYPE_SHA3_384: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wolfSSL_SHA3_384_Update((SHA3_384_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - case WC_HASH_TYPE_SHA3_512: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wolfSSL_SHA3_512_Update((SHA3_512_CTX*)&ctx->hash, data, - (unsigned long)sz); - #endif - break; - case WC_HASH_TYPE_NONE: - case WC_HASH_TYPE_MD2: - case WC_HASH_TYPE_MD5_SHA: - case WC_HASH_TYPE_BLAKE2B: - case WC_HASH_TYPE_BLAKE2S: - #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) - case WC_HASH_TYPE_SHAKE128: - #endif - #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) - case WC_HASH_TYPE_SHAKE256: - #endif - default: - return WOLFSSL_FAILURE; + if (wolfSSL_RSA_up_ref(pkey->rsa) != WOLFSSL_SUCCESS) + return NULL; + + return pkey->rsa; +} + +/* with set1 functions the pkey struct does not own the RSA structure + * + * returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure + */ +int wolfSSL_EVP_PKEY_set1_RSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_RSA *key) +{ + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_set1_RSA"); + if (pkey == NULL || key == NULL) + return WOLFSSL_FAILURE; + + if (wolfSSL_RSA_up_ref(key) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_RSA_up_ref failed"); + return WOLFSSL_FAILURE; + } + + clearEVPPkeyKeys(pkey); + pkey->rsa = key; + pkey->ownRsa = 1; /* pkey does not own RSA but needs to call free on it */ + pkey->type = EVP_PKEY_RSA; + pkey->pkcs8HeaderSz = key->pkcs8HeaderSz; + if (key->inSet == 0) { + if (SetRsaInternal(key) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("SetRsaInternal failed"); + return WOLFSSL_FAILURE; + } + } + +#if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) + if (PopulateRSAEvpPkeyDer(pkey) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("PopulateRSAEvpPkeyDer failed"); + return WOLFSSL_FAILURE; + } +#endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */ + +#ifdef WC_RSA_BLINDING + if (key->ownRng == 0) { + if (wc_RsaSetRNG((RsaKey*)pkey->rsa->internal, &pkey->rng) != 0) { + WOLFSSL_MSG("Error setting RSA rng"); + return WOLFSSL_FAILURE; + } + } +#endif + return WOLFSSL_SUCCESS; +} +#endif /* !NO_RSA */ + +#if !defined (NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN) +/* with set1 functions the pkey struct does not own the DSA structure + * + * returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure + */ +int wolfSSL_EVP_PKEY_set1_DSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DSA *key) +{ + int derMax = 0; + int derSz = 0; + DsaKey* dsa = NULL; + byte* derBuf = NULL; + + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_set1_DSA"); + + if((pkey == NULL) || (key == NULL))return WOLFSSL_FAILURE; + clearEVPPkeyKeys(pkey); + pkey->dsa = key; + pkey->ownDsa = 0; /* pkey does not own DSA */ + pkey->type = EVP_PKEY_DSA; + if (key->inSet == 0) { + if (SetDsaInternal(key) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("SetDsaInternal failed"); + return WOLFSSL_FAILURE; + } + } + dsa = (DsaKey*)key->internal; + + /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */ + derMax = 4 * wolfSSL_BN_num_bytes(key->g) + AES_BLOCK_SIZE; + + derBuf = (byte*)XMALLOC(derMax, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (derBuf == NULL) { + WOLFSSL_MSG("malloc failed"); + return WOLFSSL_FAILURE; + } + + if (dsa->type == DSA_PRIVATE) { + /* Private key to DER */ + derSz = wc_DsaKeyToDer(dsa, derBuf, derMax); + } + else { + /* Public key to DER */ + derSz = wc_DsaKeyToPublicDer(dsa, derBuf, derMax); + } + + if (derSz < 0) { + if (dsa->type == DSA_PRIVATE) { + WOLFSSL_MSG("wc_DsaKeyToDer failed"); + } + else { + WOLFSSL_MSG("wc_DsaKeyToPublicDer failed"); + } + XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); + return WOLFSSL_FAILURE; + } + + pkey->pkey.ptr = (char*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_DER); + if (pkey->pkey.ptr == NULL) { + WOLFSSL_MSG("key malloc failed"); + XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); + return WOLFSSL_FAILURE; + } + pkey->pkey_sz = derSz; + XMEMCPY(pkey->pkey.ptr, derBuf, derSz); + XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); + + return WOLFSSL_SUCCESS; +} + +WOLFSSL_DSA* wolfSSL_EVP_PKEY_get0_DSA(struct WOLFSSL_EVP_PKEY *pkey) +{ + if (!pkey) { + return NULL; + } + return pkey->dsa; +} + +WOLFSSL_DSA* wolfSSL_EVP_PKEY_get1_DSA(WOLFSSL_EVP_PKEY* key) +{ + WOLFSSL_DSA* local; + + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get1_DSA"); + + if (key == NULL) { + WOLFSSL_MSG("Bad function argument"); + return NULL; + } + + local = wolfSSL_DSA_new(); + if (local == NULL) { + WOLFSSL_MSG("Error creating a new WOLFSSL_DSA structure"); + return NULL; + } + + if (key->type == EVP_PKEY_DSA) { + if (wolfSSL_DSA_LoadDer(local, (const unsigned char*)key->pkey.ptr, + key->pkey_sz) != SSL_SUCCESS) { + /* now try public key */ + if (wolfSSL_DSA_LoadDer_ex(local, + (const unsigned char*)key->pkey.ptr, key->pkey_sz, + WOLFSSL_DSA_LOAD_PUBLIC) != SSL_SUCCESS) { + wolfSSL_DSA_free(local); + local = NULL; + } + } + } + else { + WOLFSSL_MSG("WOLFSSL_EVP_PKEY does not hold a DSA key"); + wolfSSL_DSA_free(local); + local = NULL; + } + return local; +} +#endif /* !NO_DSA && !HAVE_SELFTEST && WOLFSSL_KEY_GEN */ + +#ifdef HAVE_ECC +WOLFSSL_EC_KEY *wolfSSL_EVP_PKEY_get0_EC_KEY(WOLFSSL_EVP_PKEY *pkey) +{ + WOLFSSL_EC_KEY *eckey = NULL; + if (pkey && pkey->type == EVP_PKEY_EC) { +#ifdef HAVE_ECC + eckey = pkey->ecc; +#endif + } + return eckey; +} + +WOLFSSL_EC_KEY* wolfSSL_EVP_PKEY_get1_EC_KEY(WOLFSSL_EVP_PKEY* key) +{ + WOLFSSL_EC_KEY* local = NULL; + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get1_EC_KEY"); + + if (key == NULL || key->type != EVP_PKEY_EC) { + return NULL; + } + if (key->type == EVP_PKEY_EC) { + if (key->ecc != NULL) { + if (wolfSSL_EC_KEY_up_ref(key->ecc) != WOLFSSL_SUCCESS) { + return NULL; + } + local = key->ecc; + } + else { + key->ecc = local = wolfSSL_EC_KEY_new(); + if (local == NULL) { + WOLFSSL_MSG("Error creating a new WOLFSSL_EC_KEY structure"); + return NULL; + } + if (wolfSSL_EC_KEY_LoadDer(local, + (const unsigned char*)key->pkey.ptr, + key->pkey_sz) != WOLFSSL_SUCCESS) { + /* now try public key */ + if (wolfSSL_EC_KEY_LoadDer_ex(local, + (const unsigned char*)key->pkey.ptr, key->pkey_sz, + WOLFSSL_EC_KEY_LOAD_PUBLIC) != WOLFSSL_SUCCESS) { + + wolfSSL_EC_KEY_free(local); + local = NULL; + } + } + } + } + else { + WOLFSSL_MSG("WOLFSSL_EVP_PKEY does not hold an EC key"); + } + + return local; +} +#endif /* HAVE_ECC */ + +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || defined(WOLFSSL_OPENSSH) +#if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM) +/* with set1 functions the pkey struct does not own the DH structure + * Build the following DH Key format from the passed in WOLFSSL_DH + * then store in WOLFSSL_EVP_PKEY in DER format. + * + * returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure + */ +int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) +{ + byte havePublic = 0, havePrivate = 0; + int ret; + word32 derSz = 0; + byte* derBuf = NULL; + DhKey* dhkey = NULL; + + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_set1_DH"); + + if (pkey == NULL || key == NULL) + return WOLFSSL_FAILURE; + + clearEVPPkeyKeys(pkey); + + if (wolfSSL_DH_up_ref(key) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Failed to increase dh key ref count"); + return WOLFSSL_FAILURE; + } + + pkey->dh = key; + pkey->ownDh = 1; /* pkey does not own DH but needs to call free on it */ + pkey->type = EVP_PKEY_DH; + if (key->inSet == 0) { + if (SetDhInternal(key) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("SetDhInternal failed"); + return WOLFSSL_FAILURE; + } + } + + dhkey = (DhKey*)key->internal; + + havePublic = mp_unsigned_bin_size(&dhkey->pub) > 0; + havePrivate = mp_unsigned_bin_size(&dhkey->priv) > 0; + + /* Get size of DER buffer only */ + if (havePublic && !havePrivate) { + ret = wc_DhPubKeyToDer(dhkey, NULL, &derSz); + } else if (havePrivate && !havePublic) { + ret = wc_DhPrivKeyToDer(dhkey, NULL, &derSz); + } else { + ret = wc_DhParamsToDer(dhkey,NULL,&derSz); + } + + if (derSz == 0 || ret != LENGTH_ONLY_E) { + WOLFSSL_MSG("Failed to get size of DH Key"); + return WOLFSSL_FAILURE; + } + + derBuf = (byte*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (derBuf == NULL) { + WOLFSSL_MSG("malloc failed"); + return WOLFSSL_FAILURE; + } + + /* Fill DER buffer */ + if (havePublic && !havePrivate) { + ret = wc_DhPubKeyToDer(dhkey, derBuf, &derSz); + } else if (havePrivate && !havePublic) { + ret = wc_DhPrivKeyToDer(dhkey, derBuf, &derSz); + } else { + ret = wc_DhParamsToDer(dhkey,derBuf,&derSz); + } + + if (ret <= 0) { + WOLFSSL_MSG("Failed to export DH Key"); + XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); + return WOLFSSL_FAILURE; + } + + /* Store DH key into pkey (DER format) */ + pkey->pkey.ptr = (char*)derBuf; + pkey->pkey_sz = derSz; + + return WOLFSSL_SUCCESS; +} + +WOLFSSL_DH* wolfSSL_EVP_PKEY_get0_DH(WOLFSSL_EVP_PKEY* key) +{ + if (!key) { + return NULL; + } + return key->dh; +} + +WOLFSSL_DH* wolfSSL_EVP_PKEY_get1_DH(WOLFSSL_EVP_PKEY* key) +{ + WOLFSSL_DH* local = NULL; + + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get1_DH"); + + if (key == NULL || key->dh == NULL) { + WOLFSSL_MSG("Bad function argument"); + return NULL; + } + + if (key->type == EVP_PKEY_DH) { + /* if key->dh already exists copy instead of re-importing from DER */ + if (key->dh != NULL) { + if (wolfSSL_DH_up_ref(key->dh) != WOLFSSL_SUCCESS) { + return NULL; + } + local = key->dh; + } + else { +#if !defined(NO_DH) && (!defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION>2))) + local = wolfSSL_DH_new(); + if (local == NULL) { + WOLFSSL_MSG("Error creating a new WOLFSSL_DH structure"); + return NULL; + } + if (wolfSSL_DH_LoadDer(local, (const unsigned char*)key->pkey.ptr, + key->pkey_sz) != SSL_SUCCESS) { + wolfSSL_DH_free(local); + WOLFSSL_MSG("Error wolfSSL_DH_LoadDer"); + local = NULL; + } +#else + WOLFSSL_MSG("EVP_PKEY does not hold DH struct"); + return NULL; +#endif } + } + else { + WOLFSSL_MSG("WOLFSSL_EVP_PKEY does not hold a DH key"); + wolfSSL_DH_free(local); + return NULL; + } - return ret; + return local; +} +#endif /* NO_DH && WOLFSSL_DH_EXTRA && NO_FILESYSTEM */ + +int wolfSSL_EVP_PKEY_assign(WOLFSSL_EVP_PKEY *pkey, int type, void *key) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_assign"); + + /* pkey and key checked if NULL in subsequent assign functions */ + switch(type) { + #ifndef NO_RSA + case EVP_PKEY_RSA: + ret = wolfSSL_EVP_PKEY_assign_RSA(pkey, (WOLFSSL_RSA*)key); + break; + #endif + #ifndef NO_DSA + case EVP_PKEY_DSA: + ret = wolfSSL_EVP_PKEY_assign_DSA(pkey, (WOLFSSL_DSA*)key); + break; + #endif + #ifdef HAVE_ECC + case EVP_PKEY_EC: + ret = wolfSSL_EVP_PKEY_assign_EC_KEY(pkey, (WOLFSSL_EC_KEY*)key); + break; + #endif + #ifndef NO_DH + case EVP_PKEY_DH: + ret = wolfSSL_EVP_PKEY_assign_DH(pkey, (WOLFSSL_DH*)key); + break; + #endif + default: + WOLFSSL_MSG("Unknown EVP_PKEY type in wolfSSL_EVP_PKEY_assign."); + ret = WOLFSSL_FAILURE; } - /* WOLFSSL_SUCCESS on ok */ - int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, - unsigned int* s) - { - int ret = WOLFSSL_FAILURE; - enum wc_HashType macType; + return ret; +} +#endif /* WOLFSSL_QT || OPENSSL_ALL */ - WOLFSSL_ENTER("EVP_DigestFinal"); - macType = EvpMd2MacType(EVP_MD_CTX_md(ctx)); - switch (macType) { - case WC_HASH_TYPE_MD4: - #ifndef NO_MD4 - wolfSSL_MD4_Final(md, (MD4_CTX*)&ctx->hash); - if (s) *s = MD4_DIGEST_SIZE; - ret = WOLFSSL_SUCCESS; - #endif - break; - case WC_HASH_TYPE_MD5: - #ifndef NO_MD5 - ret = wolfSSL_MD5_Final(md, (MD5_CTX*)&ctx->hash); - if (s) *s = WC_MD5_DIGEST_SIZE; - #endif - break; - case WC_HASH_TYPE_SHA: - #ifndef NO_SHA - ret = wolfSSL_SHA_Final(md, (SHA_CTX*)&ctx->hash); - if (s) *s = WC_SHA_DIGEST_SIZE; - #endif - break; - case WC_HASH_TYPE_SHA224: - #ifdef WOLFSSL_SHA224 - ret = wolfSSL_SHA224_Final(md, (SHA224_CTX*)&ctx->hash); - if (s) *s = WC_SHA224_DIGEST_SIZE; - #endif - break; - case WC_HASH_TYPE_SHA256: - #ifndef NO_SHA256 - ret = wolfSSL_SHA256_Final(md, (SHA256_CTX*)&ctx->hash); - if (s) *s = WC_SHA256_DIGEST_SIZE; - #endif /* !NO_SHA256 */ - break; - case WC_HASH_TYPE_SHA384: - #ifdef WOLFSSL_SHA384 - ret = wolfSSL_SHA384_Final(md, (SHA384_CTX*)&ctx->hash); - if (s) *s = WC_SHA384_DIGEST_SIZE; - #endif - break; - case WC_HASH_TYPE_SHA512: - #ifdef WOLFSSL_SHA512 - ret = wolfSSL_SHA512_Final(md, (SHA512_CTX*)&ctx->hash); - if (s) *s = WC_SHA512_DIGEST_SIZE; - #endif /* WOLFSSL_SHA512 */ - break; - #ifndef WOLFSSL_NOSHA512_224 - case WC_HASH_TYPE_SHA512_224: - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_224_Final(md, (SHA512_CTX*)&ctx->hash); - if (s) *s = WC_SHA512_224_DIGEST_SIZE; - #endif - break; - #endif /* !WOLFSSL_NOSHA512_224 */ - #ifndef WOLFSSL_NOSHA512_256 - case WC_HASH_TYPE_SHA512_256: - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_256_Final(md, (SHA512_CTX*)&ctx->hash); - if (s) *s = WC_SHA512_256_DIGEST_SIZE; - #endif - break; - #endif /* !WOLFSSL_NOSHA512_256 */ - case WC_HASH_TYPE_SHA3_224: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wolfSSL_SHA3_224_Final(md, (SHA3_224_CTX*)&ctx->hash); - if (s) *s = WC_SHA3_224_DIGEST_SIZE; - #endif - break; - case WC_HASH_TYPE_SHA3_256: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wolfSSL_SHA3_256_Final(md, (SHA3_256_CTX*)&ctx->hash); - if (s) *s = WC_SHA3_256_DIGEST_SIZE; - #endif - break; - case WC_HASH_TYPE_SHA3_384: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wolfSSL_SHA3_384_Final(md, (SHA3_384_CTX*)&ctx->hash); - if (s) *s = WC_SHA3_384_DIGEST_SIZE; - #endif - break; - case WC_HASH_TYPE_SHA3_512: - #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wolfSSL_SHA3_512_Final(md, (SHA3_512_CTX*)&ctx->hash); - if (s) *s = WC_SHA3_512_DIGEST_SIZE; - #endif - break; - case WC_HASH_TYPE_NONE: - case WC_HASH_TYPE_MD2: - case WC_HASH_TYPE_MD5_SHA: - case WC_HASH_TYPE_BLAKE2B: - case WC_HASH_TYPE_BLAKE2S: - #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) - case WC_HASH_TYPE_SHAKE128: - #endif - #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) - case WC_HASH_TYPE_SHAKE256: - #endif - default: - return WOLFSSL_FAILURE; +#if defined(HAVE_ECC) +/* try and populate public pkey_sz and pkey.ptr */ +static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) +{ + int derSz = 0; + byte* derBuf = NULL; + ecc_key* ecc; + + if (pkey == NULL || key == NULL || key->internal == NULL) + return WOLFSSL_FAILURE; + + ecc = (ecc_key*)key->internal; + if (ecc->type == ECC_PRIVATEKEY || ecc->type == ECC_PRIVATEKEY_ONLY) { +#ifdef HAVE_PKCS8 + if (key->pkcs8HeaderSz) { + /* when key has pkcs8 header the pkey should too */ + if (wc_EccKeyToPKCS8(ecc, NULL, (word32*)&derSz) == LENGTH_ONLY_E) { + derBuf = (byte*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); + if (derBuf) { + if (wc_EccKeyToPKCS8(ecc, derBuf, (word32*)&derSz) >= 0) { + if (pkey->pkey.ptr) { + XFREE(pkey->pkey.ptr, pkey->heap, DYNAMIC_TYPE_OPENSSL); + } + pkey->pkey_sz = (int)derSz; + pkey->pkey.ptr = (char*)derBuf; + pkey->pkcs8HeaderSz = key->pkcs8HeaderSz; + return WOLFSSL_SUCCESS; + } + else { + XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_OPENSSL); + derBuf = NULL; + } + } + } + } + else +#endif /* HAVE_PKCS8 */ + { + if (ecc->type == ECC_PRIVATEKEY_ONLY) { + if (wc_ecc_make_pub(ecc, NULL) != MP_OKAY) { + return WOLFSSL_FAILURE; + } + } + + /* if not, the pkey will be traditional ecc key */ + if ((derSz = wc_EccKeyDerSize(ecc, 1)) > 0) { + derBuf = (byte*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); + if (derBuf) { + if (wc_EccKeyToDer(ecc, derBuf, derSz) >= 0) { + if (pkey->pkey.ptr) { + XFREE(pkey->pkey.ptr, pkey->heap, DYNAMIC_TYPE_OPENSSL); + } + pkey->pkey_sz = (int)derSz; + pkey->pkey.ptr = (char*)derBuf; + return WOLFSSL_SUCCESS; + } + else { + XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_OPENSSL); + derBuf = NULL; + } + } + } + } + } + else if (ecc->type == ECC_PUBLICKEY) { + if ((derSz = (word32)wc_EccPublicKeyDerSize(ecc, 1)) > 0) { + derBuf = (byte*)XREALLOC(pkey->pkey.ptr, derSz, NULL, + DYNAMIC_TYPE_OPENSSL); + if (derBuf != NULL) { + pkey->pkey.ptr = (char*)derBuf; + if ((derSz = wc_EccPublicKeyToDer(ecc, derBuf, derSz, 1)) < 0) { + XFREE(derBuf, NULL, DYNAMIC_TYPE_OPENSSL); + derBuf = NULL; + } + } } + } + if (derBuf != NULL) { + pkey->pkey_sz = (int)derSz; + return WOLFSSL_SUCCESS; + } + else { + return WOLFSSL_FAILURE; + } +} - return ret; +int wolfSSL_EVP_PKEY_set1_EC_KEY(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_EC_KEY *key) +{ +#ifdef HAVE_ECC + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_set1_EC_KEY"); + if (pkey == NULL || key == NULL) + return WOLFSSL_FAILURE; + clearEVPPkeyKeys(pkey); + if (wolfSSL_EC_KEY_up_ref(key) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_EC_KEY_up_ref failed"); + return WOLFSSL_FAILURE; } + pkey->ecc = key; + pkey->ownEcc = 1; /* pkey needs to call free on key */ + pkey->type = EVP_PKEY_EC; + return ECC_populate_EVP_PKEY(pkey, key); +#else + (void)pkey; + (void)key; + return WOLFSSL_FAILURE; +#endif /* HAVE_ECC */ +} - /* WOLFSSL_SUCCESS on ok */ - int wolfSSL_EVP_DigestFinal_ex(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, - unsigned int* s) - { - WOLFSSL_ENTER("EVP_DigestFinal_ex"); - return EVP_DigestFinal(ctx, md, s); +void* wolfSSL_EVP_X_STATE(const WOLFSSL_EVP_CIPHER_CTX* ctx) +{ + WOLFSSL_MSG("wolfSSL_EVP_X_STATE"); + + if (ctx) { + switch (ctx->cipherType) { + case ARC4_TYPE: + WOLFSSL_MSG("returning arc4 state"); + return (void*)&ctx->cipher.arc4.x; + + default: + WOLFSSL_MSG("bad x state type"); + return 0; + } } - void wolfSSL_EVP_cleanup(void) - { - /* nothing to do here */ + return NULL; +} +int wolfSSL_EVP_PKEY_assign_EC_KEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY* key) +{ + int ret; + + if (pkey == NULL || key == NULL) + return WOLFSSL_FAILURE; + + /* try and populate public pkey_sz and pkey.ptr */ + ret = ECC_populate_EVP_PKEY(pkey, key); + if (ret == WOLFSSL_SUCCESS) { /* take ownership of key if can be used */ + clearEVPPkeyKeys(pkey); /* clear out any previous keys */ + + pkey->type = EVP_PKEY_EC; + pkey->ecc = key; + pkey->ownEcc = 1; } + return ret; +} +#endif /* HAVE_ECC */ -const WOLFSSL_EVP_MD* wolfSSL_EVP_get_digestbynid(int id) +#ifndef NO_WOLFSSL_STUB +const WOLFSSL_EVP_MD* wolfSSL_EVP_ripemd160(void) { - WOLFSSL_MSG("wolfSSL_get_digestbynid"); + WOLFSSL_MSG("wolfSSL_ripemd160"); + WOLFSSL_STUB("EVP_ripemd160"); + return NULL; +} +#endif - switch(id) { -#ifndef NO_MD5 - case NID_md5: - return wolfSSL_EVP_md5(); + +int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) +{ + int ret = BAD_FUNC_ARG; + + WOLFSSL_ENTER("wolfSSL_EVP_MD_pkey_type"); + + if (type != NULL) { + if (XSTRCMP(type, "MD5") == 0) { + ret = NID_md5WithRSAEncryption; + } + else if (XSTRCMP(type, "SHA1") == 0) { + ret = NID_sha1WithRSAEncryption; + } + else if (XSTRCMP(type, "SHA224") == 0) { + ret = NID_sha224WithRSAEncryption; + } + else if (XSTRCMP(type, "SHA256") == 0) { + ret = NID_sha256WithRSAEncryption; + } + else if (XSTRCMP(type, "SHA384") == 0) { + ret = NID_sha384WithRSAEncryption; + } + else if (XSTRCMP(type, "SHA512") == 0) { + ret = NID_sha512WithRSAEncryption; + } + } + + WOLFSSL_LEAVE("wolfSSL_EVP_MD_pkey_type", ret); + + return ret; +} + + + +int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) +{ + WOLFSSL_MSG("wolfSSL_EVP_CIPHER_CTX_iv_length"); + + switch (ctx->cipherType) { + +#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + case AES_128_CBC_TYPE : + case AES_192_CBC_TYPE : + case AES_256_CBC_TYPE : + WOLFSSL_MSG("AES CBC"); + return AES_BLOCK_SIZE; #endif -#ifndef NO_SHA - case NID_sha1: - return wolfSSL_EVP_sha1(); +#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ + (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) +#ifdef HAVE_AESGCM + case AES_128_GCM_TYPE : + case AES_192_GCM_TYPE : + case AES_256_GCM_TYPE : + WOLFSSL_MSG("AES GCM"); + if (ctx->ivSz != 0) { + return ctx->ivSz; + } + return GCM_NONCE_MID_SZ; #endif -#ifdef WOLFSSL_SHA224 - case NID_sha224: - return wolfSSL_EVP_sha224(); +#ifdef HAVE_AESCCM + case AES_128_CCM_TYPE : + case AES_192_CCM_TYPE : + case AES_256_CCM_TYPE : + WOLFSSL_MSG("AES CCM"); + if (ctx->ivSz != 0) { + return ctx->ivSz; + } + return CCM_NONCE_MIN_SZ; #endif -#ifndef NO_SHA256 - case NID_sha256: - return wolfSSL_EVP_sha256(); +#endif /* (HAVE_FIPS && !HAVE_SELFTEST) || HAVE_FIPS_VERSION >= 2 */ +#ifdef WOLFSSL_AES_COUNTER + case AES_128_CTR_TYPE : + case AES_192_CTR_TYPE : + case AES_256_CTR_TYPE : + WOLFSSL_MSG("AES CTR"); + return AES_BLOCK_SIZE; #endif -#ifdef WOLFSSL_SHA384 - case NID_sha384: - return wolfSSL_EVP_sha384(); +#ifndef NO_DES3 + case DES_CBC_TYPE : + WOLFSSL_MSG("DES CBC"); + return DES_BLOCK_SIZE; + + case DES_EDE3_CBC_TYPE : + WOLFSSL_MSG("DES EDE3 CBC"); + return DES_BLOCK_SIZE; #endif -#ifdef WOLFSSL_SHA512 - case NID_sha512: - return wolfSSL_EVP_sha512(); +#ifndef NO_RC4 + case ARC4_TYPE : + WOLFSSL_MSG("ARC4"); + return 0; #endif - default: - WOLFSSL_MSG("Bad digest id value"); - } +#ifdef WOLFSSL_AES_CFB +#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) + case AES_128_CFB1_TYPE: + case AES_192_CFB1_TYPE: + case AES_256_CFB1_TYPE: + WOLFSSL_MSG("AES CFB1"); + return AES_BLOCK_SIZE; + case AES_128_CFB8_TYPE: + case AES_192_CFB8_TYPE: + case AES_256_CFB8_TYPE: + WOLFSSL_MSG("AES CFB8"); + return AES_BLOCK_SIZE; +#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ + case AES_128_CFB128_TYPE: + case AES_192_CFB128_TYPE: + case AES_256_CFB128_TYPE: + WOLFSSL_MSG("AES CFB128"); + return AES_BLOCK_SIZE; +#endif /* WOLFSSL_AES_CFB */ +#if defined(WOLFSSL_AES_OFB) + case AES_128_OFB_TYPE: + case AES_192_OFB_TYPE: + case AES_256_OFB_TYPE: + WOLFSSL_MSG("AES OFB"); + return AES_BLOCK_SIZE; +#endif /* WOLFSSL_AES_OFB */ +#ifdef WOLFSSL_AES_XTS + case AES_128_XTS_TYPE: + case AES_256_XTS_TYPE: + WOLFSSL_MSG("AES XTS"); + return AES_BLOCK_SIZE; +#endif /* WOLFSSL_AES_XTS */ +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + case CHACHA20_POLY1305_TYPE: + WOLFSSL_MSG("CHACHA20 POLY1305"); + return CHACHA20_POLY1305_AEAD_IV_SIZE; +#endif /* HAVE_CHACHA HAVE_POLY1305 */ +#ifdef HAVE_CHACHA + case CHACHA20_TYPE: + WOLFSSL_MSG("CHACHA20"); + return WOLFSSL_EVP_CHACHA_IV_BYTES; +#endif /* HAVE_CHACHA */ - return NULL; + case NULL_CIPHER_TYPE : + WOLFSSL_MSG("NULL"); + return 0; + + default: { + WOLFSSL_MSG("bad type"); + } + } + return 0; } -#ifdef OPENSSL_EXTRA -static void clearEVPPkeyKeys(WOLFSSL_EVP_PKEY *pkey) +int wolfSSL_EVP_CIPHER_iv_length(const WOLFSSL_EVP_CIPHER* cipher) { - if(pkey == NULL) - return; - WOLFSSL_ENTER("clearEVPPkeyKeys"); -#ifndef NO_RSA - if (pkey->rsa != NULL && pkey->ownRsa == 1) { - wolfSSL_RSA_free(pkey->rsa); - pkey->rsa = NULL; - } - pkey->ownRsa = 0; + const char *name = (const char *)cipher; + WOLFSSL_MSG("wolfSSL_EVP_CIPHER_iv_length"); + +#ifndef NO_AES +#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + #ifdef WOLFSSL_AES_128 + if (XSTRCMP(name, EVP_AES_128_CBC) == 0) + return AES_BLOCK_SIZE; + #endif + #ifdef WOLFSSL_AES_192 + if (XSTRCMP(name, EVP_AES_192_CBC) == 0) + return AES_BLOCK_SIZE; + #endif + #ifdef WOLFSSL_AES_256 + if (XSTRCMP(name, EVP_AES_256_CBC) == 0) + return AES_BLOCK_SIZE; + #endif +#endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ +#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ + (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) +#ifdef HAVE_AESGCM + #ifdef WOLFSSL_AES_128 + if (XSTRCMP(name, EVP_AES_128_GCM) == 0) + return GCM_NONCE_MID_SZ; + #endif + #ifdef WOLFSSL_AES_192 + if (XSTRCMP(name, EVP_AES_192_GCM) == 0) + return GCM_NONCE_MID_SZ; + #endif + #ifdef WOLFSSL_AES_256 + if (XSTRCMP(name, EVP_AES_256_GCM) == 0) + return GCM_NONCE_MID_SZ; + #endif +#endif /* HAVE_AESGCM */ +#ifdef HAVE_AESCCM + #ifdef WOLFSSL_AES_128 + if (XSTRCMP(name, EVP_AES_128_CCM) == 0) + return CCM_NONCE_MIN_SZ; + #endif + #ifdef WOLFSSL_AES_192 + if (XSTRCMP(name, EVP_AES_192_CCM) == 0) + return CCM_NONCE_MIN_SZ; + #endif + #ifdef WOLFSSL_AES_256 + if (XSTRCMP(name, EVP_AES_256_CCM) == 0) + return CCM_NONCE_MIN_SZ; + #endif +#endif /* HAVE_AESCCM */ +#endif /* (HAVE_FIPS && !HAVE_SELFTEST) || HAVE_FIPS_VERSION >= 2 */ +#ifdef WOLFSSL_AES_COUNTER + #ifdef WOLFSSL_AES_128 + if (XSTRCMP(name, EVP_AES_128_CTR) == 0) + return AES_BLOCK_SIZE; + #endif + #ifdef WOLFSSL_AES_192 + if (XSTRCMP(name, EVP_AES_192_CTR) == 0) + return AES_BLOCK_SIZE; + #endif + #ifdef WOLFSSL_AES_256 + if (XSTRCMP(name, EVP_AES_256_CTR) == 0) + return AES_BLOCK_SIZE; + #endif #endif -#ifndef NO_DSA - if (pkey->dsa != NULL && pkey->ownDsa == 1) { - wolfSSL_DSA_free(pkey->dsa); - pkey->dsa = NULL; - } - pkey->ownDsa = 0; +#ifdef WOLFSSL_AES_XTS + #ifdef WOLFSSL_AES_128 + if (XSTRCMP(name, EVP_AES_128_XTS) == 0) + return AES_BLOCK_SIZE; + #endif /* WOLFSSL_AES_128 */ + + #ifdef WOLFSSL_AES_256 + if (XSTRCMP(name, EVP_AES_256_XTS) == 0) + return AES_BLOCK_SIZE; + #endif /* WOLFSSL_AES_256 */ +#endif /* WOLFSSL_AES_XTS */ + #endif -#ifndef NO_DH - if (pkey->dh != NULL && pkey->ownDh == 1) { - wolfSSL_DH_free(pkey->dh); - pkey->dh = NULL; + +#ifndef NO_DES3 + if ((XSTRCMP(name, EVP_DES_CBC) == 0) || + (XSTRCMP(name, EVP_DES_EDE3_CBC) == 0)) { + return DES_BLOCK_SIZE; } - pkey->ownDh = 0; #endif -#ifdef HAVE_ECC - if (pkey->ecc != NULL && pkey->ownEcc == 1) { - wolfSSL_EC_KEY_free(pkey->ecc); - pkey->ecc = NULL; - } - pkey->ownEcc = 0; + +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + if (XSTRCMP(name, EVP_CHACHA20_POLY1305) == 0) + return CHACHA20_POLY1305_AEAD_IV_SIZE; +#endif + +#ifdef HAVE_CHACHA + if (XSTRCMP(name, EVP_CHACHA20) == 0) + return WOLFSSL_EVP_CHACHA_IV_BYTES; #endif + + (void)name; + + return 0; } -#ifndef NO_RSA -#if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) -static int PopulateRSAEvpPkeyDer(WOLFSSL_EVP_PKEY *pkey) -{ - int ret = 0; - int derSz = 0; - word32 pkcs8Sz = 0; - byte* derBuf = NULL; - RsaKey* rsa = NULL; - WOLFSSL_RSA *key = NULL; - if (pkey == NULL || pkey->rsa == NULL || pkey->rsa->internal == NULL) { - WOLFSSL_MSG("bad parameter"); - return WOLFSSL_FAILURE; - } +int wolfSSL_EVP_X_STATE_LEN(const WOLFSSL_EVP_CIPHER_CTX* ctx) +{ + WOLFSSL_MSG("wolfSSL_EVP_X_STATE_LEN"); - key = pkey->rsa; - rsa = (RsaKey*)pkey->rsa->internal; + if (ctx) { + switch (ctx->cipherType) { + case ARC4_TYPE: + WOLFSSL_MSG("returning arc4 state size"); + return sizeof(Arc4); - /* Get DER size */ - if (rsa->type == RSA_PRIVATE) { - ret = wc_RsaKeyToDer(rsa, NULL, 0); - if (ret > 0) { - derSz = ret; - #ifdef HAVE_PKCS8 - if (key->pkcs8HeaderSz) { - ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, NULL, derSz, - RSAk, NULL, 0); - if (ret == LENGTH_ONLY_E) - ret = 0; - } - #endif + default: + WOLFSSL_MSG("bad x state type"); + return 0; } } - else { - ret = wc_RsaKeyToPublicDer(rsa, NULL, 0); - if (ret > 0) - derSz = ret; - } - if (derSz == 0 || ret < 0) { - WOLFSSL_MSG("Error getting RSA DER size"); - return WOLFSSL_FAILURE; - } + return 0; +} -#ifdef WOLFSSL_NO_REALLOC - derBuf = (byte*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_DER); - if (derBuf != NULL) { - XMEMCPY(derBuf, pkey->pkey.ptr, pkey->pkey_sz); - XFREE(pkey->pkey.ptr, pkey->heap, DYNAMIC_TYPE_DER); - pkey->pkey.ptr = NULL; - } -#else - derBuf = (byte*)XREALLOC(pkey->pkey.ptr, derSz, - pkey->heap, DYNAMIC_TYPE_DER); -#endif - if (derBuf == NULL) { - WOLFSSL_MSG("PopulateRSAEvpPkeyDer malloc failed"); - return WOLFSSL_FAILURE; - } - /* Old pointer is invalid from this point on */ - pkey->pkey.ptr = (char*)derBuf; +/* return of pkey->type which will be EVP_PKEY_RSA for example. + * + * type type of EVP_PKEY + * + * returns type or if type is not found then NID_undef + */ +int wolfSSL_EVP_PKEY_type(int type) +{ + WOLFSSL_MSG("wolfSSL_EVP_PKEY_type"); - if (rsa->type == RSA_PRIVATE) { - ret = wc_RsaKeyToDer(rsa, derBuf, derSz); - if (ret > 0) { - derSz = ret; - #ifdef HAVE_PKCS8 - if (key->pkcs8HeaderSz) { - byte* keyBuf = derBuf; - int keySz = derSz; - derSz = pkcs8Sz; - /* Need new buffer for PKCS8 since we can't - * do this in-place */ - derBuf = (byte*)XMALLOC(pkcs8Sz, pkey->heap, - DYNAMIC_TYPE_DER); - if (derBuf != NULL) { - ret = wc_CreatePKCS8Key(derBuf, (word32*)&derSz, keyBuf, - keySz, RSAk, NULL, 0); - XFREE(keyBuf, pkey->heap, DYNAMIC_TYPE_DER); - pkey->pkey.ptr = (char*)derBuf; - } - else - ret = MEMORY_E; - } - #endif - } - } - else { - /* Public key to DER */ - ret = wc_RsaKeyToPublicDer(rsa, derBuf, derSz); - if (ret > 0) - derSz = ret; + switch (type) { + case EVP_PKEY_RSA: + return EVP_PKEY_RSA; + case EVP_PKEY_DSA: + return EVP_PKEY_DSA; + case EVP_PKEY_EC: + return EVP_PKEY_EC; + case EVP_PKEY_DH: + return EVP_PKEY_DH; + default: + return NID_undef; } +} - if (ret < 0) { - WOLFSSL_MSG("PopulateRSAEvpPkeyDer failed"); + +int wolfSSL_EVP_PKEY_id(const WOLFSSL_EVP_PKEY *pkey) +{ + if (pkey != NULL) + return pkey->type; + return 0; +} + + +int wolfSSL_EVP_PKEY_base_id(const WOLFSSL_EVP_PKEY *pkey) +{ + if (pkey == NULL) + return NID_undef; + return wolfSSL_EVP_PKEY_type(pkey->type); +} + +int wolfSSL_EVP_PKEY_get_default_digest_nid(WOLFSSL_EVP_PKEY *pkey, int *pnid) +{ + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get_default_digest_nid"); + + if (!pkey || !pnid) { + WOLFSSL_MSG("Bad parameter"); return WOLFSSL_FAILURE; } - else { - pkey->pkey_sz = derSz; + + switch (pkey->type) { + case EVP_PKEY_HMAC: +#ifndef NO_DSA + case EVP_PKEY_DSA: +#endif +#ifndef NO_RSA + case EVP_PKEY_RSA: +#endif +#ifdef HAVE_ECC + case EVP_PKEY_EC: +#endif + *pnid = NID_sha256; return WOLFSSL_SUCCESS; + default: + return WOLFSSL_FAILURE; } } -#endif -WOLFSSL_RSA* wolfSSL_EVP_PKEY_get0_RSA(WOLFSSL_EVP_PKEY *pkey) +#if defined(OPENSSL_ALL) || defined(WOLFSSL_WPAS_SMALL) +WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKCS82PKEY(const WOLFSSL_PKCS8_PRIV_KEY_INFO* p8) { - WOLFSSL_MSG("wolfSSL_EVP_PKEY_get0_RSA"); - - if (pkey == NULL) + if (p8 == NULL || p8->pkey.ptr == NULL) { return NULL; + } - return pkey->rsa; + return wolfSSL_d2i_PrivateKey_EVP(NULL, (unsigned char**)&p8->pkey.ptr, + p8->pkey_sz); } -WOLFSSL_RSA* wolfSSL_EVP_PKEY_get1_RSA(WOLFSSL_EVP_PKEY* pkey) +/* in wolf PKCS8_PRIV_KEY_INFO and WOLFSSL_EVP_PKEY are same type */ +/* this function just casts and returns pointer */ +WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_EVP_PKEY2PKCS8(const WOLFSSL_EVP_PKEY* pkey) { - WOLFSSL_MSG("wolfSSL_EVP_PKEY_get1_RSA"); + return (WOLFSSL_PKCS8_PRIV_KEY_INFO*)pkey; +} +#endif - if (pkey == NULL || pkey->rsa == NULL) - return NULL; +/* increments ref count of WOLFSSL_EVP_PKEY. Return 1 on success, 0 on error */ +int wolfSSL_EVP_PKEY_up_ref(WOLFSSL_EVP_PKEY* pkey) +{ + if (pkey) { + int ret; + wolfSSL_RefInc(&pkey->ref, &ret); + #ifdef WOLFSSL_REFCNT_ERROR_RETURN + if (ret != 0) { + WOLFSSL_MSG("Failed to lock pkey mutex"); + } + #else + (void)ret; + #endif - if (wolfSSL_RSA_up_ref(pkey->rsa) != WOLFSSL_SUCCESS) - return NULL; + return WOLFSSL_SUCCESS; + } - return pkey->rsa; + return WOLFSSL_FAILURE; } -/* with set1 functions the pkey struct does not own the RSA structure - * - * returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure - */ -int wolfSSL_EVP_PKEY_set1_RSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_RSA *key) +#ifndef NO_RSA +int wolfSSL_EVP_PKEY_assign_RSA(EVP_PKEY* pkey, WOLFSSL_RSA* key) { - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_set1_RSA"); if (pkey == NULL || key == NULL) return WOLFSSL_FAILURE; - if (wolfSSL_RSA_up_ref(key) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_RSA_up_ref failed"); - return WOLFSSL_FAILURE; - } - clearEVPPkeyKeys(pkey); - pkey->rsa = key; - pkey->ownRsa = 1; /* pkey does not own RSA but needs to call free on it */ - pkey->type = EVP_PKEY_RSA; - pkey->pkcs8HeaderSz = key->pkcs8HeaderSz; - if (key->inSet == 0) { - if (SetRsaInternal(key) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("SetRsaInternal failed"); - return WOLFSSL_FAILURE; - } - } - -#if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) - if (PopulateRSAEvpPkeyDer(pkey) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("PopulateRSAEvpPkeyDer failed"); - return WOLFSSL_FAILURE; - } -#endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */ + pkey->type = EVP_PKEY_RSA; + pkey->rsa = key; + pkey->ownRsa = 1; -#ifdef WC_RSA_BLINDING - if (key->ownRng == 0) { - if (wc_RsaSetRNG((RsaKey*)pkey->rsa->internal, &pkey->rng) != 0) { - WOLFSSL_MSG("Error setting RSA rng"); - return WOLFSSL_FAILURE; + /* try and populate pkey_sz and pkey.ptr */ + if (key->internal) { + RsaKey* rsa = (RsaKey*)key->internal; + int ret = wc_RsaKeyToDer(rsa, NULL, 0); + if (ret > 0) { + int derSz = ret; + byte* derBuf = (byte*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (derBuf) { + ret = wc_RsaKeyToDer(rsa, derBuf, derSz); + if (ret >= 0) { + pkey->pkey_sz = ret; + pkey->pkey.ptr = (char*)derBuf; + } + else { /* failure - okay to ignore */ + XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + derBuf = NULL; + } + } } } -#endif + return WOLFSSL_SUCCESS; } #endif /* !NO_RSA */ -#if !defined (NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN) -/* with set1 functions the pkey struct does not own the DSA structure - * - * returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure - */ -int wolfSSL_EVP_PKEY_set1_DSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DSA *key) +#ifndef NO_DSA +int wolfSSL_EVP_PKEY_assign_DSA(EVP_PKEY* pkey, WOLFSSL_DSA* key) { - int derMax = 0; - int derSz = 0; - DsaKey* dsa = NULL; - byte* derBuf = NULL; + if (pkey == NULL || key == NULL) + return WOLFSSL_FAILURE; - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_set1_DSA"); + clearEVPPkeyKeys(pkey); + pkey->type = EVP_PKEY_DSA; + pkey->dsa = key; + pkey->ownDsa = 1; + + return WOLFSSL_SUCCESS; +} +#endif /* !NO_DSA */ + +#ifndef NO_DH +int wolfSSL_EVP_PKEY_assign_DH(EVP_PKEY* pkey, WOLFSSL_DH* key) +{ + if (pkey == NULL || key == NULL) + return WOLFSSL_FAILURE; - if((pkey == NULL) || (key == NULL))return WOLFSSL_FAILURE; clearEVPPkeyKeys(pkey); - pkey->dsa = key; - pkey->ownDsa = 0; /* pkey does not own DSA */ - pkey->type = EVP_PKEY_DSA; - if (key->inSet == 0) { - if (SetDsaInternal(key) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("SetDsaInternal failed"); - return WOLFSSL_FAILURE; + pkey->type = EVP_PKEY_DH; + pkey->dh = key; + pkey->ownDh = 1; + + return WOLFSSL_SUCCESS; +} +#endif /* !NO_DH */ +#endif /* OPENSSL_EXTRA */ + +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) +/* EVP Digest functions used with cURL build too */ + +static enum wc_HashType EvpMd2MacType(const WOLFSSL_EVP_MD *md) +{ + if (md != NULL) { + const struct s_ent *ent; + for (ent = md_tbl; ent->name != NULL; ent++) { + if (XSTRCMP((const char *)md, ent->name) == 0) { + return ent->macType; + } } } - dsa = (DsaKey*)key->internal; + return WC_HASH_TYPE_NONE; +} - /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */ - derMax = 4 * wolfSSL_BN_num_bytes(key->g) + AES_BLOCK_SIZE; +int wolfSSL_EVP_DigestInit_ex(WOLFSSL_EVP_MD_CTX* ctx, + const WOLFSSL_EVP_MD* type, + WOLFSSL_ENGINE *impl) +{ + (void) impl; + WOLFSSL_ENTER("wolfSSL_EVP_DigestInit_ex"); + return wolfSSL_EVP_DigestInit(ctx, type); +} - derBuf = (byte*)XMALLOC(derMax, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (derBuf == NULL) { - WOLFSSL_MSG("malloc failed"); +/* this function makes the assumption that out buffer is big enough for digest*/ +int wolfSSL_EVP_Digest(const unsigned char* in, int inSz, unsigned char* out, + unsigned int* outSz, const WOLFSSL_EVP_MD* evp, + WOLFSSL_ENGINE* eng) +{ + int err; + int hashType = WC_HASH_TYPE_NONE; + int hashSz; + + WOLFSSL_ENTER("wolfSSL_EVP_Digest"); + if (in == NULL || out == NULL || evp == NULL) { + WOLFSSL_MSG("Null argument passed in"); return WOLFSSL_FAILURE; } - if (dsa->type == DSA_PRIVATE) { - /* Private key to DER */ - derSz = wc_DsaKeyToDer(dsa, derBuf, derMax); - } - else { - /* Public key to DER */ - derSz = wc_DsaKeyToPublicDer(dsa, derBuf, derMax); - } + err = wolfSSL_EVP_get_hashinfo(evp, &hashType, &hashSz); + if (err != WOLFSSL_SUCCESS) + return err; - if (derSz < 0) { - if (dsa->type == DSA_PRIVATE) { - WOLFSSL_MSG("wc_DsaKeyToDer failed"); - } - else { - WOLFSSL_MSG("wc_DsaKeyToPublicDer failed"); - } - XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (wc_Hash((enum wc_HashType)hashType, in, inSz, out, hashSz) != 0) { return WOLFSSL_FAILURE; } - pkey->pkey.ptr = (char*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_DER); - if (pkey->pkey.ptr == NULL) { - WOLFSSL_MSG("key malloc failed"); - XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); - return WOLFSSL_FAILURE; - } - pkey->pkey_sz = derSz; - XMEMCPY(pkey->pkey.ptr, derBuf, derSz); - XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (outSz != NULL) + *outSz = hashSz; + (void)eng; return WOLFSSL_SUCCESS; } -WOLFSSL_DSA* wolfSSL_EVP_PKEY_get0_DSA(struct WOLFSSL_EVP_PKEY *pkey) +static const struct alias { + const char *name; + const char *alias; +} digest_alias_tbl[] = { - if (!pkey) { - return NULL; - } - return pkey->dsa; -} + {"MD4", "ssl3-md4"}, + {"MD5", "ssl3-md5"}, + {"SHA1", "ssl3-sha1"}, + {"SHA1", "SHA"}, + { NULL, NULL} +}; -WOLFSSL_DSA* wolfSSL_EVP_PKEY_get1_DSA(WOLFSSL_EVP_PKEY* key) +const WOLFSSL_EVP_MD *wolfSSL_EVP_get_digestbyname(const char *name) { - WOLFSSL_DSA* local; + char nameUpper[15]; /* 15 bytes should be enough for any name */ + size_t i; - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get1_DSA"); + const struct alias *al; + const struct s_ent *ent; - if (key == NULL) { - WOLFSSL_MSG("Bad function argument"); - return NULL; + for (i = 0; i < sizeof(nameUpper) && name[i] != '\0'; i++) { + nameUpper[i] = (char)XTOUPPER((unsigned char) name[i]); } - - local = wolfSSL_DSA_new(); - if (local == NULL) { - WOLFSSL_MSG("Error creating a new WOLFSSL_DSA structure"); + if (i < sizeof(nameUpper)) + nameUpper[i] = '\0'; + else return NULL; - } - if (key->type == EVP_PKEY_DSA) { - if (wolfSSL_DSA_LoadDer(local, (const unsigned char*)key->pkey.ptr, - key->pkey_sz) != SSL_SUCCESS) { - /* now try public key */ - if (wolfSSL_DSA_LoadDer_ex(local, - (const unsigned char*)key->pkey.ptr, key->pkey_sz, - WOLFSSL_DSA_LOAD_PUBLIC) != SSL_SUCCESS) { - wolfSSL_DSA_free(local); - local = NULL; - } + name = nameUpper; + for (al = digest_alias_tbl; al->name != NULL; al++) + if(XSTRCMP(name, al->alias) == 0) { + name = al->name; + break; } - } - else { - WOLFSSL_MSG("WOLFSSL_EVP_PKEY does not hold a DSA key"); - wolfSSL_DSA_free(local); - local = NULL; - } - return local; -} -#endif /* !NO_DSA && !HAVE_SELFTEST && WOLFSSL_KEY_GEN */ -#ifdef HAVE_ECC -WOLFSSL_EC_KEY *wolfSSL_EVP_PKEY_get0_EC_KEY(WOLFSSL_EVP_PKEY *pkey) -{ - WOLFSSL_EC_KEY *eckey = NULL; - if (pkey && pkey->type == EVP_PKEY_EC) { -#ifdef HAVE_ECC - eckey = pkey->ecc; -#endif - } - return eckey; + for (ent = md_tbl; ent->name != NULL; ent++) + if(XSTRCMP(name, ent->name) == 0) { + return (EVP_MD *)ent->name; + } + return NULL; } -WOLFSSL_EC_KEY* wolfSSL_EVP_PKEY_get1_EC_KEY(WOLFSSL_EVP_PKEY* key) +/* Returns the NID of the WOLFSSL_EVP_MD passed in. + * + * type - pointer to WOLFSSL_EVP_MD for which to return NID value + * + * Returns NID on success, or NID_undef if none exists. + */ +int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) { - WOLFSSL_EC_KEY* local = NULL; - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get1_EC_KEY"); + const struct s_ent *ent ; + WOLFSSL_ENTER("EVP_MD_type"); - if (key == NULL || key->type != EVP_PKEY_EC) { - return NULL; + if (type == NULL) { + WOLFSSL_MSG("MD type arg is NULL"); + return NID_undef; } - if (key->type == EVP_PKEY_EC) { - if (key->ecc != NULL) { - if (wolfSSL_EC_KEY_up_ref(key->ecc) != WOLFSSL_SUCCESS) { - return NULL; - } - local = key->ecc; - } - else { - key->ecc = local = wolfSSL_EC_KEY_new(); - if (local == NULL) { - WOLFSSL_MSG("Error creating a new WOLFSSL_EC_KEY structure"); - return NULL; - } - if (wolfSSL_EC_KEY_LoadDer(local, - (const unsigned char*)key->pkey.ptr, - key->pkey_sz) != WOLFSSL_SUCCESS) { - /* now try public key */ - if (wolfSSL_EC_KEY_LoadDer_ex(local, - (const unsigned char*)key->pkey.ptr, key->pkey_sz, - WOLFSSL_EC_KEY_LOAD_PUBLIC) != WOLFSSL_SUCCESS) { - wolfSSL_EC_KEY_free(local); - local = NULL; - } - } + for( ent = md_tbl; ent->name != NULL; ent++){ + if(XSTRCMP((const char *)type, ent->name) == 0) { + return ent->nid; } } - else { - WOLFSSL_MSG("WOLFSSL_EVP_PKEY does not hold an EC key"); - } - - return local; + return NID_undef; } -#endif /* HAVE_ECC */ -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || defined(WOLFSSL_OPENSSH) -#if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM) -/* with set1 functions the pkey struct does not own the DH structure - * Build the following DH Key format from the passed in WOLFSSL_DH - * then store in WOLFSSL_EVP_PKEY in DER format. - * - * returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure - */ -int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) -{ - byte havePublic = 0, havePrivate = 0; - int ret; - word32 derSz = 0; - byte* derBuf = NULL; - DhKey* dhkey = NULL; +#ifndef NO_MD4 - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_set1_DH"); + /* return a pointer to MD4 EVP type */ + const WOLFSSL_EVP_MD* wolfSSL_EVP_md4(void) + { + WOLFSSL_ENTER("EVP_md4"); + return EVP_get_digestbyname("MD4"); + } - if (pkey == NULL || key == NULL) - return WOLFSSL_FAILURE; +#endif /* !NO_MD4 */ - clearEVPPkeyKeys(pkey); - if (wolfSSL_DH_up_ref(key) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Failed to increase dh key ref count"); - return WOLFSSL_FAILURE; - } +#ifndef NO_MD5 - pkey->dh = key; - pkey->ownDh = 1; /* pkey does not own DH but needs to call free on it */ - pkey->type = EVP_PKEY_DH; - if (key->inSet == 0) { - if (SetDhInternal(key) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("SetDhInternal failed"); - return WOLFSSL_FAILURE; - } + const WOLFSSL_EVP_MD* wolfSSL_EVP_md5(void) + { + WOLFSSL_ENTER("EVP_md5"); + return EVP_get_digestbyname("MD5"); } - dhkey = (DhKey*)key->internal; - - havePublic = mp_unsigned_bin_size(&dhkey->pub) > 0; - havePrivate = mp_unsigned_bin_size(&dhkey->priv) > 0; +#endif /* !NO_MD5 */ - /* Get size of DER buffer only */ - if (havePublic && !havePrivate) { - ret = wc_DhPubKeyToDer(dhkey, NULL, &derSz); - } else if (havePrivate && !havePublic) { - ret = wc_DhPrivKeyToDer(dhkey, NULL, &derSz); - } else { - ret = wc_DhParamsToDer(dhkey,NULL,&derSz); +#ifdef HAVE_BLAKE2 + /* return EVP_MD + * @param none + * @return "blake2b512" + */ + const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2b512(void) + { + WOLFSSL_ENTER("EVP_blake2b512"); + return EVP_get_digestbyname("BLAKE2b512"); } - if (derSz == 0 || ret != LENGTH_ONLY_E) { - WOLFSSL_MSG("Failed to get size of DH Key"); - return WOLFSSL_FAILURE; - } +#endif - derBuf = (byte*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (derBuf == NULL) { - WOLFSSL_MSG("malloc failed"); - return WOLFSSL_FAILURE; +#ifdef HAVE_BLAKE2S + /* return EVP_MD + * @param none + * @return "blake2s256" + */ + const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2s256(void) + { + WOLFSSL_ENTER("EVP_blake2s256"); + return EVP_get_digestbyname("BLAKE2s256"); } - /* Fill DER buffer */ - if (havePublic && !havePrivate) { - ret = wc_DhPubKeyToDer(dhkey, derBuf, &derSz); - } else if (havePrivate && !havePublic) { - ret = wc_DhPrivKeyToDer(dhkey, derBuf, &derSz); - } else { - ret = wc_DhParamsToDer(dhkey,derBuf,&derSz); - } +#endif - if (ret <= 0) { - WOLFSSL_MSG("Failed to export DH Key"); - XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); - return WOLFSSL_FAILURE; + +#ifndef NO_WOLFSSL_STUB + void wolfSSL_EVP_set_pw_prompt(const char *prompt) + { + (void)prompt; + WOLFSSL_STUB("EVP_set_pw_prompt"); } +#endif - /* Store DH key into pkey (DER format) */ - pkey->pkey.ptr = (char*)derBuf; - pkey->pkey_sz = derSz; +#ifndef NO_WOLFSSL_STUB + const WOLFSSL_EVP_MD* wolfSSL_EVP_mdc2(void) + { + WOLFSSL_STUB("EVP_mdc2"); + return NULL; + } +#endif - return WOLFSSL_SUCCESS; -} +#ifndef NO_SHA + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha1(void) + { + WOLFSSL_ENTER("EVP_sha1"); + return EVP_get_digestbyname("SHA1"); + } +#endif /* NO_SHA */ -WOLFSSL_DH* wolfSSL_EVP_PKEY_get0_DH(WOLFSSL_EVP_PKEY* key) -{ - if (!key) { - return NULL; +#ifdef WOLFSSL_SHA224 + + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha224(void) + { + WOLFSSL_ENTER("EVP_sha224"); + return EVP_get_digestbyname("SHA224"); } - return key->dh; -} -WOLFSSL_DH* wolfSSL_EVP_PKEY_get1_DH(WOLFSSL_EVP_PKEY* key) -{ - WOLFSSL_DH* local = NULL; +#endif /* WOLFSSL_SHA224 */ - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get1_DH"); - if (key == NULL || key->dh == NULL) { - WOLFSSL_MSG("Bad function argument"); - return NULL; + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha256(void) + { + WOLFSSL_ENTER("EVP_sha256"); + return EVP_get_digestbyname("SHA256"); } - if (key->type == EVP_PKEY_DH) { - /* if key->dh already exists copy instead of re-importing from DER */ - if (key->dh != NULL) { - if (wolfSSL_DH_up_ref(key->dh) != WOLFSSL_SUCCESS) { - return NULL; - } - local = key->dh; - } - else { -#if !defined(NO_DH) && (!defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ - (HAVE_FIPS_VERSION>2))) - local = wolfSSL_DH_new(); - if (local == NULL) { - WOLFSSL_MSG("Error creating a new WOLFSSL_DH structure"); - return NULL; - } - if (wolfSSL_DH_LoadDer(local, (const unsigned char*)key->pkey.ptr, - key->pkey_sz) != SSL_SUCCESS) { - wolfSSL_DH_free(local); - WOLFSSL_MSG("Error wolfSSL_DH_LoadDer"); - local = NULL; - } -#else - WOLFSSL_MSG("EVP_PKEY does not hold DH struct"); - return NULL; -#endif - } +#ifdef WOLFSSL_SHA384 + + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha384(void) + { + WOLFSSL_ENTER("EVP_sha384"); + return EVP_get_digestbyname("SHA384"); } - else { - WOLFSSL_MSG("WOLFSSL_EVP_PKEY does not hold a DH key"); - wolfSSL_DH_free(local); - return NULL; + +#endif /* WOLFSSL_SHA384 */ + +#ifdef WOLFSSL_SHA512 + + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512(void) + { + WOLFSSL_ENTER("EVP_sha512"); + return EVP_get_digestbyname("SHA512"); } - return local; -} -#endif /* NO_DH && WOLFSSL_DH_EXTRA && NO_FILESYSTEM */ +#ifndef WOLFSSL_NOSHA512_224 -int wolfSSL_EVP_PKEY_assign(WOLFSSL_EVP_PKEY *pkey, int type, void *key) -{ - int ret; + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_224(void) + { + WOLFSSL_ENTER("EVP_sha512_224"); + return EVP_get_digestbyname("SHA512_224"); + } - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_assign"); +#endif /* !WOLFSSL_NOSHA512_224 */ - /* pkey and key checked if NULL in subsequent assign functions */ - switch(type) { - #ifndef NO_RSA - case EVP_PKEY_RSA: - ret = wolfSSL_EVP_PKEY_assign_RSA(pkey, (WOLFSSL_RSA*)key); - break; - #endif - #ifndef NO_DSA - case EVP_PKEY_DSA: - ret = wolfSSL_EVP_PKEY_assign_DSA(pkey, (WOLFSSL_DSA*)key); - break; - #endif - #ifdef HAVE_ECC - case EVP_PKEY_EC: - ret = wolfSSL_EVP_PKEY_assign_EC_KEY(pkey, (WOLFSSL_EC_KEY*)key); - break; - #endif - #ifndef NO_DH - case EVP_PKEY_DH: - ret = wolfSSL_EVP_PKEY_assign_DH(pkey, (WOLFSSL_DH*)key); - break; - #endif - default: - WOLFSSL_MSG("Unknown EVP_PKEY type in wolfSSL_EVP_PKEY_assign."); - ret = WOLFSSL_FAILURE; +#ifndef WOLFSSL_NOSHA512_256 + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_256(void) + { + WOLFSSL_ENTER("EVP_sha512_256"); + return EVP_get_digestbyname("SHA512_256"); } - return ret; -} -#endif /* WOLFSSL_QT || OPENSSL_ALL */ +#endif /* !WOLFSSL_NOSHA512_224 */ -#if defined(HAVE_ECC) -/* try and populate public pkey_sz and pkey.ptr */ -static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) -{ - int derSz = 0; - byte* derBuf = NULL; - ecc_key* ecc; +#endif /* WOLFSSL_SHA512 */ - if (pkey == NULL || key == NULL || key->internal == NULL) - return WOLFSSL_FAILURE; +#ifdef WOLFSSL_SHA3 +#ifndef WOLFSSL_NOSHA3_224 + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_224(void) + { + WOLFSSL_ENTER("EVP_sha3_224"); + return EVP_get_digestbyname("SHA3_224"); + } +#endif /* WOLFSSL_NOSHA3_224 */ - ecc = (ecc_key*)key->internal; - if (ecc->type == ECC_PRIVATEKEY || ecc->type == ECC_PRIVATEKEY_ONLY) { -#ifdef HAVE_PKCS8 - if (key->pkcs8HeaderSz) { - /* when key has pkcs8 header the pkey should too */ - if (wc_EccKeyToPKCS8(ecc, NULL, (word32*)&derSz) == LENGTH_ONLY_E) { - derBuf = (byte*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); - if (derBuf) { - if (wc_EccKeyToPKCS8(ecc, derBuf, (word32*)&derSz) >= 0) { - if (pkey->pkey.ptr) { - XFREE(pkey->pkey.ptr, pkey->heap, DYNAMIC_TYPE_OPENSSL); - } - pkey->pkey_sz = (int)derSz; - pkey->pkey.ptr = (char*)derBuf; - pkey->pkcs8HeaderSz = key->pkcs8HeaderSz; - return WOLFSSL_SUCCESS; - } - else { - XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_OPENSSL); - derBuf = NULL; - } - } - } - } - else -#endif /* HAVE_PKCS8 */ - { - if (ecc->type == ECC_PRIVATEKEY_ONLY) { - if (wc_ecc_make_pub(ecc, NULL) != MP_OKAY) { - return WOLFSSL_FAILURE; - } - } - /* if not, the pkey will be traditional ecc key */ - if ((derSz = wc_EccKeyDerSize(ecc, 1)) > 0) { - derBuf = (byte*)XMALLOC(derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); - if (derBuf) { - if (wc_EccKeyToDer(ecc, derBuf, derSz) >= 0) { - if (pkey->pkey.ptr) { - XFREE(pkey->pkey.ptr, pkey->heap, DYNAMIC_TYPE_OPENSSL); - } - pkey->pkey_sz = (int)derSz; - pkey->pkey.ptr = (char*)derBuf; - return WOLFSSL_SUCCESS; - } - else { - XFREE(derBuf, pkey->heap, DYNAMIC_TYPE_OPENSSL); - derBuf = NULL; - } - } - } - } +#ifndef WOLFSSL_NOSHA3_256 + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_256(void) + { + WOLFSSL_ENTER("EVP_sha3_256"); + return EVP_get_digestbyname("SHA3_256"); } - else if (ecc->type == ECC_PUBLICKEY) { - if ((derSz = (word32)wc_EccPublicKeyDerSize(ecc, 1)) > 0) { - derBuf = (byte*)XREALLOC(pkey->pkey.ptr, derSz, NULL, - DYNAMIC_TYPE_OPENSSL); - if (derBuf != NULL) { - pkey->pkey.ptr = (char*)derBuf; - if ((derSz = wc_EccPublicKeyToDer(ecc, derBuf, derSz, 1)) < 0) { - XFREE(derBuf, NULL, DYNAMIC_TYPE_OPENSSL); - derBuf = NULL; - } - } - } +#endif /* WOLFSSL_NOSHA3_256 */ + +#ifndef WOLFSSL_NOSHA3_384 + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_384(void) + { + WOLFSSL_ENTER("EVP_sha3_384"); + return EVP_get_digestbyname("SHA3_384"); } - if (derBuf != NULL) { - pkey->pkey_sz = (int)derSz; - return WOLFSSL_SUCCESS; +#endif /* WOLFSSL_NOSHA3_384 */ + +#ifndef WOLFSSL_NOSHA3_512 + const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_512(void) + { + WOLFSSL_ENTER("EVP_sha3_512"); + return EVP_get_digestbyname("SHA3_512"); } - else { - return WOLFSSL_FAILURE; +#endif /* WOLFSSL_NOSHA3_512 */ + +#ifdef WOLFSSL_SHAKE128 + const WOLFSSL_EVP_MD* wolfSSL_EVP_shake128(void) + { + WOLFSSL_ENTER("EVP_shake128"); + return EVP_get_digestbyname("SHAKE128"); } -} +#endif /* WOLFSSL_SHAKE128 */ -int wolfSSL_EVP_PKEY_set1_EC_KEY(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_EC_KEY *key) -{ -#ifdef HAVE_ECC - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_set1_EC_KEY"); - if (pkey == NULL || key == NULL) - return WOLFSSL_FAILURE; - clearEVPPkeyKeys(pkey); - if (wolfSSL_EC_KEY_up_ref(key) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_EC_KEY_up_ref failed"); - return WOLFSSL_FAILURE; +#ifdef WOLFSSL_SHAKE256 + const WOLFSSL_EVP_MD* wolfSSL_EVP_shake256(void) + { + WOLFSSL_ENTER("EVP_shake256"); + return EVP_get_digestbyname("SHAKE256"); } - pkey->ecc = key; - pkey->ownEcc = 1; /* pkey needs to call free on key */ - pkey->type = EVP_PKEY_EC; - return ECC_populate_EVP_PKEY(pkey, key); -#else - (void)pkey; - (void)key; - return WOLFSSL_FAILURE; -#endif /* HAVE_ECC */ -} +#endif /* WOLFSSL_SHAKE256 */ + +#endif /* WOLFSSL_SHA3 */ -void* wolfSSL_EVP_X_STATE(const WOLFSSL_EVP_CIPHER_CTX* ctx) -{ - WOLFSSL_MSG("wolfSSL_EVP_X_STATE"); - if (ctx) { - switch (ctx->cipherType) { - case ARC4_TYPE: - WOLFSSL_MSG("returning arc4 state"); - return (void*)&ctx->cipher.arc4.x; - default: - WOLFSSL_MSG("bad x state type"); - return 0; + WOLFSSL_EVP_MD_CTX *wolfSSL_EVP_MD_CTX_new(void) + { + WOLFSSL_EVP_MD_CTX* ctx; + WOLFSSL_ENTER("EVP_MD_CTX_new"); + ctx = (WOLFSSL_EVP_MD_CTX*)XMALLOC(sizeof *ctx, NULL, + DYNAMIC_TYPE_OPENSSL); + if (ctx){ + wolfSSL_EVP_MD_CTX_init(ctx); } + return ctx; } - return NULL; -} -int wolfSSL_EVP_PKEY_assign_EC_KEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY* key) -{ - int ret; + void wolfSSL_EVP_MD_CTX_free(WOLFSSL_EVP_MD_CTX *ctx) + { + if (ctx) { + WOLFSSL_ENTER("EVP_MD_CTX_free"); + wolfSSL_EVP_MD_CTX_cleanup(ctx); + XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL); + } + } - if (pkey == NULL || key == NULL) - return WOLFSSL_FAILURE; + /* returns the NID of message digest used by the ctx */ + int wolfSSL_EVP_MD_CTX_type(const WOLFSSL_EVP_MD_CTX *ctx) + { + WOLFSSL_ENTER("EVP_MD_CTX_type"); - /* try and populate public pkey_sz and pkey.ptr */ - ret = ECC_populate_EVP_PKEY(pkey, key); - if (ret == WOLFSSL_SUCCESS) { /* take ownership of key if can be used */ - clearEVPPkeyKeys(pkey); /* clear out any previous keys */ + if (ctx) { + const struct s_ent *ent; - pkey->type = EVP_PKEY_EC; - pkey->ecc = key; - pkey->ownEcc = 1; - } - return ret; -} -#endif /* HAVE_ECC */ + if (ctx->isHMAC) { + return NID_hmac; + } -#ifndef NO_WOLFSSL_STUB -const WOLFSSL_EVP_MD* wolfSSL_EVP_ripemd160(void) -{ - WOLFSSL_MSG("wolfSSL_ripemd160"); - WOLFSSL_STUB("EVP_ripemd160"); - return NULL; -} -#endif + for(ent = md_tbl; ent->name != NULL; ent++) { + if (ctx->macType == ent->macType) { + return ent->nid; + } + } + /* Return whatever we got */ + return ctx->macType; + } + return 0; + } -#endif -int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) -{ - WOLFSSL_MSG("wolfSSL_EVP_MD_block_size"); + /* returns digest size */ + int wolfSSL_EVP_MD_CTX_size(const WOLFSSL_EVP_MD_CTX *ctx) { + return(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(ctx))); + } + /* returns block size */ + int wolfSSL_EVP_MD_CTX_block_size(const WOLFSSL_EVP_MD_CTX *ctx) { + return(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(ctx))); + } - if (type == NULL) { - WOLFSSL_MSG("No md type arg"); - return BAD_FUNC_ARG; + void wolfSSL_EVP_MD_CTX_init(WOLFSSL_EVP_MD_CTX* ctx) + { + WOLFSSL_ENTER("EVP_CIPHER_MD_CTX_init"); + XMEMSET(ctx, 0, sizeof(WOLFSSL_EVP_MD_CTX)); } -#ifndef NO_SHA - if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { - return WC_SHA_BLOCK_SIZE; - } else -#endif -#ifndef NO_SHA256 - if (XSTRCMP(type, "SHA256") == 0) { - return WC_SHA256_BLOCK_SIZE; - } else -#endif -#ifndef NO_MD4 - if (XSTRCMP(type, "MD4") == 0) { - return MD4_BLOCK_SIZE; - } else -#endif -#ifndef NO_MD5 - if (XSTRCMP(type, "MD5") == 0) { - return WC_MD5_BLOCK_SIZE; - } else -#endif -#ifdef WOLFSSL_SHA224 - if (XSTRCMP(type, "SHA224") == 0) { - return WC_SHA224_BLOCK_SIZE; - } else -#endif -#ifdef WOLFSSL_SHA384 - if (XSTRCMP(type, "SHA384") == 0) { - return WC_SHA384_BLOCK_SIZE; - } else -#endif -#ifdef WOLFSSL_SHA512 - if (XSTRCMP(type, "SHA512") == 0) { - return WC_SHA512_BLOCK_SIZE; - } else -#endif -#ifdef WOLFSSL_SHA3 -#ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(type, "SHA3_224") == 0) { - return WC_SHA3_224_BLOCK_SIZE; - } else -#endif -#ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(type, "SHA3_256") == 0) { - return WC_SHA3_256_BLOCK_SIZE; - } else -#endif -#ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(type, "SHA3_384") == 0) { - return WC_SHA3_384_BLOCK_SIZE; - } else -#endif -#ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(type, "SHA3_512") == 0) { - return WC_SHA3_512_BLOCK_SIZE; + const WOLFSSL_EVP_MD *wolfSSL_EVP_MD_CTX_md(const WOLFSSL_EVP_MD_CTX *ctx) + { + const struct s_ent *ent; + if (ctx == NULL) + return NULL; + WOLFSSL_ENTER("EVP_MD_CTX_md"); + if (ctx->isHMAC) { + return "HMAC"; + } + for(ent = md_tbl; ent->name != NULL; ent++) { + if(ctx->macType == ent->macType) { + return (const WOLFSSL_EVP_MD *)ent->name; + } + } + return (WOLFSSL_EVP_MD *)NULL; } -#endif -#endif /* WOLFSSL_SHA3 */ - return BAD_FUNC_ARG; -} + /* return alias name if has + * @param n message digest type name + * @return alias name, otherwise NULL + */ + static const char* hasAliasName(const char* n) + { -int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) -{ - WOLFSSL_MSG("wolfSSL_EVP_MD_size"); + const char* aliasnm = NULL; + const struct alias *al; - if (type == NULL) { - WOLFSSL_MSG("No md type arg"); - return BAD_FUNC_ARG; - } + for (al = digest_alias_tbl; al->name != NULL; al++) + if(XSTRCMP(n, al->name) == 0) { + aliasnm = al->alias; + break; + } -#ifndef NO_SHA - if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { - return WC_SHA_DIGEST_SIZE; - } else -#endif -#ifndef NO_SHA256 - if (XSTRCMP(type, "SHA256") == 0) { - return WC_SHA256_DIGEST_SIZE; - } else -#endif -#ifndef NO_MD4 - if (XSTRCMP(type, "MD4") == 0) { - return MD4_DIGEST_SIZE; - } else -#endif -#ifndef NO_MD5 - if (XSTRCMP(type, "MD5") == 0) { - return WC_MD5_DIGEST_SIZE; - } else -#endif -#ifdef WOLFSSL_SHA224 - if (XSTRCMP(type, "SHA224") == 0) { - return WC_SHA224_DIGEST_SIZE; - } else -#endif -#ifdef WOLFSSL_SHA384 - if (XSTRCMP(type, "SHA384") == 0) { - return WC_SHA384_DIGEST_SIZE; - } else -#endif -#ifdef WOLFSSL_SHA512 - if (XSTRCMP(type, "SHA512") == 0) { - return WC_SHA512_DIGEST_SIZE; - } else -#ifndef WOLFSSL_NOSHA512_224 - if (XSTRCMP(type, "SHA512_224") == 0) { - return WC_SHA512_224_DIGEST_SIZE; - } else -#endif -#ifndef WOLFSSL_NOSHA512_256 - if (XSTRCMP(type, "SHA512_256") == 0) { - return WC_SHA512_256_DIGEST_SIZE; - } else -#endif -#endif -#ifdef WOLFSSL_SHA3 -#ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(type, "SHA3_224") == 0) { - return WC_SHA3_224_DIGEST_SIZE; - } else -#endif -#ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(type, "SHA3_256") == 0) { - return WC_SHA3_256_DIGEST_SIZE; - } else -#endif -#ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(type, "SHA3_384") == 0) { - return WC_SHA3_384_DIGEST_SIZE; - } else -#endif -#ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(type, "SHA3_512") == 0) { - return WC_SHA3_512_DIGEST_SIZE; + return aliasnm; } -#endif -#endif /* WOLFSSL_SHA3 */ - return BAD_FUNC_ARG; -} -#ifdef OPENSSL_EXTRA -int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) -{ - int ret = BAD_FUNC_ARG; + struct do_all_md { + void *arg; + void (*fn) (const WOLFSSL_EVP_MD *m, + const char* from, const char* to, void *arg); + }; + + /* do all md algorithm + * @param nm a pointer to WOLFSSL_OBJ_NAME + * @param arg arguments to pass to the callback + * @return none + */ + static void md_do_all_func(const WOLFSSL_OBJ_NAME* nm, void* arg) + { + struct do_all_md *md = (struct do_all_md*)arg; + + const struct s_ent *ent; - WOLFSSL_ENTER("wolfSSL_EVP_MD_pkey_type"); + /* sanity check */ + if (md == NULL || nm == NULL || md->fn == NULL || + nm->type != WOLFSSL_OBJ_NAME_TYPE_MD_METH) + return; - if (type != NULL) { - if (XSTRCMP(type, "MD5") == 0) { - ret = NID_md5WithRSAEncryption; - } - else if (XSTRCMP(type, "SHA1") == 0) { - ret = NID_sha1WithRSAEncryption; - } - else if (XSTRCMP(type, "SHA224") == 0) { - ret = NID_sha224WithRSAEncryption; - } - else if (XSTRCMP(type, "SHA256") == 0) { - ret = NID_sha256WithRSAEncryption; - } - else if (XSTRCMP(type, "SHA384") == 0) { - ret = NID_sha384WithRSAEncryption; - } - else if (XSTRCMP(type, "SHA512") == 0) { - ret = NID_sha512WithRSAEncryption; + /* loop all md */ + for (ent = md_tbl; ent->name != NULL; ent++){ + /* check if the md has alias */ + if(hasAliasName(ent->name) != NULL) { + md->fn(NULL, ent->name, ent->name, md->arg); + } + else { + md->fn(ent->name, ent->name, NULL, md->arg); + } } } - WOLFSSL_LEAVE("wolfSSL_EVP_MD_pkey_type", ret); + /* call md_do_all function to do all md algorithm via a callback function + * @param fn a callback function to be called with all 'md' + * @param args arguments to pass to the callback + * @return none + */ + void wolfSSL_EVP_MD_do_all(void (*fn) (const WOLFSSL_EVP_MD *m, + const char* from, const char* to, void* xx), void* args) + { + struct do_all_md md; - return ret; -} + md.fn = fn; + md.arg = args; + wolfSSL_OBJ_NAME_do_all(WOLFSSL_OBJ_NAME_TYPE_MD_METH, + md_do_all_func, &md); + } + /* call "fn" based on OBJ_NAME type + * @param type OBJ_NAME type + * @param fn a callback function + * @param args arguments to pass to the callback + * @return none + */ + void wolfSSL_OBJ_NAME_do_all(int type, + void (*fn)(const WOLFSSL_OBJ_NAME*, void* arg), void* arg) + { + WOLFSSL_OBJ_NAME objnm; -int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) -{ - WOLFSSL_MSG("wolfSSL_EVP_CIPHER_CTX_iv_length"); + /* sanity check */ + if (!fn) + return; - switch (ctx->cipherType) { + objnm.type = type; -#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : - WOLFSSL_MSG("AES CBC"); - return AES_BLOCK_SIZE; -#endif -#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ - (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) -#ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : - WOLFSSL_MSG("AES GCM"); - if (ctx->ivSz != 0) { - return ctx->ivSz; - } - return GCM_NONCE_MID_SZ; -#endif -#ifdef HAVE_AESCCM - case AES_128_CCM_TYPE : - case AES_192_CCM_TYPE : - case AES_256_CCM_TYPE : - WOLFSSL_MSG("AES CCM"); - if (ctx->ivSz != 0) { - return ctx->ivSz; - } - return CCM_NONCE_MIN_SZ; -#endif -#endif /* (HAVE_FIPS && !HAVE_SELFTEST) || HAVE_FIPS_VERSION >= 2 */ -#ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : - WOLFSSL_MSG("AES CTR"); - return AES_BLOCK_SIZE; -#endif -#ifndef NO_DES3 - case DES_CBC_TYPE : - WOLFSSL_MSG("DES CBC"); - return DES_BLOCK_SIZE; + switch(type) { + case WOLFSSL_OBJ_NAME_TYPE_MD_METH: + fn(&objnm, arg); + break; + case WOLFSSL_OBJ_NAME_TYPE_CIPHER_METH: + case WOLFSSL_OBJ_NAME_TYPE_PKEY_METH: + case WOLFSSL_OBJ_NAME_TYPE_COMP_METH: + case WOLFSSL_OBJ_NAME_TYPE_NUM: + WOLFSSL_MSG("not implemented"); + FALL_THROUGH; + case WOLFSSL_OBJ_NAME_TYPE_UNDEF: + default: + break; + } + } - case DES_EDE3_CBC_TYPE : - WOLFSSL_MSG("DES EDE3 CBC"); - return DES_BLOCK_SIZE; -#endif -#ifndef NO_RC4 - case ARC4_TYPE : - WOLFSSL_MSG("ARC4"); - return 0; -#endif -#ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - WOLFSSL_MSG("AES CFB1"); - return AES_BLOCK_SIZE; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - WOLFSSL_MSG("AES CFB8"); - return AES_BLOCK_SIZE; -#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: - WOLFSSL_MSG("AES CFB128"); - return AES_BLOCK_SIZE; -#endif /* WOLFSSL_AES_CFB */ -#if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: - WOLFSSL_MSG("AES OFB"); - return AES_BLOCK_SIZE; -#endif /* WOLFSSL_AES_OFB */ -#ifdef WOLFSSL_AES_XTS - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: - WOLFSSL_MSG("AES XTS"); - return AES_BLOCK_SIZE; -#endif /* WOLFSSL_AES_XTS */ -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: - WOLFSSL_MSG("CHACHA20 POLY1305"); - return CHACHA20_POLY1305_AEAD_IV_SIZE; -#endif /* HAVE_CHACHA HAVE_POLY1305 */ -#ifdef HAVE_CHACHA - case CHACHA20_TYPE: - WOLFSSL_MSG("CHACHA20"); - return WOLFSSL_EVP_CHACHA_IV_BYTES; -#endif /* HAVE_CHACHA */ + int wolfSSL_EVP_MD_CTX_cleanup(WOLFSSL_EVP_MD_CTX* ctx) + { + int ret = WOLFSSL_SUCCESS; + WOLFSSL_ENTER("wolfSSL_EVP_MD_CTX_cleanup"); + #ifdef OPENSSL_EXTRA + if (ctx->pctx != NULL) + wolfSSL_EVP_PKEY_CTX_free(ctx->pctx); + #endif + + if (ctx->isHMAC) { + wc_HmacFree(&ctx->hash.hmac); + } + else { + switch (ctx->macType) { + case WC_HASH_TYPE_MD5: + #ifndef NO_MD5 + wc_Md5Free((wc_Md5*)&ctx->hash.digest); + #endif /* !NO_MD5 */ + break; + case WC_HASH_TYPE_SHA: + #ifndef NO_SHA + wc_ShaFree((wc_Sha*)&ctx->hash.digest); + #endif /* !NO_SHA */ + break; + case WC_HASH_TYPE_SHA224: + #ifdef WOLFSSL_SHA224 + wc_Sha224Free((wc_Sha224*)&ctx->hash.digest); + #endif /* WOLFSSL_SHA224 */ + break; + case WC_HASH_TYPE_SHA256: + #ifndef NO_SHA256 + wc_Sha256Free((wc_Sha256*)&ctx->hash.digest); + #endif /* !NO_SHA256 */ + break; + case WC_HASH_TYPE_SHA384: + #ifdef WOLFSSL_SHA384 + wc_Sha384Free((wc_Sha384*)&ctx->hash.digest); + #endif /* WOLFSSL_SHA384 */ + break; + case WC_HASH_TYPE_SHA512: + #ifdef WOLFSSL_SHA512 + wc_Sha512Free((wc_Sha512*)&ctx->hash.digest); + #endif /* WOLFSSL_SHA512 */ + break; + #ifndef WOLFSSL_NOSHA512_224 + case WC_HASH_TYPE_SHA512_224: + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) + wc_Sha512_224Free((wc_Sha512*)&ctx->hash.digest); + #endif + break; + #endif /* !WOLFSSL_NOSHA512_224 */ + #ifndef WOLFSSL_NOSHA512_256 + case WC_HASH_TYPE_SHA512_256: + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) + wc_Sha512_256Free((wc_Sha512*)&ctx->hash.digest); + #endif + break; + #endif /* !WOLFSSL_NOSHA512_256 */ + case WC_HASH_TYPE_SHA3_224: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) + wc_Sha3_224_Free((wc_Sha3*)&ctx->hash.digest); + #endif + break; + case WC_HASH_TYPE_SHA3_256: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) + wc_Sha3_256_Free((wc_Sha3*)&ctx->hash.digest); + #endif + break; + case WC_HASH_TYPE_SHA3_384: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) + wc_Sha3_384_Free((wc_Sha3*)&ctx->hash.digest); + #endif + break; + case WC_HASH_TYPE_SHA3_512: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) + wc_Sha3_512_Free((wc_Sha3*)&ctx->hash.digest); + #endif + break; + case WC_HASH_TYPE_NONE: + /* Not an error since an unused struct could be free'd or + * reset. */ + break; + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD4: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) + case WC_HASH_TYPE_SHAKE128: + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) + case WC_HASH_TYPE_SHAKE256: + #endif + default: + ret = WOLFSSL_FAILURE; + break; + } + } + ForceZero(ctx, sizeof(*ctx)); + ctx->macType = WC_HASH_TYPE_NONE; + return ret; + } - case NULL_CIPHER_TYPE : - WOLFSSL_MSG("NULL"); - return 0; + /* WOLFSSL_SUCCESS on ok */ + int wolfSSL_EVP_DigestInit(WOLFSSL_EVP_MD_CTX* ctx, + const WOLFSSL_EVP_MD* md) + { + int ret = WOLFSSL_SUCCESS; - default: { - WOLFSSL_MSG("bad type"); + WOLFSSL_ENTER("EVP_DigestInit"); + + if (ctx == NULL) { + return BAD_FUNC_ARG; } - } - return 0; -} -int wolfSSL_EVP_CIPHER_iv_length(const WOLFSSL_EVP_CIPHER* cipher) -{ - const char *name = (const char *)cipher; - WOLFSSL_MSG("wolfSSL_EVP_CIPHER_iv_length"); -#ifndef NO_AES -#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - #ifdef WOLFSSL_AES_128 - if (XSTRCMP(name, EVP_AES_128_CBC) == 0) - return AES_BLOCK_SIZE; + #ifdef WOLFSSL_ASYNC_CRYPT + /* compile-time validation of ASYNC_CTX_SIZE */ + typedef char async_test[WC_ASYNC_DEV_SIZE >= sizeof(WC_ASYNC_DEV) ? + 1 : -1]; + (void)sizeof(async_test); #endif - #ifdef WOLFSSL_AES_192 - if (XSTRCMP(name, EVP_AES_192_CBC) == 0) - return AES_BLOCK_SIZE; + + /* Set to 0 if no match */ + ctx->macType = EvpMd2MacType(md); + if (md == NULL) { + XMEMSET(&ctx->hash.digest, 0, sizeof(WOLFSSL_Hasher)); + } else + #ifndef NO_SHA + if ((XSTRCMP(md, "SHA") == 0) || (XSTRCMP(md, "SHA1") == 0)) { + ret = wolfSSL_SHA_Init(&(ctx->hash.digest.sha)); + } else #endif - #ifdef WOLFSSL_AES_256 - if (XSTRCMP(name, EVP_AES_256_CBC) == 0) - return AES_BLOCK_SIZE; + #ifndef NO_SHA256 + if (XSTRCMP(md, "SHA256") == 0) { + ret = wolfSSL_SHA256_Init(&(ctx->hash.digest.sha256)); + } else #endif -#endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ -#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ - (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) -#ifdef HAVE_AESGCM - #ifdef WOLFSSL_AES_128 - if (XSTRCMP(name, EVP_AES_128_GCM) == 0) - return GCM_NONCE_MID_SZ; + #ifdef WOLFSSL_SHA224 + if (XSTRCMP(md, "SHA224") == 0) { + ret = wolfSSL_SHA224_Init(&(ctx->hash.digest.sha224)); + } else #endif - #ifdef WOLFSSL_AES_192 - if (XSTRCMP(name, EVP_AES_192_GCM) == 0) - return GCM_NONCE_MID_SZ; + #ifdef WOLFSSL_SHA384 + if (XSTRCMP(md, "SHA384") == 0) { + ret = wolfSSL_SHA384_Init(&(ctx->hash.digest.sha384)); + } else #endif - #ifdef WOLFSSL_AES_256 - if (XSTRCMP(name, EVP_AES_256_GCM) == 0) - return GCM_NONCE_MID_SZ; + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) + if (XSTRCMP(md, "SHA512_224") == 0) { + ret = wolfSSL_SHA512_224_Init(&(ctx->hash.digest.sha512)); + } else #endif -#endif /* HAVE_AESGCM */ -#ifdef HAVE_AESCCM - #ifdef WOLFSSL_AES_128 - if (XSTRCMP(name, EVP_AES_128_CCM) == 0) - return CCM_NONCE_MIN_SZ; + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) + if (XSTRCMP(md, "SHA512_256") == 0) { + ret = wolfSSL_SHA512_256_Init(&(ctx->hash.digest.sha512)); + } else #endif - #ifdef WOLFSSL_AES_192 - if (XSTRCMP(name, EVP_AES_192_CCM) == 0) - return CCM_NONCE_MIN_SZ; + #ifdef WOLFSSL_SHA512 + if (XSTRCMP(md, "SHA512") == 0) { + ret = wolfSSL_SHA512_Init(&(ctx->hash.digest.sha512)); + } else #endif - #ifdef WOLFSSL_AES_256 - if (XSTRCMP(name, EVP_AES_256_CCM) == 0) - return CCM_NONCE_MIN_SZ; + #ifndef NO_MD4 + if (XSTRCMP(md, "MD4") == 0) { + wolfSSL_MD4_Init(&(ctx->hash.digest.md4)); + } else #endif -#endif /* HAVE_AESCCM */ -#endif /* (HAVE_FIPS && !HAVE_SELFTEST) || HAVE_FIPS_VERSION >= 2 */ -#ifdef WOLFSSL_AES_COUNTER - #ifdef WOLFSSL_AES_128 - if (XSTRCMP(name, EVP_AES_128_CTR) == 0) - return AES_BLOCK_SIZE; + #ifndef NO_MD5 + if (XSTRCMP(md, "MD5") == 0) { + ret = wolfSSL_MD5_Init(&(ctx->hash.digest.md5)); + } else #endif - #ifdef WOLFSSL_AES_192 - if (XSTRCMP(name, EVP_AES_192_CTR) == 0) - return AES_BLOCK_SIZE; +#ifdef WOLFSSL_SHA3 + #ifndef WOLFSSL_NOSHA3_224 + if (XSTRCMP(md, "SHA3_224") == 0) { + ret = wolfSSL_SHA3_224_Init(&(ctx->hash.digest.sha3_224)); + } else #endif - #ifdef WOLFSSL_AES_256 - if (XSTRCMP(name, EVP_AES_256_CTR) == 0) - return AES_BLOCK_SIZE; + #ifndef WOLFSSL_NOSHA3_256 + if (XSTRCMP(md, "SHA3_256") == 0) { + ret = wolfSSL_SHA3_256_Init(&(ctx->hash.digest.sha3_256)); + } else + #endif + #ifndef WOLFSSL_NOSHA3_384 + if (XSTRCMP(md, "SHA3_384") == 0) { + ret = wolfSSL_SHA3_384_Init(&(ctx->hash.digest.sha3_384)); + } else + #endif + #ifndef WOLFSSL_NOSHA3_512 + if (XSTRCMP(md, "SHA3_512") == 0) { + ret = wolfSSL_SHA3_512_Init(&(ctx->hash.digest.sha3_512)); + } else #endif #endif -#ifdef WOLFSSL_AES_XTS - #ifdef WOLFSSL_AES_128 - if (XSTRCMP(name, EVP_AES_128_XTS) == 0) - return AES_BLOCK_SIZE; - #endif /* WOLFSSL_AES_128 */ - - #ifdef WOLFSSL_AES_256 - if (XSTRCMP(name, EVP_AES_256_XTS) == 0) - return AES_BLOCK_SIZE; - #endif /* WOLFSSL_AES_256 */ -#endif /* WOLFSSL_AES_XTS */ - -#endif + { + ctx->macType = WC_HASH_TYPE_NONE; + return BAD_FUNC_ARG; + } -#ifndef NO_DES3 - if ((XSTRCMP(name, EVP_DES_CBC) == 0) || - (XSTRCMP(name, EVP_DES_EDE3_CBC) == 0)) { - return DES_BLOCK_SIZE; + return ret; } -#endif - -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (XSTRCMP(name, EVP_CHACHA20_POLY1305) == 0) - return CHACHA20_POLY1305_AEAD_IV_SIZE; -#endif - -#ifdef HAVE_CHACHA - if (XSTRCMP(name, EVP_CHACHA20) == 0) - return WOLFSSL_EVP_CHACHA_IV_BYTES; -#endif - (void)name; + /* WOLFSSL_SUCCESS on ok, WOLFSSL_FAILURE on failure */ + int wolfSSL_EVP_DigestUpdate(WOLFSSL_EVP_MD_CTX* ctx, const void* data, + size_t sz) + { + int ret = WOLFSSL_FAILURE; + enum wc_HashType macType; - return 0; -} + WOLFSSL_ENTER("EVP_DigestUpdate"); + macType = EvpMd2MacType(EVP_MD_CTX_md(ctx)); + switch (macType) { + case WC_HASH_TYPE_MD4: + #ifndef NO_MD4 + wolfSSL_MD4_Update((MD4_CTX*)&ctx->hash, data, + (unsigned long)sz); + ret = WOLFSSL_SUCCESS; + #endif + break; + case WC_HASH_TYPE_MD5: + #ifndef NO_MD5 + ret = wolfSSL_MD5_Update((MD5_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + case WC_HASH_TYPE_SHA: + #ifndef NO_SHA + ret = wolfSSL_SHA_Update((SHA_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + case WC_HASH_TYPE_SHA224: + #ifdef WOLFSSL_SHA224 + ret = wolfSSL_SHA224_Update((SHA224_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + case WC_HASH_TYPE_SHA256: + #ifndef NO_SHA256 + ret = wolfSSL_SHA256_Update((SHA256_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif /* !NO_SHA256 */ + break; + case WC_HASH_TYPE_SHA384: + #ifdef WOLFSSL_SHA384 + ret = wolfSSL_SHA384_Update((SHA384_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + case WC_HASH_TYPE_SHA512: + #ifdef WOLFSSL_SHA512 + ret = wolfSSL_SHA512_Update((SHA512_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif /* WOLFSSL_SHA512 */ + break; -int wolfSSL_EVP_X_STATE_LEN(const WOLFSSL_EVP_CIPHER_CTX* ctx) -{ - WOLFSSL_MSG("wolfSSL_EVP_X_STATE_LEN"); + #ifndef WOLFSSL_NOSHA512_224 + case WC_HASH_TYPE_SHA512_224: + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) + ret = wolfSSL_SHA512_224_Update((SHA512_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + #endif /* !WOLFSSL_NOSHA512_224 */ - if (ctx) { - switch (ctx->cipherType) { - case ARC4_TYPE: - WOLFSSL_MSG("returning arc4 state size"); - return sizeof(Arc4); + #ifndef WOLFSSL_NOSHA512_256 + case WC_HASH_TYPE_SHA512_256: + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) + ret = wolfSSL_SHA512_256_Update((SHA512_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif /* WOLFSSL_SHA512 */ + break; + #endif /* !WOLFSSL_NOSHA512_256 */ + case WC_HASH_TYPE_SHA3_224: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) + ret = wolfSSL_SHA3_224_Update((SHA3_224_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + case WC_HASH_TYPE_SHA3_256: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) + ret = wolfSSL_SHA3_256_Update((SHA3_256_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + case WC_HASH_TYPE_SHA3_384: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) + ret = wolfSSL_SHA3_384_Update((SHA3_384_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + case WC_HASH_TYPE_SHA3_512: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) + ret = wolfSSL_SHA3_512_Update((SHA3_512_CTX*)&ctx->hash, data, + (unsigned long)sz); + #endif + break; + case WC_HASH_TYPE_NONE: + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) + case WC_HASH_TYPE_SHAKE128: + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) + case WC_HASH_TYPE_SHAKE256: + #endif default: - WOLFSSL_MSG("bad x state type"); - return 0; + return WOLFSSL_FAILURE; } - } - - return 0; -} - - -/* return of pkey->type which will be EVP_PKEY_RSA for example. - * - * type type of EVP_PKEY - * - * returns type or if type is not found then NID_undef - */ -int wolfSSL_EVP_PKEY_type(int type) -{ - WOLFSSL_MSG("wolfSSL_EVP_PKEY_type"); - switch (type) { - case EVP_PKEY_RSA: - return EVP_PKEY_RSA; - case EVP_PKEY_DSA: - return EVP_PKEY_DSA; - case EVP_PKEY_EC: - return EVP_PKEY_EC; - case EVP_PKEY_DH: - return EVP_PKEY_DH; - default: - return NID_undef; + return ret; } -} - - -int wolfSSL_EVP_PKEY_id(const WOLFSSL_EVP_PKEY *pkey) -{ - if (pkey != NULL) - return pkey->type; - return 0; -} - - -int wolfSSL_EVP_PKEY_base_id(const WOLFSSL_EVP_PKEY *pkey) -{ - if (pkey == NULL) - return NID_undef; - return wolfSSL_EVP_PKEY_type(pkey->type); -} -int wolfSSL_EVP_PKEY_get_default_digest_nid(WOLFSSL_EVP_PKEY *pkey, int *pnid) -{ - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get_default_digest_nid"); + /* WOLFSSL_SUCCESS on ok */ + int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, + unsigned int* s) + { + int ret = WOLFSSL_FAILURE; + enum wc_HashType macType; - if (!pkey || !pnid) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } + WOLFSSL_ENTER("EVP_DigestFinal"); + macType = EvpMd2MacType(EVP_MD_CTX_md(ctx)); + switch (macType) { + case WC_HASH_TYPE_MD4: + #ifndef NO_MD4 + wolfSSL_MD4_Final(md, (MD4_CTX*)&ctx->hash); + if (s) *s = MD4_DIGEST_SIZE; + ret = WOLFSSL_SUCCESS; + #endif + break; + case WC_HASH_TYPE_MD5: + #ifndef NO_MD5 + ret = wolfSSL_MD5_Final(md, (MD5_CTX*)&ctx->hash); + if (s) *s = WC_MD5_DIGEST_SIZE; + #endif + break; + case WC_HASH_TYPE_SHA: + #ifndef NO_SHA + ret = wolfSSL_SHA_Final(md, (SHA_CTX*)&ctx->hash); + if (s) *s = WC_SHA_DIGEST_SIZE; + #endif + break; + case WC_HASH_TYPE_SHA224: + #ifdef WOLFSSL_SHA224 + ret = wolfSSL_SHA224_Final(md, (SHA224_CTX*)&ctx->hash); + if (s) *s = WC_SHA224_DIGEST_SIZE; + #endif + break; + case WC_HASH_TYPE_SHA256: + #ifndef NO_SHA256 + ret = wolfSSL_SHA256_Final(md, (SHA256_CTX*)&ctx->hash); + if (s) *s = WC_SHA256_DIGEST_SIZE; + #endif /* !NO_SHA256 */ + break; + case WC_HASH_TYPE_SHA384: + #ifdef WOLFSSL_SHA384 + ret = wolfSSL_SHA384_Final(md, (SHA384_CTX*)&ctx->hash); + if (s) *s = WC_SHA384_DIGEST_SIZE; + #endif + break; + case WC_HASH_TYPE_SHA512: + #ifdef WOLFSSL_SHA512 + ret = wolfSSL_SHA512_Final(md, (SHA512_CTX*)&ctx->hash); + if (s) *s = WC_SHA512_DIGEST_SIZE; + #endif /* WOLFSSL_SHA512 */ + break; + #ifndef WOLFSSL_NOSHA512_224 + case WC_HASH_TYPE_SHA512_224: + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) + ret = wolfSSL_SHA512_224_Final(md, (SHA512_CTX*)&ctx->hash); + if (s) *s = WC_SHA512_224_DIGEST_SIZE; + #endif + break; + #endif /* !WOLFSSL_NOSHA512_224 */ + #ifndef WOLFSSL_NOSHA512_256 + case WC_HASH_TYPE_SHA512_256: + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ + defined(WOLFSSL_SHA512) + ret = wolfSSL_SHA512_256_Final(md, (SHA512_CTX*)&ctx->hash); + if (s) *s = WC_SHA512_256_DIGEST_SIZE; + #endif + break; + #endif /* !WOLFSSL_NOSHA512_256 */ + case WC_HASH_TYPE_SHA3_224: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) + ret = wolfSSL_SHA3_224_Final(md, (SHA3_224_CTX*)&ctx->hash); + if (s) *s = WC_SHA3_224_DIGEST_SIZE; + #endif + break; + case WC_HASH_TYPE_SHA3_256: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) + ret = wolfSSL_SHA3_256_Final(md, (SHA3_256_CTX*)&ctx->hash); + if (s) *s = WC_SHA3_256_DIGEST_SIZE; + #endif + break; + case WC_HASH_TYPE_SHA3_384: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) + ret = wolfSSL_SHA3_384_Final(md, (SHA3_384_CTX*)&ctx->hash); + if (s) *s = WC_SHA3_384_DIGEST_SIZE; + #endif + break; + case WC_HASH_TYPE_SHA3_512: + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) + ret = wolfSSL_SHA3_512_Final(md, (SHA3_512_CTX*)&ctx->hash); + if (s) *s = WC_SHA3_512_DIGEST_SIZE; + #endif + break; + case WC_HASH_TYPE_NONE: + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) + case WC_HASH_TYPE_SHAKE128: + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) + case WC_HASH_TYPE_SHAKE256: + #endif + default: + return WOLFSSL_FAILURE; + } - switch (pkey->type) { - case EVP_PKEY_HMAC: -#ifndef NO_DSA - case EVP_PKEY_DSA: -#endif -#ifndef NO_RSA - case EVP_PKEY_RSA: -#endif -#ifdef HAVE_ECC - case EVP_PKEY_EC: -#endif - *pnid = NID_sha256; - return WOLFSSL_SUCCESS; - default: - return WOLFSSL_FAILURE; + return ret; } -} -#if defined(OPENSSL_ALL) || defined(WOLFSSL_WPAS_SMALL) -WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKCS82PKEY(const WOLFSSL_PKCS8_PRIV_KEY_INFO* p8) -{ - if (p8 == NULL || p8->pkey.ptr == NULL) { - return NULL; + /* WOLFSSL_SUCCESS on ok */ + int wolfSSL_EVP_DigestFinal_ex(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, + unsigned int* s) + { + WOLFSSL_ENTER("EVP_DigestFinal_ex"); + return EVP_DigestFinal(ctx, md, s); } - return wolfSSL_d2i_PrivateKey_EVP(NULL, (unsigned char**)&p8->pkey.ptr, - p8->pkey_sz); -} - -/* in wolf PKCS8_PRIV_KEY_INFO and WOLFSSL_EVP_PKEY are same type */ -/* this function just casts and returns pointer */ -WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_EVP_PKEY2PKCS8(const WOLFSSL_EVP_PKEY* pkey) -{ - return (WOLFSSL_PKCS8_PRIV_KEY_INFO*)pkey; -} -#endif + void wolfSSL_EVP_cleanup(void) + { + /* nothing to do here */ + } -/* increments ref count of WOLFSSL_EVP_PKEY. Return 1 on success, 0 on error */ -int wolfSSL_EVP_PKEY_up_ref(WOLFSSL_EVP_PKEY* pkey) +const WOLFSSL_EVP_MD* wolfSSL_EVP_get_digestbynid(int id) { - if (pkey) { - int ret; - wolfSSL_RefInc(&pkey->ref, &ret); - #ifdef WOLFSSL_REFCNT_ERROR_RETURN - if (ret != 0) { - WOLFSSL_MSG("Failed to lock pkey mutex"); - } - #else - (void)ret; - #endif + WOLFSSL_MSG("wolfSSL_get_digestbynid"); - return WOLFSSL_SUCCESS; + switch(id) { +#ifndef NO_MD5 + case NID_md5: + return wolfSSL_EVP_md5(); +#endif +#ifndef NO_SHA + case NID_sha1: + return wolfSSL_EVP_sha1(); +#endif +#ifdef WOLFSSL_SHA224 + case NID_sha224: + return wolfSSL_EVP_sha224(); +#endif +#ifndef NO_SHA256 + case NID_sha256: + return wolfSSL_EVP_sha256(); +#endif +#ifdef WOLFSSL_SHA384 + case NID_sha384: + return wolfSSL_EVP_sha384(); +#endif +#ifdef WOLFSSL_SHA512 + case NID_sha512: + return wolfSSL_EVP_sha512(); +#endif + default: + WOLFSSL_MSG("Bad digest id value"); } - return WOLFSSL_FAILURE; + return NULL; } - -#ifndef NO_RSA -int wolfSSL_EVP_PKEY_assign_RSA(EVP_PKEY* pkey, WOLFSSL_RSA* key) +int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) { - if (pkey == NULL || key == NULL) - return WOLFSSL_FAILURE; + WOLFSSL_MSG("wolfSSL_EVP_MD_block_size"); - clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_RSA; - pkey->rsa = key; - pkey->ownRsa = 1; + if (type == NULL) { + WOLFSSL_MSG("No md type arg"); + return BAD_FUNC_ARG; + } - /* try and populate pkey_sz and pkey.ptr */ - if (key->internal) { - RsaKey* rsa = (RsaKey*)key->internal; - int ret = wc_RsaKeyToDer(rsa, NULL, 0); - if (ret > 0) { - int derSz = ret; - byte* derBuf = (byte*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (derBuf) { - ret = wc_RsaKeyToDer(rsa, derBuf, derSz); - if (ret >= 0) { - pkey->pkey_sz = ret; - pkey->pkey.ptr = (char*)derBuf; - } - else { /* failure - okay to ignore */ - XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - derBuf = NULL; - } - } - } +#ifndef NO_SHA + if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { + return WC_SHA_BLOCK_SIZE; + } else +#endif +#ifndef NO_SHA256 + if (XSTRCMP(type, "SHA256") == 0) { + return WC_SHA256_BLOCK_SIZE; + } else +#endif +#ifndef NO_MD4 + if (XSTRCMP(type, "MD4") == 0) { + return MD4_BLOCK_SIZE; + } else +#endif +#ifndef NO_MD5 + if (XSTRCMP(type, "MD5") == 0) { + return WC_MD5_BLOCK_SIZE; + } else +#endif +#ifdef WOLFSSL_SHA224 + if (XSTRCMP(type, "SHA224") == 0) { + return WC_SHA224_BLOCK_SIZE; + } else +#endif +#ifdef WOLFSSL_SHA384 + if (XSTRCMP(type, "SHA384") == 0) { + return WC_SHA384_BLOCK_SIZE; + } else +#endif +#ifdef WOLFSSL_SHA512 + if (XSTRCMP(type, "SHA512") == 0) { + return WC_SHA512_BLOCK_SIZE; + } else +#endif +#ifdef WOLFSSL_SHA3 +#ifndef WOLFSSL_NOSHA3_224 + if (XSTRCMP(type, "SHA3_224") == 0) { + return WC_SHA3_224_BLOCK_SIZE; + } else +#endif +#ifndef WOLFSSL_NOSHA3_256 + if (XSTRCMP(type, "SHA3_256") == 0) { + return WC_SHA3_256_BLOCK_SIZE; + } else +#endif +#ifndef WOLFSSL_NOSHA3_384 + if (XSTRCMP(type, "SHA3_384") == 0) { + return WC_SHA3_384_BLOCK_SIZE; + } else +#endif +#ifndef WOLFSSL_NOSHA3_512 + if (XSTRCMP(type, "SHA3_512") == 0) { + return WC_SHA3_512_BLOCK_SIZE; } +#endif +#endif /* WOLFSSL_SHA3 */ - return WOLFSSL_SUCCESS; + return BAD_FUNC_ARG; } -#endif /* !NO_RSA */ -#ifndef NO_DSA -int wolfSSL_EVP_PKEY_assign_DSA(EVP_PKEY* pkey, WOLFSSL_DSA* key) +int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) { - if (pkey == NULL || key == NULL) - return WOLFSSL_FAILURE; - - clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_DSA; - pkey->dsa = key; - pkey->ownDsa = 1; - - return WOLFSSL_SUCCESS; -} -#endif /* !NO_DSA */ + WOLFSSL_MSG("wolfSSL_EVP_MD_size"); -#ifndef NO_DH -int wolfSSL_EVP_PKEY_assign_DH(EVP_PKEY* pkey, WOLFSSL_DH* key) -{ - if (pkey == NULL || key == NULL) - return WOLFSSL_FAILURE; + if (type == NULL) { + WOLFSSL_MSG("No md type arg"); + return BAD_FUNC_ARG; + } - clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_DH; - pkey->dh = key; - pkey->ownDh = 1; +#ifndef NO_SHA + if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { + return WC_SHA_DIGEST_SIZE; + } else +#endif +#ifndef NO_SHA256 + if (XSTRCMP(type, "SHA256") == 0) { + return WC_SHA256_DIGEST_SIZE; + } else +#endif +#ifndef NO_MD4 + if (XSTRCMP(type, "MD4") == 0) { + return MD4_DIGEST_SIZE; + } else +#endif +#ifndef NO_MD5 + if (XSTRCMP(type, "MD5") == 0) { + return WC_MD5_DIGEST_SIZE; + } else +#endif +#ifdef WOLFSSL_SHA224 + if (XSTRCMP(type, "SHA224") == 0) { + return WC_SHA224_DIGEST_SIZE; + } else +#endif +#ifdef WOLFSSL_SHA384 + if (XSTRCMP(type, "SHA384") == 0) { + return WC_SHA384_DIGEST_SIZE; + } else +#endif +#ifdef WOLFSSL_SHA512 + if (XSTRCMP(type, "SHA512") == 0) { + return WC_SHA512_DIGEST_SIZE; + } else +#ifndef WOLFSSL_NOSHA512_224 + if (XSTRCMP(type, "SHA512_224") == 0) { + return WC_SHA512_224_DIGEST_SIZE; + } else +#endif +#ifndef WOLFSSL_NOSHA512_256 + if (XSTRCMP(type, "SHA512_256") == 0) { + return WC_SHA512_256_DIGEST_SIZE; + } else +#endif +#endif +#ifdef WOLFSSL_SHA3 +#ifndef WOLFSSL_NOSHA3_224 + if (XSTRCMP(type, "SHA3_224") == 0) { + return WC_SHA3_224_DIGEST_SIZE; + } else +#endif +#ifndef WOLFSSL_NOSHA3_256 + if (XSTRCMP(type, "SHA3_256") == 0) { + return WC_SHA3_256_DIGEST_SIZE; + } else +#endif +#ifndef WOLFSSL_NOSHA3_384 + if (XSTRCMP(type, "SHA3_384") == 0) { + return WC_SHA3_384_DIGEST_SIZE; + } else +#endif +#ifndef WOLFSSL_NOSHA3_512 + if (XSTRCMP(type, "SHA3_512") == 0) { + return WC_SHA3_512_DIGEST_SIZE; + } +#endif +#endif /* WOLFSSL_SHA3 */ - return WOLFSSL_SUCCESS; + return BAD_FUNC_ARG; } -#endif /* !NO_DH */ - - -#endif /* OPENSSL_EXTRA */ -#endif /* OPENSSL_EXTRA */ +#endif /* OPENSSL_EXTRA || HAVE_CURL */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* Subset of OPENSSL_EXTRA for PKEY operations PKEY free is needed by the From 2affcb72ec11189fd5d899ec129869ff095aed48 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 3 May 2023 07:44:28 +1000 Subject: [PATCH 241/391] SP int: _sp_copy don't check a == b, change calls to _sp_copy Simplify code to make it easier for software analysers. Reduce work done by using _sp_copy instead of sp_copy where possible. --- wolfcrypt/src/sp_int.c | 97 ++++++++++++++++++++++-------------------- 1 file changed, 50 insertions(+), 47 deletions(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index c95512b32f7..7eaf259dbf6 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -5059,22 +5059,19 @@ void sp_forcezero(sp_int* a) */ static void _sp_copy(const sp_int* a, sp_int* r) { - /* Only copy if different pointers. */ - if (a != r) { - /* Copy words across. */ - if (a->used == 0) { - r->dp[0] = 0; - } - else { - XMEMCPY(r->dp, a->dp, a->used * SP_WORD_SIZEOF); - } - /* Set number of used words in result. */ - r->used = a->used; - #ifdef WOLFSSL_SP_INT_NEGATIVE - /* Set sign of result. */ - r->sign = a->sign; - #endif + /* Copy words across. */ + if (a->used == 0) { + r->dp[0] = 0; + } + else { + XMEMCPY(r->dp, a->dp, a->used * SP_WORD_SIZEOF); } + /* Set number of used words in result. */ + r->used = a->used; +#ifdef WOLFSSL_SP_INT_NEGATIVE + /* Set sign of result. */ + r->sign = a->sign; +#endif } /* Copy value of multi-precision number a into r. @@ -5092,12 +5089,15 @@ int sp_copy(const sp_int* a, sp_int* r) if ((a == NULL) || (r == NULL)) { err = MP_VAL; } - /* Validated space in result. */ - if ((err == MP_OKAY) && (a->used > r->size)) { - err = MP_VAL; - } - if (err == MP_OKAY) { - _sp_copy(a, r); + /* Only copy if different pointers. */ + if (a != r) { + /* Validated space in result. */ + if ((err == MP_OKAY) && (a->used > r->size)) { + err = MP_VAL; + } + if (err == MP_OKAY) { + _sp_copy(a, r); + } } return err; @@ -8374,7 +8374,7 @@ static int _sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem, ret = _sp_cmp_abs(a, d); if (ret == MP_LT) { /* a = 0 * d + a */ - if (rem != NULL) { + if ((rem != NULL) && (a != rem)) { _sp_copy(a, rem); } if (r != NULL) { @@ -8622,7 +8622,7 @@ static int _sp_mod(const sp_int* a, const sp_int* m, sp_int* r) err = sp_add(t, m, r); } else { - err = sp_copy(t, r); + _sp_copy(t, r); } } FREE_SP_INT(t, NULL); @@ -11818,7 +11818,9 @@ static int _sp_invmod_bin(const sp_int* a, const sp_int* m, sp_int* u, /* 1. u = m, v = a, b = 0, c = 1 */ _sp_copy(m, u); - _sp_copy(a, v); + if (a != v) { + _sp_copy(a, v); + } _sp_zero(b); _sp_set(c, 1); @@ -11920,7 +11922,9 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, mp_init(d); /* 1. x = m, y = a, b = 1, c = 0 */ - _sp_copy(a, y); + if (a != y) { + _sp_copy(a, y); + } _sp_copy(m, x); _sp_set(b, 1); _sp_zero(c); @@ -12128,7 +12132,7 @@ static int _sp_invmod(const sp_int* a, const sp_int* m, sp_int* r) } } else if (err == MP_OKAY) { - err = sp_copy(c, r); + _sp_copy(c, r); } } @@ -12290,7 +12294,7 @@ static int _sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, /* 1. pre[0] = 2^0 * a mod m * Start with 1.a = a. */ - err = sp_copy(a, pre[0]); + _sp_copy(a, pre[0]); /* 2. For i in 2..CT_INV_MOD_PRE_CNT * For rest of entries in table. */ @@ -12325,7 +12329,7 @@ static int _sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, } } /* 3. Set tmp to product of leading bits. */ - err = sp_copy(pre[j-1], t); + _sp_copy(pre[j-1], t); /* 4. s = 0 */ s = 0; @@ -12402,7 +12406,7 @@ static int _sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, } /* 9. Else r = t */ else { - err = sp_copy(t, r); + _sp_copy(t, r); } } @@ -12535,7 +12539,7 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, } else { /* Copy base into working variable. */ - err = sp_copy(b, t[0]); + _sp_copy(b, t[0]); } } @@ -12543,7 +12547,7 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, /* 3. t[1] = t[0] * Set real working value to base. */ - err = sp_copy(t[0], t[1]); + _sp_copy(t[0], t[1]); /* 4. For i in (bits-1)...0 */ for (i = bits - 1; (err == MP_OKAY) && (i >= 0); i--) { @@ -12591,7 +12595,7 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, } if ((!done) && (err == MP_OKAY)) { /* 5. r = t[1] */ - err = sp_copy(t[1], r); + _sp_copy(t[1], r); } FREE_SP_INT_ARRAY(t, NULL); @@ -12661,7 +12665,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, } else { /* Copy base into working variable. */ - err = sp_copy(b, t[0]); + _sp_copy(b, t[0]); } } @@ -12732,7 +12736,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, } if ((!done) && (err == MP_OKAY)) { /* 8. r = t[1] */ - err = sp_copy(t[1], r); + _sp_copy(t[1], r); } FREE_SP_INT_ARRAY(t, NULL); @@ -12842,7 +12846,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, } else { /* Copy base into entry of table to contain b^1. */ - err = sp_copy(b, t[1]); + _sp_copy(b, t[1]); } } @@ -12954,7 +12958,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, } if ((!done) && (err == MP_OKAY)) { /* 8. r = tr */ - err = sp_copy(tr, r); + _sp_copy(tr, r); } FREE_SP_INT_ARRAY(t, NULL); @@ -13188,7 +13192,7 @@ static int _sp_exptmod_base_2(const sp_int* e, int digits, const sp_int* m, } if (err == MP_OKAY) { /* 8. r = tr */ - err = sp_copy(tr, r); + _sp_copy(tr, r); } #if 0 @@ -13538,7 +13542,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, } else { /* Copy base into Montogmery base variable. */ - err = sp_copy(b, bm); + _sp_copy(b, bm); } } @@ -13556,7 +13560,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, } if (err == MP_OKAY) { /* Copy Montgomery form of base into first element of table. */ - err = sp_copy(bm, t[0]); + _sp_copy(bm, t[0]); } /* Calculate b^(2^(winBits-1)) */ for (i = 1; (i < winBits) && (err == MP_OKAY); i++) { @@ -13605,7 +13609,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, n <<= winBits; c -= winBits; } - err = sp_copy(t[y], tr); + _sp_copy(t[y], tr); } else { /* 1 in Montgomery form. */ @@ -13729,7 +13733,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, } if ((!done) && (err == MP_OKAY)) { /* Copy temporary result into parameter. */ - err = sp_copy(tr, r); + _sp_copy(tr, r); } #ifndef WOLFSSL_SP_NO_MALLOC @@ -13792,7 +13796,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, } else { /* Copy base into temp. */ - err = sp_copy(b, t[0]); + _sp_copy(b, t[0]); } } @@ -13838,7 +13842,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, } if ((!done) && (err == MP_OKAY)) { /* Copy temporary result into parameter. */ - err = sp_copy(t[0], r); + _sp_copy(t[0], r); } FREE_SP_INT_ARRAY(t, NULL); @@ -17817,10 +17821,9 @@ int sp_todecimal(const sp_int* a, char* str) ALLOC_SP_INT_SIZE(t, a->used + 1, err, NULL); if (err == MP_OKAY) { - err = sp_copy(a, t); + _sp_copy(a, t); } if (err == MP_OKAY) { - #ifdef WOLFSSL_SP_INT_NEGATIVE if (a->sign == MP_NEG) { /* Add negative sign character. */ @@ -17969,7 +17972,7 @@ int sp_radix_size(const sp_int* a, int radix, int* size) ALLOC_SP_INT(t, a->used, err, NULL); if (err == MP_OKAY) { t->size = a->used; - err = sp_copy(a, t); + _sp_copy(a, t); } if (err == MP_OKAY) { @@ -18786,7 +18789,7 @@ static WC_INLINE int _sp_gcd(const sp_int* a, const sp_int* b, sp_int* r) } if (err == MP_OKAY) { /* 5. r = u */ - err = sp_copy(u, r); + _sp_copy(u, r); } FREE_SP_INT_ARRAY(d, NULL); From 2893810155878b153f6f5e17510996ade77bdfb5 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Thu, 27 Apr 2023 18:33:27 +0000 Subject: [PATCH 242/391] test: fix test AEAD limit server set fds as nonblock --- tests/api.c | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/api.c b/tests/api.c index 0bea13ed9b4..981671d50a6 100644 --- a/tests/api.c +++ b/tests/api.c @@ -61308,6 +61308,7 @@ static void test_AEAD_limit_server(WOLFSSL* ssl) XMEMSET(&delay, 0, sizeof(delay)); delay.tv_nsec = 100000000; /* wait 0.1 seconds */ tcp_set_nonblocking(&fd); /* So that read doesn't block */ + wolfSSL_dtls_set_using_nonblock(ssl, 1); test_AEAD_get_limits(ssl, NULL, NULL, &sendLimit); while (!test_AEAD_done && ret > 0) { counter++; From 8c4e7816a2d06dacc244ae39238459cd4aca419b Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 2 May 2023 16:13:44 +0000 Subject: [PATCH 243/391] async: fix overwrite of keylen params between calls The `kse->pubKeyLen` parameter is used as an input parameter to `DhGenKeyPair` to provide the size of the `pubKey` buffer (the same size as the prime p). After that, `kse->pubKeyLen` is used to check that the public key generated is of the same length as the prime p. If this is not the case, the public key is padded. If the key generation is asynchronous, then `TLSX_KeyShare_GenDhKey` may be invoked twice. The second time, the `kse->pubKeyLen` value, updated asynchronously by the async code, is overwritten with the prime size at the beginning of the function. When this happens, a wrong public key value is used, and the shared secret computed is incorrect. Similar reasoning can be applied to `kse->keyLen` --- src/tls.c | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/tls.c b/src/tls.c index 18dce34d1c2..929250708f6 100644 --- a/src/tls.c +++ b/src/tls.c @@ -7077,31 +7077,31 @@ static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse) #ifdef HAVE_FFDHE_2048 case WOLFSSL_FFDHE_2048: params = wc_Dh_ffdhe2048_Get(); - kse->keyLen = 29; + pvtSz = 29; break; #endif #ifdef HAVE_FFDHE_3072 case WOLFSSL_FFDHE_3072: params = wc_Dh_ffdhe3072_Get(); - kse->keyLen = 34; + pvtSz = 34; break; #endif #ifdef HAVE_FFDHE_4096 case WOLFSSL_FFDHE_4096: params = wc_Dh_ffdhe4096_Get(); - kse->keyLen = 39; + pvtSz = 39; break; #endif #ifdef HAVE_FFDHE_6144 case WOLFSSL_FFDHE_6144: params = wc_Dh_ffdhe6144_Get(); - kse->keyLen = 46; + pvtSz = 46; break; #endif #ifdef HAVE_FFDHE_8192 case WOLFSSL_FFDHE_8192: params = wc_Dh_ffdhe8192_Get(); - kse->keyLen = 52; + pvtSz = 52; break; #endif default: @@ -7110,19 +7110,16 @@ static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse) if (params == NULL) return BAD_FUNC_ARG; pSz = params->p_len; - pvtSz = kse->keyLen; #else - kse->keyLen = wc_DhGetNamedKeyMinSize(kse->group); - if (kse->keyLen == 0) { + pvtSz = wc_DhGetNamedKeyMinSize(kse->group); + if (pvtSz == 0) { return BAD_FUNC_ARG; } ret = wc_DhGetNamedKeyParamSize(kse->group, &pSz, NULL, NULL); if (ret != 0) { return BAD_FUNC_ARG; } - pvtSz = kse->keyLen; #endif - kse->pubKeyLen = pSz; /* Trigger Key Generation */ if (kse->pubKey == NULL || kse->privKey == NULL) { @@ -7147,14 +7144,14 @@ static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse) /* Allocate space for the private and public key */ if (ret == 0 && kse->pubKey == NULL) { - kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap, + kse->pubKey = (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); if (kse->pubKey == NULL) ret = MEMORY_E; } if (ret == 0 && kse->privKey == NULL) { - kse->privKey = (byte*)XMALLOC(kse->keyLen, ssl->heap, + kse->privKey = (byte*)XMALLOC(pvtSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); if (kse->privKey == NULL) ret = MEMORY_E; @@ -7163,6 +7160,8 @@ static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse) if (ret == 0) { #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(WOLFSSL_DH_EXTRA) ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_DH, kse->key); + kse->pubKeyLen = pSz; + kse->keyLen = pvtSz; if (ret == 0) { ret = wc_DhExportKeyPair(dhKey, (byte*)kse->privKey, &kse->keyLen, /* private */ @@ -7176,6 +7175,8 @@ static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse) /* For async this is called once and when event is done, the * provided buffers will be populated. * Final processing is zero pad below. */ + kse->pubKeyLen = pSz; + kse->keyLen = pvtSz; ret = DhGenKeyPair(ssl, dhKey, (byte*)kse->privKey, &kse->keyLen, /* private */ kse->pubKey, &kse->pubKeyLen /* public */ From ed446fde8e375c8b27514217a37dd46d616214a5 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 2 May 2023 12:35:14 -0700 Subject: [PATCH 244/391] Fixes and improvements for building with low footprint. Fix for ASN template with RSA verify only (was missing `mp_leading_bit`). Fix to allow disabling DRBG with crypto callbacks enabled. Updated the wolfTPM user_settings.h template with low resource option. --- IDE/NETOS/user_settings.h | 1 - configure.ac | 5 +- examples/configs/user_settings_wolftpm.h | 176 +++++++++++++++++------ wolfcrypt/benchmark/benchmark.c | 4 +- wolfcrypt/src/cryptocb.c | 2 +- wolfcrypt/src/sp_int.c | 2 +- wolfcrypt/test/test.c | 45 +++++- wolfssl/wolfcrypt/random.h | 2 + 8 files changed, 183 insertions(+), 54 deletions(-) diff --git a/IDE/NETOS/user_settings.h b/IDE/NETOS/user_settings.h index d7b5d4d2953..8c6ac7730c7 100644 --- a/IDE/NETOS/user_settings.h +++ b/IDE/NETOS/user_settings.h @@ -458,7 +458,6 @@ extern "C" { /* RNG */ /* ------------------------------------------------------------------------- */ -/* Seed Source */ /* Seed Source */ #if 1 extern int my_rng_generate_seed(unsigned char* output, int sz); diff --git a/configure.ac b/configure.ac index 2f4bc3e6d88..9a7337606b0 100644 --- a/configure.ac +++ b/configure.ac @@ -1849,10 +1849,13 @@ AC_ARG_ENABLE([lowresource], if test "$ENABLED_LOWRESOURCE" = "yes" then # low memory / flash flags - AM_CFLAGS="$AM_CFLAGS -DNO_SESSION_CACHE -DRSA_LOW_MEM -DGCM_SMALL -DCURVE25519_SMALL -DED25519_SMALL -DWOLFSSL_SMALL_CERT_VERIFY -DWOLFSSL_NO_ASYNC_IO" + AM_CFLAGS="$AM_CFLAGS -DNO_SESSION_CACHE -DRSA_LOW_MEM -DCURVE25519_SMALL -DED25519_SMALL -DWOLFSSL_SMALL_CERT_VERIFY -DWOLFSSL_NO_ASYNC_IO" # low flash flags AM_CFLAGS="$AM_CFLAGS -DUSE_SLOW_SHA -DUSE_SLOW_SHA256 -DUSE_SLOW_SHA512" + + # AES small + AM_CFLAGS="$AM_CFLAGS -DGCM_SMALL -DWOLFSSL_AES_NO_UNROLL -DWOLFSSL_AES_SMALL_TABLES" fi diff --git a/examples/configs/user_settings_wolftpm.h b/examples/configs/user_settings_wolftpm.h index 8c6a3ebf6df..67972113034 100644 --- a/examples/configs/user_settings_wolftpm.h +++ b/examples/configs/user_settings_wolftpm.h @@ -20,16 +20,44 @@ */ -/* should be renamed to user_settings.h for customer use - * generated from configure and wolfssl/options.h using: - * ./configure --enable-wolftpm --disable-dh --disable-oldtls \ - * --disable-sha3 --disable-sha512 --disable-sha384 --disable-sha224 \ - * --disable-pkcs12 --disable-chacha --disable-poly1305 \ - * --disable-sys-ca-certs --disable-examples - * - * Cleaned up by David Garske +/* To use the rename file to user_settings.h and define WOLFSSL_USER_SETTINGS */ + +/* Test using: +cp ./examples/configs/user_settings_wolftpm.h user_settings.h +./configure --enable-usersettings --disable-examples CFLAGS="-Os" +make +*/ + +/* Options generated from configure and wolfssl/options.h using: +./configure --enable-wolftpm --disable-dh --disable-oldtls \ + --disable-sha3 --disable-sha512 --disable-sha384 --disable-sha224 \ + --disable-pkcs12 --disable-chacha --disable-poly1305 \ + --disable-sys-ca-certs --disable-examples +*/ + +/* Options for USE_LOW_RESOURCE generated with configure and wolfssl/options.h + * using: +./configure --enable-lowresource --enable-cryptonly --enable-aescfb \ + --enable-hmac --enable-cryptocb --enable-singlethreaded \ + --enable-sp=smallrsa2048 --enable-sp-math --disable-sp-asm \ + --disable-filesystem --disable-asm --disable-pkcs8 --disable-pkcs12 \ + --disable-ecc --disable-dh \ + --disable-sha224 --disable-sha384 --disable-sha512 \ + --disable-md5 --disable-sha3 \ + --disable-aescbc --disable-aesgcm --disable-aesccm \ + --disable-poly1305 --disable-chacha \ + --disable-hashdrbg \ + --disable-sys-ca-certs --disable-error-queue-per-thread \ + --disable-oldtls --disable-errorstrings --disable-memory --disable-coding \ + --disable-examples --disable-optflags \ + CFLAGS="-Os -DNO_SIG_WRAPPER -DNO_AES_192 -DNO_AES_256 \ + -DWOLFSSL_RSA_PUBLIC_ONLY -DWOLFSSL_RSA_VERIFY_INLINE -DNO_CHECK_PRIVATE_KEY" */ +/* For the wolfTPM build: +./configure --enable-swtpm CFLAGS="-Os" && make +*/ + #ifndef WOLF_USER_SETTINGS_TPM_H #define WOLF_USER_SETTINGS_TPM_H @@ -38,7 +66,15 @@ extern "C" { #endif -#if 1 +/* enable for low resource options */ +#if 0 + #define USE_LOW_RESOURCE +#endif + +#ifdef USE_LOW_RESOURCE + /* wolfCrypt only (no SSL/TLS) */ + #define WOLFCRYPT_ONLY +#else /* wolfTPM with TLS example (v1.3 only) */ #define WOLFSSL_TLS13 #define WOLFSSL_NO_TLS12 @@ -52,78 +88,136 @@ extern "C" { #define HAVE_HKDF #define WC_RSA_PSS #define WOLFSSL_PSS_LONG_SALT -#else - /* wolfCrypt only (no SSL/TLS) */ - #define WOLFCRYPT_ONLY #endif /* No threading or file system */ #define SINGLE_THREADED -/* File system disable */ -#if 0 - #define NO_FILESYSTEM -#endif /* Enable crypto callbacks */ #define WOLF_CRYPTO_CB -/* Enable PRNG (SHA2-256) */ -#define HAVE_HASHDRBG - -/* Enable SP math all (sp_int.c) with multi-precision support */ -#define WOLFSSL_SP_MATH_ALL +#ifdef USE_LOW_RESOURCE + /* Single Precision math for RSA 2048 only (small) */ + #define WOLFSSL_HAVE_SP_RSA + #define WOLFSSL_SP_MATH + #define WOLFSSL_SP_SMALL + #define WOLFSSL_SP_NO_3072 /* 2048-only */ +#else + /* Enable SP math all (sp_int.c) with multi-precision support */ + #define WOLFSSL_SP_MATH_ALL +#endif /* Enable hardening (timing resistance) */ #define TFM_TIMING_RESISTANT #define ECC_TIMING_RESISTANT #define WC_RSA_BLINDING +/* Enable PRNG (SHA2-256) */ +#ifdef USE_LOW_RESOURCE + /* use TPM TRNG */ + #define WC_NO_HASHDRBG +#else + #define HAVE_HASHDRBG +#endif + /* Asymmetric */ -#define HAVE_ECC -#undef NO_RSA -#define NO_DH -#ifndef NO_DH +#if 1 /* RSA - needed to encrypt salt */ + #undef NO_RSA + #ifdef USE_LOW_RESOURCE + #define WOLFSSL_RSA_PUBLIC_ONLY + #define WOLFSSL_RSA_VERIFY_INLINE + #define NO_CHECK_PRIVATE_KEY + #endif +#else + #define NO_RSA +#endif +#ifndef USE_LOW_RESOURCE /* ECC */ + #define HAVE_ECC + #define ECC_USER_CURVES /* default to only SECP256R1 */ +#endif +#ifndef USE_LOW_RESOURCE /* DH */ + #undef NO_DH #define HAVE_FFDHE_2048 #define HAVE_DH_DEFAULT_PARAMS +#else + #define NO_DH #endif /* Symmetric Hash */ #undef NO_SHA #undef NO_SHA256 -#define WOLFSSL_SHA512 -#define WOLFSSL_SHA384 +#ifndef USE_LOW_RESOURCE + #define WOLFSSL_SHA512 + #define WOLFSSL_SHA384 +#endif /* Symmetric Cipher */ -#define HAVE_AES_KEYWRAP -#define WOLFSSL_AES_DIRECT #define WOLFSSL_AES_CFB -#define HAVE_AESGCM -#define GCM_TABLE_4BIT +#define HAVE_AES_DECRYPT +#ifndef USE_LOW_RESOURCE + #define HAVE_AES_KEYWRAP + #define WOLFSSL_AES_DIRECT + #define HAVE_AESGCM + #define GCM_TABLE_4BIT +#else + #define NO_AES_CBC +#endif -#if 0 +#if 0 /* ChaCha20 / Poly1305 */ #define HAVE_POLY1305 #define HAVE_CHACHA #endif /* Features */ -#define WOLFSSL_CERT_GEN -#define WOLFSSL_CERT_REQ -#define WOLFSSL_CERT_EXT - -#define HAVE_PKCS7 -#define HAVE_X963_KDF -#define WOLFSSL_BASE64_ENCODE - +#define WOLFSSL_ASN_TEMPLATE +#define WOLFSSL_USER_IO /* user recv/send callbacks for network IO */ +#ifndef USE_LOW_RESOURCE + #define WOLFSSL_CERT_GEN + #define WOLFSSL_CERT_REQ + #define WOLFSSL_CERT_EXT + + #define HAVE_PKCS7 + #define HAVE_X963_KDF + #define WOLFSSL_BASE64_ENCODE +#endif /* Disables */ +#define NO_PKCS8 +#define NO_PKCS12 +#define NO_PWDBASED #define NO_DSA #define NO_DES3 #define NO_RC4 #define NO_PSK #define NO_MD4 +#define NO_MD5 #define WOLFSSL_NO_SHAKE128 #define WOLFSSL_NO_SHAKE256 - +#define NO_WRITEV + +/* Low Resource Options */ +#ifdef USE_LOW_RESOURCE + #define NO_FILESYSTEM /* File system disable */ + #define NO_ERROR_STRINGS + #define WOLFSSL_NO_ASM + #define TFM_NO_ASM + #define NO_WOLFSSL_MEMORY + #define NO_SESSION_CACHE + #define RSA_LOW_MEM + #define WOLFSSL_AES_SMALL_TABLES + #define WOLFSSL_AES_NO_UNROLL + #define GCM_SMALL + #undef GCM_TABLE_4BIT + #define NO_AES_192 + #define NO_AES_256 + #define USE_SLOW_SHA + #define USE_SLOW_SHA256 + #define USE_SLOW_SHA512 + #define NO_SIG_WRAPPER + #define NO_ASN_TIME + #define NO_CODING + #define NO_BIG_INT +#endif #ifdef __cplusplus } diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 42f12b73d2d..5d354d9bec9 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -6516,7 +6516,7 @@ static void bench_rsa_helper(int useDeviceID, RsaKey rsaKey[BENCH_MAX_PENDING], BENCH_ASYNC_GET_DEV(&rsaKey[i]), 1, ×, ntimes, &pending)) { ret = wc_RsaSSL_Sign(message, len, enc[i], - rsaKeySz/8, &rsaKey[i], &gRng); + rsaKeySz/8, &rsaKey[i], GLOBAL_RNG); if (!bench_async_handle(&ret, BENCH_ASYNC_GET_DEV(&rsaKey[i]), 1, ×, &pending)) { @@ -7371,7 +7371,7 @@ void bench_ecc(int useDeviceID, int curveId) } ret = wc_ecc_sign_hash(digest[i], (word32)keySize, sig[i], - &x[i], &gRng, &genKey[i]); + &x[i], GLOBAL_RNG, &genKey[i]); if (!bench_async_handle(&ret, BENCH_ASYNC_GET_DEV(&genKey[i]), 1, ×, diff --git a/wolfcrypt/src/cryptocb.c b/wolfcrypt/src/cryptocb.c index 8d3a683566f..ed4f9518839 100644 --- a/wolfcrypt/src/cryptocb.c +++ b/wolfcrypt/src/cryptocb.c @@ -235,7 +235,7 @@ int wc_CryptoCb_GetDevIdAtIndex(int startIdx) /* Used to register a find device function. Useful for cases where the * device ID in the struct may not have been set but still wanting to use - * a specifice crypto callback device ID. The find callback is global and + * a specific crypto callback device ID. The find callback is global and * not thread safe. */ void wc_CryptoCb_SetDeviceFindCb(CryptoDevCallbackFind cb) { diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 7eaf259dbf6..d15a4e27e6b 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -5605,7 +5605,7 @@ int sp_cnt_lsb(const sp_int* a) } #endif /* WOLFSSL_SP_MATH_ALL || WOLFSSL_HAVE_SP_DH || (HAVE_ECC && FP_ECC) */ -#if !defined(WOLFSSL_RSA_VERIFY_ONLY) || \ +#if !defined(WOLFSSL_RSA_VERIFY_ONLY) || defined(WOLFSSL_ASN_TEMPLATE) || \ (defined(WOLFSSL_SP_MATH_ALL) && !defined(NO_ASN)) /* Determine if the most significant byte of the encoded multi-precision number * has the top bit set. diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 4b8d11d145a..90b65ca9b37 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -758,6 +758,22 @@ static int wolfssl_pb_print(const char* msg, ...) } #endif /* WOLFSSL_PB */ + +#if defined(WOLF_CRYPTO_CB) && !defined(HAVE_HASHDRBG) && \ + !defined(WC_NO_RNG) && !defined(CUSTOM_RAND_GENERATE_BLOCK) +/* Enable support for RNG with crypto callback */ +static int rng_crypto_cb(int thisDevId, wc_CryptoInfo* info, void* ctx) +{ + int rc = CRYPTOCB_UNAVAILABLE; + if (info->algo_type == WC_ALGO_TYPE_RNG) { + rc = wc_GenerateSeed(&info->rng.rng->seed, info->rng.out, info->rng.sz); + } + (void)ctx; + (void)thisDevId; + return rc; +} +#endif + /* optional macro to add sleep between tests */ #ifndef TEST_SLEEP #define TEST_SLEEP() @@ -925,6 +941,16 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #endif #endif +#if defined(WOLF_CRYPTO_CB) && !defined(HAVE_HASHDRBG) && \ + !defined(WC_NO_RNG) && !defined(CUSTOM_RAND_GENERATE_BLOCK) + if (devId == INVALID_DEVID) { + /* for testing RNG with crypto callback register function */ + devId = 100; /* any value beside -2 (INVALID_DEVID) */ + wc_CryptoCb_RegisterDevice(devId, rng_crypto_cb, NULL); + } +#endif + + #ifdef HAVE_SELFTEST if ( (ret = wolfCrypt_SelfTest()) != 0) TEST_FAIL("CAVP selftest failed!\n", ret); @@ -8561,6 +8587,7 @@ static int EVP_test(const WOLFSSL_EVP_CIPHER* type, const byte* key, } #endif #endif +#endif /* WOLFSSL_AES_256 */ out: @@ -8580,7 +8607,6 @@ static int EVP_test(const WOLFSSL_EVP_CIPHER* type, const byte* key, #endif #endif -#endif /* WOLFSSL_AES_256 */ return ret; } @@ -8776,6 +8802,7 @@ static int EVP_test(const WOLFSSL_EVP_CIPHER* type, const byte* key, goto out; } #endif +#endif /* WOLFSSL_AES_256 */ out: @@ -8795,8 +8822,6 @@ static int EVP_test(const WOLFSSL_EVP_CIPHER* type, const byte* key, #endif #endif -#endif /* WOLFSSL_AES_256 */ - return ret; } #endif /* !HAVE_SELFTEST && !HAVE_FIPS */ @@ -13244,7 +13269,6 @@ static int _rng_test(WC_RNG* rng, int errorOffset) return ret; } - static int random_rng_test(void) { WC_RNG localRng; @@ -13277,6 +13301,7 @@ static int random_rng_test(void) if (rng == NULL) return WC_TEST_RET_ENC_ERRNO; + rng->devId = devId; ret = _rng_test(rng, WC_TEST_RET_ENC_NC); wc_rng_free(rng); @@ -44565,7 +44590,12 @@ static int myCryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) #endif if (info->algo_type == WC_ALGO_TYPE_RNG) { - #ifndef WC_NO_RNG + #if defined(WOLF_CRYPTO_CB) && !defined(HAVE_HASHDRBG) && \ + !defined(WC_NO_RNG) && !defined(CUSTOM_RAND_GENERATE_BLOCK) + /* if RNG only supports crypto callback, just use seed */ + ret = wc_GenerateSeed(&info->rng.rng->seed, + info->rng.out, info->rng.sz); + #elif !defined(WC_NO_RNG) /* set devId to invalid, so software is used */ info->rng.rng->devId = INVALID_DEVID; @@ -45172,6 +45202,7 @@ static int myCryptoCbFind(int currentId, int algoType) WOLFSSL_TEST_SUBROUTINE int cryptocb_test(void) { int ret = 0; + int origDevId = devId; myCryptoDevCtx myCtx; /* example data for callback */ @@ -45272,8 +45303,8 @@ WOLFSSL_TEST_SUBROUTINE int cryptocb_test(void) ret = cmac_test(); #endif - /* reset devId */ - devId = INVALID_DEVID; + /* restore devId */ + devId = origDevId; return ret; } diff --git a/wolfssl/wolfcrypt/random.h b/wolfssl/wolfcrypt/random.h index 07707edc2a4..b7d7588499d 100644 --- a/wolfssl/wolfcrypt/random.h +++ b/wolfssl/wolfcrypt/random.h @@ -113,6 +113,8 @@ /* allow whitewood as direct RNG source using wc_GenerateSeed directly */ #elif defined(HAVE_INTEL_RDRAND) /* Intel RDRAND or RDSEED */ +#elif defined(WOLF_CRYPTO_CB) + /* Requires registered Crypto Callback to service RNG, with devId set */ #elif !defined(WC_NO_RNG) #error No RNG source defined! #endif From 908a86961ba1ec241b805fb89fabecee64ea750d Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 2 May 2023 18:10:25 -0700 Subject: [PATCH 245/391] Provide way to disable ASN but have `wc_RsaPublicKeyDecodeRaw`, which doesn't need ASN.1 parsing. --- configure.ac | 4 +- wolfcrypt/src/asn.c | 123 ++++++++++++++++++++++-------------------- wolfcrypt/test/test.c | 2 + 3 files changed, 69 insertions(+), 60 deletions(-) diff --git a/configure.ac b/configure.ac index 9a7337606b0..f289f186ffb 100644 --- a/configure.ac +++ b/configure.ac @@ -4001,7 +4001,7 @@ else fi if test "$ENABLED_RSA" = "yes" && test "$ENABLED_RSAVFY" = "no" && \ - test "$ENABLED_ASN" = "no" + test "$ENABLED_ASN" = "no" && test "$ENABLED_LOWRESOURCE" = "no" then AC_MSG_ERROR([please disable rsa if disabling asn.]) fi @@ -8481,7 +8481,7 @@ AM_CONDITIONAL([BUILD_SAKKE],[test "x$ENABLED_SAKKE" = "xyes" || test "x$ENABLED AM_CONDITIONAL([BUILD_MEMORY],[test "x$ENABLED_MEMORY" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) AM_CONDITIONAL([BUILD_RSA],[test "x$ENABLED_RSA" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) AM_CONDITIONAL([BUILD_DH],[test "x$ENABLED_DH" != "xno" || test "x$ENABLED_USERSETTINGS" = "xyes"]) -AM_CONDITIONAL([BUILD_ASN],[test "x$ENABLED_ASN" != "xno" || test "x$ENABLED_USERSETTINGS" = "xyes"]) +AM_CONDITIONAL([BUILD_ASN],[test "x$ENABLED_ASN" != "xno" || test "x$ENABLED_RSA" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) AM_CONDITIONAL([BUILD_AES],[test "x$ENABLED_AES" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) AM_CONDITIONAL([BUILD_CODING],[test "x$ENABLED_CODING" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) AM_CONDITIONAL([BUILD_RC4],[test "x$ENABLED_ARC4" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 2ddcbb17d0d..46ab68d0b60 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -96,12 +96,20 @@ ASN Options: * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs. */ +#include +#ifndef NO_RSA + #include + #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL) + extern int wc_InitRsaHw(RsaKey* key); + #endif +#endif + #ifndef NO_ASN + #include #include #include #include -#include #include #include #include @@ -168,13 +176,6 @@ ASN Options: #include #endif -#ifndef NO_RSA - #include -#if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL) -extern int wc_InitRsaHw(RsaKey* key); -#endif -#endif - #ifndef NO_DSA #include #else @@ -9518,56 +9519,6 @@ int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key, return ret; } - -/* import RSA public key elements (n, e) into RsaKey structure (key) */ -int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e, - word32 eSz, RsaKey* key) -{ - if (n == NULL || e == NULL || key == NULL) - return BAD_FUNC_ARG; - - key->type = RSA_PUBLIC; - - if (mp_init(&key->n) != MP_OKAY) - return MP_INIT_E; - - if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) { - mp_clear(&key->n); - return ASN_GETINT_E; - } -#ifdef HAVE_WOLF_BIGINT - if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) { - mp_clear(&key->n); - return ASN_GETINT_E; - } -#endif /* HAVE_WOLF_BIGINT */ - - if (mp_init(&key->e) != MP_OKAY) { - mp_clear(&key->n); - return MP_INIT_E; - } - - if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) { - mp_clear(&key->n); - mp_clear(&key->e); - return ASN_GETINT_E; - } -#ifdef HAVE_WOLF_BIGINT - if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) { - mp_clear(&key->n); - mp_clear(&key->e); - return ASN_GETINT_E; - } -#endif /* HAVE_WOLF_BIGINT */ - -#ifdef WOLFSSL_XILINX_CRYPT - if (wc_InitRsaHw(key) != 0) { - return BAD_STATE_E; - } -#endif - - return 0; -} #endif /* HAVE_USER_RSA */ #endif /* !NO_RSA */ @@ -37022,6 +36973,62 @@ int wc_MIME_free_hdrs(MimeHdr* head) #endif /* !NO_ASN */ +/* Functions that parse, but are not using ASN.1 */ +#if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \ + (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH)) +/* import RSA public key elements (n, e) into RsaKey structure (key) */ +/* this function does not use any ASN.1 parsing */ +int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e, + word32 eSz, RsaKey* key) +{ + if (n == NULL || e == NULL || key == NULL) + return BAD_FUNC_ARG; + + key->type = RSA_PUBLIC; + + if (mp_init(&key->n) != MP_OKAY) + return MP_INIT_E; + + if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) { + mp_clear(&key->n); + return ASN_GETINT_E; + } +#ifdef HAVE_WOLF_BIGINT + if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) { + mp_clear(&key->n); + return ASN_GETINT_E; + } +#endif /* HAVE_WOLF_BIGINT */ + + if (mp_init(&key->e) != MP_OKAY) { + mp_clear(&key->n); + return MP_INIT_E; + } + + if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) { + mp_clear(&key->n); + mp_clear(&key->e); + return ASN_GETINT_E; + } +#ifdef HAVE_WOLF_BIGINT + if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) { + mp_clear(&key->n); + mp_clear(&key->e); + return ASN_GETINT_E; + } +#endif /* HAVE_WOLF_BIGINT */ + +#ifdef WOLFSSL_XILINX_CRYPT + if (wc_InitRsaHw(key) != 0) { + return BAD_STATE_E; + } +#endif + + return 0; +} +#endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */ + + #ifdef WOLFSSL_SEP diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 90b65ca9b37..31f3426bca6 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -13301,7 +13301,9 @@ static int random_rng_test(void) if (rng == NULL) return WC_TEST_RET_ENC_ERRNO; + #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) rng->devId = devId; + #endif ret = _rng_test(rng, WC_TEST_RET_ENC_NC); wc_rng_free(rng); From 06e812b16792a4d2992d8dd21475b27761a8a638 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Thu, 4 May 2023 08:04:25 -0700 Subject: [PATCH 246/391] WOLFSSL_SP_INT_NEGATIVE declaration for all Espressif chipsets (#6374) * WOLFSSL_SP_INT_NEGATIVE declaration for all Espressif chipsets * correct naming for WOLFSSL_SHA384 on ESP32-C3 --- wolfcrypt/src/port/Espressif/esp32_mp.c | 51 ++++++++++++++---------- wolfcrypt/src/port/Espressif/esp32_sha.c | 2 +- 2 files changed, 30 insertions(+), 23 deletions(-) diff --git a/wolfcrypt/src/port/Espressif/esp32_mp.c b/wolfcrypt/src/port/Espressif/esp32_mp.c index 7e57eff4cac..982991ac247 100644 --- a/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -330,7 +330,22 @@ static int esp_get_rinv(MATH_INT_T *rinv, MATH_INT_T *M, word32 exp) /* Z = X * Y; */ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) { - int ret = 0; + int ret; + +#ifdef WOLFSSL_SP_INT_NEGATIVE + /* neg check: X*Y becomes negative */ + int neg; + + /* aka (X->sign == Y->sign) ? MP_ZPOS : MP_NEG; , but with mp_isneg(): */ + neg = (mp_isneg(X) == mp_isneg(Y)) ? MP_ZPOS : MP_NEG; + if (neg) { + /* Negative numbers are relatively infrequent. + * May be interesting during verbose debugging: */ + ESP_LOGV(TAG, "mp_isneg(X) = %d; mp_isneg(Y) = %d; neg = %d ", + mp_isneg(X), mp_isneg(Y), neg); + } +#endif + ret = MP_OKAY; /* assume success until proven wrong */ #if CONFIG_IDF_TARGET_ESP32S3 @@ -345,10 +360,6 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) int WordsForOperand = bits2words(MinXYBits); int WordsForResult = bits2words(BitsInX + BitsInY); -#ifdef WOLFSSL_SP_INT_NEGATIVE - int neg; - neg = (X->sign == Y->sign) ? MP_ZPOS : MP_NEG; -#endif /* Make sure we are within capabilities of hardware. */ if ( (WordsForOperand * BITS_IN_ONE_WORD) > ESP_HW_MULTI_RSAMAX_BITS ) { ESP_LOGW(TAG, "exceeds max bit length(2048)"); @@ -377,8 +388,9 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) return ret; } - /* 2. Disable completion interrupt signal; we don't use. */ - DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); // 0 => no interrupt; 1 => interrupt on completion. + /* 2. Disable completion interrupt signal; we don't use. + ** 0 => no interrupt; 1 => interrupt on completion. */ + DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); /* 3. Write number of words required for result. */ if ( (WordsForOperand * BITS_IN_ONE_WORD * 2) > ESP_HW_RSAMAX_BIT) { @@ -407,11 +419,6 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) /* 7. clear and release HW */ esp_mp_hw_unlock(); -#ifdef WOLFSSL_SP_INT_NEGATIVE - Z->sign = (Z->used > 0) ? neg : MP_ZPOS; -#endif - - return ret; /* end if CONFIG_IDF_TARGET_ESP32S3 */ #else /* not CONFIG_IDF_TARGET_ESP32S3 */ @@ -422,11 +429,6 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) word32 maxWords_sz; word32 hwWords_sz; - /* neg check - X*Y becomes negative */ -#ifdef WOLFSSL_SP_INT_NEGATIVE - neg = mp_isneg(X) != mp_isneg(Y) ? 1 : 0; -#endif - /* ask bits number */ Xs = mp_count_bits(X); Ys = mp_count_bits(Y); @@ -492,15 +494,18 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) /* step.7 clear and release HW */ esp_mp_hw_unlock(); +#endif /* CONFIG_IDF_TARGET_ESP32S3 or not */ + /* common exit for all chipset types */ #ifdef WOLFSSL_SP_INT_NEGATIVE if (!mp_iszero(Z) && neg) { + /* for non-zero negative numbers, set negative flag for our result: + * Z->sign = FP_NEG */ mp_setneg(Z); } #endif return ret; -#endif /* CONFIG_IDF_TARGET_ESP32S3 or not */ } /* Z = X * Y (mod M) */ @@ -596,8 +601,9 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) return ret; } - /* 2. Disable completion interrupt signal; we don't use. */ - DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); // 0 => no interrupt; 1 => interrupt on completion. + /* 2. Disable completion interrupt signal; we don't use. + ** 0 => no interrupt; 1 => interrupt on completion. */ + DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); /* 3. Write (N_result_bits/32 - 1) to the RSA_MODE_REG. */ OperandBits = max(max(Xs, Ys), Ms); @@ -815,8 +821,9 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, word32 Ys, MATH_INT_T* M, MATH_ return ret; } - /* 2. Disable completion interrupt signal; we don't use. */ - DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); // 0 => no interrupt; 1 => interrupt on completion. + /* 2. Disable completion interrupt signal; we don't use. + ** 0 => no interrupt; 1 => interrupt on completion. */ + DPORT_REG_WRITE(RSA_INTERRUPT_REG, 0); /* 3. Write (N_result_bits/32 - 1) to the RSA_MODE_REG. */ OperandBits = max(max(Xs, Ys), Ms); diff --git a/wolfcrypt/src/port/Espressif/esp32_sha.c b/wolfcrypt/src/port/Espressif/esp32_sha.c index 3f5535ba35a..39f4ad8ab16 100644 --- a/wolfcrypt/src/port/Espressif/esp32_sha.c +++ b/wolfcrypt/src/port/Espressif/esp32_sha.c @@ -855,7 +855,7 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) break; #if defined(WOLFSSL_SHA384) case SHA2_384: - uHardwareAlgorithm = 3; + HardwareAlgorithm = 3; break; #endif #if defined(WOLFSSL_SHA512) From 25e306b9cadd932cbef2fc9353e62aee038cfb82 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 24 Apr 2023 17:03:34 +1000 Subject: [PATCH 247/391] Memory usage improvements ECC: make private key field 'k' able to be smaller when ALT_ECC_SIZE is defined. WOLFSSL_SMALL_STACK_CACHE: allocate temps using new macros. --- configure.ac | 5 + examples/client/client.c | 33 ++- scripts/openssl.test | 57 ++++- src/internal.c | 50 ++++- src/pk.c | 19 +- tests/api.c | 31 ++- wolfcrypt/src/ecc.c | 242 +++++++++++++-------- wolfcrypt/src/eccsi.c | 32 ++- wolfcrypt/src/port/caam/wolfcaam_ecdsa.c | 24 +- wolfcrypt/src/port/caam/wolfcaam_fsl_nxp.c | 18 +- wolfcrypt/src/port/kcapi/kcapi_ecc.c | 21 +- wolfcrypt/src/port/maxim/maxq10xx.c | 11 +- wolfcrypt/src/port/silabs/silabs_ecc.c | 29 ++- wolfcrypt/src/port/st/stm32.c | 10 +- wolfcrypt/src/sakke.c | 33 ++- wolfcrypt/src/wc_pkcs11.c | 18 +- wolfcrypt/test/test.c | 9 +- wolfssl/wolfcrypt/ecc.h | 51 ++++- 18 files changed, 495 insertions(+), 198 deletions(-) diff --git a/configure.ac b/configure.ac index f289f186ffb..21c74d003ae 100644 --- a/configure.ac +++ b/configure.ac @@ -7695,6 +7695,11 @@ case $host_cpu in ;; esac +if test "$ENABLED_LOWRESOURCE" = "yes" && test "$ENABLED_ECC" = "yes" && (test "$ENABLED_RSA" = "yes" || test "$ENABLED_DH" == "yes") && (test "$ENABLED_SP_MATH" = "yes" || test "$ENABLED_SP_MATH_ALL" = "yes") +then + AM_CFLAGS="$AM_CFLAGS -DALT_ECC_SIZE" +fi + ################################################################################ # Update ENABLE_* variables # ################################################################################ diff --git a/examples/client/client.c b/examples/client/client.c index 058c193ce9c..dd507ddd756 100644 --- a/examples/client/client.c +++ b/examples/client/client.c @@ -1260,10 +1260,14 @@ static const char* client_usage_msg[][70] = { #endif #ifdef HAVE_SUPPORTED_CURVES "--onlyPskDheKe Must use DHE key exchange with PSK\n", /* 73 */ +#endif +#ifndef NO_PSK + "--openssl-psk Use TLS 1.3 PSK callback compatible with " + "OpenSSL\n", /* 74 */ #endif "\n" "For simpler wolfSSL TLS client examples, visit\n" - "https://github.com/wolfSSL/wolfssl-examples/tree/master/tls\n", /* 74 */ + "https://github.com/wolfSSL/wolfssl-examples/tree/master/tls\n", /* 75 */ NULL, }, #ifndef NO_MULTIBYTE_PRINT @@ -1481,11 +1485,15 @@ static const char* client_usage_msg[][70] = { #endif #ifdef HAVE_SUPPORTED_CURVES "--onlyPskDheKe Must use DHE key exchange with PSK\n", /* 73 */ +#endif +#ifndef NO_PSK + "--openssl-psk Use TLS 1.3 PSK callback compatible with " + "OpenSSL\n", /* 74 */ #endif "\n" "より簡単なwolfSSL TSL クライアントの例については" "下記にアクセスしてください\n" - "https://github.com/wolfSSL/wolfssl-examples/tree/master/tls\n", /* 74 */ + "https://github.com/wolfSSL/wolfssl-examples/tree/master/tls\n", /* 75 */ NULL, }, #endif @@ -1852,6 +1860,9 @@ THREAD_RETURN WOLFSSL_THREAD client_test(void* args) #endif #ifdef HAVE_SUPPORTED_CURVES { "onlyPskDheKe", 0, 264 }, +#endif +#ifndef NO_PSK + { "openssl-psk", 0, 265 }, #endif { 0, 0, 0 } }; @@ -1859,6 +1870,7 @@ THREAD_RETURN WOLFSSL_THREAD client_test(void* args) int version = CLIENT_INVALID_VERSION; int minVersion = CLIENT_INVALID_VERSION; int usePsk = 0; + int opensslPsk = 0; int useAnon = 0; int sendGET = 0; int benchmark = 0; @@ -2066,6 +2078,7 @@ THREAD_RETURN WOLFSSL_THREAD client_test(void* args) (void)loadCertKeyIntoSSLObj; (void)usePqc; (void)pqcAlg; + (void)opensslPsk; StackTrap(); /* Reinitialize the global myVerifyAction. */ @@ -2678,6 +2691,11 @@ THREAD_RETURN WOLFSSL_THREAD client_test(void* args) #ifdef WOLFSSL_TLS13 onlyPskDheKe = 1; #endif +#endif + break; + case 265: +#ifndef NO_PSK + opensslPsk = 1; #endif break; default: @@ -3060,10 +3078,15 @@ THREAD_RETURN WOLFSSL_THREAD client_test(void* args) wolfSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb); #ifdef WOLFSSL_TLS13 #if !defined(WOLFSSL_PSK_TLS13_CB) && !defined(WOLFSSL_PSK_ONE_ID) - wolfSSL_CTX_set_psk_client_cs_callback(ctx, my_psk_client_cs_cb); - #else - wolfSSL_CTX_set_psk_client_tls13_callback(ctx, my_psk_client_tls13_cb); + if (!opensslPsk) { + wolfSSL_CTX_set_psk_client_cs_callback(ctx, my_psk_client_cs_cb); + } + else #endif + { + wolfSSL_CTX_set_psk_client_tls13_callback(ctx, + my_psk_client_tls13_cb); + } #endif if (defaultCipherList == NULL) { #if defined(HAVE_AESGCM) && !defined(NO_DH) diff --git a/scripts/openssl.test b/scripts/openssl.test index 193fbfeb363..8a515333faa 100755 --- a/scripts/openssl.test +++ b/scripts/openssl.test @@ -1,6 +1,6 @@ #!/bin/bash -#openssl.test +# openssl.test # Enviornment variables used: # OPENSSL (openssl app to use) @@ -409,6 +409,14 @@ OIFS=$IFS # store old separator to reset # # Start # +echo +echo "wolfSSL configuration:" +./config.status --config +echo +echo "OpenSSL version:" +$OPENSSL version -a +echo + ps -p $PPID >/dev/null 2>&1 if [ "$?" = "1" ] then @@ -494,51 +502,86 @@ esac if [ "$wolf_certs" != "" ] then + echo + # Check if RSA certificates supported in wolfSSL + wolf_rsa=`$WOLFSSL_CLIENT -A "${CERT_DIR}/ca-cert.pem" 2>&1` + case $wolf_rsa in + *"ca file"*) + echo "wolfSSL does not support RSA" + wolf_rsa="" + ;; + *) + ;; + esac + if [ "$wolf_rsa" != "" ]; then + echo "wolfSSL supports RSA" + fi # Check if ECC certificates supported in wolfSSL - wolf_ecc=`$WOLFSSL_CLIENT -A "${CERT_DIR}/ed25519/ca-ecc-cert.pem" 2>&1` + wolf_ecc=`$WOLFSSL_CLIENT -A "${CERT_DIR}/ca-ecc-cert.pem" 2>&1` case $wolf_ecc in *"ca file"*) + echo "wolfSSL does not support ECDSA" wolf_ecc="" ;; *) ;; esac + if [ "$wolf_ecc" != "" ]; then + echo "wolfSSL supports ECDSA" + fi # Check if Ed25519 certificates supported in wolfSSL wolf_ed25519=`$WOLFSSL_CLIENT -A "${CERT_DIR}/ed25519/root-ed25519.pem" 2>&1` case $wolf_ed25519 in *"ca file"*) + echo "wolfSSL does not support Ed25519" wolf_ed25519="" ;; *) ;; esac + if [ "$wolf_ed25519" != "" ]; then + echo "wolfSSL supports Ed25519" + fi # Check if Ed25519 certificates supported in OpenSSL openssl_ed25519=`$OPENSSL s_client -cert "${CERT_DIR}/ed25519/client-ed25519.pem" -key "${CERT_DIR}/ed25519/client-ed25519-priv.pem" 2>&1` case $openssl_ed25519 in *"unable to load"*) + echo "OpenSSL does not support Ed25519" wolf_ed25519="" ;; *) ;; esac + if [ "$wolf_ed25519" != "" ]; then + echo "OpenSSL supports Ed25519" + fi # Check if Ed448 certificates supported in wolfSSL wolf_ed448=`$WOLFSSL_CLIENT -A "${CERT_DIR}/ed448/root-ed448.pem" 2>&1` case $wolf_ed448 in *"ca file"*) + echo "wolfSSL does not support Ed448" wolf_ed448="" ;; *) ;; esac + if [ "$wolf_ed448" != "" ]; then + echo "wolfSSL supports Ed448" + fi # Check if Ed448 certificates supported in OpenSSL openssl_ed448=`$OPENSSL s_client -cert "${CERT_DIR}/ed448/client-ed448.pem" -key "${CERT_DIR}/ed448/client-ed448-priv.pem" 2>&1` case $openssl_ed448 in *"unable to load"*) + echo "OpenSSL does not support Ed448" wolf_ed448="" ;; *) ;; esac + if [ "$wolf_ed448" != "" ]; then + echo "OpenSSL supports Ed448" + fi + echo fi openssl_tls13=`$OPENSSL s_client -help 2>&1` @@ -664,7 +707,7 @@ if [ "$wolf_ecdsa" != "" -a "$wolf_ecc" != "" ] then cert_file="${CERT_DIR}/server-ecc.pem" key_file="${CERT_DIR}/ecc-key.pem" - ca_file="${CERT_DIR}/client-ca.pem" + ca_file="${CERT_DIR}/client-ecc-cert.pem" openssl_suite="ECDH[E]-ECDSA" start_openssl_server @@ -727,7 +770,7 @@ then tls13_psk_openssl_port=$server_port tls13_psk_openssl_pid=$server_pid - psk="-s" + psk="-s --openssl-psk" wolfssl_suite="TLSv1.3_PSK" start_wolfssl_server tls13_psk_wolfssl_port=$server_port @@ -977,8 +1020,8 @@ do *ECDHE-ECDSA*|*ECDH-ECDSA*) if [ "$wolf_ecc" != "" ] then - cert="${CERT_DIR}/client-cert.pem" - key="${CERT_DIR}/client-key.pem" + cert="${CERT_DIR}/client-ecc-cert.pem" + key="${CERT_DIR}/ecc-client-key.pem" caCert="${CERT_DIR}/ca-ecc-cert.pem" port=$ecdsa_openssl_port @@ -1090,7 +1133,7 @@ do wolf_temp_cases_total=$((wolf_temp_cases_total + 1)) port=$tls13_psk_openssl_port - psk="-s" + psk="-s --openssl-psk" # OpenSSL doesn't support DH for key exchange so do no PSK # DHE when ECC not supported if [ "$wolf_ecc" = "" ] diff --git a/src/internal.c b/src/internal.c index c99585cf860..e36acef0684 100644 --- a/src/internal.c +++ b/src/internal.c @@ -25430,6 +25430,29 @@ int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz) if (ret == 0 && hashAlgo > ssl->options.hashAlgo) break; #endif + if (IsAtLeastTLSv1_2(ssl) && !IsAtLeastTLSv1_3(ssl->version) && + (ssl->options.side == WOLFSSL_CLIENT_END)) { + /* TLS 1.2 client deciding hash algorithm for + * CertificateVerify. Hash must be one of the handshake + * hashes being maintained. */ + if (1 + #ifndef NO_SHA + && (hashAlgo != sha_mac) + #endif + #ifndef NO_SHA256 + && (hashAlgo != sha256_mac) + #endif + #ifdef WOLFSSL_SHA384 + && (hashAlgo != sha384_mac) + #endif + #ifdef WOLFSSL_SHA512 + && (hashAlgo != sha512_mac) + #endif + ) + { + break; + } + } /* The chosen one - but keep looking. */ ssl->options.hashAlgo = hashAlgo; ssl->options.sigAlgo = sigAlgo; @@ -30203,17 +30226,22 @@ int SendCertificateVerify(WOLFSSL* ssl) } #endif - #ifndef NO_OLD_TLS - #ifndef NO_SHA - /* old tls default */ - SetDigest(ssl, sha_mac); - #endif - #else - #ifndef NO_SHA256 - /* new tls default */ - SetDigest(ssl, sha256_mac); - #endif - #endif /* !NO_OLD_TLS */ + if (!IsAtLeastTLSv1_2(ssl)) { + #ifndef NO_OLD_TLS + #ifndef NO_SHA + /* old tls default */ + SetDigest(ssl, sha_mac); + #endif + #else + #ifndef NO_SHA256 + /* new tls default */ + SetDigest(ssl, sha256_mac); + #endif + #endif /* !NO_OLD_TLS */ + } + else { + SetDigest(ssl, ssl->options.hashAlgo); + } if (ssl->hsType == DYNAMIC_TYPE_RSA) { #ifdef WC_RSA_PSS diff --git a/src/pk.c b/src/pk.c index 8ac6a8271fd..34637376158 100644 --- a/src/pk.c +++ b/src/pk.c @@ -30,6 +30,15 @@ #include #endif +#ifdef HAVE_ECC + #include +#endif +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + #if !defined(WOLFSSL_PK_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN #warning pk.c does not need to be compiled separately from ssl.c @@ -11395,7 +11404,7 @@ static int wolfssl_ec_key_int_copy(ecc_key* dst, const ecc_key* src) if (ret == 0) { /* Copy private key. */ - ret = mp_copy(&src->k, &dst->k); + ret = mp_copy(wc_ecc_key_get_priv(src), wc_ecc_key_get_priv(dst)); if (ret != MP_OKAY) { WOLFSSL_MSG("mp_copy error"); } @@ -12533,7 +12542,8 @@ int SetECKeyExternal(WOLFSSL_EC_KEY* eckey) /* set the external privkey */ if ((ret == 1) && (key->type == ECC_PRIVATEKEY) && - (wolfssl_bn_set_value(&eckey->priv_key, &key->k) != 1)) { + (wolfssl_bn_set_value(&eckey->priv_key, + wc_ecc_key_get_priv(key)) != 1)) { WOLFSSL_MSG("ec priv key error"); ret = -1; } @@ -12604,12 +12614,13 @@ int SetECKeyInternal(WOLFSSL_EC_KEY* eckey) /* set privkey */ if ((ret == 1) && (eckey->priv_key != NULL)) { - if (wolfssl_bn_get_value(eckey->priv_key, &key->k) != 1) { + if (wolfssl_bn_get_value(eckey->priv_key, + wc_ecc_key_get_priv(key)) != 1) { WOLFSSL_MSG("ec key priv error"); ret = -1; } /* private key */ - if ((ret == 1) && (!mp_iszero(&key->k))) { + if ((ret == 1) && (!mp_iszero(wc_ecc_key_get_priv(key)))) { if (pubSet) { key->type = ECC_PRIVATEKEY; } diff --git a/tests/api.c b/tests/api.c index 981671d50a6..26aa797b5ee 100644 --- a/tests/api.c +++ b/tests/api.c @@ -358,6 +358,12 @@ #endif #include +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + typedef struct testVector { const char* input; const char* output; @@ -27393,25 +27399,30 @@ static int test_wc_ecc_mulmod(void) } if (ret == 0) { - ret = wc_ecc_mulmod(&key1.k, &key2.pubkey, &key3.pubkey, &key2.k, - &key3.k, 1); + ret = wc_ecc_mulmod(wc_ecc_key_get_priv(&key1), &key2.pubkey, + &key3.pubkey, wc_ecc_key_get_priv(&key2), + wc_ecc_key_get_priv(&key3), 1); } /* Test bad args. */ if (ret == 0) { - ret = wc_ecc_mulmod(NULL, &key2.pubkey, &key3.pubkey, &key2.k, - &key3.k, 1); + ret = wc_ecc_mulmod(NULL, &key2.pubkey, &key3.pubkey, + wc_ecc_key_get_priv(&key2), + wc_ecc_key_get_priv(&key3), 1); if (ret == ECC_BAD_ARG_E) { - ret = wc_ecc_mulmod(&key1.k, NULL, &key3.pubkey, &key2.k, - &key3.k, 1); + ret = wc_ecc_mulmod(wc_ecc_key_get_priv(&key1), NULL, &key3.pubkey, + wc_ecc_key_get_priv(&key2), + wc_ecc_key_get_priv(&key3), 1); } if (ret == ECC_BAD_ARG_E) { - ret = wc_ecc_mulmod(&key1.k, &key2.pubkey, NULL, &key2.k, - &key3.k, 1); + ret = wc_ecc_mulmod(wc_ecc_key_get_priv(&key1), &key2.pubkey, NULL, + wc_ecc_key_get_priv(&key2), + wc_ecc_key_get_priv(&key3), 1); } if (ret == ECC_BAD_ARG_E) { - ret = wc_ecc_mulmod(&key1.k, &key2.pubkey, &key3.pubkey, - &key2.k, NULL, 1); + ret = wc_ecc_mulmod(wc_ecc_key_get_priv(&key1), &key2.pubkey, + &key3.pubkey, wc_ecc_key_get_priv(&key2), NULL, + 1); } if (ret == ECC_BAD_ARG_E) { ret = 0; diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index bfa69d564ce..2a183d73965 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -3366,8 +3366,43 @@ static int ecc_key_tmp_init(ecc_key* key, void* heap) { int err = MP_OKAY; + (void)heap; + XMEMSET(key, 0, sizeof(*key)); +#if defined(WOLFSSL_SP_MATH_ALL) && defined(WOLFSSL_SMALL_STACK) + NEW_MP_INT_SIZE(key->t1, ECC_KEY_MAX_BITS(key), heap, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(key->t2, ECC_KEY_MAX_BITS(key), heap, DYNAMIC_TYPE_ECC); +#ifdef ALT_ECC_SIZE + NEW_MP_INT_SIZE(key->x, ECC_KEY_MAX_BITS(key), heap, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(key->y, ECC_KEY_MAX_BITS(key), heap, DYNAMIC_TYPE_ECC); + NEW_MP_INT_SIZE(key->z, ECC_KEY_MAX_BITS(key), heap, DYNAMIC_TYPE_ECC); +#endif + if (key->t1 == NULL || key->t2 == NULL +#ifdef ALT_ECC_SIZE + || key->x == NULL || key->y == NULL || key->z == NULL +#endif + ) { + err = MEMORY_E; + } + if (err == 0) { + err = INIT_MP_INT_SIZE(key->t1, ECC_KEY_MAX_BITS(key)); + } + if (err == 0) { + err = INIT_MP_INT_SIZE(key->t2, ECC_KEY_MAX_BITS(key)); + } +#ifdef ALT_ECC_SIZE + if (err == 0) { + err = INIT_MP_INT_SIZE(key->x, ECC_KEY_MAX_BITS(key)); + } + if (err == 0) { + err = INIT_MP_INT_SIZE(key->y, ECC_KEY_MAX_BITS(key)); + } + if (err == 0) { + err = INIT_MP_INT_SIZE(key->z, ECC_KEY_MAX_BITS(key)); + } +#endif +#else key->t1 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC); key->t2 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC); #ifdef ALT_ECC_SIZE @@ -3382,6 +3417,7 @@ static int ecc_key_tmp_init(ecc_key* key, void* heap) ) { err = MEMORY_E; } +#endif return err; } @@ -3389,6 +3425,16 @@ static int ecc_key_tmp_init(ecc_key* key, void* heap) static void ecc_key_tmp_final(ecc_key* key, void* heap) { (void)heap; + +#if defined(WOLFSSL_SP_MATH_ALL) && defined(WOLFSSL_SMALL_STACK) +#ifdef ALT_ECC_SIZE + FREE_MP_INT_SIZE(key->z, heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(key->y, heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(key->x, heap, DYNAMIC_TYPE_ECC); +#endif + FREE_MP_INT_SIZE(key->t2, heap, DYNAMIC_TYPE_ECC); + FREE_MP_INT_SIZE(key->t1, heap, DYNAMIC_TYPE_ECC); +#else #ifdef ALT_ECC_SIZE if (key->z != NULL) XFREE(key->z, heap, DYNAMIC_TYPE_ECC); @@ -3401,6 +3447,7 @@ static void ecc_key_tmp_final(ecc_key* key, void* heap) XFREE(key->t2, heap, DYNAMIC_TYPE_ECC); if (key->t1 != NULL) XFREE(key->t1, heap, DYNAMIC_TYPE_ECC); +#endif } #endif /* WOLFSSL_SMALL_STACK_CACHE */ #endif /* !WOLFSSL_SP_MATH */ @@ -4459,7 +4506,7 @@ int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, byte* out, word32* outlen) { int err = MP_OKAY; - mp_int* k = &private_key->k; + mp_int* k = private_key->k; #ifdef HAVE_ECC_CDH #ifdef WOLFSSL_SMALL_STACK mp_int *k_lcl = NULL; @@ -4489,7 +4536,7 @@ int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, goto errout; } /* multiply cofactor times private key "k" */ - err = mp_mul_d(&private_key->k, cofactor, k); + err = mp_mul_d(private_key->k, cofactor, k); if (err != MP_OKAY) goto errout; } @@ -4722,7 +4769,7 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, word32 keySz = private_key->dp->size; /* sync public key x/y */ - err = wc_mp_to_bigint_sz(&private_key->k, &private_key->k.raw, keySz); + err = wc_mp_to_bigint_sz(private_key->k, &private_key->k->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(point->x, &point->x->raw, keySz); if (err == MP_OKAY) @@ -4736,7 +4783,7 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, NitroxEccGetSize(private_key)*2); if (err == MP_OKAY) err = NitroxEcdh(private_key, - &private_key->k.raw, &point->x->raw, &point->y->raw, + &private_key->k->raw, &point->x->raw, &point->y->raw, private_key->e->raw.buf, &private_key->e->raw.len, &curve->prime->raw); #else @@ -4744,7 +4791,7 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, err = wc_ecc_curve_load(private_key->dp, &curve, ECC_CURVE_FIELD_BF); if (err == MP_OKAY) err = IntelQaEcdh(&private_key->asyncDev, - &private_key->k.raw, &point->x->raw, &point->y->raw, + &private_key->k->raw, &point->x->raw, &point->y->raw, out, outlen, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, private_key->dp->cofactor); @@ -5061,8 +5108,8 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, key->type = ECC_PRIVATEKEY_ONLY; } - if ((err == MP_OKAY) && (mp_iszero(&key->k) || mp_isneg(&key->k) || - (mp_cmp(&key->k, curve->order) != MP_LT))) + if ((err == MP_OKAY) && (mp_iszero(key->k) || mp_isneg(key->k) || + (mp_cmp(key->k, curve->order) != MP_LT))) { err = ECC_PRIV_KEY_E; } @@ -5085,10 +5132,10 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, if (err == MP_OKAY && key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { word32 keySz = key->dp->size; /* sync private key to raw */ - err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz); + err = wc_mp_to_bigint_sz(key->k, &key->k->raw, keySz); if (err == MP_OKAY) { err = IntelQaEccPointMul(&key->asyncDev, - &key->k.raw, pub->x, pub->y, pub->z, + &key->k->raw, pub->x, pub->y, pub->z, &curve->Gx->raw, &curve->Gy->raw, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, key->dp->cofactor); @@ -5104,19 +5151,19 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, else #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { - err = sp_ecc_mulmod_base_256(&key->k, pub, 1, key->heap); + err = sp_ecc_mulmod_base_256(key->k, pub, 1, key->heap); } else #endif #ifdef WOLFSSL_SP_384 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) { - err = sp_ecc_mulmod_base_384(&key->k, pub, 1, key->heap); + err = sp_ecc_mulmod_base_384(key->k, pub, 1, key->heap); } else #endif #ifdef WOLFSSL_SP_521 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP521R1) { - err = sp_ecc_mulmod_base_521(&key->k, pub, 1, key->heap); + err = sp_ecc_mulmod_base_521(key->k, pub, 1, key->heap); } else #endif @@ -5148,7 +5195,7 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, /* make the public key */ if (err == MP_OKAY) { /* Map in a separate call as this should be constant time */ - err = wc_ecc_mulmod_ex2(&key->k, base, pub, curve->Af, curve->prime, + err = wc_ecc_mulmod_ex2(key->k, base, pub, curve->Af, curve->prime, curve->order, rng, 0, key->heap); if (err == MP_MEM) { err = MEMORY_E; @@ -5388,7 +5435,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, } if (err == SA_SILIB_RET_OK) { - err = mp_read_unsigned_bin(&key->k, ucompressed_key, raw_size); + err = mp_read_unsigned_bin(key->k, ucompressed_key, raw_size); } #elif defined(WOLFSSL_SILABS_SE_ACCEL) @@ -5440,7 +5487,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, err = xil_mpi_import(key->pubkey.y, key->keyRaw + key->dp->size, key->dp->size, key->heap); if (err == 0) - err = xil_mpi_import(&key->k, key->privKey, key->dp->size, key->heap); + err = xil_mpi_import(key->k, key->privKey, key->dp->size, key->heap); if (err == 0) err = mp_set(key->pubkey.z, 1); if (err) { @@ -5458,20 +5505,20 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { #ifndef WC_ECC_NONBLOCK - err = sp_ecc_make_key_256(rng, &key->k, &key->pubkey, key->heap); + err = sp_ecc_make_key_256(rng, key->k, &key->pubkey, key->heap); #else if (key->nb_ctx) { - err = sp_ecc_make_key_256_nb(&key->nb_ctx->sp_ctx, rng, &key->k, + err = sp_ecc_make_key_256_nb(&key->nb_ctx->sp_ctx, rng, key->k, &key->pubkey, key->heap); } else { #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ - err = sp_ecc_make_key_256_nb(&nb_ctx.sp_ctx, rng, &key->k, + err = sp_ecc_make_key_256_nb(&nb_ctx.sp_ctx, rng, key->k, &key->pubkey, key->heap); } while (err == FP_WOULDBLOCK); #else - err = sp_ecc_make_key_256(rng, &key->k, &key->pubkey, key->heap); + err = sp_ecc_make_key_256(rng, key->k, &key->pubkey, key->heap); #endif /* WC_ECC_NONBLOCK_ONLY */ } #endif /* !WC_ECC_NONBLOCK */ @@ -5485,20 +5532,20 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #ifdef WOLFSSL_SP_384 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) { #ifndef WC_ECC_NONBLOCK - err = sp_ecc_make_key_384(rng, &key->k, &key->pubkey, key->heap); + err = sp_ecc_make_key_384(rng, key->k, &key->pubkey, key->heap); #else if (key->nb_ctx) { - err = sp_ecc_make_key_384_nb(&key->nb_ctx->sp_ctx, rng, &key->k, + err = sp_ecc_make_key_384_nb(&key->nb_ctx->sp_ctx, rng, key->k, &key->pubkey, key->heap); } else { #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ - err = sp_ecc_make_key_384_nb(&nb_ctx.sp_ctx, rng, &key->k, + err = sp_ecc_make_key_384_nb(&nb_ctx.sp_ctx, rng, key->k, &key->pubkey, key->heap); } while (err == FP_WOULDBLOCK); #else - err = sp_ecc_make_key_384(rng, &key->k, &key->pubkey, key->heap); + err = sp_ecc_make_key_384(rng, key->k, &key->pubkey, key->heap); #endif /* WC_ECC_NONBLOCK_ONLY */ } #endif /* !WC_ECC_NONBLOCK */ @@ -5512,20 +5559,20 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #ifdef WOLFSSL_SP_521 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP521R1) { #ifndef WC_ECC_NONBLOCK - err = sp_ecc_make_key_521(rng, &key->k, &key->pubkey, key->heap); + err = sp_ecc_make_key_521(rng, key->k, &key->pubkey, key->heap); #else if (key->nb_ctx) { - err = sp_ecc_make_key_521_nb(&key->nb_ctx->sp_ctx, rng, &key->k, + err = sp_ecc_make_key_521_nb(&key->nb_ctx->sp_ctx, rng, key->k, &key->pubkey, key->heap); } else { #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ - err = sp_ecc_make_key_521_nb(&nb_ctx.sp_ctx, rng, &key->k, + err = sp_ecc_make_key_521_nb(&nb_ctx.sp_ctx, rng, key->k, &key->pubkey, key->heap); } while (err == FP_WOULDBLOCK); #else - err = sp_ecc_make_key_521(rng, &key->k, &key->pubkey, key->heap); + err = sp_ecc_make_key_521(rng, key->k, &key->pubkey, key->heap); #endif /* WC_ECC_NONBLOCK_ONLY */ } #endif /* !WC_ECC_NONBLOCK */ @@ -5545,7 +5592,12 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); /* setup the key variables */ - err = mp_init(&key->k); +#ifndef ALT_ECC_SIZE + err = mp_init(key->k); +#else + key->k = (mp_int*)key->ka; + alt_fp_init(key->k); +#endif /* load curve info */ if (err == MP_OKAY) { @@ -5557,7 +5609,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, /* generate k */ if (err == MP_OKAY) { - err = wc_ecc_gen_k(rng, key->dp->size, &key->k, curve->order); + err = wc_ecc_gen_k(rng, key->dp->size, key->k, curve->order); } /* generate public key from k */ @@ -5574,7 +5626,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, } else { /* cleanup these on failure case only */ - mp_forcezero(&key->k); + mp_forcezero(key->k); } /* cleanup allocations */ @@ -5585,7 +5637,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #ifdef HAVE_WOLF_BIGINT if (err == MP_OKAY) - err = wc_mp_to_bigint(&key->k, &key->k.raw); + err = wc_mp_to_bigint(key->k, &key->k->raw); if (err == MP_OKAY) err = wc_mp_to_bigint(key->pubkey.x, &key->pubkey.x->raw); if (err == MP_OKAY) @@ -5774,12 +5826,10 @@ int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); - ret = mp_init(&key->k); - if (ret != MP_OKAY) { - return MEMORY_E; - } + key->k = (mp_int*)key->ka; + alt_fp_init(key->k); #else - ret = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, + ret = mp_init_multi(key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); if (ret != MP_OKAY) { return MEMORY_E; @@ -5818,7 +5868,7 @@ int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) #endif #ifdef WOLFSSL_CHECK_MEM_ZERO - mp_memzero_add("ECC k", &key->k); + mp_memzero_add("ECC k", key->k); #endif #if defined(WOLFSSL_XILINX_CRYPT_VERSAL) @@ -6385,7 +6435,7 @@ static int deterministic_sign_helper(const byte* in, word32 inlen, ecc_key* key) /* currently limiting to SHA256 for auto create */ if (mp_init(key->sign_k) != MP_OKAY || wc_ecc_gen_deterministic_k(in, inlen, - WC_HASH_TYPE_SHA256, &key->k, key->sign_k, + WC_HASH_TYPE_SHA256, key->k, key->sign_k, curve->order, key->heap) != 0) { mp_free(key->sign_k); XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC); @@ -6404,7 +6454,7 @@ static int deterministic_sign_helper(const byte* in, word32 inlen, ecc_key* key) #else key->sign_k_set = 0; /* currently limiting to SHA256 for auto create */ - if (wc_ecc_gen_deterministic_k(in, inlen, WC_HASH_TYPE_SHA256, &key->k, + if (wc_ecc_gen_deterministic_k(in, inlen, WC_HASH_TYPE_SHA256, key->k, key->sign_k, curve->order, key->heap) != 0) { err = ECC_PRIV_KEY_E; } @@ -6494,7 +6544,7 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, } /* use provided sign_k */ - err = mp_copy(key->sign_k, &pubkey->k); + err = mp_copy(key->sign_k, pubkey->k); if (err != MP_OKAY) break; /* free sign_k, so only used once */ @@ -6529,7 +6579,7 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, } #ifdef WOLFSSL_CHECK_MEM_ZERO if (err == MP_OKAY) { - mp_memzero_add("ecc_sign_hash_sw k", &pubkey->k); + mp_memzero_add("ecc_sign_hash_sw k", pubkey->k); } #endif #ifdef WOLFSSL_ASYNC_CRYPT @@ -6543,15 +6593,15 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, if (err != MP_OKAY) break; if (mp_iszero(r) == MP_NO) { - mp_int* ep = &pubkey->k; - mp_int* kp = &pubkey->k; - mp_int* x = &key->k; + mp_int* ep = pubkey->k; + mp_int* kp = pubkey->k; + mp_int* x = key->k; /* find s = (e + xr)/k = b.(e/k.b + x.r/k.b) */ /* k' = k.b */ - err = mp_mulmod(&pubkey->k, b, curve->order, kp); + err = mp_mulmod(pubkey->k, b, curve->order, kp); if (err != MP_OKAY) break; /* k' = 1/k.b @@ -6593,7 +6643,7 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, mp_clear(pubkey->pubkey.y); mp_clear(pubkey->pubkey.z); #endif - mp_forcezero(&pubkey->k); + mp_forcezero(pubkey->k); } mp_forcezero(b); FREE_MP_INT_SIZE(b, key->heap, DYNAMIC_TYPE_ECC); @@ -6630,12 +6680,12 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #endif if (key->nb_ctx) { return sp_ecc_sign_256_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, - &key->k, r, s, sign_k, key->heap); + key->k, r, s, sign_k, key->heap); } #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ err = sp_ecc_sign_256_nb(&nb_ctx.sp_ctx, in, inlen, rng, - &key->k, r, s, sign_k, key->heap); + key->k, r, s, sign_k, key->heap); } while (err == FP_WOULDBLOCK); return err; #endif @@ -6644,7 +6694,7 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, { int ret; SAVE_VECTOR_REGISTERS(return _svr_ret;); - ret = sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, sign_k, + ret = sp_ecc_sign_256(in, inlen, rng, key->k, r, s, sign_k, key->heap); RESTORE_VECTOR_REGISTERS(); return ret; @@ -6660,12 +6710,12 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #endif if (key->nb_ctx) { return sp_ecc_sign_384_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, - &key->k, r, s, sign_k, key->heap); + key->k, r, s, sign_k, key->heap); } #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ err = sp_ecc_sign_384_nb(&nb_ctx.sp_ctx, in, inlen, rng, - &key->k, r, s, sign_k, key->heap); + key->k, r, s, sign_k, key->heap); } while (err == FP_WOULDBLOCK); return err; #endif @@ -6674,7 +6724,7 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, { int ret; SAVE_VECTOR_REGISTERS(return _svr_ret;); - ret = sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, sign_k, + ret = sp_ecc_sign_384(in, inlen, rng, key->k, r, s, sign_k, key->heap); RESTORE_VECTOR_REGISTERS(); return ret; @@ -6690,12 +6740,12 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #endif if (key->nb_ctx) { return sp_ecc_sign_521_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, - &key->k, r, s, sign_k, key->heap); + key->k, r, s, sign_k, key->heap); } #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ err = sp_ecc_sign_521_nb(&nb_ctx.sp_ctx, in, inlen, rng, - &key->k, r, s, sign_k, key->heap); + key->k, r, s, sign_k, key->heap); } while (err == FP_WOULDBLOCK); return err; #endif @@ -6704,7 +6754,7 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, { int ret; SAVE_VECTOR_REGISTERS(return _svr_ret;); - ret = sp_ecc_sign_521(in, inlen, rng, &key->k, r, s, sign_k, + ret = sp_ecc_sign_521(in, inlen, rng, key->k, r, s, sign_k, key->heap); RESTORE_VECTOR_REGISTERS(); return ret; @@ -6925,7 +6975,7 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, if (err == MP_OKAY) err = wc_mp_to_bigint_sz(e, &e->raw, keySz); if (err == MP_OKAY) - err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz); + err = wc_mp_to_bigint_sz(key->k, &key->k->raw, keySz); if (err == MP_OKAY) err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order); if (err == MP_OKAY) @@ -6933,11 +6983,11 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, #ifdef HAVE_CAVIUM_V if (err == MP_OKAY) - err = NitroxEcdsaSign(key, &e->raw, &key->k.raw, &k->raw, + err = NitroxEcdsaSign(key, &e->raw, &key->k->raw, &k->raw, &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw); #else if (err == MP_OKAY) - err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k.raw, + err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k->raw, &k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, &curve->order->raw, &curve->Gx->raw, &curve->Gy->raw); @@ -7438,7 +7488,7 @@ int wc_ecc_free(ecc_key* key) mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); - mp_forcezero(&key->k); + mp_forcezero(key->k); #ifdef WOLFSSL_CUSTOM_CURVES if (key->deallocSet && key->dp != NULL) @@ -7900,7 +7950,7 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, #endif XFREE(key->t2, heap, DYNAMIC_TYPE_ECC); XFREE(key->t1, heap, DYNAMIC_TYPE_ECC); - XFREE(key, heap, DYNAMIC_TYPE_ECC); + XFREE(key, heap, DYNAMIC_TYPE_ECC_BUFFER); C->key = NULL; #endif #ifdef WOLFSSL_SMALL_STACK @@ -9473,7 +9523,7 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { if (err == MP_OKAY) { - err = sp_ecc_mulmod_base_256(&key->k, res, 1, key->heap); + err = sp_ecc_mulmod_base_256(key->k, res, 1, key->heap); } } else @@ -9481,7 +9531,7 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #ifdef WOLFSSL_SP_384 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) { if (err == MP_OKAY) { - err = sp_ecc_mulmod_base_384(&key->k, res, 1, key->heap); + err = sp_ecc_mulmod_base_384(key->k, res, 1, key->heap); } } else @@ -9489,7 +9539,7 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #ifdef WOLFSSL_SP_521 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP521R1) { if (err == MP_OKAY) { - err = sp_ecc_mulmod_base_521(&key->k, res, 1, key->heap); + err = sp_ecc_mulmod_base_521(key->k, res, 1, key->heap); } } else @@ -9542,11 +9592,11 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #else #ifdef ECC_TIMING_RESISTANT if (err == MP_OKAY) - err = wc_ecc_mulmod_ex2(&key->k, base, res, a, prime, curve->order, + err = wc_ecc_mulmod_ex2(key->k, base, res, a, prime, curve->order, key->rng, 1, key->heap); #else if (err == MP_OKAY) - err = wc_ecc_mulmod_ex2(&key->k, base, res, a, prime, curve->order, + err = wc_ecc_mulmod_ex2(key->k, base, res, a, prime, curve->order, NULL, 1, key->heap); #endif #endif /* WOLFSSL_KCAPI_ECC */ @@ -9813,25 +9863,25 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { return sp_ecc_check_key_256(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? &key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); } #endif #ifdef WOLFSSL_SP_384 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) { return sp_ecc_check_key_384(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? &key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); } #endif #ifdef WOLFSSL_SP_521 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP521R1) { return sp_ecc_check_key_521(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? &key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); } #endif #if defined(WOLFSSL_SP_1024) && defined(WOLFCRYPT_HAVE_SAKKE) if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SAKKE_1) { return sp_ecc_check_key_1024(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? &key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); } #endif #endif @@ -9946,8 +9996,8 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) /* SP 800-56Ar3, section 5.6.2.1.2 */ /* private keys must be in the range [1, n-1] */ if ((err == MP_OKAY) && (key->type == ECC_PRIVATEKEY) && - (mp_iszero(&key->k) || mp_isneg(&key->k) || - (mp_cmp(&key->k, curve->order) != MP_LT)) + (mp_iszero(key->k) || mp_isneg(key->k) || + (mp_cmp(key->k, curve->order) != MP_LT)) #ifdef WOLFSSL_KCAPI_ECC && key->handle == NULL #endif @@ -10029,9 +10079,10 @@ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); - err = mp_init(&key->k); + key->k = (mp_int*)key->ka; + alt_fp_init(key->k); #else - err = mp_init_multi(&key->k, + err = mp_init_multi(key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); #endif if (err != MP_OKAY) @@ -10277,7 +10328,7 @@ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, mp_clear(key->pubkey.x); mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); - mp_clear(&key->k); + mp_clear(key->k); } RESTORE_VECTOR_REGISTERS(); @@ -10336,7 +10387,7 @@ int wc_ecc_export_ex(ecc_key* key, byte* qx, word32* qxLen, return BUFFER_E; } - err = wc_export_int(&key->k, d, dLen, keySz + WC_CAAM_MAC_SZ, + err = wc_export_int(key->k, d, dLen, keySz + WC_CAAM_MAC_SZ, encType); *dLen = keySz + WC_CAAM_MAC_SZ; } @@ -10358,7 +10409,7 @@ int wc_ecc_export_ex(ecc_key* key, byte* qx, word32* qxLen, else #endif { - err = wc_export_int(&key->k, d, dLen, keySz, encType); + err = wc_export_int(key->k, d, dLen, keySz, encType); if (err != MP_OKAY) return err; } @@ -10490,11 +10541,11 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, return ret; } - ret = mp_read_unsigned_bin(&key->k, priv, privSz); + ret = mp_read_unsigned_bin(key->k, priv, privSz); } #elif defined(WOLFSSL_SILABS_SE_ACCEL) if (ret == MP_OKAY) - ret = mp_read_unsigned_bin(&key->k, priv, privSz); + ret = mp_read_unsigned_bin(key->k, priv, privSz); if (ret == MP_OKAY) { if (pub) { @@ -10533,12 +10584,12 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, } #else key->blackKey = CAAM_BLACK_KEY_CCM; - ret = mp_read_unsigned_bin(&key->k, priv, privSz); + ret = mp_read_unsigned_bin(key->k, priv, privSz); #endif } else { key->blackKey = 0; - ret = mp_read_unsigned_bin(&key->k, priv, privSz); + ret = mp_read_unsigned_bin(key->k, priv, privSz); /* If using AES-ECB encrypted black keys check here if key is valid, * if not valid than assume is an encrypted key. A public key is needed @@ -10565,11 +10616,11 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, SAVE_VECTOR_REGISTERS(return _svr_ret;); #endif - ret = mp_read_unsigned_bin(&key->k, priv, privSz); + ret = mp_read_unsigned_bin(key->k, priv, privSz); #ifdef HAVE_WOLF_BIGINT if (ret == 0 && - wc_bigint_from_unsigned_bin(&key->k.raw, priv, privSz) != 0) { - mp_clear(&key->k); + wc_bigint_from_unsigned_bin(&key->k->raw, priv, privSz) != 0) { + mp_clear(key->k); ret = ASN_GETINT_E; } #endif /* HAVE_WOLF_BIGINT */ @@ -10594,7 +10645,7 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, if (ret == 0) { ret = mp_read_radix(order, key->dp->order, MP_RADIX_HEX); } - if ((ret == 0) && (mp_cmp(&key->k, order) != MP_LT)) { + if ((ret == 0) && (mp_cmp(key->k, order) != MP_LT)) { ret = ECC_PRIV_KEY_E; } @@ -10787,9 +10838,10 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); - err = mp_init(&key->k); + key->k = (mp_int*)key->ka; + alt_fp_init(key->k); #else - err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, + err = mp_init_multi(key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); #endif if (err != MP_OKAY) @@ -10940,12 +10992,12 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, key->type = ECC_PRIVATEKEY; if (encType == WC_TYPE_HEX_STR) - err = mp_read_radix(&key->k, d, MP_RADIX_HEX); + err = mp_read_radix(key->k, d, MP_RADIX_HEX); else - err = mp_read_unsigned_bin(&key->k, (const byte*)d, + err = mp_read_unsigned_bin(key->k, (const byte*)d, key->dp->size); if (err == MP_OKAY) { - err = wc_export_int(&key->k, &keyRaw[0], &keySz, keySz, + err = wc_export_int(key->k, &keyRaw[0], &keySz, keySz, WC_TYPE_UNSIGNED_BIN); } @@ -10965,17 +11017,17 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, #else key->type = ECC_PRIVATEKEY; if (encType == WC_TYPE_HEX_STR) - err = mp_read_radix(&key->k, d, MP_RADIX_HEX); + err = mp_read_radix(key->k, d, MP_RADIX_HEX); else { #if defined(WOLFSSL_QNX_CAAM) || defined(WOLFSSL_IMXRT1170_CAAM) if (key->blackKey == CAAM_BLACK_KEY_CCM) { - err = mp_read_unsigned_bin(&key->k, (const byte*)d, + err = mp_read_unsigned_bin(key->k, (const byte*)d, key->dp->size + WC_CAAM_MAC_SZ); } else #endif /* WOLFSSL_QNX_CAAM */ { - err = mp_read_unsigned_bin(&key->k, (const byte*)d, + err = mp_read_unsigned_bin(key->k, (const byte*)d, (word32)key->dp->size); } } @@ -10983,14 +11035,14 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, if (err == MP_OKAY) { const word32 key_size = key->dp->size; word32 buf_size = key_size; - err = wc_export_int(&key->k, key->privKey, + err = wc_export_int(key->k, key->privKey, &buf_size, key_size, WC_TYPE_UNSIGNED_BIN); mp_reverse(key->privKey, key_size); } #endif #endif /* #else-case of custom HW-specific implementations */ - if (mp_iszero(&key->k) || mp_isneg(&key->k)) { + if (mp_iszero(key->k) || mp_isneg(key->k)) { WOLFSSL_MSG("Invalid private key"); err = BAD_FUNC_ARG; } @@ -11023,7 +11075,7 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, mp_clear(key->pubkey.x); mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); - mp_clear(&key->k); + mp_clear(key->k); #if defined(WOLFSSL_XILINX_CRYPT_VERSAL) ForceZero(key->keyRaw, sizeof(key->keyRaw)); #endif diff --git a/wolfcrypt/src/eccsi.c b/wolfcrypt/src/eccsi.c index a707a5e3cff..23c95f49b06 100644 --- a/wolfcrypt/src/eccsi.c +++ b/wolfcrypt/src/eccsi.c @@ -43,6 +43,12 @@ #include #endif +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + /** * Initialize the components of the ECCSI key and use the specified curve. * @@ -594,7 +600,8 @@ static int eccsi_encode_key(EccsiKey* key, byte* data) word32 sz = (word32)key->ecc.dp->size * 2; /* Write out the secret value into key size bytes. */ - err = mp_to_unsigned_bin_len(&key->ecc.k, data, key->ecc.dp->size); + err = mp_to_unsigned_bin_len(wc_ecc_key_get_priv(&key->ecc), data, + key->ecc.dp->size); if (err == 0) { data += key->ecc.dp->size; /* Write the public key. */ @@ -676,7 +683,8 @@ static int eccsi_decode_key(EccsiKey* key, const byte* data) int err; /* Read the secret value from key size bytes. */ - err = mp_read_unsigned_bin(&key->ecc.k, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data, + key->ecc.dp->size); if (err == 0) { data += key->ecc.dp->size; /* Read public key. */ @@ -771,7 +779,8 @@ int wc_ExportEccsiPrivateKey(EccsiKey* key, byte* data, word32* sz) } } if (err == 0) { - err = mp_to_unsigned_bin_len(&key->ecc.k, data, key->ecc.dp->size); + err = mp_to_unsigned_bin_len(wc_ecc_key_get_priv(&key->ecc), data, + key->ecc.dp->size); } return err; @@ -804,7 +813,8 @@ int wc_ImportEccsiPrivateKey(EccsiKey* key, const byte* data, word32 sz) } if (err == 0) { - err = mp_read_unsigned_bin(&key->ecc.k, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data, + key->ecc.dp->size); } return err; @@ -907,18 +917,20 @@ static int eccsi_make_pair(EccsiKey* key, WC_RNG* rng, err = mp_read_unsigned_bin(ssk, key->data, hashSz); } if (err == 0) { - err = mp_mulmod(ssk, &key->pubkey.k, &key->params.order, ssk); + err = mp_mulmod(ssk, wc_ecc_key_get_priv(&key->pubkey), + &key->params.order, ssk); } if (err == 0) { - err = mp_addmod(ssk, &key->ecc.k, &key->params.order, ssk); + err = mp_addmod(ssk, wc_ecc_key_get_priv(&key->ecc), + &key->params.order, ssk); } } while ((err == 0) && (mp_iszero(ssk) || - (mp_cmp(ssk, &key->ecc.k) == MP_EQ))); + (mp_cmp(ssk, wc_ecc_key_get_priv(&key->ecc)) == MP_EQ))); /* Step 5: ensure SSK and HS are non-zero (code lines above) */ /* Step 6: Copy out SSK (done during calc) and PVT. Erase v */ - mp_forcezero(&key->pubkey.k); + mp_forcezero(wc_ecc_key_get_priv(&key->pubkey)); return err; } @@ -2005,7 +2017,7 @@ int wc_SignEccsiHash(EccsiKey* key, WC_RNG* rng, enum wc_HashType hashType, err = mp_invmod(s, &key->params.order, s); } if (err == 0) { - j = &key->pubkey.k; + j = wc_ecc_key_get_priv(&key->pubkey); err = mp_mulmod(s, j, &key->params.order, s); } if (err == 0) { @@ -2215,7 +2227,7 @@ int wc_VerifyEccsiHash(EccsiKey* key, enum wc_HashType hashType, SAVE_VECTOR_REGISTERS(return _svr_ret;); /* Decode the signature into components. */ - r = &key->pubkey.k; + r = wc_ecc_key_get_priv(&key->pubkey); pvt = &key->pubkey.pubkey; err = eccsi_decode_sig_r_pvt(key, sig, sigSz, r, pvt); diff --git a/wolfcrypt/src/port/caam/wolfcaam_ecdsa.c b/wolfcrypt/src/port/caam/wolfcaam_ecdsa.c index bf063e78066..f6bb27055a9 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_ecdsa.c +++ b/wolfcrypt/src/port/caam/wolfcaam_ecdsa.c @@ -47,6 +47,12 @@ #include #endif +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + #if defined(WOLFSSL_DEVCRYPTO_ECDSA) /* offload calls through devcrypto support */ @@ -79,7 +85,8 @@ static int wc_CAAM_DevEccSign(const byte* in, int inlen, byte* out, keySz = wc_ecc_size(key); /* private key */ - if (mp_to_unsigned_bin_len(&key->k, pk, keySz) != MP_OKAY) { + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(key), pk, keySz) != MP_OKAY) + { return MP_TO_E; } @@ -191,7 +198,8 @@ static int wc_CAAM_DevEcdh(ecc_key* private_key, ecc_key* public_key, byte* out, XMEMCPY(qxy+qxSz, qy, qySz); /* private key */ - if (mp_to_unsigned_bin_len(&private_key->k, pk, keySz) != MP_OKAY) { + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(private_key), pk, keySz) != + MP_OKAY) { WOLFSSL_MSG("error getting private key buffer"); return MP_TO_E; } @@ -330,14 +338,15 @@ int wc_CAAM_EccSign(const byte* in, int inlen, byte* out, word32* outlen, } else { if (key->blackKey == CAAM_BLACK_KEY_CCM) { - if (mp_to_unsigned_bin_len(&key->k, pk, keySz + WC_CAAM_MAC_SZ) - != MP_OKAY) { + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(key), pk, + keySz + WC_CAAM_MAC_SZ) != MP_OKAY) { return MP_TO_E; } buf[idx].Length = keySz + WC_CAAM_MAC_SZ; } else { - if (mp_to_unsigned_bin_len(&key->k, pk, keySz) != MP_OKAY) { + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(key), pk, keySz) != + MP_OKAY) { return MP_TO_E; } buf[idx].Length = keySz; @@ -599,14 +608,15 @@ int wc_CAAM_Ecdh(ecc_key* private_key, ecc_key* public_key, byte* out, } if (private_key->blackKey == CAAM_BLACK_KEY_CCM) { - if (mp_to_unsigned_bin_len(&private_key->k, pk, + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(private_key), pk, keySz + WC_CAAM_MAC_SZ) != MP_OKAY) { return MP_TO_E; } buf[idx].Length = keySz + WC_CAAM_MAC_SZ; } else { - if (mp_to_unsigned_bin_len(&private_key->k, pk, keySz) != MP_OKAY) { + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(private_key), pk, + keySz) != MP_OKAY) { return MP_TO_E; } buf[idx].Length = keySz; diff --git a/wolfcrypt/src/port/caam/wolfcaam_fsl_nxp.c b/wolfcrypt/src/port/caam/wolfcaam_fsl_nxp.c index ae02692c0bf..4a8801895e5 100644 --- a/wolfcrypt/src/port/caam/wolfcaam_fsl_nxp.c +++ b/wolfcrypt/src/port/caam/wolfcaam_fsl_nxp.c @@ -31,6 +31,12 @@ #include #include +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + #if defined(FSL_FEATURE_HAS_L1CACHE) || defined(__DCACHE_PRESENT) /* Setup for if memory is cached */ AT_NONCACHEABLE_SECTION(static caam_job_ring_interface_t jr0); @@ -439,13 +445,14 @@ int wc_CAAM_EccSign(const byte* in, int inlen, byte* out, word32* outlen, } else { if (key->blackKey == CAAM_BLACK_KEY_CCM) { - if (mp_to_unsigned_bin_len(&key->k, k, kSz + WC_CAAM_MAC_SZ) - != MP_OKAY) { + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(key), k, + kSz + WC_CAAM_MAC_SZ) != MP_OKAY) { return MP_TO_E; } } else { - if (mp_to_unsigned_bin_len(&key->k, k, kSz) != MP_OKAY) { + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(key), k, kSz) != + MP_OKAY) { return MP_TO_E; } } @@ -696,13 +703,14 @@ int wc_CAAM_Ecdh(ecc_key* private_key, ecc_key* public_key, byte* out, } if (private_key->blackKey == CAAM_BLACK_KEY_CCM) { - if (mp_to_unsigned_bin_len(&private_key->k, k, + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(private_key), k, keySz + WC_CAAM_MAC_SZ) != MP_OKAY) { return MP_TO_E; } } else { - if (mp_to_unsigned_bin_len(&private_key->k, k, keySz) != MP_OKAY) { + if (mp_to_unsigned_bin_len(wc_ecc_key_get_priv(private_key), k, keySz) + != MP_OKAY) { return MP_TO_E; } } diff --git a/wolfcrypt/src/port/kcapi/kcapi_ecc.c b/wolfcrypt/src/port/kcapi/kcapi_ecc.c index eedc87c8f4a..1f66b5222ac 100644 --- a/wolfcrypt/src/port/kcapi/kcapi_ecc.c +++ b/wolfcrypt/src/port/kcapi/kcapi_ecc.c @@ -34,6 +34,12 @@ #include #include +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + #ifndef ECC_CURVE_NIST_P256 #define ECC_CURVE_NIST_P256 2 #endif @@ -113,10 +119,11 @@ int KcapiEcc_LoadKey(ecc_key* key, byte* pubkey_raw, word32* pubkey_sz, /* set the key */ if (ret == 0) { - if (mp_iszero(&key->k) != MP_YES) { + if (mp_iszero(wc_ecc_key_get_priv(key)) != MP_YES) { /* if a private key value is set, load and use it */ byte priv[MAX_ECC_BYTES]; - ret = wc_export_int(&key->k, priv, &keySz, keySz, WC_TYPE_UNSIGNED_BIN); + ret = wc_export_int(wc_ecc_key_get_priv(key), priv, &keySz, keySz, + WC_TYPE_UNSIGNED_BIN); if (ret == 0) { ret = kcapi_kpp_setkey(key->handle, priv, keySz); } @@ -231,10 +238,10 @@ int KcapiEcc_SharedSecret(ecc_key* private_key, ecc_key* public_key, byte* out, } /* if a private key value is set, load and use it */ - if (ret == 0 && mp_iszero(&private_key->k) != MP_YES) { + if (ret == 0 && mp_iszero(wc_ecc_key_get_priv(private_key)) != MP_YES) { byte priv[MAX_ECC_BYTES]; - ret = wc_export_int(&private_key->k, priv, &keySz, keySz, - WC_TYPE_UNSIGNED_BIN); + ret = wc_export_int(wc_ecc_key_get_priv(private_key), priv, &keySz, + keySz, WC_TYPE_UNSIGNED_BIN); if (ret == 0) { ret = kcapi_kpp_setkey(private_key->handle, priv, keySz); if (ret >= 0) { @@ -302,8 +309,8 @@ static int KcapiEcc_SetPrivKey(ecc_key* key) else #endif { - ret = wc_export_int(&key->k, priv + KCAPI_PARAM_SZ, &keySz, keySz, - WC_TYPE_UNSIGNED_BIN); + ret = wc_export_int(wc_ecc_key_get_priv(key), priv + KCAPI_PARAM_SZ, + &keySz, keySz, WC_TYPE_UNSIGNED_BIN); } } if (ret == 0) { diff --git a/wolfcrypt/src/port/maxim/maxq10xx.c b/wolfcrypt/src/port/maxim/maxq10xx.c index b7f136ca41f..a4736bf0641 100644 --- a/wolfcrypt/src/port/maxim/maxq10xx.c +++ b/wolfcrypt/src/port/maxim/maxq10xx.c @@ -43,6 +43,12 @@ #include #include +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + #ifdef MAXQ_DEBUG void dbg_dumphex(const char *identifier, const uint8_t* pdata, uint32_t plen); #else @@ -525,8 +531,9 @@ int wc_MAXQ10XX_EccSetKey(ecc_key* key, word32 keysize) if (err == 0) { if ((keytype == ECC_PRIVATEKEY) || (keytype == ECC_PRIVATEKEY_ONLY)) { - err = wc_export_int(&key->k, key->maxq_ctx.ecc_key + (2 * keysize), - &bufflen, keysize, WC_TYPE_UNSIGNED_BIN); + err = wc_export_int(wc_ecc_key_get_priv(key), + key->maxq_ctx.ecc_key + (2 * keysize), &bufflen, keysize, + WC_TYPE_UNSIGNED_BIN); } } diff --git a/wolfcrypt/src/port/silabs/silabs_ecc.c b/wolfcrypt/src/port/silabs/silabs_ecc.c index 1a820bef691..dcd6b256880 100644 --- a/wolfcrypt/src/port/silabs/silabs_ecc.c +++ b/wolfcrypt/src/port/silabs/silabs_ecc.c @@ -32,6 +32,11 @@ #include #include +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif #define SILABS_UNSUPPORTED_KEY_TYPE 0xFFFFFFFF @@ -163,7 +168,7 @@ int silabs_ecc_make_key(ecc_key* key, int keysize) mp_read_unsigned_bin (key->pubkey.y, key->key.storage.location.buffer.pointer + keysize, keysize); - mp_read_unsigned_bin (&key->k, + mp_read_unsigned_bin (wc_ecc_key_get_priv(key), key->key.storage.location.buffer.pointer + 2 * keysize, keysize); @@ -203,9 +208,9 @@ int silabs_ecc_import(ecc_key* key, word32 keysize) &used, keysize, WC_TYPE_UNSIGNED_BIN); if (err == MP_OKAY) - err = wc_export_int(&key->k, key->key.storage.location.buffer.pointer + 2 * keysize, - &used, keysize, - WC_TYPE_UNSIGNED_BIN); + err = wc_export_int(wc_ecc_key_get_priv(key), + key->key.storage.location.buffer.pointer + 2 * keysize, &used, + keysize, WC_TYPE_UNSIGNED_BIN); return err; } @@ -229,9 +234,9 @@ int silabs_ecc_import_private(ecc_key* key, word32 keysize) if (sl_stat != SL_STATUS_OK) return WC_HW_E; - ret = wc_export_int(&key->k, key->key.storage.location.buffer.pointer, - &keySz, keySz, - WC_TYPE_UNSIGNED_BIN); + ret = wc_export_int(wc_ecc_key_get_priv(key), + key->key.storage.location.buffer.pointer, &keySz, keySz, + WC_TYPE_UNSIGNED_BIN); if (keySz != keysize) ret = WC_HW_E; @@ -284,14 +289,14 @@ int silabs_ecc_import_private_raw(ecc_key* key, word32 keySz, const char* d, int return WC_HW_E; if (encType == WC_TYPE_HEX_STR) - err = mp_read_radix(&key->k, d, MP_RADIX_HEX); + err = mp_read_radix(wc_ecc_key_get_priv(key), d, MP_RADIX_HEX); else - err = mp_read_unsigned_bin(&key->k, (const byte*)d, + err = mp_read_unsigned_bin(wc_ecc_key_get_priv(key), (const byte*)d, key->dp->size); if (err == MP_OKAY) { - err = wc_export_int(&key->k, key->key.storage.location.buffer.pointer + (2 * keySz), - &keySz, keySz, - WC_TYPE_UNSIGNED_BIN); + err = wc_export_int(wc_ecc_key_get_priv(key), + key->key.storage.location.buffer.pointer + (2 * keySz), &keySz, + keySz, WC_TYPE_UNSIGNED_BIN); } return err; diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index 82408dc5879..ad64ec2cb87 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -43,6 +43,11 @@ #include #endif +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif #ifdef STM32_HASH @@ -954,7 +959,8 @@ int stm32_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, if (status == MP_OKAY) status = stm32_get_from_mp_int(Qybin, key->pubkey.y, szModulus); if (status == MP_OKAY) - status = stm32_get_from_mp_int(privKeybin, &key->k, szModulus); + status = stm32_get_from_mp_int(privKeybin, wc_ecc_key_get_priv(key), + szModulus); if (status != MP_OKAY) return status; @@ -1020,7 +1026,7 @@ int stm32_ecc_sign_hash_ex(const byte* hash, word32 hashlen, WC_RNG* rng, size = wc_ecc_size(key); - status = stm32_get_from_mp_int(Keybin, &key->k, size); + status = stm32_get_from_mp_int(Keybin, wc_ecc_key_get_priv(key), size); if (status != MP_OKAY) return status; diff --git a/wolfcrypt/src/sakke.c b/wolfcrypt/src/sakke.c index 3803a4dd57a..3adc01dd7f9 100644 --- a/wolfcrypt/src/sakke.c +++ b/wolfcrypt/src/sakke.c @@ -44,6 +44,12 @@ #include #include +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + /* SAKKE Build Options: * WOLFSSL_SAKKE_SMALL: Small code size version of SAKKE. * WOLFSSL_SAKKE_SMALL_MODEXP: Small code size for just SAKKE modexp. @@ -515,17 +521,19 @@ int wc_MakeSakkeKey(SakkeKey* key, WC_RNG* rng) err = RNG_FAILURE_E; } if (err == 0) { - err = mp_rand(&key->ecc.k, digits, rng); + err = mp_rand(wc_ecc_key_get_priv(&key->ecc), digits, rng); } if (err == 0) { - err = mp_mod(&key->ecc.k, &key->params.q, &key->ecc.k); + err = mp_mod(wc_ecc_key_get_priv(&key->ecc), &key->params.q, + wc_ecc_key_get_priv(&key->ecc)); } } - while ((err == 0) && mp_iszero(&key->ecc.k)); + while ((err == 0) && mp_iszero(wc_ecc_key_get_priv(&key->ecc))); } if (err == 0) { /* Calculate public key by multiply master secret by base point. */ - err = sakke_mulmod_base(key, &key->ecc.k, &key->ecc.pubkey, 1); + err = sakke_mulmod_base(key, wc_ecc_key_get_priv(&key->ecc), + &key->ecc.pubkey, 1); } if (err == 0) { key->ecc.type = ECC_PRIVATEKEY; @@ -561,7 +569,7 @@ int wc_MakeSakkePublicKey(SakkeKey* key, ecc_point* pub) err = sakke_load_base_point(key); } if (err == 0) { - err = sakke_mulmod_base(key, &key->ecc.k, pub, 1); + err = sakke_mulmod_base(key, wc_ecc_key_get_priv(&key->ecc), pub, 1); } return err; @@ -601,7 +609,7 @@ int wc_ExportSakkeKey(SakkeKey* key, byte* data, word32* sz) } if (err == 0) { /* Write out the secret value into key size bytes. */ - err = mp_to_unsigned_bin_len(&key->ecc.k, data, key->ecc.dp->size); + err = mp_to_unsigned_bin_len(wc_ecc_key_get_priv(&key->ecc), data, key->ecc.dp->size); } if (err == 0) { data += key->ecc.dp->size; @@ -651,7 +659,8 @@ int wc_ImportSakkeKey(SakkeKey* key, const byte* data, word32 sz) if (err == 0) { /* Read the secret value from key size bytes. */ - err = mp_read_unsigned_bin(&key->ecc.k, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data, + key->ecc.dp->size); } if (err == 0) { data += key->ecc.dp->size; @@ -706,7 +715,8 @@ int wc_ExportSakkePrivateKey(SakkeKey* key, byte* data, word32* sz) } if (err == 0) { /* Write out the secret value into key size bytes. */ - err = mp_to_unsigned_bin_len(&key->ecc.k, data, key->ecc.dp->size); + err = mp_to_unsigned_bin_len(wc_ecc_key_get_priv(&key->ecc), data, + key->ecc.dp->size); } if (err == 0) { *sz = key->ecc.dp->size; @@ -745,7 +755,8 @@ int wc_ImportSakkePrivateKey(SakkeKey* key, const byte* data, word32 sz) if (err == 0) { /* Read the secret value from key size bytes. */ - err = mp_read_unsigned_bin(&key->ecc.k, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data, + key->ecc.dp->size); } return err; @@ -972,7 +983,7 @@ int wc_MakeSakkeRsk(SakkeKey* key, const byte* id, word16 idSz, ecc_point* rsk) } /* a + z_T */ if (err == 0) { - err = mp_addmod(a, &key->ecc.k, &key->params.q, a); + err = mp_addmod(a, wc_ecc_key_get_priv(&key->ecc), &key->params.q, a); } /* (a + z_T) ^ 1 modulo q */ if (err == 0) { @@ -2361,7 +2372,7 @@ static int sakke_compute_point_i(SakkeKey* key, const byte* id, word16 idSz, ecc_point* i) { int err; - mp_int* b = &key->ecc.k; + mp_int* b = wc_ecc_key_get_priv(&key->ecc); /* Load b - ID of receiver */ err = mp_read_unsigned_bin(b, id, idSz); diff --git a/wolfcrypt/src/wc_pkcs11.c b/wolfcrypt/src/wc_pkcs11.c index d988f6ee6d9..b2386f57bfb 100644 --- a/wolfcrypt/src/wc_pkcs11.c +++ b/wolfcrypt/src/wc_pkcs11.c @@ -45,6 +45,12 @@ #include #endif +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + #if defined(NO_PKCS11_RSA) && !defined(NO_RSA) #define NO_RSA #endif @@ -1184,8 +1190,8 @@ static int Pkcs11CreateEccPrivateKey(CK_OBJECT_HANDLE* privateKey, ret = Pkcs11EccSetParams(private_key, keyTemplate, 3); if (ret == 0) { - keyTemplate[4].pValue = private_key->k.raw.buf; - keyTemplate[4].ulValueLen = private_key->k.raw.len; + keyTemplate[4].pValue = wc_ecc_key_get_priv(private_key)->raw.buf; + keyTemplate[4].ulValueLen = wc_ecc_key_get_priv(private_key)->raw.len; PKCS11_DUMP_TEMPLATE("Ec Private Key", keyTemplate, keyTmplCnt); rv = session->func->C_CreateObject(session->handle, keyTemplate, @@ -1426,7 +1432,7 @@ int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key) ret = ret2; } if (ret == 0 && clear) - mp_forcezero(&eccKey->k); + mp_forcezero(wc_ecc_key_get_priv(eccKey)); break; } #endif @@ -2448,7 +2454,8 @@ static int Pkcs11ECDH(Pkcs11Session* session, wc_CryptoInfo* info) if (ret == 0) { WOLFSSL_MSG("PKCS#11: EC Key Derivation Operation"); - if ((sessionKey = !mp_iszero(&info->pk.ecdh.private_key->k))) + if ((sessionKey = !mp_iszero( + wc_ecc_key_get_priv(info->pk.ecdh.private_key)))) ret = Pkcs11CreateEccPrivateKey(&privateKey, session, info->pk.ecdh.private_key, CKA_DERIVE); else if (info->pk.ecdh.private_key->labelLen > 0) { @@ -2742,7 +2749,8 @@ static int Pkcs11ECDSA_Sign(Pkcs11Session* session, wc_CryptoInfo* info) if (ret == 0) { WOLFSSL_MSG("PKCS#11: EC Signing Operation"); - if ((sessionKey = !mp_iszero(&info->pk.eccsign.key->k))) + if ((sessionKey = !mp_iszero( + wc_ecc_key_get_priv(info->pk.eccsign.key)))) ret = Pkcs11CreateEccPrivateKey(&privateKey, session, info->pk.eccsign.key, CKA_SIGN); else if (info->pk.eccsign.key->labelLen > 0) { diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 31f3426bca6..7e2c4b25fd1 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -356,6 +356,12 @@ #include #endif +#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV + /* FIPS build has replaced ecc.h. */ + #define wc_ecc_key_get_priv(key) (&((key)->k)) + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV +#endif + #ifdef WOLFSSL_STATIC_MEMORY static WOLFSSL_HEAP_HINT* HEAP_HINT; #else @@ -25748,7 +25754,8 @@ static int ecc_mulmod_test(ecc_key* key1) if (ret != 0) goto done; - ret = wc_ecc_mulmod(&key1->k, &key2->pubkey, &key3->pubkey, &key2->k, &key3->k, + ret = wc_ecc_mulmod(wc_ecc_key_get_priv(key1), &key2->pubkey, &key3->pubkey, + wc_ecc_key_get_priv(key2), wc_ecc_key_get_priv(key3), 1); if (ret != 0) { ret = WC_TEST_RET_ENC_EC(ret); diff --git a/wolfssl/wolfcrypt/ecc.h b/wolfssl/wolfcrypt/ecc.h index 80141bdd801..8bb07f60e07 100644 --- a/wolfssl/wolfcrypt/ecc.h +++ b/wolfssl/wolfcrypt/ecc.h @@ -347,14 +347,15 @@ typedef struct ecc_set_type { * The ALT_ECC_SIZE option only applies to stack based fast math USE_FAST_MATH. */ -#if !defined(USE_FAST_MATH) && !defined(WOLFSSL_SP_MATH_ALL) && \ - !defined(WOLFSSL_SP_MATH) - #error USE_FAST_MATH must be defined to use ALT_ECC_SIZE +#if defined(USE_INTEGER_HEAP_MATH) + #error Cannot use integer math with ALT_ECC_SIZE #endif #ifdef WOLFSSL_NO_MALLOC #error ALT_ECC_SIZE cannot be used with no malloc (WOLFSSL_NO_MALLOC) #endif +#ifdef USE_FAST_MATH + /* determine max bits required for ECC math */ #ifndef FP_MAX_BITS_ECC /* max bits rounded up by 8 then doubled */ @@ -385,6 +386,40 @@ typedef struct alt_fp_int { int used, sign, size; mp_digit dp[FP_SIZE_ECC]; } alt_fp_int; + +#else + +#ifdef FP_MAX_BITS_ECC + #define SP_INT_BITS_ECC (FP_MAX_BITS_ECC / 2) +#elif SP_INT_BITS < MAX_ECC_BITS + #define SP_INT_BITS_ECC SP_INT_BITS +#else + #define SP_INT_BITS_ECC MAX_ECC_BITS +#endif + +#define SP_INT_DIGITS_ECC \ + (((SP_INT_BITS_ECC + SP_WORD_SIZE - 1) / SP_WORD_SIZE) * 2 + 1) + +#define FP_SIZE_ECC SP_INT_DIGITS_ECC + +typedef struct alt_fp_int { + /** Number of words that contain data. */ + unsigned int used; + /** Maximum number of words in data. */ + unsigned int size; +#ifdef WOLFSSL_SP_INT_NEGATIVE + /** Indicates whether number is 0/positive or negative. */ + unsigned int sign; +#endif +#ifdef HAVE_WOLF_BIGINT + /** Unsigned binary (big endian) representation of number. */ + struct WC_BIGINT raw; +#endif + /** Data of number. */ + sp_int_digit dp[SP_INT_DIGITS_ECC]; +} alt_fp_int; + +#endif #endif /* ALT_ECC_SIZE */ #ifndef WC_ECCKEY_TYPE_DEFINED @@ -446,7 +481,12 @@ struct ecc_key { #endif void* heap; /* heap hint */ ecc_point pubkey; /* public key */ - mp_int k; /* private key */ +#ifndef ALT_ECC_SIZE + mp_int k[1]; /* private key */ +#else + mp_int* k; + alt_fp_int ka[1]; +#endif #ifdef WOLFSSL_CAAM word32 blackKey; /* address of key encrypted and in secure memory */ @@ -543,6 +583,9 @@ struct ecc_key { #endif }; +#define wc_ecc_key_get_priv(key) ((key)->k) +#define WOLFSSL_HAVE_ECC_KEY_GET_PRIV + WOLFSSL_ABI WOLFSSL_API ecc_key* wc_ecc_key_new(void* heap); WOLFSSL_ABI WOLFSSL_API void wc_ecc_key_free(ecc_key* key); From 6f50d8e77458279582b7de57e96fdcce6ded15be Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 28 Apr 2023 12:10:05 +1000 Subject: [PATCH 248/391] ASN.1 print: implementation to parse and print added New API to parse and print DER/BER data from a buffer. Add an example to parse DER, Base64 and PEM files and print out ASN.1 items. --- .gitignore | 1 + configure.ac | 21 + doc/dox_comments/header_files/asn_public.h | 145 ++++ examples/asn1/asn1.c | 494 +++++++++++ examples/asn1/include.am | 12 + examples/include.am | 1 + wolfcrypt/src/asn.c | 964 +++++++++++++++++++-- wolfcrypt/src/error.c | 6 + wolfssl/wolfcrypt/asn.h | 13 +- wolfssl/wolfcrypt/asn_public.h | 100 +++ wolfssl/wolfcrypt/error-crypt.h | 5 +- 11 files changed, 1679 insertions(+), 83 deletions(-) create mode 100644 examples/asn1/asn1.c create mode 100644 examples/asn1/include.am diff --git a/.gitignore b/.gitignore index ca5861e8a6a..d6e72cb5581 100644 --- a/.gitignore +++ b/.gitignore @@ -73,6 +73,7 @@ examples/sctp/sctp-server examples/sctp/sctp-server-dtls examples/sctp/sctp-client examples/sctp/sctp-client-dtls +examples/asn1/asn1 server_ready snifftest output diff --git a/configure.ac b/configure.ac index 21c74d003ae..a196cc92b12 100644 --- a/configure.ac +++ b/configure.ac @@ -4030,6 +4030,26 @@ else ENABLED_BIGNUM="yes" fi +case $host_os in +*linux* | *darwin* | *freebsd*) + DEF_ASN_PRINT="yes" + ;; +*) + DEF_ASN_PRINT="no" + ;; +esac + +AC_ARG_ENABLE([asn-print], + [AS_HELP_STRING([--enable-asn-print],[Enable ASN Print API (default: enabled)])], + [ ENABLED_ASN_PRINT=$enableval ], + [ ENABLED_ASN_PRINT=$DEF_ASN_PRINT ] + ) + +if test "$ENABLED_ASN_PRINT" = "yes" +then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_ASN_PRINT" +fi + # AES AC_ARG_ENABLE([aes], @@ -8528,6 +8548,7 @@ AM_CONDITIONAL([BUILD_FASTMATH],[test "x$ENABLED_FASTMATH" = "xyes" || test "x$E AM_CONDITIONAL([BUILD_HEAPMATH],[test "x$ENABLED_HEAPMATH" = "xyes" || test "x$ENABLED_USERSETTINGS" = "xyes"]) AM_CONDITIONAL([BUILD_EXAMPLE_SERVERS],[test "x$ENABLED_EXAMPLES" = "xyes" && test "x$ENABLED_LEANTLS" = "xno"]) AM_CONDITIONAL([BUILD_EXAMPLE_CLIENTS],[test "x$ENABLED_EXAMPLES" = "xyes"]) +AM_CONDITIONAL([BUILD_EXAMPLE_ASN1],[test "x$ENABLED_EXAMPLES" = "xyes"] && [test "x$ENABLED_ASN_PRINT" = "xyes"] && [test "x$ENABLED_ASN" = "xyes"]) AM_CONDITIONAL([BUILD_TESTS],[test "x$ENABLED_EXAMPLES" = "xyes"]) AM_CONDITIONAL([BUILD_THREADED_EXAMPLES],[test "x$ENABLED_SINGLETHREADED" = "xno" && test "x$ENABLED_EXAMPLES" = "xyes" && test "x$ENABLED_LEANTLS" = "xno"]) AM_CONDITIONAL([BUILD_WOLFCRYPT_TESTS],[test "x$ENABLED_CRYPT_TESTS" = "xyes"]) diff --git a/doc/dox_comments/header_files/asn_public.h b/doc/dox_comments/header_files/asn_public.h index 06d29fe4b8a..882ab89cfe4 100644 --- a/doc/dox_comments/header_files/asn_public.h +++ b/doc/dox_comments/header_files/asn_public.h @@ -2167,3 +2167,148 @@ int wc_SetUnknownExtCallback(DecodedCert* cert, int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap, const byte* pubKey, word32 pubKeySz, int pubKeyOID); + +/*! + \ingroup ASN + + \brief This function initializes the ASN.1 print options. + + \return 0 on success. + \return BAD_FUNC_ARG when asn1 is NULL. + + \param opts The ASN.1 options for printing. + + _Example_ + \code + Asn1PrintOptions opt; + + // Initialize ASN.1 print options before use. + wc_Asn1PrintOptions_Init(&opt); + \endcode + + \sa wc_Asn1PrintOptions_Set + \sa wc_Asn1_PrintAll +*/ +int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts); + +/*! + \ingroup ASN + + \brief This function sets a print option into an ASN.1 print options object. + + \return 0 on success. + \return BAD_FUNC_ARG when asn1 is NULL. + \return BAD_FUNC_ARG when val is out of range for option. + + \param opts The ASN.1 options for printing. + \param opt An option to set value for. + \param val The value to set. + + _Example_ + \code + Asn1PrintOptions opt; + + // Initialize ASN.1 print options before use. + wc_Asn1PrintOptions_Init(&opt); + // Set the number of indents when printing tag name to be 1. + wc_Asn1PrintOptions_Set(&opt, ASN1_PRINT_OPT_INDENT, 1); + \endcode + + \sa wc_Asn1PrintOptions_Init + \sa wc_Asn1_PrintAll +*/ +int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt, + word32 val); + +/*! + \ingroup ASN + + \brief This function initializes an ASN.1 parsing object. + + \return 0 on success. + \return BAD_FUNC_ARG when asn1 is NULL. + + \param asn1 ASN.1 parse object. + + _Example_ + \code + Asn1 asn1; + + // Initialize ASN.1 parse object before use. + wc_Asn1_Init(&asn1); + \endcode + + \sa wc_Asn1_SetFile + \sa wc_Asn1_PrintAll + */ +int wc_Asn1_Init(Asn1* asn1); + +/*! + \ingroup ASN + + \brief This function sets the file to use when printing into an ASN.1 + parsing object. + + \return 0 on success. + \return BAD_FUNC_ARG when asn1 is NULL. + \return BAD_FUNC_ARG when file is XBADFILE. + + \param asn1 The ASN.1 parse object. + \param file File to print to. + + _Example_ + \code + Asn1 asn1; + + // Initialize ASN.1 parse object before use. + wc_Asn1_Init(&asn1); + // Set standard out to be the file descriptor to write to. + wc_Asn1_SetFile(&asn1, stdout); + \endcode + + \sa wc_Asn1_Init + \sa wc_Asn1_PrintAll + */ +int wc_Asn1_SetFile(Asn1* asn1, XFILE file); + +/*! + \ingroup ASN + + \brief Print all ASN.1 items. + + \return 0 on success. + \return BAD_FUNC_ARG when asn1 or opts is NULL. + \return ASN_LEN_E when ASN.1 item's length too long. + \return ASN_DEPTH_E when end offset invalid. + \return ASN_PARSE_E when not all of an ASN.1 item parsed. + + \param asn1 The ASN.1 parse object. + \param opts The ASN.1 print options. + \param data Buffer containing BER/DER data to print. + \param len Length of data to print in bytes. + + \code + Asn1PrintOptions opts; + Asn1 asn1; + unsigned char data[] = { Initialize with DER/BER data }; + word32 len = sizeof(data); + + // Initialize ASN.1 print options before use. + wc_Asn1PrintOptions_Init(&opt); + // Set the number of indents when printing tag name to be 1. + wc_Asn1PrintOptions_Set(&opt, ASN1_PRINT_OPT_INDENT, 1); + + // Initialize ASN.1 parse object before use. + wc_Asn1_Init(&asn1); + // Set standard out to be the file descriptor to write to. + wc_Asn1_SetFile(&asn1, stdout); + // Print all ASN.1 items in buffer with the specified print options. + wc_Asn1_PrintAll(&asn1, &opts, data, len); + \endcode + + \sa wc_Asn1_Init + \sa wc_Asn1_SetFile + */ +int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data, + word32 len); + diff --git a/examples/asn1/asn1.c b/examples/asn1/asn1.c new file mode 100644 index 00000000000..0397a14263f --- /dev/null +++ b/examples/asn1/asn1.c @@ -0,0 +1,494 @@ +/* asn1.c + * + * Copyright (C) 2006-2023 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#ifndef WOLFSSL_USER_SETTINGS + #include +#endif +#include +#include +#include +#include + +#ifdef WOLFSSL_ASN_PRINT + +/* Increment allocated data by this much. */ +#define DATA_INC_LEN 256 + + +/* File format is DER/BER. */ +#define FORMAT_DER 0 +/* File format is BASE64. */ +#define FORMAT_BASE64 1 +/* File format is PEM. */ +#define FORMAT_PEM 2 + +/* ASN.1 print options. */ +static Asn1PrintOptions opts; +/* ASN.1 parsing state. */ +static Asn1 asn1; + +/* Read the contents of a file into a dynamically allocated buffer. + * + * Uses realloc as input may be stdin. + * + * @param [in] fp File pointer to read from. + * @param [out] pdata Pointer to data. + * @param [out] plen Pointer to length. + * @return 0 on success. + * @return 1 on failure. + */ +static int ReadFile(FILE* fp, unsigned char** pdata, word32* plen) +{ + int ret = 0; + word32 len = 0; + size_t read_len; + /* Allocate a minimum amount. */ + unsigned char* data = (unsigned char*)malloc(DATA_INC_LEN); + + if (data != NULL) { + /* Read more data. */ + while ((read_len = fread(data + len, 1, DATA_INC_LEN, fp)) != 0) { + unsigned char* p; + + /* Add read data amount to length. */ + len += (word32)read_len; + + /* Stop if we are at end-of-file. */ + if (feof(fp)) { + break; + } + + /* Make space for more data to be added to buffer. */ + p = (unsigned char*)realloc(data, len + DATA_INC_LEN); + if (p == NULL) { + /* Reallocation failed - free current buffer. */ + free(data); + data = NULL; + break; + } + /* Set data to new pointer. */ + data = p; + } + /* Done with file. */ + fclose(fp); + } + + if (data != NULL) { + /* Return data and length. */ + *pdata = data; + *plen = len; + } + else { + /* Failed to allocate data. */ + ret = MEMORY_E; + } + return ret; +} + +/* Print ASN.1 of a file containing BER/DER data. + * + * @param [in] fp File pointer to read from. + * @return 0 on success. + * @return 1 on failure. + */ +static int PrintDer(FILE* fp) +{ + int ret = 0; + word32 len = 0; + unsigned char* data = NULL; + + /* Load DER/BER file. */ + if (ReadFile(fp, &data, &len) != 0) { + ret = 1; + } + + if ((ret == 0) && (data != NULL)) { + /* Print DER/BER. */ + ret = wc_Asn1_PrintAll(&asn1, &opts, data, len); + /* Dispose of buffer. */ + free(data); + } + + return ret; +} + +/* Print ASN.1 of a file containing Base64 encoding of BER/DER data. + * + * @param [in] fp File pointer to read from. + * @return 0 on success. + * @return 1 on failure. + */ +static int PrintBase64(FILE* fp) +{ + int ret = 0; + word32 len = 0; + unsigned char* data = NULL; + + /* Load Base64 encoded file. */ + if (ReadFile(fp, &data, &len) != 0) { + ret = 1; + } + + if ((ret == 0) && (data != NULL)) { + /* Decode Base64. */ + if (Base64_Decode(data, len, data, &len) != 0) { + fprintf(stderr, "Invalid Base64 encoding\n"); + ret = 1; + } + + if (ret == 0) { + /* Print DER/BER. */ + ret = wc_Asn1_PrintAll(&asn1, &opts, data, len); + } + /* Dispose of buffer. */ + free(data); + } + + return ret; +} + +/* Find the next PEM block. + * + * @param [in] data PEM data. + * @param [in] offset Offset into data to start looking. + * @param [in] len Length of PEM data. + * @param [out] start Start of Base64 encoding. + * @param [out] end End of Base64 encoding. + */ +static int FindPem(unsigned char* data, word32 offset, word32 len, + word32* start, word32* end) +{ + int ret = 0; + word32 i; + word32 j; + + /* Find header. */ + for (i = offset; i < len; i++) { + if ((data[i] == '-') && + (strncmp((char*)data + i, "-----BEGIN", 10) == 0)) { + break; + } + } + if (i == len) { + /* Got to end without finding PEM header. */ + fprintf(stderr, "No PEM header found\n"); + ret = 1; + } + if (ret == 0) { + /* Confirm header. */ + for (i += 10; i < len; i++) { + if ((data[i] == '-') && + (strncmp((char*)data + i, "-----", 5) == 0)) { + break; + } + } + if (i == len) { + /* Got to end without finding rest of PEM header. */ + fprintf(stderr, "Invalid PEM header\n"); + ret = 1; + } + } + if (ret == 0) { + /* Find footer. */ + i += 6; + for (j = i + 1; j < len; j++) { + if ((data[j] == '-') && + (strncmp((char*)data + j, "-----END", 8) == 0)) { + break; + } + } + if (j == len) { + /* Got to end without finding PEM footer. */ + fprintf(stderr, "No PEM footer found\n"); + ret = 1; + } + } + + if (ret == 0) { + /* Return start and end indeces. */ + *start = i; + *end = j; + } + return ret; +} + +/* Print ASN.1 of file containing PEM. + * + * Only one block is printed. + * + * @param [in] fp File pointer to read from. + * @param [in] pem_skip Number of PEM blocks to skip. + * @return 0 on success. + * @return 1 on failure. + */ +static int PrintPem(FILE* fp, int pem_skip) +{ + int ret = 0; + unsigned char* data = NULL; + word32 len = 0; + + /* Load PEM file. */ + if (ReadFile(fp, &data, &len) != 0) { + ret = 1; + } + + if ((ret == 0) && (data != NULL)) { + word32 i = 0; + word32 j = 0; + + /* Find PEM blocks and skip number requested. */ + do { + /* Find start and end of PEM Base64 data. */ + ret = FindPem(data, j, len, &i, &j); + } while ((ret == 0) && ((pem_skip--) != 0)); + + /* Decode data between header and footer. */ + if ((ret == 0) && (Base64_Decode(data + i, j - i, data, &len) != 0)) { + fprintf(stderr, "Invalid Base64 encoding\n"); + ret = 1; + } + + if (ret == 0) { + /* Print DER/BER. */ + ret = wc_Asn1_PrintAll(&asn1, &opts, data, len); + } + /* Dispose of buffer. */ + free(data); + } + + return ret; +} + +/* Usage lines to show. */ +const char* usage[] = { + "asn1 [OPTOIN]... [FILE]", + "Display a human-readable version of a DER/BER encoding.", + "", + "Options:", + " -?, --help display this help and exit", + " -b, --branch draw branches before tag name", + " -B, --base64 file contents are Base64 encoded", + " -d, --dump show all ASN.1 item data as a hex dump", + " -h, --headers show all ASN.1 item headers as a hex dump", + " -i, --indent indent tag name with depth", + " -l, --length LEN display length bytes of data", + " -n, --no-text do not show data as text", + " -N, --no-dump-text do not show data as a hex dump text", + " -o, --offset OFFSET start decoding from offset", + " -O, --oid show wolfSSL OID value in text", + " -p, --pem file contents are PEM", + " -s, --skip-pem NUM number of PEM blocks to skip", +}; +/* Number of usage lines. */ +#define USAGE_SZ ((int)(sizeof(usage) / sizeof(*usage))) + +/* Print out usage lines. + */ +static void Usage(void) +{ + int i; + + for (i = 0; i < USAGE_SZ; i++) { + printf("%s\n", usage[i]); + } +} + +/* Main entry of ASN.1 printing program. + * + * @param [in] argc Count of command line argements. + * @param [in] argv Command line argements. + * @return 0 on success. + * @return 1 on failure. + */ +int main(int argc, char* argv[]) +{ + int ret = 0; + /* Default to reading STDIN. */ + FILE* fp = stdin; + int file_format = FORMAT_DER; + int indent = 0; + int pem_skip = 0; + + /* Reset options. */ + (void)wc_Asn1PrintOptions_Init(&opts); + + /* Skip over program name. */ + argc--; + argv++; + while (argc > 0) { + /* Show branches instead of indenting. */ + if ((strcmp(argv[0], "-b") == 0) || + (strcmp(argv[0], "--branch") == 0)) { + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_DRAW_BRANCH, 1); + } + /* File is Base64 encoded data. */ + else if ((strcmp(argv[0], "-b64") == 0) || + (strcmp(argv[0], "--base64") == 0)) { + file_format = FORMAT_BASE64; + } + /* Dump all ASN.1 item data. */ + else if ((strcmp(argv[0], "-d") == 0) || + (strcmp(argv[0], "--dump") == 0)) { + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_SHOW_DATA, 1); + } + /* Dump ASN.1 item headers. */ + else if ((strcmp(argv[0], "-h") == 0) || + (strcmp(argv[0], "--headers") == 0)) { + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_SHOW_HEADER_DATA, 1); + } + /* Indent to text to indicate depth. */ + else if ((strcmp(argv[0], "-i") == 0) || + (strcmp(argv[0], "--indent") == 0)) { + indent++; + if (indent > 15) { + } + } + /* Only parse the specified length of DER/BER data. */ + else if ((strcmp(argv[0], "-l") == 0) || + (strcmp(argv[0], "--length") == 0)) { + if (argc == 1) { + printf("Missing length value\n"); + return 1; + } + argc--; + argv++; + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_LENGTH, + atoi(argv[0])); + } + /* Do not show text representations of ASN.1 item data. */ + else if ((strcmp(argv[0], "-n") == 0) || + (strcmp(argv[0], "--no-text") == 0)) { + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_SHOW_NO_TEXT, 1); + } + /* Do not show hex dump text representations of ASN.1 item data. */ + else if ((strcmp(argv[0], "-N") == 0) || + (strcmp(argv[0], "--no-dump-text") == 0)) { + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT, 1); + } + /* Offset into DER/BER to start decoding from. */ + else if ((strcmp(argv[0], "-o") == 0) || + (strcmp(argv[0], "--offset") == 0)) { + if (argc == 1) { + fprintf(stderr, "Missing offset value\n"); + return 1; + } + argc--; + argv++; + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_OFFSET, + atoi(argv[0])); + } + /* Show wolfSSL OID value for all OBJECT_IDs. */ + else if ((strcmp(argv[0], "-O") == 0) || + (strcmp(argv[0], "--oid") == 0)) { + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_SHOW_OID, 1); + } + /* File contains PEM blocks. */ + else if ((strcmp(argv[0], "-p") == 0) || + (strcmp(argv[0], "--pem") == 0)) { + file_format = FORMAT_PEM; + } + /* Skip a number of PEM blocks. */ + else if ((strcmp(argv[0], "-s") == 0) || + (strcmp(argv[0], "--skip-pem") == 0)) { + if (argc == 1) { + fprintf(stderr, "Missing number of PEM blocks to skip\n"); + return 1; + } + argc--; + argv++; + pem_skip = atoi(argv[0]); + if ((pem_skip < 0) || (pem_skip > 15)) { + fprintf(stderr, "Skip value out of range: %d\n", pem_skip); + return 1; + } + } + /* Display help/usage. */ + else if ((strcmp(argv[0], "-?") == 0) || + (strcmp(argv[0], "--help") == 0)) { + Usage(); + return 0; + } + /* Unknown option dectection. */ + else if (argv[0][0] == '-') { + fprintf(stderr, "Bad option: %s\n", argv[0]); + Usage(); + return 1; + } + else { + /* Name of file to read. */ + fp = fopen(argv[0], "r"); + if (fp == NULL) { + fprintf(stderr, "File not able to be read: %s\n", argv[0]); + return 1; + } + } + + /* Move on to next command line argument. */ + argc--; + argv++; + } + + wc_Asn1PrintOptions_Set(&opts, ASN1_PRINT_OPT_INDENT, indent); + + (void)wc_Asn1_Init(&asn1); + (void)wc_Asn1_SetFile(&asn1, stdout); + + /* Process file based on type. */ + if (file_format == FORMAT_DER) { + ret = PrintDer(fp); + } + else if (file_format == FORMAT_BASE64) { + ret = PrintBase64(fp); + } + else if (file_format == FORMAT_PEM) { + ret = PrintPem(fp, pem_skip); + } + + if (ret != 0) { + fprintf(stderr, "%s\n", wc_GetErrorString(ret)); + } + return (ret == 0) ? 0 : 1; +} + +#else + +/* Main entry of ASN.1 printing program. + * + * @param [in] argc Count of command line argements. + * @param [in] argv Command line argements. + * @return 0 on success. + * @return 1 on failure. + */ +int main(int argc, char* argv[]) +{ + (void)argc; + (void)argv; + fprintf(stderr, "ASN.1 Parsing and Printing not compiled in.\n"); + return 0; +} + +#endif + + diff --git a/examples/asn1/include.am b/examples/asn1/include.am new file mode 100644 index 00000000000..9406211e529 --- /dev/null +++ b/examples/asn1/include.am @@ -0,0 +1,12 @@ +# vim:ft=automake +# included from Top Level Makefile.am +# All paths should be given relative to the root + + +if BUILD_EXAMPLE_ASN1 +noinst_PROGRAMS += examples/asn1/asn1 +examples_asn1_asn1_SOURCES = examples/asn1/asn1.c +examples_asn1_asn1_LDADD = src/libwolfssl@LIBSUFFIX@.la $(LIB_STATIC_ADD) +examples_asn1_asn1_DEPENDENCIES = src/libwolfssl@LIBSUFFIX@.la +endif + diff --git a/examples/include.am b/examples/include.am index afde4305721..76f48161a83 100644 --- a/examples/include.am +++ b/examples/include.am @@ -8,4 +8,5 @@ include examples/echoserver/include.am include examples/server/include.am include examples/sctp/include.am include examples/configs/include.am +include examples/asn1/include.am EXTRA_DIST += examples/README.md diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 46ab68d0b60..037822c3448 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -219,6 +219,88 @@ ASN Options: #endif /* HAVE_SELFTEST */ #endif +#if defined(WOLFSSL_ASN_PRINT) || defined(WOLFSSL_DEBUG_ASN_TEMPLATE) + +/* String representations of tags. */ +static const char* tagString[4][32] = { + /* Universal */ + { + "EOC", + "BOOLEAN", + "INTEGER", + "BIT STRING", + "OCTET STRING", + "NULL", + "OBJECT ID", + "ObjectDescriptor", + "INSTANCE OF", + "REAL", + "ENUMERATED", + "EMBEDDED PDV", + "UT8String", + "RELATIVE-OID", + "(0x0e) 14", + "(0x0f) 15", + "SEQUENCE", + "SET", + "NumericString", + "PrintableString", + "T61String", + "VideotexString", + "IA5String", + "UTCTime", + "GeneralizedTime", + "GraphicString", + "ISO646String", + "GeneralString", + "UniversalString", + "CHARACTER STRING", + "BMPString", + "(0x1f) 31", + }, + /* Application */ + { + "[A 0]", "[A 1]", "[A 2]", "[A 3]", + "[A 4]", "[A 5]", "[A 6]", "[A 7]", + "[A 8]", "[A 9]", "[A 10]", "[A 11]", + "[A 12]", "[A 13]", "[A 14]", "[A 15]", + "[A 16]", "[A 17]", "[A 18]", "[A 19]", + "[A 20]", "[A 21]", "[A 22]", "[A 23]", + "[A 24]", "[A 25]", "[A 26]", "[A 27]", + "[A 28]", "[A 20]", "[A 30]", "[A 31]" + }, + /* Context-Specific */ + { + "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]", + "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]", + "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]", + "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]" + }, + /* Private */ + { + "[P 0]", "[P 1]", "[P 2]", "[P 3]", + "[P 4]", "[P 5]", "[P 6]", "[P 7]", + "[P 8]", "[P 9]", "[P 10]", "[P 11]", + "[P 12]", "[P 13]", "[P 14]", "[P 15]", + "[P 16]", "[P 17]", "[P 18]", "[P 19]", + "[P 20]", "[P 21]", "[P 22]", "[P 23]", + "[P 24]", "[P 25]", "[P 26]", "[P 27]", + "[P 28]", "[P 20]", "[P 30]", "[P 31]" + } +}; + +/* Converts a tag byte to string. + * + * @param [in] tag BER tag value to interpret. + * @return String corresponding to tag. + */ +static const char* TagString(byte tag) +{ + return tagString[tag >> 6][tag & ASN_TYPE_MASK]; +} + +#endif + /* Calculates the minimum number of bytes required to encode the value. * @@ -483,83 +565,6 @@ static word32 SizeASNLength(word32 length) #endif #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE -/* String representations of tags. */ -static const char* tagString[4][32] = { - /* Universal */ - { - "EOC", - "BOOLEAN", - "INTEGER", - "BIT STRING", - "OCTET STRING", - "NULL", - "OBJECT ID", - "ObjectDescriptor", - "INSTANCE OF", - "REAL", - "ENUMERATED", - "EMBEDDED PDV", - "UT8String", - "RELATIVE-OID", - "(0x0e) 14", - "(0x0f) 15", - "SEQUENCE", - "SET", - "NumericString", - "PrintableString", - "T61String", - "VideotexString", - "IA5String", - "UTCTime", - "GeneralizedTime", - "GraphicString", - "ISO646String", - "GeneralString", - "UniversalString", - "CHARACTER STRING", - "BMPString", - "(0x1f) 31", - }, - /* Application */ - { - "[A 0]", "[A 1]", "[A 2]", "[A 3]", - "[A 4]", "[A 5]", "[A 6]", "[A 7]", - "[A 8]", "[A 9]", "[A 10]", "[A 11]", - "[A 12]", "[A 13]", "[A 14]", "[A 15]", - "[A 16]", "[A 17]", "[A 18]", "[A 19]", - "[A 20]", "[A 21]", "[A 22]", "[A 23]", - "[A 24]", "[A 25]", "[A 26]", "[A 27]", - "[A 28]", "[A 20]", "[A 30]", "[A 31]" - }, - /* Context-Specific */ - { - "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]", - "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]", - "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]", - "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]" - }, - /* Private */ - { - "[P 0]", "[P 1]", "[P 2]", "[P 3]", - "[P 4]", "[P 5]", "[P 6]", "[P 7]", - "[P 8]", "[P 9]", "[P 10]", "[P 11]", - "[P 12]", "[P 13]", "[P 14]", "[P 15]", - "[P 16]", "[P 17]", "[P 18]", "[P 19]", - "[P 20]", "[P 21]", "[P 22]", "[P 23]", - "[P 24]", "[P 25]", "[P 26]", "[P 27]", - "[P 28]", "[P 20]", "[P 30]", "[P 31]" - } -}; - -/* Converts a tag byte to string. - * - * @param [in] tag BER tag value to interpret. - * @return String corresponding to tag. - */ -static const char* TagString(byte tag) -{ - return tagString[tag >> 6][tag & ASN_TYPE_MASK]; -} #include @@ -5508,7 +5513,7 @@ int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz) } #endif /* HAVE_OID_ENCODING */ -#ifdef HAVE_OID_DECODING +#if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT) /* Encode dotted form of OID into byte array version. * * @param [in] in Byte array containing OID. @@ -5538,12 +5543,12 @@ int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz) return BUFFER_E; } if (y == 0) { - out[0] = (t / 40); - out[1] = (t % 40); + out[0] = (word16)(t / 40); + out[1] = (word16)(t % 40); y = 2; } else { - out[y++] = t; + out[y++] = (word16)t; } t = 0; /* reset tmp */ } @@ -36971,6 +36976,803 @@ int wc_MIME_free_hdrs(MimeHdr* head) #undef ERROR_OUT + +#ifdef WOLFSSL_ASN_PRINT + +/******************************************************************************* + * ASN.1 Parsing and Printing Implemenation + ******************************************************************************/ + +/* Initialize ASN.1 print options. + * + * @param [in, out] opts ASN.1 options for printing. + * @return 0 on success. + * @return BAD_FUNC_ARG when asn1 is NULL. + */ +int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts) +{ + int ret = 0; + + if (opts == NULL) { + ret = BAD_FUNC_ARG; + } + else { + XMEMSET(opts, 0, sizeof(*opts)); + } + + return ret; +} + +/* Set a print option into Asn1PrintOptions object. + * + * @param [in, out] opts ASN.1 options for printing. + * @param [in] opt Option to set value of. + * @param [in] val Value to set for option. + * @return 0 on success. + * @return BAD_FUNC_ARG when asn1 is NULL. + * @return BAD_FUNC_ARG when val is out of range for option. + */ +int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt, + word32 val) +{ + int ret = 0; + + /* Validate parameters. */ + if (opts == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + switch (opt) { + /* Offset into DER/BER data to start decoding from. */ + case ASN1_PRINT_OPT_OFFSET: + opts->offset = val; + break; + /* Length of DER/BER encoding to parse. */ + case ASN1_PRINT_OPT_LENGTH: + opts->length = val; + break; + /* Number of spaces to indent for each change in depth. */ + case ASN1_PRINT_OPT_INDENT: + /* Only 4 bits available for value. */ + if (val >= (1 << 4)) { + ret = BAD_FUNC_ARG; + } + else { + opts->indent = val; + } + break; + /* Draw branches instead of indenting. */ + case ASN1_PRINT_OPT_DRAW_BRANCH: + /* Boolean value. */ + if (val > 1) { + ret = BAD_FUNC_ARG; + } + else { + opts->draw_branch = val; + } + break; + /* Show raw data of primitive types as octets. */ + case ASN1_PRINT_OPT_SHOW_DATA: + /* Boolean value. */ + if (val > 1) { + ret = BAD_FUNC_ARG; + } + else { + opts->show_data = val; + } + break; + /* Show header data as octets. */ + case ASN1_PRINT_OPT_SHOW_HEADER_DATA: + /* Boolean value. */ + if (val > 1) { + ret = BAD_FUNC_ARG; + } + else { + opts->show_header_data = val; + } + break; + /* Show the wolfSSL OID value for OBJECT_ID. */ + case ASN1_PRINT_OPT_SHOW_OID: + /* Boolean value. */ + if (val > 1) { + ret = BAD_FUNC_ARG; + } + else { + opts->show_oid = val; + } + break; + /* Don't show text representations of primitive types. */ + case ASN1_PRINT_OPT_SHOW_NO_TEXT: + /* Boolean value. */ + if (val > 1) { + ret = BAD_FUNC_ARG; + } + else { + opts->show_no_text = val; + } + break; + /* Don't show dump text representations of primitive types. */ + case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT: + /* Boolean value. */ + if (val > 1) { + ret = BAD_FUNC_ARG; + } + else { + opts->show_no_dump_text = val; + } + break; + } + } + + return ret; +} + +/* Initialize an ASN.1 parse object. + * + * @param [in, out] asn1 ASN.1 parse object. + * @return 0 on success. + * @return BAD_FUNC_ARG when asn1 is NULL. + */ +int wc_Asn1_Init(Asn1* asn1) +{ + int ret = 0; + + if (asn1 == NULL) { + ret = BAD_FUNC_ARG; + } + else { + XMEMSET(asn1, 0, sizeof(*asn1)); + asn1->file = XBADFILE; + } + + return ret; +} + +/* Set the file to use when printing. + * + * @param [in, out] asn1 ASN.1 parse object. + * @param [in] file File to print to. + * @return 0 on success. + * @return BAD_FUNC_ARG when asn1 is NULL. + * @return BAD_FUNC_ARG when file is XBADFILE. + */ +int wc_Asn1_SetFile(Asn1* asn1, XFILE file) +{ + int ret = 0; + + if ((asn1 == NULL) || (file == XBADFILE)) { + ret = BAD_FUNC_ARG; + } + else { + asn1->file = file; + } + + return ret; +} + +/* Maximum OID dotted form size. */ +#define ASN1_OID_DOTTED_MAX_SZ 16 + +/* Print OID in dotted form or as hex bytes. + * + * @param [in] file File pointer to write to. + * @param [in] oid OBJECT_ID data. + * @param [in] oid_len Length of OBJECT_ID data. + */ +static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len) +{ + word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ]; + word32 num = ASN1_OID_DOTTED_MAX_SZ; + word32 i; + + /* Decode OBJECT_ID into dotted form array. */ + if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) { + /* Print out each number of dotted form. */ + for (i = 0; i < num; i++) { + XFPRINTF(file, "%d", dotted_nums[i]); + /* Add separetor. */ + if (i < num - 1) { + XFPRINTF(file, "."); + } + } + } + else { + /* Print out bytes as we couldn't decode. */ + for (i = 0; i < len; i++) { + XFPRINTF(file, "%02x", oid[i]); + /* Add separetor. */ + if (i < len - 1) { + XFPRINTF(file, ":"); + } + } + } +} + +/* OID value to name mapping. */ +typedef struct OidName { + /* wolfSSL OID value. */ + word32 oid; + /* Long name to print when OID seen. */ + const char* name; +} OidName; + +/* Extra OID to name mappings. */ +static const OidName extraOids[] = { + { 0x005c, "commonName" }, + { 0x005d, "surname" }, + { 0x005e, "serialNumber" }, + { 0x005f, "countryName" }, + { 0x0060, "localityName" }, + { 0x0061, "stateOrProvinceName" }, + { 0x0062, "streetAddress" }, + { 0x0063, "organizationName" }, + { 0x0064, "organizationUnitName" }, + { 0x0065, "title" }, + { 0x0086, "certificateExtension" }, + { 0x028d, "emailAddress" }, + { 0x0293, "challengePassword" }, + { 0x029a, "extensionReq" }, +}; +/* Length of table of extra OID to name mappings. */ +#define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids))) + +/* Convert OID value to long name. + * + * @param [in] oid OID value. + * @param [out] name Long name for OID when known. + * @return 1 when OID known. + * @return 0 when OID not known. + */ +static int Oid2LongName(word32 oid, const char** name) +{ + int ret = 0; + int i; + + /* Step through each entry in table. */ + for (i = 0; i < EXTRA_OIDS_LEN; i++) { + if (extraOids[i].oid == oid) { + /* Return the name associated with the OID value. */ + *name = extraOids[i].name; + ret = 1; + break; + } + } + + return ret; +} + +/* Print the text version of the OBJECT_ID. + * + * @param [in] asn1 ASN.1 parse object. + * @param [in] opts ASN.1 options for printing. + */ +static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts) +{ + word32 oid = (word32)-1; +#if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) + word32 nid; +#endif + const char* ln = NULL; + word32 i = 0; + int known = 1; + + /* Get the OID value for the OBJECT_ID. */ + GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType, + asn1->item.len + 2); +#if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) + /* Lookup NID for OID value. */ + if ((nid = oid2nid(oid, oidIgnoreType)) != (word32)-1) { + /* Lookup long name for NID. */ + ln = wolfSSL_OBJ_nid2ln(nid); + } + else +#endif + /* Lookup long name for extra known OID values. */ + if (!Oid2LongName(oid, &ln)) { + /* Unknown OID value. */ + ln = NULL; + known = 0; + } + + XFPRINTF(asn1->file, ":"); + /* Show OID value if not known or asked to. */ + if ((!known) || opts->show_oid) { + XFPRINTF(asn1->file, "(0x%x) ", oid); + } + if (ln != NULL) { + /* Print long name. */ + XFPRINTF(asn1->file, "%s", ln); + } + else { + /* Print out as numbers - either dotted or hex values. */ + PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx, + asn1->item.len); + } +} + +/* Print ASN.1 data as a character string. + * + * @param [in] asn1 ASN.1 parse object. + */ +static void PrintText(Asn1* asn1) +{ + word32 i; + + XFPRINTF(asn1->file, ":"); + /* Print all data bytes as characters. */ + for (i = 0; i < asn1->item.len; i++) { + XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]); + } +} + +/* Print data as a hex bytes. + * + * @param [in] file File pointer to write to. + * @param [in] data Data to print. + * @param [in] len Number of bytes to print. + */ +static void PrintHex(XFILE file, unsigned char* data, word32 len) +{ + word32 i; + + /* Print data bytes as hex numbers. */ + for (i = 0; i < len; i++) { + XFPRINTF(file, "%02x", data[i]); + } +} + +/* Print ASN.1 data as a hex bytes. + * + * @param [in] asn1 ASN.1 parse object. + */ +static void PrintHexText(Asn1* asn1) +{ + XFPRINTF(asn1->file, ":"); + PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len); +} + +/* Print ASN.1 BIT_STRING data as hex bytes noting special first byte. + * + * @param [in] asn1 ASN.1 parse object. + */ +static void PrintBitStringText(Asn1* asn1) +{ + if (asn1->item.len > 0) { + XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]); + PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1, + asn1->item.len - 1); + } +} + +/* Print ASN.1 BOOLEAN data as text with value. + * + * @param [in] asn1 ASN.1 parse object. + */ +static void PrintBooleanText(Asn1* asn1) +{ + /* Booleans should be 1 byte of data. */ + if (asn1->item.len == 1) { + XFPRINTF(asn1->file, ":%s (%d)", + (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE", + asn1->data[asn1->item.data_idx]); + } +} + +/* Print ASN.1 data as single byte +/- number. + * + * @param [in] asn1 ASN.1 parse object. + */ +static void PrintNumberText(Asn1* asn1) +{ + /* Only supporting 1 byte of data for now. */ + if (asn1->item.len == 1) { + int num = asn1->data[asn1->item.data_idx]; + + XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num); + } +} + +/* Print ASN.1 data as a text based on the tag. + * + * TODO: handle more tags. + * + * @param [in] asn1 ASN.1 parse object. + * @param [in] opts ASN.1 options for printing. + */ +static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts) +{ + /* Get the long name for OBJECT_ID where possible. */ + if (asn1->item.tag == ASN_OBJECT_ID) { + PrintObjectIdText(asn1, opts); + } + /* Data is an array of printable characters. */ + else if ((asn1->item.tag == ASN_UTF8STRING) || + (asn1->item.tag == ASN_IA5_STRING) || + (asn1->item.tag == ASN_PRINTABLE_STRING) || + (asn1->item.tag == ASN_T61STRING) || + (asn1->item.tag == ASN_BMPSTRING) || + (asn1->item.tag == ASN_UTC_TIME) || + (asn1->item.tag == ASN_GENERALIZED_TIME) || + (asn1->item.tag == ASN_UNIVERSALSTRING) || + (asn1->item.tag == ASN_OBJECT_DESC) || + (asn1->item.tag == ASN_CHARACTER_STRING)) { + PrintText(asn1); + } + /* Show TRUE and FALSE with number. */ + else if (asn1->item.tag == ASN_BOOLEAN) { + PrintBooleanText(asn1); + } + /* Show number. */ + else if (asn1->item.tag == ASN_ENUMERATED) { + PrintNumberText(asn1); + } + /* Dumping potentially long string of hex digites. */ + else if (!opts->show_no_dump_text) { + /* Dump all bytes. */ + if ((asn1->item.tag == ASN_INTEGER) || + (asn1->item.tag == ASN_OCTET_STRING) || + ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) { + PrintHexText(asn1); + } + /* First byte is number of unused bits in last byte. + * Print first specially and dump rest of the bytes. */ + else if (asn1->item.tag == ASN_BIT_STRING) { + PrintBitStringText(asn1); + } + } +} + +#define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.') + +/* Dump data as hex bytes. + * + * @param [in] file File pointer to write to. + * @param [in] data Data to print. + * @param [in] len Number of bytes to print. + */ +static void DumpData(XFILE file, unsigned char* data, word32 len) +{ + word32 i; + word32 j; + + for (i = 0; i < len; i += j) { + /* Print offset. */ + XFPRINTF(file, " %04x:", i); + for (j = 0; (j < 16) && (i + j < len); j++) { + /* Print byte as hex number. */ + XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]); + } + /* Print spaces between hex and characters. */ + XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), ""); + for (j = 0; (j < 16) && (i + j < len); j++) { + /* Print byte as hex number. */ + XFPRINTF(file, "%c", HexToChar(data[i + j])); + } + XFPRINTF(file, "\n"); + } +} + +/* Update current depth based on the current position. + * + * @param [in, out] asn1 ASN.1 parse object. + */ +static void UpdateDepth(Asn1* asn1) +{ + /* If current index is greater than or equal end index then it is done. */ + while ((asn1->depth > 0) && + (asn1->end_idx[asn1->depth-1] <= asn1->curr)) { + /* Move up a depth. */ + asn1->depth--; + } +} + +/* Check validity of end index of constructed ASN.1 items. + * + * @param [in, out] asn1 ASN.1 parse object. + * @return 0 on success. + * @return ASN_DEPTH_E when end offset invalid. + */ +static int CheckDepth(Asn1* asn1) +{ + int ret = 0; + int i; + word32 curr_end = asn1->curr + asn1->item.len; + + for (i = 0; (ret == 0) && (i < asn1->depth); i++) { + /* Each end index must be at least as large as the current one. */ + if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) { + ret = ASN_DEPTH_E; + } + /* Each end index must be at least as large as current index. */ + if (asn1->end_idx[i] < curr_end) { + ret = ASN_DEPTH_E; + } + } + + return ret; +} + +/* Draw branching based on depth for an ASN.1 item. + * + * @param [in] asn1 ASN.1 parse object. + */ +static void DrawBranch(Asn1* asn1) +{ + int i; + word32 end = asn1->curr + asn1->item.len; + + /* Write out the character for all depths but current. */ + for (i = 0; i < asn1->depth; i++) { + if (asn1->item.cons || (end < asn1->end_idx[i])) { + if (i < asn1->depth - 1) { + /* Constructed or not end index and not current depth: | */ + XFPRINTF(asn1->file, "\xe2\x94\x82"); + } + else { + /* Constructed or not end index and current depth: |- */ + XFPRINTF(asn1->file, "\xe2\x94\x9c"); + } + } + else if ((i > 1) && (end >= asn1->end_idx[i-1])) { + /* End index for previous: _|_ (in top half) */ + XFPRINTF(asn1->file, "\xe2\x94\xb4"); + } + else { + /* End index but not for previous: L (in top half) */ + XFPRINTF(asn1->file, "\xe2\x94\x94"); + } + } + /* Prefix to tag name. */ + if (asn1->item.cons) { + if (asn1->depth > 0) { + /* Have other line to connect to: T (in bottom half) */ + XFPRINTF(asn1->file, "\xe2\x94\xac"); + } + else { + /* Have no other line to connect to: r */ + XFPRINTF(asn1->file, "\xe2\x94\x8c"); + } + } + else { + /* In a sequence: - */ + XFPRINTF(asn1->file, "\xe2\x94\x80"); + } +} + +/* Print data as hex bytes separated by space. + * + * @param [in] file File pointer to write to. + * @param [in] data Data to print. + * @param [in] len Number of bytes to print. + */ +static void PrintHexBytes(XFILE file, unsigned char* data, int len) +{ + int i; + + for (i = 0; i < len; i++) { + XFPRINTF(file, " %02x", data[i]); + } +} + +/* Dump header data. + * + * @param [in] asn1 ASN.1 parse object. + * @param [in] opts ASN.1 options for printing. + */ +static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts) +{ + /* Put on same line when not showing data too and not showing text data. */ + if ((!opts->show_data) && opts->show_no_text) { + XFPRINTF(asn1->file, "%10s %02x", "", asn1->item.tag); + } + else { + /* Align with start of data. */ + XFPRINTF(asn1->file, "\n%12s %02x", "", asn1->item.tag); + } + /* Print the header bytes as hex bytes separated by a space. */ + PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1, + asn1->curr - (asn1->offset + 1)); +} + +/* Print ASN.1 item info based on header and indeces. + * + * @param [in] asn1 ASN.1 parse object. + * @param [in] opts ASN.1 options for printing. + */ +static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts) +{ + /* Print offset of this ASN.1 item. */ + XFPRINTF(asn1->file, "%4d: ", asn1->offset); + /* Print length of header. */ + XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset); + /* Print data length. */ + XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len, + asn1->item.cons ? ']' : ' '); + /* Print depth. */ + XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth); + if (!opts->draw_branch) { + /* Indent to depth as required. */ + XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, ""); + if (!opts->indent) { + /* Indicate constructed if no indent. */ + XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' '); + } + } + else { + /* Draw branch structure for ASN.1 item. */ + XFPRINTF(asn1->file, " "); + DrawBranch(asn1); + } + /* Print tag name. */ + XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag)); +} + +/* Expecting tag part of ASN.1 item. */ +#define ASN_PART_TAG 0 +/* Expecting length part of ASN.1 item. */ +#define ASN_PART_LENGTH 1 +/* Expecting data part of ASN.1 item. */ +#define ASN_PART_DATA 2 + +/* Print next ASN.1 item. + * + * @param [in, out] asn1 ASN.1 parse object. + * @param [in] opts ASN.1 print options. + * @return 0 on success. + * @return BAD_FUNC_ARG when asn1 or opts is NULL. + * @return ASN_LEN_E when ASN.1 item's length too long. + * @return ASN_DEPTH_E when end offset invalid. + */ +static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts) +{ + int ret = 0; + + if ((asn1 == NULL) || (opts == NULL)) { + ret = BAD_FUNC_ARG; + } + + /* Process tag. */ + if (asn1->part == ASN_PART_TAG) { + /* Recalculate which depth we are at. */ + UpdateDepth(asn1); + /* Get tag. */ + asn1->item.tag = asn1->data[asn1->curr] & ~ASN_CONSTRUCTED; + /* Store whether tag indicates constructed. */ + asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) == + ASN_CONSTRUCTED; + /* Start of ASN.1 item is current index. */ + asn1->offset = asn1->curr; + /* Step over tag. */ + asn1->curr++; + /* Next part is length. */ + asn1->part = ASN_PART_LENGTH; + } + /* Process length. */ + if (asn1->part == ASN_PART_LENGTH) { + int len; + + /* Decode length and step over it. */ + if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) { + ret = ASN_LEN_E; + } + else { + /* Store ASN.1 item data offset. */ + asn1->item.data_idx = asn1->curr; + /* Store ASN.1 item data length. */ + asn1->item.len = len; + + /* Print info about ASN.1 item. */ + PrintInfo(asn1, opts); + + if (!asn1->item.cons) { + /* Move on to print data. */ + asn1->part = ASN_PART_DATA; + } + else { + /* Print header now if not printing data. */ + if (opts->show_header_data) { + DumpHeader(asn1, opts); + } + XFPRINTF(asn1->file, "\n"); + /* Record end offset for this depth. */ + asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len; + /* Done with this ASN.1 item. */ + asn1->part = ASN_PART_TAG; + } + /* Check end indeces are valid. */ + ret = CheckDepth(asn1); + } + } + /* Process data. */ + if ((ret == 0) && (asn1->part == ASN_PART_DATA)) { + if (!opts->show_no_text) { + /* Print text representation of data. */ + PrintAsn1Text(asn1, opts); + } + if (opts->show_header_data) { + /* Dump header bytes. */ + DumpHeader(asn1, opts); + } + XFPRINTF(asn1->file, "\n"); + if (opts->show_data) { + /* Dump data bytes. */ + DumpData(asn1->file, asn1->data + asn1->item.data_idx, + asn1->item.len); + } + /* Step past data to next ASN.1 item. */ + asn1->curr += asn1->item.len; + /* Update the depth based on end indeces. */ + UpdateDepth(asn1); + /* Done with this ASN.1 item. */ + asn1->part = ASN_PART_TAG; + } + + /* Make ASN.1 item printing go out. */ + fflush(asn1->file); + + return ret; +} + +/* Print all ASN.1 items. + * + * @param [in, out] asn1 ASN.1 parse object. + * @param [in] opts ASN.1 print options. + * @param [in] data BER/DER data to print. + * @param [in] len Length of data to print in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when asn1 or opts is NULL. + * @return ASN_LEN_E when ASN.1 item's length too long. + * @return ASN_DEPTH_E when end offset invalid. + * @return ASN_PARSE_E when not all of an ASN.1 item parsed. + */ +int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data, + word32 len) +{ + int ret = 0; + + if (asn1 == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Initialize start position. */ + asn1->curr = 0; + /* Start parsing at tag. */ + asn1->part = ASN_PART_TAG; + /* Start depth at 0. */ + asn1->depth = 0; + + /* Store the starting point of the data to parse. */ + asn1->data = data + opts->offset; + if (opts->length > 0) { + /* Use user specified maximum length. */ + asn1->max = opts->length; + } + else { + /* Maximum length is up to end from offset. */ + asn1->max = len - opts->offset; + } + + /* Keep going while no error and have data to parse. */ + while ((ret == 0) && (asn1->curr < asn1->max)) { + /* Print an ASN.1 item. */ + ret = wc_Asn1_Print(asn1, opts); + } + } + if ((ret == 0) && (asn1->part != ASN_PART_TAG)) { + /* Stopped before finishing ASN.1 item. */ + ret = ASN_PARSE_E; + } + if ((ret == 0) && (asn1->depth != 0)) { + /* Stopped without seeing all items in a constructed item. */ + ret = ASN_DEPTH_E; + } + + return ret; +} + +#endif /* WOLFSSL_ASN_PRINT */ #endif /* !NO_ASN */ /* Functions that parse, but are not using ASN.1 */ diff --git a/wolfcrypt/src/error.c b/wolfcrypt/src/error.c index ca3d2dcac55..27bf6538995 100644 --- a/wolfcrypt/src/error.c +++ b/wolfcrypt/src/error.c @@ -583,6 +583,12 @@ const char* wc_GetErrorString(int error) case ENTROPY_APT_E: return "Entropy Adaptive Proportion Test failed"; + case ASN_DEPTH_E: + return "Invalid ASN.1 - depth check"; + + case ASN_LEN_E: + return "ASN.1 length invalid"; + default: return "unknown error number"; diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 3794acde637..78bff4e196a 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -95,16 +95,27 @@ enum ASN_Tags { ASN_OCTET_STRING = 0x04, ASN_TAG_NULL = 0x05, ASN_OBJECT_ID = 0x06, + ASN_OBJECT_DESC = 0x07, + ASN_INSTANCE_OF = 0x08, + ASN_REAL = 0x09, ASN_ENUMERATED = 0x0a, + ASN_EMBEDDED_PDV = 0x0b, ASN_UTF8STRING = 0x0c, + ASN_RELATIVE_OID = 0x0d, ASN_SEQUENCE = 0x10, ASN_SET = 0x11, + ASN_NUMERICSTRING = 0x12, ASN_PRINTABLE_STRING = 0x13, ASN_T61STRING = 0x14, + ASN_VIDEOTEXSTRING = 0x15, ASN_IA5_STRING = 0x16, ASN_UTC_TIME = 0x17, ASN_GENERALIZED_TIME = 0x18, + ASN_GRAPHICSTRING = 0x19, + ASN_ISO646STRING = 0x1a, + ASN_GENERALSTRING = 0x1b, ASN_UNIVERSALSTRING = 0x1c, + ASN_CHARACTER_STRING = 0x1d, ASN_BMPSTRING = 0x1e, ASN_TYPE_MASK = 0x1f, @@ -2153,7 +2164,7 @@ WOLFSSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, WOLFSSL_LOCAL int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz); #endif -#ifdef HAVE_OID_DECODING +#if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT) WOLFSSL_LOCAL int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz); #endif diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index cbe60b8f03c..de779286b01 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -914,4 +914,104 @@ WOLFSSL_API int wc_GetFASCNFromCert(struct DecodedCert* cert, } /* extern "C" */ #endif +#if !defined(XFPRINTF) || defined(NO_FILESYSTEM) || \ + defined(NO_STDIO_FILESYSTEM) && defined(WOLFSSL_ASN_PRINT) +#undef WOLFSSL_ASN_PRINT +#endif + +#ifdef WOLFSSL_ASN_PRINT + +enum Asn1PrintOpt { + /* Offset into DER/BER data to start decoding from. */ + ASN1_PRINT_OPT_OFFSET, + /* Length of DER/BER encoding to parse. */ + ASN1_PRINT_OPT_LENGTH, + /* Number of spaces to indent for each change in depth. */ + ASN1_PRINT_OPT_INDENT, + /* Draw branches instead of indenting. */ + ASN1_PRINT_OPT_DRAW_BRANCH, + /* Show raw data of primitive types as octets. */ + ASN1_PRINT_OPT_SHOW_DATA, + /* Show header data as octets. */ + ASN1_PRINT_OPT_SHOW_HEADER_DATA, + /* Show the wolfSSL OID value for OBJECT_ID. */ + ASN1_PRINT_OPT_SHOW_OID, + /* Don't show text representations of primitive types. */ + ASN1_PRINT_OPT_SHOW_NO_TEXT, + /* Don't show dump text representations of primitive types. */ + ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT, +}; + +/* ASN.1 print options. */ +typedef struct Asn1PrintOptions { + /* Offset into DER/BER encoding to start parsing from. */ + word32 offset; + /* Length of DER/BER encoding to parse. */ + word32 length; + /* Number of spaces to indent for each change in depth. */ + int indent:4; + /* Draw branches instead of indenting. */ + int draw_branch:1; + /* Show raw data of primitive types as octets. */ + int show_data:1; + /* Show header data as octets. */ + int show_header_data:1; + /* Show the wolfSSL OID value for OBJECT_ID. */ + int show_oid:1; + /* Don't show text representations of primitive types. */ + int show_no_text:1; + /* Don't show dump text representations of primitive types. */ + int show_no_dump_text:1; +} Asn1PrintOptions; + +/* ASN.1 item data. */ +typedef struct Asn1Item { + /* Tag of current item. */ + unsigned char tag; + /* Whether current item is constructed. */ + unsigned char cons; + /* Length of data in current ASN.1 item. */ + word32 len; + /* Index into data of ASN.1 item data. */ + word32 data_idx; +} Asn1Item; + +/* Maximum supported depth of ASN.1 items. */ +#define ASN_MAX_DEPTH 16 + +/* ASN.1 parsing state. */ +typedef struct Asn1 { + /* ASN.1 item data. */ + Asn1Item item; + /* Current depth of ASN.1 item. */ + unsigned char depth; + /* End indeces of ASN.1 items at different depths. */ + word32 end_idx[ASN_MAX_DEPTH]; + + /* Buffer to print. */ + unsigned char* data; + /* Maximum number of bytes to process. */ + word32 max; + /* Starting offset of current ASN.1 item. */ + word32 offset; + /* Current offset into ASN.1 data. */ + word32 curr; + /* Next part of ASN.1 item expected. */ + unsigned char part; + + /* File pointer to print to. */ + XFILE file; +} Asn1; + +WOLFSSL_API int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts); +WOLFSSL_API int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, + enum Asn1PrintOpt opt, word32 val); + +WOLFSSL_API int wc_Asn1_Init(Asn1* asn1); +WOLFSSL_API int wc_Asn1_SetFile(Asn1* asn1, XFILE file); +WOLFSSL_API int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, + unsigned char* data, word32 len); + +#endif /* WOLFSSL_ASN_PRINT */ + #endif /* WOLF_CRYPT_ASN_PUBLIC_H */ diff --git a/wolfssl/wolfcrypt/error-crypt.h b/wolfssl/wolfcrypt/error-crypt.h index 7f0db6aa8b0..5c062efd4c5 100644 --- a/wolfssl/wolfcrypt/error-crypt.h +++ b/wolfssl/wolfcrypt/error-crypt.h @@ -257,7 +257,10 @@ enum { ENTROPY_RT_E = -294, /* Entropy Repetition Test failed */ ENTROPY_APT_E = -295, /* Entropy Adaptive Proportion Test failed */ - WC_LAST_E = -295, /* Update this to indicate last error */ + ASN_DEPTH_E = -296, /* Invalid ASN.1 - depth check */ + ASN_LEN_E = -297, /* ASN.1 length invalid */ + + WC_LAST_E = -297, /* Update this to indicate last error */ MIN_CODE_E = -300 /* errors -101 - -299 */ /* add new companion error id strings for any new error codes From 54c70129bef9bea8f16832b51e37ff22c5890bec Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Thu, 4 May 2023 14:26:12 -0600 Subject: [PATCH 249/391] Define WOLFSSL_THREAD for FREERTOS case --- wolfssl/wolfcrypt/settings.h | 1 + wolfssl/wolfcrypt/types.h | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 9953ff6d2f0..38bf145fe3e 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -808,6 +808,7 @@ extern void uITRON4_free(void *p) ; #ifdef FREERTOS #include "FreeRTOS.h" + #include #if !defined(XMALLOC_USER) && !defined(NO_WOLFSSL_MEMORY) && \ !defined(WOLFSSL_STATIC_MEMORY) && !defined(WOLFSSL_TRACK_MEMORY) diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 28ab2cbc5fe..cd6d4205105 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -1327,6 +1327,10 @@ typedef struct w64wrapper { #define WOLFSSL_THREAD #define INFINITE (-1) #define WAIT_OBJECT_0 0L + #elif defined(FREERTOS) + typedef unsigned int THREAD_RETURN; + typedef TaskHandle_t THREAD_TYPE; + #define WOLFSSL_THREAD #else typedef unsigned int THREAD_RETURN; typedef size_t THREAD_TYPE; From 6047df87201d16ac27180e999a329a954dcc907d Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 5 May 2023 08:43:50 +1000 Subject: [PATCH 250/391] Minor fixes configure.ac: Don't use == in test. client.c: Merge string to one line. asn.c/asn_public.h: fix conversion warnings/errors. wc_Asn1_Print no longer public and doesn't need to check for NULL. wc_Asn1_PrintAll check all pointer parameters for NULL. --- configure.ac | 2 +- examples/client/client.c | 6 +-- wolfcrypt/src/asn.c | 81 +++++++++++----------------------- wolfssl/wolfcrypt/asn_public.h | 14 +++--- 4 files changed, 35 insertions(+), 68 deletions(-) diff --git a/configure.ac b/configure.ac index a196cc92b12..538460478a2 100644 --- a/configure.ac +++ b/configure.ac @@ -7715,7 +7715,7 @@ case $host_cpu in ;; esac -if test "$ENABLED_LOWRESOURCE" = "yes" && test "$ENABLED_ECC" = "yes" && (test "$ENABLED_RSA" = "yes" || test "$ENABLED_DH" == "yes") && (test "$ENABLED_SP_MATH" = "yes" || test "$ENABLED_SP_MATH_ALL" = "yes") +if test "$ENABLED_LOWRESOURCE" = "yes" && test "$ENABLED_ECC" = "yes" && (test "$ENABLED_RSA" = "yes" || test "$ENABLED_DH" = "yes") && (test "$ENABLED_SP_MATH" = "yes" || test "$ENABLED_SP_MATH_ALL" = "yes") then AM_CFLAGS="$AM_CFLAGS -DALT_ECC_SIZE" fi diff --git a/examples/client/client.c b/examples/client/client.c index dd507ddd756..a3c52449cee 100644 --- a/examples/client/client.c +++ b/examples/client/client.c @@ -1262,8 +1262,7 @@ static const char* client_usage_msg[][70] = { "--onlyPskDheKe Must use DHE key exchange with PSK\n", /* 73 */ #endif #ifndef NO_PSK - "--openssl-psk Use TLS 1.3 PSK callback compatible with " - "OpenSSL\n", /* 74 */ + "--openssl-psk Use TLS 1.3 PSK callback compatible with OpenSSL\n", /* 74 */ #endif "\n" "For simpler wolfSSL TLS client examples, visit\n" @@ -1487,8 +1486,7 @@ static const char* client_usage_msg[][70] = { "--onlyPskDheKe Must use DHE key exchange with PSK\n", /* 73 */ #endif #ifndef NO_PSK - "--openssl-psk Use TLS 1.3 PSK callback compatible with " - "OpenSSL\n", /* 74 */ + "--openssl-psk Use TLS 1.3 PSK callback compatible with OpenSSL\n", /* 74 */ #endif "\n" "より簡単なwolfSSL TSL クライアントの例については" diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 037822c3448..3bf56f08e14 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -5556,7 +5556,7 @@ int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz) } /* return length */ - *outSz = y; + *outSz = (word32)y; return 0; } @@ -37034,73 +37034,43 @@ int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt, break; /* Number of spaces to indent for each change in depth. */ case ASN1_PRINT_OPT_INDENT: - /* Only 4 bits available for value. */ + /* Only 4 bits allowed for value. */ if (val >= (1 << 4)) { ret = BAD_FUNC_ARG; } else { - opts->indent = val; + opts->indent = (word8)val; } break; /* Draw branches instead of indenting. */ case ASN1_PRINT_OPT_DRAW_BRANCH: /* Boolean value. */ - if (val > 1) { - ret = BAD_FUNC_ARG; - } - else { - opts->draw_branch = val; - } + opts->draw_branch = (val > 0); break; /* Show raw data of primitive types as octets. */ case ASN1_PRINT_OPT_SHOW_DATA: /* Boolean value. */ - if (val > 1) { - ret = BAD_FUNC_ARG; - } - else { - opts->show_data = val; - } + opts->show_data = (val > 0); break; /* Show header data as octets. */ case ASN1_PRINT_OPT_SHOW_HEADER_DATA: /* Boolean value. */ - if (val > 1) { - ret = BAD_FUNC_ARG; - } - else { - opts->show_header_data = val; - } + opts->show_header_data = (val > 0); break; /* Show the wolfSSL OID value for OBJECT_ID. */ case ASN1_PRINT_OPT_SHOW_OID: /* Boolean value. */ - if (val > 1) { - ret = BAD_FUNC_ARG; - } - else { - opts->show_oid = val; - } + opts->show_oid = (val > 0); break; /* Don't show text representations of primitive types. */ case ASN1_PRINT_OPT_SHOW_NO_TEXT: /* Boolean value. */ - if (val > 1) { - ret = BAD_FUNC_ARG; - } - else { - opts->show_no_text = val; - } + opts->show_no_text = (val > 0); break; /* Don't show dump text representations of primitive types. */ case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT: /* Boolean value. */ - if (val > 1) { - ret = BAD_FUNC_ARG; - } - else { - opts->show_no_dump_text = val; - } + opts->show_no_dump_text = (val > 0); break; } } @@ -37251,7 +37221,7 @@ static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts) { word32 oid = (word32)-1; #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) - word32 nid; + int nid; #endif const char* ln = NULL; word32 i = 0; @@ -37262,7 +37232,7 @@ static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts) asn1->item.len + 2); #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) /* Lookup NID for OID value. */ - if ((nid = oid2nid(oid, oidIgnoreType)) != (word32)-1) { + if ((nid = oid2nid(oid, oidIgnoreType)) != -1) { /* Lookup long name for NID. */ ln = wolfSSL_OBJ_nid2ln(nid); } @@ -37546,9 +37516,9 @@ static void DrawBranch(Asn1* asn1) * @param [in] data Data to print. * @param [in] len Number of bytes to print. */ -static void PrintHexBytes(XFILE file, unsigned char* data, int len) +static void PrintHexBytes(XFILE file, unsigned char* data, word32 len) { - int i; + word32 i; for (i = 0; i < len; i++) { XFPRINTF(file, " %02x", data[i]); @@ -37564,15 +37534,18 @@ static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts) { /* Put on same line when not showing data too and not showing text data. */ if ((!opts->show_data) && opts->show_no_text) { - XFPRINTF(asn1->file, "%10s %02x", "", asn1->item.tag); + XFPRINTF(asn1->file, "%10s", ""); } else { /* Align with start of data. */ - XFPRINTF(asn1->file, "\n%12s %02x", "", asn1->item.tag); + XFPRINTF(asn1->file, "\n%12s", ""); + } + XFPRINTF(asn1->file, " %02x", asn1->item.tag); + if (asn1->curr >= asn1->offset + 1) { + /* Print the header bytes as hex bytes separated by a space. */ + PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1, + asn1->curr - (asn1->offset + 1)); } - /* Print the header bytes as hex bytes separated by a space. */ - PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1, - asn1->curr - (asn1->offset + 1)); } /* Print ASN.1 item info based on header and indeces. @@ -37628,16 +37601,12 @@ static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts) { int ret = 0; - if ((asn1 == NULL) || (opts == NULL)) { - ret = BAD_FUNC_ARG; - } - /* Process tag. */ if (asn1->part == ASN_PART_TAG) { /* Recalculate which depth we are at. */ UpdateDepth(asn1); /* Get tag. */ - asn1->item.tag = asn1->data[asn1->curr] & ~ASN_CONSTRUCTED; + asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED; /* Store whether tag indicates constructed. */ asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED; @@ -37660,7 +37629,7 @@ static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts) /* Store ASN.1 item data offset. */ asn1->item.data_idx = asn1->curr; /* Store ASN.1 item data length. */ - asn1->item.len = len; + asn1->item.len = (word32)len; /* Print info about ASN.1 item. */ PrintInfo(asn1, opts); @@ -37721,7 +37690,7 @@ static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts) * @param [in] data BER/DER data to print. * @param [in] len Length of data to print in bytes. * @return 0 on success. - * @return BAD_FUNC_ARG when asn1 or opts is NULL. + * @return BAD_FUNC_ARG when asn1, opts or data is NULL. * @return ASN_LEN_E when ASN.1 item's length too long. * @return ASN_DEPTH_E when end offset invalid. * @return ASN_PARSE_E when not all of an ASN.1 item parsed. @@ -37731,7 +37700,7 @@ int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data, { int ret = 0; - if (asn1 == NULL) { + if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) { ret = BAD_FUNC_ARG; } diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index de779286b01..7e8b8f52e59 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -949,19 +949,19 @@ typedef struct Asn1PrintOptions { /* Length of DER/BER encoding to parse. */ word32 length; /* Number of spaces to indent for each change in depth. */ - int indent:4; + word8 indent; /* Draw branches instead of indenting. */ - int draw_branch:1; + word8 draw_branch:1; /* Show raw data of primitive types as octets. */ - int show_data:1; + word8 show_data:1; /* Show header data as octets. */ - int show_header_data:1; + word8 show_header_data:1; /* Show the wolfSSL OID value for OBJECT_ID. */ - int show_oid:1; + word8 show_oid:1; /* Don't show text representations of primitive types. */ - int show_no_text:1; + word8 show_no_text:1; /* Don't show dump text representations of primitive types. */ - int show_no_dump_text:1; + word8 show_no_dump_text:1; } Asn1PrintOptions; /* ASN.1 item data. */ From 5c670651e857718b2812cf242b624407dfa56bfb Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 5 May 2023 09:11:47 +1000 Subject: [PATCH 251/391] SP int; fix sp_gcd error checking r can be as large as the smaller of a and b. Fix sign check. Add comments as to what GCD does. --- wolfcrypt/src/sp_int.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index d15a4e27e6b..74ded88aa9d 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -18697,6 +18697,9 @@ int sp_prime_is_prime_ex(const sp_int* a, int trials, int* result, WC_RNG* rng) #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) /* Calculates the Greatest Common Denominator (GCD) of a and b into r. + * + * Find the largest number that divides both a and b without remainder. + * r <= a, r <= b, a % r == 0, b % r == 0 * * a and b are positive integers. * @@ -18800,6 +18803,9 @@ static WC_INLINE int _sp_gcd(const sp_int* a, const sp_int* b, sp_int* r) } /* Calculates the Greatest Common Denominator (GCD) of a and b into r. + * + * Find the largest number that divides both a and b without remainder. + * r <= a, r <= b, a % r == 0, b % r == 0 * * a and b are positive integers. * @@ -18823,8 +18829,14 @@ int sp_gcd(const sp_int* a, const sp_int* b, sp_int* r) else if ((a->used >= SP_INT_DIGITS) || (b->used >= SP_INT_DIGITS)) { err = MP_VAL; } + /* Check that r is large enough to hold maximum sized result. */ + else if (((a->used <= b->used) && (r->size < a->used)) || + ((b->used < a->used) && (r->size < b->used))) { + err = MP_VAL; + } #ifdef WOLFSSL_SP_INT_NEGATIVE - else if ((a->sign == MP_NEG) || (b->sign >= MP_NEG)) { + /* Algorithm doesn't work with negative numbers. */ + else if ((a->sign == MP_NEG) || (b->sign == MP_NEG)) { err = MP_VAL; } #endif From a7d58c3ea4545b674f7763f5af683e021785fc1f Mon Sep 17 00:00:00 2001 From: jordan Date: Mon, 8 May 2023 10:46:33 -0500 Subject: [PATCH 252/391] Fix memory leak in TLSX_KeyShare_Setup --- src/tls.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/tls.c b/src/tls.c index 929250708f6..6853ab90d56 100644 --- a/src/tls.c +++ b/src/tls.c @@ -9602,6 +9602,7 @@ int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE) && ret != WC_PENDING_E #endif ) { + TLSX_KeyShare_FreeAll(list, ssl->heap); return ret; } } From 7db2a7c1a310168b762bda04c1eb01cc66d4baf0 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Tue, 25 Apr 2023 10:48:52 -0400 Subject: [PATCH 253/391] Allow for unknown OIDs in extensions in wolfSSL_X509_set_ext() ...and add some testing to show we properly inserted the extensions. --- src/x509.c | 37 +++++++++++-------- tests/api.c | 104 +++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 124 insertions(+), 17 deletions(-) diff --git a/src/x509.c b/src/x509.c index feb50548ddd..d599a473097 100644 --- a/src/x509.c +++ b/src/x509.c @@ -687,16 +687,9 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) /* Check if extension has been set */ isSet = wolfSSL_X509_ext_isSet_by_NID((WOLFSSL_X509*)x509, nid); ext->obj = wolfSSL_OBJ_nid2obj(nid); - if (ext->obj == NULL) { - WOLFSSL_MSG("\tfail: Invalid OBJECT"); - wolfSSL_X509_EXTENSION_free(ext); - FreeDecodedCert(cert); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); - #endif - return NULL; + if (ext->obj != NULL) { + ext->obj->nid = nid; } - ext->obj->nid = nid; switch (oid) { case BASIC_CA_OID: @@ -1000,8 +993,8 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) default: WOLFSSL_MSG("Unknown extension type found, parsing OID"); /* If the extension type is not recognized/supported, - set the ASN1_OBJECT in the extension with the - parsed oid for access in later function calls */ + * set the ASN1_OBJECT in the extension with the + * parsed oid for access in later function calls */ /* Get OID from input */ if (GetASNObjectId(input, &idx, &length, sz) != 0) { @@ -1030,6 +1023,18 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) objSz += length; /* Set object size and reallocate space in object buffer */ + if (ext->obj == NULL) { + ext->obj = wolfSSL_ASN1_OBJECT_new(); + if (ext->obj == NULL) { + wolfSSL_X509_EXTENSION_free(ext); + FreeDecodedCert(cert); + #ifdef WOLFSSL_SMALL_STACK + XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); + #endif + return NULL; + } + } + ext->obj->objSz = objSz; if(((ext->obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) || (ext->obj->obj == NULL)) { @@ -4600,10 +4605,12 @@ static void wolfSSL_GENERAL_NAME_type_free(WOLFSSL_GENERAL_NAME* name) name->d.registeredID = NULL; break; case GEN_OTHERNAME: - wolfSSL_ASN1_OBJECT_free(name->d.otherName->type_id); - wolfSSL_ASN1_TYPE_free(name->d.otherName->value); - XFREE(name->d.otherName, NULL, DYNAMIC_TYPE_ASN1); - name->d.otherName = NULL; + if (name->d.otherName != NULL) { + wolfSSL_ASN1_OBJECT_free(name->d.otherName->type_id); + wolfSSL_ASN1_TYPE_free(name->d.otherName->value); + XFREE(name->d.otherName, NULL, DYNAMIC_TYPE_ASN1); + name->d.otherName = NULL; + } break; case GEN_X400: /* Unsupported: fall through */ diff --git a/tests/api.c b/tests/api.c index 26aa797b5ee..97268fed147 100644 --- a/tests/api.c +++ b/tests/api.c @@ -43880,7 +43880,13 @@ static int test_GENERAL_NAME_set0_othername(void) { #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) && \ defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ALT_NAMES) && \ - defined(WOLFSSL_CERT_EXT) && !defined(NO_FILESYSTEM) + defined(WOLFSSL_CERT_EXT) && !defined(NO_FILESYSTEM) && \ + defined(WOLFSSL_FPKI) + + /* ./configure --enable-opensslall --enable-certgen --enable-certreq + * --enable-certext --enable-debug 'CPPFLAGS=-DWOLFSSL_CUSTOM_OID + * -DWOLFSSL_ALT_NAMES -DWOLFSSL_FPKI' */ + const char * cert_fname = "./certs/server-cert.der"; const char * key_fname = "./certs/server-key.der"; X509* x509 = NULL; @@ -43896,6 +43902,18 @@ static int test_GENERAL_NAME_set0_othername(void) { int derSz = 0; EVP_PKEY* priv = NULL; FILE* f = NULL; + /* The length of this buffer is 37 */ + const unsigned char expected_asn1[] = { + /* OID specifier and length */ + 0x06, 0x0A, + /* 1.3.6.1.4.1.311.20.2.3 */ + 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x14, 0x02, 0x03, + /* TODO */ + 0xA0, 0x17, 0x0C, 0x15, + /* othername@wolfssl.com */ + 0x6F, 0x74, 0x68, 0x65, 0x72, 0x6E, 0x61, 0x6D, 0x65, 0x40, 0x77, 0x6F, + 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D + }; AssertNotNull(f = fopen(cert_fname, "rb")); AssertNotNull(x509 = d2i_X509_fp(f, NULL)); @@ -43919,6 +43937,25 @@ static int test_GENERAL_NAME_set0_othername(void) { (const unsigned char**)&pt, derSz)); AssertIntGT(X509_sign(x509, priv, EVP_sha256()), 0); sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); + AssertNotNull(gns = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, + NULL)); + + AssertIntEQ(sk_GENERAL_NAME_num(gns), 3); + + AssertNotNull(gn = sk_GENERAL_NAME_value(gns, 2)); + AssertIntEQ(gn->type, 0); + + /* It is odd that we are using ASN_RFC822_TYPE. It is because when we are + * parsing der, the string is not fully parsed. It is still raw der whereas + * when we encode we set the oid (for example, upn) and value. As we are + * overloading the meaning of the type, here we manually do the right thing. + */ + AssertIntEQ(ASN1_STRING_length(gn->d.rfc822Name), 37); + AssertIntEQ(XMEMCMP(ASN1_STRING_data(gn->d.rfc822Name), expected_asn1, 37), + 0); + gn->type = ASN_RFC822_TYPE; + sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); + ASN1_OBJECT_free(upn_oid); X509_EXTENSION_free(ext); X509_free(x509); @@ -43934,7 +43971,13 @@ static int test_othername_and_SID_ext(void) { #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) && \ defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ALT_NAMES) && \ - defined(WOLFSSL_CERT_EXT) && !defined(NO_FILESYSTEM) + defined(WOLFSSL_CERT_EXT) && !defined(NO_FILESYSTEM) && \ + defined(WOLFSSL_FPKI) && defined(WOLFSSL_ASN_TEMPLATE) + + /* ./configure --enable-opensslall --enable-certgen --enable-certreq + * --enable-certext --enable-debug 'CPPFLAGS=-DWOLFSSL_CUSTOM_OID + * -DWOLFSSL_ALT_NAMES -DWOLFSSL_FPKI' */ + const char* csr_fname = "./certs/csr.signed.der"; const char* key_fname = "./certs/server-key.der"; @@ -43945,11 +43988,13 @@ static int test_othername_and_SID_ext(void) { STACK_OF(X509_EXTENSION) *exts = NULL; X509_EXTENSION * san_ext = NULL; + X509_EXTENSION * ext = NULL; GENERAL_NAME* gn = NULL; GENERAL_NAMES* gns = NULL; ASN1_OBJECT* upn_oid = NULL; ASN1_UTF8STRING *utf8str = NULL; ASN1_TYPE *value = NULL; + ASN1_STRING *extval = NULL; /* SID extension. SID data format explained here: * https://blog.qdsecurity.se/2022/05/27/manually-injecting-a-sid-in-a-certificate/ @@ -43959,6 +44004,13 @@ static int test_othername_and_SID_ext(void) { 48, 4, 46, 83, 45, 49, 45, 53, 45, 50, 49, 45, 50, 56, 52, 51, 57, 48, 55, 52, 49, 56, 45, 51, 57, 50, 54, 50, 55, 55, 52, 50, 49, 45, 51, 56, 49, 53, 57, 57, 51, 57, 55, 50, 45, 52, 54, 48, 49}; + + uint8_t expectedAltName[] = { + 0x30, 0x27, 0xA0, 0x25, 0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, + 0x37, 0x14, 0x02, 0x03, 0xA0, 0x17, 0x0C, 0x15, 0x6F, 0x74, 0x68, 0x65, + 0x72, 0x6E, 0x61, 0x6D, 0x65, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, + 0x6C, 0x2E, 0x63, 0x6F, 0x6D}; + X509_EXTENSION *sid_ext = NULL; ASN1_OBJECT* sid_oid = NULL; ASN1_OCTET_STRING *sid_data = NULL; @@ -43966,6 +44018,7 @@ static int test_othername_and_SID_ext(void) { EVP_PKEY* priv = NULL; FILE* f = NULL; byte* pt = NULL; + BIO* bio = NULL; AssertNotNull(f = fopen(csr_fname, "rb")); AssertNotNull(x509 = d2i_X509_REQ_fp(f, NULL)); @@ -44007,7 +44060,54 @@ static int test_othername_and_SID_ext(void) { ASN1_OBJECT_free(sid_oid); ASN1_OCTET_STRING_free(sid_data); X509_REQ_free(x509); + x509 = NULL; EVP_PKEY_free(priv); + + /* At this point everything used to generate what is in der is cleaned up. + * We now read back from der to confirm the extensions were inserted + * correctly. */ + bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); + AssertNotNull(bio); + + AssertIntEQ(BIO_write(bio, der, derSz), derSz); /* d2i consumes BIO */ + d2i_X509_REQ_bio(bio, &x509); + AssertNotNull(x509); + BIO_free(bio); + AssertNotNull(exts = (STACK_OF(X509_EXTENSION)*) X509_REQ_get_extensions( + x509)); + AssertIntEQ(sk_X509_EXTENSION_num(exts), 2); + + /* Check the SID extension. */ + AssertNotNull(ext = sk_X509_EXTENSION_value(exts, 0)); + AssertNotNull(extval = X509_EXTENSION_get_data(ext)); + AssertIntEQ(extval->length, sizeof(SidExtension)); + AssertIntEQ(XMEMCMP(SidExtension, extval->data, sizeof(SidExtension)), 0); + + /* Check the AltNames extension. */ + AssertNotNull(ext = sk_X509_EXTENSION_value(exts, 1)); + AssertNotNull(extval = X509_EXTENSION_get_data(ext)); + AssertIntEQ(extval->length, sizeof(expectedAltName)); + AssertIntEQ(XMEMCMP(expectedAltName, extval->data, sizeof(expectedAltName)), + 0); + + /* Cleanup */ + AssertNotNull(gns = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, + NULL)); + AssertIntEQ(sk_GENERAL_NAME_num(gns), 1); + AssertNotNull(gn = sk_GENERAL_NAME_value(gns, 0)); + AssertIntEQ(gn->type, 0); + + /* It is odd that we are using ASN_RFC822_TYPE. It is because when we are + * parsing der, the string is not fully parsed. It is still raw der whereas + * when we encode we set the oid (for example, upn) and value. As we are + * overloading the meaning of the type, here we manually do the right thing. + */ + gn->type = ASN_RFC822_TYPE; + sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); + + ext->ext_sk->data.gn->type = ASN_RFC822_TYPE; + sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); + X509_REQ_free(x509); res = TEST_RES_CHECK(1); #endif return res; From c7f6cc2bc49e653150be7444c6bf62b0f946c5ca Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Mon, 8 May 2023 14:47:22 -0400 Subject: [PATCH 254/391] Address Jacob's comment --- src/x509.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/x509.c b/src/x509.c index d599a473097..abecda5e300 100644 --- a/src/x509.c +++ b/src/x509.c @@ -686,8 +686,22 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) /* extCount == loc. Now get the extension. */ /* Check if extension has been set */ isSet = wolfSSL_X509_ext_isSet_by_NID((WOLFSSL_X509*)x509, nid); - ext->obj = wolfSSL_OBJ_nid2obj(nid); - if (ext->obj != NULL) { + + if (wolfSSL_OBJ_nid2ln(nid) != NULL) { + /* This is NOT an unknown OID. */ + ext->obj = wolfSSL_OBJ_nid2obj(nid); + if (ext->obj == NULL) { + WOLFSSL_MSG("\tfail: Invalid OBJECT"); + wolfSSL_X509_EXTENSION_free(ext); + FreeDecodedCert(cert); + #ifdef WOLFSSL_SMALL_STACK + XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); + #endif + return NULL; + } + } + + if (ext->obj) { ext->obj->nid = nid; } From 80ac0b83165d5af99b82bf009e9b40d1d45096ac Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Wed, 3 May 2023 12:20:52 +0000 Subject: [PATCH 255/391] tls13: correctly propagatae SendAlert err message --- src/tls13.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/tls13.c b/src/tls13.c index 9ef9c283855..6717f2d0b2e 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -10999,7 +10999,7 @@ static int SanityCheckTls13MsgReceived(WOLFSSL* ssl, byte type) int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, byte type, word32 size, word32 totalSz) { - int ret = 0; + int ret = 0, tmp; word32 inIdx = *inOutIdx; int alertType = invalid_alert; #if defined(HAVE_ECH) @@ -11239,7 +11239,11 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (type == client_hello && ssl->options.dtls) DtlsSetSeqNumForReply(ssl); #endif - SendAlert(ssl, alert_fatal, alertType); + tmp = SendAlert(ssl, alert_fatal, alertType); + /* propagate socket error instead of tls error to be sure the error is + * not ignored by DTLS code */ + if (tmp == SOCKET_ERROR_E) + ret = SOCKET_ERROR_E; } if (ret == 0 && ssl->options.tls1_3) { From 18c7b57919cdf7188ac27025a0db2b88e2ebd23b Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Tue, 9 May 2023 13:26:19 -0600 Subject: [PATCH 256/391] Fix for compiling with NO_ASN_TIME --- src/ssl.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ssl.c b/src/ssl.c index 1271304a32e..014154949ac 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -14578,7 +14578,9 @@ void SetupSession(WOLFSSL* ssl) } #endif session->timeout = ssl->timeout; +#ifndef NO_ASN_TIME session->bornOn = LowResTimer(); +#endif #if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ defined(HAVE_SESSION_TICKET)) session->version = ssl->version; From 09f426483f0d25cbbb8aca4e88020172a6d02ac2 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Tue, 9 May 2023 13:28:20 -0600 Subject: [PATCH 257/391] Remove inaccurate STM32 documentation --- IDE/STM32Cube/README.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/IDE/STM32Cube/README.md b/IDE/STM32Cube/README.md index 8689b9e34a8..8a5bcea4487 100644 --- a/IDE/STM32Cube/README.md +++ b/IDE/STM32Cube/README.md @@ -37,16 +37,6 @@ You need both the STM32 IDE and the STM32 initialization code generator (STM32Cu 8. The Benchmark example uses float. To enable go to "Project Properties" -> "C/C++ Build" -> "Settings" -> "Tool Settings" -> "MCU Settings" -> Check "Use float with printf". 9. To enable printf make the `main.c` changes below in the [STM32 Printf](#stm32-printf) section. -### STM32 Cube Pack Examples - -In the `I-CUBE-wolfSSL.pack` pack there are pre-assembled example projects available. -After installing the pack you can find these example projects in `STM32Cube/Repository/Packs/wolfSSL/wolfSSL/[Version]/Projects`. -To use an example: - -1. Open STM32CubeIDE -2. Choose "Import" -> "Import an Existing STM32CubeMX Configuration File (.ioc)". -3. Browse to find the .ioc in `STM32Cube/Repository/Packs/wolfSSL/wolfSSL/[Version]/Projects` and click finish. - ### Creating your own STM32CubeMX configuration If none of the examples fit your STM32 type then you can create your own in STM32CubeMX by doing the following: From 870ecbcec2987b70be6f4155a02a903ec211392c Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 9 May 2023 09:30:47 +0000 Subject: [PATCH 258/391] dtls13: fix: use dtls label to derive ExportKey/Resumption secrets --- src/tls13.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/tls13.c b/src/tls13.c index 6717f2d0b2e..a173d60bff3 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -885,9 +885,19 @@ int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen, const byte* protocol = tls13ProtocolLabel; word32 protocolLen = TLS13_PROTOCOL_LABEL_SZ; - if (ssl->version.minor != TLSv1_3_MINOR) + if (ssl->options.dtls && ssl->version.minor != DTLSv1_3_MINOR) return VERSION_ERROR; + if (!ssl->options.dtls && ssl->version.minor != TLSv1_3_MINOR) + return VERSION_ERROR; + +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls) { + protocol = dtls13ProtocolLabel; + protocolLen = DTLS13_PROTOCOL_LABEL_SZ; + } +#endif /* WOLFSSL_DTLS13 */ + switch (ssl->specs.mac_algorithm) { #ifndef NO_SHA256 case sha256_mac: @@ -1166,6 +1176,13 @@ int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen, byte* secret) WOLFSSL_MSG("Derive Resumption PSK"); +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls) { + protocol = dtls13ProtocolLabel; + protocolLen = DTLS13_PROTOCOL_LABEL_SZ; + } +#endif /* WOLFSSL_DTLS13 */ + switch (ssl->specs.mac_algorithm) { #ifndef NO_SHA256 case sha256_mac: From 575d72e57fb025215edfb472b9f410ec5aa45e6b Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 17 Apr 2023 17:29:39 +1000 Subject: [PATCH 259/391] AES: touch each cache line when getting offset from table --- wolfcrypt/src/aes.c | 613 +++++++++++++++++++++++++++----------------- 1 file changed, 371 insertions(+), 242 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 184838a6bf3..0996539b29b 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -1725,12 +1725,14 @@ static WARN_UNUSED_RESULT word32 inv_col_mul( #endif #endif +#define WOLFSSL_AES_TOUCH_LINES #ifndef WC_NO_CACHE_RESISTANT #ifndef WOLFSSL_AES_SMALL_TABLES /* load 4 Te Tables into cache by cache line stride */ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchTe(void) { +#ifndef WOLFSSL_AES_TOUCH_LINES word32 x = 0; int i,j; @@ -1741,11 +1743,15 @@ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchTe(void) } } return x; +#else + return 0; +#endif } #else /* load sbox into cache by cache line stride */ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchSBox(void) { +#ifndef WOLFSSL_AES_TOUCH_LINES word32 x = 0; int i; @@ -1753,10 +1759,121 @@ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchSBox(void) x &= Tsbox[i]; } return x; +#else + return 0; +#endif } #endif #endif +#ifdef WOLFSSL_AES_TOUCH_LINES +#if WC_CACHE_LINE_SZ == 128 + #define WC_CACHE_LINE_BITS 5 + #define WC_CACHE_LINE_MASK_HI 0xe0 + #define WC_CACHE_LINE_MASK_LO 0x1f + #define WC_CACHE_LINE_ADD 0x20 +#elif WC_CACHE_LINE_SZ == 64 + #define WC_CACHE_LINE_BITS 4 + #define WC_CACHE_LINE_MASK_HI 0xf0 + #define WC_CACHE_LINE_MASK_LO 0x0f + #define WC_CACHE_LINE_ADD 0x10 +#elif WC_CACHE_LINE_SZ == 32 + #define WC_CACHE_LINE_BITS 3 + #define WC_CACHE_LINE_MASK_HI 0xf8 + #define WC_CACHE_LINE_MASK_LO 0x07 + #define WC_CACHE_LINE_ADD 0x08 +#elif WC_CACHE_LINE_SZ = 16 + #define WC_CACHE_LINE_BITS 2 + #define WC_CACHE_LINE_MASK_HI 0xfc + #define WC_CACHE_LINE_MASK_LO 0x03 + #define WC_CACHE_LINE_ADD 0x04 +#else + #error Cache line size not supported +#endif + +static word32 GetTable(const word32* t, byte o) +{ +#if WC_CACHE_LINE_SZ == 64 + word32 e; + byte hi = o & 0xf0; + byte lo = o & 0x0f; + + e = t[lo + 0x00] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x10] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x20] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x30] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x40] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x50] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x60] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x70] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x80] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x90] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xa0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xb0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xc0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xd0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xe0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xf0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); + + return e; +#else + word32 e = 0; + int i; + byte hi = o & WC_CACHE_LINE_MASK_HI; + byte lo = o & WC_CACHE_LINE_MASK_LO; + + for (i = 0; i < 256; i += (1 << WC_CACHE_LINE_BITS)) { + e |= t[lo + i] & ((word32)0 - (((word32)hi - 0x01) >> 31)); + hi -= WC_CACHE_LINE_ADD; + } + + return e; +#endif +} +static byte GetTable8(const byte* t, byte o) +{ +#if WC_CACHE_LINE_SZ == 64 + byte e; + byte hi = o & 0xf0; + byte lo = o & 0x0f; + + e = t[lo + 0x00] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x10] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x20] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x30] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x40] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x50] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x60] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x70] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x80] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0x90] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xa0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xb0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xc0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xd0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xe0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); hi -= 0x10; + e |= t[lo + 0xf0] & ((word32)0 - (((word32)hi - 0x01) >> 31)); + + return e; +#else + byte e = 0; + int i; + byte hi = o & WC_CACHE_LINE_MASK_HI; + byte lo = o & WC_CACHE_LINE_MASK_LO; + + for (i = 0; i < 256; i += (1 << WC_CACHE_LINE_BITS)) { + e |= t[lo + i] & ((word32)0 - (((word32)hi - 0x01) >> 31)); + hi -= WC_CACHE_LINE_ADD; + } + + return e; +#endif +} +#else +#define GetTable(t, o) t[o] +#define GetTable8(t, o) t[o] +#endif + /* Software AES - ECB Encrypt */ static WARN_UNUSED_RESULT int wc_AesEncrypt( Aes* aes, const byte* inBlock, byte* outBlock) @@ -1865,24 +1982,32 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( #ifndef WOLFSSL_AES_NO_UNROLL /* Unroll the loop. */ -#define ENC_ROUND_T_S(o) \ - t0 = Te[0][GETBYTE(s0, 3)] ^ Te[1][GETBYTE(s1, 2)] ^ \ - Te[2][GETBYTE(s2, 1)] ^ Te[3][GETBYTE(s3, 0)] ^ rk[(o)+4]; \ - t1 = Te[0][GETBYTE(s1, 3)] ^ Te[1][GETBYTE(s2, 2)] ^ \ - Te[2][GETBYTE(s3, 1)] ^ Te[3][GETBYTE(s0, 0)] ^ rk[(o)+5]; \ - t2 = Te[0][GETBYTE(s2, 3)] ^ Te[1][GETBYTE(s3, 2)] ^ \ - Te[2][GETBYTE(s0, 1)] ^ Te[3][GETBYTE(s1, 0)] ^ rk[(o)+6]; \ - t3 = Te[0][GETBYTE(s3, 3)] ^ Te[1][GETBYTE(s0, 2)] ^ \ - Te[2][GETBYTE(s1, 1)] ^ Te[3][GETBYTE(s2, 0)] ^ rk[(o)+7] -#define ENC_ROUND_S_T(o) \ - s0 = Te[0][GETBYTE(t0, 3)] ^ Te[1][GETBYTE(t1, 2)] ^ \ - Te[2][GETBYTE(t2, 1)] ^ Te[3][GETBYTE(t3, 0)] ^ rk[(o)+0]; \ - s1 = Te[0][GETBYTE(t1, 3)] ^ Te[1][GETBYTE(t2, 2)] ^ \ - Te[2][GETBYTE(t3, 1)] ^ Te[3][GETBYTE(t0, 0)] ^ rk[(o)+1]; \ - s2 = Te[0][GETBYTE(t2, 3)] ^ Te[1][GETBYTE(t3, 2)] ^ \ - Te[2][GETBYTE(t0, 1)] ^ Te[3][GETBYTE(t1, 0)] ^ rk[(o)+2]; \ - s3 = Te[0][GETBYTE(t3, 3)] ^ Te[1][GETBYTE(t0, 2)] ^ \ - Te[2][GETBYTE(t1, 1)] ^ Te[3][GETBYTE(t2, 0)] ^ rk[(o)+3] +#define ENC_ROUND_T_S(o) \ + t0 = GetTable(Te[0], GETBYTE(s0, 3)) ^ GetTable(Te[1], GETBYTE(s1, 2)) ^ \ + GetTable(Te[2], GETBYTE(s2, 1)) ^ GetTable(Te[3], GETBYTE(s3, 0)) ^ \ + rk[(o)+4]; \ + t1 = GetTable(Te[0], GETBYTE(s1, 3)) ^ GetTable(Te[1], GETBYTE(s2, 2)) ^ \ + GetTable(Te[2], GETBYTE(s3, 1)) ^ GetTable(Te[3], GETBYTE(s0, 0)) ^ \ + rk[(o)+5]; \ + t2 = GetTable(Te[0], GETBYTE(s2, 3)) ^ GetTable(Te[1], GETBYTE(s3, 2)) ^ \ + GetTable(Te[2], GETBYTE(s0, 1)) ^ GetTable(Te[3], GETBYTE(s1, 0)) ^ \ + rk[(o)+6]; \ + t3 = GetTable(Te[0], GETBYTE(s3, 3)) ^ GetTable(Te[1], GETBYTE(s0, 2)) ^ \ + GetTable(Te[2], GETBYTE(s1, 1)) ^ GetTable(Te[3], GETBYTE(s2, 0)) ^ \ + rk[(o)+7] +#define ENC_ROUND_S_T(o) \ + s0 = GetTable(Te[0], GETBYTE(t0, 3)) ^ GetTable(Te[1], GETBYTE(t1, 2)) ^ \ + GetTable(Te[2], GETBYTE(t2, 1)) ^ GetTable(Te[3], GETBYTE(t3, 0)) ^ \ + rk[(o)+0]; \ + s1 = GetTable(Te[0], GETBYTE(t1, 3)) ^ GetTable(Te[1], GETBYTE(t2, 2)) ^ \ + GetTable(Te[2], GETBYTE(t3, 1)) ^ GetTable(Te[3], GETBYTE(t0, 0)) ^ \ + rk[(o)+1]; \ + s2 = GetTable(Te[0], GETBYTE(t2, 3)) ^ GetTable(Te[1], GETBYTE(t3, 2)) ^ \ + GetTable(Te[2], GETBYTE(t0, 1)) ^ GetTable(Te[3], GETBYTE(t1, 0)) ^ \ + rk[(o)+2]; \ + s3 = GetTable(Te[0], GETBYTE(t3, 3)) ^ GetTable(Te[1], GETBYTE(t0, 2)) ^ \ + GetTable(Te[2], GETBYTE(t1, 1)) ^ GetTable(Te[3], GETBYTE(t2, 0)) ^ \ + rk[(o)+3] ENC_ROUND_T_S( 0); ENC_ROUND_S_T( 8); ENC_ROUND_T_S( 8); @@ -1903,28 +2028,28 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( for (;;) { t0 = - Te[0][GETBYTE(s0, 3)] ^ - Te[1][GETBYTE(s1, 2)] ^ - Te[2][GETBYTE(s2, 1)] ^ - Te[3][GETBYTE(s3, 0)] ^ + GetTable(Te[0], GETBYTE(s0, 3)) ^ + GetTable(Te[1], GETBYTE(s1, 2)) ^ + GetTable(Te[2], GETBYTE(s2, 1)) ^ + GetTable(Te[3], GETBYTE(s3, 0)) ^ rk[4]; t1 = - Te[0][GETBYTE(s1, 3)] ^ - Te[1][GETBYTE(s2, 2)] ^ - Te[2][GETBYTE(s3, 1)] ^ - Te[3][GETBYTE(s0, 0)] ^ + GetTable(Te[0], GETBYTE(s1, 3)) ^ + GetTable(Te[1], GETBYTE(s2, 2)) ^ + GetTable(Te[2], GETBYTE(s3, 1)) ^ + GetTable(Te[3], GETBYTE(s0, 0)) ^ rk[5]; t2 = - Te[0][GETBYTE(s2, 3)] ^ - Te[1][GETBYTE(s3, 2)] ^ - Te[2][GETBYTE(s0, 1)] ^ - Te[3][GETBYTE(s1, 0)] ^ + GetTable(Te[0], GETBYTE(s2, 3)) ^ + GetTable(Te[1], GETBYTE(s3, 2)) ^ + GetTable(Te[2], GETBYTE(s0, 1)) ^ + GetTable(Te[3], GETBYTE(s1, 0)) ^ rk[6]; t3 = - Te[0][GETBYTE(s3, 3)] ^ - Te[1][GETBYTE(s0, 2)] ^ - Te[2][GETBYTE(s1, 1)] ^ - Te[3][GETBYTE(s2, 0)] ^ + GetTable(Te[0], GETBYTE(s3, 3)) ^ + GetTable(Te[1], GETBYTE(s0, 2)) ^ + GetTable(Te[2], GETBYTE(s1, 1)) ^ + GetTable(Te[3], GETBYTE(s2, 0)) ^ rk[7]; rk += 8; @@ -1933,28 +2058,28 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( } s0 = - Te[0][GETBYTE(t0, 3)] ^ - Te[1][GETBYTE(t1, 2)] ^ - Te[2][GETBYTE(t2, 1)] ^ - Te[3][GETBYTE(t3, 0)] ^ + GetTable(Te[0], GETBYTE(t0, 3)) ^ + GetTable(Te[1], GETBYTE(t1, 2)) ^ + GetTable(Te[2], GETBYTE(t2, 1)) ^ + GetTable(Te[3], GETBYTE(t3, 0)) ^ rk[0]; s1 = - Te[0][GETBYTE(t1, 3)] ^ - Te[1][GETBYTE(t2, 2)] ^ - Te[2][GETBYTE(t3, 1)] ^ - Te[3][GETBYTE(t0, 0)] ^ + GetTable(Te[0], GETBYTE(t1, 3)) ^ + GetTable(Te[1], GETBYTE(t2, 2)) ^ + GetTable(Te[2], GETBYTE(t3, 1)) ^ + GetTable(Te[3], GETBYTE(t0, 0)) ^ rk[1]; s2 = - Te[0][GETBYTE(t2, 3)] ^ - Te[1][GETBYTE(t3, 2)] ^ - Te[2][GETBYTE(t0, 1)] ^ - Te[3][GETBYTE(t1, 0)] ^ + GetTable(Te[0], GETBYTE(t2, 3)) ^ + GetTable(Te[1], GETBYTE(t3, 2)) ^ + GetTable(Te[2], GETBYTE(t0, 1)) ^ + GetTable(Te[3], GETBYTE(t1, 0)) ^ rk[2]; s3 = - Te[0][GETBYTE(t3, 3)] ^ - Te[1][GETBYTE(t0, 2)] ^ - Te[2][GETBYTE(t1, 1)] ^ - Te[3][GETBYTE(t2, 0)] ^ + GetTable(Te[0], GETBYTE(t3, 3)) ^ + GetTable(Te[1], GETBYTE(t0, 2)) ^ + GetTable(Te[2], GETBYTE(t1, 1)) ^ + GetTable(Te[3], GETBYTE(t2, 0)) ^ rk[3]; } #endif @@ -1965,28 +2090,28 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( */ s0 = - (Te[2][GETBYTE(t0, 3)] & 0xff000000) ^ - (Te[3][GETBYTE(t1, 2)] & 0x00ff0000) ^ - (Te[0][GETBYTE(t2, 1)] & 0x0000ff00) ^ - (Te[1][GETBYTE(t3, 0)] & 0x000000ff) ^ + (GetTable(Te[2], GETBYTE(t0, 3)) & 0xff000000) ^ + (GetTable(Te[3], GETBYTE(t1, 2)) & 0x00ff0000) ^ + (GetTable(Te[0], GETBYTE(t2, 1)) & 0x0000ff00) ^ + (GetTable(Te[1], GETBYTE(t3, 0)) & 0x000000ff) ^ rk[0]; s1 = - (Te[2][GETBYTE(t1, 3)] & 0xff000000) ^ - (Te[3][GETBYTE(t2, 2)] & 0x00ff0000) ^ - (Te[0][GETBYTE(t3, 1)] & 0x0000ff00) ^ - (Te[1][GETBYTE(t0, 0)] & 0x000000ff) ^ + (GetTable(Te[2], GETBYTE(t1, 3)) & 0xff000000) ^ + (GetTable(Te[3], GETBYTE(t2, 2)) & 0x00ff0000) ^ + (GetTable(Te[0], GETBYTE(t3, 1)) & 0x0000ff00) ^ + (GetTable(Te[1], GETBYTE(t0, 0)) & 0x000000ff) ^ rk[1]; s2 = - (Te[2][GETBYTE(t2, 3)] & 0xff000000) ^ - (Te[3][GETBYTE(t3, 2)] & 0x00ff0000) ^ - (Te[0][GETBYTE(t0, 1)] & 0x0000ff00) ^ - (Te[1][GETBYTE(t1, 0)] & 0x000000ff) ^ + (GetTable(Te[2], GETBYTE(t2, 3)) & 0xff000000) ^ + (GetTable(Te[3], GETBYTE(t3, 2)) & 0x00ff0000) ^ + (GetTable(Te[0], GETBYTE(t0, 1)) & 0x0000ff00) ^ + (GetTable(Te[1], GETBYTE(t1, 0)) & 0x000000ff) ^ rk[2]; s3 = - (Te[2][GETBYTE(t3, 3)] & 0xff000000) ^ - (Te[3][GETBYTE(t0, 2)] & 0x00ff0000) ^ - (Te[0][GETBYTE(t1, 1)] & 0x0000ff00) ^ - (Te[1][GETBYTE(t2, 0)] & 0x000000ff) ^ + (GetTable(Te[2], GETBYTE(t3, 3)) & 0xff000000) ^ + (GetTable(Te[3], GETBYTE(t0, 2)) & 0x00ff0000) ^ + (GetTable(Te[0], GETBYTE(t1, 1)) & 0x0000ff00) ^ + (GetTable(Te[1], GETBYTE(t2, 0)) & 0x000000ff) ^ rk[3]; #else #ifndef WC_NO_CACHE_RESISTANT @@ -1997,25 +2122,25 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( /* Two rounds at a time */ for (rk += 4; r > 1; r--, rk += 4) { t0 = - ((word32)Tsbox[GETBYTE(s0, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(s1, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(s2, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(s3, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(s0, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s1, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s2, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s3, 0))); t1 = - ((word32)Tsbox[GETBYTE(s1, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(s2, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(s3, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(s0, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(s1, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s2, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s3, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s0, 0))); t2 = - ((word32)Tsbox[GETBYTE(s2, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(s3, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(s0, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(s1, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(s2, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s3, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s0, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s1, 0))); t3 = - ((word32)Tsbox[GETBYTE(s3, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(s0, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(s1, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(s2, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(s3, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s0, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s1, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s2, 0))); s0 = (col_mul(t0, 3, 2, 0, 1) << 24) ^ @@ -2044,25 +2169,25 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( } t0 = - ((word32)Tsbox[GETBYTE(s0, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(s1, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(s2, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(s3, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(s0, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s1, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s2, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s3, 0))); t1 = - ((word32)Tsbox[GETBYTE(s1, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(s2, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(s3, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(s0, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(s1, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s2, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s3, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s0, 0))); t2 = - ((word32)Tsbox[GETBYTE(s2, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(s3, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(s0, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(s1, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(s2, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s3, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s0, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s1, 0))); t3 = - ((word32)Tsbox[GETBYTE(s3, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(s0, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(s1, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(s2, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(s3, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s0, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s1, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(s2, 0))); s0 = t0 ^ rk[0]; s1 = t1 ^ rk[1]; s2 = t2 ^ rk[2]; @@ -2111,6 +2236,7 @@ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchTd(void) /* load Td Table4 into cache by cache line stride */ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchTd4(void) { +#ifndef WOLFSSL_AES_TOUCH_LINES word32 x = 0; int i; @@ -2118,6 +2244,9 @@ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchTd4(void) x &= (word32)Td4[i]; } return x; +#else + return 0; +#endif } #endif @@ -2204,23 +2333,23 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( #ifndef WOLFSSL_AES_NO_UNROLL /* Unroll the loop. */ #define DEC_ROUND_T_S(o) \ - t0 = Td[0][GETBYTE(s0, 3)] ^ Td[1][GETBYTE(s3, 2)] ^ \ - Td[2][GETBYTE(s2, 1)] ^ Td[3][GETBYTE(s1, 0)] ^ rk[(o)+4]; \ - t1 = Td[0][GETBYTE(s1, 3)] ^ Td[1][GETBYTE(s0, 2)] ^ \ - Td[2][GETBYTE(s3, 1)] ^ Td[3][GETBYTE(s2, 0)] ^ rk[(o)+5]; \ - t2 = Td[0][GETBYTE(s2, 3)] ^ Td[1][GETBYTE(s1, 2)] ^ \ - Td[2][GETBYTE(s0, 1)] ^ Td[3][GETBYTE(s3, 0)] ^ rk[(o)+6]; \ - t3 = Td[0][GETBYTE(s3, 3)] ^ Td[1][GETBYTE(s2, 2)] ^ \ - Td[2][GETBYTE(s1, 1)] ^ Td[3][GETBYTE(s0, 0)] ^ rk[(o)+7] + t0 = GetTable(Td[0], GETBYTE(s0, 3)) ^ GetTable(Td[1], GETBYTE(s3, 2)) ^ \ + GetTable(Td[2], GETBYTE(s2, 1)) ^ GetTable(Td[3], GETBYTE(s1, 0)) ^ rk[(o)+4]; \ + t1 = GetTable(Td[0], GETBYTE(s1, 3)) ^ GetTable(Td[1], GETBYTE(s0, 2)) ^ \ + GetTable(Td[2], GETBYTE(s3, 1)) ^ GetTable(Td[3], GETBYTE(s2, 0)) ^ rk[(o)+5]; \ + t2 = GetTable(Td[0], GETBYTE(s2, 3)) ^ GetTable(Td[1], GETBYTE(s1, 2)) ^ \ + GetTable(Td[2], GETBYTE(s0, 1)) ^ GetTable(Td[3], GETBYTE(s3, 0)) ^ rk[(o)+6]; \ + t3 = GetTable(Td[0], GETBYTE(s3, 3)) ^ GetTable(Td[1], GETBYTE(s2, 2)) ^ \ + GetTable(Td[2], GETBYTE(s1, 1)) ^ GetTable(Td[3], GETBYTE(s0, 0)) ^ rk[(o)+7] #define DEC_ROUND_S_T(o) \ - s0 = Td[0][GETBYTE(t0, 3)] ^ Td[1][GETBYTE(t3, 2)] ^ \ - Td[2][GETBYTE(t2, 1)] ^ Td[3][GETBYTE(t1, 0)] ^ rk[(o)+0]; \ - s1 = Td[0][GETBYTE(t1, 3)] ^ Td[1][GETBYTE(t0, 2)] ^ \ - Td[2][GETBYTE(t3, 1)] ^ Td[3][GETBYTE(t2, 0)] ^ rk[(o)+1]; \ - s2 = Td[0][GETBYTE(t2, 3)] ^ Td[1][GETBYTE(t1, 2)] ^ \ - Td[2][GETBYTE(t0, 1)] ^ Td[3][GETBYTE(t3, 0)] ^ rk[(o)+2]; \ - s3 = Td[0][GETBYTE(t3, 3)] ^ Td[1][GETBYTE(t2, 2)] ^ \ - Td[2][GETBYTE(t1, 1)] ^ Td[3][GETBYTE(t0, 0)] ^ rk[(o)+3] + s0 = GetTable(Td[0], GETBYTE(t0, 3)) ^ GetTable(Td[1], GETBYTE(t3, 2)) ^ \ + GetTable(Td[2], GETBYTE(t2, 1)) ^ GetTable(Td[3], GETBYTE(t1, 0)) ^ rk[(o)+0]; \ + s1 = GetTable(Td[0], GETBYTE(t1, 3)) ^ GetTable(Td[1], GETBYTE(t0, 2)) ^ \ + GetTable(Td[2], GETBYTE(t3, 1)) ^ GetTable(Td[3], GETBYTE(t2, 0)) ^ rk[(o)+1]; \ + s2 = GetTable(Td[0], GETBYTE(t2, 3)) ^ GetTable(Td[1], GETBYTE(t1, 2)) ^ \ + GetTable(Td[2], GETBYTE(t0, 1)) ^ GetTable(Td[3], GETBYTE(t3, 0)) ^ rk[(o)+2]; \ + s3 = GetTable(Td[0], GETBYTE(t3, 3)) ^ GetTable(Td[1], GETBYTE(t2, 2)) ^ \ + GetTable(Td[2], GETBYTE(t1, 1)) ^ GetTable(Td[3], GETBYTE(t0, 0)) ^ rk[(o)+3] DEC_ROUND_T_S( 0); DEC_ROUND_S_T( 8); DEC_ROUND_T_S( 8); @@ -2242,28 +2371,28 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( for (;;) { t0 = - Td[0][GETBYTE(s0, 3)] ^ - Td[1][GETBYTE(s3, 2)] ^ - Td[2][GETBYTE(s2, 1)] ^ - Td[3][GETBYTE(s1, 0)] ^ + GetTable(Td[0], GETBYTE(s0, 3)) ^ + GetTable(Td[1], GETBYTE(s3, 2)) ^ + GetTable(Td[2], GETBYTE(s2, 1)) ^ + GetTable(Td[3], GETBYTE(s1, 0)) ^ rk[4]; t1 = - Td[0][GETBYTE(s1, 3)] ^ - Td[1][GETBYTE(s0, 2)] ^ - Td[2][GETBYTE(s3, 1)] ^ - Td[3][GETBYTE(s2, 0)] ^ + GetTable(Td[0], GETBYTE(s1, 3)) ^ + GetTable(Td[1], GETBYTE(s0, 2)) ^ + GetTable(Td[2], GETBYTE(s3, 1)) ^ + GetTable(Td[3], GETBYTE(s2, 0)) ^ rk[5]; t2 = - Td[0][GETBYTE(s2, 3)] ^ - Td[1][GETBYTE(s1, 2)] ^ - Td[2][GETBYTE(s0, 1)] ^ - Td[3][GETBYTE(s3, 0)] ^ + GetTable(Td[0], GETBYTE(s2, 3)) ^ + GetTable(Td[1], GETBYTE(s1, 2)) ^ + GetTable(Td[2], GETBYTE(s0, 1)) ^ + GetTable(Td[3], GETBYTE(s3, 0)) ^ rk[6]; t3 = - Td[0][GETBYTE(s3, 3)] ^ - Td[1][GETBYTE(s2, 2)] ^ - Td[2][GETBYTE(s1, 1)] ^ - Td[3][GETBYTE(s0, 0)] ^ + GetTable(Td[0], GETBYTE(s3, 3)) ^ + GetTable(Td[1], GETBYTE(s2, 2)) ^ + GetTable(Td[2], GETBYTE(s1, 1)) ^ + GetTable(Td[3], GETBYTE(s0, 0)) ^ rk[7]; rk += 8; @@ -2272,28 +2401,28 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( } s0 = - Td[0][GETBYTE(t0, 3)] ^ - Td[1][GETBYTE(t3, 2)] ^ - Td[2][GETBYTE(t2, 1)] ^ - Td[3][GETBYTE(t1, 0)] ^ + GetTable(Td[0], GETBYTE(t0, 3)) ^ + GetTable(Td[1], GETBYTE(t3, 2)) ^ + GetTable(Td[2], GETBYTE(t2, 1)) ^ + GetTable(Td[3], GETBYTE(t1, 0)) ^ rk[0]; s1 = - Td[0][GETBYTE(t1, 3)] ^ - Td[1][GETBYTE(t0, 2)] ^ - Td[2][GETBYTE(t3, 1)] ^ - Td[3][GETBYTE(t2, 0)] ^ + GetTable(Td[0], GETBYTE(t1, 3)) ^ + GetTable(Td[1], GETBYTE(t0, 2)) ^ + GetTable(Td[2], GETBYTE(t3, 1)) ^ + GetTable(Td[3], GETBYTE(t2, 0)) ^ rk[1]; s2 = - Td[0][GETBYTE(t2, 3)] ^ - Td[1][GETBYTE(t1, 2)] ^ - Td[2][GETBYTE(t0, 1)] ^ - Td[3][GETBYTE(t3, 0)] ^ + GetTable(Td[0], GETBYTE(t2, 3)) ^ + GetTable(Td[1], GETBYTE(t1, 2)) ^ + GetTable(Td[2], GETBYTE(t0, 1)) ^ + GetTable(Td[3], GETBYTE(t3, 0)) ^ rk[2]; s3 = - Td[0][GETBYTE(t3, 3)] ^ - Td[1][GETBYTE(t2, 2)] ^ - Td[2][GETBYTE(t1, 1)] ^ - Td[3][GETBYTE(t0, 0)] ^ + GetTable(Td[0], GETBYTE(t3, 3)) ^ + GetTable(Td[1], GETBYTE(t2, 2)) ^ + GetTable(Td[2], GETBYTE(t1, 1)) ^ + GetTable(Td[3], GETBYTE(t0, 0)) ^ rk[3]; } #endif @@ -2307,28 +2436,28 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( #endif s0 = - ((word32)Td4[GETBYTE(t0, 3)] << 24) ^ - ((word32)Td4[GETBYTE(t3, 2)] << 16) ^ - ((word32)Td4[GETBYTE(t2, 1)] << 8) ^ - ((word32)Td4[GETBYTE(t1, 0)]) ^ + ((word32)GetTable8(Td4, GETBYTE(t0, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(t3, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(t2, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(t1, 0))) ^ rk[0]; s1 = - ((word32)Td4[GETBYTE(t1, 3)] << 24) ^ - ((word32)Td4[GETBYTE(t0, 2)] << 16) ^ - ((word32)Td4[GETBYTE(t3, 1)] << 8) ^ - ((word32)Td4[GETBYTE(t2, 0)]) ^ + ((word32)GetTable8(Td4, GETBYTE(t1, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(t0, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(t3, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(t2, 0))) ^ rk[1]; s2 = - ((word32)Td4[GETBYTE(t2, 3)] << 24) ^ - ((word32)Td4[GETBYTE(t1, 2)] << 16) ^ - ((word32)Td4[GETBYTE(t0, 1)] << 8) ^ - ((word32)Td4[GETBYTE(t3, 0)]) ^ + ((word32)GetTable8(Td4, GETBYTE(t2, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(t1, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(t0, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(t3, 0))) ^ rk[2]; s3 = - ((word32)Td4[GETBYTE(t3, 3)] << 24) ^ - ((word32)Td4[GETBYTE(t2, 2)] << 16) ^ - ((word32)Td4[GETBYTE(t1, 1)] << 8) ^ - ((word32)Td4[GETBYTE(t0, 0)]) ^ + ((word32)GetTable8(Td4, GETBYTE(t3, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(t2, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(t1, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(t0, 0))) ^ rk[3]; #else #ifndef WC_NO_CACHE_RESISTANT @@ -2338,28 +2467,28 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( r *= 2; for (rk += 4; r > 1; r--, rk += 4) { t0 = - ((word32)Td4[GETBYTE(s0, 3)] << 24) ^ - ((word32)Td4[GETBYTE(s3, 2)] << 16) ^ - ((word32)Td4[GETBYTE(s2, 1)] << 8) ^ - ((word32)Td4[GETBYTE(s1, 0)]) ^ + ((word32)GetTable8(Td4, GETBYTE(s0, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(s3, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(s2, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(s1, 0))) ^ rk[0]; t1 = - ((word32)Td4[GETBYTE(s1, 3)] << 24) ^ - ((word32)Td4[GETBYTE(s0, 2)] << 16) ^ - ((word32)Td4[GETBYTE(s3, 1)] << 8) ^ - ((word32)Td4[GETBYTE(s2, 0)]) ^ + ((word32)GetTable8(Td4, GETBYTE(s1, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(s0, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(s3, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(s2, 0))) ^ rk[1]; t2 = - ((word32)Td4[GETBYTE(s2, 3)] << 24) ^ - ((word32)Td4[GETBYTE(s1, 2)] << 16) ^ - ((word32)Td4[GETBYTE(s0, 1)] << 8) ^ - ((word32)Td4[GETBYTE(s3, 0)]) ^ + ((word32)GetTable8(Td4, GETBYTE(s2, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(s1, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(s0, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(s3, 0))) ^ rk[2]; t3 = - ((word32)Td4[GETBYTE(s3, 3)] << 24) ^ - ((word32)Td4[GETBYTE(s2, 2)] << 16) ^ - ((word32)Td4[GETBYTE(s1, 1)] << 8) ^ - ((word32)Td4[GETBYTE(s0, 0)]) ^ + ((word32)GetTable8(Td4, GETBYTE(s3, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(s2, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(s1, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(s0, 0))) ^ rk[3]; s0 = @@ -2385,25 +2514,25 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( } t0 = - ((word32)Td4[GETBYTE(s0, 3)] << 24) ^ - ((word32)Td4[GETBYTE(s3, 2)] << 16) ^ - ((word32)Td4[GETBYTE(s2, 1)] << 8) ^ - ((word32)Td4[GETBYTE(s1, 0)]); + ((word32)GetTable8(Td4, GETBYTE(s0, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(s3, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(s2, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(s1, 0))); t1 = - ((word32)Td4[GETBYTE(s1, 3)] << 24) ^ - ((word32)Td4[GETBYTE(s0, 2)] << 16) ^ - ((word32)Td4[GETBYTE(s3, 1)] << 8) ^ - ((word32)Td4[GETBYTE(s2, 0)]); + ((word32)GetTable8(Td4, GETBYTE(s1, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(s0, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(s3, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(s2, 0))); t2 = - ((word32)Td4[GETBYTE(s2, 3)] << 24) ^ - ((word32)Td4[GETBYTE(s1, 2)] << 16) ^ - ((word32)Td4[GETBYTE(s0, 1)] << 8) ^ - ((word32)Td4[GETBYTE(s3, 0)]); + ((word32)GetTable8(Td4, GETBYTE(s2, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(s1, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(s0, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(s3, 0))); t3 = - ((word32)Td4[GETBYTE(s3, 3)] << 24) ^ - ((word32)Td4[GETBYTE(s2, 2)] << 16) ^ - ((word32)Td4[GETBYTE(s1, 1)] << 8) ^ - ((word32)Td4[GETBYTE(s0, 0)]); + ((word32)GetTable8(Td4, GETBYTE(s3, 3)) << 24) ^ + ((word32)GetTable8(Td4, GETBYTE(s2, 2)) << 16) ^ + ((word32)GetTable8(Td4, GETBYTE(s1, 1)) << 8) ^ + ((word32)GetTable8(Td4, GETBYTE(s0, 0))); s0 = t0 ^ rk[0]; s1 = t1 ^ rk[1]; s2 = t2 ^ rk[2]; @@ -2996,15 +3125,15 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( temp = rk[3]; rk[4] = rk[0] ^ #ifndef WOLFSSL_AES_SMALL_TABLES - (Te[2][GETBYTE(temp, 2)] & 0xff000000) ^ - (Te[3][GETBYTE(temp, 1)] & 0x00ff0000) ^ - (Te[0][GETBYTE(temp, 0)] & 0x0000ff00) ^ - (Te[1][GETBYTE(temp, 3)] & 0x000000ff) ^ + (GetTable(Te[2], GETBYTE(temp, 2)) & 0xff000000) ^ + (GetTable(Te[3], GETBYTE(temp, 1)) & 0x00ff0000) ^ + (GetTable(Te[0], GETBYTE(temp, 0)) & 0x0000ff00) ^ + (GetTable(Te[1], GETBYTE(temp, 3)) & 0x000000ff) ^ #else - ((word32)Tsbox[GETBYTE(temp, 2)] << 24) ^ - ((word32)Tsbox[GETBYTE(temp, 1)] << 16) ^ - ((word32)Tsbox[GETBYTE(temp, 0)] << 8) ^ - ((word32)Tsbox[GETBYTE(temp, 3)]) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 2)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 1)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 0)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 3))) ^ #endif rcon[i]; rk[5] = rk[1] ^ rk[4]; @@ -3030,15 +3159,15 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( temp = rk[ 5]; rk[ 6] = rk[ 0] ^ #ifndef WOLFSSL_AES_SMALL_TABLES - (Te[2][GETBYTE(temp, 2)] & 0xff000000) ^ - (Te[3][GETBYTE(temp, 1)] & 0x00ff0000) ^ - (Te[0][GETBYTE(temp, 0)] & 0x0000ff00) ^ - (Te[1][GETBYTE(temp, 3)] & 0x000000ff) ^ + (GetTable(Te[2], GETBYTE(temp, 2)) & 0xff000000) ^ + (GetTable(Te[3], GETBYTE(temp, 1)) & 0x00ff0000) ^ + (GetTable(Te[0], GETBYTE(temp, 0)) & 0x0000ff00) ^ + (GetTable(Te[1], GETBYTE(temp, 3)) & 0x000000ff) ^ #else - ((word32)Tsbox[GETBYTE(temp, 2)] << 24) ^ - ((word32)Tsbox[GETBYTE(temp, 1)] << 16) ^ - ((word32)Tsbox[GETBYTE(temp, 0)] << 8) ^ - ((word32)Tsbox[GETBYTE(temp, 3)]) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 2)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 1)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 0)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 3))) ^ #endif rcon[i]; rk[ 7] = rk[ 1] ^ rk[ 6]; @@ -3065,15 +3194,15 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( temp = rk[ 7]; rk[ 8] = rk[ 0] ^ #ifndef WOLFSSL_AES_SMALL_TABLES - (Te[2][GETBYTE(temp, 2)] & 0xff000000) ^ - (Te[3][GETBYTE(temp, 1)] & 0x00ff0000) ^ - (Te[0][GETBYTE(temp, 0)] & 0x0000ff00) ^ - (Te[1][GETBYTE(temp, 3)] & 0x000000ff) ^ + (GetTable(Te[2], GETBYTE(temp, 2)) & 0xff000000) ^ + (GetTable(Te[3], GETBYTE(temp, 1)) & 0x00ff0000) ^ + (GetTable(Te[0], GETBYTE(temp, 0)) & 0x0000ff00) ^ + (GetTable(Te[1], GETBYTE(temp, 3)) & 0x000000ff) ^ #else - ((word32)Tsbox[GETBYTE(temp, 2)] << 24) ^ - ((word32)Tsbox[GETBYTE(temp, 1)] << 16) ^ - ((word32)Tsbox[GETBYTE(temp, 0)] << 8) ^ - ((word32)Tsbox[GETBYTE(temp, 3)]) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 2)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 1)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 0)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 3))) ^ #endif rcon[i]; rk[ 9] = rk[ 1] ^ rk[ 8]; @@ -3084,15 +3213,15 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( temp = rk[11]; rk[12] = rk[ 4] ^ #ifndef WOLFSSL_AES_SMALL_TABLES - (Te[2][GETBYTE(temp, 3)] & 0xff000000) ^ - (Te[3][GETBYTE(temp, 2)] & 0x00ff0000) ^ - (Te[0][GETBYTE(temp, 1)] & 0x0000ff00) ^ - (Te[1][GETBYTE(temp, 0)] & 0x000000ff); + (GetTable(Te[2], GETBYTE(temp, 3)) & 0xff000000) ^ + (GetTable(Te[3], GETBYTE(temp, 2)) & 0x00ff0000) ^ + (GetTable(Te[0], GETBYTE(temp, 1)) & 0x0000ff00) ^ + (GetTable(Te[1], GETBYTE(temp, 0)) & 0x000000ff); #else - ((word32)Tsbox[GETBYTE(temp, 3)] << 24) ^ - ((word32)Tsbox[GETBYTE(temp, 2)] << 16) ^ - ((word32)Tsbox[GETBYTE(temp, 1)] << 8) ^ - ((word32)Tsbox[GETBYTE(temp, 0)]); + ((word32)GetTable8(Tsbox, GETBYTE(temp, 3)) << 24) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 2)) << 16) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 1)) << 8) ^ + ((word32)GetTable8(Tsbox, GETBYTE(temp, 0))); #endif rk[13] = rk[ 5] ^ rk[12]; rk[14] = rk[ 6] ^ rk[13]; @@ -3127,25 +3256,25 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( for (i = 1; i < aes->rounds; i++) { rk += 4; rk[0] = - Td[0][Te[1][GETBYTE(rk[0], 3)] & 0xff] ^ - Td[1][Te[1][GETBYTE(rk[0], 2)] & 0xff] ^ - Td[2][Te[1][GETBYTE(rk[0], 1)] & 0xff] ^ - Td[3][Te[1][GETBYTE(rk[0], 0)] & 0xff]; + GetTable(Td[0], GetTable(Te[1], GETBYTE(rk[0], 3)) & 0xff) ^ + GetTable(Td[1], GetTable(Te[1], GETBYTE(rk[0], 2)) & 0xff) ^ + GetTable(Td[2], GetTable(Te[1], GETBYTE(rk[0], 1)) & 0xff) ^ + GetTable(Td[3], GetTable(Te[1], GETBYTE(rk[0], 0)) & 0xff); rk[1] = - Td[0][Te[1][GETBYTE(rk[1], 3)] & 0xff] ^ - Td[1][Te[1][GETBYTE(rk[1], 2)] & 0xff] ^ - Td[2][Te[1][GETBYTE(rk[1], 1)] & 0xff] ^ - Td[3][Te[1][GETBYTE(rk[1], 0)] & 0xff]; + GetTable(Td[0], GetTable(Te[1], GETBYTE(rk[1], 3)) & 0xff) ^ + GetTable(Td[1], GetTable(Te[1], GETBYTE(rk[1], 2)) & 0xff) ^ + GetTable(Td[2], GetTable(Te[1], GETBYTE(rk[1], 1)) & 0xff) ^ + GetTable(Td[3], GetTable(Te[1], GETBYTE(rk[1], 0)) & 0xff); rk[2] = - Td[0][Te[1][GETBYTE(rk[2], 3)] & 0xff] ^ - Td[1][Te[1][GETBYTE(rk[2], 2)] & 0xff] ^ - Td[2][Te[1][GETBYTE(rk[2], 1)] & 0xff] ^ - Td[3][Te[1][GETBYTE(rk[2], 0)] & 0xff]; + GetTable(Td[0], GetTable(Te[1], GETBYTE(rk[2], 3)) & 0xff) ^ + GetTable(Td[1], GetTable(Te[1], GETBYTE(rk[2], 2)) & 0xff) ^ + GetTable(Td[2], GetTable(Te[1], GETBYTE(rk[2], 1)) & 0xff) ^ + GetTable(Td[3], GetTable(Te[1], GETBYTE(rk[2], 0)) & 0xff); rk[3] = - Td[0][Te[1][GETBYTE(rk[3], 3)] & 0xff] ^ - Td[1][Te[1][GETBYTE(rk[3], 2)] & 0xff] ^ - Td[2][Te[1][GETBYTE(rk[3], 1)] & 0xff] ^ - Td[3][Te[1][GETBYTE(rk[3], 0)] & 0xff]; + GetTable(Td[0], GetTable(Te[1], GETBYTE(rk[3], 3)) & 0xff) ^ + GetTable(Td[1], GetTable(Te[1], GETBYTE(rk[3], 2)) & 0xff) ^ + GetTable(Td[2], GetTable(Te[1], GETBYTE(rk[3], 1)) & 0xff) ^ + GetTable(Td[3], GetTable(Te[1], GETBYTE(rk[3], 0)) & 0xff); } #endif } From 0246322e3a7afdaca1d37b46a681acf776909cd3 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 4 May 2023 16:29:33 +1000 Subject: [PATCH 260/391] AES touch cache lines Change implementation to get from each line of a table once for each 4 variables. Only enable WOLFSSL_AES_TOUCH_LINES, by default, when RISC-V. --- wolfcrypt/src/aes.c | 329 +++++++++++++++++++++++++++----------------- 1 file changed, 204 insertions(+), 125 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 0996539b29b..a6e1be83046 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -1725,9 +1725,12 @@ static WARN_UNUSED_RESULT word32 inv_col_mul( #endif #endif -#define WOLFSSL_AES_TOUCH_LINES - #ifndef WC_NO_CACHE_RESISTANT + +#if defined(__riscv) && !defined(WOLFSSL_AES_TOUCH_LINES) + #define WOLFSSL_AES_TOUCH_LINES +#endif + #ifndef WOLFSSL_AES_SMALL_TABLES /* load 4 Te Tables into cache by cache line stride */ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchTe(void) @@ -1791,6 +1794,7 @@ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchSBox(void) #error Cache line size not supported #endif +#ifndef WOLFSSL_AES_SMALL_TABLES static word32 GetTable(const word32* t, byte o) { #if WC_CACHE_LINE_SZ == 64 @@ -1830,6 +1834,9 @@ static word32 GetTable(const word32* t, byte o) return e; #endif } +#endif + +#ifdef WOLFSSL_AES_SMALL_TABLES static byte GetTable8(const byte* t, byte o) { #if WC_CACHE_LINE_SZ == 64 @@ -1869,9 +1876,114 @@ static byte GetTable8(const byte* t, byte o) return e; #endif } +#endif + +#ifndef WOLFSSL_AES_SMALL_TABLES +static void GetTable_Multi(const word32* t, word32* t0, byte o0, + word32* t1, byte o1, word32* t2, byte o2, word32* t3, byte o3) +{ + word32 e0 = 0; + word32 e1 = 0; + word32 e2 = 0; + word32 e3 = 0; + byte hi0 = o0 & WC_CACHE_LINE_MASK_HI; + byte lo0 = o0 & WC_CACHE_LINE_MASK_LO; + byte hi1 = o1 & WC_CACHE_LINE_MASK_HI; + byte lo1 = o1 & WC_CACHE_LINE_MASK_LO; + byte hi2 = o2 & WC_CACHE_LINE_MASK_HI; + byte lo2 = o2 & WC_CACHE_LINE_MASK_LO; + byte hi3 = o3 & WC_CACHE_LINE_MASK_HI; + byte lo3 = o3 & WC_CACHE_LINE_MASK_LO; + int i; + + for (i = 0; i < 256; i += (1 << WC_CACHE_LINE_BITS)) { + e0 |= t[lo0 + i] & ((word32)0 - (((word32)hi0 - 0x01) >> 31)); + hi0 -= WC_CACHE_LINE_ADD; + e1 |= t[lo1 + i] & ((word32)0 - (((word32)hi1 - 0x01) >> 31)); + hi1 -= WC_CACHE_LINE_ADD; + e2 |= t[lo2 + i] & ((word32)0 - (((word32)hi2 - 0x01) >> 31)); + hi2 -= WC_CACHE_LINE_ADD; + e3 |= t[lo3 + i] & ((word32)0 - (((word32)hi3 - 0x01) >> 31)); + hi3 -= WC_CACHE_LINE_ADD; + } + *t0 = e0; + *t1 = e1; + *t2 = e2; + *t3 = e3; +} +static void XorTable_Multi(const word32* t, word32* t0, byte o0, + word32* t1, byte o1, word32* t2, byte o2, word32* t3, byte o3) +{ + word32 e0 = 0; + word32 e1 = 0; + word32 e2 = 0; + word32 e3 = 0; + byte hi0 = o0 & 0xf0; + byte lo0 = o0 & 0x0f; + byte hi1 = o1 & 0xf0; + byte lo1 = o1 & 0x0f; + byte hi2 = o2 & 0xf0; + byte lo2 = o2 & 0x0f; + byte hi3 = o3 & 0xf0; + byte lo3 = o3 & 0x0f; + int i; + + for (i = 0; i < 256; i += (1 << WC_CACHE_LINE_BITS)) { + e0 |= t[lo0 + i] & ((word32)0 - (((word32)hi0 - 0x01) >> 31)); + hi0 -= WC_CACHE_LINE_ADD; + e1 |= t[lo1 + i] & ((word32)0 - (((word32)hi1 - 0x01) >> 31)); + hi1 -= WC_CACHE_LINE_ADD; + e2 |= t[lo2 + i] & ((word32)0 - (((word32)hi2 - 0x01) >> 31)); + hi2 -= WC_CACHE_LINE_ADD; + e3 |= t[lo3 + i] & ((word32)0 - (((word32)hi3 - 0x01) >> 31)); + hi3 -= WC_CACHE_LINE_ADD; + } + *t0 ^= e0; + *t1 ^= e1; + *t2 ^= e2; + *t3 ^= e3; +} +static word32 GetTable8_4(const byte* t, byte o0, byte o1, byte o2, byte o3) +{ + word32 e = 0; + int i; + byte hi0 = o0 & WC_CACHE_LINE_MASK_HI; + byte lo0 = o0 & WC_CACHE_LINE_MASK_LO; + byte hi1 = o1 & WC_CACHE_LINE_MASK_HI; + byte lo1 = o1 & WC_CACHE_LINE_MASK_LO; + byte hi2 = o2 & WC_CACHE_LINE_MASK_HI; + byte lo2 = o2 & WC_CACHE_LINE_MASK_LO; + byte hi3 = o3 & WC_CACHE_LINE_MASK_HI; + byte lo3 = o3 & WC_CACHE_LINE_MASK_LO; + + for (i = 0; i < 256; i += (1 << WC_CACHE_LINE_BITS)) { + e |= (word32)(t[lo0 + i] & ((word32)0 - (((word32)hi0 - 0x01) >> 31))) + << 24; + hi0 -= WC_CACHE_LINE_ADD; + e |= (word32)(t[lo1 + i] & ((word32)0 - (((word32)hi1 - 0x01) >> 31))) + << 16; + hi1 -= WC_CACHE_LINE_ADD; + e |= (word32)(t[lo2 + i] & ((word32)0 - (((word32)hi2 - 0x01) >> 31))) + << 8; + hi2 -= WC_CACHE_LINE_ADD; + e |= (word32)(t[lo3 + i] & ((word32)0 - (((word32)hi3 - 0x01) >> 31))) + << 0; + hi3 -= WC_CACHE_LINE_ADD; + } + + return e; +} +#endif #else #define GetTable(t, o) t[o] #define GetTable8(t, o) t[o] +#define GetTable_Multi(t, t0, o0, t1, o1, t2, o2, t3, o3) \ + *t0 = t[o0]; *t1 = t[o1]; *t2 = t[o2]; *t3 = t[o3] +#define XorTable_Multi(t, t0, o0, t1, o1, t2, o2, t3, o3) \ + *t0 ^= t[o0]; *t1 ^= t[o1]; *t2 ^= t[o2]; *t3 ^= t[o3] +#define GetTable8_4(t, o0, o1, o2, o3) \ + (((word32)t[o0] << 24) | ((word32)t[o1] << 16) | \ + ((word32)t[o2] << 8) | ((word32)t[o3] << 0)) #endif /* Software AES - ECB Encrypt */ @@ -1980,8 +2092,7 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( s0 |= PreFetchTe(); #endif -#ifndef WOLFSSL_AES_NO_UNROLL -/* Unroll the loop. */ +#ifndef WOLFSSL_AES_TOUCH_LINES #define ENC_ROUND_T_S(o) \ t0 = GetTable(Te[0], GETBYTE(s0, 3)) ^ GetTable(Te[1], GETBYTE(s1, 2)) ^ \ GetTable(Te[2], GETBYTE(s2, 1)) ^ GetTable(Te[3], GETBYTE(s3, 0)) ^ \ @@ -2008,7 +2119,32 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( s3 = GetTable(Te[0], GETBYTE(t3, 3)) ^ GetTable(Te[1], GETBYTE(t0, 2)) ^ \ GetTable(Te[2], GETBYTE(t1, 1)) ^ GetTable(Te[3], GETBYTE(t2, 0)) ^ \ rk[(o)+3] +#else +#define ENC_ROUND_T_S(o) \ + GetTable_Multi(Te[0], &t0, GETBYTE(s0, 3), &t1, GETBYTE(s1, 3), \ + &t2, GETBYTE(s2, 3), &t3, GETBYTE(s3, 3)); \ + XorTable_Multi(Te[1], &t0, GETBYTE(s1, 2), &t1, GETBYTE(s2, 2), \ + &t2, GETBYTE(s3, 2), &t3, GETBYTE(s0, 2)); \ + XorTable_Multi(Te[2], &t0, GETBYTE(s2, 1), &t1, GETBYTE(s3, 1), \ + &t2, GETBYTE(s0, 1), &t3, GETBYTE(s1, 1)); \ + XorTable_Multi(Te[3], &t0, GETBYTE(s3, 0), &t1, GETBYTE(s0, 0), \ + &t2, GETBYTE(s1, 0), &t3, GETBYTE(s2, 0)); \ + t0 ^= rk[(o)+4]; t1 ^= rk[(o)+5]; t2 ^= rk[(o)+6]; t3 ^= rk[(o)+7]; + +#define ENC_ROUND_S_T(o) \ + GetTable_Multi(Te[0], &s0, GETBYTE(t0, 3), &s1, GETBYTE(t1, 3), \ + &s2, GETBYTE(t2, 3), &s3, GETBYTE(t3, 3)); \ + XorTable_Multi(Te[1], &s0, GETBYTE(t1, 2), &s1, GETBYTE(t2, 2), \ + &s2, GETBYTE(t3, 2), &s3, GETBYTE(t0, 2)); \ + XorTable_Multi(Te[2], &s0, GETBYTE(t2, 1), &s1, GETBYTE(t3, 1), \ + &s2, GETBYTE(t0, 1), &s3, GETBYTE(t1, 1)); \ + XorTable_Multi(Te[3], &s0, GETBYTE(t3, 0), &s1, GETBYTE(t0, 0), \ + &s2, GETBYTE(t1, 0), &s3, GETBYTE(t2, 0)); \ + s0 ^= rk[(o)+0]; s1 ^= rk[(o)+1]; s2 ^= rk[(o)+2]; s3 ^= rk[(o)+3]; +#endif +#ifndef WOLFSSL_AES_NO_UNROLL +/* Unroll the loop. */ ENC_ROUND_T_S( 0); ENC_ROUND_S_T( 8); ENC_ROUND_T_S( 8); ENC_ROUND_S_T(16); ENC_ROUND_T_S(16); @@ -2027,60 +2163,14 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( */ for (;;) { - t0 = - GetTable(Te[0], GETBYTE(s0, 3)) ^ - GetTable(Te[1], GETBYTE(s1, 2)) ^ - GetTable(Te[2], GETBYTE(s2, 1)) ^ - GetTable(Te[3], GETBYTE(s3, 0)) ^ - rk[4]; - t1 = - GetTable(Te[0], GETBYTE(s1, 3)) ^ - GetTable(Te[1], GETBYTE(s2, 2)) ^ - GetTable(Te[2], GETBYTE(s3, 1)) ^ - GetTable(Te[3], GETBYTE(s0, 0)) ^ - rk[5]; - t2 = - GetTable(Te[0], GETBYTE(s2, 3)) ^ - GetTable(Te[1], GETBYTE(s3, 2)) ^ - GetTable(Te[2], GETBYTE(s0, 1)) ^ - GetTable(Te[3], GETBYTE(s1, 0)) ^ - rk[6]; - t3 = - GetTable(Te[0], GETBYTE(s3, 3)) ^ - GetTable(Te[1], GETBYTE(s0, 2)) ^ - GetTable(Te[2], GETBYTE(s1, 1)) ^ - GetTable(Te[3], GETBYTE(s2, 0)) ^ - rk[7]; + ENC_ROUND_T_S(0); rk += 8; if (--r == 0) { break; } - s0 = - GetTable(Te[0], GETBYTE(t0, 3)) ^ - GetTable(Te[1], GETBYTE(t1, 2)) ^ - GetTable(Te[2], GETBYTE(t2, 1)) ^ - GetTable(Te[3], GETBYTE(t3, 0)) ^ - rk[0]; - s1 = - GetTable(Te[0], GETBYTE(t1, 3)) ^ - GetTable(Te[1], GETBYTE(t2, 2)) ^ - GetTable(Te[2], GETBYTE(t3, 1)) ^ - GetTable(Te[3], GETBYTE(t0, 0)) ^ - rk[1]; - s2 = - GetTable(Te[0], GETBYTE(t2, 3)) ^ - GetTable(Te[1], GETBYTE(t3, 2)) ^ - GetTable(Te[2], GETBYTE(t0, 1)) ^ - GetTable(Te[3], GETBYTE(t1, 0)) ^ - rk[2]; - s3 = - GetTable(Te[0], GETBYTE(t3, 3)) ^ - GetTable(Te[1], GETBYTE(t0, 2)) ^ - GetTable(Te[2], GETBYTE(t1, 1)) ^ - GetTable(Te[3], GETBYTE(t2, 0)) ^ - rk[3]; + ENC_ROUND_S_T(0); } #endif @@ -2089,6 +2179,7 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( * map cipher state to byte array block: */ +#ifndef WOLFSSL_AES_TOUCH_LINES s0 = (GetTable(Te[2], GETBYTE(t0, 3)) & 0xff000000) ^ (GetTable(Te[3], GETBYTE(t1, 2)) & 0x00ff0000) ^ @@ -2114,6 +2205,32 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( (GetTable(Te[1], GETBYTE(t2, 0)) & 0x000000ff) ^ rk[3]; #else +{ + word32 u0; + word32 u1; + word32 u2; + word32 u3; + + s0 = rk[0]; s1 = rk[1]; s2 = rk[2]; s3 = rk[3]; + GetTable_Multi(Te[2], &u0, GETBYTE(t0, 3), &u1, GETBYTE(t1, 3), + &u2, GETBYTE(t2, 3), &u3, GETBYTE(t3, 3)); + s0 ^= u0 & 0xff000000; s1 ^= u1 & 0xff000000; + s2 ^= u2 & 0xff000000; s3 ^= u3 & 0xff000000; + GetTable_Multi(Te[3], &u0, GETBYTE(t1, 2), &u1, GETBYTE(t2, 2), + &u2, GETBYTE(t3, 2), &u3, GETBYTE(t0, 2)); + s0 ^= u0 & 0x00ff0000; s1 ^= u1 & 0x00ff0000; + s2 ^= u2 & 0x00ff0000; s3 ^= u3 & 0x00ff0000; + GetTable_Multi(Te[0], &u0, GETBYTE(t2, 1), &u1, GETBYTE(t3, 1), + &u2, GETBYTE(t0, 1), &u3, GETBYTE(t1, 1)); + s0 ^= u0 & 0x0000ff00; s1 ^= u1 & 0x0000ff00; + s2 ^= u2 & 0x0000ff00; s3 ^= u3 & 0x0000ff00; + GetTable_Multi(Te[1], &u0, GETBYTE(t3, 0), &u1, GETBYTE(t0, 0), + &u2, GETBYTE(t1, 0), &u3, GETBYTE(t2, 0)); + s0 ^= u0 & 0x000000ff; s1 ^= u1 & 0x000000ff; + s2 ^= u2 & 0x000000ff; s3 ^= u3 & 0x000000ff; +} +#endif +#else #ifndef WC_NO_CACHE_RESISTANT s0 |= PreFetchSBox(); #endif @@ -2330,7 +2447,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( s0 |= PreFetchTd(); #endif -#ifndef WOLFSSL_AES_NO_UNROLL +#ifndef WOLFSSL_AES_TOUCH_LINES /* Unroll the loop. */ #define DEC_ROUND_T_S(o) \ t0 = GetTable(Td[0], GETBYTE(s0, 3)) ^ GetTable(Td[1], GETBYTE(s3, 2)) ^ \ @@ -2350,7 +2467,31 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( GetTable(Td[2], GETBYTE(t0, 1)) ^ GetTable(Td[3], GETBYTE(t3, 0)) ^ rk[(o)+2]; \ s3 = GetTable(Td[0], GETBYTE(t3, 3)) ^ GetTable(Td[1], GETBYTE(t2, 2)) ^ \ GetTable(Td[2], GETBYTE(t1, 1)) ^ GetTable(Td[3], GETBYTE(t0, 0)) ^ rk[(o)+3] +#else +#define DEC_ROUND_T_S(o) \ + GetTable_Multi(Td[0], &t0, GETBYTE(s0, 3), &t1, GETBYTE(s1, 3), \ + &t2, GETBYTE(s2, 3), &t3, GETBYTE(s3, 3)); \ + XorTable_Multi(Td[1], &t0, GETBYTE(s3, 2), &t1, GETBYTE(s0, 2), \ + &t2, GETBYTE(s1, 2), &t3, GETBYTE(s2, 2)); \ + XorTable_Multi(Td[2], &t0, GETBYTE(s2, 1), &t1, GETBYTE(s3, 1), \ + &t2, GETBYTE(s0, 1), &t3, GETBYTE(s1, 1)); \ + XorTable_Multi(Td[3], &t0, GETBYTE(s1, 0), &t1, GETBYTE(s2, 0), \ + &t2, GETBYTE(s3, 0), &t3, GETBYTE(s0, 0)); \ + t0 ^= rk[(o)+4]; t1 ^= rk[(o)+5]; t2 ^= rk[(o)+6]; t3 ^= rk[(o)+7]; + +#define DEC_ROUND_S_T(o) \ + GetTable_Multi(Td[0], &s0, GETBYTE(t0, 3), &s1, GETBYTE(t1, 3), \ + &s2, GETBYTE(t2, 3), &s3, GETBYTE(t3, 3)); \ + XorTable_Multi(Td[1], &s0, GETBYTE(t3, 2), &s1, GETBYTE(t0, 2), \ + &s2, GETBYTE(t1, 2), &s3, GETBYTE(t2, 2)); \ + XorTable_Multi(Td[2], &s0, GETBYTE(t2, 1), &s1, GETBYTE(t3, 1), \ + &s2, GETBYTE(t0, 1), &s3, GETBYTE(t1, 1)); \ + XorTable_Multi(Td[3], &s0, GETBYTE(t1, 0), &s1, GETBYTE(t2, 0), \ + &s2, GETBYTE(t3, 0), &s3, GETBYTE(t0, 0)); \ + s0 ^= rk[(o)+0]; s1 ^= rk[(o)+1]; s2 ^= rk[(o)+2]; s3 ^= rk[(o)+3]; +#endif +#ifndef WOLFSSL_AES_NO_UNROLL DEC_ROUND_T_S( 0); DEC_ROUND_S_T( 8); DEC_ROUND_T_S( 8); DEC_ROUND_S_T(16); DEC_ROUND_T_S(16); @@ -2370,60 +2511,14 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( */ for (;;) { - t0 = - GetTable(Td[0], GETBYTE(s0, 3)) ^ - GetTable(Td[1], GETBYTE(s3, 2)) ^ - GetTable(Td[2], GETBYTE(s2, 1)) ^ - GetTable(Td[3], GETBYTE(s1, 0)) ^ - rk[4]; - t1 = - GetTable(Td[0], GETBYTE(s1, 3)) ^ - GetTable(Td[1], GETBYTE(s0, 2)) ^ - GetTable(Td[2], GETBYTE(s3, 1)) ^ - GetTable(Td[3], GETBYTE(s2, 0)) ^ - rk[5]; - t2 = - GetTable(Td[0], GETBYTE(s2, 3)) ^ - GetTable(Td[1], GETBYTE(s1, 2)) ^ - GetTable(Td[2], GETBYTE(s0, 1)) ^ - GetTable(Td[3], GETBYTE(s3, 0)) ^ - rk[6]; - t3 = - GetTable(Td[0], GETBYTE(s3, 3)) ^ - GetTable(Td[1], GETBYTE(s2, 2)) ^ - GetTable(Td[2], GETBYTE(s1, 1)) ^ - GetTable(Td[3], GETBYTE(s0, 0)) ^ - rk[7]; + DEC_ROUND_T_S(0); rk += 8; if (--r == 0) { break; } - s0 = - GetTable(Td[0], GETBYTE(t0, 3)) ^ - GetTable(Td[1], GETBYTE(t3, 2)) ^ - GetTable(Td[2], GETBYTE(t2, 1)) ^ - GetTable(Td[3], GETBYTE(t1, 0)) ^ - rk[0]; - s1 = - GetTable(Td[0], GETBYTE(t1, 3)) ^ - GetTable(Td[1], GETBYTE(t0, 2)) ^ - GetTable(Td[2], GETBYTE(t3, 1)) ^ - GetTable(Td[3], GETBYTE(t2, 0)) ^ - rk[1]; - s2 = - GetTable(Td[0], GETBYTE(t2, 3)) ^ - GetTable(Td[1], GETBYTE(t1, 2)) ^ - GetTable(Td[2], GETBYTE(t0, 1)) ^ - GetTable(Td[3], GETBYTE(t3, 0)) ^ - rk[2]; - s3 = - GetTable(Td[0], GETBYTE(t3, 3)) ^ - GetTable(Td[1], GETBYTE(t2, 2)) ^ - GetTable(Td[2], GETBYTE(t1, 1)) ^ - GetTable(Td[3], GETBYTE(t0, 0)) ^ - rk[3]; + DEC_ROUND_S_T(0); } #endif /* @@ -2435,30 +2530,14 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( t0 |= PreFetchTd4(); #endif - s0 = - ((word32)GetTable8(Td4, GETBYTE(t0, 3)) << 24) ^ - ((word32)GetTable8(Td4, GETBYTE(t3, 2)) << 16) ^ - ((word32)GetTable8(Td4, GETBYTE(t2, 1)) << 8) ^ - ((word32)GetTable8(Td4, GETBYTE(t1, 0))) ^ - rk[0]; - s1 = - ((word32)GetTable8(Td4, GETBYTE(t1, 3)) << 24) ^ - ((word32)GetTable8(Td4, GETBYTE(t0, 2)) << 16) ^ - ((word32)GetTable8(Td4, GETBYTE(t3, 1)) << 8) ^ - ((word32)GetTable8(Td4, GETBYTE(t2, 0))) ^ - rk[1]; - s2 = - ((word32)GetTable8(Td4, GETBYTE(t2, 3)) << 24) ^ - ((word32)GetTable8(Td4, GETBYTE(t1, 2)) << 16) ^ - ((word32)GetTable8(Td4, GETBYTE(t0, 1)) << 8) ^ - ((word32)GetTable8(Td4, GETBYTE(t3, 0))) ^ - rk[2]; - s3 = - ((word32)GetTable8(Td4, GETBYTE(t3, 3)) << 24) ^ - ((word32)GetTable8(Td4, GETBYTE(t2, 2)) << 16) ^ - ((word32)GetTable8(Td4, GETBYTE(t1, 1)) << 8) ^ - ((word32)GetTable8(Td4, GETBYTE(t0, 0))) ^ - rk[3]; + s0 = GetTable8_4(Td4, GETBYTE(t0, 3), GETBYTE(t3, 2), + GETBYTE(t2, 1), GETBYTE(t1, 0)) ^ rk[0]; + s1 = GetTable8_4(Td4, GETBYTE(t1, 3), GETBYTE(t0, 2), + GETBYTE(t3, 1), GETBYTE(t2, 0)) ^ rk[1]; + s2 = GetTable8_4(Td4, GETBYTE(t2, 3), GETBYTE(t1, 2), + GETBYTE(t0, 1), GETBYTE(t3, 0)) ^ rk[2]; + s3 = GetTable8_4(Td4, GETBYTE(t3, 3), GETBYTE(t2, 2), + GETBYTE(t1, 1), GETBYTE(t0, 0)) ^ rk[3]; #else #ifndef WC_NO_CACHE_RESISTANT s0 |= PreFetchTd4(); From c4f9084e770643a226c6bf4f0f540f8991dd6d0e Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Tue, 9 May 2023 23:53:49 -0500 Subject: [PATCH 261/391] linuxkm: add coverage for Linux 6.4+ module memory layout refactor; also, refactor WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS to make it settable independent of WOLFSSL_AESNI etc. --- linuxkm/linuxkm_memory.c | 4 ++-- linuxkm/linuxkm_wc_port.h | 39 ++++++++++++++++++++++++++------------- linuxkm/module_hooks.c | 34 +++++++++++++++++++++------------- 3 files changed, 49 insertions(+), 28 deletions(-) diff --git a/linuxkm/linuxkm_memory.c b/linuxkm/linuxkm_memory.c index facee2af268..ee30af987be 100644 --- a/linuxkm/linuxkm_memory.c +++ b/linuxkm/linuxkm_memory.c @@ -21,7 +21,7 @@ /* included by wolfcrypt/src/memory.c */ -#if defined(WOLFSSL_LINUXKM_SIMD_X86) +#if defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) && defined(CONFIG_X86) #ifdef LINUXKM_SIMD_IRQ #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 16, 0) static union fpregs_state **wolfcrypt_linuxkm_fpu_states = NULL; @@ -335,7 +335,7 @@ return; } -#endif /* WOLFSSL_LINUXKM_SIMD_X86 && WOLFSSL_LINUXKM_SIMD_X86_IRQ_ALLOWED */ +#endif /* WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS && CONFIG_X86 */ #if defined(__PIE__) && (LINUX_VERSION_CODE >= KERNEL_VERSION(6, 1, 0)) /* needed in 6.1+ because show_free_areas() static definition in mm.h calls diff --git a/linuxkm/linuxkm_wc_port.h b/linuxkm/linuxkm_wc_port.h index 5a7fb526697..8b839161ca6 100644 --- a/linuxkm/linuxkm_wc_port.h +++ b/linuxkm/linuxkm_wc_port.h @@ -119,10 +119,30 @@ #endif #include #include + #if defined(WOLFSSL_AESNI) || defined(USE_INTEL_SPEEDUP) || defined(WOLFSSL_SP_X86_64_ASM) #ifndef CONFIG_X86 #error X86 SIMD extensions requested, but CONFIG_X86 is not set. #endif + #ifndef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS + #define WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS + #endif + #elif defined(WOLFSSL_ARMASM) || defined(WOLFSSL_SP_ARM32_ASM) || \ + defined(WOLFSSL_SP_ARM64_ASM) || defined(WOLFSSL_SP_ARM_THUMB_ASM) ||\ + defined(WOLFSSL_SP_ARM_CORTEX_M_ASM) + #if !defined(CONFIG_ARM) && !defined(CONFIG_ARM64) + #error ARM SIMD extensions requested, but CONFIG_ARM* is not set. + #endif + #ifndef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS + #define WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS + #endif + #else + #ifndef WOLFSSL_NO_ASM + #define WOLFSSL_NO_ASM + #endif + #endif + + #if defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) && defined(CONFIG_X86) #define WOLFSSL_LINUXKM_SIMD #define WOLFSSL_LINUXKM_SIMD_X86 #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0) @@ -148,28 +168,21 @@ #ifndef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() restore_vector_registers_x86() #endif - #elif defined(WOLFSSL_ARMASM) || defined(WOLFSSL_SP_ARM32_ASM) || \ - defined(WOLFSSL_SP_ARM64_ASM) || defined(WOLFSSL_SP_ARM_THUMB_ASM) ||\ - defined(WOLFSSL_SP_ARM_CORTEX_M_ASM) - #if !defined(CONFIG_ARM) && !defined(CONFIG_ARM64) - #error ARM SIMD extensions requested, but CONFIG_ARM* is not set. - #endif + #elif defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) && (defined(CONFIG_ARM) || defined(CONFIG_ARM64)) #define WOLFSSL_LINUXKM_SIMD #define WOLFSSL_LINUXKM_SIMD_ARM #include + #ifdef LINUXKM_SIMD_IRQ + #error LINUXKM_SIMD_IRQ is unavailable on ARM (not implemented) + #endif #ifndef SAVE_VECTOR_REGISTERS #define SAVE_VECTOR_REGISTERS(fail_clause) { int _svr_ret = save_vector_registers_arm(); if (_svr_ret != 0) { fail_clause } } #endif #ifndef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() restore_vector_registers_arm() #endif - #ifdef LINUXKM_SIMD_IRQ - #error LINUXKM_SIMD_IRQ is unavailable on ARM (not implemented) - #endif - #else - #ifndef WOLFSSL_NO_ASM - #define WOLFSSL_NO_ASM - #endif + #elif defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) + #error WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS is set for an unsupported architecture. #endif _Pragma("GCC diagnostic pop"); diff --git a/linuxkm/module_hooks.c b/linuxkm/module_hooks.c index 7833075272c..3f17217d3af 100644 --- a/linuxkm/module_hooks.c +++ b/linuxkm/module_hooks.c @@ -141,13 +141,21 @@ static int wolfssl_init(void) #ifdef HAVE_LINUXKM_PIE_SUPPORT -#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 5, 0) - #define THIS_MODULE_BASE (THIS_MODULE->core_layout.base) +#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0) + /* see linux commit ac3b432839 */ + #define THIS_MODULE_TEXT_BASE (THIS_MODULE->mem[MOD_TEXT].base) + #define THIS_MODULE_TEXT_SIZE (THIS_MODULE->mem[MOD_TEXT].size) + #define THIS_MODULE_RO_BASE (THIS_MODULE->mem[MOD_RODATA].base) + #define THIS_MODULE_RO_SIZE (THIS_MODULE->mem[MOD_RODATA].size) +#elif LINUX_VERSION_CODE >= KERNEL_VERSION(4, 5, 0) + #define THIS_MODULE_TEXT_BASE (THIS_MODULE->core_layout.base) #define THIS_MODULE_TEXT_SIZE (THIS_MODULE->core_layout.text_size) + #define THIS_MODULE_RO_BASE ((char *)THIS_MODULE->core_layout.base + THIS_MODULE->core_layout.text_size) #define THIS_MODULE_RO_SIZE (THIS_MODULE->core_layout.ro_size) #else - #define THIS_MODULE_BASE (THIS_MODULE->module_core) + #define THIS_MODULE_TEXT_BASE (THIS_MODULE->module_core) #define THIS_MODULE_TEXT_SIZE (THIS_MODULE->core_text_size) + #define THIS_MODULE_RO_BASE ((char *)THIS_MODULE->module_core + THIS_MODULE->core_ro_size) #define THIS_MODULE_RO_SIZE (THIS_MODULE->core_ro_size) #endif @@ -159,8 +167,8 @@ static int wolfssl_init(void) unsigned int text_hash, rodata_hash; if ((pie_text_start < pie_text_end) && - (pie_text_start >= (char *)THIS_MODULE_BASE) && - (pie_text_end - (char *)THIS_MODULE_BASE <= THIS_MODULE_TEXT_SIZE)) + (pie_text_start >= (char *)THIS_MODULE_TEXT_BASE) && + (pie_text_end - (char *)THIS_MODULE_TEXT_BASE <= THIS_MODULE_TEXT_SIZE)) { text_hash = hash_span(pie_text_start, pie_text_end); } else { @@ -169,14 +177,14 @@ static int wolfssl_init(void) pie_text_start, pie_text_end, pie_text_end-pie_text_start, - THIS_MODULE_BASE, - (char *)THIS_MODULE_BASE + THIS_MODULE_TEXT_SIZE); + THIS_MODULE_TEXT_BASE, + (char *)THIS_MODULE_TEXT_BASE + THIS_MODULE_TEXT_SIZE); text_hash = 0; } if ((pie_rodata_start < pie_rodata_end) && // cppcheck-suppress comparePointers - (pie_rodata_start >= (char *)THIS_MODULE_BASE + THIS_MODULE_TEXT_SIZE) && - (pie_rodata_end - (char *)THIS_MODULE_BASE <= THIS_MODULE_RO_SIZE)) + (pie_rodata_start >= (char *)THIS_MODULE_RO_BASE) && + (pie_rodata_end - (char *)THIS_MODULE_RO_BASE <= THIS_MODULE_RO_SIZE)) { rodata_hash = hash_span(pie_rodata_start, pie_rodata_end); } else { @@ -185,8 +193,8 @@ static int wolfssl_init(void) pie_rodata_start, pie_rodata_end, pie_rodata_end-pie_rodata_start, - (char *)THIS_MODULE_BASE + THIS_MODULE_TEXT_SIZE, - (char *)THIS_MODULE_BASE + THIS_MODULE_RO_SIZE); + (char *)THIS_MODULE_RO_BASE, + (char *)THIS_MODULE_RO_BASE + THIS_MODULE_RO_SIZE); rodata_hash = 0; } @@ -194,10 +202,10 @@ static int wolfssl_init(void) * the true module start address, which is potentially useful to an * attacker. */ - pr_info("wolfCrypt container hashes (spans): %x (%lu) %x (%lu), module base %pK\n", + pr_info("wolfCrypt container hashes (spans): %x (%lu) %x (%lu), text base %pK, ro base %pK\n", text_hash, pie_text_end-pie_text_start, rodata_hash, pie_rodata_end-pie_rodata_start, - THIS_MODULE_BASE); + THIS_MODULE_TEXT_BASE, THIS_MODULE_RO_BASE); } #endif /* HAVE_LINUXKM_PIE_SUPPORT */ From 80a841421c02cb447554bdfc4b34cc8786cd9726 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Tue, 9 May 2023 23:55:08 -0500 Subject: [PATCH 262/391] fixes for various wolfcrypt -Wconversions visible only on compilers that promote byte and word16 to signed int, then warn of a sign conflict when an intrinsically safe result is assigned back to the original type. --- wolfcrypt/src/asn.c | 27 +++++++++++++-------------- wolfcrypt/src/coding.c | 10 +++++----- wolfcrypt/src/ecc.c | 6 +++--- wolfcrypt/src/hmac.c | 2 +- wolfcrypt/src/misc.c | 14 +++++++------- wolfcrypt/src/sp_int.c | 4 ++-- 6 files changed, 31 insertions(+), 32 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 3bf56f08e14..790b57bbda8 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -2159,7 +2159,7 @@ int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx, /* Bottom 7 bits are the number of bytes to calculate length with. * Note: 0 indicates indefinite length encoding *not* 0 bytes of length. */ - word32 bytes = b & 0x7F; + word32 bytes = (word32)b & 0x7FU; int minLen; /* Calculate minimum length to be encoded with bytes. */ @@ -2935,7 +2935,7 @@ static int SetASNIntMP(mp_int* n, int maxSz, byte* output) length = mp_unsigned_bin_size(n); if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz) return BUFFER_E; - idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output); + idx = SetASNInt(length, (byte)(leadingBit ? 0x80U : 0x00U), output); if (maxSz >= 0 && (idx + length) > maxSz) return BUFFER_E; @@ -14468,7 +14468,7 @@ word32 SetLength(word32 length, byte* output) if (output) { /* Encode count byte. */ - output[i] = j | ASN_LONG_LENGTH; + output[i] = (byte)(j | ASN_LONG_LENGTH); } /* Skip over count byte. */ i++; @@ -14550,8 +14550,8 @@ word32 SetSet(word32 len, byte* output) */ word32 SetImplicit(byte tag, byte number, word32 len, byte* output) { - tag = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0) - | ASN_CONTEXT_SPECIFIC | number; + tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0) + | ASN_CONTEXT_SPECIFIC | number); return SetHeader(tag, len, output); } @@ -14566,8 +14566,8 @@ word32 SetImplicit(byte tag, byte number, word32 len, byte* output) */ word32 SetExplicit(byte number, word32 len, byte* output) { - return SetHeader(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number, len, - output); + return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number), + len, output); } #if defined(OPENSSL_EXTRA) @@ -14754,8 +14754,7 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) tagSz = (type == oidHashType || (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) || - (type == oidKeyType && algoOID == RSAk)) ? 2 : 0; - + (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U; algoName = OidFromId((word32)algoOID, (word32)type, &algoSz); if (algoName == NULL) { WOLFSSL_MSG("Unknown Algorithm"); @@ -18634,7 +18633,7 @@ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, } /* Get type, LSB 4-bits */ - bType = (b & ASN_TYPE_MASK); + bType = (byte)(b & ASN_TYPE_MASK); if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE || bType == ASN_DIR_TYPE) { @@ -21988,7 +21987,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) if (decrementMaxPathLen && cert->ca->maxPathLen > 0) { WOLFSSL_MSG("\tmaxPathLen status: reduce by 1"); - cert->maxPathLen = cert->ca->maxPathLen - 1; + cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1); if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) { WOLFSSL_MSG("\tmaxPathLen status: OK"); @@ -22006,7 +22005,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } else if (cert->ca && cert->isCA) { /* case where cert->pathLength extension is not set */ if (cert->ca->maxPathLen > 0) { - cert->maxPathLen = cert->ca->maxPathLen - 1; + cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1); } else { cert->maxPathLen = 0; if (verify != NO_VERIFY && type != CA_TYPE && @@ -31240,7 +31239,7 @@ int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen, idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out); /* store r */ - ret = SetASNInt((int)rLen, rAddLeadZero ? 0x80 : 0x00, &out[idx]); + ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]); if (ret < 0) return ret; idx += (word32)ret; @@ -31248,7 +31247,7 @@ int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen, idx += rLen; /* store s */ - ret = SetASNInt((int)sLen, sAddLeadZero ? 0x80 : 0x00, &out[idx]); + ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]); if (ret < 0) return ret; idx += (word32)ret; diff --git a/wolfcrypt/src/coding.c b/wolfcrypt/src/coding.c index a3667da34f8..be5f418d1eb 100644 --- a/wolfcrypt/src/coding.c +++ b/wolfcrypt/src/coding.c @@ -100,11 +100,11 @@ static WC_INLINE byte Base64_Char2Val(byte c) byte mask; c -= BASE64_MIN; - mask = (((byte)(0x3f - c)) >> 7) - 1; + mask = (byte)((((byte)(0x3f - c)) >> 7) - 1); /* Load a value from the first cache line and use when mask set. */ - v = base64Decode[ c & 0x3f ] & mask ; + v = (byte)(base64Decode[ c & 0x3f ] & mask); /* Load a value from the second cache line and use when mask not set. */ - v |= base64Decode[(c & 0x0f) | 0x40] & (~mask); + v |= (byte)(base64Decode[(c & 0x0f) | 0x40] & (~mask)); return v; #else @@ -236,8 +236,8 @@ int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) e1 = Base64_Char2Val(e1); e2 = Base64_Char2Val(e2); - e3 = (e3 == PAD) ? 0 : Base64_Char2Val(e3); - e4 = (e4 == PAD) ? 0 : Base64_Char2Val(e4); + e3 = (byte)((e3 == PAD) ? 0 : Base64_Char2Val(e3)); + e4 = (byte)((e4 == PAD) ? 0 : Base64_Char2Val(e4)); if (e1 == BAD || e2 == BAD || e3 == BAD || e4 == BAD) { WOLFSSL_MSG("Bad Base64 Decode bad character"); diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 2a183d73965..bb69874a7f0 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -1633,7 +1633,7 @@ static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve, curve->dp = dp; /* set dp info */ /* determine items to load */ - load_items = (((byte)~(word32)curve->load_mask) & load_mask); + load_items = (byte)(((byte)~(word32)curve->load_mask) & load_mask); curve->load_mask |= load_items; /* load items */ @@ -6928,7 +6928,7 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, /* may still need bit truncation too */ if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * inlen) > orderBits) - mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7)); + mp_rshb(e, (int)(WOLFSSL_BIT_SIZE - (orderBits & 0x7))); } /* make up a key and export the public copy */ @@ -8389,7 +8389,7 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, /* may still need bit truncation too */ if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * hashlen) > orderBits) - mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7)); + mp_rshb(e, (int)(WOLFSSL_BIT_SIZE - (orderBits & 0x7))); } /* check for async hardware acceleration */ diff --git a/wolfcrypt/src/hmac.c b/wolfcrypt/src/hmac.c index 1c7847335ea..ec8878fd7e8 100644 --- a/wolfcrypt/src/hmac.c +++ b/wolfcrypt/src/hmac.c @@ -586,7 +586,7 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) XMEMSET(ip + length, 0, hmac_block_size - length); for(i = 0; i < hmac_block_size; i++) { - op[i] = ip[i] ^ OPAD; + op[i] = (byte)(ip[i] ^ OPAD); ip[i] ^= IPAD; } } diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index 477fc5aa6a3..f80c9c649b7 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -289,7 +289,7 @@ WC_MISC_STATIC WC_INLINE void xorbufout(void* out, const void* buf, /* Move alignment so that it lines up with a * WOLFSSL_WORD_SIZE boundary */ while (((wc_ptr_t)b) % WOLFSSL_WORD_SIZE != 0 && count > 0) { - *(o++) = *(b++) ^ *(m++); + *(o++) = (byte)(*(b++) ^ *(m++)); count--; } XorWordsOut( (wolfssl_word**)&o, (const wolfssl_word**)&b, @@ -298,7 +298,7 @@ WC_MISC_STATIC WC_INLINE void xorbufout(void* out, const void* buf, } for (i = 0; i < count; i++) - o[i] = b[i] ^ m[i]; + o[i] = (byte)(b[i] ^ m[i]); } /* This routine performs a bitwise XOR operation of <*r> and <*a> for number @@ -505,8 +505,8 @@ WC_MISC_STATIC WC_INLINE int ByteToHexStr(byte in, char* out) if (out == NULL) return -1; - out[0] = ByteToHex(in >> 4); - out[1] = ByteToHex(in & 0xf); + out[0] = ByteToHex((byte)(in >> 4)); + out[1] = ByteToHex((byte)(in & 0xf)); return 0; } @@ -544,7 +544,7 @@ WC_MISC_STATIC WC_INLINE byte ctMaskLTE(int a, int b) /* Constant time - mask set when a == b. */ WC_MISC_STATIC WC_INLINE byte ctMaskEq(int a, int b) { - return (byte)(~ctMaskGT(a, b)) & (byte)(~ctMaskLT(a, b)); + return (byte)((byte)(~ctMaskGT(a, b)) & (byte)(~ctMaskLT(a, b))); } /* Constant time - sets 16 bit integer mask when a > b */ @@ -574,13 +574,13 @@ WC_MISC_STATIC WC_INLINE word16 ctMask16LTE(int a, int b) /* Constant time - sets 16 bit integer mask when a == b. */ WC_MISC_STATIC WC_INLINE word16 ctMask16Eq(int a, int b) { - return (word16)(~ctMask16GT(a, b)) & (word16)(~ctMask16LT(a, b)); + return (word16)((word16)(~ctMask16GT(a, b)) & (word16)(~ctMask16LT(a, b))); } /* Constant time - mask set when a != b. */ WC_MISC_STATIC WC_INLINE byte ctMaskNotEq(int a, int b) { - return (byte)ctMaskGT(a, b) | (byte)ctMaskLT(a, b); + return (byte)((byte)ctMaskGT(a, b) | (byte)ctMaskLT(a, b)); } /* Constant time - select a when mask is set and b otherwise. */ diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 74ded88aa9d..df16fa6eb92 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -12576,7 +12576,7 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, if (err == MP_OKAY) { /* 4.2. y = e[i] */ - int y = (e->dp[i >> SP_WORD_SHIFT] >> (i & SP_WORD_MASK)) & 1; + int y = (int)((e->dp[i >> SP_WORD_SHIFT] >> (i & SP_WORD_MASK)) & 1); /* 4.3. j = y & s */ int j = y & s; /* 4.4 s = s | y */ @@ -12709,7 +12709,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, if (err == MP_OKAY) { /* 6.2. y = e[i] */ - int y = (e->dp[i >> SP_WORD_SHIFT] >> (i & SP_WORD_MASK)) & 1; + int y = (int)((e->dp[i >> SP_WORD_SHIFT] >> (i & SP_WORD_MASK)) & 1); /* 6.3 j = y & s */ int j = y & s; /* 6.4 s = s | y */ From 94121b8d238479146021ae16317957390655578c Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 11 May 2023 11:51:27 -0500 Subject: [PATCH 263/391] wolfcrypt/src/aes.c: fixes for bugprone-macro-parentheses; wolfcrypt/src/ecc.c: fix for nullPointerRedundantCheck ("possible null pointer dereference"). --- wolfcrypt/src/aes.c | 8 ++++---- wolfcrypt/src/ecc.c | 4 ++++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index a6e1be83046..8fe05f74e98 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -1978,12 +1978,12 @@ static word32 GetTable8_4(const byte* t, byte o0, byte o1, byte o2, byte o3) #define GetTable(t, o) t[o] #define GetTable8(t, o) t[o] #define GetTable_Multi(t, t0, o0, t1, o1, t2, o2, t3, o3) \ - *t0 = t[o0]; *t1 = t[o1]; *t2 = t[o2]; *t3 = t[o3] + *(t0) = (t)[o0]; *(t1) = (t)[o1]; *(t2) = (t)[o2]; *(t3) = (t)[o3] #define XorTable_Multi(t, t0, o0, t1, o1, t2, o2, t3, o3) \ - *t0 ^= t[o0]; *t1 ^= t[o1]; *t2 ^= t[o2]; *t3 ^= t[o3] + *(t0) ^= (t)[o0]; *(t1) ^= (t)[o1]; *(t2) ^= (t)[o2]; *(t3) ^= (t)[o3] #define GetTable8_4(t, o0, o1, o2, o3) \ - (((word32)t[o0] << 24) | ((word32)t[o1] << 16) | \ - ((word32)t[o2] << 8) | ((word32)t[o3] << 0)) + (((word32)(t)[o0] << 24) | ((word32)(t)[o1] << 16) | \ + ((word32)(t)[o2] << 8) | ((word32)(t)[o3] << 0)) #endif /* Software AES - ECB Encrypt */ diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index bb69874a7f0..0e3e4fae987 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -3368,6 +3368,10 @@ static int ecc_key_tmp_init(ecc_key* key, void* heap) (void)heap; + if (key == NULL) { + return ECC_BAD_ARG_E; + } + XMEMSET(key, 0, sizeof(*key)); #if defined(WOLFSSL_SP_MATH_ALL) && defined(WOLFSSL_SMALL_STACK) From f61b7ca2c30e6e789d1d4048df1b7b2e8e2cb10a Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 8 May 2023 09:49:50 -0700 Subject: [PATCH 264/391] always call crypto cb when compiled in --- wolfcrypt/src/aes.c | 18 ++++++++-------- wolfcrypt/src/cmac.c | 14 ++++++------ wolfcrypt/src/ecc.c | 48 +++++++++++++++++------------------------- wolfcrypt/src/random.c | 14 ++++++------ wolfcrypt/src/rsa.c | 24 +++++++-------------- wolfcrypt/src/sha256.c | 12 +++++------ wolfcrypt/src/sha512.c | 16 ++++++-------- 7 files changed, 60 insertions(+), 86 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 8fe05f74e98..27adac2e55e 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -4219,7 +4219,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #endif #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int crypto_cb_ret = wc_CryptoCb_AesCbcEncrypt(aes, out, in, sz); if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) return crypto_cb_ret; @@ -4352,7 +4352,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #endif #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int crypto_cb_ret = wc_CryptoCb_AesCbcDecrypt(aes, out, in, sz); if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) return crypto_cb_ret; @@ -4670,7 +4670,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int crypto_cb_ret = wc_CryptoCb_AesCtrEncrypt(aes, out, in, sz); if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) return crypto_cb_ret; @@ -6863,7 +6863,7 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, } #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int crypto_cb_ret = wc_CryptoCb_AesGcmEncrypt(aes, out, in, sz, iv, ivSz, authTag, authTagSz, authIn, authInSz); @@ -7419,7 +7419,7 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, } #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int crypto_cb_ret = wc_CryptoCb_AesGcmDecrypt(aes, out, in, sz, iv, ivSz, authTag, authTagSz, authIn, authInSz); @@ -9311,7 +9311,7 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, } #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int crypto_cb_ret = wc_CryptoCb_AesCcmEncrypt(aes, out, in, inSz, nonce, nonceSz, authTag, authTagSz, authIn, authInSz); @@ -9490,7 +9490,7 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, } #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int crypto_cb_ret = wc_CryptoCb_AesCcmDecrypt(aes, out, in, inSz, nonce, nonceSz, authTag, authTagSz, authIn, authInSz); @@ -10009,7 +10009,7 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( word32 blocks = sz / AES_BLOCK_SIZE; #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int ret = wc_CryptoCb_AesEcbEncrypt(aes, out, in, sz); if (ret != CRYPTOCB_UNAVAILABLE) return ret; @@ -10045,7 +10045,7 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( word32 blocks = sz / AES_BLOCK_SIZE; #ifdef WOLF_CRYPTO_CB - if (aes->devId != INVALID_DEVID) { + { int ret = wc_CryptoCb_AesEcbDecrypt(aes, out, in, sz); if (ret != CRYPTOCB_UNAVAILABLE) return ret; diff --git a/wolfcrypt/src/cmac.c b/wolfcrypt/src/cmac.c index 2ceefd7acfc..65f61dc20a3 100644 --- a/wolfcrypt/src/cmac.c +++ b/wolfcrypt/src/cmac.c @@ -115,7 +115,7 @@ int wc_InitCmac_ex(Cmac* cmac, const byte* key, word32 keySz, XMEMSET(cmac, 0, sizeof(Cmac)); #ifdef WOLF_CRYPTO_CB - if (devId != INVALID_DEVID) { + { cmac->devId = devId; cmac->devCtx = NULL; @@ -178,7 +178,7 @@ int wc_CmacUpdate(Cmac* cmac, const byte* in, word32 inSz) } #ifdef WOLF_CRYPTO_CB - if (cmac->devId != INVALID_DEVID) { + { ret = wc_CryptoCb_Cmac(cmac, NULL, 0, in, inSz, NULL, NULL, 0, NULL); if (ret != CRYPTOCB_UNAVAILABLE) @@ -226,12 +226,10 @@ int wc_CmacFinal(Cmac* cmac, byte* out, word32* outSz) } #ifdef WOLF_CRYPTO_CB - if (cmac->devId != INVALID_DEVID) { - ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, 0, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ - } + ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, 0, NULL); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ #endif if (cmac->bufferSz == AES_BLOCK_SIZE) { diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 0e3e4fae987..d31fc7786eb 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -4432,16 +4432,14 @@ int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out, } #ifdef WOLF_CRYPTO_CB - if (private_key->devId != INVALID_DEVID) { - err = wc_CryptoCb_Ecdh(private_key, public_key, out, outlen); + err = wc_CryptoCb_Ecdh(private_key, public_key, out, outlen); #ifndef WOLF_CRYPTO_CB_ONLY_ECC - if (err != CRYPTOCB_UNAVAILABLE) - return err; - /* fall-through when unavailable */ + if (err != CRYPTOCB_UNAVAILABLE) + return err; + /* fall-through when unavailable */ #endif - } #ifdef WOLF_CRYPTO_CB_ONLY_ECC - else { + if (err == CRYPTOCB_UNAVAILABLE) { err = NO_VALID_DEVID; } #endif @@ -5330,18 +5328,14 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, key->flags = (byte)flags; #ifdef WOLF_CRYPTO_CB - if (key->devId != INVALID_DEVID) { - err = wc_CryptoCb_MakeEccKey(rng, keysize, key, curve_id); + err = wc_CryptoCb_MakeEccKey(rng, keysize, key, curve_id); #ifndef WOLF_CRYPTO_CB_ONLY_ECC - if (err != CRYPTOCB_UNAVAILABLE) - return err; - /* fall-through when unavailable */ - #else + if (err != CRYPTOCB_UNAVAILABLE) return err; + /* fall-through when unavailable */ #endif - } #ifdef WOLF_CRYPTO_CB_ONLY_ECC - else { + if (err == CRYPTOCB_UNAVAILABLE) { return NO_VALID_DEVID; } #endif @@ -6320,16 +6314,14 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, } #ifdef WOLF_CRYPTO_CB - if (key->devId != INVALID_DEVID) { - err = wc_CryptoCb_EccSign(in, inlen, out, outlen, rng, key); + err = wc_CryptoCb_EccSign(in, inlen, out, outlen, rng, key); #ifndef WOLF_CRYPTO_CB_ONLY_ECC - if (err != CRYPTOCB_UNAVAILABLE) - return err; - /* fall-through when unavailable */ + if (err != CRYPTOCB_UNAVAILABLE) + return err; + /* fall-through when unavailable */ #endif - } #ifdef WOLF_CRYPTO_CB_ONLY_ECC - else { + if (err == CRYPTOCB_UNAVAILABLE) { err = NO_VALID_DEVID; } #endif @@ -8020,16 +8012,14 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, } #ifdef WOLF_CRYPTO_CB - if (key->devId != INVALID_DEVID) { - err = wc_CryptoCb_EccVerify(sig, siglen, hash, hashlen, res, key); + err = wc_CryptoCb_EccVerify(sig, siglen, hash, hashlen, res, key); #ifndef WOLF_CRYPTO_CB_ONLY_ECC - if (err != CRYPTOCB_UNAVAILABLE) - return err; - /* fall-through when unavailable */ + if (err != CRYPTOCB_UNAVAILABLE) + return err; + /* fall-through when unavailable */ #endif - } #ifdef WOLF_CRYPTO_CB_ONLY_ECC - else { + if (err == CRYPTOCB_UNAVAILABLE) { err = NO_VALID_DEVID; } #endif diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 885d973d521..f2dcd5bd4a3 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -1829,12 +1829,10 @@ int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz) return 0; #ifdef WOLF_CRYPTO_CB - if (rng->devId != INVALID_DEVID) { - ret = wc_CryptoCb_RandomBlock(rng, output, sz); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ - } + ret = wc_CryptoCb_RandomBlock(rng, output, sz); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ #endif #ifdef HAVE_INTEL_RDRAND @@ -2583,7 +2581,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #ifdef WOLF_CRYPTO_CB int ret; - if (os != NULL && os->devId != INVALID_DEVID) { + if (os != NULL) { ret = wc_CryptoCb_RandomSeed(os, output, sz); if (ret != CRYPTOCB_UNAVAILABLE) return ret; @@ -3702,7 +3700,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } #ifdef WOLF_CRYPTO_CB - if (os->devId != INVALID_DEVID) { + { ret = wc_CryptoCb_RandomSeed(os, output, sz); if (ret != CRYPTOCB_UNAVAILABLE) return ret; diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index fac7e3c1459..87d75099ee9 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3172,18 +3172,14 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, } #ifdef WOLF_CRYPTO_CB - if (key->devId != INVALID_DEVID) { - ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng); + ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng); #ifndef WOLF_CRYPTO_CB_ONLY_RSA - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable and try using software */ - #else + if (ret != CRYPTOCB_UNAVAILABLE) return ret; + /* fall-through when unavailable and try using software */ #endif - } #ifdef WOLF_CRYPTO_CB_ONLY_RSA - else { + if (ret == CRYPTOCB_UNAVAILABLE) return NO_VALID_DEVID; } #endif @@ -4768,18 +4764,14 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) #endif #ifdef WOLF_CRYPTO_CB - if (key->devId != INVALID_DEVID) { - err = wc_CryptoCb_MakeRsaKey(key, size, e, rng); + err = wc_CryptoCb_MakeRsaKey(key, size, e, rng); #ifndef WOLF_CRYPTO_CB_ONLY_RSA - if (err != CRYPTOCB_UNAVAILABLE) - goto out; - /* fall-through when unavailable */ - #else + if (err != CRYPTOCB_UNAVAILABLE) goto out; + /* fall-through when unavailable */ #endif - } #ifdef WOLF_CRYPTO_CB_ONLY_RSA - else { + if (err == CRYPTOCB_UNAVAILABLE) err = NO_VALID_DEVID; goto out; } diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 94bdc265395..2220b705381 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -1231,7 +1231,7 @@ static int InitSha256(wc_Sha256* sha256) } #ifdef WOLF_CRYPTO_CB - if (sha256->devId != INVALID_DEVID) { + { int ret = wc_CryptoCb_Sha256Hash(sha256, data, len, NULL); if (ret != CRYPTOCB_UNAVAILABLE) return ret; @@ -1394,12 +1394,10 @@ static int InitSha256(wc_Sha256* sha256) } #ifdef WOLF_CRYPTO_CB - if (sha256->devId != INVALID_DEVID) { - ret = wc_CryptoCb_Sha256Hash(sha256, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ - } + ret = wc_CryptoCb_Sha256Hash(sha256, NULL, 0, hash); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA256) diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index f4e77ccc270..0803b2b8a0b 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -952,7 +952,7 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) } #ifdef WOLF_CRYPTO_CB - if (sha512->devId != INVALID_DEVID) { + { int ret = wc_CryptoCb_Sha512Hash(sha512, data, len, NULL); if (ret != CRYPTOCB_UNAVAILABLE) return ret; @@ -1151,7 +1151,7 @@ static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, size_t digestSz, } #ifdef WOLF_CRYPTO_CB - if (sha512->devId != INVALID_DEVID) { + { byte localHash[WC_SHA512_DIGEST_SIZE]; ret = wc_CryptoCb_Sha512Hash(sha512, NULL, 0, localHash); if (ret != CRYPTOCB_UNAVAILABLE) { @@ -1374,7 +1374,7 @@ int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) } #ifdef WOLF_CRYPTO_CB - if (sha384->devId != INVALID_DEVID) { + { int ret = wc_CryptoCb_Sha384Hash(sha384, data, len, NULL); if (ret != CRYPTOCB_UNAVAILABLE) return ret; @@ -1423,12 +1423,10 @@ int wc_Sha384Final(wc_Sha384* sha384, byte* hash) } #ifdef WOLF_CRYPTO_CB - if (sha384->devId != INVALID_DEVID) { - ret = wc_CryptoCb_Sha384Hash(sha384, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ - } + ret = wc_CryptoCb_Sha384Hash(sha384, NULL, 0, hash); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA384) if (sha384->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA384) { From cc661079105fabd477f25eab296bf26c25b34a1b Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 8 May 2023 12:51:22 -0700 Subject: [PATCH 265/391] fix for recursive issue in test case --- wolfcrypt/test/test.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 7e2c4b25fd1..1ef3855d0f4 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -45197,12 +45197,20 @@ static int myCryptoCbFind(int currentId, int algoType) /* can have algo specific overrides here switch (algoType) { + i.e. + WC_ALGO_TYPE_CMAC + WC_ALGO_TYPE_SEED + WC_ALGO_TYPE_HMAC + WC_ALGO_TYPE_HASH + WC_ALGO_TYPE_CIPHER + WC_ALGO_TYPE_PK + } */ (void)algoType; if (currentId == INVALID_DEVID) { - return 1; /* override invalid devid found with 1 */ + /* can override invalid devid found with 1 */ } return currentId; } From 089593ff8d42bd1101250dee5622cb3b43b627b5 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 9 May 2023 09:08:32 -0700 Subject: [PATCH 266/391] resolve CB_ONLY cases --- wolfcrypt/src/ecc.c | 1 + wolfcrypt/src/rsa.c | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index d31fc7786eb..0abc0ee9163 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -5338,6 +5338,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, if (err == CRYPTOCB_UNAVAILABLE) { return NO_VALID_DEVID; } + return err; #endif #endif diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index 87d75099ee9..a16f9ddaf20 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3179,9 +3179,10 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, /* fall-through when unavailable and try using software */ #endif #ifdef WOLF_CRYPTO_CB_ONLY_RSA - if (ret == CRYPTOCB_UNAVAILABLE) + if (ret == CRYPTOCB_UNAVAILABLE) { return NO_VALID_DEVID; } + return ret; #endif #endif From 841860974bcc52b38c2161bc14d227977ec4e7d8 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 10 May 2023 15:28:19 -0700 Subject: [PATCH 267/391] add WOLF_CRYPTO_CB_FIND macro to guard find device ID callback --- wolfcrypt/src/aes.c | 27 +++++++++++ wolfcrypt/src/cmac.c | 19 ++++++-- wolfcrypt/src/cryptocb.c | 8 ++- wolfcrypt/src/ecc.c | 94 ++++++++++++++++++++++-------------- wolfcrypt/src/random.c | 22 +++++++-- wolfcrypt/src/rsa.c | 50 +++++++++++-------- wolfcrypt/src/sha256.c | 16 ++++-- wolfcrypt/src/sha512.c | 22 +++++++-- wolfssl/wolfcrypt/cryptocb.h | 2 + wolfssl/wolfcrypt/settings.h | 2 - 10 files changed, 185 insertions(+), 77 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 27adac2e55e..3dc391c5fec 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -4219,6 +4219,9 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #endif #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int crypto_cb_ret = wc_CryptoCb_AesCbcEncrypt(aes, out, in, sz); if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) @@ -4352,6 +4355,9 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #endif #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int crypto_cb_ret = wc_CryptoCb_AesCbcDecrypt(aes, out, in, sz); if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) @@ -4670,6 +4676,9 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int crypto_cb_ret = wc_CryptoCb_AesCtrEncrypt(aes, out, in, sz); if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) @@ -6863,6 +6872,9 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int crypto_cb_ret = wc_CryptoCb_AesGcmEncrypt(aes, out, in, sz, iv, ivSz, authTag, @@ -7419,6 +7431,9 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int crypto_cb_ret = wc_CryptoCb_AesGcmDecrypt(aes, out, in, sz, iv, ivSz, @@ -9311,6 +9326,9 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int crypto_cb_ret = wc_CryptoCb_AesCcmEncrypt(aes, out, in, inSz, nonce, nonceSz, @@ -9490,6 +9508,9 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int crypto_cb_ret = wc_CryptoCb_AesCcmDecrypt(aes, out, in, inSz, nonce, nonceSz, @@ -10009,6 +10030,9 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( word32 blocks = sz / AES_BLOCK_SIZE; #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int ret = wc_CryptoCb_AesEcbEncrypt(aes, out, in, sz); if (ret != CRYPTOCB_UNAVAILABLE) @@ -10045,6 +10069,9 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( word32 blocks = sz / AES_BLOCK_SIZE; #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif { int ret = wc_CryptoCb_AesEcbDecrypt(aes, out, in, sz); if (ret != CRYPTOCB_UNAVAILABLE) diff --git a/wolfcrypt/src/cmac.c b/wolfcrypt/src/cmac.c index 65f61dc20a3..e3b9f39eae6 100644 --- a/wolfcrypt/src/cmac.c +++ b/wolfcrypt/src/cmac.c @@ -115,6 +115,9 @@ int wc_InitCmac_ex(Cmac* cmac, const byte* key, word32 keySz, XMEMSET(cmac, 0, sizeof(Cmac)); #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (devId != INVALID_DEVID) + #endif { cmac->devId = devId; cmac->devCtx = NULL; @@ -178,6 +181,9 @@ int wc_CmacUpdate(Cmac* cmac, const byte* in, word32 inSz) } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (cmac->devId != INVALID_DEVID) + #endif { ret = wc_CryptoCb_Cmac(cmac, NULL, 0, in, inSz, NULL, NULL, 0, NULL); @@ -226,10 +232,15 @@ int wc_CmacFinal(Cmac* cmac, byte* out, word32* outSz) } #ifdef WOLF_CRYPTO_CB - ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, 0, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (cmac->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, 0, NULL); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ + } #endif if (cmac->bufferSz == AES_BLOCK_SIZE) { diff --git a/wolfcrypt/src/cryptocb.c b/wolfcrypt/src/cryptocb.c index ed4f9518839..06195494f89 100644 --- a/wolfcrypt/src/cryptocb.c +++ b/wolfcrypt/src/cryptocb.c @@ -49,8 +49,10 @@ typedef struct CryptoCb { void* ctx; } CryptoCb; static WOLFSSL_GLOBAL CryptoCb gCryptoDev[MAX_CRYPTO_DEVID_CALLBACKS]; -static CryptoDevCallbackFind CryptoCb_FindCb = NULL; +#ifdef WOLF_CRYPTO_CB_FIND +static CryptoDevCallbackFind CryptoCb_FindCb = NULL; +#endif #ifdef DEBUG_CRYPTOCB static const char* GetAlgoTypeStr(int algo) @@ -188,9 +190,11 @@ static CryptoCb* wc_CryptoCb_FindDevice(int devId, int algoType) { int localDevId = devId; +#ifdef WOLF_CRYPTO_CB_FIND if (CryptoCb_FindCb != NULL) { localDevId = CryptoCb_FindCb(devId, algoType); } +#endif /* WOLF_CRYPTO_CB_FIND */ return wc_CryptoCb_GetDevice(localDevId); } @@ -233,6 +237,7 @@ int wc_CryptoCb_GetDevIdAtIndex(int startIdx) } +#ifdef WOLF_CRYPTO_CB_FIND /* Used to register a find device function. Useful for cases where the * device ID in the struct may not have been set but still wanting to use * a specific crypto callback device ID. The find callback is global and @@ -241,6 +246,7 @@ void wc_CryptoCb_SetDeviceFindCb(CryptoDevCallbackFind cb) { CryptoCb_FindCb = cb; } +#endif int wc_CryptoCb_RegisterDevice(int devId, CryptoDevCallbackFunc cb, void* ctx) { diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 0abc0ee9163..770a6f1338a 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -4432,17 +4432,22 @@ int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out, } #ifdef WOLF_CRYPTO_CB - err = wc_CryptoCb_Ecdh(private_key, public_key, out, outlen); - #ifndef WOLF_CRYPTO_CB_ONLY_ECC - if (err != CRYPTOCB_UNAVAILABLE) - return err; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (private_key->devId != INVALID_DEVID) #endif - #ifdef WOLF_CRYPTO_CB_ONLY_ECC - if (err == CRYPTOCB_UNAVAILABLE) { - err = NO_VALID_DEVID; + { + err = wc_CryptoCb_Ecdh(private_key, public_key, out, outlen); + #ifndef WOLF_CRYPTO_CB_ONLY_ECC + if (err != CRYPTOCB_UNAVAILABLE) + return err; + /* fall-through when unavailable */ + #endif + #ifdef WOLF_CRYPTO_CB_ONLY_ECC + if (err == CRYPTOCB_UNAVAILABLE) { + err = NO_VALID_DEVID; + } + #endif } - #endif #endif #ifndef WOLF_CRYPTO_CB_ONLY_ECC @@ -5328,18 +5333,23 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, key->flags = (byte)flags; #ifdef WOLF_CRYPTO_CB - err = wc_CryptoCb_MakeEccKey(rng, keysize, key, curve_id); - #ifndef WOLF_CRYPTO_CB_ONLY_ECC - if (err != CRYPTOCB_UNAVAILABLE) - return err; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) #endif - #ifdef WOLF_CRYPTO_CB_ONLY_ECC - if (err == CRYPTOCB_UNAVAILABLE) { - return NO_VALID_DEVID; + { + err = wc_CryptoCb_MakeEccKey(rng, keysize, key, curve_id); + #ifndef WOLF_CRYPTO_CB_ONLY_ECC + if (err != CRYPTOCB_UNAVAILABLE) + return err; + /* fall-through when unavailable */ + #endif + #ifdef WOLF_CRYPTO_CB_ONLY_ECC + if (err == CRYPTOCB_UNAVAILABLE) { + return NO_VALID_DEVID; + } + return err; + #endif } - return err; - #endif #endif #ifndef WOLF_CRYPTO_CB_ONLY_ECC @@ -6315,17 +6325,22 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, } #ifdef WOLF_CRYPTO_CB - err = wc_CryptoCb_EccSign(in, inlen, out, outlen, rng, key); - #ifndef WOLF_CRYPTO_CB_ONLY_ECC - if (err != CRYPTOCB_UNAVAILABLE) - return err; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) #endif - #ifdef WOLF_CRYPTO_CB_ONLY_ECC - if (err == CRYPTOCB_UNAVAILABLE) { - err = NO_VALID_DEVID; + { + err = wc_CryptoCb_EccSign(in, inlen, out, outlen, rng, key); + #ifndef WOLF_CRYPTO_CB_ONLY_ECC + if (err != CRYPTOCB_UNAVAILABLE) + return err; + /* fall-through when unavailable */ + #endif + #ifdef WOLF_CRYPTO_CB_ONLY_ECC + if (err == CRYPTOCB_UNAVAILABLE) { + err = NO_VALID_DEVID; + } + #endif } - #endif #endif #ifndef WOLF_CRYPTO_CB_ONLY_ECC @@ -8013,17 +8028,22 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, } #ifdef WOLF_CRYPTO_CB - err = wc_CryptoCb_EccVerify(sig, siglen, hash, hashlen, res, key); - #ifndef WOLF_CRYPTO_CB_ONLY_ECC - if (err != CRYPTOCB_UNAVAILABLE) - return err; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) #endif - #ifdef WOLF_CRYPTO_CB_ONLY_ECC - if (err == CRYPTOCB_UNAVAILABLE) { - err = NO_VALID_DEVID; + { + err = wc_CryptoCb_EccVerify(sig, siglen, hash, hashlen, res, key); + #ifndef WOLF_CRYPTO_CB_ONLY_ECC + if (err != CRYPTOCB_UNAVAILABLE) + return err; + /* fall-through when unavailable */ + #endif + #ifdef WOLF_CRYPTO_CB_ONLY_ECC + if (err == CRYPTOCB_UNAVAILABLE) { + err = NO_VALID_DEVID; + } + #endif } - #endif #endif #ifndef WOLF_CRYPTO_CB_ONLY_ECC diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index f2dcd5bd4a3..259dc5a682c 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -1829,10 +1829,15 @@ int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz) return 0; #ifdef WOLF_CRYPTO_CB - ret = wc_CryptoCb_RandomBlock(rng, output, sz); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (rng->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_RandomBlock(rng, output, sz); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ + } #endif #ifdef HAVE_INTEL_RDRAND @@ -2581,7 +2586,11 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #ifdef WOLF_CRYPTO_CB int ret; - if (os != NULL) { + if (os != NULL + #ifndef WOLF_CRYPTO_CB_FIND + && os->devId != INVALID_DEVID) + #endif + { ret = wc_CryptoCb_RandomSeed(os, output, sz); if (ret != CRYPTOCB_UNAVAILABLE) return ret; @@ -3700,6 +3709,9 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (os->devId != INVALID_DEVID) + #endif { ret = wc_CryptoCb_RandomSeed(os, output, sz); if (ret != CRYPTOCB_UNAVAILABLE) diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index a16f9ddaf20..f667ebc88f2 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3172,18 +3172,23 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, } #ifdef WOLF_CRYPTO_CB - ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng); - #ifndef WOLF_CRYPTO_CB_ONLY_RSA - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable and try using software */ + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) #endif - #ifdef WOLF_CRYPTO_CB_ONLY_RSA - if (ret == CRYPTOCB_UNAVAILABLE) { - return NO_VALID_DEVID; + { + ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng); + #ifndef WOLF_CRYPTO_CB_ONLY_RSA + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable and try using software */ + #endif + #ifdef WOLF_CRYPTO_CB_ONLY_RSA + if (ret == CRYPTOCB_UNAVAILABLE) { + return NO_VALID_DEVID; + } + return ret; + #endif } - return ret; - #endif #endif #ifndef WOLF_CRYPTO_CB_ONLY_RSA @@ -4765,18 +4770,23 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) #endif #ifdef WOLF_CRYPTO_CB - err = wc_CryptoCb_MakeRsaKey(key, size, e, rng); - #ifndef WOLF_CRYPTO_CB_ONLY_RSA - if (err != CRYPTOCB_UNAVAILABLE) - goto out; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) #endif - #ifdef WOLF_CRYPTO_CB_ONLY_RSA - if (err == CRYPTOCB_UNAVAILABLE) - err = NO_VALID_DEVID; - goto out; + { + err = wc_CryptoCb_MakeRsaKey(key, size, e, rng); + #ifndef WOLF_CRYPTO_CB_ONLY_RSA + if (err != CRYPTOCB_UNAVAILABLE) + goto out; + /* fall-through when unavailable */ + #endif + #ifdef WOLF_CRYPTO_CB_ONLY_RSA + if (err == CRYPTOCB_UNAVAILABLE) + err = NO_VALID_DEVID; + goto out; + } + #endif } - #endif #endif #ifndef WOLF_CRYPTO_CB_ONLY_RSA diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 2220b705381..75b975eb876 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -1231,6 +1231,9 @@ static int InitSha256(wc_Sha256* sha256) } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (sha256->devId != INVALID_DEVID) + #endif { int ret = wc_CryptoCb_Sha256Hash(sha256, data, len, NULL); if (ret != CRYPTOCB_UNAVAILABLE) @@ -1394,10 +1397,15 @@ static int InitSha256(wc_Sha256* sha256) } #ifdef WOLF_CRYPTO_CB - ret = wc_CryptoCb_Sha256Hash(sha256, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (sha256->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_Sha256Hash(sha256, NULL, 0, hash); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ + } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA256) diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index 0803b2b8a0b..3d17a09b4f8 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -952,6 +952,9 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (sha512->devId != INVALID_DEVID) + #endif { int ret = wc_CryptoCb_Sha512Hash(sha512, data, len, NULL); if (ret != CRYPTOCB_UNAVAILABLE) @@ -1151,6 +1154,9 @@ static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, size_t digestSz, } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (sha512->devId != INVALID_DEVID) + #endif { byte localHash[WC_SHA512_DIGEST_SIZE]; ret = wc_CryptoCb_Sha512Hash(sha512, NULL, 0, localHash); @@ -1374,6 +1380,9 @@ int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) } #ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (sha384->devId != INVALID_DEVID) + #endif { int ret = wc_CryptoCb_Sha384Hash(sha384, data, len, NULL); if (ret != CRYPTOCB_UNAVAILABLE) @@ -1423,10 +1432,15 @@ int wc_Sha384Final(wc_Sha384* sha384, byte* hash) } #ifdef WOLF_CRYPTO_CB - ret = wc_CryptoCb_Sha384Hash(sha384, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ + #ifndef WOLF_CRYPTO_CB_FIND + if (sha384->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_Sha384Hash(sha384, NULL, 0, hash); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ + } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA384) if (sha384->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA384) { diff --git a/wolfssl/wolfcrypt/cryptocb.h b/wolfssl/wolfcrypt/cryptocb.h index 1b11cf3e4de..b5a592b1886 100644 --- a/wolfssl/wolfcrypt/cryptocb.h +++ b/wolfssl/wolfcrypt/cryptocb.h @@ -366,8 +366,10 @@ WOLFSSL_API int wc_CryptoCb_RegisterDevice(int devId, CryptoDevCallbackFunc cb, WOLFSSL_API void wc_CryptoCb_UnRegisterDevice(int devId); WOLFSSL_API int wc_CryptoCb_DefaultDevID(void); +#ifdef WOLF_CRYPTO_CB_FIND typedef int (*CryptoDevCallbackFind)(int devId, int algoType); WOLFSSL_API void wc_CryptoCb_SetDeviceFindCb(CryptoDevCallbackFind cb); +#endif #ifdef DEBUG_CRYPTOCB WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info); diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 38bf145fe3e..d18ddcc3124 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1816,8 +1816,6 @@ extern void uITRON4_free(void *p) ; #ifdef WOLFSSL_IMXRT1170_CAAM #define WOLFSSL_CAAM - - #define WOLFSSL_NO_CAAM_BLOB #endif /* OS specific support so far */ From cee1a26ff4f7eb40dc1ac2fe772617e27433ee2a Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 10 May 2023 15:51:39 -0700 Subject: [PATCH 268/391] add macro guard on test case --- wolfcrypt/src/cryptocb.c | 1 + wolfcrypt/test/test.c | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/wolfcrypt/src/cryptocb.c b/wolfcrypt/src/cryptocb.c index 06195494f89..7f6fb75ff84 100644 --- a/wolfcrypt/src/cryptocb.c +++ b/wolfcrypt/src/cryptocb.c @@ -195,6 +195,7 @@ static CryptoCb* wc_CryptoCb_FindDevice(int devId, int algoType) localDevId = CryptoCb_FindCb(devId, algoType); } #endif /* WOLF_CRYPTO_CB_FIND */ + (void)algoType; return wc_CryptoCb_GetDevice(localDevId); } diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 1ef3855d0f4..79f1f42aedd 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -45192,6 +45192,7 @@ static int myCryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) } +#ifdef WOLF_CRYPTO_CB_FIND static int myCryptoCbFind(int currentId, int algoType) { /* can have algo specific overrides here @@ -45214,6 +45215,7 @@ static int myCryptoCbFind(int currentId, int algoType) } return currentId; } +#endif /* WOLF_CRYPTO_CB_FIND */ WOLFSSL_TEST_SUBROUTINE int cryptocb_test(void) @@ -45228,7 +45230,9 @@ WOLFSSL_TEST_SUBROUTINE int cryptocb_test(void) /* set devId to something other than INVALID_DEVID */ devId = 1; ret = wc_CryptoCb_RegisterDevice(devId, myCryptoDevCb, &myCtx); +#ifdef WOLF_CRYPTO_CB_FIND wc_CryptoCb_SetDeviceFindCb(myCryptoCbFind); +#endif /* WOLF_CRYPTO_CB_FIND */ #ifndef WC_NO_RNG if (ret == 0) ret = random_test(); From d1495c927671049b7b4fe4480f55f85984242232 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Thu, 11 May 2023 14:21:39 -0600 Subject: [PATCH 269/391] Don't test SECP vectors when disabled in test.c --- wolfcrypt/test/test.c | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 79f1f42aedd..4c31d9637f4 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -23391,6 +23391,10 @@ WOLFSSL_TEST_SUBROUTINE int hpke_test(void) #endif #define ECC_SIG_SIZE ECC_MAX_SIG_SIZE +#ifdef NO_ECC_SECP + #define NO_ECC_VECTOR_TEST +#endif + #ifndef NO_ECC_VECTOR_TEST #if (defined(HAVE_ECC192) || defined(HAVE_ECC224) ||\ !defined(NO_ECC256) || defined(HAVE_ECC384) ||\ @@ -25839,8 +25843,9 @@ static int ecc_def_curve_test(WC_RNG *rng) #else ecc_key key[1]; #endif -#if (defined(HAVE_ECC_KEY_IMPORT) && defined(HAVE_ECC_KEY_EXPORT)) || \ - (defined(HAVE_ECC_KEY_IMPORT) && !defined(WOLFSSL_VALIDATE_ECC_IMPORT)) +#if ((defined(HAVE_ECC_KEY_IMPORT) && defined(HAVE_ECC_KEY_EXPORT)) || \ + (defined(HAVE_ECC_KEY_IMPORT) && !defined(WOLFSSL_VALIDATE_ECC_IMPORT))) \ + && !defined(NO_ECC_SECP) word32 idx = 0; #endif @@ -25891,8 +25896,9 @@ static int ecc_def_curve_test(WC_RNG *rng) (void)rng; #endif /* !WC_NO_RNG */ -#if (defined(HAVE_ECC_KEY_IMPORT) && defined(HAVE_ECC_KEY_EXPORT)) || \ - (defined(HAVE_ECC_KEY_IMPORT) && !defined(WOLFSSL_VALIDATE_ECC_IMPORT)) +#if ((defined(HAVE_ECC_KEY_IMPORT) && defined(HAVE_ECC_KEY_EXPORT)) || \ + (defined(HAVE_ECC_KEY_IMPORT) && !defined(WOLFSSL_VALIDATE_ECC_IMPORT))) \ + && !defined(NO_ECC_SECP) /* Use test ECC key - ensure real private "d" exists */ #ifdef USE_CERT_BUFFERS_256 ret = wc_EccPrivateKeyDecode(ecc_key_der_256, &idx, key, @@ -26496,7 +26502,8 @@ static int ecc_test_cert_gen(WC_RNG* rng) #endif /* WOLFSSL_CERT_GEN */ #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ - !defined(WOLFSSL_NO_MALLOC) && !defined(WOLF_CRYPTO_CB_ONLY_ECC) + !defined(WOLFSSL_NO_MALLOC) && !defined(WOLF_CRYPTO_CB_ONLY_ECC) && \ + (!defined(NO_ECC_SECP) || defined(WOLFSSL_CUSTOM_CURVES)) /* Test for the wc_ecc_key_new() and wc_ecc_key_free() functions. */ static int ecc_test_allocator(WC_RNG* rng) { @@ -27084,10 +27091,12 @@ WOLFSSL_TEST_SUBROUTINE int ecc_test(void) goto done; } #endif +#if !defined(NO_ECC_SECP) || defined(WOLFSSL_CUSTOM_CURVES) ret = ecc_def_curve_test(&rng); if (ret < 0) { goto done; } +#endif #endif /* !NO_ECC256 */ #if (defined(HAVE_ECC320) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 320 ret = ecc_test_curve(&rng, 40); @@ -27166,7 +27175,7 @@ WOLFSSL_TEST_SUBROUTINE int ecc_test(void) #endif #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \ !defined(WOLFSSL_STM32_PKA) && !defined(WOLFSSL_SILABS_SE_ACCEL) && \ - !defined(WOLF_CRYPTO_CB_ONLY_ECC) + !defined(WOLF_CRYPTO_CB_ONLY_ECC) && !defined(NO_ECC_SECP) ret = ecc_test_make_pub(&rng); if (ret != 0) { printf("ecc_test_make_pub failed!: %d\n", ret); @@ -27183,7 +27192,8 @@ WOLFSSL_TEST_SUBROUTINE int ecc_test(void) } #endif #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && !defined(WOLFSSL_NO_MALLOC) && \ - !defined(WOLF_CRYPTO_CB_ONLY_ECC) + !defined(WOLF_CRYPTO_CB_ONLY_ECC) && (!defined(NO_ECC_SECP) || \ + defined(WOLFSSL_CUSTOM_CURVES)) ret = ecc_test_allocator(&rng); if (ret != 0) { printf("ecc_test_allocator failed!: %d\n", ret); From a383251d4492a73e5f9d8cf5ecd19e31c1e562a0 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Thu, 11 May 2023 15:23:35 -0400 Subject: [PATCH 270/391] Doc Fix: TI no longer maintains the documentation; we do. --- tirtos/README | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tirtos/README b/tirtos/README index dc7fbb11496..4a0e04625d4 100644 --- a/tirtos/README +++ b/tirtos/README @@ -1,7 +1,7 @@ # wolfSSL library for TI-RTOS This directory contains the files that build wolfSSL library for TI-RTOS. -Please follow the instructions in "Using wolfSSL with TI-RTOS" (http://processors.wiki.ti.com/index.php/Using_wolfSSL_with_TI-RTOS) to build the wolfSSL +Please follow the instructions in "Using wolfSSL with TI-RTOS" (https://www.wolfssl.com/documentation/Using_wolfSSL_with_TI-RTOS.pdf) to build the wolfSSL library and the example applications. Also read TI-RTOS Getting Started Guide and TI-RTOS User Guide to learn more From e1da132961b0b608053b19c09c8fff968d0ca670 Mon Sep 17 00:00:00 2001 From: lealem47 <60322859+lealem47@users.noreply.github.com> Date: Fri, 12 May 2023 12:54:03 -0600 Subject: [PATCH 271/391] Skip Async_DevCtxInit when using init rsa/ecc label/id api's (#6393) * Skip Async_DevCtxInit when using init rsa/ecc label/id api's --------- Co-authored-by: Lealem Amedie --- wolfcrypt/src/ecc.c | 32 +++++++++++++++++++++++++++++--- wolfcrypt/src/rsa.c | 38 ++++++++++++++++++++++++++++++++------ wolfssl/wolfcrypt/ecc.h | 3 +++ wolfssl/wolfcrypt/rsa.h | 3 +++ 4 files changed, 67 insertions(+), 9 deletions(-) diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 770a6f1338a..dca2d69b97d 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -5804,12 +5804,21 @@ int wc_ecc_make_key(WC_RNG* rng, int keysize, ecc_key* key) WOLFSSL_ABI int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) { - int ret = 0; + int ret = 0; +#if defined(HAVE_PKCS11) + int isPkcs11 = 0; +#endif if (key == NULL) { return BAD_FUNC_ARG; } +#if defined(HAVE_PKCS11) + if (key->isPkcs11) { + isPkcs11 = 1; + } +#endif + #ifdef ECC_DUMP_OID wc_ecc_dump_oids(); #endif @@ -5862,9 +5871,16 @@ int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) - /* handle as async */ - ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC, + #if defined(HAVE_PKCS11) + if (!isPkcs11) + #endif + { + /* handle as async */ + ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC, key->heap, devId); + } +#elif defined(HAVE_PKCS11) + (void)isPkcs11; #endif #if defined(WOLFSSL_DSP) @@ -5917,6 +5933,11 @@ int wc_ecc_init_id(ecc_key* key, unsigned char* id, int len, void* heap, if (ret == 0 && (len < 0 || len > ECC_MAX_ID_LEN)) ret = BUFFER_E; +#if defined(HAVE_PKCS11) + XMEMSET(key, 0, sizeof(ecc_key)); + key->isPkcs11 = 1; +#endif + if (ret == 0) ret = wc_ecc_init_ex(key, heap, devId); if (ret == 0 && id != NULL && len != 0) { @@ -5947,6 +5968,11 @@ int wc_ecc_init_label(ecc_key* key, const char* label, void* heap, int devId) ret = BUFFER_E; } +#if defined(HAVE_PKCS11) + XMEMSET(key, 0, sizeof(ecc_key)); + key->isPkcs11 = 1; +#endif + if (ret == 0) ret = wc_ecc_init_ex(key, heap, devId); if (ret == 0) { diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index f667ebc88f2..c756d8ee2f1 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -267,12 +267,21 @@ static void wc_RsaCleanup(RsaKey* key) int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) { - int ret = 0; + int ret = 0; +#if defined(HAVE_PKCS11) + int isPkcs11 = 0; +#endif if (key == NULL) { return BAD_FUNC_ARG; } +#if defined(HAVE_PKCS11) + if (key->isPkcs11) { + isPkcs11 = 1; + } +#endif + XMEMSET(key, 0, sizeof(RsaKey)); key->type = RSA_TYPE_UNKNOWN; @@ -299,12 +308,19 @@ int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) #endif #ifdef WC_ASYNC_ENABLE_RSA - /* handle as async */ - ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA, - key->heap, devId); - if (ret != 0) - return ret; + #if defined(HAVE_PKCS11) + if (!isPkcs11) + #endif + { + /* handle as async */ + ret = wolfAsync_DevCtxInit(&key->asyncDev, + WOLFSSL_ASYNC_MARKER_RSA, key->heap, devId); + if (ret != 0) + return ret; + } #endif /* WC_ASYNC_ENABLE_RSA */ +#elif defined(HAVE_PKCS11) + (void)isPkcs11; #endif /* WOLFSSL_ASYNC_CRYPT */ #ifndef WOLFSSL_RSA_PUBLIC_ONLY @@ -370,6 +386,11 @@ int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap, if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN)) ret = BUFFER_E; +#if defined(HAVE_PKCS11) + XMEMSET(key, 0, sizeof(RsaKey)); + key->isPkcs11 = 1; +#endif + if (ret == 0) ret = wc_InitRsaKey_ex(key, heap, devId); if (ret == 0 && id != NULL && len != 0) { @@ -400,6 +421,11 @@ int wc_InitRsaKey_Label(RsaKey* key, const char* label, void* heap, int devId) ret = BUFFER_E; } +#if defined(HAVE_PKCS11) + XMEMSET(key, 0, sizeof(RsaKey)); + key->isPkcs11 = 1; +#endif + if (ret == 0) ret = wc_InitRsaKey_ex(key, heap, devId); if (ret == 0) { diff --git a/wolfssl/wolfcrypt/ecc.h b/wolfssl/wolfcrypt/ecc.h index 8bb07f60e07..09f5492bec4 100644 --- a/wolfssl/wolfcrypt/ecc.h +++ b/wolfssl/wolfcrypt/ecc.h @@ -504,6 +504,9 @@ struct ecc_key { #if defined(PLUTON_CRYPTO_ECC) || defined(WOLF_CRYPTO_CB) int devId; #endif +#if defined(HAVE_PKCS11) + byte isPkcs11 : 1; /* indicate if PKCS11 is preferred */ +#endif #ifdef WOLFSSL_SILABS_SE_ACCEL sl_se_command_context_t cmd_ctx; sl_se_key_descriptor_t key; diff --git a/wolfssl/wolfcrypt/rsa.h b/wolfssl/wolfcrypt/rsa.h index 3af61899576..a904c8a662b 100644 --- a/wolfssl/wolfcrypt/rsa.h +++ b/wolfssl/wolfcrypt/rsa.h @@ -215,6 +215,9 @@ struct RsaKey { #ifdef WOLF_CRYPTO_CB int devId; #endif +#if defined(HAVE_PKCS11) + byte isPkcs11 : 1; /* indicate if PKCS11 is preferred */ +#endif #ifdef WOLFSSL_ASYNC_CRYPT WC_ASYNC_DEV asyncDev; #ifdef WOLFSSL_CERT_GEN From 2885b334d259ac44167de8bd7cbacc768624e163 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Fri, 12 May 2023 13:24:21 +0200 Subject: [PATCH 272/391] Small fixes to build wolfSSL without warnings --- zephyr/CMakeLists.txt | 3 +-- zephyr/zephyr_init.c | 20 +------------------- 2 files changed, 2 insertions(+), 21 deletions(-) diff --git a/zephyr/CMakeLists.txt b/zephyr/CMakeLists.txt index cb9bb5c645d..36b19b953b4 100644 --- a/zephyr/CMakeLists.txt +++ b/zephyr/CMakeLists.txt @@ -6,7 +6,7 @@ if(CONFIG_WOLFSSL) WOLFSSL_SETTINGS_FILE="${CONFIG_WOLFSSL_SETTINGS_FILE}" ) - target_include_directories(wolfSSL INTERFACE + zephyr_include_directories( ${ZEPHYR_CURRENT_MODULE_DIR} ${ZEPHYR_CURRENT_MODULE_DIR}/wolfssl ${ZEPHYR_CURRENT_MODULE_DIR}/zephyr @@ -116,7 +116,6 @@ if(CONFIG_WOLFSSL) add_definitions(-DWOLFSSL_USER_SETTINGS) add_definitions(-DWOLFSSL_ZEPHYR) - include_directories("${ZEPHYR_CURRENT_MODULE_DIR}/wolfssl") else() assert(CONFIG_WOLFSSL_LIBRARY "wolfSSL was enabled, but neither BUILTIN or LIBRARY was selected.") diff --git a/zephyr/zephyr_init.c b/zephyr/zephyr_init.c index 9ec82e2d4ed..cd8ae98e6d1 100644 --- a/zephyr/zephyr_init.c +++ b/zephyr/zephyr_init.c @@ -19,22 +19,4 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -/** @file - * @brief wolfSSL initialization - * - * Initialize the wolfSSL library. - */ - -#include - -#include "user_settings.h" -#include "wolfssl/ssl.h" - -static int _wolfssl_init(const struct device *device) -{ - ARG_UNUSED(device); - - return 0; -} - -SYS_INIT(_wolfssl_init, POST_KERNEL, 0); +/* Not needed. Keeping file for backwards compatibility. */ From f45e18a2eee36c15110fdabd4288d792c3b36056 Mon Sep 17 00:00:00 2001 From: Brett Nicholas Date: Thu, 11 May 2023 10:57:26 -0600 Subject: [PATCH 273/391] set pointer to null after freeing in InitOcspRequest() to prevent a subsequent double-free in FreeOcspRequest() --- wolfcrypt/src/asn.c | 1 + 1 file changed, 1 insertion(+) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 790b57bbda8..b9398462a0a 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -35260,6 +35260,7 @@ int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce, DYNAMIC_TYPE_OCSP_REQUEST); if (req->url == NULL) { XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP); + req->serial = NULL; return MEMORY_E; } From bf38dccd210b92978729d5d4ac4be381c67d7396 Mon Sep 17 00:00:00 2001 From: David Garske Date: Thu, 11 May 2023 11:38:12 -0700 Subject: [PATCH 274/391] Remove always true check. --- wolfcrypt/src/port/st/stm32.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index ad64ec2cb87..411ee4a3f26 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -318,7 +318,7 @@ int wc_Stm32_Hash_Update(STM32_HASH_Context* stmCtx, word32 algo, } #endif - if (len >= 0 && stmCtx->buffLen == chunkSz) { + if (stmCtx->buffLen == chunkSz) { wc_Stm32_Hash_Data(stmCtx, stmCtx->buffLen); wroteToFifo = 1; #ifdef STM32_HASH_FIFO_WORKAROUND From 7d971087b16d13def411accf7a63e4b8f9d37298 Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Fri, 14 Apr 2023 06:10:35 +0900 Subject: [PATCH 275/391] Add SCE RSA Crypt Only feature - RSA SSA 1024/2048 Sign/verify - RSA ES 1024/2048 Enc/Dec - Unit test for these RSA operation --- IDE/Renesas/e2studio/RA6M4/README.md | 30 +- .../e2studio/RA6M4/common/user_settings.h | 4 + .../RA6M4/test/key_data/key_data_sce.c | 104 ++--- .../e2studio/RA6M4/test/src/test_main.c | 91 +++- .../RA6M4/test/src/wolfssl_sce_unit_test.c | 228 +++++++++- IDE/Renesas/e2studio/RA6M4/wolfssl/.project | 5 + wolfcrypt/src/include.am | 1 + wolfcrypt/src/port/Renesas/renesas_common.c | 112 +++-- wolfcrypt/src/port/Renesas/renesas_sce_aes.c | 38 +- wolfcrypt/src/port/Renesas/renesas_sce_rsa.c | 430 ++++++++++++++++++ wolfcrypt/src/port/Renesas/renesas_sce_sha.c | 3 +- wolfcrypt/src/port/Renesas/renesas_sce_util.c | 20 +- wolfcrypt/src/random.c | 3 +- wolfcrypt/src/rsa.c | 28 +- wolfcrypt/src/sha256.c | 9 +- wolfcrypt/src/wc_port.c | 6 +- wolfcrypt/test/test.c | 7 +- wolfssl/wolfcrypt/aes.h | 3 +- .../port/Renesas/renesas-sce-crypt.h | 73 ++- wolfssl/wolfcrypt/sha256.h | 3 +- 20 files changed, 1032 insertions(+), 166 deletions(-) create mode 100644 wolfcrypt/src/port/Renesas/renesas_sce_rsa.c diff --git a/IDE/Renesas/e2studio/RA6M4/README.md b/IDE/Renesas/e2studio/RA6M4/README.md index c9658ad9d7a..629d72cf022 100644 --- a/IDE/Renesas/e2studio/RA6M4/README.md +++ b/IDE/Renesas/e2studio/RA6M4/README.md @@ -30,21 +30,21 @@ The wolfssl Project Summary is listed below and is relevant for every project. |Components|Version| |:--|:--| -|Board Support Package Common Files|v3.5.0| -|Secure Cryptography Engine on RA6 Protected Mode|v3.5.0| -|I/O Port|v3.5.0| -|Arm CMSIS Version 5 - Core (M)|v5.8.0+fsp.3.5.0| +|Board Support Package Common Files|v3.6.0| +|Secure Cryptography Engine on RA6 Protected Mode|v3.6.0| +|I/O Port|v3.6.0| +|Arm CMSIS Version 5 - Core (M)|v5.8.0+fsp.3.6.0| |RA6M4-EK Board Support Files|v3.5.0| -|Board support package for R7FA6M4AF3CFB|v3.5.0| -|Board support package for RA6M4|v3.5.0| -|Board support package for RA6M4 - FSP Data|v3.5.0| -|FreeRTOS|v10.4.3-LTS.Patch.2+fsp.3.5.0| -|FreeRTOS - Memory Management - Heap 4|v10.4.3-LTS.Patch.2+fsp.3.5.0| -|r_ether to FreeRTOS+TCP Wrapper|v3.5.0| -|Ethernet|v3.5.0| -|Ethernet PHY|v3.5.0| -|FreeRTOS+TCP|v2.3.2-LTS.Patch.1+fsp.3.5.0| -|FreeRTOS - Buffer Allocation 2|v2.3.2-LTS.Patch.1+fsp.3.5.0| +|Board support package for R7FA6M4AF3CFB|v3.6.0| +|Board support package for RA6M4|v3.6.0| +|Board support package for RA6M4 - FSP Data|v3.6.0| +|FreeRTOS|v10.4.3-LTS.Patch.2+fsp.3.6.0| +|FreeRTOS - Memory Management - Heap 4|v10.4.3-LTS.Patch.2+fsp.3.6.0| +|r_ether to FreeRTOS+TCP Wrapper|v3.6.0| +|Ethernet|v3.6.0| +|Ethernet PHY|v3.6.0| +|FreeRTOS+TCP|v2.3.2-LTS.Patch.1+fsp.3.6.0| +|FreeRTOS - Buffer Allocation 2|v2.3.2-LTS.Patch.1+fsp.3.6.0| ## Setup Steps and Build wolfSSL Library @@ -168,7 +168,7 @@ $./examples/server/server -b -d -i ECDSA sign and verify use, launch server with the following option ``` -$./examples/server/server -b -d -c -i ./certs/server-ecc.pem -k ./certs/ecc-key.pem +$./examples/server/server -b -d -i -c ./certs/server-ecc.pem -k ./certs/ecc-key.pem ``` 5.) Run the example Client diff --git a/IDE/Renesas/e2studio/RA6M4/common/user_settings.h b/IDE/Renesas/e2studio/RA6M4/common/user_settings.h index 258ca429230..38345055a0c 100644 --- a/IDE/Renesas/e2studio/RA6M4/common/user_settings.h +++ b/IDE/Renesas/e2studio/RA6M4/common/user_settings.h @@ -78,3 +78,7 @@ #if defined(WOLFSSL_RENESAS_SCEPROTECT) && defined(SCEKEY_INSTALLED) #define HAVE_RENESAS_SYNC #endif + +#if defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + #define WOLFSSL_KEY_GEN +#endif diff --git a/IDE/Renesas/e2studio/RA6M4/test/key_data/key_data_sce.c b/IDE/Renesas/e2studio/RA6M4/test/key_data/key_data_sce.c index af95a854afa..45e9de19556 100644 --- a/IDE/Renesas/e2studio/RA6M4/test/key_data/key_data_sce.c +++ b/IDE/Renesas/e2studio/RA6M4/test/key_data/key_data_sce.c @@ -72,32 +72,32 @@ const st_user_key_block_data_t g_key_block_data = * This is used for Root Certificate verify by SCE */ const unsigned char ca_cert_der_sign[] = { - 0x0E, 0x7F, 0xB2, 0x0B, 0x4E, 0x8C, 0x11, 0x5E, 0xAC, 0xD7, - 0x77, 0x3D, 0x9E, 0xA0, 0x4B, 0xA5, 0xE2, 0x9F, 0x97, 0xEB, - 0xD0, 0x1B, 0x65, 0x08, 0x7D, 0x39, 0x2E, 0xD0, 0x97, 0x19, - 0xB6, 0x47, 0xF4, 0xCC, 0xA0, 0x24, 0xFA, 0xA6, 0x08, 0x11, - 0xF4, 0xDC, 0x82, 0xCC, 0xB6, 0x14, 0xF1, 0x4A, 0x63, 0x67, - 0xF2, 0x87, 0x0C, 0xA9, 0x31, 0x03, 0xAF, 0xD5, 0x4B, 0x1B, - 0xD9, 0x99, 0x6E, 0xB4, 0xBD, 0xAB, 0x7F, 0x64, 0xB8, 0x8B, - 0xFF, 0x45, 0xFC, 0xE5, 0x86, 0xE8, 0x95, 0x4E, 0xBD, 0x7F, - 0x21, 0xB5, 0xCD, 0x25, 0x85, 0x16, 0x32, 0x6C, 0x8A, 0xC5, - 0xE7, 0xEB, 0x58, 0xA8, 0xCC, 0xD2, 0x33, 0xFC, 0xBB, 0x88, - 0xBC, 0x15, 0xDB, 0xDD, 0x6B, 0x15, 0xE3, 0x43, 0x31, 0xA9, - 0xA2, 0x2E, 0x9C, 0x8C, 0x44, 0x69, 0x1A, 0x72, 0x49, 0xAD, - 0x94, 0x8B, 0xD9, 0xA7, 0x47, 0x91, 0xA1, 0xF0, 0xAA, 0xA4, - 0xAB, 0x5B, 0xC9, 0x8F, 0x48, 0xFE, 0x6B, 0x06, 0x7A, 0xF0, - 0xC0, 0x39, 0xEF, 0xF1, 0x38, 0x96, 0x03, 0xC8, 0xDC, 0xBE, - 0xF7, 0xDB, 0xBA, 0x09, 0xA4, 0x62, 0xD1, 0x39, 0xAD, 0x1D, - 0xEB, 0x28, 0x85, 0x53, 0x76, 0xF2, 0x52, 0x3B, 0x26, 0xF2, - 0x16, 0x01, 0xB0, 0xEF, 0x2B, 0x09, 0x2F, 0x30, 0x17, 0x6F, - 0x04, 0x5C, 0x75, 0xE5, 0x7D, 0xD0, 0xCB, 0x84, 0xDE, 0xEB, - 0x24, 0x45, 0x3D, 0x3A, 0x56, 0xC4, 0x64, 0x63, 0xD9, 0x00, - 0x23, 0x5F, 0xEE, 0xD9, 0x2E, 0xA9, 0xDC, 0x94, 0xA7, 0x8D, - 0xB6, 0xD9, 0xDF, 0x96, 0x8F, 0x8B, 0x81, 0x83, 0x8A, 0x8E, - 0x36, 0x45, 0xC7, 0xB7, 0x59, 0xA0, 0x9D, 0xE8, 0xFE, 0x62, - 0x5C, 0x7A, 0xF2, 0x9E, 0xF9, 0xB6, 0x75, 0x46, 0x44, 0x6D, - 0x96, 0xFC, 0x3E, 0xE2, 0x17, 0x52, 0x0D, 0x70, 0x37, 0xD9, - 0xAE, 0x1D, 0x25, 0x30, 0xF7, 0xD9 + 0x19, 0xB4, 0xD1, 0x53, 0xBB, 0x87, 0x0B, 0xD8, 0xD8, 0xFC, + 0x22, 0x21, 0xA6, 0xC1, 0xE5, 0xB2, 0x7A, 0xEF, 0xAF, 0x89, + 0x8B, 0x92, 0xC9, 0x4E, 0x59, 0xF0, 0x0B, 0xAB, 0x24, 0x84, + 0x60, 0x2D, 0x81, 0x42, 0x4A, 0x05, 0x2F, 0x2D, 0xAB, 0x20, + 0x3F, 0x8D, 0xCA, 0x9F, 0x37, 0x4B, 0xDF, 0xE3, 0x2A, 0xA3, + 0x3F, 0x4E, 0x09, 0x20, 0x08, 0xD4, 0x46, 0xD9, 0xF0, 0xD8, + 0xA7, 0x43, 0x60, 0xE2, 0x1D, 0xF7, 0x25, 0x64, 0x38, 0xD2, + 0xB1, 0x4E, 0x1F, 0x84, 0xFC, 0xC5, 0x55, 0x2C, 0x1A, 0xA2, + 0xCE, 0x99, 0xD0, 0x21, 0x93, 0xA5, 0xDB, 0x6F, 0x14, 0x2C, + 0xDF, 0x9A, 0x01, 0x6A, 0x9A, 0xCC, 0xB0, 0x08, 0xD8, 0xCF, + 0xA8, 0x94, 0x41, 0x23, 0xBB, 0xC2, 0xA3, 0x8B, 0x77, 0x35, + 0x27, 0x0D, 0x94, 0x16, 0xF3, 0xCA, 0x16, 0xA2, 0x4C, 0x2F, + 0xB0, 0x8D, 0xE6, 0x38, 0xCC, 0x9C, 0x34, 0xE8, 0xDC, 0xDC, + 0x1C, 0x5C, 0x88, 0x52, 0x97, 0x47, 0xC6, 0xB6, 0x66, 0xCF, + 0xCE, 0xBF, 0xF0, 0x24, 0x19, 0x0F, 0x07, 0xA5, 0xC4, 0xC6, + 0x37, 0x0D, 0x2A, 0x11, 0x6A, 0x66, 0x64, 0x62, 0x0E, 0xE6, + 0xCB, 0xAF, 0xFB, 0x2E, 0x8E, 0x37, 0x1E, 0x6D, 0xD1, 0xAD, + 0xE4, 0x16, 0x06, 0xFB, 0x43, 0x2E, 0x4D, 0x64, 0x18, 0xB2, + 0x4C, 0xE7, 0xD3, 0xE9, 0x9B, 0x95, 0x13, 0x7D, 0x7D, 0x93, + 0xC2, 0x34, 0x43, 0x0C, 0xFF, 0x58, 0xD3, 0xA7, 0x21, 0x8E, + 0x2B, 0xB3, 0x36, 0x90, 0xF1, 0x1E, 0x0E, 0x87, 0x41, 0x48, + 0xC9, 0x69, 0x57, 0x89, 0xD0, 0xF7, 0x86, 0x47, 0x8F, 0xF5, + 0xA8, 0x13, 0x24, 0x0A, 0x7E, 0xE3, 0xBB, 0x9F, 0xF1, 0xDF, + 0x30, 0xE7, 0x88, 0x70, 0x8A, 0x46, 0xD9, 0x1A, 0x50, 0x42, + 0x4F, 0xCF, 0xC3, 0xCB, 0xCF, 0xE4, 0xA7, 0xA3, 0x74, 0x0A, + 0xDE, 0x14, 0xAF, 0xA5, 0x7F, 0xE2 }; const int sizeof_ca_cert_der_sign = sizeof(ca_cert_der_sign); @@ -108,32 +108,32 @@ const int sizeof_ca_cert_der_sign = sizeof(ca_cert_der_sign); */ const unsigned char ca_ecc_cert_der_sign[] = { - 0x41, 0xFC, 0x2C, 0xFD, 0x21, 0xFB, 0xF2, 0x98, 0xF3, 0x25, - 0x06, 0x8C, 0x2C, 0x4A, 0x12, 0xDB, 0xDD, 0x38, 0x39, 0x83, - 0xD5, 0x80, 0xB4, 0x52, 0xA5, 0x35, 0xA6, 0x5C, 0x38, 0x41, - 0xDA, 0xBE, 0x64, 0x84, 0x7C, 0x63, 0x7D, 0x2A, 0xBB, 0xB9, - 0x93, 0xED, 0x27, 0xE3, 0x2B, 0xAB, 0xC4, 0xBC, 0x08, 0xBE, - 0xA6, 0xF7, 0x40, 0xA3, 0x1E, 0xB1, 0x8C, 0xF8, 0x4B, 0x78, - 0x9F, 0xFE, 0xAA, 0x86, 0x15, 0xF5, 0xDD, 0xB3, 0xCD, 0xF5, - 0x3A, 0x81, 0x26, 0x3E, 0x04, 0x05, 0x65, 0xF9, 0x53, 0x8E, - 0x10, 0x1F, 0xE8, 0xD9, 0x3F, 0xA1, 0x6E, 0x8C, 0xAD, 0xFA, - 0x50, 0x36, 0xFE, 0x89, 0x4E, 0xAC, 0x27, 0xDB, 0x59, 0x80, - 0xE3, 0x77, 0x20, 0x4F, 0xC1, 0x03, 0xA4, 0x1D, 0xE5, 0x34, - 0xCB, 0x8F, 0x88, 0xD6, 0x38, 0x2A, 0x31, 0xE0, 0xC2, 0xAA, - 0x78, 0x34, 0x9C, 0xFE, 0x8F, 0x8D, 0x76, 0xDB, 0x24, 0x38, - 0xE1, 0xAB, 0xAE, 0xBA, 0xD0, 0xA9, 0x1C, 0x59, 0x01, 0xE3, - 0x49, 0x9B, 0x13, 0x7D, 0x25, 0x7C, 0x8D, 0x12, 0x36, 0xA1, - 0xEF, 0x7B, 0xD4, 0x16, 0x58, 0x3A, 0x0E, 0xE7, 0x5A, 0x36, - 0xDD, 0xD4, 0x31, 0x23, 0xBF, 0xC9, 0x49, 0x62, 0xA4, 0x01, - 0xA3, 0xAC, 0x62, 0xAB, 0xA0, 0x48, 0xE3, 0xDA, 0x72, 0xD3, - 0x6D, 0xF3, 0x57, 0x61, 0x9E, 0xEA, 0x31, 0xA7, 0x82, 0xDD, - 0x79, 0x3C, 0x8E, 0x01, 0xE9, 0xE5, 0xB2, 0x49, 0x2F, 0x3F, - 0x3F, 0x16, 0x2C, 0xCC, 0x3D, 0x78, 0x6E, 0xB6, 0x6D, 0x34, - 0x38, 0x46, 0xCC, 0xFF, 0xEF, 0x26, 0x74, 0xD8, 0x68, 0x90, - 0xF1, 0x2A, 0xAA, 0xF3, 0xF3, 0x5A, 0xFC, 0x75, 0x00, 0xE6, - 0x11, 0xE7, 0x21, 0x05, 0x6B, 0xAA, 0x53, 0x25, 0x59, 0x33, - 0xB0, 0xC0, 0x66, 0x14, 0x2F, 0x00, 0x59, 0xF3, 0xFF, 0x5E, - 0xCC, 0x10, 0x84, 0x0E, 0xE6, 0x17 + 0x66, 0x96, 0xB4, 0x9F, 0x0B, 0x56, 0x60, 0x1F, 0x01, 0x7A, + 0xDE, 0x65, 0xD6, 0x8C, 0x2A, 0xE2, 0x20, 0xA0, 0xE8, 0x19, + 0x99, 0x70, 0x8B, 0x17, 0x1B, 0xDA, 0x8C, 0x3A, 0x87, 0x07, + 0xE7, 0xF9, 0x1B, 0x7C, 0xC1, 0x32, 0x55, 0x38, 0x15, 0x9C, + 0x7B, 0x89, 0xDA, 0x9D, 0x57, 0x80, 0x50, 0xCF, 0xA6, 0x4C, + 0x51, 0x71, 0xBA, 0x52, 0xFA, 0x58, 0x4C, 0xE7, 0x33, 0x08, + 0xB9, 0xE7, 0x5F, 0x7E, 0x8A, 0x1D, 0xCC, 0xA8, 0x4A, 0xA9, + 0xAF, 0xE5, 0xA1, 0x87, 0x59, 0xD0, 0xF7, 0x23, 0xAE, 0xC5, + 0x42, 0x99, 0xFA, 0x4A, 0xAB, 0xFA, 0x08, 0xF9, 0x7C, 0x8D, + 0xD3, 0xB1, 0xF7, 0xD8, 0x01, 0x3C, 0x06, 0xD5, 0x2C, 0xBF, + 0x18, 0xF1, 0x45, 0x47, 0x5D, 0xA4, 0x7F, 0x90, 0x4E, 0x0C, + 0x86, 0x41, 0x5F, 0x26, 0x25, 0x8B, 0x8A, 0xD8, 0x3F, 0x4B, + 0xAF, 0xD5, 0xBE, 0xD9, 0xC6, 0x46, 0x2A, 0x2B, 0xC3, 0x10, + 0x93, 0xCB, 0x1E, 0xFB, 0x3D, 0x8A, 0x39, 0xB6, 0x03, 0x9D, + 0xC2, 0x16, 0xA1, 0xB5, 0x9C, 0x0D, 0x05, 0x5E, 0x1B, 0x30, + 0x9F, 0x53, 0xEE, 0xF2, 0x27, 0xE1, 0xE3, 0x2F, 0xD9, 0xEB, + 0xF2, 0xFE, 0xD3, 0x6C, 0x71, 0xCE, 0x28, 0x56, 0x9F, 0x85, + 0x34, 0xAD, 0x9D, 0x3D, 0x22, 0x3A, 0x33, 0x3B, 0x9F, 0x55, + 0x4F, 0x10, 0xA9, 0xD2, 0xAB, 0xE0, 0x29, 0x7A, 0x09, 0xF3, + 0x4E, 0xC1, 0x21, 0xA7, 0xF4, 0xE5, 0x34, 0x6D, 0x68, 0x36, + 0xE9, 0x7B, 0xD4, 0x42, 0x0A, 0xBC, 0xC4, 0x1F, 0x6C, 0x58, + 0xB6, 0x65, 0x3F, 0x9F, 0x92, 0x65, 0xF9, 0x83, 0x7A, 0x94, + 0x66, 0x7C, 0xB2, 0x03, 0x16, 0x65, 0x9E, 0xBF, 0x8C, 0x77, + 0xB8, 0xA4, 0x13, 0x8B, 0xD3, 0x82, 0x39, 0x94, 0xD1, 0x2A, + 0xE3, 0x3E, 0x51, 0xEB, 0x56, 0xE2, 0x92, 0x5C, 0x6B, 0xD1, + 0x30, 0xD1, 0x91, 0x77, 0x6E, 0x28 }; static const int sizeof_ca_ecc_cert_der_sign = sizeof(ca_ecc_cert_der_sign); #endif /* USE_CERT_BUFFERS_256 */ diff --git a/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c b/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c index 68d2b8590d7..88f05889f2b 100644 --- a/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c +++ b/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c @@ -25,7 +25,8 @@ #include #include -#if defined(WOLFSSL_RENESAS_SCEPROTECT) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || \ +defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #include #if defined(TLS_MULTITHREAD_TEST) User_SCEPKCbInfo guser_PKCbInfo_taskA; @@ -127,10 +128,42 @@ static void my_Logging_cb(const int logLevel, const char *const logMessage) } #endif +void Clr_CallbackCtx(User_SCEPKCbInfo *g) +{ + if (g->sce_wrapped_key_aes256 != NULL) + XFREE(g->sce_wrapped_key_aes256, + NULL, DYNAMIC_TYPE_TMP_BUFFER); + + if (g->sce_wrapped_key_aes128 != NULL) + XFREE(g->sce_wrapped_key_aes256, + NULL, DYNAMIC_TYPE_TMP_BUFFER); + + #if defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + if (g->sce_wrapped_key_rsapri2048 != NULL) + XFREE(g->sce_wrapped_key_rsapri2048, + NULL, DYNAMIC_TYPE_TMP_BUFFER); + + if (g->sce_wrapped_key_rsapub2048 != NULL) + XFREE(g->sce_wrapped_key_rsapub2048, + NULL, DYNAMIC_TYPE_TMP_BUFFER); + + if (g->sce_wrapped_key_rsapri1024 != NULL) + XFREE(g->sce_wrapped_key_rsapri1024, + NULL, DYNAMIC_TYPE_TMP_BUFFER); + + if (g->sce_wrapped_key_rsapub2048 != NULL) + XFREE(g->sce_wrapped_key_rsapub1024, + NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + XMEMSET(g, 0, sizeof(User_SCEPKCbInfo)); +} + void sce_test(void) { -#if defined(SCE_CRYPT_UNIT_TEST) && defined(WOLFSSL_RENESAS_SCEPROTECT) +#if defined(SCE_CRYPT_UNIT_TEST) && \ + (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) int ret = 0; BaseType_t xRet; @@ -169,7 +202,9 @@ void sce_test(void) printf("wolfCrypt_Cleanup failed %d\n", ret); } -#elif defined(CRYPT_TEST) +#elif defined(CRYPT_TEST) && \ + (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) int ret; func_args args = { 0 }; @@ -185,7 +220,9 @@ void sce_test(void) printf("wolfCrypt_Cleanup failed %d\n", ret); } -#elif defined(BENCHMARK) +#elif defined(BENCHMARK) && \ + (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) #include "hal_data.h" #include "r_sce.h" @@ -194,20 +231,38 @@ void sce_test(void) #if defined(WOLFSSL_RENESAS_SCEPROTECT) && defined(SCEKEY_INSTALLED) /* aes 256 */ - memcpy(guser_PKCbInfo.sce_wrapped_key_aes256.value, - (uint32_t *)DIRECT_KEY_ADDRESS_256, - HW_SCE_AES256_KEY_INDEX_WORD_SIZE*4); - guser_PKCbInfo.sce_wrapped_key_aes256.type = SCE_KEY_INDEX_TYPE_AES256; - guser_PKCbInfo.aes256_installedkey_set = 1; - - /* aes 128 */ - memcpy(guser_PKCbInfo.sce_wrapped_key_aes128.value, - (uint32_t *)DIRECT_KEY_ADDRESS_128, - HW_SCE_AES128_KEY_INDEX_WORD_SIZE*4); - - guser_PKCbInfo.sce_wrapped_key_aes128.type = SCE_KEY_INDEX_TYPE_AES128; - guser_PKCbInfo.aes128_installedkey_set = 1; - + XMEMSET(&guser_PKCbInfo, 0, sizeof(guser_PKCbInfo)); + sce_aes_wrapped_key_t *p1 = NULL; + sce_aes_wrapped_key_t *p2 = NULL; + + guser_PKCbInfo.sce_wrapped_key_aes256 = + (sce_aes_wrapped_key_t*)XMALLOC(sizeof(sce_aes_wrapped_key_t), + NULL, DYNAMIC_TYPE_TMP_BUFFER); + p1 = (sce_aes_wrapped_key_t*)guser_PKCbInfo.sce_wrapped_key_aes256; + + guser_PKCbInfo.sce_wrapped_key_aes128 = + (sce_aes_wrapped_key_t*)XMALLOC(sizeof(sce_aes_wrapped_key_t), + NULL, DYNAMIC_TYPE_TMP_BUFFER); + p2 = (sce_aes_wrapped_key_t*)guser_PKCbInfo.sce_wrapped_key_aes128; + + if ( p1 == NULL || p2 == NULL) { + printf("failed to alloc memory!"); + } + else { + memcpy(p1->value, + (uint32_t *)DIRECT_KEY_ADDRESS_256, + HW_SCE_AES256_KEY_INDEX_WORD_SIZE*4); + p1->type = SCE_KEY_INDEX_TYPE_AES256; + guser_PKCbInfo.flags2.bits.aes256_installedkey_set = 1; + + /* aes 128 */ + memcpy(p2->value, + (uint32_t *)DIRECT_KEY_ADDRESS_128, + HW_SCE_AES128_KEY_INDEX_WORD_SIZE*4); + + p2->type = SCE_KEY_INDEX_TYPE_AES128; + guser_PKCbInfo.flags2.bits.aes128_installedkey_set = 1; + } #endif printf("Start wolfCrypt Benchmark\n"); benchmark_test(NULL); diff --git a/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c b/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c index b840645b79f..996ed642569 100644 --- a/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c +++ b/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c @@ -28,6 +28,7 @@ #include #include #include +#include #include #include "FreeRTOS.h" @@ -62,6 +63,8 @@ int sce_crypt_Sha_AesCbcGcm_multitest(); int sce_crypt_sha_multitest(); int sce_crypt_test(); +extern User_SCEPKCbInfo guser_PKCbInfo; + #if defined(HAVE_AES_CBC) #if defined(WOLFSSL_AES_128) @@ -76,6 +79,9 @@ int sce_crypt_test(); #endif +#if !defined(NO_RSA) + sce_rsa2048_wrapped_pair_key_t g_wrapped_pair_key; +#endif typedef struct tagInfo { sce_aes_wrapped_key_t aes_key; @@ -379,9 +385,8 @@ static int sce_aesgcm256_test(int prnt, sce_aes_wrapped_key_t* aes256_key) ret = -3; goto out; } else { - XMEMCPY(&userContext.sce_wrapped_key_aes256, aes256_key, - sizeof(sce_aes_wrapped_key_t)); - userContext.aes256_installedkey_set = 1; + userContext.sce_wrapped_key_aes256 = (void*)aes256_key; + userContext.flags2.bits.aes256_installedkey_set = 1; enc->ctx.keySize = (word32)enc->keylen; } @@ -576,9 +581,8 @@ static int sce_aesgcm128_test(int prnt, sce_aes_wrapped_key_t* aes128_key) ret = -3; goto out; } else { - XMEMCPY(&userContext.sce_wrapped_key_aes128, aes128_key, - sizeof(sce_aes_wrapped_key_t)); - userContext.aes128_installedkey_set = 1; + userContext.sce_wrapped_key_aes128 = aes128_key; + userContext.flags2.bits.aes128_installedkey_set = 1; enc->ctx.keySize = (word32)enc->keylen; } /* AES-GCM encrypt and decrypt both use AES encrypt internally */ @@ -634,6 +638,170 @@ static void tskAes128_Gcm_Test(void *pvParam) #endif +#if !defined(NO_RSA) + +/* testing rsa sign/verify w/ rsa 2048 bit key */ +#define TEST_STRING "Everyone gets Friday off." +#define TEST_STRING2 "Everyone gets Friday ofv." +#define TEST_STRING_SZ 25 +#define RSA_TEST_BYTES 256 /* up to 2048-bit key */ + +static int sce_rsa_test(int prnt, int keySize) +{ + int ret = 0; + + RsaKey *key = (RsaKey *)XMALLOC(sizeof *key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + WC_RNG rng; + const char inStr [] = TEST_STRING; + const char inStr2[] = TEST_STRING2; + const word32 inLen = (word32)TEST_STRING_SZ; + const word32 outSz = RSA_TEST_BYTES; + + byte *in = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + byte *in2 = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + byte *out= (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + byte *out2 = (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + + if (key == NULL || in == NULL || out == NULL || + in2 == NULL || out2 == NULL) { + ret = -1; + goto out; + } + + XMEMSET(&rng, 0, sizeof(rng)); + XMEMSET(key, 0, sizeof *key); + XMEMCPY(in, inStr, inLen); + XMEMCPY(in2, inStr2, inLen); + XMEMSET(out, 0, outSz); + XMEMSET(out2, 0, outSz); + + ret = wc_InitRsaKey_ex(key, NULL, 7890/* fixed devid for TSIP/SCE*/); + if (ret != 0) { + goto out; + } + + if ((ret = wc_InitRng(&rng)) != 0) + goto out; + + /* make ras key by SCE */ + if ((ret = wc_MakeRsaKey(key, keySize, 65537, &rng)) != 0) { + goto out; + } + + ret = wc_RsaPublicEncrypt(in, inLen, out, outSz, key, &rng); + if (ret < 0) { + goto out; + } + + ret = wc_RsaPrivateDecrypt(out, keySize/8, out2, outSz, key); + if (ret != 0) { + ret = -1; + goto out; + } + if (XMEMCMP(in, out2, inLen) != 0) { + ret = -2; + goto out; + } + +out: + if (key != NULL) { + wc_FreeRsaKey(key); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (in != NULL) { + XFREE(in, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (in2 != NULL) { + XFREE(in2, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (out != NULL) { + XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (out2 != NULL) { + XFREE(out2, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + + return ret; +} + +static int sce_rsa_SignVerify_test(int prnt, int keySize) +{ + int ret = 0; + + RsaKey *key = (RsaKey *)XMALLOC(sizeof *key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + WC_RNG rng; + const char inStr [] = TEST_STRING; + const char inStr2[] = TEST_STRING2; + const word32 inLen = (word32)TEST_STRING_SZ; + const word32 outSz = RSA_TEST_BYTES; + + byte *in = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + byte *in2 = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + byte *out= (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + + (void) prnt; + + if (key == NULL || in == NULL || out == NULL) { + ret = -1; + goto out; + } + + XMEMSET(&rng, 0, sizeof(rng)); + XMEMSET(key, 0, sizeof *key); + XMEMCPY(in, inStr, inLen); + XMEMCPY(in2, inStr2, inLen); + + ret = wc_InitRsaKey_ex(key, NULL, 7890/* fixed devid for TSIP/SCE*/); + if (ret != 0) { + goto out; + } + + if ((ret = wc_InitRng(&rng)) != 0) + goto out; + + /* make ras key by SCE */ + if ((ret = wc_MakeRsaKey(key, keySize, 65537, &rng)) != 0) { + goto out; + } + + guser_PKCbInfo.flags2.bits.message_type = 0; + ret = wc_RsaSSL_Sign(in, inLen, out, outSz, key, &rng); + if (ret < 0) { + goto out; + } + + /* this should fail */ + ret = wc_RsaSSL_Verify(in2, inLen, out, keySize/8, key); + if (ret != FSP_ERR_CRYPTO_SCE_AUTHENTICATION) { + ret = -1; + goto out; + } + /* this should succeed */ + ret = wc_RsaSSL_Verify(in, inLen, out, keySize/8, key); + if (ret != 0) { + ret = -1; + goto out; + } + + out: + if (key != NULL) { + wc_FreeRsaKey(key); + XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (in != NULL) { + XFREE(in, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (in2 != NULL) { + XFREE(in2, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (out != NULL) { + XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + + return ret; +} +#endif + int sce_crypt_test() { int ret = 0; @@ -641,20 +809,56 @@ int sce_crypt_test() /* Generate AES sce Key */ sce_error_code = R_SCE_AES128_WrappedKeyGenerate(&g_user_aes128_key_index1); - + if (sce_error_code == FSP_SUCCESS) sce_error_code = R_SCE_AES128_WrappedKeyGenerate( &g_user_aes128_key_index2); - + if (sce_error_code == FSP_SUCCESS) sce_error_code = R_SCE_AES256_WrappedKeyGenerate( &g_user_aes256_key_index1); - + if (sce_error_code == FSP_SUCCESS) sce_error_code = R_SCE_AES256_WrappedKeyGenerate( &g_user_aes256_key_index2); - - if (sce_error_code == FSP_SUCCESS) { + + if (sce_error_code == FSP_SUCCESS) { + #if defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + /* set up Crypt Call back */ + + Clr_CallbackCtx(&guser_PKCbInfo); + + ret = wc_CryptoCb_CryptInitRenesasCmn(NULL, &guser_PKCbInfo); + + if ( ret > 0) + ret = 0; + + if (ret == 0) { + printf(" sce_rsa_test(1024)"); + ret = sce_rsa_test(1, 1024); + RESULT_STR(ret) + } + if (ret == 0) { + printf(" sce_rsa_SignVerify_test(1024)"); + ret = sce_rsa_SignVerify_test(1, 1024); + RESULT_STR(ret) + } + + Clr_CallbackCtx(&guser_PKCbInfo); + + if (ret == 0) { + printf(" sce_rsa_test(2048)"); + ret = sce_rsa_test(1, 2048); + RESULT_STR(ret) + } + + if (ret == 0 && sce_error_code == FSP_SUCCESS) { + printf(" sce_rsa_SignVerify_test(2048)"); + ret = sce_rsa_SignVerify_test(1, 2048); + RESULT_STR(ret) + } + + #endif /* WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY */ #ifndef NO_SHA256 printf(" sha256_test()"); @@ -675,7 +879,7 @@ int sce_crypt_test() ret = sce_aesgcm128_test(1, &g_user_aes128_key_index1); } - + if (ret == 0) { ret = sce_aesgcm256_test(1, &g_user_aes256_key_index1); diff --git a/IDE/Renesas/e2studio/RA6M4/wolfssl/.project b/IDE/Renesas/e2studio/RA6M4/wolfssl/.project index 86682c55691..5c20248221f 100644 --- a/IDE/Renesas/e2studio/RA6M4/wolfssl/.project +++ b/IDE/Renesas/e2studio/RA6M4/wolfssl/.project @@ -401,6 +401,11 @@ 1 PARENT-5-PROJECT_LOC/wolfcrypt/src/port/Renesas/renesas_sce_aes.c + + wolfCrypt/port/renesas_sce_rsa.c + 1 + PARENT-5-PROJECT_LOC/wolfcrypt/src/port/Renesas/renesas_sce_rsa.c + wolfCrypt/port/renesas_sce_sha.c 1 diff --git a/wolfcrypt/src/include.am b/wolfcrypt/src/include.am index dc693883ae0..608b9356800 100644 --- a/wolfcrypt/src/include.am +++ b/wolfcrypt/src/include.am @@ -124,6 +124,7 @@ EXTRA_DIST += wolfcrypt/src/port/ti/ti-aes.c \ wolfcrypt/src/port/Renesas/renesas_sce_util.c \ wolfcrypt/src/port/Renesas/renesas_sce_aes.c \ wolfcrypt/src/port/Renesas/renesas_sce_sha.c \ + wolfcrypt/src/port/Renesas/renesas_sce_rsa.c \ wolfcrypt/src/port/Renesas/renesas_common.c \ wolfcrypt/src/port/Renesas/renesas_rx64_hw_sha.c \ wolfcrypt/src/port/Renesas/renesas_rx64_hw_util.c \ diff --git a/wolfcrypt/src/port/Renesas/renesas_common.c b/wolfcrypt/src/port/Renesas/renesas_common.c index 9246e726bfd..000123b01d4 100644 --- a/wolfcrypt/src/port/Renesas/renesas_common.c +++ b/wolfcrypt/src/port/Renesas/renesas_common.c @@ -21,9 +21,10 @@ #include -#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) \ + || defined(WOLFSSL_RENESAS_TSIP_TLS) -#if defined(WOLFSSL_RENESAS_SCEPROTECT) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #include #define cmn_hw_lock wc_sce_hw_lock #define cmn_hw_unlock wc_sce_hw_unlock @@ -128,7 +129,8 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) #if defined(WOLFSSL_RENESAS_TSIP_TLS) TsipUserCtx* cbInfo = (TsipUserCtx*)ctx; -#elif defined(WOLFSSL_RENESAS_SCEPROTECT) +#elif defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) User_SCEPKCbInfo* cbInfo = (User_SCEPKCbInfo*)ctx; #endif @@ -221,7 +223,8 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) } #endif /* HAVE_ECC */ } -#elif defined(WOLFSSL_RENESAS_SCEPROTECT) +#elif defined(WOLFSSL_RENESAS_SCEPROTECT) ||\ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) if (info->algo_type == WC_ALGO_TYPE_CIPHER) { @@ -230,13 +233,13 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) if (info->cipher.type == WC_CIPHER_AES_GCM) { if (info->cipher.enc && - (cbInfo->session_key_set == 1 || - (cbInfo->aes256_installedkey_set == 1 && + (cbInfo->flags1.bits.session_key_set == 1 || + (cbInfo->flags2.bits.aes256_installedkey_set == 1 && info->cipher.aesgcm_enc.aes->keylen == 32) || - (cbInfo->aes128_installedkey_set == 1 && + (cbInfo->flags2.bits.aes128_installedkey_set == 1 && info->cipher.aesgcm_enc.aes->keylen == 16))) { - if (cbInfo->aes256_installedkey_set == 1 && + if (cbInfo->flags2.bits.aes256_installedkey_set == 1 && info->cipher.aesgcm_enc.aes->keylen == 32) { XMEMCPY(&info->cipher.aesgcm_enc.aes->ctx.sce_wrapped_key, @@ -245,7 +248,7 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) info->cipher.aesgcm_enc.aes->ctx.keySize = 32; } - else if (cbInfo->aes128_installedkey_set == 1 && + else if (cbInfo->flags2.bits.aes128_installedkey_set == 1 && info->cipher.aesgcm_enc.aes->keylen == 16) { XMEMCPY(&info->cipher.aesgcm_enc.aes->ctx.sce_wrapped_key, @@ -268,13 +271,13 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) (void*)ctx); } - else if (cbInfo->session_key_set == 1 || - (cbInfo->aes256_installedkey_set == 1 && + else if (cbInfo->flags1.bits.session_key_set == 1 || + (cbInfo->flags2.bits.aes256_installedkey_set == 1 && info->cipher.aesgcm_dec.aes->keylen == 32) || - (cbInfo->aes128_installedkey_set == 1 && + (cbInfo->flags2.bits.aes128_installedkey_set == 1 && info->cipher.aesgcm_dec.aes->keylen == 16)) { - if (cbInfo->aes256_installedkey_set == 1 && + if (cbInfo->flags2.bits.aes256_installedkey_set == 1 && info->cipher.aesgcm_dec.aes->keylen == 32) { XMEMCPY(&info->cipher.aesgcm_dec.aes->ctx.sce_wrapped_key, @@ -283,7 +286,7 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) info->cipher.aesgcm_dec.aes->ctx.keySize = 32; } - else if (cbInfo->aes128_installedkey_set == 1 && + else if (cbInfo->flags2.bits.aes128_installedkey_set == 1 && info->cipher.aesgcm_dec.aes->keylen == 16) { XMEMCPY(&info->cipher.aesgcm_dec.aes->ctx.sce_wrapped_key, @@ -309,14 +312,14 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) #endif /* HAVE_AESGCM */ #ifdef HAVE_AES_CBC if ((info->cipher.type == WC_CIPHER_AES_CBC) && - (cbInfo->session_key_set == 1 || - (cbInfo->aes256_installedkey_set == 1 && + (cbInfo->flags1.bits.session_key_set == 1 || + (cbInfo->flags2.bits.aes256_installedkey_set == 1 && info->cipher.aescbc.aes->keylen == 32) || - (cbInfo->aes128_installedkey_set == 1 && + (cbInfo->flags2.bits.aes128_installedkey_set == 1 && info->cipher.aescbc.aes->keylen == 16))) { if (info->cipher.enc) { - if (cbInfo->aes256_installedkey_set == 1 && + if (cbInfo->flags2.bits.aes256_installedkey_set == 1 && info->cipher.aescbc.aes->keylen == 32) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes256, @@ -324,7 +327,7 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) info->cipher.aescbc.aes->ctx.keySize = 32; } - else if (cbInfo->aes128_installedkey_set == 1 && + else if (cbInfo->flags2.bits.aes128_installedkey_set == 1 && info->cipher.aescbc.aes->keylen == 16) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes128, @@ -339,14 +342,14 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) info->cipher.aescbc.sz); } else { - if (cbInfo->aes256_installedkey_set == 1 && + if (cbInfo->flags2.bits.aes256_installedkey_set == 1 && info->cipher.aescbc.aes->keylen == 32) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes256, sizeof(sce_aes_wrapped_key_t)); info->cipher.aescbc.aes->ctx.keySize = 32; - } else if (cbInfo->aes128_installedkey_set == 1 && + } else if (cbInfo->flags2.bits.aes128_installedkey_set == 1 && info->cipher.aescbc.aes->keylen == 16) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes128, @@ -364,6 +367,48 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) #endif /* HAVE_AES_CBC */ #endif /* !NO_AES || !NO_DES3 */ } + #if !defined(NO_RSA) && defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + else if (info->algo_type == WC_ALGO_TYPE_PK) { + + #if !defined(NO_RSA) + if (info->pk.type == WC_PK_TYPE_RSA_KEYGEN) { + ret = wc_sce_MakeRsaKey(info->pk.rsakg.size, (void*)ctx); + } + + if (info->pk.type == WC_PK_TYPE_RSA) { + if (info->pk.rsa.type == RSA_PRIVATE_DECRYPT || + info->pk.rsa.type == RSA_PUBLIC_ENCRYPT ) + { + ret = wc_sce_RsaFunction(info->pk.rsa.in, + info->pk.rsa.inLen, + info->pk.rsa.out, + info->pk.rsa.outLen, + info->pk.rsa.type, + info->pk.rsa.key, + info->pk.rsa.rng, + (void*)ctx); + } + else if (info->pk.rsa.type == RSA_PRIVATE_ENCRYPT /* sign */){ + ret = wc_sce_RsaSign(info->pk.rsa.in, + info->pk.rsa.inLen, + info->pk.rsa.out, + info->pk.rsa.outLen, + info->pk.rsa.key, + (void*)ctx); + } + else if (info->pk.rsa.type == RSA_PUBLIC_DECRYPT /* verify */) { + ret = wc_sce_RsaVerify(info->pk.rsa.in, + info->pk.rsa.inLen, + info->pk.rsa.out, + info->pk.rsa.outLen, + info->pk.rsa.key, + (void*)ctx); + } + + } + #endif /* NO_RSA && WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY */ + } + #endif /* NO_RSA */ #endif /* TSIP or SCE */ (void)devIdArg; @@ -385,7 +430,8 @@ int Renesas_cmn_usable(const WOLFSSL* ssl, byte session_key_generated) #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_usable(ssl, session_key_generated); - #elif defined(WOLFSSL_RENESAS_SCEPROTECT) + #elif defined(WOLFSSL_RENESAS_SCEPROTECT) ||\ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) ret = wc_sce_usable(ssl, session_key_generated); #endif @@ -408,11 +454,18 @@ int wc_CryptoCb_CryptInitRenesasCmn(WOLFSSL* ssl, void* ctx) #if defined(WOLFSSL_RENESAS_TSIP_TLS) TsipUserCtx* cbInfo = (TsipUserCtx*)ctx; - #elif defined(WOLFSSL_RENESAS_SCEPROTECT) + #elif defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) User_SCEPKCbInfo* cbInfo = (User_SCEPKCbInfo*)ctx; #endif - if (cbInfo == NULL || ssl == NULL) { + if (cbInfo == NULL + #if !defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) && \ + !defined(HAVE_RENESAS_SYNC) + || ssl == NULL) { + #else + ) { + #endif + printf("invaid devid\n"); return INVALID_DEVID; } /* need exclusive control because of static variable */ @@ -456,6 +509,10 @@ void wc_CryptoCb_CleanupRenesasCmn(int* id) } #endif /* WOLF_CRYPTO_CB */ +#endif /* WOLFSSL_RENESAS_SCEPROTECT || WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY + /* WOLFSSL_RENESAS_TSIP_TLS*/ + +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS) /* Renesas Security Library Common Method * Check CA index if CA can be used for SCE/TSIP because @@ -679,11 +736,14 @@ static int Renesas_cmn_EncryptKeys(WOLFSSL* ssl, void* ctx) #if defined(WOLFSSL_RENESAS_TSIP_TLS) TsipUserCtx* cbInfo = (TsipUserCtx*)ctx; + + if (cbInfo->session_key_set == 1) { #elif defined(WOLFSSL_RENESAS_SCEPROTECT) User_SCEPKCbInfo* cbInfo = (User_SCEPKCbInfo*)ctx; - #endif - if (cbInfo->session_key_set == 1) { + + if (cbInfo->flags1.bits.session_key_set == 1) { + #endif ret = 0; wolfSSL_CTX_SetTlsFinishedCb(ssl->ctx, Renesas_cmn_TlsFinished); diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_aes.c b/wolfcrypt/src/port/Renesas/renesas_sce_aes.c index 9f73a55a37c..3c7408df6fc 100644 --- a/wolfcrypt/src/port/Renesas/renesas_sce_aes.c +++ b/wolfcrypt/src/port/Renesas/renesas_sce_aes.c @@ -26,7 +26,8 @@ #ifndef NO_AES -#if defined(WOLFSSL_RENESAS_SCEPROTECT) && \ +#if (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_SCEPROTECT_AES) #include @@ -151,9 +152,10 @@ WOLFSSL_LOCAL int wc_sce_AesGcmEncrypt(struct Aes* aes, byte* out, XMEMSET((void*)cipherBuf, 0, sz + delta); XMEMSET((void*)authTag, 0, authTagSz); } - + + #if defined(WOLFSSL_RENESAS_SCEPROTECT) if (ret == 0 && - info->session_key_set == 1) { + info->flags1.bits.session_key_set == 1) { /* generate AES-GCM session key. The key stored in * Aes.ctx.tsip_keyIdx is not used here. */ @@ -174,13 +176,20 @@ WOLFSSL_LOCAL int wc_sce_AesGcmEncrypt(struct Aes* aes, byte* out, } } - else if (info->aes256_installedkey_set == 1 || info->aes128_installedkey_set == 1) { + else + #else + if (ret == 0) + #endif + if (info->flags2.bits.aes256_installedkey_set == 1 || + info->flags2.bits.aes128_installedkey_set == 1) { if (aes->ctx.keySize == 32) { - XMEMCPY(&key_client_aes, &info->sce_wrapped_key_aes256, + XMEMCPY(&key_client_aes, + (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes256, sizeof(sce_aes_wrapped_key_t)); } else { - XMEMCPY(&key_client_aes, &info->sce_wrapped_key_aes128, + XMEMCPY(&key_client_aes, + (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes128, sizeof(sce_aes_wrapped_key_t)); } iv_l = iv; @@ -339,9 +348,9 @@ WOLFSSL_LOCAL int wc_sce_AesGcmDecrypt(struct Aes* aes, byte* out, XMEMCPY(cipherBuf, in, sz); XMEMCPY(aTagBuf, authTag, authTagSz); } - + #if defined(WOLFSSL_RENESAS_SCEPROTECT) if (ret == 0 && - info->session_key_set == 1) { + info->flags1.bits.session_key_set == 1) { /* generate AES-GCM session key. The key stored in * Aes.ctx.tsip_keyIdx is not used here. */ @@ -361,13 +370,20 @@ WOLFSSL_LOCAL int wc_sce_AesGcmDecrypt(struct Aes* aes, byte* out, ret = -1; } } - else if (info->aes256_installedkey_set == 1 || info->aes128_installedkey_set == 1) { + else + #else + if (ret == 0) + #endif + if (info->flags2.bits.aes256_installedkey_set == 1 || + info->flags2.bits.aes128_installedkey_set == 1) { if (aes->ctx.keySize == 32) { - XMEMCPY(&key_server_aes, &info->sce_wrapped_key_aes256, + XMEMCPY(&key_server_aes, + (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes256, sizeof(sce_aes_wrapped_key_t)); } else { - XMEMCPY(&key_server_aes, &info->sce_wrapped_key_aes128, + XMEMCPY(&key_server_aes, + (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes128, sizeof(sce_aes_wrapped_key_t)); } iv_l = iv; diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_rsa.c b/wolfcrypt/src/port/Renesas/renesas_sce_rsa.c new file mode 100644 index 00000000000..9d2ff905c9b --- /dev/null +++ b/wolfcrypt/src/port/Renesas/renesas_sce_rsa.c @@ -0,0 +1,430 @@ +/* renesas_sce_rsa.c + * + * Copyright (C) 2006-2023 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#if !defined(NO_RSA) && \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + +#include +#include + +#ifdef HAVE_CONFIG_H + #include +#endif + +#include +#include +#include +#include +#include + +/* Make Rsa key for SCE and set it to callback ctx + * + * size desired keylenth, in bits. supports 1024 or 2048 bits + * ctx Callback context including pointer to hold generated key + * return FSP_SUCCESS(0) on Success, otherwise negative value + */ +WOLFSSL_LOCAL int wc_sce_MakeRsaKey(int size, void* ctx) +{ + fsp_err_t ret; + User_SCEPKCbInfo *info = (User_SCEPKCbInfo*)ctx; + + sce_rsa1024_wrapped_pair_key_t *wrapped_pair1024_key = NULL; + sce_rsa2048_wrapped_pair_key_t *wrapped_pair2048_key = NULL; + + /* sanity check */ + if (ctx == NULL) + return BAD_FUNC_ARG; + + + if ((ret = wc_sce_hw_lock()) == 0) { + if (size == 1024) { + wrapped_pair1024_key = + (sce_rsa1024_wrapped_pair_key_t*)XMALLOC( + sizeof(sce_rsa1024_wrapped_pair_key_t), NULL, + DYNAMIC_TYPE_RSA_BUFFER); + if (wrapped_pair1024_key == NULL) + return MEMORY_E; + + ret = R_SCE_RSA1024_WrappedKeyPairGenerate(wrapped_pair1024_key); + } + else if (size == 2048) { + wrapped_pair2048_key = + (sce_rsa1024_wrapped_pair_key_t*)XMALLOC( + sizeof(sce_rsa2048_wrapped_pair_key_t), NULL, + DYNAMIC_TYPE_RSA_BUFFER); + if (wrapped_pair2048_key == NULL) + return MEMORY_E; + + ret = R_SCE_RSA2048_WrappedKeyPairGenerate(wrapped_pair2048_key); + } + else + return CRYPTOCB_UNAVAILABLE; + + if (ret == FSP_SUCCESS) { + if (size == 1024) { + if (info->sce_wrapped_key_rsapri1024 != NULL) { + XFREE(info->sce_wrapped_key_rsapri1024, NULL, + DYNAMIC_TYPE_RSA_BUFFER); + } + if (info->sce_wrapped_key_rsapub1024 != NULL) { + XFREE(info->sce_wrapped_key_rsapub1024, NULL, + DYNAMIC_TYPE_RSA_BUFFER); + } + info->sce_wrapped_key_rsapri1024 = + (sce_rsa1024_private_wrapped_key_t*)XMALLOC( + sizeof(sce_rsa1024_private_wrapped_key_t), NULL, + DYNAMIC_TYPE_RSA_BUFFER); + + if (info->sce_wrapped_key_rsapri1024 == NULL) { + XFREE(wrapped_pair1024_key, 0, DYNAMIC_TYPE_RSA_BUFFER); + return MEMORY_E; + } + + info->sce_wrapped_key_rsapub1024 = + (sce_rsa1024_public_wrapped_key_t*)XMALLOC( + sizeof(sce_rsa1024_public_wrapped_key_t), NULL, + DYNAMIC_TYPE_RSA_BUFFER); + + if (info->sce_wrapped_key_rsapub1024 == NULL) { + XFREE(wrapped_pair1024_key, 0, DYNAMIC_TYPE_RSA_BUFFER); + XFREE(info->sce_wrapped_key_rsapub1024, 0, + DYNAMIC_TYPE_RSA_BUFFER); + return MEMORY_E; + } + /* copy generated key pair and free malloced key */ + XMEMCPY(info->sce_wrapped_key_rsapri1024, + &wrapped_pair1024_key->priv_key, + sizeof(sce_rsa1024_private_wrapped_key_t)); + XMEMCPY(info->sce_wrapped_key_rsapub1024, + &wrapped_pair1024_key->pub_key, + sizeof(sce_rsa1024_public_wrapped_key_t)); + XFREE(wrapped_pair1024_key, 0, DYNAMIC_TYPE_RSA_BUFFER); + + info->flags2.bits.rsapri1024_installedkey_set = 1; + info->flags2.bits.rsapub1024_installedkey_set = 1; + } + else if (size == 2048) { + if (info->sce_wrapped_key_rsapri2048 != NULL) { + XFREE(info->sce_wrapped_key_rsapri2048, NULL, + DYNAMIC_TYPE_RSA_BUFFER); + } + if (info->sce_wrapped_key_rsapub2048 != NULL) { + XFREE(info->sce_wrapped_key_rsapub2048, NULL, + DYNAMIC_TYPE_RSA_BUFFER); + } + info->sce_wrapped_key_rsapri2048 = + (sce_rsa2048_private_wrapped_key_t*)XMALLOC( + sizeof(sce_rsa2048_private_wrapped_key_t), NULL, + DYNAMIC_TYPE_RSA_BUFFER); + + if (info->sce_wrapped_key_rsapri2048 == NULL) { + XFREE(wrapped_pair2048_key, 0, DYNAMIC_TYPE_RSA_BUFFER); + return MEMORY_E; + } + + info->sce_wrapped_key_rsapub2048 = + (sce_rsa2048_public_wrapped_key_t*)XMALLOC( + sizeof(sce_rsa2048_public_wrapped_key_t), NULL, + DYNAMIC_TYPE_RSA_BUFFER); + + if (info->sce_wrapped_key_rsapub2048 == NULL) { + XFREE(wrapped_pair2048_key, 0, DYNAMIC_TYPE_RSA_BUFFER); + XFREE(info->sce_wrapped_key_rsapub1024, 0, + DYNAMIC_TYPE_RSA_BUFFER); + return MEMORY_E; + } + /* copy generated key pair and free malloced key */ + XMEMCPY(info->sce_wrapped_key_rsapri2048, + &wrapped_pair2048_key->priv_key, + sizeof(sce_rsa2048_private_wrapped_key_t)); + XMEMCPY(info->sce_wrapped_key_rsapub2048, + &wrapped_pair2048_key->pub_key, + sizeof(sce_rsa2048_public_wrapped_key_t)); + XFREE(wrapped_pair2048_key, 0, DYNAMIC_TYPE_RSA_BUFFER); + + info->flags2.bits.rsapri2048_installedkey_set = 1; + info->flags2.bits.rsapub2048_installedkey_set = 1; + + } + } + else { + WOLFSSL_MSG("Failed to generate key pair by SCE"); + return CRYPTOCB_UNAVAILABLE; + } + + wc_sce_hw_unlock(); + } +} + +/* Perform rsa encryption/decryption by SCE + * + * in Buffer to hold plain text + * inLen Length of plain text in bytes + * out Buffer to hold cipher text + * outLen Length of cipher in bytes + * key Rsa key object + * rng rng object + * ctx Callback context + * return FSP_SUCCESS(0) on Success, otherwise negative value + */ +WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, + word32 outLen, int type, struct RsaKey* key, + struct WC_RNG* rng, void* ctx) +{ + int ret; + + sce_rsa_byte_data_t plain; + sce_rsa_byte_data_t cipher; + User_SCEPKCbInfo *info = (User_SCEPKCbInfo*)ctx; + + int keySize; + + (void) key; + (void) rng; + + /* sanity check */ + if (in == NULL || out == NULL || outLen == NULL || + ctx == NULL){ + return BAD_FUNC_ARG; + } + + keySize = 0; + if (info->flags2.bits.rsapri2048_installedkey_set == 1 || + info->flags2.bits.rsapub2048_installedkey_set == 1 ) + keySize = 2048; + else + keySize = 1024; + + if (keySize != 2048 && keySize != 1024) { + WOLFSSL_MSG("keySize is invalid, neither 128 or 256 bytes, " + "1024 or 2048 bits."); + return BAD_FUNC_ARG; + } + + if ((ret = wc_sce_hw_lock()) == 0) { + if (type == RSA_PUBLIC_ENCRYPT) { + + plain.pdata = (byte*)in; + plain.data_length = inLen; + cipher.pdata = out; + cipher.data_length = outLen; + + if (keySize == 1024) { + if(info->flags2.bits.rsapub1024_installedkey_set == 1) + ret = R_SCE_RSAES_PKCS1024_Encrypt(&plain, &cipher, + (sce_rsa1024_public_wrapped_key_t*) + info->sce_wrapped_key_rsapub1024); + else { + WOLFSSL_MSG("wrapped public 1024 bits key is not set."); + return BAD_FUNC_ARG; + } + } + else { + if(info->flags2.bits.rsapub2048_installedkey_set == 1) + ret = R_SCE_RSAES_PKCS2048_Encrypt(&plain, &cipher, + (sce_rsa2048_public_wrapped_key_t*) + info->sce_wrapped_key_rsapub2048); + else { + WOLFSSL_MSG("wrapped public 2048 bits key is not set."); + return BAD_FUNC_ARG; + } + } + } + else if (type == RSA_PRIVATE_DECRYPT) { + plain.pdata = out; + plain.data_length = outLen; + cipher.pdata = (byte*)in; + cipher.data_length = inLen; + + if (keySize == 1024) { + if(info->flags2.bits.rsapri1024_installedkey_set == 1) + ret = R_SCE_RSAES_PKCS1024_Decrypt(&cipher, &plain, + (sce_rsa1024_private_wrapped_key_t*) + info->sce_wrapped_key_rsapri1024); + else { + WOLFSSL_MSG("wrapped private 2048 bits key is not set."); + return BAD_FUNC_ARG; + } + } + else { + if(info->flags2.bits.rsapri2048_installedkey_set == 1) + ret = R_SCE_RSAES_PKCS2048_Decrypt(&cipher, &plain, + (sce_rsa2048_private_wrapped_key_t*) + info->sce_wrapped_key_rsapri2048); + else { + WOLFSSL_MSG("wrapped private 2048 bits key is not set."); + return BAD_FUNC_ARG; + } + } + } + + wc_sce_hw_unlock(); + } + return ret; +} + +/* Perform Rsa sign by SCE + * + * in Buffer to hold plaintext + * inLen Length of plaintext in bytes + * out Buffer to hold generated signature + * outLen Length of signature in bytes + * key rsa key object + * ctx The callback context + * return FSP_SUCCESS(0) on Success, otherwise negative value + */ + +WOLFSSL_LOCAL int wc_sce_RsaSign(const byte* in, word32 inLen, byte* out, + word32* outLen, struct RsaKey* key, void* ctx) +{ + int ret; + + sce_rsa_byte_data_t message_hash; + sce_rsa_byte_data_t signature; + User_SCEPKCbInfo *info = (User_SCEPKCbInfo*)ctx; + int keySize; + + (void) key; + + /* sanity check */ + if (in == NULL || out == NULL || outLen == NULL || + key == NULL || ctx == NULL){ + return BAD_FUNC_ARG; + } + + keySize = 0; + if (info->flags2.bits.rsapri2048_installedkey_set == 1 || + info->flags2.bits.rsapub2048_installedkey_set == 1 ) + keySize = 2048; + else + keySize = 1024; + + if (keySize != 2048 && keySize != 1024) { + WOLFSSL_MSG("keySize is invalid, neither 1024 or 2048 bits."); + return BAD_FUNC_ARG; + } + + message_hash.pdata = in; + message_hash.data_length = inLen; + message_hash.data_type = + info->flags2.bits.message_type;/* message 0, hash 1 */ + signature.pdata = out; + signature.data_length = outLen; + + if ((ret = wc_sce_hw_lock()) == 0) { + if (keySize == 1024) { + + ret = R_SCE_RSASSA_PKCS1024_SignatureGenerate(&message_hash, + &signature, + (sce_rsa1024_private_wrapped_key_t *) + info->sce_wrapped_key_rsapri1024, + HW_SCE_RSA_HASH_SHA256); + } + else { + + ret = R_SCE_RSASSA_PKCS2048_SignatureGenerate(&message_hash, + &signature, + (sce_rsa2048_private_wrapped_key_t *) + info->sce_wrapped_key_rsapri2048, + HW_SCE_RSA_HASH_SHA256); + } + + wc_sce_hw_unlock(); + } + + return ret; +} + +/* Perform Rsa verify by SCE + * + * in Buffer to hold plaintext + * inLen Length of plaintext in bytes + * out Buffer to hold generated signature + * outLen Length of signature in bytes + * key rsa key object + * ctx The callback context + * return FSP_SUCCESS(0) on Success, otherwise negative value + */ + +WOLFSSL_LOCAL int wc_sce_RsaVerify(const byte* in, word32 inLen, byte* out, + word32* outLen,struct RsaKey* key, void* ctx) +{ + int ret; + + sce_rsa_byte_data_t message_hash; + sce_rsa_byte_data_t signature; + User_SCEPKCbInfo *info = (User_SCEPKCbInfo*)ctx; + int keySize; + + (void) key; + + /* sanity check */ + if (in == NULL || out == NULL || outLen == NULL || + key == NULL || ctx == NULL){ + return BAD_FUNC_ARG; + } + + keySize = 0; + if (info->flags2.bits.rsapri2048_installedkey_set == 1 || + info->flags2.bits.rsapub2048_installedkey_set == 1 ) + keySize = 2048; + else + keySize = 1024; + + if (keySize != 2048 && keySize != 1024) { + WOLFSSL_MSG("keySize is invalid, neither 1024 or 2048 bits."); + return BAD_FUNC_ARG; + } + + + message_hash.pdata = in; + message_hash.data_length = inLen; + message_hash.data_type = + info->flags2.bits.message_type;/* message 0, hash 1 */ + + signature.pdata = out; + signature.data_length = outLen; + + if ((ret = wc_sce_hw_lock()) == 0) { + if (keySize == 1024) { + + ret = R_SCE_RSASSA_PKCS1024_SignatureVerify(&signature, + &message_hash, + (sce_rsa1024_public_wrapped_key_t *) + info->sce_wrapped_key_rsapub1024, + HW_SCE_RSA_HASH_SHA256); + } + else { + + ret = R_SCE_RSASSA_PKCS2048_SignatureVerify(&signature, + &message_hash, + (sce_rsa2048_public_wrapped_key_t *) + info->sce_wrapped_key_rsapub2048, + HW_SCE_RSA_HASH_SHA256 ); + } + + wc_sce_hw_unlock(); + } + + return ret; +} + +#endif /* !NO_RSA && WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY */ diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_sha.c b/wolfcrypt/src/port/Renesas/renesas_sce_sha.c index 37f9adb0ef0..959ea956561 100644 --- a/wolfcrypt/src/port/Renesas/renesas_sce_sha.c +++ b/wolfcrypt/src/port/Renesas/renesas_sce_sha.c @@ -30,7 +30,8 @@ #include -#if defined(WOLFSSL_RENESAS_SCEPROTECT) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #include #include diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_util.c b/wolfcrypt/src/port/Renesas/renesas_sce_util.c index f6bd06f56ab..ed7f2a323cd 100644 --- a/wolfcrypt/src/port/Renesas/renesas_sce_util.c +++ b/wolfcrypt/src/port/Renesas/renesas_sce_util.c @@ -20,7 +20,7 @@ */ #include -#if defined(WOLFSSL_RENESAS_SCEPROTECT) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #include #include @@ -168,6 +168,8 @@ WOLFSSL_LOCAL void wc_sce_Close() } } +#ifndef WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY + #if defined(WOLFSSL_RENESAS_SCEPROTECT_ECC) /* Verify Server Key Exchange while doing ECDH key exchange */ static int SCE_ServerKeyExVerify(uint32_t type, WOLFSSL* ssl, const uint8_t* sig, @@ -220,11 +222,11 @@ static int SCE_ServerKeyExVerify(uint32_t type, WOLFSSL* ssl, const uint8_t* sig if (ret != FSP_SUCCESS) { WOLFSSL_MSG("failed R_SCE_TLS_ServerKeyExchangeVerify"); - cbInfo->pk_key_set = 0; + cbInfo->flags1.bits.pk_key_set = 0; } else { ret = WOLFSSL_SUCCESS; - cbInfo->pk_key_set = 1; + cbInfo->flags1.bits.pk_key_set = 1; } } else { @@ -358,7 +360,7 @@ WOLFSSL_LOCAL int SCE_EccSharedSecret(WOLFSSL* ssl, ecc_key* otherKey, WOLFSSL_PKMSG("PK ECC PMS: Side %s, Peer Curve %d\n", side == WOLFSSL_CLIENT_END ? "client" : "server", otherKey->dp->id); - if (cbInfo->pk_key_set == 1) { + if (cbInfo->flags1.bits.pk_key_set == 1) { if ((ret = wc_sce_hw_lock()) == 0) { /* Generate ECC PUblic key pair */ ret = R_SCE_TLS_ECC_secp256r1_EphemeralWrappedKeyPairGenerate( @@ -404,6 +406,7 @@ WOLFSSL_LOCAL int SCE_EccSharedSecret(WOLFSSL* ssl, ecc_key* otherKey, return ret; } #endif + /* Return tls cipher suite enumeration that is supported by SCE library */ static uint32_t GetSceCipherSuite( uint8_t cipherSuiteFirst, @@ -780,7 +783,7 @@ WOLFSSL_LOCAL int wc_sce_generateSessionKey(WOLFSSL *ssl, dec->aes->devId = devId; /* marked as session key is set */ - cbInfo->session_key_set = 1; + cbInfo->flags1.bits.session_key_set = 1; } /* unlock hw */ wc_sce_hw_unlock(); @@ -1134,8 +1137,8 @@ WOLFSSL_API int wc_sce_set_callback_ctx(WOLFSSL* ssl, void* user_ctx) return -1; } gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx] = (User_SCEPKCbInfo*)user_ctx; - gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx]->pk_key_set = 0; - gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx]->session_key_set = 0; + gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx]->flags1.bits.pk_key_set = 0; + gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx]->flags1.bits.session_key_set = 0; wolfSSL_SetEccVerifyCtx(ssl, user_ctx); wolfSSL_SetRsaEncCtx(ssl, user_ctx); @@ -1151,5 +1154,6 @@ WOLFSSL_API int wc_sce_set_callback_ctx(WOLFSSL* ssl, void* user_ctx) return 0; } +#endif /* !WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY */ -#endif /* WOLFSSL_RENESAS_SCEPROTECT */ +#endif /* WOLFSSL_RENESAS_SCEPROTECT || WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY */ diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 259dc5a682c..4d37a4395a7 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -3488,7 +3488,8 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } return ret; } -#elif defined(WOLFSSL_RENESAS_SCEPROTECT) +#elif defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #include "r_sce.h" int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index c756d8ee2f1..41e67831a08 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3385,7 +3385,22 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, pad_value, pad_type, hash, mgf, label, labelSz, sz); } - #endif /* WOLFSSL_CRYPTOCELL */ + #elif defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + /* SCE needs warpped key which is passed via + * user ctx object of crypt-call back. + */ + #ifdef WOLF_CRYPTO_CB + if (key->devId != INVALID_DEVID) { + /* SCE supports 1024 and 2048 bits */ + ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, rsa_type, key, rng); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ + ret = 0; /* reset error code and try using software */ + } + #endif + + #endif /* WOLFSSL_SE050 */ key->state = RSA_STATE_ENCRYPT_PAD; ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, pad_value, rng, pad_type, @@ -3529,6 +3544,17 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, } return ret; } + #elif defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + #ifdef WOLF_CRYPTO_CB + if (key->devId != INVALID_DEVID) { + ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, rsa_type, key, rng); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ + ret = 0; /* reset error code and try using software */ + } + #endif + #endif /* WOLFSSL_CRYPTOCELL */ diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 75b975eb876..368d4436d07 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -222,7 +222,8 @@ on the specific device platform. (!defined(WOLFSSL_RENESAS_TSIP_CRYPT) || defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH)) && \ !defined(WOLFSSL_PSOC6_CRYPTO) && !defined(WOLFSSL_IMXRT_DCP) && !defined(WOLFSSL_SILABS_SE_ACCEL) && \ !defined(WOLFSSL_KCAPI_HASH) && !defined(WOLFSSL_SE050_HASH) && \ - (!defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH)) && \ + ((!defined(WOLFSSL_RENESAS_SCEPROTECT) && !defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) \ + || defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH)) && \ (!defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH)) && \ !defined(WOLFSSL_RENESAS_RX64_HASH) @@ -796,7 +797,7 @@ static int InitSha256(wc_Sha256* sha256) /* implemented in wolfcrypt/src/port/Renesas/renesas_tsip_sha.c */ -#elif defined(WOLFSSL_RENESAS_SCEPROTECT) && \ +#elif (defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH) /* implemented in wolfcrypt/src/port/Renesas/renesas_sce_sha.c */ @@ -1804,7 +1805,7 @@ void wc_Sha256Free(wc_Sha256* sha256) (defined(WOLFSSL_DEVCRYPTO_HASH) && defined(WOLFSSL_DEVCRYPTO_HASH_KEEP)) || \ (defined(WOLFSSL_RENESAS_TSIP_CRYPT) && \ !defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH)) || \ - (defined(WOLFSSL_RENESAS_SCEPROTECT) && \ + ((defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH)) || \ defined(WOLFSSL_RENESAS_RX64_HASH) || \ defined(WOLFSSL_HASH_KEEP) @@ -1992,7 +1993,7 @@ int wc_Sha224_Grow(wc_Sha224* sha224, const byte* in, int inSz) /* implemented in wolfcrypt/src/port/Renesas/renesas_tsip_sha.c */ -#elif defined(WOLFSSL_RENESAS_SCEPROTECT) && \ +#elif (defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH) /* implemented in wolfcrypt/src/port/Renesas/renesas_sce_sha.c */ diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index f8629df2d84..0a3515bcb50 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -187,7 +187,8 @@ int wolfCrypt_Init(void) } #endif - #if defined(WOLFSSL_RENESAS_SCEPROTECT) + #if defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) ret = wc_sce_Open( ); if( ret != FSP_SUCCESS ) { WOLFSSL_MSG("RENESAS SCE Open failed"); @@ -436,7 +437,8 @@ int wolfCrypt_Cleanup(void) rx64_hw_Close(); #endif - #ifdef WOLFSSL_RENESAS_SCEPROTECT + #if defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) wc_sce_Close(); #endif diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 4c31d9637f4..1742e1f4ff1 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -375,6 +375,7 @@ #endif #if defined(WOLFSSL_RENESAS_TSIP) || defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) || \ defined(WOLFSSL_SECO_CAAM) #define HASH_SIZE_LIMIT #endif @@ -3005,13 +3006,13 @@ WOLFSSL_TEST_SUBROUTINE int sha256_test(void) ret = wc_Sha256Update(&sha, (byte*)large_input, (word32)sizeof(large_input)); if (ret != 0) - ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit); - } + ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit); + } ret = wc_Sha256Final(&sha, hash); if (ret != 0) ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit); if (XMEMCMP(hash, large_digest, WC_SHA256_DIGEST_SIZE) != 0) - ERROR_OUT(WC_TEST_RET_ENC_NC, exit); + ERROR_OUT(WC_TEST_RET_ENC_NC, exit); } /* END LARGE HASH TEST */ #endif /* NO_LARGE_HASH_TEST */ diff --git a/wolfssl/wolfcrypt/aes.h b/wolfssl/wolfcrypt/aes.h index 719512cc5af..90cb8a86c85 100644 --- a/wolfssl/wolfcrypt/aes.h +++ b/wolfssl/wolfcrypt/aes.h @@ -296,7 +296,8 @@ struct Aes { defined(WOLFSSL_RENESAS_TSIP_TLS_AES_CRYPT) TSIP_AES_CTX ctx; #endif -#if defined(WOLFSSL_RENESAS_SCEPROTECT) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) ||\ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) SCE_AES_CTX ctx; #endif #if defined(WOLFSSL_IMXRT_DCP) diff --git a/wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h b/wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h index 1a02c6b01a3..7502533abdc 100644 --- a/wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h +++ b/wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h @@ -34,10 +34,30 @@ extern "C" { #define MAX_SCE_CBINDEX 5 +typedef void* renesas_sce_wrappedkey; + +/* related to TLS */ +struct sce_flags1 { + uint8_t pk_key_set:1; + uint8_t session_key_set:1; +}; + +/* Crypt Only */ +struct sce_flags2 { + uint8_t aes256_installedkey_set:1; + uint8_t aes128_installedkey_set:1; + uint8_t rsapri2048_installedkey_set:1; + uint8_t rsapub2048_installedkey_set:1; + uint8_t rsapri1024_installedkey_set:1; + uint8_t rsapub1024_installedkey_set:1; + uint8_t message_type:1;/*message 0, hashed 1*/ +}; + typedef struct tagUser_SCEPKCbInfo { /* unique number for each session */ int devId; - + #if defined(WOLFSSL_RENESAS_SCEPROTECT) && \ + !defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) /* out from R_SCE_TLS_ServerKeyExchangeVerify */ uint32_t encrypted_ephemeral_ecdh_public_key[SCE_TLS_ENCRYPTED_ECCPUBKEY_SZ]; /* out from R_SCE_TLS_ECC_secp256r1_EphemeralWrappedKeyPairGenerate */ @@ -48,17 +68,34 @@ typedef struct tagUser_SCEPKCbInfo { uint8_t sce_clientRandom[SCE_TLS_CLIENTRANDOM_SZ]; uint8_t sce_serverRandom[SCE_TLS_SERVERRANDOM_SZ]; uint8_t sce_cipher; + + #endif /* installed key handling */ - sce_aes_wrapped_key_t sce_wrapped_key_aes256; - uint8_t aes256_installedkey_set:1; - sce_aes_wrapped_key_t sce_wrapped_key_aes128; - uint8_t aes128_installedkey_set:1; + /* aes */ + renesas_sce_wrappedkey sce_wrapped_key_aes256; + renesas_sce_wrappedkey sce_wrapped_key_aes128; + + #if defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + /* rsa */ + renesas_sce_wrappedkey sce_wrapped_key_rsapri2048; + renesas_sce_wrappedkey sce_wrapped_key_rsapub2048; + renesas_sce_wrappedkey sce_wrapped_key_rsapri1024; + renesas_sce_wrappedkey sce_wrapped_key_rsapub1024; + #endif + /* key status flags */ /* flag whether encrypted ec key is set */ - uint8_t pk_key_set:1; - uint8_t session_key_set:1; - + union { + uint8_t chr; + struct sce_flags1 bits; + } flags1; + + union { + uint8_t chr; + struct sce_flags2 bits; + } flags2 + } User_SCEPKCbInfo; typedef struct tagSCE_PKCbInfo { @@ -138,7 +175,9 @@ typedef wolfssl_SCE_Hash wc_Sha256; #endif /* NO_SHA */ - +#if defined(WOLFSSL_RENESAS_SCEPROTECT) && \ + !defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPT_ONLY) + WOLFSSL_LOCAL int wc_sce_tls_RootCertVerify( const uint8_t* cert, uint32_t cert_len, uint32_t key_n_start, uint32_t key_n_len, @@ -220,5 +259,19 @@ WOLFSSL_API void wc_sce_inform_user_keys( WOLFSSL_API void wc_sce_set_callbacks(struct WOLFSSL_CTX* ctx); WOLFSSL_API int wc_sce_set_callback_ctx(struct WOLFSSL* ssl, void* user_ctx); WOLFSSL_API void wc_sce_inform_cert_sign(const uint8_t *sign); - + +/* rsa */ +struct RsaKey; +struct WC_RNG; +WOLFSSL_API int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, + word32 outLen, int type, struct RsaKey* key, struct WC_RNG* rng, void* ctx); +WOLFSSL_API int wc_sce_MakeRsaKey(int size, void* ctx); +WOLFSSL_API int wc_sce_RsaSign(const byte* in, word32 inLen, byte* out, + word32* outLen, struct RsaKey* key, void* ctx); +WOLFSSL_API int wc_sce_RsaVerify(const byte* in, word32 inLen, byte* out, + word32* outLen,struct RsaKey* key, void* ctx); + +#endif /* WOLFSSL_RENESAS_SCEPROTECT && + * !WOLFSSL_RENESAS_SCEPROTECT_CRYPT_ONLY */ + #endif /* __RENESAS_SCE_CRYPT_H__ */ diff --git a/wolfssl/wolfcrypt/sha256.h b/wolfssl/wolfcrypt/sha256.h index c6665c90b5e..51a91a0525a 100644 --- a/wolfssl/wolfcrypt/sha256.h +++ b/wolfssl/wolfcrypt/sha256.h @@ -153,7 +153,8 @@ enum { #elif defined(WOLFSSL_RENESAS_TSIP_CRYPT) && \ !defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH) #include "wolfssl/wolfcrypt/port/Renesas/renesas_tsip_types.h" -#elif defined(WOLFSSL_RENESAS_SCEPROTECT) && \ +#elif (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH) #include "wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h" #elif defined(WOLFSSL_RENESAS_RX64_HASH) From 255ba406e7e744178dd438f8525a59dcea809f79 Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Thu, 20 Apr 2023 16:07:51 +0900 Subject: [PATCH 276/391] fix white spaces and overlong lines --- wolfcrypt/src/port/Renesas/renesas_common.c | 13 ++++++++----- wolfcrypt/src/port/Renesas/renesas_sce_util.c | 3 ++- wolfcrypt/src/rsa.c | 12 +++++++----- wolfcrypt/src/sha256.c | 12 ++++++++---- wolfcrypt/test/test.c | 4 ++-- 5 files changed, 27 insertions(+), 17 deletions(-) diff --git a/wolfcrypt/src/port/Renesas/renesas_common.c b/wolfcrypt/src/port/Renesas/renesas_common.c index 000123b01d4..319832aff51 100644 --- a/wolfcrypt/src/port/Renesas/renesas_common.c +++ b/wolfcrypt/src/port/Renesas/renesas_common.c @@ -21,10 +21,12 @@ #include -#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) \ +#if defined(WOLFSSL_RENESAS_SCEPROTECT) + || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) \ || defined(WOLFSSL_RENESAS_TSIP_TLS) -#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #include #define cmn_hw_lock wc_sce_hw_lock #define cmn_hw_unlock wc_sce_hw_unlock @@ -349,8 +351,8 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) sizeof(sce_aes_wrapped_key_t)); info->cipher.aescbc.aes->ctx.keySize = 32; - } else if (cbInfo->flags2.bits.aes128_installedkey_set == 1 && - info->cipher.aescbc.aes->keylen == 16) { + } else if (cbInfo->flags2.bits.aes128_installedkey_set + == 1 && info->cipher.aescbc.aes->keylen == 16) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes128, sizeof(sce_aes_wrapped_key_t)); @@ -454,7 +456,8 @@ int wc_CryptoCb_CryptInitRenesasCmn(WOLFSSL* ssl, void* ctx) #if defined(WOLFSSL_RENESAS_TSIP_TLS) TsipUserCtx* cbInfo = (TsipUserCtx*)ctx; - #elif defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) + #elif defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) User_SCEPKCbInfo* cbInfo = (User_SCEPKCbInfo*)ctx; #endif diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_util.c b/wolfcrypt/src/port/Renesas/renesas_sce_util.c index ed7f2a323cd..f861826cc54 100644 --- a/wolfcrypt/src/port/Renesas/renesas_sce_util.c +++ b/wolfcrypt/src/port/Renesas/renesas_sce_util.c @@ -20,7 +20,8 @@ */ #include -#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #include #include diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index 41e67831a08..c668ced15ef 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3386,20 +3386,21 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, labelSz, sz); } #elif defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) - /* SCE needs warpped key which is passed via + /* SCE needs warpped key which is passed via * user ctx object of crypt-call back. */ #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { /* SCE supports 1024 and 2048 bits */ - ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, rsa_type, key, rng); + ret = wc_CryptoCb_Rsa(in, inLen, out, + outLen, rsa_type, key, rng); if (ret != CRYPTOCB_UNAVAILABLE) return ret; /* fall-through when unavailable */ ret = 0; /* reset error code and try using software */ } #endif - + #endif /* WOLFSSL_SE050 */ key->state = RSA_STATE_ENCRYPT_PAD; @@ -3547,14 +3548,15 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, #elif defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { - ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, rsa_type, key, rng); + ret = wc_CryptoCb_Rsa(in, inLen, out, + outLen, rsa_type, key, rng); if (ret != CRYPTOCB_UNAVAILABLE) return ret; /* fall-through when unavailable */ ret = 0; /* reset error code and try using software */ } #endif - + #endif /* WOLFSSL_CRYPTOCELL */ diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 368d4436d07..ffdd4019aeb 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -222,7 +222,8 @@ on the specific device platform. (!defined(WOLFSSL_RENESAS_TSIP_CRYPT) || defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH)) && \ !defined(WOLFSSL_PSOC6_CRYPTO) && !defined(WOLFSSL_IMXRT_DCP) && !defined(WOLFSSL_SILABS_SE_ACCEL) && \ !defined(WOLFSSL_KCAPI_HASH) && !defined(WOLFSSL_SE050_HASH) && \ - ((!defined(WOLFSSL_RENESAS_SCEPROTECT) && !defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) \ + ((!defined(WOLFSSL_RENESAS_SCEPROTECT) && \ + !defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) \ || defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH)) && \ (!defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH)) && \ !defined(WOLFSSL_RENESAS_RX64_HASH) @@ -797,7 +798,8 @@ static int InitSha256(wc_Sha256* sha256) /* implemented in wolfcrypt/src/port/Renesas/renesas_tsip_sha.c */ -#elif (defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ +#elif (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH) /* implemented in wolfcrypt/src/port/Renesas/renesas_sce_sha.c */ @@ -1805,7 +1807,8 @@ void wc_Sha256Free(wc_Sha256* sha256) (defined(WOLFSSL_DEVCRYPTO_HASH) && defined(WOLFSSL_DEVCRYPTO_HASH_KEEP)) || \ (defined(WOLFSSL_RENESAS_TSIP_CRYPT) && \ !defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH)) || \ - ((defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ + ((defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH)) || \ defined(WOLFSSL_RENESAS_RX64_HASH) || \ defined(WOLFSSL_HASH_KEEP) @@ -1993,7 +1996,8 @@ int wc_Sha224_Grow(wc_Sha224* sha224, const byte* in, int inSz) /* implemented in wolfcrypt/src/port/Renesas/renesas_tsip_sha.c */ -#elif (defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ +#elif (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_SCEPROTECT_HASH) /* implemented in wolfcrypt/src/port/Renesas/renesas_sce_sha.c */ diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 1742e1f4ff1..f4705703f0f 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -3006,13 +3006,13 @@ WOLFSSL_TEST_SUBROUTINE int sha256_test(void) ret = wc_Sha256Update(&sha, (byte*)large_input, (word32)sizeof(large_input)); if (ret != 0) - ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit); + ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit); } ret = wc_Sha256Final(&sha, hash); if (ret != 0) ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit); if (XMEMCMP(hash, large_digest, WC_SHA256_DIGEST_SIZE) != 0) - ERROR_OUT(WC_TEST_RET_ENC_NC, exit); + ERROR_OUT(WC_TEST_RET_ENC_NC, exit); } /* END LARGE HASH TEST */ #endif /* NO_LARGE_HASH_TEST */ From df9bd314827482699b1e3959d4c12014d27de820 Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Thu, 27 Apr 2023 15:13:38 +0900 Subject: [PATCH 277/391] addressed review comments --- .../e2studio/RA6M4/test/src/test_main.c | 11 +- .../RA6M4/test/src/wolfssl_sce_unit_test.c | 62 ++++++-- wolfcrypt/src/port/Renesas/renesas_common.c | 148 +++++++++++------- wolfcrypt/src/port/Renesas/renesas_sce_aes.c | 76 ++++----- wolfcrypt/src/port/Renesas/renesas_sce_rsa.c | 65 ++++---- wolfcrypt/src/port/Renesas/renesas_sce_util.c | 12 +- wolfcrypt/src/rsa.c | 21 ++- wolfcrypt/src/wc_port.c | 3 +- .../port/Renesas/renesas-sce-crypt.h | 19 +-- 9 files changed, 247 insertions(+), 170 deletions(-) diff --git a/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c b/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c index 88f05889f2b..d6d9394d8b5 100644 --- a/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c +++ b/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c @@ -135,7 +135,7 @@ void Clr_CallbackCtx(User_SCEPKCbInfo *g) NULL, DYNAMIC_TYPE_TMP_BUFFER); if (g->sce_wrapped_key_aes128 != NULL) - XFREE(g->sce_wrapped_key_aes256, + XFREE(g->sce_wrapped_key_aes128, NULL, DYNAMIC_TYPE_TMP_BUFFER); #if defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) @@ -220,6 +220,8 @@ void sce_test(void) printf("wolfCrypt_Cleanup failed %d\n", ret); } + Clr_CallbackCtx(&guser_PKCbInfo); + #elif defined(BENCHMARK) && \ (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) @@ -253,7 +255,7 @@ void sce_test(void) (uint32_t *)DIRECT_KEY_ADDRESS_256, HW_SCE_AES256_KEY_INDEX_WORD_SIZE*4); p1->type = SCE_KEY_INDEX_TYPE_AES256; - guser_PKCbInfo.flags2.bits.aes256_installedkey_set = 1; + guser_PKCbInfo.keyflgs_crypt.bits.aes256_installedkey_set = 1; /* aes 128 */ memcpy(p2->value, @@ -261,13 +263,16 @@ void sce_test(void) HW_SCE_AES128_KEY_INDEX_WORD_SIZE*4); p2->type = SCE_KEY_INDEX_TYPE_AES128; - guser_PKCbInfo.flags2.bits.aes128_installedkey_set = 1; + guser_PKCbInfo.keyflgs_crypt.bits.aes128_installedkey_set = 1; } #endif printf("Start wolfCrypt Benchmark\n"); benchmark_test(NULL); printf("End wolfCrypt Benchmark\n"); + /* free */ + Clr_CallbackCtx(&guser_PKCbInfo); + #elif defined(TLS_CLIENT) #include "hal_data.h" #include "r_sce.h" diff --git a/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c b/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c index 996ed642569..04509629c33 100644 --- a/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c +++ b/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c @@ -386,7 +386,7 @@ static int sce_aesgcm256_test(int prnt, sce_aes_wrapped_key_t* aes256_key) goto out; } else { userContext.sce_wrapped_key_aes256 = (void*)aes256_key; - userContext.flags2.bits.aes256_installedkey_set = 1; + userContext.keyflgs_crypt.bits.aes256_installedkey_set = 1; enc->ctx.keySize = (word32)enc->keylen; } @@ -582,7 +582,7 @@ static int sce_aesgcm128_test(int prnt, sce_aes_wrapped_key_t* aes128_key) goto out; } else { userContext.sce_wrapped_key_aes128 = aes128_key; - userContext.flags2.bits.aes128_installedkey_set = 1; + userContext.keyflgs_crypt.bits.aes128_installedkey_set = 1; enc->ctx.keySize = (word32)enc->keylen; } /* AES-GCM encrypt and decrypt both use AES encrypt internally */ @@ -656,11 +656,15 @@ static int sce_rsa_test(int prnt, int keySize) const char inStr2[] = TEST_STRING2; const word32 inLen = (word32)TEST_STRING_SZ; const word32 outSz = RSA_TEST_BYTES; + byte *in = NULL; + byte *in2 = NULL; + byte *out= NULL; + byte *out2 = NULL; - byte *in = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); - byte *in2 = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); - byte *out= (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); - byte *out2 = (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + in = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + in2 = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + out= (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + out2 = (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (key == NULL || in == NULL || out == NULL || in2 == NULL || out2 == NULL) { @@ -682,8 +686,11 @@ static int sce_rsa_test(int prnt, int keySize) if ((ret = wc_InitRng(&rng)) != 0) goto out; - - /* make ras key by SCE */ + + if ((ret = wc_RsaSetRNG(key, &rng)) != 0) + goto out; + + /* make rsa key by SCE */ if ((ret = wc_MakeRsaKey(key, keySize, 65537, &rng)) != 0) { goto out; } @@ -694,7 +701,7 @@ static int sce_rsa_test(int prnt, int keySize) } ret = wc_RsaPrivateDecrypt(out, keySize/8, out2, outSz, key); - if (ret != 0) { + if (ret < 0) { ret = -1; goto out; } @@ -703,6 +710,7 @@ static int sce_rsa_test(int prnt, int keySize) goto out; } + ret = 0; out: if (key != NULL) { wc_FreeRsaKey(key); @@ -735,10 +743,14 @@ static int sce_rsa_SignVerify_test(int prnt, int keySize) const word32 inLen = (word32)TEST_STRING_SZ; const word32 outSz = RSA_TEST_BYTES; - byte *in = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); - byte *in2 = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); - byte *out= (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + byte *in = NULL; + byte *in2 = NULL; + byte *out= NULL; + in = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + in2 = (byte*)XMALLOC(inLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + out= (byte*)XMALLOC(outSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + (void) prnt; if (key == NULL || in == NULL || out == NULL) { @@ -759,12 +771,15 @@ static int sce_rsa_SignVerify_test(int prnt, int keySize) if ((ret = wc_InitRng(&rng)) != 0) goto out; - /* make ras key by SCE */ + if ((ret = wc_RsaSetRNG(key, &rng)) != 0) + goto out; + + /* make rsa key by SCE */ if ((ret = wc_MakeRsaKey(key, keySize, 65537, &rng)) != 0) { goto out; } - guser_PKCbInfo.flags2.bits.message_type = 0; + guser_PKCbInfo.keyflgs_crypt.bits.message_type = 0; ret = wc_RsaSSL_Sign(in, inLen, out, outSz, key, &rng); if (ret < 0) { goto out; @@ -778,11 +793,11 @@ static int sce_rsa_SignVerify_test(int prnt, int keySize) } /* this should succeed */ ret = wc_RsaSSL_Verify(in, inLen, out, keySize/8, key); - if (ret != 0) { + if (ret < 0) { ret = -1; goto out; } - + ret = 0; out: if (key != NULL) { wc_FreeRsaKey(key); @@ -833,11 +848,26 @@ int sce_crypt_test() if ( ret > 0) ret = 0; + if (ret == 0) { + printf(" sce_rsa_test(512)(this will be done" + " by SW because SCE doesn't support 512 bits key size.)"); + ret = sce_rsa_test(1, 512); + RESULT_STR(ret) + } + if (ret == 0) { printf(" sce_rsa_test(1024)"); ret = sce_rsa_test(1, 1024); RESULT_STR(ret) } + + if (ret == 0) { + printf(" sce_rsa_SignVerify_test(512)(this will be done" + " by SW because SCE doesn't support 512 bits key size.)"); + ret = sce_rsa_SignVerify_test(1, 512); + RESULT_STR(ret) + } + if (ret == 0) { printf(" sce_rsa_SignVerify_test(1024)"); ret = sce_rsa_SignVerify_test(1, 1024); diff --git a/wolfcrypt/src/port/Renesas/renesas_common.c b/wolfcrypt/src/port/Renesas/renesas_common.c index 319832aff51..92401bd0459 100644 --- a/wolfcrypt/src/port/Renesas/renesas_common.c +++ b/wolfcrypt/src/port/Renesas/renesas_common.c @@ -21,7 +21,7 @@ #include -#if defined(WOLFSSL_RENESAS_SCEPROTECT) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) \ || defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) \ || defined(WOLFSSL_RENESAS_TSIP_TLS) @@ -235,13 +235,13 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) if (info->cipher.type == WC_CIPHER_AES_GCM) { if (info->cipher.enc && - (cbInfo->flags1.bits.session_key_set == 1 || - (cbInfo->flags2.bits.aes256_installedkey_set == 1 && + (cbInfo->keyflgs_tls.bits.session_key_set == 1 || + (cbInfo->keyflgs_crypt.bits.aes256_installedkey_set == 1 && info->cipher.aesgcm_enc.aes->keylen == 32) || - (cbInfo->flags2.bits.aes128_installedkey_set == 1 && + (cbInfo->keyflgs_crypt.bits.aes128_installedkey_set == 1 && info->cipher.aesgcm_enc.aes->keylen == 16))) { - if (cbInfo->flags2.bits.aes256_installedkey_set == 1 && + if (cbInfo->keyflgs_crypt.bits.aes256_installedkey_set == 1 && info->cipher.aesgcm_enc.aes->keylen == 32) { XMEMCPY(&info->cipher.aesgcm_enc.aes->ctx.sce_wrapped_key, @@ -250,7 +250,8 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) info->cipher.aesgcm_enc.aes->ctx.keySize = 32; } - else if (cbInfo->flags2.bits.aes128_installedkey_set == 1 && + else if ( + cbInfo->keyflgs_crypt.bits.aes128_installedkey_set == 1 && info->cipher.aesgcm_enc.aes->keylen == 16) { XMEMCPY(&info->cipher.aesgcm_enc.aes->ctx.sce_wrapped_key, @@ -273,13 +274,13 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) (void*)ctx); } - else if (cbInfo->flags1.bits.session_key_set == 1 || - (cbInfo->flags2.bits.aes256_installedkey_set == 1 && + else if (cbInfo->keyflgs_tls.bits.session_key_set == 1 || + (cbInfo->keyflgs_crypt.bits.aes256_installedkey_set == 1 && info->cipher.aesgcm_dec.aes->keylen == 32) || - (cbInfo->flags2.bits.aes128_installedkey_set == 1 && + (cbInfo->keyflgs_crypt.bits.aes128_installedkey_set == 1 && info->cipher.aesgcm_dec.aes->keylen == 16)) { - if (cbInfo->flags2.bits.aes256_installedkey_set == 1 && + if (cbInfo->keyflgs_crypt.bits.aes256_installedkey_set == 1 && info->cipher.aesgcm_dec.aes->keylen == 32) { XMEMCPY(&info->cipher.aesgcm_dec.aes->ctx.sce_wrapped_key, @@ -288,7 +289,8 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) info->cipher.aesgcm_dec.aes->ctx.keySize = 32; } - else if (cbInfo->flags2.bits.aes128_installedkey_set == 1 && + else if ( + cbInfo->keyflgs_crypt.bits.aes128_installedkey_set == 1 && info->cipher.aesgcm_dec.aes->keylen == 16) { XMEMCPY(&info->cipher.aesgcm_dec.aes->ctx.sce_wrapped_key, @@ -314,23 +316,25 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) #endif /* HAVE_AESGCM */ #ifdef HAVE_AES_CBC if ((info->cipher.type == WC_CIPHER_AES_CBC) && - (cbInfo->flags1.bits.session_key_set == 1 || - (cbInfo->flags2.bits.aes256_installedkey_set == 1 && + (cbInfo->keyflgs_tls.bits.session_key_set == 1 || + (cbInfo->keyflgs_crypt.bits.aes256_installedkey_set == 1 && info->cipher.aescbc.aes->keylen == 32) || - (cbInfo->flags2.bits.aes128_installedkey_set == 1 && + (cbInfo->keyflgs_crypt.bits.aes128_installedkey_set == 1 && info->cipher.aescbc.aes->keylen == 16))) { if (info->cipher.enc) { - if (cbInfo->flags2.bits.aes256_installedkey_set == 1 && - info->cipher.aescbc.aes->keylen == 32) { + if ( + cbInfo->keyflgs_crypt.bits.aes256_installedkey_set == 1 && + info->cipher.aescbc.aes->keylen == 32) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes256, sizeof(sce_aes_wrapped_key_t)); info->cipher.aescbc.aes->ctx.keySize = 32; } - else if (cbInfo->flags2.bits.aes128_installedkey_set == 1 && - info->cipher.aescbc.aes->keylen == 16) { + else if ( + cbInfo->keyflgs_crypt.bits.aes128_installedkey_set == 1 + && info->cipher.aescbc.aes->keylen == 16) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes128, sizeof(sce_aes_wrapped_key_t)); @@ -344,15 +348,16 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) info->cipher.aescbc.sz); } else { - if (cbInfo->flags2.bits.aes256_installedkey_set == 1 && - info->cipher.aescbc.aes->keylen == 32) { + if ( + cbInfo->keyflgs_crypt.bits.aes256_installedkey_set == 1 && + info->cipher.aescbc.aes->keylen == 32) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes256, sizeof(sce_aes_wrapped_key_t)); info->cipher.aescbc.aes->ctx.keySize = 32; - - } else if (cbInfo->flags2.bits.aes128_installedkey_set - == 1 && info->cipher.aescbc.aes->keylen == 16) { + } else if ( + cbInfo->keyflgs_crypt.bits.aes128_installedkey_set == 1 + && info->cipher.aescbc.aes->keylen == 16) { XMEMCPY(&info->cipher.aescbc.aes->ctx.sce_wrapped_key, &cbInfo->sce_wrapped_key_aes128, sizeof(sce_aes_wrapped_key_t)); @@ -373,40 +378,63 @@ static int Renesas_cmn_CryptoDevCb(int devIdArg, wc_CryptoInfo* info, void* ctx) else if (info->algo_type == WC_ALGO_TYPE_PK) { #if !defined(NO_RSA) - if (info->pk.type == WC_PK_TYPE_RSA_KEYGEN) { + #if defined(WOLFSSL_KEY_GEN) + if (info->pk.type == WC_PK_TYPE_RSA_KEYGEN && + (info->pk.rsakg.size == 1024 || + info->pk.rsakg.size == 2048)) { ret = wc_sce_MakeRsaKey(info->pk.rsakg.size, (void*)ctx); } - + #endif if (info->pk.type == WC_PK_TYPE_RSA) { - if (info->pk.rsa.type == RSA_PRIVATE_DECRYPT || - info->pk.rsa.type == RSA_PUBLIC_ENCRYPT ) - { - ret = wc_sce_RsaFunction(info->pk.rsa.in, - info->pk.rsa.inLen, - info->pk.rsa.out, - info->pk.rsa.outLen, - info->pk.rsa.type, - info->pk.rsa.key, - info->pk.rsa.rng, - (void*)ctx); - } - else if (info->pk.rsa.type == RSA_PRIVATE_ENCRYPT /* sign */){ - ret = wc_sce_RsaSign(info->pk.rsa.in, - info->pk.rsa.inLen, - info->pk.rsa.out, - info->pk.rsa.outLen, - info->pk.rsa.key, - (void*)ctx); + /* to perform RSA on SCE, wrapped keys should be installed + * in advance. SCE supports 1024 or 2048 bits key size. + * otherwise, falls-through happens. + */ + if (cbInfo->keyflgs_crypt.bits.rsapri2048_installedkey_set == 1 + || + cbInfo->keyflgs_crypt.bits.rsapub2048_installedkey_set == 1 + || + cbInfo->keyflgs_crypt.bits.rsapri1024_installedkey_set == 1 + || + cbInfo->keyflgs_crypt.bits.rsapub1024_installedkey_set == 1 + ) { + + if (info->pk.rsa.type == RSA_PRIVATE_DECRYPT || + info->pk.rsa.type == RSA_PUBLIC_ENCRYPT ) + { + ret = wc_sce_RsaFunction(info->pk.rsa.in, + info->pk.rsa.inLen, + info->pk.rsa.out, + info->pk.rsa.outLen, + info->pk.rsa.type, + info->pk.rsa.key, + info->pk.rsa.rng, + (void*)ctx); + } + else if (info->pk.rsa.type == RSA_PRIVATE_ENCRYPT /* sign */){ + ret = wc_sce_RsaSign(info->pk.rsa.in, + info->pk.rsa.inLen, + info->pk.rsa.out, + info->pk.rsa.outLen, + info->pk.rsa.key, + (void*)ctx); + } + else if (info->pk.rsa.type == RSA_PUBLIC_DECRYPT /* verify */) { + ret = wc_sce_RsaVerify(info->pk.rsa.in, + info->pk.rsa.inLen, + info->pk.rsa.out, + info->pk.rsa.outLen, + info->pk.rsa.key, + (void*)ctx); + } } - else if (info->pk.rsa.type == RSA_PUBLIC_DECRYPT /* verify */) { - ret = wc_sce_RsaVerify(info->pk.rsa.in, - info->pk.rsa.inLen, - info->pk.rsa.out, - info->pk.rsa.outLen, - info->pk.rsa.key, - (void*)ctx); + else { + WOLFSSL_MSG( + "SCE can handle 1024 or 2048 bit key size. " + "key size is not either 1024 or 2048. " + "Or wrapped key is not installed. " + "RSA operation falls through to SW operation."); } - } #endif /* NO_RSA && WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY */ } @@ -468,7 +496,7 @@ int wc_CryptoCb_CryptInitRenesasCmn(WOLFSSL* ssl, void* ctx) #else ) { #endif - printf("invaid devid\n"); + printf("Invalid devId\n"); return INVALID_DEVID; } /* need exclusive control because of static variable */ @@ -488,9 +516,11 @@ int wc_CryptoCb_CryptInitRenesasCmn(WOLFSSL* ssl, void* ctx) return INVALID_DEVID; } + #if !defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) && \ + !defined(HAVE_RENESAS_SYNC) if (ssl) wolfSSL_SetDevId(ssl, cbInfo->devId); - + #endif /* sanity check for overflow */ if (gdevId < 0) { gdevId = 7890; @@ -651,8 +681,9 @@ WOLFSSL_LOCAL int Renesas_cmn_EccVerify(WOLFSSL* ssl, const unsigned char* sig, * cm_row CA index * return FSP_SUCCESS(0) on success, otherwise WOLFSSL_FATAL_ERROR */ -int wc_Renesas_cmn_RootCertVerify(const byte* cert, word32 cert_len, word32 key_n_start, - word32 key_n_len, word32 key_e_start, word32 key_e_len, word32 cm_row) +int wc_Renesas_cmn_RootCertVerify(const byte* cert, word32 cert_len, + word32 key_n_start, word32 key_n_len, word32 key_e_start, + word32 key_e_len, word32 cm_row) { int ret; @@ -721,7 +752,8 @@ WOLFSSL_LOCAL int Renesas_cmn_TlsFinished(WOLFSSL* ssl, const byte *side, /* Renesas Security Library Common Callback * Callback for setting Encrypt Keys. - * Register callback for setting Encrypt Keys when keys are generated by SCE/TSIP + * Register callback for setting Encrypt Keys when keys are generated + * by SCE/TSIP * * ssl the WOLFSSL object * ctx Callback context @@ -745,7 +777,7 @@ static int Renesas_cmn_EncryptKeys(WOLFSSL* ssl, void* ctx) User_SCEPKCbInfo* cbInfo = (User_SCEPKCbInfo*)ctx; - if (cbInfo->flags1.bits.session_key_set == 1) { + if (cbInfo->keyflgs_tls.bits.session_key_set == 1) { #endif ret = 0; diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_aes.c b/wolfcrypt/src/port/Renesas/renesas_sce_aes.c index 3c7408df6fc..adad4d5df64 100644 --- a/wolfcrypt/src/port/Renesas/renesas_sce_aes.c +++ b/wolfcrypt/src/port/Renesas/renesas_sce_aes.c @@ -155,7 +155,7 @@ WOLFSSL_LOCAL int wc_sce_AesGcmEncrypt(struct Aes* aes, byte* out, #if defined(WOLFSSL_RENESAS_SCEPROTECT) if (ret == 0 && - info->flags1.bits.session_key_set == 1) { + info->keyflgs_tls.bits.session_key_set == 1) { /* generate AES-GCM session key. The key stored in * Aes.ctx.tsip_keyIdx is not used here. */ @@ -176,28 +176,29 @@ WOLFSSL_LOCAL int wc_sce_AesGcmEncrypt(struct Aes* aes, byte* out, } } - else + else { #else - if (ret == 0) + if (ret == 0) { #endif - if (info->flags2.bits.aes256_installedkey_set == 1 || - info->flags2.bits.aes128_installedkey_set == 1) { - if (aes->ctx.keySize == 32) { - XMEMCPY(&key_client_aes, - (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes256, - sizeof(sce_aes_wrapped_key_t)); + if (info->keyflgs_crypt.bits.aes256_installedkey_set == 1 || + info->keyflgs_crypt.bits.aes128_installedkey_set == 1) { + if (aes->ctx.keySize == 32) { + XMEMCPY(&key_client_aes, + (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes256, + sizeof(sce_aes_wrapped_key_t)); + } + else { + XMEMCPY(&key_client_aes, + (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes128, + sizeof(sce_aes_wrapped_key_t)); + } + iv_l = iv; + ivSz_l = ivSz; } else { - XMEMCPY(&key_client_aes, - (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes128, - sizeof(sce_aes_wrapped_key_t)); + WOLFSSL_MSG("AES key for SCE is not set."); + ret = -1; } - iv_l = iv; - ivSz_l = ivSz; - } - else { - WOLFSSL_MSG("AES key for SCE is not set."); - ret = -1; } if (ret == 0) { @@ -350,7 +351,7 @@ WOLFSSL_LOCAL int wc_sce_AesGcmDecrypt(struct Aes* aes, byte* out, } #if defined(WOLFSSL_RENESAS_SCEPROTECT) if (ret == 0 && - info->flags1.bits.session_key_set == 1) { + info->keyflgs_tls.bits.session_key_set == 1) { /* generate AES-GCM session key. The key stored in * Aes.ctx.tsip_keyIdx is not used here. */ @@ -370,30 +371,31 @@ WOLFSSL_LOCAL int wc_sce_AesGcmDecrypt(struct Aes* aes, byte* out, ret = -1; } } - else + else { #else - if (ret == 0) + if (ret == 0) { #endif - if (info->flags2.bits.aes256_installedkey_set == 1 || - info->flags2.bits.aes128_installedkey_set == 1) { - if (aes->ctx.keySize == 32) { - XMEMCPY(&key_server_aes, - (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes256, - sizeof(sce_aes_wrapped_key_t)); + if (info->keyflgs_crypt.bits.aes256_installedkey_set == 1 || + info->keyflgs_crypt.bits.aes128_installedkey_set == 1) { + if (aes->ctx.keySize == 32) { + XMEMCPY(&key_server_aes, + (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes256, + sizeof(sce_aes_wrapped_key_t)); + } + else { + XMEMCPY(&key_server_aes, + (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes128, + sizeof(sce_aes_wrapped_key_t)); + } + iv_l = iv; + ivSz_l = ivSz; } else { - XMEMCPY(&key_server_aes, - (sce_aes_wrapped_key_t*)info->sce_wrapped_key_aes128, - sizeof(sce_aes_wrapped_key_t)); + WOLFSSL_MSG("AES key for SCE is not set."); + ret = -1; } - iv_l = iv; - ivSz_l = ivSz; } - else { - WOLFSSL_MSG("AES key for SCE is not set."); - ret = -1; - } - + if (ret == 0) { /* since key_index has iv and ivSz in it, no need to pass them init * func. Pass NULL and 0 as 3rd and 4th parameter respectively. diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_rsa.c b/wolfcrypt/src/port/Renesas/renesas_sce_rsa.c index 9d2ff905c9b..e866556af92 100644 --- a/wolfcrypt/src/port/Renesas/renesas_sce_rsa.c +++ b/wolfcrypt/src/port/Renesas/renesas_sce_rsa.c @@ -36,12 +36,13 @@ #include /* Make Rsa key for SCE and set it to callback ctx + * Assumes to be called by Crypt Callback * * size desired keylenth, in bits. supports 1024 or 2048 bits * ctx Callback context including pointer to hold generated key * return FSP_SUCCESS(0) on Success, otherwise negative value */ -WOLFSSL_LOCAL int wc_sce_MakeRsaKey(int size, void* ctx) +WOLFSSL_LOCAL int wc_sce_MakeRsaKey(int size, void* ctx) { fsp_err_t ret; User_SCEPKCbInfo *info = (User_SCEPKCbInfo*)ctx; @@ -118,8 +119,8 @@ WOLFSSL_LOCAL int wc_sce_MakeRsaKey(int size, void* ctx) sizeof(sce_rsa1024_public_wrapped_key_t)); XFREE(wrapped_pair1024_key, 0, DYNAMIC_TYPE_RSA_BUFFER); - info->flags2.bits.rsapri1024_installedkey_set = 1; - info->flags2.bits.rsapub1024_installedkey_set = 1; + info->keyflgs_crypt.bits.rsapri1024_installedkey_set = 1; + info->keyflgs_crypt.bits.rsapub1024_installedkey_set = 1; } else if (size == 2048) { if (info->sce_wrapped_key_rsapri2048 != NULL) { @@ -160,8 +161,8 @@ WOLFSSL_LOCAL int wc_sce_MakeRsaKey(int size, void* ctx) sizeof(sce_rsa2048_public_wrapped_key_t)); XFREE(wrapped_pair2048_key, 0, DYNAMIC_TYPE_RSA_BUFFER); - info->flags2.bits.rsapri2048_installedkey_set = 1; - info->flags2.bits.rsapub2048_installedkey_set = 1; + info->keyflgs_crypt.bits.rsapri2048_installedkey_set = 1; + info->keyflgs_crypt.bits.rsapub2048_installedkey_set = 1; } } @@ -175,6 +176,7 @@ WOLFSSL_LOCAL int wc_sce_MakeRsaKey(int size, void* ctx) } /* Perform rsa encryption/decryption by SCE + * Assumes to be called by Crypt Callback * * in Buffer to hold plain text * inLen Length of plain text in bytes @@ -185,7 +187,7 @@ WOLFSSL_LOCAL int wc_sce_MakeRsaKey(int size, void* ctx) * ctx Callback context * return FSP_SUCCESS(0) on Success, otherwise negative value */ -WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, +WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, word32 outLen, int type, struct RsaKey* key, struct WC_RNG* rng, void* ctx) { @@ -207,13 +209,14 @@ WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, } keySize = 0; - if (info->flags2.bits.rsapri2048_installedkey_set == 1 || - info->flags2.bits.rsapub2048_installedkey_set == 1 ) + if (info->keyflgs_crypt.bits.rsapri2048_installedkey_set == 1 || + info->keyflgs_crypt.bits.rsapub2048_installedkey_set == 1 ) keySize = 2048; - else + else if (info->keyflgs_crypt.bits.rsapri1024_installedkey_set == 1 || + info->keyflgs_crypt.bits.rsapub1024_installedkey_set == 1 ) keySize = 1024; - - if (keySize != 2048 && keySize != 1024) { + + if (keySize == 0) { WOLFSSL_MSG("keySize is invalid, neither 128 or 256 bytes, " "1024 or 2048 bits."); return BAD_FUNC_ARG; @@ -228,7 +231,7 @@ WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, cipher.data_length = outLen; if (keySize == 1024) { - if(info->flags2.bits.rsapub1024_installedkey_set == 1) + if(info->keyflgs_crypt.bits.rsapub1024_installedkey_set == 1) ret = R_SCE_RSAES_PKCS1024_Encrypt(&plain, &cipher, (sce_rsa1024_public_wrapped_key_t*) info->sce_wrapped_key_rsapub1024); @@ -238,7 +241,7 @@ WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, } } else { - if(info->flags2.bits.rsapub2048_installedkey_set == 1) + if(info->keyflgs_crypt.bits.rsapub2048_installedkey_set == 1) ret = R_SCE_RSAES_PKCS2048_Encrypt(&plain, &cipher, (sce_rsa2048_public_wrapped_key_t*) info->sce_wrapped_key_rsapub2048); @@ -255,7 +258,7 @@ WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, cipher.data_length = inLen; if (keySize == 1024) { - if(info->flags2.bits.rsapri1024_installedkey_set == 1) + if(info->keyflgs_crypt.bits.rsapri1024_installedkey_set == 1) ret = R_SCE_RSAES_PKCS1024_Decrypt(&cipher, &plain, (sce_rsa1024_private_wrapped_key_t*) info->sce_wrapped_key_rsapri1024); @@ -265,7 +268,7 @@ WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, } } else { - if(info->flags2.bits.rsapri2048_installedkey_set == 1) + if(info->keyflgs_crypt.bits.rsapri2048_installedkey_set == 1) ret = R_SCE_RSAES_PKCS2048_Decrypt(&cipher, &plain, (sce_rsa2048_private_wrapped_key_t*) info->sce_wrapped_key_rsapri2048); @@ -282,7 +285,8 @@ WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, } /* Perform Rsa sign by SCE - * + * Assumes to be called by Crypt Callback + * * in Buffer to hold plaintext * inLen Length of plaintext in bytes * out Buffer to hold generated signature @@ -292,7 +296,7 @@ WOLFSSL_LOCAL int wc_sce_RsaFunction(const byte* in, word32 inLen, byte* out, * return FSP_SUCCESS(0) on Success, otherwise negative value */ -WOLFSSL_LOCAL int wc_sce_RsaSign(const byte* in, word32 inLen, byte* out, +WOLFSSL_LOCAL int wc_sce_RsaSign(const byte* in, word32 inLen, byte* out, word32* outLen, struct RsaKey* key, void* ctx) { int ret; @@ -311,13 +315,14 @@ WOLFSSL_LOCAL int wc_sce_RsaSign(const byte* in, word32 inLen, byte* out, } keySize = 0; - if (info->flags2.bits.rsapri2048_installedkey_set == 1 || - info->flags2.bits.rsapub2048_installedkey_set == 1 ) + if (info->keyflgs_crypt.bits.rsapri2048_installedkey_set == 1 || + info->keyflgs_crypt.bits.rsapub2048_installedkey_set == 1 ) keySize = 2048; - else + else if (info->keyflgs_crypt.bits.rsapri1024_installedkey_set == 1 || + info->keyflgs_crypt.bits.rsapub1024_installedkey_set == 1 ) keySize = 1024; - if (keySize != 2048 && keySize != 1024) { + if (keySize == 0) { WOLFSSL_MSG("keySize is invalid, neither 1024 or 2048 bits."); return BAD_FUNC_ARG; } @@ -325,7 +330,7 @@ WOLFSSL_LOCAL int wc_sce_RsaSign(const byte* in, word32 inLen, byte* out, message_hash.pdata = in; message_hash.data_length = inLen; message_hash.data_type = - info->flags2.bits.message_type;/* message 0, hash 1 */ + info->keyflgs_crypt.bits.message_type;/* message 0, hash 1 */ signature.pdata = out; signature.data_length = outLen; @@ -354,7 +359,8 @@ WOLFSSL_LOCAL int wc_sce_RsaSign(const byte* in, word32 inLen, byte* out, } /* Perform Rsa verify by SCE - * + * Assumes to be called by Crypt Callback + * * in Buffer to hold plaintext * inLen Length of plaintext in bytes * out Buffer to hold generated signature @@ -364,7 +370,7 @@ WOLFSSL_LOCAL int wc_sce_RsaSign(const byte* in, word32 inLen, byte* out, * return FSP_SUCCESS(0) on Success, otherwise negative value */ -WOLFSSL_LOCAL int wc_sce_RsaVerify(const byte* in, word32 inLen, byte* out, +WOLFSSL_LOCAL int wc_sce_RsaVerify(const byte* in, word32 inLen, byte* out, word32* outLen,struct RsaKey* key, void* ctx) { int ret; @@ -383,13 +389,14 @@ WOLFSSL_LOCAL int wc_sce_RsaVerify(const byte* in, word32 inLen, byte* out, } keySize = 0; - if (info->flags2.bits.rsapri2048_installedkey_set == 1 || - info->flags2.bits.rsapub2048_installedkey_set == 1 ) + if (info->keyflgs_crypt.bits.rsapri2048_installedkey_set == 1 || + info->keyflgs_crypt.bits.rsapub2048_installedkey_set == 1 ) keySize = 2048; - else + else if (info->keyflgs_crypt.bits.rsapri1024_installedkey_set == 1 || + info->keyflgs_crypt.bits.rsapub1024_installedkey_set == 1 ) keySize = 1024; - if (keySize != 2048 && keySize != 1024) { + if (keySize == 0) { WOLFSSL_MSG("keySize is invalid, neither 1024 or 2048 bits."); return BAD_FUNC_ARG; } @@ -398,7 +405,7 @@ WOLFSSL_LOCAL int wc_sce_RsaVerify(const byte* in, word32 inLen, byte* out, message_hash.pdata = in; message_hash.data_length = inLen; message_hash.data_type = - info->flags2.bits.message_type;/* message 0, hash 1 */ + info->keyflgs_crypt.bits.message_type;/* message 0, hash 1 */ signature.pdata = out; signature.data_length = outLen; diff --git a/wolfcrypt/src/port/Renesas/renesas_sce_util.c b/wolfcrypt/src/port/Renesas/renesas_sce_util.c index f861826cc54..6d791700acb 100644 --- a/wolfcrypt/src/port/Renesas/renesas_sce_util.c +++ b/wolfcrypt/src/port/Renesas/renesas_sce_util.c @@ -223,11 +223,11 @@ static int SCE_ServerKeyExVerify(uint32_t type, WOLFSSL* ssl, const uint8_t* sig if (ret != FSP_SUCCESS) { WOLFSSL_MSG("failed R_SCE_TLS_ServerKeyExchangeVerify"); - cbInfo->flags1.bits.pk_key_set = 0; + cbInfo->keyflgs_tls.bits.pk_key_set = 0; } else { ret = WOLFSSL_SUCCESS; - cbInfo->flags1.bits.pk_key_set = 1; + cbInfo->keyflgs_tls.bits.pk_key_set = 1; } } else { @@ -361,7 +361,7 @@ WOLFSSL_LOCAL int SCE_EccSharedSecret(WOLFSSL* ssl, ecc_key* otherKey, WOLFSSL_PKMSG("PK ECC PMS: Side %s, Peer Curve %d\n", side == WOLFSSL_CLIENT_END ? "client" : "server", otherKey->dp->id); - if (cbInfo->flags1.bits.pk_key_set == 1) { + if (cbInfo->keyflgs_tls.bits.pk_key_set == 1) { if ((ret = wc_sce_hw_lock()) == 0) { /* Generate ECC PUblic key pair */ ret = R_SCE_TLS_ECC_secp256r1_EphemeralWrappedKeyPairGenerate( @@ -784,7 +784,7 @@ WOLFSSL_LOCAL int wc_sce_generateSessionKey(WOLFSSL *ssl, dec->aes->devId = devId; /* marked as session key is set */ - cbInfo->flags1.bits.session_key_set = 1; + cbInfo->keyflgs_tls.bits.session_key_set = 1; } /* unlock hw */ wc_sce_hw_unlock(); @@ -1138,8 +1138,8 @@ WOLFSSL_API int wc_sce_set_callback_ctx(WOLFSSL* ssl, void* user_ctx) return -1; } gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx] = (User_SCEPKCbInfo*)user_ctx; - gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx]->flags1.bits.pk_key_set = 0; - gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx]->flags1.bits.session_key_set = 0; + gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx]->keyflgs_tls.bits.pk_key_set = 0; + gSCE_PKCbInfo.user_PKCbInfo[sce_sess_idx]->keyflgs_tls.bits.session_key_set = 0; wolfSSL_SetEccVerifyCtx(ssl, user_ctx); wolfSSL_SetRsaEncCtx(ssl, user_ctx); diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index c668ced15ef..61288aa4f36 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3389,7 +3389,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, /* SCE needs warpped key which is passed via * user ctx object of crypt-call back. */ - #ifdef WOLF_CRYPTO_CB + #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { /* SCE supports 1024 and 2048 bits */ ret = wc_CryptoCb_Rsa(in, inLen, out, @@ -3399,8 +3399,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, /* fall-through when unavailable */ ret = 0; /* reset error code and try using software */ } - #endif - + #endif #endif /* WOLFSSL_SE050 */ key->state = RSA_STATE_ENCRYPT_PAD; @@ -3547,14 +3546,14 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, } #elif defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #ifdef WOLF_CRYPTO_CB - if (key->devId != INVALID_DEVID) { - ret = wc_CryptoCb_Rsa(in, inLen, out, - outLen, rsa_type, key, rng); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ - ret = 0; /* reset error code and try using software */ - } + if (key->devId != INVALID_DEVID) { + ret = wc_CryptoCb_Rsa(in, inLen, out, + outLen, rsa_type, key, rng); + if (ret != CRYPTOCB_UNAVAILABLE) + return ret; + /* fall-through when unavailable */ + ret = 0; /* reset error code and try using software */ + } #endif #endif /* WOLFSSL_CRYPTOCELL */ diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index 0a3515bcb50..b6736e50183 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -61,7 +61,8 @@ #if defined(WOLFSSL_RENESAS_TSIP) #include #endif -#if defined(WOLFSSL_RENESAS_SCE) +#if defined(WOLFSSL_RENESAS_SCEPROTECT) || \ + defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY) #include #endif #if defined(WOLFSSL_RENESAS_RX64_HASH) diff --git a/wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h b/wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h index 7502533abdc..35847131c0e 100644 --- a/wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h +++ b/wolfssl/wolfcrypt/port/Renesas/renesas-sce-crypt.h @@ -36,14 +36,14 @@ extern "C" { typedef void* renesas_sce_wrappedkey; -/* related to TLS */ -struct sce_flags1 { +/* flsgas related to TLS */ +struct sce_keyflgs_tls { uint8_t pk_key_set:1; uint8_t session_key_set:1; }; -/* Crypt Only */ -struct sce_flags2 { +/* flags Crypt Only */ +struct sce_keyflgs_cryt { uint8_t aes256_installedkey_set:1; uint8_t aes128_installedkey_set:1; uint8_t rsapri2048_installedkey_set:1; @@ -88,13 +88,14 @@ typedef struct tagUser_SCEPKCbInfo { /* flag whether encrypted ec key is set */ union { uint8_t chr; - struct sce_flags1 bits; - } flags1; - + struct sce_keyflgs_tls bits; + } keyflgs_tls; + /* key status flags */ + /* flags shows status if wrapped keys are installed */ union { uint8_t chr; - struct sce_flags2 bits; - } flags2 + struct sce_keyflgs_cryt bits; + } keyflgs_crypt; } User_SCEPKCbInfo; From 94517f264d2e125d1e3498b70e52c1a279fb8ad3 Mon Sep 17 00:00:00 2001 From: Kareem Date: Thu, 11 May 2023 15:15:46 -0700 Subject: [PATCH 278/391] Fix wolfssl_asn1_time_to_tm setting unexpected fields in tm struct. --- src/ssl_asn1.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 5a09e2742b2..20dbe67585d 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -3652,6 +3652,9 @@ static int wolfssl_asn1_time_to_tm(const WOLFSSL_ASN1_TIME* asnTime, const unsigned char* asn1TimeBuf; int asn1TimeBufLen; int i = 0; +#ifdef XMKTIME + struct tm localTm = {0}; +#endif /* Get the string buffer - fixed array, can't fail. */ asn1TimeBuf = wolfSSL_ASN1_TIME_get_data(asnTime); @@ -3706,8 +3709,13 @@ static int wolfssl_asn1_time_to_tm(const WOLFSSL_ASN1_TIME* asnTime, tm->tm_sec += (asn1TimeBuf[i] - '0'); #ifdef XMKTIME - /* Call XMKTIME on tm to get tm_wday and tm_yday fields populated. */ - XMKTIME(tm); + XMEMCPY(&localTm, tm, sizeof(struct tm)); + /* Call XMKTIME on tm to get tm_wday and tm_yday fields populated. + Note that localTm is used here to avoid modifying other fields, + such as tm_isdst/tm_gmtoff. */ + XMKTIME(&localTm); + tm->tm_wday = localTm.tm_wday; + tm->tm_yday = localTm.tm_yday; #endif } From 0818f46cd0f9bf04f84e65675895f85f5d58ef79 Mon Sep 17 00:00:00 2001 From: Kareem Date: Fri, 12 May 2023 14:30:55 -0700 Subject: [PATCH 279/391] Add test case for ASN1_TIME_to_tm fix. --- tests/api.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/api.c b/tests/api.c index 97268fed147..f337a47b482 100644 --- a/tests/api.c +++ b/tests/api.c @@ -33143,6 +33143,7 @@ static int test_wolfSSL_ASN1_TIME_to_tm(void) defined(OPENSSL_ALL)) && !defined(NO_ASN_TIME) ASN1_TIME asnTime; struct tm tm; + time_t testTime = 1683926567; /* Fri May 12 09:22:47 PM UTC 2023 */ XMEMSET(&asnTime, 0, sizeof(ASN1_TIME)); AssertIntEQ(ASN1_TIME_set_string(&asnTime, "000222211515Z"), 1); @@ -33188,6 +33189,22 @@ static int test_wolfSSL_ASN1_TIME_to_tm(void) AssertIntEQ(ASN1_TIME_set_string(&asnTime, "20000222211515U"), 1); AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); +#ifdef XMKTIME + AssertNotNull(ASN1_TIME_adj(&asnTime, testTime, 0, 0)); + AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 1); + AssertIntEQ(tm.tm_sec, 47); + AssertIntEQ(tm.tm_min, 22); + AssertIntEQ(tm.tm_hour, 21); + AssertIntEQ(tm.tm_mday, 12); + AssertIntEQ(tm.tm_mon, 4); + AssertIntEQ(tm.tm_year, 123); + AssertIntEQ(tm.tm_wday, 5); + AssertIntEQ(tm.tm_yday, 131); + /* Confirm that when used with a tm struct from ASN1_TIME_adj, all other + fields are zeroed out as expected. */ + AssertIntEQ(tm.tm_isdst, 0); +#endif + res = TEST_RES_CHECK(1); #endif return res; From eeca8a35456fb0247c05f018168ed6e0c00278c1 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 12 May 2023 09:52:01 -0700 Subject: [PATCH 280/391] check for socket errors on SendAlert --- src/internal.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/internal.c b/src/internal.c index e36acef0684..109f1caf63c 100644 --- a/src/internal.c +++ b/src/internal.c @@ -33342,7 +33342,14 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ret != 0 || !ssl->options.dtlsStateful) { int alertType = TranslateErrorToAlert(ret); if (alertType != invalid_alert) - SendAlert(ssl, alert_fatal, alertType); + if (alertType != invalid_alert) { + int err; + + /* propogate socket errors to avoid re-calling send alert */ + err = SendAlert(ssl, alert_fatal, alertType); + if (err == SOCKET_ERROR_E) + ret = SOCKET_ERROR_E; + } *inOutIdx += helloSz; DtlsResetState(ssl); if (DtlsIgnoreError(ret)) From 0e19d54894d0b399f446952ccfc1cb2dd05732e7 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Mon, 15 May 2023 14:12:24 -0600 Subject: [PATCH 281/391] Fixes for wolfcrypt test without ECC SECP --- tests/api.c | 2 +- wolfcrypt/test/test.c | 33 +++++++++++++++++++-------------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/tests/api.c b/tests/api.c index f337a47b482..5ccee232126 100644 --- a/tests/api.c +++ b/tests/api.c @@ -53894,11 +53894,11 @@ static int test_tls13_apis(void) ":P256_KYBER_LEVEL1" #endif #endif +#endif /* !defined(NO_ECC_SECP) */ #ifdef HAVE_PQC ":KYBER_LEVEL1" #endif ""; -#endif /* !defined(NO_ECC_SECP) */ #endif /* defined(OPENSSL_EXTRA) && defined(HAVE_ECC) */ (void)ret; diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index f4705703f0f..f5f08015f39 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -513,7 +513,7 @@ WOLFSSL_TEST_SUBROUTINE int scrypt_test(void); #if defined(USE_CERT_BUFFERS_256) && !defined(WOLFSSL_ATECC508A) && \ !defined(WOLFSSL_ATECC608A) && !defined(NO_ECC256) && \ defined(HAVE_ECC_VERIFY) && defined(HAVE_ECC_SIGN) && \ - !defined(WOLF_CRYPTO_CB_ONLY_ECC) + !defined(WOLF_CRYPTO_CB_ONLY_ECC) && !defined(NO_ECC_SECP) /* skip for ATECC508/608A, cannot import private key buffers */ WOLFSSL_TEST_SUBROUTINE int ecc_test_buffers(void); #endif @@ -1453,7 +1453,7 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #if defined(USE_CERT_BUFFERS_256) && !defined(WOLFSSL_ATECC508A) && \ !defined(WOLFSSL_ATECC608A) && !defined(NO_ECC256) && \ defined(HAVE_ECC_VERIFY) && defined(HAVE_ECC_SIGN) && \ - !defined(WOLF_CRYPTO_CB_ONLY_ECC) + !defined(WOLF_CRYPTO_CB_ONLY_ECC) && !defined(NO_ECC_SECP) /* skip for ATECC508/608A, cannot import private key buffers */ if ( (ret = ecc_test_buffers()) != 0) TEST_FAIL("ECC buffer test failed!\n", ret); @@ -13778,7 +13778,8 @@ WOLFSSL_TEST_SUBROUTINE int memory_test(void) #endif #endif #if !defined(USE_CERT_BUFFERS_256) && !defined(NO_ASN) - #if defined(HAVE_ECC) && defined(WOLFSSL_CERT_GEN) + #if defined(HAVE_ECC) && defined(WOLFSSL_CERT_GEN) && \ + !defined(NO_ECC_SECP) #ifndef NO_RSA static const char* eccKeyPubFileDer = CERT_ROOT "ecc-keyPub.der"; #endif @@ -13827,13 +13828,15 @@ WOLFSSL_TEST_SUBROUTINE int memory_test(void) #ifndef NO_WRITE_TEMP_FILES #ifdef HAVE_ECC - #if defined(WOLFSSL_CERT_GEN) && !defined(NO_ASN_TIME) - static const char* certEccPemFile = CERT_WRITE_TEMP_DIR "certecc.pem"; - static const char* certEccDerFile = CERT_WRITE_TEMP_DIR "certecc.der"; - #endif - #if defined(WOLFSSL_CERT_GEN) && !defined(NO_RSA) + #ifndef NO_ECC_SECP + #if defined(WOLFSSL_CERT_GEN) && !defined(NO_ASN_TIME) + static const char* certEccPemFile = CERT_WRITE_TEMP_DIR "certecc.pem"; + static const char* certEccDerFile = CERT_WRITE_TEMP_DIR "certecc.der"; + #endif + #if defined(WOLFSSL_CERT_GEN) && !defined(NO_RSA) static const char* certEccRsaPemFile = CERT_WRITE_TEMP_DIR "certeccrsa.pem"; static const char* certEccRsaDerFile = CERT_WRITE_TEMP_DIR "certeccrsa.der"; + #endif #endif #if defined(HAVE_ECC_KEY_EXPORT) && !defined(WC_NO_RNG) && \ !defined(WOLF_CRYPTO_CB_ONLY_ECC) && !defined(NO_ASN_CRYPT) @@ -16298,7 +16301,8 @@ static int rsa_certgen_test(RsaKey* key, RsaKey* keypub, WC_RNG* rng, byte* tmp) } #endif -#if !defined(NO_RSA) && defined(HAVE_ECC) && defined(WOLFSSL_CERT_GEN) +#if !defined(NO_RSA) && defined(HAVE_ECC) && !defined(NO_ECC_SECP) && \ + defined(WOLFSSL_CERT_GEN) /* Make Cert / Sign example for ECC cert and RSA CA */ static int rsa_ecc_certgen_test(WC_RNG* rng, byte* tmp) { @@ -17445,7 +17449,7 @@ WOLFSSL_TEST_SUBROUTINE int rsa_test(void) if (ret != 0) goto exit_rsa; -#if !defined(NO_RSA) && defined(HAVE_ECC) +#if !defined(NO_RSA) && defined(HAVE_ECC) && !defined(NO_ECC_SECP) ret = rsa_ecc_certgen_test(&rng, tmp); if (ret != 0) goto exit_rsa; @@ -26268,7 +26272,7 @@ static int ecc_test_custom_curves(WC_RNG* rng) } #endif /* WOLFSSL_CUSTOM_CURVES */ -#if defined(WOLFSSL_CERT_GEN) && !defined(NO_ASN_TIME) +#if defined(WOLFSSL_CERT_GEN) && !defined(NO_ECC_SECP) && !defined(NO_ASN_TIME) /* Make Cert / Sign example for ECC cert and ECC CA */ static int ecc_test_cert_gen(WC_RNG* rng) @@ -27167,7 +27171,8 @@ WOLFSSL_TEST_SUBROUTINE int ecc_test(void) goto done; } #endif -#if defined(HAVE_ECC_CDH) && defined(HAVE_ECC_DHE) +#if defined(HAVE_ECC_VECTOR_TEST) && defined(HAVE_ECC_CDH) && \ + defined(HAVE_ECC_DHE) ret = ecc_test_cdh_vectors(&rng); if (ret != 0) { printf("ecc_test_cdh_vectors failed! %d\n", ret); @@ -27185,7 +27190,7 @@ WOLFSSL_TEST_SUBROUTINE int ecc_test(void) #elif defined(HAVE_ECC_KEY_IMPORT) (void)ecc_test_make_pub; /* for compiler warning */ #endif -#if defined(WOLFSSL_CERT_GEN) && !defined(NO_ASN_TIME) +#if defined(WOLFSSL_CERT_GEN) && !defined(NO_ECC_SECP) && !defined(NO_ASN_TIME) ret = ecc_test_cert_gen(&rng); if (ret != 0) { printf("ecc_test_cert_gen failed!: %d\n", ret); @@ -27996,7 +28001,7 @@ WOLFSSL_TEST_SUBROUTINE int ecc_encrypt_test(void) #if defined(USE_CERT_BUFFERS_256) && !defined(WOLFSSL_ATECC508A) && \ !defined(WOLFSSL_ATECC608A) && !defined(NO_ECC256) && \ defined(HAVE_ECC_VERIFY) && defined(HAVE_ECC_SIGN) && \ - !defined(WOLF_CRYPTO_CB_ONLY_ECC) + !defined(WOLF_CRYPTO_CB_ONLY_ECC) && !defined(NO_ECC_SECP) WOLFSSL_TEST_SUBROUTINE int ecc_test_buffers(void) { size_t bytes; From 2bf5b432e636f82d02611b9dc47f3d51d5cfb898 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Mon, 15 May 2023 14:12:53 -0600 Subject: [PATCH 282/391] Fix for conflicting types for HAL timer --- wolfssl/wolfcrypt/wc_port.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 98606204b51..c44ce4a2e5e 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -964,7 +964,7 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #elif defined(HAL_RTC_MODULE_ENABLED) #include - WOLFSSL_LOCAL time_t* stm32_hal_time(time_t* t1); + WOLFSSL_LOCAL time_t stm32_hal_time(time_t* t1); #define XTIME(t1) stm32_hal_time(t1) #define WOLFSSL_GMTIME #else From aef49546d21c8f9b899d17dbcf25dd61936b8c99 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 9 May 2023 13:22:39 +0000 Subject: [PATCH 283/391] dtls13: fix: check plaintext record header epoch is 0 In DTLS v1.3 the normal (plaintext) record header can be used only with unprotected message (epoch == 0). Protected messages use the unified header. Check this invariant using `IsAtLeastTLSv1_3` instead of `ssl->options.tls1_3` because the latter is false before version negotiation. In DTLSv1.2 the DTLS normal header is used for all the epoch, this check doesn't interfere because: 1. the first CH's epoch must be zero in all DTLS versions 2. In case of downgrade after version negotiation `IsAtLeastTLSv1_3` is false --- src/internal.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/internal.c b/src/internal.c index 109f1caf63c..97ec44c544e 100644 --- a/src/internal.c +++ b/src/internal.c @@ -10421,16 +10421,19 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, ENUM_LEN + VERSION_SZ); *inOutIdx += ENUM_LEN + VERSION_SZ; ato16(ssl->buffers.inputBuffer.buffer + *inOutIdx, &ssl->keys.curEpoch); + #ifdef WOLFSSL_DTLS13 /* only non protected message can use the DTLSPlaintext record header */ - if (ssl->options.tls1_3 && ssl->keys.curEpoch != 0) + if (IsAtLeastTLSv1_3(ssl->version)) { + if (ssl->keys.curEpoch != 0) return SEQUENCE_ERROR; - w64Zero(&ssl->keys.curEpoch64); - if (!w64IsZero(ssl->dtls13DecryptEpoch->epochNumber)) - Dtls13SetEpochKeys(ssl, ssl->keys.curEpoch64, DECRYPT_SIDE_ONLY); - + w64Zero(&ssl->keys.curEpoch64); + if (!w64IsZero(ssl->dtls13DecryptEpoch->epochNumber)) + Dtls13SetEpochKeys(ssl, ssl->keys.curEpoch64, DECRYPT_SIDE_ONLY); + } #endif /* WOLFSSL_DTLS13 */ + *inOutIdx += OPAQUE16_LEN; if (ssl->options.haveMcast) { #ifdef WOLFSSL_MULTICAST From 0a1e5dbb64437255b8712051b26714ea554a6044 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 9 May 2023 13:31:48 +0000 Subject: [PATCH 284/391] test: add check that CH with epoch != 0 are ignored --- tests/api.c | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/tests/api.c b/tests/api.c index 5ccee232126..d9958a5a324 100644 --- a/tests/api.c +++ b/tests/api.c @@ -65778,6 +65778,76 @@ static int test_override_alt_cert_chain(void) } #endif +#if defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(WOLFSSL_DTLS13) + + +static int test_dtls13_bad_epoch_ch(void) +{ + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + const int EPOCH_OFF = 3; + int ret, err; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ret = test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfDTLSv1_3_client_method, wolfDTLSv1_3_server_method); + if (ret != 0) + return TEST_FAIL; + + /* disable hrr cookie so we can later check msgsReceived.got_client_hello + * with just one message */ + ret = wolfSSL_disable_hrr_cookie(ssl_s); + if (ret != WOLFSSL_SUCCESS) + return TEST_FAIL; + + ret = wolfSSL_connect(ssl_c); + err = wolfSSL_get_error(ssl_c, ret); + if (ret == WOLFSSL_SUCCESS || err != WOLFSSL_ERROR_WANT_READ) + return TEST_FAIL; + + if (test_ctx.s_len < EPOCH_OFF + 2) + return TEST_FAIL; + + /* first CH should use epoch 0x0 */ + if (test_ctx.s_buff[EPOCH_OFF] != 0x0 || + test_ctx.s_buff[EPOCH_OFF + 1] != 0x0) + return TEST_FAIL; + + /* change epoch to 2 */ + test_ctx.s_buff[EPOCH_OFF + 1] = 0x2; + + ret = wolfSSL_accept(ssl_s); + err = wolfSSL_get_error(ssl_s, ret); + if (ret == WOLFSSL_SUCCESS || err != WOLFSSL_ERROR_WANT_READ) + return TEST_FAIL; + + if (ssl_s->msgsReceived.got_client_hello == 1) + return TEST_FAIL; + + /* resend the CH */ + ret = wolfSSL_dtls_got_timeout(ssl_c); + if (ret != WOLFSSL_SUCCESS) + return TEST_FAIL; + + ret = test_memio_do_handshake(ssl_c, ssl_s, 10, NULL); + if (ret != 0) + return TEST_FAIL; + + wolfSSL_free(ssl_c); + wolfSSL_CTX_free(ctx_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_s); + + return TEST_SUCCESS; +} +#else +static int test_dtls13_bad_epoch_ch(void) +{ + return TEST_SKIPPED; +} +#endif + /*----------------------------------------------------------------------------* | Main @@ -66815,6 +66885,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_extra_alerts_bad_psk), TEST_DECL(test_harden_no_secure_renegotiation), TEST_DECL(test_override_alt_cert_chain), + TEST_DECL(test_dtls13_bad_epoch_ch), /* If at some point a stub get implemented this test should fail indicating * a need to implement a new test case */ From 0176551091229b30f66a0dcaf1732ef0b3e5d03f Mon Sep 17 00:00:00 2001 From: Eric Blankenhorn Date: Tue, 16 May 2023 09:44:00 -0500 Subject: [PATCH 285/391] Documentation for wolfSSL_CertManagerFreeCRL --- doc/dox_comments/header_files/ssl.h | 34 ++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/doc/dox_comments/header_files/ssl.h b/doc/dox_comments/header_files/ssl.h index 03ddb76e596..ccb2f8bd19e 100644 --- a/doc/dox_comments/header_files/ssl.h +++ b/doc/dox_comments/header_files/ssl.h @@ -9825,7 +9825,8 @@ int wolfSSL_CertManagerDisableCRL(WOLFSSL_CERT_MANAGER*); /*! \ingroup CertManager \brief Error checks and passes through to LoadCRL() in order to load the - cert into the CRL for revocation checking. + cert into the CRL for revocation checking. An updated CRL can be loaded by + first calling wolfSSL_CertManagerFreeCRL, then loading the new CRL. \return SSL_SUCCESS if there is no error in wolfSSL_CertManagerLoadCRL and if LoadCRL returns successfully. @@ -9853,6 +9854,7 @@ int wolfSSL_CertManagerDisableCRL(WOLFSSL_CERT_MANAGER*); \sa wolfSSL_CertManagerEnableCRL \sa wolfSSL_LoadCRL + \sa wolfSSL_CertManagerFreeCRL */ int wolfSSL_CertManagerLoadCRL(WOLFSSL_CERT_MANAGER* cm, const char* path, int type, int monitor); @@ -9935,6 +9937,36 @@ int wolfSSL_CertManagerLoadCRLBuffer(WOLFSSL_CERT_MANAGER* cm, int wolfSSL_CertManagerSetCRL_Cb(WOLFSSL_CERT_MANAGER* cm, CbMissingCRL cb); +/*! + \ingroup CertManager + \brief This function frees the CRL stored in the Cert Manager. An + application can update the CRL by calling wolfSSL_CertManagerFreeCRL + and then loading the new CRL. + + \return SSL_SUCCESS returned upon successful execution of the function and + subroutines. + \return BAD_FUNC_ARG returned if the WOLFSSL_CERT_MANAGER structure is NULL. + + \param cm a pointer to a WOLFSSL_CERT_MANAGER structure, created using + wolfSSL_CertManagerNew(). + + _Example_ + \code + #include + + const char* crl1 = "./certs/crl/crl.pem"; + WOLFSSL_CERT_MANAGER* cm = NULL; + + cm = wolfSSL_CertManagerNew(); + wolfSSL_CertManagerLoadCRL(cm, crl1, WOLFSSL_FILETYPE_PEM, 0); + … + wolfSSL_CertManagerFreeCRL(cm); + \endcode + + \sa wolfSSL_CertManagerLoadCRL +*/ +int wolfSSL_CertManagerFreeCRL(WOLFSSL_CERT_MANAGER* cm); + /*! \ingroup CertManager \brief The function enables the WOLFSSL_CERT_MANAGER’s member, ocspEnabled From 1c4de32e97ba459bb7cd6a1caf6e095d13ff0014 Mon Sep 17 00:00:00 2001 From: Kareem Date: Tue, 16 May 2023 14:31:51 -0700 Subject: [PATCH 286/391] Update AES documentation to clarify block size requirement. Fix parameter ordering in wc_ChaCha20Poly1305_Decrypt documentation. --- doc/dox_comments/header_files/aes.h | 8 ++++++++ doc/dox_comments/header_files/chacha20_poly1305.h | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/doc/dox_comments/header_files/aes.h b/doc/dox_comments/header_files/aes.h index 1b281ba5101..3a9b974f90d 100644 --- a/doc/dox_comments/header_files/aes.h +++ b/doc/dox_comments/header_files/aes.h @@ -136,8 +136,10 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, \param aes pointer to the AES object used to decrypt data. \param out pointer to the output buffer in which to store the plain text of the decrypted message. + size must be a multiple of AES_BLOCK_LENGTH, padded if necessary \param in pointer to the input buffer containing cipher text to be decrypted. + size must be a multiple of AES_BLOCK_LENGTH, padded if necessary \param sz size of input message. _Example_ @@ -176,7 +178,9 @@ int wc_AesCbcDecrypt(Aes* aes, byte* out, \param aes pointer to the AES object used to decrypt data \param out pointer to the output buffer in which to store the cipher text of the encrypted message + size must be a multiple of AES_BLOCK_LENGTH, padded if necessary \param in pointer to the input buffer containing plain text to be encrypted + size must be a multiple of AES_BLOCK_LENGTH, padded if necessary \param sz size of the input plain text _Example_ @@ -353,7 +357,9 @@ int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len); \param aes - pointer to the AES object used to encrypt data \param out pointer to the output buffer in which to store the cipher text + size must match in's size (sz) \param in pointer to the input buffer holding the message to encrypt + size must be a multiple of AES_BLOCK_LENGTH, padded if necessary \param sz length of the input message to encrypt \param iv pointer to the buffer containing the initialization vector \param ivSz length of the initialization vector @@ -403,7 +409,9 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, \param aes pointer to the AES object used to encrypt data \param out pointer to the output buffer in which to store the message text + size must match in's size (sz) \param in pointer to the input buffer holding the cipher text to decrypt + size must be a multiple of AES_BLOCK_LENGTH, padded if necessary \param sz length of the cipher text to decrypt \param iv pointer to the buffer containing the initialization vector \param ivSz length of the initialization vector diff --git a/doc/dox_comments/header_files/chacha20_poly1305.h b/doc/dox_comments/header_files/chacha20_poly1305.h index 6a8e59a7d2e..5a7f819508b 100644 --- a/doc/dox_comments/header_files/chacha20_poly1305.h +++ b/doc/dox_comments/header_files/chacha20_poly1305.h @@ -97,7 +97,7 @@ int wc_ChaCha20Poly1305_Encrypt( byte plain[sizeof(cipher)]; int ret = wc_ChaCha20Poly1305_Decrypt(key, iv, inAAD, sizeof(inAAD), - cipher, sizeof(cipher), plain, authTag); + cipher, sizeof(cipher), authTag, plain); if(ret == MAC_CMP_FAILED_E) { // error during authentication From 2fb885bea5099d43333d37dfd887dce451a9a7e9 Mon Sep 17 00:00:00 2001 From: Eric Blankenhorn Date: Tue, 16 May 2023 14:38:51 -0500 Subject: [PATCH 287/391] Fix valgrind issue with memcpy --- wolfcrypt/src/aes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 3dc391c5fec..1ab87695c07 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -8410,7 +8410,7 @@ int wc_AesGcmInit(Aes* aes, const byte* key, word32 len, const byte* iv, if (ret == 0) { /* Set the IV passed in if it is smaller than a block. */ if ((iv != NULL) && (ivSz <= AES_BLOCK_SIZE)) { - XMEMCPY((byte*)aes->reg, iv, ivSz); + XMEMMOVE((byte*)aes->reg, iv, ivSz); aes->nonceSz = ivSz; } /* No IV passed in, check for cached IV. */ From e3aeef3480fe50e3907dcd8ff7a3c5801ebce4c2 Mon Sep 17 00:00:00 2001 From: oltolm Date: Wed, 17 May 2023 23:26:46 +0200 Subject: [PATCH 288/391] CMake: improve build scripts (#6331) * make wolfssl compile with Mingw-w64 * cmake: CMAKE_SYSTEM_PROCESSOR is AMD64 on Windows * cmake: use target_compile_definitions instead of add_definitions * cmake: change default value of WOLFSSL_BUILD_OUT_OF_TREE_DEFAULT to ON * cmake: link crypt32.lib on Windows * cmake: export wolfssl * move Config.cmake.in to cmake directory * revert changes to .gitignore * add Config.cmake.in to include.am --- .gitignore | 2 +- CMakeLists.txt | 55 +++++++++++++++++++++++++++++--------- cmake/Config.cmake.in | 3 +++ cmake/include.am | 1 + wolfssl/wolfcrypt/sp_int.h | 2 +- wolfssl/wolfcrypt/types.h | 2 +- 6 files changed, 49 insertions(+), 16 deletions(-) create mode 100644 cmake/Config.cmake.in diff --git a/.gitignore b/.gitignore index d6e72cb5581..0279aadbc43 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,7 @@ ctaocrypt/src/src/ *.cache .dirstamp *.user -configure +configure config.* !cmake/config.in *Debug/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 7628354a591..5703e0da283 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -548,7 +548,7 @@ endif() # SHA224 set(SHA224_DEFAULT "no") -if(("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") OR +if(("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64") OR ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")) if(NOT WOLFSSL_AFALG AND NOT WOLFSSL_DEVCRYPTO AND (NOT WOLFSSL_FIPS OR ("${FIPS_VERSION}" STREQUAL "v2"))) @@ -562,7 +562,7 @@ add_option("WOLFSSL_SHA224" # SHA3 set(SHA3_DEFAULT "no") -if(("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") OR +if(("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64") OR ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")) if(NOT WOLFSSL_FIPS OR ("${FIPS_VERSION}" STREQUAL "v2")) set(SHA3_DEFAULT "yes") @@ -1048,7 +1048,7 @@ endif() # Base64 set(BASE64_ENCODE_DEFAULT "no") -if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") +if("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64") set(BASE64_ENCODE_DEFAULT "yes") endif() @@ -1526,7 +1526,7 @@ if(WOLFSSL_FAST_MATH) set(WOLFSSL_SLOWMATH "no") endif() - if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") + if("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64") # Have settings.h set FP_MAX_BITS higher if user didn't set directly list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_X86_64_BUILD") endif() @@ -1534,7 +1534,7 @@ endif() # TODO: - Fast huge math -if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") +if("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64") list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_X86_64_BUILD") endif() @@ -1908,10 +1908,6 @@ if(WOLFSSL_USER_SETTINGS_ASM) endif() endif() -# TODO: Applying definitions to everything like this, rather than -# individual targets, is discouraged in CMake. -add_definitions(${WOLFSSL_DEFINITIONS}) - add_option("WOLFSSL_CONFIG_H" "Enable generation of config.h and define HAVE_CONFIG_H (default: enabled)" "yes" "yes;no") @@ -1933,7 +1929,7 @@ message("Generating user options header...") if (${CMAKE_DISABLE_SOURCE_CHANGES}) set(WOLFSSL_BUILD_OUT_OF_TREE_DEFAULT "${CMAKE_DISABLE_SOURCE_CHANGES}") else() - set(WOLFSSL_BUILD_OUT_OF_TREE_DEFAULT "no") + set(WOLFSSL_BUILD_OUT_OF_TREE_DEFAULT "yes") endif() add_option("WOLFSSL_BUILD_OUT_OF_TREE" "Don't generate files in the source tree (default: ${WOLFSSL_BUILD_OUT_OF_TREE_DEFAULT})" @@ -1995,7 +1991,13 @@ set(LIB_SOURCES "") # Corresponds to the instances of "src_libwolfssl_la_SOURCES += ..." # in the *.am files. generate_lib_src_list("${LIB_SOURCES}") -add_library(wolfssl ${LIB_SOURCES}) +if(BUILD_SHARED_LIBS) + add_library(wolfssl SHARED ${LIB_SOURCES}) +else() + add_library(wolfssl STATIC ${LIB_SOURCES}) +endif() + +add_library(wolfssl::wolfssl ALIAS wolfssl) set_target_properties(wolfssl PROPERTIES @@ -2007,6 +2009,7 @@ target_compile_definitions(wolfssl PRIVATE "BUILDING_WOLFSSL") if(${BUILD_SHARED_LIBS}) target_compile_definitions(wolfssl PUBLIC "WOLFSSL_DLL") endif() +target_compile_definitions(wolfssl PUBLIC ${WOLFSSL_DEFINITIONS}) #################################################### # Include Directories @@ -2029,7 +2032,7 @@ target_link_libraries(wolfssl PUBLIC ${WOLFSSL_LINK_LIBS}) if(WIN32) # For Windows link ws2_32 target_link_libraries(wolfssl PUBLIC - $<$:ws2_32>) + $<$:ws2_32 crypt32>) elseif(APPLE) if(WOLFSSL_SYS_CA_CERTS) target_link_libraries(wolfssl PUBLIC @@ -2350,7 +2353,8 @@ install(FILES # Install the export set install(EXPORT wolfssl-targets DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/wolfssl - FILE wolfssl-config.cmake) + FILE wolfssl-targets.cmake + NAMESPACE wolfssl::) # TODO: Distro build + rules for what to include in the distro. # See various include.am files. @@ -2364,3 +2368,28 @@ set(VERSION ${PROJECT_VERSION}) configure_file(support/wolfssl.pc.in ${CMAKE_CURRENT_BINARY_DIR}/support/wolfssl.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/support/wolfssl.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) + +include(CMakePackageConfigHelpers) +configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/Config.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/wolfssl-config.cmake" + INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/wolfssl" + NO_SET_AND_CHECK_MACRO + NO_CHECK_REQUIRED_COMPONENTS_MACRO +) + +export(EXPORT wolfssl-targets + FILE "${CMAKE_CURRENT_BINARY_DIR}/wolfssl-targets.cmake" + NAMESPACE wolfssl:: +) + +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/wolfssl-config-version.cmake" + VERSION "${wolfssl_VERSION_MAJOR}.${wolfssl_VERSION_MINOR}" + COMPATIBILITY AnyNewerVersion +) + +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/wolfssl-config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/wolfssl-config-version.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/wolfssl +) diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in new file mode 100644 index 00000000000..19d60ed7ea5 --- /dev/null +++ b/cmake/Config.cmake.in @@ -0,0 +1,3 @@ +@PACKAGE_INIT@ + +include ( "${CMAKE_CURRENT_LIST_DIR}/wolfssl-targets.cmake" ) diff --git a/cmake/include.am b/cmake/include.am index 9d9bc038c81..52ecdd0e23b 100644 --- a/cmake/include.am +++ b/cmake/include.am @@ -1,3 +1,4 @@ +EXTRA_DIST += cmake/Config.cmake.in EXTRA_DIST += cmake/config.in EXTRA_DIST += cmake/functions.cmake EXTRA_DIST += cmake/modules/FindOQS.cmake diff --git a/wolfssl/wolfcrypt/sp_int.h b/wolfssl/wolfcrypt/sp_int.h index d96c7480eba..1a9704f88e3 100644 --- a/wolfssl/wolfcrypt/sp_int.h +++ b/wolfssl/wolfcrypt/sp_int.h @@ -234,7 +234,7 @@ extern "C" { #ifndef SP_WORD_SIZE #ifdef NO_64BIT #define SP_WORD_SIZE 16 - #elif !defined(HAVE___UINT128_T) + #elif !defined(HAVE___UINT128_T) || defined(_WIN32) #define SP_WORD_SIZE 32 #else #define SP_WORD_SIZE 64 diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index cd6d4205105..f274baf8318 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -141,7 +141,7 @@ decouple library dependencies with standard string, memory and so on. #define WC_STRINGIFY(str) _WC_STRINGIFY_L2(str) /* try to set SIZEOF_LONG or SIZEOF_LONG_LONG if user didn't */ - #if defined(_MSC_VER) || defined(HAVE_LIMITS_H) + #if defined(_WIN32) || defined(HAVE_LIMITS_H) /* make sure both SIZEOF_LONG_LONG and SIZEOF_LONG are set, * otherwise causes issues with CTC_SETTINGS */ #if !defined(SIZEOF_LONG_LONG) || !defined(SIZEOF_LONG) From 75161e9d2e909481015d3a491e05b35ce4b79db1 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:03:26 -0500 Subject: [PATCH 289/391] add --enable-linuxkm-benchmarks; add check for async.{c,h} when --enable-asynccrypt; update failure message for the opensslextra AC_CHECK_HEADER() test. --- Makefile.am | 2 +- configure.ac | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Makefile.am b/Makefile.am index e6d7fcb91cb..f3decb03ce8 100644 --- a/Makefile.am +++ b/Makefile.am @@ -218,7 +218,7 @@ if BUILD_LINUXKM CFLAGS_FPU_DISABLE CFLAGS_FPU_ENABLE CFLAGS_SIMD_DISABLE CFLAGS_SIMD_ENABLE \ CFLAGS_AUTO_VECTORIZE_DISABLE CFLAGS_AUTO_VECTORIZE_ENABLE \ ASFLAGS_FPU_DISABLE_SIMD_ENABLE ASFLAGS_FPU_ENABLE_SIMD_DISABLE \ - ASFLAGS_FPUSIMD_DISABLE ASFLAGS_FPUSIMD_ENABLE + ASFLAGS_FPUSIMD_DISABLE ASFLAGS_FPUSIMD_ENABLE ENABLED_LINUXKM_BENCHMARKS module: +$(MAKE) -C linuxkm libwolfssl.ko diff --git a/configure.ac b/configure.ac index 538460478a2..699dd55d30f 100644 --- a/configure.ac +++ b/configure.ac @@ -495,6 +495,16 @@ then fi AC_SUBST([ENABLED_LINUXKM_PIE]) +AC_ARG_ENABLE([linuxkm-benchmarks], + [AS_HELP_STRING([--enable-linuxkm-benchmarks],[Enable crypto benchmarking autorun at module load time for Linux kernel module (default: disabled)])], + [ENABLED_LINUXKM_BENCHMARKS=$enableval], + [ENABLED_LINUXKM_BENCHMARKS=no] + ) +if test "$ENABLED_LINUXKM_BENCHMARKS" = "yes" +then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_LINUXKM_BENCHMARKS" +fi +AC_SUBST([ENABLED_LINUXKM_BENCHMARKS]) if test "$ENABLED_LINUXKM_DEFAULTS" = "yes" then @@ -7382,6 +7392,11 @@ fi if test "$ENABLED_ASYNCCRYPT" = "yes" then + if ! test -f ${srcdir}/wolfcrypt/src/async.c || ! test -f ${srcdir}/wolfssl/wolfcrypt/async.h + then + AC_MSG_ERROR([--enable-asynccrypt requested, but WOLFSSL_ASYNC_CRYPT source files are missing.]) + fi + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_ASYNC_CRYPT -DHAVE_WOLF_EVENT -DHAVE_WOLF_BIGINT -DWOLFSSL_NO_HASH_RAW" # If no async backend (hardware or software) has been explicitly enabled, @@ -8823,9 +8838,9 @@ then for header in $openssl_headers do AC_CHECK_HEADER([$header], [], [ - AC_MSG_ERROR([Error including $header. Possible circular dependency introduced or missing include.]) + AC_MSG_ERROR([Header file inconsistency detected -- error including ${header}.]) ], [ - #include + #include <${OPTION_FILE}> extern int dummy_int_to_make_compiler_happy; ]) done @@ -8865,6 +8880,7 @@ echo " * FPU enable as flags: $ASFLAGS_FPU_ENABLE_SIMD_DISABLE" && \ echo " * SIMD+FPU disable as flags: $ASFLAGS_FPUSIMD_DISABLE" && \ echo " * SIMD+FPU enable as flags: $ASFLAGS_FPUSIMD_ENABLE" && \ echo " * Linux kernel module PIE: $ENABLED_LINUXKM_PIE" +echo " * Linux kernel module bench: $ENABLED_LINUXKM_BENCHMARKS" echo " * Debug enabled: $ax_enable_debug" echo " * Coverage enabled: $ax_enable_coverage" From 062948cf3be5ce2405110c23c2747d38ae4cc70d Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:04:40 -0500 Subject: [PATCH 290/391] refactor benchmark.c for linux kernel compatibility -- WOLFSSL_SMALL_STACK and WOLFSSL_NO_FLOAT_FMT codepaths, SAVE/RESTORE_VECTOR_REGISTERS, refactor of several stack array initializations that broke in the kernel, and replacement of an fputs() call with printf(). --- wolfcrypt/benchmark/benchmark.c | 459 +++++++++++++++++++++++--------- 1 file changed, 337 insertions(+), 122 deletions(-) diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 5d354d9bec9..59a51cc0de2 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -65,6 +65,28 @@ #include #include +#ifdef WOLFSSL_NO_FLOAT_FMT + #define FLT_FMT "%0ld,%09lu" + #define FLT_FMT_PREC "%0ld.%0*lu" + #define FLT_FMT_PREC2 FLT_FMT_PREC + #define FLT_FMT_ARGS(x) (long)(x), ((x) < 0) ? (unsigned long)(-(((x) - (double)(long)(x)) * 1000000000.0)) : (unsigned long)(((x) - (double)(long)(x)) * 1000000000.0) + static const double pow_10_array[] = { 0.0, 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0 }; + #define FLT_FMT_PREC_ARGS(p, x) \ + (long)(x), \ + p, \ + (x) >= 0.0 ? \ + (unsigned long int)((((x) - (double)(long)(x)) * pow_10_array[(p)+1]) + 0.5) : \ + (unsigned long int)((((-(x)) - (double)((long)-(x))) * pow_10_array[(p)+1]) + 0.5) + #define FLT_FMT_PREC2_ARGS(w, p, x) FLT_FMT_PREC_ARGS(p, x) +#else + #define FLT_FMT "%f" + #define FLT_FMT_PREC "%.*f" + #define FLT_FMT_PREC2 "%*.*f" + #define FLT_FMT_ARGS(x) x + #define FLT_FMT_PREC_ARGS(p, x) p, x + #define FLT_FMT_PREC2_ARGS(w, p, x) w, p, x +#endif + #ifdef WOLFSSL_ESPIDF #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) #include "driver/gptimer.h" @@ -922,12 +944,12 @@ static const char* bench_desc_words[][15] = { #define END_INTEL_CYCLES total_cycles = get_intel_cycles() - total_cycles; /* s == size in bytes that 1 count represents, normally BENCH_SIZE */ #define SHOW_INTEL_CYCLES(b, n, s) \ - (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), " %s = %6.2f\n", \ + (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), " %s = " FLT_FMT_PREC2 "\n", \ bench_result_words1[lng_index][2], \ - count == 0 ? 0 : (double)total_cycles / ((word64)count*(s))) + FLT_FMT_PREC2_ARGS(6, 2, count == 0 ? 0 : (double)total_cycles / ((word64)count*(s)))) #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ - (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), "%.6f,\n", \ - count == 0 ? 0 : (double)total_cycles / ((word64)count*(s))) + (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), FLT_FMT_PREC ",\n", \ + FLT_FMT_PREC_ARGS(6, count == 0 ? 0 : (double)total_cycles / ((word64)count*(s)))) #elif defined(LINUX_CYCLE_COUNT) #include #include @@ -952,12 +974,12 @@ static const char* bench_desc_words[][15] = { /* s == size in bytes that 1 count represents, normally BENCH_SIZE */ #define SHOW_INTEL_CYCLES(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = %6.2f\n", \ + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = " FLT_FMT_PREC2 "\n", \ bench_result_words1[lng_index][2], \ - (float)total_cycles / (count*s)) + FLT_FMT_PREC2_ARGS(6, 2, (double)total_cycles / (count*s))) #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), "%.6f,\n", \ - (float)total_cycles / (count*s)) + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), FLT_FMT_PREC ",\n", \ + FLT_FMT_PREC_ARGS(6, (double)total_cycles / (count*s))) #elif defined(SYNERGY_CYCLE_COUNT) #include "hal_data.h" @@ -970,12 +992,12 @@ static const char* bench_desc_words[][15] = { /* s == size in bytes that 1 count represents, normally BENCH_SIZE */ #define SHOW_INTEL_CYCLES(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = %6.2f\n", \ + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = " FLT_FMT_PREC2 "\n", \ bench_result_words1[lng_index][2], \ - (float)total_cycles / (count*s)) + FLT_FMT_PREC2_ARGS(6, 2, (double)total_cycles / (count*s))) #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), "%.6f,\n", \ - (float)total_cycles / (count*s)) + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), FLT_FMT_PREC ",\n", \ + FLT_FMT_PREC_ARGS(6, (double)total_cycles / (count*s))) #elif defined(WOLFSSL_ESPIDF) static THREAD_LS_T word64 begin_cycles; static THREAD_LS_T word64 total_cycles; @@ -1005,14 +1027,14 @@ static const char* bench_desc_words[][15] = { total_cycles = (get_xtensa_cycles() - begin_cycles); #define SHOW_ESP_CYCLES(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = %6.2f\n", \ + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = " FLT_FMT_PREC2 "\n", \ bench_result_words1[lng_index][2], \ - (float)total_cycles / (count*s) \ + FLT_FMT_PREC2_ARGS(6, 2, (double)total_cycles / (count*s)) \ ) #define SHOW_ESP_CYCLES_CSV(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), "%.6f,\n", \ - (float)total_cycles / (count*s)) + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), FLT_FMT_PREC ",\n", \ + FLT_FMT_PREC_ARGS(6, (double)total_cycles / (count*s))) /* xthal_get_ccount_ex() is a single-overflow-tolerant extension to ** the Espressif `unsigned xthal_get_ccount()` which is known to overflow @@ -1283,7 +1305,7 @@ static const char* bench_result_words2[][5] = { } #else - #define BENCH_MAX_PENDING (1) + #define BENCH_MAX_PENDING 1 #define BENCH_ASYNC_GET_DEV(obj) NULL static WC_INLINE int bench_async_check(int* ret, void* asyncDev, @@ -1590,14 +1612,14 @@ typedef enum bench_stat_type { for (bstat = bench_stats_head; bstat != NULL; ) { if (bstat->type == BENCH_STAT_SYM) { - printf("%-16s%s %8.3f %s/s\n", bstat->desc, - BENCH_DEVID_GET_NAME(bstat->useDeviceID), bstat->perfsec, + printf("%-16s%s " FLT_FMT_PREC2 " %s/s\n", bstat->desc, + BENCH_DEVID_GET_NAME(bstat->useDeviceID), FLT_FMT_PREC2_ARGS(8, 3, bstat->perfsec), base2 ? "MB" : "mB"); } else { - printf("%-5s %4d %-9s %s %.3f ops/sec\n", + printf("%-5s %4d %-9s %s " FLT_FMT_PREC " ops/sec\n", bstat->algo, bstat->strength, bstat->desc, - BENCH_DEVID_GET_NAME(bstat->useDeviceID), bstat->perfsec); + BENCH_DEVID_GET_NAME(bstat->useDeviceID), FLT_FMT_PREC_ARGS(3, bstat->perfsec)); } bstat = bstat->next; @@ -1651,12 +1673,12 @@ typedef enum bench_stat_type { for (i=0; itype == BENCH_STAT_SYM) { - printf("%-16s %8.3f %s/s\n", bstat->desc, bstat->perfsec, + printf("%-16s " FLT_FMT_PREC2 " %s/s\n", bstat->desc, FLT_FMT_PREC2_ARGS(8, 3, bstat->perfsec), base2 ? "MB" : "mB"); } else if (bstat->type == BENCH_STAT_ASYM) { - printf("%-5s %4d %-9s %.3f ops/sec\n", - bstat->algo, bstat->strength, bstat->desc, bstat->perfsec); + printf("%-5s %4d %-9s " FLT_FMT_PREC " ops/sec\n", + bstat->algo, bstat->strength, bstat->desc, FLT_FMT_PREC_ARGS(3, bstat->perfsec)); } } } @@ -1673,12 +1695,14 @@ static WC_INLINE void bench_stats_init(void) static WC_INLINE void bench_stats_start(int* count, double* start) { + SAVE_VECTOR_REGISTERS(pr_err("SAVE_VECTOR_REGISTERS failed for benchmark run.");); + *count = 0; *start = current_time(1); #ifdef WOLFSSL_ESPIDF - ESP_LOGV(TAG, "finish total_cycles = %llu, start=%f", - total_cycles, *start ); + ESP_LOGV(TAG, "finish total_cycles = %llu, start=" FLT_FMT, + total_cycles, FLT_FMT_ARG(*start) ); BEGIN_ESP_CYCLES #else @@ -1785,10 +1809,12 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, { double total, persec = 0, blocks = (double)count; const char* blockType; - char msg[__BENCHMARK_MAXIMUM_LINE_LENGTH] = {0}; + char msg[__BENCHMARK_MAXIMUM_LINE_LENGTH]; const char** word = bench_result_words1[lng_index]; static int sym_header_printed = 0; + XMEMSET(msg, 0, sizeof(msg)); + #ifdef WOLFSSL_ESPIDF END_ESP_CYCLES #else @@ -1873,9 +1899,9 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, /* note this codepath brings in all the fields from the non-CSV case. */ #ifdef WOLFSSL_ESPIDF #ifdef HAVE_GET_CYCLES - (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu,%f,%f,%lu,", desc, + (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu," FLT_FMT "," FLT_FMT ",%lu,", desc, BENCH_DEVID_GET_NAME(useDeviceID), - bytes_processed, total, persec, + bytes_processed, FLT_FMT_ARGS(total), FLT_FMT_ARGS(persec), (long unsigned int) total_cycles); #else #warning "HAVE_GET_CYCLES should be defined for WOLFSSL_ESPIDF" @@ -1885,20 +1911,20 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, #else #ifdef HAVE_GET_CYCLES - (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu,%f,%f,%lu,", desc, + (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu," FLT_FMT "," FLT_FMT ",%lu,", desc, BENCH_DEVID_GET_NAME(useDeviceID), - bytes_processed, total, persec, total_cycles); + bytes_processed, FLT_FMT_ARGS(total), FLT_FMT_ARGS(persec), total_cycles); #else - (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu,%f,%f,", desc, + (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu," FLT_FMT "," FLT_FMT ",", desc, BENCH_DEVID_GET_NAME(useDeviceID), - bytes_processed, total, persec); + bytes_processed, FLT_FMT_ARGS(total), FLT_FMT_ARGS(persec)); #endif #endif #elif defined(BENCH_DEVID) - (void)XSNPRINTF(msg, sizeof(msg), "%s,%s,%f,", desc, - BENCH_DEVID_GET_NAME(useDeviceID), persec); + (void)XSNPRINTF(msg, sizeof(msg), "%s,%s," FLT_FMT ",", desc, + BENCH_DEVID_GET_NAME(useDeviceID), FLT_FMT_ARGS(persec)); #else - (void)XSNPRINTF(msg, sizeof(msg), "%s,%f,", desc, persec); + (void)XSNPRINTF(msg, sizeof(msg), "%s," FLT_FMT ",", desc, FLT_FMT_ARGS(persec)); #endif #ifdef WOLFSSL_ESPIDF @@ -1914,23 +1940,23 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, #ifdef GENERATE_MACHINE_PARSEABLE_REPORT #ifdef HAVE_GET_CYCLES (void)XSNPRINTF(msg, sizeof(msg), - "%-24s%s %5.0f %s %s %5.3f %s, %8.3f %s/s" + "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " FLT_FMT_PREC2 " %s/s" ", %lu cycles,", - desc, BENCH_DEVID_GET_NAME(useDeviceID), blocks, blockType, - word[0], total, word[1], persec, blockType, + desc, BENCH_DEVID_GET_NAME(useDeviceID), FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, + word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], FLT_FMT_PREC2_ARGS(8, 3, persec), blockType, (unsigned long) total_cycles); #else (void)XSNPRINTF(msg, sizeof(msg), - "%-24s%s %5.0f %s %s %5.3f %s, %8.3f %s/s" + "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " FLT_FMT_PREC2 " %s/s" ",", - desc, BENCH_DEVID_GET_NAME(useDeviceID), blocks, blockType, - word[0], total, word[1], persec, blockType); + desc, BENCH_DEVID_GET_NAME(useDeviceID), FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, + word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], FLT_FMT_PREC2_ARGS(8, 3, persec), blockType); #endif /* HAVE_GET_CYCLES */ #else (void)XSNPRINTF(msg, sizeof(msg), - "%-24s%s %5.0f %s %s %5.3f %s, %8.3f %s/s", - desc, BENCH_DEVID_GET_NAME(useDeviceID), blocks, blockType, - word[0], total, word[1], persec, blockType); + "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " FLT_FMT_PREC2 " %s/s", + desc, BENCH_DEVID_GET_NAME(useDeviceID), FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, + word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], FLT_FMT_PREC2_ARGS(8, 3, persec), blockType); #endif #ifdef WOLFSSL_ESPIDF @@ -1961,6 +1987,8 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, (void)useDeviceID; (void)ret; + RESTORE_VECTOR_REGISTERS(); + TEST_SLEEP(); } /* bench_stats_sym_finish */ @@ -1976,9 +2004,11 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, double total, each = 0, opsSec, milliEach; const char **word = bench_result_words2[lng_index]; const char* kOpsSec = "Ops/Sec"; - char msg[256] = {0}; + char msg[256]; static int asym_header_printed = 0; + XMEMSET(msg, 0, sizeof(msg)); + total = current_time(0) - start; #ifdef LINUX_RUSAGE_UTIME @@ -2034,19 +2064,19 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, #ifdef GENERATE_MACHINE_PARSEABLE_REPORT #ifdef HAVE_GET_CYCLES (void)XSNPRINTF(msg, sizeof(msg), - "asym,%s,%d,%s%s,%.3f,%.3f,%d,%f,%lu,%.6f\n", - algo, strength, desc, desc_extra, milliEach, opsSec, - count, total, (unsigned long) total_cycles, - (double)total_cycles / (double)count); + "asym,%s,%d,%s%s," FLT_FMT_PREC "," FLT_FMT_PREC ",%d," FLT_FMT ",%lu," FLT_FMT_PREC "\n", + algo, strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), + count, FLT_FMT_ARGS(total), (unsigned long) total_cycles, + FLT_FMT_PREC_ARGS(6, (double)total_cycles / (double)count)); #else (void)XSNPRINTF(msg, sizeof(msg), - "asym,%s,%d,%s%s,%.3f,%.3f,%d,%f\n", - algo, strength, desc, desc_extra, milliEach, opsSec, - count, total); + "asym,%s,%d,%s%s," FLT_FMT_PREC "," FLT_FMT_PREC ",%d," FLT_FMT "\n", + algo, strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), + count, FLT_FMT_ARGS(total)); #endif #else - (void)XSNPRINTF(msg, sizeof(msg), "%s,%d,%s%s,%.3f,%.3f,\n", algo, - strength, desc, desc_extra, milliEach, opsSec); + (void)XSNPRINTF(msg, sizeof(msg), "%s,%d,%s%s," FLT_FMT_PREC "," FLT_FMT_PREC ",\n", algo, + strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec)); #endif } /* if (csv_format == 1) */ @@ -2054,25 +2084,25 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, #ifdef GENERATE_MACHINE_PARSEABLE_REPORT #ifdef HAVE_GET_CYCLES (void)XSNPRINTF(msg, sizeof(msg), - "%-6s %5d %8s%-2s %s %6d %s %5.3f %s, %s %5.3f ms," - " %.3f %s, %lu cycles\n", algo, strength, desc, + "%-6s %5d %8s%-2s %s %6d %s " FLT_FMT_PREC2 " %s, %s " FLT_FMT_PREC2 " ms," + " " FLT_FMT_PREC " %s, %lu cycles\n", algo, strength, desc, desc_extra, BENCH_DEVID_GET_NAME(useDeviceID), - count, word[0], total, word[1], word[2], milliEach, - opsSec, word[3], (unsigned long) total_cycles); + count, word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], FLT_FMT_PREC2_ARGS(5, 3, milliEach), + FLT_FMT_PREC_ARGS(3, opsSec), word[3], (unsigned long) total_cycles); #else (void)XSNPRINTF(msg, sizeof(msg), - "%-6s %5d %8s%-2s %s %6d %s %5.3f %s, %s %5.3f ms," - " %.3f %s\n", algo, strength, desc, + "%-6s %5d %8s%-2s %s %6d %s " FLT_FMT_PREC2 " %s, %s " FLT_FMT_PREC2 " ms," + " " FLT_FMT_PREC " %s\n", algo, strength, desc, desc_extra, BENCH_DEVID_GET_NAME(useDeviceID), - count, word[0], total, word[1], word[2], milliEach, - opsSec, word[3]); + count, word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], FLT_FMT_PREC2_ARGS(5, 3, milliEach), + FLT_FMT_PREC_ARGS(3, opsSec), word[3]); #endif /* HAVE_GET_CYCLES */ #else (void)XSNPRINTF(msg, sizeof(msg), - "%-6s %5d %8s%-2s %s %6d %s %5.3f %s, %s %5.3f ms," - " %.3f %s\n", algo, strength, desc, desc_extra, + "%-6s %5d %8s%-2s %s %6d %s " FLT_FMT_PREC2 " %s, %s " FLT_FMT_PREC2 " ms," + " " FLT_FMT_PREC " %s\n", algo, strength, desc, desc_extra, BENCH_DEVID_GET_NAME(useDeviceID), count, word[0], - total, word[1], word[2], milliEach, opsSec, word[3]); + FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], FLT_FMT_PREC2_ARGS(5, 3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), word[3]); #endif } printf("%s", msg); @@ -2094,6 +2124,8 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, (void)useDeviceID; (void)ret; + RESTORE_VECTOR_REGISTERS(); + TEST_SLEEP(); } /* bench_stats_asym_finish_ex */ @@ -2906,8 +2938,8 @@ int benchmark_init(void) wolfSSL_Debugging_ON(); #endif - printf("%swolfCrypt Benchmark (block bytes %d, min %.1f sec each)\n", - info_prefix, (int)bench_size, BENCH_MIN_RUNTIME_SEC); + printf("%swolfCrypt Benchmark (block bytes %d, min " FLT_FMT_PREC " sec each)\n", + info_prefix, (int)bench_size, FLT_FMT_PREC_ARGS(1, BENCH_MIN_RUNTIME_SEC)); #ifndef GENERATE_MACHINE_PARSEABLE_REPORT if (csv_format == 1) { @@ -3280,7 +3312,7 @@ static void bench_aesgcm_internal(int useDeviceID, int ret = 0, i, count = 0, times, pending = 0; Aes enc[BENCH_MAX_PENDING]; #ifdef HAVE_AES_DECRYPT - Aes dec[BENCH_MAX_PENDING]; + Aes dec[BENCH_MAX_PENDING+1]; #endif double start; @@ -3295,9 +3327,6 @@ static void bench_aesgcm_internal(int useDeviceID, /* clear for done cleanup */ XMEMSET(enc, 0, sizeof(enc)); -#ifdef HAVE_AES_DECRYPT - XMEMSET(dec, 0, sizeof(dec)); -#endif #ifdef WOLFSSL_ASYNC_CRYPT if (bench_additional) #endif @@ -3350,6 +3379,8 @@ static void bench_aesgcm_internal(int useDeviceID, start, ret); #ifdef HAVE_AES_DECRYPT + XMEMSET(dec, 0, sizeof(dec)); + /* init keys */ for (i = 0; i < BENCH_MAX_PENDING; i++) { if ((ret = wc_AesInit(&dec[i], HEAP_HINT, @@ -3955,7 +3986,10 @@ static void bench_aesctr_internal(const byte* key, word32 keySz, printf("wc_AesInit failed, ret = %d\n", ret); } - wc_AesSetKeyDirect(&enc, key, keySz, iv, AES_ENCRYPTION); + if (wc_AesSetKeyDirect(&enc, key, keySz, iv, AES_ENCRYPTION) < 0) { + printf("wc_AesSetKeyDirect failed, ret = %d\n", ret); + return; + } bench_stats_start(&count, &start); do { @@ -5965,7 +5999,7 @@ void bench_scrypt(void) #ifndef NO_HMAC static void bench_hmac(int useDeviceID, int type, int digestSz, - byte* key, word32 keySz, const char* label) + const byte* key, word32 keySz, const char* label) { Hmac hmac[BENCH_MAX_PENDING]; double start; @@ -6057,7 +6091,7 @@ static void bench_hmac(int useDeviceID, int type, int digestSz, void bench_hmac_md5(int useDeviceID) { - byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; bench_hmac(useDeviceID, WC_MD5, WC_MD5_DIGEST_SIZE, key, sizeof(key), @@ -6070,7 +6104,7 @@ void bench_hmac_md5(int useDeviceID) void bench_hmac_sha(int useDeviceID) { - byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; @@ -6084,7 +6118,7 @@ void bench_hmac_sha(int useDeviceID) void bench_hmac_sha224(int useDeviceID) { - byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; @@ -6100,7 +6134,7 @@ void bench_hmac_sha224(int useDeviceID) void bench_hmac_sha256(int useDeviceID) { - byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; @@ -6115,7 +6149,7 @@ void bench_hmac_sha256(int useDeviceID) void bench_hmac_sha384(int useDeviceID) { - byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, @@ -6132,7 +6166,7 @@ void bench_hmac_sha384(int useDeviceID) void bench_hmac_sha512(int useDeviceID) { - byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, @@ -6153,7 +6187,7 @@ void bench_pbkdf2(void) double start; int ret = 0, count = 0; const char* passwd32 = "passwordpasswordpasswordpassword"; - const byte salt32[] = { 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06, + static const byte salt32[] = { 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06, 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06, 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06, 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06 }; @@ -6207,14 +6241,27 @@ void bench_siphash(void) #if defined(WOLFSSL_KEY_GEN) static void bench_rsaKeyGen_helper(int useDeviceID, word32 keySz) { +#ifdef WOLFSSL_SMALL_STACK + RsaKey *genKey; +#else RsaKey genKey[BENCH_MAX_PENDING]; +#endif double start; int ret = 0, i, count = 0, times, pending = 0; const long rsa_e_val = WC_RSA_EXPONENT; const char**desc = bench_desc_words[lng_index]; +#ifdef WOLFSSL_SMALL_STACK + genKey = (RsaKey *)XMALLOC(sizeof(*genKey) * BENCH_MAX_PENDING, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (genKey == NULL) { + printf("bench_rsaKeyGen_helper malloc failed\n"); + return; + } +#endif + /* clear for done cleanup */ - XMEMSET(genKey, 0, sizeof(genKey)); + XMEMSET(genKey, 0, sizeof(*genKey) * BENCH_MAX_PENDING); bench_stats_start(&count, &start); do { @@ -6252,6 +6299,10 @@ static void bench_rsaKeyGen_helper(int useDeviceID, word32 keySz) for (i = 0; i < BENCH_MAX_PENDING; i++) { wc_FreeRsaKey(&genKey[i]); } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(genKey, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); +#endif } void bench_rsaKeyGen(int useDeviceID) @@ -6292,7 +6343,7 @@ void bench_rsaKeyGen_size(int useDeviceID, word32 keySz) #if defined(WOLFSSL_RSA_VERIFY_INLINE) || defined(WOLFSSL_RSA_PUBLIC_ONLY) #if defined(USE_CERT_BUFFERS_2048) -static unsigned char rsa_2048_sig[] = { +static const unsigned char rsa_2048_sig[] = { 0x8c, 0x9e, 0x37, 0xbf, 0xc3, 0xa6, 0xba, 0x1c, 0x53, 0x22, 0x40, 0x4b, 0x8b, 0x0d, 0x3c, 0x0e, 0x2e, 0x8c, 0x31, 0x2c, 0x47, 0xbf, 0x03, 0x48, @@ -6327,7 +6378,7 @@ static unsigned char rsa_2048_sig[] = { 0x9e, 0xd2, 0x51, 0xe6, 0x41, 0xbf, 0x4f, 0xa2 }; #elif defined(USE_CERT_BUFFERS_3072) -static unsigned char rsa_3072_sig[] = { +static const unsigned char rsa_3072_sig[] = { 0x1a, 0xd6, 0x0d, 0xfd, 0xe3, 0x41, 0x95, 0x76, 0x27, 0x16, 0x7d, 0xc7, 0x94, 0x16, 0xca, 0xa8, 0x26, 0x08, 0xbe, 0x78, 0x87, 0x72, 0x4c, 0xd9, @@ -6603,7 +6654,11 @@ static void bench_rsa_helper(int useDeviceID, RsaKey rsaKey[BENCH_MAX_PENDING], void bench_rsa(int useDeviceID) { int i; +#ifdef WOLFSSL_SMALL_STACK + RsaKey *rsaKey; +#else RsaKey rsaKey[BENCH_MAX_PENDING]; +#endif int ret = 0; word32 rsaKeySz = 0; const byte* tmp; @@ -6612,6 +6667,15 @@ void bench_rsa(int useDeviceID) word32 idx; #endif +#ifdef WOLFSSL_SMALL_STACK + rsaKey = (RsaKey *)XMALLOC(sizeof(*rsaKey) * BENCH_MAX_PENDING, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (rsaKey == NULL) { + printf("bench_rsa malloc failed\n"); + return; + } +#endif + #ifdef USE_CERT_BUFFERS_1024 tmp = rsa_key_der_1024; bytes = (size_t)sizeof_rsa_key_der_1024; @@ -6633,7 +6697,7 @@ void bench_rsa(int useDeviceID) #endif /* USE_CERT_BUFFERS */ /* clear for done cleanup */ - XMEMSET(rsaKey, 0, sizeof(rsaKey)); + XMEMSET(rsaKey, 0, sizeof(*rsaKey) * BENCH_MAX_PENDING); /* init keys */ for (i = 0; i < BENCH_MAX_PENDING; i++) { @@ -6695,6 +6759,10 @@ void bench_rsa(int useDeviceID) for (i = 0; i < BENCH_MAX_PENDING; i++) { wc_FreeRsaKey(&rsaKey[i]); } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(rsaKey, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); +#endif } @@ -6703,12 +6771,25 @@ void bench_rsa(int useDeviceID) void bench_rsa_key(int useDeviceID, word32 rsaKeySz) { int ret = 0, i, pending = 0; +#ifdef WOLFSSL_SMALL_STACK + RsaKey *rsaKey; +#else RsaKey rsaKey[BENCH_MAX_PENDING]; +#endif int isPending[BENCH_MAX_PENDING]; long exp = 65537L; +#ifdef WOLFSSL_SMALL_STACK + rsaKey = (RsaKey *)XMALLOC(sizeof(*rsaKey) * BENCH_MAX_PENDING, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (rsaKey == NULL) { + printf("bench_rsa_key malloc failed\n"); + return; + } +#endif + /* clear for done cleanup */ - XMEMSET(rsaKey, 0, sizeof(rsaKey)); + XMEMSET(rsaKey, 0, sizeof(*rsaKey) * BENCH_MAX_PENDING); XMEMSET(isPending, 0, sizeof(isPending)); /* init keys */ @@ -6750,6 +6831,10 @@ void bench_rsa_key(int useDeviceID, word32 rsaKeySz) for (i = 0; i < BENCH_MAX_PENDING; i++) { wc_FreeRsaKey(&rsaKey[i]); } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(rsaKey, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); +#endif } #endif /* WOLFSSL_KEY_GEN */ #endif /* !NO_RSA */ @@ -6785,7 +6870,11 @@ void bench_dh(int useDeviceID) int count = 0, times, pending = 0; const byte* tmp = NULL; double start = 0.0F; +#ifdef WOLFSSL_SMALL_STACK + DhKey *dhKey = NULL; +#else DhKey dhKey[BENCH_MAX_PENDING]; +#endif int dhKeySz = BENCH_DH_KEY_SIZE * 8; /* used in printf */ const char**desc = bench_desc_words[lng_index]; #ifndef NO_ASN @@ -6823,6 +6912,14 @@ void bench_dh(int useDeviceID) WC_INIT_ARRAY(priv, byte, BENCH_MAX_PENDING, BENCH_DH_PRIV_SIZE, HEAP_HINT); +#ifdef WOLFSSL_SMALL_STACK + dhKey = (DhKey *)XMALLOC(sizeof(DhKey) * BENCH_MAX_PENDING, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (! dhKey) { + ret = MEMORY_E; + goto exit; + } +#endif + #ifdef WC_DECLARE_VAR_IS_HEAP_ALLOC if (pub[0] == NULL || pub2 == NULL || agree[0] == NULL || priv[0] == NULL || priv2 == NULL) { ret = MEMORY_E; @@ -6888,7 +6985,12 @@ void bench_dh(int useDeviceID) #endif /* clear for done cleanup */ - XMEMSET(dhKey, 0, sizeof(dhKey)); + XMEMSET(dhKey, 0, sizeof(DhKey) * BENCH_MAX_PENDING); +#if 0 + for (i = 0; i < BENCH_MAX_PENDING; i++) { + XMEMSET(dhKey[i], 0, sizeof(DhKey)); + } +#endif /* init keys */ for (i = 0; i < BENCH_MAX_PENDING; i++) { @@ -6999,9 +7101,18 @@ void bench_dh(int useDeviceID) useDeviceID, count, start, ret); /* cleanup */ +#ifdef WOLFSSL_SMALL_STACK + if (dhKey) { + for (i = 0; i < BENCH_MAX_PENDING; i++) { + wc_FreeDhKey(&dhKey[i]); + } + XFREE(dhKey, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + } +#else for (i = 0; i < BENCH_MAX_PENDING; i++) { wc_FreeDhKey(&dhKey[i]); } +#endif WC_FREE_ARRAY(pub, BENCH_MAX_PENDING, HEAP_HINT); WC_FREE_VAR(pub2, HEAP_HINT); @@ -7169,16 +7280,29 @@ void bench_eccMakeKey(int useDeviceID, int curveId) int ret = 0, i, times, count, pending = 0; int deviceID; int keySize; +#ifdef WOLFSSL_SMALL_STACK + ecc_key *genKey; +#else ecc_key genKey[BENCH_MAX_PENDING]; +#endif char name[BENCH_ECC_NAME_SZ]; double start; const char**desc = bench_desc_words[lng_index]; +#ifdef WOLFSSL_SMALL_STACK + genKey = (ecc_key *)XMALLOC(sizeof(*genKey) * BENCH_MAX_PENDING, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (genKey == NULL) { + printf("bench_eccMakeKey malloc failed\n"); + return; + } +#endif + deviceID = useDeviceID ? devId : INVALID_DEVID; keySize = wc_ecc_get_curve_size_from_id(curveId); /* clear for done cleanup */ - XMEMSET(&genKey, 0, sizeof(genKey)); + XMEMSET(genKey, 0, sizeof(*genKey) * BENCH_MAX_PENDING); /* ECC Make Key */ bench_stats_start(&count, &start); @@ -7221,6 +7345,10 @@ void bench_eccMakeKey(int useDeviceID, int curveId) for (i = 0; i < BENCH_MAX_PENDING; i++) { wc_ecc_free(&genKey[i]); } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(genKey, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); +#endif } @@ -7230,10 +7358,18 @@ void bench_ecc(int useDeviceID, int curveId) int deviceID; int keySize; char name[BENCH_ECC_NAME_SZ]; +#ifdef WOLFSSL_SMALL_STACK + ecc_key *genKey; +#else ecc_key genKey[BENCH_MAX_PENDING]; +#endif #ifdef HAVE_ECC_DHE +#ifdef WOLFSSL_SMALL_STACK + ecc_key *genKey2; +#else ecc_key genKey2[BENCH_MAX_PENDING]; #endif +#endif #if !defined(NO_ASN) && defined(HAVE_ECC_SIGN) #ifdef HAVE_ECC_VERIFY @@ -7257,6 +7393,24 @@ void bench_ecc(int useDeviceID, int curveId) BENCH_MAX_PENDING, MAX_ECC_BYTES, HEAP_HINT); #endif +#ifdef WOLFSSL_SMALL_STACK + genKey = (ecc_key *)XMALLOC(sizeof(*genKey) * BENCH_MAX_PENDING, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (genKey == NULL) { + printf("bench_eccMakeKey malloc failed\n"); + return; + } +#ifdef HAVE_ECC_DHE + genKey2 = (ecc_key *)XMALLOC(sizeof(*genKey2) * BENCH_MAX_PENDING, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (genKey2 == NULL) { + XFREE(genKey, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + printf("bench_eccMakeKey malloc failed\n"); + return; + } +#endif +#endif + #ifdef HAVE_ECC_DHE WC_INIT_ARRAY(shared, byte, BENCH_MAX_PENDING, MAX_ECC_BYTES, HEAP_HINT); @@ -7269,9 +7423,9 @@ void bench_ecc(int useDeviceID, int curveId) deviceID = useDeviceID ? devId : INVALID_DEVID; /* clear for done cleanup */ - XMEMSET(&genKey, 0, sizeof(genKey)); + XMEMSET(genKey, 0, sizeof(*genKey) * BENCH_MAX_PENDING); #ifdef HAVE_ECC_DHE - XMEMSET(&genKey2, 0, sizeof(genKey2)); + XMEMSET(genKey2, 0, sizeof(*genKey2) * BENCH_MAX_PENDING); #endif keySize = wc_ecc_get_curve_size_from_id(curveId); @@ -7446,6 +7600,13 @@ void bench_ecc(int useDeviceID, int curveId) #endif } +#ifdef WOLFSSL_SMALL_STACK + XFREE(genKey, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + #ifdef HAVE_ECC_DHE + XFREE(genKey2, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + #endif +#endif + #ifdef HAVE_ECC_DHE WC_FREE_ARRAY(shared, BENCH_MAX_PENDING, HEAP_HINT); #endif @@ -7468,58 +7629,83 @@ void bench_ecc(int useDeviceID, int curveId) #ifdef HAVE_ECC_ENCRYPT void bench_eccEncrypt(int curveId) { - ecc_key userA, userB; +#define BENCH_ECCENCRYPT_MSG_SIZE 48 +#define BENCH_ECCENCRYPT_OUT_SIZE (BENCH_ECCENCRYPT_MSG_SIZE + WC_SHA256_DIGEST_SIZE + (MAX_ECC_BITS+3)/4 + 2) + word32 outSz = BENCH_ECCENCRYPT_OUT_SIZE; +#ifdef WOLFSSL_SMALL_STACK + ecc_key *userA = NULL, *userB = NULL; + byte *msg = NULL; + byte *out = NULL; + char *name = NULL; +#else + ecc_key userA[1], userB[1]; + byte msg[BENCH_ECCENCRYPT_MSG_SIZE]; + byte out[BENCH_ECCENCRYPT_OUT_SIZE]; + char name[BENCH_ECC_NAME_SZ]; +#endif int keySize; - byte msg[48]; - byte out[sizeof(msg) + WC_SHA256_DIGEST_SIZE + (MAX_ECC_BITS+3)/4 + 2]; - word32 outSz = sizeof(out); word32 bench_plainSz = bench_size; int ret, i, count; double start; const char**desc = bench_desc_words[lng_index]; - char name[BENCH_ECC_NAME_SZ]; + +#ifdef WOLFSSL_SMALL_STACK + userA = (ecc_key *)XMALLOC(sizeof(*userA), + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + userB = (ecc_key *)XMALLOC(sizeof(*userB), + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + msg = (byte *)XMALLOC(BENCH_ECCENCRYPT_MSG_SIZE, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + out = (byte *)XMALLOC(outSz, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + name = (char *)XMALLOC(BENCH_ECC_NAME_SZ, + HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if ((! userA) || (! userB) || (! msg) || (! out) || (! name)) { + printf("bench_eccEncrypt malloc failed\n"); + goto exit; + } +#endif keySize = wc_ecc_get_curve_size_from_id(curveId); - ret = wc_ecc_init_ex(&userA, HEAP_HINT, devId); + ret = wc_ecc_init_ex(userA, HEAP_HINT, devId); if (ret != 0) { printf("wc_ecc_encrypt make key A failed: %d\n", ret); - return; + goto exit; } - ret = wc_ecc_init_ex(&userB, HEAP_HINT, devId); + ret = wc_ecc_init_ex(userB, HEAP_HINT, devId); if (ret != 0) { printf("wc_ecc_encrypt make key B failed: %d\n", ret); - wc_ecc_free(&userA); - return; + goto exit; } #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \ (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \ !defined(HAVE_SELFTEST) - ret = wc_ecc_set_rng(&userA, &gRng); + ret = wc_ecc_set_rng(userA, &gRng); if (ret != 0) { goto exit; } - ret = wc_ecc_set_rng(&userB, &gRng); + ret = wc_ecc_set_rng(userB, &gRng); if (ret != 0) { goto exit; } #endif - ret = wc_ecc_make_key_ex(&gRng, keySize, &userA, curveId); + ret = wc_ecc_make_key_ex(&gRng, keySize, userA, curveId); #ifdef WOLFSSL_ASYNC_CRYPT - ret = wc_AsyncWait(ret, &userA.asyncDev, WC_ASYNC_FLAG_NONE); + ret = wc_AsyncWait(ret, &userA->asyncDev, WC_ASYNC_FLAG_NONE); #endif if (ret != 0) goto exit; - ret = wc_ecc_make_key_ex(&gRng, keySize, &userB, curveId); + ret = wc_ecc_make_key_ex(&gRng, keySize, userB, curveId); #ifdef WOLFSSL_ASYNC_CRYPT - ret = wc_AsyncWait(ret, &userB.asyncDev, WC_ASYNC_FLAG_NONE); + ret = wc_AsyncWait(ret, &userB->asyncDev, WC_ASYNC_FLAG_NONE); #endif if (ret != 0) goto exit; - for (i = 0; i < (int)sizeof(msg); i++) { + for (i = 0; i < BENCH_ECCENCRYPT_MSG_SIZE; i++) { msg[i] = (byte)i; } @@ -7527,7 +7713,7 @@ void bench_eccEncrypt(int curveId) do { for (i = 0; i < ntimes; i++) { /* encrypt msg to B */ - ret = wc_ecc_encrypt(&userA, &userB, msg, sizeof(msg), + ret = wc_ecc_encrypt(userA, userB, msg, BENCH_ECCENCRYPT_MSG_SIZE, out, &outSz, NULL); if (ret != 0) { printf("wc_ecc_encrypt failed! %d\n", ret); @@ -7546,7 +7732,7 @@ void bench_eccEncrypt(int curveId) do { for (i = 0; i < ntimes; i++) { /* decrypt msg from A */ - ret = wc_ecc_decrypt(&userB, &userA, out, outSz, bench_plain, + ret = wc_ecc_decrypt(userB, userA, out, outSz, bench_plain, &bench_plainSz, NULL); if (ret != 0) { printf("wc_ecc_decrypt failed! %d\n", ret); @@ -7561,8 +7747,25 @@ void bench_eccEncrypt(int curveId) exit: /* cleanup */ - wc_ecc_free(&userB); - wc_ecc_free(&userA); +#ifdef WOLFSSL_SMALL_STACK + if (userA) { + wc_ecc_free(userA); + XFREE(userA, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + } + if (userB) { + wc_ecc_free(userB); + XFREE(userB, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + } + if (msg) + XFREE(msg, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (out) + XFREE(out, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + if (name) + XFREE(name, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); +#else + wc_ecc_free(userB); + wc_ecc_free(userA); +#endif } #endif #endif /* HAVE_ECC */ @@ -7928,7 +8131,7 @@ void bench_eccsiPairGen(void) const char**desc = bench_desc_words[lng_index]; mp_int ssk; ecc_point* pvt; - byte id[] = { 0x01, 0x23, 0x34, 0x45 }; + static const byte id[] = { 0x01, 0x23, 0x34, 0x45 }; int ret; (void)mp_init(&ssk); @@ -7966,7 +8169,7 @@ void bench_eccsiValidate(void) const char**desc = bench_desc_words[lng_index]; mp_int ssk; ecc_point* pvt; - byte id[] = { 0x01, 0x23, 0x34, 0x45 }; + static const byte id[] = { 0x01, 0x23, 0x34, 0x45 }; int valid; int ret; @@ -8006,8 +8209,8 @@ void bench_eccsi(void) const char**desc = bench_desc_words[lng_index]; mp_int ssk; ecc_point* pvt; - byte id[] = { 0x01, 0x23, 0x34, 0x45 }; - byte msg[] = { 0x01, 0x23, 0x34, 0x45 }; + static const byte id[] = { 0x01, 0x23, 0x34, 0x45 }; + static const byte msg[] = { 0x01, 0x23, 0x34, 0x45 }; byte hash[WC_SHA256_DIGEST_SIZE]; byte hashSz = (byte)sizeof(hash); byte sig[257]; @@ -8098,7 +8301,7 @@ void bench_sakkeRskGen(void) int i, count; const char**desc = bench_desc_words[lng_index]; ecc_point* rsk; - byte id[] = { 0x01, 0x23, 0x34, 0x45 }; + static const byte id[] = { 0x01, 0x23, 0x34, 0x45 }; int ret; rsk = wc_ecc_new_point(); @@ -8132,7 +8335,7 @@ void bench_sakkeValidate(void) int i, count; const char**desc = bench_desc_words[lng_index]; ecc_point* rsk; - byte id[] = { 0x01, 0x23, 0x34, 0x45 }; + static const byte id[] = { 0x01, 0x23, 0x34, 0x45 }; int valid; int ret; @@ -8168,8 +8371,9 @@ void bench_sakke(void) int i, count; const char**desc = bench_desc_words[lng_index]; ecc_point* rsk; - byte id[] = { 0x01, 0x23, 0x34, 0x45 }; - byte ssv[] = { 0x01, 0x23, 0x34, 0x45 }; + static const byte id[] = { 0x01, 0x23, 0x34, 0x45 }; + static const byte ssv_init[] = { 0x01, 0x23, 0x34, 0x45 }; + byte ssv[sizeof(ssv_init)]; byte derSSV[sizeof(ssv)]; byte auth[257]; word16 authSz = sizeof(auth); @@ -8179,6 +8383,8 @@ void bench_sakke(void) byte* iTable = NULL; word32 iTableLen = 0; + XMEMCPY(ssv, ssv_init, sizeof ssv); + rsk = wc_ecc_new_point(); (void)wc_InitSakkeKey_ex(&genKey, 128, ECC_SAKKE_1, NULL, INVALID_DEVID); (void)wc_MakeSakkeKey(&genKey, &gRng); @@ -8910,8 +9116,17 @@ void bench_sphincsKeySign(byte level, byte optim) (cur_stime - start_stime) / (cur_utime - start_utime); if (stime_utime_ratio > .1) printf("%swarning, " - "excessive system time ratio for %s%s (%.3f%%).\n", - err_prefix, desc, desc_extra, stime_utime_ratio * 100.0); + "excessive system time ratio for %s%s (" FLT_FMT_PREC "%%).\n", + err_prefix, desc, desc_extra, FLT_FMT_PREC_ARGS(3, stime_utime_ratio * 100.0)); + } + +#elif defined(WOLFSSL_LINUXKM) + + double current_time(int reset) + { + (void)reset; + u64 ns = ktime_get_ns(); + return (double)ns / 1000000000.0; } #else @@ -8983,7 +9198,7 @@ static void print_alg(const char* str, int* line) { const char* const ident = " "; if (*line == 0) { - fputs(ident, stdout); + printf("%s", ident); *line = (int)XSTRLEN(ident); } printf(" %s", str); From 0452d0d802421b42e7c59e3e42e6b195b07073cd Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:05:14 -0500 Subject: [PATCH 291/391] src/internal.c: fix for typo (identicalInnerCondition) in DoClientHello(). --- src/internal.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/internal.c b/src/internal.c index 97ec44c544e..560ed002871 100644 --- a/src/internal.c +++ b/src/internal.c @@ -33344,7 +33344,6 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ret = DoClientHelloStateless(ssl, input, inOutIdx, helloSz); if (ret != 0 || !ssl->options.dtlsStateful) { int alertType = TranslateErrorToAlert(ret); - if (alertType != invalid_alert) if (alertType != invalid_alert) { int err; From 073c195381ae4087edeb5e1d84405d12b09a219c Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:05:33 -0500 Subject: [PATCH 292/391] fix for benign sign clash in wc_RNG_GenerateBlock(). --- wolfcrypt/src/random.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 4d37a4395a7..43e09378e49 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -1864,7 +1864,7 @@ int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz) #ifdef CUSTOM_RAND_GENERATE_BLOCK XMEMSET(output, 0, sz); - ret = CUSTOM_RAND_GENERATE_BLOCK(output, sz); + ret = (int)CUSTOM_RAND_GENERATE_BLOCK(output, sz); #else #ifdef HAVE_HASHDRBG From 0b16f623f4a35d24efed9dd061d6fe20b9754810 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:06:17 -0500 Subject: [PATCH 293/391] src/ssl_asn1.c: in wolfssl_asn1_time_to_tm(), initialize localTm with memset, not the zero initializer, for C++ compatibility. --- src/ssl_asn1.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 20dbe67585d..5c5d9068514 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -3653,7 +3653,9 @@ static int wolfssl_asn1_time_to_tm(const WOLFSSL_ASN1_TIME* asnTime, int asn1TimeBufLen; int i = 0; #ifdef XMKTIME - struct tm localTm = {0}; + struct tm localTm; + + XMEMSET(&localTm, 0, sizeof localTm); #endif /* Get the string buffer - fixed array, can't fail. */ From bb01dd9625ef9f7069cd146eecef68b9547b9a47 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:07:47 -0500 Subject: [PATCH 294/391] wolfcrypt/src/aes.c: in wc_AesSetKeyLocal(), add an alignment check in the haveAESNI path for WOLFSSL_LINUXKM, because the failure mode is module crash. --- wolfcrypt/src/aes.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 1ab87695c07..d1a7a00f77d 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -3129,6 +3129,12 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( checkAESNI = 1; } if (haveAESNI) { + #ifdef WOLFSSL_LINUXKM + /* runtime alignment check */ + if ((unsigned long)&aes->key & 0xf) { + return BAD_ALIGN_E; + } + #endif aes->use_aesni = 1; if (iv) XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE); From a0600532e4c00b3533c9bffa4fc07df1a59456e2 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:11:01 -0500 Subject: [PATCH 295/391] wolfssl/wolfcrypt/types.h: add missing do-while-0 nonstatments to WC_FREE_VAR() and WC_FREE_ARRAY() for pedantic semicolon swallowing. --- wolfssl/wolfcrypt/types.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index f274baf8318..b105028e30a 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -598,8 +598,8 @@ typedef struct w64wrapper { #define WC_DECLARE_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ VAR_TYPE VAR_NAME[VAR_ITEMS][VAR_SIZE] #define WC_INIT_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) do {} while(0) - #define WC_FREE_VAR(VAR_NAME, HEAP) /* nothing to free, its stack */ - #define WC_FREE_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) /* nothing to free, its stack */ + #define WC_FREE_VAR(VAR_NAME, HEAP) do {} while(0) /* nothing to free, its stack */ + #define WC_FREE_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) do {} while(0) /* nothing to free, its stack */ #define WC_DECLARE_ARRAY_DYNAMIC_DEC(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ VAR_TYPE* VAR_NAME[VAR_ITEMS]; \ From aedacbc0a0570f88d43da4aa3b438ccbd899d5cb Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:13:36 -0500 Subject: [PATCH 296/391] wolfssl/wolfcrypt/mem_track.h: refactor for linuxkm compatibility, mainly by supporting NO_STDIO_FILESYSTEM. --- wolfssl/wolfcrypt/mem_track.h | 71 +++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 32 deletions(-) diff --git a/wolfssl/wolfcrypt/mem_track.h b/wolfssl/wolfcrypt/mem_track.h index 945c10acc19..483f14ab79a 100644 --- a/wolfssl/wolfcrypt/mem_track.h +++ b/wolfssl/wolfcrypt/mem_track.h @@ -62,15 +62,24 @@ #include "wolfssl/wolfcrypt/settings.h" #include "wolfssl/wolfcrypt/logging.h" +#include "wolfssl/wolfcrypt/memory.h" #if defined(WOLFSSL_TRACK_MEMORY) || defined(HAVE_STACK_SIZE) || \ defined(HAVE_STACK_SIZE_VERBOSE) -#include + #ifdef NO_STDIO_FILESYSTEM + /* if wc_port.h/linuxkm_wc_port.h doesn't define printf, then the user + * needs to define it. + */ + #define wc_mem_printf(...) printf(__VA_ARGS__) + #else + #include + #define wc_mem_printf(...) fprintf(stderr, __VA_ARGS__) + #endif #endif #if defined(WOLFSSL_TRACK_MEMORY) #define DO_MEM_STATS - #if defined(__linux__) || defined(__MACH__) + #if (defined(__linux__) && !defined(WOLFSSL_LINUXKM)) || defined(__MACH__) #define DO_MEM_LIST #endif #endif @@ -160,7 +169,7 @@ static WC_INLINE void* TrackMalloc(size_t sz) #ifdef WOLFSSL_DEBUG_MEMORY #ifdef WOLFSSL_DEBUG_MEMORY_PRINT - fprintf(stderr, "Alloc: %p -> %u at %s:%d\n", header->thisMemory, (word32)sz, func, line); + wc_mem_printf("Alloc: %p -> %u at %s:%d\n", header->thisMemory, (word32)sz, func, line); #else (void)func; (void)line; @@ -268,7 +277,7 @@ static WC_INLINE void TrackFree(void* ptr) #ifdef WOLFSSL_DEBUG_MEMORY #ifdef WOLFSSL_DEBUG_MEMORY_PRINT - fprintf(stderr, "Free: %p -> %u at %s:%d\n", ptr, (word32)sz, func, line); + wc_mem_printf("Free: %p -> %u at %s:%d\n", ptr, (word32)sz, func, line); #else (void)func; (void)line; @@ -334,11 +343,11 @@ static WC_INLINE int InitMemoryTracker(void) ret = wolfSSL_GetAllocators(&mfDefault, &ffDefault, &rfDefault); if (ret < 0) { - fprintf(stderr, "wolfSSL GetAllocators failed to get the defaults\n"); + wc_mem_printf("wolfSSL GetAllocators failed to get the defaults\n"); } ret = wolfSSL_SetAllocators(TrackMalloc, TrackFree, TrackRealloc); if (ret < 0) { - fprintf(stderr, "wolfSSL SetAllocators failed for track memory\n"); + wc_mem_printf("wolfSSL SetAllocators failed for track memory\n"); return ret; } @@ -377,11 +386,11 @@ static WC_INLINE void ShowMemoryTracker(void) #endif #ifdef DO_MEM_STATS - fprintf(stderr, "total Allocs = %9ld\n", ourMemStats.totalAllocs); - fprintf(stderr, "total Deallocs = %9ld\n", ourMemStats.totalDeallocs); - fprintf(stderr, "total Bytes = %9ld\n", ourMemStats.totalBytes); - fprintf(stderr, "peak Bytes = %9ld\n", ourMemStats.peakBytes); - fprintf(stderr, "current Bytes = %9ld\n", ourMemStats.currentBytes); + wc_mem_printf("total Allocs = %9ld\n", ourMemStats.totalAllocs); + wc_mem_printf("total Deallocs = %9ld\n", ourMemStats.totalDeallocs); + wc_mem_printf("total Bytes = %9ld\n", ourMemStats.totalBytes); + wc_mem_printf("peak Bytes = %9ld\n", ourMemStats.peakBytes); + wc_mem_printf("current Bytes = %9ld\n", ourMemStats.currentBytes); #endif #ifdef DO_MEM_LIST @@ -389,16 +398,14 @@ static WC_INLINE void ShowMemoryTracker(void) /* print list of allocations */ memHint* header; for (header = ourMemList.head; header != NULL; header = header->next) { - fprintf(stderr, "Leak: Ptr %p, Size %u" #ifdef WOLFSSL_DEBUG_MEMORY - ", Func %s, Line %d" - #endif - "\n", - (byte*)header + sizeof(memHint), (unsigned int)header->thisSize - #ifdef WOLFSSL_DEBUG_MEMORY - , header->func, header->line - #endif - ); + wc_mem_printf("Leak: Ptr %p, Size %u, Func %s, Line %d\n", + (byte*)header + sizeof(memHint), (unsigned int)header->thisSize, + header->func, header->line); +#else + wc_mem_printf("Leak: Ptr %p, Size %u\n", + (byte*)header + sizeof(memHint), (unsigned int)header->thisSize); +#endif } } @@ -538,7 +545,7 @@ int StackSizeHWMReset(void) #define STACK_SIZE_CHECKPOINT_MSG(msg) ({ \ ssize_t HWM = StackSizeHWM_OffsetCorrected(); \ - fprintf(stderr, "%ld\t%s\n", (long int)HWM, msg); \ + wc_mem_printf("%ld\t%s\n", (long int)HWM, msg); \ StackSizeHWMReset(); \ }) @@ -549,7 +556,7 @@ int StackSizeHWMReset(void) printf(" relative stack peak usage = %ld bytes\n", (long int)HWM); \ _ret = StackSizeHWMReset(); \ if ((max >= 0) && (HWM > (ssize_t)(max))) { \ - fprintf(stderr, \ + wc_mem_printf( \ " relative stack usage at %s L%d exceeds designated max %ld bytes.\n", \ __FILE__, __LINE__, (long int)(max)); \ _ret = -1; \ @@ -585,7 +592,7 @@ static WC_INLINE int StackSizeCheck(struct func_args* args, thread_func tf) ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize); if (ret != 0 || myStack == NULL) { - fprintf(stderr, "posix_memalign failed\n"); + wc_mem_printf("posix_memalign failed\n"); return -1; } @@ -593,13 +600,13 @@ static WC_INLINE int StackSizeCheck(struct func_args* args, thread_func tf) ret = pthread_attr_init(&myAttr); if (ret != 0) { - fprintf(stderr, "attr_init failed\n"); + wc_mem_printf("attr_init failed\n"); return ret; } ret = pthread_attr_setstack(&myAttr, myStack, stackSize); if (ret != 0) { - fprintf(stderr, "attr_setstackaddr failed\n"); + wc_mem_printf("attr_setstackaddr failed\n"); return ret; } @@ -623,7 +630,7 @@ static WC_INLINE int StackSizeCheck(struct func_args* args, thread_func tf) ret = pthread_join(threadId, &status); if (ret != 0) { - fprintf(stderr, "pthread_join failed\n"); + wc_mem_printf("pthread_join failed\n"); return ret; } @@ -672,7 +679,7 @@ static WC_INLINE int StackSizeCheck_launch(struct func_args* args, ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize); if (ret != 0 || myStack == NULL) { - fprintf(stderr, "posix_memalign failed\n"); + wc_mem_printf("posix_memalign failed\n"); free(shim_args); return -1; } @@ -681,7 +688,7 @@ static WC_INLINE int StackSizeCheck_launch(struct func_args* args, ret = pthread_attr_init(&myAttr); if (ret != 0) { - fprintf(stderr, "attr_init failed\n"); + wc_mem_printf("attr_init failed\n"); free(shim_args); free(myStack); return ret; @@ -689,7 +696,7 @@ static WC_INLINE int StackSizeCheck_launch(struct func_args* args, ret = pthread_attr_setstack(&myAttr, myStack, stackSize); if (ret != 0) { - fprintf(stderr, "attr_setstackaddr failed\n"); + wc_mem_printf("attr_setstackaddr failed\n"); } shim_args->myStack = myStack; @@ -721,7 +728,7 @@ static WC_INLINE int StackSizeCheck_reap(pthread_t threadId, void *stack_context void *status; int ret = pthread_join(threadId, &status); if (ret != 0) { - fprintf(stderr, "pthread_join failed\n"); + wc_mem_printf("pthread_join failed\n"); return ret; } @@ -770,12 +777,12 @@ static WC_INLINE void StackTrap(void) { struct rlimit rl; if (getrlimit(RLIMIT_STACK, &rl) != 0) { - fprintf(stderr, "getrlimit failed\n"); + wc_mem_printf("getrlimit failed\n"); } printf("rlim_cur = %llu\n", rl.rlim_cur); rl.rlim_cur = 1024*21; /* adjust trap size here */ if (setrlimit(RLIMIT_STACK, &rl) != 0) { - fprintf(stderr, "setrlimit failed\n"); + wc_mem_printf("setrlimit failed\n"); } } From d7050ccb4e1b92e36b8f9d62514b6012023fff18 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 01:44:36 -0500 Subject: [PATCH 297/391] linuxkm/linuxkm_memory.c: refactor SAVE/RESTORE_VECTOR_REGISTERS() to be per-process rather than per-CPU, and add migrate_disable/enable() to kernel_fpu_begin/end() because preempt_disable() is just a barrier on _PREEMPT_VOLUNTARY kernels; linuxkm/linuxkm_wc_port.h: activate SAVE/RESTORE_VECTOR_REGISTERS() whenever defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) for benchmark.c support, independent of vector crypto features; fix and optimize various alignment issues with stack and heap allocations; fix macro definitions for XMALLOC/XREALLOC/XFREE to correctly use kvmalloc and friends when defined(HAVE_KVMALLOC), and to use wolfSSL_Malloc() and friends when defined(WOLFSSL_TRACK_MEMORY); purge stale LINUXKM_SIMD_IRQ code. --- linuxkm/Kbuild | 5 + linuxkm/linuxkm_memory.c | 502 +++++++++++++++++--------------------- linuxkm/linuxkm_wc_port.h | 226 +++++++++-------- linuxkm/module_hooks.c | 67 +++-- wolfcrypt/src/wc_port.c | 54 +--- 5 files changed, 380 insertions(+), 474 deletions(-) diff --git a/linuxkm/Kbuild b/linuxkm/Kbuild index 57ad487cfab..3133ea8fcfa 100644 --- a/linuxkm/Kbuild +++ b/linuxkm/Kbuild @@ -90,6 +90,11 @@ ifeq "$(ENABLED_LINUXKM_PIE)" "yes" $(obj)/linuxkm/module_hooks.o: ccflags-y += $(PIE_SUPPORT_FLAGS) endif +ifeq "$(ENABLED_LINUXKM_BENCHMARKS)" "yes" + $(obj)/linuxkm/module_hooks.o: ccflags-y = $(WOLFSSL_CFLAGS) $(CFLAGS_FPU_ENABLE) $(CFLAGS_SIMD_ENABLE) $(PIE_SUPPORT_FLAGS) + $(obj)/linuxkm/module_hooks.o: asflags-y = $(WOLFSSL_ASFLAGS) $(ASFLAGS_FPU_ENABLE_SIMD_DISABLE) +endif + asflags-y := $(WOLFSSL_ASFLAGS) $(ASFLAGS_FPUSIMD_DISABLE) # vectorized implementations that are kernel-safe are listed here. diff --git a/linuxkm/linuxkm_memory.c b/linuxkm/linuxkm_memory.c index ee30af987be..31a7b93553e 100644 --- a/linuxkm/linuxkm_memory.c +++ b/linuxkm/linuxkm_memory.c @@ -21,320 +21,262 @@ /* included by wolfcrypt/src/memory.c */ -#if defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) && defined(CONFIG_X86) - #ifdef LINUXKM_SIMD_IRQ - #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 16, 0) - static union fpregs_state **wolfcrypt_linuxkm_fpu_states = NULL; - #else - static struct fpstate **wolfcrypt_linuxkm_fpu_states = NULL; - #endif - #else - static unsigned int *wolfcrypt_linuxkm_fpu_states = NULL; - #define WC_FPU_COUNT_MASK 0x7fffffffU - #define WC_FPU_SAVED_MASK 0x80000000U - #endif - - static WARN_UNUSED_RESULT inline int am_in_hard_interrupt_handler(void) - { - return (preempt_count() & (NMI_MASK | HARDIRQ_MASK)) != 0; +#ifdef HAVE_KVMALLOC +/* adapted from kvrealloc() draft by Changli Gao, 2010-05-13 */ +void *lkm_realloc(void *ptr, size_t newsize) { + void *nptr; + size_t oldsize; + + if (unlikely(newsize == 0)) { + kvfree(ptr); + return ZERO_SIZE_PTR; } - WARN_UNUSED_RESULT int allocate_wolfcrypt_linuxkm_fpu_states(void) - { - #ifdef LINUXKM_SIMD_IRQ - #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 16, 0) - wolfcrypt_linuxkm_fpu_states = - (union fpregs_state **)kzalloc(nr_cpu_ids - * sizeof(struct fpu_state *), - GFP_KERNEL); - #else - wolfcrypt_linuxkm_fpu_states = - (struct fpstate **)kzalloc(nr_cpu_ids - * sizeof(struct fpstate *), - GFP_KERNEL); - #endif - #else - wolfcrypt_linuxkm_fpu_states = - (unsigned int *)kzalloc(nr_cpu_ids * sizeof(unsigned int), - GFP_KERNEL); - #endif - - if (! wolfcrypt_linuxkm_fpu_states) { - pr_err("warning, allocation of %lu bytes for " - "wolfcrypt_linuxkm_fpu_states failed.\n", - nr_cpu_ids * sizeof(struct fpu_state *)); - return MEMORY_E; - } -#ifdef LINUXKM_SIMD_IRQ - { - typeof(nr_cpu_ids) i; - for (i=0; iprivate; + if (newsize <= oldsize) + return ptr; } -#endif /* LINUXKM_SIMD_IRQ */ - return 0; +#endif /* ! __PIE__ */ } - void free_wolfcrypt_linuxkm_fpu_states(void) - { - if (wolfcrypt_linuxkm_fpu_states) { -#ifdef LINUXKM_SIMD_IRQ - typeof(nr_cpu_ids) i; - for (i=0; istate, which - * has stringent alignment requirements (64 byte cache - * line), but takes a pointer to the parent struct. work - * around this. - */ - #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 14, 0) - struct fpu *fake_fpu_pointer = - (struct fpu *)(((char *)wolfcrypt_linuxkm_fpu_states[processor_id]) - - offsetof(struct fpu, state)); - copy_fpregs_to_fpstate(fake_fpu_pointer); - #elif LINUX_VERSION_CODE < KERNEL_VERSION(5, 16, 0) - struct fpu *fake_fpu_pointer = - (struct fpu *)(((char *)wolfcrypt_linuxkm_fpu_states[processor_id]) - - offsetof(struct fpu, state)); - save_fpregs_to_fpstate(fake_fpu_pointer); - #else - struct fpu *fake_fpu_pointer = - (struct fpu *)(((char *)wolfcrypt_linuxkm_fpu_states[processor_id]) - - offsetof(struct fpu, fpstate)); - save_fpregs_to_fpstate(fake_fpu_pointer); - #endif - } - /* mark the slot as used. */ - ((unsigned char *)wolfcrypt_linuxkm_fpu_states[processor_id])[PAGE_SIZE-1] = 1; - /* note, not preempt_enable()ing, mirroring kernel_fpu_begin() - * semantics, even though routine will have been entered already - * non-preemptable. - */ - return 0; - } else -#endif /* LINUXKM_SIMD_IRQ */ - { - preempt_enable(); - return BAD_STATE_E; - } - } else { + if (nr_cpu_ids >= 16) + wc_linuxkm_fpu_states_n_tracked = nr_cpu_ids * 2; + else + wc_linuxkm_fpu_states_n_tracked = 32; - /* allow for nested calls */ -#ifdef LINUXKM_SIMD_IRQ - if (((unsigned char *)wolfcrypt_linuxkm_fpu_states[processor_id])[PAGE_SIZE-1] != 0) { - if (((unsigned char *)wolfcrypt_linuxkm_fpu_states[processor_id])[PAGE_SIZE-1] == 255) { - preempt_enable(); - pr_err("save_vector_registers_x86 recursion register overflow for " - "cpu id %d.\n", processor_id); - return BAD_STATE_E; - } else { - ++((unsigned char *)wolfcrypt_linuxkm_fpu_states[processor_id])[PAGE_SIZE-1]; - return 0; - } - } - kernel_fpu_begin(); - preempt_enable(); /* kernel_fpu_begin() does its own - * preempt_disable(). decrement ours. - */ - ((unsigned char *)wolfcrypt_linuxkm_fpu_states[processor_id])[PAGE_SIZE-1] = 1; -#else /* !LINUXKM_SIMD_IRQ */ - if (wolfcrypt_linuxkm_fpu_states[processor_id] != 0U) { - if ((wolfcrypt_linuxkm_fpu_states[processor_id] & WC_FPU_COUNT_MASK) - == WC_FPU_COUNT_MASK) - { - preempt_enable(); - pr_err("save_vector_registers_x86 recursion register overflow for " - "cpu id %d.\n", processor_id); - return BAD_STATE_E; - } else { - ++wolfcrypt_linuxkm_fpu_states[processor_id]; - return 0; - } - } + wc_linuxkm_fpu_states = + (struct wc_thread_fpu_count_ent *)malloc( + wc_linuxkm_fpu_states_n_tracked * sizeof(wc_linuxkm_fpu_states[0])); - /* if kernel_fpu_begin() won't actually save the reg file (because - * it was already saved and invalidated, or because we're in a - * kernel thread), don't call kernel_fpu_begin() here, nor call - * kernel_fpu_end() in cleanup. this avoids pointless overhead. in - * kernels >=5.17.12 (from changes to irq_fpu_usable() in linux - * commit 59f5ede3bc0f, backported somewhere >5.17.5), this also - * fixes register corruption. - */ - if ((current->flags & PF_KTHREAD) || - test_thread_flag(TIF_NEED_FPU_LOAD)) - { - wolfcrypt_linuxkm_fpu_states[processor_id] = - WC_FPU_SAVED_MASK + 1U; /* set msb 1 to inhibit kernel_fpu_end() at cleanup. */ - /* keep preempt_disable()d from above. */ - } else { - kernel_fpu_begin(); - preempt_enable(); /* kernel_fpu_begin() does its own - * preempt_disable(). decrement ours. - */ - wolfcrypt_linuxkm_fpu_states[processor_id] = 1U; /* set msb 0 to trigger kernel_fpu_end() at cleanup. */ - } -#endif /* !LINUXKM_SIMD_IRQ */ + if (! wc_linuxkm_fpu_states) { + pr_err("allocation of %lu bytes for " + "wc_linuxkm_fpu_states failed.\n", + nr_cpu_ids * sizeof(struct fpu_state *)); + return MEMORY_E; + } - return 0; - } + memset(wc_linuxkm_fpu_states, 0, wc_linuxkm_fpu_states_n_tracked * sizeof(wc_linuxkm_fpu_states[0])); + + return 0; +} + +void free_wolfcrypt_linuxkm_fpu_states(void) { + struct wc_thread_fpu_count_ent *i, *i_endptr; + pid_t i_pid; + + if (wc_linuxkm_fpu_states == NULL) { + pr_err("free_wolfcrypt_linuxkm_fpu_states called" + " before allocate_wolfcrypt_linuxkm_fpu_states.\n"); + return; } - void restore_vector_registers_x86(void) - { - int processor_id = smp_processor_id(); - if ((wolfcrypt_linuxkm_fpu_states == NULL) -#ifdef LINUXKM_SIMD_IRQ - || (wolfcrypt_linuxkm_fpu_states[processor_id] == NULL) -#endif - ) - { - pr_err("restore_vector_registers_x86 called for cpu id %d " - "with null context buffer.\n", processor_id); - return; + for (i = wc_linuxkm_fpu_states, + i_endptr = &wc_linuxkm_fpu_states[wc_linuxkm_fpu_states_n_tracked]; + i < i_endptr; + ++i) + { + i_pid = __atomic_load_n(&i->pid, __ATOMIC_CONSUME); + if (i_pid == 0) + continue; + if (i->fpu_state != 0) { + pr_err("free_wolfcrypt_linuxkm_fpu_states called" + " with nonzero state 0x%x for pid %d.\n", i->fpu_state, i_pid); + i->fpu_state = 0; } + } + + free(wc_linuxkm_fpu_states); + wc_linuxkm_fpu_states = NULL; +} -#ifdef LINUXKM_SIMD_IRQ - if (((unsigned char *)wolfcrypt_linuxkm_fpu_states[processor_id])[PAGE_SIZE-1] == 0) +/* lock-(mostly)-free thread-local storage facility for tracking recursive fpu pushing/popping */ +static struct wc_thread_fpu_count_ent *wc_linuxkm_fpu_state_assoc(int create_p) { + struct wc_thread_fpu_count_ent *i, *i_endptr, *i_empty; + pid_t my_pid = task_pid_nr(current), i_pid; + + { + static int _warned_on_null = 0; + if (wc_linuxkm_fpu_states == NULL) { - pr_err("restore_vector_registers_x86 called for cpu id %d " - "without saved context.\n", processor_id); - return; + if (_warned_on_null == 0) { + pr_err("wc_linuxkm_fpu_state_assoc called by pid %d" + " before allocate_wolfcrypt_linuxkm_fpu_states.\n", my_pid); + _warned_on_null = 1; + } + return NULL; } + } - if (--((unsigned char *)wolfcrypt_linuxkm_fpu_states[processor_id])[PAGE_SIZE-1] > 0) { - preempt_enable(); /* preempt_disable count will still be nonzero after this decrement. */ - return; - } + i_endptr = &wc_linuxkm_fpu_states[wc_linuxkm_fpu_states_n_tracked]; - if (am_in_hard_interrupt_handler()) { - #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 14, 0) - copy_kernel_to_fpregs(wolfcrypt_linuxkm_fpu_states[processor_id]); - #elif LINUX_VERSION_CODE < KERNEL_VERSION(5, 16, 0) - __restore_fpregs_from_fpstate(wolfcrypt_linuxkm_fpu_states[processor_id], - xfeatures_mask_all); - #else - restore_fpregs_from_fpstate(wolfcrypt_linuxkm_fpu_states[processor_id], - fpu_kernel_cfg.max_features); - #endif - preempt_enable(); - } else { - kernel_fpu_end(); + for (;;) { + for (i = wc_linuxkm_fpu_states, + i_empty = NULL; + i < i_endptr; + ++i) + { + i_pid = __atomic_load_n(&i->pid, __ATOMIC_CONSUME); + if (i_pid == my_pid) + return i; + if ((i_empty == NULL) && (i_pid == 0)) + i_empty = i; } -#else /* !LINUXKM_SIMD_IRQ */ - if ((wolfcrypt_linuxkm_fpu_states[processor_id] & WC_FPU_COUNT_MASK) == 0U) + if ((i_empty == NULL) || (! create_p)) + return NULL; + + i_pid = 0; + if (__atomic_compare_exchange_n( + &(i_empty->pid), + &i_pid, + my_pid, + 0 /* weak */, + __ATOMIC_SEQ_CST /* success_memmodel */, + __ATOMIC_SEQ_CST /* failure_memmodel */)) { - pr_err("restore_vector_registers_x86 called for cpu id %d " - "without saved context.\n", processor_id); - return; + return i_empty; } + } +} - if ((--wolfcrypt_linuxkm_fpu_states[processor_id] & WC_FPU_COUNT_MASK) > 0U) { - preempt_enable(); /* preempt_disable count may still be nonzero - * after this decrement, but any remaining - * count(s) aren't ours. - */ - return; +static void wc_linuxkm_fpu_state_free(struct wc_thread_fpu_count_ent *ent) { + if (ent->fpu_state != 0) { + static int warned_nonzero_fpu_state = 0; + if (! warned_nonzero_fpu_state) { + pr_err("wc_linuxkm_fpu_state_free for pid %d" + " with nonzero fpu_state 0x%x.\n", ent->pid, ent->fpu_state); + warned_nonzero_fpu_state = 1; } + ent->fpu_state = 0; + } + __atomic_store_n(&ent->pid, 0, __ATOMIC_RELEASE); +} + +WARN_UNUSED_RESULT int save_vector_registers_x86(void) +{ + struct wc_thread_fpu_count_ent *pstate = wc_linuxkm_fpu_state_assoc(1); + if (pstate == NULL) + return ENOMEM; - if (wolfcrypt_linuxkm_fpu_states[processor_id] == 0U) { - kernel_fpu_end(); + /* allow for nested calls */ + if (pstate->fpu_state != 0U) { + if ((pstate->fpu_state & WC_FPU_COUNT_MASK) + == WC_FPU_COUNT_MASK) + { + pr_err("save_vector_registers_x86 recursion register overflow for " + "pid %d.\n", pstate->pid); + return BAD_STATE_E; } else { - preempt_enable(); /* preempt_disable count will still be nonzero - * after this decrement. - */ - wolfcrypt_linuxkm_fpu_states[processor_id] = 0U; + ++pstate->fpu_state; + return 0; } -#endif /* !LINUXKM_SIMD_IRQ */ + } + + if (irq_fpu_usable()) { +#if defined(CONFIG_SMP) && !defined(CONFIG_PREEMPT_COUNT) && (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0)) + /* inhibit migration, which gums up the algorithm in kernel_fpu_{begin,end}(). */ + migrate_disable(); +#endif + kernel_fpu_begin(); + pstate->fpu_state = 1U; /* set msb 0 to trigger kernel_fpu_end() at cleanup. */ + } else if (in_nmi() || (hardirq_count() > 0) || (softirq_count() > 0)) { + static int warned_fpu_forbidden = 0; + if (! warned_fpu_forbidden) + pr_err("save_vector_registers_x86 called from IRQ handler.\n"); + wc_linuxkm_fpu_state_free(pstate); + return EPERM; + } else { +#if defined(CONFIG_SMP) && !defined(CONFIG_PREEMPT_COUNT) && (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0)) + migrate_disable(); +#endif + /* assume already safely in_kernel_fpu. */ + pstate->fpu_state = + WC_FPU_SAVED_MASK + 1U; /* set msb 1 to inhibit kernel_fpu_end() at cleanup. */ + } + return 0; +} + +void restore_vector_registers_x86(void) +{ + struct wc_thread_fpu_count_ent *pstate = wc_linuxkm_fpu_state_assoc(0); + if (pstate == NULL) { + pr_err("restore_vector_registers_x86 called by pid %d " + "with no saved state.\n", task_pid_nr(current)); return; } + + if ((--pstate->fpu_state & WC_FPU_COUNT_MASK) > 0U) { + return; + } + + if (pstate->fpu_state == 0U) + kernel_fpu_end(); + else + pstate->fpu_state = 0U; +#if defined(CONFIG_SMP) && !defined(CONFIG_PREEMPT_COUNT) && (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0)) + migrate_enable(); +#endif + + wc_linuxkm_fpu_state_free(pstate); + + return; +} #endif /* WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS && CONFIG_X86 */ #if defined(__PIE__) && (LINUX_VERSION_CODE >= KERNEL_VERSION(6, 1, 0)) diff --git a/linuxkm/linuxkm_wc_port.h b/linuxkm/linuxkm_wc_port.h index 8b839161ca6..bc17aa57f7c 100644 --- a/linuxkm/linuxkm_wc_port.h +++ b/linuxkm/linuxkm_wc_port.h @@ -24,6 +24,12 @@ #ifndef LINUXKM_WC_PORT_H #define LINUXKM_WC_PORT_H + #include + + #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 16, 0) + #error Unsupported kernel. + #endif + #ifdef HAVE_CONFIG_H #ifndef PACKAGE_NAME #error wc_port.h included before config.h @@ -59,6 +65,23 @@ (int)_xatoi_res; \ }) + /* Kbuild+gcc on x86 doesn't consistently honor the default ALIGN16 on stack objects, + * but gives adequate alignment with "32". + */ + #if defined(CONFIG_X86) && !defined(ALIGN16) + #define ALIGN16 __attribute__ ( (aligned (32))) + #endif + + /* kvmalloc()/kvfree() and friends added in linux commit a7c3e901 */ + #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 12, 0) + #define HAVE_KVMALLOC + #endif + + /* kernel printf doesn't implement fp. */ + #ifndef WOLFSSL_NO_FLOAT_FMT + #define WOLFSSL_NO_FLOAT_FMT + #endif + #ifdef BUILDING_WOLFSSL #if defined(CONFIG_MIPS) && defined(HAVE_LINUXKM_PIE_SUPPORT) @@ -95,7 +118,6 @@ #include #include - #include #include #include #include @@ -124,6 +146,8 @@ #ifndef CONFIG_X86 #error X86 SIMD extensions requested, but CONFIG_X86 is not set. #endif + #define WOLFSSL_LINUXKM_SIMD + #define WOLFSSL_LINUXKM_SIMD_X86 #ifndef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS #define WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS #endif @@ -133,6 +157,8 @@ #if !defined(CONFIG_ARM) && !defined(CONFIG_ARM64) #error ARM SIMD extensions requested, but CONFIG_ARM* is not set. #endif + #define WOLFSSL_LINUXKM_SIMD + #define WOLFSSL_LINUXKM_SIMD_ARM #ifndef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS #define WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS #endif @@ -142,26 +168,17 @@ #endif #endif + /* benchmarks.c uses floating point math, so needs a working SAVE_VECTOR_REGISTERS(). */ + #if defined(WOLFSSL_LINUXKM_BENCHMARKS) && !defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) + #define WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS + #endif + #if defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) && defined(CONFIG_X86) - #define WOLFSSL_LINUXKM_SIMD - #define WOLFSSL_LINUXKM_SIMD_X86 #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0) #include #else #include #endif - #ifdef LINUXKM_SIMD_IRQ - #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0) - #include - #endif - #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 16, 0) - #error LINUXKM_SIMD_IRQ is unavailable on linux >= 5.16 (missing exports around fpregs) - /* - * #include - * #include - */ - #endif - #endif #ifndef SAVE_VECTOR_REGISTERS #define SAVE_VECTOR_REGISTERS(fail_clause) { int _svr_ret = save_vector_registers_x86(); if (_svr_ret != 0) { fail_clause } } #endif @@ -169,12 +186,7 @@ #define RESTORE_VECTOR_REGISTERS() restore_vector_registers_x86() #endif #elif defined(WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS) && (defined(CONFIG_ARM) || defined(CONFIG_ARM64)) - #define WOLFSSL_LINUXKM_SIMD - #define WOLFSSL_LINUXKM_SIMD_ARM #include - #ifdef LINUXKM_SIMD_IRQ - #error LINUXKM_SIMD_IRQ is unavailable on ARM (not implemented) - #endif #ifndef SAVE_VECTOR_REGISTERS #define SAVE_VECTOR_REGISTERS(fail_clause) { int _svr_ret = save_vector_registers_arm(); if (_svr_ret != 0) { fail_clause } } #endif @@ -195,11 +207,6 @@ #define NO_THREAD_LS #define NO_ATTRIBUTE_CONSTRUCTOR - /* kvmalloc()/kvfree() and friends added in linux commit a7c3e901 */ - #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 12, 0) - #define HAVE_KVMALLOC - #endif - #ifdef HAVE_FIPS extern int wolfCrypt_FIPS_first(void); extern int wolfCrypt_FIPS_last(void); @@ -215,7 +222,7 @@ #endif #if defined(__PIE__) && !defined(USE_WOLFSSL_LINUXKM_PIE_REDIRECT_TABLE) - #error "compiling -fPIE without PIE support." + #error "compiling -fPIE requires PIE redirect table." #endif #if defined(HAVE_FIPS) && !defined(HAVE_LINUXKM_PIE_SUPPORT) @@ -307,42 +314,37 @@ struct task_struct *(*get_current)(void); int (*preempt_count)(void); - #ifdef WOLFSSL_LINUXKM_SIMD_X86 - typeof(irq_fpu_usable) *irq_fpu_usable; - /* kernel_fpu_begin() replaced by kernel_fpu_begin_mask() in commit e4512289, - * released in kernel 5.11, backported to 5.4.93 - */ - #ifdef kernel_fpu_begin - typeof(kernel_fpu_begin_mask) *kernel_fpu_begin_mask; - #else - typeof(kernel_fpu_begin) *kernel_fpu_begin; - #endif - typeof(kernel_fpu_end) *kernel_fpu_end; - - #ifdef LINUXKM_SIMD_IRQ - #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 14, 0) - typeof(copy_fpregs_to_fpstate) *copy_fpregs_to_fpstate; - typeof(copy_kernel_to_fpregs) *copy_kernel_to_fpregs; - #elif LINUX_VERSION_CODE < KERNEL_VERSION(5, 16, 0) - typeof(save_fpregs_to_fpstate) *save_fpregs_to_fpstate; - typeof(__restore_fpregs_from_fpstate) *__restore_fpregs_from_fpstate; - typeof(xfeatures_mask_all) *xfeatures_mask_all; - /* - * #else - * typeof(save_fpregs_to_fpstate) *save_fpregs_to_fpstate; - * typeof(restore_fpregs_from_fpstate) *restore_fpregs_from_fpstate; - * typeof(fpu_kernel_cfg) *fpu_kernel_cfg; - */ + #ifdef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS + + #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 2, 0) + typeof(cpu_number) *cpu_number; + #else + typeof(pcpu_hot) *pcpu_hot; + #endif + typeof(nr_cpu_ids) *nr_cpu_ids; + + #if defined(CONFIG_SMP) && (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0)) + /* note the current and needed version of these were added in af449901b8 (2020-Sep-17) */ + typeof(migrate_disable) *migrate_disable; + typeof(migrate_enable) *migrate_enable; #endif - #endif - #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 2, 0) - typeof(cpu_number) *cpu_number; - #else - typeof(pcpu_hot) *pcpu_hot; - #endif - typeof(nr_cpu_ids) *nr_cpu_ids; - #endif /* WOLFSSL_LINUXKM_SIMD_X86 */ + #ifdef CONFIG_X86 + typeof(irq_fpu_usable) *irq_fpu_usable; + /* kernel_fpu_begin() replaced by kernel_fpu_begin_mask() in commit e4512289, + * released in kernel 5.11, backported to 5.4.93 + */ + #ifdef kernel_fpu_begin + typeof(kernel_fpu_begin_mask) *kernel_fpu_begin_mask; + #else + typeof(kernel_fpu_begin) *kernel_fpu_begin; + #endif + typeof(kernel_fpu_end) *kernel_fpu_end; + #else /* !CONFIG_X86 */ + #error WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS is set for an unsupported architecture. + #endif /* arch */ + + #endif /* WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS */ typeof(__mutex_init) *__mutex_init; #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0) @@ -452,37 +454,31 @@ #undef preempt_count #define preempt_count (wolfssl_linuxkm_get_pie_redirect_table()->preempt_count) - #ifdef WOLFSSL_LINUXKM_SIMD_X86 - #define irq_fpu_usable (wolfssl_linuxkm_get_pie_redirect_table()->irq_fpu_usable) - #ifdef kernel_fpu_begin - #define kernel_fpu_begin_mask (wolfssl_linuxkm_get_pie_redirect_table()->kernel_fpu_begin_mask) - #else - #define kernel_fpu_begin (wolfssl_linuxkm_get_pie_redirect_table()->kernel_fpu_begin) - #endif - #define kernel_fpu_end (wolfssl_linuxkm_get_pie_redirect_table()->kernel_fpu_end) - #ifdef LINUXKM_SIMD_IRQ - #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 14, 0) - #define copy_fpregs_to_fpstate (wolfssl_linuxkm_get_pie_redirect_table()->copy_fpregs_to_fpstate) - #define copy_kernel_to_fpregs (wolfssl_linuxkm_get_pie_redirect_table()->copy_kernel_to_fpregs) - #elif LINUX_VERSION_CODE < KERNEL_VERSION(5, 16, 0) - #define save_fpregs_to_fpstate (wolfssl_linuxkm_get_pie_redirect_table()->save_fpregs_to_fpstate) - #define __restore_fpregs_from_fpstate (wolfssl_linuxkm_get_pie_redirect_table()->__restore_fpregs_from_fpstate) - #define xfeatures_mask_all (*(wolfssl_linuxkm_get_pie_redirect_table()->xfeatures_mask_all)) - /* - * #else - * #define save_fpregs_to_fpstate (wolfssl_linuxkm_get_pie_redirect_table()->save_fpregs_to_fpstate) - * #define restore_fpregs_from_fpstate (wolfssl_linuxkm_get_pie_redirect_table()->restore_fpregs_from_fpstate) - * #define fpu_kernel_cfg (*(wolfssl_linuxkm_get_pie_redirect_table()->fpu_kernel_cfg)) - */ - #endif - #endif + #ifdef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 2, 0) #define cpu_number (*(wolfssl_linuxkm_get_pie_redirect_table()->cpu_number)) #else #define pcpu_hot (*(wolfssl_linuxkm_get_pie_redirect_table()->pcpu_hot)) #endif #define nr_cpu_ids (*(wolfssl_linuxkm_get_pie_redirect_table()->nr_cpu_ids)) - #endif + + #if defined(CONFIG_SMP) && (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0)) + #define migrate_disable (*(wolfssl_linuxkm_get_pie_redirect_table()->migrate_disable)) + #define migrate_enable (*(wolfssl_linuxkm_get_pie_redirect_table()->migrate_enable)) + #endif + + #ifdef CONFIG_X86 + #define irq_fpu_usable (wolfssl_linuxkm_get_pie_redirect_table()->irq_fpu_usable) + #ifdef kernel_fpu_begin + #define kernel_fpu_begin_mask (wolfssl_linuxkm_get_pie_redirect_table()->kernel_fpu_begin_mask) + #else + #define kernel_fpu_begin (wolfssl_linuxkm_get_pie_redirect_table()->kernel_fpu_begin) + #endif + #define kernel_fpu_end (wolfssl_linuxkm_get_pie_redirect_table()->kernel_fpu_end) + #else /* !CONFIG_X86 */ + #error WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS is set for an unsupported architecture. + #endif /* archs */ + #endif /* WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS */ #define __mutex_init (wolfssl_linuxkm_get_pie_redirect_table()->__mutex_init) #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0) @@ -515,9 +511,9 @@ #endif /* USE_WOLFSSL_LINUXKM_PIE_REDIRECT_TABLE */ -#ifdef WOLFSSL_LINUXKM_SIMD +#ifdef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS -#ifdef WOLFSSL_LINUXKM_SIMD_X86 +#ifdef CONFIG_X86 extern __must_check int allocate_wolfcrypt_linuxkm_fpu_states(void); extern void free_wolfcrypt_linuxkm_fpu_states(void); @@ -547,7 +543,7 @@ #endif -#endif /* WOLFSSL_LINUXKM_SIMD */ +#endif /* WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS */ /* remove this multifariously conflicting macro, picked up from * Linux arch//include/asm/current.h. @@ -556,22 +552,6 @@ #undef current #endif - /* prevent gcc's mm_malloc.h from being included, since it unconditionally - * includes stdlib.h, which is kernel-incompatible. - */ - #define _MM_MALLOC_H_INCLUDED - - #ifdef HAVE_KVMALLOC - #define malloc(x) kvmalloc_node(x, GFP_KERNEL, NUMA_NO_NODE) - #define free(x) kvfree(x) - void *lkm_realloc(void *ptr, size_t newsize); - #define realloc(x, y) lkm_realloc(x, y) - #else - #define malloc(x) kmalloc(x, GFP_KERNEL) - #define free(x) kfree(x) - #define realloc(x,y) krealloc(x, y, GFP_KERNEL) - #endif - /* min() and max() in linux/kernel.h over-aggressively type-check, producing * myriad spurious -Werrors throughout the codebase. */ @@ -618,9 +598,41 @@ #include typedef struct mutex wolfSSL_Mutex; - #define XMALLOC(s, h, t) ({(void)(h); (void)(t); kmalloc(s, GFP_KERNEL);}) - #define XFREE(p, h, t) ({void* _xp; (void)(h); _xp = (p); if(_xp) kfree(_xp);}) - #define XREALLOC(p, n, h, t) ({(void)(h); (void)(t); krealloc((p), (n), GFP_KERNEL);}) + /* prevent gcc's mm_malloc.h from being included, since it unconditionally + * includes stdlib.h, which is kernel-incompatible. + */ + #define _MM_MALLOC_H_INCLUDED + + /* fun fact: since linux commit 59bb47985c, kmalloc with power-of-2 size is + * aligned to the size. + */ + #define WC_LINUXKM_ROUND_UP_P_OF_2(x) ( \ + { \ + size_t _alloc_sz = (x); \ + _alloc_sz = 1UL << ((sizeof(_alloc_sz) * 8UL) - __builtin_clzl(_alloc_sz)); \ + _alloc_sz; \ + }) + #ifdef HAVE_KVMALLOC + #define malloc(size) kvmalloc_node(WC_LINUXKM_ROUND_UP_P_OF_2(size), GFP_KERNEL, NUMA_NO_NODE) + #define free(ptr) kvfree(ptr) + void *lkm_realloc(void *ptr, size_t newsize); + #define realloc(ptr, newsize) lkm_realloc(ptr, WC_LINUXKM_ROUND_UP_P_OF_2(newsize)) + #else + #define malloc(size) kmalloc(WC_LINUXKM_ROUND_UP_P_OF_2(size), GFP_KERNEL) + #define free(ptr) kfree(ptr) + #define realloc(ptr, newsize) krealloc(ptr, WC_LINUXKM_ROUND_UP_P_OF_2(newsize), GFP_KERNEL) + #endif + +#ifdef WOLFSSL_TRACK_MEMORY + #include + #define XMALLOC(s, h, t) ({(void)(h); (void)(t); wolfSSL_Malloc(s);}) + #define XFREE(p, h, t) ({void* _xp; (void)(h); _xp = (p); if(_xp) wolfSSL_Free(_xp);}) + #define XREALLOC(p, n, h, t) ({(void)(h); (void)(t); wolfSSL_Realloc(p, n);}) +#else + #define XMALLOC(s, h, t) ({(void)(h); (void)(t); malloc(s);}) + #define XFREE(p, h, t) ({void* _xp; (void)(h); _xp = (p); if(_xp) free(_xp);}) + #define XREALLOC(p, n, h, t) ({(void)(h); (void)(t); realloc(p, n);}) +#endif #include diff --git a/linuxkm/module_hooks.c b/linuxkm/module_hooks.c index 3f17217d3af..7f9f8399403 100644 --- a/linuxkm/module_hooks.c +++ b/linuxkm/module_hooks.c @@ -113,6 +113,15 @@ static void lkmFipsCb(int ok, int err, const char* hash) static int updateFipsHash(void); #endif +#ifdef WOLFSSL_LINUXKM_BENCHMARKS +#undef HAVE_PTHREAD +#define STRING_USER +#define NO_MAIN_FUNCTION +#define current_time benchmark_current_time +#define WOLFSSL_NO_FLOAT_FMT +#include "/home/douzzer/com/wolfssl/src/wolfssl/wolfcrypt/benchmark/benchmark.c" +#endif /* WOLFSSL_LINUXKM_BENCHMARKS */ + #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 0, 0) static int __init wolfssl_init(void) #else @@ -202,10 +211,9 @@ static int wolfssl_init(void) * the true module start address, which is potentially useful to an * attacker. */ - pr_info("wolfCrypt container hashes (spans): %x (%lu) %x (%lu), text base %pK, ro base %pK\n", + pr_info("wolfCrypt container hashes (spans): text 0x%x (%lu), rodata 0x%x (%lu)\n", text_hash, pie_text_end-pie_text_start, - rodata_hash, pie_rodata_end-pie_rodata_start, - THIS_MODULE_TEXT_BASE, THIS_MODULE_RO_BASE); + rodata_hash, pie_rodata_end-pie_rodata_start); } #endif /* HAVE_LINUXKM_PIE_SUPPORT */ @@ -277,6 +285,10 @@ static int wolfssl_init(void) pr_info("wolfCrypt self-test passed.\n"); #endif +#ifdef WOLFSSL_LINUXKM_BENCHMARKS + wolfcrypt_benchmark_main(0, (char**)NULL); +#endif + #ifdef WOLFCRYPT_ONLY pr_info("wolfCrypt " LIBWOLFSSL_VERSION_STRING " loaded%s" ".\nSee https://www.wolfssl.com/ for more information.\n" @@ -334,15 +346,6 @@ static int my_preempt_count(void) { return preempt_count(); } -#if defined(WOLFSSL_LINUXKM_SIMD_X86) && (LINUX_VERSION_CODE < KERNEL_VERSION(5, 14, 0)) -static int my_copy_fpregs_to_fpstate(struct fpu *fpu) { - return copy_fpregs_to_fpstate(fpu); -} -static void my_copy_kernel_to_fpregs(union fpregs_state *fpstate) { - copy_kernel_to_fpregs(fpstate); -} -#endif - static int set_up_wolfssl_linuxkm_pie_redirect_table(void) { memset( &wolfssl_linuxkm_pie_redirect_table, @@ -430,6 +433,20 @@ static int set_up_wolfssl_linuxkm_pie_redirect_table(void) { wolfssl_linuxkm_pie_redirect_table.get_current = my_get_current_thread; wolfssl_linuxkm_pie_redirect_table.preempt_count = my_preempt_count; +#ifdef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS + + #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 2, 0) + wolfssl_linuxkm_pie_redirect_table.cpu_number = &cpu_number; + #else + wolfssl_linuxkm_pie_redirect_table.pcpu_hot = &pcpu_hot; + #endif + wolfssl_linuxkm_pie_redirect_table.nr_cpu_ids = &nr_cpu_ids; + + #if defined(CONFIG_SMP) && (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0)) + wolfssl_linuxkm_pie_redirect_table.migrate_disable = &migrate_disable; + wolfssl_linuxkm_pie_redirect_table.migrate_enable = &migrate_enable; + #endif + #ifdef WOLFSSL_LINUXKM_SIMD_X86 wolfssl_linuxkm_pie_redirect_table.irq_fpu_usable = irq_fpu_usable; #ifdef kernel_fpu_begin @@ -440,29 +457,9 @@ static int set_up_wolfssl_linuxkm_pie_redirect_table(void) { kernel_fpu_begin; #endif wolfssl_linuxkm_pie_redirect_table.kernel_fpu_end = kernel_fpu_end; - #ifdef LINUXKM_SIMD_IRQ - #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 14, 0) - wolfssl_linuxkm_pie_redirect_table.copy_fpregs_to_fpstate = my_copy_fpregs_to_fpstate; - wolfssl_linuxkm_pie_redirect_table.copy_kernel_to_fpregs = my_copy_kernel_to_fpregs; - #elif LINUX_VERSION_CODE < KERNEL_VERSION(5, 16, 0) - wolfssl_linuxkm_pie_redirect_table.save_fpregs_to_fpstate = save_fpregs_to_fpstate; - wolfssl_linuxkm_pie_redirect_table.__restore_fpregs_from_fpstate = __restore_fpregs_from_fpstate; - wolfssl_linuxkm_pie_redirect_table.xfeatures_mask_all = &xfeatures_mask_all; - /* - * #else - * wolfssl_linuxkm_pie_redirect_table.save_fpregs_to_fpstate = save_fpregs_to_fpstate; - * wolfssl_linuxkm_pie_redirect_table.restore_fpregs_from_fpstate = restore_fpregs_from_fpstate; - * wolfssl_linuxkm_pie_redirect_table.fpu_kernel_cfg = &fpu_kernel_cfg; - */ - #endif - #endif - #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 2, 0) - wolfssl_linuxkm_pie_redirect_table.cpu_number = &cpu_number; - #else - wolfssl_linuxkm_pie_redirect_table.pcpu_hot = &pcpu_hot; - #endif - wolfssl_linuxkm_pie_redirect_table.nr_cpu_ids = &nr_cpu_ids; -#endif +#endif /* WOLFSSL_LINUXKM_SIMD_X86 */ + +#endif /* WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS */ wolfssl_linuxkm_pie_redirect_table.__mutex_init = __mutex_init; #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0) diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index b6736e50183..ff1a817b0e0 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -207,7 +207,7 @@ int wolfCrypt_Init(void) } #endif - #if defined(WOLFSSL_LINUXKM_SIMD_X86) + #ifdef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS ret = allocate_wolfcrypt_linuxkm_fpu_states(); if (ret != 0) { WOLFSSL_MSG("allocate_wolfcrypt_linuxkm_fpu_states failed"); @@ -466,7 +466,7 @@ int wolfCrypt_Cleanup(void) rpcmem_deinit(); wolfSSL_CleanupHandle(); #endif - #if defined(WOLFSSL_LINUXKM_SIMD_X86) + #ifdef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS free_wolfcrypt_linuxkm_fpu_states(); #endif @@ -3207,56 +3207,6 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) #endif /* WOLFSSL_NUCLEUS_1_2 */ -#if defined(WOLFSSL_LINUXKM) && defined(HAVE_KVMALLOC) - /* adapted from kvrealloc() draft by Changli Gao, 2010-05-13 */ - void *lkm_realloc(void *ptr, size_t newsize) { - void *nptr; - size_t oldsize; - - if (unlikely(newsize == 0)) { - kvfree(ptr); - return ZERO_SIZE_PTR; - } - - if (unlikely(ptr == NULL)) - return kvmalloc_node(newsize, GFP_KERNEL, NUMA_NO_NODE); - - if (is_vmalloc_addr(ptr)) { - /* no way to discern the size of the old allocation, - * because the kernel doesn't export find_vm_area(). if - * it did, we could then call get_vm_area_size() on the - * returned struct vm_struct. - */ - return NULL; - } else { -#ifndef __PIE__ - struct page *page; - - page = virt_to_head_page(ptr); - if (PageSlab(page) || PageCompound(page)) { - if (newsize < PAGE_SIZE) -#endif /* ! __PIE__ */ - return krealloc(ptr, newsize, GFP_KERNEL); -#ifndef __PIE__ - oldsize = ksize(ptr); - } else { - oldsize = page->private; - if (newsize <= oldsize) - return ptr; - } -#endif /* ! __PIE__ */ - } - - nptr = kvmalloc_node(newsize, GFP_KERNEL, NUMA_NO_NODE); - if (nptr != NULL) { - memcpy(nptr, ptr, oldsize); - kvfree(ptr); - } - - return nptr; - } -#endif /* WOLFSSL_LINUXKM && HAVE_KVMALLOC */ - #if defined(WOLFSSL_TI_CRYPT) || defined(WOLFSSL_TI_HASH) #include /* initialize and Mutex for TI Crypt Engine */ #include /* md5, sha1, sha224, sha256 */ From 674826fee2429b5efbf2a8d9022f4baf9c5f6102 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 02:27:04 -0500 Subject: [PATCH 298/391] wolfcrypt/benchmark/benchmark.c: fix typo in bench_stats_start(). --- wolfcrypt/benchmark/benchmark.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 59a51cc0de2..88bff614258 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -1702,7 +1702,7 @@ static WC_INLINE void bench_stats_start(int* count, double* start) #ifdef WOLFSSL_ESPIDF ESP_LOGV(TAG, "finish total_cycles = %llu, start=" FLT_FMT, - total_cycles, FLT_FMT_ARG(*start) ); + total_cycles, FLT_FMT_ARGS(*start) ); BEGIN_ESP_CYCLES #else From 8952a0cbeda9aa1afa0b108632306922a6f62f17 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 17 May 2023 13:00:46 -0500 Subject: [PATCH 299/391] cleanups: line length, WOLFSSL_SMALL_STACK_STATIC, and SAVE_VECTOR_REGISTERS() failure trap in benchmark.c, proper path to benchmark.c in linuxkm/module_hooks.c, and proper casting in aes.c. also harmonized semantics and prototype of bench_ripemd(). --- linuxkm/module_hooks.c | 2 +- wolfcrypt/benchmark/benchmark.c | 212 ++++++++++++++++++++------------ wolfcrypt/benchmark/benchmark.h | 2 +- wolfcrypt/src/aes.c | 2 +- 4 files changed, 138 insertions(+), 80 deletions(-) diff --git a/linuxkm/module_hooks.c b/linuxkm/module_hooks.c index 7f9f8399403..fb7f114208c 100644 --- a/linuxkm/module_hooks.c +++ b/linuxkm/module_hooks.c @@ -119,7 +119,7 @@ static int updateFipsHash(void); #define NO_MAIN_FUNCTION #define current_time benchmark_current_time #define WOLFSSL_NO_FLOAT_FMT -#include "/home/douzzer/com/wolfssl/src/wolfssl/wolfcrypt/benchmark/benchmark.c" +#include "wolfcrypt/benchmark/benchmark.c" #endif /* WOLFSSL_LINUXKM_BENCHMARKS */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 0, 0) diff --git a/wolfcrypt/benchmark/benchmark.c b/wolfcrypt/benchmark/benchmark.c index 88bff614258..6609a2e20fe 100644 --- a/wolfcrypt/benchmark/benchmark.c +++ b/wolfcrypt/benchmark/benchmark.c @@ -69,14 +69,21 @@ #define FLT_FMT "%0ld,%09lu" #define FLT_FMT_PREC "%0ld.%0*lu" #define FLT_FMT_PREC2 FLT_FMT_PREC - #define FLT_FMT_ARGS(x) (long)(x), ((x) < 0) ? (unsigned long)(-(((x) - (double)(long)(x)) * 1000000000.0)) : (unsigned long)(((x) - (double)(long)(x)) * 1000000000.0) - static const double pow_10_array[] = { 0.0, 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0 }; + #define FLT_FMT_ARGS(x) (long)(x), ((x) < 0) ? \ + (unsigned long)(-(((x) - (double)(long)(x)) * 1000000000.0)) : \ + (unsigned long)(((x) - (double)(long)(x)) * 1000000000.0) + static const double pow_10_array[] = { 0.0, 1.0, 10.0, 100.0, 1000.0, \ + 10000.0, 100000.0, 1000000.0, \ + 10000000.0, 100000000.0, \ + 1000000000.0 }; #define FLT_FMT_PREC_ARGS(p, x) \ (long)(x), \ p, \ - (x) >= 0.0 ? \ - (unsigned long int)((((x) - (double)(long)(x)) * pow_10_array[(p)+1]) + 0.5) : \ - (unsigned long int)((((-(x)) - (double)((long)-(x))) * pow_10_array[(p)+1]) + 0.5) + (x) >= 0.0 ? \ + (unsigned long int)((((x) - (double)(long)(x)) * \ + pow_10_array[(p)+1]) + 0.5) : \ + (unsigned long int)((((-(x)) - (double)((long)-(x))) * \ + pow_10_array[(p)+1]) + 0.5) #define FLT_FMT_PREC2_ARGS(w, p, x) FLT_FMT_PREC_ARGS(p, x) #else #define FLT_FMT "%f" @@ -943,13 +950,16 @@ static const char* bench_desc_words[][15] = { #define BEGIN_INTEL_CYCLES total_cycles = get_intel_cycles(); #define END_INTEL_CYCLES total_cycles = get_intel_cycles() - total_cycles; /* s == size in bytes that 1 count represents, normally BENCH_SIZE */ - #define SHOW_INTEL_CYCLES(b, n, s) \ - (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), " %s = " FLT_FMT_PREC2 "\n", \ - bench_result_words1[lng_index][2], \ - FLT_FMT_PREC2_ARGS(6, 2, count == 0 ? 0 : (double)total_cycles / ((word64)count*(s)))) - #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ + #define SHOW_INTEL_CYCLES(b, n, s) \ + (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), \ + " %s = " FLT_FMT_PREC2 "\n", \ + bench_result_words1[lng_index][2], \ + FLT_FMT_PREC2_ARGS(6, 2, count == 0 ? 0 : \ + (double)total_cycles / ((word64)count*(s)))) + #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ (void)XSNPRINTF((b) + XSTRLEN(b), (n) - XSTRLEN(b), FLT_FMT_PREC ",\n", \ - FLT_FMT_PREC_ARGS(6, count == 0 ? 0 : (double)total_cycles / ((word64)count*(s)))) + FLT_FMT_PREC_ARGS(6, count == 0 ? 0 : \ + (double)total_cycles / ((word64)count*(s)))) #elif defined(LINUX_CYCLE_COUNT) #include #include @@ -960,25 +970,26 @@ static const char* bench_desc_words[][15] = { static THREAD_LS_T int cycles = -1; static THREAD_LS_T struct perf_event_attr atr; - #define INIT_CYCLE_COUNTER do { \ - atr.type = PERF_TYPE_HARDWARE; \ - atr.config = PERF_COUNT_HW_CPU_CYCLES; \ - cycles = (int)syscall(__NR_perf_event_open, &atr, 0, -1, -1, 0); \ + #define INIT_CYCLE_COUNTER do { \ + atr.type = PERF_TYPE_HARDWARE; \ + atr.config = PERF_COUNT_HW_CPU_CYCLES; \ + cycles = (int)syscall(__NR_perf_event_open, &atr, 0, -1, -1, 0); \ } while (0); #define BEGIN_INTEL_CYCLES read(cycles, &begin_cycles, sizeof(begin_cycles)); - #define END_INTEL_CYCLES do { \ - read(cycles, &total_cycles, sizeof(total_cycles)); \ - total_cycles = total_cycles - begin_cycles; \ + #define END_INTEL_CYCLES do { \ + read(cycles, &total_cycles, sizeof(total_cycles)); \ + total_cycles = total_cycles - begin_cycles; \ } while (0); /* s == size in bytes that 1 count represents, normally BENCH_SIZE */ - #define SHOW_INTEL_CYCLES(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = " FLT_FMT_PREC2 "\n", \ - bench_result_words1[lng_index][2], \ + #define SHOW_INTEL_CYCLES(b, n, s) \ + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), \ + " %s = " FLT_FMT_PREC2 "\n", \ + bench_result_words1[lng_index][2], \ FLT_FMT_PREC2_ARGS(6, 2, (double)total_cycles / (count*s))) - #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), FLT_FMT_PREC ",\n", \ + #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), FLT_FMT_PREC ",\n", \ FLT_FMT_PREC_ARGS(6, (double)total_cycles / (count*s))) #elif defined(SYNERGY_CYCLE_COUNT) @@ -991,12 +1002,13 @@ static const char* bench_desc_words[][15] = { #define END_INTEL_CYCLES total_cycles = DWT->CYCCNT - begin_cycles; /* s == size in bytes that 1 count represents, normally BENCH_SIZE */ - #define SHOW_INTEL_CYCLES(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = " FLT_FMT_PREC2 "\n", \ - bench_result_words1[lng_index][2], \ + #define SHOW_INTEL_CYCLES(b, n, s) \ + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), \ + " %s = " FLT_FMT_PREC2 "\n", \ + bench_result_words1[lng_index][2], \ FLT_FMT_PREC2_ARGS(6, 2, (double)total_cycles / (count*s))) - #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), FLT_FMT_PREC ",\n", \ + #define SHOW_INTEL_CYCLES_CSV(b, n, s) \ + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), FLT_FMT_PREC ",\n", \ FLT_FMT_PREC_ARGS(6, (double)total_cycles / (count*s))) #elif defined(WOLFSSL_ESPIDF) static THREAD_LS_T word64 begin_cycles; @@ -1027,9 +1039,10 @@ static const char* bench_desc_words[][15] = { total_cycles = (get_xtensa_cycles() - begin_cycles); #define SHOW_ESP_CYCLES(b, n, s) \ - (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), " %s = " FLT_FMT_PREC2 "\n", \ - bench_result_words1[lng_index][2], \ - FLT_FMT_PREC2_ARGS(6, 2, (double)total_cycles / (count*s)) \ + (void)XSNPRINTF(b + XSTRLEN(b), n - XSTRLEN(b), \ + " %s = " FLT_FMT_PREC2 "\n", \ + bench_result_words1[lng_index][2], \ + FLT_FMT_PREC2_ARGS(6, 2, (double)total_cycles / (count*s)) \ ) #define SHOW_ESP_CYCLES_CSV(b, n, s) \ @@ -1613,13 +1626,15 @@ typedef enum bench_stat_type { for (bstat = bench_stats_head; bstat != NULL; ) { if (bstat->type == BENCH_STAT_SYM) { printf("%-16s%s " FLT_FMT_PREC2 " %s/s\n", bstat->desc, - BENCH_DEVID_GET_NAME(bstat->useDeviceID), FLT_FMT_PREC2_ARGS(8, 3, bstat->perfsec), + BENCH_DEVID_GET_NAME(bstat->useDeviceID), + FLT_FMT_PREC2_ARGS(8, 3, bstat->perfsec), base2 ? "MB" : "mB"); } else { printf("%-5s %4d %-9s %s " FLT_FMT_PREC " ops/sec\n", bstat->algo, bstat->strength, bstat->desc, - BENCH_DEVID_GET_NAME(bstat->useDeviceID), FLT_FMT_PREC_ARGS(3, bstat->perfsec)); + BENCH_DEVID_GET_NAME(bstat->useDeviceID), + FLT_FMT_PREC_ARGS(3, bstat->perfsec)); } bstat = bstat->next; @@ -1673,12 +1688,14 @@ typedef enum bench_stat_type { for (i=0; itype == BENCH_STAT_SYM) { - printf("%-16s " FLT_FMT_PREC2 " %s/s\n", bstat->desc, FLT_FMT_PREC2_ARGS(8, 3, bstat->perfsec), + printf("%-16s " FLT_FMT_PREC2 " %s/s\n", bstat->desc, + FLT_FMT_PREC2_ARGS(8, 3, bstat->perfsec), base2 ? "MB" : "mB"); } else if (bstat->type == BENCH_STAT_ASYM) { printf("%-5s %4d %-9s " FLT_FMT_PREC " ops/sec\n", - bstat->algo, bstat->strength, bstat->desc, FLT_FMT_PREC_ARGS(3, bstat->perfsec)); + bstat->algo, bstat->strength, bstat->desc, + FLT_FMT_PREC_ARGS(3, bstat->perfsec)); } } } @@ -1695,8 +1712,6 @@ static WC_INLINE void bench_stats_init(void) static WC_INLINE void bench_stats_start(int* count, double* start) { - SAVE_VECTOR_REGISTERS(pr_err("SAVE_VECTOR_REGISTERS failed for benchmark run.");); - *count = 0; *start = current_time(1); @@ -1710,6 +1725,14 @@ static WC_INLINE void bench_stats_start(int* count, double* start) #endif } +#ifdef WOLFSSL_LINUXKM_USE_SAVE_VECTOR_REGISTERS + #define bench_stats_start(count, start) do { \ + SAVE_VECTOR_REGISTERS(pr_err("SAVE_VECTOR_REGISTERS failed for benchmark run."); \ + return; ); \ + bench_stats_start(count, start); \ + } while (0) +#endif + static WC_INLINE int bench_stats_check(double start) { return ((current_time(0) - start) < BENCH_MIN_RUNTIME_SEC); @@ -1911,13 +1934,17 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, #else #ifdef HAVE_GET_CYCLES - (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu," FLT_FMT "," FLT_FMT ",%lu,", desc, + (void)XSNPRINTF(msg, sizeof(msg), + "sym,%s,%s,%lu," FLT_FMT "," FLT_FMT ",%lu,", desc, BENCH_DEVID_GET_NAME(useDeviceID), - bytes_processed, FLT_FMT_ARGS(total), FLT_FMT_ARGS(persec), total_cycles); + bytes_processed, FLT_FMT_ARGS(total), + FLT_FMT_ARGS(persec), total_cycles); #else - (void)XSNPRINTF(msg, sizeof(msg), "sym,%s,%s,%lu," FLT_FMT "," FLT_FMT ",", desc, + (void)XSNPRINTF(msg, sizeof(msg), + "sym,%s,%s,%lu," FLT_FMT "," FLT_FMT ",", desc, BENCH_DEVID_GET_NAME(useDeviceID), - bytes_processed, FLT_FMT_ARGS(total), FLT_FMT_ARGS(persec)); + bytes_processed, FLT_FMT_ARGS(total), + FLT_FMT_ARGS(persec)); #endif #endif #elif defined(BENCH_DEVID) @@ -1940,23 +1967,30 @@ static void bench_stats_sym_finish(const char* desc, int useDeviceID, #ifdef GENERATE_MACHINE_PARSEABLE_REPORT #ifdef HAVE_GET_CYCLES (void)XSNPRINTF(msg, sizeof(msg), - "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " FLT_FMT_PREC2 " %s/s" - ", %lu cycles,", - desc, BENCH_DEVID_GET_NAME(useDeviceID), FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, - word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], FLT_FMT_PREC2_ARGS(8, 3, persec), blockType, + "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " + FLT_FMT_PREC2 " %s/s, %lu cycles,", + desc, BENCH_DEVID_GET_NAME(useDeviceID), + FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, + word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], + FLT_FMT_PREC2_ARGS(8, 3, persec), blockType, (unsigned long) total_cycles); #else (void)XSNPRINTF(msg, sizeof(msg), - "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " FLT_FMT_PREC2 " %s/s" - ",", - desc, BENCH_DEVID_GET_NAME(useDeviceID), FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, - word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], FLT_FMT_PREC2_ARGS(8, 3, persec), blockType); + "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " + FLT_FMT_PREC2 " %s/s,", + desc, BENCH_DEVID_GET_NAME(useDeviceID), + FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, + word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], + FLT_FMT_PREC2_ARGS(8, 3, persec), blockType); #endif /* HAVE_GET_CYCLES */ #else (void)XSNPRINTF(msg, sizeof(msg), - "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " FLT_FMT_PREC2 " %s/s", - desc, BENCH_DEVID_GET_NAME(useDeviceID), FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, - word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], FLT_FMT_PREC2_ARGS(8, 3, persec), blockType); + "%-24s%s " FLT_FMT_PREC2 " %s %s " FLT_FMT_PREC2 " %s, " + FLT_FMT_PREC2 " %s/s", + desc, BENCH_DEVID_GET_NAME(useDeviceID), + FLT_FMT_PREC2_ARGS(5, 0, blocks), blockType, + word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], + FLT_FMT_PREC2_ARGS(8, 3, persec), blockType); #endif #ifdef WOLFSSL_ESPIDF @@ -2064,19 +2098,23 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, #ifdef GENERATE_MACHINE_PARSEABLE_REPORT #ifdef HAVE_GET_CYCLES (void)XSNPRINTF(msg, sizeof(msg), - "asym,%s,%d,%s%s," FLT_FMT_PREC "," FLT_FMT_PREC ",%d," FLT_FMT ",%lu," FLT_FMT_PREC "\n", - algo, strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), + "asym,%s,%d,%s%s," FLT_FMT_PREC "," FLT_FMT_PREC ",%d," FLT_FMT + ",%lu," FLT_FMT_PREC "\n", + algo, strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), + FLT_FMT_PREC_ARGS(3, opsSec), count, FLT_FMT_ARGS(total), (unsigned long) total_cycles, FLT_FMT_PREC_ARGS(6, (double)total_cycles / (double)count)); #else (void)XSNPRINTF(msg, sizeof(msg), "asym,%s,%d,%s%s," FLT_FMT_PREC "," FLT_FMT_PREC ",%d," FLT_FMT "\n", - algo, strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), + algo, strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), + FLT_FMT_PREC_ARGS(3, opsSec), count, FLT_FMT_ARGS(total)); #endif #else (void)XSNPRINTF(msg, sizeof(msg), "%s,%d,%s%s," FLT_FMT_PREC "," FLT_FMT_PREC ",\n", algo, - strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec)); + strength, desc, desc_extra, FLT_FMT_PREC_ARGS(3, milliEach), + FLT_FMT_PREC_ARGS(3, opsSec)); #endif } /* if (csv_format == 1) */ @@ -2087,14 +2125,16 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, "%-6s %5d %8s%-2s %s %6d %s " FLT_FMT_PREC2 " %s, %s " FLT_FMT_PREC2 " ms," " " FLT_FMT_PREC " %s, %lu cycles\n", algo, strength, desc, desc_extra, BENCH_DEVID_GET_NAME(useDeviceID), - count, word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], FLT_FMT_PREC2_ARGS(5, 3, milliEach), + count, word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], + FLT_FMT_PREC2_ARGS(5, 3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), word[3], (unsigned long) total_cycles); #else (void)XSNPRINTF(msg, sizeof(msg), "%-6s %5d %8s%-2s %s %6d %s " FLT_FMT_PREC2 " %s, %s " FLT_FMT_PREC2 " ms," " " FLT_FMT_PREC " %s\n", algo, strength, desc, desc_extra, BENCH_DEVID_GET_NAME(useDeviceID), - count, word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], FLT_FMT_PREC2_ARGS(5, 3, milliEach), + count, word[0], FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], + FLT_FMT_PREC2_ARGS(5, 3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), word[3]); #endif /* HAVE_GET_CYCLES */ #else @@ -2102,7 +2142,8 @@ static void bench_stats_asym_finish_ex(const char* algo, int strength, "%-6s %5d %8s%-2s %s %6d %s " FLT_FMT_PREC2 " %s, %s " FLT_FMT_PREC2 " ms," " " FLT_FMT_PREC " %s\n", algo, strength, desc, desc_extra, BENCH_DEVID_GET_NAME(useDeviceID), count, word[0], - FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], FLT_FMT_PREC2_ARGS(5, 3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), word[3]); + FLT_FMT_PREC2_ARGS(5, 3, total), word[1], word[2], + FLT_FMT_PREC2_ARGS(5, 3, milliEach), FLT_FMT_PREC_ARGS(3, opsSec), word[3]); #endif } printf("%s", msg); @@ -5717,7 +5758,7 @@ void bench_shake256(int useDeviceID) #ifdef WOLFSSL_RIPEMD -int bench_ripemd(void) +void bench_ripemd(void) { RipeMd hash; byte digest[RIPEMD_DIGEST_SIZE]; @@ -5727,7 +5768,8 @@ int bench_ripemd(void) if (digest_stream) { ret = wc_InitRipeMd(&hash); if (ret != 0) { - return ret; + printf("wc_InitRipeMd failed, retval %d\n", ret); + return; } bench_stats_start(&count, &start); @@ -5735,12 +5777,14 @@ int bench_ripemd(void) for (i = 0; i < numBlocks; i++) { ret = wc_RipeMdUpdate(&hash, bench_plain, bench_size); if (ret != 0) { - return ret; + printf("wc_RipeMdUpdate failed, retval %d\n", ret); + return; } } ret = wc_RipeMdFinal(&hash, digest); if (ret != 0) { - return ret; + printf("wc_RipeMdFinal failed, retval %d\n", ret); + return; } count += i; @@ -5752,15 +5796,18 @@ int bench_ripemd(void) for (i = 0; i < numBlocks; i++) { ret = wc_InitRipeMd(&hash); if (ret != 0) { - return ret; + printf("wc_InitRipeMd failed, retval %d\n", ret); + return; } ret = wc_RipeMdUpdate(&hash, bench_plain, bench_size); if (ret != 0) { - return ret; + printf("wc_RipeMdUpdate failed, retval %d\n", ret); + return; } ret = wc_RipeMdFinal(&hash, digest); if (ret != 0) { - return ret; + printf("wc_RipeMdFinal failed, retval %d\n", ret); + return; } } count += i; @@ -5768,7 +5815,7 @@ int bench_ripemd(void) } bench_stats_sym_finish("RIPEMD", 0, count, bench_size, start, ret); - return 0; + return; } #endif @@ -6091,7 +6138,8 @@ static void bench_hmac(int useDeviceID, int type, int digestSz, void bench_hmac_md5(int useDeviceID) { - static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + WOLFSSL_SMALL_STACK_STATIC const byte key[] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; bench_hmac(useDeviceID, WC_MD5, WC_MD5_DIGEST_SIZE, key, sizeof(key), @@ -6104,7 +6152,8 @@ void bench_hmac_md5(int useDeviceID) void bench_hmac_sha(int useDeviceID) { - static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + WOLFSSL_SMALL_STACK_STATIC const byte key[] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; @@ -6118,7 +6167,8 @@ void bench_hmac_sha(int useDeviceID) void bench_hmac_sha224(int useDeviceID) { - static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + WOLFSSL_SMALL_STACK_STATIC const byte key[] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; @@ -6134,7 +6184,8 @@ void bench_hmac_sha224(int useDeviceID) void bench_hmac_sha256(int useDeviceID) { - static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + WOLFSSL_SMALL_STACK_STATIC const byte key[] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; @@ -6149,7 +6200,8 @@ void bench_hmac_sha256(int useDeviceID) void bench_hmac_sha384(int useDeviceID) { - static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + WOLFSSL_SMALL_STACK_STATIC const byte key[] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, @@ -6166,7 +6218,8 @@ void bench_hmac_sha384(int useDeviceID) void bench_hmac_sha512(int useDeviceID) { - static const byte key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + WOLFSSL_SMALL_STACK_STATIC const byte key[] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, @@ -6187,7 +6240,8 @@ void bench_pbkdf2(void) double start; int ret = 0, count = 0; const char* passwd32 = "passwordpasswordpasswordpassword"; - static const byte salt32[] = { 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06, + WOLFSSL_SMALL_STACK_STATIC const byte salt32[] = { + 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06, 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06, 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06, 0x78, 0x57, 0x8E, 0x5a, 0x5d, 0x63, 0xcb, 0x06 }; @@ -6913,7 +6967,8 @@ void bench_dh(int useDeviceID) BENCH_MAX_PENDING, BENCH_DH_PRIV_SIZE, HEAP_HINT); #ifdef WOLFSSL_SMALL_STACK - dhKey = (DhKey *)XMALLOC(sizeof(DhKey) * BENCH_MAX_PENDING, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); + dhKey = (DhKey *)XMALLOC(sizeof(DhKey) * BENCH_MAX_PENDING, HEAP_HINT, + DYNAMIC_TYPE_TMP_BUFFER); if (! dhKey) { ret = MEMORY_E; goto exit; @@ -7630,7 +7685,9 @@ void bench_ecc(int useDeviceID, int curveId) void bench_eccEncrypt(int curveId) { #define BENCH_ECCENCRYPT_MSG_SIZE 48 -#define BENCH_ECCENCRYPT_OUT_SIZE (BENCH_ECCENCRYPT_MSG_SIZE + WC_SHA256_DIGEST_SIZE + (MAX_ECC_BITS+3)/4 + 2) +#define BENCH_ECCENCRYPT_OUT_SIZE (BENCH_ECCENCRYPT_MSG_SIZE + \ + WC_SHA256_DIGEST_SIZE + \ + (MAX_ECC_BITS+3)/4 + 2) word32 outSz = BENCH_ECCENCRYPT_OUT_SIZE; #ifdef WOLFSSL_SMALL_STACK ecc_key *userA = NULL, *userB = NULL; @@ -9117,7 +9174,8 @@ void bench_sphincsKeySign(byte level, byte optim) if (stime_utime_ratio > .1) printf("%swarning, " "excessive system time ratio for %s%s (" FLT_FMT_PREC "%%).\n", - err_prefix, desc, desc_extra, FLT_FMT_PREC_ARGS(3, stime_utime_ratio * 100.0)); + err_prefix, desc, desc_extra, + FLT_FMT_PREC_ARGS(3, stime_utime_ratio * 100.0)); } #elif defined(WOLFSSL_LINUXKM) diff --git a/wolfcrypt/benchmark/benchmark.h b/wolfcrypt/benchmark/benchmark.h index a42b133de20..f119fc969ae 100644 --- a/wolfcrypt/benchmark/benchmark.h +++ b/wolfcrypt/benchmark/benchmark.h @@ -81,7 +81,7 @@ void bench_sha3_384(int useDeviceID); void bench_sha3_512(int useDeviceID); void bench_shake128(int useDeviceID); void bench_shake256(int useDeviceID); -int bench_ripemd(void); +void bench_ripemd(void); void bench_cmac(int useDeviceID); void bench_scrypt(void); void bench_hmac_md5(int useDeviceID); diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index d1a7a00f77d..51e1c416fde 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -3131,7 +3131,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( if (haveAESNI) { #ifdef WOLFSSL_LINUXKM /* runtime alignment check */ - if ((unsigned long)&aes->key & 0xf) { + if ((wc_ptr_t)&aes->key & (wc_ptr_t)0xf) { return BAD_ALIGN_E; } #endif From 72776e2cccbad53b08ed6bade77cbcb62a68eb5b Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 15 May 2023 15:49:44 -0700 Subject: [PATCH 300/391] add tls extension sanity check --- src/tls.c | 3 +++ src/tls13.c | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/src/tls.c b/src/tls.c index 6853ab90d56..bf7e49f4d58 100644 --- a/src/tls.c +++ b/src/tls.c @@ -8828,6 +8828,9 @@ int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length, if (!WOLFSSL_NAMED_GROUP_IS_PQC(group)) #endif ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions); + + if (ret == 0) + ssl->session->namedGroup = ssl->namedGroup = group; } else { /* Not a message type that is allowed to have this extension. */ diff --git a/src/tls13.c b/src/tls13.c index a173d60bff3..7deac91e84a 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -5241,8 +5241,18 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif + /* sanity check on PSK / KSE */ + if ( + #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) + ssl->options.pskNegotiated == 0 && + #endif + ssl->session->namedGroup == 0) { + return EXT_MISSING; + } + ssl->keys.encryptionOn = 1; ssl->options.serverState = SERVER_HELLO_COMPLETE; + } else { ssl->options.tls1_3 = 1; From 2247f763e2dfc5ba1fc68fc4d096c5f44230c2ee Mon Sep 17 00:00:00 2001 From: John Safranek Date: Thu, 18 May 2023 10:51:04 -0700 Subject: [PATCH 301/391] Configure Typo 1. The description text for the brainpool enable option in configure was using a shell variable that ended up in the output. Switched to the description pattern used in other options. --- configure.ac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index 699dd55d30f..5d2ba34d7d7 100644 --- a/configure.ac +++ b/configure.ac @@ -3234,7 +3234,7 @@ else fi AC_ARG_ENABLE([brainpool], - [AS_HELP_STRING([--enable-brainpool],[Enable Brainpool ECC curves (default: ${BRAINPOOL_DEFAULT})])], + [AS_HELP_STRING([--enable-brainpool],[Enable Brainpool ECC curves (default: enabled with ECC custom curves)])], [ ENABLED_BRAINPOOL=$enableval ], [ ENABLED_BRAINPOOL="$BRAINPOOL_DEFAULT" ] ) From 2f5745c30db2a224aed4010f9e2eedcba5d3ff50 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 19 May 2023 12:17:41 +1000 Subject: [PATCH 302/391] scan-build fixes sp_mulmod - scan-build getting confused with size of result - don't check result size as checked already - split out implementation of sp_mulmod from check StoreEccKey - ensure pubKey is not NULL even though all uses will not be GetCertKey - ensure source is not NULL - cert->source may be NULL in incorrect usages of APIs --- wolfcrypt/src/asn.c | 15 ++++++++++ wolfcrypt/src/sp_int.c | 62 ++++++++++++++++++++++++++++-------------- 2 files changed, 57 insertions(+), 20 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index b9398462a0a..67f91768cc7 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -11451,6 +11451,7 @@ enum { * @param [in] pubKey Buffer holding encoded public key. * @param [in] pubKeyLen Length of encoded public key in bytes. * @return 0 on success. + * @return BAD_FUNC_ARG when pubKey is NULL. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or * is invalid. * @return BUFFER_E when data in buffer is too small. @@ -11470,6 +11471,10 @@ static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx, byte tag; int length; + if (pubKey == NULL) { + return BAD_FUNC_ARG; + } + localIdx = *srcIdx; if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0) return ASN_PARSE_E; @@ -11527,6 +11532,11 @@ static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx, DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length); byte* publicKey; + /* Validate parameters. */ + if (pubKey == NULL) { + ret = BAD_FUNC_ARG; + } + /* Clear dynamic data and check OID is a curve. */ CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap); if (ret == 0) { @@ -11695,6 +11705,11 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, int ret = 0; int length; + /* Validate paramaters. */ + if (source == NULL) { + return ASN_PARSE_E; + } + #ifndef WOLFSSL_ASN_TEMPLATE if (GetSequence(source, &srcIdx, &length, maxIdx) < 0) #else diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index df16fa6eb92..58f853046d8 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -11696,7 +11696,7 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) * @return MP_OKAY on success. * @return MP_MEM when dynamic memory allocation fails. */ -static int _sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, +static int _sp_mulmod_tmp(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) { int err = MP_OKAY; @@ -11722,6 +11722,39 @@ static int _sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, return err; } +/* Multiply a by b mod m and store in r: r = (a * b) mod m + * + * @param [in] a SP integer to multiply. + * @param [in] b SP integer to multiply. + * @param [in] m SP integer that is the modulus. + * @param [out] r SP integer result. + * + * @return MP_OKAY on success. + * @return MP_MEM when dynamic memory allocation fails. + */ +static int _sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, + sp_int* r) +{ + int err = MP_OKAY; + + /* Use r as intermediate result if not same as pointer m which is needed + * after first intermediate result. + */ + if (r != m) { + /* Multiply and reduce. */ + err = sp_mul(a, b, r); + if (err == MP_OKAY) { + err = sp_mod(r, m, r); + } + } + else { + /* Do operation using temporary. */ + _sp_mulmod_tmp(a, b, m, r); + } + + return err; +} + /* Multiply a by b mod m and store in r: r = (a * b) mod m * * @param [in] a SP integer to multiply. @@ -11755,19 +11788,8 @@ int sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) } #endif - /* Use r as intermediate result if not same as pointer m which is needed - * after first intermediate result. - */ - if ((err == MP_OKAY) && (r != m)) { - /* Multiply and reduce. */ - err = sp_mul(a, b, r); - if (err == MP_OKAY) { - err = sp_mod(r, m, r); - } - } - else if (err == MP_OKAY) { - /* Do operation using temporary. */ - _sp_mulmod(a, b, m, r); + if (err == MP_OKAY) { + err = _sp_mulmod(a, b, m, r); } #if 0 @@ -12562,7 +12584,7 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, /* 4.4 s = s | y */ s |= y; /* 4.5. t[j] = t[j] * b */ - err = sp_mulmod(t[j], b, m, t[j]); + err = _sp_mulmod(t[j], b, m, t[j]); } #else /* 4.1. t[s] = t[s] ^ 2 */ @@ -12585,7 +12607,7 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, _sp_copy((sp_int*)(((size_t)t[0] & sp_off_on_addr[j^1]) + ((size_t)t[1] & sp_off_on_addr[j ])), t[2]); - err = sp_mulmod(t[2], b, m, t[2]); + err = _sp_mulmod(t[2], b, m, t[2]); _sp_copy(t[2], (sp_int*)(((size_t)t[0] & sp_off_on_addr[j^1]) + ((size_t)t[1] & sp_off_on_addr[j ]))); @@ -12682,7 +12704,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, */ err = sp_mont_norm(t[1], m); if (err == MP_OKAY) { - err = sp_mulmod(t[0], t[1], m, t[0]); + err = _sp_mulmod(t[0], t[1], m, t[0]); } if (err == MP_OKAY) { /* 4. t[1] = t[0] @@ -12860,7 +12882,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, err = sp_mont_norm(t[0], m); if (err == MP_OKAY) { /* 3. t[1] = ToMont(t[1]) */ - err = sp_mulmod(t[1], t[0], m, t[1]); + err = _sp_mulmod(t[1], t[0], m, t[1]); } /* 4. For i in 2..(2 ^ w) - 1 */ @@ -13556,7 +13578,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, err = sp_mont_norm(t[0], m); if (err == MP_OKAY) { /* 2. Convert base to Montgomery form. */ - err = sp_mulmod(bm, t[0], m, bm); + err = _sp_mulmod(bm, t[0], m, bm); } if (err == MP_OKAY) { /* Copy Montgomery form of base into first element of table. */ @@ -13807,7 +13829,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, err = sp_mont_norm(t[1], m); if (err == MP_OKAY) { /* 1. Convert base to Montgomery form. */ - err = sp_mulmod(t[0], t[1], m, t[0]); + err = _sp_mulmod(t[0], t[1], m, t[0]); } if (err == MP_OKAY) { /* 2. Result starts as Montgomery form of base (assuming e > 0). */ From f11ac9dcef797be47cf6b9b939514dd3bc220b7d Mon Sep 17 00:00:00 2001 From: John Bland <106998124+jpbland1@users.noreply.github.com> Date: Fri, 19 May 2023 12:12:44 -0400 Subject: [PATCH 303/391] Fix for FIPS ECC integrity check with crypto callback set (#6425) Skip ECC private key check when the TPM is used to generate the key, since it doesn't release the private part. this option needs to be used with a FIPS approved TPM for the end result to be FIPS approved --- configure.ac | 1 - wolfcrypt/src/ecc.c | 7 ++++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index 5d2ba34d7d7..fa65867962b 100644 --- a/configure.ac +++ b/configure.ac @@ -434,7 +434,6 @@ AS_CASE([$FIPS_VERSION], ] ) - # For reproducible build, gate out from the build anything that might # introduce semantically frivolous jitter, maximizing chance of # identical object files. diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index dca2d69b97d..9018105cbc5 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -5676,7 +5676,12 @@ int wc_ecc_make_key_ex2(WC_RNG* rng, int keysize, ecc_key* key, int curve_id, if (err == MP_OKAY) { err = _ecc_validate_public_key(key, 0, 0); } - if (err == MP_OKAY) { + if (err == MP_OKAY +#if defined(WOLF_CRYPTO_CB) + /* even if WOLF_CRYPTO_CB we generate the key if the devId is invalid */ + && key->devId == INVALID_DEVID +#endif + ) { err = _ecc_pairwise_consistency_test(key, rng); } #endif From 1578c3a8dbdf10c5d9432a04cc10ea7a1662c108 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 19 May 2023 09:15:16 +1000 Subject: [PATCH 304/391] Coverity scan fixes DecodeRsaPssParams() assumed params is never NULL. Should never be called with NULL but check saves a NULL dereference. PrintObjectIdText() didn't check return of call to GetObjectId. 'oid' will retain -1 value on error and work as normal on error return. Cleaner to check for ASN_PARSE_E and handle - other error, ASN_UNKNOWN_OID_E, is OK for printing. --- wolfcrypt/src/asn.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 67f91768cc7..192ab09aeaa 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -6146,6 +6146,7 @@ enum { * @param [out] hash Hash algorithm to use on message. * @param [out] mgf MGF algorithm to use with PSS padding. * @param [out] saltLen Length of salt in PSS padding. + * @return BAD_FUNC_ARG when the params is NULL. * @return ASN_PARSE_E when the decoding fails. * @return 0 on success. */ @@ -6160,7 +6161,10 @@ static int DecodeRsaPssParams(const byte* params, word32 sz, byte tag; int length; - if (GetSequence_ex(params, &idx, &len, sz, 1) < 0) { + if (params == NULL) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) { ret = ASN_PARSE_E; } if (ret == 0) { @@ -6252,6 +6256,10 @@ static int DecodeRsaPssParams(const byte* params, word32 sz, int ret = 0; word16 sLen = 20; + if (params == NULL) { + ret = BAD_FUNC_ARG; + } + CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL); if (ret == 0) { word32 inOutIdx = 0; @@ -37243,8 +37251,11 @@ static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts) int known = 1; /* Get the OID value for the OBJECT_ID. */ - GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType, - asn1->item.len + 2); + if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType, + asn1->item.len + 2) == ASN_PARSE_E) { + known = 0; + } + else #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) /* Lookup NID for OID value. */ if ((nid = oid2nid(oid, oidIgnoreType)) != -1) { From d1aba6f8caa25cc408406fe665bf98467a2a33b4 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Wed, 12 Apr 2023 12:14:51 +0000 Subject: [PATCH 305/391] dtls13: support Authentication and Integrity-Only Cipher Suites See RFC 9150. To enable the feature use HAVE_NULL_CIPHER compilation flag. --- src/dtls13.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/dtls13.c b/src/dtls13.c index 6149031f5d5..2e0f68ad6a8 100644 --- a/src/dtls13.c +++ b/src/dtls13.c @@ -301,6 +301,12 @@ static int Dtls13EncryptDecryptRecordNumber(WOLFSSL* ssl, byte* seq, byte mask[DTLS13_RN_MASK_SIZE]; int ret; +#ifdef HAVE_NULL_CIPHER + /* Do not encrypt record numbers with null cipher. See RFC 9150 Sec 9 */ + if (ssl->specs.bulk_cipher_algorithm == wolfssl_cipher_null) + return 0; +#endif /*HAVE_NULL_CIPHER */ + ret = Dtls13GetRnMask(ssl, ciphertext, mask, dir); if (ret != 0) return ret; @@ -2266,6 +2272,15 @@ int Dtls13SetRecordNumberKeys(WOLFSSL* ssl, enum encrypt_side side) } #endif /* HAVE_CHACHA */ +#ifdef HAVE_NULL_CIPHER + if (ssl->specs.bulk_cipher_algorithm == wolfssl_cipher_null) { +#ifdef WOLFSSL_DEBUG_TLS + WOLFSSL_MSG("Skipping Record Number key provisioning with null cipher"); +#endif /* WOLFSSL_DEBUG_TLS */ + return 0; + } +#endif /* HAVE_NULL_CIPHER */ + return NOT_COMPILED_IN; } From 4279b52091531e6eb8ac62717990b495a61333d1 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Thu, 13 Apr 2023 10:00:09 +0000 Subject: [PATCH 306/391] tests: add dtls13 null cipher test --- tests/api.c | 69 ++++++++++++++++++++++++++++++++++++++++++ tests/test-dtls13.conf | 20 ++++++++++++ 2 files changed, 89 insertions(+) diff --git a/tests/api.c b/tests/api.c index d9958a5a324..45095191277 100644 --- a/tests/api.c +++ b/tests/api.c @@ -65849,6 +65849,74 @@ static int test_dtls13_bad_epoch_ch(void) #endif +#if defined(HAVE_NULL_CIPHER) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ + defined(WOLFSSL_DTLS13) +static byte* test_find_string(const char *string, + byte *buf, int buf_size) +{ + int string_size, i; + + string_size = XSTRLEN(string); + for (i = 0; i < buf_size - string_size - 1; i++) { + if (XSTRCMP((char*)&buf[i], string) == 0) + return &buf[i]; + } + return NULL; +} + +static int test_wolfSSL_dtls13_null_cipher(void) +{ + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + const char *test_str = "test"; + int ret, test_str_size; + byte buf[255], *ptr; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + test_ctx.c_ciphers = test_ctx.s_ciphers = "TLS13-SHA256-SHA256"; + ret = test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfDTLSv1_3_client_method, wolfDTLSv1_3_server_method); + if (ret != 0) + return TEST_FAIL; + ret = test_memio_do_handshake(ssl_c, ssl_s, 10, NULL); + if (ret != 0) + return TEST_FAIL; + test_str_size = XSTRLEN("test") + 1; + ret = wolfSSL_write(ssl_c, test_str, test_str_size); + if (ret != test_str_size) + return TEST_FAIL; + ret = wolfSSL_read(ssl_s, buf, sizeof(buf)); + if (ret != test_str_size || XSTRCMP((char*)buf, test_str) != 0) + return TEST_FAIL; + + ret = wolfSSL_write(ssl_c, test_str, test_str_size); + if (ret != test_str_size) + return TEST_FAIL; + + /* check that the packet was sent cleartext */ + ptr = test_find_string(test_str, test_ctx.s_buff, test_ctx.s_len); + if (ptr == NULL) + return TEST_FAIL; + /* modify the message */ + *ptr = 'H'; + /* bad messages should be ignored in DTLS */ + ret = wolfSSL_read(ssl_s, buf, sizeof(buf)); + if (ret != -1 || ssl_s->error != WANT_READ) + return TEST_FAIL; + + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); + return TEST_SUCCESS; +} +#else +static int test_wolfSSL_dtls13_null_cipher(void) +{ + return TEST_SKIPPED; +} +#endif /*----------------------------------------------------------------------------* | Main *----------------------------------------------------------------------------*/ @@ -66886,6 +66954,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_harden_no_secure_renegotiation), TEST_DECL(test_override_alt_cert_chain), TEST_DECL(test_dtls13_bad_epoch_ch), + TEST_DECL(test_wolfSSL_dtls13_null_cipher), /* If at some point a stub get implemented this test should fail indicating * a need to implement a new test case */ diff --git a/tests/test-dtls13.conf b/tests/test-dtls13.conf index 0186b9a7fe2..57724e68c2e 100644 --- a/tests/test-dtls13.conf +++ b/tests/test-dtls13.conf @@ -270,3 +270,23 @@ -u -v 4 -l TLS_AES_128_GCM_SHA256 + +# server DTLSv1.3 Integrity-only SHA256 +-u +-v 4 +-l TLS13-SHA256-SHA256 + +# client DTLSv1.3 Integrity-only SHA256 +-u +-v 4 +-l TLS13-SHA256-SHA256 + +# server DTSv1.3 Integrity-only SHA384 +-u +-v 4 +-l TLS13-SHA384-SHA384 + +# client DTLSv1.3 Integrity-only SHA384 +-u +-v 4 +-l TLS13-SHA384-SHA384 From fa45aeadbccfcbfaef2ca3d1cd672c2d5f22f121 Mon Sep 17 00:00:00 2001 From: jordan Date: Thu, 4 May 2023 22:21:55 -0500 Subject: [PATCH 307/391] Fix session ticket leak in wolfSSL_Cleanup --- src/ssl.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 014154949ac..495ae2c2f3b 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -14433,12 +14433,9 @@ int wolfSSL_Cleanup(void) { int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */ int release = 0; -#if !defined(NO_SESSION_CACHE) && (defined(ENABLE_SESSION_CACHE_ROW_LOCK) || \ - defined(SESSION_CACHE_DYNAMIC_MEM)) +#if !defined(NO_SESSION_CACHE) int i; - #ifdef SESSION_CACHE_DYNAMIC_MEM int j; - #endif #endif WOLFSSL_ENTER("wolfSSL_Cleanup"); @@ -14483,17 +14480,20 @@ int wolfSSL_Cleanup(void) } session_lock_valid = 0; #endif - #ifdef SESSION_CACHE_DYNAMIC_MEM for (i = 0; i < SESSION_ROWS; i++) { for (j = 0; j < SESSIONS_PER_ROW; j++) { + #ifdef SESSION_CACHE_DYNAMIC_MEM if (SessionCache[i].Sessions[j]) { + EvictSessionFromCache(SessionCache[i].Sessions[j]); XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap, DYNAMIC_TYPE_SESSION); SessionCache[i].Sessions[j] = NULL; } + #else + EvictSessionFromCache(&SessionCache[i].Sessions[j]); + #endif } } - #endif #ifndef NO_CLIENT_CACHE if ((clisession_mutex_valid == 1) && (wc_FreeMutex(&clisession_mutex) != 0)) { From c3d97ca9be4bb993d533f529179ac5a93d5d2516 Mon Sep 17 00:00:00 2001 From: jordan Date: Wed, 17 May 2023 16:25:27 -0400 Subject: [PATCH 308/391] Don't orphan ticBuff pointer in wolfSSL_DupSessionEx --- src/ssl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 495ae2c2f3b..dc006de2863 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -21534,8 +21534,8 @@ static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, * the static buffer. */ if (ticBuff != NULL) { if (ticLenAlloc >= input->ticketLen) { - output->ticket = output->staticTicket; - output->ticketLenAlloc = 0; + output->ticket = ticBuff; + output->ticketLenAlloc = ticLenAlloc; } else { WOLFSSL_MSG("ticket dynamic buffer too small but we are " From c9c9fbde4f8443feb3ea2e2ca49523da8e49d81d Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 17 May 2023 16:22:55 +0200 Subject: [PATCH 309/391] Implement atomic operations interface --- wolfcrypt/src/wc_port.c | 44 ++++++++++++++++++++++++++++++++++++- wolfssl/wolfcrypt/wc_port.h | 42 ++++++++++++++++++++++++++++------- 2 files changed, 77 insertions(+), 9 deletions(-) diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index ff1a817b0e0..df729cc17e3 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -1155,7 +1155,49 @@ int wc_strncasecmp(const char *s1, const char *s2, size_t n) } #endif /* USE_WOLF_STRNCASECMP */ -#if !defined(SINGLE_THREADED) && !defined(HAVE_C___ATOMIC) +#ifdef WOLFSSL_ATOMIC_OPS + +#ifdef HAVE_C___ATOMIC +/* Atomic ops using standard C lib */ +#ifdef __cplusplus +/* C++ using direct calls to compiler built-in functions */ +void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i) +{ + *c = i; +} + +int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i) +{ + return __atomic_fetch_add(c, i, __ATOMIC_RELAXED); +} + +int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i) +{ + return __atomic_fetch_sub(c, i, __ATOMIC_RELAXED); +} +#else +/* Default C Implementation */ +WC_INLINE void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i) +{ + atomic_init(c, i); +} + +WC_INLINE int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i) +{ + return atomic_fetch_add_explicit(c, i, memory_order_relaxed); +} + +WC_INLINE int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i) +{ + return atomic_fetch_sub_explicit(c, i, memory_order_relaxed); +} +#endif /* __cplusplus */ + +#endif /* HAVE_C___ATOMIC */ + +#endif /* WOLFSSL_ATOMIC_OPS */ + +#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_ATOMIC_OPS) void wolfSSL_RefInit(wolfSSL_Ref* ref, int* err) { int ret = wc_InitMutex(&ref->mutex); diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index c44ce4a2e5e..635ed59fd5e 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -298,12 +298,39 @@ typedef wolfSSL_Mutex wolfSSL_RwLock; #endif +#ifdef HAVE_C___ATOMIC +#ifdef __cplusplus +#if defined(__GNUC__) && defined(__ATOMIC_RELAXED) + /* C++ using direct calls to compiler built-in functions */ + typedef volatile int wolfSSL_Atomic_Int; + #define WOLFSSL_ATOMIC_OPS +#endif +#else + /* Default C Implementation */ + #include + typedef atomic_int wolfSSL_Atomic_Int; + #define WOLFSSL_ATOMIC_OPS +#endif +#endif + +#ifdef WOLFSSL_ATOMIC_OPS + WOLFSSL_LOCAL void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i); + /* Fetch* functions return the value of the counter immediately preceding + * the effects of the function. */ + WOLFSSL_LOCAL int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i); + WOLFSSL_LOCAL int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i); +#endif + /* Reference counting. */ typedef struct wolfSSL_Ref { -#if !defined(SINGLE_THREADED) && !defined(HAVE_C___ATOMIC) +#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_ATOMIC_OPS) wolfSSL_Mutex mutex; #endif +#ifdef WOLFSSL_ATOMIC_OPS + wolfSSL_Atomic_Int count; +#else int count; +#endif } wolfSSL_Ref; #ifdef SINGLE_THREADED @@ -326,25 +353,24 @@ typedef struct wolfSSL_Ref { *(err) = 0; \ } while(0) -#elif defined(HAVE_C___ATOMIC) +#elif defined(WOLFSSL_ATOMIC_OPS) #define wolfSSL_RefInit(ref, err) \ do { \ - (ref)->count = 1; \ + wolfSSL_Atomic_Int_Init(&(ref)->count, 1); \ *(err) = 0; \ } while(0) #define wolfSSL_RefFree(ref) #define wolfSSL_RefInc(ref, err) \ do { \ - __atomic_fetch_add(&(ref)->count, 1, \ - __ATOMIC_RELAXED); \ + (void)wolfSSL_Atomic_Int_FetchAdd(&(ref)->count, 1); \ *(err) = 0; \ } while(0) #define wolfSSL_RefDec(ref, isZero, err) \ do { \ - __atomic_fetch_sub(&(ref)->count, 1, \ - __ATOMIC_RELAXED); \ - *(isZero) = ((ref)->count == 0); \ + int __prev = wolfSSL_Atomic_Int_FetchSub(&(ref)->count, 1); \ + /* __prev holds the value of count before subtracting 1 */ \ + *(isZero) = (__prev == 1); \ *(err) = 0; \ } while(0) From acd72a41958f7253a2a2892ebad8d750a5e26abd Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Thu, 18 May 2023 12:06:54 +0200 Subject: [PATCH 310/391] Add MSVC atomics --- wolfcrypt/src/wc_port.c | 26 ++++++++++++++++++++++---- wolfssl/wolfcrypt/wc_port.h | 7 +++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index df729cc17e3..1d0e935d28f 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -1177,23 +1177,41 @@ int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i) } #else /* Default C Implementation */ -WC_INLINE void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i) +void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i) { atomic_init(c, i); } -WC_INLINE int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i) +int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i) { return atomic_fetch_add_explicit(c, i, memory_order_relaxed); } -WC_INLINE int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i) +int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i) { return atomic_fetch_sub_explicit(c, i, memory_order_relaxed); } #endif /* __cplusplus */ -#endif /* HAVE_C___ATOMIC */ +#elif defined(_MSC_VER) + +/* Default C Implementation */ +void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i) +{ + *c = i; +} + +int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i) +{ + return (int)_InterlockedExchangeAdd(c, (long)i); +} + +int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i) +{ + return (int)_InterlockedExchangeAdd(c, (long)-i); +} + +#endif #endif /* WOLFSSL_ATOMIC_OPS */ diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 635ed59fd5e..1737c3f63ed 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -298,6 +298,7 @@ typedef wolfSSL_Mutex wolfSSL_RwLock; #endif +#ifndef WOLFSSL_NO_ATOMICS #ifdef HAVE_C___ATOMIC #ifdef __cplusplus #if defined(__GNUC__) && defined(__ATOMIC_RELAXED) @@ -311,7 +312,13 @@ typedef atomic_int wolfSSL_Atomic_Int; #define WOLFSSL_ATOMIC_OPS #endif +#elif defined(_MSC_VER) + /* Use MSVC compiler intrinsics for atomic ops */ + #include + typedef volatile long wolfSSL_Atomic_Int; + #define WOLFSSL_ATOMIC_OPS #endif +#endif /* WOLFSSL_NO_ATOMICS */ #ifdef WOLFSSL_ATOMIC_OPS WOLFSSL_LOCAL void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i); From f17c268e0157c7514f13bdbc76e2414e37f051a1 Mon Sep 17 00:00:00 2001 From: Chris Conlon Date: Thu, 18 May 2023 14:45:55 -0600 Subject: [PATCH 311/391] fix PKCS#7 build when using NO_PKCS7_STREAM --- tests/api.c | 2 +- wolfcrypt/src/pkcs7.c | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/tests/api.c b/tests/api.c index 45095191277..013ae38c512 100644 --- a/tests/api.c +++ b/tests/api.c @@ -28961,7 +28961,7 @@ static int test_wc_PKCS7_EncodeSignedData_ex(void) outputHead, outputHeadSz, outputFoot, 0), WC_PKCS7_WANT_READ_E); #else AssertIntEQ(wc_PKCS7_VerifySignedData_ex(pkcs7, hashBuf, hashSz, - outputHead, outputHeadSz, outputFoot, 0), ASN_PARSE_E); + outputHead, outputHeadSz, outputFoot, 0), BUFFER_E); #endif wc_PKCS7_Free(pkcs7); diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index b5ec1d82f0e..c301cf7eba9 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -4790,6 +4790,9 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, pkiMsg2 = pkiMsg; pkiMsg2Sz = pkiMsgSz; + + /* reset ret */ + ret = 0; } #ifndef NO_PKCS7_STREAM @@ -4963,7 +4966,6 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, ret = 0; /* reset ret state on degenerate case */ } - #ifndef NO_PKCS7_STREAM /* save content */ if (detached == 1) { /* if detached, use content from user in pkcs7 struct */ @@ -4971,6 +4973,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, contentSz = pkcs7->contentSz; } + #ifndef NO_PKCS7_STREAM if (content != NULL) { XFREE(pkcs7->stream->content, pkcs7->heap, DYNAMIC_TYPE_PKCS7); pkcs7->stream->content = (byte*)XMALLOC(contentSz, pkcs7->heap, @@ -4986,6 +4989,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, } #endif /* !NO_PKCS7_STREAM */ + /* Certificates begin "footer" section (ie pkiMsg2) if being used */ /* Get the implicit[0] set of certificates */ if (ret == 0 && idx >= pkiMsg2Sz) ret = BUFFER_E; @@ -5270,6 +5274,9 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, break; } stateIdx = idx; + #else + /* if not streaming, maxIdx is just pkiMsg2Sz */ + maxIdx = pkiMsg2Sz; #endif /* set contentType and size after init of PKCS7 structure */ @@ -11619,7 +11626,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, { #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) int recipFound = 0; - int ret = 0, length; + int ret = 0, length = 0; word32 idx = 0; #ifndef NO_PKCS7_STREAM word32 tmpIdx = 0; @@ -12019,8 +12026,6 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, length = pkcs7->stream->expected; encodedAttribs = pkcs7->stream->aad; - #else - length = 0; #endif /* save pointer and length */ @@ -12541,7 +12546,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, #ifndef NO_PKCS7_STREAM word32 tmpIdx = 0; #endif - word32 contentType = 0, encOID; + word32 contentType = 0, encOID = 0; int expBlockSz = 0; byte tmpIvBuf[MAX_CONTENT_IV_SIZE]; @@ -12797,8 +12802,6 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, encryptedContentSz = pkcs7->stream->varThree; version = pkcs7->stream->vers; tmpIv = pkcs7->stream->tmpIv; -#else - encOID = 0; #endif if (ret == 0 && (encryptedContent = (byte*)XMALLOC( encryptedContentSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7)) == NULL) { From c2739324cd55917270264ecfebb8903b95318b4c Mon Sep 17 00:00:00 2001 From: John Bland Date: Thu, 18 May 2023 20:31:05 -0400 Subject: [PATCH 312/391] add check to sp_invmod_mont_ct to make sure the result integer can hold the range of the modulus --- wolfcrypt/src/sp_int.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 58f853046d8..8e69911f953 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -12467,6 +12467,10 @@ int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, else if (m->used * 2 >= SP_INT_DIGITS) { err = MP_VAL; } + /* check that r can hold the range of the modulus result */ + else if (m->used > r->size) { + err = MP_VAL; + } /* 0 != n*m + 1 (+ve m), r*a mod 0 is always 0 (never 1) */ if ((err == MP_OKAY) && (sp_iszero(a) || sp_iszero(m) || From 22261b7ca872a0b06cb61a820c6ccaec2de260c5 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Sun, 21 May 2023 10:51:24 -0500 Subject: [PATCH 313/391] wolfssl/test.h: in wolfsentry_setup(), add lock-unlock wrap before wolfsentry_route_get_main_table() (enforced by wolfSentry 1.3+, and was always required for thread safety). --- wolfssl/test.h | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/wolfssl/test.h b/wolfssl/test.h index b39b7d21a61..27e7d833eec 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -1684,6 +1684,16 @@ static int wolfsentry_setup( { struct wolfsentry_route_table *table; +#ifdef WOLFSENTRY_THREADSAFE + ret = WOLFSENTRY_SHARED_EX(*_wolfsentry); + if (ret < 0) { + fprintf(stderr, "wolfsentry shared lock op failed: " + WOLFSENTRY_ERROR_FMT ".\n", + WOLFSENTRY_ERROR_FMT_ARGS(ret)); + return ret; + } +#endif + if ((ret = wolfsentry_route_get_main_table( WOLFSENTRY_CONTEXT_ARGS_OUT_EX(*_wolfsentry), &table)) < 0) @@ -1691,6 +1701,11 @@ static int wolfsentry_setup( fprintf(stderr, "wolfsentry_route_get_main_table() returned " WOLFSENTRY_ERROR_FMT "\n", WOLFSENTRY_ERROR_FMT_ARGS(ret)); +#ifdef WOLFSENTRY_THREADSAFE + WOLFSENTRY_WARN_ON_FAILURE( + wolfsentry_context_unlock( + WOLFSENTRY_CONTEXT_ARGS_OUT_EX(*_wolfsentry))); +#endif return ret; } @@ -1708,6 +1723,11 @@ static int wolfsentry_setup( "wolfsentry_route_table_default_policy_set() returned " WOLFSENTRY_ERROR_FMT "\n", WOLFSENTRY_ERROR_FMT_ARGS(ret)); +#ifdef WOLFSENTRY_THREADSAFE + WOLFSENTRY_WARN_ON_FAILURE( + wolfsentry_context_unlock( + WOLFSENTRY_CONTEXT_ARGS_OUT_EX(*_wolfsentry))); +#endif return ret; } @@ -1742,6 +1762,11 @@ static int wolfsentry_setup( fprintf(stderr, "wolfsentry_route_insert() returned " WOLFSENTRY_ERROR_FMT "\n", WOLFSENTRY_ERROR_FMT_ARGS(ret)); +#ifdef WOLFSENTRY_THREADSAFE + WOLFSENTRY_WARN_ON_FAILURE( + wolfsentry_context_unlock( + WOLFSENTRY_CONTEXT_ARGS_OUT_EX(*_wolfsentry))); +#endif return ret; } } else if (WOLFSENTRY_MASKIN_BITS(route_flags, WOLFSENTRY_ROUTE_FLAG_DIRECTION_IN)) { @@ -1757,6 +1782,11 @@ static int wolfsentry_setup( "wolfsentry_route_table_default_policy_set() returned " WOLFSENTRY_ERROR_FMT "\n", WOLFSENTRY_ERROR_FMT_ARGS(ret)); +#ifdef WOLFSENTRY_THREADSAFE + WOLFSENTRY_WARN_ON_FAILURE( + wolfsentry_context_unlock( + WOLFSENTRY_CONTEXT_ARGS_OUT_EX(*_wolfsentry))); +#endif return ret; } @@ -1791,9 +1821,19 @@ static int wolfsentry_setup( fprintf(stderr, "wolfsentry_route_insert() returned " WOLFSENTRY_ERROR_FMT "\n", WOLFSENTRY_ERROR_FMT_ARGS(ret)); +#ifdef WOLFSENTRY_THREADSAFE + WOLFSENTRY_WARN_ON_FAILURE( + wolfsentry_context_unlock( + WOLFSENTRY_CONTEXT_ARGS_OUT_EX(*_wolfsentry))); +#endif return ret; } } +#ifdef WOLFSENTRY_THREADSAFE + WOLFSENTRY_WARN_ON_FAILURE( + wolfsentry_context_unlock( + WOLFSENTRY_CONTEXT_ARGS_OUT_EX(*_wolfsentry))); +#endif } #if defined(WOLFSENTRY_THREADSAFE) && defined(HAVE_WOLFSENTRY_API_0v8) From 4981a5592ba1ae699936a638bff8a09da266e19e Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 22 May 2023 16:57:07 +1000 Subject: [PATCH 314/391] Memory usage: reduce stack usage AES C impl: don't align to 32 bytes, align to 16 as buffer is 16 bytes long. SP int: Don't call _sp_mulmod but call sp_mul and _sp_div to do mod operation. For RSA, fewer calls for mod operation means less stack used at deepest point. --- wolfcrypt/src/aes.c | 14 +++++++------- wolfcrypt/src/sp_int.c | 36 ++++++++++++++++++++++++++---------- 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 51e1c416fde..e36d0f4f31a 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -6767,9 +6767,9 @@ WARN_UNUSED_RESULT int AES_GCM_encrypt_C( word32 partial = sz % AES_BLOCK_SIZE; const byte* p = in; byte* c = out; - ALIGN32 byte counter[AES_BLOCK_SIZE]; - ALIGN32 byte initialCounter[AES_BLOCK_SIZE]; - ALIGN32 byte scratch[AES_BLOCK_SIZE]; + ALIGN16 byte counter[AES_BLOCK_SIZE]; + ALIGN16 byte initialCounter[AES_BLOCK_SIZE]; + ALIGN16 byte scratch[AES_BLOCK_SIZE]; if (ivSz == GCM_NONCE_MID_SZ) { /* Counter is IV with bottom 4 bytes set to: 0x00,0x00,0x00,0x01. */ @@ -7289,10 +7289,10 @@ int WARN_UNUSED_RESULT AES_GCM_decrypt_C( word32 partial = sz % AES_BLOCK_SIZE; const byte* c = in; byte* p = out; - ALIGN32 byte counter[AES_BLOCK_SIZE]; - ALIGN32 byte scratch[AES_BLOCK_SIZE]; - ALIGN32 byte Tprime[AES_BLOCK_SIZE]; - ALIGN32 byte EKY0[AES_BLOCK_SIZE]; + ALIGN16 byte counter[AES_BLOCK_SIZE]; + ALIGN16 byte scratch[AES_BLOCK_SIZE]; + ALIGN16 byte Tprime[AES_BLOCK_SIZE]; + ALIGN16 byte EKY0[AES_BLOCK_SIZE]; sword32 res; if (ivSz == GCM_NONCE_MID_SZ) { diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 8e69911f953..b3342611f2a 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -12708,7 +12708,11 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, */ err = sp_mont_norm(t[1], m); if (err == MP_OKAY) { - err = _sp_mulmod(t[0], t[1], m, t[0]); + err = sp_mul(t[0], t[1], t[0]); + } + if (err == MP_OKAY) { + /* t[0] = t[0] mod m, temporary size has to be bigger than t[0]. */ + err = _sp_div(t[0], m, NULL, t[0], t[0]->used + 1); } if (err == MP_OKAY) { /* 4. t[1] = t[0] @@ -12886,7 +12890,11 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, err = sp_mont_norm(t[0], m); if (err == MP_OKAY) { /* 3. t[1] = ToMont(t[1]) */ - err = _sp_mulmod(t[1], t[0], m, t[1]); + err = sp_mul(t[1], t[0], t[1]); + } + if (err == MP_OKAY) { + /* t[1] = t[1] mod m, temporary size has to be bigger than t[1]. */ + err = _sp_div(t[1], m, NULL, t[1], t[1]->used + 1); } /* 4. For i in 2..(2 ^ w) - 1 */ @@ -13491,8 +13499,6 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, sp_int* r) { int i = 0; - int c = 0; - int y = 0; int bits; int winBits; int preCnt; @@ -13500,7 +13506,6 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, int done = 0; sp_int* tr = NULL; sp_int* bm = NULL; - sp_int_digit mask; /* Maximum winBits is 6 and preCnt is (1 << (winBits - 1)). */ #ifndef WOLFSSL_SP_NO_MALLOC DECL_DYN_SP_INT_ARRAY(t, m->used * 2 + 1, (1 << 5) + 2); @@ -13532,8 +13537,6 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, } /* Top bit of exponent fixed as 1 for pre-calculated window. */ preCnt = 1 << (winBits - 1); - /* Mask for calculating index into pre-computed table. */ - mask = (sp_int_digit)preCnt - 1; /* Allocate sp_ints for: * - pre-computation table @@ -13573,8 +13576,9 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, } if ((!done) && (err == MP_OKAY)) { + int y = 0; + int c = 0; sp_int_digit mp; - sp_int_digit n; /* Calculate Montgomery multiplier for reduction. */ _sp_mont_setup(m, &mp); @@ -13582,7 +13586,11 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, err = sp_mont_norm(t[0], m); if (err == MP_OKAY) { /* 2. Convert base to Montgomery form. */ - err = _sp_mulmod(bm, t[0], m, bm); + err = sp_mul(bm, t[0], bm); + } + if (err == MP_OKAY) { + /* bm = bm mod m, temporary size has to be bigger than bm->used. */ + err = _sp_div(bm, m, NULL, bm, bm->used + 1); } if (err == MP_OKAY) { /* Copy Montgomery form of base into first element of table. */ @@ -13608,6 +13616,10 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, * if less than windows bits in exponent, 1 in Montgomery form. */ if (err == MP_OKAY) { + sp_int_digit n; + /* Mask for calculating index into pre-computed table. */ + sp_int_digit mask = (sp_int_digit)preCnt - 1; + /* Find the top bit. */ i = (bits - 1) >> SP_WORD_SHIFT; n = e->dp[i--]; @@ -13833,7 +13845,11 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, err = sp_mont_norm(t[1], m); if (err == MP_OKAY) { /* 1. Convert base to Montgomery form. */ - err = _sp_mulmod(t[0], t[1], m, t[0]); + err = sp_mul(t[0], t[1], t[0]); + } + if (err == MP_OKAY) { + /* t[0] = t[0] mod m, temporary size has to be bigger than t[0]. */ + err = _sp_div(t[0], m, NULL, t[0], t[0]->used + 1); } if (err == MP_OKAY) { /* 2. Result starts as Montgomery form of base (assuming e > 0). */ From 65384a93e8f73d91dcc6fb4184ec37578a9f56d4 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Wed, 24 May 2023 12:14:02 -0400 Subject: [PATCH 315/391] Without HAVE_EXT_CACHE session dup is not compiled in --- tests/api.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/api.c b/tests/api.c index 013ae38c512..d9805bff474 100644 --- a/tests/api.c +++ b/tests/api.c @@ -62956,7 +62956,7 @@ static int test_wolfSSL_CRYPTO_get_ex_new_index(void) return res; } -#if defined(HAVE_EX_DATA) && \ +#if defined(HAVE_EX_DATA) && defined(HAVE_EXT_CACHE) && \ (defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ From 1b55d9b3256a90466922a730455712dedfaf1263 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 14 Feb 2023 12:46:47 +0000 Subject: [PATCH 316/391] tests: api: error out on read error in test_server_nofail --- tests/api.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/api.c b/tests/api.c index d9805bff474..7db1fac9667 100644 --- a/tests/api.c +++ b/tests/api.c @@ -5435,6 +5435,9 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_nofail(void* args) input[idx] = '\0'; fprintf(stderr, "Client message: %s\n", input); } + else if (idx < 0) { + goto done; + } if (wolfSSL_write(ssl, msg, sizeof(msg)) != sizeof(msg)) { /*err_sys("SSL_write failed");*/ From d7fc9db075cfcdaffb92975a7c0b11e223336b78 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 21 Feb 2023 13:34:14 +0000 Subject: [PATCH 317/391] tests: add test_wolfssl_client_server_no_fail(_ex) to set client cb --- tests/api.c | 15 ++++++++++----- wolfssl/test.h | 4 ++++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/tests/api.c b/tests/api.c index 7db1fac9667..211cba090d4 100644 --- a/tests/api.c +++ b/tests/api.c @@ -5687,8 +5687,6 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_loop(void* args) } #endif /* defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && !defined(WOLFSSL_TLS13) */ -typedef int (*cbType)(WOLFSSL_CTX *ctx, WOLFSSL *ssl); - static int test_client_nofail(void* args, cbType cb) { #if !defined(NO_WOLFSSL_CLIENT) @@ -5931,8 +5929,8 @@ static int test_client_nofail(void* args, cbType cb) return 0; } -void test_wolfSSL_client_server_nofail(callback_functions* client_cb, - callback_functions* server_cb) +void test_wolfSSL_client_server_nofail_ex(callback_functions* client_cb, + callback_functions* server_cb, cbType client_on_handshake) { func_args client_args; func_args server_args; @@ -5961,7 +5959,7 @@ void test_wolfSSL_client_server_nofail(callback_functions* client_cb, start_thread(test_server_nofail, &server_args, &serverThread); wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); + test_client_nofail(&client_args, client_on_handshake); join_thread(serverThread); client_cb->return_code = client_args.return_code; @@ -5974,6 +5972,13 @@ void test_wolfSSL_client_server_nofail(callback_functions* client_cb, #endif } +void test_wolfSSL_client_server_nofail(callback_functions* client_cb, + callback_functions* server_cb) +{ + test_wolfSSL_client_server_nofail_ex(client_cb, server_cb, NULL); +} + + #if defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && \ !defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_CLIENT) static void test_client_reuse_WOLFSSLobj(void* args, void *cb, void* server_args) diff --git a/wolfssl/test.h b/wolfssl/test.h index 27e7d833eec..5bd9aea8f8c 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -636,6 +636,10 @@ typedef THREAD_RETURN WOLFSSL_THREAD THREAD_FUNC(void*); void start_thread(THREAD_FUNC fun, func_args* args, THREAD_TYPE* thread); void join_thread(THREAD_TYPE thread); +typedef int (*cbType)(WOLFSSL_CTX *ctx, WOLFSSL *ssl); + +void test_wolfSSL_client_server_nofail_ex(callback_functions* client_cb, + callback_functions* server_cb, cbType client_on_handshake); void test_wolfSSL_client_server_nofail(callback_functions* client_cb, callback_functions* server_cb); From 360350e5d9a7461271691cfec723e66d2e941138 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 14 Feb 2023 14:03:37 +0000 Subject: [PATCH 318/391] wolfio: dtls: retry instead of returning WANT_READ on different peer If EmbedReceiveFrom() returns WANT_READ, a blocking socket will not know how to deal with the error. Retry the recvfrom instead adjusting the timeout. --- src/wolfio.c | 186 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 117 insertions(+), 69 deletions(-) diff --git a/src/wolfio.c b/src/wolfio.c index 8c475aea43d..a29223f81ec 100644 --- a/src/wolfio.c +++ b/src/wolfio.c @@ -51,6 +51,14 @@ Possible IO enable options: * HAVE_HTTP_CLIENT: Enables HTTP client API's default: off (unless HAVE_OCSP or HAVE_CRL_IO defined) * HAVE_IO_TIMEOUT: Enables support for connect timeout default: off + * + * DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER: This flag has effect only if + * ASN_NO_TIME is enabled. If enabled invalid peers messages are ignored + * indefinetely. If not enabled EmbedReceiveFrom will return timeout after + * DTLS_RECEIVEFROM_MAX_INVALID_PEER number of packets from invalid peers. When + * enabled, without a timer, EmbedReceivefrom can't check if the timeout is + * expired and it may never return under a continous flow of invalid packets. + * default: off */ @@ -59,6 +67,11 @@ Possible IO enable options: but they'll still need SetCallback xxx() at end of file */ +#if defined(NO_ASN_TIME) && !defined(DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER) \ + && !defined(DTLS_RECEIVEFROM_MAX_INVALID_PEER) +#define DTLS_RECEIVEFROM_MAX_INVALID_PEER 10 +#endif + #if defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT) /* Translates return codes returned from @@ -400,6 +413,11 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) SOCKADDR_S lclPeer; SOCKADDR_S* peer; XSOCKLENT peerSz = 0; +#ifndef NO_ASN_TIME + word32 start = 0; +#elif !defined(DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER) + word32 invalidPeerPackets = 0; +#endif WOLFSSL_ENTER("EmbedReceiveFrom"); @@ -438,10 +456,26 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) } #endif /* WOLFSSL_DTLS13 */ - if (!doDtlsTimeout) - dtls_timeout = 0; + do { + + if (!doDtlsTimeout) { + dtls_timeout = 0; + } + else { +#ifndef NO_ASN_TIME + if (start == 0) { + start = LowResTimer(); + } + else { + dtls_timeout -= LowResTimer() - start; + start = LowResTimer(); + if (dtls_timeout < 0 || dtls_timeout > DTLS_TIMEOUT_MAX) + return WOLFSSL_CBIO_ERR_TIMEOUT; + } +#endif + } - if (!wolfSSL_get_using_nonblock(ssl)) { + if (!wolfSSL_get_using_nonblock(ssl)) { #ifdef USE_WINDOWS_API DWORD timeout = dtls_timeout * 1000; #ifdef WOLFSSL_DTLS13 @@ -464,87 +498,101 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) #endif /* WOLFSSL_DTLS13 */ timeout.tv_sec = dtls_timeout; #endif - if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, - sizeof(timeout)) != 0) { + if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, + sizeof(timeout)) != 0) { WOLFSSL_MSG("setsockopt rcvtimeo failed"); + } } - } #ifndef NO_ASN_TIME - else if(IsSCR(ssl)) { - if (ssl->dtls_start_timeout && - LowResTimer() - ssl->dtls_start_timeout > (word32)dtls_timeout) { - ssl->dtls_start_timeout = 0; - return WOLFSSL_CBIO_ERR_TIMEOUT; - } - else if (!ssl->dtls_start_timeout) { - ssl->dtls_start_timeout = LowResTimer(); + else if (IsSCR(ssl)) { + if (ssl->dtls_start_timeout && + LowResTimer() - ssl->dtls_start_timeout > + (word32)dtls_timeout) { + ssl->dtls_start_timeout = 0; + return WOLFSSL_CBIO_ERR_TIMEOUT; + } + else if (!ssl->dtls_start_timeout) { + ssl->dtls_start_timeout = LowResTimer(); + } } - } #endif /* !NO_ASN_TIME */ - recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags, - (SOCKADDR*)peer, peer != NULL ? &peerSz : NULL); + recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags, + (SOCKADDR*)peer, peer != NULL ? &peerSz : NULL); - /* From the RECV(2) man page - * The returned address is truncated if the buffer provided is too small; in - * this case, addrlen will return a value greater than was supplied to the - * call. - */ - if (dtlsCtx->connected) { - /* No need to sanitize the value of peerSz */ - } - else if (dtlsCtx->userSet) { - /* Truncate peer size */ - if (peerSz > (XSOCKLENT)sizeof(lclPeer)) - peerSz = (XSOCKLENT)sizeof(lclPeer); - } - else { - /* Truncate peer size */ - if (peerSz > (XSOCKLENT)dtlsCtx->peer.bufSz) - peerSz = (XSOCKLENT)dtlsCtx->peer.bufSz; - } + /* From the RECV(2) man page + * The returned address is truncated if the buffer provided is too + * small; in this case, addrlen will return a value greater than was + * supplied to the call. + */ + if (dtlsCtx->connected) { + /* No need to sanitize the value of peerSz */ + } + else if (dtlsCtx->userSet) { + /* Truncate peer size */ + if (peerSz > (XSOCKLENT)sizeof(lclPeer)) + peerSz = (XSOCKLENT)sizeof(lclPeer); + } + else { + /* Truncate peer size */ + if (peerSz > (XSOCKLENT)dtlsCtx->peer.bufSz) + peerSz = (XSOCKLENT)dtlsCtx->peer.bufSz; + } - recvd = TranslateReturnCode(recvd, sd); + recvd = TranslateReturnCode(recvd, sd); - if (recvd < 0) { - WOLFSSL_MSG("Embed Receive From error"); - recvd = TranslateIoError(recvd); - if (recvd == WOLFSSL_CBIO_ERR_WANT_READ && - !wolfSSL_dtls_get_using_nonblock(ssl)) { - recvd = WOLFSSL_CBIO_ERR_TIMEOUT; + if (recvd < 0) { + WOLFSSL_MSG("Embed Receive From error"); + recvd = TranslateIoError(recvd); + if (recvd == WOLFSSL_CBIO_ERR_WANT_READ && + !wolfSSL_dtls_get_using_nonblock(ssl)) { + recvd = WOLFSSL_CBIO_ERR_TIMEOUT; + } + return recvd; } - return recvd; - } - else if (recvd == 0) { - if (!isDGramSock(sd)) { - /* Closed TCP connection */ - recvd = WOLFSSL_CBIO_ERR_CONN_CLOSE; + else if (recvd == 0) { + if (!isDGramSock(sd)) { + /* Closed TCP connection */ + recvd = WOLFSSL_CBIO_ERR_CONN_CLOSE; + } + else { + WOLFSSL_MSG("Ignoring 0-length datagram"); + continue; + } + return recvd; } - else { - WOLFSSL_MSG("Ignoring 0-length datagram"); + else if (dtlsCtx->connected) { + /* Nothing to do */ + } + else if (dtlsCtx->userSet) { + /* Check we received the packet from the correct peer */ + if (dtlsCtx->peer.sz > 0 && + (peerSz != (XSOCKLENT)dtlsCtx->peer.sz || + !sockAddrEqual(peer, peerSz, (SOCKADDR_S*)dtlsCtx->peer.sa, + dtlsCtx->peer.sz))) { + WOLFSSL_MSG(" Ignored packet from invalid peer"); +#if defined(NO_ASN_TIME) && \ + !defined(DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER) + if (doDtlsTimeout) { + invalidPeerPackets++; + if (invalidPeerPackets > DTLS_RECEIVEFROM_MAX_INVALID_PEER) + return wolfSSL_dtls_get_using_nonblock(ssl) + ? WOLFSSL_CBIO_ERR_WANT_READ + : WOLFSSL_CBIO_ERR_TIMEOUT; + } +#endif /* NO_ASN_TIME && !DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER */ + continue; + } } - return recvd; - } - else if (dtlsCtx->connected) { - /* Nothing to do */ - } - else if (dtlsCtx->userSet) { - /* Check we received the packet from the correct peer */ - if (dtlsCtx->peer.sz > 0 && - (peerSz != (XSOCKLENT)dtlsCtx->peer.sz || - !sockAddrEqual(peer, peerSz, (SOCKADDR_S*)dtlsCtx->peer.sa, - dtlsCtx->peer.sz))) { - WOLFSSL_MSG(" Ignored packet from invalid peer"); - return WOLFSSL_CBIO_ERR_WANT_READ; + else { + /* Store size of saved address */ + dtlsCtx->peer.sz = peerSz; } - } - else { - /* Store size of saved address */ - dtlsCtx->peer.sz = peerSz; - } #ifndef NO_ASN_TIME - ssl->dtls_start_timeout = 0; + ssl->dtls_start_timeout = 0; #endif /* !NO_ASN_TIME */ + break; + } while (1); return recvd; } From 5b2d8a0fb962d154de924b6ee7ba1ab21ec630ca Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 14 Feb 2023 12:47:09 +0000 Subject: [PATCH 319/391] tests: add dtls ignoring different peer test --- tests/api.c | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/tests/api.c b/tests/api.c index 211cba090d4..13b78dd9da5 100644 --- a/tests/api.c +++ b/tests/api.c @@ -65925,6 +65925,103 @@ static int test_wolfSSL_dtls13_null_cipher(void) return TEST_SKIPPED; } #endif +#if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ + !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ + !defined(SINGLE_THREADED) + +static int test_dtls_msg_get_connected_port(int fd, word16 *port) +{ + SOCKADDR_S peer; + XSOCKLENT len; + int ret; + + XMEMSET((byte*)&peer, 0, sizeof(peer)); + len = sizeof(peer); + ret = getpeername(fd, (SOCKADDR*)&peer, &len); + if (ret != 0 || len > sizeof(peer)) + return -1; + switch (peer.ss_family) { +#ifdef WOLFSSL_IPV6 + case WOLFSSL_IP6: { + *port = ntohs(((SOCKADDR_IN6*)&peer)->sin6_port); + break; + } +#endif /* WOLFSSL_IPV6 */ + case WOLFSSL_IP4: + *port = ntohs(((SOCKADDR_IN*)&peer)->sin_port); + break; + default: + return -1; + } + return 0; +} + +static int test_dtls_msg_from_other_peer_cb(WOLFSSL_CTX *ctx, WOLFSSL *ssl) +{ + char buf[1] = {'t'}; + SOCKADDR_IN_T addr; + int sock_fd; + word16 port; + int err; + + (void)ssl; + (void)ctx; + + err = test_dtls_msg_get_connected_port(wolfSSL_get_fd(ssl), &port); + if (err != 0) + return -1; + + sock_fd = socket(AF_INET_V, SOCK_DGRAM, 0); + if (sock_fd == -1) + return -1; + build_addr(&addr, wolfSSLIP, port, 1, 0); + + /* send a packet to the server. Being another socket, the kernel will ensure + * the source port will be different. */ + err = (int)sendto(sock_fd, buf, sizeof(buf), 0, (SOCKADDR*)&addr, + sizeof(addr)); + + close(sock_fd); + if (err == -1) + return -1; + + return 0; +} + +/* setup a SSL session but just after the handshake send a packet to the server + * with a source address different than the one of the connected client. The I/O + * callback EmbedRecvFrom should just ignore the packet. Sending of the packet + * is done in test_dtls_msg_from_other_peer_cb */ +static int test_dtls_msg_from_other_peer(void) +{ + callback_functions client_cbs; + callback_functions server_cbs; + + XMEMSET((byte*)&client_cbs, 0, sizeof(client_cbs)); + XMEMSET((byte*)&server_cbs, 0, sizeof(server_cbs)); + + client_cbs.method = wolfDTLSv1_2_client_method; + server_cbs.method = wolfDTLSv1_2_server_method; + client_cbs.doUdp = 1; + server_cbs.doUdp = 1; + + test_wolfSSL_client_server_nofail_ex(&client_cbs, &server_cbs, + test_dtls_msg_from_other_peer_cb); + + if (client_cbs.return_code != WOLFSSL_SUCCESS || + server_cbs.return_code != WOLFSSL_SUCCESS) + return TEST_FAIL; + + return TEST_SUCCESS; +} +#else +static int test_dtls_msg_from_other_peer(void) +{ + return TEST_SKIPPED; +} +#endif /* defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ + * !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ + * !defined(SINGLE_THREADED) */ /*----------------------------------------------------------------------------* | Main *----------------------------------------------------------------------------*/ @@ -66963,6 +67060,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_override_alt_cert_chain), TEST_DECL(test_dtls13_bad_epoch_ch), TEST_DECL(test_wolfSSL_dtls13_null_cipher), + TEST_DECL(test_dtls_msg_from_other_peer), /* If at some point a stub get implemented this test should fail indicating * a need to implement a new test case */ From cb7609ffc5d0943ff9b885ab3b31f1254857c993 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Tue, 21 Feb 2023 13:27:45 +0000 Subject: [PATCH 320/391] wolfio: EmbedRecvFrom: check ipv6 peer on non-ipv6 version --- src/wolfio.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/wolfio.c b/src/wolfio.c index a29223f81ec..f957d46651e 100644 --- a/src/wolfio.c +++ b/src/wolfio.c @@ -385,6 +385,15 @@ static int sockAddrEqual( return 0; } +#ifndef WOLFSSL_IPV6 +static int PeerIsIpv6(const SOCKADDR_S *peer, XSOCKLENT len) +{ + if (len < sizeof(peer->ss_family)) + return 0; + return peer->ss_family == WOLFSSL_IP6; +} +#endif /* !WOLFSSL_IPV6 */ + static int isDGramSock(int sfd) { char type = 0; @@ -425,6 +434,12 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) peer = NULL; } else if (dtlsCtx->userSet) { +#ifndef WOLFSSL_IPV6 + if (PeerIsIpv6((SOCKADDR_S*)dtlsCtx->peer.sa, dtlsCtx->peer.sz)) { + WOLFSSL_MSG("ipv6 dtls peer set but no ipv6 support compiled"); + return NOT_COMPILED_IN; + } +#endif peer = &lclPeer; XMEMSET(&lclPeer, 0, sizeof(lclPeer)); peerSz = sizeof(lclPeer); @@ -617,6 +632,12 @@ int EmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx) else if (!dtlsCtx->connected) { peer = (const SOCKADDR_S*)dtlsCtx->peer.sa; peerSz = dtlsCtx->peer.sz; +#ifndef WOLFSSL_IPV6 + if (PeerIsIpv6(peer, peerSz)) { + WOLFSSL_MSG("ipv6 dtls peer setted but no ipv6 support compiled"); + return NOT_COMPILED_IN; + } +#endif } sent = (int)DTLS_SENDTO_FUNCTION(sd, buf, sz, ssl->wflags, From 03cde440c2605bd59a412742160dcc5b952abe5d Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Thu, 18 May 2023 14:05:46 +0000 Subject: [PATCH 321/391] tests: EmbedRecvFrom/EmbedSendTo error if ipv6 w/o ipv6 compiled in --- tests/api.c | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/tests/api.c b/tests/api.c index 13b78dd9da5..0e299dd7742 100644 --- a/tests/api.c +++ b/tests/api.c @@ -66022,6 +66022,85 @@ static int test_dtls_msg_from_other_peer(void) #endif /* defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ * !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ * !defined(SINGLE_THREADED) */ +#if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_IPV6) && \ + !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ + defined(HAVE_IO_TESTS_DEPENDENCIES) +static int test_dtls_ipv6_check(void) +{ + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + SOCKADDR_IN fake_addr6; + int sockfd; + int ret; + + ctx_c = wolfSSL_CTX_new(wolfDTLSv1_2_client_method()); + if (ctx_c == NULL) + return TEST_FAIL; + ssl_c = wolfSSL_new(ctx_c); + if (ssl_c == NULL) + return TEST_FAIL; + ctx_s = wolfSSL_CTX_new(wolfDTLSv1_2_server_method()); + if (ctx_s == NULL) + return TEST_FAIL; + ret = wolfSSL_CTX_use_PrivateKey_file(ctx_s, svrKeyFile, + WOLFSSL_FILETYPE_PEM); + if (ret != WOLFSSL_SUCCESS) + return- -1; + ret = wolfSSL_CTX_use_certificate_file(ctx_s, svrCertFile, + WOLFSSL_FILETYPE_PEM); + if (ret != WOLFSSL_SUCCESS) + return -1; + ssl_s = wolfSSL_new(ctx_s); + if (ssl_s == NULL) + return TEST_FAIL; + XMEMSET((byte*)&fake_addr6, 0, sizeof(fake_addr6)); + /* mimic a sockaddr_in6 struct, this way we can't test without + * WOLFSSL_IPV6 */ + fake_addr6.sin_family = WOLFSSL_IP6; + sockfd = socket(AF_INET, SOCK_DGRAM, 0); + if (sockfd == -1) + return TEST_FAIL; + ret = wolfSSL_set_fd(ssl_c, sockfd); + if (ret != WOLFSSL_SUCCESS) + return TEST_FAIL; + /* can't return error here, as the peer is opaque for wolfssl library at + * this point */ + ret = wolfSSL_dtls_set_peer(ssl_c, &fake_addr6, sizeof(fake_addr6)); + if (ret != WOLFSSL_SUCCESS) + return TEST_FAIL; + ret = fcntl(sockfd, F_SETFL, O_NONBLOCK); + if (ret == -1) + return TEST_FAIL; + wolfSSL_dtls_set_using_nonblock(ssl_c, 1); + ret = wolfSSL_connect(ssl_c); + if (ret != WOLFSSL_FAILURE && ssl_c->error != SOCKET_ERROR_E) + return TEST_FAIL; + + ret = wolfSSL_dtls_set_peer(ssl_s, &fake_addr6, sizeof(fake_addr6)); + if (ret != WOLFSSL_SUCCESS) + return TEST_FAIL; + /* re-use the socket */ + ret = wolfSSL_set_fd(ssl_c, sockfd); + if (ret != WOLFSSL_SUCCESS) + return TEST_FAIL; + wolfSSL_dtls_set_using_nonblock(ssl_s, 1); + ret = wolfSSL_accept(ssl_s); + if (ret != WOLFSSL_FAILURE && ssl_s->error != SOCKET_ERROR_E) + return TEST_FAIL; + close(sockfd); + + wolfSSL_free(ssl_c); + wolfSSL_CTX_free(ctx_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_s); + return TEST_SUCCESS; +} +#else +static int test_dtls_ipv6_check(void) +{ + return TEST_SKIPPED; +} +#endif /*----------------------------------------------------------------------------* | Main *----------------------------------------------------------------------------*/ @@ -67061,6 +67140,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_dtls13_bad_epoch_ch), TEST_DECL(test_wolfSSL_dtls13_null_cipher), TEST_DECL(test_dtls_msg_from_other_peer), + TEST_DECL(test_dtls_ipv6_check), /* If at some point a stub get implemented this test should fail indicating * a need to implement a new test case */ From 763aea2d8a3f0b4af93d8e16b4a0a0418f7d28fc Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Thu, 18 May 2023 14:07:49 +0000 Subject: [PATCH 322/391] wolfio: cleaning: use WOLFSSL_IP6 define instead of AF_INET6 --- src/wolfio.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/wolfio.c b/src/wolfio.c index f957d46651e..4ee1605c82f 100644 --- a/src/wolfio.c +++ b/src/wolfio.c @@ -346,7 +346,7 @@ static int sockAddrEqual( if (a->ss_family != b->ss_family) return 0; - if (a->ss_family == AF_INET) { + if (a->ss_family == WOLFSSL_IP4) { if (aLen < (XSOCKLENT)sizeof(SOCKADDR_IN)) return 0; @@ -362,7 +362,7 @@ static int sockAddrEqual( } #ifdef WOLFSSL_IPV6 - if (a->ss_family == AF_INET6) { + if (a->ss_family == WOLFSSL_IP6) { SOCKADDR_IN6 *a6, *b6; if (aLen < (XSOCKLENT)sizeof(SOCKADDR_IN6)) @@ -380,7 +380,7 @@ static int sockAddrEqual( return 1; } -#endif /* WOLFSSL_HAVE_IPV6 */ +#endif /* WOLFSSL_IPV6 */ return 0; } From b8ee8fa099cf661449b53d489fc0cde48be3a82c Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Tue, 23 May 2023 09:20:22 +1000 Subject: [PATCH 323/391] SP int: clenaup sp_count_bits More explicitly handle used == 0 for static code analyser. Make sp_count_bits clearer. --- wolfcrypt/src/sp_int.c | 83 ++++++++++++++++++------------------------ 1 file changed, 35 insertions(+), 48 deletions(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index b3342611f2a..f5da4780e3d 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -5473,76 +5473,63 @@ int sp_is_bit_set(const sp_int* a, unsigned int b) */ int sp_count_bits(const sp_int* a) { - int n = 0; + int n = -1; /* Check parameter. */ - if (a != NULL) { + if ((a != NULL) && (a->used > 0)) { /* Get index of last word. */ n = (int)(a->used - 1); /* Don't count leading zeros. */ while ((n >= 0) && (a->dp[n] == 0)) { n--; } - /* -1 indicates SP integer value was zero. */ - if (n < 0) { - n = 0; - } - else { - #ifdef SP_ASM_HI_BIT_SET_IDX - sp_int_digit hi; - sp_int_digit d; + } - /* Get the most significant word. */ - d = a->dp[n]; - /* Count of bits up to last word. */ - n *= SP_WORD_SIZE; + /* -1 indicates SP integer value was zero. */ + if (n < 0) { + n = 0; + } + else { + /* Get the most significant word. */ + sp_int_digit d = a->dp[n]; + /* Count of bits up to last word. */ + n *= SP_WORD_SIZE; + #ifdef SP_ASM_HI_BIT_SET_IDX + { + sp_int_digit hi; /* Get index of highest set bit. */ SP_ASM_HI_BIT_SET_IDX(d, hi); - /* Add bits up to and including index. */ n += (int)hi + 1; - #elif defined(SP_ASM_LZCNT) + } + #elif defined(SP_ASM_LZCNT) + { sp_int_digit lz; - sp_int_digit d; - - /* Get the most significant word. */ - d = a->dp[n]; - /* Count of bits up to last word. */ - n *= SP_WORD_SIZE; - /* Count number of leading zeros in highest non-zero digit. */ SP_ASM_LZCNT(d, lz); - /* Add non-leading zero bits count. */ n += SP_WORD_SIZE - (int)lz; - #else - sp_int_digit d; - - /* Get the most significant word. */ - d = a->dp[n]; - /* Count of bits up to last word. */ - n *= SP_WORD_SIZE; - - /* Check if top word has more than half the bits set. */ - if (d > SP_HALF_MAX) { - /* Set count to a full last word. */ - n += SP_WORD_SIZE; - /* Don't count leading zero bits. */ - while ((d & ((sp_int_digit)1 << (SP_WORD_SIZE - 1))) == 0) { - n--; - d <<= 1; - } + } + #else + /* Check if top word has more than half the bits set. */ + if (d > SP_HALF_MAX) { + /* Set count to a full last word. */ + n += SP_WORD_SIZE; + /* Don't count leading zero bits. */ + while ((d & ((sp_int_digit)1 << (SP_WORD_SIZE - 1))) == 0) { + n--; + d <<= 1; } - else { - /* Add to count until highest set bit is shifted out. */ - while (d != 0) { - n++; - d >>= 1; - } + } + else { + /* Add to count until highest set bit is shifted out. */ + while (d != 0) { + n++; + d >>= 1; } - #endif } + #endif } return n; From e757efc7ad44620474b9f2b331574fa55515a769 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Wed, 24 May 2023 12:46:11 -0600 Subject: [PATCH 324/391] CMake: add option to enable asio --- CMakeLists.txt | 49 +++++++++++++++++++++++++++++++++++++------ cmake/functions.cmake | 1 + src/pk.c | 4 ++++ 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5703e0da283..0be34caf81d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ # CMakeList.txt # -# Copyright (C) 2006-2020 wolfSSL Inc. +# Copyright (C) 2006-2023 wolfSSL Inc. # # This file is part of wolfSSL. (formerly known as CyaSSL) # @@ -391,6 +391,24 @@ add_option(WOLFSSL_OPENSSLEXTRA "Enable extra OpenSSL API, size+ (default: disabled)" "no" "yes;no") +add_option(WOLFSSL_OPENSSLALL + "Enable all OpenSSL API, size++ (default: disabled)" + "no" "yes;no") + +add_option(WOLFSSL_ASIO + "Enable asio support (default: disabled)" + "no" "yes;no") + +if (WOLFSSL_ASIO) + list(APPEND WOLFSSL_DEFINITIONS + "-DWOLFSSL_ASIO" "-DASIO_USE_WOLFSSL" + "-DBOOST_ASIO_USE_WOLFSSL" "-DHAVE_EX_DATA" + "-DSSL_TXT_TLSV1_2" "-DOPENSSL_NO_SSL2" "-DOPENSSL_NO_SSL3" + "-DHAVE_OCSP" "-DWOLFSSL_KEY_GEN") + override_cache(WOLFSSL_OPENSSLALL "yes") + override_cache(WOLFSSL_OPENSSLEXTRA "yes") +endif() + if (WOLFSSL_OPENSSLEXTRA AND NOT WOLFSSL_OPENSSLCOEXIST) list(APPEND WOLFSSL_DEFINITIONS "-DOPENSSL_EXTRA" @@ -401,6 +419,14 @@ if (WOLFSSL_OPENSSLEXTRA AND NOT WOLFSSL_OPENSSLCOEXIST) "-DWOLFSSL_FORCE_CACHE_ON_TICKET") endif() +if (WOLFSSL_OPENSSLALL) + list(APPEND WOLFSSL_DEFINITIONS + "-DOPENSSL_ALL" "-DWOLFSSL_EITHER_SIDE" "-DWC_RSA_NO_PADDING" + "-DWC_RSA_PSS" "-DWOLFSSL_PSS_LONG_SALT" "-DWOLFSSL_TICKET_HAVE_ID" + "-DWOLFSSL_ERROR_CODE_OPENSSL" "-DWOLFSSL_CERT_NAME_ALL") +endif() + + # TODO: - IPv6 test apps set(WOLFSSL_SLOW_MATH "yes") @@ -548,7 +574,7 @@ endif() # SHA224 set(SHA224_DEFAULT "no") -if(("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64") OR +if(("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64|arm64") OR ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")) if(NOT WOLFSSL_AFALG AND NOT WOLFSSL_DEVCRYPTO AND (NOT WOLFSSL_FIPS OR ("${FIPS_VERSION}" STREQUAL "v2"))) @@ -562,7 +588,7 @@ add_option("WOLFSSL_SHA224" # SHA3 set(SHA3_DEFAULT "no") -if(("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64") OR +if(("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64|arm64") OR ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")) if(NOT WOLFSSL_FIPS OR ("${FIPS_VERSION}" STREQUAL "v2")) set(SHA3_DEFAULT "yes") @@ -1048,7 +1074,7 @@ endif() # Base64 set(BASE64_ENCODE_DEFAULT "no") -if("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64") +if("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64|AMD64|arm64") set(BASE64_ENCODE_DEFAULT "yes") endif() @@ -1068,7 +1094,8 @@ add_option("WOLFSSL_DES3" ${WOLFSSL_DES3_HELP_STRING} "no" "yes;no") if(WOLFSSL_OPENSSH OR WOLFSSL_QT OR WOLFSSL_OPENVPN OR - WOLFSSL_WPAS) + WOLFSSL_WPAS OR + WOLFSSL_ASIO) override_cache(WOLFSSL_DES3 "yes") endif() @@ -1922,6 +1949,16 @@ if(WOLFSSL_CONFIG_H) "${CMAKE_CURRENT_BINARY_DIR}/wolfcrypt/test/test_paths.h" ) endif() +# If config.h or wolfssl/options.h exists, delete it to avoid +# a mixup with build/wolfssl/options.h. +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/wolfssl/options.h") + file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/wolfssl/options.h") +endif() + +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/config.h") + file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/config.h") +endif() + # Suppress some warnings about separate compilation, inlining add_definitions("-DWOLFSSL_IGNORE_FILE_WARN") # Generate user options header @@ -1947,7 +1984,7 @@ file(REMOVE ${OPTION_FILE}) file(APPEND ${OPTION_FILE} "/* wolfssl options.h\n") file(APPEND ${OPTION_FILE} " * generated from configure options\n") file(APPEND ${OPTION_FILE} " *\n") -file(APPEND ${OPTION_FILE} " * Copyright (C) 2006-2020 wolfSSL Inc.\n") +file(APPEND ${OPTION_FILE} " * Copyright (C) 2006-2023 wolfSSL Inc.\n") file(APPEND ${OPTION_FILE} " *\n") file(APPEND ${OPTION_FILE} " * This file is part of wolfSSL. (formerly known as CyaSSL)\n") file(APPEND ${OPTION_FILE} " *\n") diff --git a/cmake/functions.cmake b/cmake/functions.cmake index a81e862004d..e77991ea146 100644 --- a/cmake/functions.cmake +++ b/cmake/functions.cmake @@ -827,6 +827,7 @@ function(generate_lib_src_list LIB_SOURCES) src/wolfio.c src/keys.c src/ssl.c + src/ocsp.c src/tls.c) if(BUILD_TLS13) diff --git a/src/pk.c b/src/pk.c index 34637376158..2ad3ed59c3d 100644 --- a/src/pk.c +++ b/src/pk.c @@ -7433,6 +7433,10 @@ static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh, != 0) { err = 1; } + /* If Success on X9.42 DH format, clear error from failed DH format */ + else { + wolfSSL_ERR_clear_error(); + } } if (memAlloced) { /* PEM data no longer needed. */ From 71a118ffe2e228c40f71b5918e8a2450f26a2530 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Wed, 24 May 2023 14:17:46 -0600 Subject: [PATCH 325/391] Only clear last ASN_PEM_NO_HEADER error --- src/pk.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pk.c b/src/pk.c index 2ad3ed59c3d..f4665818539 100644 --- a/src/pk.c +++ b/src/pk.c @@ -7435,7 +7435,8 @@ static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh, } /* If Success on X9.42 DH format, clear error from failed DH format */ else { - wolfSSL_ERR_clear_error(); + unsigned long error; + CLEAR_ASN_NO_PEM_HEADER_ERROR(error); } } if (memAlloced) { From 32d73186902dc19b203383dff640f8cc07f18d80 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 22 May 2023 10:52:51 +1000 Subject: [PATCH 326/391] X509 NAME ENTRY create: ensure existing object is not lost wolfSSL_X509_NAME_ENTRY_create_by_txt and wolfSSL_X509_NAME_ENTRY_create_by_NID: - object field was being reused if it existed but lost on error - extracted common code - store object only on success, ie object is not NULL --- src/x509.c | 56 +++++++++++++++++++++++++++--------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/src/x509.c b/src/x509.c index abecda5e300..6af78177814 100644 --- a/src/x509.c +++ b/src/x509.c @@ -11383,6 +11383,31 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) return ne; } + static void wolfssl_x509_name_entry_set(WOLFSSL_X509_NAME_ENTRY* ne, + int nid, int type, const unsigned char *data, int dataSz) + { + WOLFSSL_ASN1_OBJECT* object; + + ne->nid = nid; + /* Reuse the object if already available. */ + object = wolfSSL_OBJ_nid2obj_ex(nid, ne->object); + if (object != NULL) { + /* Set the object when no error. */ + ne->object = object; + } + ne->value = wolfSSL_ASN1_STRING_type_new(type); + if (ne->value != NULL) { + if (wolfSSL_ASN1_STRING_set(ne->value, (const void*)data, + dataSz) == WOLFSSL_SUCCESS) { + ne->set = 1; + } + else { + /* Free the ASN1_STRING if it is not set. */ + wolfSSL_ASN1_STRING_free(ne->value); + ne->value = NULL; + } + } + } /* Create a new WOLFSSL_X509_NAME_ENTRY structure based on the text passed * in. Returns NULL on failure */ @@ -11415,20 +11440,8 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) return NULL; } } - ne->nid = nid; - ne->object = wolfSSL_OBJ_nid2obj_ex(nid, ne->object); - ne->value = wolfSSL_ASN1_STRING_type_new(type); - if (ne->value != NULL) { - if (wolfSSL_ASN1_STRING_set(ne->value, (const void*)data, - dataSz) == WOLFSSL_SUCCESS) { - ne->set = 1; - } - else { - /* Free the ASN1_STRING if it is not set. */ - wolfSSL_ASN1_STRING_free(ne->value); - ne->value = NULL; - } - } + + wolfssl_x509_name_entry_set(ne, nid, type, data, dataSz); } return ne; @@ -11469,20 +11482,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) ne = *out; } - ne->nid = nid; - ne->object = wolfSSL_OBJ_nid2obj_ex(nid, ne->object); - ne->value = wolfSSL_ASN1_STRING_type_new(type); - if (ne->value != NULL) { - if (wolfSSL_ASN1_STRING_set(ne->value, (const void*)data, dataSz) - == WOLFSSL_SUCCESS) { - ne->set = 1; - } - else { - /* Free the ASN1_STRING if it is not set. */ - wolfSSL_ASN1_STRING_free(ne->value); - ne->value = NULL; - } - } + wolfssl_x509_name_entry_set(ne, nid, type, data, dataSz); return ne; } From 9deda0754ed6a8e29f136a48a6f49d20cc2ff857 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 25 May 2023 09:26:22 +1000 Subject: [PATCH 327/391] X509 NAME Entry: fix get object to not leak wolfSSL_X509_NAME_ENTRY_get_object - object field was being reused if it existed but lost on error - store object only on success, ie object is not NULL - moved function into x509.c --- src/ssl.c | 21 --------------------- src/x509.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index dc006de2863..6d7ef4f351b 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -30056,27 +30056,6 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) #endif } -#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE || - HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */ -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ - defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ - defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ - defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY) - WOLFSSL_ASN1_OBJECT * wolfSSL_X509_NAME_ENTRY_get_object(WOLFSSL_X509_NAME_ENTRY *ne) - { -#ifdef WOLFSSL_DEBUG_OPENSSL - WOLFSSL_ENTER("wolfSSL_X509_NAME_ENTRY_get_object"); -#endif - if (ne == NULL) { - return NULL; - } - - ne->object = wolfSSL_OBJ_nid2obj_ex(ne->nid, ne->object); - - return ne->object; - } - - #endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE || HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */ diff --git a/src/x509.c b/src/x509.c index 6af78177814..baf7e81588c 100644 --- a/src/x509.c +++ b/src/x509.c @@ -11486,7 +11486,36 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) return ne; } +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ + defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY) +WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( + WOLFSSL_X509_NAME_ENTRY *ne) +{ + WOLFSSL_ASN1_OBJECT* object = NULL; + +#ifdef WOLFSSL_DEBUG_OPENSSL + WOLFSSL_ENTER("wolfSSL_X509_NAME_ENTRY_get_object"); +#endif + + if (ne != NULL) { + /* Create object from nid - reuse existing object if possible. */ + object = wolfSSL_OBJ_nid2obj_ex(ne->nid, ne->object); + if (object != NULL) { + /* Set the object when no error. */ + ne->object = object; + } + } + + return object; +} +#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE || + * HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* add all entry of type "nid" to the buffer "fullName" and advance "idx" * since number of entries is small, a brute force search is used here * returns the number of entries added From 33d12ed73541b7a3175610e5c9e1ea237fdbcab2 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Fri, 26 May 2023 16:12:14 -0400 Subject: [PATCH 328/391] Fix a syntax error. Tested with: ./configure --enable-debug --enable-all CFLAGS=-DDEBUG_WOLFSSL_VERBOSE --- tests/api.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/api.c b/tests/api.c index 0e299dd7742..fde5cda3fd6 100644 --- a/tests/api.c +++ b/tests/api.c @@ -63268,9 +63268,9 @@ static void obj_name_t(const OBJ_NAME* nm, void* arg) /* print to stderr */ AssertNotNull(arg); - bio = BIO_new(BIO_s_file()); + BIO *bio = BIO_new(BIO_s_file()); BIO_set_fp(bio, arg, BIO_NOCLOSE); - BIO_printf(bio, "%s\n", mn); + BIO_printf(bio, "%s\n", nm); BIO_free(bio); #endif } From fbfcb937bc9f9b78e6cc157d834fb03da4d8f43b Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 24 May 2023 11:42:52 +1000 Subject: [PATCH 329/391] CryptoCb, PKCS#11: add RSA key size lookup wc_RsaEncryptSize(): assumed a key size of 2048 when using hardware key. Added callback to do lookup and implemented for PKCS#11. If lookup not supported then assumes 2048 bits. --- wolfcrypt/src/cryptocb.c | 24 ++++++++++ wolfcrypt/src/rsa.c | 4 +- wolfcrypt/src/wc_pkcs11.c | 92 +++++++++++++++++++++++++++++++++++- wolfssl/wolfcrypt/cryptocb.h | 5 ++ wolfssl/wolfcrypt/types.h | 3 +- 5 files changed, 124 insertions(+), 4 deletions(-) diff --git a/wolfcrypt/src/cryptocb.c b/wolfcrypt/src/cryptocb.c index 7f6fb75ff84..13edcc49e9d 100644 --- a/wolfcrypt/src/cryptocb.c +++ b/wolfcrypt/src/cryptocb.c @@ -359,6 +359,30 @@ int wc_CryptoCb_RsaCheckPrivKey(RsaKey* key, const byte* pubKey, return wc_CryptoCb_TranslateErrorCode(ret); } + +int wc_CryptoCb_RsaGetSize(const RsaKey* key, int* keySize) +{ + int ret = CRYPTOCB_UNAVAILABLE; + CryptoCb* dev; + + if (key == NULL) + return ret; + + /* locate registered callback */ + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); + if (dev && dev->cb) { + wc_CryptoInfo cryptoInfo; + XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); + cryptoInfo.algo_type = WC_ALGO_TYPE_PK; + cryptoInfo.pk.type = WC_PK_TYPE_RSA_GET_SIZE; + cryptoInfo.pk.rsa_get_size.key = key; + cryptoInfo.pk.rsa_get_size.keySize = keySize; + + ret = dev->cb(dev->devId, &cryptoInfo, dev->ctx); + } + + return wc_CryptoCb_TranslateErrorCode(ret); +} #endif /* !NO_RSA */ #ifdef HAVE_ECC diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index 61288aa4f36..33fb3bc6464 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -4307,7 +4307,9 @@ int wc_RsaEncryptSize(const RsaKey* key) #ifdef WOLF_CRYPTO_CB if (ret == 0 && key->devId != INVALID_DEVID) { - ret = 2048/8; /* hardware handles, use 2048-bit as default */ + if (wc_CryptoCb_RsaGetSize(key, &ret) == CRYPTOCB_UNAVAILABLE) { + ret = 2048/8; /* hardware handles, use 2048-bit as default */ + } } #endif diff --git a/wolfcrypt/src/wc_pkcs11.c b/wolfcrypt/src/wc_pkcs11.c index b2386f57bfb..6ae88d79685 100644 --- a/wolfcrypt/src/wc_pkcs11.c +++ b/wolfcrypt/src/wc_pkcs11.c @@ -1724,6 +1724,42 @@ static int Pkcs11GetRsaPublicKey(RsaKey* key, Pkcs11Session* session, return ret; } +/** + * Get the RSA modulus size in bytes from the PKCS#11 object. + * + * @param [in] session Session object. + * @param [in] pubkey Public key object. + * @param [out] modSize Size of the modulus in bytes. + * @return WC_HW_E when a PKCS#11 library call fails. + * @return MEMORY_E when a memory allocation fails. + * @return 0 on success. + */ +static int Pkcs11GetRsaModulusSize(Pkcs11Session* session, + CK_OBJECT_HANDLE pubKey, int* modSize) +{ + int ret = 0; + CK_ATTRIBUTE tmpl[] = { + { CKA_MODULUS, NULL_PTR, 0 } + }; + CK_ULONG tmplCnt = sizeof(tmpl) / sizeof(*tmpl); + CK_RV rv; + + PKCS11_DUMP_TEMPLATE("Get RSA Modulus Length", tmpl, tmplCnt); + rv = session->func->C_GetAttributeValue(session->handle, pubKey, tmpl, + tmplCnt); + PKCS11_RV("C_GetAttributeValue", rv); + if (rv != CKR_OK) { + ret = WC_HW_E; + } + PKCS11_DUMP_TEMPLATE("RSA Modulus Length", tmpl, tmplCnt); + + if (ret == 0) { + *modSize = (int)tmpl[0].ulValueLen; + } + + return ret; +} + /** * Make a handle to a private RSA key. * @@ -2965,7 +3001,6 @@ static int wc_Pkcs11CheckPrivKey_Rsa(RsaKey* priv, * @param [in] info Cryptographic operation data. * @return WC_HW_E when a PKCS#11 library call fails. * @return MEMORY_E when a memory allocation fails. - * @return MEMORY_E when a memory allocation fails. * @return MP_CMP_E when the public parts are different. * @return 0 on success. */ @@ -2982,7 +3017,7 @@ static int Pkcs11RsaCheckPrivKey(Pkcs11Session* session, wc_CryptoInfo* info) CKK_RSA, session, priv->label, priv->labelLen); } - else if (info->pk.rsa.key->idLen > 0) { + else if (priv->idLen > 0) { ret = Pkcs11FindKeyById(&privateKey, CKO_PRIVATE_KEY, CKK_RSA, session, priv->id, priv->idLen); } @@ -3003,6 +3038,52 @@ static int Pkcs11RsaCheckPrivKey(Pkcs11Session* session, wc_CryptoInfo* info) return ret; } + +/** + * Get the size of the RSA key in bytes. + * + * @param [in] session Session object. + * @param [in] info Cryptographic operation data. + * @return WC_HW_E when a PKCS#11 library call fails. + * @return NOT_COMPILED_IN when no modulus, label or id. + * @return 0 on success. + */ +static int Pkcs11RsaGetSize(Pkcs11Session* session, wc_CryptoInfo* info) +{ + int ret = 0; + CK_OBJECT_HANDLE privateKey; + const RsaKey* priv = info->pk.rsa_get_size.key; + + if (!mp_iszero(&priv->n)) { + /* Use the key's modulus MP integer to determine size. */ + *info->pk.rsa_get_size.keySize = mp_unsigned_bin_size(&priv->n); + } + else { + /* Get the RSA private key object. */ + if (priv->labelLen > 0) { + ret = Pkcs11FindKeyByLabel(&privateKey, CKO_PRIVATE_KEY, + CKK_RSA, session, (char*)priv->label, + priv->labelLen); + } + else if (priv->idLen > 0) { + ret = Pkcs11FindKeyById(&privateKey, CKO_PRIVATE_KEY, CKK_RSA, + session, (unsigned char*)priv->id, + priv->idLen); + } + else { + /* Lookup is by modulus which is not present. */ + ret = NOT_COMPILED_IN; + } + + if (ret == 0) { + /* Lookup the modulus size in bytes. */ + ret = Pkcs11GetRsaModulusSize(session, privateKey, + info->pk.rsa_get_size.keySize); + } + } + + return ret; +} #endif #ifdef HAVE_ECC @@ -3710,6 +3791,13 @@ int wc_Pkcs11_CryptoDevCb(int devId, wc_CryptoInfo* info, void* ctx) Pkcs11CloseSession(token, &session); } break; + case WC_PK_TYPE_RSA_GET_SIZE: + ret = Pkcs11OpenSession(token, &session, readWrite); + if (ret == 0) { + ret = Pkcs11RsaGetSize(&session, info); + Pkcs11CloseSession(token, &session); + } + break; #endif #ifdef HAVE_ECC #ifndef NO_PKCS11_EC_KEYGEN diff --git a/wolfssl/wolfcrypt/cryptocb.h b/wolfssl/wolfcrypt/cryptocb.h index b5a592b1886..c1b4307fe74 100644 --- a/wolfssl/wolfcrypt/cryptocb.h +++ b/wolfssl/wolfcrypt/cryptocb.h @@ -107,6 +107,10 @@ typedef struct wc_CryptoInfo { const byte* pubKey; word32 pubKeySz; } rsa_check; + struct { + const RsaKey* key; + int* keySize; + } rsa_get_size; #endif #ifdef HAVE_ECC struct { @@ -391,6 +395,7 @@ WOLFSSL_LOCAL int wc_CryptoCb_MakeRsaKey(RsaKey* key, int size, long e, WOLFSSL_LOCAL int wc_CryptoCb_RsaCheckPrivKey(RsaKey* key, const byte* pubKey, word32 pubKeySz); +WOLFSSL_LOCAL int wc_CryptoCb_RsaGetSize(const RsaKey* key, int* keySize); #endif /* !NO_RSA */ #ifdef HAVE_ECC diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index b105028e30a..83f868dec2b 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -1141,7 +1141,8 @@ typedef struct w64wrapper { WC_PK_TYPE_ED25519_VERIFY = 14, WC_PK_TYPE_ED25519_KEYGEN = 15, WC_PK_TYPE_CURVE25519_KEYGEN = 16, - WC_PK_TYPE_MAX = WC_PK_TYPE_CURVE25519_KEYGEN + WC_PK_TYPE_RSA_GET_SIZE = 17, + WC_PK_TYPE_MAX = WC_PK_TYPE_RSA_GET_SIZE }; From b6554bc162168cee3721d8850b37f9b88eebb7de Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Wed, 24 May 2023 17:28:53 -0400 Subject: [PATCH 330/391] Added ASN.1 Integer sequencing --- src/ssl_asn1.c | 17 ++++++++++++++++- tests/api.c | 13 +++++++++---- wolfssl/openssl/asn1.h | 1 + wolfssl/ssl.h | 2 +- 4 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 5c5d9068514..ca8a01c015c 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -65,6 +65,9 @@ static int wolfssl_asn1_item_new(void** item, int type) case WOLFSSL_ASN1_BIT_STRING_ASN1: *(WOLFSSL_ASN1_BIT_STRING**)item = wolfSSL_ASN1_BIT_STRING_new(); break; + case WOLFSSL_ASN1_INTEGER_ASN1: + *(WOLFSSL_ASN1_INTEGER**)item = wolfSSL_ASN1_INTEGER_new(); + break; default: WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_new"); *(void**)item = NULL; @@ -128,6 +131,9 @@ static void wolfssl_asn1_item_free(void** item, int type) case WOLFSSL_ASN1_BIT_STRING_ASN1: wolfSSL_ASN1_BIT_STRING_free(*(WOLFSSL_ASN1_BIT_STRING**)item); break; + case WOLFSSL_ASN1_INTEGER_ASN1: + wolfSSL_ASN1_INTEGER_free(*(WOLFSSL_ASN1_INTEGER**)item); + break; default: WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_free"); } @@ -225,6 +231,15 @@ static int wolfssl_i2d_asn1_item(void** item, int type, byte* buf) len = wolfSSL_i2d_ASN1_BIT_STRING( *(const WOLFSSL_ASN1_BIT_STRING**)item, buf); break; + case WOLFSSL_ASN1_INTEGER_ASN1: + byte *tmp_buf = buf; + len = wolfSSL_i2d_ASN1_INTEGER( + *(const WOLFSSL_ASN1_INTEGER**)item, &tmp_buf); + if ((buf == NULL) && (tmp_buf != NULL)) { + XFREE(tmp_buf, NULL, DYNAMIC_TYPE_ASN1); + tmp_buf = NULL; + } + break; default: WOLFSSL_MSG("Type not support in processMembers"); len = 0; @@ -787,7 +802,7 @@ static int wolfssl_asn1_int_twos_compl(byte* data, int length, byte* neg) * @return -1 when a is NULL or no data, out is NULL, dynamic memory allocation * fails or encoding length fails. */ -int wolfSSL_i2d_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER* a, unsigned char** out) +int wolfSSL_i2d_ASN1_INTEGER(const WOLFSSL_ASN1_INTEGER* a, unsigned char** out) { int ret = 0; byte* buf = NULL; diff --git a/tests/api.c b/tests/api.c index fde5cda3fd6..3c58812d3eb 100644 --- a/tests/api.c +++ b/tests/api.c @@ -33539,7 +33539,8 @@ static int test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS(void) const EC_GROUP *group; const EC_POINT *point; int nid; - TEST_ASN1 test_asn1; + TEST_ASN1 *test_asn1 = NULL; + const unsigned char badObjDer[] = { 0x06, 0x00 }; const unsigned char goodObjDer[] = { 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01 @@ -33631,12 +33632,16 @@ static int test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS(void) XFREE(der, NULL, DYNAMIC_TYPE_ASN1); DPP_BOOTSTRAPPING_KEY_free(bootstrap); + /* Test integer */ + AssertNotNull(test_asn1 = TEST_ASN1_new()); + der = NULL; + AssertIntEQ(i2d_TEST_ASN1(test_asn1, &der), 4); + XFREE(der, NULL, DYNAMIC_TYPE_ASN1); + TEST_ASN1_free(test_asn1); + /* Test error cases. */ - AssertNull(TEST_ASN1_new()); AssertNull(wolfSSL_ASN1_item_new(NULL)); TEST_ASN1_free(NULL); - XMEMSET(&test_asn1, 0, sizeof(TEST_ASN1)); - AssertIntEQ(i2d_TEST_ASN1(&test_asn1, &der), 0); res = TEST_RES_CHECK(1); #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ diff --git a/wolfssl/openssl/asn1.h b/wolfssl/openssl/asn1.h index edfa662919e..12ad3698070 100644 --- a/wolfssl/openssl/asn1.h +++ b/wolfssl/openssl/asn1.h @@ -140,6 +140,7 @@ typedef struct { typedef enum { WOLFSSL_X509_ALGOR_ASN1 = 0, WOLFSSL_ASN1_BIT_STRING_ASN1, + WOLFSSL_ASN1_INTEGER_ASN1, } WOLFSSL_ASN1_TYPES; #define ASN1_SEQUENCE(type) \ diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index 28f4515dde9..e753cdb3a3c 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -2058,7 +2058,7 @@ WOLFSSL_API WOLFSSL_ASN1_INTEGER* wolfSSL_d2i_ASN1_INTEGER( WOLFSSL_ASN1_INTEGER** a, const unsigned char** in, long inSz); -WOLFSSL_API int wolfSSL_i2d_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER* a, +WOLFSSL_API int wolfSSL_i2d_ASN1_INTEGER(const WOLFSSL_ASN1_INTEGER* a, unsigned char** out); WOLFSSL_API int wolfSSL_ASN1_TIME_print(WOLFSSL_BIO* bio, const WOLFSSL_ASN1_TIME* asnTime); From 664af284d76cc12f2ad80ef9611ae3e3163cbcb8 Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Wed, 24 May 2023 17:37:51 -0400 Subject: [PATCH 331/391] Fixed typo in comment --- src/ssl_asn1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index ca8a01c015c..d7bbc2baad6 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -558,7 +558,7 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_ASN1_INTEGER_new(void) void wolfSSL_ASN1_INTEGER_free(WOLFSSL_ASN1_INTEGER* in) { if ((in != NULL) && (in->isDynamic)) { - /* Dispose of any data allocated in BIT_STRING. */ + /* Dispose of any data allocated in INTEGER. */ XFREE(in->data, NULL, DYNAMIC_TYPE_OPENSSL); } /* Dispose of the ASN.1 INTEGER object. */ From 47b47208d623a3097210fb75492ad47abaf6cd90 Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Sun, 28 May 2023 18:59:16 -0400 Subject: [PATCH 332/391] Added braces to support older compilers --- src/ssl_asn1.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index d7bbc2baad6..3075665dc5a 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -232,6 +232,7 @@ static int wolfssl_i2d_asn1_item(void** item, int type, byte* buf) *(const WOLFSSL_ASN1_BIT_STRING**)item, buf); break; case WOLFSSL_ASN1_INTEGER_ASN1: + { byte *tmp_buf = buf; len = wolfSSL_i2d_ASN1_INTEGER( *(const WOLFSSL_ASN1_INTEGER**)item, &tmp_buf); @@ -239,6 +240,7 @@ static int wolfssl_i2d_asn1_item(void** item, int type, byte* buf) XFREE(tmp_buf, NULL, DYNAMIC_TYPE_ASN1); tmp_buf = NULL; } + } break; default: WOLFSSL_MSG("Type not support in processMembers"); From a55d843ec4abd838a398c5e516cff9c610e6c72f Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Sun, 28 May 2023 21:18:45 -0400 Subject: [PATCH 333/391] Added valid ASN.1 integer value to test_asn1 --- tests/api.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/api.c b/tests/api.c index 3c58812d3eb..a68bd1db8ab 100644 --- a/tests/api.c +++ b/tests/api.c @@ -33635,7 +33635,8 @@ static int test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS(void) /* Test integer */ AssertNotNull(test_asn1 = TEST_ASN1_new()); der = NULL; - AssertIntEQ(i2d_TEST_ASN1(test_asn1, &der), 4); + ASN1_INTEGER_set(test_asn1->integer, 100); + AssertIntEQ(i2d_TEST_ASN1(test_asn1, &der), 5); XFREE(der, NULL, DYNAMIC_TYPE_ASN1); TEST_ASN1_free(test_asn1); From b6d505686a1eaae60b4f9f6f02996cec00745f81 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 26 May 2023 15:49:14 +1000 Subject: [PATCH 334/391] Tests api.c: rework for malloc failure testing Modified number of tests to not crash on failure and cleanup allocations on failure. Added memory fail count option to set which memory allocation to start failing on. Fix issues found from testing. bio.c: BIO_new() move ref count up so that calls to wolfSSL_BIO_free() work. internal.c: ImportCipherSpecState wasn't checking SetKeySide for failure. Crash when pointer is NULL and accessed directly. ocsp.c: wolfSSL_OCSP_response_get1_basic() doesn't need to free vs->source as it is freed in WOLFSSL_OCSP_RESPONSE_free(). ssl.c: ProcessBuffer() Don't strip PKCS#8 header if failed to create DER. Crasged as directly accessing 'der' which was NULL. ssl_asn.c: wolfssl_asn1_integer_require_len was checking wrong variable to see if allocation failed. x509,c: wolfSSL_X509_ALGOR_set0 needs to set aobj only when no failure possible. wolfSSL_X509_chain_up_ref needs to call cleanup to ensure everything is freed. --- src/bio.c | 33 +- src/internal.c | 5 +- src/ocsp.c | 6 +- src/ssl.c | 10 +- src/ssl_asn1.c | 2 +- src/x509.c | 10 +- tests/api.c | 6834 +++++++++++++++++++----------------- tests/unit.c | 14 +- tests/unit.h | 103 +- wolfcrypt/src/asn.c | 9 +- wolfcrypt/src/memory.c | 96 +- wolfcrypt/src/wc_port.c | 6 + wolfssl/test.h | 11 +- wolfssl/wolfcrypt/memory.h | 5 + 14 files changed, 3890 insertions(+), 3254 deletions(-) diff --git a/src/bio.c b/src/bio.c index 103d7771f2c..39e542b2585 100644 --- a/src/bio.c +++ b/src/bio.c @@ -2481,6 +2481,23 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->shutdown = BIO_CLOSE; /* default to close things */ bio->num = WOLFSSL_BIO_ERROR; bio->init = 1; + + #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) + { + int ret; + wolfSSL_RefInit(&bio->ref, &ret); + #ifdef WOLFSSL_REFCNT_ERROR_RETURN + if (ret != 0) { + wolfSSL_BIO_free(bio); + WOLFSSL_MSG("wc_InitMutex failed for WOLFSSL_BIO"); + return NULL; + } + #else + (void)ret; + #endif + } + #endif + if (method->type == WOLFSSL_BIO_MEMORY) bio->eof = WOLFSSL_BIO_ERROR; /* Return value for empty buffer */ if (method->type == WOLFSSL_BIO_MEMORY || @@ -2507,22 +2524,6 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) method->createCb(bio); } - #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) - { - int ret; - wolfSSL_RefInit(&bio->ref, &ret); - #ifdef WOLFSSL_REFCNT_ERROR_RETURN - if (ret != 0) { - wolfSSL_BIO_free(bio); - WOLFSSL_MSG("wc_InitMutex failed for WOLFSSL_BIO"); - return NULL; - } - #else - (void)ret; - #endif - } - #endif - } return bio; } diff --git a/src/internal.c b/src/internal.c index 560ed002871..5f4988f6297 100644 --- a/src/internal.c +++ b/src/internal.c @@ -913,6 +913,7 @@ static int ImportCipherSpecState(WOLFSSL* ssl, const byte* exp, word32 len, word32 tmp_seq_peer_hi; word32 tmp_seq_lo; word32 tmp_seq_hi; + int ret; WOLFSSL_ENTER("ImportCipherSpecState"); @@ -951,7 +952,9 @@ static int ImportCipherSpecState(WOLFSSL* ssl, const byte* exp, word32 len, tmp_seq_lo = ssl->keys.sequence_number_lo; tmp_seq_hi = ssl->keys.sequence_number_hi; - SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE); + if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) < 0) { + return ret; + } /* reset sequence numbers after setting keys */ ssl->keys.peer_sequence_number_lo = tmp_seq_peer_lo; diff --git a/src/ocsp.c b/src/ocsp.c index 796b80f55b5..30f5e16a06e 100644 --- a/src/ocsp.c +++ b/src/ocsp.c @@ -938,8 +938,10 @@ WOLFSSL_OCSP_BASICRESP* wolfSSL_OCSP_response_get1_basic(OcspResponse* response) DYNAMIC_TYPE_OCSP_ENTRY); bs->source = (byte*)XMALLOC(bs->maxIdx, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (bs->single == NULL || bs->source == NULL) { - if (bs->single) XFREE(bs->single, NULL, DYNAMIC_TYPE_OCSP_ENTRY); - if (bs->source) XFREE(bs->source, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (bs->single) { + XFREE(bs->single, NULL, DYNAMIC_TYPE_OCSP_ENTRY); + bs->single = NULL; + } wolfSSL_OCSP_RESPONSE_free(bs); bs = NULL; } diff --git a/src/ssl.c b/src/ssl.c index 6d7ef4f351b..061d328879a 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -7442,7 +7442,7 @@ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, #ifdef HAVE_PKCS8 /* if private key try and remove PKCS8 header */ - if (type == PRIVATEKEY_TYPE) { + if (ret == 0 && type == PRIVATEKEY_TYPE) { if ((ret = ToTraditional_ex(der->buffer, der->length, &algId)) > 0) { /* Found PKCS8 header */ @@ -8090,7 +8090,10 @@ static int ProcessChainBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, ret = ProcessBuffer(ctx, buff + used, sz - used, format, type, ssl, &consumed, 0, verify); - if (ret < 0) { + if (ret == MEMORY_E) { + return ret; + } + else if (ret < 0) { #if defined(WOLFSSL_WPAS) && defined(HAVE_CRL) DerBuffer* der = NULL; EncryptedInfo info; @@ -38547,7 +38550,7 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); } if (certData != NULL) { - XFREE(*cert, heap, DYNAMIC_TYPE_PKCS); *cert = NULL; + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); } /* Free up WC_DerCertList and move on */ while (current != NULL) { @@ -38661,6 +38664,7 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; } wolfSSL_X509_free(*cert); *cert = NULL; + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); ret = WOLFSSL_FAILURE; goto out; } diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 3075665dc5a..53503ee2d9a 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -623,7 +623,7 @@ static int wolfssl_asn1_integer_require_len(WOLFSSL_ASN1_INTEGER* a, int len, if ((!a->isDynamic) && (len > (int)a->dataMax)) { /* Create a new buffer to hold large integer value. */ data = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL); - if (a->data == NULL) { + if (data == NULL) { ret = 0; } else { diff --git a/src/x509.c b/src/x509.c index baf7e81588c..6f5e095d3c8 100644 --- a/src/x509.c +++ b/src/x509.c @@ -9007,9 +9007,6 @@ int wolfSSL_X509_ALGOR_set0(WOLFSSL_X509_ALGOR *algor, WOLFSSL_ASN1_OBJECT *aobj if (!algor) { return WOLFSSL_FAILURE; } - if (aobj) { - algor->algorithm = aobj; - } if (!algor->parameter) { algor->parameter = wolfSSL_ASN1_TYPE_new(); @@ -9018,6 +9015,9 @@ int wolfSSL_X509_ALGOR_set0(WOLFSSL_X509_ALGOR *algor, WOLFSSL_ASN1_OBJECT *aobj } } + if (aobj) { + algor->algorithm = aobj; + } wolfSSL_ASN1_TYPE_set(algor->parameter, ptype, pval); return WOLFSSL_SUCCESS; @@ -9991,8 +9991,8 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( { ret = wc_InitRng(&rng); if (ret != 0) { - XFREE(cert, NULL, DYNAMIC_TYPE_CERT); - return WOLFSSL_FAILURE; + ret = WOLFSSL_FAILURE; + goto cleanup; } ret = wc_MakeCert_ex(cert, der, *derSz, type, key, &rng); diff --git a/tests/api.c b/tests/api.c index a68bd1db8ab..a427e2de937 100644 --- a/tests/api.c +++ b/tests/api.c @@ -583,37 +583,39 @@ static int test_fileAccess(void) { int res = TEST_SKIPPED; #if defined(WOLFSSL_TEST_PLATFORMDEPEND) && !defined(NO_FILESYSTEM) + EXPECT_DECLS; const char *fname[] = { - svrCertFile, svrKeyFile, caCertFile, - eccCertFile, eccKeyFile, eccRsaCertFile, - cliCertFile, cliCertDerFile, cliKeyFile, - dhParamFile, - cliEccKeyFile, cliEccCertFile, caEccCertFile, edCertFile, edKeyFile, - cliEdCertFile, cliEdKeyFile, caEdCertFile, - NULL + svrCertFile, svrKeyFile, caCertFile, + eccCertFile, eccKeyFile, eccRsaCertFile, + cliCertFile, cliCertDerFile, cliKeyFile, + dhParamFile, + cliEccKeyFile, cliEccCertFile, caEccCertFile, edCertFile, edKeyFile, + cliEdCertFile, cliEdKeyFile, caEdCertFile, + NULL }; - const char derfile[] = "./certs/server-cert.der"; - XFILE f; + const char derfile[] = "./certs/server-cert.der"; + XFILE f = XBADFILE; size_t sz; - byte *buff; + byte *buff = NULL; int i; - AssertTrue(XFOPEN("badfilename", "rb") == XBADFILE); + ExpectTrue(XFOPEN("badfilename", "rb") == XBADFILE); for (i=0; fname[i] != NULL ; i++) { - AssertTrue((f = XFOPEN(fname[i], "rb")) != XBADFILE); + ExpectTrue((f = XFOPEN(fname[i], "rb")) != XBADFILE); XFCLOSE(f); } - AssertTrue((f = XFOPEN(derfile, "rb")) != XBADFILE); - AssertTrue(XFSEEK(f, 0, XSEEK_END) == 0); - sz = (size_t) XFTELL(f); - AssertTrue(XFSEEK(f, 0, XSEEK_SET) == 0); - AssertTrue(sz == sizeof_server_cert_der_2048); - AssertTrue((buff = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)) != NULL) ; - AssertTrue(XFREAD(buff, 1, sz, f) == sz); - XMEMCMP(server_cert_der_2048, buff, sz); + ExpectTrue((f = XFOPEN(derfile, "rb")) != XBADFILE); + ExpectTrue(XFSEEK(f, 0, XSEEK_END) == 0); + ExpectIntGE(sz = (size_t) XFTELL(f), sizeof_server_cert_der_2048); + ExpectTrue(XFSEEK(f, 0, XSEEK_SET) == 0); + ExpectTrue((buff = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)) != NULL); + ExpectTrue(XFREAD(buff, 1, sz, f) == sz); + ExpectIntEQ(XMEMCMP(server_cert_der_2048, buff, sz), 0); + XFREE(buff, NULL, DYNAMIC_TYPE_FILE); + XFCLOSE(f); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -624,18 +626,20 @@ static int test_fileAccess(void) static int test_wolfSSL_Method_Allocators(void) { + EXPECT_DECLS; + #define TEST_METHOD_ALLOCATOR(allocator, condition) \ do { \ - WOLFSSL_METHOD *method; \ + WOLFSSL_METHOD *method = NULL; \ condition(method = allocator()); \ XFREE(method, 0, DYNAMIC_TYPE_METHOD); \ - } while(0) + } while (0) #define TEST_VALID_METHOD_ALLOCATOR(a) \ - TEST_METHOD_ALLOCATOR(a, AssertNotNull) + TEST_METHOD_ALLOCATOR(a, ExpectNotNull) #define TEST_INVALID_METHOD_ALLOCATOR(a) \ - TEST_METHOD_ALLOCATOR(a, AssertNull) + TEST_METHOD_ALLOCATOR(a, ExpectNull) #ifndef NO_OLD_TLS #ifdef WOLFSSL_ALLOW_SSLV3 @@ -742,7 +746,7 @@ static int test_wolfSSL_Method_Allocators(void) #endif /* WOLFSSL_DTLS */ #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ - return TEST_SUCCESS; + return EXPECT_RESULT(); } @@ -752,16 +756,17 @@ static int test_wolfSSL_Method_Allocators(void) #ifndef NO_WOLFSSL_SERVER static int test_wolfSSL_CTX_new(void) { + EXPECT_DECLS; WOLFSSL_CTX *ctx; WOLFSSL_METHOD* method; - AssertNull(ctx = wolfSSL_CTX_new(NULL)); - AssertNotNull(method = wolfSSLv23_server_method()); - AssertNotNull(ctx = wolfSSL_CTX_new(method)); + ExpectNull(ctx = wolfSSL_CTX_new(NULL)); + ExpectNotNull(method = wolfSSLv23_server_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(method)); wolfSSL_CTX_free(ctx); - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } #endif @@ -769,8 +774,9 @@ static int test_wolfSSL_CTX_new(void) (!defined(NO_RSA) || defined(HAVE_ECC)) && !defined(NO_FILESYSTEM) static int test_for_double_Free(void) { - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; int skipTest = 0; const char* testCertFile; const char* testKeyFile; @@ -811,106 +817,112 @@ static int test_for_double_Free(void) #endif #ifndef NO_RSA - testCertFile = svrCertFile; - testKeyFile = svrKeyFile; + testCertFile = svrCertFile; + testKeyFile = svrKeyFile; #elif defined(HAVE_ECC) - testCertFile = eccCertFile; - testKeyFile = eccKeyFile; + testCertFile = eccCertFile; + testKeyFile = eccKeyFile; #else skipTest = 1; #endif if (skipTest != 1) { #ifndef NO_WOLFSSL_SERVER - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #else - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, WOLFSSL_FILETYPE_PEM)); - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, + WOLFSSL_FILETYPE_PEM)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); /* First test freeing SSL, then CTX */ wolfSSL_free(ssl); + ssl = NULL; wolfSSL_CTX_free(ctx); + ctx = NULL; #ifndef NO_WOLFSSL_CLIENT - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, WOLFSSL_FILETYPE_PEM)); - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, + WOLFSSL_FILETYPE_PEM)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); /* Next test freeing CTX then SSL */ wolfSSL_CTX_free(ctx); + ctx = NULL; wolfSSL_free(ssl); + ssl = NULL; #ifndef NO_WOLFSSL_SERVER - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #else - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #endif /* Test setting ciphers at ctx level */ - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_set_cipher_list(ctx, optionsCiphers)); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, + WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctx, optionsCiphers)); #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_TLS13) && defined(HAVE_AESGCM) && \ defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256) /* only update TLSv13 suites */ - AssertTrue(wolfSSL_CTX_set_cipher_list(ctx, "TLS13-AES256-GCM-SHA384")); + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctx, "TLS13-AES256-GCM-SHA384")); #endif #if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) && defined(HAVE_AESGCM) && \ !defined(NO_SHA256) && !defined(WOLFSSL_NO_TLS12) && \ defined(WOLFSSL_AES_128) && !defined(NO_RSA) /* only update pre-TLSv13 suites */ - AssertTrue(wolfSSL_CTX_set_cipher_list(ctx, "ECDHE-RSA-AES128-GCM-SHA256")); + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctx, + "ECDHE-RSA-AES128-GCM-SHA256")); #endif #ifdef OPENSSL_EXTRA - AssertTrue(wolfSSL_CTX_set_cipher_list(ctx, openvpnCiphers)); + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctx, openvpnCiphers)); #endif - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); wolfSSL_CTX_free(ctx); + ctx = NULL; wolfSSL_free(ssl); + ssl = NULL; #ifndef NO_WOLFSSL_CLIENT - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, WOLFSSL_FILETYPE_PEM)); - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, + WOLFSSL_FILETYPE_PEM)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); /* test setting ciphers at SSL level */ - AssertTrue(wolfSSL_set_cipher_list(ssl, optionsCiphers)); + ExpectTrue(wolfSSL_set_cipher_list(ssl, optionsCiphers)); #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_TLS13) && defined(HAVE_AESGCM) && \ defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256) /* only update TLSv13 suites */ - AssertTrue(wolfSSL_set_cipher_list(ssl, "TLS13-AES256-GCM-SHA384")); + ExpectTrue(wolfSSL_set_cipher_list(ssl, "TLS13-AES256-GCM-SHA384")); #endif #if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) && defined(HAVE_AESGCM) && \ !defined(NO_SHA256) && !defined(WOLFSSL_NO_TLS12) && \ defined(WOLFSSL_AES_128) && !defined(NO_RSA) /* only update pre-TLSv13 suites */ - AssertTrue(wolfSSL_set_cipher_list(ssl, "ECDHE-RSA-AES128-GCM-SHA256")); + ExpectTrue(wolfSSL_set_cipher_list(ssl, "ECDHE-RSA-AES128-GCM-SHA256")); #endif wolfSSL_CTX_free(ctx); + ctx = NULL; wolfSSL_free(ssl); + ssl = NULL; } - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } #endif @@ -921,10 +933,11 @@ static int test_wolfSSL_CTX_set_cipher_list_bytes(void) #if (defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)) && \ (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) && \ (!defined(NO_RSA) || defined(HAVE_ECC)) + EXPECT_DECLS; const char* testCertFile; const char* testKeyFile; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; const byte cipherList[] = { @@ -1077,41 +1090,37 @@ static int test_wolfSSL_CTX_set_cipher_list_bytes(void) #endif #ifndef NO_WOLFSSL_SERVER - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #else - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(wolfSSL_CTX_set_cipher_list_bytes(ctx, &cipherList[0U], + ExpectTrue(wolfSSL_CTX_set_cipher_list_bytes(ctx, &cipherList[0U], sizeof(cipherList))); wolfSSL_CTX_free(ctx); + ctx = NULL; #ifndef NO_WOLFSSL_SERVER - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #else - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, WOLFSSL_FILETYPE_PEM)); - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); + ExpectNotNull(ssl = wolfSSL_new(ctx)); - AssertTrue(wolfSSL_set_cipher_list_bytes(ssl, &cipherList[0U], + ExpectTrue(wolfSSL_set_cipher_list_bytes(ssl, &cipherList[0U], sizeof(cipherList))); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* (OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES) && (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && (!NO_RSA || HAVE_ECC) */ @@ -1123,30 +1132,33 @@ static int test_wolfSSL_CTX_use_certificate_file(void) { int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX *ctx; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); /* invalid context */ - AssertFalse(wolfSSL_CTX_use_certificate_file(NULL, svrCertFile, - WOLFSSL_FILETYPE_PEM)); + ExpectFalse(wolfSSL_CTX_use_certificate_file(NULL, svrCertFile, + WOLFSSL_FILETYPE_PEM)); /* invalid cert file */ - AssertFalse(wolfSSL_CTX_use_certificate_file(ctx, bogusFile, - WOLFSSL_FILETYPE_PEM)); + ExpectFalse(wolfSSL_CTX_use_certificate_file(ctx, bogusFile, + WOLFSSL_FILETYPE_PEM)); /* invalid cert type */ - AssertFalse(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, 9999)); + ExpectFalse(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, 9999)); #ifdef NO_RSA /* rsa needed */ - AssertFalse(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile,WOLFSSL_FILETYPE_PEM)); + ExpectFalse(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + WOLFSSL_FILETYPE_PEM)); #else /* success */ - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + WOLFSSL_FILETYPE_PEM)); #endif wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -1183,17 +1195,19 @@ static int test_wolfSSL_CTX_use_certificate_buffer(void) int res = TEST_SKIPPED; #if !defined(NO_CERTS) && defined(USE_CERT_BUFFERS_2048) && \ !defined(NO_RSA) && !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX* ctx; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; int ret; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); - ret = wolfSSL_CTX_use_certificate_buffer(ctx, server_cert_der_2048, - sizeof_server_cert_der_2048, WOLFSSL_FILETYPE_ASN1); + ExpectIntEQ(ret = wolfSSL_CTX_use_certificate_buffer(ctx, + server_cert_der_2048, sizeof_server_cert_der_2048, + WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(ret == WOLFSSL_SUCCESS); + res = EXPECT_RESULT(); #endif return res; @@ -1203,31 +1217,34 @@ static int test_wolfSSL_CTX_use_PrivateKey_file(void) { int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX *ctx; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); /* invalid context */ - AssertFalse(wolfSSL_CTX_use_PrivateKey_file(NULL, svrKeyFile, - WOLFSSL_FILETYPE_PEM)); + ExpectFalse(wolfSSL_CTX_use_PrivateKey_file(NULL, svrKeyFile, + WOLFSSL_FILETYPE_PEM)); /* invalid key file */ - AssertFalse(wolfSSL_CTX_use_PrivateKey_file(ctx, bogusFile, - WOLFSSL_FILETYPE_PEM)); + ExpectFalse(wolfSSL_CTX_use_PrivateKey_file(ctx, bogusFile, + WOLFSSL_FILETYPE_PEM)); /* invalid key type */ - AssertFalse(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, 9999)); + ExpectFalse(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, 9999)); /* success */ #ifdef NO_RSA /* rsa needed */ - AssertFalse(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); + ExpectFalse(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + WOLFSSL_FILETYPE_PEM)); #else /* success */ - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + WOLFSSL_FILETYPE_PEM)); #endif wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -1240,72 +1257,73 @@ static int test_wolfSSL_CTX_trust_peer_cert(void) int res = TEST_SKIPPED; #if !defined(NO_CERTS) && defined(WOLFSSL_TRUST_PEER_CERT) && \ !defined(NO_WOLFSSL_CLIENT) && !defined(NO_RSA) - WOLFSSL_CTX *ctx; - WOLFSSL* ssl; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL* ssl = NULL; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); #if !defined(NO_FILESYSTEM) /* invalid file */ - AssertIntNE(wolfSSL_CTX_trust_peer_cert(ctx, NULL, + ExpectIntNE(wolfSSL_CTX_trust_peer_cert(ctx, NULL, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); - AssertIntNE(wolfSSL_CTX_trust_peer_cert(ctx, bogusFile, + ExpectIntNE(wolfSSL_CTX_trust_peer_cert(ctx, bogusFile, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); - AssertIntNE(wolfSSL_CTX_trust_peer_cert(ctx, cliCertFile, + ExpectIntNE(wolfSSL_CTX_trust_peer_cert(ctx, cliCertFile, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* success */ - AssertIntEQ(wolfSSL_CTX_trust_peer_cert(ctx, cliCertFile, + ExpectIntEQ(wolfSSL_CTX_trust_peer_cert(ctx, cliCertFile, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); /* unload cert */ - AssertIntNE(wolfSSL_CTX_Unload_trust_peers(NULL), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_Unload_trust_peers(ctx), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_CTX_Unload_trust_peers(NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_Unload_trust_peers(ctx), WOLFSSL_SUCCESS); /* invalid file */ - AssertIntNE(wolfSSL_trust_peer_cert(ssl, NULL, + ExpectIntNE(wolfSSL_trust_peer_cert(ssl, NULL, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); - AssertIntNE(wolfSSL_trust_peer_cert(ssl, bogusFile, + ExpectIntNE(wolfSSL_trust_peer_cert(ssl, bogusFile, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); - AssertIntNE(wolfSSL_trust_peer_cert(ssl, cliCertFile, + ExpectIntNE(wolfSSL_trust_peer_cert(ssl, cliCertFile, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* success */ - AssertIntEQ(wolfSSL_trust_peer_cert(ssl, cliCertFile, + ExpectIntEQ(wolfSSL_trust_peer_cert(ssl, cliCertFile, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); #ifdef WOLFSSL_LOCAL_X509_STORE /* unload cert */ - AssertIntNE(wolfSSL_Unload_trust_peers(NULL), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_Unload_trust_peers(ssl), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_Unload_trust_peers(NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_Unload_trust_peers(ssl), WOLFSSL_SUCCESS); #endif #endif /* Test of loading certs from buffers */ /* invalid buffer */ - AssertIntNE(wolfSSL_CTX_trust_peer_buffer(ctx, NULL, -1, + ExpectIntNE(wolfSSL_CTX_trust_peer_buffer(ctx, NULL, -1, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* success */ #ifdef USE_CERT_BUFFERS_1024 - AssertIntEQ(wolfSSL_CTX_trust_peer_buffer(ctx, client_cert_der_1024, + ExpectIntEQ(wolfSSL_CTX_trust_peer_buffer(ctx, client_cert_der_1024, sizeof_client_cert_der_1024, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #endif #ifdef USE_CERT_BUFFERS_2048 - AssertIntEQ(wolfSSL_CTX_trust_peer_buffer(ctx, client_cert_der_2048, + ExpectIntEQ(wolfSSL_CTX_trust_peer_buffer(ctx, client_cert_der_2048, sizeof_client_cert_der_2048, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #endif /* unload cert */ - AssertIntNE(wolfSSL_CTX_Unload_trust_peers(NULL), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_Unload_trust_peers(ctx), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_CTX_Unload_trust_peers(NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_Unload_trust_peers(ctx), WOLFSSL_SUCCESS); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -1316,9 +1334,10 @@ static int test_wolfSSL_CTX_load_verify_locations(void) { int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_WOLFSSL_CLIENT) - WOLFSSL_CTX *ctx; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; #ifndef NO_RSA - WOLFSSL_CERT_MANAGER* cm; + WOLFSSL_CERT_MANAGER* cm = NULL; #ifdef PERSIST_CERT_CACHE int cacheSz; #endif @@ -1329,56 +1348,60 @@ static int test_wolfSSL_CTX_load_verify_locations(void) const char* load_expired_path = "./certs/test/expired"; #endif - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); /* invalid arguments */ - AssertIntEQ(wolfSSL_CTX_load_verify_locations(NULL, caCertFile, NULL), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_load_verify_locations(ctx, NULL, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(NULL, caCertFile, NULL), + WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, NULL, NULL), + WOLFSSL_FAILURE); /* invalid ca file */ - AssertIntEQ(wolfSSL_CTX_load_verify_locations(ctx, bogusFile, NULL), - WS_RETURN_CODE(WOLFSSL_BAD_FILE,WOLFSSL_FAILURE)); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, bogusFile, NULL), + WS_RETURN_CODE(WOLFSSL_BAD_FILE,WOLFSSL_FAILURE)); #if !defined(NO_WOLFSSL_DIR) && !defined(WOLFSSL_TIRTOS) && \ (defined(WOLFSSL_QT) && \ !(WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS & WOLFSSL_LOAD_FLAG_IGNORE_BAD_PATH_ERR)) /* invalid path */ - AssertIntEQ(wolfSSL_CTX_load_verify_locations(ctx, NULL, bogusFile), - WS_RETURN_CODE(BAD_PATH_ERROR,WOLFSSL_FAILURE)); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, NULL, bogusFile), + WS_RETURN_CODE(BAD_PATH_ERROR,WOLFSSL_FAILURE)); #endif /* load ca cert */ #ifdef NO_RSA - AssertIntEQ(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, NULL), - WS_RETURN_CODE(ASN_UNKNOWN_OID_E,WOLFSSL_FAILURE)); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, NULL), + WS_RETURN_CODE(ASN_UNKNOWN_OID_E,WOLFSSL_FAILURE)); #else /* Skip the following test without RSA certs. */ - AssertIntEQ(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, NULL), + WOLFSSL_SUCCESS); #ifdef PERSIST_CERT_CACHE /* Get cert cache size */ - cacheSz = wolfSSL_CTX_get_cert_cache_memsize(ctx); + ExpectIntGT(cacheSz = wolfSSL_CTX_get_cert_cache_memsize(ctx), 0); #endif /* Test unloading CA's */ - AssertIntEQ(wolfSSL_CTX_UnloadCAs(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_UnloadCAs(ctx), WOLFSSL_SUCCESS); #ifdef PERSIST_CERT_CACHE /* Verify no certs (result is less than cacheSz) */ - AssertIntGT(cacheSz, wolfSSL_CTX_get_cert_cache_memsize(ctx)); + ExpectIntGT(cacheSz, wolfSSL_CTX_get_cert_cache_memsize(ctx)); #endif /* load ca cert again */ - AssertIntEQ(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, NULL), + WOLFSSL_SUCCESS); /* Test getting CERT_MANAGER */ - AssertNotNull(cm = wolfSSL_CTX_GetCertManager(ctx)); + ExpectNotNull(cm = wolfSSL_CTX_GetCertManager(ctx)); /* Test unloading CA's using CM */ - AssertIntEQ(wolfSSL_CertManagerUnloadCAs(cm), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CertManagerUnloadCAs(cm), WOLFSSL_SUCCESS); #ifdef PERSIST_CERT_CACHE /* Verify no certs (result is less than cacheSz) */ - AssertIntGT(cacheSz, wolfSSL_CTX_get_cert_cache_memsize(ctx)); + ExpectIntGT(cacheSz, wolfSSL_CTX_get_cert_cache_memsize(ctx)); #endif #endif @@ -1386,41 +1409,43 @@ static int test_wolfSSL_CTX_load_verify_locations(void) /* Test loading CA certificates using a path */ #ifdef NO_RSA /* failure here okay since certs in external directory are RSA */ - AssertIntNE(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_certs_path, + ExpectIntNE(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_certs_path, WOLFSSL_LOAD_FLAG_PEM_CA_ONLY), WOLFSSL_SUCCESS); #else - AssertIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_certs_path, + ExpectIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_certs_path, WOLFSSL_LOAD_FLAG_PEM_CA_ONLY), WOLFSSL_SUCCESS); #endif /* Test loading path with no files */ - AssertIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_no_certs_path, - WOLFSSL_LOAD_FLAG_PEM_CA_ONLY), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, + load_no_certs_path, WOLFSSL_LOAD_FLAG_PEM_CA_ONLY), WOLFSSL_FAILURE); /* Test loading expired CA certificates */ #ifdef NO_RSA - AssertIntNE(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_expired_path, + ExpectIntNE(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, + load_expired_path, WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY | WOLFSSL_LOAD_FLAG_PEM_CA_ONLY), WOLFSSL_SUCCESS); #else - AssertIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_expired_path, + ExpectIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, + load_expired_path, WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY | WOLFSSL_LOAD_FLAG_PEM_CA_ONLY), WOLFSSL_SUCCESS); #endif /* Test loading CA certificates and ignoring all errors */ #ifdef NO_RSA - AssertIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_certs_path, + ExpectIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_certs_path, WOLFSSL_LOAD_FLAG_IGNORE_ERR), WOLFSSL_FAILURE); #else - AssertIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_certs_path, + ExpectIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, load_certs_path, WOLFSSL_LOAD_FLAG_IGNORE_ERR), WOLFSSL_SUCCESS); #endif #endif wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -1638,6 +1663,7 @@ static int test_wolfSSL_CertManagerCheckOCSPResponse(void) #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_APACHE_HTTPD) || \ defined(HAVE_LIGHTY) + EXPECT_DECLS; WOLFSSL_CERT_MANAGER* cm = NULL; /* Raw OCSP response bytes captured using the following setup: * - Run responder with @@ -1774,7 +1800,7 @@ static int test_wolfSSL_CertManagerCheckOCSPResponse(void) }; OcspEntry entry[1]; CertStatus status[1]; - OcspRequest* request; + OcspRequest* request = NULL; byte serial[] = {0x05}; byte issuerHash[] = {0x71, 0x4d, 0x82, 0x23, 0x40, 0x59, 0xc0, 0x96, 0xa1, 0x37, 0x43, 0xfa, 0x31, 0xdb, 0xba, 0xb1, 0x43, 0x18, 0xda, 0x04}; @@ -1784,36 +1810,38 @@ static int test_wolfSSL_CertManagerCheckOCSPResponse(void) XMEMSET(entry, 0, sizeof(OcspEntry)); XMEMSET(status, 0, sizeof(CertStatus)); - AssertNotNull(request = wolfSSL_OCSP_REQUEST_new()); - request->serial = (byte*)XMALLOC(sizeof(serial), NULL, - DYNAMIC_TYPE_OCSP_REQUEST); - AssertNotNull(request->serial); + ExpectNotNull(request = wolfSSL_OCSP_REQUEST_new()); + ExpectNotNull(request->serial = (byte*)XMALLOC(sizeof(serial), NULL, + DYNAMIC_TYPE_OCSP_REQUEST)); - request->serialSz = sizeof(serial); - XMEMCPY(request->serial, serial, sizeof(serial)); - XMEMCPY(request->issuerHash, issuerHash, sizeof(issuerHash)); - XMEMCPY(request->issuerKeyHash, issuerKeyHash, sizeof(issuerKeyHash)); + if ((request != NULL) && (request->serial != NULL)) { + request->serialSz = sizeof(serial); + XMEMCPY(request->serial, serial, sizeof(serial)); + XMEMCPY(request->issuerHash, issuerHash, sizeof(issuerHash)); + XMEMCPY(request->issuerKeyHash, issuerKeyHash, sizeof(issuerKeyHash)); + } - AssertNotNull(cm = wolfSSL_CertManagerNew_ex(NULL)); - AssertIntEQ(wolfSSL_CertManagerEnableOCSP(cm, 0), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CertManagerLoadCA(cm, + ExpectNotNull(cm = wolfSSL_CertManagerNew_ex(NULL)); + ExpectIntEQ(wolfSSL_CertManagerEnableOCSP(cm, 0), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CertManagerLoadCA(cm, "./certs/ocsp/intermediate1-ca-cert.pem", NULL), WOLFSSL_SUCCESS); /* Response should be valid. */ - AssertIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, response, + ExpectIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, response, sizeof(response), NULL, status, entry, request), WOLFSSL_SUCCESS); /* Flip a byte in the request serial number, response should be invalid * now. */ - request->serial[0] ^= request->serial[0]; - AssertIntNE(wolfSSL_CertManagerCheckOCSPResponse(cm, response, + if ((request != NULL) && (request->serial != NULL)) + request->serial[0] ^= request->serial[0]; + ExpectIntNE(wolfSSL_CertManagerCheckOCSPResponse(cm, response, sizeof(response), NULL, status, entry, request), WOLFSSL_SUCCESS); wolfSSL_OCSP_REQUEST_free(request); wolfSSL_CertManagerFree(cm); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY || * WOLFSSL_APACHE_HTTPD || HAVE_LIGHTY */ #endif /* HAVE_OCSP */ @@ -1824,60 +1852,62 @@ static int test_wolfSSL_CheckOCSPResponse(void) { int result = TEST_SKIPPED; #if defined(HAVE_OCSP) && !defined(NO_RSA) && defined(OPENSSL_ALL) + EXPECT_DECLS; const char* responseFile = "./certs/ocsp/test-response.der"; const char* responseMultiFile = "./certs/ocsp/test-multi-response.der"; - const char* responseNoInternFile = "./certs/ocsp/test-response-nointern.der"; + const char* responseNoInternFile = + "./certs/ocsp/test-response-nointern.der"; const char* caFile = "./certs/ocsp/root-ca-cert.pem"; OcspResponse* res = NULL; byte data[4096]; const unsigned char* pt; int dataSz; - XFILE f; - WOLFSSL_OCSP_BASICRESP* bs; - WOLFSSL_X509_STORE* st; - WOLFSSL_X509* issuer; + XFILE f = XBADFILE; + WOLFSSL_OCSP_BASICRESP* bs = NULL; + WOLFSSL_X509_STORE* st = NULL; + WOLFSSL_X509* issuer = NULL; - f = XFOPEN(responseFile, "rb"); - AssertTrue(f != XBADFILE); - dataSz = (word32)XFREAD(data, 1, sizeof(data), f); - AssertIntGT(dataSz, 0); + ExpectTrue((f = XFOPEN(responseFile, "rb")) != XBADFILE); + ExpectIntGT(dataSz = (word32)XFREAD(data, 1, sizeof(data), f), 0); XFCLOSE(f); + f = XBADFILE; pt = data; - res = wolfSSL_d2i_OCSP_RESPONSE(NULL, &pt, dataSz); - AssertNotNull(res); - issuer = wolfSSL_X509_load_certificate_file(caFile, SSL_FILETYPE_PEM); - AssertNotNull(issuer); - st = wolfSSL_X509_STORE_new(); - AssertNotNull(st); - AssertIntEQ(wolfSSL_X509_STORE_add_cert(st, issuer), WOLFSSL_SUCCESS); - bs = wolfSSL_OCSP_response_get1_basic(res); - AssertNotNull(bs); - AssertIntEQ(wolfSSL_OCSP_basic_verify(bs, NULL, st, 0), WOLFSSL_SUCCESS); + ExpectNotNull(res = wolfSSL_d2i_OCSP_RESPONSE(NULL, &pt, dataSz)); + ExpectNotNull(issuer = wolfSSL_X509_load_certificate_file(caFile, + SSL_FILETYPE_PEM)); + ExpectNotNull(st = wolfSSL_X509_STORE_new()); + ExpectIntEQ(wolfSSL_X509_STORE_add_cert(st, issuer), WOLFSSL_SUCCESS); + ExpectNotNull(bs = wolfSSL_OCSP_response_get1_basic(res)); + ExpectIntEQ(wolfSSL_OCSP_basic_verify(bs, NULL, st, 0), WOLFSSL_SUCCESS); wolfSSL_OCSP_BASICRESP_free(bs); + bs = NULL; wolfSSL_OCSP_RESPONSE_free(res); + res = NULL; wolfSSL_X509_STORE_free(st); + st = NULL; wolfSSL_X509_free(issuer); + issuer = NULL; /* check loading a response with optional certs */ - f = XFOPEN(responseNoInternFile, "rb"); - AssertTrue(f != XBADFILE); - dataSz = (word32)XFREAD(data, 1, sizeof(data), f); - AssertIntGT(dataSz, 0); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(responseNoInternFile, "rb")) != XBADFILE); + ExpectIntGT(dataSz = (word32)XFREAD(data, 1, sizeof(data), f), 0); + if (f != XBADFILE) + XFCLOSE(f); + f = XBADFILE; pt = data; - res = wolfSSL_d2i_OCSP_RESPONSE(NULL, &pt, dataSz); - AssertNotNull(res); + ExpectNotNull(res = wolfSSL_d2i_OCSP_RESPONSE(NULL, &pt, dataSz)); wolfSSL_OCSP_RESPONSE_free(res); + res = NULL; /* check loading a response with multiple certs */ { WOLFSSL_CERT_MANAGER* cm = NULL; - OcspEntry *entry; - CertStatus* status; - OcspRequest* request; + OcspEntry *entry = NULL; + CertStatus* status = NULL; + OcspRequest* request = NULL; byte serial1[] = {0x01}; byte serial[] = {0x02}; @@ -1893,63 +1923,72 @@ static int test_wolfSSL_CheckOCSPResponse(void) 0x7E, 0x72, 0x15, 0x21 }; - entry = (OcspEntry*)XMALLOC(sizeof(OcspEntry), NULL, - DYNAMIC_TYPE_OPENSSL); - AssertNotNull(entry); + ExpectNotNull(entry = (OcspEntry*)XMALLOC(sizeof(OcspEntry), NULL, + DYNAMIC_TYPE_OPENSSL)); - status = (CertStatus*)XMALLOC(sizeof(CertStatus), NULL, - DYNAMIC_TYPE_OPENSSL); - AssertNotNull(status); + ExpectNotNull(status = (CertStatus*)XMALLOC(sizeof(CertStatus), NULL, + DYNAMIC_TYPE_OPENSSL)); - XMEMSET(entry, 0, sizeof(OcspEntry)); - XMEMSET(status, 0, sizeof(CertStatus)); + if (entry != NULL) + XMEMSET(entry, 0, sizeof(OcspEntry)); + if (status != NULL) + XMEMSET(status, 0, sizeof(CertStatus)); - AssertNotNull(request = wolfSSL_OCSP_REQUEST_new()); - request->serial = (byte*)XMALLOC(sizeof(serial), NULL, - DYNAMIC_TYPE_OCSP_REQUEST); - AssertNotNull(request->serial); + ExpectNotNull(request = wolfSSL_OCSP_REQUEST_new()); + ExpectNotNull(request->serial = (byte*)XMALLOC(sizeof(serial), NULL, + DYNAMIC_TYPE_OCSP_REQUEST)); - request->serialSz = sizeof(serial); - XMEMCPY(request->serial, serial, sizeof(serial)); - XMEMCPY(request->issuerHash, issuerHash, sizeof(issuerHash)); - XMEMCPY(request->issuerKeyHash, issuerKeyHash, sizeof(issuerKeyHash)); + if (request != NULL && request->serial != NULL) { + request->serialSz = sizeof(serial); + XMEMCPY(request->serial, serial, sizeof(serial)); + XMEMCPY(request->issuerHash, issuerHash, sizeof(issuerHash)); + XMEMCPY(request->issuerKeyHash, issuerKeyHash, + sizeof(issuerKeyHash)); + } - AssertNotNull(cm = wolfSSL_CertManagerNew_ex(NULL)); - AssertIntEQ(wolfSSL_CertManagerEnableOCSP(cm, 0), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CertManagerLoadCA(cm, caFile, NULL), + ExpectNotNull(cm = wolfSSL_CertManagerNew_ex(NULL)); + ExpectIntEQ(wolfSSL_CertManagerEnableOCSP(cm, 0), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CertManagerLoadCA(cm, caFile, NULL), WOLFSSL_SUCCESS); - f = XFOPEN(responseMultiFile, "rb"); - AssertTrue(f != XBADFILE); - dataSz = (word32)XFREAD(data, 1, sizeof(data), f); - AssertIntGT(dataSz, 0); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(responseMultiFile, "rb")) != XBADFILE); + ExpectIntGT(dataSz = (word32)XFREAD(data, 1, sizeof(data), f), 0); + if (f != XBADFILE) + XFCLOSE(f); + f = XBADFILE; - AssertIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, data, + ExpectIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, data, dataSz, NULL, status, entry, request), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, data, + ExpectIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, data, dataSz, NULL, entry->status, entry, request), WOLFSSL_SUCCESS); - AssertNotNull(entry->status); + ExpectNotNull(entry->status); - XMEMCPY(request->serial, serial1, sizeof(serial1)); - AssertIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, data, + if (request != NULL && request->serial != NULL) + XMEMCPY(request->serial, serial1, sizeof(serial1)); + ExpectIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, data, dataSz, NULL, status, entry, request), WOLFSSL_SUCCESS); /* store both status's in the entry to check that "next" is not * overwritten */ - status->next = entry->status; - entry->status = status; + if (EXPECT_SUCCESS() && status != NULL && entry != NULL) { + status->next = entry->status; + entry->status = status; + } - XMEMCPY(request->serial, serial, sizeof(serial)); - AssertIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, data, + if (request != NULL && request->serial != NULL) + XMEMCPY(request->serial, serial, sizeof(serial)); + ExpectIntEQ(wolfSSL_CertManagerCheckOCSPResponse(cm, data, dataSz, NULL, entry->status, entry, request), WOLFSSL_SUCCESS); - AssertNotNull(entry->status->next); + ExpectNotNull(entry->status->next); /* compare the status found */ - AssertIntEQ(status->serialSz, entry->status->serialSz); - AssertIntEQ(XMEMCMP(status->serial, entry->status->serial, + ExpectIntEQ(status->serialSz, entry->status->serialSz); + ExpectIntEQ(XMEMCMP(status->serial, entry->status->serial, status->serialSz), 0); + if (status != NULL && entry != NULL && entry->status != status) { + XFREE(status, NULL, DYNAMIC_TYPE_OPENSSL); + } wolfSSL_OCSP_CERTID_free(entry); wolfSSL_OCSP_REQUEST_free(request); wolfSSL_CertManagerFree(cm); @@ -1960,25 +1999,22 @@ static int test_wolfSSL_CheckOCSPResponse(void) const char* responsePssFile = "./certs/ocsp/test-response-rsapss.der"; /* check loading a response with RSA-PSS signature */ - f = XFOPEN(responsePssFile, "rb"); - AssertTrue(f != XBADFILE); - dataSz = (word32)XFREAD(data, 1, sizeof(data), f); - AssertIntGT(dataSz, 0); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(responsePssFile, "rb")) != XBADFILE); + ExpectIntGT(dataSz = (word32)XFREAD(data, 1, sizeof(data), f), 0); + if (f != XBADFILE) + XFCLOSE(f); pt = data; - res = wolfSSL_d2i_OCSP_RESPONSE(NULL, &pt, dataSz); - AssertNotNull(res); + ExpectNotNull(res = wolfSSL_d2i_OCSP_RESPONSE(NULL, &pt, dataSz)); /* try to verify the response */ - issuer = wolfSSL_X509_load_certificate_file(caFile, SSL_FILETYPE_PEM); - AssertNotNull(issuer); - st = wolfSSL_X509_STORE_new(); - AssertNotNull(st); - AssertIntEQ(wolfSSL_X509_STORE_add_cert(st, issuer), WOLFSSL_SUCCESS); - bs = wolfSSL_OCSP_response_get1_basic(res); - AssertNotNull(bs); - AssertIntEQ(wolfSSL_OCSP_basic_verify(bs, NULL, st, 0), WOLFSSL_SUCCESS); + ExpectNotNull(issuer = wolfSSL_X509_load_certificate_file(caFile, + SSL_FILETYPE_PEM)); + ExpectNotNull(st = wolfSSL_X509_STORE_new()); + ExpectIntEQ(wolfSSL_X509_STORE_add_cert(st, issuer), WOLFSSL_SUCCESS); + ExpectNotNull(bs = wolfSSL_OCSP_response_get1_basic(res)); + ExpectIntEQ(wolfSSL_OCSP_basic_verify(bs, NULL, st, 0), + WOLFSSL_SUCCESS); wolfSSL_OCSP_BASICRESP_free(bs); wolfSSL_OCSP_RESPONSE_free(res); wolfSSL_X509_STORE_free(st); @@ -1986,7 +2022,7 @@ static int test_wolfSSL_CheckOCSPResponse(void) } #endif - result = TEST_RES_CHECK(1); + result = EXPECT_RESULT(); #endif /* HAVE_OCSP */ return result; } @@ -1995,34 +2031,32 @@ static int test_wolfSSL_CertManagerLoadCABuffer(void) { int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) + EXPECT_DECLS; const char* ca_cert = "./certs/ca-cert.pem"; const char* ca_expired_cert = "./certs/test/expired/expired-ca.pem"; int ret; ret = test_cm_load_ca_file(ca_cert); #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER) - AssertIntEQ(ret, WOLFSSL_FATAL_ERROR); + ExpectIntEQ(ret, WOLFSSL_FATAL_ERROR); #elif defined(NO_RSA) - AssertIntEQ(ret, ASN_UNKNOWN_OID_E); + ExpectIntEQ(ret, ASN_UNKNOWN_OID_E); #else - AssertIntEQ(ret, WOLFSSL_SUCCESS); + ExpectIntEQ(ret, WOLFSSL_SUCCESS); #endif ret = test_cm_load_ca_file(ca_expired_cert); #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER) - AssertIntEQ(ret, WOLFSSL_FATAL_ERROR); - res = TEST_RES_CHECK(ret == WOLFSSL_FATAL_ERROR); + ExpectIntEQ(ret, WOLFSSL_FATAL_ERROR); #elif defined(NO_RSA) - AssertIntEQ(ret, ASN_UNKNOWN_OID_E); - res = TEST_RES_CHECK(ret == ASN_UNKNOWN_OID_E); + ExpectIntEQ(ret, ASN_UNKNOWN_OID_E); #elif !(WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY) && \ !defined(OPENSSL_COMPATIBLE_DEFAULTS) && !defined(NO_ASN_TIME) - AssertIntEQ(ret, ASN_AFTER_DATE_E); - res = TEST_RES_CHECK(ret == ASN_AFTER_DATE_E); + ExpectIntEQ(ret, ASN_AFTER_DATE_E); #else - AssertIntEQ(ret, WOLFSSL_SUCCESS); - res = TEST_RES_CHECK(ret == WOLFSSL_SUCCESS); + ExpectIntEQ(ret, WOLFSSL_SUCCESS); #endif + res = EXPECT_RESULT(); #endif return res; @@ -2032,31 +2066,31 @@ static int test_wolfSSL_CertManagerLoadCABuffer_ex(void) { int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) + EXPECT_DECLS; const char* ca_cert = "./certs/ca-cert.pem"; const char* ca_expired_cert = "./certs/test/expired/expired-ca.pem"; int ret; ret = test_cm_load_ca_file_ex(ca_cert, WOLFSSL_LOAD_FLAG_NONE); #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER) - AssertIntEQ(ret, WOLFSSL_FATAL_ERROR); + ExpectIntEQ(ret, WOLFSSL_FATAL_ERROR); #elif defined(NO_RSA) - AssertIntEQ(ret, ASN_UNKNOWN_OID_E); + ExpectIntEQ(ret, ASN_UNKNOWN_OID_E); #else - AssertIntEQ(ret, WOLFSSL_SUCCESS); + ExpectIntEQ(ret, WOLFSSL_SUCCESS); #endif ret = test_cm_load_ca_file_ex(ca_expired_cert, WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY); #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER) - AssertIntEQ(ret, WOLFSSL_FATAL_ERROR); - res = TEST_RES_CHECK(ret == WOLFSSL_FATAL_ERROR); + ExpectIntEQ(ret, WOLFSSL_FATAL_ERROR); #elif defined(NO_RSA) - AssertIntEQ(ret, ASN_UNKNOWN_OID_E); - res = TEST_RES_CHECK(ret == ASN_UNKNOWN_OID_E); + ExpectIntEQ(ret, ASN_UNKNOWN_OID_E); #else - AssertIntEQ(ret, WOLFSSL_SUCCESS); - res = TEST_RES_CHECK(ret == WOLFSSL_SUCCESS); + ExpectIntEQ(ret, WOLFSSL_SUCCESS); #endif + + res = EXPECT_RESULT(); #endif return res; @@ -2069,7 +2103,7 @@ static int test_wolfSSL_CertManagerGetCerts(void) #if defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && \ defined(WOLFSSL_SIGNER_DER_CERT) - + EXPECT_DECLS; WOLFSSL_CERT_MANAGER* cm = NULL; WOLFSSL_STACK* sk = NULL; X509* x509 = NULL; @@ -2083,32 +2117,36 @@ static int test_wolfSSL_CertManagerGetCerts(void) const byte* der; int derSz = 0; - AssertNotNull(file1=fopen("./certs/ca-cert.pem", "rb")); + ExpectNotNull(file1 = fopen("./certs/ca-cert.pem", "rb")); - AssertNotNull(cert1 = wolfSSL_PEM_read_X509(file1, NULL, NULL, NULL)); - fclose(file1); + ExpectNotNull(cert1 = wolfSSL_PEM_read_X509(file1, NULL, NULL, NULL)); + if (file1 != NULL) { + fclose(file1); + } - AssertNotNull(cm = wolfSSL_CertManagerNew_ex(NULL)); - AssertNull(sk = wolfSSL_CertManagerGetCerts(cm)); + ExpectNotNull(cm = wolfSSL_CertManagerNew_ex(NULL)); + ExpectNull(sk = wolfSSL_CertManagerGetCerts(cm)); - AssertNotNull(der = wolfSSL_X509_get_der(cert1, &derSz)); - ret = wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1); + ExpectNotNull(der = wolfSSL_X509_get_der(cert1, &derSz)); + ExpectIntEQ(ret = wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + WOLFSSL_FILETYPE_ASN1), #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) /* Check that ASN_SELF_SIGNED_E is returned for a self-signed cert for QT * and full OpenSSL compatibility */ - AssertIntEQ(ret, ASN_SELF_SIGNED_E); + ASN_SELF_SIGNED_E #else - AssertIntEQ(ret, ASN_NO_SIGNER_E); + ASN_NO_SIGNER_E #endif + ); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCA(cm, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCA(cm, "./certs/ca-cert.pem", NULL)); - AssertNotNull(sk = wolfSSL_CertManagerGetCerts(cm)); + ExpectNotNull(sk = wolfSSL_CertManagerGetCerts(cm)); for (i = 0; i < sk_X509_num(sk); i++) { - x509 = sk_X509_value(sk, i); - AssertIntEQ(0, wolfSSL_X509_cmp(x509, cert1)); + ExpectNotNull(x509 = sk_X509_value(sk, i)); + ExpectIntEQ(0, wolfSSL_X509_cmp(x509, cert1)); #ifdef DEBUG_WOLFSSL_VERBOSE bio = BIO_new(wolfSSL_BIO_s_file()); @@ -2123,7 +2161,7 @@ static int test_wolfSSL_CertManagerGetCerts(void) sk_X509_pop_free(sk, NULL); wolfSSL_CertManagerFree(cm); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && \ defined(WOLFSSL_SIGNER_DER_CERT) */ @@ -2137,28 +2175,29 @@ static int test_wolfSSL_CertManagerSetVerify(void) #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && \ !defined(NO_WOLFSSL_CM_VERIFY) && !defined(NO_RSA) && \ (!defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)) + EXPECT_DECLS; int ret = 0; - WOLFSSL_CERT_MANAGER* cm; + WOLFSSL_CERT_MANAGER* cm = NULL; int tmp = myVerifyAction; const char* ca_cert = "./certs/ca-cert.pem"; const char* expiredCert = "./certs/test/expired/expired-cert.pem"; - cm = wolfSSL_CertManagerNew(); - AssertNotNull(cm); + ExpectNotNull(cm = wolfSSL_CertManagerNew()); wolfSSL_CertManagerSetVerify(cm, myVerify); - ret = wolfSSL_CertManagerLoadCA(cm, ca_cert, NULL); + ExpectIntEQ(ret = wolfSSL_CertManagerLoadCA(cm, ca_cert, NULL), #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER) - AssertIntEQ(ret, -1); + -1 #else - AssertIntEQ(ret, WOLFSSL_SUCCESS); + WOLFSSL_SUCCESS #endif + ); /* Use the test CB that always accepts certs */ myVerifyAction = VERIFY_OVERRIDE_ERROR; - ret = wolfSSL_CertManagerVerify(cm, expiredCert, WOLFSSL_FILETYPE_PEM); - AssertIntEQ(ret, WOLFSSL_SUCCESS); + ExpectIntEQ(ret = wolfSSL_CertManagerVerify(cm, expiredCert, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); #ifdef WOLFSSL_ALWAYS_VERIFY_CB { @@ -2166,15 +2205,15 @@ static int test_wolfSSL_CertManagerSetVerify(void) /* Use the test CB that always fails certs */ myVerifyAction = VERIFY_FORCE_FAIL; - ret = wolfSSL_CertManagerVerify(cm, verifyCert, WOLFSSL_FILETYPE_PEM); - AssertIntEQ(ret, VERIFY_CERT_ERROR); + ExpectIntEQ(ret = wolfSSL_CertManagerVerify(cm, verifyCert, + WOLFSSL_FILETYPE_PEM), VERIFY_CERT_ERROR); } #endif wolfSSL_CertManagerFree(cm); myVerifyAction = tmp; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -2214,9 +2253,10 @@ static int test_wolfSSL_CertManagerNameConstraint(void) defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_ALT_NAMES) && \ !defined(NO_SHA256) - WOLFSSL_CERT_MANAGER* cm; - WOLFSSL_EVP_PKEY *priv; - WOLFSSL_X509_NAME* name; + EXPECT_DECLS; + WOLFSSL_CERT_MANAGER* cm = NULL; + WOLFSSL_EVP_PKEY *priv = NULL; + WOLFSSL_X509_NAME* name = NULL; const char* ca_cert = "./certs/test/cert-ext-nc.der"; const char* server_cert = "./certs/test/server-goodcn.pem"; int i = 0; @@ -2224,53 +2264,56 @@ static int test_wolfSSL_CertManagerNameConstraint(void) RsaKey key; WC_RNG rng; - byte *der; - int derSz; + byte *der = NULL; + int derSz = 0; word32 idx = 0; byte *pt; - WOLFSSL_X509 *x509, *ca; + WOLFSSL_X509 *x509 = NULL; + WOLFSSL_X509 *ca = NULL; wc_InitRng(&rng); /* load in CA private key for signing */ - AssertIntEQ(wc_InitRsaKey_ex(&key, HEAP_HINT, testDevId), 0); - AssertIntEQ(wc_RsaPrivateKeyDecode(server_key_der_2048, &idx, &key, + ExpectIntEQ(wc_InitRsaKey_ex(&key, HEAP_HINT, testDevId), 0); + ExpectIntEQ(wc_RsaPrivateKeyDecode(server_key_der_2048, &idx, &key, sizeof_server_key_der_2048), 0); /* get ca certificate then alter it */ - AssertNotNull(der = + ExpectNotNull(der = (byte*)XMALLOC(FOURK_BUF, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER)); - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(ca_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(ca_cert, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull(pt = (byte*)wolfSSL_X509_get_tbs(x509, &derSz)); - XMEMCPY(der, pt, derSz); + ExpectNotNull(pt = (byte*)wolfSSL_X509_get_tbs(x509, &derSz)); + if (der != NULL) { + XMEMCPY(der, pt, derSz); - /* find the name constraint extension and alter it */ - pt = der; - for (i = 0; i < derSz - 3; i++) { - if (XMEMCMP(pt, extNameConsOid, 3) == 0) { - pt += 3; - break; + /* find the name constraint extension and alter it */ + pt = der; + for (i = 0; i < derSz - 3; i++) { + if (XMEMCMP(pt, extNameConsOid, 3) == 0) { + pt += 3; + break; + } + pt++; } - pt++; - } - AssertIntNE(i, derSz - 3); /* did not find OID if this case is hit */ + ExpectIntNE(i, derSz - 3); /* did not find OID if this case is hit */ - /* go to the length value and set it to 0 */ - while (i < derSz && *pt != 0x81) { + /* go to the length value and set it to 0 */ + while (i < derSz && *pt != 0x81) { + pt++; + i++; + } + ExpectIntNE(i, derSz); /* did not place to alter */ pt++; - i++; + *pt = 0x00; } - AssertIntNE(i, derSz); /* did not place to alter */ - pt++; - *pt = 0x00; /* resign the altered certificate */ - AssertIntGT((derSz = wc_SignCert(derSz, CTC_SHA256wRSA, der, + ExpectIntGT((derSz = wc_SignCert(derSz, CTC_SHA256wRSA, der, FOURK_BUF, &key, NULL, &rng)), 0); - AssertNotNull(cm = wolfSSL_CertManagerNew()); - AssertIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_PARSE_E); wolfSSL_CertManagerFree(cm); @@ -2281,70 +2324,74 @@ static int test_wolfSSL_CertManagerNameConstraint(void) /* add email alt name to satisfy constraint */ pt = (byte*)server_key_der_2048; - AssertNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, + ExpectNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, (const unsigned char**)&pt, sizeof_server_key_der_2048)); - AssertNotNull(cm = wolfSSL_CertManagerNew()); - AssertNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(ca, &derSz))); + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(ca, &derSz))); DEBUG_WRITE_DER(der, derSz, "ca.der"); - AssertIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* Good cert test with proper alt email name */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, - (byte*)"support@info.wolfssl.com", 24, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, + (byte*)"support@info.wolfssl.com", 24, -1, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "wolfssl@info.wolfssl.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "good-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); + x509 = NULL; /* Cert with bad alt name list */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, - (byte*)"support@info.wolfssl.com", 24, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, + (byte*)"support@info.wolfssl.com", 24, -1, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); wolfSSL_X509_add_altname(x509, "wolfssl@info.com", ASN_RFC822_TYPE); wolfSSL_X509_add_altname(x509, "wolfssl@info.wolfssl.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "bad-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); wolfSSL_CertManagerFree(cm); @@ -2352,7 +2399,7 @@ static int test_wolfSSL_CertManagerNameConstraint(void) wolfSSL_X509_free(ca); wolfSSL_EVP_PKEY_free(priv); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -2366,17 +2413,19 @@ static int test_wolfSSL_CertManagerNameConstraint2(void) !defined(NO_WOLFSSL_CM_VERIFY) && !defined(NO_RSA) && \ defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_ALT_NAMES) + EXPECT_DECLS; const char* ca_cert = "./certs/test/cert-ext-ndir.der"; const char* ca_cert2 = "./certs/test/cert-ext-ndir-exc.der"; const char* server_cert = "./certs/server-cert.pem"; - WOLFSSL_CERT_MANAGER* cm; - WOLFSSL_X509 *x509, *ca; + WOLFSSL_CERT_MANAGER* cm = NULL; + WOLFSSL_X509 *x509 = NULL; + WOLFSSL_X509 *ca = NULL; - const unsigned char *der; + const unsigned char *der = NULL; const unsigned char *pt; - WOLFSSL_EVP_PKEY *priv; - WOLFSSL_X509_NAME* name; - int derSz; + WOLFSSL_EVP_PKEY *priv = NULL; + WOLFSSL_X509_NAME* name = NULL; + int derSz = 0; /* C=US*/ char altName[] = { @@ -2401,27 +2450,27 @@ static int test_wolfSSL_CertManagerNameConstraint2(void) }; /* load in CA private key for signing */ pt = ca_key_der_2048; - AssertNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, &pt, + ExpectNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, &pt, sizeof_ca_key_der_2048)); - AssertNotNull(cm = wolfSSL_CertManagerNew()); - AssertNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull((der = wolfSSL_X509_get_der(ca, &derSz))); - AssertIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, + ExpectNotNull((der = wolfSSL_X509_get_der(ca, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) wolfSSL_X509_sign(x509, priv, EVP_sha3_256()); #else wolfSSL_X509_sign(x509, priv, EVP_sha256()); #endif - AssertNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* add in matching DIR alt name and resign */ @@ -2432,16 +2481,17 @@ static int test_wolfSSL_CertManagerNameConstraint2(void) wolfSSL_X509_sign(x509, priv, EVP_sha256()); #endif - AssertNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); + x509 = NULL; /* check verify fail */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); /* add in miss matching DIR alt name and resign */ wolfSSL_X509_add_altname_ex(x509, altNameFail, sizeof(altNameFail), @@ -2452,22 +2502,23 @@ static int test_wolfSSL_CertManagerNameConstraint2(void) #else wolfSSL_X509_sign(x509, priv, EVP_sha256()); #endif - AssertNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); + ExpectNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); #ifndef WOLFSSL_NO_ASN_STRICT - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); #else - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #endif /* check that it still fails if one bad altname and one good altname is in * the certificate */ wolfSSL_X509_free(x509); - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + x509 = NULL; + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); wolfSSL_X509_add_altname_ex(x509, altName, sizeof(altName), ASN_DIR_TYPE); wolfSSL_X509_add_altname_ex(x509, altNameFail, sizeof(altNameFail), ASN_DIR_TYPE); @@ -2477,21 +2528,22 @@ static int test_wolfSSL_CertManagerNameConstraint2(void) #else wolfSSL_X509_sign(x509, priv, EVP_sha256()); #endif - AssertNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); + ExpectNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); #ifndef WOLFSSL_NO_ASN_STRICT - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); #else - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #endif /* check it fails with switching position of bad altname */ wolfSSL_X509_free(x509); - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + x509 = NULL; + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); wolfSSL_X509_add_altname_ex(x509, altNameFail, sizeof(altNameFail), ASN_DIR_TYPE); wolfSSL_X509_add_altname_ex(x509, altName, sizeof(altName), ASN_DIR_TYPE); @@ -2501,45 +2553,47 @@ static int test_wolfSSL_CertManagerNameConstraint2(void) #else wolfSSL_X509_sign(x509, priv, EVP_sha256()); #endif - AssertNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); + ExpectNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); #ifndef WOLFSSL_NO_ASN_STRICT - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); #else - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #endif wolfSSL_CertManagerFree(cm); wolfSSL_X509_free(x509); + x509 = NULL; wolfSSL_X509_free(ca); + ca = NULL; /* now test with excluded name constraint */ - AssertNotNull(cm = wolfSSL_CertManagerNew()); - AssertNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert2, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert2, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull((der = wolfSSL_X509_get_der(ca, &derSz))); - AssertIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, + ExpectNotNull((der = wolfSSL_X509_get_der(ca, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); wolfSSL_X509_add_altname_ex(x509, altNameExc, sizeof(altNameExc), ASN_DIR_TYPE); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) wolfSSL_X509_sign(x509, priv, EVP_sha3_256()); #else wolfSSL_X509_sign(x509, priv, EVP_sha256()); #endif - AssertNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); + ExpectNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); #ifndef WOLFSSL_NO_ASN_STRICT - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); #else - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #endif wolfSSL_CertManagerFree(cm); @@ -2547,7 +2601,7 @@ static int test_wolfSSL_CertManagerNameConstraint2(void) wolfSSL_X509_free(ca); wolfSSL_EVP_PKEY_free(priv); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -2561,105 +2615,114 @@ static int test_wolfSSL_CertManagerNameConstraint3(void) defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_ALT_NAMES) && \ !defined(NO_SHA256) - WOLFSSL_CERT_MANAGER* cm; - WOLFSSL_EVP_PKEY *priv; - WOLFSSL_X509_NAME* name; + EXPECT_DECLS; + WOLFSSL_CERT_MANAGER* cm = NULL; + WOLFSSL_EVP_PKEY *priv = NULL; + WOLFSSL_X509_NAME* name = NULL; const char* ca_cert = "./certs/test/cert-ext-mnc.der"; const char* server_cert = "./certs/test/server-goodcn.pem"; - byte *der; - int derSz; + byte *der = NULL; + int derSz = 0; byte *pt; - WOLFSSL_X509 *x509, *ca; + WOLFSSL_X509 *x509 = NULL; + WOLFSSL_X509 *ca = NULL; pt = (byte*)server_key_der_2048; - AssertNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, + ExpectNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, (const unsigned char**)&pt, sizeof_server_key_der_2048)); - AssertNotNull(cm = wolfSSL_CertManagerNew()); - AssertNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(ca, &derSz))); + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(ca, &derSz))); DEBUG_WRITE_DER(der, derSz, "ca.der"); - AssertIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* check satisfying .wolfssl.com constraint passes */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, - (byte*)"support@info.wolfssl.com", 24, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, + (byte*)"support@info.wolfssl.com", 24, -1, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "wolfssl@info.wolfssl.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "good-1st-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); + x509 = NULL; /* check satisfying .random.com constraint passes */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, - (byte*)"support@info.example.com", 24, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, + (byte*)"support@info.example.com", 24, -1, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "wolfssl@info.example.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "good-2nd-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); + x509 = NULL; /* check fail case when neither constraint is matched */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, (byte*)"support@info.com", 16, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); wolfSSL_X509_add_altname(x509, "wolfssl@info.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "bad-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); wolfSSL_CertManagerFree(cm); @@ -2667,7 +2730,7 @@ static int test_wolfSSL_CertManagerNameConstraint3(void) wolfSSL_X509_free(ca); wolfSSL_EVP_PKEY_free(priv); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -2681,146 +2744,161 @@ static int test_wolfSSL_CertManagerNameConstraint4(void) defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_ALT_NAMES) && \ !defined(NO_SHA256) - WOLFSSL_CERT_MANAGER* cm; - WOLFSSL_EVP_PKEY *priv; - WOLFSSL_X509_NAME* name; + EXPECT_DECLS; + WOLFSSL_CERT_MANAGER* cm = NULL; + WOLFSSL_EVP_PKEY *priv = NULL; + WOLFSSL_X509_NAME* name = NULL; const char* ca_cert = "./certs/test/cert-ext-ncdns.der"; const char* server_cert = "./certs/test/server-goodcn.pem"; - byte *der; + byte *der = NULL; int derSz; byte *pt; - WOLFSSL_X509 *x509, *ca; + WOLFSSL_X509 *x509 = NULL; + WOLFSSL_X509 *ca = NULL; pt = (byte*)server_key_der_2048; - AssertNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, + ExpectNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, (const unsigned char**)&pt, sizeof_server_key_der_2048)); - AssertNotNull(cm = wolfSSL_CertManagerNew()); - AssertNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(ca, &derSz))); + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(ca, &derSz))); DEBUG_WRITE_DER(der, derSz, "ca.der"); - AssertIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* check satisfying wolfssl.com constraint passes */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "www.wolfssl.com", ASN_DNS_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "good-1st-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); + x509 = NULL; /* check satisfying example.com constraint passes */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"example.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "www.example.com", ASN_DNS_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "good-2nd-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); + x509 = NULL; /* check satisfying wolfssl.com constraint passes with list of DNS's */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "www.wolfssl.com", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "www.info.wolfssl.com", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "extra.wolfssl.com", ASN_DNS_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "good-multiple-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); + x509 = NULL; /* check fail when one DNS in the list is bad */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "www.wolfssl.com", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "www.nomatch.com", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "www.info.wolfssl.com", ASN_DNS_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "bad-multiple-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); wolfSSL_X509_free(x509); + x509 = NULL; /* check fail case when neither constraint is matched */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"common", 6, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); wolfSSL_X509_add_altname(x509, "www.random.com", ASN_DNS_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "bad-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); wolfSSL_CertManagerFree(cm); @@ -2828,7 +2906,7 @@ static int test_wolfSSL_CertManagerNameConstraint4(void) wolfSSL_X509_free(ca); wolfSSL_EVP_PKEY_free(priv); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -2842,142 +2920,157 @@ static int test_wolfSSL_CertManagerNameConstraint5(void) defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_ALT_NAMES) && \ !defined(NO_SHA256) - WOLFSSL_CERT_MANAGER* cm; - WOLFSSL_EVP_PKEY *priv; - WOLFSSL_X509_NAME* name; + EXPECT_DECLS; + WOLFSSL_CERT_MANAGER* cm = NULL; + WOLFSSL_EVP_PKEY *priv = NULL; + WOLFSSL_X509_NAME* name = NULL; const char* ca_cert = "./certs/test/cert-ext-ncmixed.der"; const char* server_cert = "./certs/test/server-goodcn.pem"; - byte *der; + byte *der = NULL; int derSz; byte *pt; - WOLFSSL_X509 *x509, *ca; + WOLFSSL_X509 *x509 = NULL; + WOLFSSL_X509 *ca = NULL; pt = (byte*)server_key_der_2048; - AssertNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, + ExpectNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, (const unsigned char**)&pt, sizeof_server_key_der_2048)); - AssertNotNull(cm = wolfSSL_CertManagerNew()); - AssertNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectNotNull(ca = wolfSSL_X509_load_certificate_file(ca_cert, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(ca, &derSz))); + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(ca, &derSz))); DEBUG_WRITE_DER(der, derSz, "ca.der"); - AssertIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, + ExpectIntEQ(wolfSSL_CertManagerLoadCABuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* check satisfying wolfssl.com constraint passes */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"example", 7, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "good.example", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "facts@into.wolfssl.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "good-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); + x509 = NULL; /* fail with DNS check because of common name */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "example", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "facts@wolfssl.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "bad-cn-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); wolfSSL_X509_free(x509); + x509 = NULL; /* fail on permitted DNS name constraint */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "www.example", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "www.wolfssl", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "info@wolfssl.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "bad-1st-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); wolfSSL_X509_free(x509); + x509 = NULL; /* fail on permitted email name constraint */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); + name = NULL; wolfSSL_X509_add_altname(x509, "example", ASN_DNS_TYPE); wolfSSL_X509_add_altname(x509, "info@wolfssl.com", ASN_RFC822_TYPE); wolfSSL_X509_add_altname(x509, "info@example.com", ASN_RFC822_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "bad-2nd-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), ASN_NAME_INVALID_E); wolfSSL_X509_free(x509); + x509 = NULL; /* success with empty email name */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(server_cert, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); X509_NAME_free(name); wolfSSL_X509_add_altname(x509, "example", ASN_DNS_TYPE); - AssertIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); DEBUG_WRITE_CERT_X509(x509, "good-missing-constraint-cert.pem"); - AssertNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + ExpectNotNull((der = (byte*)wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntEQ(wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_X509_free(x509); @@ -2995,37 +3088,37 @@ static int test_wolfSSL_FPKI(void) { int res = TEST_SKIPPED; #if defined(WOLFSSL_FPKI) && !defined(NO_RSA) && !defined(NO_FILESYSTEM) - XFILE f; + EXPECT_DECLS; + XFILE f = XBADFILE; const char* fpkiCert = "./certs/fpki-cert.der"; DecodedCert cert; byte buf[4096]; - byte* uuid; - byte* fascn; + byte* uuid = NULL; + byte* fascn = NULL; word32 fascnSz; word32 uuidSz; - int bytes; + int bytes = 0; - f = XFOPEN(fpkiCert, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(fpkiCert, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) + XFCLOSE(f); wc_InitDecodedCert(&cert, buf, bytes, NULL); - AssertIntEQ(wc_ParseCert(&cert, CERT_TYPE, 0, NULL), 0); - AssertIntEQ(wc_GetFASCNFromCert(&cert, NULL, &fascnSz), LENGTH_ONLY_E) ; - fascn = (byte*)XMALLOC(fascnSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); - AssertNotNull(fascn); - AssertIntEQ(wc_GetFASCNFromCert(&cert, fascn, &fascnSz), 0); + ExpectIntEQ(wc_ParseCert(&cert, CERT_TYPE, 0, NULL), 0); + ExpectIntEQ(wc_GetFASCNFromCert(&cert, NULL, &fascnSz), LENGTH_ONLY_E) ; + ExpectNotNull(fascn = (byte*)XMALLOC(fascnSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER)); + ExpectIntEQ(wc_GetFASCNFromCert(&cert, fascn, &fascnSz), 0); XFREE(fascn, NULL, DYNAMIC_TYPE_TMP_BUFFER); - AssertIntEQ(wc_GetUUIDFromCert(&cert, NULL, &uuidSz), LENGTH_ONLY_E); - uuid = (byte*)XMALLOC(uuidSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); - AssertNotNull(uuid); - AssertIntEQ(wc_GetUUIDFromCert(&cert, uuid, &uuidSz), 0); + ExpectIntEQ(wc_GetUUIDFromCert(&cert, NULL, &uuidSz), LENGTH_ONLY_E); + ExpectNotNull(uuid = (byte*)XMALLOC(uuidSz, NULL, DYNAMIC_TYPE_TMP_BUFFER)); + ExpectIntEQ(wc_GetUUIDFromCert(&cert, uuid, &uuidSz), 0); XFREE(uuid, NULL, DYNAMIC_TYPE_TMP_BUFFER); wc_FreeDecodedCert(&cert); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3037,22 +3130,23 @@ static int test_wolfSSL_OtherName(void) { int res = TEST_SKIPPED; #if !defined(NO_RSA) && !defined(NO_FILESYSTEM) - XFILE f; + EXPECT_DECLS; + XFILE f = XBADFILE; const char* ridCert = "./certs/rid-cert.der"; DecodedCert cert; byte buf[4096]; - int bytes; + int bytes = 0; - f = XFOPEN(ridCert, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(ridCert, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) + XFCLOSE(f); wc_InitDecodedCert(&cert, buf, bytes, NULL); - AssertIntEQ(wc_ParseCert(&cert, CERT_TYPE, 0, NULL), 0); + ExpectIntEQ(wc_ParseCert(&cert, CERT_TYPE, 0, NULL), 0); wc_FreeDecodedCert(&cert); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3066,7 +3160,8 @@ static int test_wolfSSL_CertRsaPss(void) (!defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ (HAVE_FIPS_VERSION > 2))) && (!defined(HAVE_SELFTEST) || \ (defined(HAVE_SELFTEST_VERSION) && (HAVE_SELFTEST_VERSION > 2))) - XFILE f; + EXPECT_DECLS; + XFILE f = XBADFILE; const char* rsaPssSha256Cert = "./certs/rsapss/ca-rsapss.der"; const char* rsaPssRootSha256Cert = "./certs/rsapss/root-rsapss.pem"; #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_PSS_LONG_SALT) && \ @@ -3078,40 +3173,41 @@ static int test_wolfSSL_CertRsaPss(void) #endif DecodedCert cert; byte buf[4096]; - int bytes; - WOLFSSL_CERT_MANAGER* cm; + int bytes = 0; + WOLFSSL_CERT_MANAGER* cm = NULL; - cm = wolfSSL_CertManagerNew(); - AssertNotNull(cm); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCA(cm, rsaPssRootSha256Cert, NULL)); #if defined(WOLFSSL_SHA384) && RSA_MAX_SIZE >= 3072 - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCA(cm, rsaPssRootSha384Cert, NULL)); #endif - f = XFOPEN(rsaPssSha256Cert, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(rsaPssSha256Cert, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } wc_InitDecodedCert(&cert, buf, bytes, NULL); - AssertIntEQ(wc_ParseCert(&cert, CERT_TYPE, VERIFY, cm), 0); + ExpectIntEQ(wc_ParseCert(&cert, CERT_TYPE, VERIFY, cm), 0); wc_FreeDecodedCert(&cert); #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_PSS_LONG_SALT) && \ RSA_MAX_SIZE >= 3072 - f = XFOPEN(rsaPssSha384Cert, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(rsaPssSha384Cert, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) + XFCLOSE(f); wc_InitDecodedCert(&cert, buf, bytes, NULL); - AssertIntEQ(wc_ParseCert(&cert, CERT_TYPE, VERIFY, cm), 0); + ExpectIntEQ(wc_ParseCert(&cert, CERT_TYPE, VERIFY, cm), 0); wc_FreeDecodedCert(&cert); #endif wolfSSL_CertManagerFree(cm); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3122,29 +3218,29 @@ static int test_wolfSSL_CertManagerCRL(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && defined(HAVE_CRL) && \ !defined(NO_RSA) - + EXPECT_DECLS; const char* ca_cert = "./certs/ca-cert.pem"; const char* crl1 = "./certs/crl/crl.pem"; const char* crl2 = "./certs/crl/crl2.pem"; WOLFSSL_CERT_MANAGER* cm = NULL; - AssertNotNull(cm = wolfSSL_CertManagerNew()); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectNotNull(cm = wolfSSL_CertManagerNew()); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCA(cm, ca_cert, NULL)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCRL(cm, crl1, WOLFSSL_FILETYPE_PEM, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCRL(cm, crl2, WOLFSSL_FILETYPE_PEM, 0)); wolfSSL_CertManagerFreeCRL(cm); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCRL(cm, crl1, WOLFSSL_FILETYPE_PEM, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCA(cm, ca_cert, NULL)); wolfSSL_CertManagerFree(cm); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3155,31 +3251,32 @@ static int test_wolfSSL_CTX_load_verify_locations_ex(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ !defined(NO_WOLFSSL_CLIENT) - WOLFSSL_CTX* ctx; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; const char* ca_cert = "./certs/ca-cert.pem"; const char* ca_expired_cert = "./certs/test/expired/expired-ca.pem"; - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); /* test good CA */ - AssertTrue(WOLFSSL_SUCCESS == + ExpectTrue(WOLFSSL_SUCCESS == wolfSSL_CTX_load_verify_locations_ex(ctx, ca_cert, NULL, WOLFSSL_LOAD_FLAG_NONE)); /* test expired CA */ #if !defined(OPENSSL_COMPATIBLE_DEFAULTS) && !defined(NO_ASN_TIME) - AssertIntNE(wolfSSL_CTX_load_verify_locations_ex(ctx, ca_expired_cert, NULL, + ExpectIntNE(wolfSSL_CTX_load_verify_locations_ex(ctx, ca_expired_cert, NULL, WOLFSSL_LOAD_FLAG_NONE), WOLFSSL_SUCCESS); #else - AssertIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, ca_expired_cert, NULL, + ExpectIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, ca_expired_cert, NULL, WOLFSSL_LOAD_FLAG_NONE), WOLFSSL_SUCCESS); #endif - AssertIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, ca_expired_cert, NULL, + ExpectIntEQ(wolfSSL_CTX_load_verify_locations_ex(ctx, ca_expired_cert, NULL, WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY), WOLFSSL_SUCCESS); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3191,54 +3288,55 @@ static int test_wolfSSL_CTX_load_verify_buffer_ex(void) #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ defined(USE_CERT_BUFFERS_2048) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; WOLFSSL_CTX* ctx; const char* ca_expired_cert_file = "./certs/test/expired/expired-ca.der"; byte ca_expired_cert[TWOK_BUF]; word32 sizeof_ca_expired_cert; - XFILE fp; + XFILE fp = XBADFILE; #ifndef NO_WOLFSSL_CLIENT ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); #else ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); #endif - AssertNotNull(ctx); + ExpectNotNull(ctx); /* test good CA */ - AssertTrue(WOLFSSL_SUCCESS == + ExpectTrue(WOLFSSL_SUCCESS == wolfSSL_CTX_load_verify_buffer_ex(ctx, ca_cert_der_2048, sizeof_ca_cert_der_2048, WOLFSSL_FILETYPE_ASN1, 0, WOLFSSL_LOAD_FLAG_NONE)); /* load expired CA */ XMEMSET(ca_expired_cert, 0, sizeof(ca_expired_cert)); - fp = XFOPEN(ca_expired_cert_file, "rb"); - AssertTrue(fp != XBADFILE); - sizeof_ca_expired_cert = (word32)XFREAD(ca_expired_cert, 1, - sizeof(ca_expired_cert), fp); - XFCLOSE(fp); + ExpectTrue((fp = XFOPEN(ca_expired_cert_file, "rb")) != XBADFILE); + ExpectIntGT(sizeof_ca_expired_cert = (word32)XFREAD(ca_expired_cert, 1, + sizeof(ca_expired_cert), fp), 0); + if (fp != XBADFILE) + XFCLOSE(fp); /* test expired CA failure */ #if !defined(OPENSSL_COMPATIBLE_DEFAULTS) && !defined(NO_ASN_TIME) - AssertIntNE(wolfSSL_CTX_load_verify_buffer_ex(ctx, ca_expired_cert, + ExpectIntNE(wolfSSL_CTX_load_verify_buffer_ex(ctx, ca_expired_cert, sizeof_ca_expired_cert, WOLFSSL_FILETYPE_ASN1, 0, WOLFSSL_LOAD_FLAG_NONE), WOLFSSL_SUCCESS); #else - AssertIntEQ(wolfSSL_CTX_load_verify_buffer_ex(ctx, ca_expired_cert, + ExpectIntEQ(wolfSSL_CTX_load_verify_buffer_ex(ctx, ca_expired_cert, sizeof_ca_expired_cert, WOLFSSL_FILETYPE_ASN1, 0, WOLFSSL_LOAD_FLAG_NONE), WOLFSSL_SUCCESS); #endif /* test expired CA success */ - AssertIntEQ(wolfSSL_CTX_load_verify_buffer_ex(ctx, ca_expired_cert, + ExpectIntEQ(wolfSSL_CTX_load_verify_buffer_ex(ctx, ca_expired_cert, sizeof_ca_expired_cert, WOLFSSL_FILETYPE_ASN1, 0, WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY), WOLFSSL_SUCCESS); wolfSSL_CTX_free(ctx); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3250,21 +3348,22 @@ static int test_wolfSSL_CTX_load_verify_chain_buffer_format(void) #if !defined(NO_CERTS) && !defined(NO_RSA) && defined(OPENSSL_EXTRA) && \ defined(WOLFSSL_CERT_GEN) && defined(USE_CERT_BUFFERS_2048) && \ (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) - WOLFSSL_CTX* ctx; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; #ifndef NO_WOLFSSL_CLIENT - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif - AssertTrue(WOLFSSL_SUCCESS == wolfSSL_CTX_load_verify_chain_buffer_format( + ExpectTrue(WOLFSSL_SUCCESS == wolfSSL_CTX_load_verify_chain_buffer_format( ctx, ca_cert_chain_der, sizeof_ca_cert_chain_der, WOLFSSL_FILETYPE_ASN1)); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3275,8 +3374,9 @@ static int test_wolfSSL_CTX_add1_chain_cert(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && defined(OPENSSL_EXTRA) && \ defined(KEEP_OUR_CERT) && !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + WOLFSSL* ssl = NULL;; const char *certChain[] = { "./certs/intermediate/client-int-cert.pem", "./certs/intermediate/ca-int2-cert.pem", @@ -3285,34 +3385,36 @@ static int test_wolfSSL_CTX_add1_chain_cert(void) NULL }; const char** cert; - WOLFSSL_X509* x509; + WOLFSSL_X509* x509 = NULL; WOLF_STACK_OF(X509)* chain = NULL; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); for (cert = certChain; *cert != NULL; cert++) { - x509 = wolfSSL_X509_load_certificate_file(*cert, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); - AssertIntEQ(SSL_CTX_add1_chain_cert(ctx, x509), 1); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(*cert, + WOLFSSL_FILETYPE_PEM)); + ExpectIntEQ(SSL_CTX_add1_chain_cert(ctx, x509), 1); X509_free(x509); + x509 = NULL; } for (cert = certChain; *cert != NULL; cert++) { - x509 = wolfSSL_X509_load_certificate_file(*cert, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); - AssertIntEQ(SSL_add1_chain_cert(ssl, x509), 1); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(*cert, + WOLFSSL_FILETYPE_PEM)); + ExpectIntEQ(SSL_add1_chain_cert(ssl, x509), 1); X509_free(x509); + x509 = NULL; } - AssertIntEQ(SSL_CTX_get0_chain_certs(ctx, &chain), 1); - AssertIntEQ(sk_X509_num(chain), 3); - AssertIntEQ(SSL_get0_chain_certs(ssl, &chain), 1); - AssertIntEQ(sk_X509_num(chain), 3); + ExpectIntEQ(SSL_CTX_get0_chain_certs(ctx, &chain), 1); + ExpectIntEQ(sk_X509_num(chain), 3); + ExpectIntEQ(SSL_get0_chain_certs(ssl, &chain), 1); + ExpectIntEQ(sk_X509_num(chain), 3); SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -3322,30 +3424,30 @@ static int test_wolfSSL_CTX_use_certificate_chain_file_format(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) + EXPECT_DECLS; const char* server_chain_der = "./certs/server-cert-chain.der"; const char* client_single_pem = "./certs/client-cert.pem"; WOLFSSL_CTX* ctx; - int ret = 0; (void)server_chain_der; (void)client_single_pem; (void)ctx; + #ifndef NO_WOLFSSL_CLIENT ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); #else ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); #endif + ExpectNotNull(ctx); - AssertIntEQ(wolfSSL_CTX_use_certificate_chain_file_format(ctx, + ExpectIntEQ(wolfSSL_CTX_use_certificate_chain_file_format(ctx, server_chain_der, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_use_certificate_chain_file_format(ctx, + ExpectIntEQ(wolfSSL_CTX_use_certificate_chain_file_format(ctx, client_single_pem, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(ret == 0); + res = EXPECT_RESULT(); #endif return res; } @@ -3355,32 +3457,35 @@ static int test_wolfSSL_CTX_SetTmpDH_file(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_DH) && \ (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) - WOLFSSL_CTX *ctx; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + (void)ctx; + #ifndef NO_WOLFSSL_CLIENT - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif /* invalid context */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_file(NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_file(NULL, dhParamFile, WOLFSSL_FILETYPE_PEM)); /* invalid dhParamFile file */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_file(ctx, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_file(ctx, NULL, WOLFSSL_FILETYPE_PEM)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_file(ctx, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_file(ctx, bogusFile, WOLFSSL_FILETYPE_PEM)); /* success */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_file(ctx, dhParamFile, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_file(ctx, dhParamFile, WOLFSSL_FILETYPE_PEM)); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -3390,32 +3495,36 @@ static int test_wolfSSL_CTX_SetTmpDH_buffer(void) int res = TEST_SKIPPED; #if !defined(NO_CERTS) && !defined(NO_DH) && \ (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) - WOLFSSL_CTX *ctx; - (void)ctx; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + #ifndef NO_WOLFSSL_CLIENT - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif /* invalid context */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(NULL, dh_key_der_2048, - sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(NULL, + dh_key_der_2048, sizeof_dh_key_der_2048, + WOLFSSL_FILETYPE_ASN1)); /* invalid dhParamFile file */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(NULL, NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(NULL, NULL, 0, WOLFSSL_FILETYPE_ASN1)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(ctx, dsa_key_der_2048, - sizeof_dsa_key_der_2048, WOLFSSL_FILETYPE_ASN1)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(ctx, + dsa_key_der_2048, sizeof_dsa_key_der_2048, + WOLFSSL_FILETYPE_ASN1)); /* success */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(ctx, dh_key_der_2048, - sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(ctx, + dh_key_der_2048, sizeof_dh_key_der_2048, + WOLFSSL_FILETYPE_ASN1)); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -3425,39 +3534,44 @@ static int test_wolfSSL_CTX_SetMinMaxDhKey_Sz(void) int res = TEST_SKIPPED; #if !defined(NO_CERTS) && !defined(NO_DH) && \ (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) + EXPECT_DECLS; WOLFSSL_CTX *ctx; + (void)ctx; + #ifndef NO_WOLFSSL_CLIENT ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); #else ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); #endif + ExpectNotNull(ctx); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMinDhKey_Sz(ctx, 3072)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMinDhKey_Sz(ctx, 3072)); - AssertIntEQ(DH_KEY_SIZE_E, wolfSSL_CTX_SetTmpDH_buffer(ctx, dh_key_der_2048, + ExpectIntEQ(DH_KEY_SIZE_E, wolfSSL_CTX_SetTmpDH_buffer(ctx, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMinDhKey_Sz(ctx, 2048)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMinDhKey_Sz(ctx, 2048)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(ctx, dh_key_der_2048, - sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(ctx, + dh_key_der_2048, sizeof_dh_key_der_2048, + WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMaxDhKey_Sz(ctx, 1024)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMaxDhKey_Sz(ctx, 1024)); - AssertIntEQ(DH_KEY_SIZE_E, wolfSSL_CTX_SetTmpDH_buffer(ctx, dh_key_der_2048, - sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); + ExpectIntEQ(DH_KEY_SIZE_E, wolfSSL_CTX_SetTmpDH_buffer(ctx, + dh_key_der_2048, sizeof_dh_key_der_2048, + WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMaxDhKey_Sz(ctx, 2048)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMaxDhKey_Sz(ctx, 2048)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(ctx, dh_key_der_2048, - sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpDH_buffer(ctx, + dh_key_der_2048, sizeof_dh_key_der_2048, + WOLFSSL_FILETYPE_ASN1)); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -3467,6 +3581,7 @@ static int test_wolfSSL_CTX_der_load_verify_locations(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_DER_LOAD) && \ (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) + EXPECT_DECLS; WOLFSSL_CTX* ctx = NULL; const char* derCert = "./certs/server-cert.der"; const char* nullPath = NULL; @@ -3474,36 +3589,36 @@ static int test_wolfSSL_CTX_der_load_verify_locations(void) const char* emptyPath = ""; /* der load Case 1 ctx NULL */ - AssertIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, derCert, + ExpectIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, derCert, WOLFSSL_FILETYPE_ASN1), WOLFSSL_FAILURE); #ifndef NO_WOLFSSL_CLIENT - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif /* Case 2 filePath NULL */ - AssertIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, nullPath, + ExpectIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, nullPath, WOLFSSL_FILETYPE_ASN1), WOLFSSL_FAILURE); /* Case 3 invalid format */ - AssertIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, derCert, + ExpectIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, derCert, WOLFSSL_FILETYPE_PEM), WOLFSSL_FAILURE); /* Case 4 filePath not valid */ - AssertIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, invalidPath, + ExpectIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, invalidPath, WOLFSSL_FILETYPE_ASN1), WOLFSSL_FAILURE); /* Case 5 filePath empty */ - AssertIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, emptyPath, + ExpectIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, emptyPath, WOLFSSL_FILETYPE_ASN1), WOLFSSL_FAILURE); #ifndef NO_RSA /* Case 6 success case */ - AssertIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, derCert, + ExpectIntEQ(wolfSSL_CTX_der_load_verify_locations(ctx, derCert, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #endif wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3513,69 +3628,70 @@ static int test_wolfSSL_CTX_enable_disable(void) { int res = TEST_SKIPPED; #ifndef NO_CERTS + EXPECT_DECLS; WOLFSSL_CTX* ctx = NULL; #ifdef HAVE_CRL - AssertIntEQ(wolfSSL_CTX_DisableCRL(ctx), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_CTX_EnableCRL(ctx, 0), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_DisableCRL(ctx), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_EnableCRL(ctx, 0), BAD_FUNC_ARG); #endif #ifdef HAVE_OCSP - AssertIntEQ(wolfSSL_CTX_DisableOCSP(ctx), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_CTX_EnableOCSP(ctx, 0), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_DisableOCSP(ctx), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_EnableOCSP(ctx, 0), BAD_FUNC_ARG); #endif #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) - AssertIntEQ(wolfSSL_CTX_DisableOCSPStapling(ctx), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_CTX_EnableOCSPStapling(ctx), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_CTX_DisableOCSPMustStaple(ctx), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_CTX_EnableOCSPMustStaple(ctx), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_DisableOCSPStapling(ctx), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_EnableOCSPStapling(ctx), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_DisableOCSPMustStaple(ctx), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_EnableOCSPMustStaple(ctx), BAD_FUNC_ARG); #endif #ifndef NO_WOLFSSL_CLIENT #ifdef HAVE_EXTENDED_MASTER - AssertIntEQ(wolfSSL_CTX_DisableExtendedMasterSecret(ctx), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_DisableExtendedMasterSecret(ctx), BAD_FUNC_ARG); #endif - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #ifdef HAVE_EXTENDED_MASTER - AssertIntEQ(wolfSSL_CTX_DisableExtendedMasterSecret(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_DisableExtendedMasterSecret(ctx), WOLFSSL_SUCCESS); #endif #elif !defined(NO_WOLFSSL_SERVER) - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); - #else - return TEST_SUCCESS; + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif - #ifdef HAVE_CRL - AssertIntEQ(wolfSSL_CTX_DisableCRL(ctx), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_EnableCRL(ctx, 0), WOLFSSL_SUCCESS); - #endif + #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - #ifdef HAVE_OCSP - AssertIntEQ(wolfSSL_CTX_DisableOCSP(ctx), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_URL_OVERRIDE), - WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE), - WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_CHECKALL), - WOLFSSL_SUCCESS); - #endif + #ifdef HAVE_CRL + ExpectIntEQ(wolfSSL_CTX_DisableCRL(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_EnableCRL(ctx, 0), WOLFSSL_SUCCESS); + #endif - #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ - defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) - AssertIntEQ(wolfSSL_CTX_DisableOCSPStapling(ctx), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_EnableOCSPStapling(ctx), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_DisableOCSPMustStaple(ctx), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_DisableOCSPMustStaple(ctx), WOLFSSL_SUCCESS); - #endif - wolfSSL_CTX_free(ctx); + #ifdef HAVE_OCSP + ExpectIntEQ(wolfSSL_CTX_DisableOCSP(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_URL_OVERRIDE), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_CHECKALL), + WOLFSSL_SUCCESS); + #endif - res = TEST_RES_CHECK(1); + #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ + defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + ExpectIntEQ(wolfSSL_CTX_DisableOCSPStapling(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_EnableOCSPStapling(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_DisableOCSPMustStaple(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_DisableOCSPMustStaple(ctx), WOLFSSL_SUCCESS); + #endif + wolfSSL_CTX_free(ctx); + #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ + + res = EXPECT_RESULT(); #endif /* NO_CERTS */ return res; @@ -3585,20 +3701,21 @@ static int test_wolfSSL_CTX_ticket_API(void) { int res = TEST_SKIPPED; #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; WOLFSSL_CTX* ctx = NULL; void *userCtx = (void*)"this is my ctx"; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_set_TicketEncCtx(ctx, userCtx)); - AssertTrue(userCtx == wolfSSL_CTX_get_TicketEncCtx(ctx)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_set_TicketEncCtx(ctx, userCtx)); + ExpectTrue(userCtx == wolfSSL_CTX_get_TicketEncCtx(ctx)); wolfSSL_CTX_free(ctx); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_set_TicketEncCtx(NULL, userCtx)); - AssertNull(wolfSSL_CTX_get_TicketEncCtx(NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_set_TicketEncCtx(NULL, userCtx)); + ExpectNull(wolfSSL_CTX_get_TicketEncCtx(NULL)); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* HAVE_SESSION_TICKET && !NO_WOLFSSL_SERVER */ return res; } @@ -3701,30 +3818,34 @@ static int test_server_wolfSSL_new(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX *ctx; - WOLFSSL_CTX *ctx_nocert; - WOLFSSL *ssl; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL_CTX *ctx_nocert = NULL; + WOLFSSL *ssl = NULL; - AssertNotNull(ctx_nocert = wolfSSL_CTX_new(wolfSSLv23_server_method())); - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx_nocert = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + WOLFSSL_FILETYPE_PEM)); /* invalid context */ - AssertNull(ssl = wolfSSL_new(NULL)); -#if !defined(WOLFSSL_SESSION_EXPORT) && !defined(WOLFSSL_QT) && !defined(OPENSSL_EXTRA) - AssertNull(ssl = wolfSSL_new(ctx_nocert)); + ExpectNull(ssl = wolfSSL_new(NULL)); +#if !defined(WOLFSSL_SESSION_EXPORT) && !defined(WOLFSSL_QT) && \ + !defined(OPENSSL_EXTRA) + ExpectNull(ssl = wolfSSL_new(ctx_nocert)); #endif /* success */ - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); wolfSSL_CTX_free(ctx_nocert); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3736,30 +3857,32 @@ static int test_client_wolfSSL_new(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ !defined(NO_WOLFSSL_CLIENT) - WOLFSSL_CTX *ctx; - WOLFSSL_CTX *ctx_nocert; - WOLFSSL *ssl; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL_CTX *ctx_nocert = NULL; + WOLFSSL *ssl = NULL; - AssertNotNull(ctx_nocert = wolfSSL_CTX_new(wolfSSLv23_client_method())); - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx_nocert = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); - AssertTrue(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); + ExpectTrue(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); /* invalid context */ - AssertNull(ssl = wolfSSL_new(NULL)); + ExpectNull(ssl = wolfSSL_new(NULL)); /* success */ - AssertNotNull(ssl = wolfSSL_new(ctx_nocert)); + ExpectNotNull(ssl = wolfSSL_new(ctx_nocert)); wolfSSL_free(ssl); + ssl = NULL; /* success */ - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); wolfSSL_CTX_free(ctx_nocert); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3770,51 +3893,52 @@ static int test_wolfSSL_SetTmpDH_file(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_DH) && \ !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX *ctx; - WOLFSSL *ssl; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #ifndef NO_RSA - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); #elif defined(HAVE_ECC) - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, eccCertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, eccCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, WOLFSSL_FILETYPE_PEM)); #elif defined(HAVE_ED25519) - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, edCertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, edCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, edKeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, edKeyFile, WOLFSSL_FILETYPE_PEM)); #elif defined(HAVE_ED448) - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, ed448CertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, ed448CertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, ed448KeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, ed448KeyFile, WOLFSSL_FILETYPE_PEM)); #endif - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); /* invalid ssl */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_file(NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_file(NULL, dhParamFile, WOLFSSL_FILETYPE_PEM)); /* invalid dhParamFile file */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_file(ssl, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_file(ssl, NULL, WOLFSSL_FILETYPE_PEM)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_file(ssl, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_file(ssl, bogusFile, WOLFSSL_FILETYPE_PEM)); /* success */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_file(ssl, dhParamFile, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_file(ssl, dhParamFile, WOLFSSL_FILETYPE_PEM)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3824,34 +3948,35 @@ static int test_wolfSSL_SetTmpDH_buffer(void) { int res = TEST_SKIPPED; #if !defined(NO_CERTS) && !defined(NO_DH) && !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX *ctx; - WOLFSSL *ssl; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); - AssertTrue(wolfSSL_CTX_use_certificate_buffer(ctx, server_cert_der_2048, - sizeof_server_cert_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_buffer(ctx, server_key_der_2048, - sizeof_server_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectTrue(wolfSSL_CTX_use_certificate_buffer(ctx, server_cert_der_2048, + sizeof_server_cert_der_2048, WOLFSSL_FILETYPE_ASN1)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_buffer(ctx, server_key_der_2048, + sizeof_server_key_der_2048, WOLFSSL_FILETYPE_ASN1)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); /* invalid ssl */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(NULL, dh_key_der_2048, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(NULL, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); /* invalid dhParamFile file */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(NULL, NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(NULL, NULL, 0, WOLFSSL_FILETYPE_ASN1)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl, dsa_key_der_2048, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl, dsa_key_der_2048, sizeof_dsa_key_der_2048, WOLFSSL_FILETYPE_ASN1)); /* success */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -3861,47 +3986,47 @@ static int test_wolfSSL_SetMinMaxDhKey_Sz(void) { int res = TEST_SKIPPED; #if !defined(NO_CERTS) && !defined(NO_DH) && !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX *ctx, *ctx2; - WOLFSSL *ssl, *ssl2; - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); - AssertTrue(wolfSSL_CTX_use_certificate_buffer(ctx, server_cert_der_2048, + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL_CTX *ctx2 = NULL; + WOLFSSL *ssl = NULL; + WOLFSSL *ssl2 = NULL; + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectTrue(wolfSSL_CTX_use_certificate_buffer(ctx, server_cert_der_2048, sizeof_server_cert_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_buffer(ctx, server_key_der_2048, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_buffer(ctx, server_key_der_2048, sizeof_server_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMinDhKey_Sz(ctx, 3072)); - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); - ctx2 = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx2); - AssertTrue(wolfSSL_CTX_use_certificate_buffer(ctx2, server_cert_der_2048, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMinDhKey_Sz(ctx, 3072)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ctx2 = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectTrue(wolfSSL_CTX_use_certificate_buffer(ctx2, server_cert_der_2048, sizeof_server_cert_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_buffer(ctx2, server_key_der_2048, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_buffer(ctx2, server_key_der_2048, sizeof_server_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMaxDhKey_Sz(ctx, 1024)); - ssl2 = wolfSSL_new(ctx2); - AssertNotNull(ssl2); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetMaxDhKey_Sz(ctx, 1024)); + ExpectNotNull(ssl2 = wolfSSL_new(ctx2)); - AssertIntEQ(DH_KEY_SIZE_E, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, + ExpectIntEQ(DH_KEY_SIZE_E, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetMinDhKey_Sz(ssl, 2048)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetMinDhKey_Sz(ssl, 2048)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetMinDhKey_Sz(ssl, 3072)); - AssertIntEQ(DH_KEY_SIZE_E, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetMinDhKey_Sz(ssl, 3072)); + ExpectIntEQ(DH_KEY_SIZE_E, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl2, dh_key_der_2048, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl2, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetMaxDhKey_Sz(ssl2, 2048)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl2, dh_key_der_2048, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetMaxDhKey_Sz(ssl2, 2048)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpDH_buffer(ssl2, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetMaxDhKey_Sz(ssl2, 1024)); - AssertIntEQ(DH_KEY_SIZE_E, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetMaxDhKey_Sz(ssl2, 1024)); + ExpectIntEQ(DH_KEY_SIZE_E, wolfSSL_SetTmpDH_buffer(ssl, dh_key_der_2048, sizeof_dh_key_der_2048, WOLFSSL_FILETYPE_ASN1)); wolfSSL_free(ssl2); @@ -3909,7 +4034,7 @@ static int test_wolfSSL_SetMinMaxDhKey_Sz(void) wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -3924,8 +4049,8 @@ static int test_wolfSSL_SetMinVersion(void) int res = TEST_SKIPPED; #ifndef NO_WOLFSSL_CLIENT int failFlag = WOLFSSL_SUCCESS; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; int itr; #ifndef NO_OLD_TLS @@ -5225,6 +5350,11 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_nofail(void* args) ctx = wolfSSL_CTX_new(method); } if (ctx == NULL) { + /* Release the wait for TCP ready. */ + PTHREAD_CHECK_RET(pthread_mutex_lock(&opts->signal->mutex)); + opts->signal->ready = 1; + PTHREAD_CHECK_RET(pthread_cond_signal(&opts->signal->cond)); + PTHREAD_CHECK_RET(pthread_mutex_unlock(&opts->signal->mutex)); goto done; } @@ -5441,11 +5571,7 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_nofail(void* args) if (wolfSSL_write(ssl, msg, sizeof(msg)) != sizeof(msg)) { /*err_sys("SSL_write failed");*/ -#ifdef WOLFSSL_TIRTOS - return; -#else - return 0; -#endif + goto done; } if (cbf != NULL && cbf->on_result != NULL) @@ -5495,7 +5621,8 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_nofail(void* args) #endif } -#if defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && !defined(WOLFSSL_TLS13) +#if defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && \ + !defined(WOLFSSL_NO_TLS12) static THREAD_RETURN WOLFSSL_THREAD test_server_loop(void* args) { SOCKET_T sockfd = 0; @@ -5511,15 +5638,16 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_loop(void* args) int idx; int ret, err = 0; int sharedCtx = 0; - int loop_count = ((func_args*)args)->argc; + func_args* opts = (func_args*)args; + int loop_count = opts->argc; int count = 0; #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif - ((func_args*)args)->return_code = TEST_FAIL; - cbf = ((func_args*)args)->callbacks; + opts->return_code = TEST_FAIL; + cbf = opts->callbacks; #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) if (cbf != NULL && cbf->ctx) { @@ -5540,7 +5668,7 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_loop(void* args) } #if defined(USE_WINDOWS_API) - port = ((func_args*)args)->signal->port; + port = opts->signal->port; #elif defined(NO_MAIN_DRIVER) && !defined(WOLFSSL_SNIFFER) && \ !defined(WOLFSSL_MDK_SHELL) && !defined(WOLFSSL_TIRTOS) /* Let tcp_listen assign port */ @@ -5560,18 +5688,33 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_loop(void* args) if (wolfSSL_CTX_load_verify_locations(ctx, cliCertFile, 0) != WOLFSSL_SUCCESS) { /*err_sys("can't load ca file, Please run from wolfSSL home dir");*/ + /* Release the wait for TCP ready. */ + PTHREAD_CHECK_RET(pthread_mutex_lock(&opts->signal->mutex)); + opts->signal->ready = 1; + PTHREAD_CHECK_RET(pthread_cond_signal(&opts->signal->cond)); + PTHREAD_CHECK_RET(pthread_mutex_unlock(&opts->signal->mutex)); goto done; } if (!sharedCtx && wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { /*err_sys("can't load server cert chain file, " "Please run from wolfSSL home dir");*/ + /* Release the wait for TCP ready. */ + PTHREAD_CHECK_RET(pthread_mutex_lock(&opts->signal->mutex)); + opts->signal->ready = 1; + PTHREAD_CHECK_RET(pthread_cond_signal(&opts->signal->cond)); + PTHREAD_CHECK_RET(pthread_mutex_unlock(&opts->signal->mutex)); goto done; } if (!sharedCtx && wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { /*err_sys("can't load server key file, " "Please run from wolfSSL home dir");*/ + /* Release the wait for TCP ready. */ + PTHREAD_CHECK_RET(pthread_mutex_lock(&opts->signal->mutex)); + opts->signal->ready = 1; + PTHREAD_CHECK_RET(pthread_cond_signal(&opts->signal->cond)); + PTHREAD_CHECK_RET(pthread_mutex_unlock(&opts->signal->mutex)); goto done; } /* call ctx setup callback */ @@ -5582,18 +5725,33 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_loop(void* args) while (count != loop_count) { ssl = wolfSSL_new(ctx); if (ssl == NULL) { + /* Release the wait for TCP ready. */ + PTHREAD_CHECK_RET(pthread_mutex_lock(&opts->signal->mutex)); + opts->signal->ready = 1; + PTHREAD_CHECK_RET(pthread_cond_signal(&opts->signal->cond)); + PTHREAD_CHECK_RET(pthread_mutex_unlock(&opts->signal->mutex)); goto done; } if (sharedCtx && wolfSSL_use_certificate_file(ssl, svrCertFile, WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { /*err_sys("can't load server cert chain file, " "Please run from wolfSSL home dir");*/ + /* Release the wait for TCP ready. */ + PTHREAD_CHECK_RET(pthread_mutex_lock(&opts->signal->mutex)); + opts->signal->ready = 1; + PTHREAD_CHECK_RET(pthread_cond_signal(&opts->signal->cond)); + PTHREAD_CHECK_RET(pthread_mutex_unlock(&opts->signal->mutex)); goto done; } if (sharedCtx && wolfSSL_use_PrivateKey_file(ssl, svrKeyFile, WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { /*err_sys("can't load server key file, " "Please run from wolfSSL home dir");*/ + /* Release the wait for TCP ready. */ + PTHREAD_CHECK_RET(pthread_mutex_lock(&opts->signal->mutex)); + opts->signal->ready = 1; + PTHREAD_CHECK_RET(pthread_cond_signal(&opts->signal->cond)); + PTHREAD_CHECK_RET(pthread_mutex_unlock(&opts->signal->mutex)); goto done; } @@ -5643,11 +5801,7 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_loop(void* args) if (wolfSSL_write(ssl, msg, sizeof(msg)) != sizeof(msg)) { /*err_sys("SSL_write failed");*/ - #ifdef WOLFSSL_TIRTOS - return; - #else - return 0; - #endif + goto done; } /* free ssl for this connection */ wolfSSL_shutdown(ssl); @@ -5660,7 +5814,7 @@ static THREAD_RETURN WOLFSSL_THREAD test_server_loop(void* args) Task_yield(); #endif - ((func_args*)args)->return_code = TEST_SUCCESS; + opts->return_code = TEST_SUCCESS; done: if (ssl != NULL) { @@ -5980,7 +6134,7 @@ void test_wolfSSL_client_server_nofail(callback_functions* client_cb, #if defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && \ - !defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_CLIENT) + !defined(WOLFSSL_NO_TLS12) && !defined(NO_WOLFSSL_CLIENT) static void test_client_reuse_WOLFSSLobj(void* args, void *cb, void* server_args) { SOCKET_T sockfd = 0; @@ -6129,6 +6283,7 @@ static void test_client_reuse_WOLFSSLobj(void* args, void *cb, void* server_args } session = wolfSSL_get1_session(ssl); if (wolfSSL_clear(ssl) != WOLFSSL_SUCCESS) { + wolfSSL_SESSION_free(session); /* err_sys ("SSL_clear failed"); */ goto done; } @@ -6202,129 +6357,6 @@ static void test_client_reuse_WOLFSSLobj(void* args, void *cb, void* server_args #endif /* defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && !defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_CLIENT) */ - -static int test_client_verifyDepth(void* args) -{ -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) - SOCKET_T sockfd = 0; - callback_functions* cbf; - - WOLFSSL_CTX* ctx = 0; - WOLFSSL* ssl = 0; - - char msg[64] = "hello wolfssl!"; - char reply[1024]; - int input; - int msgSz = (int)XSTRLEN(msg); - int ret, err = 0; - int verify_depth = ((func_args*)args)->argc; - - ((func_args*)args)->return_code = TEST_FAIL; - cbf = ((func_args*)args)->callbacks; - - { - WOLFSSL_METHOD* method = NULL; - if (cbf != NULL && cbf->method != NULL) { - method = cbf->method(); - } - else { - method = wolfSSLv23_client_method(); - } - ctx = wolfSSL_CTX_new(method); - } - - /* Do connect here so server detects failures */ - tcp_connect(&sockfd, wolfSSLIP, ((func_args*)args)->signal->port, - 0, 0, NULL); - - if (wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0) - != WOLFSSL_SUCCESS) - { - /* err_sys("can't load ca file, Please run from wolfSSL home dir");*/ - goto done; - } - if (wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, - WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { - /*err_sys("can't load client cert file, " - "Please run from wolfSSL home dir");*/ - goto done; - } - if (wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, - WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { - /*err_sys("can't load client key file, " - "Please run from wolfSSL home dir");*/ - goto done; - } - - SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); - - /* set verify depth */ - if (verify_depth == 0) { - myVerifyAction = VERIFY_OVERRIDE_ERROR; - SSL_CTX_set_verify_depth(ctx, verify_depth); - } - else if (verify_depth == -1) { - myVerifyAction = VERIFY_USE_PREVERFIY; - SSL_CTX_set_verify_depth(ctx, 0); - } - else if (verify_depth > 0) { - myVerifyAction = VERIFY_USE_PREVERFIY; - SSL_CTX_set_verify_depth(ctx, verify_depth); - } - - ssl = wolfSSL_new(ctx); - if (ssl == NULL) { - goto done; - } - - if (wolfSSL_set_fd(ssl, sockfd) != WOLFSSL_SUCCESS) { - /*err_sys("SSL_set_fd failed");*/ - goto done; - } - - #ifdef WOLFSSL_ASYNC_CRYPT - err = 0; /* Reset error */ - #endif - do { - #ifdef WOLFSSL_ASYNC_CRYPT - if (err == WC_PENDING_E) { - ret = wolfSSL_AsyncPoll(ssl, WOLF_POLL_FLAG_CHECK_HW); - if (ret < 0) { break; } else if (ret == 0) { continue; } - } - #endif - ret = wolfSSL_connect(ssl); - err = wolfSSL_get_error(ssl, 0); - } while (err == WC_PENDING_E); - if (ret != WOLFSSL_SUCCESS) { - char buff[WOLFSSL_MAX_ERROR_SZ]; - fprintf(stderr, "error = %d, %s\n", err, - wolfSSL_ERR_error_string(err, buff)); - goto done; - } - - if (wolfSSL_write(ssl, msg, msgSz) != msgSz) { - goto done; - } - - input = wolfSSL_read(ssl, reply, sizeof(reply)-1); - if (input > 0) { - reply[input] = '\0'; - fprintf(stderr, "Server response: %s\n", reply); - } - - ((func_args*)args)->return_code = TEST_SUCCESS; - -done: - wolfSSL_free(ssl); - wolfSSL_CTX_free(ctx); - CloseSocket(sockfd); -#else - (void)args; -#endif /* defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) */ - - return 0; -} - #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)) && \ defined(HAVE_ALPN) && defined(HAVE_SNI) && \ @@ -6347,11 +6379,11 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) { callback_functions* callbacks = ((func_args*)args)->callbacks; - WOLFSSL_CTX* ctx = NULL; - WOLFSSL* ssl = NULL; - SOCKET_T sfd = 0; - SOCKET_T cfd = 0; - word16 port; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; + SOCKET_T sfd = 0; + SOCKET_T cfd = 0; + word16 port; char msg[] = "I hear you fa shizzle!"; int len = (int) XSTRLEN(msg); @@ -6361,6 +6393,49 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) ((func_args*)args)->return_code = TEST_FAIL; +#if defined(USE_WINDOWS_API) + port = ((func_args*)args)->signal->port; +#elif defined(NO_MAIN_DRIVER) && !defined(WOLFSSL_SNIFFER) && \ + !defined(WOLFSSL_MDK_SHELL) && !defined(WOLFSSL_TIRTOS) + /* Let tcp_listen assign port */ + port = 0; +#else + /* Use default port */ + port = wolfSSLPort; +#endif + +#ifdef WOLFSSL_DTLS + if (callbacks->method == wolfDTLS_server_method +#ifdef WOLFSSL_STATIC_MEMORY + || callbacks->method_ex == wolfDTLS_server_method_ex +#endif +#ifndef NO_OLD_TLS + || callbacks->method == wolfDTLSv1_server_method +#ifdef WOLFSSL_STATIC_MEMORY + || callbacks->method_ex == wolfDTLSv1_server_method_ex +#endif +#endif +#ifndef WOLFSSL_NO_TLS12 + || callbacks->method == wolfDTLSv1_2_server_method +#ifdef WOLFSSL_STATIC_MEMORY + || callbacks->method_ex == wolfDTLSv1_2_server_method_ex +#endif +#endif +#ifdef WOLFSSL_DTLS13 + || callbacks->method == wolfDTLSv1_3_server_method +#ifdef WOLFSSL_STATIC_MEMORY + || callbacks->method_ex == wolfDTLSv1_3_server_method_ex +#endif +#endif + ) { + tcp_accept(&sfd, &cfd, (func_args*)args, port, 0, 1, 0, 0, 0, 0, 0); + } + else +#endif + { + tcp_accept(&sfd, &cfd, (func_args*)args, port, 0, 0, 0, 0, 1, 0, 0); + } + #ifdef WOLFSSL_STATIC_MEMORY if (callbacks->method_ex != NULL && callbacks->mem != NULL && callbacks->memSz > 0) { @@ -6368,16 +6443,14 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) callbacks->mem, callbacks->memSz, 0, 1); if (ret != WOLFSSL_SUCCESS) { fprintf(stderr, "CTX static new failed %d\n", ret); - return 0; + goto cleanup; } } #else - if (ctx == NULL) { - ctx = wolfSSL_CTX_new(callbacks->method()); - } + ctx = wolfSSL_CTX_new(callbacks->method()); if (ctx == NULL) { fprintf(stderr, "CTX new failed\n"); - return 0; + goto cleanup; } #endif @@ -6395,17 +6468,6 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) wolfSSL_CTX_SetDevId(ctx, callbacks->devId); -#if defined(USE_WINDOWS_API) - port = ((func_args*)args)->signal->port; -#elif defined(NO_MAIN_DRIVER) && !defined(WOLFSSL_SNIFFER) && \ - !defined(WOLFSSL_MDK_SHELL) && !defined(WOLFSSL_TIRTOS) - /* Let tcp_listen assign port */ - port = 0; -#else - /* Use default port */ - port = wolfSSLPort; -#endif - wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER | WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); @@ -6414,28 +6476,33 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) #endif #if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS) if (callbacks->method == wolfDTLSv1_2_server_method) { - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_dtls_set_export(ctx, test_export)); + if (wolfSSL_CTX_dtls_set_export(ctx, test_export) != WOLFSSL_SUCCESS) + goto cleanup; } #endif - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_load_verify_locations(ctx, callbacks->caPemFile, 0)); + if (wolfSSL_CTX_load_verify_locations(ctx, callbacks->caPemFile, 0) != + WOLFSSL_SUCCESS) { + goto cleanup; + } - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_certificate_file(ctx, callbacks->certPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_CTX_use_certificate_file(ctx, callbacks->certPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_PrivateKey_file(ctx, callbacks->keyPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_CTX_use_PrivateKey_file(ctx, callbacks->keyPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } #ifdef HAVE_CRL if (callbacks->crlPemFile != NULL) { - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_LoadCRLFile(ctx, callbacks->crlPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_CTX_LoadCRLFile(ctx, callbacks->crlPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } } #endif @@ -6445,37 +6512,40 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) ssl = wolfSSL_new(ctx); if (ssl == NULL) { fprintf(stderr, "SSL new failed\n"); - wolfSSL_CTX_free(ctx); - return 0; + goto cleanup; } if (wolfSSL_dtls(ssl)) { SOCKADDR_IN_T cliAddr; socklen_t cliLen; cliLen = sizeof(cliAddr); - tcp_accept(&sfd, &cfd, (func_args*)args, port, 0, 1, 0, 0, 0, 0, 0); idx = (int)recvfrom(sfd, input, sizeof(input), MSG_PEEK, (struct sockaddr*)&cliAddr, &cliLen); - AssertIntGT(idx, 0); + if (idx <= 0) { + goto cleanup; + } wolfSSL_dtls_set_peer(ssl, &cliAddr, cliLen); } else { - tcp_accept(&sfd, &cfd, (func_args*)args, port, 0, 0, 0, 0, 1, 0, 0); CloseSocket(sfd); } - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_set_fd(ssl, cfd)); + if (wolfSSL_set_fd(ssl, cfd) != WOLFSSL_SUCCESS) { + goto cleanup; + } if (callbacks->loadToSSL) { wolfSSL_SetDevId(ssl, callbacks->devId); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_use_certificate_file(ssl, callbacks->certPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_use_certificate_file(ssl, callbacks->certPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_use_PrivateKey_file(ssl, callbacks->keyPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_use_PrivateKey_file(ssl, callbacks->keyPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } } #ifdef NO_PSK @@ -6540,7 +6610,9 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) ret = wolfSSL_write(ssl, msg, len); err = wolfSSL_get_error(ssl, ret); } while (err == WC_PENDING_E); - AssertIntEQ(len, ret); + if (len != ret) { + goto cleanup; + } #if defined(WOLFSSL_SESSION_EXPORT) && !defined(HAVE_IO_POOL) && \ defined(WOLFSSL_DTLS) @@ -6550,10 +6622,16 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) wolfSSL_dtls_export(ssl, NULL, &sz); import = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_TMP_BUFFER); - AssertNotNull(import); + if (import == NULL) { + goto cleanup; + } idx = wolfSSL_dtls_export(ssl, import, &sz); - AssertIntGE(idx, 0); - AssertIntGE(wolfSSL_dtls_import(ssl, import, idx), 0); + if (idx < 0) { + goto cleanup; + } + if (wolfSSL_dtls_import(ssl, import, idx) < 0) { + goto cleanup; + } XFREE(import, NULL, DYNAMIC_TYPE_TMP_BUFFER); } #endif @@ -6567,6 +6645,8 @@ static THREAD_RETURN WOLFSSL_THREAD run_wolfssl_server(void* args) callbacks->on_result(ssl); wolfSSL_shutdown(ssl); + +cleanup: wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); CloseSocket(cfd); @@ -6617,7 +6697,7 @@ static void run_wolfssl_client(void* args) callbacks->mem, callbacks->memSz, 0, 1); if (ret != WOLFSSL_SUCCESS) { fprintf(stderr, "CTX static new failed %d\n", ret); - return; + goto cleanup; } } #else @@ -6626,7 +6706,7 @@ static void run_wolfssl_client(void* args) } if (ctx == NULL) { fprintf(stderr, "CTX new failed\n"); - return; + goto cleanup; } #endif @@ -6642,24 +6722,29 @@ static void run_wolfssl_client(void* args) wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); #endif - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_load_verify_locations(ctx, callbacks->caPemFile, 0)); + if (wolfSSL_CTX_load_verify_locations(ctx, callbacks->caPemFile, 0) != + WOLFSSL_SUCCESS) { + goto cleanup; + } if (!callbacks->loadToSSL) { - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_certificate_file(ctx, callbacks->certPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_CTX_use_certificate_file(ctx, callbacks->certPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_PrivateKey_file(ctx, callbacks->keyPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_CTX_use_PrivateKey_file(ctx, callbacks->keyPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } } #ifdef HAVE_CRL if (callbacks->crlPemFile != NULL) { - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_LoadCRLFile(ctx, callbacks->crlPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_CTX_LoadCRLFile(ctx, callbacks->crlPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } } #endif @@ -6675,18 +6760,22 @@ static void run_wolfssl_client(void* args) tcp_connect(&sfd, wolfSSLIP, ((func_args*)args)->signal->port, 0, 0, ssl); } - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_set_fd(ssl, sfd)); + if (wolfSSL_set_fd(ssl, sfd) != WOLFSSL_SUCCESS) { + goto cleanup; + } if (callbacks->loadToSSL) { wolfSSL_SetDevId(ssl, callbacks->devId); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_use_certificate_file(ssl, callbacks->certPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_use_certificate_file(ssl, callbacks->certPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_use_PrivateKey_file(ssl, callbacks->keyPemFile, - WOLFSSL_FILETYPE_PEM)); + if (wolfSSL_use_PrivateKey_file(ssl, callbacks->keyPemFile, + WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { + goto cleanup; + } } if (callbacks->ssl_ready) @@ -6725,7 +6814,8 @@ static void run_wolfssl_client(void* args) ret = wolfSSL_write(ssl, msg, len); err = wolfSSL_get_error(ssl, ret); } while (err == WC_PENDING_E); - AssertIntEQ(len, ret); + if (len != ret) + goto cleanup; #ifdef WOLFSSL_ASYNC_CRYPT err = 0; /* Reset error */ @@ -6750,6 +6840,7 @@ static void run_wolfssl_client(void* args) if (callbacks->on_result) callbacks->on_result(ssl); +cleanup: wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); CloseSocket(sfd); @@ -6787,6 +6878,7 @@ static int test_wolfSSL_read_write(void) func_args client_args; func_args server_args; THREAD_TYPE serverThread; + EXPECT_DECLS; XMEMSET(&client_args, 0, sizeof(func_args)); XMEMSET(&server_args, 0, sizeof(func_args)); @@ -6810,8 +6902,8 @@ static int test_wolfSSL_read_write(void) test_client_nofail(&client_args, NULL); join_thread(serverThread); - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); + ExpectTrue(client_args.return_code); + ExpectTrue(server_args.return_code); FreeTcpReady(&ready); @@ -6819,14 +6911,14 @@ static int test_wolfSSL_read_write(void) fdOpenSession(Task_self()); #endif - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } static int test_wolfSSL_reuse_WOLFSSLobj(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && \ - !defined(WOLFSSL_TLS13) + !defined(WOLFSSL_NO_TLS12) /* The unit test for session resumption by re-using WOLFSSL object. * WOLFSSL object is not cleared after first session. It re-use the obeject * for second connection. @@ -6835,9 +6927,14 @@ static int test_wolfSSL_reuse_WOLFSSLobj(void) func_args client_args; func_args server_args; THREAD_TYPE serverThread; + callback_functions client_cbf; + callback_functions server_cbf; + EXPECT_DECLS; XMEMSET(&client_args, 0, sizeof(func_args)); XMEMSET(&server_args, 0, sizeof(func_args)); + XMEMSET(&client_cbf, 0, sizeof(callback_functions)); + XMEMSET(&server_cbf, 0, sizeof(callback_functions)); #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif @@ -6850,6 +6947,11 @@ static int test_wolfSSL_reuse_WOLFSSLobj(void) ready.port = GetRandomPort(); #endif + client_cbf.method = wolfTLSv1_2_client_method; + server_cbf.method = wolfTLSv1_2_server_method; + client_args.callbacks = &client_cbf; + server_args.callbacks = &server_cbf; + server_args.signal = &ready; client_args.signal = &ready; /* the var is used for loop number */ @@ -6860,8 +6962,8 @@ static int test_wolfSSL_reuse_WOLFSSLobj(void) test_client_reuse_WOLFSSLobj(&client_args, NULL, &server_args); join_thread(serverThread); - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); + ExpectTrue(client_args.return_code); + ExpectTrue(server_args.return_code); FreeTcpReady(&ready); @@ -6869,99 +6971,131 @@ static int test_wolfSSL_reuse_WOLFSSLobj(void) fdOpenSession(Task_self()); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && !defined(WOLFSSL_TLS13) */ return res; } -static int test_wolfSSL_CTX_verifyDepth_ServerClient(void) +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) +static void test_wolfSSL_CTX_verifyDepth_ServerClient_1_ctx_ready( + WOLFSSL_CTX* ctx) +{ + wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); + myVerifyAction = VERIFY_USE_PREVERFIY; + wolfSSL_CTX_set_verify_depth(ctx, 2); +} +#endif + +static int test_wolfSSL_CTX_verifyDepth_ServerClient_1(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) - - /* This unit test is to check set verify Depth */ - tcp_ready ready; - func_args client_args; - func_args server_args; - THREAD_TYPE serverThread; + EXPECT_DECLS; callback_functions client_cbf; + callback_functions server_cbf; - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); XMEMSET(&client_cbf, 0, sizeof(callback_functions)); + XMEMSET(&server_cbf, 0, sizeof(callback_functions)); #ifdef WOLFSSL_TLS13 client_cbf.method = wolfTLSv1_3_client_method; #endif /* WOLFSSL_TLS13 */ + client_cbf.ctx_ready = + test_wolfSSL_CTX_verifyDepth_ServerClient_1_ctx_ready; - client_args.callbacks = &client_cbf; + /* test case 1 verify depth is equal to peer chain */ + test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); - StartTCP(); - InitTcpReady(&ready); + ExpectIntEQ(client_cbf.return_code, TEST_SUCCESS); + ExpectIntEQ(server_cbf.return_code, TEST_SUCCESS); -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif + res = EXPECT_RESULT(); +#endif /* (OPENSSL_EXTRA) && !(WOLFSSL_TIRTOS) && (NO_WOLFSSL_CLIENT) */ - server_args.signal = &ready; - client_args.signal = &ready; - /* the var is used for loop number */ - server_args.argc = 1; + return res; +} - /* test case 1 verify depth is equal to peer chain */ - { - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) +static void test_wolfSSL_CTX_verifyDepth_ServerClient_2_ctx_ready( + WOLFSSL_CTX* ctx) +{ + wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); + myVerifyAction = VERIFY_USE_PREVERFIY; + wolfSSL_CTX_set_verify_depth(ctx, 1); +} +#endif - /* the var is used for verify depth */ - client_args.argc = 2; +static int test_wolfSSL_CTX_verifyDepth_ServerClient_2(void) +{ + int res = TEST_SKIPPED; +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; + callback_functions client_cbf; + callback_functions server_cbf; - test_client_verifyDepth(&client_args); - join_thread(serverThread); - AssertIntEQ(client_args.return_code, TEST_SUCCESS); - AssertIntEQ(server_args.return_code, TEST_SUCCESS); - } + XMEMSET(&client_cbf, 0, sizeof(callback_functions)); + XMEMSET(&server_cbf, 0, sizeof(callback_functions)); + +#ifdef WOLFSSL_TLS13 + client_cbf.method = wolfTLSv1_3_client_method; +#endif /* WOLFSSL_TLS13 */ + client_cbf.ctx_ready = + test_wolfSSL_CTX_verifyDepth_ServerClient_2_ctx_ready; /* test case 2 * verify depth is zero, number of peer's chain is 2. * verify result becomes MAX_CHAIN_ERROR, but it is overridden in * callback. */ + test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); - /* the var is used for verify depth 0 and VERIFY_OVERRIDE_ERROR */ - { - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); + ExpectIntEQ(client_cbf.return_code, TEST_SUCCESS); + ExpectIntEQ(server_cbf.return_code, TEST_SUCCESS); + + res = EXPECT_RESULT(); +#endif /* (OPENSSL_EXTRA) && !(WOLFSSL_TIRTOS) && (NO_WOLFSSL_CLIENT) */ + + return res; +} + +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) +static void test_wolfSSL_CTX_verifyDepth_ServerClient_3_ctx_ready( + WOLFSSL_CTX* ctx) +{ + wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); + myVerifyAction = VERIFY_USE_PREVERFIY; + wolfSSL_CTX_set_verify_depth(ctx, 0); +} +#endif + +static int test_wolfSSL_CTX_verifyDepth_ServerClient_3(void) +{ + int res = TEST_SKIPPED; +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; + callback_functions client_cbf; + callback_functions server_cbf; + + XMEMSET(&client_cbf, 0, sizeof(callback_functions)); + XMEMSET(&server_cbf, 0, sizeof(callback_functions)); + +#ifdef WOLFSSL_TLS13 + client_cbf.method = wolfTLSv1_3_client_method; +#endif /* WOLFSSL_TLS13 */ + client_cbf.ctx_ready = + test_wolfSSL_CTX_verifyDepth_ServerClient_3_ctx_ready; - client_args.argc = 0; - test_client_verifyDepth(&client_args); - join_thread(serverThread); - AssertIntEQ(client_args.return_code, TEST_SUCCESS); - AssertIntEQ(server_args.return_code, TEST_SUCCESS); - } /* test case 3 * verify depth is zero, number of peer's chain is 2 * verify result becomes MAX_CHAIN_ERRO. call-back returns failure. * therefore, handshake becomes failure. */ - /* the var is used for verify depth 0 and VERIFY_USE_PREVERFIY */ - { - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); + test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); - client_args.argc = -1; - test_client_verifyDepth(&client_args); - join_thread(serverThread); - AssertIntEQ(client_args.return_code, TEST_SUCCESS); - AssertIntEQ(server_args.return_code, TEST_SUCCESS); - } + ExpectIntEQ(client_cbf.return_code, TEST_SUCCESS); + ExpectIntEQ(server_cbf.return_code, TEST_SUCCESS); - FreeTcpReady(&ready); - - res = TEST_RES_CHECK(1); -#else - (void)test_client_verifyDepth; + res = EXPECT_RESULT(); #endif /* (OPENSSL_EXTRA) && !(WOLFSSL_TIRTOS) && (NO_WOLFSSL_CLIENT) */ return res; @@ -6975,9 +7109,10 @@ static int test_wolfSSL_CTX_set_cipher_list(void) #if defined(OPENSSL_ALL) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ !defined(WOLFSSL_TIRTOS) && !defined(NO_AES) && !defined(WOLFSSL_NO_TLS12) \ && !defined(NO_SHA256) && defined(HAVE_ECC) - WOLFSSL_CTX* ctx; - WOLFSSL_CTX* ctxClient; - WOLFSSL* sslClient; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL_CTX* ctxClient = NULL; + WOLFSSL* sslClient = NULL; tcp_ready ready; func_args client_args; func_args server_args; @@ -6994,18 +7129,18 @@ static int test_wolfSSL_CTX_set_cipher_list(void) XMEMSET(&client_cb, 0, sizeof(callback_functions)); XMEMSET(&server_cb, 0, sizeof(callback_functions)); - AssertNotNull((ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method()))); - AssertTrue(wolfSSL_CTX_set_cipher_list(ctx, "DEFAULT:!NULL")); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectNotNull((ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method()))); + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctx, "DEFAULT:!NULL")); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); - AssertNotNull((ctxClient = wolfSSL_CTX_new(wolfTLSv1_2_client_method()))); - AssertTrue(wolfSSL_CTX_set_cipher_list(ctxClient, "ECDHE-RSA-AES128-SHA256")); + ExpectNotNull((ctxClient = wolfSSL_CTX_new(wolfTLSv1_2_client_method()))); + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctxClient, "ECDHE-RSA-AES128-SHA256")); client_cb.ctx = ctxClient; server_cb.ctx = ctx; @@ -7019,33 +7154,35 @@ static int test_wolfSSL_CTX_set_cipher_list(void) client_args.callbacks = &client_cb; client_args.return_code = TEST_FAIL; - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); + if (EXPECT_SUCCESS()) { + start_thread(test_server_nofail, &server_args, &serverThread); + wait_tcp_ready(&server_args); + test_client_nofail(&client_args, NULL); + join_thread(serverThread); + } wolfSSL_CTX_free(client_cb.ctx); wolfSSL_CTX_free(server_cb.ctx); - AssertIntEQ(server_args.return_code, TEST_SUCCESS); + ExpectIntEQ(server_args.return_code, TEST_SUCCESS); FreeTcpReady(&ready); /* check with cipher string that has '+' */ - AssertNotNull((ctxClient = wolfSSL_CTX_new(wolfTLSv1_2_client_method()))); - AssertTrue(wolfSSL_CTX_set_cipher_list(ctxClient, "ECDHE+AESGCM")); - AssertNotNull((sslClient = wolfSSL_new(ctxClient))); + ExpectNotNull((ctxClient = wolfSSL_CTX_new(wolfTLSv1_2_client_method()))); + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctxClient, "ECDHE+AESGCM")); + ExpectNotNull((sslClient = wolfSSL_new(ctxClient))); /* check for the existance of an ECDHE ECDSA cipher suite */ - { + if (EXPECT_SUCCESS()) { int i = 0; int found = 0; const char* suite; - WOLF_STACK_OF(WOLFSSL_CIPHER)* sk; + WOLF_STACK_OF(WOLFSSL_CIPHER)* sk = NULL; WOLFSSL_CIPHER* current; - AssertNotNull((sk = wolfSSL_get_ciphers_compat(sslClient))); + ExpectNotNull((sk = wolfSSL_get_ciphers_compat(sslClient))); do { current = wolfSSL_sk_SSL_CIPHER_value(sk, i++); if (current) { @@ -7056,13 +7193,13 @@ static int test_wolfSSL_CTX_set_cipher_list(void) } } } while (current); - AssertIntEQ(found, 1); + ExpectIntEQ(found, 1); } wolfSSL_free(sslClient); wolfSSL_CTX_free(ctxClient); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -7203,6 +7340,9 @@ static int test_client_get_finished(void* args, cbType cb) reply[ret] = '\0'; fprintf(stderr, "Server response: %s\n", reply); } + else if (ret < 0) { + goto done; + } ((func_args*)args)->return_code = TEST_SUCCESS; @@ -7223,6 +7363,7 @@ static int test_wolfSSL_get_finished(void) { int res = TEST_SKIPPED; #if !defined(NO_RSA) && defined(WOLFSSL_HAVE_TLS_UNIQUE) + EXPECT_DECLS; tcp_ready ready; func_args client_args; func_args server_args; @@ -7247,16 +7388,16 @@ static int test_wolfSSL_get_finished(void) test_client_get_finished(&client_args, NULL); join_thread(serverThread); - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); + ExpectTrue(client_args.return_code); + ExpectTrue(server_args.return_code); /* test received msg vs sent msg */ - AssertIntEQ(0, XMEMCMP(client_side_msg1, server_side_msg2, MD_MAX_SIZE)); - AssertIntEQ(0, XMEMCMP(client_side_msg2, server_side_msg1, MD_MAX_SIZE)); + ExpectIntEQ(0, XMEMCMP(client_side_msg1, server_side_msg2, MD_MAX_SIZE)); + ExpectIntEQ(0, XMEMCMP(client_side_msg2, server_side_msg1, MD_MAX_SIZE)); FreeTcpReady(&ready); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #else (void)test_client_get_finished; #endif /* !NO_RSA && WOLFSSL_HAVE_TLS_UNIQUE */ @@ -7366,6 +7507,7 @@ static int test_wolfSSL_CTX_add_session(void) #if defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_EXT_CACHE) && \ !defined(SINGLE_THREADED) && defined(WOLFSSL_TLS13) && \ !defined(NO_SESSION_CACHE) + EXPECT_DECLS; tcp_ready ready; func_args client_args; func_args server_args; @@ -7446,17 +7588,23 @@ static int test_wolfSSL_CTX_add_session(void) test_client_nofail(&client_args, NULL); join_thread(serverThread); - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); + ExpectTrue(client_args.return_code); + ExpectTrue(server_args.return_code); FreeTcpReady(&ready); + + if (EXPECT_FAIL()) + break; } wolfSSL_SESSION_free(test_wolfSSL_CTX_add_session_client_sess); wolfSSL_SESSION_free(test_wolfSSL_CTX_add_session_server_sess); wolfSSL_CTX_free(test_wolfSSL_CTX_add_session_server_ctx); + + if (EXPECT_FAIL()) + break; } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -7789,6 +7937,7 @@ static int test_wolfSSL_CTX_add_session_ext(void) !defined(HUGE_SESSION_CACHE) && \ !defined(BIG_SESSION_CACHE) && \ !defined(MEDIUM_SESSION_CACHE) + EXPECT_DECLS; /* Test the default 33 sessions */ struct test_params { @@ -7891,26 +8040,29 @@ static int test_wolfSSL_CTX_add_session_ext(void) test_wolfSSL_client_server_nofail(&client_cb, &server_cb); - AssertTrue(client_cb.return_code); - AssertTrue(server_cb.return_code); - AssertIntEQ(twcase_get_session_called, 0); + ExpectTrue(client_cb.return_code); + ExpectTrue(server_cb.return_code); + ExpectIntEQ(twcase_get_session_called, 0); + if (EXPECT_FAIL()) + break; + switch (j) { case 0: case 1: case 2: /* cache cannot be searched with out a connection */ /* Add a new session */ - AssertIntEQ(twcase_new_session_called, 1); + ExpectIntEQ(twcase_new_session_called, 1); /* In twcase_server_sess_ctx_pre_shutdown * wolfSSL_CTX_add_session which evicts the existing session * in cache and adds it back in */ - AssertIntLE(twcase_remove_session_called, 1); + ExpectIntLE(twcase_remove_session_called, 1); break; case 3: case 4: /* no external cache */ - AssertIntEQ(twcase_new_session_called, 0); - AssertIntEQ(twcase_remove_session_called, 0); + ExpectIntEQ(twcase_new_session_called, 0); + ExpectIntEQ(twcase_remove_session_called, 0); break; } @@ -7931,8 +8083,8 @@ static int test_wolfSSL_CTX_add_session_ext(void) test_wolfSSL_client_server_nofail(&client_cb, &server_cb); - AssertTrue(client_cb.return_code); - AssertTrue(server_cb.return_code); + ExpectTrue(client_cb.return_code); + ExpectTrue(server_cb.return_code); /* Clear cache before checking */ wolfSSL_CTX_flush_sessions(NULL, -1); @@ -7944,12 +8096,12 @@ static int test_wolfSSL_CTX_add_session_ext(void) /* cache hit */ /* DTLS accesses cache once for stateless parsing and * once for stateful parsing */ - AssertIntEQ(twcase_get_session_called, !dtls ? 1 : 2); + ExpectIntEQ(twcase_get_session_called, !dtls ? 1 : 2); /* (D)TLSv1.3 creates a new ticket, * updates both internal and external cache */ - AssertIntEQ(twcase_new_session_called, 1); - AssertIntEQ(twcase_remove_session_called, 1); + ExpectIntEQ(twcase_new_session_called, 1); + ExpectIntEQ(twcase_remove_session_called, 1); } else { @@ -7957,27 +8109,27 @@ static int test_wolfSSL_CTX_add_session_ext(void) /* DTLS accesses cache once for stateless parsing and * once for stateful parsing */ #ifdef WOLFSSL_DTLS_NO_HVR_ON_RESUME - AssertIntEQ(twcase_get_session_called, !dtls ? 1 : 2); + ExpectIntEQ(twcase_get_session_called, !dtls ? 1 : 2); #else - AssertIntEQ(twcase_get_session_called, 1); + ExpectIntEQ(twcase_get_session_called, 1); #endif - AssertIntEQ(twcase_new_session_called, 0); + ExpectIntEQ(twcase_new_session_called, 0); /* Called on session added in * twcase_server_sess_ctx_pre_shutdown */ - AssertIntEQ(twcase_remove_session_called, 1); + ExpectIntEQ(twcase_remove_session_called, 1); } break; case 1: if (tls13) { /* (D)TLSv1.3 case */ /* cache hit */ - AssertIntEQ(twcase_get_session_called, 1); + ExpectIntEQ(twcase_get_session_called, 1); /* (D)TLSv1.3 creates a new ticket, * updates both internal and external cache */ - AssertIntEQ(twcase_new_session_called, 1); + ExpectIntEQ(twcase_new_session_called, 1); /* Called on session added in * twcase_server_sess_ctx_pre_shutdown and by wolfSSL */ - AssertIntEQ(twcase_remove_session_called, 1); + ExpectIntEQ(twcase_remove_session_called, 1); } else { /* non (D)TLSv1.3 case */ @@ -7985,27 +8137,27 @@ static int test_wolfSSL_CTX_add_session_ext(void) /* DTLS accesses cache once for stateless parsing and * once for stateful parsing */ #ifdef WOLFSSL_DTLS_NO_HVR_ON_RESUME - AssertIntEQ(twcase_get_session_called, !dtls ? 1 : 2); + ExpectIntEQ(twcase_get_session_called, !dtls ? 1 : 2); #else - AssertIntEQ(twcase_get_session_called, 1); + ExpectIntEQ(twcase_get_session_called, 1); #endif - AssertIntEQ(twcase_new_session_called, 0); + ExpectIntEQ(twcase_new_session_called, 0); /* Called on session added in * twcase_server_sess_ctx_pre_shutdown */ - AssertIntEQ(twcase_remove_session_called, 1); + ExpectIntEQ(twcase_remove_session_called, 1); } break; case 2: if (tls13) { /* (D)TLSv1.3 case */ /* cache hit */ - AssertIntEQ(twcase_get_session_called, 1); + ExpectIntEQ(twcase_get_session_called, 1); /* (D)TLSv1.3 creates a new ticket, * updates both internal and external cache */ - AssertIntEQ(twcase_new_session_called, 1); + ExpectIntEQ(twcase_new_session_called, 1); /* Called on session added in * twcase_server_sess_ctx_pre_shutdown and by wolfSSL */ - AssertIntEQ(twcase_remove_session_called, 1); + ExpectIntEQ(twcase_remove_session_called, 1); } else { /* non (D)TLSv1.3 case */ @@ -8013,35 +8165,41 @@ static int test_wolfSSL_CTX_add_session_ext(void) /* DTLS accesses cache once for stateless parsing and * once for stateful parsing */ #ifdef WOLFSSL_DTLS_NO_HVR_ON_RESUME - AssertIntEQ(twcase_get_session_called, !dtls ? 1 : 2); + ExpectIntEQ(twcase_get_session_called, !dtls ? 1 : 2); #else - AssertIntEQ(twcase_get_session_called, 1); + ExpectIntEQ(twcase_get_session_called, 1); #endif - AssertIntEQ(twcase_new_session_called, 0); + ExpectIntEQ(twcase_new_session_called, 0); /* Called on session added in * twcase_server_sess_ctx_pre_shutdown */ - AssertIntEQ(twcase_remove_session_called, 1); + ExpectIntEQ(twcase_remove_session_called, 1); } break; case 3: case 4: /* no external cache */ - AssertIntEQ(twcase_get_session_called, 0); - AssertIntEQ(twcase_new_session_called, 0); - AssertIntEQ(twcase_remove_session_called, 0); + ExpectIntEQ(twcase_get_session_called, 0); + ExpectIntEQ(twcase_new_session_called, 0); + ExpectIntEQ(twcase_remove_session_called, 0); break; } wolfSSL_SESSION_free(twcase_client_first_session_ptr); wolfSSL_SESSION_free(twcase_server_first_session_ptr); wolfSSL_CTX_free(twcase_server_current_ctx_ptr); + + if (EXPECT_FAIL()) + break; } twcase_get_sessionCb_cleanup(); XMEMSET(&server_sessionCache.entries, 0, sizeof(server_sessionCache.entries)); fprintf(stderr, "\tEnd %s\n", params[i].tls_version); + + if (EXPECT_FAIL()) + break; } wc_FreeMutex(&server_sessionCache.htLock); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -8108,6 +8266,7 @@ static int test_wolfSSL_dtls_export(void) { int res = TEST_SKIPPED; #if defined(WOLFSSL_DTLS) && defined(WOLFSSL_SESSION_EXPORT) + EXPECT_DECLS; tcp_ready ready; func_args client_args; func_args server_args; @@ -8143,8 +8302,8 @@ static int test_wolfSSL_dtls_export(void) run_wolfssl_client(&client_args); join_thread(serverThread); - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); + ExpectTrue(client_args.return_code); + ExpectTrue(server_args.return_code); FreeTcpReady(&ready); @@ -8152,15 +8311,16 @@ static int test_wolfSSL_dtls_export(void) fdOpenSession(Task_self()); #endif - { + if (EXPECT_SUCCESS()) { SOCKET_T sockfd = 0; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; char msg[64] = "hello wolfssl!"; char reply[1024]; int msgSz = (int)XSTRLEN(msg); byte *session, *window; - unsigned int sessionSz, windowSz; + unsigned int sessionSz = 0; + unsigned int windowSz = 0; #ifndef TEST_IPV6 struct sockaddr_in peerAddr; @@ -8172,17 +8332,17 @@ static int test_wolfSSL_dtls_export(void) /* Set ctx to DTLS 1.2 */ - AssertNotNull(ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method())); - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); /* test importing version 3 */ - AssertIntGE(wolfSSL_dtls_import(ssl, version_3, sizeof(version_3)), 0); + ExpectIntGE(wolfSSL_dtls_import(ssl, version_3, sizeof(version_3)), 0); /* test importing bad length and bad version */ version_3[2] += 1; - AssertIntLT(wolfSSL_dtls_import(ssl, version_3, sizeof(version_3)), 0); + ExpectIntLT(wolfSSL_dtls_import(ssl, version_3, sizeof(version_3)), 0); version_3[2] -= 1; version_3[1] = 0XA0; - AssertIntLT(wolfSSL_dtls_import(ssl, version_3, sizeof(version_3)), 0); + ExpectIntLT(wolfSSL_dtls_import(ssl, version_3, sizeof(version_3)), 0); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); @@ -8213,55 +8373,55 @@ static int test_wolfSSL_dtls_export(void) wait_tcp_ready(&server_args); /* create and connect with client */ - AssertNotNull(ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method())); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method())); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); tcp_connect(&sockfd, wolfSSLIP, server_args.signal->port, 1, 0, NULL); - AssertNotNull(ssl = wolfSSL_new(ctx)); - AssertIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + ExpectIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); /* store server information connected too */ XMEMSET(&peerAddr, 0, sizeof(peerAddr)); #ifndef TEST_IPV6 peerAddr.sin_family = AF_INET; - AssertIntEQ(XINET_PTON(AF_INET, wolfSSLIP, &peerAddr.sin_addr),1); + ExpectIntEQ(XINET_PTON(AF_INET, wolfSSLIP, &peerAddr.sin_addr),1); peerAddr.sin_port = XHTONS(server_args.signal->port); #else peerAddr.sin6_family = AF_INET6; - AssertIntEQ( + ExpectIntEQ( XINET_PTON(AF_INET6, wolfSSLIP, &peerAddr.sin6_addr),1); peerAddr.sin6_port = XHTONS(server_args.signal->port); #endif - AssertIntEQ(wolfSSL_dtls_set_peer(ssl, &peerAddr, sizeof(peerAddr)), + ExpectIntEQ(wolfSSL_dtls_set_peer(ssl, &peerAddr, sizeof(peerAddr)), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_connect(ssl), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_dtls_export(ssl, NULL, &sessionSz), 0); + ExpectIntEQ(wolfSSL_connect(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_dtls_export(ssl, NULL, &sessionSz), 0); session = (byte*)XMALLOC(sessionSz, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); - AssertIntGT(wolfSSL_dtls_export(ssl, session, &sessionSz), 0); - AssertIntEQ(wolfSSL_write(ssl, msg, msgSz), msgSz); - AssertIntGT(wolfSSL_read(ssl, reply, sizeof(reply)), 0); - AssertIntEQ(wolfSSL_dtls_export_state_only(ssl, NULL, &windowSz), 0); + ExpectIntGT(wolfSSL_dtls_export(ssl, session, &sessionSz), 0); + ExpectIntEQ(wolfSSL_write(ssl, msg, msgSz), msgSz); + ExpectIntGT(wolfSSL_read(ssl, reply, sizeof(reply)), 0); + ExpectIntEQ(wolfSSL_dtls_export_state_only(ssl, NULL, &windowSz), 0); window = (byte*)XMALLOC(windowSz, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); - AssertIntGT(wolfSSL_dtls_export_state_only(ssl, window, &windowSz), 0); + ExpectIntGT(wolfSSL_dtls_export_state_only(ssl, window, &windowSz), 0); wolfSSL_free(ssl); for (i = 1; i < server_args.argc; i++) { /* restore state */ - AssertNotNull(ssl = wolfSSL_new(ctx)); - AssertIntGT(wolfSSL_dtls_import(ssl, session, sessionSz), 0); - AssertIntGT(wolfSSL_dtls_import(ssl, window, windowSz), 0); - AssertIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_dtls_set_peer(ssl, &peerAddr, sizeof(peerAddr)), + ExpectNotNull(ssl = wolfSSL_new(ctx)); + ExpectIntGT(wolfSSL_dtls_import(ssl, session, sessionSz), 0); + ExpectIntGT(wolfSSL_dtls_import(ssl, window, windowSz), 0); + ExpectIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_dtls_set_peer(ssl, &peerAddr, sizeof(peerAddr)), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_write(ssl, msg, msgSz), msgSz); - AssertIntGE(wolfSSL_read(ssl, reply, sizeof(reply)), 0); - AssertIntGT(wolfSSL_dtls_export_state_only(ssl, window, &windowSz), 0); + ExpectIntEQ(wolfSSL_write(ssl, msg, msgSz), msgSz); + ExpectIntGE(wolfSSL_read(ssl, reply, sizeof(reply)), 0); + ExpectIntGT(wolfSSL_dtls_export_state_only(ssl, window, &windowSz), 0); wolfSSL_free(ssl); } XFREE(session, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); @@ -8270,7 +8430,7 @@ static int test_wolfSSL_dtls_export(void) fprintf(stderr, "done and waiting for server\n"); join_thread(serverThread); - AssertIntEQ(server_args.return_code, TEST_SUCCESS); + ExpectIntEQ(server_args.return_code, TEST_SUCCESS); FreeTcpReady(&ready); @@ -8279,7 +8439,7 @@ static int test_wolfSSL_dtls_export(void) #endif } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -8478,21 +8638,6 @@ static THREAD_RETURN WOLFSSL_THREAD tls_export_server(void* args) ((func_args*)args)->return_code = TEST_FAIL; cbf = ((func_args*)args)->callbacks; - { - WOLFSSL_METHOD* method = NULL; - if (cbf != NULL && cbf->method != NULL) { - method = cbf->method(); - } - else { - method = wolfTLSv1_2_server_method(); - } - ctx = wolfSSL_CTX_new(method); - } - if (ctx == NULL) { - goto done; - } - wolfSSL_CTX_set_cipher_list(ctx, "ECDHE-RSA-AES128-SHA256"); - #if defined(USE_WINDOWS_API) port = ((func_args*)args)->signal->port; #elif defined(NO_MAIN_DRIVER) && !defined(WOLFSSL_SNIFFER) && \ @@ -8508,6 +8653,21 @@ static THREAD_RETURN WOLFSSL_THREAD tls_export_server(void* args) tcp_accept(&sockfd, &clientfd, (func_args*)args, port, 0, 0, 0, 0, 1, 0, 0); CloseSocket(sockfd); + { + WOLFSSL_METHOD* method = NULL; + if (cbf != NULL && cbf->method != NULL) { + method = cbf->method(); + } + else { + method = wolfTLSv1_2_server_method(); + } + ctx = wolfSSL_CTX_new(method); + } + if (ctx == NULL) { + goto done; + } + wolfSSL_CTX_set_cipher_list(ctx, "ECDHE-RSA-AES128-SHA256"); + /* call ctx setup callback */ if (cbf != NULL && cbf->ctx_ready != NULL) { cbf->ctx_ready(ctx); @@ -8604,6 +8764,7 @@ static void load_tls13_canned_server(WOLFSSL* ssl) /* v is for version WOLFSSL_TLSV1_2 or WOLFSSL_TLSV1_3 */ static int test_wolfSSL_tls_export_run(int v) { + EXPECT_DECLS; SOCKET_T sockfd = 0; WOLFSSL_CTX* ctx = 0; WOLFSSL* ssl = 0; @@ -8638,7 +8799,7 @@ static int test_wolfSSL_tls_export_run(int v) server_cbf.ssl_ready = load_tls12_canned_server; /* setup the client side */ - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); wolfSSL_CTX_set_cipher_list(ctx, "ECDHE-RSA-AES128-SHA256"); clientSession = canned_client_session; clientSessionSz = sizeof(canned_client_session); @@ -8649,7 +8810,7 @@ static int test_wolfSSL_tls_export_run(int v) server_cbf.ssl_ready = load_tls13_canned_server; /* setup the client side */ - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); clientSession = canned_client_tls13_session; clientSessionSz = sizeof(canned_client_tls13_session); break; @@ -8666,20 +8827,20 @@ static int test_wolfSSL_tls_export_run(int v) fdOpenSession(Task_self()); #endif - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); tcp_connect(&sockfd, wolfSSLIP, ready.port, 0, 0, ssl); - AssertIntEQ(wolfSSL_tls_import(ssl, clientSession, clientSessionSz), + ExpectIntEQ(wolfSSL_tls_import(ssl, clientSession, clientSessionSz), clientSessionSz); replySz = sizeof(reply); - AssertIntGT(wolfSSL_tls_export(ssl, (byte*)reply, &replySz), 0); + ExpectIntGT(wolfSSL_tls_export(ssl, (byte*)reply, &replySz), 0); #if !defined(NO_PSK) && defined(HAVE_ANON) /* index 20 has is setting if PSK was on and 49 is if anon is allowed */ - AssertIntEQ(XMEMCMP(reply, clientSession, replySz), 0); + ExpectIntEQ(XMEMCMP(reply, clientSession, replySz), 0); #endif wolfSSL_set_fd(ssl, sockfd); - AssertIntEQ(wolfSSL_write(ssl, msg, msgSz), msgSz); - AssertIntGT(wolfSSL_read(ssl, reply, sizeof(reply)-1), 0); + ExpectIntEQ(wolfSSL_write(ssl, msg, msgSz), msgSz); + ExpectIntGT(wolfSSL_read(ssl, reply, sizeof(reply)-1), 0); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); @@ -8697,15 +8858,14 @@ static int test_wolfSSL_tls_export_run(int v) join_thread(serverThread); - AssertIntEQ(server_args.return_code, TEST_SUCCESS); + ExpectIntEQ(server_args.return_code, TEST_SUCCESS); FreeTcpReady(&ready); #ifdef WOLFSSL_TIRTOS fdOpenSession(Task_self()); #endif - - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } #endif @@ -8782,29 +8942,30 @@ static int test_wolfSSL_UseSNI_params(void) { int res = TEST_SKIPPED; #if !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); WOLFSSL *ssl = wolfSSL_new(ctx); - AssertNotNull(ctx); - AssertNotNull(ssl); + ExpectNotNull(ctx); + ExpectNotNull(ssl); /* invalid [ctx|ssl] */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSNI(NULL, 0, "ctx", 3)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSNI( NULL, 0, "ssl", 3)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSNI(NULL, 0, "ctx", 3)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSNI( NULL, 0, "ssl", 3)); /* invalid type */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx, -1, "ctx", 3)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSNI( ssl, -1, "ssl", 3)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx, -1, "ctx", 3)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSNI( ssl, -1, "ssl", 3)); /* invalid data */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx, 0, NULL, 3)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSNI( ssl, 0, NULL, 3)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx, 0, NULL, 3)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSNI( ssl, 0, NULL, 3)); /* success case */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx, 0, "ctx", 3)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSNI( ssl, 0, "ssl", 3)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSNI(ctx, 0, "ctx", 3)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSNI( ssl, 0, "ssl", 3)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT */ return res; @@ -9013,6 +9174,7 @@ static int test_wolfSSL_UseSNI_connection(void) static int test_wolfSSL_SNI_GetFromBuffer(void) { + EXPECT_DECLS; byte buff[] = { /* www.paypal.com */ 0x00, 0x00, 0x00, 0x00, 0xff, 0x01, 0x00, 0x00, 0x60, 0x03, 0x03, 0x5c, 0xc4, 0xb3, 0x8c, 0x87, 0xef, 0xa4, 0x09, 0xe0, 0x02, 0xab, 0x86, 0xca, @@ -9086,60 +9248,60 @@ static int test_wolfSSL_SNI_GetFromBuffer(void) byte result[32] = {0}; word32 length = 32; - AssertIntEQ(0, wolfSSL_SNI_GetFromBuffer(buff4, sizeof(buff4), + ExpectIntEQ(0, wolfSSL_SNI_GetFromBuffer(buff4, sizeof(buff4), 0, result, &length)); - AssertIntEQ(0, wolfSSL_SNI_GetFromBuffer(buff3, sizeof(buff3), + ExpectIntEQ(0, wolfSSL_SNI_GetFromBuffer(buff3, sizeof(buff3), 0, result, &length)); - AssertIntEQ(0, wolfSSL_SNI_GetFromBuffer(buff2, sizeof(buff2), + ExpectIntEQ(0, wolfSSL_SNI_GetFromBuffer(buff2, sizeof(buff2), 1, result, &length)); - AssertIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), + ExpectIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), 0, result, &length)); buff[0] = 0x16; - AssertIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), + ExpectIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), 0, result, &length)); buff[1] = 0x03; - AssertIntEQ(SNI_UNSUPPORTED, wolfSSL_SNI_GetFromBuffer(buff, + ExpectIntEQ(SNI_UNSUPPORTED, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), 0, result, &length)); buff[2] = 0x03; - AssertIntEQ(INCOMPLETE_DATA, wolfSSL_SNI_GetFromBuffer(buff, + ExpectIntEQ(INCOMPLETE_DATA, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), 0, result, &length)); buff[4] = 0x64; - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), 0, result, &length)); result[length] = 0; - AssertStrEQ("www.paypal.com", (const char*) result); + ExpectStrEQ("www.paypal.com", (const char*) result); length = 32; - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SNI_GetFromBuffer(buff2, sizeof(buff2), + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SNI_GetFromBuffer(buff2, sizeof(buff2), 0, result, &length)); result[length] = 0; - AssertStrEQ("api.textmate.org", (const char*) result); + ExpectStrEQ("api.textmate.org", (const char*) result); /* SSL v2.0 tests */ - AssertIntEQ(SNI_UNSUPPORTED, wolfSSL_SNI_GetFromBuffer(buff5, + ExpectIntEQ(SNI_UNSUPPORTED, wolfSSL_SNI_GetFromBuffer(buff5, sizeof(buff5), 0, result, &length)); buff5[2] = 0x02; - AssertIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff5, + ExpectIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff5, sizeof(buff5), 0, result, &length)); buff5[2] = 0x01; buff5[6] = 0x08; - AssertIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff5, + ExpectIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff5, sizeof(buff5), 0, result, &length)); buff5[6] = 0x09; buff5[8] = 0x01; - AssertIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff5, + ExpectIntEQ(BUFFER_ERROR, wolfSSL_SNI_GetFromBuffer(buff5, sizeof(buff5), 0, result, &length)); - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } #endif /* HAVE_SNI */ @@ -9152,49 +9314,50 @@ static int test_wolfSSL_UseTrustedCA(void) #if defined(HAVE_TRUSTED_CA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) \ && !defined(NO_RSA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX *ctx; - WOLFSSL *ssl; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; byte id[20]; #ifndef NO_WOLFSSL_SERVER - AssertNotNull((ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()))); - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); + ExpectNotNull((ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()))); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); #else - AssertNotNull((ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()))); + ExpectNotNull((ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()))); #endif - AssertNotNull((ssl = wolfSSL_new(ctx))); + ExpectNotNull((ssl = wolfSSL_new(ctx))); XMEMSET(id, 0, sizeof(id)); /* error cases */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(NULL, 0, NULL, 0)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(NULL, 0, NULL, 0)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, WOLFSSL_TRUSTED_CA_CERT_SHA1+1, NULL, 0)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, WOLFSSL_TRUSTED_CA_CERT_SHA1, NULL, 0)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, WOLFSSL_TRUSTED_CA_CERT_SHA1, id, 5)); #ifdef NO_SHA - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, WOLFSSL_TRUSTED_CA_KEY_SHA1, id, sizeof(id))); #endif - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, WOLFSSL_TRUSTED_CA_X509_NAME, id, 0)); /* success cases */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, WOLFSSL_TRUSTED_CA_PRE_AGREED, NULL, 0)); #ifndef NO_SHA - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, WOLFSSL_TRUSTED_CA_KEY_SHA1, id, sizeof(id))); #endif - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseTrustedCA(ssl, WOLFSSL_TRUSTED_CA_X509_NAME, id, 5)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* HAVE_TRUSTED_CA */ return res; @@ -9207,12 +9370,13 @@ static int test_wolfSSL_UseMaxFragment(void) !defined(NO_FILESYSTEM) && !defined(NO_RSA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; #ifndef NO_WOLFSSL_SERVER WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); #else WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); #endif - WOLFSSL *ssl; + WOLFSSL *ssl = NULL; #ifdef OPENSSL_EXTRA int (*UseMaxFragment)(SSL *s, uint8_t mode); int (*CTX_UseMaxFragment)(SSL_CTX *c, uint8_t mode); @@ -9222,14 +9386,13 @@ static int test_wolfSSL_UseMaxFragment(void) #endif #ifndef NO_WOLFSSL_SERVER - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); #endif - AssertNotNull(ctx); + ExpectNotNull(ctx); - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); + ExpectNotNull(ssl = wolfSSL_new(ctx)); #ifdef OPENSSL_EXTRA CTX_UseMaxFragment = SSL_CTX_set_tlsext_max_fragment_length; @@ -9240,47 +9403,47 @@ static int test_wolfSSL_UseMaxFragment(void) #endif /* error cases */ - AssertIntNE(WOLFSSL_SUCCESS, CTX_UseMaxFragment(NULL, WOLFSSL_MFL_2_9)); - AssertIntNE(WOLFSSL_SUCCESS, UseMaxFragment( NULL, WOLFSSL_MFL_2_9)); - AssertIntNE(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_MIN-1)); - AssertIntNE(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_MAX+1)); - AssertIntNE(WOLFSSL_SUCCESS, UseMaxFragment(ssl, WOLFSSL_MFL_MIN-1)); - AssertIntNE(WOLFSSL_SUCCESS, UseMaxFragment(ssl, WOLFSSL_MFL_MAX+1)); + ExpectIntNE(WOLFSSL_SUCCESS, CTX_UseMaxFragment(NULL, WOLFSSL_MFL_2_9)); + ExpectIntNE(WOLFSSL_SUCCESS, UseMaxFragment( NULL, WOLFSSL_MFL_2_9)); + ExpectIntNE(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_MIN-1)); + ExpectIntNE(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_MAX+1)); + ExpectIntNE(WOLFSSL_SUCCESS, UseMaxFragment(ssl, WOLFSSL_MFL_MIN-1)); + ExpectIntNE(WOLFSSL_SUCCESS, UseMaxFragment(ssl, WOLFSSL_MFL_MAX+1)); /* success case */ #ifdef OPENSSL_EXTRA - AssertIntEQ(BAD_FUNC_ARG, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_8)); + ExpectIntEQ(BAD_FUNC_ARG, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_8)); #else - AssertIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_8)); + ExpectIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_8)); #endif - AssertIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_9)); - AssertIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_10)); - AssertIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_11)); - AssertIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_12)); + ExpectIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_9)); + ExpectIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_10)); + ExpectIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_11)); + ExpectIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_12)); #ifdef OPENSSL_EXTRA - AssertIntEQ(BAD_FUNC_ARG, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_13)); + ExpectIntEQ(BAD_FUNC_ARG, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_13)); - AssertIntEQ(BAD_FUNC_ARG, UseMaxFragment( ssl, WOLFSSL_MFL_2_8)); + ExpectIntEQ(BAD_FUNC_ARG, UseMaxFragment( ssl, WOLFSSL_MFL_2_8)); #else - AssertIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_13)); + ExpectIntEQ(WOLFSSL_SUCCESS, CTX_UseMaxFragment(ctx, WOLFSSL_MFL_2_13)); - AssertIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_8)); + ExpectIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_8)); #endif - AssertIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_9)); - AssertIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_10)); - AssertIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_11)); - AssertIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_12)); + ExpectIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_9)); + ExpectIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_10)); + ExpectIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_11)); + ExpectIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_12)); #ifdef OPENSSL_EXTRA - AssertIntEQ(BAD_FUNC_ARG, UseMaxFragment( ssl, WOLFSSL_MFL_2_13)); + ExpectIntEQ(BAD_FUNC_ARG, UseMaxFragment( ssl, WOLFSSL_MFL_2_13)); #else - AssertIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_13)); + ExpectIntEQ(WOLFSSL_SUCCESS, UseMaxFragment( ssl, WOLFSSL_MFL_2_13)); #endif wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif return res; @@ -9292,35 +9455,35 @@ static int test_wolfSSL_UseTruncatedHMAC(void) #if defined(HAVE_TRUNCATED_HMAC) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; #ifndef NO_WOLFSSL_SERVER WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); #else WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); #endif - WOLFSSL *ssl; + WOLFSSL *ssl = NULL; - AssertNotNull(ctx); + ExpectNotNull(ctx); #ifndef NO_WOLFSSL_SERVER - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); #endif - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); + ExpectNotNull(ssl = wolfSSL_new(ctx)); /* error cases */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseTruncatedHMAC(NULL)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTruncatedHMAC(NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseTruncatedHMAC(NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseTruncatedHMAC(NULL)); /* success case */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseTruncatedHMAC(ctx)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseTruncatedHMAC(ssl)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseTruncatedHMAC(ctx)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseTruncatedHMAC(ssl)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif return res; @@ -9329,32 +9492,34 @@ static int test_wolfSSL_UseTruncatedHMAC(void) static int test_wolfSSL_UseSupportedCurve(void) { int res = TEST_SKIPPED; -#if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS) +#if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_TLS) + EXPECT_DECLS; WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); WOLFSSL *ssl = wolfSSL_new(ctx); - AssertNotNull(ctx); - AssertNotNull(ssl); + ExpectNotNull(ctx); + ExpectNotNull(ssl); /* error cases */ - AssertIntNE(WOLFSSL_SUCCESS, - wolfSSL_CTX_UseSupportedCurve(NULL, WOLFSSL_ECC_SECP256R1)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSupportedCurve(ctx, 0)); + ExpectIntNE(WOLFSSL_SUCCESS, + wolfSSL_CTX_UseSupportedCurve(NULL, WOLFSSL_ECC_SECP256R1)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSupportedCurve(ctx, 0)); - AssertIntNE(WOLFSSL_SUCCESS, - wolfSSL_UseSupportedCurve(NULL, WOLFSSL_ECC_SECP256R1)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSupportedCurve(ssl, 0)); + ExpectIntNE(WOLFSSL_SUCCESS, + wolfSSL_UseSupportedCurve(NULL, WOLFSSL_ECC_SECP256R1)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSupportedCurve(ssl, 0)); /* success case */ - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_UseSupportedCurve(ctx, WOLFSSL_ECC_SECP256R1)); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP256R1)); + ExpectIntEQ(WOLFSSL_SUCCESS, + wolfSSL_CTX_UseSupportedCurve(ctx, WOLFSSL_ECC_SECP256R1)); + ExpectIntEQ(WOLFSSL_SUCCESS, + wolfSSL_UseSupportedCurve(ssl, WOLFSSL_ECC_SECP256R1)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -9558,6 +9723,7 @@ static int test_wolfSSL_UseALPN_params(void) { int res = TEST_SKIPPED; #ifndef NO_WOLFSSL_CLIENT + EXPECT_DECLS; /* "http/1.1" */ char http1[] = {0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31}; /* "spdy/1" */ @@ -9572,19 +9738,19 @@ static int test_wolfSSL_UseALPN_params(void) WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); WOLFSSL *ssl = wolfSSL_new(ctx); - AssertNotNull(ctx); - AssertNotNull(ssl); + ExpectNotNull(ctx); + ExpectNotNull(ssl); /* error cases */ - AssertIntNE(WOLFSSL_SUCCESS, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseALPN(NULL, http1, sizeof(http1), WOLFSSL_ALPN_FAILED_ON_MISMATCH)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, NULL, 0, - WOLFSSL_ALPN_FAILED_ON_MISMATCH)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, NULL, 0, + WOLFSSL_ALPN_FAILED_ON_MISMATCH)); /* success case */ /* http1 only */ - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, http1, sizeof(http1), WOLFSSL_ALPN_FAILED_ON_MISMATCH)); @@ -9594,8 +9760,8 @@ static int test_wolfSSL_UseALPN_params(void) buff[idx++] = ','; XMEMCPY(buff+idx, spdy1, sizeof(spdy1)); idx += sizeof(spdy1); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, buff, idx, - WOLFSSL_ALPN_FAILED_ON_MISMATCH)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, buff, idx, + WOLFSSL_ALPN_FAILED_ON_MISMATCH)); /* http1, spdy2, spdy1 */ XMEMCPY(buff, http1, sizeof(http1)); @@ -9606,8 +9772,8 @@ static int test_wolfSSL_UseALPN_params(void) buff[idx++] = ','; XMEMCPY(buff+idx, spdy1, sizeof(spdy1)); idx += sizeof(spdy1); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, buff, idx, - WOLFSSL_ALPN_FAILED_ON_MISMATCH)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, buff, idx, + WOLFSSL_ALPN_FAILED_ON_MISMATCH)); /* spdy3, http1, spdy2, spdy1 */ XMEMCPY(buff, spdy3, sizeof(spdy3)); @@ -9621,13 +9787,13 @@ static int test_wolfSSL_UseALPN_params(void) buff[idx++] = ','; XMEMCPY(buff+idx, spdy1, sizeof(spdy1)); idx += sizeof(spdy1); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, buff, idx, - WOLFSSL_ALPN_CONTINUE_ON_MISMATCH)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseALPN(ssl, buff, idx, + WOLFSSL_ALPN_CONTINUE_ON_MISMATCH)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -9728,7 +9894,7 @@ static int test_wolfSSL_set_alpn_protos(void) server_cb.ctx_ready = NULL; server_cb.ssl_ready = set_alpn_protos; server_cb.on_result = verify_alpn_matching_spdy3; test_wolfSSL_client_server(&client_cb, &server_cb); - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif /* !NO_WOLFSSL_CLIENT && !NO_WOLFSSL_SERVER */ return res; } @@ -9739,24 +9905,25 @@ static int test_wolfSSL_DisableExtendedMasterSecret(void) { int res = TEST_SKIPPED; #if defined(HAVE_EXTENDED_MASTER) && !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); WOLFSSL *ssl = wolfSSL_new(ctx); - AssertNotNull(ctx); - AssertNotNull(ssl); + ExpectNotNull(ctx); + ExpectNotNull(ssl); /* error cases */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_DisableExtendedMasterSecret(NULL)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_DisableExtendedMasterSecret(NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_DisableExtendedMasterSecret(NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_DisableExtendedMasterSecret(NULL)); /* success cases */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_DisableExtendedMasterSecret(ctx)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_DisableExtendedMasterSecret(ssl)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_DisableExtendedMasterSecret(ctx)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_DisableExtendedMasterSecret(ssl)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -9765,24 +9932,25 @@ static int test_wolfSSL_wolfSSL_UseSecureRenegotiation(void) { int res = TEST_SKIPPED; #if defined(HAVE_SECURE_RENEGOTIATION) && !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); WOLFSSL *ssl = wolfSSL_new(ctx); - AssertNotNull(ctx); - AssertNotNull(ssl); + ExpectNotNull(ctx); + ExpectNotNull(ssl); /* error cases */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSecureRenegotiation(NULL)); - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSecureRenegotiation(NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSecureRenegotiation(NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_UseSecureRenegotiation(NULL)); /* success cases */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSecureRenegotiation(ctx)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSecureRenegotiation(ssl)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSecureRenegotiation(ctx)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSecureRenegotiation(ssl)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -9795,6 +9963,7 @@ static int test_wolfSSL_SCR_Reconnect(void) #if defined(HAVE_SECURE_RENEGOTIATION) && \ defined(BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) && \ defined(BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256) + EXPECT_DECLS; struct test_memio_ctx test_ctx; WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; WOLFSSL *ssl_c = NULL, *ssl_s = NULL; @@ -9804,21 +9973,21 @@ static int test_wolfSSL_SCR_Reconnect(void) test_ctx.c_ciphers = "ECDHE-RSA-AES256-GCM-SHA384"; test_ctx.s_ciphers = "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305"; - AssertIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, wolfTLSv1_2_client_method, wolfTLSv1_2_server_method), 0); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSecureRenegotiation(ctx_c)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSecureRenegotiation(ctx_s)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSecureRenegotiation(ssl_c)); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSecureRenegotiation(ssl_s)); - AssertIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSecureRenegotiation(ctx_c)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_UseSecureRenegotiation(ctx_s)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSecureRenegotiation(ssl_c)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSecureRenegotiation(ssl_s)); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); /* WOLFSSL_FATAL_ERROR since it will block */ - AssertIntEQ(wolfSSL_Rehandshake(ssl_s), WOLFSSL_FATAL_ERROR); - AssertIntEQ(wolfSSL_get_error(ssl_s, WOLFSSL_FATAL_ERROR), + ExpectIntEQ(wolfSSL_Rehandshake(ssl_s), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(wolfSSL_get_error(ssl_s, WOLFSSL_FATAL_ERROR), WOLFSSL_ERROR_WANT_READ); - AssertIntEQ(wolfSSL_read(ssl_c, &data, 1), WOLFSSL_FATAL_ERROR); - AssertIntEQ(wolfSSL_get_error(ssl_s, WOLFSSL_FATAL_ERROR), + ExpectIntEQ(wolfSSL_read(ssl_c, &data, 1), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(wolfSSL_get_error(ssl_s, WOLFSSL_FATAL_ERROR), WOLFSSL_ERROR_WANT_READ); - AssertIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); wolfSSL_free(ssl_c); ssl_c = NULL; wolfSSL_free(ssl_s); @@ -9826,15 +9995,15 @@ static int test_wolfSSL_SCR_Reconnect(void) wolfSSL_CTX_free(ctx_c); ctx_c = NULL; test_ctx.c_ciphers = "ECDHE-RSA-CHACHA20-POLY1305"; - AssertIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, wolfTLSv1_2_client_method, wolfTLSv1_2_server_method), 0); - AssertIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); wolfSSL_free(ssl_s); wolfSSL_free(ssl_c); wolfSSL_CTX_free(ctx_s); wolfSSL_CTX_free(ctx_c); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -9882,6 +10051,7 @@ static int test_tls_ext_duplicate(void) int res = TEST_SKIPPED; #if !defined(NO_WOLFSSL_SERVER) && (!defined(NO_RSA) || defined(HAVE_ECC)) && \ !defined(NO_FILESYSTEM) + EXPECT_DECLS; const unsigned char clientHelloDupTlsExt[] = { 0x16, 0x03, 0x03, 0x00, 0x6a, 0x01, 0x00, 0x00, 0x66, 0x03, 0x03, 0xf4, 0x65, 0xbd, 0x22, 0xfe, @@ -9905,8 +10075,8 @@ static int test_tls_ext_duplicate(void) WOLFSSL_BUFFER_INFO msg; const char* testCertFile; const char* testKeyFile; - WOLFSSL_CTX *ctx; - WOLFSSL *ssl; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; #ifndef NO_RSA testCertFile = svrCertFile; @@ -9916,12 +10086,11 @@ static int test_tls_ext_duplicate(void) testKeyFile = eccKeyFile; #endif - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, WOLFSSL_FILETYPE_PEM)); /* Read from 'msg'. */ @@ -9930,19 +10099,19 @@ static int test_tls_ext_duplicate(void) wolfSSL_SetIOSend(ctx, DummySend); ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); + ExpectNotNull(ssl); msg.buffer = (unsigned char*)clientHelloDupTlsExt; msg.length = (unsigned int)sizeof(clientHelloDupTlsExt); wolfSSL_SetIOReadCtx(ssl, &msg); - AssertIntNE(wolfSSL_accept(ssl), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_get_error(ssl, 0), DUPLICATE_TLS_EXT_E); + ExpectIntNE(wolfSSL_accept(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_get_error(ssl, 0), DUPLICATE_TLS_EXT_E); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -9957,10 +10126,11 @@ static int test_wolfSSL_X509_NAME_get_entry(void) #if defined(OPENSSL_ALL) || \ (defined(OPENSSL_EXTRA) && \ (defined(KEEP_PEER_CERT) || defined(SESSION_CERTS))) + EXPECT_DECLS; /* use openssl like name to test mapping */ X509_NAME_ENTRY* ne; X509_NAME* name; - X509* x509; + X509* x509 = NULL; #ifndef NO_FILESYSTEM ASN1_STRING* asn; char* subCN = NULL; @@ -9970,51 +10140,44 @@ static int test_wolfSSL_X509_NAME_get_entry(void) #if defined(WOLFSSL_APACHE_HTTPD) || defined(OPENSSL_ALL) || \ defined(WOLFSSL_NGINX) #ifndef NO_BIO - BIO* bio; + BIO* bio = NULL; #endif #endif #ifndef NO_FILESYSTEM - x509 = wolfSSL_X509_load_certificate_file(cliCertFile, - WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); - name = X509_get_subject_name(x509); - idx = X509_NAME_get_index_by_NID(name, NID_commonName, -1); - AssertIntGE(idx, 0); - ne = X509_NAME_get_entry(name, idx); - AssertNotNull(ne); - asn = X509_NAME_ENTRY_get_data(ne); - AssertNotNull(asn); - subCN = (char*)ASN1_STRING_data(asn); - AssertNotNull(subCN); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectNotNull(name = X509_get_subject_name(x509)); + ExpectIntGE(idx = X509_NAME_get_index_by_NID(name, NID_commonName, -1), 0); + ExpectNotNull(ne = X509_NAME_get_entry(name, idx)); + ExpectNotNull(asn = X509_NAME_ENTRY_get_data(ne)); + ExpectNotNull(subCN = (char*)ASN1_STRING_data(asn)); wolfSSL_FreeX509(x509); + x509 = NULL; #endif - x509 = wolfSSL_X509_load_certificate_file(cliCertFile, - WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); - name = X509_get_subject_name(x509); - idx = X509_NAME_get_index_by_NID(name, NID_commonName, -1); - AssertIntGE(idx, 0); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectNotNull(name = X509_get_subject_name(x509)); + ExpectIntGE(idx = X509_NAME_get_index_by_NID(name, NID_commonName, -1), 0); #if defined(WOLFSSL_APACHE_HTTPD) || defined(OPENSSL_ALL) || \ defined(WOLFSSL_NGINX) #ifndef NO_BIO - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(bio, name, 4, + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(bio, name, 4, (XN_FLAG_RFC2253 & ~XN_FLAG_DN_REV)), WOLFSSL_SUCCESS); - AssertIntEQ(X509_NAME_print_ex_fp(stderr, name, 4, + ExpectIntEQ(X509_NAME_print_ex_fp(stderr, name, 4, (XN_FLAG_RFC2253 & ~XN_FLAG_DN_REV)), WOLFSSL_SUCCESS); BIO_free(bio); #endif #endif - ne = X509_NAME_get_entry(name, idx); - AssertNotNull(ne); - AssertNotNull(object = X509_NAME_ENTRY_get_object(ne)); + ExpectNotNull(ne = X509_NAME_get_entry(name, idx)); + ExpectNotNull(object = X509_NAME_ENTRY_get_object(ne)); wolfSSL_FreeX509(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (KEEP_PEER_CERT || SESSION_CERTS) */ #endif /* !NO_CERTS && !NO_RSA */ @@ -10033,6 +10196,7 @@ static int test_wolfSSL_PKCS12(void) #if defined(OPENSSL_EXTRA) && !defined(NO_DES3) && !defined(NO_FILESYSTEM) && \ !defined(NO_ASN) && !defined(NO_PWDBASED) && !defined(NO_RSA) && \ !defined(NO_SHA) && defined(HAVE_PKCS12) && !defined(NO_BIO) + EXPECT_DECLS; byte buf[6000]; char file[] = "./certs/test-servercert.p12"; char order[] = "./certs/ecc-rsa-server.p12"; @@ -10043,70 +10207,71 @@ static int test_wolfSSL_PKCS12(void) const char goodPsw[] = "wolfSSL test"; const char badPsw[] = "bad"; #ifdef HAVE_ECC - WOLFSSL_X509_NAME* subject; - WOLFSSL_X509 *x509; + WOLFSSL_X509_NAME *subject = NULL; + WOLFSSL_X509 *x509 = NULL; #endif - XFILE f; + XFILE f = XBADFILE; int bytes, ret, goodPswLen, badPswLen; - WOLFSSL_BIO *bio; - WOLFSSL_EVP_PKEY *pkey; - WC_PKCS12 *pkcs12; - WC_PKCS12 *pkcs12_2; - WOLFSSL_X509 *cert; - WOLFSSL_X509 *tmp; - WOLF_STACK_OF(WOLFSSL_X509) *ca; + WOLFSSL_BIO *bio = NULL; + WOLFSSL_EVP_PKEY *pkey = NULL; + WC_PKCS12 *pkcs12 = NULL; + WC_PKCS12 *pkcs12_2 = NULL; + WOLFSSL_X509 *cert = NULL; + WOLFSSL_X509 *tmp = NULL; + WOLF_STACK_OF(WOLFSSL_X509) *ca = NULL; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \ || defined(WOLFSSL_NGINX)) && defined(SESSION_CERTS) - WOLFSSL_CTX *ctx; - WOLFSSL *ssl; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; WOLF_STACK_OF(WOLFSSL_X509) *tmp_ca = NULL; #endif - f = XFOPEN(file, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(file, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } goodPswLen = (int)XSTRLEN(goodPsw); badPswLen = (int)XSTRLEN(badPsw); - bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); - AssertNotNull(bio); + ExpectNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(BIO_write(bio, buf, bytes), bytes); /* d2i consumes BIO */ - d2i_PKCS12_bio(bio, &pkcs12); - AssertNotNull(pkcs12); + ExpectIntEQ(BIO_write(bio, buf, bytes), bytes); /* d2i consumes BIO */ + ExpectNotNull(d2i_PKCS12_bio(bio, &pkcs12)); + ExpectNotNull(pkcs12); BIO_free(bio); + bio = NULL; /* check verify MAC directly */ - ret = PKCS12_verify_mac(pkcs12, goodPsw, goodPswLen); - AssertIntEQ(ret, 1); + ExpectIntEQ(ret = PKCS12_verify_mac(pkcs12, goodPsw, goodPswLen), 1); /* check verify MAC fail case directly */ - ret = PKCS12_verify_mac(pkcs12, badPsw, badPswLen); - AssertIntEQ(ret, 0); + ExpectIntEQ(ret = PKCS12_verify_mac(pkcs12, badPsw, badPswLen), 0); /* check verify MAC fail case */ - ret = PKCS12_parse(pkcs12, "bad", &pkey, &cert, NULL); - AssertIntEQ(ret, 0); - AssertNull(pkey); - AssertNull(cert); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "bad", &pkey, &cert, NULL), 0); + ExpectNull(pkey); + ExpectNull(cert); /* check parse with no extra certs kept */ - ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, NULL); - AssertIntEQ(ret, 1); - AssertNotNull(pkey); - AssertNotNull(cert); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, NULL), + 1); + ExpectNotNull(pkey); + ExpectNotNull(cert); wolfSSL_EVP_PKEY_free(pkey); + pkey = NULL; wolfSSL_X509_free(cert); + cert = NULL; /* check parse with extra certs kept */ - ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, &ca); - AssertIntEQ(ret, 1); - AssertNotNull(pkey); - AssertNotNull(cert); - AssertNotNull(ca); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, &ca), + 1); + ExpectNotNull(pkey); + ExpectNotNull(cert); + ExpectNotNull(ca); #if (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \ || defined(WOLFSSL_NGINX)) && defined(SESSION_CERTS) @@ -10114,111 +10279,131 @@ static int test_wolfSSL_PKCS12(void) /* Check that SSL_CTX_set0_chain correctly sets the certChain buffer */ #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) #if !defined(NO_WOLFSSL_CLIENT) && defined(SESSION_CERTS) - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif /* Copy stack structure */ - AssertNotNull(tmp_ca = X509_chain_up_ref(ca)); - AssertIntEQ(SSL_CTX_set0_chain(ctx, tmp_ca), 1); + ExpectNotNull(tmp_ca = X509_chain_up_ref(ca)); + ExpectIntEQ(SSL_CTX_set0_chain(ctx, tmp_ca), 1); /* CTX now owns the tmp_ca stack structure */ tmp_ca = NULL; - AssertIntEQ(wolfSSL_CTX_get_extra_chain_certs(ctx, &tmp_ca), 1); - AssertNotNull(tmp_ca); - AssertIntEQ(sk_X509_num(tmp_ca), sk_X509_num(ca)); + ExpectIntEQ(wolfSSL_CTX_get_extra_chain_certs(ctx, &tmp_ca), 1); + ExpectNotNull(tmp_ca); + ExpectIntEQ(sk_X509_num(tmp_ca), sk_X509_num(ca)); /* Check that the main cert is also set */ - AssertNotNull(SSL_CTX_get0_certificate(ctx)); - AssertNotNull(ssl = SSL_new(ctx)); - AssertNotNull(SSL_get_certificate(ssl)); + ExpectNotNull(SSL_CTX_get0_certificate(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(SSL_get_certificate(ssl)); SSL_free(ssl); SSL_CTX_free(ctx); + ctx = NULL; #endif #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ /* should be 2 other certs on stack */ - tmp = sk_X509_pop(ca); - AssertNotNull(tmp); + ExpectNotNull(tmp = sk_X509_pop(ca)); X509_free(tmp); - tmp = sk_X509_pop(ca); - AssertNotNull(tmp); + ExpectNotNull(tmp = sk_X509_pop(ca)); X509_free(tmp); - AssertNull(sk_X509_pop(ca)); + ExpectNull(sk_X509_pop(ca)); EVP_PKEY_free(pkey); + pkey = NULL; X509_free(cert); + cert = NULL; sk_X509_pop_free(ca, X509_free); + ca = NULL; /* check PKCS12_create */ - AssertNull(PKCS12_create(pass, NULL, NULL, NULL, NULL, -1, -1, -1, -1,0)); - AssertIntEQ(PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, &ca), + ExpectNull(PKCS12_create(pass, NULL, NULL, NULL, NULL, -1, -1, -1, -1,0)); + ExpectIntEQ(PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, &ca), SSL_SUCCESS); - AssertNotNull((pkcs12_2 = PKCS12_create(pass, NULL, pkey, cert, ca, + ExpectNotNull((pkcs12_2 = PKCS12_create(pass, NULL, pkey, cert, ca, -1, -1, 100, -1, 0))); EVP_PKEY_free(pkey); + pkey = NULL; X509_free(cert); + cert = NULL; sk_X509_pop_free(ca, NULL); + ca = NULL; - AssertIntEQ(PKCS12_parse(pkcs12_2, "a password", &pkey, &cert, &ca), + ExpectIntEQ(PKCS12_parse(pkcs12_2, "a password", &pkey, &cert, &ca), SSL_SUCCESS); PKCS12_free(pkcs12_2); - AssertNotNull((pkcs12_2 = PKCS12_create(pass, NULL, pkey, cert, ca, + pkcs12_2 = NULL; + ExpectNotNull((pkcs12_2 = PKCS12_create(pass, NULL, pkey, cert, ca, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, 2000, 1, 0))); EVP_PKEY_free(pkey); + pkey = NULL; X509_free(cert); + cert = NULL; sk_X509_pop_free(ca, NULL); + ca = NULL; /* convert to DER then back and parse */ - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertIntEQ(i2d_PKCS12_bio(bio, pkcs12_2), SSL_SUCCESS); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(i2d_PKCS12_bio(bio, pkcs12_2), SSL_SUCCESS); PKCS12_free(pkcs12_2); + pkcs12_2 = NULL; - AssertNotNull(pkcs12_2 = d2i_PKCS12_bio(bio, NULL)); + ExpectNotNull(pkcs12_2 = d2i_PKCS12_bio(bio, NULL)); BIO_free(bio); - AssertIntEQ(PKCS12_parse(pkcs12_2, "a password", &pkey, &cert, &ca), + bio = NULL; + ExpectIntEQ(PKCS12_parse(pkcs12_2, "a password", &pkey, &cert, &ca), SSL_SUCCESS); /* should be 2 other certs on stack */ - tmp = sk_X509_pop(ca); - AssertNotNull(tmp); + ExpectNotNull(tmp = sk_X509_pop(ca)); X509_free(tmp); - tmp = sk_X509_pop(ca); - AssertNotNull(tmp); + ExpectNotNull(tmp = sk_X509_pop(ca)); X509_free(tmp); - AssertNull(sk_X509_pop(ca)); + ExpectNull(sk_X509_pop(ca)); #ifndef NO_RC4 PKCS12_free(pkcs12_2); - AssertNotNull((pkcs12_2 = PKCS12_create(pass, NULL, pkey, cert, NULL, + pkcs12_2 = NULL; + ExpectNotNull((pkcs12_2 = PKCS12_create(pass, NULL, pkey, cert, NULL, NID_pbe_WithSHA1And128BitRC4, NID_pbe_WithSHA1And128BitRC4, 2000, 1, 0))); EVP_PKEY_free(pkey); + pkey = NULL; X509_free(cert); + cert = NULL; sk_X509_pop_free(ca, NULL); + ca = NULL; - AssertIntEQ(PKCS12_parse(pkcs12_2, "a password", &pkey, &cert, &ca), + ExpectIntEQ(PKCS12_parse(pkcs12_2, "a password", &pkey, &cert, &ca), SSL_SUCCESS); #endif /* NO_RC4 */ EVP_PKEY_free(pkey); + pkey = NULL; X509_free(cert); + cert = NULL; PKCS12_free(pkcs12); + pkcs12 = NULL; PKCS12_free(pkcs12_2); + pkcs12_2 = NULL; sk_X509_pop_free(ca, NULL); + ca = NULL; #ifdef HAVE_ECC /* test order of parsing */ - f = XFOPEN(order, "rb"); - AssertTrue(f != XBADFILE); - bytes = (int)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(order, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } - AssertNotNull(bio = BIO_new_mem_buf((void*)buf, bytes)); - AssertNotNull(pkcs12 = d2i_PKCS12_bio(bio, NULL)); - AssertIntEQ((ret = PKCS12_parse(pkcs12, "", &pkey, &cert, &ca)), + ExpectNotNull(bio = BIO_new_mem_buf((void*)buf, bytes)); + ExpectNotNull(pkcs12 = d2i_PKCS12_bio(bio, NULL)); + ExpectIntEQ((ret = PKCS12_parse(pkcs12, "", &pkey, &cert, &ca)), WOLFSSL_SUCCESS); /* check use of pkey after parse */ @@ -10226,151 +10411,168 @@ static int test_wolfSSL_PKCS12(void) || defined(WOLFSSL_NGINX)) && defined(SESSION_CERTS) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) #if !defined(NO_WOLFSSL_CLIENT) && defined(SESSION_CERTS) - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif - AssertIntEQ(SSL_CTX_use_PrivateKey(ctx, pkey), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_CTX_use_PrivateKey(ctx, pkey), WOLFSSL_SUCCESS); SSL_CTX_free(ctx); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif - AssertNotNull(pkey); - AssertNotNull(cert); - AssertNotNull(ca); + ExpectNotNull(pkey); + ExpectNotNull(cert); + ExpectNotNull(ca); /* compare subject lines of certificates */ - AssertNotNull(subject = wolfSSL_X509_get_subject_name(cert)); - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(eccRsaCertFile, + ExpectNotNull(subject = wolfSSL_X509_get_subject_name(cert)); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(eccRsaCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(wolfSSL_X509_NAME_cmp((const WOLFSSL_X509_NAME*)subject, + ExpectIntEQ(wolfSSL_X509_NAME_cmp((const WOLFSSL_X509_NAME*)subject, (const WOLFSSL_X509_NAME*)wolfSSL_X509_get_subject_name(x509)), 0); X509_free(x509); + x509 = NULL; /* test expected fail case */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(eccCertFile, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(eccCertFile, SSL_FILETYPE_PEM)); - AssertIntNE(wolfSSL_X509_NAME_cmp((const WOLFSSL_X509_NAME*)subject, + ExpectIntNE(wolfSSL_X509_NAME_cmp((const WOLFSSL_X509_NAME*)subject, (const WOLFSSL_X509_NAME*)wolfSSL_X509_get_subject_name(x509)), 0); X509_free(x509); + x509 = NULL; X509_free(cert); + cert = NULL; /* get subject line from ca stack */ - AssertNotNull(cert = sk_X509_pop(ca)); - AssertNotNull(subject = wolfSSL_X509_get_subject_name(cert)); + ExpectNotNull(cert = sk_X509_pop(ca)); + ExpectNotNull(subject = wolfSSL_X509_get_subject_name(cert)); /* compare subject from certificate in ca to expected */ - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(eccCertFile, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(eccCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(wolfSSL_X509_NAME_cmp((const WOLFSSL_X509_NAME*)subject, + ExpectIntEQ(wolfSSL_X509_NAME_cmp((const WOLFSSL_X509_NAME*)subject, (const WOLFSSL_X509_NAME*)wolfSSL_X509_get_subject_name(x509)), 0); EVP_PKEY_free(pkey); + pkey = NULL; X509_free(x509); + x509 = NULL; X509_free(cert); + cert = NULL; BIO_free(bio); + bio = NULL; PKCS12_free(pkcs12); + pkcs12 = NULL; sk_X509_pop_free(ca, NULL); /* TEST d2i_PKCS12_fp */ + ca = NULL; /* test order of parsing */ - f = XFOPEN(file, "rb"); - AssertTrue(f != XBADFILE); - AssertNotNull(pkcs12 = d2i_PKCS12_fp(f, NULL)); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(file, "rb")) != XBADFILE); + ExpectNotNull(pkcs12 = d2i_PKCS12_fp(f, NULL)); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } /* check verify MAC fail case */ - ret = PKCS12_parse(pkcs12, "bad", &pkey, &cert, NULL); - AssertIntEQ(ret, 0); - AssertNull(pkey); - AssertNull(cert); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "bad", &pkey, &cert, NULL), 0); + ExpectNull(pkey); + ExpectNull(cert); /* check parse with no extra certs kept */ - ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, NULL); - AssertIntEQ(ret, 1); - AssertNotNull(pkey); - AssertNotNull(cert); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, NULL), + 1); + ExpectNotNull(pkey); + ExpectNotNull(cert); wolfSSL_EVP_PKEY_free(pkey); + pkey = NULL; wolfSSL_X509_free(cert); + cert = NULL; /* check parse with extra certs kept */ - ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, &ca); - AssertIntEQ(ret, 1); - AssertNotNull(pkey); - AssertNotNull(cert); - AssertNotNull(ca); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, &ca), + 1); + ExpectNotNull(pkey); + ExpectNotNull(cert); + ExpectNotNull(ca); wolfSSL_EVP_PKEY_free(pkey); + pkey = NULL; wolfSSL_X509_free(cert); + cert = NULL; sk_X509_pop_free(ca, NULL); + ca = NULL; PKCS12_free(pkcs12); + pkcs12 = NULL; #endif /* HAVE_ECC */ #ifdef WC_RC2 /* test PKCS#12 with RC2 encryption */ - f = XFOPEN(rc2p12, "rb"); - AssertTrue(f != XBADFILE); - bytes = (int)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(rc2p12, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } - AssertNotNull(bio = BIO_new_mem_buf((void*)buf, bytes)); - AssertNotNull(pkcs12 = d2i_PKCS12_bio(bio, NULL)); + ExpectNotNull(bio = BIO_new_mem_buf((void*)buf, bytes)); + ExpectNotNull(pkcs12 = d2i_PKCS12_bio(bio, NULL)); /* check verify MAC fail case */ - ret = PKCS12_parse(pkcs12, "bad", &pkey, &cert, NULL); - AssertIntEQ(ret, 0); - AssertNull(pkey); - AssertNull(cert); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "bad", &pkey, &cert, NULL), 0); + ExpectNull(pkey); + ExpectNull(cert); /* check parse iwth not extra certs kept */ - ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, NULL); - AssertIntEQ(ret, WOLFSSL_SUCCESS); - AssertNotNull(pkey); - AssertNotNull(cert); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, NULL), + WOLFSSL_SUCCESS); + ExpectNotNull(pkey); + ExpectNotNull(cert); wolfSSL_EVP_PKEY_free(pkey); + pkey = NULL; wolfSSL_X509_free(cert); + cert = NULL; /* check parse with extra certs kept */ - ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, &ca); - AssertIntEQ(ret, WOLFSSL_SUCCESS); - AssertNotNull(pkey); - AssertNotNull(cert); - AssertNotNull(ca); + ExpectIntEQ(ret = PKCS12_parse(pkcs12, "wolfSSL test", &pkey, &cert, &ca), + WOLFSSL_SUCCESS);; + ExpectNotNull(pkey); + ExpectNotNull(cert); + ExpectNotNull(ca); wolfSSL_EVP_PKEY_free(pkey); wolfSSL_X509_free(cert); sk_X509_pop_free(ca, NULL); BIO_free(bio); + bio = NULL; PKCS12_free(pkcs12); + pkcs12 = NULL; #endif /* WC_RC2 */ /* Test i2d_PKCS12_bio */ - f = XFOPEN(file, "rb"); - AssertTrue((f != XBADFILE)); - AssertNotNull(pkcs12 = d2i_PKCS12_fp(f, NULL)); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(file, "rb")) != XBADFILE); + ExpectNotNull(pkcs12 = d2i_PKCS12_fp(f, NULL)); + if (f != XBADFILE) + XFCLOSE(f); - bio = BIO_new(BIO_s_mem()); - AssertNotNull(bio); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); - ret = i2d_PKCS12_bio(bio, pkcs12); - AssertIntEQ(ret, 1); + ExpectIntEQ(ret = i2d_PKCS12_bio(bio, pkcs12), 1); - ret = i2d_PKCS12_bio(NULL, pkcs12); - AssertIntEQ(ret, 0); + ExpectIntEQ(ret = i2d_PKCS12_bio(NULL, pkcs12), 0); - ret = i2d_PKCS12_bio(bio, NULL); - AssertIntEQ(ret, 0); + ExpectIntEQ(ret = i2d_PKCS12_bio(bio, NULL), 0); PKCS12_free(pkcs12); BIO_free(bio); (void)order; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ #endif /* HAVE_FIPS */ return res; @@ -10408,43 +10610,45 @@ static int test_wolfSSL_no_password_cb(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && !defined(NO_ASN) && defined(HAVE_PKCS8) \ && defined(HAVE_ECC) && defined(WOLFSSL_ENCRYPTED_KEYS) - WOLFSSL_CTX* ctx; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; byte buff[FOURK_BUF]; const char eccPkcs8PrivKeyDerFile[] = "./certs/ecc-privkeyPkcs8.der"; const char eccPkcs8PrivKeyPemFile[] = "./certs/ecc-privkeyPkcs8.pem"; - XFILE f; + XFILE f = XBADFILE; int bytes; #ifndef NO_WOLFSSL_CLIENT - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLS_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLS_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLS_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLS_server_method())); #endif wolfSSL_CTX_set_default_passwd_cb(ctx, FailTestCallBack); - AssertTrue((f = XFOPEN(eccPkcs8PrivKeyDerFile, "rb")) != XBADFILE); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); - AssertIntLE(bytes, sizeof(buff)); - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectTrue((f = XFOPEN(eccPkcs8PrivKeyDerFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } + ExpectIntLE(bytes, sizeof(buff)); + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); - AssertTrue((f = XFOPEN(eccPkcs8PrivKeyPemFile, "rb")) != XBADFILE); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); - AssertIntLE(bytes, sizeof(buff)); - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectTrue((f = XFOPEN(eccPkcs8PrivKeyPemFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) + XFCLOSE(f); + ExpectIntLE(bytes, sizeof(buff)); + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); wolfSSL_CTX_free(ctx); - if (failTestCallbackCalled != 0) { - Fail(("Password callback should not be called by default"), - ("Password callback was called without attempting " - "to first decipher private key without password.")); - } + /* Password callback should not be called by default */ + ExpectIntEQ(failTestCallbackCalled, 0); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -10480,6 +10684,7 @@ static int test_wolfSSL_PKCS8(void) #if !defined(NO_FILESYSTEM) && !defined(NO_ASN) && defined(HAVE_PKCS8) && \ !defined(WOLFCRYPT_ONLY) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; byte buff[FOURK_BUF]; byte der[FOURK_BUF]; #ifndef NO_RSA @@ -10490,9 +10695,9 @@ static int test_wolfSSL_PKCS8(void) #ifdef HAVE_ECC const char eccPkcs8PrivKeyDerFile[] = "./certs/ecc-privkeyPkcs8.der"; #endif - XFILE f; - int bytes; - WOLFSSL_CTX* ctx; + XFILE f = XBADFILE; + int bytes = 0; + WOLFSSL_CTX* ctx = NULL; #if defined(HAVE_ECC) && !defined(NO_CODING) int ret; ecc_key key; @@ -10514,15 +10719,15 @@ static int test_wolfSSL_PKCS8(void) #ifndef NO_WOLFSSL_CLIENT #ifndef WOLFSSL_NO_TLS12 - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); #endif #else #ifndef WOLFSSL_NO_TLS12 - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method())); #endif #endif @@ -10533,76 +10738,84 @@ static int test_wolfSSL_PKCS8(void) #if !defined(NO_RSA) && !defined(NO_SHA) /* test loading PEM PKCS8 encrypted file */ - f = XFOPEN(serverKeyPkcs8EncPemFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectTrue((f = XFOPEN(serverKeyPkcs8EncPemFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); /* this next case should fail because of password callback return code */ flag = 0; /* used by password callback as return code */ - AssertIntNE(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntNE(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); /* decrypt PKCS8 PEM to key in DER format with not using WOLFSSL_CTX */ - AssertIntGT(wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), + ExpectIntGT(wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), "yassl123"), 0); /* test that error value is returned with a bad password */ - AssertIntLT(wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), + ExpectIntLT(wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), "bad"), 0); /* test loading PEM PKCS8 encrypted file */ - f = XFOPEN(serverKeyPkcs8EncDerFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(serverKeyPkcs8EncDerFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } flag = 1; /* used by password callback as return code */ - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* this next case should fail because of password callback return code */ flag = 0; /* used by password callback as return code */ - AssertIntNE(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntNE(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #endif /* !NO_RSA && !NO_SHA */ #if defined(HAVE_ECC) && !defined(NO_SHA) /* test loading PEM PKCS8 encrypted ECC Key file */ - f = XFOPEN(eccPkcs8EncPrivKeyPemFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(eccPkcs8EncPrivKeyPemFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } flag = 1; /* used by password callback as return code */ - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); /* this next case should fail because of password callback return code */ flag = 0; /* used by password callback as return code */ - AssertIntNE(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntNE(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); /* decrypt PKCS8 PEM to key in DER format with not using WOLFSSL_CTX */ - AssertIntGT(wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), + ExpectIntGT(wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), "yassl123"), 0); /* test that error value is returned with a bad password */ - AssertIntLT(wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), + ExpectIntLT(wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), "bad"), 0); /* test loading DER PKCS8 encrypted ECC Key file */ - f = XFOPEN(eccPkcs8EncPrivKeyDerFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(eccPkcs8EncPrivKeyDerFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } flag = 1; /* used by password callback as return code */ - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* this next case should fail because of password callback return code */ flag = 0; /* used by password callback as return code */ - AssertIntNE(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntNE(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* leave flag as "okay" */ @@ -10613,62 +10826,68 @@ static int test_wolfSSL_PKCS8(void) #ifndef NO_RSA /* test loading ASN.1 (DER) PKCS8 private key file (not encrypted) */ - f = XFOPEN(serverKeyPkcs8DerFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectTrue((f = XFOPEN(serverKeyPkcs8DerFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); /* test loading PEM PKCS8 private key file (not encrypted) */ - f = XFOPEN(serverKeyPkcs8PemFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectTrue((f = XFOPEN(serverKeyPkcs8PemFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); #endif /* !NO_RSA */ /* Test PKCS8 PEM ECC key no crypt */ - f = XFOPEN(eccPkcs8PrivKeyPemFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(eccPkcs8PrivKeyPemFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } #ifdef HAVE_ECC /* Test PKCS8 PEM ECC key no crypt */ - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); #ifndef NO_CODING /* decrypt PKCS8 PEM to key in DER format */ - AssertIntGT((bytes = wc_KeyPemToDer(buff, bytes, der, + ExpectIntGT((bytes = wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), NULL)), 0); ret = wc_ecc_init(&key); if (ret == 0) { ret = wc_EccPrivateKeyDecode(der, &x, &key, bytes); wc_ecc_free(&key); } - AssertIntEQ(ret, 0); + ExpectIntEQ(ret, 0); #endif /* Test PKCS8 DER ECC key no crypt */ - f = XFOPEN(eccPkcs8PrivKeyDerFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(eccPkcs8PrivKeyDerFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) + XFCLOSE(f); /* Test using a PKCS8 ECC PEM */ - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); #else /* if HAVE_ECC is not defined then BEGIN EC PRIVATE KEY is not found */ - AssertIntEQ((bytes = wc_KeyPemToDer(buff, bytes, der, + ExpectIntEQ((bytes = wc_KeyPemToDer(buff, bytes, der, (word32)sizeof(der), NULL)), ASN_NO_PEM_HEADER); #endif /* HAVE_ECC */ wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* !NO_FILESYSTEM && !NO_ASN && HAVE_PKCS8 */ return res; @@ -10680,6 +10899,7 @@ static int test_wolfSSL_PKCS8_ED25519(void) #if !defined(NO_ASN) && defined(HAVE_PKCS8) && defined(HAVE_AES_CBC) && \ defined(WOLFSSL_ENCRYPTED_KEYS) && defined(HAVE_ED25519) && \ defined(HAVE_ED25519_KEY_IMPORT) + EXPECT_DECLS; const byte encPrivKey[] = \ "-----BEGIN ENCRYPTED PRIVATE KEY-----\n" "MIGbMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAheCGLmWGh7+AICCAAw\n" @@ -10689,24 +10909,24 @@ static int test_wolfSSL_PKCS8_ED25519(void) "-----END ENCRYPTED PRIVATE KEY-----\n"; const char password[] = "abcdefghijklmnopqrstuvwxyz"; byte der[FOURK_BUF]; - WOLFSSL_CTX* ctx; + WOLFSSL_CTX* ctx = NULL; int bytes; XMEMSET(der, 0, sizeof(der)); - AssertIntGT((bytes = wc_KeyPemToDer(encPrivKey, sizeof(encPrivKey), der, + ExpectIntGT((bytes = wc_KeyPemToDer(encPrivKey, sizeof(encPrivKey), der, (word32)sizeof(der), password)), 0); #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, bytes, + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif return res; @@ -10718,6 +10938,7 @@ static int test_wolfSSL_PKCS8_ED448(void) #if !defined(NO_ASN) && defined(HAVE_PKCS8) && defined(HAVE_AES_CBC) && \ defined(WOLFSSL_ENCRYPTED_KEYS) && defined(HAVE_ED448) && \ defined(HAVE_ED448_KEY_IMPORT) + EXPECT_DECLS; const byte encPrivKey[] = \ "-----BEGIN ENCRYPTED PRIVATE KEY-----\n" "MIGrMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAjSbZKnG4EPggICCAAw\n" @@ -10727,24 +10948,24 @@ static int test_wolfSSL_PKCS8_ED448(void) "-----END ENCRYPTED PRIVATE KEY-----\n"; const char password[] = "abcdefghijklmnopqrstuvwxyz"; byte der[FOURK_BUF]; - WOLFSSL_CTX* ctx; + WOLFSSL_CTX* ctx = NULL; int bytes; XMEMSET(der, 0, sizeof(der)); - AssertIntGT((bytes = wc_KeyPemToDer(encPrivKey, sizeof(encPrivKey), der, + ExpectIntGT((bytes = wc_KeyPemToDer(encPrivKey, sizeof(encPrivKey), der, (word32)sizeof(der), password)), 0); #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, bytes, + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, bytes, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif return res; @@ -10755,6 +10976,7 @@ static int test_wolfSSL_PKCS5(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_SHA) && !defined(NO_PWDBASED) + EXPECT_DECLS; #ifdef HAVE_FIPS /* Password minimum length is 14 (112-bit) in FIPS MODE */ const char* passwd = "myfipsPa$$W0rd"; #else @@ -10765,22 +10987,20 @@ static int test_wolfSSL_PKCS5(void) DYNAMIC_TYPE_TMP_BUFFER); int ret = 0; - AssertNotNull(out); - ret = PKCS5_PBKDF2_HMAC_SHA1(passwd,(int)XSTRLEN(passwd), salt, - (int)XSTRLEN((const char *) salt), 10, - WC_SHA_DIGEST_SIZE,out); - AssertIntEQ(ret, SSL_SUCCESS); + ExpectNotNull(out); + ExpectIntEQ(ret = PKCS5_PBKDF2_HMAC_SHA1(passwd,(int)XSTRLEN(passwd), salt, + (int)XSTRLEN((const char *) salt), 10, WC_SHA_DIGEST_SIZE,out), + WOLFSSL_SUCCESS); #ifdef WOLFSSL_SHA512 - ret = PKCS5_PBKDF2_HMAC(passwd,(int)XSTRLEN(passwd), salt, - (int)XSTRLEN((const char *) salt), 10, - wolfSSL_EVP_sha512(), WC_SHA_DIGEST_SIZE, out); - AssertIntEQ(ret, SSL_SUCCESS); + ExpectIntEQ(ret = PKCS5_PBKDF2_HMAC(passwd,(int)XSTRLEN(passwd), salt, + (int)XSTRLEN((const char *) salt), 10, wolfSSL_EVP_sha512(), + WC_SHA_DIGEST_SIZE, out), SSL_SUCCESS); #endif XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_SHA) */ return res; } @@ -10792,29 +11012,33 @@ static int test_wolfSSL_URI(void) #if !defined(NO_CERTS) && !defined(NO_RSA) && !defined(NO_FILESYSTEM) \ && (defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \ defined(OPENSSL_EXTRA)) - WOLFSSL_X509* x509; + EXPECT_DECLS; + WOLFSSL_X509* x509 = NULL; const char uri[] = "./certs/client-uri-cert.pem"; const char urn[] = "./certs/client-absolute-urn.pem"; const char badUri[] = "./certs/client-relative-uri.pem"; - x509 = wolfSSL_X509_load_certificate_file(uri, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(uri, + WOLFSSL_FILETYPE_PEM)); wolfSSL_FreeX509(x509); + x509 = NULL; - x509 = wolfSSL_X509_load_certificate_file(urn, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(urn, + WOLFSSL_FILETYPE_PEM)); wolfSSL_FreeX509(x509); + x509 = NULL; - x509 = wolfSSL_X509_load_certificate_file(badUri, WOLFSSL_FILETYPE_PEM); #if !defined(IGNORE_NAME_CONSTRAINTS) && !defined(WOLFSSL_NO_ASN_STRICT) \ && !defined(WOLFSSL_FPKI) - AssertNull(x509); + ExpectNull(x509 = wolfSSL_X509_load_certificate_file(badUri, + WOLFSSL_FILETYPE_PEM)); #else - AssertNotNull(x509); - wolfSSL_FreeX509(x509); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(badUri, + WOLFSSL_FILETYPE_PEM)); #endif + wolfSSL_FreeX509(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -10825,21 +11049,22 @@ static int test_wolfSSL_TBS(void) int res = TEST_SKIPPED; #if !defined(NO_CERTS) && !defined(NO_RSA) && !defined(NO_FILESYSTEM) \ && defined(OPENSSL_EXTRA) - WOLFSSL_X509* x509; + EXPECT_DECLS; + WOLFSSL_X509* x509 = NULL; const unsigned char* tbs; int tbsSz; - AssertNotNull(x509 = - wolfSSL_X509_load_certificate_file(caCertFile, WOLFSSL_FILETYPE_PEM)); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(caCertFile, + WOLFSSL_FILETYPE_PEM)); - AssertNull(tbs = wolfSSL_X509_get_tbs(NULL, &tbsSz)); - AssertNull(tbs = wolfSSL_X509_get_tbs(x509, NULL)); - AssertNotNull(tbs = wolfSSL_X509_get_tbs(x509, &tbsSz)); - AssertIntEQ(tbsSz, 1003); + ExpectNull(tbs = wolfSSL_X509_get_tbs(NULL, &tbsSz)); + ExpectNull(tbs = wolfSSL_X509_get_tbs(x509, NULL)); + ExpectNotNull(tbs = wolfSSL_X509_get_tbs(x509, &tbsSz)); + ExpectIntEQ(tbsSz, 1003); wolfSSL_FreeX509(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -10849,57 +11074,59 @@ static int test_wolfSSL_X509_verify(void) int res = TEST_SKIPPED; #if !defined(NO_CERTS) && !defined(NO_RSA) && !defined(NO_FILESYSTEM) \ && defined(OPENSSL_EXTRA) - WOLFSSL_X509* ca; - WOLFSSL_X509* serv; - WOLFSSL_EVP_PKEY* pkey; + EXPECT_DECLS; + WOLFSSL_X509* ca = NULL; + WOLFSSL_X509* serv = NULL; + WOLFSSL_EVP_PKEY* pkey = NULL; unsigned char buf[2048]; const unsigned char* pt = NULL; int bufSz; - AssertNotNull(ca = + ExpectNotNull(ca = wolfSSL_X509_load_certificate_file(caCertFile, WOLFSSL_FILETYPE_PEM)); - AssertIntNE(wolfSSL_X509_get_pubkey_buffer(NULL, buf, &bufSz), + ExpectIntNE(wolfSSL_X509_get_pubkey_buffer(NULL, buf, &bufSz), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_get_pubkey_buffer(ca, NULL, &bufSz), + ExpectIntEQ(wolfSSL_X509_get_pubkey_buffer(ca, NULL, &bufSz), WOLFSSL_SUCCESS); - AssertIntEQ(bufSz, 294); + ExpectIntEQ(bufSz, 294); bufSz = 2048; - AssertIntEQ(wolfSSL_X509_get_pubkey_buffer(ca, buf, &bufSz), + ExpectIntEQ(wolfSSL_X509_get_pubkey_buffer(ca, buf, &bufSz), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_get_pubkey_type(NULL), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_X509_get_pubkey_type(ca), RSAk); + ExpectIntEQ(wolfSSL_X509_get_pubkey_type(NULL), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_X509_get_pubkey_type(ca), RSAk); - AssertNotNull(serv = + ExpectNotNull(serv = wolfSSL_X509_load_certificate_file(svrCertFile, WOLFSSL_FILETYPE_PEM)); /* success case */ pt = buf; - AssertNotNull(pkey = wolfSSL_d2i_PUBKEY(NULL, &pt, bufSz)); + ExpectNotNull(pkey = wolfSSL_d2i_PUBKEY(NULL, &pt, bufSz)); - AssertIntEQ(i2d_PUBKEY(pkey, NULL), bufSz); + ExpectIntEQ(i2d_PUBKEY(pkey, NULL), bufSz); - AssertIntEQ(wolfSSL_X509_verify(serv, pkey), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_verify(serv, pkey), WOLFSSL_SUCCESS); wolfSSL_EVP_PKEY_free(pkey); + pkey = NULL; /* fail case */ bufSz = 2048; - AssertIntEQ(wolfSSL_X509_get_pubkey_buffer(serv, buf, &bufSz), + ExpectIntEQ(wolfSSL_X509_get_pubkey_buffer(serv, buf, &bufSz), WOLFSSL_SUCCESS); pt = buf; - AssertNotNull(pkey = wolfSSL_d2i_PUBKEY(NULL, &pt, bufSz)); - AssertIntEQ(wolfSSL_X509_verify(serv, pkey), WOLFSSL_FAILURE); + ExpectNotNull(pkey = wolfSSL_d2i_PUBKEY(NULL, &pt, bufSz)); + ExpectIntEQ(wolfSSL_X509_verify(serv, pkey), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_X509_verify(NULL, pkey), WOLFSSL_FATAL_ERROR); - AssertIntEQ(wolfSSL_X509_verify(serv, NULL), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(wolfSSL_X509_verify(NULL, pkey), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(wolfSSL_X509_verify(serv, NULL), WOLFSSL_FATAL_ERROR); wolfSSL_EVP_PKEY_free(pkey); wolfSSL_FreeX509(ca); wolfSSL_FreeX509(serv); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -11000,6 +11227,7 @@ static int test_wolfSSL_X509_TLS_version(void) defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(SINGLE_THREADED) && \ defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && !defined(NO_BIO) \ && !defined(NO_ASN_TIME) + EXPECT_DECLS; tcp_ready ready; func_args server_args; func_args client_args; @@ -11050,11 +11278,11 @@ static int test_wolfSSL_X509_TLS_version(void) join_thread(serverThread); #ifndef OPENSSL_COMPATIBLE_DEFAULTS - AssertIntEQ(client_args.return_code, TEST_FAIL); - AssertIntEQ(server_args.return_code, TEST_FAIL); + ExpectIntEQ(client_args.return_code, TEST_FAIL); + ExpectIntEQ(server_args.return_code, TEST_FAIL); #else - AssertIntEQ(client_args.return_code, TEST_SUCCESS); - AssertIntEQ(server_args.return_code, TEST_SUCCESS); + ExpectIntEQ(client_args.return_code, TEST_SUCCESS); + ExpectIntEQ(server_args.return_code, TEST_SUCCESS); #endif FreeTcpReady(&ready); @@ -11106,8 +11334,8 @@ static int test_wolfSSL_X509_TLS_version(void) test_client_nofail(&client_args, NULL); join_thread(serverThread); - AssertIntEQ(client_args.return_code, TEST_SUCCESS); - AssertIntEQ(server_args.return_code, TEST_SUCCESS); + ExpectIntEQ(client_args.return_code, TEST_SUCCESS); + ExpectIntEQ(server_args.return_code, TEST_SUCCESS); FreeTcpReady(&ready); @@ -11115,7 +11343,7 @@ static int test_wolfSSL_X509_TLS_version(void) fdCloseSession(Task_self()); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -11178,37 +11406,45 @@ static int test_wolfSSL_CTX_SetMinVersion(void) */ static int test_wolfSSL_UseOCSPStapling(void) { - int res = TEST_SKIPPED; - #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && defined(HAVE_OCSP) && \ - !defined(NO_WOLFSSL_CLIENT) - int ret; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + int res = TEST_SKIPPED; +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && defined(HAVE_OCSP) && \ + !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; #ifndef NO_WOLFSSL_CLIENT #ifndef WOLFSSL_NO_TLS12 - ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); #else - ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); #endif #else #ifndef WOLFSSL_NO_TLS12 - ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method())); #else - ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method())); #endif #endif - ssl = wolfSSL_new(ctx); + ExpectNotNull(ssl = wolfSSL_new(ctx)); - ret = wolfSSL_UseOCSPStapling(ssl, WOLFSSL_CSR2_OCSP, - WOLFSSL_CSR2_OCSP_USE_NONCE); + ExpectIntEQ(wolfSSL_UseOCSPStapling(NULL, WOLFSSL_CSR2_OCSP, + WOLFSSL_CSR2_OCSP_USE_NONCE), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_UseOCSPStapling(ssl, WOLFSSL_CSR2_OCSP, + WOLFSSL_CSR2_OCSP_USE_NONCE), +#ifndef NO_WOLFSSL_CLIENT + 1 +#else + BAD_FUNC_ARG +#endif + ); - wolfSSL_free(ssl); - wolfSSL_CTX_free(ctx); + wolfSSL_free(ssl); + wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(ret == WOLFSSL_SUCCESS); - #endif - return res; + res = EXPECT_RESULT(); +#endif + return res; } /*END test_wolfSSL_UseOCSPStapling */ @@ -11219,39 +11455,47 @@ static int test_wolfSSL_UseOCSPStapling(void) */ static int test_wolfSSL_UseOCSPStaplingV2(void) { - int res = TEST_SKIPPED; - #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && defined(HAVE_OCSP) && \ - !defined(NO_WOLFSSL_CLIENT) - int ret; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + int res = TEST_SKIPPED; +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && defined(HAVE_OCSP) && \ + !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; #ifndef NO_WOLFSSL_CLIENT #ifndef WOLFSSL_NO_TLS12 - ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); #else - ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); #endif #else #ifndef WOLFSSL_NO_TLS12 - ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method())); #else - ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method()); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method())); #endif #endif - ssl = wolfSSL_new(ctx); + ExpectNotNull(ssl = wolfSSL_new(ctx)); - ret = wolfSSL_UseOCSPStaplingV2(ssl, WOLFSSL_CSR2_OCSP, - WOLFSSL_CSR2_OCSP_USE_NONCE ); + ExpectIntEQ(wolfSSL_UseOCSPStaplingV2(NULL, WOLFSSL_CSR2_OCSP, + WOLFSSL_CSR2_OCSP_USE_NONCE), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_UseOCSPStaplingV2(ssl, WOLFSSL_CSR2_OCSP, + WOLFSSL_CSR2_OCSP_USE_NONCE), +#ifndef NO_WOLFSSL_CLIENT + 1 +#else + BAD_FUNC_ARG +#endif + ); - wolfSSL_free(ssl); - wolfSSL_CTX_free(ctx); + wolfSSL_free(ssl); + wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(ret == WOLFSSL_SUCCESS); - #endif - return res; + res = EXPECT_RESULT(); +#endif + return res; -} /*END test_wolfSSL_UseOCSPStaplingV2*/ +} /* END test_wolfSSL_UseOCSPStaplingV2 */ /*----------------------------------------------------------------------------* | Multicast Tests @@ -11261,9 +11505,9 @@ static int test_wolfSSL_mcast(void) int res = TEST_SKIPPED; #if defined(WOLFSSL_DTLS) && defined(WOLFSSL_MULTICAST) && \ (defined(WOLFSSL_TLS13) || defined(WOLFSSL_SNIFFER)) - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; - int result; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; byte preMasterSecret[512]; byte clientRandom[32]; byte serverRandom[32]; @@ -11271,31 +11515,26 @@ static int test_wolfSSL_mcast(void) byte buf[256]; word16 newId; - ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method())); - result = wolfSSL_CTX_mcast_set_member_id(ctx, 0); - AssertIntEQ(result, WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_mcast_set_member_id(ctx, 0), WOLFSSL_SUCCESS); - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); + ExpectNotNull(ssl = wolfSSL_new(ctx)); XMEMSET(preMasterSecret, 0x23, sizeof(preMasterSecret)); XMEMSET(clientRandom, 0xA5, sizeof(clientRandom)); XMEMSET(serverRandom, 0x5A, sizeof(serverRandom)); - result = wolfSSL_set_secret(ssl, 23, - preMasterSecret, sizeof(preMasterSecret), - clientRandom, serverRandom, suite); - AssertIntEQ(result, WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set_secret(ssl, 23, preMasterSecret, + sizeof(preMasterSecret), clientRandom, serverRandom, suite), + WOLFSSL_SUCCESS); - result = wolfSSL_mcast_read(ssl, &newId, buf, sizeof(buf)); - AssertIntLE(result, 0); - AssertIntLE(newId, 100); + ExpectIntLE(wolfSSL_mcast_read(ssl, &newId, buf, sizeof(buf)), 0); + ExpectIntLE(newId, 100); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* WOLFSSL_DTLS && WOLFSSL_MULTICAST && (WOLFSSL_TLS13 || * WOLFSSL_SNIFFER) */ return res; @@ -31313,45 +31552,47 @@ static int test_wolfSSL_ASN1_BIT_STRING(void) { int res = TEST_SKIPPED; #if !defined(NO_CERTS) && defined(OPENSSL_ALL) - ASN1_BIT_STRING* str; + EXPECT_DECLS; + ASN1_BIT_STRING* str = NULL; - AssertNotNull(str = ASN1_BIT_STRING_new()); + ExpectNotNull(str = ASN1_BIT_STRING_new()); /* Empty data testing. */ - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 1), 0); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 1), 0); ASN1_BIT_STRING_free(str); + str = NULL; - AssertNotNull(str = ASN1_BIT_STRING_new()); + ExpectNotNull(str = ASN1_BIT_STRING_new()); /* Invalid parameter testing. */ - AssertIntEQ(ASN1_BIT_STRING_set_bit(NULL, 42, 1), 0); - AssertIntEQ(ASN1_BIT_STRING_set_bit(str, -1, 1), 0); - AssertIntEQ(ASN1_BIT_STRING_set_bit(str, 42, 2), 0); - AssertIntEQ(ASN1_BIT_STRING_set_bit(str, 42, -1), 0); + ExpectIntEQ(ASN1_BIT_STRING_set_bit(NULL, 42, 1), 0); + ExpectIntEQ(ASN1_BIT_STRING_set_bit(str, -1, 1), 0); + ExpectIntEQ(ASN1_BIT_STRING_set_bit(str, 42, 2), 0); + ExpectIntEQ(ASN1_BIT_STRING_set_bit(str, 42, -1), 0); /* No bit string - bit is always 0. */ - AssertIntEQ(ASN1_BIT_STRING_get_bit(NULL, 42), 0); - AssertIntEQ(ASN1_BIT_STRING_get_bit(NULL, -1), 0); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, -1), 0); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 0), 0); - - AssertIntEQ(ASN1_BIT_STRING_set_bit(str, 42, 1), 1); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 42), 1); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 41), 0); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, -1), 0); - AssertIntEQ(ASN1_BIT_STRING_set_bit(str, 84, 1), 1); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 84), 1); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 83), 0); - AssertIntEQ(ASN1_BIT_STRING_set_bit(str, 91, 0), 1); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 91), 0); - AssertIntEQ(ASN1_BIT_STRING_set_bit(str, 89, 0), 1); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 89), 0); - AssertIntEQ(ASN1_BIT_STRING_set_bit(str, 42, 0), 1); - AssertIntEQ(ASN1_BIT_STRING_get_bit(str, 42), 0); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(NULL, 42), 0); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(NULL, -1), 0); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, -1), 0); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 0), 0); + + ExpectIntEQ(ASN1_BIT_STRING_set_bit(str, 42, 1), 1); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 42), 1); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 41), 0); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, -1), 0); + ExpectIntEQ(ASN1_BIT_STRING_set_bit(str, 84, 1), 1); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 84), 1); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 83), 0); + ExpectIntEQ(ASN1_BIT_STRING_set_bit(str, 91, 0), 1); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 91), 0); + ExpectIntEQ(ASN1_BIT_STRING_set_bit(str, 89, 0), 1); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 89), 0); + ExpectIntEQ(ASN1_BIT_STRING_set_bit(str, 42, 0), 1); + ExpectIntEQ(ASN1_BIT_STRING_get_bit(str, 42), 0); ASN1_BIT_STRING_free(str); ASN1_BIT_STRING_free(NULL); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -31360,8 +31601,9 @@ static int test_wolfSSL_ASN1_INTEGER(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) - ASN1_INTEGER* a; - ASN1_INTEGER* dup; + EXPECT_DECLS; + ASN1_INTEGER* a = NULL; + ASN1_INTEGER* dup = NULL; const unsigned char invalidLenDer[] = { 0x02, 0x20, 0x00 }; @@ -31376,24 +31618,26 @@ static int test_wolfSSL_ASN1_INTEGER(void) /* Invalid parameter testing. */ ASN1_INTEGER_free(NULL); - AssertNull(wolfSSL_ASN1_INTEGER_dup(NULL)); + ExpectNull(wolfSSL_ASN1_INTEGER_dup(NULL)); - AssertNotNull(a = ASN1_INTEGER_new()); - AssertNotNull(dup = wolfSSL_ASN1_INTEGER_dup(a)); + ExpectNotNull(a = ASN1_INTEGER_new()); + ExpectNotNull(dup = wolfSSL_ASN1_INTEGER_dup(a)); ASN1_INTEGER_free(dup); + dup = NULL; ASN1_INTEGER_free(a); + a = NULL; p = longDer; - AssertNull(d2i_ASN1_INTEGER(NULL, &p, sizeof(invalidLenDer))); + ExpectNull(d2i_ASN1_INTEGER(NULL, &p, sizeof(invalidLenDer))); p = longDer; - AssertNotNull(a = d2i_ASN1_INTEGER(NULL, &p, sizeof(longDer))); - AssertPtrNE(p, longDer); - AssertNotNull(dup = wolfSSL_ASN1_INTEGER_dup(a)); + ExpectNotNull(a = d2i_ASN1_INTEGER(NULL, &p, sizeof(longDer))); + ExpectPtrNE(p, longDer); + ExpectNotNull(dup = wolfSSL_ASN1_INTEGER_dup(a)); ASN1_INTEGER_free(dup); ASN1_INTEGER_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -31402,35 +31646,36 @@ static int test_wolfSSL_ASN1_INTEGER_cmp(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) - ASN1_INTEGER* a; - ASN1_INTEGER* b; + EXPECT_DECLS; + ASN1_INTEGER* a = NULL; + ASN1_INTEGER* b = NULL; - AssertNotNull(a = ASN1_INTEGER_new()); - AssertNotNull(b = ASN1_INTEGER_new()); - AssertIntEQ(ASN1_INTEGER_set(a, 1), 1); - AssertIntEQ(ASN1_INTEGER_set(b, 1), 1); + ExpectNotNull(a = ASN1_INTEGER_new()); + ExpectNotNull(b = ASN1_INTEGER_new()); + ExpectIntEQ(ASN1_INTEGER_set(a, 1), 1); + ExpectIntEQ(ASN1_INTEGER_set(b, 1), 1); /* Invalid parameter testing. */ - AssertIntEQ(wolfSSL_ASN1_INTEGER_cmp(NULL, NULL), -1); - AssertIntEQ(wolfSSL_ASN1_INTEGER_cmp(a, NULL), -1); - AssertIntEQ(wolfSSL_ASN1_INTEGER_cmp(NULL, b), -1); - - AssertIntEQ(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); - AssertIntEQ(ASN1_INTEGER_set(b, -1), 1); - AssertIntGT(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); - AssertIntEQ(ASN1_INTEGER_set(a, -2), 1); - AssertIntLT(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); - AssertIntEQ(ASN1_INTEGER_set(b, 1), 1); - AssertIntLT(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); - AssertIntEQ(ASN1_INTEGER_set(a, 0x01), 1); - AssertIntEQ(ASN1_INTEGER_set(b, 0x1000), 1); - AssertIntLT(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); - AssertIntGT(wolfSSL_ASN1_INTEGER_cmp(b, a), 0); + ExpectIntEQ(wolfSSL_ASN1_INTEGER_cmp(NULL, NULL), -1); + ExpectIntEQ(wolfSSL_ASN1_INTEGER_cmp(a, NULL), -1); + ExpectIntEQ(wolfSSL_ASN1_INTEGER_cmp(NULL, b), -1); + + ExpectIntEQ(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); + ExpectIntEQ(ASN1_INTEGER_set(b, -1), 1); + ExpectIntGT(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); + ExpectIntEQ(ASN1_INTEGER_set(a, -2), 1); + ExpectIntLT(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); + ExpectIntEQ(ASN1_INTEGER_set(b, 1), 1); + ExpectIntLT(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); + ExpectIntEQ(ASN1_INTEGER_set(a, 0x01), 1); + ExpectIntEQ(ASN1_INTEGER_set(b, 0x1000), 1); + ExpectIntLT(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); + ExpectIntGT(wolfSSL_ASN1_INTEGER_cmp(b, a), 0); ASN1_INTEGER_free(b); ASN1_INTEGER_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -31439,90 +31684,103 @@ static int test_wolfSSL_ASN1_INTEGER_BN(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) - ASN1_INTEGER* ai; - ASN1_INTEGER* ai2; - BIGNUM* bn; - BIGNUM* bn2; + EXPECT_DECLS; + ASN1_INTEGER* ai = NULL; + ASN1_INTEGER* ai2 = NULL; + BIGNUM* bn = NULL; + BIGNUM* bn2 = NULL; - ai = ASN1_INTEGER_new(); - AssertNotNull(ai); - bn2 = BN_new(); - AssertNotNull(bn2); + ExpectNotNull(ai = ASN1_INTEGER_new()); + ExpectNotNull(bn2 = BN_new()); /* Invalid parameter testing. */ - AssertNull(bn = ASN1_INTEGER_to_BN(NULL, NULL)); - AssertNull(ai2 = BN_to_ASN1_INTEGER(NULL, NULL)); + ExpectNull(bn = ASN1_INTEGER_to_BN(NULL, NULL)); + ExpectNull(ai2 = BN_to_ASN1_INTEGER(NULL, NULL)); /* at the moment hard setting since no set function */ - ai->data[0] = 0xff; /* No DER encoding. */ - ai->length = 1; + if (ai != NULL) { + ai->data[0] = 0xff; /* No DER encoding. */ + ai->length = 1; + } #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY) - AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); + ExpectNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); BN_free(bn); + bn = NULL; #else - AssertNull(ASN1_INTEGER_to_BN(ai, NULL)); + ExpectNull(ASN1_INTEGER_to_BN(ai, NULL)); #endif - ai->data[0] = 0x02; /* tag for ASN_INTEGER */ - ai->data[1] = 0x04; /* bad length of integer */ - ai->data[2] = 0x03; - ai->length = 3; + if (ai != NULL) { + ai->data[0] = 0x02; /* tag for ASN_INTEGER */ + ai->data[1] = 0x04; /* bad length of integer */ + ai->data[2] = 0x03; + ai->length = 3; + } #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY) /* Interpreted as a number 0x020403. */ - AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); + ExpectNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); BN_free(bn); + bn = NULL; #else - AssertNull(ASN1_INTEGER_to_BN(ai, NULL)); -#endif - - ai->data[0] = 0x02; /* tag for ASN_INTEGER */ - ai->data[1] = 0x01; /* length of integer */ - ai->data[2] = 0x03; - ai->length = 3; - AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); - AssertNotNull(ai2 = BN_to_ASN1_INTEGER(bn, NULL)); - AssertIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); - AssertNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); - AssertIntEQ(BN_cmp(bn, bn2), 0); - - ai->data[0] = 0x02; /* tag for ASN_INTEGER */ - ai->data[1] = 0x02; /* length of integer */ - ai->data[2] = 0x00; /* padding byte to ensure positive */ - ai->data[3] = 0xff; - ai->length = 4; - AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); - AssertNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); - AssertIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); - AssertNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); - AssertIntEQ(BN_cmp(bn, bn2), 0); - - ai->data[0] = 0x02; /* tag for ASN_INTEGER */ - ai->data[1] = 0x01; /* length of integer */ - ai->data[2] = 0x00; - ai->length = 3; - AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); - AssertNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); - AssertIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); - AssertNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); - AssertIntEQ(BN_cmp(bn, bn2), 0); - - ai->data[0] = 0x02; /* tag for ASN_INTEGER */ - ai->data[1] = 0x01; /* length of integer */ - ai->data[2] = 0x01; - ai->length = 3; - ai->negative = 1; - AssertNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); - AssertNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); - AssertIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); - AssertNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); - AssertIntEQ(BN_cmp(bn, bn2), 0); + ExpectNull(ASN1_INTEGER_to_BN(ai, NULL)); +#endif + + if (ai != NULL) { + ai->data[0] = 0x02; /* tag for ASN_INTEGER */ + ai->data[1] = 0x01; /* length of integer */ + ai->data[2] = 0x03; + ai->length = 3; + } + ExpectNotNull(bn = ASN1_INTEGER_to_BN(ai, NULL)); + ExpectNotNull(ai2 = BN_to_ASN1_INTEGER(bn, NULL)); + ExpectIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); + ExpectNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); + ExpectIntEQ(BN_cmp(bn, bn2), 0); + + if (ai != NULL) { + ai->data[0] = 0x02; /* tag for ASN_INTEGER */ + ai->data[1] = 0x02; /* length of integer */ + ai->data[2] = 0x00; /* padding byte to ensure positive */ + ai->data[3] = 0xff; + ai->length = 4; + } + ExpectNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); + ExpectNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); + ExpectIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); + ExpectNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); + ExpectIntEQ(BN_cmp(bn, bn2), 0); + + if (ai != NULL) { + ai->data[0] = 0x02; /* tag for ASN_INTEGER */ + ai->data[1] = 0x01; /* length of integer */ + ai->data[2] = 0x00; + ai->length = 3; + } + ExpectNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); + ExpectNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); + ExpectIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); + ExpectNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); + ExpectIntEQ(BN_cmp(bn, bn2), 0); + + if (ai != NULL) { + ai->data[0] = 0x02; /* tag for ASN_INTEGER */ + ai->data[1] = 0x01; /* length of integer */ + ai->data[2] = 0x01; + ai->length = 3; + ai->negative = 1; + } + ExpectNotNull(bn = ASN1_INTEGER_to_BN(ai, bn)); + ExpectNotNull(ai2 = BN_to_ASN1_INTEGER(bn, ai2)); + ExpectIntEQ(ASN1_INTEGER_cmp(ai, ai2), 0); + ExpectNotNull(bn2 = ASN1_INTEGER_to_BN(ai2, bn2)); + ExpectIntEQ(BN_cmp(bn, bn2), 0); BN_free(bn2); BN_free(bn); ASN1_INTEGER_free(ai2); ASN1_INTEGER_free(ai); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -31531,99 +31789,99 @@ static int test_wolfSSL_ASN1_INTEGER_get_set(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) - ASN1_INTEGER *a; + EXPECT_DECLS; + ASN1_INTEGER *a = NULL; long val; - int ret; - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); /* Invalid parameter testing. */ - AssertIntEQ(ASN1_INTEGER_get(NULL), 0); + ExpectIntEQ(ASN1_INTEGER_get(NULL), 0); #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY) - AssertIntEQ(ASN1_INTEGER_get(a), 0); + ExpectIntEQ(ASN1_INTEGER_get(a), 0); #else - AssertIntEQ(ASN1_INTEGER_get(a), -1); + ExpectIntEQ(ASN1_INTEGER_get(a), -1); #endif ASN1_INTEGER_free(a); + a = NULL; - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = 0; - ret = ASN1_INTEGER_set(NULL, val); - AssertIntEQ(ret, 0); + ExpectIntEQ(ASN1_INTEGER_set(NULL, val), 0); ASN1_INTEGER_free(a); + a = NULL; /* 0 */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = 0; - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); + a = NULL; /* 40 */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = 40; - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); + a = NULL; /* -40 */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = -40; - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); + a = NULL; /* 128 */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = 128; - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); + a = NULL; /* -128 */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = -128; - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); + a = NULL; /* 200 */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = 200; - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); + a = NULL; /* int max (2147483647) */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = 2147483647; - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); + a = NULL; /* int min (-2147483648) */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = -2147483647 - 1; - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); + a = NULL; /* long max positive */ - a = ASN1_INTEGER_new(); + ExpectNotNull(a = ASN1_INTEGER_new()); val = (long)(((unsigned long)-1) >> 1); - ret = ASN1_INTEGER_set(a, val); - AssertIntEQ(ret, 1); - AssertIntEQ(ASN1_INTEGER_get(a), val); + ExpectIntEQ(ASN1_INTEGER_set(a, val), 1); + ExpectTrue(ASN1_INTEGER_get(a) == val); ASN1_INTEGER_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -31639,11 +31897,13 @@ static int test_wolfSSL_d2i_ASN1_INTEGER(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) + EXPECT_DECLS; size_t i; WOLFSSL_ASN1_INTEGER* a = NULL; WOLFSSL_ASN1_INTEGER* b = NULL; WOLFSSL_ASN1_INTEGER* c = NULL; const byte* p = NULL; + byte* p2 = NULL; byte* reEncoded = NULL; int reEncodedSz; @@ -31699,76 +31959,80 @@ static int test_wolfSSL_d2i_ASN1_INTEGER(void) /* Check d2i error conditions */ /* NULL pointer to input. */ - AssertNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, NULL, 1))); - AssertNull(b); + ExpectNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, NULL, 1))); + ExpectNull(b); /* NULL input. */ - AssertNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, 1))); - AssertNull(b); + ExpectNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, 1))); + ExpectNull(b); /* 0 length. */ p = testVectors[0].der; - AssertNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, 0))); - AssertNull(b); + ExpectNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, 0))); + ExpectNull(b); /* Negative length. */ p = testVectors[0].der; - AssertNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, -1))); - AssertNull(b); + ExpectNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, -1))); + ExpectNull(b); /* Garbage DER input. */ p = garbageDer; - AssertNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, sizeof(garbageDer)))); - AssertNull(b); + ExpectNull((a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, sizeof(garbageDer)))); + ExpectNull(b); - { /* Check i2d error conditions */ /* NULL input. */ - byte* p2 = NULL; - AssertIntLT(wolfSSL_i2d_ASN1_INTEGER(NULL, &p2), 0); + ExpectIntLT(wolfSSL_i2d_ASN1_INTEGER(NULL, &p2), 0); /* 0 length input data buffer (a->length == 0). */ - AssertNotNull((a = wolfSSL_ASN1_INTEGER_new())); - AssertIntLT(wolfSSL_i2d_ASN1_INTEGER(a, &p2), 0); - a->data = NULL; + ExpectNotNull((a = wolfSSL_ASN1_INTEGER_new())); + ExpectIntLT(wolfSSL_i2d_ASN1_INTEGER(a, &p2), 0); + if (a != NULL) + a->data = NULL; /* NULL input data buffer. */ - AssertIntLT(wolfSSL_i2d_ASN1_INTEGER(a, &p2), 0); - /* Reset a->data. */ - a->data = a->intData; + ExpectIntLT(wolfSSL_i2d_ASN1_INTEGER(a, &p2), 0); + if (a != NULL) { + /* Reset a->data. */ + a->data = a->intData; + } /* Set a to valid value. */ - AssertIntEQ(wolfSSL_ASN1_INTEGER_set(a, 1), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_ASN1_INTEGER_set(a, 1), WOLFSSL_SUCCESS); /* NULL output buffer. */ - AssertIntLT(wolfSSL_i2d_ASN1_INTEGER(a, NULL), 0); + ExpectIntLT(wolfSSL_i2d_ASN1_INTEGER(a, NULL), 0); wolfSSL_ASN1_INTEGER_free(a); - } + a = NULL; for (i = 0; i < NUM_TEST_VECTORS; ++i) { p = testVectors[i].der; - a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, testVectors[i].derSz); - AssertIntEQ(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); + ExpectNotNull(a = wolfSSL_d2i_ASN1_INTEGER(&b, &p, + testVectors[i].derSz)); + ExpectIntEQ(wolfSSL_ASN1_INTEGER_cmp(a, b), 0); if (testVectors[i].derSz <= sizeof(long)) { - c = wolfSSL_ASN1_INTEGER_new(); - wolfSSL_ASN1_INTEGER_set(c, testVectors[i].value); - AssertIntEQ(wolfSSL_ASN1_INTEGER_cmp(a, c), 0); + ExpectNotNull(c = wolfSSL_ASN1_INTEGER_new()); + ExpectIntEQ(wolfSSL_ASN1_INTEGER_set(c, testVectors[i].value), 1); + ExpectIntEQ(wolfSSL_ASN1_INTEGER_cmp(a, c), 0); wolfSSL_ASN1_INTEGER_free(c); + c = NULL; } /* Convert to DER without a pre-allocated output buffer. */ - AssertIntGT((reEncodedSz = wolfSSL_i2d_ASN1_INTEGER(a, &reEncoded)), 0); - AssertIntEQ(reEncodedSz, testVectors[i].derSz); - AssertIntEQ(XMEMCMP(reEncoded, testVectors[i].der, reEncodedSz), 0); + ExpectIntGT((reEncodedSz = wolfSSL_i2d_ASN1_INTEGER(a, &reEncoded)), 0); + ExpectIntEQ(reEncodedSz, testVectors[i].derSz); + ExpectIntEQ(XMEMCMP(reEncoded, testVectors[i].der, reEncodedSz), 0); /* Convert to DER with a pre-allocated output buffer. In this case, the * output buffer pointer should be incremented just past the end of the * encoded data. */ - p = reEncoded; - AssertIntGT((reEncodedSz = wolfSSL_i2d_ASN1_INTEGER(a, &reEncoded)), 0); - AssertIntEQ(reEncodedSz, testVectors[i].derSz); - AssertPtrEq(p, reEncoded - reEncodedSz); - AssertIntEQ(XMEMCMP(p, testVectors[i].der, reEncodedSz), 0); + p2 = reEncoded; + ExpectIntGT((reEncodedSz = wolfSSL_i2d_ASN1_INTEGER(a, &p2)), 0); + ExpectIntEQ(reEncodedSz, testVectors[i].derSz); + ExpectPtrEq(reEncoded, p2 - reEncodedSz); + ExpectIntEQ(XMEMCMP(reEncoded, testVectors[i].der, reEncodedSz), 0); - XFREE(reEncoded - reEncodedSz, NULL, DYNAMIC_TYPE_ASN1); + XFREE(reEncoded, NULL, DYNAMIC_TYPE_ASN1); reEncoded = NULL; wolfSSL_ASN1_INTEGER_free(a); + a = NULL; } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -31777,10 +32041,11 @@ static int test_wolfSSL_a2i_ASN1_INTEGER(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_BIO) - BIO* bio; - BIO* out; - BIO* fixed; - ASN1_INTEGER* ai; + EXPECT_DECLS; + BIO* bio = NULL; + BIO* out = NULL; + BIO* fixed = NULL; + ASN1_INTEGER* ai = NULL; char buf[] = "123456\n12345\n1123456789123456\\\n78901234567890 \r\n\n"; char tmp[1024]; int tmpSz; @@ -31790,81 +32055,81 @@ static int test_wolfSSL_a2i_ASN1_INTEGER(void) char longStr[] = "123456781234567812345678123456781234567812345678\n" "123456781234567812345678123456781234567812345678\\\n12345678\n"; - AssertNotNull(out = BIO_new(BIO_s_mem())); - AssertNotNull(ai = ASN1_INTEGER_new()); + ExpectNotNull(out = BIO_new(BIO_s_mem())); + ExpectNotNull(ai = ASN1_INTEGER_new()); - AssertNotNull(bio = BIO_new_mem_buf(buf, -1)); + ExpectNotNull(bio = BIO_new_mem_buf(buf, -1)); /* Invalid parameter testing. */ - AssertIntEQ(a2i_ASN1_INTEGER(NULL, NULL, NULL, -1), 0); - AssertIntEQ(a2i_ASN1_INTEGER(bio, NULL, NULL, -1), 0); - AssertIntEQ(a2i_ASN1_INTEGER(NULL, ai, NULL, -1), 0); - AssertIntEQ(a2i_ASN1_INTEGER(NULL, NULL, tmp, -1), 0); - AssertIntEQ(a2i_ASN1_INTEGER(NULL, NULL, NULL, 1024), 0); - AssertIntEQ(a2i_ASN1_INTEGER(NULL, ai, tmp, 1024), 0); - AssertIntEQ(a2i_ASN1_INTEGER(bio, NULL, tmp, 1024), 0); - AssertIntEQ(a2i_ASN1_INTEGER(bio, ai, NULL, 1024), 0); - AssertIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, -1), 0); - AssertIntEQ(i2a_ASN1_INTEGER(NULL, NULL), 0); - AssertIntEQ(i2a_ASN1_INTEGER(bio, NULL), 0); - AssertIntEQ(i2a_ASN1_INTEGER(NULL, ai), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(NULL, NULL, NULL, -1), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, NULL, NULL, -1), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(NULL, ai, NULL, -1), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(NULL, NULL, tmp, -1), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(NULL, NULL, NULL, 1024), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(NULL, ai, tmp, 1024), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, NULL, tmp, 1024), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, ai, NULL, 1024), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, -1), 0); + ExpectIntEQ(i2a_ASN1_INTEGER(NULL, NULL), 0); + ExpectIntEQ(i2a_ASN1_INTEGER(bio, NULL), 0); + ExpectIntEQ(i2a_ASN1_INTEGER(NULL, ai), 0); /* No data to read from BIO. */ - AssertIntEQ(a2i_ASN1_INTEGER(out, ai, tmp, 1024), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(out, ai, tmp, 1024), 0); /* read first line */ - AssertIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 1); - AssertIntEQ(i2a_ASN1_INTEGER(out, ai), 6); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 1); + ExpectIntEQ(i2a_ASN1_INTEGER(out, ai), 6); XMEMSET(tmp, 0, 1024); tmpSz = BIO_read(out, tmp, 1024); - AssertIntEQ(tmpSz, 6); - AssertIntEQ(XMEMCMP(tmp, expected1, tmpSz), 0); + ExpectIntEQ(tmpSz, 6); + ExpectIntEQ(XMEMCMP(tmp, expected1, tmpSz), 0); /* fail on second line (not % 2) */ - AssertIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 0); /* read 3rd long line */ - AssertIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 1); - AssertIntEQ(i2a_ASN1_INTEGER(out, ai), 30); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 1); + ExpectIntEQ(i2a_ASN1_INTEGER(out, ai), 30); XMEMSET(tmp, 0, 1024); tmpSz = BIO_read(out, tmp, 1024); - AssertIntEQ(tmpSz, 30); - AssertIntEQ(XMEMCMP(tmp, expected2, tmpSz), 0); + ExpectIntEQ(tmpSz, 30); + ExpectIntEQ(XMEMCMP(tmp, expected2, tmpSz), 0); /* fail on empty line */ - AssertIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 0); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 0); BIO_free(bio); + bio = NULL; /* Make long integer, requiring dynamic memory, even longer. */ - AssertNotNull(bio = BIO_new_mem_buf(longStr, -1)); - AssertIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 1); - AssertIntEQ(i2a_ASN1_INTEGER(out, ai), 48); + ExpectNotNull(bio = BIO_new_mem_buf(longStr, -1)); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 1); + ExpectIntEQ(i2a_ASN1_INTEGER(out, ai), 48); XMEMSET(tmp, 0, 1024); tmpSz = BIO_read(out, tmp, 1024); - AssertIntEQ(tmpSz, 48); - AssertIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 1); - AssertIntEQ(i2a_ASN1_INTEGER(out, ai), 56); + ExpectIntEQ(tmpSz, 48); + ExpectIntEQ(a2i_ASN1_INTEGER(bio, ai, tmp, 1024), 1); + ExpectIntEQ(i2a_ASN1_INTEGER(out, ai), 56); XMEMSET(tmp, 0, 1024); tmpSz = BIO_read(out, tmp, 1024); - AssertIntEQ(tmpSz, 56); - AssertIntEQ(wolfSSL_ASN1_INTEGER_set(ai, 1), 1); + ExpectIntEQ(tmpSz, 56); + ExpectIntEQ(wolfSSL_ASN1_INTEGER_set(ai, 1), 1); BIO_free(bio); BIO_free(out); - AssertNotNull(fixed = BIO_new(wolfSSL_BIO_s_fixed_mem())); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectNotNull(fixed = BIO_new(wolfSSL_BIO_s_fixed_mem())); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(fixed, tmp, 1), 1); - AssertIntEQ(i2a_ASN1_INTEGER(fixed, ai), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); - AssertIntEQ(i2a_ASN1_INTEGER(fixed, ai), 0); + ExpectIntEQ(BIO_write(fixed, tmp, 1), 1); + ExpectIntEQ(i2a_ASN1_INTEGER(fixed, ai), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(i2a_ASN1_INTEGER(fixed, ai), 0); BIO_free(fixed); ASN1_INTEGER_free(ai); - - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -31873,178 +32138,208 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) - ASN1_INTEGER *a; + EXPECT_DECLS; + ASN1_INTEGER *a = NULL; unsigned char *pp,*tpp; int ret; - a = wolfSSL_ASN1_INTEGER_new(); + ExpectNotNull(a = wolfSSL_ASN1_INTEGER_new()); /* Invalid parameter testing. */ /* Set pp to an invalid value. */ pp = NULL; - AssertIntEQ(i2c_ASN1_INTEGER(NULL, &pp), 0); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 0); - AssertIntEQ(i2c_ASN1_INTEGER(NULL, NULL), 0); + ExpectIntEQ(i2c_ASN1_INTEGER(NULL, &pp), 0); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &pp), 0); + ExpectIntEQ(i2c_ASN1_INTEGER(NULL, NULL), 0); /* 40 */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 1; - a->intData[2] = 40; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 1; + a->intData[2] = 40; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 1); - pp--; - AssertIntEQ(*pp, 40); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 40); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* 128 */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 1; - a->intData[2] = 128; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 1; + a->intData[2] = 128; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 2); - pp--; - AssertIntEQ(*(pp--), 128); - AssertIntEQ(*pp, 0); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); + tpp--; + ExpectIntEQ(*(tpp--), 128); + ExpectIntEQ(*tpp, 0); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* -40 */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 1; - a->intData[2] = 40; - a->negative = 1; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 1; + a->intData[2] = 40; + a->negative = 1; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 1); - pp--; - AssertIntEQ(*pp, 216); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 216); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* -128 */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 1; - a->intData[2] = 128; - a->negative = 1; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 1; + a->intData[2] = 128; + a->negative = 1; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 1); - pp--; - AssertIntEQ(*pp, 128); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 128); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* -200 */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 1; - a->intData[2] = 200; - a->negative = 1; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 1; + a->intData[2] = 200; + a->negative = 1; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 2); - pp--; - AssertIntEQ(*(pp--), 56); - AssertIntEQ(*pp, 255); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); + tpp--; + ExpectIntEQ(*(tpp--), 56); + ExpectIntEQ(*tpp, 255); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* Empty */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 0; - a->negative = 0; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 0; + a->negative = 0; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 1); - pp--; - AssertIntEQ(*pp, 0); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 0); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* 0 */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 1; - a->intData[2] = 0; - a->negative = 1; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 1; + a->intData[2] = 0; + a->negative = 1; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 1); - pp--; - AssertIntEQ(*pp, 0); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 0); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* 0x100 */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 2; - a->intData[2] = 0x01; - a->intData[3] = 0x00; - a->negative = 0; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 2; + a->intData[2] = 0x01; + a->intData[3] = 0x00; + a->negative = 0; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 2); - pp -= 2; - AssertIntEQ(pp[0], 0x01); - AssertIntEQ(pp[1], 0x00); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); + tpp -= 2; + ExpectIntEQ(tpp[0], 0x01); + ExpectIntEQ(tpp[1], 0x00); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* -0x8000 => 0x8000 */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 2; - a->intData[2] = 0x80; - a->intData[3] = 0x00; - a->negative = 1; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 2; + a->intData[2] = 0x80; + a->intData[3] = 0x00; + a->negative = 1; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 2); - pp -= 2; - AssertIntEQ(pp[0], 0x80); - AssertIntEQ(pp[1], 0x00); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); + tpp -= 2; + ExpectIntEQ(tpp[0], 0x80); + ExpectIntEQ(tpp[1], 0x00); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pp = NULL; /* -0x8001 => 0xFF7FFF */ - a->intData[0] = ASN_INTEGER; - a->intData[1] = 2; - a->intData[2] = 0x80; - a->intData[3] = 0x01; - a->negative = 1; - AssertIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 3); - AssertNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, + if (a != NULL) { + a->intData[0] = ASN_INTEGER; + a->intData[1] = 2; + a->intData[2] = 0x80; + a->intData[3] = 0x01; + a->negative = 1; + } + ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 3); + ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - XMEMSET(pp, 0, ret + 1); - AssertIntEQ(i2c_ASN1_INTEGER(a, &pp), 3); - pp -= 3; - AssertIntEQ(pp[0], 0xFF); - AssertIntEQ(pp[1], 0x7F); - AssertIntEQ(pp[2], 0xFF); - XFREE(tpp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 3); + tpp -= 3; + ExpectIntEQ(tpp[0], 0xFF); + ExpectIntEQ(tpp[1], 0x7F); + ExpectIntEQ(tpp[2], 0xFF); + XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); wolfSSL_ASN1_INTEGER_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && !NO_ASN */ return res; } @@ -32053,26 +32348,28 @@ static int test_wolfSSL_ASN1_OBJECT(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) - ASN1_OBJECT* a; + EXPECT_DECLS; + ASN1_OBJECT* a = NULL; ASN1_OBJECT s; const unsigned char der[] = { 0x06, 0x01, 0x00 }; /* Invalid parameter testing. */ ASN1_OBJECT_free(NULL); - AssertNull(wolfSSL_ASN1_OBJECT_dup(NULL)); + ExpectNull(wolfSSL_ASN1_OBJECT_dup(NULL)); /* Test that a static ASN1_OBJECT can be freed. */ XMEMSET(&s, 0, sizeof(ASN1_OBJECT)); ASN1_OBJECT_free(&s); - AssertNotNull(a = wolfSSL_ASN1_OBJECT_dup(&s)); + ExpectNotNull(a = wolfSSL_ASN1_OBJECT_dup(&s)); ASN1_OBJECT_free(a); + a = NULL; s.obj = der; s.objSz = sizeof(der); - AssertNotNull(a = wolfSSL_ASN1_OBJECT_dup(&s)); + ExpectNotNull(a = wolfSSL_ASN1_OBJECT_dup(&s)); ASN1_OBJECT_free(a); ASN1_OBJECT_free(&s); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -32081,6 +32378,7 @@ static int test_wolfSSL_ASN1_get_object(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) && defined(USE_CERT_BUFFERS_256) + EXPECT_DECLS; const unsigned char* derBuf = cliecc_cert_der_256; const unsigned char* nullPtr = NULL; const unsigned char objDerInvalidLen[] = { 0x30, 0x81 }; @@ -32095,124 +32393,125 @@ static int test_wolfSSL_ASN1_get_object(void) long asnLen = 0; int tag = 0; int cls = 0; - ASN1_OBJECT* a; + ASN1_OBJECT* a = NULL; ASN1_OBJECT s; XMEMSET(&s, 0, sizeof(ASN1_OBJECT)); /* Invalid encoding at length. */ p = objDerInvalidLen; - AssertIntEQ(ASN1_get_object(&p, &asnLen, &tag, &cls, sizeof(objDerBadLen)), + ExpectIntEQ(ASN1_get_object(&p, &asnLen, &tag, &cls, sizeof(objDerBadLen)), 0x80); p = objDerBadLen; /* Error = 0x80, Constructed = 0x20 */ - AssertIntEQ(ASN1_get_object(&p, &asnLen, &tag, &cls, sizeof(objDerBadLen)), + ExpectIntEQ(ASN1_get_object(&p, &asnLen, &tag, &cls, sizeof(objDerBadLen)), 0x80 | 0x20); /* Read a couple TLV triplets and make sure they match the expected values */ /* SEQUENCE */ - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, len) & 0x80, 0); - AssertIntEQ(asnLen, 862); - AssertIntEQ(tag, 0x10); - AssertIntEQ(cls, 0); + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, len) & 0x80, 0); + ExpectIntEQ(asnLen, 862); + ExpectIntEQ(tag, 0x10); + ExpectIntEQ(cls, 0); /* SEQUENCE */ - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, len - (derBuf - cliecc_cert_der_256)) & 0x80, 0); - AssertIntEQ(asnLen, 772); - AssertIntEQ(tag, 0x10); - AssertIntEQ(cls, 0); + ExpectIntEQ(asnLen, 772); + ExpectIntEQ(tag, 0x10); + ExpectIntEQ(cls, 0); /* [0] */ - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, len - (derBuf - cliecc_cert_der_256)) & 0x80, 0); - AssertIntEQ(asnLen, 3); - AssertIntEQ(tag, 0); - AssertIntEQ(cls, 0x80); + ExpectIntEQ(asnLen, 3); + ExpectIntEQ(tag, 0); + ExpectIntEQ(cls, 0x80); /* INTEGER */ - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, len - (derBuf - cliecc_cert_der_256)) & 0x80, 0); - AssertIntEQ(asnLen, 1); - AssertIntEQ(tag, 0x2); - AssertIntEQ(cls, 0); + ExpectIntEQ(asnLen, 1); + ExpectIntEQ(tag, 0x2); + ExpectIntEQ(cls, 0); derBuf += asnLen; /* INTEGER */ - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, len - (derBuf - cliecc_cert_der_256)) & 0x80, 0); - AssertIntEQ(asnLen, 20); - AssertIntEQ(tag, 0x2); - AssertIntEQ(cls, 0); + ExpectIntEQ(asnLen, 20); + ExpectIntEQ(tag, 0x2); + ExpectIntEQ(cls, 0); derBuf += asnLen; /* SEQUENCE */ - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, len - (derBuf - cliecc_cert_der_256)) & 0x80, 0); - AssertIntEQ(asnLen, 10); - AssertIntEQ(tag, 0x10); - AssertIntEQ(cls, 0); + ExpectIntEQ(asnLen, 10); + ExpectIntEQ(tag, 0x10); + ExpectIntEQ(cls, 0); /* Found OBJECT_ID. */ /* Invalid parameter testing. */ - AssertIntEQ(ASN1_get_object(NULL, NULL, NULL, NULL, 0), 0x80); - AssertIntEQ(ASN1_get_object(&nullPtr, NULL, NULL, NULL, 0), 0x80); - AssertIntEQ(ASN1_get_object(NULL, &asnLen, &tag, &cls, len), 0x80); - AssertIntEQ(ASN1_get_object(&nullPtr, &asnLen, &tag, &cls, len), 0x80); - AssertIntEQ(ASN1_get_object(&derBuf, NULL, &tag, &cls, len), 0x80); - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, NULL, &cls, len), 0x80); - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, NULL, len), 0x80); - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, 0), 0x80); - AssertIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, -1), 0x80); - AssertNull(d2i_ASN1_OBJECT(NULL, NULL, -1)); - AssertNull(d2i_ASN1_OBJECT(NULL, &nullPtr, -1)); - AssertNull(d2i_ASN1_OBJECT(NULL, &derBuf, -1)); - AssertNull(d2i_ASN1_OBJECT(NULL, NULL, 0)); - AssertNull(d2i_ASN1_OBJECT(&a, NULL, len)); - AssertNull(d2i_ASN1_OBJECT(&a, &nullPtr, len)); - AssertNull(d2i_ASN1_OBJECT(&a, &derBuf, -1)); - AssertNull(c2i_ASN1_OBJECT(NULL, NULL, -1)); - AssertNull(c2i_ASN1_OBJECT(NULL, &nullPtr, -1)); - AssertNull(c2i_ASN1_OBJECT(NULL, &derBuf, -1)); - AssertNull(c2i_ASN1_OBJECT(NULL, NULL, 1)); - AssertNull(c2i_ASN1_OBJECT(NULL, &nullPtr, 1)); + ExpectIntEQ(ASN1_get_object(NULL, NULL, NULL, NULL, 0), 0x80); + ExpectIntEQ(ASN1_get_object(&nullPtr, NULL, NULL, NULL, 0), 0x80); + ExpectIntEQ(ASN1_get_object(NULL, &asnLen, &tag, &cls, len), 0x80); + ExpectIntEQ(ASN1_get_object(&nullPtr, &asnLen, &tag, &cls, len), 0x80); + ExpectIntEQ(ASN1_get_object(&derBuf, NULL, &tag, &cls, len), 0x80); + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, NULL, &cls, len), 0x80); + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, NULL, len), 0x80); + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, 0), 0x80); + ExpectIntEQ(ASN1_get_object(&derBuf, &asnLen, &tag, &cls, -1), 0x80); + ExpectNull(d2i_ASN1_OBJECT(NULL, NULL, -1)); + ExpectNull(d2i_ASN1_OBJECT(NULL, &nullPtr, -1)); + ExpectNull(d2i_ASN1_OBJECT(NULL, &derBuf, -1)); + ExpectNull(d2i_ASN1_OBJECT(NULL, NULL, 0)); + ExpectNull(d2i_ASN1_OBJECT(&a, NULL, len)); + ExpectNull(d2i_ASN1_OBJECT(&a, &nullPtr, len)); + ExpectNull(d2i_ASN1_OBJECT(&a, &derBuf, -1)); + ExpectNull(c2i_ASN1_OBJECT(NULL, NULL, -1)); + ExpectNull(c2i_ASN1_OBJECT(NULL, &nullPtr, -1)); + ExpectNull(c2i_ASN1_OBJECT(NULL, &derBuf, -1)); + ExpectNull(c2i_ASN1_OBJECT(NULL, NULL, 1)); + ExpectNull(c2i_ASN1_OBJECT(NULL, &nullPtr, 1)); /* Invalid encoding at length. */ p = objDerInvalidLen; - AssertNull(d2i_ASN1_OBJECT(&a, &p, sizeof(objDerInvalidLen))); + ExpectNull(d2i_ASN1_OBJECT(&a, &p, sizeof(objDerInvalidLen))); p = objDerBadLen; - AssertNull(d2i_ASN1_OBJECT(&a, &p, sizeof(objDerBadLen))); + ExpectNull(d2i_ASN1_OBJECT(&a, &p, sizeof(objDerBadLen))); p = objDerNotObj; - AssertNull(d2i_ASN1_OBJECT(&a, &p, sizeof(objDerNotObj))); + ExpectNull(d2i_ASN1_OBJECT(&a, &p, sizeof(objDerNotObj))); p = objDerNoData; - AssertNull(d2i_ASN1_OBJECT(&a, &p, sizeof(objDerNoData))); + ExpectNull(d2i_ASN1_OBJECT(&a, &p, sizeof(objDerNoData))); /* Create an ASN OBJECT from content */ p = derBuf + 2; - AssertNotNull(a = c2i_ASN1_OBJECT(NULL, &p, 8)); + ExpectNotNull(a = c2i_ASN1_OBJECT(NULL, &p, 8)); ASN1_OBJECT_free(a); + a = NULL; /* Create an ASN OBJECT from DER */ - AssertNotNull(d2i_ASN1_OBJECT(&a, &derBuf, len)); + ExpectNotNull(d2i_ASN1_OBJECT(&a, &derBuf, len)); /* Invalid parameter testing. */ - AssertIntEQ(i2d_ASN1_OBJECT(NULL, NULL), 0); - AssertIntEQ(i2d_ASN1_OBJECT(&s, NULL), 0); + ExpectIntEQ(i2d_ASN1_OBJECT(NULL, NULL), 0); + ExpectIntEQ(i2d_ASN1_OBJECT(&s, NULL), 0); - AssertIntEQ(i2d_ASN1_OBJECT(a, NULL), 8); + ExpectIntEQ(i2d_ASN1_OBJECT(a, NULL), 8); der = NULL; - AssertIntEQ(i2d_ASN1_OBJECT(a, &der), 8); + ExpectIntEQ(i2d_ASN1_OBJECT(a, &der), 8); derPtr = objDer; - AssertIntEQ(i2d_ASN1_OBJECT(a, &derPtr), 8); - AssertPtrNE(derPtr, objDer); - AssertIntEQ(XMEMCMP(der, objDer, 8), 0); + ExpectIntEQ(i2d_ASN1_OBJECT(a, &derPtr), 8); + ExpectPtrNE(derPtr, objDer); + ExpectIntEQ(XMEMCMP(der, objDer, 8), 0); XFREE(der, NULL, DYNAMIC_TYPE_OPENSSL); ASN1_OBJECT_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && HAVE_ECC && USE_CERT_BUFFERS_256 */ return res; } @@ -32221,6 +32520,7 @@ static int test_wolfSSL_i2a_ASN1_OBJECT(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && !defined(NO_BIO) + EXPECT_DECLS; ASN1_OBJECT* obj = NULL; ASN1_OBJECT* a = NULL; BIO *bio = NULL; @@ -32229,38 +32529,41 @@ static int test_wolfSSL_i2a_ASN1_OBJECT(void) const unsigned char goodDer[] = { 0x06, 0x01, 0x01 }; const unsigned char* p; - AssertNotNull(obj = OBJ_nid2obj(NID_sha256)); - AssertTrue((bio = BIO_new(BIO_s_mem())) != NULL); + ExpectNotNull(obj = OBJ_nid2obj(NID_sha256)); + ExpectTrue((bio = BIO_new(BIO_s_mem())) != NULL); - AssertIntGT(wolfSSL_i2a_ASN1_OBJECT(bio, obj), 0); - AssertIntGT(wolfSSL_i2a_ASN1_OBJECT(bio, NULL), 0); + ExpectIntGT(wolfSSL_i2a_ASN1_OBJECT(bio, obj), 0); + ExpectIntGT(wolfSSL_i2a_ASN1_OBJECT(bio, NULL), 0); - AssertIntEQ(wolfSSL_i2a_ASN1_OBJECT(NULL, obj), 0); + ExpectIntEQ(wolfSSL_i2a_ASN1_OBJECT(NULL, obj), 0); /* No DER encoding in ASN1_OBJECT. */ - a = wolfSSL_ASN1_OBJECT_new(); - AssertIntEQ(wolfSSL_i2a_ASN1_OBJECT(bio, a), 0); + ExpectNotNull(a = wolfSSL_ASN1_OBJECT_new()); + ExpectIntEQ(wolfSSL_i2a_ASN1_OBJECT(bio, a), 0); ASN1_OBJECT_free(a); + a = NULL; /* DER encoding - not OBJECT_ID */ p = notObjDer; - AssertNotNull(a = c2i_ASN1_OBJECT(NULL, &p, 3)); - AssertIntEQ(wolfSSL_i2a_ASN1_OBJECT(bio, a), 0); + ExpectNotNull(a = c2i_ASN1_OBJECT(NULL, &p, 3)); + ExpectIntEQ(wolfSSL_i2a_ASN1_OBJECT(bio, a), 0); ASN1_OBJECT_free(a); + a = NULL; /* Bad length encoding. */ p = badLenDer; - AssertNotNull(a = c2i_ASN1_OBJECT(NULL, &p, 3)); - AssertIntEQ(wolfSSL_i2a_ASN1_OBJECT(bio, a), 0); + ExpectNotNull(a = c2i_ASN1_OBJECT(NULL, &p, 3)); + ExpectIntEQ(wolfSSL_i2a_ASN1_OBJECT(bio, a), 0); ASN1_OBJECT_free(a); + a = NULL; /* Good encoding - but unknown. */ p = goodDer; - AssertNotNull(a = c2i_ASN1_OBJECT(NULL, &p, 3)); - AssertIntGT(wolfSSL_i2a_ASN1_OBJECT(bio, a), 0); + ExpectNotNull(a = c2i_ASN1_OBJECT(NULL, &p, 3)); + ExpectIntGT(wolfSSL_i2a_ASN1_OBJECT(bio, a), 0); ASN1_OBJECT_free(a); BIO_free(bio); ASN1_OBJECT_free(obj); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -32270,24 +32573,24 @@ static int test_wolfSSL_i2t_ASN1_OBJECT(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN) - + EXPECT_DECLS; char buf[50] = {0}; ASN1_OBJECT* obj; const char* oid = "2.5.29.19"; const char* ln = "X509v3 Basic Constraints"; obj = NULL; - AssertIntEQ(i2t_ASN1_OBJECT(NULL, sizeof(buf), obj), 0); - AssertIntEQ(i2t_ASN1_OBJECT(buf, sizeof(buf), NULL), 0); - AssertIntEQ(i2t_ASN1_OBJECT(buf, 0, NULL), 0); + ExpectIntEQ(i2t_ASN1_OBJECT(NULL, sizeof(buf), obj), 0); + ExpectIntEQ(i2t_ASN1_OBJECT(buf, sizeof(buf), NULL), 0); + ExpectIntEQ(i2t_ASN1_OBJECT(buf, 0, NULL), 0); - AssertNotNull(obj = OBJ_txt2obj(oid, 0)); + ExpectNotNull(obj = OBJ_txt2obj(oid, 0)); XMEMSET(buf, 0, sizeof(buf)); - AssertIntEQ(i2t_ASN1_OBJECT(buf, sizeof(buf), obj), XSTRLEN(ln)); - AssertIntEQ(XSTRNCMP(buf, ln, XSTRLEN(ln)), 0); + ExpectIntEQ(i2t_ASN1_OBJECT(buf, sizeof(buf), obj), XSTRLEN(ln)); + ExpectIntEQ(XSTRNCMP(buf, ln, XSTRLEN(ln)), 0); ASN1_OBJECT_free(obj); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && WOLFSSL_CERT_EXT && WOLFSSL_CERT_GEN */ return res; } @@ -32296,30 +32599,33 @@ static int test_wolfSSL_sk_ASN1_OBJECT(void) { int res = TEST_SKIPPED; #if !defined(NO_ASN) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) - WOLFSSL_STACK* sk; + EXPECT_DECLS; + WOLFSSL_STACK* sk = NULL; WOLFSSL_ASN1_OBJECT* obj; - AssertNotNull(obj = wolfSSL_ASN1_OBJECT_new()); + ExpectNotNull(obj = wolfSSL_ASN1_OBJECT_new()); - AssertNotNull(sk = wolfSSL_sk_new_asn1_obj()); + ExpectNotNull(sk = wolfSSL_sk_new_asn1_obj()); wolfSSL_sk_ASN1_OBJECT_free(sk); + sk = NULL; - AssertNotNull(sk = wolfSSL_sk_new_asn1_obj()); - AssertIntEQ(wolfSSL_sk_ASN1_OBJECT_push(NULL, NULL), 0); - AssertIntEQ(wolfSSL_sk_ASN1_OBJECT_push(sk, NULL), 0); - AssertIntEQ(wolfSSL_sk_ASN1_OBJECT_push(NULL, obj), 0); - AssertIntEQ(wolfSSL_sk_ASN1_OBJECT_push(sk, obj), 1); + ExpectNotNull(sk = wolfSSL_sk_new_asn1_obj()); + ExpectIntEQ(wolfSSL_sk_ASN1_OBJECT_push(NULL, NULL), 0); + ExpectIntEQ(wolfSSL_sk_ASN1_OBJECT_push(sk, NULL), 0); + ExpectIntEQ(wolfSSL_sk_ASN1_OBJECT_push(NULL, obj), 0); + ExpectIntEQ(wolfSSL_sk_ASN1_OBJECT_push(sk, obj), 1); wolfSSL_sk_ASN1_OBJECT_pop_free(sk, NULL); + sk = NULL; /* obj freed in pop_free call. */ - AssertNotNull(obj = wolfSSL_ASN1_OBJECT_new()); - AssertNotNull(sk = wolfSSL_sk_new_asn1_obj()); - AssertIntEQ(wolfSSL_sk_ASN1_OBJECT_push(sk, obj), 1); - AssertPtrEq(obj, wolfSSL_sk_ASN1_OBJECT_pop(sk)); + ExpectNotNull(obj = wolfSSL_ASN1_OBJECT_new()); + ExpectNotNull(sk = wolfSSL_sk_new_asn1_obj()); + ExpectIntEQ(wolfSSL_sk_ASN1_OBJECT_push(sk, obj), 1); + ExpectPtrEq(obj, wolfSSL_sk_ASN1_OBJECT_pop(sk)); wolfSSL_sk_ASN1_OBJECT_free(sk); wolfSSL_ASN1_OBJECT_free(obj); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_ASN && (OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL) */ return res; } @@ -32328,6 +32634,7 @@ static int test_wolfSSL_ASN1_STRING(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) + EXPECT_DECLS; ASN1_STRING* str = NULL; ASN1_STRING* c = NULL; const char data[] = "hello wolfSSL"; @@ -32335,55 +32642,56 @@ static int test_wolfSSL_ASN1_STRING(void) const char longData[] = "This string must be longer than CTC_NAME_SIZE that is defined as 64."; - AssertNotNull(str = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); + ExpectNotNull(str = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); ASN1_STRING_free(str); + str = NULL; - AssertNotNull(str = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); - AssertIntEQ(ASN1_STRING_type(str), V_ASN1_OCTET_STRING); - AssertIntEQ(ASN1_STRING_type(NULL), 0); + ExpectNotNull(str = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); + ExpectIntEQ(ASN1_STRING_type(str), V_ASN1_OCTET_STRING); + ExpectIntEQ(ASN1_STRING_type(NULL), 0); /* Check setting to NULL works. */ - AssertIntEQ(ASN1_STRING_set(str, NULL, 0), 1); - AssertIntEQ(ASN1_STRING_set(str, (const void*)data, sizeof(data)), 1); - AssertIntEQ(ASN1_STRING_set(str, (const void*)data, -1), 1); - AssertIntEQ(ASN1_STRING_set(str, NULL, -1), 0); - AssertIntEQ(ASN1_STRING_set(NULL, NULL, 0), 0); - - AssertIntEQ(wolfSSL_ASN1_STRING_copy(NULL, NULL), 0); - AssertIntEQ(wolfSSL_ASN1_STRING_copy(str, NULL), 0); - AssertIntEQ(wolfSSL_ASN1_STRING_copy(NULL, str), 0); - AssertNull(wolfSSL_ASN1_STRING_dup(NULL)); - - AssertNotNull(c = wolfSSL_ASN1_STRING_dup(str)); - AssertIntEQ(ASN1_STRING_cmp(NULL, NULL), -1); - AssertIntEQ(ASN1_STRING_cmp(str, NULL), -1); - AssertIntEQ(ASN1_STRING_cmp(NULL, c), -1); - AssertIntEQ(ASN1_STRING_cmp(str, c), 0); - AssertIntEQ(ASN1_STRING_set(c, (const void*)data2, -1), 1); - AssertIntGT(ASN1_STRING_cmp(str, c), 0); - AssertIntEQ(ASN1_STRING_set(str, (const void*)longData, -1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_copy(c, str), 1); - AssertIntEQ(ASN1_STRING_cmp(str, c), 0); + ExpectIntEQ(ASN1_STRING_set(str, NULL, 0), 1); + ExpectIntEQ(ASN1_STRING_set(str, (const void*)data, sizeof(data)), 1); + ExpectIntEQ(ASN1_STRING_set(str, (const void*)data, -1), 1); + ExpectIntEQ(ASN1_STRING_set(str, NULL, -1), 0); + ExpectIntEQ(ASN1_STRING_set(NULL, NULL, 0), 0); + + ExpectIntEQ(wolfSSL_ASN1_STRING_copy(NULL, NULL), 0); + ExpectIntEQ(wolfSSL_ASN1_STRING_copy(str, NULL), 0); + ExpectIntEQ(wolfSSL_ASN1_STRING_copy(NULL, str), 0); + ExpectNull(wolfSSL_ASN1_STRING_dup(NULL)); + + ExpectNotNull(c = wolfSSL_ASN1_STRING_dup(str)); + ExpectIntEQ(ASN1_STRING_cmp(NULL, NULL), -1); + ExpectIntEQ(ASN1_STRING_cmp(str, NULL), -1); + ExpectIntEQ(ASN1_STRING_cmp(NULL, c), -1); + ExpectIntEQ(ASN1_STRING_cmp(str, c), 0); + ExpectIntEQ(ASN1_STRING_set(c, (const void*)data2, -1), 1); + ExpectIntGT(ASN1_STRING_cmp(str, c), 0); + ExpectIntEQ(ASN1_STRING_set(str, (const void*)longData, -1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_copy(c, str), 1); + ExpectIntEQ(ASN1_STRING_cmp(str, c), 0); /* Check setting back to smaller size frees dynamic data. */ - AssertIntEQ(ASN1_STRING_set(str, (const void*)data, -1), 1); - AssertIntLT(ASN1_STRING_cmp(str, c), 0); - AssertIntGT(ASN1_STRING_cmp(c, str), 0); + ExpectIntEQ(ASN1_STRING_set(str, (const void*)data, -1), 1); + ExpectIntLT(ASN1_STRING_cmp(str, c), 0); + ExpectIntGT(ASN1_STRING_cmp(c, str), 0); - AssertNull(ASN1_STRING_get0_data(NULL)); - AssertNotNull(ASN1_STRING_get0_data(str)); - AssertNull(ASN1_STRING_data(NULL)); - AssertNotNull(ASN1_STRING_data(str)); - AssertIntEQ(ASN1_STRING_length(NULL), 0); - AssertIntGT(ASN1_STRING_length(str), 0); + ExpectNull(ASN1_STRING_get0_data(NULL)); + ExpectNotNull(ASN1_STRING_get0_data(str)); + ExpectNull(ASN1_STRING_data(NULL)); + ExpectNotNull(ASN1_STRING_data(str)); + ExpectIntEQ(ASN1_STRING_length(NULL), 0); + ExpectIntGT(ASN1_STRING_length(str), 0); ASN1_STRING_free(c); ASN1_STRING_free(str); ASN1_STRING_free(NULL); #ifndef NO_WOLFSSL_STUB - AssertNull(d2i_DISPLAYTEXT(NULL, NULL, 0)); + ExpectNull(d2i_DISPLAYTEXT(NULL, NULL, 0)); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -32391,49 +32699,51 @@ static int test_wolfSSL_ASN1_STRING(void) static int test_wolfSSL_ASN1_STRING_to_UTF8(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_ALL) && !defined(NO_ASN) && !defined(NO_RSA) - WOLFSSL_X509* x509; - WOLFSSL_X509_NAME* subject; - WOLFSSL_X509_NAME_ENTRY* e; - WOLFSSL_ASN1_STRING* a; - FILE* file; +#if defined(OPENSSL_ALL) && !defined(NO_ASN) && !defined(NO_RSA) && \ + !defined(NO_FILESYSTEM) + EXPECT_DECLS; + WOLFSSL_X509* x509 = NULL; + WOLFSSL_X509_NAME* subject = NULL; + WOLFSSL_X509_NAME_ENTRY* e = NULL; + WOLFSSL_ASN1_STRING* a = NULL; + FILE* file = XBADFILE; int idx = 0; char targetOutput[16] = "www.wolfssl.com"; - unsigned char* actual_output; + unsigned char* actual_output = NULL; int len = 0; - int result = 0; - AssertNotNull(file = fopen("./certs/server-cert.pem", "rb")); - AssertNotNull(x509 = wolfSSL_PEM_read_X509(file, NULL, NULL, NULL)); - fclose(file); + ExpectNotNull(file = fopen("./certs/server-cert.pem", "rb")); + ExpectNotNull(x509 = wolfSSL_PEM_read_X509(file, NULL, NULL, NULL)); + if (file != NULL) + fclose(file); /* wolfSSL_ASN1_STRING_to_UTF8(): NID_commonName */ - AssertNotNull(subject = wolfSSL_X509_get_subject_name(x509)); - AssertIntEQ((idx = wolfSSL_X509_NAME_get_index_by_NID(subject, + ExpectNotNull(subject = wolfSSL_X509_get_subject_name(x509)); + ExpectIntEQ((idx = wolfSSL_X509_NAME_get_index_by_NID(subject, NID_commonName, -1)), 5); - AssertNotNull(e = wolfSSL_X509_NAME_get_entry(subject, idx)); - AssertNotNull(a = wolfSSL_X509_NAME_ENTRY_get_data(e)); - AssertIntEQ((len = wolfSSL_ASN1_STRING_to_UTF8(&actual_output, a)), 15); - result = strncmp((const char*)actual_output, targetOutput, len); - AssertIntEQ(result, 0); + ExpectNotNull(e = wolfSSL_X509_NAME_get_entry(subject, idx)); + ExpectNotNull(a = wolfSSL_X509_NAME_ENTRY_get_data(e)); + ExpectIntEQ((len = wolfSSL_ASN1_STRING_to_UTF8(&actual_output, a)), 15); + ExpectIntEQ(strncmp((const char*)actual_output, targetOutput, len), 0); + a = NULL; /* wolfSSL_ASN1_STRING_to_UTF8(NULL, valid) */ - AssertIntEQ((len = wolfSSL_ASN1_STRING_to_UTF8(NULL, a)), -1); + ExpectIntEQ((len = wolfSSL_ASN1_STRING_to_UTF8(NULL, a)), -1); /* wolfSSL_ASN1_STRING_to_UTF8(valid, NULL) */ - AssertIntEQ((len = wolfSSL_ASN1_STRING_to_UTF8(&actual_output, NULL)), -1); + ExpectIntEQ((len = wolfSSL_ASN1_STRING_to_UTF8(&actual_output, NULL)), -1); /* wolfSSL_ASN1_STRING_to_UTF8(NULL, NULL) */ - AssertIntEQ((len = wolfSSL_ASN1_STRING_to_UTF8(NULL, NULL)), -1); + ExpectIntEQ((len = wolfSSL_ASN1_STRING_to_UTF8(NULL, NULL)), -1); wolfSSL_X509_free(x509); XFREE(actual_output, NULL, DYNAMIC_TYPE_TMP_BUFFER); - AssertNotNull(a = ASN1_STRING_new()); - AssertIntEQ(wolfSSL_ASN1_STRING_to_UTF8(&actual_output, a), -1); + ExpectNotNull(a = ASN1_STRING_new()); + ExpectIntEQ(wolfSSL_ASN1_STRING_to_UTF8(&actual_output, a), -1); ASN1_STRING_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -32442,28 +32752,30 @@ static int test_wolfSSL_i2s_ASN1_STRING(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) - WOLFSSL_ASN1_STRING* str; + EXPECT_DECLS; + WOLFSSL_ASN1_STRING* str = NULL; const char* data = "test_wolfSSL_i2s_ASN1_STRING"; - char* ret; + char* ret = NULL; - AssertNotNull(str = ASN1_STRING_new()); + ExpectNotNull(str = ASN1_STRING_new()); - AssertNull(wolfSSL_i2s_ASN1_STRING(NULL, NULL)); + ExpectNull(wolfSSL_i2s_ASN1_STRING(NULL, NULL)); /* No data. */ - AssertNull(wolfSSL_i2s_ASN1_STRING(NULL, str)); + ExpectNull(wolfSSL_i2s_ASN1_STRING(NULL, str)); - AssertIntEQ(ASN1_STRING_set(str, data, 0), 1); - AssertNotNull(ret = wolfSSL_i2s_ASN1_STRING(NULL, str)); + ExpectIntEQ(ASN1_STRING_set(str, data, 0), 1); + ExpectNotNull(ret = wolfSSL_i2s_ASN1_STRING(NULL, str)); XFREE(ret, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ret = NULL; - AssertIntEQ(ASN1_STRING_set(str, data, -1), 1); + ExpectIntEQ(ASN1_STRING_set(str, data, -1), 1); /* No type. */ - AssertNotNull(ret = wolfSSL_i2s_ASN1_STRING(NULL, str)); + ExpectNotNull(ret = wolfSSL_i2s_ASN1_STRING(NULL, str)); XFREE(ret, NULL, DYNAMIC_TYPE_TMP_BUFFER); ASN1_STRING_free(str); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -32474,8 +32786,9 @@ static int test_wolfSSL_ASN1_STRING_canon(void) #if defined(WOLFSSL_TEST_STATIC_BUILD) #if !defined(NO_CERTS) && (defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) - WOLFSSL_ASN1_STRING* orig; - WOLFSSL_ASN1_STRING* canon; + EXPECT_DECLS; + WOLFSSL_ASN1_STRING* orig = NULL; + WOLFSSL_ASN1_STRING* canon = NULL; const char* data = "test_wolfSSL_ASN1_STRING_canon"; const char* whitespaceOnly = "\t\r\n"; const char* modData = " \x01\f\t\x02\r\n\v\xff\nTt \n"; @@ -32483,45 +32796,48 @@ static int test_wolfSSL_ASN1_STRING_canon(void) const char longData[] = "This string must be longer than CTC_NAME_SIZE that is defined as 64."; - AssertNotNull(orig = ASN1_STRING_new()); - AssertNotNull(canon = ASN1_STRING_new()); + ExpectNotNull(orig = ASN1_STRING_new()); + ExpectNotNull(canon = ASN1_STRING_new()); /* Invalid parameter testing. */ - AssertIntEQ(wolfSSL_ASN1_STRING_canon(NULL, NULL), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_ASN1_STRING_canon(canon, NULL), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_ASN1_STRING_canon(NULL, orig), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_ASN1_STRING_canon(NULL, NULL), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_ASN1_STRING_canon(canon, NULL), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_ASN1_STRING_canon(NULL, orig), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); - AssertIntEQ(ASN1_STRING_cmp(orig, canon), 0); + ExpectIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); + ExpectIntEQ(ASN1_STRING_cmp(orig, canon), 0); - AssertIntEQ(ASN1_STRING_set(orig, longData, (int)XSTRLEN(data)), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); - AssertIntEQ(ASN1_STRING_cmp(orig, canon), 0); + ExpectIntEQ(ASN1_STRING_set(orig, longData, (int)XSTRLEN(data)), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); + ExpectIntEQ(ASN1_STRING_cmp(orig, canon), 0); - AssertIntEQ(ASN1_STRING_set(orig, data, (int)XSTRLEN(data)), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); - AssertIntEQ(ASN1_STRING_cmp(orig, canon), 0); + ExpectIntEQ(ASN1_STRING_set(orig, data, (int)XSTRLEN(data)), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); + ExpectIntEQ(ASN1_STRING_cmp(orig, canon), 0); ASN1_STRING_free(orig); + orig = NULL; - AssertNotNull(orig = ASN1_STRING_type_new(MBSTRING_UTF8)); - AssertIntEQ(ASN1_STRING_set(orig, modData, 15), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); - AssertIntEQ(ASN1_STRING_set(orig, canonData, 8), 1); - AssertIntEQ(ASN1_STRING_cmp(orig, canon), 0); + ExpectNotNull(orig = ASN1_STRING_type_new(MBSTRING_UTF8)); + ExpectIntEQ(ASN1_STRING_set(orig, modData, 15), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); + ExpectIntEQ(ASN1_STRING_set(orig, canonData, 8), 1); + ExpectIntEQ(ASN1_STRING_cmp(orig, canon), 0); ASN1_STRING_free(orig); + orig = NULL; - AssertNotNull(orig = ASN1_STRING_type_new(V_ASN1_PRINTABLESTRING)); - AssertIntEQ(ASN1_STRING_set(orig, whitespaceOnly, 3), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); + ExpectNotNull(orig = ASN1_STRING_type_new(V_ASN1_PRINTABLESTRING)); + ExpectIntEQ(ASN1_STRING_set(orig, whitespaceOnly, 3), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_canon(canon, orig), 1); ASN1_STRING_free(orig); - AssertNotNull(orig = ASN1_STRING_type_new(MBSTRING_UTF8)); - AssertIntEQ(ASN1_STRING_cmp(orig, canon), 0); + orig = NULL; + ExpectNotNull(orig = ASN1_STRING_type_new(MBSTRING_UTF8)); + ExpectIntEQ(ASN1_STRING_cmp(orig, canon), 0); ASN1_STRING_free(orig); ASN1_STRING_free(canon); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif #endif return res; @@ -32532,6 +32848,7 @@ static int test_wolfSSL_ASN1_STRING_print(void) int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_ASN) && !defined(NO_CERTS) && \ !defined(NO_BIO) + EXPECT_DECLS; ASN1_STRING* asnStr = NULL; const char HELLO_DATA[]= \ {'H','e','l','l','o',' ','w','o','l','f','S','S','L','!'}; @@ -32540,9 +32857,9 @@ static int test_wolfSSL_ASN1_STRING_print(void) unsigned char unprintableData[MAX_UNPRINTABLE_CHAR + sizeof(HELLO_DATA)]; unsigned char expected[sizeof(unprintableData)+1]; unsigned char rbuf[MAX_BUF]; - - BIO *bio; - int p_len, i; + BIO *bio = NULL; + int p_len; + int i; /* setup */ @@ -32564,37 +32881,38 @@ static int test_wolfSSL_ASN1_STRING_print(void) expected[sizeof(expected)-1] = '\0'; XMEMSET(rbuf, 0, MAX_BUF); - bio = BIO_new(BIO_s_mem()); - BIO_set_write_buf_size(bio, MAX_BUF); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(BIO_set_write_buf_size(bio, MAX_BUF), 0); - asnStr = ASN1_STRING_type_new(V_ASN1_OCTET_STRING); - ASN1_STRING_set(asnStr,(const void*)unprintableData, - (int)sizeof(unprintableData)); + ExpectNotNull(asnStr = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); + ExpectIntEQ(ASN1_STRING_set(asnStr,(const void*)unprintableData, + (int)sizeof(unprintableData)), 1); /* test */ - AssertIntEQ(wolfSSL_ASN1_STRING_print(NULL, NULL), 0); - AssertIntEQ(wolfSSL_ASN1_STRING_print(bio, NULL), 0); - AssertIntEQ(wolfSSL_ASN1_STRING_print(NULL, asnStr), 0); - AssertIntEQ(p_len = wolfSSL_ASN1_STRING_print(bio, asnStr), 46); - BIO_read(bio, (void*)rbuf, 46); + ExpectIntEQ(wolfSSL_ASN1_STRING_print(NULL, NULL), 0); + ExpectIntEQ(wolfSSL_ASN1_STRING_print(bio, NULL), 0); + ExpectIntEQ(wolfSSL_ASN1_STRING_print(NULL, asnStr), 0); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print(bio, asnStr), 46); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 46), 46); - AssertStrEQ((char*)rbuf, (const char*)expected); + ExpectStrEQ((char*)rbuf, (const char*)expected); BIO_free(bio); + bio = NULL; - AssertNotNull(bio = BIO_new(wolfSSL_BIO_s_fixed_mem())); - AssertIntEQ(BIO_set_write_buf_size(bio, 1), 1); + ExpectNotNull(bio = BIO_new(wolfSSL_BIO_s_fixed_mem())); + ExpectIntEQ(BIO_set_write_buf_size(bio, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(bio, rbuf, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print(bio, asnStr), 0); - AssertIntEQ(BIO_set_write_buf_size(bio, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print(bio, asnStr), 0); - AssertIntEQ(BIO_set_write_buf_size(bio, 45), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print(bio, asnStr), 0); + ExpectIntEQ(BIO_write(bio, rbuf, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print(bio, asnStr), 0); + ExpectIntEQ(BIO_set_write_buf_size(bio, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print(bio, asnStr), 0); + ExpectIntEQ(BIO_set_write_buf_size(bio, 45), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print(bio, asnStr), 0); BIO_free(bio); ASN1_STRING_free(asnStr); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && !NO_ASN && !NO_CERTS && !NO_BIO */ return res; } @@ -32603,149 +32921,143 @@ static int test_wolfSSL_ASN1_STRING_print_ex(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && !defined(NO_BIO) - ASN1_STRING* asn_str; + EXPECT_DECLS; + ASN1_STRING* asn_str = NULL; const char data[] = "Hello wolfSSL!"; - ASN1_STRING* esc_str; + ASN1_STRING* esc_str = NULL; const char esc_data[] = "a+;<>"; - ASN1_STRING* neg_int; + ASN1_STRING* neg_int = NULL; const char neg_int_data[] = "\xff"; - ASN1_STRING* neg_enum; + ASN1_STRING* neg_enum = NULL; const char neg_enum_data[] = "\xff"; - BIO *bio; - BIO *fixed; + BIO *bio = NULL; + BIO *fixed = NULL; unsigned long flags; int p_len; unsigned char rbuf[255]; /* setup */ XMEMSET(rbuf, 0, 255); - AssertNotNull(bio = BIO_new(BIO_s_mem())); - BIO_set_write_buf_size(bio, 255); - AssertNotNull(fixed = BIO_new(wolfSSL_BIO_s_fixed_mem())); - - asn_str = ASN1_STRING_type_new(V_ASN1_OCTET_STRING); - ASN1_STRING_set(asn_str, (const void*)data, sizeof(data)); - esc_str = ASN1_STRING_type_new(V_ASN1_OCTET_STRING); - ASN1_STRING_set(esc_str, (const void*)esc_data, sizeof(esc_data)); - neg_int = ASN1_STRING_type_new(V_ASN1_NEG_INTEGER); - ASN1_STRING_set(neg_int, (const void*)neg_int_data, - sizeof(neg_int_data) - 1); - neg_enum = ASN1_STRING_type_new(V_ASN1_NEG_ENUMERATED); - ASN1_STRING_set(neg_enum, (const void*)neg_enum_data, - sizeof(neg_enum_data) - 1); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(BIO_set_write_buf_size(bio, 255), 0); + ExpectNotNull(fixed = BIO_new(wolfSSL_BIO_s_fixed_mem())); + + ExpectNotNull(asn_str = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); + ExpectIntEQ(ASN1_STRING_set(asn_str, (const void*)data, sizeof(data)), 1); + ExpectNotNull(esc_str = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); + ExpectIntEQ(ASN1_STRING_set(esc_str, (const void*)esc_data, + sizeof(esc_data)), 1); + ExpectNotNull(neg_int = ASN1_STRING_type_new(V_ASN1_NEG_INTEGER)); + ExpectIntEQ(ASN1_STRING_set(neg_int, (const void*)neg_int_data, + sizeof(neg_int_data) - 1), 1); + ExpectNotNull(neg_enum = ASN1_STRING_type_new(V_ASN1_NEG_ENUMERATED)); + ExpectIntEQ(ASN1_STRING_set(neg_enum, (const void*)neg_enum_data, + sizeof(neg_enum_data) - 1), 1); /* Invalid parameter testing. */ - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(NULL, NULL, 0), 0); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(bio, NULL, 0), 0); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(NULL, asn_str, 0), 0); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(NULL, NULL, 0), 0); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(bio, NULL, 0), 0); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(NULL, asn_str, 0), 0); /* no flags */ XMEMSET(rbuf, 0, 255); flags = 0; - p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags); - AssertIntEQ(p_len, 15); - BIO_read(bio, (void*)rbuf, 15); - AssertStrEQ((char*)rbuf, "Hello wolfSSL!"); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags), 15); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 15), 15); + ExpectStrEQ((char*)rbuf, "Hello wolfSSL!"); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 14), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_write(fixed, rbuf, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 14), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); /* RFC2253 Escape */ XMEMSET(rbuf, 0, 255); flags = ASN1_STRFLGS_ESC_2253; - p_len = wolfSSL_ASN1_STRING_print_ex(bio, esc_str, flags); - AssertIntEQ(p_len, 9); - BIO_read(bio, (void*)rbuf, 9); - AssertStrEQ((char*)rbuf, "a\\+\\;\\<\\>"); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print_ex(bio, esc_str, flags), 9); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 9), 9); + ExpectStrEQ((char*)rbuf, "a\\+\\;\\<\\>"); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 8), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); + ExpectIntEQ(BIO_write(fixed, rbuf, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 8), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, esc_str, flags), 0); /* Show type */ XMEMSET(rbuf, 0, 255); flags = ASN1_STRFLGS_SHOW_TYPE; - p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags); - AssertIntEQ(p_len, 28); - BIO_read(bio, (void*)rbuf, 28); - AssertStrEQ((char*)rbuf, "OCTET STRING:Hello wolfSSL!"); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags), 28); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 28), 28); + ExpectStrEQ((char*)rbuf, "OCTET STRING:Hello wolfSSL!"); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 12), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 27), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_write(fixed, rbuf, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 12), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 27), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); /* Dump All */ XMEMSET(rbuf, 0, 255); flags = ASN1_STRFLGS_DUMP_ALL; - p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags); - AssertIntEQ(p_len, 31); - BIO_read(bio, (void*)rbuf, 31); - AssertStrEQ((char*)rbuf, "#48656C6C6F20776F6C6653534C2100"); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags), 31); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 31), 31); + ExpectStrEQ((char*)rbuf, "#48656C6C6F20776F6C6653534C2100"); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 30), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_write(fixed, rbuf, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 30), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); /* Dump Der */ XMEMSET(rbuf, 0, 255); flags = ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER; - p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags); - AssertIntEQ(p_len, 35); - BIO_read(bio, (void*)rbuf, 35); - AssertStrEQ((char*)rbuf, "#040F48656C6C6F20776F6C6653534C2100"); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags), 35); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 35), 35); + ExpectStrEQ((char*)rbuf, "#040F48656C6C6F20776F6C6653534C2100"); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(fixed, rbuf, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 2), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 30), 1); - AssertIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_write(fixed, rbuf, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 2), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 30), 1); + ExpectIntEQ(wolfSSL_ASN1_STRING_print_ex(fixed, asn_str, flags), 0); /* Dump All + Show type */ XMEMSET(rbuf, 0, 255); flags = ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_SHOW_TYPE; - p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags); - AssertIntEQ(p_len, 44); - BIO_read(bio, (void*)rbuf, 44); - AssertStrEQ((char*)rbuf, "OCTET STRING:#48656C6C6F20776F6C6653534C2100"); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print_ex(bio, asn_str, flags), 44); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 44), 44); + ExpectStrEQ((char*)rbuf, "OCTET STRING:#48656C6C6F20776F6C6653534C2100"); /* Dump All + Show type - Negative Integer. */ XMEMSET(rbuf, 0, 255); flags = ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_SHOW_TYPE; - p_len = wolfSSL_ASN1_STRING_print_ex(bio, neg_int, flags); - AssertIntEQ(p_len, 11); - BIO_read(bio, (void*)rbuf, 11); - AssertStrEQ((char*)rbuf, "INTEGER:#FF"); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print_ex(bio, neg_int, flags), 11); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 11), 11); + ExpectStrEQ((char*)rbuf, "INTEGER:#FF"); /* Dump All + Show type - Negative Enumerated. */ XMEMSET(rbuf, 0, 255); flags = ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_SHOW_TYPE; - p_len = wolfSSL_ASN1_STRING_print_ex(bio, neg_enum, flags); - AssertIntEQ(p_len, 14); - BIO_read(bio, (void*)rbuf, 14); - AssertStrEQ((char*)rbuf, "ENUMERATED:#FF"); + ExpectIntEQ(p_len = wolfSSL_ASN1_STRING_print_ex(bio, neg_enum, flags), 14); + ExpectIntEQ(BIO_read(bio, (void*)rbuf, 14), 14); + ExpectStrEQ((char*)rbuf, "ENUMERATED:#FF"); BIO_free(fixed); BIO_free(bio); @@ -32754,10 +33066,10 @@ static int test_wolfSSL_ASN1_STRING_print_ex(void) ASN1_STRING_free(neg_int); ASN1_STRING_free(neg_enum); - AssertStrEQ(wolfSSL_ASN1_tag2str(-1), "(unknown)"); - AssertStrEQ(wolfSSL_ASN1_tag2str(31), "(unknown)"); + ExpectStrEQ(wolfSSL_ASN1_tag2str(-1), "(unknown)"); + ExpectStrEQ(wolfSSL_ASN1_tag2str(31), "(unknown)"); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -32766,8 +33078,9 @@ static int test_wolfSSL_ASN1_UNIVERSALSTRING_to_string(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_ASN) - ASN1_STRING* asn1str_test; - ASN1_STRING* asn1str_answer; + EXPECT_DECLS; + ASN1_STRING* asn1str_test = NULL; + ASN1_STRING* asn1str_answer = NULL; /* Each character is encoded using 4 bytes */ char input[] = { 0, 0, 0, 'T', @@ -32782,38 +33095,39 @@ static int test_wolfSSL_ASN1_UNIVERSALSTRING_to_string(void) 0, 0, 1, 's', }; - AssertIntEQ(ASN1_UNIVERSALSTRING_to_string(NULL), 0); + ExpectIntEQ(ASN1_UNIVERSALSTRING_to_string(NULL), 0); /* Test wrong type. */ - AssertNotNull(asn1str_test = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); - AssertIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); + ExpectNotNull(asn1str_test = ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); + ExpectIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); ASN1_STRING_free(asn1str_test); + asn1str_test = NULL; - AssertNotNull(asn1str_test = ASN1_STRING_type_new(V_ASN1_UNIVERSALSTRING)); + ExpectNotNull(asn1str_test = ASN1_STRING_type_new(V_ASN1_UNIVERSALSTRING)); /* Test bad length. */ - AssertIntEQ(ASN1_STRING_set(asn1str_test, input, sizeof(input) - 1), 1); - AssertIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); + ExpectIntEQ(ASN1_STRING_set(asn1str_test, input, sizeof(input) - 1), 1); + ExpectIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); /* Test bad input. */ - AssertIntEQ(ASN1_STRING_set(asn1str_test, badInput + 0, 4), 1); - AssertIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); - AssertIntEQ(ASN1_STRING_set(asn1str_test, badInput + 4, 4), 1); - AssertIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); - AssertIntEQ(ASN1_STRING_set(asn1str_test, badInput + 8, 4), 1); - AssertIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); + ExpectIntEQ(ASN1_STRING_set(asn1str_test, badInput + 0, 4), 1); + ExpectIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); + ExpectIntEQ(ASN1_STRING_set(asn1str_test, badInput + 4, 4), 1); + ExpectIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); + ExpectIntEQ(ASN1_STRING_set(asn1str_test, badInput + 8, 4), 1); + ExpectIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 0); - AssertIntEQ(ASN1_STRING_set(asn1str_test, input, sizeof(input)), 1); - AssertIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 1); + ExpectIntEQ(ASN1_STRING_set(asn1str_test, input, sizeof(input)), 1); + ExpectIntEQ(ASN1_UNIVERSALSTRING_to_string(asn1str_test), 1); - AssertNotNull( + ExpectNotNull( asn1str_answer = ASN1_STRING_type_new(V_ASN1_PRINTABLESTRING)); - AssertIntEQ(ASN1_STRING_set(asn1str_answer, output, sizeof(output)-1), 1); + ExpectIntEQ(ASN1_STRING_set(asn1str_answer, output, sizeof(output)-1), 1); - AssertIntEQ(ASN1_STRING_cmp(asn1str_test, asn1str_answer), 0); + ExpectIntEQ(ASN1_STRING_cmp(asn1str_test, asn1str_answer), 0); ASN1_STRING_free(asn1str_test); ASN1_STRING_free(asn1str_answer); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_ALL && !NO_ASN */ return res; } @@ -32822,24 +33136,24 @@ static int test_wolfSSL_ASN1_GENERALIZEDTIME_free(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) - WOLFSSL_ASN1_GENERALIZEDTIME* asn1_gtime; + EXPECT_DECLS; + WOLFSSL_ASN1_GENERALIZEDTIME* asn1_gtime = NULL; unsigned char nullstr[32]; XMEMSET(nullstr, 0, 32); - asn1_gtime = (WOLFSSL_ASN1_GENERALIZEDTIME*)XMALLOC( - sizeof(WOLFSSL_ASN1_GENERALIZEDTIME), NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (asn1_gtime) { + ExpectNotNull(asn1_gtime = (WOLFSSL_ASN1_GENERALIZEDTIME*)XMALLOC( + sizeof(WOLFSSL_ASN1_GENERALIZEDTIME), NULL, DYNAMIC_TYPE_TMP_BUFFER)); + if (asn1_gtime != NULL) { XMEMCPY(asn1_gtime->data,"20180504123500Z",ASN_GENERALIZED_TIME_SIZE); wolfSSL_ASN1_GENERALIZEDTIME_free(asn1_gtime); - AssertIntEQ(0, XMEMCMP(asn1_gtime->data, nullstr, 32)); + ExpectIntEQ(0, XMEMCMP(asn1_gtime->data, nullstr, 32)); XFREE(asn1_gtime, NULL, DYNAMIC_TYPE_TMP_BUFFER); } wolfSSL_ASN1_GENERALIZEDTIME_free(NULL); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -32848,46 +33162,48 @@ static int test_wolfSSL_ASN1_GENERALIZEDTIME_print(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_BIO) + EXPECT_DECLS; WOLFSSL_ASN1_GENERALIZEDTIME gtime; - BIO* bio; + BIO* bio = NULL; unsigned char buf[24]; int i; - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); BIO_set_write_buf_size(bio, 24); XMEMSET(>ime, 0, sizeof(WOLFSSL_ASN1_GENERALIZEDTIME)); XMEMCPY(gtime.data, "20180504123500Z", ASN_GENERALIZED_TIME_SIZE); gtime.length = ASN_GENERALIZED_TIME_SIZE; /* Type not set. */ - AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 0); + ExpectIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 0); gtime.type = V_ASN1_GENERALIZEDTIME; /* Invalid parameters testing. */ - AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(NULL, NULL), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, NULL), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(NULL, >ime), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(NULL, NULL), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, NULL), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(NULL, >ime), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 1); - AssertIntEQ(BIO_read(bio, buf, sizeof(buf)), 20); - AssertIntEQ(XMEMCMP(buf, "May 04 12:35:00 2018", 20), 0); + ExpectIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 1); + ExpectIntEQ(BIO_read(bio, buf, sizeof(buf)), 20); + ExpectIntEQ(XMEMCMP(buf, "May 04 12:35:00 2018", 20), 0); BIO_free(bio); + bio = NULL; - AssertNotNull(bio = BIO_new(wolfSSL_BIO_s_fixed_mem())); - AssertIntEQ(BIO_set_write_buf_size(bio, 1), 1); + ExpectNotNull(bio = BIO_new(wolfSSL_BIO_s_fixed_mem())); + ExpectIntEQ(BIO_set_write_buf_size(bio, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(bio, buf, 1), 1); - AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 0); + ExpectIntEQ(BIO_write(bio, buf, 1), 1); + ExpectIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 0); for (i = 1; i < 20; i++) { - AssertIntEQ(BIO_set_write_buf_size(bio, i), 1); - AssertIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 0); + ExpectIntEQ(BIO_set_write_buf_size(bio, i), 1); + ExpectIntEQ(wolfSSL_ASN1_GENERALIZEDTIME_print(bio, >ime), 0); } BIO_free(bio); wolfSSL_ASN1_GENERALIZEDTIME_free(>ime); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -32896,34 +33212,35 @@ static int test_wolfSSL_ASN1_TIME(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) - WOLFSSL_ASN1_TIME* asn_time; + EXPECT_DECLS; + WOLFSSL_ASN1_TIME* asn_time = NULL; unsigned char *data; - AssertNotNull(asn_time = ASN1_TIME_new()); + ExpectNotNull(asn_time = ASN1_TIME_new()); #ifndef NO_WOLFSSL_STUB - AssertNotNull(ASN1_TIME_set(asn_time, 1)); + ExpectNotNull(ASN1_TIME_set(asn_time, 1)); #endif - AssertIntEQ(ASN1_TIME_set_string(NULL, NULL), 0); - AssertIntEQ(ASN1_TIME_set_string(asn_time, NULL), 0); - AssertIntEQ(ASN1_TIME_set_string(NULL, + ExpectIntEQ(ASN1_TIME_set_string(NULL, NULL), 0); + ExpectIntEQ(ASN1_TIME_set_string(asn_time, NULL), 0); + ExpectIntEQ(ASN1_TIME_set_string(NULL, "String longer than CTC_DATA_SIZE that is 32 bytes"), 0); - AssertIntEQ(ASN1_TIME_set_string(NULL, "101219181011Z"), 1); - AssertIntEQ(ASN1_TIME_set_string(asn_time, "101219181011Z"), 1); + ExpectIntEQ(ASN1_TIME_set_string(NULL, "101219181011Z"), 1); + ExpectIntEQ(ASN1_TIME_set_string(asn_time, "101219181011Z"), 1); - AssertIntEQ(wolfSSL_ASN1_TIME_get_length(NULL), 0); - AssertIntEQ(wolfSSL_ASN1_TIME_get_length(asn_time), ASN_UTC_TIME_SIZE - 1); - AssertNull(wolfSSL_ASN1_TIME_get_data(NULL)); - AssertNotNull(data = wolfSSL_ASN1_TIME_get_data(asn_time)); - AssertIntEQ(XMEMCMP(data, "101219181011Z", 14), 0); + ExpectIntEQ(wolfSSL_ASN1_TIME_get_length(NULL), 0); + ExpectIntEQ(wolfSSL_ASN1_TIME_get_length(asn_time), ASN_UTC_TIME_SIZE - 1); + ExpectNull(wolfSSL_ASN1_TIME_get_data(NULL)); + ExpectNotNull(data = wolfSSL_ASN1_TIME_get_data(asn_time)); + ExpectIntEQ(XMEMCMP(data, "101219181011Z", 14), 0); - AssertIntEQ(ASN1_TIME_check(NULL), 0); - AssertIntEQ(ASN1_TIME_check(asn_time), 1); + ExpectIntEQ(ASN1_TIME_check(NULL), 0); + ExpectIntEQ(ASN1_TIME_check(asn_time), 1); ASN1_TIME_free(asn_time); ASN1_TIME_free(NULL); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -32934,26 +33251,27 @@ static int test_wolfSSL_ASN1_TIME_to_string(void) #ifndef NO_ASN_TIME #if defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) || \ defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) - WOLFSSL_ASN1_TIME* t; + EXPECT_DECLS; + WOLFSSL_ASN1_TIME* t = NULL; char buf[ASN_GENERALIZED_TIME_SIZE]; - AssertNotNull((t = ASN1_TIME_new())); - AssertIntEQ(ASN1_TIME_set_string(t, "030222211515Z"), 1); + ExpectNotNull((t = ASN1_TIME_new())); + ExpectIntEQ(ASN1_TIME_set_string(t, "030222211515Z"), 1); /* Invalid parameter testing. */ - AssertNull(ASN1_TIME_to_string(NULL, NULL, 4)); - AssertNull(ASN1_TIME_to_string(t, NULL, 4)); - AssertNull(ASN1_TIME_to_string(NULL, buf, 4)); - AssertNull(ASN1_TIME_to_string(NULL, NULL, 5)); - AssertNull(ASN1_TIME_to_string(NULL, buf, 5)); - AssertNull(ASN1_TIME_to_string(t, NULL, 5)); - AssertNull(ASN1_TIME_to_string(t, buf, 4)); + ExpectNull(ASN1_TIME_to_string(NULL, NULL, 4)); + ExpectNull(ASN1_TIME_to_string(t, NULL, 4)); + ExpectNull(ASN1_TIME_to_string(NULL, buf, 4)); + ExpectNull(ASN1_TIME_to_string(NULL, NULL, 5)); + ExpectNull(ASN1_TIME_to_string(NULL, buf, 5)); + ExpectNull(ASN1_TIME_to_string(t, NULL, 5)); + ExpectNull(ASN1_TIME_to_string(t, buf, 4)); /* Buffer needs to be longer than minimum of 5 characters. */ - AssertNull(ASN1_TIME_to_string(t, buf, 5)); + ExpectNull(ASN1_TIME_to_string(t, buf, 5)); ASN1_TIME_free(t); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif #endif /* NO_ASN_TIME */ return res; @@ -32963,92 +33281,93 @@ static int test_wolfSSL_ASN1_TIME_diff_compare(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) - ASN1_TIME* fromTime; - ASN1_TIME* closeToTime; - ASN1_TIME* toTime; - ASN1_TIME* invalidTime; + EXPECT_DECLS; + ASN1_TIME* fromTime = NULL; + ASN1_TIME* closeToTime = NULL; + ASN1_TIME* toTime = NULL; + ASN1_TIME* invalidTime = NULL; int daysDiff; int secsDiff; - AssertNotNull((fromTime = ASN1_TIME_new())); + ExpectNotNull((fromTime = ASN1_TIME_new())); /* Feb 22, 2003, 21:15:15 */ - AssertIntEQ(ASN1_TIME_set_string(fromTime, "030222211515Z"), 1); - AssertNotNull((closeToTime = ASN1_TIME_new())); + ExpectIntEQ(ASN1_TIME_set_string(fromTime, "030222211515Z"), 1); + ExpectNotNull((closeToTime = ASN1_TIME_new())); /* Feb 22, 2003, 21:16:15 */ - AssertIntEQ(ASN1_TIME_set_string(closeToTime, "030222211615Z"), 1); - AssertNotNull((toTime = ASN1_TIME_new())); + ExpectIntEQ(ASN1_TIME_set_string(closeToTime, "030222211615Z"), 1); + ExpectNotNull((toTime = ASN1_TIME_new())); /* Dec 19, 2010, 18:10:11 */ - AssertIntEQ(ASN1_TIME_set_string(toTime, "101219181011Z"), 1); - AssertNotNull((invalidTime = ASN1_TIME_new())); + ExpectIntEQ(ASN1_TIME_set_string(toTime, "101219181011Z"), 1); + ExpectNotNull((invalidTime = ASN1_TIME_new())); /* Dec 19, 2010, 18:10:11 but 'U' instead of 'Z' which is invalid. */ - AssertIntEQ(ASN1_TIME_set_string(invalidTime, "102519181011U"), 1); + ExpectIntEQ(ASN1_TIME_set_string(invalidTime, "102519181011U"), 1); - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, invalidTime), 0); - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, invalidTime, toTime), 0); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, invalidTime), 0); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, invalidTime, toTime), 0); - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, toTime), 1); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, toTime), 1); /* Error conditions. */ - AssertIntEQ(ASN1_TIME_diff(NULL, &secsDiff, fromTime, toTime), 0); - AssertIntEQ(ASN1_TIME_diff(&daysDiff, NULL, fromTime, toTime), 0); + ExpectIntEQ(ASN1_TIME_diff(NULL, &secsDiff, fromTime, toTime), 0); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, NULL, fromTime, toTime), 0); /* If both times are NULL, difference is 0. */ - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, NULL, NULL), 1); - AssertIntEQ(daysDiff, 0); - AssertIntEQ(secsDiff, 0); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, NULL, NULL), 1); + ExpectIntEQ(daysDiff, 0); + ExpectIntEQ(secsDiff, 0); /* If one time is NULL, it defaults to the current time. */ - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, NULL, toTime), 1); - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, NULL), 1); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, NULL, toTime), 1); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, NULL), 1); /* Normal operation. Both times non-NULL. */ - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, toTime), 1); - AssertIntEQ(daysDiff, 2856); - AssertIntEQ(secsDiff, 75296); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, toTime), 1); + ExpectIntEQ(daysDiff, 2856); + ExpectIntEQ(secsDiff, 75296); /* Swapping the times should return negative values. */ - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, toTime, fromTime), 1); - AssertIntEQ(daysDiff, -2856); - AssertIntEQ(secsDiff, -75296); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, toTime, fromTime), 1); + ExpectIntEQ(daysDiff, -2856); + ExpectIntEQ(secsDiff, -75296); /* Compare with invalid time string. */ - AssertIntEQ(ASN1_TIME_compare(fromTime, invalidTime), -2); - AssertIntEQ(ASN1_TIME_compare(invalidTime, toTime), -2); + ExpectIntEQ(ASN1_TIME_compare(fromTime, invalidTime), -2); + ExpectIntEQ(ASN1_TIME_compare(invalidTime, toTime), -2); /* Compare with days difference of 0. */ - AssertIntEQ(ASN1_TIME_compare(fromTime, closeToTime), -1); - AssertIntEQ(ASN1_TIME_compare(closeToTime, fromTime), 1); + ExpectIntEQ(ASN1_TIME_compare(fromTime, closeToTime), -1); + ExpectIntEQ(ASN1_TIME_compare(closeToTime, fromTime), 1); /* Days and seconds differences not 0. */ - AssertIntEQ(ASN1_TIME_compare(fromTime, toTime), -1); - AssertIntEQ(ASN1_TIME_compare(toTime, fromTime), 1); + ExpectIntEQ(ASN1_TIME_compare(fromTime, toTime), -1); + ExpectIntEQ(ASN1_TIME_compare(toTime, fromTime), 1); /* Same time. */ - AssertIntEQ(ASN1_TIME_compare(fromTime, fromTime), 0); + ExpectIntEQ(ASN1_TIME_compare(fromTime, fromTime), 0); /* Compare regression test: No seconds difference, just difference in days. */ ASN1_TIME_set_string(fromTime, "19700101000000Z"); ASN1_TIME_set_string(toTime, "19800101000000Z"); - AssertIntEQ(ASN1_TIME_compare(fromTime, toTime), -1); - AssertIntEQ(ASN1_TIME_compare(toTime, fromTime), 1); - AssertIntEQ(ASN1_TIME_compare(fromTime, fromTime), 0); + ExpectIntEQ(ASN1_TIME_compare(fromTime, toTime), -1); + ExpectIntEQ(ASN1_TIME_compare(toTime, fromTime), 1); + ExpectIntEQ(ASN1_TIME_compare(fromTime, fromTime), 0); /* Edge case with Unix epoch. */ - AssertNotNull(ASN1_TIME_set_string(fromTime, "19700101000000Z")); - AssertNotNull(ASN1_TIME_set_string(toTime, "19800101000000Z")); - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, toTime), 1); - AssertIntEQ(daysDiff, 3652); - AssertIntEQ(secsDiff, 0); + ExpectNotNull(ASN1_TIME_set_string(fromTime, "19700101000000Z")); + ExpectNotNull(ASN1_TIME_set_string(toTime, "19800101000000Z")); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, toTime), 1); + ExpectIntEQ(daysDiff, 3652); + ExpectIntEQ(secsDiff, 0); /* Edge case with year > 2038 (year 2038 problem). */ - AssertNotNull(ASN1_TIME_set_string(toTime, "99991231235959Z")); - AssertIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, toTime), 1); - AssertIntEQ(daysDiff, 2932896); - AssertIntEQ(secsDiff, 86399); + ExpectNotNull(ASN1_TIME_set_string(toTime, "99991231235959Z")); + ExpectIntEQ(ASN1_TIME_diff(&daysDiff, &secsDiff, fromTime, toTime), 1); + ExpectIntEQ(daysDiff, 2932896); + ExpectIntEQ(secsDiff, 86399); ASN1_TIME_free(fromTime); ASN1_TIME_free(closeToTime); ASN1_TIME_free(toTime); ASN1_TIME_free(invalidTime); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -33058,6 +33377,7 @@ static int test_wolfSSL_ASN1_TIME_adj(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) \ && !defined(USER_TIME) && !defined(TIME_OVERRIDES) + EXPECT_DECLS; const int year = 365*24*60*60; const int day = 24*60*60; const int hour = 60*60; @@ -33066,37 +33386,40 @@ static int test_wolfSSL_ASN1_TIME_adj(void) #if !defined(TIME_T_NOT_64BIT) && !defined(NO_64BIT) const byte asn_gen_time = ASN_GENERALIZED_TIME; #endif - WOLFSSL_ASN1_TIME* asn_time; - WOLFSSL_ASN1_TIME* s; + WOLFSSL_ASN1_TIME* asn_time = NULL; + WOLFSSL_ASN1_TIME* s = NULL; int offset_day; long offset_sec; char date_str[CTC_DATE_SIZE + 1]; time_t t; - AssertNotNull(s = wolfSSL_ASN1_TIME_new()); + ExpectNotNull(s = wolfSSL_ASN1_TIME_new()); /* UTC notation test */ /* 2000/2/15 20:30:00 */ t = (time_t)30 * year + 45 * day + 20 * hour + 30 * mini + 7 * day; offset_day = 7; offset_sec = 45 * mini; /* offset_sec = -45 * min;*/ - AssertNotNull(asn_time = + ExpectNotNull(asn_time = wolfSSL_ASN1_TIME_adj(s, t, offset_day, offset_sec)); - AssertTrue(asn_time->type == asn_utc_time); - XSTRNCPY(date_str, (const char*)&asn_time->data, CTC_DATE_SIZE); + ExpectTrue(asn_time->type == asn_utc_time); + ExpectNotNull(XSTRNCPY(date_str, (const char*)&asn_time->data, + CTC_DATE_SIZE)); date_str[CTC_DATE_SIZE] = '\0'; - AssertIntEQ(0, XMEMCMP(date_str, "000222211500Z", 13)); + ExpectIntEQ(0, XMEMCMP(date_str, "000222211500Z", 13)); /* negative offset */ offset_sec = -45 * mini; asn_time = wolfSSL_ASN1_TIME_adj(s, t, offset_day, offset_sec); - AssertNotNull(asn_time); - AssertTrue(asn_time->type == asn_utc_time); - XSTRNCPY(date_str, (const char*)&asn_time->data, CTC_DATE_SIZE); + ExpectNotNull(asn_time); + ExpectTrue(asn_time->type == asn_utc_time); + ExpectNotNull(XSTRNCPY(date_str, (const char*)&asn_time->data, + CTC_DATE_SIZE)); date_str[CTC_DATE_SIZE] = '\0'; - AssertIntEQ(0, XMEMCMP(date_str, "000222194500Z", 13)); + ExpectIntEQ(0, XMEMCMP(date_str, "000222194500Z", 13)); XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL); + s = NULL; XMEMSET(date_str, 0, sizeof(date_str)); /* Generalized time will overflow time_t if not long */ @@ -33108,13 +33431,16 @@ static int test_wolfSSL_ASN1_TIME_adj(void) t = (time_t)85 * year + 59 * day + 9 * hour + 21 * day; offset_day = 12; offset_sec = 10 * mini; - asn_time = wolfSSL_ASN1_TIME_adj(s, t, offset_day, offset_sec); - AssertTrue(asn_time->type == asn_gen_time); - XSTRNCPY(date_str, (const char*)&asn_time->data, CTC_DATE_SIZE); + ExpectNotNull(asn_time = wolfSSL_ASN1_TIME_adj(s, t, offset_day, + offset_sec)); + ExpectTrue(asn_time->type == asn_gen_time); + ExpectNotNull(XSTRNCPY(date_str, (const char*)&asn_time->data, + CTC_DATE_SIZE)); date_str[CTC_DATE_SIZE] = '\0'; - AssertIntEQ(0, XMEMCMP(date_str, "20550313091000Z", 15)); + ExpectIntEQ(0, XMEMCMP(date_str, "20550313091000Z", 15)); XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL); + s = NULL; XMEMSET(date_str, 0, sizeof(date_str)); #endif /* !TIME_T_NOT_64BIT && !NO_64BIT */ @@ -33124,21 +33450,25 @@ static int test_wolfSSL_ASN1_TIME_adj(void) t = (time_t)30 * year + 45 * day + 20 * hour + 30 * mini + 15 + 7 * day; offset_day = 7; offset_sec = 45 * mini; - asn_time = wolfSSL_ASN1_TIME_adj(s, t, offset_day, offset_sec); - AssertTrue(asn_time->type == asn_utc_time); - XSTRNCPY(date_str, (const char*)&asn_time->data, CTC_DATE_SIZE); + ExpectNotNull(asn_time = wolfSSL_ASN1_TIME_adj(s, t, offset_day, + offset_sec)); + ExpectTrue(asn_time->type == asn_utc_time); + ExpectNotNull(XSTRNCPY(date_str, (const char*)&asn_time->data, + CTC_DATE_SIZE)); date_str[CTC_DATE_SIZE] = '\0'; - AssertIntEQ(0, XMEMCMP(date_str, "000222211515Z", 13)); + ExpectIntEQ(0, XMEMCMP(date_str, "000222211515Z", 13)); XFREE(asn_time, NULL, DYNAMIC_TYPE_OPENSSL); - asn_time = wolfSSL_ASN1_TIME_adj(NULL, t, offset_day, offset_sec); - AssertTrue(asn_time->type == asn_utc_time); - XSTRNCPY(date_str, (const char*)&asn_time->data, CTC_DATE_SIZE); + ExpectNotNull(asn_time = wolfSSL_ASN1_TIME_adj(NULL, t, offset_day, + offset_sec)); + ExpectTrue(asn_time->type == asn_utc_time); + ExpectNotNull(XSTRNCPY(date_str, (const char*)&asn_time->data, + CTC_DATE_SIZE)); date_str[CTC_DATE_SIZE] = '\0'; - AssertIntEQ(0, XMEMCMP(date_str, "000222211515Z", 13)); + ExpectIntEQ(0, XMEMCMP(date_str, "000222211515Z", 13)); XFREE(asn_time, NULL, DYNAMIC_TYPE_OPENSSL); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -33149,71 +33479,72 @@ static int test_wolfSSL_ASN1_TIME_to_tm(void) #if (defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) || \ defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ defined(OPENSSL_ALL)) && !defined(NO_ASN_TIME) + EXPECT_DECLS; ASN1_TIME asnTime; struct tm tm; time_t testTime = 1683926567; /* Fri May 12 09:22:47 PM UTC 2023 */ XMEMSET(&asnTime, 0, sizeof(ASN1_TIME)); - AssertIntEQ(ASN1_TIME_set_string(&asnTime, "000222211515Z"), 1); - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, NULL), 1); - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 1); - - AssertIntEQ(tm.tm_sec, 15); - AssertIntEQ(tm.tm_min, 15); - AssertIntEQ(tm.tm_hour, 21); - AssertIntEQ(tm.tm_mday, 22); - AssertIntEQ(tm.tm_mon, 1); - AssertIntEQ(tm.tm_year, 100); - AssertIntEQ(tm.tm_isdst, 0); + ExpectIntEQ(ASN1_TIME_set_string(&asnTime, "000222211515Z"), 1); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, NULL), 1); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 1); + + ExpectIntEQ(tm.tm_sec, 15); + ExpectIntEQ(tm.tm_min, 15); + ExpectIntEQ(tm.tm_hour, 21); + ExpectIntEQ(tm.tm_mday, 22); + ExpectIntEQ(tm.tm_mon, 1); + ExpectIntEQ(tm.tm_year, 100); + ExpectIntEQ(tm.tm_isdst, 0); #ifdef XMKTIME - AssertIntEQ(tm.tm_wday, 2); - AssertIntEQ(tm.tm_yday, 52); + ExpectIntEQ(tm.tm_wday, 2); + ExpectIntEQ(tm.tm_yday, 52); #endif - AssertIntEQ(ASN1_TIME_set_string(&asnTime, "500222211515Z"), 1); - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 1); - AssertIntEQ(tm.tm_year, 50); + ExpectIntEQ(ASN1_TIME_set_string(&asnTime, "500222211515Z"), 1); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 1); + ExpectIntEQ(tm.tm_year, 50); /* Get current time. */ - AssertIntEQ(ASN1_TIME_to_tm(NULL, NULL), 0); - AssertIntEQ(ASN1_TIME_to_tm(NULL, &tm), 1); + ExpectIntEQ(ASN1_TIME_to_tm(NULL, NULL), 0); + ExpectIntEQ(ASN1_TIME_to_tm(NULL, &tm), 1); XMEMSET(&asnTime, 0, sizeof(ASN1_TIME)); /* 0 length. */ - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); /* No type. */ asnTime.length = 1; - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); /* Not UTCTIME length. */ asnTime.type = V_ASN1_UTCTIME; - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); /* Not GENERALIZEDTIME length. */ asnTime.type = V_ASN1_GENERALIZEDTIME; - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); /* Not Zulu timezone. */ - AssertIntEQ(ASN1_TIME_set_string(&asnTime, "000222211515U"), 1); - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); - AssertIntEQ(ASN1_TIME_set_string(&asnTime, "20000222211515U"), 1); - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); + ExpectIntEQ(ASN1_TIME_set_string(&asnTime, "000222211515U"), 1); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); + ExpectIntEQ(ASN1_TIME_set_string(&asnTime, "20000222211515U"), 1); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 0); #ifdef XMKTIME - AssertNotNull(ASN1_TIME_adj(&asnTime, testTime, 0, 0)); - AssertIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 1); - AssertIntEQ(tm.tm_sec, 47); - AssertIntEQ(tm.tm_min, 22); - AssertIntEQ(tm.tm_hour, 21); - AssertIntEQ(tm.tm_mday, 12); - AssertIntEQ(tm.tm_mon, 4); - AssertIntEQ(tm.tm_year, 123); - AssertIntEQ(tm.tm_wday, 5); - AssertIntEQ(tm.tm_yday, 131); + ExpectNotNull(ASN1_TIME_adj(&asnTime, testTime, 0, 0)); + ExpectIntEQ(ASN1_TIME_to_tm(&asnTime, &tm), 1); + ExpectIntEQ(tm.tm_sec, 47); + ExpectIntEQ(tm.tm_min, 22); + ExpectIntEQ(tm.tm_hour, 21); + ExpectIntEQ(tm.tm_mday, 12); + ExpectIntEQ(tm.tm_mon, 4); + ExpectIntEQ(tm.tm_year, 123); + ExpectIntEQ(tm.tm_wday, 5); + ExpectIntEQ(tm.tm_yday, 131); /* Confirm that when used with a tm struct from ASN1_TIME_adj, all other fields are zeroed out as expected. */ - AssertIntEQ(tm.tm_isdst, 0); + ExpectIntEQ(tm.tm_isdst, 0); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -33222,87 +33553,96 @@ static int test_wolfSSL_ASN1_TIME_to_generalizedtime(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) - WOLFSSL_ASN1_TIME *t; - WOLFSSL_ASN1_TIME *out; - WOLFSSL_ASN1_TIME *gtime; + EXPECT_DECLS; + WOLFSSL_ASN1_TIME *t = NULL; + WOLFSSL_ASN1_TIME *out = NULL; + WOLFSSL_ASN1_TIME *gtime = NULL; int tlen = 0; - unsigned char *data; + unsigned char *data = NULL; - AssertNotNull(t = wolfSSL_ASN1_TIME_new()); - AssertNull(wolfSSL_ASN1_TIME_to_generalizedtime(NULL, &out)); + ExpectNotNull(t = wolfSSL_ASN1_TIME_new()); + ExpectNull(wolfSSL_ASN1_TIME_to_generalizedtime(NULL, &out)); /* type not set. */ - AssertNull(wolfSSL_ASN1_TIME_to_generalizedtime(t, &out)); + ExpectNull(wolfSSL_ASN1_TIME_to_generalizedtime(t, &out)); XFREE(t, NULL, DYNAMIC_TYPE_TMP_BUFFER); + t = NULL; /* UTC Time test */ - AssertNotNull(t = wolfSSL_ASN1_TIME_new()); - XMEMSET(t->data, 0, ASN_GENERALIZED_TIME_SIZE); - t->type = ASN_UTC_TIME; - t->length = ASN_UTC_TIME_SIZE; - XMEMCPY(t->data, "050727123456Z", ASN_UTC_TIME_SIZE); + ExpectNotNull(t = wolfSSL_ASN1_TIME_new()); + if (t != NULL) { + XMEMSET(t->data, 0, ASN_GENERALIZED_TIME_SIZE); + t->type = ASN_UTC_TIME; + t->length = ASN_UTC_TIME_SIZE; + XMEMCPY(t->data, "050727123456Z", ASN_UTC_TIME_SIZE); + } - tlen = wolfSSL_ASN1_TIME_get_length(t); - AssertIntEQ(tlen, ASN_UTC_TIME_SIZE); - data = wolfSSL_ASN1_TIME_get_data(t); - AssertStrEQ((char*)data, "050727123456Z"); + ExpectIntEQ(tlen = wolfSSL_ASN1_TIME_get_length(t), ASN_UTC_TIME_SIZE); + ExpectStrEQ((char*)(data = wolfSSL_ASN1_TIME_get_data(t)), "050727123456Z"); out = NULL; - gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, &out); + ExpectNotNull(gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, &out)); wolfSSL_ASN1_TIME_free(gtime); - AssertNotNull(out = wolfSSL_ASN1_TIME_new()); - gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, &out); - AssertPtrEq(gtime, out); - AssertIntEQ(gtime->type, ASN_GENERALIZED_TIME); - AssertIntEQ(gtime->length, ASN_GENERALIZED_TIME_SIZE); - AssertStrEQ((char*)gtime->data, "20050727123456Z"); + gtime = NULL; + ExpectNotNull(out = wolfSSL_ASN1_TIME_new()); + ExpectNotNull(gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, &out)); + ExpectPtrEq(gtime, out); + ExpectIntEQ(gtime->type, ASN_GENERALIZED_TIME); + ExpectIntEQ(gtime->length, ASN_GENERALIZED_TIME_SIZE); + ExpectStrEQ((char*)gtime->data, "20050727123456Z"); /* Generalized Time test */ - XMEMSET(t, 0, ASN_GENERALIZED_TIME_SIZE); - XMEMSET(out, 0, ASN_GENERALIZED_TIME_SIZE); - XMEMSET(data, 0, ASN_GENERALIZED_TIME_SIZE); - t->type = ASN_GENERALIZED_TIME; - t->length = ASN_GENERALIZED_TIME_SIZE; - XMEMCPY(t->data, "20050727123456Z", ASN_GENERALIZED_TIME_SIZE); - - tlen = wolfSSL_ASN1_TIME_get_length(t); - AssertIntEQ(tlen, ASN_GENERALIZED_TIME_SIZE); - data = wolfSSL_ASN1_TIME_get_data(t); - AssertStrEQ((char*)data, "20050727123456Z"); - gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, &out); - AssertIntEQ(gtime->type, ASN_GENERALIZED_TIME); - AssertIntEQ(gtime->length, ASN_GENERALIZED_TIME_SIZE); - AssertStrEQ((char*)gtime->data, "20050727123456Z"); + ExpectNotNull(XMEMSET(t, 0, ASN_GENERALIZED_TIME_SIZE)); + ExpectNotNull(XMEMSET(out, 0, ASN_GENERALIZED_TIME_SIZE)); + ExpectNotNull(XMEMSET(data, 0, ASN_GENERALIZED_TIME_SIZE)); + if (t != NULL) { + t->type = ASN_GENERALIZED_TIME; + t->length = ASN_GENERALIZED_TIME_SIZE; + XMEMCPY(t->data, "20050727123456Z", ASN_GENERALIZED_TIME_SIZE); + } + + ExpectIntEQ(tlen = wolfSSL_ASN1_TIME_get_length(t), + ASN_GENERALIZED_TIME_SIZE); + ExpectStrEQ((char*)(data = wolfSSL_ASN1_TIME_get_data(t)), + "20050727123456Z"); + ExpectNotNull(gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, &out)); + ExpectIntEQ(gtime->type, ASN_GENERALIZED_TIME); + ExpectIntEQ(gtime->length, ASN_GENERALIZED_TIME_SIZE); + ExpectStrEQ((char*)gtime->data, "20050727123456Z"); /* UTC Time to Generalized Time 1900's test */ - XMEMSET(t, 0, ASN_GENERALIZED_TIME_SIZE); - XMEMSET(out, 0, ASN_GENERALIZED_TIME_SIZE); - XMEMSET(data, 0, ASN_GENERALIZED_TIME_SIZE); - t->type = ASN_UTC_TIME; - t->length = ASN_UTC_TIME_SIZE; - XMEMCPY(t->data, "500727123456Z", ASN_UTC_TIME_SIZE); - - gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, &out); - AssertIntEQ(gtime->type, ASN_GENERALIZED_TIME); - AssertIntEQ(gtime->length, ASN_GENERALIZED_TIME_SIZE); - AssertStrEQ((char*)gtime->data, "19500727123456Z"); + ExpectNotNull(XMEMSET(t, 0, ASN_GENERALIZED_TIME_SIZE)); + ExpectNotNull(XMEMSET(out, 0, ASN_GENERALIZED_TIME_SIZE)); + ExpectNotNull(XMEMSET(data, 0, ASN_GENERALIZED_TIME_SIZE)); + if (t != NULL) { + t->type = ASN_UTC_TIME; + t->length = ASN_UTC_TIME_SIZE; + XMEMCPY(t->data, "500727123456Z", ASN_UTC_TIME_SIZE); + } + + ExpectNotNull(gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, &out)); + ExpectIntEQ(gtime->type, ASN_GENERALIZED_TIME); + ExpectIntEQ(gtime->length, ASN_GENERALIZED_TIME_SIZE); + ExpectStrEQ((char*)gtime->data, "19500727123456Z"); XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER); /* Null parameter test */ - XMEMSET(t, 0, ASN_GENERALIZED_TIME_SIZE); + ExpectNotNull(XMEMSET(t, 0, ASN_GENERALIZED_TIME_SIZE)); gtime = NULL; out = NULL; - t->type = ASN_UTC_TIME; - t->length = ASN_UTC_TIME_SIZE; - XMEMCPY(t->data, "050727123456Z", ASN_UTC_TIME_SIZE); - AssertNotNull(gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, NULL)); - AssertIntEQ(gtime->type, ASN_GENERALIZED_TIME); - AssertIntEQ(gtime->length, ASN_GENERALIZED_TIME_SIZE); - AssertStrEQ((char*)gtime->data, "20050727123456Z"); + if (t != NULL) { + t->type = ASN_UTC_TIME; + t->length = ASN_UTC_TIME_SIZE; + XMEMCPY(t->data, "050727123456Z", ASN_UTC_TIME_SIZE); + } + ExpectNotNull(gtime = wolfSSL_ASN1_TIME_to_generalizedtime(t, NULL)); + ExpectIntEQ(gtime->type, ASN_GENERALIZED_TIME); + ExpectIntEQ(gtime->length, ASN_GENERALIZED_TIME_SIZE); + ExpectStrEQ((char*)gtime->data, "20050727123456Z"); XFREE(gtime, NULL, DYNAMIC_TYPE_TMP_BUFFER); XFREE(t, NULL, DYNAMIC_TYPE_TMP_BUFFER); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -33315,53 +33655,56 @@ static int test_wolfSSL_ASN1_TIME_print(void) defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ defined(OPENSSL_ALL)) && defined(USE_CERT_BUFFERS_2048) && \ !defined(NO_ASN_TIME) - BIO* bio; - BIO* fixed; - X509* x509; + EXPECT_DECLS; + BIO* bio = NULL; + BIO* fixed = NULL; + X509* x509 = NULL; const unsigned char* der = client_cert_der_2048; ASN1_TIME* notAfter; ASN1_TIME* notBefore; unsigned char buf[25]; - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertNotNull(fixed = BIO_new(wolfSSL_BIO_s_fixed_mem())); - AssertNotNull(x509 = wolfSSL_X509_load_certificate_buffer(der, + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(fixed = BIO_new(wolfSSL_BIO_s_fixed_mem())); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_buffer(der, sizeof_client_cert_der_2048, WOLFSSL_FILETYPE_ASN1)); - AssertNotNull(notBefore = X509_get_notBefore(x509)); + ExpectNotNull(notBefore = X509_get_notBefore(x509)); - AssertIntEQ(ASN1_TIME_print(NULL, NULL), 0); - AssertIntEQ(ASN1_TIME_print(bio, NULL), 0); - AssertIntEQ(ASN1_TIME_print(NULL, notBefore), 0); + ExpectIntEQ(ASN1_TIME_print(NULL, NULL), 0); + ExpectIntEQ(ASN1_TIME_print(bio, NULL), 0); + ExpectIntEQ(ASN1_TIME_print(NULL, notBefore), 0); - AssertIntEQ(ASN1_TIME_print(bio, notBefore), 1); - AssertIntEQ(BIO_read(bio, buf, sizeof(buf)), 24); - AssertIntEQ(XMEMCMP(buf, "Dec 16 21:17:49 2022 GMT", sizeof(buf) - 1), 0); + ExpectIntEQ(ASN1_TIME_print(bio, notBefore), 1); + ExpectIntEQ(BIO_read(bio, buf, sizeof(buf)), 24); + ExpectIntEQ(XMEMCMP(buf, "Dec 16 21:17:49 2022 GMT", sizeof(buf) - 1), 0); /* Test BIO_write fails. */ - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); /* Ensure there is 0 bytes avaialble to write into. */ - AssertIntEQ(BIO_write(fixed, buf, 1), 1); - AssertIntEQ(ASN1_TIME_print(fixed, notBefore), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 1), 1); - AssertIntEQ(ASN1_TIME_print(fixed, notBefore), 0); - AssertIntEQ(BIO_set_write_buf_size(fixed, 23), 1); - AssertIntEQ(ASN1_TIME_print(fixed, notBefore), 0); + ExpectIntEQ(BIO_write(fixed, buf, 1), 1); + ExpectIntEQ(ASN1_TIME_print(fixed, notBefore), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 1), 1); + ExpectIntEQ(ASN1_TIME_print(fixed, notBefore), 0); + ExpectIntEQ(BIO_set_write_buf_size(fixed, 23), 1); + ExpectIntEQ(ASN1_TIME_print(fixed, notBefore), 0); /* create a bad time and test results */ - AssertNotNull(notAfter = X509_get_notAfter(x509)); - AssertIntEQ(ASN1_TIME_check(notAfter), 1); - notAfter->data[8] = 0; - notAfter->data[3] = 0; - AssertIntNE(ASN1_TIME_print(bio, notAfter), 1); - AssertIntEQ(BIO_read(bio, buf, sizeof(buf)), 14); - AssertIntEQ(XMEMCMP(buf, "Bad time value", 14), 0); - AssertIntEQ(ASN1_TIME_check(notAfter), 0); + ExpectNotNull(notAfter = X509_get_notAfter(x509)); + ExpectIntEQ(ASN1_TIME_check(notAfter), 1); + if (EXPECT_SUCCESS()) { + notAfter->data[8] = 0; + notAfter->data[3] = 0; + } + ExpectIntNE(ASN1_TIME_print(bio, notAfter), 1); + ExpectIntEQ(BIO_read(bio, buf, sizeof(buf)), 14); + ExpectIntEQ(XMEMCMP(buf, "Bad time value", 14), 0); + ExpectIntEQ(ASN1_TIME_check(notAfter), 0); BIO_free(bio); BIO_free(fixed); X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -33370,7 +33713,8 @@ static int test_wolfSSL_ASN1_UTCTIME_print(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) && !defined(NO_BIO) - BIO* bio; + EXPECT_DECLS; + BIO* bio = NULL; ASN1_UTCTIME* utc = NULL; unsigned char buf[25]; const char* validDate = "190424111501Z"; /* UTC = YYMMDDHHMMSSZ */ @@ -33378,43 +33722,50 @@ static int test_wolfSSL_ASN1_UTCTIME_print(void) const char* genDate = "20190424111501Z"; /* GEN = YYYYMMDDHHMMSSZ */ /* Valid date */ - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertNotNull(utc = (ASN1_UTCTIME*)XMALLOC(sizeof(ASN1_UTCTIME), NULL, + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(utc = (ASN1_UTCTIME*)XMALLOC(sizeof(ASN1_UTCTIME), NULL, DYNAMIC_TYPE_ASN1)); - utc->type = ASN_UTC_TIME; - utc->length = ASN_UTC_TIME_SIZE; - XMEMCPY(utc->data, (byte*)validDate, ASN_UTC_TIME_SIZE); + if (utc != NULL) { + utc->type = ASN_UTC_TIME; + utc->length = ASN_UTC_TIME_SIZE; + XMEMCPY(utc->data, (byte*)validDate, ASN_UTC_TIME_SIZE); + } - AssertIntEQ(ASN1_UTCTIME_print(NULL, NULL), 0); - AssertIntEQ(ASN1_UTCTIME_print(bio, NULL), 0); - AssertIntEQ(ASN1_UTCTIME_print(NULL, utc), 0); + ExpectIntEQ(ASN1_UTCTIME_print(NULL, NULL), 0); + ExpectIntEQ(ASN1_UTCTIME_print(bio, NULL), 0); + ExpectIntEQ(ASN1_UTCTIME_print(NULL, utc), 0); - AssertIntEQ(ASN1_UTCTIME_print(bio, utc), 1); - AssertIntEQ(BIO_read(bio, buf, sizeof(buf)), 24); - AssertIntEQ(XMEMCMP(buf, "Apr 24 11:15:01 2019 GMT", sizeof(buf)-1), 0); + ExpectIntEQ(ASN1_UTCTIME_print(bio, utc), 1); + ExpectIntEQ(BIO_read(bio, buf, sizeof(buf)), 24); + ExpectIntEQ(XMEMCMP(buf, "Apr 24 11:15:01 2019 GMT", sizeof(buf)-1), 0); XMEMSET(buf, 0, sizeof(buf)); BIO_free(bio); + bio = NULL; /* Invalid format */ - AssertNotNull(bio = BIO_new(BIO_s_mem())); - utc->type = ASN_UTC_TIME; - utc->length = ASN_UTC_TIME_SIZE; - XMEMCPY(utc->data, (byte*)invalidDate, ASN_UTC_TIME_SIZE); - AssertIntEQ(ASN1_UTCTIME_print(bio, utc), 0); - AssertIntEQ(BIO_read(bio, buf, sizeof(buf)), 14); - AssertIntEQ(XMEMCMP(buf, "Bad time value", 14), 0); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + if (utc != NULL) { + utc->type = ASN_UTC_TIME; + utc->length = ASN_UTC_TIME_SIZE; + XMEMCPY(utc->data, (byte*)invalidDate, ASN_UTC_TIME_SIZE); + } + ExpectIntEQ(ASN1_UTCTIME_print(bio, utc), 0); + ExpectIntEQ(BIO_read(bio, buf, sizeof(buf)), 14); + ExpectIntEQ(XMEMCMP(buf, "Bad time value", 14), 0); /* Invalid type */ - utc->type = ASN_GENERALIZED_TIME; - utc->length = ASN_GENERALIZED_TIME_SIZE; - XMEMCPY(utc->data, (byte*)genDate, ASN_GENERALIZED_TIME_SIZE); - AssertIntEQ(ASN1_UTCTIME_print(bio, utc), 0); + if (utc != NULL) { + utc->type = ASN_GENERALIZED_TIME; + utc->length = ASN_GENERALIZED_TIME_SIZE; + XMEMCPY(utc->data, (byte*)genDate, ASN_GENERALIZED_TIME_SIZE); + } + ExpectIntEQ(ASN1_UTCTIME_print(bio, utc), 0); XFREE(utc, NULL, DYNAMIC_TYPE_ASN1); BIO_free(bio); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && !NO_ASN_TIME && !NO_BIO */ return res; } @@ -33424,73 +33775,85 @@ static int test_wolfSSL_ASN1_TYPE(void) int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD) || \ defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS) - WOLFSSL_ASN1_TYPE* t; - WOLFSSL_ASN1_OBJECT* obj; + EXPECT_DECLS; + WOLFSSL_ASN1_TYPE* t = NULL; + WOLFSSL_ASN1_OBJECT* obj = NULL; #ifndef NO_ASN_TIME - WOLFSSL_ASN1_TIME* time; + WOLFSSL_ASN1_TIME* time = NULL; #endif - WOLFSSL_ASN1_STRING* str; + WOLFSSL_ASN1_STRING* str = NULL; unsigned char data[] = { 0x00 }; ASN1_TYPE_set(NULL, V_ASN1_NULL, NULL); - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); ASN1_TYPE_set(t, V_ASN1_EOC, NULL); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); ASN1_TYPE_set(t, V_ASN1_NULL, NULL); ASN1_TYPE_set(t, V_ASN1_NULL, data); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(obj = wolfSSL_ASN1_OBJECT_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(obj = wolfSSL_ASN1_OBJECT_new()); ASN1_TYPE_set(t, V_ASN1_OBJECT, obj); wolfSSL_ASN1_TYPE_free(t); + t = NULL; #ifndef NO_ASN_TIME - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(time = wolfSSL_ASN1_TIME_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(time = wolfSSL_ASN1_TIME_new()); ASN1_TYPE_set(t, V_ASN1_UTCTIME, time); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(time = wolfSSL_ASN1_TIME_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(time = wolfSSL_ASN1_TIME_new()); ASN1_TYPE_set(t, V_ASN1_GENERALIZEDTIME, time); wolfSSL_ASN1_TYPE_free(t); + t = NULL; #endif - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(str = wolfSSL_ASN1_STRING_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(str = wolfSSL_ASN1_STRING_new()); ASN1_TYPE_set(t, V_ASN1_UTF8STRING, str); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(str = wolfSSL_ASN1_STRING_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(str = wolfSSL_ASN1_STRING_new()); ASN1_TYPE_set(t, V_ASN1_PRINTABLESTRING, str); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(str = wolfSSL_ASN1_STRING_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(str = wolfSSL_ASN1_STRING_new()); ASN1_TYPE_set(t, V_ASN1_T61STRING, str); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(str = wolfSSL_ASN1_STRING_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(str = wolfSSL_ASN1_STRING_new()); ASN1_TYPE_set(t, V_ASN1_IA5STRING, str); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(str = wolfSSL_ASN1_STRING_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(str = wolfSSL_ASN1_STRING_new()); ASN1_TYPE_set(t, V_ASN1_UNIVERSALSTRING, str); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - AssertNotNull(t = wolfSSL_ASN1_TYPE_new()); - AssertNotNull(str = wolfSSL_ASN1_STRING_new()); + ExpectNotNull(t = wolfSSL_ASN1_TYPE_new()); + ExpectNotNull(str = wolfSSL_ASN1_STRING_new()); ASN1_TYPE_set(t, V_ASN1_SEQUENCE, str); wolfSSL_ASN1_TYPE_free(t); + t = NULL; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -33516,12 +33879,22 @@ typedef struct { ASN1_INTEGER *integer; } TEST_ASN1; -#define WOLFSSL_ASN1_INTEGER_ASN1 2 ASN1_SEQUENCE(TEST_ASN1) = { ASN1_SIMPLE(TEST_ASN1, integer, ASN1_INTEGER), } ASN1_SEQUENCE_END(TEST_ASN1) IMPLEMENT_ASN1_FUNCTIONS(TEST_ASN1) + +typedef struct { + ASN1_OCTET_STRING *octet_string; +} TEST_FAIL_ASN1; + +#define WOLFSSL_ASN1_OCTET_STRING_ASN1 4 +ASN1_SEQUENCE(TEST_FAIL_ASN1) = { + ASN1_SIMPLE(TEST_FAIL_ASN1, octet_string, ASN1_OCTET_STRING), +} ASN1_SEQUENCE_END(TEST_FAIL_ASN1) + +IMPLEMENT_ASN1_FUNCTIONS(TEST_FAIL_ASN1) #endif static int test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS(void) @@ -33530,16 +33903,20 @@ static int test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS(void) /* Testing code used in dpp.c in hostap */ #if defined(OPENSSL_ALL) && defined(HAVE_ECC) && defined(USE_CERT_BUFFERS_256) #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION>2)) - EC_KEY *eckey; - EVP_PKEY *key; + EXPECT_DECLS; + EC_KEY *eckey = NULL; + EVP_PKEY *key = NULL; size_t len; unsigned char *der = NULL; DPP_BOOTSTRAPPING_KEY *bootstrap = NULL; const unsigned char *in = ecc_clikey_der_256; - const EC_GROUP *group; - const EC_POINT *point; + WOLFSSL_ASN1_OBJECT* ec_obj = NULL; + WOLFSSL_ASN1_OBJECT* group_obj = NULL; + const EC_GROUP *group = NULL; + const EC_POINT *point = NULL; int nid; TEST_ASN1 *test_asn1 = NULL; + TEST_FAIL_ASN1 test_fail_asn1; const unsigned char badObjDer[] = { 0x06, 0x00 }; const unsigned char goodObjDer[] = { @@ -33549,102 +33926,128 @@ static int test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS(void) XMEMSET(&emptyTemplate, 0, sizeof(WOLFSSL_ASN1_ITEM)); - AssertNotNull(bootstrap = DPP_BOOTSTRAPPING_KEY_new()); + ExpectNotNull(bootstrap = DPP_BOOTSTRAPPING_KEY_new()); der = NULL; - AssertIntEQ(i2d_DPP_BOOTSTRAPPING_KEY(NULL, &der), 0); - AssertIntEQ(wolfSSL_ASN1_item_i2d(bootstrap, &der, NULL), 0); - AssertIntEQ(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 0); + ExpectIntEQ(i2d_DPP_BOOTSTRAPPING_KEY(NULL, &der), 0); + ExpectIntEQ(wolfSSL_ASN1_item_i2d(bootstrap, &der, NULL), 0); + ExpectIntEQ(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 0); - AssertNotNull(key = d2i_PrivateKey(EVP_PKEY_EC, NULL, &in, + ExpectNotNull(key = d2i_PrivateKey(EVP_PKEY_EC, NULL, &in, (long)sizeof_ecc_clikey_der_256)); - AssertNotNull(eckey = EVP_PKEY_get1_EC_KEY(key)); - AssertNotNull(group = EC_KEY_get0_group(eckey)); - AssertNotNull(point = EC_KEY_get0_public_key(eckey)); + ExpectNotNull(eckey = EVP_PKEY_get1_EC_KEY(key)); + ExpectNotNull(group = EC_KEY_get0_group(eckey)); + ExpectNotNull(point = EC_KEY_get0_public_key(eckey)); nid = EC_GROUP_get_curve_name(group); - AssertIntEQ(X509_ALGOR_set0(bootstrap->alg, OBJ_nid2obj(EVP_PKEY_EC), - V_ASN1_OBJECT, OBJ_nid2obj(nid)), 1); - AssertIntEQ(EC_POINT_point2oct(group, point, 0, NULL, 0, NULL), 0); + ec_obj = OBJ_nid2obj(EVP_PKEY_EC); + group_obj = OBJ_nid2obj(nid); + if ((ec_obj != NULL) && (group_obj != NULL)) { + ExpectIntEQ(X509_ALGOR_set0(bootstrap->alg, ec_obj, V_ASN1_OBJECT, + group_obj), 1); + if (EXPECT_SUCCESS()) { + ec_obj = NULL; + group_obj = NULL; + } + } + wolfSSL_ASN1_OBJECT_free(group_obj); + wolfSSL_ASN1_OBJECT_free(ec_obj); + ExpectIntEQ(EC_POINT_point2oct(group, point, 0, NULL, 0, NULL), 0); #ifdef HAVE_COMP_KEY - AssertIntGT((len = EC_POINT_point2oct( + ExpectIntGT((len = EC_POINT_point2oct( group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, NULL)), 0); #else - AssertIntGT((len = EC_POINT_point2oct( + ExpectIntGT((len = EC_POINT_point2oct( group, point, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL)), 0); #endif - AssertNotNull(der = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1)); + ExpectNotNull(der = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1)); #ifdef HAVE_COMP_KEY - AssertIntEQ(EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, + ExpectIntEQ(EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, der, len-1, NULL), 0); - AssertIntEQ(EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, + ExpectIntEQ(EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, der, len, NULL), len); #else - AssertIntEQ(EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, + ExpectIntEQ(EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, der, len-1, NULL), 0); - AssertIntEQ(EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, + ExpectIntEQ(EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, der, len, NULL), len); #endif - bootstrap->pub_key->data = der; - bootstrap->pub_key->length = (int)len; - /* Not actually used */ - bootstrap->pub_key->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); - bootstrap->pub_key->flags |= ASN1_STRING_FLAG_BITS_LEFT; + if (EXPECT_SUCCESS()) { + bootstrap->pub_key->data = der; + bootstrap->pub_key->length = (int)len; + /* Not actually used */ + bootstrap->pub_key->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); + bootstrap->pub_key->flags |= ASN1_STRING_FLAG_BITS_LEFT; + } - AssertIntGT(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, NULL), 0); + ExpectIntGT(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, NULL), 0); der = NULL; - AssertIntGT(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 0); - AssertIntGT(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 0); + ExpectIntGT(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 0); + ExpectIntGT(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 0); XFREE(der, NULL, DYNAMIC_TYPE_ASN1); EVP_PKEY_free(key); EC_KEY_free(eckey); DPP_BOOTSTRAPPING_KEY_free(bootstrap); + bootstrap = NULL; DPP_BOOTSTRAPPING_KEY_free(NULL); /* Create bootstrap key with bad OBJECT_ID DER data, parameter that is * a NULL and an empty BIT_STRING. */ - AssertNotNull(bootstrap = DPP_BOOTSTRAPPING_KEY_new()); - bootstrap->alg->algorithm = wolfSSL_ASN1_OBJECT_new(); - bootstrap->alg->algorithm->obj = badObjDer; - bootstrap->alg->algorithm->objSz = (unsigned int)sizeof(badObjDer); - bootstrap->alg->parameter = wolfSSL_ASN1_TYPE_new(); - bootstrap->alg->parameter->type = V_ASN1_NULL; - bootstrap->alg->parameter->value.ptr = NULL; - bootstrap->pub_key->data = NULL; - bootstrap->pub_key->length = 0; - /* Not actually used */ - bootstrap->pub_key->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); - bootstrap->pub_key->flags |= ASN1_STRING_FLAG_BITS_LEFT; + ExpectNotNull(bootstrap = DPP_BOOTSTRAPPING_KEY_new()); + ExpectNotNull(bootstrap->alg->algorithm = wolfSSL_ASN1_OBJECT_new()); + if (EXPECT_SUCCESS()) { + bootstrap->alg->algorithm->obj = badObjDer; + bootstrap->alg->algorithm->objSz = (unsigned int)sizeof(badObjDer); + } + ExpectNotNull(bootstrap->alg->parameter = wolfSSL_ASN1_TYPE_new()); + if (EXPECT_SUCCESS()) { + bootstrap->alg->parameter->type = V_ASN1_NULL; + bootstrap->alg->parameter->value.ptr = NULL; + bootstrap->pub_key->data = NULL; + bootstrap->pub_key->length = 0; + /* Not actually used */ + bootstrap->pub_key->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); + bootstrap->pub_key->flags |= ASN1_STRING_FLAG_BITS_LEFT; + } /* Encode with bad OBJECT_ID. */ der = NULL; - AssertIntEQ(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 0); + ExpectIntEQ(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 0); /* Fix OBJECT_ID and encode with empty BIT_STRING. */ - bootstrap->alg->algorithm->obj = goodObjDer; - bootstrap->alg->algorithm->objSz = (unsigned int)sizeof(goodObjDer); - bootstrap->alg->algorithm->grp = 2; + if (EXPECT_SUCCESS()) { + bootstrap->alg->algorithm->obj = goodObjDer; + bootstrap->alg->algorithm->objSz = (unsigned int)sizeof(goodObjDer); + bootstrap->alg->algorithm->grp = 2; + } der = NULL; - AssertIntEQ(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 16); - AssertIntEQ(wolfSSL_ASN1_item_i2d(bootstrap, &der, &emptyTemplate), 0); + ExpectIntEQ(i2d_DPP_BOOTSTRAPPING_KEY(bootstrap, &der), 16); + ExpectIntEQ(wolfSSL_ASN1_item_i2d(bootstrap, &der, &emptyTemplate), 0); XFREE(der, NULL, DYNAMIC_TYPE_ASN1); DPP_BOOTSTRAPPING_KEY_free(bootstrap); /* Test integer */ - AssertNotNull(test_asn1 = TEST_ASN1_new()); + ExpectNotNull(test_asn1 = TEST_ASN1_new()); der = NULL; - ASN1_INTEGER_set(test_asn1->integer, 100); - AssertIntEQ(i2d_TEST_ASN1(test_asn1, &der), 5); + ExpectIntEQ(ASN1_INTEGER_set(test_asn1->integer, 100), 1); + ExpectIntEQ(i2d_TEST_ASN1(test_asn1, &der), 5); XFREE(der, NULL, DYNAMIC_TYPE_ASN1); TEST_ASN1_free(test_asn1); - /* Test error cases. */ - AssertNull(wolfSSL_ASN1_item_new(NULL)); + /* Test integer cases. */ + ExpectNull(wolfSSL_ASN1_item_new(NULL)); TEST_ASN1_free(NULL); - res = TEST_RES_CHECK(1); + /* Test error cases. */ + ExpectNull(TEST_FAIL_ASN1_new()); + ExpectNull(wolfSSL_ASN1_item_new(NULL)); + TEST_FAIL_ASN1_free(NULL); + XMEMSET(&test_fail_asn1, 0, sizeof(TEST_FAIL_ASN1)); + ExpectIntEQ(i2d_TEST_FAIL_ASN1(&test_fail_asn1, &der), 0); + + res = EXPECT_RESULT(); #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ #endif /* OPENSSL_ALL && HAVE_ECC && USE_CERT_BUFFERS_256 */ return res; @@ -34295,6 +34698,7 @@ static int test_wc_PemToDer(void) { int res = TEST_SKIPPED; #if !defined(NO_CERTS) && defined(WOLFSSL_PEM_TO_DER) && !defined(NO_FILESYSTEM) + EXPECT_DECLS; int ret; DerBuffer* pDer = NULL; const char* ca_cert = "./certs/server-cert.pem"; @@ -34305,17 +34709,16 @@ static int test_wc_PemToDer(void) XMEMSET(&info, 0, sizeof(info)); - ret = load_file(ca_cert, &cert_buf, &cert_sz); - if (ret == 0) { - ret = wc_PemToDer(cert_buf, cert_sz, CERT_TYPE, - &pDer, NULL, &info, &eccKey); - AssertIntEQ(ret, 0); - - wc_FreeDer(&pDer); - } + ExpectIntEQ(ret = load_file(ca_cert, &cert_buf, &cert_sz), 0); + ExpectIntEQ(ret = wc_PemToDer(cert_buf, cert_sz, CERT_TYPE, &pDer, NULL, + &info, &eccKey), 0); + wc_FreeDer(&pDer); + pDer = NULL; - if (cert_buf) + if (cert_buf != NULL) { free(cert_buf); + cert_buf = NULL; + } #ifdef HAVE_ECC { @@ -34323,22 +34726,23 @@ static int test_wc_PemToDer(void) byte key_buf[256] = {0}; /* Test fail of loading a key with cert type */ - AssertIntEQ(load_file(ecc_private_key, &cert_buf, &cert_sz), 0); + ExpectIntEQ(load_file(ecc_private_key, &cert_buf, &cert_sz), 0); key_buf[0] = '\n'; - XMEMCPY(key_buf + 1, cert_buf, cert_sz); - AssertIntNE((ret = wc_PemToDer(key_buf, cert_sz + 1, CERT_TYPE, + ExpectNotNull(XMEMCPY(key_buf + 1, cert_buf, cert_sz)); + ExpectIntNE((ret = wc_PemToDer(key_buf, cert_sz + 1, CERT_TYPE, &pDer, NULL, &info, &eccKey)), 0); #ifdef OPENSSL_EXTRA - AssertIntEQ((ret = wc_PemToDer(key_buf, cert_sz + 1, PRIVATEKEY_TYPE, + ExpectIntEQ((ret = wc_PemToDer(key_buf, cert_sz + 1, PRIVATEKEY_TYPE, &pDer, NULL, &info, &eccKey)), 0); #endif wc_FreeDer(&pDer); - if (cert_buf) + if (cert_buf != NULL) free(cert_buf); } #endif - res = TEST_RES_CHECK(1); + + res = EXPECT_RESULT(); #endif return res; } @@ -34347,16 +34751,17 @@ static int test_wc_AllocDer(void) { int res = TEST_SKIPPED; #if !defined(NO_CERTS) - int ret; + EXPECT_DECLS; DerBuffer* pDer = NULL; word32 testSize = 1024; - ret = wc_AllocDer(&pDer, testSize, CERT_TYPE, HEAP_HINT); - AssertIntEQ(ret, 0); - AssertNotNull(pDer); + ExpectIntEQ(wc_AllocDer(NULL, testSize, CERT_TYPE, HEAP_HINT), + BAD_FUNC_ARG); + ExpectIntEQ(wc_AllocDer(&pDer, testSize, CERT_TYPE, HEAP_HINT), 0); + ExpectNotNull(pDer); wc_FreeDer(&pDer); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34365,29 +34770,40 @@ static int test_wc_CertPemToDer(void) { int res = TEST_SKIPPED; #if !defined(NO_CERTS) && defined(WOLFSSL_PEM_TO_DER) && !defined(NO_FILESYSTEM) - int ret; + EXPECT_DECLS; const char* ca_cert = "./certs/ca-cert.pem"; byte* cert_buf = NULL; - size_t cert_sz = 0, cert_dersz = 0; + size_t cert_sz = 0; + size_t cert_dersz = 0; byte* cert_der = NULL; - ret = load_file(ca_cert, &cert_buf, &cert_sz); - if (ret == 0) { - cert_dersz = cert_sz; /* DER will be smaller than PEM */ - cert_der = (byte*)malloc(cert_dersz); - if (cert_der) { - ret = wc_CertPemToDer(cert_buf, (int)cert_sz, - cert_der, (int)cert_dersz, CERT_TYPE); - AssertIntGE(ret, 0); - } - } - - if (cert_der) + ExpectIntEQ(load_file(ca_cert, &cert_buf, &cert_sz), 0); + cert_dersz = cert_sz; /* DER will be smaller than PEM */ + ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); + ExpectIntGE(wc_CertPemToDer(cert_buf, (int)cert_sz, cert_der, + (int)cert_dersz, CERT_TYPE), 0); + + ExpectIntEQ(wc_CertPemToDer(NULL, (int)cert_sz, NULL, -1, CERT_TYPE), + BAD_FUNC_ARG); + ExpectIntEQ(wc_CertPemToDer(cert_buf, (int)cert_sz, NULL, -1, CERT_TYPE), + BAD_FUNC_ARG); + ExpectIntEQ(wc_CertPemToDer(NULL, (int)cert_sz, cert_der, -1, CERT_TYPE), + BAD_FUNC_ARG); + ExpectIntEQ(wc_CertPemToDer(NULL, (int)cert_sz, NULL, (int)cert_dersz, + CERT_TYPE), BAD_FUNC_ARG); + ExpectIntEQ(wc_CertPemToDer(NULL, (int)cert_sz, cert_der, + (int)cert_dersz, CERT_TYPE), BAD_FUNC_ARG); + ExpectIntEQ(wc_CertPemToDer(cert_buf, (int)cert_sz, NULL, + (int)cert_dersz, CERT_TYPE), BAD_FUNC_ARG); + ExpectIntEQ(wc_CertPemToDer(cert_buf, (int)cert_sz, cert_der, -1, + CERT_TYPE), BAD_FUNC_ARG); + + if (cert_der != NULL) free(cert_der); - if (cert_buf) + if (cert_buf != NULL) free(cert_buf); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34395,9 +34811,8 @@ static int test_wc_CertPemToDer(void) static int test_wc_KeyPemToDer(void) { int res = TEST_SKIPPED; - #if defined(WOLFSSL_PEM_TO_DER) && !defined(NO_FILESYSTEM) && !defined(NO_RSA) - + EXPECT_DECLS; int ret; const byte cert_buf[] = \ "-----BEGIN PRIVATE KEY-----\n" @@ -34434,44 +34849,36 @@ static int test_wc_KeyPemToDer(void) byte* cert_der = NULL; /* Bad arg: Cert buffer is NULL */ - ret = wc_KeyPemToDer(NULL, cert_sz, cert_der, cert_dersz, ""); - AssertIntEQ(ret, BAD_FUNC_ARG); + ExpectIntEQ(wc_KeyPemToDer(NULL, cert_sz, cert_der, cert_dersz, ""), + BAD_FUNC_ARG); /* Bad arg: Cert DER buffer non-NULL but size zero (or less) */ - ret = wc_KeyPemToDer(cert_buf, cert_sz, (byte*)&cert_der, 0, ""); - AssertIntEQ(ret, BAD_FUNC_ARG); + ExpectIntEQ(wc_KeyPemToDer(cert_buf, cert_sz, (byte*)&cert_der, 0, ""), + BAD_FUNC_ARG); /* Test normal operation */ cert_dersz = cert_sz; /* DER will be smaller than PEM */ - cert_der = (byte*)malloc(cert_dersz); - AssertNotNull(cert_der); - if (cert_der) { - ret = wc_KeyPemToDer(cert_buf, cert_sz, cert_der, cert_dersz, cert_pw); - AssertIntGE(ret, 0); - AssertIntLE(ret, cert_sz); + ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); + ExpectIntGE(ret = wc_KeyPemToDer(cert_buf, cert_sz, cert_der, cert_dersz, + cert_pw), 0); + ExpectIntLE(ret, cert_sz); + if (cert_der != NULL) { free(cert_der); cert_der = NULL; - ret = 0; } - if (ret == 0) { - /* Test NULL for DER buffer to return needed DER buffer size */ - ret = wc_KeyPemToDer(cert_buf, cert_sz, NULL, 0, ""); - AssertIntGT(ret, 0); - AssertIntLE(ret, cert_sz); - cert_dersz = ret; - cert_der = (byte*)malloc(cert_dersz); - AssertNotNull(cert_der); - if (cert_der) { - ret = wc_KeyPemToDer(cert_buf, cert_sz, cert_der, cert_dersz, cert_pw); - AssertIntGE(ret, 0); - AssertIntLE(ret, cert_sz); - free(cert_der); - cert_der = NULL; - } - } + /* Test NULL for DER buffer to return needed DER buffer size */ + ExpectIntGT(ret = wc_KeyPemToDer(cert_buf, cert_sz, NULL, 0, ""), 0); + ExpectIntLE(ret, cert_sz); + cert_dersz = ret; + ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); + ExpectIntGE(ret = wc_KeyPemToDer(cert_buf, cert_sz, cert_der, cert_dersz, + cert_pw), 0); + ExpectIntLE(ret, cert_sz); + if (cert_der != NULL) + free(cert_der); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34481,53 +34888,42 @@ static int test_wc_PubKeyPemToDer(void) int res = TEST_SKIPPED; #if defined(WOLFSSL_PEM_TO_DER) && !defined(NO_FILESYSTEM) && \ (defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)) - int ret; + EXPECT_DECLS; + int ret = 0; const char* key = "./certs/ecc-client-keyPub.pem"; byte* cert_buf = NULL; size_t cert_sz = 0, cert_dersz = 0; byte* cert_der = NULL; - ret = wc_PubKeyPemToDer(cert_buf, (int)cert_sz, - cert_der, (int)cert_dersz); - AssertIntGE(ret, BAD_FUNC_ARG); - - ret = load_file(key, &cert_buf, &cert_sz); - if (ret == 0) { - cert_dersz = cert_sz; /* DER will be smaller than PEM */ - cert_der = (byte*)malloc(cert_dersz); - AssertNotNull(cert_der); - if (cert_der) { - ret = wc_PubKeyPemToDer(cert_buf, (int)cert_sz, cert_der, - (int)cert_dersz); - AssertIntGE(ret, 0); - free(cert_der); - cert_der = NULL; - ret = 0; - } + ExpectIntEQ(wc_PubKeyPemToDer(cert_buf, (int)cert_sz, + cert_der, (int)cert_dersz), BAD_FUNC_ARG); + + ExpectIntEQ(load_file(key, &cert_buf, &cert_sz), 0); + cert_dersz = cert_sz; /* DER will be smaller than PEM */ + ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); + ExpectIntGE(wc_PubKeyPemToDer(cert_buf, (int)cert_sz, cert_der, + (int)cert_dersz), 0); + if (cert_der != NULL) { + free(cert_der); + cert_der = NULL; } - if (ret == 0) { - /* Test NULL for DER buffer to return needed DER buffer size */ - ret = wc_PubKeyPemToDer(cert_buf, (int)cert_sz, NULL, 0); - AssertIntGT(ret, 0); - AssertIntLE(ret, cert_sz); - cert_dersz = ret; - cert_der = (byte*)malloc(cert_dersz); - AssertNotNull(cert_der); - if (cert_der) { - ret = wc_PubKeyPemToDer(cert_buf, (int)cert_sz, cert_der, - (int)cert_dersz); - AssertIntGE(ret, 0); - free(cert_der); - cert_der = NULL; - } + /* Test NULL for DER buffer to return needed DER buffer size */ + ExpectIntGT(ret = wc_PubKeyPemToDer(cert_buf, (int)cert_sz, NULL, 0), 0); + ExpectIntLE(ret, cert_sz); + cert_dersz = ret; + ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); + ExpectIntGE(wc_PubKeyPemToDer(cert_buf, (int)cert_sz, cert_der, + (int)cert_dersz), 0); + if (cert_der != NULL) { + free(cert_der); } - if (cert_buf) { + if (cert_buf != NULL) { free(cert_buf); } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34537,22 +34933,21 @@ static int test_wc_PemPubKeyToDer(void) int res = TEST_SKIPPED; #if !defined(NO_FILESYSTEM) && \ (defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)) - int ret; + EXPECT_DECLS; const char* key = "./certs/ecc-client-keyPub.pem"; size_t cert_dersz = 1024; - byte* cert_der = (byte*)malloc(cert_dersz); - - ret = wc_PemPubKeyToDer(NULL, cert_der, (int)cert_dersz); - AssertIntGE(ret, BAD_FUNC_ARG); + byte* cert_der = NULL; - if (cert_der) { - ret = wc_PemPubKeyToDer(key, cert_der, (int)cert_dersz); - AssertIntGE(ret, 0); + ExpectIntGE(wc_PemPubKeyToDer(NULL, cert_der, (int)cert_dersz), + BAD_FUNC_ARG); + ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); + ExpectIntGE(wc_PemPubKeyToDer(key, cert_der, (int)cert_dersz), 0); + if (cert_der != NULL) { free(cert_der); } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34561,6 +34956,7 @@ static int test_wc_GetPubKeyDerFromCert(void) { int res = TEST_SKIPPED; #if !defined(NO_RSA) || defined(HAVE_ECC) + EXPECT_DECLS; int ret; word32 idx = 0; byte keyDer[TWOK_BUF]; /* large enough for up to RSA 2048 */ @@ -34572,7 +34968,7 @@ static int test_wc_GetPubKeyDerFromCert(void) #endif #if ((!defined(USE_CERT_BUFFERS_2048) && !defined(USE_CERT_BUFFERS_1024)) || \ defined(WOLFSSL_CERT_REQ)) && !defined(NO_RSA) && !defined(NO_FILESYSTEM) - XFILE fp; + XFILE fp = XBADFILE; #endif #ifndef NO_RSA RsaKey rsaKey; @@ -34595,53 +34991,53 @@ static int test_wc_GetPubKeyDerFromCert(void) #else unsigned char eccCert[ONEK_BUF]; word32 eccCertSz; - XFILE fp2; + XFILE fp2 = XBADFILE; #endif #endif #ifndef NO_RSA #if !defined(USE_CERT_BUFFERS_1024) && !defined(USE_CERT_BUFFERS_2048) - fp = XFOPEN("./certs/1024/client-cert.der", "rb"); - AssertTrue((fp != XBADFILE)); - rsaCertDerSz = (word32)XFREAD(rsaCertDer, 1, sizeof(rsaCertDer), fp); - XFCLOSE(fp); + ExpectTrue((fp = XFOPEN("./certs/1024/client-cert.der", "rb")) != XBADFILE); + ExpectIntGT(rsaCertDerSz = (word32)XFREAD(rsaCertDer, 1, sizeof(rsaCertDer), + fp), 0); + if (fp != XBADFILE) { + XFCLOSE(fp); + fp = XBADFILE; + } #endif /* good test case - RSA DER cert */ wc_InitDecodedCert(&decoded, rsaCertDer, rsaCertDerSz, NULL); - ret = wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL); - AssertIntEQ(ret, 0); + ExpectIntEQ(wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL), 0); - ret = wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz); - AssertIntEQ(ret, 0); - AssertIntGT(keyDerSz, 0); + ExpectIntEQ(wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz), 0); + ExpectIntGT(keyDerSz, 0); /* sanity check, verify we can import DER public key */ ret = wc_InitRsaKey(&rsaKey, HEAP_HINT); - AssertIntEQ(ret, 0); - ret = wc_RsaPublicKeyDecode(keyDer, &idx, &rsaKey, keyDerSz); - AssertIntEQ(ret, 0); - wc_FreeRsaKey(&rsaKey); + ExpectIntEQ(ret, 0); + ExpectIntEQ(wc_RsaPublicKeyDecode(keyDer, &idx, &rsaKey, keyDerSz), 0); + if (ret == 0) { + wc_FreeRsaKey(&rsaKey); + } /* test LENGTH_ONLY_E case */ keyDerSz = 0; - ret = wc_GetPubKeyDerFromCert(&decoded, NULL, &keyDerSz); - AssertIntEQ(ret, LENGTH_ONLY_E); - AssertIntGT(keyDerSz, 0); + ExpectIntEQ(wc_GetPubKeyDerFromCert(&decoded, NULL, &keyDerSz), + LENGTH_ONLY_E); + ExpectIntGT(keyDerSz, 0); /* bad args: DecodedCert NULL */ - ret = wc_GetPubKeyDerFromCert(NULL, keyDer, &keyDerSz); - AssertIntEQ(ret, BAD_FUNC_ARG); + ExpectIntEQ(wc_GetPubKeyDerFromCert(NULL, keyDer, &keyDerSz), BAD_FUNC_ARG); /* bad args: output key buff size */ - ret = wc_GetPubKeyDerFromCert(&decoded, keyDer, NULL); - AssertIntEQ(ret, BAD_FUNC_ARG); + ExpectIntEQ(wc_GetPubKeyDerFromCert(&decoded, keyDer, NULL), BAD_FUNC_ARG); /* bad args: zero size output key buffer */ keyDerSz = 0; - ret = wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz); - AssertIntEQ(ret, BAD_FUNC_ARG); + ExpectIntEQ(ret = wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz), + BAD_FUNC_ARG); wc_FreeDecodedCert(&decoded); @@ -34649,28 +35045,29 @@ static int test_wc_GetPubKeyDerFromCert(void) #if defined(WOLFSSL_CERT_REQ) && !defined(NO_FILESYSTEM) { XMEMSET(certBuf, 0, sizeof(certBuf)); - fp = XFOPEN("./certs/csr.signed.der", "rb"); - AssertTrue((fp != XBADFILE)); - certBufSz = (word32)XFREAD(certBuf, 1, certBufSz, fp); - XFCLOSE(fp); + ExpectTrue((fp = XFOPEN("./certs/csr.signed.der", "rb")) != XBADFILE); + ExpectIntGT(certBufSz = (word32)XFREAD(certBuf, 1, certBufSz, fp), 0); + if (fp != XBADFILE) { + XFCLOSE(fp); + } wc_InitDecodedCert(&decoded, certBuf, certBufSz, NULL); - ret = wc_ParseCert(&decoded, CERTREQ_TYPE, VERIFY, NULL); - AssertIntEQ(ret, 0); + ExpectIntEQ(wc_ParseCert(&decoded, CERTREQ_TYPE, VERIFY, NULL), 0); /* good test case - RSA DER certificate request */ keyDerSz = sizeof(keyDer); - ret = wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz); - AssertIntEQ(ret, 0); - AssertIntGT(keyDerSz, 0); + ExpectIntEQ(ret = wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz), + 0); + ExpectIntGT(keyDerSz, 0); /* sanity check, verify we can import DER public key */ ret = wc_InitRsaKey(&rsaKey, HEAP_HINT); - AssertIntEQ(ret, 0); + ExpectIntEQ(ret, 0); idx = 0; - ret = wc_RsaPublicKeyDecode(keyDer, &idx, &rsaKey, keyDerSz); - AssertIntEQ(ret, 0); - wc_FreeRsaKey(&rsaKey); + ExpectIntEQ(wc_RsaPublicKeyDecode(keyDer, &idx, &rsaKey, keyDerSz), 0); + if (ret == 0) { + wc_FreeRsaKey(&rsaKey); + } wc_FreeDecodedCert(&decoded); } @@ -34679,41 +35076,42 @@ static int test_wc_GetPubKeyDerFromCert(void) #ifdef HAVE_ECC #ifndef USE_CERT_BUFFERS_256 - fp2 = XFOPEN("./certs/client-ecc-cert.der", "rb"); - AssertTrue((fp2 != XBADFILE)); - eccCertSz = (word32)XFREAD(eccCert, 1, ONEK_BUF, fp2); - XFCLOSE(fp2); + ExpectTrue((fp2 = XFOPEN("./certs/client-ecc-cert.der", "rb")) != + XBADFILE); + ExpectIntGT(eccCertSz = (word32)XFREAD(eccCert, 1, ONEK_BUF, fp2), 0); + if (fp2 != XBADFILE) { + XFCLOSE(fp2); + } #endif wc_InitDecodedCert(&decoded, eccCert, eccCertSz, NULL); - ret = wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL); - AssertIntEQ(ret, 0); + ExpectIntEQ(wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL), 0); /* good test case - ECC */ XMEMSET(keyDer, 0, sizeof(keyDer)); keyDerSz = sizeof(keyDer); - ret = wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz); - AssertIntEQ(ret, 0); - AssertIntGT(keyDerSz, 0); + ExpectIntEQ(wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz), 0); + ExpectIntGT(keyDerSz, 0); /* sanity check, verify we can import DER public key */ ret = wc_ecc_init(&eccKey); - AssertIntEQ(ret, 0); + ExpectIntEQ(ret, 0); idx = 0; /* reset idx to 0, used above in RSA case */ - ret = wc_EccPublicKeyDecode(keyDer, &idx, &eccKey, keyDerSz); - AssertIntEQ(ret, 0); - wc_ecc_free(&eccKey); + ExpectIntEQ(wc_EccPublicKeyDecode(keyDer, &idx, &eccKey, keyDerSz), 0); + if (ret == 0) { + wc_ecc_free(&eccKey); + } /* test LENGTH_ONLY_E case */ keyDerSz = 0; - ret = wc_GetPubKeyDerFromCert(&decoded, NULL, &keyDerSz); - AssertIntEQ(ret, LENGTH_ONLY_E); - AssertIntGT(keyDerSz, 0); + ExpectIntEQ(wc_GetPubKeyDerFromCert(&decoded, NULL, &keyDerSz), + LENGTH_ONLY_E); + ExpectIntGT(keyDerSz, 0); wc_FreeDecodedCert(&decoded); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_RSA || HAVE_ECC */ return res; } @@ -34723,6 +35121,7 @@ static int test_wc_CheckCertSigPubKey(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) && \ !defined(NO_RSA) && defined(WOLFSSL_PEM_TO_DER) && defined(HAVE_ECC) + EXPECT_DECLS; int ret; const char* ca_cert = "./certs/ca-cert.pem"; byte* cert_buf = NULL; @@ -34733,62 +35132,50 @@ static int test_wc_CheckCertSigPubKey(void) word32 keyDerSz = (word32)sizeof(keyDer); DecodedCert decoded; - ret = load_file(ca_cert, &cert_buf, &cert_sz); - if (ret == 0) { - cert_dersz = (word32)cert_sz; /* DER will be smaller than PEM */ - cert_der = (byte*)malloc(cert_dersz); - if (cert_der) { - ret = wc_CertPemToDer(cert_buf, (int)cert_sz, - cert_der, (int)cert_dersz, CERT_TYPE); - AssertIntGE(ret, 0); - } - } + ExpectIntEQ(load_file(ca_cert, &cert_buf, &cert_sz), 0); + cert_dersz = (word32)cert_sz; /* DER will be smaller than PEM */ + ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); + ExpectIntGE(ret = wc_CertPemToDer(cert_buf, (int)cert_sz, cert_der, + (int)cert_dersz, CERT_TYPE), 0); wc_InitDecodedCert(&decoded, cert_der, cert_dersz, NULL); - ret = wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL); - AssertIntEQ(ret, 0); + ExpectIntEQ(wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL), 0); - ret = wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz); - AssertIntEQ(ret, 0); - AssertIntGT(keyDerSz, 0); + ExpectIntEQ(wc_GetPubKeyDerFromCert(&decoded, keyDer, &keyDerSz), 0); + ExpectIntGT(keyDerSz, 0); /* Good test case. */ - ret = wc_CheckCertSigPubKey(cert_der, cert_dersz, NULL, keyDer, keyDerSz, - RSAk); - AssertIntEQ(ret, 0); + ExpectIntEQ(wc_CheckCertSigPubKey(cert_der, cert_dersz, NULL, keyDer, + keyDerSz, RSAk), 0); /* No certificate. */ - ret = wc_CheckCertSigPubKey(NULL, cert_dersz, NULL, keyDer, keyDerSz, - ECDSAk); - AssertIntEQ(ret, BAD_FUNC_ARG); + ExpectIntEQ(wc_CheckCertSigPubKey(NULL, cert_dersz, NULL, keyDer, keyDerSz, + ECDSAk), BAD_FUNC_ARG); /* Bad cert size. */ - ret = wc_CheckCertSigPubKey(cert_der, 0, NULL, keyDer, keyDerSz, - RSAk); - AssertTrue(ret == ASN_PARSE_E || ret == BUFFER_E); + ExpectIntNE(ret = wc_CheckCertSigPubKey(cert_der, 0, NULL, keyDer, keyDerSz, + RSAk), 0); + ExpectTrue(ret == ASN_PARSE_E || ret == BUFFER_E); /* No public key. */ - ret = wc_CheckCertSigPubKey(cert_der, cert_dersz, NULL, NULL, keyDerSz, - RSAk); - AssertIntEQ(ret, ASN_NO_SIGNER_E); + ExpectIntEQ(wc_CheckCertSigPubKey(cert_der, cert_dersz, NULL, NULL, + keyDerSz, RSAk), ASN_NO_SIGNER_E); /* Bad public key size. */ - ret = wc_CheckCertSigPubKey(cert_der, cert_dersz, NULL, keyDer, 0, - RSAk); - AssertIntEQ(ret, BAD_FUNC_ARG); + ExpectIntEQ(wc_CheckCertSigPubKey(cert_der, cert_dersz, NULL, keyDer, 0, + RSAk), BAD_FUNC_ARG); /* Wrong aglo. */ - ret = wc_CheckCertSigPubKey(cert_der, cert_dersz, NULL, keyDer, keyDerSz, - ECDSAk); - AssertIntEQ(ret, ASN_PARSE_E); + ExpectIntEQ(wc_CheckCertSigPubKey(cert_der, cert_dersz, NULL, keyDer, + keyDerSz, ECDSAk), ASN_PARSE_E); wc_FreeDecodedCert(&decoded); - if (cert_der) + if (cert_der != NULL) free(cert_der); - if (cert_buf) + if (cert_buf != NULL) free(cert_buf); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -38694,64 +39081,66 @@ static int test_wolfSSL_Tls13_Key_Logging_test(void) #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) static int test_wolfSSL_Tls13_ECH_params(void) { + EXPECT_DECLS; #if !defined(NO_WOLFSSL_CLIENT) word32 outputLen = 0; byte testBuf[72]; WOLFSSL_CTX *ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method()); WOLFSSL *ssl = wolfSSL_new(ctx); - AssertNotNull(ctx); - AssertNotNull(ssl); + ExpectNotNull(ctx); + ExpectNotNull(ssl); /* invalid ctx */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GenerateEchConfig(NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GenerateEchConfig(NULL, "ech-public-name.com", 0, 0, 0)); /* invalid public name */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GenerateEchConfig(ctx, NULL, 0, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GenerateEchConfig(ctx, NULL, 0, 0, 0)); /* invalid algorithms */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GenerateEchConfig(ctx, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GenerateEchConfig(ctx, "ech-public-name.com", 1000, 1000, 1000)); /* invalid ctx */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GetEchConfigs(NULL, NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GetEchConfigs(NULL, NULL, &outputLen)); /* invalid output len */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GetEchConfigs(ctx, NULL, NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_CTX_GetEchConfigs(ctx, NULL, NULL)); /* invalid ssl */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigsBase64(NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigsBase64(NULL, (char*)testBuf, sizeof(testBuf))); /* invalid configs64 */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigsBase64(ssl, NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigsBase64(ssl, NULL, sizeof(testBuf))); /* invalid size */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigsBase64(ssl, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigsBase64(ssl, (char*)testBuf, 0)); /* invalid ssl */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigs(NULL, testBuf, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigs(NULL, testBuf, sizeof(testBuf))); /* invalid configs */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigs(ssl, NULL, + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigs(ssl, NULL, sizeof(testBuf))); /* invalid size */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigs(ssl, testBuf, 0)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigs(ssl, testBuf, 0)); /* invalid ssl */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_GetEchConfigs(NULL, NULL, &outputLen)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_GetEchConfigs(NULL, NULL, &outputLen)); /* invalid size */ - AssertIntNE(WOLFSSL_SUCCESS, wolfSSL_GetEchConfigs(ssl, NULL, NULL)); + ExpectIntNE(WOLFSSL_SUCCESS, wolfSSL_GetEchConfigs(ssl, NULL, NULL)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); #endif /* !NO_WOLFSSL_CLIENT */ - return TEST_SUCCESS; + return EXPECT_RESULT(); } static int test_wolfSSL_Tls13_ECH(void) { + EXPECT_DECLS; tcp_ready ready; func_args client_args; func_args server_args; @@ -38759,8 +39148,8 @@ static int test_wolfSSL_Tls13_ECH(void) callback_functions server_cbf; callback_functions client_cbf; SOCKET_T sockfd = 0; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; const char* publicName = "ech-public-name.com"; const char* privateName = "ech-private-name.com"; int privateNameLen = 20; @@ -38779,15 +39168,15 @@ static int test_wolfSSL_Tls13_ECH(void) server_cbf.method = wolfTLSv1_3_server_method; /* TLS1.3 */ /* create the server context here so we can get the ech config */ - AssertNotNull(server_cbf.ctx = + ExpectNotNull(server_cbf.ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method())); /* generate ech config */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_GenerateEchConfig(server_cbf.ctx, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_GenerateEchConfig(server_cbf.ctx, publicName, 0, 0, 0)); /* get the config for the client to use */ - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_GetEchConfigs(server_cbf.ctx, rawEchConfig, &rawEchConfigLen)); @@ -38799,36 +39188,36 @@ static int test_wolfSSL_Tls13_ECH(void) wait_tcp_ready(&server_args); /* run as a TLS1.3 client */ - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); tcp_connect(&sockfd, wolfSSLIP, server_args.signal->port, 0, 0, NULL); /* get connected the server task */ - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); /* set the ech configs for the client */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigs(ssl, rawEchConfig, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetEchConfigs(ssl, rawEchConfig, rawEchConfigLen)); /* set the sni for the client */ - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME, privateName, privateNameLen)); - AssertIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_connect(ssl), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_write(ssl, privateName, privateNameLen), + ExpectIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_connect(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_write(ssl, privateName, privateNameLen), privateNameLen); - AssertIntGT((replyLen = wolfSSL_read(ssl, reply, sizeof(reply))), 0); + ExpectIntGT((replyLen = wolfSSL_read(ssl, reply, sizeof(reply))), 0); /* add th null terminator for string compare */ reply[replyLen] = 0; /* check that the server replied with the private name */ - AssertStrEQ(privateName, reply); + ExpectStrEQ(privateName, reply); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); @@ -38836,7 +39225,7 @@ static int test_wolfSSL_Tls13_ECH(void) FreeTcpReady(&ready); - return TEST_SUCCESS; + return EXPECT_RESULT(); } #endif /* HAVE_ECH && WOLFSSL_TLS13 */ @@ -60775,19 +61164,19 @@ static int test_SetTmpEC_DHE_Sz(void) { int res = TEST_SKIPPED; #if defined(HAVE_ECC) && !defined(NO_WOLFSSL_CLIENT) - WOLFSSL_CTX *ctx; - WOLFSSL *ssl; - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpEC_DHE_Sz(ctx, 32)); - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpEC_DHE_Sz(ssl, 32)); + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_SetTmpEC_DHE_Sz(ctx, 32)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SetTmpEC_DHE_Sz(ssl, 32)); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -60797,32 +61186,36 @@ static int test_wolfSSL_CTX_get0_privatekey(void) { int res = TEST_SKIPPED; #ifdef OPENSSL_ALL + EXPECT_DECLS; WOLFSSL_CTX* ctx = NULL; + (void)ctx; + #ifndef NO_RSA - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_method())); - AssertNull(SSL_CTX_get0_privatekey(ctx)); - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_method())); + ExpectNull(SSL_CTX_get0_privatekey(ctx)); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertNull(SSL_CTX_get0_privatekey(ctx)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + ExpectNull(SSL_CTX_get0_privatekey(ctx)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(SSL_CTX_get0_privatekey(ctx)); + ExpectNotNull(SSL_CTX_get0_privatekey(ctx)); wolfSSL_CTX_free(ctx); + ctx = NULL; #endif #ifdef HAVE_ECC - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_method())); - AssertNull(SSL_CTX_get0_privatekey(ctx)); - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, eccCertFile, + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_method())); + ExpectNull(SSL_CTX_get0_privatekey(ctx)); + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, eccCertFile, WOLFSSL_FILETYPE_PEM)); - AssertNull(SSL_CTX_get0_privatekey(ctx)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, + ExpectNull(SSL_CTX_get0_privatekey(ctx)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(SSL_CTX_get0_privatekey(ctx)); + ExpectNotNull(SSL_CTX_get0_privatekey(ctx)); wolfSSL_CTX_free(ctx); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -60833,12 +61226,13 @@ static int test_wolfSSL_dtls_set_mtu(void) int res = TEST_SKIPPED; #if (defined(WOLFSSL_DTLS_MTU) || defined(WOLFSSL_SCTP)) && \ !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_DTLS) + EXPECT_DECLS; WOLFSSL_CTX* ctx = NULL; WOLFSSL* ssl = NULL; const char* testCertFile; const char* testKeyFile; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfDTLSv1_2_server_method())); #ifndef NO_RSA testCertFile = svrCertFile; testKeyFile = svrKeyFile; @@ -60847,25 +61241,25 @@ static int test_wolfSSL_dtls_set_mtu(void) testKeyFile = eccKeyFile; #endif if (testCertFile != NULL && testKeyFile != NULL) { - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, testCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, testKeyFile, WOLFSSL_FILETYPE_PEM)); } - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); - AssertIntEQ(wolfSSL_CTX_dtls_set_mtu(NULL, 1488), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_dtls_set_mtu(NULL, 1488), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_CTX_dtls_set_mtu(ctx, 20000), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_dtls_set_mtu(ssl, 20000), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_get_error(ssl, WOLFSSL_FAILURE), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_CTX_dtls_set_mtu(ctx, 1488), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_dtls_set_mtu(ssl, 1488), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_dtls_set_mtu(NULL, 1488), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_dtls_set_mtu(NULL, 1488), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_dtls_set_mtu(ctx, 20000), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_dtls_set_mtu(ssl, 20000), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_get_error(ssl, WOLFSSL_FAILURE), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_CTX_dtls_set_mtu(ctx, 1488), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_dtls_set_mtu(ssl, 1488), WOLFSSL_SUCCESS); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -60983,7 +61377,7 @@ static int test_wolfSSL_dtls_plaintext(void) return TEST_FAIL; } - return TEST_RES_CHECK(1); + return TEST_SUCCESS; } #else static int test_wolfSSL_dtls_plaintext(void) { @@ -63106,6 +63500,7 @@ static int test_wolfSSL_ERR_strings(void) int res = TEST_SKIPPED; #if !defined(NO_ERROR_STRINGS) + EXPECT_DECLS; const char* err1 = "unsupported cipher suite"; const char* err2 = "wolfSSL PEM routines"; const char* err = NULL; @@ -63115,33 +63510,27 @@ static int test_wolfSSL_ERR_strings(void) (void)err2; #if defined(OPENSSL_EXTRA) - err = ERR_reason_error_string(UNSUPPORTED_SUITE); - AssertTrue(err != NULL); - AssertIntEQ(XSTRNCMP(err, err1, XSTRLEN(err1)), 0); + ExpectNotNull(err = ERR_reason_error_string(UNSUPPORTED_SUITE)); + ExpectIntEQ(XSTRNCMP(err, err1, XSTRLEN(err1)), 0); - err = ERR_func_error_string(UNSUPPORTED_SUITE); - AssertTrue(err != NULL); - AssertIntEQ((*err == '\0'), 1); + ExpectNotNull(err = ERR_func_error_string(UNSUPPORTED_SUITE)); + ExpectIntEQ((*err == '\0'), 1); - err = ERR_lib_error_string(PEM_R_PROBLEMS_GETTING_PASSWORD); - AssertTrue(err != NULL); - AssertIntEQ(XSTRNCMP(err, err2, XSTRLEN(err2)), 0); + ExpectNotNull(err = ERR_lib_error_string(PEM_R_PROBLEMS_GETTING_PASSWORD)); + ExpectIntEQ(XSTRNCMP(err, err2, XSTRLEN(err2)), 0); #else - err = wolfSSL_ERR_reason_error_string(UNSUPPORTED_SUITE); - AssertTrue(err != NULL); - AssertIntEQ(XSTRNCMP(err, err1, XSTRLEN(err1)), 0); + ExpectNotNull(err = wolfSSL_ERR_reason_error_string(UNSUPPORTED_SUITE)); + ExpectIntEQ(XSTRNCMP(err, err1, XSTRLEN(err1)), 0); - err = wolfSSL_ERR_func_error_string(UNSUPPORTED_SUITE); - AssertTrue(err != NULL); - AssertIntEQ((*err == '\0'), 1); + ExpectNotNull(err = wolfSSL_ERR_func_error_string(UNSUPPORTED_SUITE)); + ExpectIntEQ((*err == '\0'), 1); /* The value -MIN_CODE_E+2 is PEM_R_PROBLEMS_GETTING_PASSWORD. */ - err = wolfSSL_ERR_lib_error_string(-MIN_CODE_E+2); - AssertTrue(err != NULL); - AssertIntEQ((*err == '\0'), 1); + ExpectNotNull(err = wolfSSL_ERR_lib_error_string(-MIN_CODE_E+2)); + ExpectIntEQ((*err == '\0'), 1); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -63151,13 +63540,13 @@ static int test_wolfSSL_EVP_shake128(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_SHA3) && \ defined(WOLFSSL_SHAKE128) + EXPECT_DECLS; const EVP_MD* md = NULL; - md = EVP_shake128(); - AssertTrue(md != NULL); - AssertIntEQ(XSTRNCMP(md, "SHAKE128", XSTRLEN("SHAKE128")), 0); + ExpectNotNull(md = EVP_shake128()); + ExpectIntEQ(XSTRNCMP(md, "SHAKE128", XSTRLEN("SHAKE128")), 0); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -63168,13 +63557,13 @@ static int test_wolfSSL_EVP_shake256(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_SHA3) && \ defined(WOLFSSL_SHAKE256) + EXPECT_DECLS; const EVP_MD* md = NULL; - md = EVP_shake256(); - AssertTrue(md != NULL); - AssertIntEQ(XSTRNCMP(md, "SHAKE256", XSTRLEN("SHAKE256")), 0); + ExpectNotNull(md = EVP_shake256()); + ExpectIntEQ(XSTRNCMP(md, "SHAKE256", XSTRLEN("SHAKE256")), 0); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -63184,22 +63573,21 @@ static int test_EVP_blake2(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && (defined(HAVE_BLAKE2) || defined(HAVE_BLAKE2S)) + EXPECT_DECLS; const EVP_MD* md = NULL; (void)md; #if defined(HAVE_BLAKE2) - md = EVP_blake2b512(); - AssertTrue(md != NULL); - AssertIntEQ(XSTRNCMP(md, "BLAKE2B512", XSTRLEN("BLAKE2B512")), 0); + ExpectNotNull(md = EVP_blake2b512()); + ExpectIntEQ(XSTRNCMP(md, "BLAKE2B512", XSTRLEN("BLAKE2B512")), 0); #endif #if defined(HAVE_BLAKE2S) - md = EVP_blake2s256(); - AssertTrue(md != NULL); - AssertIntEQ(XSTRNCMP(md, "BLAKE2S256", XSTRLEN("BLAKE2S256")), 0); + ExpectNotNull(md = EVP_blake2s256()); + ExpectIntEQ(XSTRNCMP(md, "BLAKE2S256", XSTRLEN("BLAKE2S256")), 0); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -63248,15 +63636,10 @@ static int test_EVP_MD_do_all(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) EVP_MD_do_all(NULL, stderr); - /* to confirm previous call gives no harm */ - AssertTrue(1); - EVP_MD_do_all(list_md_fn, stderr); - /* to confirm previous call gives no harm */ - AssertTrue(1); - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif return res; @@ -63288,29 +63671,18 @@ static int test_OBJ_NAME_do_all(void) #if defined(OPENSSL_EXTRA) OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, NULL, NULL); - /* to confirm previous call gives no harm */ - AssertTrue(1); OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH, NULL, stderr); - /* to confirm previous call gives no harm */ - AssertTrue(1); OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, obj_name_t, stderr); - AssertTrue(1); OBJ_NAME_do_all(OBJ_NAME_TYPE_PKEY_METH, obj_name_t, stderr); - AssertTrue(1); OBJ_NAME_do_all(OBJ_NAME_TYPE_COMP_METH, obj_name_t, stderr); - AssertTrue(1); OBJ_NAME_do_all(OBJ_NAME_TYPE_NUM, obj_name_t, stderr); - AssertTrue(1); OBJ_NAME_do_all(OBJ_NAME_TYPE_UNDEF, obj_name_t, stderr); - AssertTrue(1); OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH, obj_name_t, stderr); - AssertTrue(1); OBJ_NAME_do_all(-1, obj_name_t, stderr); - AssertTrue(1); - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif return res; @@ -63321,6 +63693,7 @@ static int test_SSL_CIPHER_get_xxx(void) int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) + EXPECT_DECLS; const SSL_CIPHER* cipher = NULL; STACK_OF(SSL_CIPHER) *supportedCiphers = NULL; int i, numCiphers = 0; @@ -63372,9 +63745,9 @@ static int test_SSL_CIPHER_get_xxx(void) #endif #ifdef NO_WOLFSSL_SERVER - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #endif if (cipher_id) { @@ -63389,15 +63762,14 @@ static int test_SSL_CIPHER_get_xxx(void) testKeyFile = NULL; #endif if (testCertFile != NULL && testKeyFile != NULL) { - AssertTrue(SSL_CTX_use_certificate_file(ctx, testCertFile, + ExpectTrue(SSL_CTX_use_certificate_file(ctx, testCertFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, testKeyFile, + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, testKeyFile, SSL_FILETYPE_PEM)); } - ssl = SSL_new(ctx); - AssertNotNull(ssl); - AssertIntEQ(SSL_in_init(ssl), 1); + ExpectNotNull(ssl = SSL_new(ctx)); + ExpectIntEQ(SSL_in_init(ssl), 1); supportedCiphers = SSL_get_ciphers(ssl); numCiphers = sk_num(supportedCiphers); @@ -63414,11 +63786,11 @@ static int test_SSL_CIPHER_get_xxx(void) } /* test case for */ if (i != numCiphers) { - AssertIntEQ(wolfSSL_CIPHER_get_auth_nid(cipher), expect_nid1); - AssertIntEQ(wolfSSL_CIPHER_get_cipher_nid(cipher), expect_nid2); - AssertIntEQ(wolfSSL_CIPHER_get_digest_nid(cipher), expect_nid3); - AssertIntEQ(wolfSSL_CIPHER_get_kx_nid(cipher), expect_nid4); - AssertIntEQ(wolfSSL_CIPHER_is_aead(cipher), expect_nid5); + ExpectIntEQ(wolfSSL_CIPHER_get_auth_nid(cipher), expect_nid1); + ExpectIntEQ(wolfSSL_CIPHER_get_cipher_nid(cipher), expect_nid2); + ExpectIntEQ(wolfSSL_CIPHER_get_digest_nid(cipher), expect_nid3); + ExpectIntEQ(wolfSSL_CIPHER_get_kx_nid(cipher), expect_nid4); + ExpectIntEQ(wolfSSL_CIPHER_is_aead(cipher), expect_nid5); } if (cipher_id2) { @@ -63435,21 +63807,19 @@ static int test_SSL_CIPHER_get_xxx(void) } /* test case for */ if (i != numCiphers) { - AssertIntEQ(wolfSSL_CIPHER_get_auth_nid(cipher), expect_nid21); - AssertIntEQ(wolfSSL_CIPHER_get_cipher_nid(cipher), expect_nid22); - AssertIntEQ(wolfSSL_CIPHER_get_digest_nid(cipher), expect_nid23); - AssertIntEQ(wolfSSL_CIPHER_get_kx_nid(cipher), expect_nid24); - AssertIntEQ(wolfSSL_CIPHER_is_aead(cipher), expect_nid25); + ExpectIntEQ(wolfSSL_CIPHER_get_auth_nid(cipher), expect_nid21); + ExpectIntEQ(wolfSSL_CIPHER_get_cipher_nid(cipher), expect_nid22); + ExpectIntEQ(wolfSSL_CIPHER_get_digest_nid(cipher), expect_nid23); + ExpectIntEQ(wolfSSL_CIPHER_get_kx_nid(cipher), expect_nid24); + ExpectIntEQ(wolfSSL_CIPHER_is_aead(cipher), expect_nid25); } } } - if (ctx) - SSL_CTX_free(ctx); - if (ssl) - SSL_free(ssl); + SSL_CTX_free(ctx); + SSL_free(ssl); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -66116,9 +66486,10 @@ typedef struct { const char *name; TEST_FUNC func; byte run:1; + byte fail:1; } TEST_CASE; -#define TEST_DECL(func) { #func, func, 0 } +#define TEST_DECL(func) { #func, func, 0, 0 } int testAll = 1; @@ -66129,13 +66500,17 @@ TEST_CASE testCases[] = { #ifndef NO_WOLFSSL_SERVER TEST_DECL(test_wolfSSL_CTX_new), #endif + TEST_DECL(test_server_wolfSSL_new), + TEST_DECL(test_client_wolfSSL_new), #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) && \ (!defined(NO_RSA) || defined(HAVE_ECC)) && !defined(NO_FILESYSTEM) TEST_DECL(test_for_double_Free), #endif #ifdef HAVE_IO_TESTS_DEPENDENCIES TEST_DECL(test_wolfSSL_get_finished), + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_CTX_add_session), + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_CTX_add_session_ext), #endif TEST_DECL(test_SSL_CIPHER_get_xxx), @@ -66150,7 +66525,9 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_CTX_use_certificate_buffer), TEST_DECL(test_wolfSSL_CTX_use_PrivateKey_file), TEST_DECL(test_wolfSSL_CTX_load_verify_locations), + /* Large number of memory allocations. */ TEST_DECL(test_wolfSSL_CTX_load_system_CA_certs), + TEST_DECL(test_wolfSSL_CertManagerCheckOCSPResponse), TEST_DECL(test_wolfSSL_CheckOCSPResponse), TEST_DECL(test_wolfSSL_CertManagerLoadCABuffer), @@ -66178,22 +66555,27 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_CTX_der_load_verify_locations), TEST_DECL(test_wolfSSL_CTX_enable_disable), TEST_DECL(test_wolfSSL_CTX_ticket_API), - TEST_DECL(test_server_wolfSSL_new), - TEST_DECL(test_client_wolfSSL_new), TEST_DECL(test_wolfSSL_SetTmpDH_file), TEST_DECL(test_wolfSSL_SetTmpDH_buffer), TEST_DECL(test_wolfSSL_SetMinMaxDhKey_Sz), TEST_DECL(test_SetTmpEC_DHE_Sz), TEST_DECL(test_wolfSSL_CTX_get0_privatekey), TEST_DECL(test_wolfSSL_dtls_set_mtu), + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_dtls_plaintext), #if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ defined(HAVE_IO_TESTS_DEPENDENCIES) TEST_DECL(test_wolfSSL_read_write), + /* Can't memory test as server hangs if client fails before second connect. + */ TEST_DECL(test_wolfSSL_reuse_WOLFSSLobj), - TEST_DECL(test_wolfSSL_CTX_verifyDepth_ServerClient), + TEST_DECL(test_wolfSSL_CTX_verifyDepth_ServerClient_1), + TEST_DECL(test_wolfSSL_CTX_verifyDepth_ServerClient_2), + TEST_DECL(test_wolfSSL_CTX_verifyDepth_ServerClient_3), TEST_DECL(test_wolfSSL_CTX_set_cipher_list), + /* Can't memory test as server hangs. */ TEST_DECL(test_wolfSSL_dtls_export), + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_tls_export), #endif TEST_DECL(test_wolfSSL_SetMinVersion), @@ -66203,6 +66585,7 @@ TEST_CASE testCases[] = { #ifdef HAVE_IO_TESTS_DEPENDENCIES #ifdef HAVE_SNI TEST_DECL(test_wolfSSL_UseSNI_params), + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_UseSNI_connection), TEST_DECL(test_wolfSSL_SNI_GetFromBuffer), #endif /* HAVE_SNI */ @@ -66212,10 +66595,12 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_UseTruncatedHMAC), TEST_DECL(test_wolfSSL_UseSupportedCurve), #if defined(HAVE_ALPN) && defined(HAVE_IO_TESTS_DEPENDENCIES) + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_UseALPN_connection), TEST_DECL(test_wolfSSL_UseALPN_params), #endif #ifdef HAVE_ALPN_PROTOS_SUPPORT + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_set_alpn_protos), #endif TEST_DECL(test_wolfSSL_DisableExtendedMasterSecret), @@ -66224,6 +66609,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_tls_ext_duplicate), #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) TEST_DECL(test_wolfSSL_Tls13_ECH_params), + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_Tls13_ECH), #endif @@ -66238,6 +66624,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_URI), TEST_DECL(test_wolfSSL_TBS), TEST_DECL(test_wolfSSL_X509_verify), + /* Uses Assert in handshake callback. */ TEST_DECL(test_wolfSSL_X509_TLS_version), TEST_DECL(test_wc_PemToDer), @@ -66290,6 +66677,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_ASN1_TYPE), TEST_DECL(test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS), + /* Converted above to use Expect unless where stated. */ /* compatibility tests */ TEST_DECL(test_wolfSSL_lhash), TEST_DECL(test_wolfSSL_X509_NAME), @@ -67256,13 +67644,15 @@ static double gettime_secs(void) } #endif -void ApiTest(void) +int ApiTest(void) { int i; int ret; + int res = 0; #ifndef WOLFSSL_UNIT_TEST_NO_TIMING double timeDiff; #endif + EXPECT_DECLS; printf(" Begin API Tests\n"); fflush(stdout); @@ -67270,46 +67660,56 @@ void ApiTest(void) /* we must perform init and cleanup if not all tests are running */ if (!testAll) { #ifdef WOLFCRYPT_ONLY - wolfCrypt_Init(); + if (wolfCrypt_Init() != 0) { + printf("wolfCrypt Initialization failed\n"); + res = 1; + } #else - wolfSSL_Init(); + if (wolfSSL_Init() != WOLFSSL_SUCCESS) { + printf("wolfSSL Initialization failed\n"); + res = 1; + } #endif } - for (i = 0; i < TEST_CASE_CNT; ++i) { - /* When not testing all cases then skip if not marked for running. */ - if (!testAll && !testCases[i].run) { - continue; - } - - TestSetup(); + if (res == 0) { + for (i = 0; i < TEST_CASE_CNT; ++i) { + /* When not testing all cases then skip if not marked for running. + */ + if (!testAll && !testCases[i].run) { + continue; + } - printf(" %3d: %-52s:", i + 1, testCases[i].name); - fflush(stdout); - #ifndef WOLFSSL_UNIT_TEST_NO_TIMING - timeDiff = gettime_secs(); - #endif - ret = testCases[i].func(); - #ifndef WOLFSSL_UNIT_TEST_NO_TIMING - timeDiff = gettime_secs() - timeDiff; - #endif - #ifndef WOLFSSL_UNIT_TEST_NO_TIMING - if (ret != TEST_SKIPPED) { - printf(" %s (%9.5lf)\n", apitest_res_string(ret), timeDiff); - } - else - #endif - { - printf(" %s\n", apitest_res_string(ret)); - } - fflush(stdout); - /* if return code is < 0 and not skipped then assert error */ - Assert((ret > 0 || ret == TEST_SKIPPED), - ("Test failed\n"), - ("ret %d", ret)); + TestSetup(); + printf(" %3d: %-52s:", i + 1, testCases[i].name); + fflush(stdout); + #ifndef WOLFSSL_UNIT_TEST_NO_TIMING + timeDiff = gettime_secs(); + #endif + ret = testCases[i].func(); + #ifndef WOLFSSL_UNIT_TEST_NO_TIMING + timeDiff = gettime_secs() - timeDiff; + #endif + #ifndef WOLFSSL_UNIT_TEST_NO_TIMING + if (ret != TEST_SKIPPED) { + printf(" %s (%9.5lf)\n", apitest_res_string(ret), timeDiff); + } + else + #endif + { + printf(" %s\n", apitest_res_string(ret)); + } + fflush(stdout); + /* if return code is < 0 and not skipped then assert error */ + Expect((ret > 0 || ret == TEST_SKIPPED), + ("Test failed\n"), + ("ret %d", ret)); + testCases[i].fail = ((ret <= 0) && (ret != TEST_SKIPPED)); + res |= ((ret <= 0) && (ret != TEST_SKIPPED)); - TestCleanup(); + TestCleanup(); + } } #if defined(HAVE_ECC) && defined(FP_ECC) && defined(HAVE_THREAD_LS) \ @@ -67327,6 +67727,18 @@ void ApiTest(void) (void)testDevId; + if (res != 0) { + printf("\nFAILURES:\n"); + for (i = 0; i < TEST_CASE_CNT; ++i) { + if (testCases[i].fail) { + printf(" %3d: %s\n", i + 1, testCases[i].name); + } + } + printf("\n"); + fflush(stdout); + } + printf(" End API Tests\n"); fflush(stdout); + return res; } diff --git a/tests/unit.c b/tests/unit.c index bfb629cae63..0f54f7a72e2 100644 --- a/tests/unit.c +++ b/tests/unit.c @@ -34,6 +34,7 @@ int allTesting = 1; +int apiTesting = 1; int myoptind = 0; char* myoptarg = NULL; int unit_test(int argc, char** argv); @@ -185,21 +186,26 @@ int unit_test(int argc, char** argv) goto exit; } else if (XSTRCMP(argv[1], "--api") == 0) { + allTesting = 0; + } + else if (XSTRCMP(argv[1], "--no-api") == 0) { + apiTesting = 0; } else if (argv[1][1] >= '0' && argv[1][1] <= '9') { ret = ApiTest_RunIdx(atoi(argv[1] + 1)); if (ret != 0) { goto exit; } + allTesting = 0; } else { ret = ApiTest_RunName(argv[1] + 1); if (ret != 0) { goto exit; } + allTesting = 0; } - allTesting = 0; argc--; argv++; } @@ -208,7 +214,11 @@ int unit_test(int argc, char** argv) if (argc == 1) #endif { - ApiTest(); + if (apiTesting) { + ret = ApiTest(); + if (ret != 0) + goto exit; + } if (!allTesting) { goto exit; diff --git a/tests/unit.h b/tests/unit.h index 1801df4dd01..cce5257df41 100644 --- a/tests/unit.h +++ b/tests/unit.h @@ -122,10 +122,111 @@ #define AssertPtrLE(x, y) AssertPtr(x, y, <=, >) +#define EXPECT_DECLS \ + int _ret = 0 +#define EXPECT_RESULT() \ + ((_ret == 0) ? TEST_SUCCESS : TEST_FAIL) +#define EXPECT_SUCCESS() \ + (_ret == 0) +#define EXPECT_FAIL() \ + (_ret != 0) + +#define ExpFail(description, result) do { \ + printf("\nERROR - %s line %d failed with:", __FILE__, __LINE__); \ + fputs("\n expected: ", stdout); printf description; \ + fputs("\n result: ", stdout); printf result; fputs("\n\n", stdout); \ + fflush(stdout); \ + _ret = -1; \ +} while (0) + +#define Expect(test, description, result) \ + if ((_ret == 0) && (!(test))) ExpFail(description, result) + +#define ExpectTrue(x) Expect( (x), ("%s is true", #x), (#x " => FALSE")) +#define ExpectFalse(x) Expect(!(x), ("%s is false", #x), (#x " => TRUE")) +#define ExpectNotNull(x) Expect( (x), ("%s is not null", #x), (#x " => NULL")) + +#define ExpectNull(x) do { \ + if (_ret == 0) { \ + PEDANTIC_EXTENSION void* _x = (void*)(x); \ + Expect(!_x, ("%s is null", #x), (#x " => %p", _x)); \ + } \ +} while(0) + +#define ExpectInt(x, y, op, er) do { \ + if (_ret == 0) { \ + int _x = (int)(x); \ + int _y = (int)(y); \ + Expect(_x op _y, ("%s " #op " %s", #x, #y), ("%d " #er " %d", _x, _y));\ + } \ +} while(0) + +#define ExpectIntEQ(x, y) ExpectInt(x, y, ==, !=) +#define ExpectIntNE(x, y) ExpectInt(x, y, !=, ==) +#define ExpectIntGT(x, y) ExpectInt(x, y, >, <=) +#define ExpectIntLT(x, y) ExpectInt(x, y, <, >=) +#define ExpectIntGE(x, y) ExpectInt(x, y, >=, <) +#define ExpectIntLE(x, y) ExpectInt(x, y, <=, >) + +#define ExpectStr(x, y, op, er) do { \ + if (_ret == 0) { \ + const char* _x = (const char*)(x); \ + const char* _y = (const char*)(y); \ + int _z = (_x && _y) ? strcmp(_x, _y) : -1; \ + Expect(_z op 0, ("%s " #op " %s", #x, #y), \ + ("\"%s\" " #er " \"%s\"", _x, _y));\ + } \ +} while(0) + +#define ExpectStrEQ(x, y) ExpectStr(x, y, ==, !=) +#define ExpectStrNE(x, y) ExpectStr(x, y, !=, ==) +#define ExpectStrGT(x, y) ExpectStr(x, y, >, <=) +#define ExpectStrLT(x, y) ExpectStr(x, y, <, >=) +#define ExpectStrGE(x, y) ExpectStr(x, y, >=, <) +#define ExpectStrLE(x, y) ExpectStr(x, y, <=, >) + +#define ExpectPtr(x, y, op, er) do { \ + if (_ret == 0) { \ + PRAGMA_GCC_DIAG_PUSH; \ + /* remarkably, without this inhibition, */ \ + /* the _Pragma()s make the declarations warn. */ \ + PRAGMA_GCC("GCC diagnostic ignored \"-Wdeclaration-after-statement\"");\ + /* inhibit "ISO C forbids conversion of function pointer */ \ + /* to object pointer type [-Werror=pedantic]" */ \ + PRAGMA_GCC("GCC diagnostic ignored \"-Wpedantic\""); \ + void* _x = (void*)(x); \ + void* _y = (void*)(y); \ + Expect(_x op _y, ("%s " #op " %s", #x, #y), ("%p " #er " %p", _x, _y));\ + PRAGMA_GCC_DIAG_POP; \ + } \ +} while(0) + +#define ExpectPtrEq(x, y) ExpectPtr(x, y, ==, !=) +#define ExpectPtrNE(x, y) ExpectPtr(x, y, !=, ==) +#define ExpectPtrGT(x, y) ExpectPtr(x, y, >, <=) +#define ExpectPtrLT(x, y) ExpectPtr(x, y, <, >=) +#define ExpectPtrGE(x, y) ExpectPtr(x, y, >=, <) +#define ExpectPtrLE(x, y) ExpectPtr(x, y, <=, >) + +#define ExpectBuf(x, y, z, op, er) do { \ + if (_ret == 0) { \ + const byte* _x = (const byte*)(x); \ + const byte* _y = (const byte*)(y); \ + int _z = (int)(z); \ + int _w = ((_x) && (_y)) ? XMEMCMP(_x, _y, _z) : -1; \ + Expect(_w op 0, ("%s " #op " %s for %s", #x, #y, #z), \ + ("\"%p\" " #er " \"%p\" for \"%d\"", _x, _y, _z));\ + } \ +} while(0) + +#define ExpectBufEQ(x, y, z) ExpectBuf(x, y, z, ==, !=) +#define ExpectBufNE(x, y, z) ExpectBuf(x, y, z, !=, ==) + + void ApiTest_PrintTestCases(void); int ApiTest_RunIdx(int idx); int ApiTest_RunName(char* name); -void ApiTest(void); +int ApiTest(void); int SuiteTest(int argc, char** argv); int HashTest(void); diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 192ab09aeaa..a1897c00a98 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -15390,15 +15390,18 @@ static int ConfirmSignature(SignatureCtx* sigCtx, sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey), sigCtx->heap, DYNAMIC_TYPE_RSA); - sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap, - DYNAMIC_TYPE_SIGNATURE); - if (sigCtx->key.rsa == NULL || sigCtx->sigCpy == NULL) { + if (sigCtx->key.rsa == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap, sigCtx->devId)) != 0) { goto exit_cs; } + sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap, + DYNAMIC_TYPE_SIGNATURE); + if (sigCtx->sigCpy == NULL) { + ERROR_OUT(MEMORY_E, exit_cs); + } if (sigSz > MAX_ENCODED_SIG_SZ) { WOLFSSL_MSG("Verify Signature is too big"); ERROR_OUT(BUFFER_E, exit_cs); diff --git a/wolfcrypt/src/memory.c b/wolfcrypt/src/memory.c index 83a23ad7928..ce98b437639 100644 --- a/wolfcrypt/src/memory.c +++ b/wolfcrypt/src/memory.c @@ -24,10 +24,6 @@ #include #endif -#ifdef WOLFSSL_LINUXKM - #define WOLFSSL_NEED_LINUX_CURRENT -#endif - #include /* check old macros @wc_fips */ @@ -55,6 +51,8 @@ Possible memory options: * WOLFSSL_MALLOC_CHECK: Reports malloc or alignment failure using WOLFSSL_STATIC_ALIGN * WOLFSSL_FORCE_MALLOC_FAIL_TEST: Used for internal testing to induce random malloc failures. * WOLFSSL_HEAP_TEST: Used for internal testing of heap hint + * WOLFSSL_MEM_FAIL_COUNT: Fail memory allocation at a count from + * environment variable: MEM_FAIL_CNT. */ #ifdef WOLFSSL_ZEPHYR @@ -264,6 +262,50 @@ void wc_MemZero_Check(void* addr, size_t len) } #endif /* WOLFSSL_CHECK_MEM_ZERO */ +#ifdef WOLFSSL_MEM_FAIL_COUNT +static wolfSSL_Mutex memFailMutex; +int mem_fail_allocs = 0; +int mem_fail_frees = 0; +int mem_fail_cnt = 0; + +void wc_MemFailCount_Init() +{ + wc_InitMutex(&memFailMutex); + char* cnt = getenv("MEM_FAIL_CNT"); + if (cnt != NULL) { + fprintf(stderr, "MemFailCount At: %d\n", mem_fail_cnt); + mem_fail_cnt = atoi(cnt); + } +} +static int wc_MemFailCount_AllocMem(void) +{ + int ret = 1; + + wc_LockMutex(&memFailMutex); + if ((mem_fail_cnt > 0) && (mem_fail_cnt <= mem_fail_allocs + 1)) { + ret = 0; + } + else { + mem_fail_allocs++; + } + wc_UnLockMutex(&memFailMutex); + + return ret; +} +static void wc_MemFailCount_FreeMem(void) +{ + wc_LockMutex(&memFailMutex); + mem_fail_frees++; + wc_UnLockMutex(&memFailMutex); +} +void wc_MemFailCount_Free() +{ + wc_FreeMutex(&memFailMutex); + fprintf(stderr, "MemFailCount Total: %d\n", mem_fail_allocs); + fprintf(stderr, "MemFailCount Frees: %d\n", mem_fail_frees); +} +#endif + #ifdef WOLFSSL_DEBUG_MEMORY void* wolfSSL_Malloc(size_t size, const char* func, unsigned int line) #else @@ -272,6 +314,13 @@ void* wolfSSL_Malloc(size_t size) { void* res = 0; +#ifdef WOLFSSL_MEM_FAIL_COUNT + if (!wc_MemFailCount_AllocMem()) { + WOLFSSL_MSG("MemFailCnt: Fail malloc"); + return NULL; + } +#endif + #ifdef WOLFSSL_CHECK_MEM_ZERO /* Space for requested size. */ size += MEM_ALIGN; @@ -365,6 +414,9 @@ void wolfSSL_Free(void *ptr) /* Check that the pointer is zero where required. */ wc_MemZero_Check(((unsigned char*)ptr) + MEM_ALIGN, *(size_t*)ptr); #endif +#ifdef WOLFSSL_MEM_FAIL_COUNT + wc_MemFailCount_FreeMem(); +#endif if (free_function) { #ifdef WOLFSSL_DEBUG_MEMORY @@ -417,6 +469,13 @@ void* wolfSSL_Realloc(void *ptr, size_t size) #else void* res = 0; +#ifdef WOLFSSL_MEM_FAIL_COUNT + if (!wc_MemFailCount_AllocMem()) { + WOLFSSL_MSG("MemFailCnt: Fail realloc"); + return NULL; + } +#endif + if (realloc_function) { #ifdef WOLFSSL_DEBUG_MEMORY res = realloc_function(ptr, size, func, line); @@ -432,6 +491,12 @@ void* wolfSSL_Realloc(void *ptr, size_t size) #endif } +#ifdef WOLFSSL_MEM_FAIL_COUNT + if (ptr != NULL) { + wc_MemFailCount_FreeMem(); + } +#endif + return res; #endif } @@ -1245,6 +1310,13 @@ void *xmalloc(size_t n, void* heap, int type, const char* func, void* p = NULL; word32* p32; +#ifdef WOLFSSL_MEM_FAIL_COUNT + if (!wc_MemFailCount_AllocMem()) { + WOLFSSL_MSG("MemFailCnt: Fail malloc"); + return NULL; + } +#endif + if (malloc_function) p32 = malloc_function(n + sizeof(word32) * 4); else @@ -1270,6 +1342,13 @@ void *xrealloc(void *p, size_t n, void* heap, int type, const char* func, word32* oldp32 = NULL; word32 oldLen; +#ifdef WOLFSSL_MEM_FAIL_COUNT + if (!wc_MemFailCount_AllocMem()) { + WOLFSSL_MSG("MemFailCnt: Fail malloc"); + return NULL; + } +#endif + if (p != NULL) { oldp32 = (word32*)p; oldp32 -= 4; @@ -1293,6 +1372,12 @@ void *xrealloc(void *p, size_t n, void* heap, int type, const char* func, type, func, file, line); } +#ifdef WOLFSSL_MEM_FAIL_COUNT + if (p != NULL) { + wc_MemFailCount_FreeMem(); + } +#endif + (void)heap; return newp; @@ -1303,6 +1388,9 @@ void xfree(void *p, void* heap, int type, const char* func, const char* file, word32* p32 = (word32*)p; if (p != NULL) { + #ifdef WOLFSSL_MEM_FAIL_COUNT + wc_MemFailCount_FreeMem(); + #endif p32 -= 4; fprintf(stderr, "Free: %p -> %u (%d) at %s:%s:%u\n", p, p32[0], type, diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index 1d0e935d28f..7b387e1515d 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -144,6 +144,9 @@ int wolfCrypt_Init(void) * must be freed. */ wc_MemZero_Init(); #endif + #ifdef WOLFSSL_MEM_FAIL_COUNT + wc_MemFailCount_Init(); + #endif #ifdef WOLFSSL_FORCE_MALLOC_FAIL_TEST { @@ -474,6 +477,9 @@ int wolfCrypt_Cleanup(void) Entropy_Final(); #endif + #ifdef WOLFSSL_MEM_FAIL_COUNT + wc_MemFailCount_Free(); + #endif #ifdef WOLFSSL_CHECK_MEM_ZERO /* Free the mutex for access to the list of memory locations that * must be freed. */ diff --git a/wolfssl/test.h b/wolfssl/test.h index 5bd9aea8f8c..8dac9e4ec46 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -2930,12 +2930,13 @@ static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) wolfSSL_X509_get_subject_name(peer), 0, 0); printf("\tPeer's cert info:\n issuer : %s\n subject: %s\n", issuer, subject); - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - /* preverify needs to be self-signer error for Qt compat. - * Should be ASN_SELF_SIGNED_E */ - if (XSTRCMP(issuer, subject) == 0 && preverify == ASN_NO_SIGNER_E) - return 0; + if (issuer != NULL && subject != NULL) { + /* preverify needs to be self-signer error for Qt compat. + * Should be ASN_SELF_SIGNED_E */ + if (XSTRCMP(issuer, subject) == 0 && preverify == ASN_NO_SIGNER_E) + return 0; + } #endif XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL); diff --git a/wolfssl/wolfcrypt/memory.h b/wolfssl/wolfcrypt/memory.h index 969a0c26e56..15978b83765 100644 --- a/wolfssl/wolfcrypt/memory.h +++ b/wolfssl/wolfcrypt/memory.h @@ -238,6 +238,11 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, __cyg_profile_func_exit(void *func, void *caller); #endif /* WOLFSSL_STACK_LOG */ +#ifdef WOLFSSL_MEM_FAIL_COUNT +WOLFSSL_LOCAL void wc_MemFailCount_Init(void); +WOLFSSL_LOCAL void wc_MemFailCount_Free(void); +#endif + #ifdef WOLFSSL_CHECK_MEM_ZERO WOLFSSL_LOCAL void wc_MemZero_Init(void); WOLFSSL_LOCAL void wc_MemZero_Free(void); From 08295f2f90dc634f36fb57b3b61a80f38653cfe4 Mon Sep 17 00:00:00 2001 From: dell5060 Date: Wed, 24 May 2023 17:29:04 -0600 Subject: [PATCH 335/391] added test case for wolfSSL_configure_args and added fix new fix removing redundant () in code --- tests/api.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/api.c b/tests/api.c index a427e2de937..12f095531d9 100644 --- a/tests/api.c +++ b/tests/api.c @@ -66477,6 +66477,16 @@ static int test_dtls_ipv6_check(void) return TEST_SKIPPED; } #endif + +static int test_wolfSSL_configure_args(void) +{ +#if defined(LIBWOLFSSL_CONFIGURE_ARGS) && defined(HAVE_WC_INTROSPECTION) + AssertNotNull(wolfSSL_configure_args()); + return TEST_SUCCESS; +#else + return TEST_SKIPPED; +#endif +} /*----------------------------------------------------------------------------* | Main *----------------------------------------------------------------------------*/ @@ -66742,6 +66752,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_wc_ERR_remove_state), TEST_DECL(test_wc_ERR_print_errors_fp), #endif + TEST_DECL(test_wolfSSL_configure_args), TEST_DECL(test_wolfSSL_set_options), TEST_DECL(test_wolfSSL_sk_SSL_CIPHER), TEST_DECL(test_wolfSSL_set1_curves_list), From e4b077b570a19cd5002f25684692375c2b56eb7a Mon Sep 17 00:00:00 2001 From: jordan Date: Tue, 30 May 2023 11:36:43 -0500 Subject: [PATCH 336/391] Used codespell and fixed obvious typos in src and wolfssl. --- src/internal.c | 4 ++-- src/ssl_asn1.c | 6 +++--- src/ssl_bn.c | 6 +++--- src/tls13.c | 2 +- src/wolfio.c | 2 +- src/x509.c | 2 +- wolfssl/internal.h | 2 +- wolfssl/test.h | 2 +- wolfssl/wolfcrypt/asn_public.h | 2 +- wolfssl/wolfcrypt/settings.h | 2 +- 10 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/internal.c b/src/internal.c index 5f4988f6297..1acb926f553 100644 --- a/src/internal.c +++ b/src/internal.c @@ -33350,7 +33350,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (alertType != invalid_alert) { int err; - /* propogate socket errors to avoid re-calling send alert */ + /* propagate socket errors to avoid re-calling send alert */ err = SendAlert(ssl, alert_fatal, alertType); if (err == SOCKET_ERROR_E) ret = SOCKET_ERROR_E; @@ -34886,7 +34886,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, byte bogusID[ID_LEN]; byte bogusIDSz = ssl->session->sessionIDSz; XMEMCPY(bogusID, ssl->session->sessionID, ID_LEN); - /* Failure here should not interupt the resumption. We already have + /* Failure here should not interrupt the resumption. We already have * all the cipher material we need in `it` */ WOLFSSL_MSG("Copying in session from passed in arg"); (void)wolfSSL_DupSession(sess, ssl->session, 1); diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 53503ee2d9a..d285dffea14 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -2382,7 +2382,7 @@ char* wolfSSL_i2s_ASN1_STRING(WOLFSSL_v3_ext_method *method, } } else { - /* Convert unreadable strings to hexdecimal. */ + /* Convert unreadable strings to hexadecimal. */ ret = wolfssl_asn1_string_to_hex_chars(s); } @@ -2833,7 +2833,7 @@ static int wolfssl_asn1_string_dump_hex(WOLFSSL_BIO *bio, /* Calculate end of string. */ end = str->data + str->length - 1; for (p = str->data; p <= end; p++) { - /* Encode string characther as hex into temporary. */ + /* Encode string character as hex into temporary. */ ByteToHexStr((byte)*p, hex_tmp); /* Update count of written characters. */ str_len += 2; @@ -2853,7 +2853,7 @@ static int wolfssl_asn1_string_dump_hex(WOLFSSL_BIO *bio, * @param [in] c Character to check for. * @param [in] str String to check. * @return 1 when character found. - * @return 0 when characther not found. + * @return 0 when character not found. */ static int wolfssl_check_esc_char(char c) { diff --git a/src/ssl_bn.c b/src/ssl_bn.c index ffc0179e1ff..4cdacbd6466 100644 --- a/src/ssl_bn.c +++ b/src/ssl_bn.c @@ -1777,7 +1777,7 @@ int wolfSSL_BN_mod_add(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *a, ret = 0; } - /* Perfom operation with wolfCrypt. */ + /* Perform operation with wolfCrypt. */ if ((ret == 1) && (mp_addmod((mp_int*)a->internal, (mp_int*)b->internal, (mp_int*)m->internal, (mp_int*)r->internal) != MP_OKAY)) { WOLFSSL_MSG("mp_add_d error"); @@ -1973,7 +1973,7 @@ int wolfSSL_BN_gcd(WOLFSSL_BIGNUM* r, WOLFSSL_BIGNUM* a, WOLFSSL_BIGNUM* b, * @param [in] top Whether top bits must be set. * Valid values: WOLFSSL_BN_RAND_TOP_ANY, * WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_TOP_TWO. - * @param [in] botttom Whether bottom bit must be set. + * @param [in] bottom Whether bottom bit must be set. * Valid values: WOLFSSL_BN_RAND_BOTTOM_ANY, WOLFSSL_BN_RAND_BOTTOM_ODD. * @return 1 on success. @@ -2081,7 +2081,7 @@ int wolfSSL_BN_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) * @param [in] top Whether top bits must be set. * Valid values: WOLFSSL_BN_RAND_TOP_ANY, * WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_TOP_TWO. - * @param [in] botttom Whether bottom bit must be set. + * @param [in] bottom Whether bottom bit must be set. * Valid values: WOLFSSL_BN_RAND_BOTTOM_ANY, WOLFSSL_BN_RAND_BOTTOM_ODD. * @return 1 on success. diff --git a/src/tls13.c b/src/tls13.c index 7deac91e84a..f1a9e6b9400 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -2165,7 +2165,7 @@ static void AddTls13HandShakeHeader(byte* output, word32 length, (void)ssl; #ifdef WOLFSSL_DTLS13 - /* message_hash type is used for a syntetic message that replaces the first + /* message_hash type is used for a synthetic message that replaces the first ClientHello in the hash transcript when using HelloRetryRequest. It will never be transmitted and, as the DTLS-only fields must not be considered when computing the hash transcript, we can avoid to use the DTLS diff --git a/src/wolfio.c b/src/wolfio.c index 4ee1605c82f..1e4d0adb8cf 100644 --- a/src/wolfio.c +++ b/src/wolfio.c @@ -57,7 +57,7 @@ Possible IO enable options: * indefinetely. If not enabled EmbedReceiveFrom will return timeout after * DTLS_RECEIVEFROM_MAX_INVALID_PEER number of packets from invalid peers. When * enabled, without a timer, EmbedReceivefrom can't check if the timeout is - * expired and it may never return under a continous flow of invalid packets. + * expired and it may never return under a continuous flow of invalid packets. * default: off */ diff --git a/src/x509.c b/src/x509.c index 6f5e095d3c8..9ced66eee74 100644 --- a/src/x509.c +++ b/src/x509.c @@ -9500,7 +9500,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( if (ret == WOLFSSL_SUCCESS) { for (idx = 0; idx < req->customExtCount; idx++) { - /* Note that ownership is NOT transfered. + /* Note that ownership is NOT transferred. * req->custom_exts buffers still need to be cleaned * up. */ cert->customCertExt[idx] = req->custom_exts[idx]; diff --git a/wolfssl/internal.h b/wolfssl/internal.h index a8ed9f36714..781d6c1c8ba 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -3241,7 +3241,7 @@ typedef struct KeyShareEntry { byte* pubKey; /* Public key */ word32 pubKeyLen; /* Public key length */ #if !defined(NO_DH) || defined(HAVE_PQC) - byte* privKey; /* Private key - DH ond PQ KEMs only */ + byte* privKey; /* Private key - DH and PQ KEMs only */ #endif #ifdef WOLFSSL_ASYNC_CRYPT int lastRet; diff --git a/wolfssl/test.h b/wolfssl/test.h index 8dac9e4ec46..06794334322 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -3767,7 +3767,7 @@ static WC_INLINE int myEccSharedSecret(WOLFSSL* ssl, ecc_key* otherKey, #endif pubKey = otherKey; - /* TLS v1.2 and older we must generate a key here for the client ony. + /* TLS v1.2 and older we must generate a key here for the client only. * TLS v1.3 calls key gen early with key share */ if (wolfSSL_GetVersion(ssl) < WOLFSSL_TLSV1_3) { ret = myEccKeyGen(ssl, privKey, 0, otherKey->dp->id, ctx); diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index 7e8b8f52e59..903d087389d 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -985,7 +985,7 @@ typedef struct Asn1 { Asn1Item item; /* Current depth of ASN.1 item. */ unsigned char depth; - /* End indeces of ASN.1 items at different depths. */ + /* End indices of ASN.1 items at different depths. */ word32 end_idx[ASN_MAX_DEPTH]; /* Buffer to print. */ diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index d18ddcc3124..d5b1553ab7c 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -1855,7 +1855,7 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_CAAM_HASH #endif #if defined(WOLFSSL_DEVCRYPTO_HMAC) - /* HMAC is throught the devcrypto calls */ + /* HMAC is through the devcrypto calls */ #define WOLFSSL_CAAM_HMAC #endif From fc28bbe3e80df86ea3d720a80406c7424c222c5f Mon Sep 17 00:00:00 2001 From: kaleb-himes Date: Tue, 30 May 2023 10:36:01 -0600 Subject: [PATCH 337/391] Checkin STARCORE project OE52_OE54_ACVP effort --- IDE/STARCORE/README.txt | 5 + IDE/STARCORE/include.am | 13 + IDE/STARCORE/starcore_test.c | 379 +++++++++++++++++++++ IDE/STARCORE/user_settings.h | 640 +++++++++++++++++++++++++++++++++++ IDE/include.am | 1 + 5 files changed, 1038 insertions(+) create mode 100644 IDE/STARCORE/README.txt create mode 100644 IDE/STARCORE/include.am create mode 100644 IDE/STARCORE/starcore_test.c create mode 100644 IDE/STARCORE/user_settings.h diff --git a/IDE/STARCORE/README.txt b/IDE/STARCORE/README.txt new file mode 100644 index 00000000000..d024934dbae --- /dev/null +++ b/IDE/STARCORE/README.txt @@ -0,0 +1,5 @@ +Please refer to the provided +wolfssl-X.X.X-commercial-fips-432b-v2/v4.3.2b-SP-and-user-guide/*.pdf +for FIPS validated build instructions. + + diff --git a/IDE/STARCORE/include.am b/IDE/STARCORE/include.am new file mode 100644 index 00000000000..7120d5bfdbd --- /dev/null +++ b/IDE/STARCORE/include.am @@ -0,0 +1,13 @@ +# vim:ft=automake +# included from Top Level Makefile.am +# All paths should be given relative to the root +# +# NOTE: append_wolfssl_git_version.sh is not included as the +# distribution file set will not contain GitHub info +# +# + +EXTRA_DIST+= IDE/STARCORE/README.txt +EXTRA_DIST+= IDE/STARCORE/starcore_test.c +EXTRA_DIST+= IDE/STARCORE/user_settings.h + diff --git a/IDE/STARCORE/starcore_test.c b/IDE/STARCORE/starcore_test.c new file mode 100644 index 00000000000..a8ef00af14b --- /dev/null +++ b/IDE/STARCORE/starcore_test.c @@ -0,0 +1,379 @@ +/* starcore_test.c + * + * Copyright (C) 2006-2023 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + + +#include + +#include +#ifndef WOLFSSL_USER_SETTINGS + #error "USER SETTINGS not set" +#endif +#include +#include +#include +#include +#include +#ifdef HAVE_FIPS + #include + /* #include */ + #if 1 + #include + #endif +#endif + +typedef struct test_func_args { + int argc; + char** argv; + int return_code; +} test_func_args; + +#ifdef HAVE_FIPS + static void appFipsCb(int ok, int err, const char* hash) + { + printf("in appFipsCb Fips callback, ok = %d, err = %d\n", ok, err); + fflush(stdout); + printf("message = %s\n", wc_GetErrorString(err)); + fflush(stdout); + printf("hash = %s\n", hash); + fflush(stdout); + + if (err == IN_CORE_FIPS_E) { + printf("In core integrity hash check failure, copy above hash\n"); + fflush(stdout); + printf("into verifyCore[] in fips_test.c and rebuild\n"); + fflush(stdout); + } + fflush(stdout); + } +#endif + +int my_rng_generate_seed(unsigned char* output, int sz) +{ + unsigned int i; + long t; + + time(&t); /* init */ + srand(t); /* init */ + for (i = 0; i < sz; i++) { + output[i] = (unsigned char) rand(); + } + return 0; +} + +#define SAMPLE_SIZE 32 +int simpleRngTest(void) +{ + WC_RNG rng; + int ret; + char block[SAMPLE_SIZE] = {0}; + + ret = wc_InitRng(&rng); + if (ret != 0) { + printf("Failed to init RNG with return %d\n", ret); + fflush(stdout); + return ret; + } + + ret = wc_RNG_GenerateBlock(&rng, (byte*) block, SAMPLE_SIZE); + /* This should trigger FIPS callback if the hash needs updated */ + printf("ret from wc_RNG_GenerateBlock was %d\n", ret); + fflush(stdout); + return ret; +} + +#define FILE_PATH_LEN 160 +/* The directory used to hold the vector files, update accordingly */ +#define FIXED_PATH "../../../../fips/wolfACVP/wolfSSL-14699641-PRODUCTION/" + +void reset_path(char* fName) { + memset(fName, 0, FILE_PATH_LEN); + strncpy(fName, FIXED_PATH, strlen(FIXED_PATH)); +} + +#if 0 +/* Disable when not processing vector files */ +int process_a_file(char* fName) +{ + int ret = 0; + test_func_args args = {0}; + char* argIn[3] = {0}; + argIn[0] = "wolfacvp_client"; + argIn[1] = "-i"; + argIn[2] = fName; +#if 0 + argIn[3] = "-K"; /* Remove this when processing vectors from the lab, + * we don't know the answers to those */ + args.argc = 4; /* change to 3 when processing vectors from the lab */ +#else + args.argc = 3; +#endif + args.argv = argIn; + printf("Case: START\n"); + ret = wolfacvp_harness(args.argc, args.argv); + if (ret != 0) { + printf("Result of wolfCrypt harness is %d\n", ret); fflush(stdout); + } else { + printf("Case: END\n"); + } + return ret; +} +#endif + +void check_ret(int ret) +{ + if(ret != 0) { + exit(-1); + } +} + +int testharness_main() +{ + int ret = -1; + int* CpuidAddr=(int*) 0xFFF28028; + + printf("The CPU ID is stored at 0xFFF28028 and it's value is %04x\n", *CpuidAddr); + +#ifdef HAVE_FIPS + wolfCrypt_SetCb_fips(appFipsCb); + /* fipsEntry(); */ /* Prior to Vortec Scheduler was called here, call is + * now at the vortec Scheduler level during Core Init + */ +#endif + + ret = simpleRngTest(); + + if (ret == 0) { + + /* uncomment to see performance */ + #if 0 /* Benchmark */ + printf("Kicking off the benchmark\n"); fflush(stdout); + ret = benchmark_test(NULL); + printf("Result of wolfCrypt benchmark is %d\n", ret); fflush(stdout); + #endif + +#if 0 /* File-based Harness */ + #ifdef HAVE_FIPS + char* testFN = "grep-for-this-file.txt"; + char* testStr = "This is my test string, hello from STARCORE!\n"; + char path[FILE_PATH_LEN] = {0}; + FILE* fstream = fopen(testFN, "wb"); + + strncpy(path, FIXED_PATH, strlen(FIXED_PATH)); + + #if 0 /* Crypto Tests */ + printf("Running testwolfcrypt on starcore\n"); fflush(stdout); + wolfcrypt_test(NULL); + #endif + + if (fstream == NULL) { + printf("Failed to open testFN\n"); + } else { + ret = fwrite(testStr, 1, strlen(testStr), fstream); + printf("Wrote %d bytes to fstream\n", ret); + fclose(fstream); + } +#if 0 /* PRODUCTION VECTORS */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19392-vectorSets-215826.json")); reset_path(path); /* AES-ECB */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19392-vectorSets-215827.json")); reset_path(path); /* AES-CBC */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19392-vectorSets-215828.json")); reset_path(path); /* AES-CTR */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19397-vectorSets-215833.json")); reset_path(path); /* ECDSA keyGen */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19397-vectorSets-215834.json")); reset_path(path); /* ECDSA keyVer */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19397-vectorSets-215835.json")); reset_path(path); /* ECDSA sigGen */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19397-vectorSets-215836.json")); reset_path(path); /* ECDSA sigVer */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215845.json")); reset_path(path); /* HMAC-SHA1 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215846.json")); reset_path(path); /* HMAC-SHA2-224 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215847.json")); reset_path(path); /* HMAC-SHA2-256 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215848.json")); reset_path(path); /* HMAC-SHA2-384 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215849.json")); reset_path(path); /* HMAC-SHA2-512 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215850.json")); reset_path(path); /* HMAC-SHA3-224 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215851.json")); reset_path(path); /* HMAC-SHA3-256 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215852.json")); reset_path(path); /* HMAC-SHA3-384 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19400-vectorSets-215853.json")); reset_path(path); /* HMAC-SHA3-512 */ + process_a_file(strcat(path, "acvp-v1-testSessions-19404-vectorSets-215857.json")); reset_path(path); /* RSA keyGen */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19404-vectorSets-215858.json")); reset_path(path); /* RSA sigGen */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19404-vectorSets-215859.json")); reset_path(path); /* RSA sigVer */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19404-vectorSets-215860.json")); reset_path(path); /* RSA decPrim */ + //process_a_file(strcat(path, "acvp-v1_testSessions_19395_vectorSets_215831.json")); reset_path(path); /* hashDRBG */ + //process_a_file(strcat(path, "acvp-v1_testSessions_19396_vectorSets_215832.json")); reset_path(path); /* DSA */ + //process_a_file(strcat(path, "acvp-v1_testSessions_19401_vectorSets_215854.json")); reset_path(path); /* KAS-ECC */ + //process_a_file(strcat(path, "acvp-v1_testSessions_19402_vectorSets_215855.json")); reset_path(path); /* KAS-ECC-SSC */ + //process_a_file(strcat(path, "acvp-v1_testSessions_19403_vectorSets_215856.json")); reset_path(path); /* KAS-FFC-SSC */ + //process_a_file(strcat(path, "acvp-v1_testSessions_19407_vectorSets_215870.json")); reset_path(path); /* TDES */ + //process_a_file(strcat(path, "acvp-v1_testSessions_19394_vectorSets_215830.json")); reset_path(path); /* CMAC_AES */ + //process_a_file(strcat(path, "acvp-v1_testSessions_19393_vectorSets_215829.json")); reset_path(path); /* AES-CCM */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19398-vectorSets-215837.json")); reset_path(path); /* AES-GCM */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19398-vectorSets-215838.json")); reset_path(path); /* AES-GCM */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19398-vectorSets-215839.json")); reset_path(path); /* AES-GCM */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19398-vectorSets-215840.json")); reset_path(path); /* AES-GCM */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19399-vectorSets-215841.json")); reset_path(path); /* AES-GMAC */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19399-vectorSets-215842.json")); reset_path(path); /* AES-GMAC */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19399-vectorSets-215843.json")); reset_path(path); /* AES-GMAC */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19399-vectorSets-215844.json")); reset_path(path); /* AES-GMAC */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19405-vectorSets-215861.json")); reset_path(path); /* SHA-1 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19406-vectorSets-215866.json")); reset_path(path); /* SHA3-224 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19406-vectorSets-215867.json")); reset_path(path); /* SHA3-256 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19406-vectorSets-215868.json")); reset_path(path); /* SHA3-384 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19406-vectorSets-215869.json")); reset_path(path); /* SHA3-512 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19405-vectorSets-215862.json")); reset_path(path); /* SHA2-224*/ + //process_a_file(strcat(path, "acvp-v1-testSessions-19405-vectorSets-215863.json")); reset_path(path); /* SHA2-256 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19405-vectorSets-215864.json")); reset_path(path); /* SHA2-384 */ + //process_a_file(strcat(path, "acvp-v1-testSessions-19405-vectorSets-215865.json")); reset_path(path); /* SHA2-512 */ +#endif +#if 0 /* DEMO VECTORS */ + //process_a_file(strcat(path, "acvp-v1-testSessions-365458-vectorSets-1479140.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365458-vectorSets-1479141.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365458-vectorSets-1479142.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365465-vectorSets-1479149.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365465-vectorSets-1479150.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365465-vectorSets-1479151.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365465-vectorSets-1479152.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365467-vectorSets-1479154.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365467-vectorSets-1479155.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365467-vectorSets-1479156.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365467-vectorSets-1479157.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365469-vectorSets-1479161.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365469-vectorSets-1479162.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365469-vectorSets-1479163.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365469-vectorSets-1479164.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479170.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479171.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479172.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479173.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479174.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479175.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479176.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479177.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365473-vectorSets-1479178.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365485-vectorSets-1479194.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365485-vectorSets-1479195.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365485-vectorSets-1479196.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365485-vectorSets-1479197.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365488-vectorSets-1479202.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365488-vectorSets-1479203.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365488-vectorSets-1479204.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365488-vectorSets-1479205.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365488-vectorSets-1479206.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365490-vectorSets-1479211.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365490-vectorSets-1479212.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365490-vectorSets-1479213.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1-testSessions-365490-vectorSets-1479214.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1_testSessions_365459_vectorSets_1479143.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1_testSessions_365461_vectorSets_1479145.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1_testSessions_365462_vectorSets_1479146.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1_testSessions_365463_vectorSets_1479147.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1_testSessions_365481_vectorSets_1479190.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1_testSessions_365483_vectorSets_1479192.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1_testSessions_365484_vectorSets_1479193.json")); reset_path(path); + //process_a_file(strcat(path, "acvp-v1_testSessions_365491_vectorSets_1479215.json")); reset_path(path); +#endif + +#if 0 /* VECTORS that passed previously (sanity check before asking FIPS lab + to send vectors) */ + +/* ------------------------------------------------------------------- */ + process_a_file(strcat(path, "hashDRBG_47251.json"));// Success + process_a_file(strcat(path, "AES_CBC_47242.json")); // Failed to allocate buffer large enough for file, fixed by chopping into smaller sections + process_a_file(strcat(path, "AES_CCM_47247.json")); // Failed, increase stack/heap + process_a_file(strcat(path, "AES_CCM_47247-part1.json")); // Failed to write out the entire response (got 104 of 370 tgId's in the response) + process_a_file(strcat(path, "AES_CCM_47247-part2.json")); // Failed ot write out the entire response (started at 371 and got to 429 of 741 tgId's in the response) looks like alloc failures, increase HEAP + process_a_file(strcat(path, "DSA_keyGen_47253.json")); // Success + process_a_file(strcat(path, "RSA_DecPrim_47306.json")); // Success + process_a_file(strcat(path, "ECDSA_sigVer_47258.json")); // Success + process_a_file(strcat(path, "AES_CMAC_47249.json")); // Success + process_a_file(strcat(path, "AES_CTR_47243.json")); // Success + process_a_file(strcat(path, "AES_ECB_47241.json")); // Success + process_a_file(strcat(path, "AES_GCM_external_8_2_1_47263.json")); // Success + process_a_file(strcat(path, "AES_GCM_external_8_2_2_47265.json")); // Success + process_a_file(strcat(path, "AES_GCM_internal_8_2_1_47267.json")); // Success + process_a_file(strcat(path, "AES_GCM_internal_8_2_2_47269.json")); // Success + process_a_file(strcat(path, "AES_GMAC_external_8_2_1_47271.json")); // Failed to alloc response (passed but couldn't output), use smaller chunks + process_a_file(strcat(path, "AES_CMAC_47249.json")); // Success + process_a_file(strcat(path, "AES_CTR_47243.json")); // Success + process_a_file(strcat(path, "AES_CBC_47242.json")); // Success + process_a_file(strcat(path, "AES_CCM_47247.json")); // Success + process_a_file(strcat(path, "AES_CMAC_47249.json")); // Success + process_a_file(strcat(path, "AES_CTR_47243.json")); // Success + process_a_file(strcat(path, "AES_ECB_47241.json")); // Success + process_a_file(strcat(path, "AES_GCM_external_8_2_1_47263.json")); // Success + process_a_file(strcat(path, "AES_GCM_external_8_2_2_47265.json")); // Success + process_a_file(strcat(path, "AES_GCM_internal_8_2_1_47267.json")); // Success + process_a_file(strcat(path, "AES_GCM_internal_8_2_2_47269.json")); // Success + process_a_file(strcat(path, "AES_GMAC_external_8_2_1_47271.json")); // Success + process_a_file(strcat(path, "AES_GMAC_external_8_2_2_47273.json")); // Success + process_a_file(strcat(path, "AES_GMAC_internal_8_2_1_47275.json")); // Success + process_a_file(strcat(path, "AES_GMAC_internal_8_2_2_47277.json")); // Success + process_a_file(strcat(path, "ECDSA_keyGen_47255.json")); // Success + process_a_file(strcat(path, "ECDSA_keyVer_47256.json")); // Success + process_a_file(strcat(path, "ECDSA_sigGen_47257.json")); // Success + process_a_file(strcat(path, "HMAC_SHA1_47279.json")); // Success + process_a_file(strcat(path, "HMAC_SHA2_224_47280.json")); // Success + process_a_file(strcat(path, "HMAC_SHA2_256_47281.json")); // Success + process_a_file(strcat(path, "HMAC_SHA2_384_47282.json")); // Success + process_a_file(strcat(path, "HMAC_SHA2_512_47283.json")); // Success + process_a_file(strcat(path, "HMAC_SHA3_224_47284.json")); // Success + process_a_file(strcat(path, "HMAC_SHA3_256_47285.json")); // Success + process_a_file(strcat(path, "HMAC_SHA3_384_47286.json")); // Success + process_a_file(strcat(path, "HMAC_SHA3_512_47287.json")); // Success + process_a_file(strcat(path, "KAS_ECC_47299.json")); // Success + process_a_file(strcat(path, "KAS_ECC_CDH_Component_47297.json")); // Success + process_a_file(strcat(path, "KAS_ECC_SSC_652956.json")); // Success + process_a_file(strcat(path, "KAS_FFC_47301.json")); // Success + process_a_file(strcat(path, "KAS_FFC_SSC_652957.json")); // Success + process_a_file(strcat(path, "RSA_keyGen_47303.json")); // Success + process_a_file(strcat(path, "RSA_sigGen_47304.json")); // Success + process_a_file(strcat(path, "RSA_sigVer_47305.json")); // Success + process_a_file(strcat(path, "SHA1_47311.json")); // Success + process_a_file(strcat(path, "SHA2_224_47312.json")); // Success + process_a_file(strcat(path, "SHA2_256_47313.json")); // Success + process_a_file(strcat(path, "SHA2_384_47314.json")); // Success + process_a_file(strcat(path, "SHA2_512_47315.json")); // Success + process_a_file(strcat(path, "SHA3_224_47321.json")); // Success + process_a_file(strcat(path, "SHA3_256_47322.json")); // Success + process_a_file(strcat(path, "SHA3_384_47323.json")); // Success + process_a_file(strcat(path, "SHA3_512_47324.json")); // Success +#endif + + #endif /* HAVE_FIPS */ +#endif /* Harness if */ + + #if 1 /* optest */ + #ifdef HAVE_FIPS +#define VALUES_LEN 15 + int i; + + printf("Kicking off the operational test app\n"); fflush(stdout); + { + int values[VALUES_LEN] = { 0, -203, -204, -205, -206, -207, -208, -209, -210, -242, -256, -257, + -258, -259, 0 }; + for (i = 0; i < VALUES_LEN; i++) { + ret = op_test(values[i], 0); + printf("ret from running case %d = %d\n", values[i], ret); fflush(stdout); + } + } + #endif /* HAVE_FIPS */ + #endif /* optest if */ + } else { + printf("Skipping test until hash is updated\n"); fflush(stdout); + } + wolfCrypt_Cleanup(); + return 0; +} + diff --git a/IDE/STARCORE/user_settings.h b/IDE/STARCORE/user_settings.h new file mode 100644 index 00000000000..8be26569771 --- /dev/null +++ b/IDE/STARCORE/user_settings.h @@ -0,0 +1,640 @@ +/* user_settings.h +* +* Copyright (C) 2006-2023 wolfSSL Inc. +* +* This file is part of wolfSSL. +* +* wolfSSL is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2 of the License, or +* (at your option) any later version. +* +* wolfSSL is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA +*/ + +/* Custom wolfSSL user settings for Vortec Scheduler, + * VxWorks 6.9 and VxWorks 7.0 */ + +#ifndef WOLFSSL_USER_SETTINGS_H +#define WOLFSSL_USER_SETTINGS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------------------------------------------------------- */ +/* Platform */ +/* ------------------------------------------------------------------------- */ +#undef WOLFSSL_GENERAL_ALIGNMENT +#define WOLFSSL_GENERAL_ALIGNMENT 4 + +/* Platform */ +#undef WOLFSSL_STARCORE +#define WOLFSSL_STARCORE + +/* Endianess */ +#undef BIG_ENDIAN_ORDER +#define BIG_ENDIAN_ORDER + +#undef WOLFSSL_SMALL_STACK +#define WOLFSSL_SMALL_STACK + +#undef WOLFSSL_USER_IO +/* #define WOLFSSL_USER_IO */ + +#undef SINGLE_THREADED +#define SINGLE_THREADED + +/* ------------------------------------------------------------------------- */ +/* Math Configuration */ +/* ------------------------------------------------------------------------- */ +#undef SIZEOF_LONG_LONG +#define SIZEOF_LONG_LONG 8 + +#undef SIZEOF_LONG +#define SIZEOF_LONG 4 + +#undef USE_FAST_MATH +#if 1 + #define USE_FAST_MATH + + #undef TFM_TIMING_RESISTANT + #define TFM_TIMING_RESISTANT + + /* Optimizations (footprint) */ + #define WOLFCRYPT_ONLY + #define TFM_NO_ASM +#endif + +#if 0 + #define WOLFSSL_SP + #define WOLFSSL_SP_SMALL + #define WOLFSSL_HAVE_SP_RSA + #define WOLFSSL_HAVE_SP_DH + #define WOLFSSL_HAVE_SP_ECC +#endif + +/* ------------------------------------------------------------------------- */ +/* FIPS - Requires eval or license from wolfSSL */ +/* ------------------------------------------------------------------------- */ +#undef HAVE_FIPS +#if 1 + #define HAVE_FIPS + + #undef HAVE_FIPS_VERSION + #define HAVE_FIPS_VERSION 2 + + #ifdef SINGLE_THREADED + #undef NO_THREAD_LS + #define NO_THREAD_LS + #endif + + #if 1 + #undef NO_ATTRIBUTE_CONSTRUCTOR + #define NO_ATTRIBUTE_CONSTRUCTOR + #endif +#endif + + +/* ------------------------------------------------------------------------- */ +/* Crypto */ +/* ------------------------------------------------------------------------- */ +/* RSA */ +#undef NO_RSA +#if 1 + #ifdef USE_FAST_MATH + /* Maximum math bits (Max RSA key bits * 2) */ + #undef FP_MAX_BITS + #define FP_MAX_BITS 8192 + #endif + + /* half as much memory but twice as slow */ + #undef RSA_LOW_MEM + #define RSA_LOW_MEM + + /* Enables blinding mode, to prevent timing attacks */ + #if 0 + #undef WC_RSA_BLINDING + #define WC_RSA_BLINDING + #else + #undef WC_NO_HARDEN + #define WC_NO_HARDEN + #endif + + /* RSA PSS Support */ + #if 1 + #define WC_RSA_PSS + #endif + + #if 1 + #define WC_RSA_NO_PADDING + #endif +#else + #define NO_RSA +#endif + +/* ECC */ +#undef HAVE_ECC +#if 1 + #define HAVE_ECC + + /* Manually define enabled curves */ + #undef ECC_USER_CURVES + #define ECC_USER_CURVES + + #ifdef ECC_USER_CURVES + /* Manual Curve Selection */ + #define HAVE_ECC192 + #define HAVE_ECC224 + #undef NO_ECC256 + #define HAVE_ECC384 + #define HAVE_ECC521 + #endif + + /* Fixed point cache (speeds repeated operations against same private key) */ + #undef FP_ECC + /* #define FP_ECC */ + + #ifdef FP_ECC + /* Bits / Entries */ + #undef FP_ENTRIES + #define FP_ENTRIES 2 + #undef FP_LUT + #define FP_LUT 4 + #endif + + /* Optional ECC calculation method */ + /* Note: doubles heap usage, but slightly faster */ + #undef ECC_SHAMIR + /* #define ECC_SHAMIR */ + + /* Reduces heap usage, but slower */ + #undef ECC_TIMING_RESISTANT + #define ECC_TIMING_RESISTANT + + #ifdef HAVE_FIPS + #undef HAVE_ECC_CDH + #define HAVE_ECC_CDH /* Enable cofactor support */ + + #undef NO_STRICT_ECDSA_LEN + #define NO_STRICT_ECDSA_LEN /* Do not force fixed len w/ FIPS */ + + #undef WOLFSSL_VALIDATE_ECC_IMPORT + #define WOLFSSL_VALIDATE_ECC_IMPORT /* Validate import */ + #endif + + /* Compressed Key Support */ + #undef HAVE_COMP_KEY + /* #define HAVE_COMP_KEY */ + + /* Use alternate ECC size for ECC math */ + #ifdef USE_FAST_MATH + /* MAX ECC BITS = ROUND8(MAX ECC) * 2 */ + #ifdef NO_RSA + /* Custom fastmath size if not using RSA */ + #undef FP_MAX_BITS + #define FP_MAX_BITS (256 * 2) + #else + #undef ALT_ECC_SIZE + #define ALT_ECC_SIZE + /* wolfSSL will compute the FP_MAX_BITS_ECC, but it can be overriden */ + /* #undef FP_MAX_BITS_ECC */ + /* #define FP_MAX_BITS_ECC (256 * 2) */ + #endif + + /* Speedups specific to curve */ + #ifndef NO_ECC256 + #undef TFM_ECC256 + #define TFM_ECC256 + #endif + #endif +#endif + +/* DH */ +#undef NO_DH +#if 1 + /* Use table for DH instead of -lm (math) lib dependency */ + #if 1 + #define WOLFSSL_DH_CONST + #define HAVE_FFDHE_2048 + #define HAVE_FFDHE_3072 + #define HAVE_FFDHE_4096 + /* #define HAVE_FFDHE_6144 */ + /* #define HAVE_FFDHE_8192 */ + #endif + + #ifdef HAVE_FIPS + #define WOLFSSL_VALIDATE_FFC_IMPORT + #define HAVE_FFDHE_Q + #endif +#else + #define NO_DH +#endif + + +/* AES */ +#undef NO_AES +#if 1 + #undef HAVE_AES_CBC + #define HAVE_AES_CBC + + #undef HAVE_AESGCM + #define HAVE_AESGCM + + /* GCM Method: GCM_SMALL, GCM_WORD32 or GCM_TABLE */ + /* #define GCM_SMALL */ + /* #define GCM_WORD32 */ + #define GCM_TABLE + + #undef WOLFSSL_AES_DIRECT + #define WOLFSSL_AES_DIRECT + + #undef HAVE_AES_ECB + #define HAVE_AES_ECB + + #undef WOLFSSL_AES_COUNTER + #define WOLFSSL_AES_COUNTER + + #undef HAVE_AESCCM + #define HAVE_AESCCM +#else + #define NO_AES +#endif + + +/* DES3 */ +#undef NO_DES3 +#if 1 + /* No change */ +#else + #define NO_DES3 +#endif + +/* ChaCha20 / Poly1305 */ +#undef HAVE_CHACHA +#undef HAVE_POLY1305 +#if 0 + #define HAVE_CHACHA + #define HAVE_POLY1305 + + /* Needed for Poly1305 */ + #undef HAVE_ONE_TIME_AUTH + #define HAVE_ONE_TIME_AUTH +#endif + +/* Ed25519 / Curve25519 */ +#undef HAVE_CURVE25519 +#undef HAVE_ED25519 +#if 0 + #define HAVE_CURVE25519 + #define HAVE_ED25519 /* ED25519 Requires SHA512 */ + + /* Optionally use small math (less flash usage, but much slower) */ + #if 1 + #define CURVED25519_SMALL + #endif +#endif + + +/* ------------------------------------------------------------------------- */ +/* Hashing */ +/* ------------------------------------------------------------------------- */ +/* Sha */ +#undef NO_SHA +#if 1 + /* 1k smaller, but 25% slower */ + /* #define USE_SLOW_SHA */ +#else + #define NO_SHA +#endif + +/* Sha256 */ +#undef NO_SHA256 +#if 1 + /* not unrolled - ~2k smaller and ~25% slower */ + /* #define USE_SLOW_SHA256 */ + + /* Sha224 */ + #if 1 + #define WOLFSSL_SHA224 + #endif +#else + #define NO_SHA256 +#endif + +/* Sha512 */ +#undef WOLFSSL_SHA512 +#if 1 + #define WOLFSSL_SHA512 + + /* Sha384 */ + #undef WOLFSSL_SHA384 + #if 1 + #define WOLFSSL_SHA384 + #endif + + /* over twice as small, but 50% slower */ + /* #define USE_SLOW_SHA512 */ +#endif + +/* Sha3 */ +#undef WOLFSSL_SHA3 +#if 1 + #define WOLFSSL_SHA3 +#endif + +/* MD5 */ +#undef NO_MD5 +#if 1 + /* No change */ +#else + #define NO_MD5 +#endif + +/* HKDF */ +#undef HAVE_HKDF +#if 1 + #define HAVE_HKDF +#endif + +/* CMAC */ +#undef WOLFSSL_CMAC +#if 1 + #define WOLFSSL_CMAC +#endif + + +/* ------------------------------------------------------------------------- */ +/* Benchmark / Test */ +/* ------------------------------------------------------------------------- */ +/* Use reduced benchmark / test sizes */ +#undef BENCH_EMBEDDED +#define BENCH_EMBEDDED + +#undef USE_CERT_BUFFERS_2048 +#define USE_CERT_BUFFERS_2048 + +#undef USE_CERT_BUFFERS_1024 +/* #define USE_CERT_BUFFERS_1024 */ + +#undef USE_CERT_BUFFERS_256 +#define USE_CERT_BUFFERS_256 + +#undef FORCE_BUFFER_TEST +#define FORCE_BUFFER_TEST + + +/* ------------------------------------------------------------------------- */ +/* Debugging */ +/* ------------------------------------------------------------------------- */ + +#undef DEBUG_WOLFSSL +#undef NO_ERROR_STRINGS +#if 0 + #define DEBUG_WOLFSSL +#else + #if 1 + #define NO_ERROR_STRINGS + #endif +#endif + + +/* ------------------------------------------------------------------------- */ +/* Memory */ +/* ------------------------------------------------------------------------- */ + +/* Override Memory API's */ +#if 0 + #undef XMALLOC_OVERRIDE + #define XMALLOC_OVERRIDE + + /* prototypes for user heap override functions */ + /* Note: Realloc only required for normal math */ + #include /* for size_t */ + extern void *myMalloc(size_t n, void* heap, int type); + extern void myFree(void *p, void* heap, int type); + extern void *myRealloc(void *p, size_t n, void* heap, int type); + + #define XMALLOC(n, h, t) myMalloc(n, h, t) + #define XFREE(p, h, t) myFree(p, h, t) + #define XREALLOC(p, n, h, t) myRealloc(p, n, h, t) +#endif + +#if 0 + /* Static memory requires fast math */ + #define WOLFSSL_STATIC_MEMORY + + /* Disable fallback malloc/free */ + #define WOLFSSL_NO_MALLOC + #if 1 + #define WOLFSSL_MALLOC_CHECK /* trap malloc failure */ + #endif +#endif + +/* Memory callbacks */ +#if 1 + #undef USE_WOLFSSL_MEMORY + #define USE_WOLFSSL_MEMORY + + /* Use this to measure / print heap usage */ + #if 0 + #undef WOLFSSL_TRACK_MEMORY + /* #define WOLFSSL_TRACK_MEMORY */ + + #undef WOLFSSL_DEBUG_MEMORY + /* #define WOLFSSL_DEBUG_MEMORY */ + + #undef WOLFSSL_DEBUG_MEMORY_PRINT + /* #define WOLFSSL_DEBUG_MEMORY_PRINT */ + #endif +#else + #ifndef WOLFSSL_STATIC_MEMORY + #define NO_WOLFSSL_MEMORY + /* Otherwise we will use stdlib malloc, free and realloc */ + #endif +#endif + +/* ------------------------------------------------------------------------- */ +/* RNG */ +/* ------------------------------------------------------------------------- */ + +/* Seed Source */ +/* Seed Source */ +#if 1 + extern int my_rng_generate_seed(unsigned char* output, int sz); + #undef CUSTOM_RAND_GENERATE_SEED + #define CUSTOM_RAND_GENERATE_SEED my_rng_generate_seed +#endif + +/* NETOS */ +#if 0 + extern unsigned char get_byte_from_pool(void); + #define CUSTOM_RAND_GENERATE get_byte_from_pool + #define CUSTOM_RAND_TYPE unsigned char +#endif + +/* Choose RNG method */ +#if 1 + /* Use built-in P-RNG (SHA256 based) with HW RNG */ + /* P-RNG + HW RNG (P-RNG is ~8K) */ + /* #define WOLFSSL_GENSEED_FORTEST */ + #undef HAVE_HASHDRBG + #define HAVE_HASHDRBG +#else + #undef WC_NO_HASHDRBG + #define WC_NO_HASHDRBG + + /* Bypass P-RNG and use only HW RNG */ + extern int my_rng_gen_block(unsigned char* output, unsigned int sz); + #undef CUSTOM_RAND_GENERATE_BLOCK + #define CUSTOM_RAND_GENERATE_BLOCK my_rng_gen_block +#endif + +/* ------------------------------------------------------------------------- */ +/* Enable Features */ +/* ------------------------------------------------------------------------- */ +#undef WOLFSSL_TLS13 +#if 0 + #define WOLFSSL_TLS13 +#endif + +#undef WOLFSSL_KEY_GEN +#if 1 + #define WOLFSSL_KEY_GEN +#endif + +#if defined(HAVE_FIPS) && !defined(WOLFSSL_KEY_GEN) + #define WOLFSSL_OLD_PRIME_CHECK +#endif + +#undef KEEP_PEER_CERT +/* #define KEEP_PEER_CERT */ + +#undef HAVE_COMP_KEY +/* #define HAVE_COMP_KEY */ + +#undef HAVE_TLS_EXTENSIONS +/* #define HAVE_TLS_EXTENSIONS */ + +#undef HAVE_SUPPORTED_CURVES +/* #define HAVE_SUPPORTED_CURVES */ + +#undef WOLFSSL_BASE64_ENCODE +#define WOLFSSL_BASE64_ENCODE + +/* TLS Session Cache */ +#if 0 + #define SMALL_SESSION_CACHE +#else + #define NO_SESSION_CACHE +#endif + + +/* ------------------------------------------------------------------------- */ +/* Disable Features */ +/* ------------------------------------------------------------------------- */ +#undef NO_WOLFSSL_SERVER +/* #define NO_WOLFSSL_SERVER */ + +#undef NO_WOLFSSL_CLIENT +/* #define NO_WOLFSSL_CLIENT */ + +#undef NO_CRYPT_TEST +/* #define NO_CRYPT_TEST */ + +#undef NO_CRYPT_BENCHMARK +/* #define NO_CRYPT_BENCHMARK */ + +/* In-lining of misc.c functions */ +/* If defined, must include wolfcrypt/src/misc.c in build */ +/* Slower, but about 1k smaller */ +#undef NO_INLINE +/* #define NO_INLINE */ + +#undef NO_FILESYSTEM +/* #define NO_FILESYSTEM */ + +#undef NO_WRITE_TEMP_FILES +#define NO_WRITE_TEMP_FILES + +#undef NO_WOLFSSL_DIR +#define NO_WOLFSSL_DIR + +#undef NO_WRITEV +#define NO_WRITEV + +#undef WOLFSSL_NO_SOCK +#define WOLFSSL_NO_SOCK + +#undef NO_MAIN_DRIVER +#define NO_MAIN_DRIVER + +#undef NO_DEV_RANDOM +/* #define NO_DEV_RANDOM */ + +#undef NO_DSA +#define NO_DSA + +#undef NO_RC4 +#define NO_RC4 + +#undef NO_OLD_TLS +#define NO_OLD_TLS + +#undef NO_PSK +#define NO_PSK + +#undef NO_MD4 +#define NO_MD4 + +#undef WOLFSSL_NO_SHAKE128 +#define WOLFSSL_NO_SHAKE128 + +#undef WOLFSSL_NO_SHAKE256 +#define WOLFSSL_NO_SHAKE256 + +#undef NO_PWDBASED +/* #define NO_PWDBASED */ + +#undef NO_CODING +/* #define NO_CODING */ + +#undef NO_ASN_TIME +/* #define NO_ASN_TIME */ + +#undef NO_CERTS +/* #define NO_CERTS */ + +#undef NO_SIG_WRAPPER +/* #define NO_SIG_WRAPPER */ + +/* ACVP Testing ONLY specific settings */ +#if 0 + #define ACVP_NO_DIR_SUPPORT + /* #define DEBUG_ACVP_PRINTF */ + + #undef USE_UART_READ_LINE + /* #define USE_UART_READ_LINE */ + + #undef USE_SMALL_MONTE + /* #define USE_SMALL_MONTE */ + + #undef WOLFSSL_PUBLIC_MP + /* #define WOLFSSL_PUBLIC_MP */ + + #undef HAVE_FORCE_FIPS_FAILURE + #define HAVE_FORCE_FIPS_FAILURE +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* WOLFSSL_USER_SETTINGS_H */ diff --git a/IDE/include.am b/IDE/include.am index e8e94e820c6..379400d7ece 100644 --- a/IDE/include.am +++ b/IDE/include.am @@ -52,6 +52,7 @@ include IDE/zephyr/include.am include IDE/AURIX/include.am include IDE/MCUEXPRESSO/include.am include IDE/Espressif/include.am +include IDE/STARCORE/include.am EXTRA_DIST+= IDE/IAR-EWARM IDE/MDK-ARM IDE/MDK5-ARM IDE/MYSQL IDE/LPCXPRESSO IDE/HEXIWEAR IDE/Espressif EXTRA_DIST+= IDE/OPENSTM32/README.md From 04730779f5d443ac7ae25dd9c116078a3c487774 Mon Sep 17 00:00:00 2001 From: Anthony Hu Date: Tue, 30 May 2023 10:56:05 -0400 Subject: [PATCH 338/391] For NO_RSA, don't advertise support for RSA. --- src/internal.c | 4 ++++ src/tls.c | 2 ++ tests/api.c | 15 +++++++++------ 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/internal.c b/src/internal.c index 1acb926f553..e20d2c9c89c 100644 --- a/src/internal.c +++ b/src/internal.c @@ -3190,6 +3190,10 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, } #endif /* !NO_WOLFSSL_SERVER */ +#ifdef NO_RSA + haveRSAsig = 0; /* can't have RSA sig if don't have RSA */ +#endif + #ifdef WOLFSSL_DTLS if (pv.major == DTLS_MAJOR) { dtls = 1; diff --git a/src/tls.c b/src/tls.c index bf7e49f4d58..1e836cdd7d8 100644 --- a/src/tls.c +++ b/src/tls.c @@ -6853,8 +6853,10 @@ static word16 TLSX_SignatureAlgorithms_Write(void* data, byte* output) hashSigAlgoSz = sa->hashSigAlgoSz; } +#ifndef NO_RSA TLSX_SignatureAlgorithms_MapPss(sa->ssl, output + OPAQUE16_LEN, hashSigAlgoSz); +#endif return OPAQUE16_LEN + hashSigAlgoSz; } diff --git a/tests/api.c b/tests/api.c index 12f095531d9..3dc19db2861 100644 --- a/tests/api.c +++ b/tests/api.c @@ -64696,8 +64696,9 @@ static int test_wolfSSL_DTLS_fragment_buckets(void) #if !defined(NO_FILESYSTEM) && \ - defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ - !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) + defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ + !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ + !defined(NO_RSA) static int test_wolfSSL_dtls_stateless2(void) { @@ -64956,7 +64957,7 @@ static int test_wolfSSL_dtls_stateless_downgrade(void) #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ - !defined(NO_OLD_TLS) + !defined(NO_OLD_TLS) && !defined(NO_RSA) static int test_WOLFSSL_dtls_version_alert(void) { struct test_memio_ctx test_ctx; @@ -65011,7 +65012,7 @@ static int test_WOLFSSL_dtls_version_alert(void) } #endif /* defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && * !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && - * !defined(NO_OLD_TLS) + * !defined(NO_OLD_TLS) && !defined(NO_RSA) */ @@ -66303,7 +66304,7 @@ static int test_wolfSSL_dtls13_null_cipher(void) #endif #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ - !defined(SINGLE_THREADED) + !defined(SINGLE_THREADED) && !defined(NO_RSA) static int test_dtls_msg_get_connected_port(int fd, word16 *port) { @@ -66397,7 +66398,7 @@ static int test_dtls_msg_from_other_peer(void) } #endif /* defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ * !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ - * !defined(SINGLE_THREADED) */ + * !defined(SINGLE_THREADED) && !defined(NO_RSA) */ #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_IPV6) && \ !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ defined(HAVE_IO_TESTS_DEPENDENCIES) @@ -67513,10 +67514,12 @@ TEST_CASE testCases[] = { #ifdef HAVE_MAX_FRAGMENT TEST_DECL(test_wolfSSL_dtls_stateless_maxfrag), #endif /* HAVE_MAX_FRAGMENT */ +#ifndef NO_RSA TEST_DECL(test_wolfSSL_dtls_stateless2), #if !defined(NO_OLD_TLS) TEST_DECL(test_wolfSSL_dtls_stateless_downgrade), #endif /* !defined(NO_OLD_TLS) */ +#endif /* ! NO_RSA */ #endif /* defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ * !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) */ TEST_DECL(test_wolfSSL_CTX_set_ciphersuites), From ed335c5924bfff0ca0e5e2afe94e91d867af6865 Mon Sep 17 00:00:00 2001 From: John Bland Date: Thu, 25 May 2023 12:50:23 -0400 Subject: [PATCH 339/391] add ex functions to use other digest algorithms --- wolfcrypt/src/dsa.c | 22 +++++++++++++++++----- wolfssl/wolfcrypt/dsa.h | 4 ++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/wolfcrypt/src/dsa.c b/wolfcrypt/src/dsa.c index 625b6ae68c3..77d1ad5aca7 100644 --- a/wolfcrypt/src/dsa.c +++ b/wolfcrypt/src/dsa.c @@ -637,8 +637,14 @@ int wc_DsaExportKeyRaw(DsaKey* dsa, byte* x, word32* xSz, byte* y, word32* ySz) return err; } - int wc_DsaSign(const byte* digest, byte* out, DsaKey* key, WC_RNG* rng) +{ + /* use sha1 by default for backwards compatability */ + return wc_DsaSign_ex(digest, WC_SHA_DIGEST_SIZE, out, key, rng); +} + +int wc_DsaSign_ex(const byte* digest, word32 digestSz, byte* out, DsaKey* key, + WC_RNG* rng) { #ifdef WOLFSSL_SMALL_STACK mp_int *k = NULL; @@ -781,7 +787,7 @@ int wc_DsaSign(const byte* digest, byte* out, DsaKey* key, WC_RNG* rng) } /* generate H from sha digest */ - if (mp_read_unsigned_bin(H, digest,WC_SHA_DIGEST_SIZE) != MP_OKAY) { + if (mp_read_unsigned_bin(H, digest, digestSz) != MP_OKAY) { ret = MP_READ_E; break; } @@ -824,7 +830,7 @@ int wc_DsaSign(const byte* digest, byte* out, DsaKey* key, WC_RNG* rng) } /* set H from sha digest */ - if (mp_read_unsigned_bin(H, digest, WC_SHA_DIGEST_SIZE) != MP_OKAY) { + if (mp_read_unsigned_bin(H, digest, digestSz) != MP_OKAY) { ret = MP_READ_E; break; } @@ -964,8 +970,14 @@ int wc_DsaSign(const byte* digest, byte* out, DsaKey* key, WC_RNG* rng) return ret; } - int wc_DsaVerify(const byte* digest, const byte* sig, DsaKey* key, int* answer) +{ + /* use sha1 by default for backwards compatability */ + return wc_DsaVerify_ex(digest, WC_SHA_DIGEST_SIZE, sig, key, answer); +} + +int wc_DsaVerify_ex(const byte* digest, word32 digestSz, const byte* sig, + DsaKey* key, int* answer) { #ifdef WOLFSSL_SMALL_STACK mp_int *w = NULL; @@ -1029,7 +1041,7 @@ int wc_DsaVerify(const byte* digest, const byte* sig, DsaKey* key, int* answer) } /* put H into u1 from sha digest */ - if (mp_read_unsigned_bin(u1,digest,WC_SHA_DIGEST_SIZE) != MP_OKAY) { + if (mp_read_unsigned_bin(u1,digest, digestSz) != MP_OKAY) { ret = MP_READ_E; break; } diff --git a/wolfssl/wolfcrypt/dsa.h b/wolfssl/wolfcrypt/dsa.h index c6d0ec19d92..d5ae3a4f828 100644 --- a/wolfssl/wolfcrypt/dsa.h +++ b/wolfssl/wolfcrypt/dsa.h @@ -81,8 +81,12 @@ WOLFSSL_API int wc_InitDsaKey_h(DsaKey* key, void* h); WOLFSSL_API void wc_FreeDsaKey(DsaKey* key); WOLFSSL_API int wc_DsaSign(const byte* digest, byte* out, DsaKey* key, WC_RNG* rng); +WOLFSSL_API int wc_DsaSign_ex(const byte* digest, word32 digestSz, byte* out, + DsaKey* key, WC_RNG* rng); WOLFSSL_API int wc_DsaVerify(const byte* digest, const byte* sig, DsaKey* key, int* answer); +WOLFSSL_API int wc_DsaVerify_ex(const byte* digest, word32 digestSz, + const byte* sig, DsaKey* key, int* answer); WOLFSSL_API int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key, word32 inSz); WOLFSSL_API int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, From 4bf701b616b42689c517ee0015dc53c7f44d26d1 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 31 May 2023 15:17:01 -0500 Subject: [PATCH 340/391] wolfcrypt/src/memory.c: restore required linuxkm #define WOLFSSL_NEED_LINUX_CURRENT --- wolfcrypt/src/memory.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/wolfcrypt/src/memory.c b/wolfcrypt/src/memory.c index ce98b437639..f70206baf9f 100644 --- a/wolfcrypt/src/memory.c +++ b/wolfcrypt/src/memory.c @@ -24,6 +24,13 @@ #include #endif +#ifdef WOLFSSL_LINUXKM + /* inhibit "#undef current" in linuxkm_wc_port.h, included from wc_port.h, + * because needed in linuxkm_memory.c, included below. + */ + #define WOLFSSL_NEED_LINUX_CURRENT +#endif + #include /* check old macros @wc_fips */ From 481876f4fb30ad8d0ca0091ca0f73405cbeaafbc Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 31 May 2023 15:19:15 -0500 Subject: [PATCH 341/391] wolfssl/wolfcrypt/types.h: add PRAGMA_DIAG_PUSH, PRAGMA(), and PRAGMA_DIAG_POP(), using the gcc or clang variants as applicable, to facilitate pragmas to be used on both gcc and clang; tests/unit.h: fix ExpectPtr() to inhibit pedantic warnings on both gcc and clang; wolfssl/test.h: in myVerify(), explicitly check for nullness when printing issuer/subject, to avoid cppcheck null-deref warning; tests/api.c: fixes for: * myriad "embedding a directive within macro arguments is not portable" * an "ISO C forbids conversion of object pointer to function pointer type" * some "stringop-overflow"s * a clang-analyzer-core.uninitialized.Assign * a clang-analyzer-core.CallAndMessage "2nd function call argument is an uninitialized value" * a nullPointerRedundantCheck * several clang-diagnostic-declaration-after-statement * a spurious gcc sanitizer maybe-uninitialized in test_wolfSSL_CheckOCSPResponse() --- tests/api.c | 58 ++++++++++++++++++++------------------- tests/unit.h | 8 +++--- wolfssl/test.h | 5 ++-- wolfssl/wolfcrypt/types.h | 16 +++++++++++ 4 files changed, 53 insertions(+), 34 deletions(-) diff --git a/tests/api.c b/tests/api.c index 3dc19db2861..e992c6f5db6 100644 --- a/tests/api.c +++ b/tests/api.c @@ -1861,7 +1861,9 @@ static int test_wolfSSL_CheckOCSPResponse(void) OcspResponse* res = NULL; byte data[4096]; const unsigned char* pt; - int dataSz; + int dataSz = 0; /* initialize to mitigate spurious maybe-uninitialized from + * gcc sanitizer with --enable-heapmath. + */ XFILE f = XBADFILE; WOLFSSL_OCSP_BASICRESP* bs = NULL; WOLFSSL_X509_STORE* st = NULL; @@ -2128,16 +2130,15 @@ static int test_wolfSSL_CertManagerGetCerts(void) ExpectNull(sk = wolfSSL_CertManagerGetCerts(cm)); ExpectNotNull(der = wolfSSL_X509_get_der(cert1, &derSz)); - ExpectIntEQ(ret = wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, - WOLFSSL_FILETYPE_ASN1), #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) /* Check that ASN_SELF_SIGNED_E is returned for a self-signed cert for QT * and full OpenSSL compatibility */ - ASN_SELF_SIGNED_E + ExpectIntEQ(ret = wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + WOLFSSL_FILETYPE_ASN1), ASN_SELF_SIGNED_E); #else - ASN_NO_SIGNER_E + ExpectIntEQ(ret = wolfSSL_CertManagerVerifyBuffer(cm, der, derSz, + WOLFSSL_FILETYPE_ASN1), ASN_NO_SIGNER_E); #endif - ); ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CertManagerLoadCA(cm, "./certs/ca-cert.pem", NULL)); @@ -2186,13 +2187,12 @@ static int test_wolfSSL_CertManagerSetVerify(void) wolfSSL_CertManagerSetVerify(cm, myVerify); - ExpectIntEQ(ret = wolfSSL_CertManagerLoadCA(cm, ca_cert, NULL), #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER) - -1 + ExpectIntEQ(ret = wolfSSL_CertManagerLoadCA(cm, ca_cert, NULL), -1); #else - WOLFSSL_SUCCESS + ExpectIntEQ(ret = wolfSSL_CertManagerLoadCA(cm, ca_cert, NULL), + WOLFSSL_SUCCESS); #endif - ); /* Use the test CB that always accepts certs */ myVerifyAction = VERIFY_OVERRIDE_ERROR; @@ -2284,7 +2284,7 @@ static int test_wolfSSL_CertManagerNameConstraint(void) ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(ca_cert, WOLFSSL_FILETYPE_ASN1)); ExpectNotNull(pt = (byte*)wolfSSL_X509_get_tbs(x509, &derSz)); - if (der != NULL) { + if (EXPECT_SUCCESS() && (der != NULL)) { XMEMCPY(der, pt, derSz); /* find the name constraint extension and alter it */ @@ -3376,7 +3376,7 @@ static int test_wolfSSL_CTX_add1_chain_cert(void) defined(KEEP_OUR_CERT) && !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) EXPECT_DECLS; WOLFSSL_CTX* ctx; - WOLFSSL* ssl = NULL;; + WOLFSSL* ssl = NULL; const char *certChain[] = { "./certs/intermediate/client-int-cert.pem", "./certs/intermediate/ca-int2-cert.pem", @@ -6135,7 +6135,8 @@ void test_wolfSSL_client_server_nofail(callback_functions* client_cb, #if defined(OPENSSL_EXTRA) && !defined(NO_SESSION_CACHE) && \ !defined(WOLFSSL_NO_TLS12) && !defined(NO_WOLFSSL_CLIENT) -static void test_client_reuse_WOLFSSLobj(void* args, void *cb, void* server_args) +static void test_client_reuse_WOLFSSLobj(void* args, cbType cb, + void* server_args) { SOCKET_T sockfd = 0; callback_functions* cbf; @@ -6262,7 +6263,7 @@ static void test_client_reuse_WOLFSSLobj(void* args, void *cb, void* server_args } /* Build first session */ if (cb != NULL) - ((cbType)cb)(ctx, ssl); + cb(ctx, ssl); if (wolfSSL_write(ssl, msg, msgSz) != msgSz) { /*err_sys("SSL_write failed");*/ @@ -6326,7 +6327,7 @@ static void test_client_reuse_WOLFSSLobj(void* args, void *cb, void* server_args } /* Build first session */ if (cb != NULL) - ((cbType)cb)(ctx, ssl); + cb(ctx, ssl); if (wolfSSL_write(ssl, msg, msgSz) != msgSz) { /*err_sys("SSL_write failed");*/ @@ -9275,14 +9276,16 @@ static int test_wolfSSL_SNI_GetFromBuffer(void) ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), 0, result, &length)); - result[length] = 0; + if (EXPECT_RESULT() == TEST_SUCCESS) + result[length] = 0; ExpectStrEQ("www.paypal.com", (const char*) result); length = 32; ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SNI_GetFromBuffer(buff2, sizeof(buff2), 0, result, &length)); - result[length] = 0; + if (EXPECT_RESULT() == TEST_SUCCESS) + result[length] = 0; ExpectStrEQ("api.textmate.org", (const char*) result); /* SSL v2.0 tests */ @@ -11430,14 +11433,13 @@ static int test_wolfSSL_UseOCSPStapling(void) ExpectIntEQ(wolfSSL_UseOCSPStapling(NULL, WOLFSSL_CSR2_OCSP, WOLFSSL_CSR2_OCSP_USE_NONCE), BAD_FUNC_ARG); - ExpectIntEQ(wolfSSL_UseOCSPStapling(ssl, WOLFSSL_CSR2_OCSP, - WOLFSSL_CSR2_OCSP_USE_NONCE), #ifndef NO_WOLFSSL_CLIENT - 1 + ExpectIntEQ(wolfSSL_UseOCSPStapling(ssl, WOLFSSL_CSR2_OCSP, + WOLFSSL_CSR2_OCSP_USE_NONCE), 1); #else - BAD_FUNC_ARG + ExpectIntEQ(wolfSSL_UseOCSPStapling(ssl, WOLFSSL_CSR2_OCSP, + WOLFSSL_CSR2_OCSP_USE_NONCE), BAD_FUNC_ARG); #endif - ); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); @@ -11479,14 +11481,13 @@ static int test_wolfSSL_UseOCSPStaplingV2(void) ExpectIntEQ(wolfSSL_UseOCSPStaplingV2(NULL, WOLFSSL_CSR2_OCSP, WOLFSSL_CSR2_OCSP_USE_NONCE), BAD_FUNC_ARG); - ExpectIntEQ(wolfSSL_UseOCSPStaplingV2(ssl, WOLFSSL_CSR2_OCSP, - WOLFSSL_CSR2_OCSP_USE_NONCE), #ifndef NO_WOLFSSL_CLIENT - 1 + ExpectIntEQ(wolfSSL_UseOCSPStaplingV2(ssl, WOLFSSL_CSR2_OCSP, + WOLFSSL_CSR2_OCSP_USE_NONCE), 1); #else - BAD_FUNC_ARG + ExpectIntEQ(wolfSSL_UseOCSPStaplingV2(ssl, WOLFSSL_CSR2_OCSP, + WOLFSSL_CSR2_OCSP_USE_NONCE), BAD_FUNC_ARG); #endif - ); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); @@ -34870,7 +34871,8 @@ static int test_wc_KeyPemToDer(void) /* Test NULL for DER buffer to return needed DER buffer size */ ExpectIntGT(ret = wc_KeyPemToDer(cert_buf, cert_sz, NULL, 0, ""), 0); ExpectIntLE(ret, cert_sz); - cert_dersz = ret; + if (EXPECT_RESULT() == TEST_SUCCESS) + cert_dersz = ret; ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); ExpectIntGE(ret = wc_KeyPemToDer(cert_buf, cert_sz, cert_der, cert_dersz, cert_pw), 0); diff --git a/tests/unit.h b/tests/unit.h index cce5257df41..53e25ab7296 100644 --- a/tests/unit.h +++ b/tests/unit.h @@ -187,17 +187,17 @@ #define ExpectPtr(x, y, op, er) do { \ if (_ret == 0) { \ - PRAGMA_GCC_DIAG_PUSH; \ + PRAGMA_DIAG_PUSH; \ /* remarkably, without this inhibition, */ \ /* the _Pragma()s make the declarations warn. */ \ - PRAGMA_GCC("GCC diagnostic ignored \"-Wdeclaration-after-statement\"");\ + PRAGMA("GCC diagnostic ignored \"-Wdeclaration-after-statement\""); \ /* inhibit "ISO C forbids conversion of function pointer */ \ /* to object pointer type [-Werror=pedantic]" */ \ - PRAGMA_GCC("GCC diagnostic ignored \"-Wpedantic\""); \ + PRAGMA("GCC diagnostic ignored \"-Wpedantic\""); \ void* _x = (void*)(x); \ void* _y = (void*)(y); \ Expect(_x op _y, ("%s " #op " %s", #x, #y), ("%p " #er " %p", _x, _y));\ - PRAGMA_GCC_DIAG_POP; \ + PRAGMA_DIAG_POP; \ } \ } while(0) diff --git a/wolfssl/test.h b/wolfssl/test.h index 06794334322..49445bce6c5 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -2928,8 +2928,9 @@ static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) wolfSSL_X509_get_issuer_name(peer), 0, 0); char* subject = wolfSSL_X509_NAME_oneline( wolfSSL_X509_get_subject_name(peer), 0, 0); - printf("\tPeer's cert info:\n issuer : %s\n subject: %s\n", issuer, - subject); + printf("\tPeer's cert info:\n issuer : %s\n subject: %s\n", + issuer ? issuer : "[none]", + subject ? subject : "[none]"); #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) if (issuer != NULL && subject != NULL) { /* preverify needs to be self-signer error for Qt compat. diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 83f868dec2b..0298654c9fa 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -1379,6 +1379,9 @@ typedef struct w64wrapper { #define PRAGMA_GCC_DIAG_PUSH _Pragma("GCC diagnostic push") #define PRAGMA_GCC(str) _Pragma(str) #define PRAGMA_GCC_DIAG_POP _Pragma("GCC diagnostic pop") + #define PRAGMA_DIAG_PUSH PRAGMA_GCC_DIAG_PUSH + #define PRAGMA(str) PRAGMA_GCC(str) + #define PRAGMA_DIAG_POP PRAGMA_GCC_DIAG_POP #else #define PRAGMA_GCC_DIAG_PUSH #define PRAGMA_GCC(str) @@ -1389,12 +1392,25 @@ typedef struct w64wrapper { #define PRAGMA_CLANG_DIAG_PUSH _Pragma("clang diagnostic push") #define PRAGMA_CLANG(str) _Pragma(str) #define PRAGMA_CLANG_DIAG_POP _Pragma("clang diagnostic pop") + #define PRAGMA_DIAG_PUSH PRAGMA_CLANG_DIAG_PUSH + #define PRAGMA(str) PRAGMA_CLANG(str) + #define PRAGMA_DIAG_POP PRAGMA_CLANG_DIAG_POP #else #define PRAGMA_CLANG_DIAG_PUSH #define PRAGMA_CLANG(str) #define PRAGMA_CLANG_DIAG_POP #endif + #ifndef PRAGMA_DIAG_PUSH + #define PRAGMA_DIAG_PUSH + #endif + #ifndef PRAGMA + #define PRAGMA(str) + #endif + #ifndef PRAGMA_DIAG_POP + #define PRAGMA_DIAG_POP + #endif + #ifdef DEBUG_VECTOR_REGISTER_ACCESS WOLFSSL_API extern THREAD_LS_T int wc_svr_count; WOLFSSL_API extern THREAD_LS_T const char *wc_svr_last_file; From 182df5f2506957e740925ca30ef65db8202cdb39 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 31 May 2023 15:48:52 -0500 Subject: [PATCH 342/391] move definitions of XASM_LINK() from wolfcrypt/src/aes.c, wolfcrypt/src/asm.c, and wolfcrypt/src/cpuid.c, to wolfssl/wolfcrypt/types.h, and use __asm__() instead of asm() if __GNUC__, for compatibility with -std=c99. --- wolfcrypt/src/aes.c | 8 -------- wolfcrypt/src/asm.c | 6 ------ wolfcrypt/src/cpuid.c | 4 ---- wolfssl/wolfcrypt/types.h | 18 ++++++++++++++++-- 4 files changed, 16 insertions(+), 20 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index e36d0f4f31a..9a021dbf691 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -709,14 +709,6 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #define AESNI_ALIGN 16 #endif - #ifdef _MSC_VER - #define XASM_LINK(f) - #elif defined(__APPLE__) - #define XASM_LINK(f) asm("_" f) - #else - #define XASM_LINK(f) asm(f) - #endif /* _MSC_VER */ - static int checkAESNI = 0; static int haveAESNI = 0; static word32 intel_flags = 0; diff --git a/wolfcrypt/src/asm.c b/wolfcrypt/src/asm.c index 5b9d1ffd7b3..ea2b4e6d7db 100644 --- a/wolfcrypt/src/asm.c +++ b/wolfcrypt/src/asm.c @@ -46,15 +46,9 @@ __asm__ __volatile__ ("cpuid":\ "=a" (reg[0]), "=b" (reg[1]), "=c" (reg[2]), "=d" (reg[3]) :\ "a" (leaf), "c"(sub)); - - #define XASM_LINK(f) asm(f) #else - #include #define cpuid(a,b,c) __cpuidex((int*)a,b,c) - - #define XASM_LINK(f) - #endif /* _MSC_VER */ #define EAX 0 diff --git a/wolfcrypt/src/cpuid.c b/wolfcrypt/src/cpuid.c index 744bb498681..c1924c1e5c8 100644 --- a/wolfcrypt/src/cpuid.c +++ b/wolfcrypt/src/cpuid.c @@ -43,14 +43,10 @@ __asm__ __volatile__ ("cpuid":\ "=a" ((reg)[0]), "=b" ((reg)[1]), "=c" ((reg)[2]), "=d" ((reg)[3]) :\ "a" (leaf), "c"(sub)); - - #define XASM_LINK(f) asm(f) #else #include #define cpuid(a,b,c) __cpuidex((int*)a,b,c) - - #define XASM_LINK(f) #endif /* _MSC_VER */ #define EAX 0 diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 0298654c9fa..6a11c44b77e 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -1180,8 +1180,22 @@ typedef struct w64wrapper { /* invalid device id */ #define INVALID_DEVID (-2) - /* AESNI requires alignment and ARMASM gains some performance from it - * Xilinx RSA operations require alignment */ + #ifdef XASM_LINK + /* keep user-supplied definition */ + #elif defined(_MSC_VER) + #define XASM_LINK(f) + #elif defined(__APPLE__) + #define XASM_LINK(f) asm("_" f) + #elif defined(__GNUC__) + /* use alternate keyword for compatibility with -std=c99 */ + #define XASM_LINK(f) __asm__(f) + #else + #define XASM_LINK(f) asm(f) + #endif + + /* AESNI requires alignment and ARMASM gains some performance from it. + * Xilinx RSA operations require alignment. + */ #if defined(WOLFSSL_AESNI) || defined(WOLFSSL_ARMASM) || \ defined(USE_INTEL_SPEEDUP) || defined(WOLFSSL_AFALG_XILINX) || \ defined(WOLFSSL_XILINX) From 8daa3d983cf300838511f114bd610f1c8893d615 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Wed, 31 May 2023 18:26:27 -0500 Subject: [PATCH 343/391] api.c: fix 3 missed EXPECT_RESULT() == WOLFSSL_SUCCESSes to use the succincter EXPECT_SUCCESS(). --- tests/api.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/api.c b/tests/api.c index e992c6f5db6..7b154a5f016 100644 --- a/tests/api.c +++ b/tests/api.c @@ -9276,7 +9276,7 @@ static int test_wolfSSL_SNI_GetFromBuffer(void) ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SNI_GetFromBuffer(buff, sizeof(buff), 0, result, &length)); - if (EXPECT_RESULT() == TEST_SUCCESS) + if (EXPECT_SUCCESS()) result[length] = 0; ExpectStrEQ("www.paypal.com", (const char*) result); @@ -9284,7 +9284,7 @@ static int test_wolfSSL_SNI_GetFromBuffer(void) ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_SNI_GetFromBuffer(buff2, sizeof(buff2), 0, result, &length)); - if (EXPECT_RESULT() == TEST_SUCCESS) + if (EXPECT_SUCCESS()) result[length] = 0; ExpectStrEQ("api.textmate.org", (const char*) result); @@ -34871,7 +34871,7 @@ static int test_wc_KeyPemToDer(void) /* Test NULL for DER buffer to return needed DER buffer size */ ExpectIntGT(ret = wc_KeyPemToDer(cert_buf, cert_sz, NULL, 0, ""), 0); ExpectIntLE(ret, cert_sz); - if (EXPECT_RESULT() == TEST_SUCCESS) + if (EXPECT_SUCCESS()) cert_dersz = ret; ExpectNotNull(cert_der = (byte*)malloc(cert_dersz)); ExpectIntGE(ret = wc_KeyPemToDer(cert_buf, cert_sz, cert_der, cert_dersz, From 9710b7aa9898cf540755017b0aedb2dfc9ad0ab5 Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Tue, 30 May 2023 17:32:42 +0900 Subject: [PATCH 344/391] fix to cast diff type, int and uint --- src/wolfio.c | 2 +- tests/api.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wolfio.c b/src/wolfio.c index 1e4d0adb8cf..09016956ac5 100644 --- a/src/wolfio.c +++ b/src/wolfio.c @@ -388,7 +388,7 @@ static int sockAddrEqual( #ifndef WOLFSSL_IPV6 static int PeerIsIpv6(const SOCKADDR_S *peer, XSOCKLENT len) { - if (len < sizeof(peer->ss_family)) + if (len < (int)sizeof(peer->ss_family)) return 0; return peer->ss_family == WOLFSSL_IP6; } diff --git a/tests/api.c b/tests/api.c index 7b154a5f016..2c58e7447dd 100644 --- a/tests/api.c +++ b/tests/api.c @@ -66317,7 +66317,7 @@ static int test_dtls_msg_get_connected_port(int fd, word16 *port) XMEMSET((byte*)&peer, 0, sizeof(peer)); len = sizeof(peer); ret = getpeername(fd, (SOCKADDR*)&peer, &len); - if (ret != 0 || len > sizeof(peer)) + if (ret != 0 || len > (int)sizeof(peer)) return -1; switch (peer.ss_family) { #ifdef WOLFSSL_IPV6 From e4cfdf37363f7ba096f0a7f87b69d6374ef634ff Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Wed, 31 May 2023 06:54:14 +0900 Subject: [PATCH 345/391] addressed review comments --- src/wolfio.c | 2 +- tests/api.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wolfio.c b/src/wolfio.c index 09016956ac5..26c11ad49fd 100644 --- a/src/wolfio.c +++ b/src/wolfio.c @@ -388,7 +388,7 @@ static int sockAddrEqual( #ifndef WOLFSSL_IPV6 static int PeerIsIpv6(const SOCKADDR_S *peer, XSOCKLENT len) { - if (len < (int)sizeof(peer->ss_family)) + if (len < (XSOCKLENT)sizeof(peer->ss_family)) return 0; return peer->ss_family == WOLFSSL_IP6; } diff --git a/tests/api.c b/tests/api.c index 2c58e7447dd..4aede25239c 100644 --- a/tests/api.c +++ b/tests/api.c @@ -66317,7 +66317,7 @@ static int test_dtls_msg_get_connected_port(int fd, word16 *port) XMEMSET((byte*)&peer, 0, sizeof(peer)); len = sizeof(peer); ret = getpeername(fd, (SOCKADDR*)&peer, &len); - if (ret != 0 || len > (int)sizeof(peer)) + if (ret != 0 || len > (XSOCKLENT)sizeof(peer)) return -1; switch (peer.ss_family) { #ifdef WOLFSSL_IPV6 From e739d074b81c4af3b983bc32be678af7871b69b7 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 31 May 2023 17:12:16 +1000 Subject: [PATCH 346/391] Test api.c: change more tests to use Expect instead of Assert Added a new version of 'nofail' handshaking that doesn't use threads. More tests can be run in single threaded. Changed tests over to use test_wolfSSL_client_server_nofail() or test_wolfSSL_client_server_nofail_memio() to simplfy test cases. Changed tests to use Expect. CRL: BufferLoadCRL wasn't freeing allocated data when currentEntry couldn't be allocated. ssl.c: DecodeToX509(): Needs to call FreeDecodedCert even if ParseCertRelative fails. wolfSSL_PEM_read_PUBKEY(): Need to check result of wolfSSL_d2i_PUBKEY is NULL rather than the passed in WOLFSSL_EVP_PKEY. X509: wolfSSL_X509_set_ext(): Must free allocated WOLFSSL_X509_EXTENSION if not pushed on to stack regardless of stack being NULL. wolfSSL_X509V3_EXT_i2d(): Don't free asn1str on error as it is the data passed in. wolfSSL_i2d_X509_NAME_canon(): free names and cano_data when call to wolfSSL_ASN1_STRING_canon() fails. PKCS7: wc_PKCS7_InitWithCert(): Check memory allocation of cert for NULL. --- src/crl.c | 4 + src/ssl.c | 20 +- src/x509.c | 12 +- tests/api.c | 5509 ++++++++++++++++++++------------------- wolfcrypt/src/pkcs7.c | 6 + wolfcrypt/src/wc_port.c | 2 +- wolfssl/wolfcrypt/asn.h | 2 +- 7 files changed, 2863 insertions(+), 2692 deletions(-) diff --git a/src/crl.c b/src/crl.c index 76a7a67f271..659a780938a 100644 --- a/src/crl.c +++ b/src/crl.c @@ -597,6 +597,10 @@ int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type, DYNAMIC_TYPE_CRL_ENTRY); if (crl->currentEntry == NULL) { WOLFSSL_MSG("alloc CRL Entry failed"); + #ifdef WOLFSSL_SMALL_STACK + XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + FreeDer(&der); return MEMORY_E; } XMEMSET(crl->currentEntry, 0, sizeof(CRL_Entry)); diff --git a/src/ssl.c b/src/ssl.c index 061d328879a..d321165b32a 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -20687,8 +20687,8 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, if (x509->dynamicMemory != TRUE) InitX509(x509, 0, NULL); ret = CopyDecodedToX509(x509, cert); - FreeDecodedCert(cert); } + FreeDecodedCert(cert); #ifdef WOLFSSL_SMALL_STACK XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); #endif @@ -26205,7 +26205,7 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { { NID_postalCode, NID_postalCode, oidCertNameType, "postalCode", "postalCode"}, { NID_userId, NID_userId, oidCertNameType, "UID", "userId"}, -#ifdef WOLFSSL_CERT_REQ +#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL) { NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID, oidCsrAttrType, "challengePassword", "challengePassword"}, { NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID, @@ -27939,28 +27939,31 @@ WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_PUBKEY(XFILE fp, WOLFSSL_EVP_PKEY **key, DerBuffer* der = NULL; int keyFormat = 0; - WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PUBKEY"); + WOLFSSL_ENTER("wolfSSL_PEM_read_PUBKEY"); if (pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE, &keyFormat, &der) >= 0) { const unsigned char* ptr = der->buffer; /* handle case where reuse is attempted */ - if (key != NULL && *key != NULL) + if ((key != NULL) && (*key != NULL)) { pkey = *key; + } - wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length); - if (pkey == NULL) { + if ((wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) || + (pkey == NULL)) { WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); + pkey = NULL; } } FreeDer(&der); - if (key != NULL && pkey != NULL) + if ((key != NULL) && (pkey != NULL)) { *key = pkey; + } - WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PUBKEY", 0); + WOLFSSL_LEAVE("wolfSSL_PEM_read_PUBKEY", 0); return pkey; } @@ -37527,6 +37530,7 @@ int wolfSSL_PKCS7_encode_certs(PKCS7* pkcs7, WOLFSSL_STACK* certs, /* take ownership of certs */ p7->certs = certs; + /* TODO: takes ownership even on failure below but not on above failure. */ if (pkcs7->certList) { WOLFSSL_MSG("wolfSSL_PKCS7_encode_certs called multiple times on same " diff --git a/src/x509.c b/src/x509.c index 9ced66eee74..54eccaf870a 100644 --- a/src/x509.c +++ b/src/x509.c @@ -1124,8 +1124,9 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) */ if (x509->ext_sk == NULL) x509->ext_sk = wolfSSL_sk_new_x509_ext(); - if (x509->ext_sk != NULL) - wolfSSL_sk_X509_EXTENSION_push(x509->ext_sk, ext); + if (wolfSSL_sk_X509_EXTENSION_push(x509->ext_sk, ext) == WOLFSSL_FAILURE) { + wolfSSL_X509_EXTENSION_free(ext); + } FreeDecodedCert(cert); #ifdef WOLFSSL_SMALL_STACK @@ -2926,9 +2927,6 @@ WOLFSSL_X509_EXTENSION *wolfSSL_X509V3_EXT_i2d(int nid, int crit, if (ext) { wolfSSL_X509_EXTENSION_free(ext); } - if (asn1str) { - wolfSSL_ASN1_STRING_free(asn1str); - } return NULL; } @@ -10354,6 +10352,10 @@ int wolfSSL_i2d_X509_NAME_canon(WOLFSSL_X509_NAME* name, unsigned char** out) return WOLFSSL_FATAL_ERROR; } if (wolfSSL_ASN1_STRING_canon(cano_data, data) != WOLFSSL_SUCCESS) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + wolfSSL_ASN1_STRING_free(cano_data); return WOLFSSL_FAILURE; } nameStr = (const char*)wolfSSL_ASN1_STRING_data(cano_data); diff --git a/tests/api.c b/tests/api.c index 4aede25239c..1e2435a72aa 100644 --- a/tests/api.c +++ b/tests/api.c @@ -398,6 +398,61 @@ typedef struct testVector { #endif #endif /* HAVE_PKCS7 */ +typedef int (*ctx_cb)(WOLFSSL_CTX* ctx); +typedef int (*ssl_cb)(WOLFSSL* ssl); +typedef int (*test_cbType)(WOLFSSL_CTX *ctx, WOLFSSL *ssl); + +typedef struct test_ssl_cbf { + method_provider method; + ctx_cb ctx_ready; + ssl_cb ssl_ready; + ssl_cb on_result; + ssl_cb on_cleanup; + WOLFSSL_CTX* ctx; + const char* caPemFile; + const char* certPemFile; + const char* keyPemFile; + const char* crlPemFile; +#ifdef WOLFSSL_STATIC_MEMORY + byte* mem; + word32 memSz; + wolfSSL_method_func method_ex; +#endif + int devId; + int return_code; + int last_err; + unsigned char isSharedCtx:1; + unsigned char loadToSSL:1; + unsigned char ticNoInit:1; + unsigned char doUdp:1; +} test_ssl_cbf; + +#define TEST_SSL_MEMIO_BUF_SZ (64 * 1024) +typedef struct test_ssl_memio_ctx { + WOLFSSL_CTX* s_ctx; + WOLFSSL_CTX* c_ctx; + WOLFSSL* s_ssl; + WOLFSSL* c_ssl; + + const char* c_ciphers; + const char* s_ciphers; + + char* c_msg; + int c_msglen; + char* s_msg; + int s_msglen; + + test_ssl_cbf s_cb; + test_ssl_cbf c_cb; + + byte c_buff[TEST_SSL_MEMIO_BUF_SZ]; + int c_len; + byte s_buff[TEST_SSL_MEMIO_BUF_SZ]; + int s_len; +} test_ssl_memio_ctx; + +int test_wolfSSL_client_server_nofail_memio(test_ssl_cbf* client_cb, + test_ssl_cbf* server_cb, test_cbType client_on_handshake); /*----------------------------------------------------------------------------* | Constants @@ -473,6 +528,11 @@ static int testDevId = INVALID_DEVID; #define HAVE_IO_TESTS_DEPENDENCIES #endif +#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_WOLFSSL_CLIENT) +#define HAVE_SSL_MEMIO_TESTS_DEPENDENCIES +#endif + /*----------------------------------------------------------------------------* | BIO with fixed read/write size *----------------------------------------------------------------------------*/ @@ -3765,24 +3825,30 @@ static int test_wolfSSL_set_minmax_proto_version(void) } #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_TLS12) && \ - defined(OPENSSL_EXTRA) && defined(HAVE_IO_TESTS_DEPENDENCIES) -static void test_wolfSSL_CTX_set_max_proto_version_on_result(WOLFSSL* ssl) + defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) +static int test_wolfSSL_CTX_set_max_proto_version_on_result(WOLFSSL* ssl) { - AssertStrEQ(wolfSSL_get_version(ssl), "TLSv1.2"); + EXPECT_DECLS; + ExpectStrEQ(wolfSSL_get_version(ssl), "TLSv1.2"); + return EXPECT_RESULT(); } -static void test_wolfSSL_CTX_set_max_proto_version_ctx_ready(WOLFSSL_CTX* ctx) +static int test_wolfSSL_CTX_set_max_proto_version_ctx_ready(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; /* Set TLS 1.2 */ - AssertIntEQ(wolfSSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION), + ExpectIntEQ(wolfSSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION), WOLFSSL_SUCCESS); + return EXPECT_RESULT(); } /* Test using wolfSSL_CTX_set_max_proto_version to limit the version below * what was set at ctx creation. */ static int test_wolfSSL_CTX_set_max_proto_version(void) { - callback_functions client_cbs, server_cbs; + EXPECT_DECLS; + test_ssl_cbf client_cbs; + test_ssl_cbf server_cbs; XMEMSET(&client_cbs, 0, sizeof(client_cbs)); XMEMSET(&server_cbs, 0, sizeof(server_cbs)); @@ -3795,12 +3861,10 @@ static int test_wolfSSL_CTX_set_max_proto_version(void) client_cbs.on_result = test_wolfSSL_CTX_set_max_proto_version_on_result; server_cbs.on_result = test_wolfSSL_CTX_set_max_proto_version_on_result; - test_wolfSSL_client_server_nofail(&client_cbs, &server_cbs); - - AssertIntEQ(client_cbs.return_code, TEST_SUCCESS); - AssertIntEQ(server_cbs.return_code, TEST_SUCCESS); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbs, + &server_cbs, NULL), TEST_SUCCESS); - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } #else static int test_wolfSSL_CTX_set_max_proto_version(void) @@ -4170,6 +4234,7 @@ static int test_wolfSSL_EVP_PKEY_print_public(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_BIO) + EXPECT_DECLS; WOLFSSL_BIO* rbio = NULL; WOLFSSL_BIO* wbio = NULL; WOLFSSL_EVP_PKEY* pkey = NULL; @@ -4178,7 +4243,7 @@ static int test_wolfSSL_EVP_PKEY_print_public(void) int i; /* test error cases */ - AssertIntEQ( EVP_PKEY_print_public(NULL,NULL,0,NULL),0L); + ExpectIntEQ( EVP_PKEY_print_public(NULL,NULL,0,NULL),0L); /* * test RSA public key print @@ -4186,43 +4251,40 @@ static int test_wolfSSL_EVP_PKEY_print_public(void) */ #if !defined(NO_RSA) && defined(USE_CERT_BUFFERS_1024) - rbio = BIO_new_mem_buf( client_keypub_der_1024, - sizeof_client_keypub_der_1024); - AssertNotNull(rbio); + ExpectNotNull(rbio = BIO_new_mem_buf( client_keypub_der_1024, + sizeof_client_keypub_der_1024)); - wolfSSL_d2i_PUBKEY_bio(rbio, &pkey); - AssertNotNull(pkey); + ExpectNotNull(wolfSSL_d2i_PUBKEY_bio(rbio, &pkey)); - wbio = BIO_new(BIO_s_mem()); - AssertNotNull(wbio); + ExpectNotNull(wbio = BIO_new(BIO_s_mem())); - AssertIntEQ(EVP_PKEY_print_public(wbio, pkey,3,NULL),1); + ExpectIntEQ(EVP_PKEY_print_public(wbio, pkey,3,NULL),1); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, " RSA Public-Key: (1024 bit)\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP(line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, " Modulus:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, " 00:bc:73:0e:a8:49:f3:74:a2:a9:ef:18:a5:da:55:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* skip to the end of modulus element*/ for (i = 0; i < 8 ;i++) { - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); } - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, " Exponent: 65537 (0x010001)\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* should reach EOF */ - AssertIntLE(BIO_gets(wbio, line, sizeof(line)) ,0); + ExpectIntLE(BIO_gets(wbio, line, sizeof(line)), 0); EVP_PKEY_free(pkey); pkey = NULL; @@ -4237,63 +4299,60 @@ static int test_wolfSSL_EVP_PKEY_print_public(void) * test DSA public key print */ #if !defined(NO_DSA) && defined(USE_CERT_BUFFERS_2048) - rbio = BIO_new_mem_buf( dsa_pub_key_der_2048, - sizeof_dsa_pub_key_der_2048); - AssertNotNull(rbio); + ExpectNotNull(rbio = BIO_new_mem_buf( dsa_pub_key_der_2048, + sizeof_dsa_pub_key_der_2048)); - wolfSSL_d2i_PUBKEY_bio(rbio, &pkey); - AssertNotNull(pkey); + ExpectNotNull(wolfSSL_d2i_PUBKEY_bio(rbio, &pkey)); - wbio = BIO_new(BIO_s_mem()); - AssertNotNull(wbio); + ExpectNotNull(wbio = BIO_new(BIO_s_mem())); - AssertIntEQ(EVP_PKEY_print_public(wbio, pkey,0,NULL),1); + ExpectIntEQ(EVP_PKEY_print_public(wbio, pkey,0,NULL),1); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "DSA Public-Key: (2048 bit)\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "pub:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, " 00:C2:35:2D:EC:83:83:6C:73:13:9E:52:7C:74:C8:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* skip to the end of pub element*/ for (i = 0; i < 17 ;i++) { - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); } - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "P:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* skip to the end of P element*/ for (i = 0; i < 18 ;i++) { - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); } - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "Q:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* skip to the end of Q element*/ for (i = 0; i < 3 ;i++) { - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); } - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "G:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* skip to the end of G element*/ for (i = 0; i < 18 ;i++) { - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); } /* should reach EOF */ - AssertIntLE(BIO_gets(wbio, line, sizeof(line)) ,0); + ExpectIntLE(BIO_gets(wbio, line, sizeof(line)), 0); EVP_PKEY_free(pkey); pkey = NULL; @@ -4309,47 +4368,44 @@ static int test_wolfSSL_EVP_PKEY_print_public(void) */ #if defined(HAVE_ECC) && defined(USE_CERT_BUFFERS_256) - rbio = BIO_new_mem_buf( ecc_clikeypub_der_256, - sizeof_ecc_clikeypub_der_256); - AssertNotNull(rbio); + ExpectNotNull(rbio = BIO_new_mem_buf( ecc_clikeypub_der_256, + sizeof_ecc_clikeypub_der_256)); - wolfSSL_d2i_PUBKEY_bio(rbio, &pkey); - AssertNotNull(pkey); + ExpectNotNull(wolfSSL_d2i_PUBKEY_bio(rbio, &pkey)); - wbio = BIO_new(BIO_s_mem()); - AssertNotNull(wbio); + ExpectNotNull(wbio = BIO_new(BIO_s_mem())); - AssertIntEQ(EVP_PKEY_print_public(wbio, pkey,0,NULL),1); + ExpectIntEQ(EVP_PKEY_print_public(wbio, pkey,0,NULL),1); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "Public-Key: (256 bit)\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "pub:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, " 04:55:BF:F4:0F:44:50:9A:3D:CE:9B:B7:F0:C5:4D:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* skip to the end of pub element*/ for (i = 0; i < 4 ;i++) { - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); } - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "ASN1 OID: prime256v1\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "NIST CURVE: P-256\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* should reach EOF */ - AssertIntLE(BIO_gets(wbio, line, sizeof(line)) ,0); + ExpectIntLE(BIO_gets(wbio, line, sizeof(line)), 0); EVP_PKEY_free(pkey); pkey = NULL; @@ -4365,56 +4421,53 @@ static int test_wolfSSL_EVP_PKEY_print_public(void) */ #if defined(WOLFSSL_DH_EXTRA) && defined(USE_CERT_BUFFERS_2048) - rbio = BIO_new_mem_buf( dh_pub_key_der_2048, - sizeof_dh_pub_key_der_2048); - AssertNotNull(rbio); + ExpectNotNull(rbio = BIO_new_mem_buf( dh_pub_key_der_2048, + sizeof_dh_pub_key_der_2048)); - wolfSSL_d2i_PUBKEY_bio(rbio, &pkey); - AssertNotNull(pkey); + ExpectNotNull(wolfSSL_d2i_PUBKEY_bio(rbio, &pkey)); - wbio = BIO_new(BIO_s_mem()); - AssertNotNull(wbio); + ExpectNotNull(wbio = BIO_new(BIO_s_mem())); - AssertIntEQ(EVP_PKEY_print_public(wbio, pkey,0,NULL),1); + ExpectIntEQ(EVP_PKEY_print_public(wbio, pkey,0,NULL), 1); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "DH Public-Key: (2048 bit)\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "public-key:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, " 34:41:BF:E9:F2:11:BF:05:DB:B2:72:A8:29:CC:BD:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* skip to the end of public-key element*/ for (i = 0; i < 17 ;i++) { - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); } - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "prime:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, " 00:D3:B2:99:84:5C:0A:4C:E7:37:CC:FC:18:37:01:\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* skip to the end of prime element*/ for (i = 0; i < 17 ;i++) { - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); } - BIO_gets(wbio, line, sizeof(line)); + ExpectIntGT(BIO_gets(wbio, line, sizeof(line)), 0); strcpy(line1, "generator: 2 (0x02)\n"); - AssertIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); + ExpectIntEQ(XSTRNCMP( line, line1, XSTRLEN(line1)), 0); /* should reach EOF */ - AssertIntLE(BIO_gets(wbio, line, sizeof(line)) ,0); + ExpectIntLE(BIO_gets(wbio, line, sizeof(line)), 0); EVP_PKEY_free(pkey); pkey = NULL; @@ -4433,7 +4486,7 @@ static int test_wolfSSL_EVP_PKEY_print_public(void) (void)line1; (void)i; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -4443,15 +4496,16 @@ static int test_wolfSSL_EVP_ENCODE_CTX_new(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && \ ( defined(WOLFSSL_BASE64_ENCODE) || defined(WOLFSSL_BASE64_DECODE)) + EXPECT_DECLS; EVP_ENCODE_CTX* ctx = NULL; - AssertNotNull( ctx = EVP_ENCODE_CTX_new()); - AssertIntEQ( ctx->remaining,0); - AssertIntEQ( ctx->data[0],0); - AssertIntEQ( ctx->data[sizeof(ctx->data) -1],0); + ExpectNotNull(ctx = EVP_ENCODE_CTX_new()); + ExpectIntEQ(ctx->remaining,0); + ExpectIntEQ(ctx->data[0],0); + ExpectIntEQ(ctx->data[sizeof(ctx->data) -1],0); EVP_ENCODE_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && (WOLFSSL_BASE64_ENCODE || WOLFSSL_BASE64_DECODE)*/ return res; } @@ -4460,12 +4514,13 @@ static int test_wolfSSL_EVP_ENCODE_CTX_free(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && \ ( defined(WOLFSSL_BASE64_ENCODE) || defined(WOLFSSL_BASE64_DECODE)) + EXPECT_DECLS; EVP_ENCODE_CTX* ctx = NULL; - AssertNotNull( ctx = EVP_ENCODE_CTX_new()); + ExpectNotNull(ctx = EVP_ENCODE_CTX_new()); EVP_ENCODE_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /*OPENSSL_EXTRA && (WOLFSSL_BASE64_ENCODE || WOLFSSL_BASE64_DECODE)*/ return res; } @@ -4474,26 +4529,29 @@ static int test_wolfSSL_EVP_EncodeInit(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_BASE64_ENCODE) + EXPECT_DECLS; EVP_ENCODE_CTX* ctx = NULL; - AssertNotNull( ctx = EVP_ENCODE_CTX_new()); - AssertIntEQ( ctx->remaining,0); - AssertIntEQ( ctx->data[0],0); - AssertIntEQ( ctx->data[sizeof(ctx->data) -1],0); + ExpectNotNull(ctx = EVP_ENCODE_CTX_new()); + ExpectIntEQ(ctx->remaining, 0); + ExpectIntEQ(ctx->data[0], 0); + ExpectIntEQ(ctx->data[sizeof(ctx->data) -1], 0); - /* make ctx dirty */ - ctx->remaining = 10; - XMEMSET( ctx->data, 0x77, sizeof(ctx->data)); + if (ctx != NULL) { + /* make ctx dirty */ + ctx->remaining = 10; + XMEMSET(ctx->data, 0x77, sizeof(ctx->data)); + } EVP_EncodeInit(ctx); - AssertIntEQ( ctx->remaining,0); - AssertIntEQ( ctx->data[0],0); - AssertIntEQ( ctx->data[sizeof(ctx->data) -1],0); + ExpectIntEQ(ctx->remaining, 0); + ExpectIntEQ(ctx->data[0], 0); + ExpectIntEQ(ctx->data[sizeof(ctx->data) -1], 0); EVP_ENCODE_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && WOLFSSL_BASE64_ENCODE*/ return res; } @@ -4501,6 +4559,7 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_BASE64_ENCODE) + EXPECT_DECLS; int outl; int total; @@ -4519,12 +4578,12 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) EVP_ENCODE_CTX* ctx = NULL; - AssertNotNull( ctx = EVP_ENCODE_CTX_new()); + ExpectNotNull(ctx = EVP_ENCODE_CTX_new()); EVP_EncodeInit(ctx); /* illegal parameter test */ - AssertIntEQ( + ExpectIntEQ( EVP_EncodeUpdate( NULL, /* pass NULL as ctx */ encOutBuff, @@ -4534,7 +4593,7 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) 0 /* expected result code 0: fail */ ); - AssertIntEQ( + ExpectIntEQ( EVP_EncodeUpdate( ctx, NULL, /* pass NULL as out buff */ @@ -4544,7 +4603,7 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) 0 /* expected result code 0: fail */ ); - AssertIntEQ( + ExpectIntEQ( EVP_EncodeUpdate( ctx, encOutBuff, @@ -4554,7 +4613,7 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) 0 /* expected result code 0: fail */ ); - AssertIntEQ( + ExpectIntEQ( EVP_EncodeUpdate( ctx, encOutBuff, @@ -4564,11 +4623,11 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) 0 /* expected result code 0: fail */ ); - AssertIntEQ(EVP_EncodeBlock(NULL, NULL, 0), -1); + ExpectIntEQ(EVP_EncodeBlock(NULL, NULL, 0), -1); /* meaningless parameter test */ - AssertIntEQ( + ExpectIntEQ( EVP_EncodeUpdate( ctx, encOutBuff, @@ -4582,7 +4641,7 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) EVP_EncodeInit(ctx); - AssertIntEQ( + ExpectIntEQ( EVP_EncodeUpdate( ctx, encOutBuff, @@ -4591,24 +4650,24 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) sizeof(plain0)-1), 1 /* expected result code 1: success */ ); - AssertIntEQ(outl,0); + ExpectIntEQ(outl,0); EVP_EncodeFinal( ctx, encOutBuff + outl, &outl); - AssertIntEQ( outl, sizeof(enc0)-1); - AssertIntEQ( + ExpectIntEQ( outl, sizeof(enc0)-1); + ExpectIntEQ( XSTRNCMP( (const char*)encOutBuff, (const char*)enc0,sizeof(enc0) ), 0); XMEMSET( encOutBuff,0, sizeof(encOutBuff)); - AssertIntEQ(EVP_EncodeBlock(encOutBuff, plain0, sizeof(plain0)-1), + ExpectIntEQ(EVP_EncodeBlock(encOutBuff, plain0, sizeof(plain0)-1), sizeof(enc0)-1); - AssertIntEQ( + ExpectIntEQ( XSTRNCMP( (const char*)encOutBuff, (const char*)enc0,sizeof(enc0) ), @@ -4624,7 +4683,7 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) outl = 0; XMEMSET( encOutBuff,0, sizeof(encOutBuff)); - AssertIntEQ( + ExpectIntEQ( EVP_EncodeUpdate( ctx, encOutBuff, /* buffer for output */ @@ -4635,18 +4694,18 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) total += outl; - AssertIntEQ(outl, 0); /* no output expected */ - AssertIntEQ(ctx->remaining, sizeof(plain1) -1); - AssertTrue( + ExpectIntEQ(outl, 0); /* no output expected */ + ExpectIntEQ(ctx->remaining, sizeof(plain1) -1); + ExpectTrue( XSTRNCMP((const char*)(ctx->data), (const char*)plain1, ctx->remaining) ==0 ); - AssertTrue(encOutBuff[0] == 0); + ExpectTrue(encOutBuff[0] == 0); /* call wolfSSL_EVP_EncodeUpdate again to make it encode * the stored data and the new input together */ - AssertIntEQ( + ExpectIntEQ( EVP_EncodeUpdate( ctx, encOutBuff + outl, /* buffer for output */ @@ -4657,9 +4716,9 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) total += outl; - AssertIntNE(outl, 0); /* some output is expected this time*/ - AssertIntEQ(outl, BASE64_ENCODE_RESULT_BLOCK_SIZE +1); /* 64 bytes and LF */ - AssertIntEQ( + ExpectIntNE(outl, 0); /* some output is expected this time*/ + ExpectIntEQ(outl, BASE64_ENCODE_RESULT_BLOCK_SIZE +1); /* 64 bytes and LF */ + ExpectIntEQ( XSTRNCMP((const char*)encOutBuff,(const char*)enc1,sizeof(enc1) ),0); /* call wolfSSL_EVP_EncodeFinal to flush all the unprocessed input */ @@ -4670,24 +4729,24 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) total += outl; - AssertIntNE(total,0); - AssertIntNE(outl,0); - AssertIntEQ(XSTRNCMP( + ExpectIntNE(total,0); + ExpectIntNE(outl,0); + ExpectIntEQ(XSTRNCMP( (const char*)encOutBuff,(const char*)enc2,sizeof(enc2) ),0); /* test with illeagal parameters */ outl = 1; EVP_EncodeFinal(NULL, encOutBuff + outl, &outl); - AssertIntEQ(outl, 0); + ExpectIntEQ(outl, 0); outl = 1; EVP_EncodeFinal(ctx, NULL, &outl); - AssertIntEQ(outl, 0); + ExpectIntEQ(outl, 0); EVP_EncodeFinal(ctx, encOutBuff + outl, NULL); EVP_EncodeFinal(NULL, NULL, NULL); EVP_ENCODE_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && WOLFSSL_BASE64_ENCODE*/ return res; } @@ -4698,7 +4757,7 @@ static int test_wolfSSL_EVP_EncodeFinal(void) /* tests for wolfSSL_EVP_EncodeFinal are included in * test_wolfSSL_EVP_EncodeUpdate */ - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif /* OPENSSL_EXTRA && WOLFSSL_BASE64_ENCODE*/ return res; } @@ -4708,26 +4767,29 @@ static int test_wolfSSL_EVP_DecodeInit(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_BASE64_DECODE) + EXPECT_DECLS; EVP_ENCODE_CTX* ctx = NULL; - AssertNotNull( ctx = EVP_ENCODE_CTX_new()); - AssertIntEQ( ctx->remaining,0); - AssertIntEQ( ctx->data[0],0); - AssertIntEQ( ctx->data[sizeof(ctx->data) -1],0); + ExpectNotNull( ctx = EVP_ENCODE_CTX_new()); + ExpectIntEQ( ctx->remaining,0); + ExpectIntEQ( ctx->data[0],0); + ExpectIntEQ( ctx->data[sizeof(ctx->data) -1],0); - /* make ctx dirty */ - ctx->remaining = 10; - XMEMSET( ctx->data, 0x77, sizeof(ctx->data)); + if (ctx != NULL) { + /* make ctx dirty */ + ctx->remaining = 10; + XMEMSET( ctx->data, 0x77, sizeof(ctx->data)); + } EVP_DecodeInit(ctx); - AssertIntEQ( ctx->remaining,0); - AssertIntEQ( ctx->data[0],0); - AssertIntEQ( ctx->data[sizeof(ctx->data) -1],0); + ExpectIntEQ( ctx->remaining,0); + ExpectIntEQ( ctx->data[0],0); + ExpectIntEQ( ctx->data[sizeof(ctx->data) -1],0); EVP_ENCODE_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL && WOLFSSL_BASE_DECODE */ return res; } @@ -4735,24 +4797,25 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_BASE64_DECODE) + EXPECT_DECLS; int outl; unsigned char decOutBuff[300]; - EVP_ENCODE_CTX* ctx; + EVP_ENCODE_CTX* ctx = NULL; static const unsigned char enc1[] = {"VGhpcyBpcyBhIGJhc2U2NCBkZWNvZGluZyB0ZXN0Lg==\n"}; /* const unsigned char plain1[] = {"This is a base64 decoding test."} */ - ctx = EVP_ENCODE_CTX_new(); + ExpectNotNull(ctx = EVP_ENCODE_CTX_new()); EVP_DecodeInit(ctx); /* illegal parameter tests */ /* pass NULL as ctx */ - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( NULL, /* pass NULL as ctx */ decOutBuff, @@ -4761,10 +4824,10 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) sizeof(enc1)-1), -1 /* expected result code -1: fail */ ); - AssertIntEQ( outl, 0); + ExpectIntEQ( outl, 0); /* pass NULL as output */ - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, NULL, /* pass NULL as out buff */ @@ -4773,10 +4836,10 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) sizeof(enc1)-1), -1 /* expected result code -1: fail */ ); - AssertIntEQ( outl, 0); + ExpectIntEQ( outl, 0); /* pass NULL as outl */ - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, decOutBuff, @@ -4787,7 +4850,7 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) ); /* pass NULL as input */ - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, decOutBuff, @@ -4796,13 +4859,13 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) sizeof(enc1)-1), -1 /* expected result code -1: fail */ ); - AssertIntEQ( outl, 0); + ExpectIntEQ( outl, 0); - AssertIntEQ(EVP_DecodeBlock(NULL, NULL, 0), -1); + ExpectIntEQ(EVP_DecodeBlock(NULL, NULL, 0), -1); /* pass zero length input */ - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, decOutBuff, @@ -4822,7 +4885,7 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) EVP_EncodeInit(ctx); - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, decOutBuff, @@ -4832,22 +4895,22 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) 0 /* expected result code 0: success */ ); - AssertIntEQ(outl,sizeof(plain2) -1); + ExpectIntEQ(outl,sizeof(plain2) -1); - AssertIntEQ( + ExpectIntEQ( EVP_DecodeFinal( ctx, decOutBuff + outl, &outl), 1 /* expected result code 1: success */ ); - AssertIntEQ(outl, 0); /* expected DecodeFinal outout no data */ + ExpectIntEQ(outl, 0); /* expected DecodeFinal outout no data */ - AssertIntEQ(XSTRNCMP( (const char*)plain2,(const char*)decOutBuff, + ExpectIntEQ(XSTRNCMP( (const char*)plain2,(const char*)decOutBuff, sizeof(plain2) -1 ),0); - AssertIntEQ(EVP_DecodeBlock(decOutBuff, enc2, sizeof(enc2)), + ExpectIntEQ(EVP_DecodeBlock(decOutBuff, enc2, sizeof(enc2)), sizeof(plain2)-1); - AssertIntEQ(XSTRNCMP( (const char*)plain2,(const char*)decOutBuff, + ExpectIntEQ(XSTRNCMP( (const char*)plain2,(const char*)decOutBuff, sizeof(plain2) -1 ),0); } @@ -4861,7 +4924,7 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) EVP_EncodeInit(ctx); - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, decOutBuff, @@ -4871,12 +4934,12 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) 0 /* expected result code 0: success */ ); - AssertIntEQ(outl,sizeof(plain3)-1); /* 31 chars should be output */ + ExpectIntEQ(outl,sizeof(plain3)-1); /* 31 chars should be output */ - AssertIntEQ(XSTRNCMP( (const char*)plain3,(const char*)decOutBuff, + ExpectIntEQ(XSTRNCMP( (const char*)plain3,(const char*)decOutBuff, sizeof(plain3) -1 ),0); - AssertIntEQ( + ExpectIntEQ( EVP_DecodeFinal( ctx, decOutBuff + outl, @@ -4884,11 +4947,11 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) 1 /* expected result code 1: success */ ); - AssertIntEQ(outl,0 ); + ExpectIntEQ(outl,0 ); - AssertIntEQ(EVP_DecodeBlock(decOutBuff, enc3, sizeof(enc3)-1), + ExpectIntEQ(EVP_DecodeBlock(decOutBuff, enc3, sizeof(enc3)-1), sizeof(plain3)-1); - AssertIntEQ(XSTRNCMP( (const char*)plain3,(const char*)decOutBuff, + ExpectIntEQ(XSTRNCMP( (const char*)plain3,(const char*)decOutBuff, sizeof(plain3) -1 ),0); } @@ -4900,7 +4963,7 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) EVP_EncodeInit(ctx); - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, decOutBuff, @@ -4909,8 +4972,8 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) sizeof(enc4)-1), -1 /* expected result code -1: error */ ); - AssertIntEQ(outl,0); - AssertIntEQ(EVP_DecodeBlock(decOutBuff, enc4, sizeof(enc4)-1), -1); + ExpectIntEQ(outl,0); + ExpectIntEQ(EVP_DecodeBlock(decOutBuff, enc4, sizeof(enc4)-1), -1); } /* small data decode test */ @@ -4922,7 +4985,7 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) EVP_EncodeInit(ctx); - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, decOutBuff, @@ -4931,9 +4994,9 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) sizeof(enc00)-1), 1 /* expected result code 1: success */ ); - AssertIntEQ(outl,0); + ExpectIntEQ(outl,0); - AssertIntEQ( + ExpectIntEQ( EVP_DecodeUpdate( ctx, decOutBuff + outl, @@ -4943,21 +5006,21 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) 0 /* expected result code 0: success */ ); - AssertIntEQ(outl,sizeof(plain4)-1); + ExpectIntEQ(outl,sizeof(plain4)-1); /* test with illegal parameters */ - AssertIntEQ(EVP_DecodeFinal(NULL,decOutBuff + outl,&outl), -1); - AssertIntEQ(EVP_DecodeFinal(ctx,NULL,&outl), -1); - AssertIntEQ(EVP_DecodeFinal(ctx,decOutBuff + outl, NULL), -1); - AssertIntEQ(EVP_DecodeFinal(NULL,NULL, NULL), -1); + ExpectIntEQ(EVP_DecodeFinal(NULL,decOutBuff + outl,&outl), -1); + ExpectIntEQ(EVP_DecodeFinal(ctx,NULL,&outl), -1); + ExpectIntEQ(EVP_DecodeFinal(ctx,decOutBuff + outl, NULL), -1); + ExpectIntEQ(EVP_DecodeFinal(NULL,NULL, NULL), -1); EVP_DecodeFinal( ctx, decOutBuff + outl, &outl); - AssertIntEQ( outl, 0); - AssertIntEQ( + ExpectIntEQ( outl, 0); + ExpectIntEQ( XSTRNCMP( (const char*)decOutBuff, (const char*)plain4,sizeof(plain4)-1 ), @@ -4966,7 +5029,7 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) EVP_ENCODE_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL && WOLFSSL_BASE_DECODE */ return res; } @@ -4977,7 +5040,7 @@ static int test_wolfSSL_EVP_DecodeFinal(void) /* tests for wolfSSL_EVP_DecodeFinal are included in * test_wolfSSL_EVP_DecodeUpdate */ - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif /* OPENSSL && WOLFSSL_BASE_DECODE */ return res; } @@ -5122,7 +5185,525 @@ static int test_wolfSSL_EVP_CIPHER_CTX(void) | IO *----------------------------------------------------------------------------*/ +#if defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) || \ + defined(HAVE_IO_TESTS_DEPENDENCIES) +#ifdef WOLFSSL_HAVE_TLS_UNIQUE + #ifdef WC_SHA512_DIGEST_SIZE + #define MD_MAX_SIZE WC_SHA512_DIGEST_SIZE + #else + #define MD_MAX_SIZE WC_SHA256_DIGEST_SIZE + #endif + byte server_side_msg1[MD_MAX_SIZE] = {0};/* msg sent by server */ + byte server_side_msg2[MD_MAX_SIZE] = {0};/* msg received from client */ + byte client_side_msg1[MD_MAX_SIZE] = {0};/* msg sent by client */ + byte client_side_msg2[MD_MAX_SIZE] = {0};/* msg received from server */ +#endif /* WOLFSSL_HAVE_TLS_UNIQUE */ + +/* TODO: Expand and enable this when EVP_chacha20_poly1305 is supported */ +#if defined(HAVE_SESSION_TICKET) && defined(OPENSSL_EXTRA) && \ + defined(HAVE_AES_CBC) + + typedef struct openssl_key_ctx { + byte name[WOLFSSL_TICKET_NAME_SZ]; /* server name */ + byte key[WOLFSSL_TICKET_KEY_SZ]; /* cipher key */ + byte hmacKey[WOLFSSL_TICKET_NAME_SZ]; /* hmac key */ + byte iv[WOLFSSL_TICKET_IV_SZ]; /* cipher iv */ + } openssl_key_ctx; + + static THREAD_LS_T openssl_key_ctx myOpenSSLKey_ctx; + static THREAD_LS_T WC_RNG myOpenSSLKey_rng; + + static WC_INLINE int OpenSSLTicketInit(void) + { + int ret = wc_InitRng(&myOpenSSLKey_rng); + if (ret != 0) return ret; + + ret = wc_RNG_GenerateBlock(&myOpenSSLKey_rng, myOpenSSLKey_ctx.name, + sizeof(myOpenSSLKey_ctx.name)); + if (ret != 0) return ret; + + ret = wc_RNG_GenerateBlock(&myOpenSSLKey_rng, myOpenSSLKey_ctx.key, + sizeof(myOpenSSLKey_ctx.key)); + if (ret != 0) return ret; + + ret = wc_RNG_GenerateBlock(&myOpenSSLKey_rng, myOpenSSLKey_ctx.hmacKey, + sizeof(myOpenSSLKey_ctx.hmacKey)); + if (ret != 0) return ret; + + ret = wc_RNG_GenerateBlock(&myOpenSSLKey_rng, myOpenSSLKey_ctx.iv, + sizeof(myOpenSSLKey_ctx.iv)); + if (ret != 0) return ret; + + return 0; + } + + static WC_INLINE int myTicketEncCbOpenSSL(WOLFSSL* ssl, + byte name[WOLFSSL_TICKET_NAME_SZ], + byte iv[WOLFSSL_TICKET_IV_SZ], + WOLFSSL_EVP_CIPHER_CTX *ectx, + WOLFSSL_HMAC_CTX *hctx, int enc) { + (void)ssl; + if (enc) { + XMEMCPY(name, myOpenSSLKey_ctx.name, sizeof(myOpenSSLKey_ctx.name)); + XMEMCPY(iv, myOpenSSLKey_ctx.iv, sizeof(myOpenSSLKey_ctx.iv)); + } + else if (XMEMCMP(name, myOpenSSLKey_ctx.name, + sizeof(myOpenSSLKey_ctx.name)) != 0 || + XMEMCMP(iv, myOpenSSLKey_ctx.iv, + sizeof(myOpenSSLKey_ctx.iv)) != 0) { + return 0; + } + HMAC_Init_ex(hctx, myOpenSSLKey_ctx.hmacKey, WOLFSSL_TICKET_NAME_SZ, EVP_sha256(), NULL); + if (enc) + EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, myOpenSSLKey_ctx.key, iv); + else + EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, myOpenSSLKey_ctx.key, iv); + return 1; + } + + static WC_INLINE void OpenSSLTicketCleanup(void) + { + wc_FreeRng(&myOpenSSLKey_rng); + } +#endif +#endif + /* helper functions */ +#ifdef HAVE_SSL_MEMIO_TESTS_DEPENDENCIES +static WC_INLINE int test_ssl_memio_write_cb(WOLFSSL *ssl, char *data, int sz, + void *ctx) +{ + struct test_ssl_memio_ctx *test_ctx; + byte *buf; + int *len; + + test_ctx = (struct test_ssl_memio_ctx*)ctx; + + if (wolfSSL_GetSide(ssl) == WOLFSSL_SERVER_END) { + buf = test_ctx->c_buff; + len = &test_ctx->c_len; + } + else { + buf = test_ctx->s_buff; + len = &test_ctx->s_len; + } + + if ((unsigned)(*len + sz) > TEST_SSL_MEMIO_BUF_SZ) + return WOLFSSL_CBIO_ERR_WANT_READ; + + XMEMCPY(buf + *len, data, sz); + *len += sz; + + return sz; +} + +static WC_INLINE int test_ssl_memio_read_cb(WOLFSSL *ssl, char *data, int sz, + void *ctx) +{ + struct test_ssl_memio_ctx *test_ctx; + int read_sz; + byte *buf; + int *len; + + test_ctx = (struct test_ssl_memio_ctx*)ctx; + + if (wolfSSL_GetSide(ssl) == WOLFSSL_SERVER_END) { + buf = test_ctx->s_buff; + len = &test_ctx->s_len; + } + else { + buf = test_ctx->c_buff; + len = &test_ctx->c_len; + } + + if (*len == 0) + return WOLFSSL_CBIO_ERR_WANT_READ; + + read_sz = sz < *len ? sz : *len; + + XMEMCPY(data, buf, read_sz); + XMEMMOVE(buf, buf + read_sz, *len - read_sz); + + *len -= read_sz; + + return read_sz; +} + +static WC_INLINE int test_ssl_memio_setup(test_ssl_memio_ctx *ctx) +{ + EXPECT_DECLS; +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + int c_sharedCtx = 0; + int s_sharedCtx = 0; +#endif + const char* certFile = svrCertFile; + const char* keyFile = svrKeyFile; + + /******************************** + * Create WOLFSSL_CTX for client. + ********************************/ +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + if (ctx->c_ctx != NULL) { + c_sharedCtx = ctx->c_cb.isSharedCtx; + } + else +#endif + { + WOLFSSL_METHOD* method = NULL; + if (ctx->c_cb.method != NULL) { + method = ctx->c_cb.method(); + } + else { + method = wolfSSLv23_client_method(); + } + ExpectNotNull(ctx->c_ctx = wolfSSL_CTX_new(method)); + } + wolfSSL_SetIORecv(ctx->c_ctx, test_ssl_memio_read_cb); + wolfSSL_SetIOSend(ctx->c_ctx, test_ssl_memio_write_cb); +#ifdef WOLFSSL_ENCRYPTED_KEYS + wolfSSL_CTX_set_default_passwd_cb(ctx->c_ctx, PasswordCallBack); +#endif + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx->c_ctx, caCertFile, 0), + WOLFSSL_SUCCESS); +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + if (!c_sharedCtx) +#endif + { + ExpectIntEQ(wolfSSL_CTX_use_certificate_file(ctx->c_ctx, cliCertFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_file(ctx->c_ctx, cliKeyFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + } +#ifdef HAVE_CRL + if (ctx->c_cb.crlPemFile != NULL) { + ExpectIntEQ(wolfSSL_CTX_EnableCRL(ctx->c_ctx, WOLFSSL_CRL_CHECKALL), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_LoadCRLFile(ctx->c_ctx, ctx->c_cb.crlPemFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + } +#endif + if (ctx->c_ciphers != NULL) { + ExpectIntEQ(wolfSSL_CTX_set_cipher_list(ctx->c_ctx, ctx->c_ciphers), + WOLFSSL_SUCCESS); + } + if (ctx->c_cb.ctx_ready != NULL) { + ExpectIntEQ(ctx->c_cb.ctx_ready(ctx->c_ctx), TEST_SUCCESS); + } + + + /******************************** + * Create WOLFSSL_CTX for server. + ********************************/ + if (ctx->s_ctx != NULL) { +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + s_sharedCtx = 1; +#endif + ctx->s_cb.isSharedCtx = 1; + } + else + { + WOLFSSL_METHOD* method = NULL; + if (ctx->s_cb.method != NULL) { + method = ctx->s_cb.method(); + } + else { + method = wolfSSLv23_server_method(); + } + ExpectNotNull(ctx->s_ctx = wolfSSL_CTX_new(method)); + ctx->s_cb.isSharedCtx = 0; + } + if (!ctx->s_cb.ticNoInit && (ctx->s_ctx != NULL)) { +#if defined(HAVE_SESSION_TICKET) && \ + ((defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) || defined(HAVE_AESGCM)) +#if defined(OPENSSL_EXTRA) && defined(HAVE_AES_CBC) + OpenSSLTicketInit(); + wolfSSL_CTX_set_tlsext_ticket_key_cb(ctx->s_ctx, myTicketEncCbOpenSSL); +#elif defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) + TicketInit(); + wolfSSL_CTX_set_TicketEncCb(ctx->s_ctx, myTicketEncCb); +#endif +#endif + } + wolfSSL_SetIORecv(ctx->s_ctx, test_ssl_memio_read_cb); + wolfSSL_SetIOSend(ctx->s_ctx, test_ssl_memio_write_cb); + wolfSSL_CTX_set_verify(ctx->s_ctx, WOLFSSL_VERIFY_PEER | + WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx->s_ctx, cliCertFile, 0), + WOLFSSL_SUCCESS); +#ifdef WOLFSSL_ENCRYPTED_KEYS + wolfSSL_CTX_set_default_passwd_cb(ctx->s_ctx, PasswordCallBack); +#endif + if (ctx->s_cb.certPemFile != NULL) { + certFile = ctx->s_cb.certPemFile; + } +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + if (!s_sharedCtx) +#endif + { + ExpectIntEQ(wolfSSL_CTX_use_certificate_file(ctx->s_ctx, certFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + } + if (ctx->s_cb.keyPemFile != NULL) { + keyFile = ctx->s_cb.keyPemFile; + } +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + if (!s_sharedCtx) +#endif + { + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_file(ctx->s_ctx, keyFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + } + if (ctx->s_ciphers != NULL) { + ExpectIntEQ(wolfSSL_CTX_set_cipher_list(ctx->s_ctx, ctx->s_ciphers), + WOLFSSL_SUCCESS); + } + if (ctx->s_cb.ctx_ready != NULL) { + ExpectIntEQ(ctx->s_cb.ctx_ready(ctx->s_ctx), TEST_SUCCESS); + } + + + /**************************** + * Create WOLFSSL for client. + ****************************/ + ExpectNotNull(ctx->c_ssl = wolfSSL_new(ctx->c_ctx)); + wolfSSL_SetIOWriteCtx(ctx->c_ssl, ctx); + wolfSSL_SetIOReadCtx(ctx->c_ssl, ctx); + if (0 +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + || c_sharedCtx +#endif + ) + { + ExpectIntEQ(wolfSSL_use_certificate_file(ctx->c_ssl, cliCertFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_use_PrivateKey_file(ctx->c_ssl, cliKeyFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + } + if (ctx->c_cb.ssl_ready != NULL) { + ExpectIntEQ(ctx->c_cb.ssl_ready(ctx->c_ssl), TEST_SUCCESS); + } + + /**************************** + * Create WOLFSSL for server. + ****************************/ + ExpectNotNull(ctx->s_ssl = wolfSSL_new(ctx->s_ctx)); + wolfSSL_SetIOWriteCtx(ctx->s_ssl, ctx); + wolfSSL_SetIOReadCtx(ctx->s_ssl, ctx); + if (0 +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + || s_sharedCtx +#endif + ) + { + ExpectIntEQ(wolfSSL_use_certificate_file(ctx->s_ssl, certFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + } + if (0 +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + || s_sharedCtx +#endif + ) + { + ExpectIntEQ(wolfSSL_use_PrivateKey_file(ctx->s_ssl, keyFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + } +#if !defined(NO_FILESYSTEM) && !defined(NO_DH) + wolfSSL_SetTmpDH_file(ctx->s_ssl, dhParamFile, WOLFSSL_FILETYPE_PEM); +#elif !defined(NO_DH) + /* will repick suites with DHE, higher priority than PSK */ + SetDH(ctx->s_ssl); +#endif + if (ctx->s_cb.ssl_ready != NULL) { + ExpectIntEQ(ctx->s_cb.ssl_ready(ctx->s_ssl), TEST_SUCCESS); + } + + return EXPECT_RESULT(); +} + +static int test_ssl_memio_do_handshake(test_ssl_memio_ctx* ctx, int max_rounds, + int* rounds) +{ + int handshake_complete = 0; + int hs_c = 0; + int hs_s = 0; + int failing_s = 0; + int failing_c = 0; + int ret; + int err; + + if (rounds != NULL) { + *rounds = 0; + } + while ((!handshake_complete) && (max_rounds > 0)) { + if (!hs_c) { + ret = wolfSSL_connect(ctx->c_ssl); + if (ret == WOLFSSL_SUCCESS) { + hs_c = 1; + } + else { + err = wolfSSL_get_error(ctx->c_ssl, ret); + if (err != WOLFSSL_ERROR_WANT_READ && + err != WOLFSSL_ERROR_WANT_WRITE) { + failing_c = 1; + hs_c = 1; + if (failing_c && failing_s) { + break; + } + } + } + } + if (!hs_s) { + ret = wolfSSL_accept(ctx->s_ssl); + if (ret == WOLFSSL_SUCCESS) { + hs_s = 1; + } + else { + err = wolfSSL_get_error(ctx->s_ssl, ret); + if (err != WOLFSSL_ERROR_WANT_READ && + err != WOLFSSL_ERROR_WANT_WRITE) { + failing_s = 1; + hs_s = 1; + if (failing_c && failing_s) { + break; + } + } + } + } + handshake_complete = hs_c && hs_s; + max_rounds--; + if (rounds != NULL) { + *rounds += 1; + } + } + + if (!handshake_complete) { + return TEST_FAIL; + } + + return TEST_SUCCESS; +} + +static int test_ssl_memio_read_write(test_ssl_memio_ctx* ctx) +{ + EXPECT_DECLS; + char input[1024]; + int idx = 0; + const char* msg_c = "hello wolfssl!"; + int msglen_c = (int)XSTRLEN(msg_c); + const char* msg_s = "I hear you fa shizzle!"; + int msglen_s = (int)XSTRLEN(msg_s); + + if (ctx->c_msg != NULL) { + msg_c = ctx->c_msg; + msglen_c = ctx->c_msglen; + } + if (ctx->s_msg != NULL) { + msg_s = ctx->s_msg; + msglen_s = ctx->s_msglen; + } + + ExpectIntEQ(wolfSSL_write(ctx->c_ssl, msg_c, msglen_c), msglen_c); + ExpectIntGT(idx = wolfSSL_read(ctx->s_ssl, input, sizeof(input) - 1), 0); + input[idx] = '\0'; + ExpectIntGT(fprintf(stderr, "Client message: %s\n", input), 0); + ExpectIntEQ(wolfSSL_write(ctx->s_ssl, msg_s, msglen_s), msglen_s); + ctx->s_cb.return_code = EXPECT_RESULT(); + ExpectIntGT(idx = wolfSSL_read(ctx->c_ssl, input, sizeof(input) - 1), 0); + input[idx] = '\0'; + ExpectIntGT(fprintf(stderr, "Server response: %s\n", input), 0); + ctx->c_cb.return_code = EXPECT_RESULT(); + if (ctx->c_cb.on_result != NULL) { + ExpectIntEQ(ctx->c_cb.on_result(ctx->c_ssl), TEST_SUCCESS); + } + if (ctx->s_cb.on_result != NULL) { + ExpectIntEQ(ctx->s_cb.on_result(ctx->s_ssl), TEST_SUCCESS); + } + + return EXPECT_RESULT(); +} + +static void test_ssl_memio_cleanup(test_ssl_memio_ctx* ctx) +{ + ctx->c_cb.last_err = wolfSSL_get_error(ctx->c_ssl, 0); + ctx->s_cb.last_err = wolfSSL_get_error(ctx->s_ssl, 0); + if (ctx->c_cb.on_cleanup != NULL) { + ctx->c_cb.on_cleanup(ctx->c_ssl); + } + if (ctx->s_cb.on_cleanup != NULL) { + ctx->s_cb.on_cleanup(ctx->s_ssl); + } + wolfSSL_shutdown(ctx->s_ssl); + wolfSSL_shutdown(ctx->c_ssl); + wolfSSL_free(ctx->s_ssl); + wolfSSL_free(ctx->c_ssl); + if (!ctx->s_cb.isSharedCtx) { + wolfSSL_CTX_free(ctx->s_ctx); + ctx->s_ctx = NULL; + } + if (!ctx->c_cb.isSharedCtx) { + wolfSSL_CTX_free(ctx->c_ctx); + ctx->c_ctx = NULL; + } + + if (!ctx->s_cb.ticNoInit) { +#if defined(HAVE_SESSION_TICKET) && \ + ((defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) || defined(HAVE_AESGCM)) +#if defined(OPENSSL_EXTRA) && defined(HAVE_AES_CBC) + OpenSSLTicketCleanup(); +#elif defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) + TicketCleanup(); +#endif +#endif + } +} + +int test_wolfSSL_client_server_nofail_memio(test_ssl_cbf* client_cb, + test_ssl_cbf* server_cb, cbType client_on_handshake) +{ + EXPECT_DECLS; + struct test_ssl_memio_ctx test_ctx; +#ifdef WOLFSSL_HAVE_TLS_UNIQUE + size_t msg_len; +#endif /* WOLFSSL_HAVE_TLS_UNIQUE */ + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + XMEMCPY(&test_ctx.c_cb, client_cb, sizeof(test_ssl_cbf)); + XMEMCPY(&test_ctx.s_cb, server_cb, sizeof(test_ssl_cbf)); + + test_ctx.c_ctx = client_cb->ctx; + test_ctx.s_ctx = server_cb->ctx; + test_ctx.c_cb.return_code = TEST_FAIL; + test_ctx.s_cb.return_code = TEST_FAIL; + + ExpectIntEQ(test_ssl_memio_setup(&test_ctx), TEST_SUCCESS); + ExpectIntEQ(test_ssl_memio_do_handshake(&test_ctx, 10, NULL), TEST_SUCCESS); + + if (client_on_handshake != NULL) { + ExpectIntEQ(client_on_handshake(test_ctx.c_ctx, test_ctx.c_ssl), + TEST_SUCCESS); + } +#ifdef WOLFSSL_HAVE_TLS_UNIQUE + XMEMSET(server_side_msg2, 0, MD_MAX_SIZE); + msg_len = wolfSSL_get_peer_finished(test_ctx.s_ssl, server_side_msg2, + MD_MAX_SIZE); + ExpectIntGE(msg_len, 0); + + XMEMSET(server_side_msg1, 0, MD_MAX_SIZE); + msg_len = wolfSSL_get_finished(test_ctx.s_ssl, server_side_msg1, + MD_MAX_SIZE); + ExpectIntGE(msg_len, 0); +#endif /* WOLFSSL_HAVE_TLS_UNIQUE */ + + ExpectIntEQ(test_ssl_memio_read_write(&test_ctx), TEST_SUCCESS); + test_ssl_memio_cleanup(&test_ctx); + + client_cb->return_code = test_ctx.c_cb.return_code; + server_cb->return_code = test_ctx.s_cb.return_code; + + return EXPECT_RESULT(); +} +#endif + #ifdef HAVE_IO_TESTS_DEPENDENCIES #ifdef WOLFSSL_SESSION_EXPORT @@ -5221,85 +5802,6 @@ static int nonblocking_accept_read(void* args, WOLFSSL* ssl, SOCKET_T* sockfd) } #endif /* WOLFSSL_SESSION_EXPORT */ -/* TODO: Expand and enable this when EVP_chacha20_poly1305 is supported */ -#if defined(HAVE_SESSION_TICKET) && defined(OPENSSL_EXTRA) && \ - defined(HAVE_AES_CBC) - - typedef struct openssl_key_ctx { - byte name[WOLFSSL_TICKET_NAME_SZ]; /* server name */ - byte key[WOLFSSL_TICKET_KEY_SZ]; /* cipher key */ - byte hmacKey[WOLFSSL_TICKET_NAME_SZ]; /* hmac key */ - byte iv[WOLFSSL_TICKET_IV_SZ]; /* cipher iv */ - } openssl_key_ctx; - - static THREAD_LS_T openssl_key_ctx myOpenSSLKey_ctx; - static THREAD_LS_T WC_RNG myOpenSSLKey_rng; - - static WC_INLINE int OpenSSLTicketInit(void) - { - int ret = wc_InitRng(&myOpenSSLKey_rng); - if (ret != 0) return ret; - - ret = wc_RNG_GenerateBlock(&myOpenSSLKey_rng, myOpenSSLKey_ctx.name, - sizeof(myOpenSSLKey_ctx.name)); - if (ret != 0) return ret; - - ret = wc_RNG_GenerateBlock(&myOpenSSLKey_rng, myOpenSSLKey_ctx.key, - sizeof(myOpenSSLKey_ctx.key)); - if (ret != 0) return ret; - - ret = wc_RNG_GenerateBlock(&myOpenSSLKey_rng, myOpenSSLKey_ctx.hmacKey, - sizeof(myOpenSSLKey_ctx.hmacKey)); - if (ret != 0) return ret; - - ret = wc_RNG_GenerateBlock(&myOpenSSLKey_rng, myOpenSSLKey_ctx.iv, - sizeof(myOpenSSLKey_ctx.iv)); - if (ret != 0) return ret; - - return 0; - } - - static WC_INLINE int myTicketEncCbOpenSSL(WOLFSSL* ssl, - byte name[WOLFSSL_TICKET_NAME_SZ], - byte iv[WOLFSSL_TICKET_IV_SZ], - WOLFSSL_EVP_CIPHER_CTX *ectx, - WOLFSSL_HMAC_CTX *hctx, int enc) { - (void)ssl; - if (enc) { - XMEMCPY(name, myOpenSSLKey_ctx.name, sizeof(myOpenSSLKey_ctx.name)); - XMEMCPY(iv, myOpenSSLKey_ctx.iv, sizeof(myOpenSSLKey_ctx.iv)); - } - else if (XMEMCMP(name, myOpenSSLKey_ctx.name, - sizeof(myOpenSSLKey_ctx.name)) != 0 || - XMEMCMP(iv, myOpenSSLKey_ctx.iv, - sizeof(myOpenSSLKey_ctx.iv)) != 0) { - return 0; - } - HMAC_Init_ex(hctx, myOpenSSLKey_ctx.hmacKey, WOLFSSL_TICKET_NAME_SZ, EVP_sha256(), NULL); - if (enc) - EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, myOpenSSLKey_ctx.key, iv); - else - EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, myOpenSSLKey_ctx.key, iv); - return 1; - } - - static WC_INLINE void OpenSSLTicketCleanup(void) - { - wc_FreeRng(&myOpenSSLKey_rng); - } -#endif - -#ifdef WOLFSSL_HAVE_TLS_UNIQUE - #ifdef WC_SHA512_DIGEST_SIZE - #define MD_MAX_SIZE WC_SHA512_DIGEST_SIZE - #else - #define MD_MAX_SIZE WC_SHA256_DIGEST_SIZE - #endif - byte server_side_msg1[MD_MAX_SIZE] = {0};/* msg sent by server */ - byte server_side_msg2[MD_MAX_SIZE] = {0};/* msg received from client */ - byte client_side_msg1[MD_MAX_SIZE] = {0};/* msg sent by client */ - byte client_side_msg2[MD_MAX_SIZE] = {0};/* msg received from server */ -#endif /* WOLFSSL_HAVE_TLS_UNIQUE */ static THREAD_RETURN WOLFSSL_THREAD test_server_nofail(void* args) { SOCKET_T sockfd = 0; @@ -6977,23 +7479,26 @@ static int test_wolfSSL_reuse_WOLFSSLobj(void) return res; } -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) -static void test_wolfSSL_CTX_verifyDepth_ServerClient_1_ctx_ready( +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) +static int test_wolfSSL_CTX_verifyDepth_ServerClient_1_ctx_ready( WOLFSSL_CTX* ctx) { wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); myVerifyAction = VERIFY_USE_PREVERFIY; wolfSSL_CTX_set_verify_depth(ctx, 2); + return TEST_SUCCESS; } #endif static int test_wolfSSL_CTX_verifyDepth_ServerClient_1(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) EXPECT_DECLS; - callback_functions client_cbf; - callback_functions server_cbf; + test_ssl_cbf client_cbf; + test_ssl_cbf server_cbf; XMEMSET(&client_cbf, 0, sizeof(callback_functions)); XMEMSET(&server_cbf, 0, sizeof(callback_functions)); @@ -7005,34 +7510,39 @@ static int test_wolfSSL_CTX_verifyDepth_ServerClient_1(void) test_wolfSSL_CTX_verifyDepth_ServerClient_1_ctx_ready; /* test case 1 verify depth is equal to peer chain */ - test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, NULL), TEST_SUCCESS); ExpectIntEQ(client_cbf.return_code, TEST_SUCCESS); ExpectIntEQ(server_cbf.return_code, TEST_SUCCESS); res = EXPECT_RESULT(); -#endif /* (OPENSSL_EXTRA) && !(WOLFSSL_TIRTOS) && (NO_WOLFSSL_CLIENT) */ +#endif /* OPENSSL_EXTRA && !WOLFSSL_TIRTOS && + * HAVE_SSL_MEMIO_TESTS_DEPENDENCIES */ return res; } -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) -static void test_wolfSSL_CTX_verifyDepth_ServerClient_2_ctx_ready( +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) +static int test_wolfSSL_CTX_verifyDepth_ServerClient_2_ctx_ready( WOLFSSL_CTX* ctx) { wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); myVerifyAction = VERIFY_USE_PREVERFIY; wolfSSL_CTX_set_verify_depth(ctx, 1); + return TEST_SUCCESS; } #endif static int test_wolfSSL_CTX_verifyDepth_ServerClient_2(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) EXPECT_DECLS; - callback_functions client_cbf; - callback_functions server_cbf; + test_ssl_cbf client_cbf; + test_ssl_cbf server_cbf; XMEMSET(&client_cbf, 0, sizeof(callback_functions)); XMEMSET(&server_cbf, 0, sizeof(callback_functions)); @@ -7048,34 +7558,39 @@ static int test_wolfSSL_CTX_verifyDepth_ServerClient_2(void) * verify result becomes MAX_CHAIN_ERROR, but it is overridden in * callback. */ - test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, NULL), TEST_SUCCESS); ExpectIntEQ(client_cbf.return_code, TEST_SUCCESS); ExpectIntEQ(server_cbf.return_code, TEST_SUCCESS); res = EXPECT_RESULT(); -#endif /* (OPENSSL_EXTRA) && !(WOLFSSL_TIRTOS) && (NO_WOLFSSL_CLIENT) */ +#endif /* OPENSSL_EXTRA && !WOLFSSL_TIRTOS && + * HAVE_SSL_MEMIO_TESTS_DEPENDENCIES */ return res; } -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) -static void test_wolfSSL_CTX_verifyDepth_ServerClient_3_ctx_ready( +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) +static int test_wolfSSL_CTX_verifyDepth_ServerClient_3_ctx_ready( WOLFSSL_CTX* ctx) { wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify); myVerifyAction = VERIFY_USE_PREVERFIY; wolfSSL_CTX_set_verify_depth(ctx, 0); + return TEST_SUCCESS; } #endif static int test_wolfSSL_CTX_verifyDepth_ServerClient_3(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && !defined(NO_WOLFSSL_CLIENT) +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_TIRTOS) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) EXPECT_DECLS; - callback_functions client_cbf; - callback_functions server_cbf; + test_ssl_cbf client_cbf; + test_ssl_cbf server_cbf; XMEMSET(&client_cbf, 0, sizeof(callback_functions)); XMEMSET(&server_cbf, 0, sizeof(callback_functions)); @@ -7091,83 +7606,63 @@ static int test_wolfSSL_CTX_verifyDepth_ServerClient_3(void) * verify result becomes MAX_CHAIN_ERRO. call-back returns failure. * therefore, handshake becomes failure. */ - test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, NULL), TEST_SUCCESS); ExpectIntEQ(client_cbf.return_code, TEST_SUCCESS); ExpectIntEQ(server_cbf.return_code, TEST_SUCCESS); res = EXPECT_RESULT(); -#endif /* (OPENSSL_EXTRA) && !(WOLFSSL_TIRTOS) && (NO_WOLFSSL_CLIENT) */ +#endif /* OPENSSL_EXTRA && !WOLFSSL_TIRTOS && + * HAVE_SSL_MEMIO_TESTS_DEPENDENCIES */ return res; } +#if defined(OPENSSL_ALL) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ + !defined(WOLFSSL_TIRTOS) && !defined(NO_AES) && !defined(WOLFSSL_NO_TLS12) \ + && !defined(NO_SHA256) && defined(HAVE_ECC) +static int test_wolfSSL_CTX_set_cipher_list_server_ctx_ready(WOLFSSL_CTX* ctx) +{ + EXPECT_DECLS; + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctx, "DEFAULT:!NULL")); + return EXPECT_RESULT(); +} + +static int test_wolfSSL_CTX_set_cipher_list_client_ctx_ready(WOLFSSL_CTX* ctx) +{ + EXPECT_DECLS; + ExpectTrue(wolfSSL_CTX_set_cipher_list(ctx, "ECDHE-RSA-AES128-SHA256")); + return EXPECT_RESULT(); +} +#endif static int test_wolfSSL_CTX_set_cipher_list(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_ALL) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ +#if defined(OPENSSL_ALL) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ !defined(WOLFSSL_TIRTOS) && !defined(NO_AES) && !defined(WOLFSSL_NO_TLS12) \ && !defined(NO_SHA256) && defined(HAVE_ECC) EXPECT_DECLS; - WOLFSSL_CTX* ctx = NULL; WOLFSSL_CTX* ctxClient = NULL; WOLFSSL* sslClient = NULL; - tcp_ready ready; - func_args client_args; - func_args server_args; - callback_functions client_cb; - callback_functions server_cb; - THREAD_TYPE serverThread; - - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); + test_ssl_cbf client_cbf; + test_ssl_cbf server_cbf; - StartTCP(); - InitTcpReady(&ready); - - XMEMSET(&client_cb, 0, sizeof(callback_functions)); - XMEMSET(&server_cb, 0, sizeof(callback_functions)); - - ExpectNotNull((ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method()))); - ExpectTrue(wolfSSL_CTX_set_cipher_list(ctx, "DEFAULT:!NULL")); - ExpectIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); - ExpectIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, SSL_FILETYPE_PEM)); - ExpectIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); - - - ExpectNotNull((ctxClient = wolfSSL_CTX_new(wolfTLSv1_2_client_method()))); - ExpectTrue(wolfSSL_CTX_set_cipher_list(ctxClient, "ECDHE-RSA-AES128-SHA256")); - - client_cb.ctx = ctxClient; - server_cb.ctx = ctx; - - /* we are responsible for free'ing WOLFSSL_CTX */ - server_cb.isSharedCtx = client_cb.isSharedCtx = 1; - - server_args.signal = &ready; - server_args.callbacks = &server_cb; - client_args.signal = &ready; - client_args.callbacks = &client_cb; - client_args.return_code = TEST_FAIL; - - if (EXPECT_SUCCESS()) { - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); - } + XMEMSET(&client_cbf, 0, sizeof(client_cbf)); + XMEMSET(&server_cbf, 0, sizeof(server_cbf)); - wolfSSL_CTX_free(client_cb.ctx); - wolfSSL_CTX_free(server_cb.ctx); + server_cbf.method = wolfTLSv1_2_server_method; + server_cbf.ctx_ready = test_wolfSSL_CTX_set_cipher_list_server_ctx_ready; + client_cbf.method = wolfTLSv1_2_client_method; + client_cbf.ctx_ready = test_wolfSSL_CTX_set_cipher_list_client_ctx_ready; - ExpectIntEQ(server_args.return_code, TEST_SUCCESS); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, NULL), TEST_SUCCESS); - FreeTcpReady(&ready); + ExpectIntEQ(client_cbf.return_code, TEST_SUCCESS); + ExpectIntEQ(server_cbf.return_code, TEST_SUCCESS); /* check with cipher string that has '+' */ ExpectNotNull((ctxClient = wolfSSL_CTX_new(wolfTLSv1_2_client_method()))); @@ -7205,203 +7700,51 @@ static int test_wolfSSL_CTX_set_cipher_list(void) return res; } -static int test_client_get_finished(void* args, cbType cb) +#if defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ + defined(WOLFSSL_HAVE_TLS_UNIQUE) +static int test_wolfSSL_get_finished_client_on_handshake(WOLFSSL_CTX* ctx, + WOLFSSL* ssl) { -#if defined(WOLFSSL_HAVE_TLS_UNIQUE) && !defined(NO_WOLFSSL_CLIENT) - SOCKET_T sockfd = 0; - callback_functions* cbf; - - WOLFSSL_CTX* ctx = 0; - WOLFSSL* ssl = 0; - - char msg[64] = "hello wolfssl!"; - char reply[1024]; - int msgSz = (int)XSTRLEN(msg); - int ret, err = 0; - WOLFSSL_METHOD* method = NULL; - size_t msg_len = 0; - - (void) args; - (void) cb; - - ((func_args*)args)->return_code = TEST_FAIL; - cbf = ((func_args*)args)->callbacks; - - if (cbf != NULL && cbf->method != NULL) { - method = cbf->method(); - } - else { - method = wolfSSLv23_client_method(); - } - ctx = wolfSSL_CTX_new(method); - - /* Do connect here so server detects failures */ - tcp_connect(&sockfd, wolfSSLIP, ((func_args*)args)->signal->port, - 0, 0, NULL); - - if (wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0) != WOLFSSL_SUCCESS) - { - /* err_sys("can't load ca file, Please run from wolfSSL home dir");*/ - goto done; - } - - if (wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, - WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { - goto done; - } - if (wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, - WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) { - goto done; - } - - /* call ctx setup callback */ - if (cbf != NULL && cbf->ctx_ready != NULL) { - cbf->ctx_ready(ctx); - } - - ssl = wolfSSL_new(ctx); - if (ssl == NULL) { - goto done; - } - - if (wolfSSL_set_fd(ssl, sockfd) != WOLFSSL_SUCCESS) { - goto done; - } - - /* call ssl setup callback */ - if (cbf != NULL && cbf->ssl_ready != NULL) { - cbf->ssl_ready(ssl); - } + EXPECT_DECLS; + size_t msg_len; - #ifdef WOLFSSL_ASYNC_CRYPT - err = 0; /* Reset error */ - #endif - do { - #ifdef WOLFSSL_ASYNC_CRYPT - if (err == WC_PENDING_E) { - ret = wolfSSL_AsyncPoll(ssl, WOLF_POLL_FLAG_CHECK_HW); - if (ret < 0) { break; } else if (ret == 0) { continue; } - } - #endif - ret = wolfSSL_connect(ssl); - err = wolfSSL_get_error(ssl, 0); - } while (err == WC_PENDING_E); - if (ret != WOLFSSL_SUCCESS) { - char buff[WOLFSSL_MAX_ERROR_SZ]; - fprintf(stderr, "error = %d, %s\n", err, - wolfSSL_ERR_error_string(err, buff)); - goto done; - } + (void)ctx; /* get_finished test */ /* 1. get own sent message */ XMEMSET(client_side_msg1, 0, MD_MAX_SIZE); msg_len = wolfSSL_get_finished(ssl, client_side_msg1, MD_MAX_SIZE); - AssertIntGE(msg_len, 0); + ExpectIntGE(msg_len, 0); /* 2. get peer message */ XMEMSET(client_side_msg2, 0, MD_MAX_SIZE); msg_len = wolfSSL_get_peer_finished(ssl, client_side_msg2, MD_MAX_SIZE); - AssertIntGE(msg_len, 0); - - if (cb != NULL) - (cb)(ctx, ssl); - - #ifdef WOLFSSL_ASYNC_CRYPT - err = 0; /* Reset error */ - #endif - do { - #ifdef WOLFSSL_ASYNC_CRYPT - if (err == WC_PENDING_E) { - ret = wolfSSL_AsyncPoll(ssl, WOLF_POLL_FLAG_CHECK_HW); - if (ret < 0) { break; } else if (ret == 0) { continue; } - } - #endif - ret = wolfSSL_write(ssl, msg, msgSz); - err = wolfSSL_get_error(ssl, 0); - } while (err == WC_PENDING_E); - if (ret != msgSz) { - /*err_sys("SSL_write failed");*/ - goto done; - } - - #ifdef WOLFSSL_ASYNC_CRYPT - err = 0; /* Reset error */ - #endif - do { - #ifdef WOLFSSL_ASYNC_CRYPT - if (err == WC_PENDING_E) { - ret = wolfSSL_AsyncPoll(ssl, WOLF_POLL_FLAG_CHECK_HW); - if (ret < 0) { break; } else if (ret == 0) { continue; } - } - #endif - ret = wolfSSL_read(ssl, reply, sizeof(reply)-1); - err = wolfSSL_get_error(ssl, 0); - } while (err == WC_PENDING_E); - if (ret > 0) { - reply[ret] = '\0'; - fprintf(stderr, "Server response: %s\n", reply); - } - else if (ret < 0) { - goto done; - } - - ((func_args*)args)->return_code = TEST_SUCCESS; - -done: - wolfSSL_free(ssl); - wolfSSL_CTX_free(ctx); - CloseSocket(sockfd); - -#else - (void)args; - (void)cb; -#endif /* WOLFSSL_HAVE_TLS_UNIQUE && !NO_WOLFSSL_CLIENT */ - - return 0; + ExpectIntGE(msg_len, 0); + return EXPECT_RESULT(); } +#endif static int test_wolfSSL_get_finished(void) { int res = TEST_SKIPPED; -#if !defined(NO_RSA) && defined(WOLFSSL_HAVE_TLS_UNIQUE) +#if defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ + defined(WOLFSSL_HAVE_TLS_UNIQUE) EXPECT_DECLS; - tcp_ready ready; - func_args client_args; - func_args server_args; - THREAD_TYPE serverThread; + test_ssl_cbf client_cbf; + test_ssl_cbf server_cbf; - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif - - server_args.signal = &ready; - client_args.signal = &ready; - - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_get_finished(&client_args, NULL); - join_thread(serverThread); + XMEMSET(&client_cbf, 0, sizeof(client_cbf)); + XMEMSET(&server_cbf, 0, sizeof(server_cbf)); - ExpectTrue(client_args.return_code); - ExpectTrue(server_args.return_code); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, test_wolfSSL_get_finished_client_on_handshake), + TEST_SUCCESS); /* test received msg vs sent msg */ ExpectIntEQ(0, XMEMCMP(client_side_msg1, server_side_msg2, MD_MAX_SIZE)); ExpectIntEQ(0, XMEMCMP(client_side_msg2, server_side_msg1, MD_MAX_SIZE)); - FreeTcpReady(&ready); - res = EXPECT_RESULT(); -#else - (void)test_client_get_finished; -#endif /* !NO_RSA && WOLFSSL_HAVE_TLS_UNIQUE */ +#endif /* HAVE_SSL_MEMIO_TESTS_DEPENDENCIES && WOLFSSL_HAVE_TLS_UNIQUE */ return res; } @@ -7546,7 +7889,7 @@ static int test_wolfSSL_CTX_add_session(void) test_wolfSSL_CTX_add_session_server_ctx = NULL; #ifdef NO_SESSION_CACHE_REF - for (j = 0; j < 5; j++) { + for (j = 0; j < 4; j++) { #else /* The session may be overwritten in this case. Do only one resumption * to stop this test from failing intermittently. */ @@ -7610,10 +7953,10 @@ static int test_wolfSSL_CTX_add_session(void) return res; } -#if defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_EXT_CACHE) && \ - !defined(SINGLE_THREADED) && defined(WOLFSSL_TLS13) && \ - !defined(NO_SESSION_CACHE) && defined(OPENSSL_EXTRA) && \ - defined(SESSION_CERTS) && defined(HAVE_SESSION_TICKET) && \ +#if defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && defined(HAVE_EXT_CACHE) && \ + defined(WOLFSSL_TLS13) && !defined(NO_SESSION_CACHE) && \ + defined(OPENSSL_EXTRA) && defined(SESSION_CERTS) && \ + defined(HAVE_SESSION_TICKET) && \ !defined(TITAN_SESSION_CACHE) && \ !defined(HUGE_SESSION_CACHE) && \ !defined(BIG_SESSION_CACHE) && \ @@ -7754,7 +8097,7 @@ static WOLFSSL_SESSION *twcase_get_sessionCb(WOLFSSL *ssl, } return NULL; } -static void twcase_get_sessionCb_cleanup(void) +static int twcase_get_sessionCb_cleanup(void) { int i; int cnt = 0; @@ -7771,15 +8114,18 @@ static void twcase_get_sessionCb_cleanup(void) fprintf(stderr, "\t\ttwcase_get_sessionCb_cleanup freed %d sessions\n", cnt); + + return TEST_SUCCESS; } -static void twcase_cache_intOff_extOff(WOLFSSL_CTX* ctx) +static int twcase_cache_intOff_extOff(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; /* off - Disable internal cache */ - AssertIntEQ(wolfSSL_CTX_set_session_cache_mode(ctx, + ExpectIntEQ(wolfSSL_CTX_set_session_cache_mode(ctx, WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE), WOLFSSL_SUCCESS); #ifdef OPENSSL_EXTRA - AssertIntEQ(wolfSSL_CTX_get_session_cache_mode(ctx) & + ExpectIntEQ(wolfSSL_CTX_get_session_cache_mode(ctx) & WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE, WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE); #endif @@ -7787,37 +8133,43 @@ static void twcase_cache_intOff_extOff(WOLFSSL_CTX* ctx) /* Require both peers to provide certs */ wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + return EXPECT_RESULT(); } -static void twcase_cache_intOn_extOff(WOLFSSL_CTX* ctx) +static int twcase_cache_intOn_extOff(WOLFSSL_CTX* ctx) { - /* on - internal cache is on by default*/ - /* off - Donot setup external cache */ - /* Require both peers to provide certs */ - wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + EXPECT_DECLS; + /* on - internal cache is on by default*/ + /* off - Donot setup external cache */ + /* Require both peers to provide certs */ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + return EXPECT_RESULT(); } -static void twcase_cache_intOff_extOn(WOLFSSL_CTX* ctx) +static int twcase_cache_intOff_extOn(WOLFSSL_CTX* ctx) { - /* off - Disable internal cache */ - AssertIntEQ(wolfSSL_CTX_set_session_cache_mode(ctx, - WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE), WOLFSSL_SUCCESS); + EXPECT_DECLS; + /* off - Disable internal cache */ + ExpectIntEQ(wolfSSL_CTX_set_session_cache_mode(ctx, + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE), WOLFSSL_SUCCESS); #ifdef OPENSSL_EXTRA - AssertIntEQ(wolfSSL_CTX_get_session_cache_mode(ctx) & - WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE, - WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE); + ExpectIntEQ(wolfSSL_CTX_get_session_cache_mode(ctx) & + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE, + WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE); #endif - /* on - Enable external cache */ - wolfSSL_CTX_sess_set_new_cb(ctx, twcase_new_sessionCb); - wolfSSL_CTX_sess_set_remove_cb(ctx, twcase_remove_sessionCb); - wolfSSL_CTX_sess_set_get_cb(ctx, twcase_get_sessionCb); + /* on - Enable external cache */ + wolfSSL_CTX_sess_set_new_cb(ctx, twcase_new_sessionCb); + wolfSSL_CTX_sess_set_remove_cb(ctx, twcase_remove_sessionCb); + wolfSSL_CTX_sess_set_get_cb(ctx, twcase_get_sessionCb); - /* Require both peers to provide certs */ - wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + /* Require both peers to provide certs */ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + return EXPECT_RESULT(); } -static void twcase_cache_intOn_extOn(WOLFSSL_CTX* ctx) +static int twcase_cache_intOn_extOn(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; /* on - internal cache is on by default */ /* on - Enable external cache */ wolfSSL_CTX_sess_set_new_cb(ctx, twcase_new_sessionCb); @@ -7826,9 +8178,11 @@ static void twcase_cache_intOn_extOn(WOLFSSL_CTX* ctx) /* Require both peers to provide certs */ wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + return EXPECT_RESULT(); } -static void twcase_cache_intOn_extOn_noTicket(WOLFSSL_CTX* ctx) +static int twcase_cache_intOn_extOn_noTicket(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; /* on - internal cache is on by default */ /* on - Enable external cache */ wolfSSL_CTX_sess_set_new_cb(ctx, twcase_new_sessionCb); @@ -7838,17 +8192,19 @@ static void twcase_cache_intOn_extOn_noTicket(WOLFSSL_CTX* ctx) wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TICKET); /* Require both peers to provide certs */ wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + return EXPECT_RESULT(); } -static void twcase_server_sess_ctx_pre_shutdown(WOLFSSL* ssl) +static int twcase_server_sess_ctx_pre_shutdown(WOLFSSL* ssl) { + EXPECT_DECLS; WOLFSSL_SESSION** sess; if (wolfSSL_is_server(ssl)) sess = &twcase_server_first_session_ptr; else - return; + return TEST_SUCCESS; if (*sess == NULL) { - AssertNotNull(*sess = wolfSSL_get1_session(ssl)); + ExpectNotNull(*sess = wolfSSL_get1_session(ssl)); /* Now save the session in the internal store to make it available * for lookup. For TLS 1.3, we can't save the session without * WOLFSSL_TICKET_HAVE_ID because there is no way to retrieve the @@ -7859,14 +8215,14 @@ static void twcase_server_sess_ctx_pre_shutdown(WOLFSSL* ssl) && wolfSSL_version(ssl) != DTLS1_3_VERSION #endif ) { - AssertIntEQ(wolfSSL_CTX_add_session(wolfSSL_get_SSL_CTX(ssl), + ExpectIntEQ(wolfSSL_CTX_add_session(wolfSSL_get_SSL_CTX(ssl), *sess), WOLFSSL_SUCCESS); } } /* Save CTX to be able to decrypt tickets */ if (twcase_server_current_ctx_ptr == NULL) { - AssertNotNull(twcase_server_current_ctx_ptr = wolfSSL_get_SSL_CTX(ssl)); - AssertIntEQ(wolfSSL_CTX_up_ref(wolfSSL_get_SSL_CTX(ssl)), + ExpectNotNull(twcase_server_current_ctx_ptr = wolfSSL_get_SSL_CTX(ssl)); + ExpectIntEQ(wolfSSL_CTX_up_ref(wolfSSL_get_SSL_CTX(ssl)), WOLFSSL_SUCCESS); } #ifdef SESSION_CERTS @@ -7879,25 +8235,27 @@ static void twcase_server_sess_ctx_pre_shutdown(WOLFSSL* ssl) * for all connections. TLS 1.3 only has tickets so if we don't * include the session id in the ticket then the certificates * will not be available on resumption. */ - WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl); - AssertNotNull(peer); + WOLFSSL_X509* peer = NULL; + ExpectNotNull(peer = wolfSSL_get_peer_certificate(ssl)); wolfSSL_X509_free(peer); - AssertNotNull(wolfSSL_SESSION_get_peer_chain(*sess)); + ExpectNotNull(wolfSSL_SESSION_get_peer_chain(*sess)); } #endif + return EXPECT_RESULT(); } -static void twcase_client_sess_ctx_pre_shutdown(WOLFSSL* ssl) +static int twcase_client_sess_ctx_pre_shutdown(WOLFSSL* ssl) { + EXPECT_DECLS; WOLFSSL_SESSION** sess; sess = &twcase_client_first_session_ptr; if (*sess == NULL) { - AssertNotNull(*sess = wolfSSL_get1_session(ssl)); + ExpectNotNull(*sess = wolfSSL_get1_session(ssl)); } else { /* If we have a session retrieved then remaining connections should be * resuming on that session */ - AssertIntEQ(wolfSSL_session_reused(ssl), 1); + ExpectIntEQ(wolfSSL_session_reused(ssl), 1); } #ifdef SESSION_CERTS @@ -7908,22 +8266,25 @@ static void twcase_client_sess_ctx_pre_shutdown(WOLFSSL* ssl) { WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl); - AssertNotNull(peer); + ExpectNotNull(peer); wolfSSL_X509_free(peer); - AssertNotNull(wolfSSL_SESSION_get_peer_chain(*sess)); + ExpectNotNull(wolfSSL_SESSION_get_peer_chain(*sess)); #ifdef OPENSSL_EXTRA - AssertNotNull(wolfSSL_SESSION_get0_peer(*sess)); + ExpectNotNull(wolfSSL_SESSION_get0_peer(*sess)); #endif } #endif + return EXPECT_RESULT(); } -static void twcase_client_set_sess_ssl_ready(WOLFSSL* ssl) +static int twcase_client_set_sess_ssl_ready(WOLFSSL* ssl) { + EXPECT_DECLS; /* Set the session to reuse for the client */ - AssertNotNull(ssl); - AssertNotNull(twcase_client_first_session_ptr); - AssertIntEQ(wolfSSL_set_session(ssl,twcase_client_first_session_ptr), + ExpectNotNull(ssl); + ExpectNotNull(twcase_client_first_session_ptr); + ExpectIntEQ(wolfSSL_set_session(ssl,twcase_client_first_session_ptr), WOLFSSL_SUCCESS); + return EXPECT_RESULT(); } #endif @@ -7931,9 +8292,9 @@ static int test_wolfSSL_CTX_add_session_ext(void) { int res = TEST_SKIPPED; #if defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_EXT_CACHE) && \ - !defined(SINGLE_THREADED) && defined(WOLFSSL_TLS13) && \ - !defined(NO_SESSION_CACHE) && defined(OPENSSL_EXTRA) && \ - defined(SESSION_CERTS) && defined(HAVE_SESSION_TICKET) && \ + defined(WOLFSSL_TLS13) && !defined(NO_SESSION_CACHE) && \ + defined(OPENSSL_EXTRA) && defined(SESSION_CERTS) && \ + defined(HAVE_SESSION_TICKET) && \ !defined(TITAN_SESSION_CACHE) && \ !defined(HUGE_SESSION_CACHE) && \ !defined(BIG_SESSION_CACHE) && \ @@ -7984,8 +8345,8 @@ static int test_wolfSSL_CTX_add_session_ext(void) for (j = 0; j < 5; j++) { int tls13 = XSTRSTR(params[i].tls_version, "TLSv1_3") != NULL; int dtls = XSTRSTR(params[i].tls_version, "DTLS") != NULL; - callback_functions client_cb; - callback_functions server_cb; + test_ssl_cbf client_cb; + test_ssl_cbf server_cb; (void)dtls; @@ -8039,13 +8400,16 @@ static int test_wolfSSL_CTX_add_session_ext(void) server_cb.ctx = twcase_server_current_ctx_ptr; server_cb.isSharedCtx = 1; - test_wolfSSL_client_server_nofail(&client_cb, &server_cb); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cb, + &server_cb, NULL), TEST_SUCCESS); - ExpectTrue(client_cb.return_code); - ExpectTrue(server_cb.return_code); ExpectIntEQ(twcase_get_session_called, 0); - if (EXPECT_FAIL()) + if (EXPECT_FAIL()) { + wolfSSL_SESSION_free(twcase_client_first_session_ptr); + wolfSSL_SESSION_free(twcase_server_first_session_ptr); + wolfSSL_CTX_free(twcase_server_current_ctx_ptr); break; + } switch (j) { case 0: @@ -8082,10 +8446,8 @@ static int test_wolfSSL_CTX_add_session_ext(void) /* try session resumption */ client_cb.ssl_ready = twcase_client_set_sess_ssl_ready; - test_wolfSSL_client_server_nofail(&client_cb, &server_cb); - - ExpectTrue(client_cb.return_code); - ExpectTrue(server_cb.return_code); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cb, + &server_cb, NULL), TEST_SUCCESS); /* Clear cache before checking */ wolfSSL_CTX_flush_sessions(NULL, -1); @@ -11135,59 +11497,60 @@ static int test_wolfSSL_X509_verify(void) } -#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ - !defined(NO_WOLFSSL_CLIENT) && !defined(NO_DH) && !defined(NO_AES) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(SINGLE_THREADED) && \ - defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && !defined(NO_BIO) \ - && !defined(NO_ASN_TIME) +#if !defined(NO_DH) && !defined(NO_AES) && defined(WOLFSSL_CERT_GEN) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ + defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) /* create certificate with version 2 */ -static void test_set_x509_badversion(WOLFSSL_CTX* ctx) +static int test_set_x509_badversion(WOLFSSL_CTX* ctx) { - WOLFSSL_X509 *x509, *x509v2; - WOLFSSL_EVP_PKEY *priv, *pub; + EXPECT_DECLS; + WOLFSSL_X509 *x509 = NULL, *x509v2 = NULL; + WOLFSSL_EVP_PKEY *priv = NULL, *pub = NULL; unsigned char *der = NULL, *key = NULL, *pt; - char *header, *name; + char *header = NULL, *name = NULL; int derSz; long keySz; - XFILE fp; - WOLFSSL_ASN1_TIME *notBefore, *notAfter; + XFILE fp = XBADFILE; + WOLFSSL_ASN1_TIME *notBefore = NULL, *notAfter = NULL; time_t t; - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, WOLFSSL_FILETYPE_PEM)); - fp = XFOPEN(cliKeyFile, "rb"); - AssertIntEQ(wolfSSL_PEM_read(fp, &name, &header, &key, &keySz), + ExpectTrue((fp = XFOPEN(cliKeyFile, "rb")) != XBADFILE); + ExpectIntEQ(wolfSSL_PEM_read(fp, &name, &header, &key, &keySz), WOLFSSL_SUCCESS); - XFCLOSE(fp); + if (fp != XBADFILE) + XFCLOSE(fp); pt = key; - AssertNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, + ExpectNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, (const unsigned char**)&pt, keySz)); /* create the version 2 certificate */ - AssertNotNull(x509v2 = X509_new()); - AssertIntEQ(wolfSSL_X509_set_version(x509v2, 1), WOLFSSL_SUCCESS); + ExpectNotNull(x509v2 = X509_new()); + ExpectIntEQ(wolfSSL_X509_set_version(x509v2, 1), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_subject_name(x509v2, + ExpectIntEQ(wolfSSL_X509_set_subject_name(x509v2, wolfSSL_X509_get_subject_name(x509)), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509v2, + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509v2, wolfSSL_X509_get_issuer_name(x509)), WOLFSSL_SUCCESS); - AssertNotNull(pub = wolfSSL_X509_get_pubkey(x509)); - AssertIntEQ(X509_set_pubkey(x509v2, pub), WOLFSSL_SUCCESS); + ExpectNotNull(pub = wolfSSL_X509_get_pubkey(x509)); + ExpectIntEQ(X509_set_pubkey(x509v2, pub), WOLFSSL_SUCCESS); t = time(NULL); - AssertNotNull(notBefore = wolfSSL_ASN1_TIME_adj(NULL, t, 0, 0)); - AssertNotNull(notAfter = wolfSSL_ASN1_TIME_adj(NULL, t, 365, 0)); - AssertTrue(wolfSSL_X509_set_notBefore(x509v2, notBefore)); - AssertTrue(wolfSSL_X509_set_notAfter(x509v2, notAfter)); + ExpectNotNull(notBefore = wolfSSL_ASN1_TIME_adj(NULL, t, 0, 0)); + ExpectNotNull(notAfter = wolfSSL_ASN1_TIME_adj(NULL, t, 365, 0)); + ExpectTrue(wolfSSL_X509_set_notBefore(x509v2, notBefore)); + ExpectTrue(wolfSSL_X509_set_notAfter(x509v2, notAfter)); - AssertIntGT(wolfSSL_X509_sign(x509v2, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509v2, priv, EVP_sha256()), 0); derSz = wolfSSL_i2d_X509(x509v2, &der); - AssertIntGT(derSz, 0); - AssertIntEQ(wolfSSL_CTX_use_certificate_buffer(ctx, der, derSz, + ExpectIntGT(derSz, 0); + ExpectIntEQ(wolfSSL_CTX_use_certificate_buffer(ctx, der, derSz, WOLFSSL_FILETYPE_ASN1), WOLFSSL_SUCCESS); - XFREE(der, HEAP_HINT, DYNAMIC_TYPE_OPENSSL); /* TODO: Replace with API call */ + /* TODO: Replace with API call */ + XFREE(der, HEAP_HINT, DYNAMIC_TYPE_OPENSSL); XFREE(key, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); XFREE(name, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); XFREE(header, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); @@ -11197,68 +11560,48 @@ static void test_set_x509_badversion(WOLFSSL_CTX* ctx) wolfSSL_EVP_PKEY_free(pub); wolfSSL_ASN1_TIME_free(notBefore); wolfSSL_ASN1_TIME_free(notAfter); + + return EXPECT_RESULT(); } /* override certificate version error */ static int test_override_x509(int preverify, WOLFSSL_X509_STORE_CTX* store) { + EXPECT_DECLS; #ifndef OPENSSL_COMPATIBLE_DEFAULTS - AssertIntEQ(store->error, ASN_VERSION_E); + ExpectIntEQ(store->error, ASN_VERSION_E); #else - AssertIntEQ(store->error, 0); + ExpectIntEQ(store->error, 0); #endif - AssertIntEQ((int)wolfSSL_X509_get_version(store->current_cert), 1); + ExpectIntEQ((int)wolfSSL_X509_get_version(store->current_cert), 1); (void)preverify; - return 1; + return EXPECT_RESULT() == TEST_SUCCESS; } /* set verify callback that will override bad certificate version */ -static void test_set_override_x509(WOLFSSL_CTX* ctx) +static int test_set_override_x509(WOLFSSL_CTX* ctx) { wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, test_override_x509); + return TEST_SUCCESS; } #endif -static int test_wolfSSL_X509_TLS_version(void) +static int test_wolfSSL_X509_TLS_version_test_1(void) { int res = TEST_SKIPPED; -#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ - !defined(NO_WOLFSSL_CLIENT) && !defined(NO_DH) && !defined(NO_AES) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(SINGLE_THREADED) && \ - defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && !defined(NO_BIO) \ - && !defined(NO_ASN_TIME) +#if !defined(NO_DH) && !defined(NO_AES) && defined(WOLFSSL_CERT_GEN) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ + defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) EXPECT_DECLS; - tcp_ready ready; - func_args server_args; - func_args client_args; - THREAD_TYPE serverThread; - callback_functions func_cb_client; - callback_functions func_cb_server; + test_ssl_cbf func_cb_client; + test_ssl_cbf func_cb_server; /* test server rejects a client certificate that is not version 3 */ -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - XMEMSET(&server_args, 0, sizeof(func_args)); - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&func_cb_client, 0, sizeof(callback_functions)); - XMEMSET(&func_cb_server, 0, sizeof(callback_functions)); - - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif - - server_args.signal = &ready; - client_args.signal = &ready; - server_args.return_code = TEST_FAIL; - client_args.return_code = TEST_FAIL; + XMEMSET(&func_cb_client, 0, sizeof(func_cb_client)); + XMEMSET(&func_cb_server, 0, sizeof(func_cb_server)); func_cb_client.ctx_ready = &test_set_x509_badversion; #ifndef WOLFSSL_NO_TLS12 @@ -11266,55 +11609,40 @@ static int test_wolfSSL_X509_TLS_version(void) #else func_cb_client.method = wolfTLSv1_3_client_method; #endif - client_args.callbacks = &func_cb_client; #ifndef WOLFSSL_NO_TLS12 func_cb_server.method = wolfTLSv1_2_server_method; #else func_cb_server.method = wolfTLSv1_3_server_method; #endif - server_args.callbacks = &func_cb_server; - - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, + &func_cb_server, NULL), #ifndef OPENSSL_COMPATIBLE_DEFAULTS - ExpectIntEQ(client_args.return_code, TEST_FAIL); - ExpectIntEQ(server_args.return_code, TEST_FAIL); + TEST_FAIL #else - ExpectIntEQ(client_args.return_code, TEST_SUCCESS); - ExpectIntEQ(server_args.return_code, TEST_SUCCESS); + TEST_SUCCESS #endif + ); - FreeTcpReady(&ready); - -#ifdef WOLFSSL_TIRTOS - fdCloseSession(Task_self()); -#endif - - /* Now re run but override the bad X509 version */ -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); + res = EXPECT_RESULT(); #endif - XMEMSET(&server_args, 0, sizeof(func_args)); - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&func_cb_client, 0, sizeof(callback_functions)); - XMEMSET(&func_cb_server, 0, sizeof(callback_functions)); - StartTCP(); - InitTcpReady(&ready); + return res; +} -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif +static int test_wolfSSL_X509_TLS_version_test_2(void) +{ + int res = TEST_SKIPPED; +#if !defined(NO_DH) && !defined(NO_AES) && defined(WOLFSSL_CERT_GEN) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ + defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) + EXPECT_DECLS; + test_ssl_cbf func_cb_client; + test_ssl_cbf func_cb_server; - server_args.signal = &ready; - client_args.signal = &ready; - server_args.return_code = TEST_FAIL; - client_args.return_code = TEST_FAIL; + XMEMSET(&func_cb_client, 0, sizeof(callback_functions)); + XMEMSET(&func_cb_server, 0, sizeof(callback_functions)); func_cb_client.ctx_ready = &test_set_x509_badversion; func_cb_server.ctx_ready = &test_set_override_x509; @@ -11323,28 +11651,15 @@ static int test_wolfSSL_X509_TLS_version(void) #else func_cb_client.method = wolfTLSv1_3_client_method; #endif - client_args.callbacks = &func_cb_client; #ifndef WOLFSSL_NO_TLS12 func_cb_server.method = wolfTLSv1_2_server_method; #else func_cb_server.method = wolfTLSv1_3_server_method; #endif - server_args.callbacks = &func_cb_server; - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); - - ExpectIntEQ(client_args.return_code, TEST_SUCCESS); - ExpectIntEQ(server_args.return_code, TEST_SUCCESS); - - FreeTcpReady(&ready); - -#ifdef WOLFSSL_TIRTOS - fdCloseSession(Task_self()); -#endif + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, + &func_cb_server, NULL), TEST_SUCCESS); res = EXPECT_RESULT(); #endif @@ -34059,17 +34374,18 @@ static int test_wolfSSL_lhash(void) { int res = TEST_SKIPPED; #ifdef OPENSSL_ALL + EXPECT_DECLS; const char testStr[] = "Like a true nature's child\n" "We were born\n" "Born to be wild"; #ifdef NO_SHA - AssertIntEQ(lh_strhash(testStr), 0xf9dc8a43); + ExpectIntEQ(lh_strhash(testStr), 0xf9dc8a43); #else - AssertIntEQ(lh_strhash(testStr), 0x5b7541dc); + ExpectIntEQ(lh_strhash(testStr), 0x5b7541dc); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34077,20 +34393,21 @@ static int test_wolfSSL_lhash(void) static int test_wolfSSL_X509_NAME(void) { int res = TEST_SKIPPED; - #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ - !defined(NO_CERTS) && !defined(NO_FILESYSTEM) \ - && !defined(NO_RSA) && defined(WOLFSSL_CERT_GEN) && \ - (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT) || \ - defined(OPENSSL_EXTRA)) - X509* x509; +#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ + !defined(NO_CERTS) && !defined(NO_FILESYSTEM) && \ + !defined(NO_RSA) && defined(WOLFSSL_CERT_GEN) && \ + (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT) || \ + defined(OPENSSL_EXTRA)) + EXPECT_DECLS; + X509* x509 = NULL; const unsigned char* c; unsigned char buf[4096]; int bytes; - XFILE f; - const X509_NAME* a; - const X509_NAME* b; + XFILE f = XBADFILE; + const X509_NAME* a = NULL; + const X509_NAME* b = NULL; X509_NAME* d2i_name = NULL; - int sz; + int sz = 0; unsigned char* tmp; char file[] = "./certs/ca-cert.der"; #ifndef OPENSSL_EXTRA_X509_SMALL @@ -34105,30 +34422,31 @@ static int test_wolfSSL_X509_NAME(void) #ifndef OPENSSL_EXTRA_X509_SMALL /* test compile of deprecated function, returns 0 */ - AssertIntEQ(CRYPTO_thread_id(), 0); + ExpectIntEQ(CRYPTO_thread_id(), 0); #endif - AssertNotNull(a = X509_NAME_new()); + ExpectNotNull(a = X509_NAME_new()); X509_NAME_free((X509_NAME*)a); + a = NULL; - f = XFOPEN(file, "rb"); - AssertTrue(f != XBADFILE); - bytes = (int)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(file, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) + XFCLOSE(f); c = buf; - AssertNotNull(x509 = wolfSSL_X509_d2i(NULL, c, bytes)); + ExpectNotNull(x509 = wolfSSL_X509_d2i(NULL, c, bytes)); /* test cmp function */ - AssertNotNull(a = X509_get_issuer_name(x509)); - AssertNotNull(b = X509_get_subject_name(x509)); + ExpectNotNull(a = X509_get_issuer_name(x509)); + ExpectNotNull(b = X509_get_subject_name(x509)); #ifndef OPENSSL_EXTRA_X509_SMALL - AssertIntEQ(X509_NAME_cmp(a, b), 0); /* self signed should be 0 */ + ExpectIntEQ(X509_NAME_cmp(a, b), 0); /* self signed should be 0 */ #endif tmp = buf; - AssertIntGT((sz = i2d_X509_NAME((X509_NAME*)a, &tmp)), 0); + ExpectIntGT((sz = i2d_X509_NAME((X509_NAME*)a, &tmp)), 0); if (sz > 0 && tmp == buf) { fprintf(stderr, "\nERROR - %s line %d failed with:", __FILE__, __LINE__); @@ -34138,70 +34456,74 @@ static int test_wolfSSL_X509_NAME(void) #ifndef OPENSSL_EXTRA_X509_SMALL tmp = buf; - AssertNotNull(d2i_name = d2i_X509_NAME(NULL, &tmp, sz)); + ExpectNotNull(d2i_name = d2i_X509_NAME(NULL, &tmp, sz)); #endif /* if output parameter is NULL, should still return required size. */ - AssertIntGT((sz = i2d_X509_NAME((X509_NAME*)b, NULL)), 0); + ExpectIntGT((sz = i2d_X509_NAME((X509_NAME*)b, NULL)), 0); /* retry but with the function creating a buffer */ tmp = NULL; - AssertIntGT((sz = i2d_X509_NAME((X509_NAME*)b, &tmp)), 0); + ExpectIntGT((sz = i2d_X509_NAME((X509_NAME*)b, &tmp)), 0); XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL); + tmp = NULL; #ifdef WOLFSSL_CERT_NAME_ALL /* test for givenName and name */ { - WOLFSSL_X509_NAME_ENTRY* entry; + WOLFSSL_X509_NAME_ENTRY* entry = NULL; const byte gName[] = "test-given-name"; const byte name[] = "test-name"; - entry = wolfSSL_X509_NAME_ENTRY_create_by_NID(NULL, NID_givenName, - ASN_UTF8STRING, gName, sizeof(gName)); - AssertNotNull(entry); - wolfSSL_X509_NAME_add_entry((X509_NAME*)b, entry, -1, 0); + ExpectNotNull(entry = wolfSSL_X509_NAME_ENTRY_create_by_NID(NULL, + NID_givenName, ASN_UTF8STRING, gName, sizeof(gName))); + ExpectIntEQ(wolfSSL_X509_NAME_add_entry((X509_NAME*)b, entry, -1, 0), + 1); wolfSSL_X509_NAME_ENTRY_free(entry); + entry = NULL; - entry = wolfSSL_X509_NAME_ENTRY_create_by_NID(NULL, NID_name, - ASN_UTF8STRING, name, sizeof(name)); - AssertNotNull(entry); - wolfSSL_X509_NAME_add_entry((X509_NAME*)b, entry, -1, 0); + ExpectNotNull(entry = wolfSSL_X509_NAME_ENTRY_create_by_NID(NULL, + NID_name, ASN_UTF8STRING, name, sizeof(name))); + ExpectIntEQ(wolfSSL_X509_NAME_add_entry((X509_NAME*)b, entry, -1, 0), + 1); wolfSSL_X509_NAME_ENTRY_free(entry); tmp = NULL; - AssertIntGT((sz = i2d_X509_NAME((X509_NAME*)b, &tmp)), 0); + ExpectIntGT((sz = i2d_X509_NAME((X509_NAME*)b, &tmp)), 0); XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL); } #endif - AssertNotNull(b = X509_NAME_dup((X509_NAME*)a)); + b = NULL; + ExpectNotNull(b = X509_NAME_dup((X509_NAME*)a)); #ifndef OPENSSL_EXTRA_X509_SMALL - AssertIntEQ(X509_NAME_cmp(a, b), 0); + ExpectIntEQ(X509_NAME_cmp(a, b), 0); #endif X509_NAME_free((X509_NAME*)b); X509_NAME_free(d2i_name); + d2i_name = NULL; X509_free(x509); #ifndef OPENSSL_EXTRA_X509_SMALL /* test with an empty domain component */ tmp = empty; sz = sizeof(empty); - AssertNotNull(d2i_name = d2i_X509_NAME(NULL, &tmp, sz)); - AssertIntEQ(X509_NAME_entry_count(d2i_name), 2); + ExpectNotNull(d2i_name = d2i_X509_NAME(NULL, &tmp, sz)); + ExpectIntEQ(X509_NAME_entry_count(d2i_name), 2); /* size of empty emailAddress will be 0 */ tmp = buf; - AssertIntEQ(X509_NAME_get_text_by_NID(d2i_name, NID_emailAddress, + ExpectIntEQ(X509_NAME_get_text_by_NID(d2i_name, NID_emailAddress, (char*)tmp, sizeof(buf)), 0); /* should contain no organization name */ tmp = buf; - AssertIntEQ(X509_NAME_get_text_by_NID(d2i_name, NID_organizationName, + ExpectIntEQ(X509_NAME_get_text_by_NID(d2i_name, NID_organizationName, (char*)tmp, sizeof(buf)), -1); X509_NAME_free(d2i_name); #endif - res = TEST_RES_CHECK(1); - #endif /* defined(OPENSSL_EXTRA) && !defined(NO_DES3) */ + res = EXPECT_RESULT(); +#endif return res; } @@ -34210,18 +34532,19 @@ static int test_wolfSSL_X509_NAME_hash(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) \ && !defined(NO_RSA) && !defined(NO_SHA) && !defined(NO_BIO) - BIO* bio; + EXPECT_DECLS; + BIO* bio = NULL; X509* x509 = NULL; - AssertNotNull(bio = BIO_new(BIO_s_file())); - AssertIntGT(BIO_read_filename(bio, svrCertFile), 0); - AssertNotNull(PEM_read_bio_X509(bio, &x509, NULL, NULL)); - AssertIntEQ(X509_NAME_hash(X509_get_subject_name(x509)), 0x137DC03F); - AssertIntEQ(X509_NAME_hash(X509_get_issuer_name(x509)), 0xFDB2DA4); + ExpectNotNull(bio = BIO_new(BIO_s_file())); + ExpectIntGT(BIO_read_filename(bio, svrCertFile), 0); + ExpectNotNull(PEM_read_bio_X509(bio, &x509, NULL, NULL)); + ExpectIntEQ(X509_NAME_hash(X509_get_subject_name(x509)), 0x137DC03F); + ExpectIntEQ(X509_NAME_hash(X509_get_issuer_name(x509)), 0xFDB2DA4); X509_free(x509); BIO_free(bio); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34234,6 +34557,7 @@ static int test_wolfSSL_X509_NAME_print_ex(void) defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))) && \ !defined(NO_BIO) && !defined(NO_RSA) + EXPECT_DECLS; int memSz; byte* mem = NULL; BIO* bio = NULL; @@ -34250,114 +34574,124 @@ static int test_wolfSSL_X509_NAME_print_ex(void) "CN=\\#wolfssl.com\\<\\>\\;, C=\\ US\\,\\+\\\"\\\\\\ "; /* Test with real cert (svrCertFile) first */ - AssertNotNull(bio = BIO_new(BIO_s_file())); - AssertIntGT(BIO_read_filename(bio, svrCertFile), 0); - AssertNotNull(PEM_read_bio_X509(bio, &x509, NULL, NULL)); - AssertNotNull(name = X509_get_subject_name(x509)); + ExpectNotNull(bio = BIO_new(BIO_s_file())); + ExpectIntGT(BIO_read_filename(bio, svrCertFile), 0); + ExpectNotNull(PEM_read_bio_X509(bio, &x509, NULL, NULL)); + ExpectNotNull(name = X509_get_subject_name(x509)); /* Test without flags */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, 0), WOLFSSL_SUCCESS); + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, 0), WOLFSSL_SUCCESS); BIO_free(membio); + membio = NULL; /* Test flag: XN_FLAG_RFC2253 */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, XN_FLAG_RFC2253), WOLFSSL_SUCCESS); BIO_free(membio); + membio = NULL; /* Test flag: XN_FLAG_RFC2253 | XN_FLAG_DN_REV */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, XN_FLAG_RFC2253 | XN_FLAG_DN_REV), WOLFSSL_SUCCESS); BIO_free(membio); + membio = NULL; X509_free(x509); BIO_free(bio); + name = NULL; /* Test normal case without escaped characters */ { /* Create name: "/C=US/CN=wolfssl.com" */ - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), WOLFSSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), WOLFSSL_SUCCESS); /* Test without flags */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, 0), WOLFSSL_SUCCESS); - AssertIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); - AssertIntEQ(memSz, XSTRLEN(expNormal)); - AssertIntEQ(XSTRNCMP((char*)mem, expNormal, XSTRLEN(expNormal)), 0); + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, 0), WOLFSSL_SUCCESS); + ExpectIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); + ExpectIntEQ(memSz, XSTRLEN(expNormal)); + ExpectIntEQ(XSTRNCMP((char*)mem, expNormal, XSTRLEN(expNormal)), 0); BIO_free(membio); + membio = NULL; /* Test flags: XN_FLAG_RFC2253 - should be reversed */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, XN_FLAG_RFC2253), WOLFSSL_SUCCESS); - AssertIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); - AssertIntEQ(memSz, XSTRLEN(expReverse)); + ExpectIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); + ExpectIntEQ(memSz, XSTRLEN(expReverse)); BIO_free(membio); + membio = NULL; /* Test flags: XN_FLAG_DN_REV - reversed */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, XN_FLAG_DN_REV), WOLFSSL_SUCCESS); - AssertIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); - AssertIntEQ(memSz, XSTRLEN(expReverse)); - AssertIntEQ(XSTRNCMP((char*)mem, expReverse, XSTRLEN(expReverse)), 0); + ExpectIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); + ExpectIntEQ(memSz, XSTRLEN(expReverse)); + ExpectIntEQ(XSTRNCMP((char*)mem, expReverse, XSTRLEN(expReverse)), 0); BIO_free(membio); + membio = NULL; X509_NAME_free(name); + name = NULL; } /* Test RFC2253 characters are escaped with backslashes */ { - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", /* space at beginning and end, and: ,+"\ */ MBSTRING_UTF8, (byte*)" US,+\"\\ ", 8, -1, 0), WOLFSSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", /* # at beginning, and: <>;*/ MBSTRING_UTF8, (byte*)"#wolfssl.com<>;", 15, -1, 0), WOLFSSL_SUCCESS); /* Test without flags */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, 0), WOLFSSL_SUCCESS); - AssertIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); - AssertIntEQ(memSz, XSTRLEN(expNotEscaped)); - AssertIntEQ(XSTRNCMP((char*)mem, expNotEscaped, + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, 0), WOLFSSL_SUCCESS); + ExpectIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); + ExpectIntEQ(memSz, XSTRLEN(expNotEscaped)); + ExpectIntEQ(XSTRNCMP((char*)mem, expNotEscaped, XSTRLEN(expNotEscaped)), 0); BIO_free(membio); + membio = NULL; /* Test flags: XN_FLAG_RFC5523 - should be reversed and escaped */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, XN_FLAG_RFC2253), WOLFSSL_SUCCESS); - AssertIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); - AssertIntEQ(memSz, XSTRLEN(expRFC5523)); - AssertIntEQ(XSTRNCMP((char*)mem, expRFC5523, XSTRLEN(expRFC5523)), 0); + ExpectIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); + ExpectIntEQ(memSz, XSTRLEN(expRFC5523)); + ExpectIntEQ(XSTRNCMP((char*)mem, expRFC5523, XSTRLEN(expRFC5523)), 0); BIO_free(membio); + membio = NULL; /* Test flags: XN_FLAG_DN_REV - reversed but not escaped */ - AssertNotNull(membio = BIO_new(BIO_s_mem())); - AssertIntEQ(X509_NAME_print_ex(membio, name, 0, + ExpectNotNull(membio = BIO_new(BIO_s_mem())); + ExpectIntEQ(X509_NAME_print_ex(membio, name, 0, XN_FLAG_DN_REV), WOLFSSL_SUCCESS); - AssertIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); - AssertIntEQ(memSz, XSTRLEN(expNotEscapedRev)); - AssertIntEQ(XSTRNCMP((char*)mem, expNotEscapedRev, + ExpectIntGE((memSz = BIO_get_mem_data(membio, &mem)), 0); + ExpectIntEQ(memSz, XSTRLEN(expNotEscapedRev)); + ExpectIntEQ(XSTRNCMP((char*)mem, expNotEscapedRev, XSTRLEN(expNotEscapedRev)), 0); BIO_free(membio); X509_NAME_free(name); } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34367,8 +34701,9 @@ static int test_wolfSSL_X509_INFO_multiple_info(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_RSA) - STACK_OF(X509_INFO) *info_stack; - X509_INFO *info; + EXPECT_DECLS; + STACK_OF(X509_INFO) *info_stack = NULL; + X509_INFO *info = NULL; int len; int i; const char* files[] = { @@ -34381,47 +34716,50 @@ static int test_wolfSSL_X509_INFO_multiple_info(void) NULL, }; const char** curFile; - BIO *fileBIO; + BIO *fileBIO = NULL; BIO *concatBIO = NULL; byte tmp[FOURK_BUF]; /* concatenate the cert and the key file to force PEM_X509_INFO_read_bio * to group objects together. */ - AssertNotNull(concatBIO = BIO_new(BIO_s_mem())); + ExpectNotNull(concatBIO = BIO_new(BIO_s_mem())); for (curFile = files; *curFile != NULL; curFile++) { int fileLen; - AssertNotNull(fileBIO = BIO_new_file(*curFile, "rb")); - fileLen = wolfSSL_BIO_get_len(fileBIO); - while ((len = BIO_read(fileBIO, tmp, sizeof(tmp))) > 0) { - AssertIntEQ(BIO_write(concatBIO, tmp, len), len); - fileLen -= len; - } - /* Make sure we read the entire file */ - AssertIntEQ(fileLen, 0); + ExpectNotNull(fileBIO = BIO_new_file(*curFile, "rb")); + ExpectIntGT(fileLen = wolfSSL_BIO_get_len(fileBIO), 0); + if (EXPECT_SUCCESS()) { + while ((len = BIO_read(fileBIO, tmp, sizeof(tmp))) > 0) { + ExpectIntEQ(BIO_write(concatBIO, tmp, len), len); + fileLen -= len; + } + /* Make sure we read the entire file */ + ExpectIntEQ(fileLen, 0); + } BIO_free(fileBIO); + fileBIO = NULL; } - AssertNotNull(info_stack = PEM_X509_INFO_read_bio(concatBIO, NULL, NULL, - NULL)); - AssertIntEQ(sk_X509_INFO_num(info_stack), 3); + ExpectNotNull(info_stack = PEM_X509_INFO_read_bio(concatBIO, NULL, NULL, + NULL)); + ExpectIntEQ(sk_X509_INFO_num(info_stack), 3); for (i = 0; i < sk_X509_INFO_num(info_stack); i++) { - AssertNotNull(info = sk_X509_INFO_value(info_stack, i)); - AssertNotNull(info->x509); - AssertNull(info->crl); + ExpectNotNull(info = sk_X509_INFO_value(info_stack, i)); + ExpectNotNull(info->x509); + ExpectNull(info->crl); if (i != 0) { - AssertNotNull(info->x_pkey); - AssertIntEQ(X509_check_private_key(info->x509, + ExpectNotNull(info->x_pkey); + ExpectIntEQ(X509_check_private_key(info->x509, info->x_pkey->dec_pkey), 1); } else { - AssertNull(info->x_pkey); + ExpectNull(info->x_pkey); } } sk_X509_INFO_pop_free(info_stack, X509_INFO_free); BIO_free(concatBIO); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34432,9 +34770,10 @@ static int test_wolfSSL_X509_INFO(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_RSA) - STACK_OF(X509_INFO) *info_stack; - X509_INFO *info; - BIO *cert; + EXPECT_DECLS; + STACK_OF(X509_INFO) *info_stack = NULL; + X509_INFO *info = NULL; + BIO *cert = NULL; int i; /* PEM in hex format to avoid null terminator */ byte data[] = { @@ -34455,35 +34794,41 @@ static int test_wolfSSL_X509_INFO(void) 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d }; - AssertNotNull(cert = BIO_new_file(cliCertFileExt, "rb")); - AssertNotNull(info_stack = PEM_X509_INFO_read_bio(cert, NULL, NULL, NULL)); + ExpectNotNull(cert = BIO_new_file(cliCertFileExt, "rb")); + ExpectNotNull(info_stack = PEM_X509_INFO_read_bio(cert, NULL, NULL, NULL)); for (i = 0; i < sk_X509_INFO_num(info_stack); i++) { - AssertNotNull(info = sk_X509_INFO_value(info_stack, i)); - AssertNotNull(info->x509); - AssertNull(info->crl); - AssertNull(info->x_pkey); + ExpectNotNull(info = sk_X509_INFO_value(info_stack, i)); + ExpectNotNull(info->x509); + ExpectNull(info->crl); + ExpectNull(info->x_pkey); } sk_X509_INFO_pop_free(info_stack, X509_INFO_free); + info_stack = NULL; BIO_free(cert); + cert = NULL; - AssertNotNull(cert = BIO_new_file(cliCertFileExt, "rb")); - AssertNotNull(info_stack = PEM_X509_INFO_read_bio(cert, NULL, NULL, NULL)); + ExpectNotNull(cert = BIO_new_file(cliCertFileExt, "rb")); + ExpectNotNull(info_stack = PEM_X509_INFO_read_bio(cert, NULL, NULL, NULL)); sk_X509_INFO_pop_free(info_stack, X509_INFO_free); + info_stack = NULL; BIO_free(cert); + cert = NULL; /* This case should fail due to invalid input. */ - AssertNotNull(cert = BIO_new(BIO_s_mem())); - AssertIntEQ(BIO_write(cert, data, sizeof(data)), sizeof(data)); - AssertNull(info_stack = PEM_X509_INFO_read_bio(cert, NULL, NULL, NULL)); + ExpectNotNull(cert = BIO_new(BIO_s_mem())); + ExpectIntEQ(BIO_write(cert, data, sizeof(data)), sizeof(data)); + ExpectNull(info_stack = PEM_X509_INFO_read_bio(cert, NULL, NULL, NULL)); sk_X509_INFO_pop_free(info_stack, X509_INFO_free); + info_stack = NULL; BIO_free(cert); - AssertNotNull(cert = BIO_new(BIO_s_mem())); - AssertIntEQ(BIO_write(cert, data2, sizeof(data2)), sizeof(data2)); - AssertNull(info_stack = PEM_X509_INFO_read_bio(cert, NULL, NULL, NULL)); + cert = NULL; + ExpectNotNull(cert = BIO_new(BIO_s_mem())); + ExpectIntEQ(BIO_write(cert, data2, sizeof(data2)), sizeof(data2)); + ExpectNull(info_stack = PEM_X509_INFO_read_bio(cert, NULL, NULL, NULL)); sk_X509_INFO_pop_free(info_stack, X509_INFO_free); BIO_free(cert); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34494,14 +34839,15 @@ static int test_wolfSSL_X509_subject_name_hash(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) \ && !defined(NO_RSA) && (!defined(NO_SHA) || !defined(NO_SHA256)) - X509* x509; + EXPECT_DECLS; + X509* x509 = NULL; X509_NAME* subjectName = NULL; unsigned long ret1 = 0; unsigned long ret2 = 0; - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, SSL_FILETYPE_PEM)); - AssertNotNull(subjectName = wolfSSL_X509_get_subject_name(x509)); + ExpectNotNull(subjectName = wolfSSL_X509_get_subject_name(x509)); /* These two * - X509_subject_name_hash(x509) @@ -34509,20 +34855,20 @@ static int test_wolfSSL_X509_subject_name_hash(void) * should give the same hash, if !defined(NO_SHA) is true. */ ret1 = X509_subject_name_hash(x509); - AssertIntNE(ret1, 0); + ExpectIntNE(ret1, 0); #if !defined(NO_SHA) ret2 = X509_NAME_hash(X509_get_subject_name(x509)); - AssertIntNE(ret2, 0); + ExpectIntNE(ret2, 0); - AssertIntEQ(ret1, ret2); + ExpectIntEQ(ret1, ret2); #else (void) ret2; #endif X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34532,14 +34878,15 @@ static int test_wolfSSL_X509_issuer_name_hash(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) \ && !defined(NO_RSA) && (!defined(NO_SHA) || !defined(NO_SHA256)) - X509* x509; + EXPECT_DECLS; + X509* x509 = NULL; X509_NAME* issuertName = NULL; unsigned long ret1 = 0; unsigned long ret2 = 0; - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, SSL_FILETYPE_PEM)); - AssertNotNull(issuertName = wolfSSL_X509_get_issuer_name(x509)); + ExpectNotNull(issuertName = wolfSSL_X509_get_issuer_name(x509)); /* These two * - X509_issuer_name_hash(x509) @@ -34547,20 +34894,20 @@ static int test_wolfSSL_X509_issuer_name_hash(void) * should give the same hash, if !defined(NO_SHA) is true. */ ret1 = X509_issuer_name_hash(x509); - AssertIntNE(ret1, 0); + ExpectIntNE(ret1, 0); #if !defined(NO_SHA) ret2 = X509_NAME_hash(X509_get_issuer_name(x509)); - AssertIntNE(ret2, 0); + ExpectIntNE(ret2, 0); - AssertIntEQ(ret1, ret2); + ExpectIntEQ(ret1, ret2); #else (void) ret2; #endif X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34570,25 +34917,25 @@ static int test_wolfSSL_X509_check_host(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) \ && !defined(NO_SHA) && !defined(NO_RSA) - - X509* x509; + EXPECT_DECLS; + X509* x509 = NULL; const char altName[] = "example.com"; - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(X509_check_host(x509, altName, XSTRLEN(altName), 0, NULL), + ExpectIntEQ(X509_check_host(x509, altName, XSTRLEN(altName), 0, NULL), WOLFSSL_SUCCESS); - AssertIntEQ(X509_check_host(x509, NULL, 0, 0, NULL), + ExpectIntEQ(X509_check_host(x509, NULL, 0, 0, NULL), WOLFSSL_FAILURE); X509_free(x509); - AssertIntEQ(X509_check_host(NULL, altName, XSTRLEN(altName), 0, NULL), + ExpectIntEQ(X509_check_host(NULL, altName, XSTRLEN(altName), 0, NULL), WOLFSSL_FAILURE); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -34597,33 +34944,34 @@ static int test_wolfSSL_X509_check_email(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_GEN) && !defined(NO_RSA) - X509* x509; + EXPECT_DECLS; + X509* x509 = NULL; const char goodEmail[] = "info@wolfssl.com"; const char badEmail[] = "disinfo@wolfssl.com"; - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, SSL_FILETYPE_PEM)); /* Should fail on non-matching email address */ - AssertIntEQ(wolfSSL_X509_check_email(x509, badEmail, XSTRLEN(badEmail), 0), + ExpectIntEQ(wolfSSL_X509_check_email(x509, badEmail, XSTRLEN(badEmail), 0), WOLFSSL_FAILURE); /* Should succeed on matching email address */ - AssertIntEQ(wolfSSL_X509_check_email(x509, goodEmail, XSTRLEN(goodEmail), 0), + ExpectIntEQ(wolfSSL_X509_check_email(x509, goodEmail, XSTRLEN(goodEmail), 0), WOLFSSL_SUCCESS); /* Should compute length internally when not provided */ - AssertIntEQ(wolfSSL_X509_check_email(x509, goodEmail, 0, 0), + ExpectIntEQ(wolfSSL_X509_check_email(x509, goodEmail, 0, 0), WOLFSSL_SUCCESS); /* Should fail when email address is NULL */ - AssertIntEQ(wolfSSL_X509_check_email(x509, NULL, 0, 0), + ExpectIntEQ(wolfSSL_X509_check_email(x509, NULL, 0, 0), WOLFSSL_FAILURE); X509_free(x509); /* Should fail when x509 is NULL */ - AssertIntEQ(wolfSSL_X509_check_email(NULL, goodEmail, 0, 0), + ExpectIntEQ(wolfSSL_X509_check_email(NULL, goodEmail, 0, 0), WOLFSSL_FAILURE); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && WOLFSSL_CERT_GEN */ return res; } @@ -34631,7 +34979,8 @@ static int test_wolfSSL_X509_check_email(void) static int test_wolfSSL_DES(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && !defined(NO_DES3) +#if defined(OPENSSL_EXTRA) && !defined(NO_DES3) + EXPECT_DECLS; const_DES_cblock myDes; DES_cblock iv; DES_key_schedule key; @@ -34643,55 +34992,56 @@ static int test_wolfSSL_DES(void) DES_set_key(&myDes, &key); /* check, check of odd parity */ - XMEMSET(myDes, 4, sizeof(const_DES_cblock)); myDes[0] = 6; /*set even parity*/ + XMEMSET(myDes, 4, sizeof(const_DES_cblock)); + myDes[0] = 6; /*set even parity*/ XMEMSET(key, 5, sizeof(DES_key_schedule)); - AssertIntEQ(DES_set_key_checked(&myDes, &key), -1); - AssertIntNE(key[0], myDes[0]); /* should not have copied over key */ + ExpectIntEQ(DES_set_key_checked(&myDes, &key), -1); + ExpectIntNE(key[0], myDes[0]); /* should not have copied over key */ /* set odd parity for success case */ DES_set_odd_parity(&myDes); - AssertIntEQ(DES_check_key_parity(&myDes), 1); + ExpectIntEQ(DES_check_key_parity(&myDes), 1); fprintf(stderr, "%02x %02x %02x %02x", myDes[0], myDes[1], myDes[2], myDes[3]); - AssertIntEQ(DES_set_key_checked(&myDes, &key), 0); + ExpectIntEQ(DES_set_key_checked(&myDes, &key), 0); for (i = 0; i < sizeof(DES_key_schedule); i++) { - AssertIntEQ(key[i], myDes[i]); + ExpectIntEQ(key[i], myDes[i]); } - AssertIntEQ(DES_is_weak_key(&myDes), 0); + ExpectIntEQ(DES_is_weak_key(&myDes), 0); /* check weak key */ XMEMSET(myDes, 1, sizeof(const_DES_cblock)); XMEMSET(key, 5, sizeof(DES_key_schedule)); - AssertIntEQ(DES_set_key_checked(&myDes, &key), -2); - AssertIntNE(key[0], myDes[0]); /* should not have copied over key */ + ExpectIntEQ(DES_set_key_checked(&myDes, &key), -2); + ExpectIntNE(key[0], myDes[0]); /* should not have copied over key */ /* now do unchecked copy of a weak key over */ DES_set_key_unchecked(&myDes, &key); /* compare arrays, should be the same */ for (i = 0; i < sizeof(DES_key_schedule); i++) { - AssertIntEQ(key[i], myDes[i]); + ExpectIntEQ(key[i], myDes[i]); } - AssertIntEQ(DES_is_weak_key(&myDes), 1); + ExpectIntEQ(DES_is_weak_key(&myDes), 1); /* check DES_key_sched API */ XMEMSET(key, 1, sizeof(DES_key_schedule)); - AssertIntEQ(DES_key_sched(&myDes, NULL), 0); - AssertIntEQ(DES_key_sched(NULL, &key), 0); - AssertIntEQ(DES_key_sched(&myDes, &key), 0); + ExpectIntEQ(DES_key_sched(&myDes, NULL), 0); + ExpectIntEQ(DES_key_sched(NULL, &key), 0); + ExpectIntEQ(DES_key_sched(&myDes, &key), 0); /* compare arrays, should be the same */ for (i = 0; i < sizeof(DES_key_schedule); i++) { - AssertIntEQ(key[i], myDes[i]); + ExpectIntEQ(key[i], myDes[i]); } /* DES_cbc_cksum should return the last 4 of the last 8 bytes after * DES_cbc_encrypt on the input */ XMEMSET(iv, 0, sizeof(DES_cblock)); XMEMSET(myDes, 5, sizeof(DES_key_schedule)); - AssertIntGT((dl = DES_cbc_cksum(msg, &key, sizeof(msg), &myDes, &iv)), 0); - AssertIntEQ(dl, 480052723); + ExpectIntGT((dl = DES_cbc_cksum(msg, &key, sizeof(msg), &myDes, &iv)), 0); + ExpectIntEQ(dl, 480052723); - res = TEST_RES_CHECK(1); - #endif /* defined(OPENSSL_EXTRA) && !defined(NO_DES3) */ + res = EXPECT_RESULT(); +#endif /* defined(OPENSSL_EXTRA) && !defined(NO_DES3) */ return res; } @@ -35187,62 +35537,63 @@ static int test_wolfSSL_certs(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) && \ !defined(NO_RSA) - X509* x509ext; + EXPECT_DECLS; + X509* x509ext = NULL; #ifdef OPENSSL_ALL - X509* x509; - WOLFSSL_X509_EXTENSION* ext; - ASN1_OBJECT* obj; + X509* x509 = NULL; + WOLFSSL_X509_EXTENSION* ext = NULL; + ASN1_OBJECT* obj = NULL; #endif - WOLFSSL* ssl; - WOLFSSL_CTX* ctx; - STACK_OF(ASN1_OBJECT)* sk; - ASN1_STRING* asn1_str; - AUTHORITY_KEYID* akey; - BASIC_CONSTRAINTS* bc; + WOLFSSL* ssl = NULL; + WOLFSSL_CTX* ctx = NULL; + STACK_OF(ASN1_OBJECT)* sk = NULL; + ASN1_STRING* asn1_str = NULL; + AUTHORITY_KEYID* akey = NULL; + BASIC_CONSTRAINTS* bc = NULL; int crit; #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(SSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(SSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(SSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(SSLv23_client_method())); #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(SSL_CTX_check_private_key(ctx), SSL_FAILURE); + ExpectIntEQ(SSL_CTX_check_private_key(ctx), SSL_FAILURE); #endif - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(SSL_CTX_check_private_key(ctx), SSL_SUCCESS); + ExpectIntEQ(SSL_CTX_check_private_key(ctx), SSL_SUCCESS); #endif - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif #ifdef HAVE_PK_CALLBACKS - AssertIntEQ((int)SSL_set_tlsext_debug_arg(ssl, NULL), WOLFSSL_SUCCESS); + ExpectIntEQ((int)SSL_set_tlsext_debug_arg(ssl, NULL), WOLFSSL_SUCCESS); #endif /* HAVE_PK_CALLBACKS */ /* create and use x509 */ #ifdef OPENSSL_ALL - x509 = wolfSSL_X509_load_certificate_file(cliCertFile, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + WOLFSSL_FILETYPE_PEM)); #endif - x509ext = wolfSSL_X509_load_certificate_file(cliCertFileExt, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509ext); - AssertIntEQ(SSL_use_certificate(ssl, x509ext), WOLFSSL_SUCCESS); + ExpectNotNull(x509ext = wolfSSL_X509_load_certificate_file(cliCertFileExt, + WOLFSSL_FILETYPE_PEM)); + ExpectIntEQ(SSL_use_certificate(ssl, x509ext), WOLFSSL_SUCCESS); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) /* with loading in a new cert the check on private key should now fail */ - AssertIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif #if defined(USE_CERT_BUFFERS_2048) - AssertIntEQ(SSL_use_certificate_ASN1(ssl, + ExpectIntEQ(SSL_use_certificate_ASN1(ssl, (unsigned char*)server_cert_der_2048, sizeof_server_cert_der_2048), WOLFSSL_SUCCESS); #endif @@ -35254,167 +35605,179 @@ static int test_wolfSSL_certs(void) word32 digestSz; XMEMSET(digest, 0, sizeof(digest)); - AssertIntEQ(X509_digest(x509ext, wolfSSL_EVP_sha1(), digest, &digestSz), + ExpectIntEQ(X509_digest(x509ext, wolfSSL_EVP_sha1(), digest, &digestSz), WOLFSSL_SUCCESS); - AssertIntEQ(X509_digest(x509ext, wolfSSL_EVP_sha256(), digest, &digestSz), + ExpectIntEQ(X509_digest(x509ext, wolfSSL_EVP_sha256(), digest, &digestSz), WOLFSSL_SUCCESS); - AssertIntEQ(X509_digest(NULL, wolfSSL_EVP_sha1(), digest, &digestSz), + ExpectIntEQ(X509_digest(NULL, wolfSSL_EVP_sha1(), digest, &digestSz), WOLFSSL_FAILURE); } #endif /* !NO_SHA && !NO_SHA256 && !NO_PWDBASED */ /* test and checkout X509 extensions */ - bc = (BASIC_CONSTRAINTS*)X509_get_ext_d2i(x509ext, NID_basic_constraints, - &crit, NULL); - AssertNotNull(bc); - AssertIntEQ(crit, 0); + ExpectNotNull(bc = (BASIC_CONSTRAINTS*)X509_get_ext_d2i(x509ext, + NID_basic_constraints, &crit, NULL)); + ExpectIntEQ(crit, 0); #ifdef OPENSSL_ALL - ext = X509V3_EXT_i2d(NID_basic_constraints, crit, bc); - AssertNotNull(ext); + ExpectNotNull(ext = X509V3_EXT_i2d(NID_basic_constraints, crit, bc)); X509_EXTENSION_free(ext); + ext = NULL; - AssertNotNull(ext = X509_EXTENSION_new()); + ExpectNotNull(ext = X509_EXTENSION_new()); X509_EXTENSION_set_critical(ext, 1); - AssertNotNull(obj = OBJ_nid2obj(NID_basic_constraints)); - AssertIntEQ(X509_EXTENSION_set_object(ext, obj), SSL_SUCCESS); + ExpectNotNull(obj = OBJ_nid2obj(NID_basic_constraints)); + ExpectIntEQ(X509_EXTENSION_set_object(ext, obj), SSL_SUCCESS); ASN1_OBJECT_free(obj); + obj = NULL; X509_EXTENSION_free(ext); + ext = NULL; - AssertNotNull(ext = X509_EXTENSION_new()); + ExpectNotNull(ext = X509_EXTENSION_new()); X509_EXTENSION_set_critical(ext, 0); - AssertIntEQ(X509_EXTENSION_set_data(ext, NULL), SSL_FAILURE); + ExpectIntEQ(X509_EXTENSION_set_data(ext, NULL), SSL_FAILURE); asn1_str = (ASN1_STRING*)X509_get_ext_d2i(x509ext, NID_key_usage, &crit, NULL); - AssertIntEQ(X509_EXTENSION_set_data(ext, asn1_str), SSL_SUCCESS); + ExpectIntEQ(X509_EXTENSION_set_data(ext, asn1_str), SSL_SUCCESS); ASN1_STRING_free(asn1_str); /* X509_EXTENSION_set_data has made a copy * and X509_get_ext_d2i has created new */ + asn1_str = NULL; X509_EXTENSION_free(ext); + ext = NULL; #endif BASIC_CONSTRAINTS_free(bc); + bc = NULL; - asn1_str = (ASN1_STRING*)X509_get_ext_d2i(x509ext, NID_key_usage, &crit, NULL); - AssertNotNull(asn1_str); - AssertIntEQ(crit, 1); - AssertIntEQ(asn1_str->type, NID_key_usage); + ExpectNotNull(asn1_str = (ASN1_STRING*)X509_get_ext_d2i(x509ext, + NID_key_usage, &crit, NULL)); + ExpectIntEQ(crit, 1); + ExpectIntEQ(asn1_str->type, NID_key_usage); #ifdef OPENSSL_ALL - ext = X509V3_EXT_i2d(NID_key_usage, crit, asn1_str); - AssertNotNull(ext); + ExpectNotNull(ext = X509V3_EXT_i2d(NID_key_usage, crit, asn1_str)); X509_EXTENSION_free(ext); + ext = NULL; #endif ASN1_STRING_free(asn1_str); + asn1_str = NULL; #ifdef OPENSSL_ALL - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509, NID_ext_key_usage, - &crit, NULL); - AssertNotNull(sk); - ext = X509V3_EXT_i2d(NID_ext_key_usage, crit, sk); - AssertNotNull(ext); + ExpectNotNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509, + NID_ext_key_usage, &crit, NULL)); + ExpectNotNull(ext = X509V3_EXT_i2d(NID_ext_key_usage, crit, sk)); X509_EXTENSION_free(ext); + ext = NULL; sk_ASN1_OBJECT_pop_free(sk, NULL); + sk = NULL; #else sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_ext_key_usage, &crit, NULL); - AssertNull(sk); + ExpectNull(sk); #endif - akey = (AUTHORITY_KEYID*)X509_get_ext_d2i(x509ext, - NID_authority_key_identifier, &crit, NULL); - AssertNotNull(akey); + ExpectNotNull(akey = (AUTHORITY_KEYID*)X509_get_ext_d2i(x509ext, + NID_authority_key_identifier, &crit, NULL)); #ifdef OPENSSL_ALL - ext = X509V3_EXT_i2d(NID_authority_key_identifier, crit, akey); - AssertNotNull(ext); + ExpectNotNull(ext = X509V3_EXT_i2d(NID_authority_key_identifier, crit, + akey)); X509_EXTENSION_free(ext); + ext = NULL; #endif wolfSSL_AUTHORITY_KEYID_free(akey); + akey = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, - NID_private_key_usage_period, &crit, NULL); - /* AssertNotNull(sk); NID not yet supported */ - AssertIntEQ(crit, -1); + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_private_key_usage_period, &crit, NULL)); + ExpectIntEQ(crit, -1); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(x509ext, NID_subject_alt_name, - &crit, NULL); + ExpectNotNull(sk = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(x509ext, + NID_subject_alt_name, &crit, NULL)); { int i; for (i = 0; i < sk_GENERAL_NAME_num(sk); i++) { GENERAL_NAME* gen = sk_GENERAL_NAME_value(sk, i); - AssertIntEQ(gen->type, GEN_DNS); - AssertIntEQ(gen->d.dNSName->type, V_ASN1_IA5STRING); + ExpectIntEQ(gen->type, GEN_DNS); + ExpectIntEQ(gen->d.dNSName->type, V_ASN1_IA5STRING); } } - /* AssertNotNull(sk); no alt names set */ sk_GENERAL_NAME_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_issuer_alt_name, - &crit, NULL); - /* AssertNotNull(sk); NID not yet supported */ - AssertIntEQ(crit, -1); + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_issuer_alt_name, &crit, NULL)); + ExpectIntEQ(crit, -1); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_info_access, &crit, - NULL); - /* AssertNotNull(sk); no auth info set */ + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_info_access, &crit, NULL)); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_sinfo_access, - &crit, NULL); - /* AssertNotNull(sk); NID not yet supported */ - AssertIntEQ(crit, -1); + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_sinfo_access, &crit, NULL)); + ExpectIntEQ(crit, -1); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_name_constraints, - &crit, NULL); - /* AssertNotNull(sk); NID not yet supported */ - AssertIntEQ(crit, -1); + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_name_constraints, &crit, NULL)); + ExpectIntEQ(crit, -1); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, - NID_certificate_policies, &crit, NULL); - #if !defined(WOLFSSL_SEP) && !defined(WOLFSSL_CERT_EXT) - AssertNull(sk); - #else - /* AssertNotNull(sk); no cert policy set */ - #endif + /* no cert policy set */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_certificate_policies, &crit, NULL)); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_policy_mappings, - &crit, NULL); - /* AssertNotNull(sk); NID not yet supported */ - AssertIntEQ(crit, -1); + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_policy_mappings, &crit, NULL)); + ExpectIntEQ(crit, -1); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_policy_constraints, - &crit, NULL); - /* AssertNotNull(sk); NID not yet supported */ - AssertIntEQ(crit, -1); + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_policy_constraints, &crit, NULL)); + ExpectIntEQ(crit, -1); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_inhibit_any_policy, - &crit, NULL); - /* AssertNotNull(sk); NID not yet supported */ - AssertIntEQ(crit, -1); + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_inhibit_any_policy, &crit, NULL)); + ExpectIntEQ(crit, -1); sk_ASN1_OBJECT_free(sk); + sk = NULL; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, NID_tlsfeature, &crit, - NULL); - /* AssertNotNull(sk); NID not yet supported */ - AssertIntEQ(crit, -1); + /* NID not yet supported */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, + NID_tlsfeature, &crit, NULL)); + ExpectIntEQ(crit, -1); sk_ASN1_OBJECT_free(sk); + sk = NULL; /* test invalid cases */ crit = 0; - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, -1, &crit, NULL); - AssertNull(sk); - AssertIntEQ(crit, -1); - sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(NULL, NID_tlsfeature, - NULL, NULL); - AssertNull(sk); - - AssertIntEQ(SSL_get_hit(ssl), 0); + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(x509ext, -1, &crit, + NULL)); + ExpectIntEQ(crit, -1); + /* NULL passed for criticality. */ + ExpectNull(sk = (STACK_OF(ASN1_OBJECT)*)X509_get_ext_d2i(NULL, + NID_tlsfeature, NULL, NULL)); + + ExpectIntEQ(SSL_get_hit(ssl), 0); #ifdef OPENSSL_ALL X509_free(x509); #endif @@ -35422,7 +35785,7 @@ static int test_wolfSSL_certs(void) SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && !NO_CERTS */ return res; } @@ -35432,35 +35795,36 @@ static int test_wolfSSL_X509_check_private_key(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_RSA) && \ defined(USE_CERT_BUFFERS_2048) && !defined(NO_CHECK_PRIVATE_KEY) - X509* x509; + EXPECT_DECLS; + X509* x509 = NULL; EVP_PKEY* pkey = NULL; const byte* key; /* Check with correct key */ - AssertNotNull((x509 = X509_load_certificate_file(cliCertFile, - SSL_FILETYPE_PEM))); + ExpectNotNull((x509 = X509_load_certificate_file(cliCertFile, + SSL_FILETYPE_PEM))); key = client_key_der_2048; - AssertNotNull(d2i_PrivateKey(EVP_PKEY_RSA, &pkey, - &key, (long)sizeof_client_key_der_2048)); - AssertIntEQ(X509_check_private_key(x509, pkey), 1); + ExpectNotNull(d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &key, + (long)sizeof_client_key_der_2048)); + ExpectIntEQ(X509_check_private_key(x509, pkey), 1); EVP_PKEY_free(pkey); pkey = NULL; /* Check with wrong key */ key = server_key_der_2048; - AssertNotNull(d2i_PrivateKey(EVP_PKEY_RSA, &pkey, - &key, (long)sizeof_server_key_der_2048)); - AssertIntEQ(X509_check_private_key(x509, pkey), 0); + ExpectNotNull(d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &key, + (long)sizeof_server_key_der_2048)); + ExpectIntEQ(X509_check_private_key(x509, pkey), 0); /* test for incorrect parameter */ - AssertIntEQ(X509_check_private_key(NULL, pkey), 0); - AssertIntEQ(X509_check_private_key(x509, NULL), 0); - AssertIntEQ(X509_check_private_key(NULL, NULL), 0); + ExpectIntEQ(X509_check_private_key(NULL, pkey), 0); + ExpectIntEQ(X509_check_private_key(x509, NULL), 0); + ExpectIntEQ(X509_check_private_key(NULL, NULL), 0); EVP_PKEY_free(pkey); X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -35473,8 +35837,9 @@ static int test_wolfSSL_private_keys(void) #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - WOLFSSL* ssl; - WOLFSSL_CTX* ctx; + EXPECT_DECLS; + WOLFSSL* ssl = NULL; + WOLFSSL_CTX* ctx = NULL; EVP_PKEY* pkey = NULL; OpenSSL_add_all_digests(); @@ -35482,24 +35847,24 @@ static int test_wolfSSL_private_keys(void) #ifndef NO_RSA #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); /* Have to load a cert before you can check the private key against that * certificates public key! */ #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(wolfSSL_CTX_check_private_key(ctx), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_check_private_key(ctx), WOLFSSL_FAILURE); #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(wolfSSL_CTX_check_private_key(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_check_private_key(ctx), WOLFSSL_SUCCESS); #endif - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif #ifdef USE_CERT_BUFFERS_2048 @@ -35508,162 +35873,174 @@ static int test_wolfSSL_private_keys(void) unsigned char buf[FOURK_BUF]; word32 bufSz; - AssertIntEQ(SSL_use_RSAPrivateKey_ASN1(ssl, + ExpectIntEQ(SSL_use_RSAPrivateKey_ASN1(ssl, (unsigned char*)client_key_der_2048, sizeof_client_key_der_2048), WOLFSSL_SUCCESS); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) /* Should mismatch now that a different private key loaded */ - AssertIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif - AssertIntEQ(SSL_use_PrivateKey_ASN1(0, ssl, + ExpectIntEQ(SSL_use_PrivateKey_ASN1(0, ssl, (unsigned char*)server_key, sizeof_server_key_der_2048), WOLFSSL_SUCCESS); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) /* After loading back in DER format of original key, should match */ - AssertIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif /* test loading private key to the WOLFSSL_CTX */ - AssertIntEQ(SSL_CTX_use_PrivateKey_ASN1(0, ctx, + ExpectIntEQ(SSL_CTX_use_PrivateKey_ASN1(0, ctx, (unsigned char*)client_key_der_2048, sizeof_client_key_der_2048), WOLFSSL_SUCCESS); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) /* Should mismatch now that a different private key loaded */ - AssertIntNE(wolfSSL_CTX_check_private_key(ctx), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_CTX_check_private_key(ctx), WOLFSSL_SUCCESS); #endif - AssertIntEQ(SSL_CTX_use_PrivateKey_ASN1(0, ctx, + ExpectIntEQ(SSL_CTX_use_PrivateKey_ASN1(0, ctx, (unsigned char*)server_key, sizeof_server_key_der_2048), WOLFSSL_SUCCESS); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) /* After loading back in DER format of original key, should match */ - AssertIntEQ(wolfSSL_CTX_check_private_key(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_check_private_key(ctx), WOLFSSL_SUCCESS); #endif /* pkey not set yet, expecting to fail */ - AssertIntEQ(SSL_use_PrivateKey(ssl, pkey), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_use_PrivateKey(ssl, pkey), WOLFSSL_FAILURE); /* set PKEY and test again */ - AssertNotNull(wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, &pkey, + ExpectNotNull(wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &server_key, (long)sizeof_server_key_der_2048)); - AssertIntEQ(SSL_use_PrivateKey(ssl, pkey), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_use_PrivateKey(ssl, pkey), WOLFSSL_SUCCESS); /* reuse PKEY structure and test * this should be checked with a memory management sanity checker */ - AssertFalse(server_key == (const unsigned char*)server_key_der_2048); + ExpectFalse(server_key == (const unsigned char*)server_key_der_2048); server_key = (const unsigned char*)server_key_der_2048; - AssertNotNull(wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, &pkey, + ExpectNotNull(wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &server_key, (long)sizeof_server_key_der_2048)); - AssertIntEQ(SSL_use_PrivateKey(ssl, pkey), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_use_PrivateKey(ssl, pkey), WOLFSSL_SUCCESS); /* check striping PKCS8 header with wolfSSL_d2i_PrivateKey */ bufSz = FOURK_BUF; - AssertIntGT((bufSz = wc_CreatePKCS8Key(buf, &bufSz, + ExpectIntGT((bufSz = wc_CreatePKCS8Key(buf, &bufSz, (byte*)server_key_der_2048, sizeof_server_key_der_2048, RSAk, NULL, 0)), 0); server_key = (const unsigned char*)buf; - AssertNotNull(wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &server_key, + ExpectNotNull(wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &server_key, (long)bufSz)); } #endif EVP_PKEY_free(pkey); + pkey = NULL; SSL_free(ssl); /* frees x509 also since loaded into ssl */ + ssl = NULL; SSL_CTX_free(ctx); + ctx = NULL; #endif /* end of RSA private key match tests */ #ifdef HAVE_ECC #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, eccCertFile, + ExpectTrue(SSL_CTX_use_certificate_file(ctx, eccCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif SSL_free(ssl); + ssl = NULL; - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, cliEccKeyFile, + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, cliEccKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); #ifdef WOLFSSL_VALIDATE_ECC_IMPORT - AssertIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif SSL_free(ssl); + ssl = NULL; SSL_CTX_free(ctx); + ctx = NULL; #endif /* end of ECC private key match tests */ #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, edCertFile, + ExpectTrue(SSL_CTX_use_certificate_file(ctx, edCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, edKeyFile, + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, edKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif SSL_free(ssl); + ssl = NULL; - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, cliEdKeyFile, + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, cliEdKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif SSL_free(ssl); + ssl = NULL; SSL_CTX_free(ctx); + ctx = NULL; #endif /* end of Ed25519 private key match tests */ #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, ed448CertFile, + ExpectTrue(SSL_CTX_use_certificate_file(ctx, ed448CertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, ed448KeyFile, + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, ed448KeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif SSL_free(ssl); + ssl = NULL; - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, cliEd448KeyFile, + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, cliEd448KeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); #if !defined(HAVE_USER_RSA) && !defined(NO_CHECK_PRIVATE_KEY) - AssertIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); + ExpectIntNE(wolfSSL_check_private_key(ssl), WOLFSSL_SUCCESS); #endif SSL_free(ssl); + ssl = NULL; SSL_CTX_free(ctx); + ctx = NULL; #endif /* end of Ed448 private key match tests */ EVP_cleanup(); @@ -35677,7 +36054,7 @@ static int test_wolfSSL_private_keys(void) (void)ctx; (void)pkey; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) */ return res; @@ -35688,40 +36065,41 @@ static int test_wolfSSL_PEM_read_PrivateKey(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_RSA) \ && !defined(NO_FILESYSTEM) - XFILE file; + EXPECT_DECLS; + XFILE file = XBADFILE; const char* fname = "./certs/server-key.pem"; - EVP_PKEY* pkey; - RSA* rsa; - WOLFSSL_EVP_PKEY_CTX* ctx; - unsigned char* sig; + EVP_PKEY* pkey = NULL; + RSA* rsa = NULL; + WOLFSSL_EVP_PKEY_CTX* ctx = NULL; + unsigned char* sig = NULL; size_t sigLen; const unsigned char tbs[] = {0, 1, 2, 3, 4, 5, 6, 7}; size_t tbsLen = sizeof(tbs); /* Check error case. */ - AssertNull(pkey = PEM_read_PrivateKey(NULL, NULL, NULL, NULL)); + ExpectNull(pkey = PEM_read_PrivateKey(NULL, NULL, NULL, NULL)); /* Read in an RSA key. */ - file = XFOPEN(fname, "rb"); - AssertTrue(file != XBADFILE); - AssertNotNull(pkey = PEM_read_PrivateKey(file, NULL, NULL, NULL)); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(fname, "rb")) != XBADFILE); + ExpectNotNull(pkey = PEM_read_PrivateKey(file, NULL, NULL, NULL)); + if (file != XBADFILE) + XFCLOSE(file); /* Make sure the key is usable by signing some data with it. */ - AssertNotNull(rsa = EVP_PKEY_get0_RSA(pkey)); - AssertIntGT((sigLen = RSA_size(rsa)), 0); - AssertNotNull(sig = (unsigned char*)XMALLOC(sigLen, HEAP_HINT, + ExpectNotNull(rsa = EVP_PKEY_get0_RSA(pkey)); + ExpectIntGT((sigLen = RSA_size(rsa)), 0); + ExpectNotNull(sig = (unsigned char*)XMALLOC(sigLen, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER)); - AssertNotNull(ctx = EVP_PKEY_CTX_new(pkey, NULL)); - AssertIntEQ(EVP_PKEY_sign_init(ctx), WOLFSSL_SUCCESS); - AssertIntEQ(EVP_PKEY_sign(ctx, sig, &sigLen, tbs, tbsLen), + ExpectNotNull(ctx = EVP_PKEY_CTX_new(pkey, NULL)); + ExpectIntEQ(EVP_PKEY_sign_init(ctx), WOLFSSL_SUCCESS); + ExpectIntEQ(EVP_PKEY_sign(ctx, sig, &sigLen, tbs, tbsLen), WOLFSSL_SUCCESS); XFREE(sig, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -35731,21 +36109,22 @@ static int test_wolfSSL_PEM_read_PUBKEY(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_RSA) \ && !defined(NO_FILESYSTEM) - XFILE file; + EXPECT_DECLS; + XFILE file = XBADFILE; const char* fname = "./certs/client-keyPub.pem"; - EVP_PKEY* pkey; + EVP_PKEY* pkey = NULL; /* Check error case. */ - AssertNull(pkey = PEM_read_PUBKEY(NULL, NULL, NULL, NULL)); + ExpectNull(pkey = PEM_read_PUBKEY(NULL, NULL, NULL, NULL)); /* Read in an RSA key. */ - file = XFOPEN(fname, "rb"); - AssertTrue(file != XBADFILE); - AssertNotNull(pkey = PEM_read_PUBKEY(file, NULL, NULL, NULL)); + ExpectTrue((file = XFOPEN(fname, "rb")) != XBADFILE); + ExpectNotNull(pkey = PEM_read_PUBKEY(file, NULL, NULL, NULL)); EVP_PKEY_free(pkey); - XFCLOSE(file); + if (file != XBADFILE) + XFCLOSE(file); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -35755,7 +36134,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ (!defined(NO_RSA) || defined(HAVE_ECC)) && defined(USE_CERT_BUFFERS_2048) - + EXPECT_DECLS; #ifndef NO_BIO BIO* bio = NULL; #endif @@ -35765,72 +36144,80 @@ static int test_wolfSSL_PEM_PrivateKey(void) #ifndef NO_BIO /* test creating new EVP_PKEY with bad arg */ - AssertNull((pkey = PEM_read_bio_PrivateKey(NULL, NULL, NULL, NULL))); + ExpectNull((pkey = PEM_read_bio_PrivateKey(NULL, NULL, NULL, NULL))); /* test loading RSA key using BIO */ #if !defined(NO_RSA) && !defined(NO_FILESYSTEM) { - XFILE file; + XFILE file = XBADFILE; const char* fname = "./certs/server-key.pem"; const char* fname_rsa_p8 = "./certs/server-keyPkcs8.pem"; size_t sz; - byte* buf; - EVP_PKEY* pkey2; - EVP_PKEY* pkey3; + byte* buf = NULL; + EVP_PKEY* pkey2 = NULL; + EVP_PKEY* pkey3 = NULL; RSA* rsa_key = NULL; - file = XFOPEN(fname, "rb"); - AssertTrue((file != XBADFILE)); - AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); - sz = XFTELL(file); - AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); - AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); - if (buf) { - AssertIntEQ(XFREAD(buf, 1, sz, file), sz); + ExpectTrue((file = XFOPEN(fname, "rb")) != XBADFILE); + ExpectTrue(XFSEEK(file, 0, XSEEK_END) == 0); + ExpectIntGT(sz = XFTELL(file), 0); + ExpectTrue(XFSEEK(file, 0, XSEEK_SET) == 0); + ExpectNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); + if (buf != NULL) { + ExpectIntEQ(XFREAD(buf, 1, sz, file), sz); + } + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; } - XFCLOSE(file); /* Test using BIO new mem and loading PEM private key */ - bio = BIO_new_mem_buf(buf, (int)sz); - AssertNotNull(bio); - AssertNotNull((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); + ExpectNotNull((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); XFREE(buf, NULL, DYNAMIC_TYPE_FILE); + buf = NULL; BIO_free(bio); bio = NULL; - AssertNotNull(pkey2 = EVP_PKEY_new()); - pkey2->type = EVP_PKEY_RSA; + ExpectNotNull(pkey2 = EVP_PKEY_new()); + if (pkey2 != NULL) { + pkey2->type = EVP_PKEY_RSA; + } /* Test parameter copy */ - AssertIntEQ(EVP_PKEY_copy_parameters(pkey2, pkey), 0); + ExpectIntEQ(EVP_PKEY_copy_parameters(pkey2, pkey), 0); EVP_PKEY_free(pkey2); EVP_PKEY_free(pkey); pkey = NULL; /* Qt unit test case : rsa pkcs8 key */ - file = XFOPEN(fname_rsa_p8, "rb"); - AssertTrue((file != XBADFILE)); - AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); - sz = XFTELL(file); - AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); - AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); - if (buf) - AssertIntEQ(XFREAD(buf, 1, sz, file), sz); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(fname_rsa_p8, "rb")) != XBADFILE); + ExpectTrue(XFSEEK(file, 0, XSEEK_END) == 0); + ExpectIntGT(sz = XFTELL(file), 0); + ExpectTrue(XFSEEK(file, 0, XSEEK_SET) == 0); + ExpectNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); + if (buf) { + ExpectIntEQ(XFREAD(buf, 1, sz, file), sz); + } + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } - AssertNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); - AssertNotNull((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); + ExpectNotNull((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); XFREE(buf, NULL, DYNAMIC_TYPE_FILE); + buf = NULL; BIO_free(bio); bio = NULL; - AssertNotNull(pkey3 = EVP_PKEY_new()); + ExpectNotNull(pkey3 = EVP_PKEY_new()); - AssertNotNull(rsa_key = EVP_PKEY_get1_RSA(pkey)); - AssertIntEQ(EVP_PKEY_set1_RSA(pkey3, rsa_key), WOLFSSL_SUCCESS); + ExpectNotNull(rsa_key = EVP_PKEY_get1_RSA(pkey)); + ExpectIntEQ(EVP_PKEY_set1_RSA(pkey3, rsa_key), WOLFSSL_SUCCESS); #ifdef WOLFSSL_ERROR_CODE_OPENSSL - AssertIntEQ(EVP_PKEY_cmp(pkey, pkey3), 1/* match */); + ExpectIntEQ(EVP_PKEY_cmp(pkey, pkey3), 1/* match */); #else - AssertIntEQ(EVP_PKEY_cmp(pkey, pkey3), 0); + ExpectIntEQ(EVP_PKEY_cmp(pkey, pkey3), 0); #endif RSA_free(rsa_key); @@ -35843,79 +36230,92 @@ static int test_wolfSSL_PEM_PrivateKey(void) /* test loading ECC key using BIO */ #if defined(HAVE_ECC) && !defined(NO_FILESYSTEM) { - XFILE file; + XFILE file = XBADFILE; const char* fname = "./certs/ecc-key.pem"; const char* fname_ecc_p8 = "./certs/ecc-keyPkcs8.pem"; size_t sz; - byte* buf; - EVP_PKEY* pkey2; - EVP_PKEY* pkey3; - EC_KEY* ec_key; + byte* buf = NULL; + EVP_PKEY* pkey2 = NULL; + EVP_PKEY* pkey3 = NULL; + EC_KEY* ec_key = NULL; int nid = 0; - file = XFOPEN(fname, "rb"); - AssertTrue((file != XBADFILE)); - AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); - sz = XFTELL(file); - AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); - AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); - if (buf) - AssertIntEQ(XFREAD(buf, 1, sz, file), sz); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(fname, "rb")) != XBADFILE); + ExpectTrue(XFSEEK(file, 0, XSEEK_END) == 0); + ExpectIntGT(sz = XFTELL(file), 0); + ExpectTrue(XFSEEK(file, 0, XSEEK_SET) == 0); + ExpectNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); + if (buf) { + ExpectIntEQ(XFREAD(buf, 1, sz, file), sz); + } + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } /* Test using BIO new mem and loading PEM private key */ - AssertNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); - AssertNotNull((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); + ExpectNotNull((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); XFREE(buf, NULL, DYNAMIC_TYPE_FILE); + buf = NULL; BIO_free(bio); bio = NULL; - AssertNotNull(pkey2 = EVP_PKEY_new()); - AssertNotNull(pkey3 = EVP_PKEY_new()); - pkey2->type = EVP_PKEY_EC; + ExpectNotNull(pkey2 = EVP_PKEY_new()); + ExpectNotNull(pkey3 = EVP_PKEY_new()); + if (pkey2 != NULL) { + pkey2->type = EVP_PKEY_EC; + } /* Test parameter copy */ - AssertIntEQ(EVP_PKEY_copy_parameters(pkey2, pkey), 1); + ExpectIntEQ(EVP_PKEY_copy_parameters(pkey2, pkey), 1); /* Qt unit test case 1*/ - AssertNotNull(ec_key = EVP_PKEY_get1_EC_KEY(pkey)); - AssertIntEQ(EVP_PKEY_set1_EC_KEY(pkey3, ec_key), WOLFSSL_SUCCESS); + ExpectNotNull(ec_key = EVP_PKEY_get1_EC_KEY(pkey)); + ExpectIntEQ(EVP_PKEY_set1_EC_KEY(pkey3, ec_key), WOLFSSL_SUCCESS); #ifdef WOLFSSL_ERROR_CODE_OPENSSL - AssertIntEQ(EVP_PKEY_cmp(pkey, pkey3), 1/* match */); + ExpectIntEQ(EVP_PKEY_cmp(pkey, pkey3), 1/* match */); #else - AssertIntEQ(EVP_PKEY_cmp(pkey, pkey3), 0); + ExpectIntEQ(EVP_PKEY_cmp(pkey, pkey3), 0); #endif /* Test default digest */ - AssertIntEQ(EVP_PKEY_get_default_digest_nid(pkey, &nid), 1); - AssertIntEQ(nid, NID_sha256); + ExpectIntEQ(EVP_PKEY_get_default_digest_nid(pkey, &nid), 1); + ExpectIntEQ(nid, NID_sha256); EC_KEY_free(ec_key); + ec_key = NULL; EVP_PKEY_free(pkey3); + pkey3 = NULL; EVP_PKEY_free(pkey2); + pkey2 = NULL; EVP_PKEY_free(pkey); pkey = NULL; /* Qt unit test case ec pkcs8 key */ - file = XFOPEN(fname_ecc_p8, "rb"); - AssertTrue((file != XBADFILE)); - AssertTrue(XFSEEK(file, 0, XSEEK_END) == 0); - sz = XFTELL(file); - AssertTrue(XFSEEK(file, 0, XSEEK_SET) == 0); - AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); - if (buf) - AssertIntEQ(XFREAD(buf, 1, sz, file), sz); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(fname_ecc_p8, "rb")) != XBADFILE); + ExpectTrue(XFSEEK(file, 0, XSEEK_END) == 0); + ExpectIntGT(sz = XFTELL(file), 0); + ExpectTrue(XFSEEK(file, 0, XSEEK_SET) == 0); + ExpectNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); + if (buf) { + ExpectIntEQ(XFREAD(buf, 1, sz, file), sz); + } + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } - AssertNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); - AssertNotNull((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); + ExpectNotNull((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); XFREE(buf, NULL, DYNAMIC_TYPE_FILE); + buf = NULL; BIO_free(bio); bio = NULL; - AssertNotNull(pkey3 = EVP_PKEY_new()); + ExpectNotNull(pkey3 = EVP_PKEY_new()); /* Qt unit test case */ - AssertNotNull(ec_key = EVP_PKEY_get1_EC_KEY(pkey)); - AssertIntEQ(EVP_PKEY_set1_EC_KEY(pkey3, ec_key), WOLFSSL_SUCCESS); + ExpectNotNull(ec_key = EVP_PKEY_get1_EC_KEY(pkey)); + ExpectIntEQ(EVP_PKEY_set1_EC_KEY(pkey3, ec_key), WOLFSSL_SUCCESS); #ifdef WOLFSSL_ERROR_CODE_OPENSSL - AssertIntEQ(EVP_PKEY_cmp(pkey, pkey3), 1/* match */); + ExpectIntEQ(EVP_PKEY_cmp(pkey, pkey3), 1/* match */); #else - AssertIntEQ(EVP_PKEY_cmp(pkey, pkey3), 0); + ExpectIntEQ(EVP_PKEY_cmp(pkey, pkey3), 0); #endif EC_KEY_free(ec_key); EVP_PKEY_free(pkey3); @@ -35935,59 +36335,59 @@ static int test_wolfSSL_PEM_PrivateKey(void) XMEMSET(extra, BIO_PEM_TEST_CHAR, sizeof(extra)); - AssertNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(BIO_set_write_buf_size(bio, 4096), SSL_FAILURE); - AssertNotNull(pub_bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(BIO_set_write_buf_size(pub_bio, 4096), SSL_FAILURE); + ExpectNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(BIO_set_write_buf_size(bio, 4096), SSL_FAILURE); + ExpectNotNull(pub_bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(BIO_set_write_buf_size(pub_bio, 4096), SSL_FAILURE); - AssertNull(d2i_PrivateKey(EVP_PKEY_EC, &pkey, + ExpectNull(d2i_PrivateKey(EVP_PKEY_EC, &pkey, &server_key, (long)sizeof_server_key_der_2048)); - AssertNull(pkey); + ExpectNull(pkey); - AssertNotNull(wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, &pkey, + ExpectNotNull(wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &server_key, (long)sizeof_server_key_der_2048)); - AssertIntEQ(PEM_write_bio_PrivateKey(NULL, pkey, NULL, NULL, 0, NULL, + ExpectIntEQ(PEM_write_bio_PrivateKey(NULL, pkey, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_bio_PrivateKey(bio, NULL, NULL, NULL, 0, NULL, + ExpectIntEQ(PEM_write_bio_PrivateKey(bio, NULL, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, NULL, + ExpectIntEQ(PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, NULL, NULL), WOLFSSL_SUCCESS); - AssertIntGT(BIO_pending(bio), 0); - AssertIntEQ(BIO_pending(bio), 1679); + ExpectIntGT(BIO_pending(bio), 0); + ExpectIntEQ(BIO_pending(bio), 1679); /* Check if the pubkey API writes only the public key */ #ifdef WOLFSSL_KEY_GEN - AssertIntEQ(PEM_write_bio_PUBKEY(NULL, pkey), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_bio_PUBKEY(pub_bio, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_bio_PUBKEY(pub_bio, pkey), WOLFSSL_SUCCESS); - AssertIntGT(BIO_pending(pub_bio), 0); + ExpectIntEQ(PEM_write_bio_PUBKEY(NULL, pkey), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_bio_PUBKEY(pub_bio, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_bio_PUBKEY(pub_bio, pkey), WOLFSSL_SUCCESS); + ExpectIntGT(BIO_pending(pub_bio), 0); /* Previously both the private key and the pubkey calls would write * out the private key and the PEM header was the only difference. * The public PEM should be significantly shorter than the * private key versison. */ - AssertIntEQ(BIO_pending(pub_bio), 451); + ExpectIntEQ(BIO_pending(pub_bio), 451); #endif /* test creating new EVP_PKEY with good args */ - AssertNotNull((pkey2 = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); + ExpectNotNull((pkey2 = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))); if (pkey && pkey->pkey.ptr && pkey2 && pkey2->pkey.ptr) - AssertIntEQ((int)XMEMCMP(pkey->pkey.ptr, pkey2->pkey.ptr, pkey->pkey_sz), 0); + ExpectIntEQ((int)XMEMCMP(pkey->pkey.ptr, pkey2->pkey.ptr, pkey->pkey_sz), 0); /* test of reuse of EVP_PKEY */ - AssertNull(PEM_read_bio_PrivateKey(bio, &pkey, NULL, NULL)); - AssertIntEQ(BIO_pending(bio), 0); - AssertIntEQ(PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, NULL, NULL), + ExpectNull(PEM_read_bio_PrivateKey(bio, &pkey, NULL, NULL)); + ExpectIntEQ(BIO_pending(bio), 0); + ExpectIntEQ(PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, NULL, NULL), SSL_SUCCESS); - AssertIntEQ(BIO_write(bio, extra, 10), 10); /* add 10 extra bytes after PEM */ - AssertNotNull(PEM_read_bio_PrivateKey(bio, &pkey, NULL, NULL)); - AssertNotNull(pkey); + ExpectIntEQ(BIO_write(bio, extra, 10), 10); /* add 10 extra bytes after PEM */ + ExpectNotNull(PEM_read_bio_PrivateKey(bio, &pkey, NULL, NULL)); + ExpectNotNull(pkey); if (pkey && pkey->pkey.ptr && pkey2 && pkey2->pkey.ptr) { - AssertIntEQ((int)XMEMCMP(pkey->pkey.ptr, pkey2->pkey.ptr, pkey->pkey_sz),0); + ExpectIntEQ((int)XMEMCMP(pkey->pkey.ptr, pkey2->pkey.ptr, pkey->pkey_sz),0); } - AssertIntEQ(BIO_pending(bio), 10); /* check 10 extra bytes still there */ - AssertIntEQ(BIO_read(bio, extra, 10), 10); + ExpectIntEQ(BIO_pending(bio), 10); /* check 10 extra bytes still there */ + ExpectIntEQ(BIO_read(bio, extra, 10), 10); for (i = 0; i < 10; i++) { - AssertIntEQ(extra[i], BIO_PEM_TEST_CHAR); + ExpectIntEQ(extra[i], BIO_PEM_TEST_CHAR); } BIO_free(pub_bio); @@ -36005,49 +36405,52 @@ static int test_wolfSSL_PEM_PrivateKey(void) !defined(NO_MD5) && defined(WOLFSSL_KEY_GEN) && \ !defined(HAVE_USER_RSA) && !defined(NO_RSA) { - XFILE f; + XFILE f = XBADFILE; wc_pem_password_cb* passwd_cb; void* passwd_cb_userdata; - SSL_CTX* ctx; + SSL_CTX* ctx = NULL; char passwd[] = "bad password"; #ifndef WOLFSSL_NO_TLS12 #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(TLSv1_2_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(TLSv1_2_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(TLSv1_2_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(TLSv1_2_client_method())); #endif #else #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfTLSv1_3_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfTLSv1_3_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfTLSv1_3_client_method())); #endif #endif - AssertNotNull(bio = BIO_new_file("./certs/server-keyEnc.pem", "rb")); + ExpectNotNull(bio = BIO_new_file("./certs/server-keyEnc.pem", "rb")); SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); - AssertNotNull(passwd_cb = SSL_CTX_get_default_passwd_cb(ctx)); - AssertNull(passwd_cb_userdata = + ExpectNotNull(passwd_cb = SSL_CTX_get_default_passwd_cb(ctx)); + ExpectNull(passwd_cb_userdata = SSL_CTX_get_default_passwd_cb_userdata(ctx)); /* fail case with password call back */ - AssertNull(pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, + ExpectNull(pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, (void*)passwd)); BIO_free(bio); - AssertNotNull(bio = BIO_new_file("./certs/server-keyEnc.pem", "rb")); - AssertNull(pkey = PEM_read_bio_PrivateKey(bio, NULL, passwd_cb, + ExpectNotNull(bio = BIO_new_file("./certs/server-keyEnc.pem", "rb")); + ExpectNull(pkey = PEM_read_bio_PrivateKey(bio, NULL, passwd_cb, (void*)passwd)); BIO_free(bio); - f = XFOPEN("./certs/server-keyEnc.pem", "rb"); - AssertNotNull(bio = BIO_new_fp(f, BIO_CLOSE)); + ExpectTrue((f = XFOPEN("./certs/server-keyEnc.pem", "rb")) != XBADFILE); + ExpectNotNull(bio = BIO_new_fp(f, BIO_CLOSE)); + if ((bio == NULL) && (f != XBADFILE)) { + XFCLOSE(f); + } /* use callback that works */ - AssertNotNull(pkey = PEM_read_bio_PrivateKey(bio, NULL, passwd_cb, + ExpectNotNull(pkey = PEM_read_bio_PrivateKey(bio, NULL, passwd_cb, (void*)"yassl123")); - AssertIntEQ(SSL_CTX_use_PrivateKey(ctx, pkey), SSL_SUCCESS); + ExpectIntEQ(SSL_CTX_use_PrivateKey(ctx, pkey), SSL_SUCCESS); EVP_PKEY_free(pkey); pkey = NULL; @@ -36062,35 +36465,35 @@ static int test_wolfSSL_PEM_PrivateKey(void) #if defined(HAVE_ECC) && !defined(NO_FILESYSTEM) { unsigned char buf[2048]; - size_t bytes; - XFILE f; - SSL_CTX* ctx; + size_t bytes = 0; + XFILE f = XBADFILE; + SSL_CTX* ctx = NULL; #ifndef WOLFSSL_NO_TLS12 #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(TLSv1_2_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(TLSv1_2_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(TLSv1_2_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(TLSv1_2_client_method())); #endif #else #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfTLSv1_3_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfTLSv1_3_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfTLSv1_3_client_method())); #endif #endif - f = XFOPEN("./certs/ecc-key.der", "rb"); - AssertTrue((f != XBADFILE)); - bytes = (size_t)XFREAD(buf, 1, sizeof(buf), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN("./certs/ecc-key.der", "rb")) != XBADFILE); + ExpectIntGT(bytes = (size_t)XFREAD(buf, 1, sizeof(buf), f), 0); + if (f != XBADFILE) + XFCLOSE(f); server_key = buf; pkey = NULL; - AssertNull(d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &server_key, bytes)); - AssertNull(pkey); - AssertNotNull(d2i_PrivateKey(EVP_PKEY_EC, &pkey, &server_key, bytes)); - AssertIntEQ(SSL_CTX_use_PrivateKey(ctx, pkey), SSL_SUCCESS); + ExpectNull(d2i_PrivateKey(EVP_PKEY_RSA, &pkey, &server_key, bytes)); + ExpectNull(pkey); + ExpectNotNull(d2i_PrivateKey(EVP_PKEY_EC, &pkey, &server_key, bytes)); + ExpectIntEQ(SSL_CTX_use_PrivateKey(ctx, pkey), SSL_SUCCESS); EVP_PKEY_free(pkey); pkey = NULL; @@ -36098,7 +36501,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) } #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #ifndef NO_BIO (void)bio; @@ -36116,25 +36519,27 @@ static int test_wolfSSL_PEM_file_RSAKey(void) #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && \ defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) && \ !defined(HAVE_USER_RSA) && !defined(NO_FILESYSTEM) && !defined(NO_CERTS) + EXPECT_DECLS; RSA* rsa = NULL; - XFILE fp; + XFILE fp = XBADFILE; - AssertTrue((fp = XFOPEN("./certs/rsa-pub-2048.pem", "rb")) != XBADFILE); - AssertNotNull((rsa = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL))); - XFCLOSE(fp); - AssertIntEQ(RSA_size(rsa), 256); + ExpectTrue((fp = XFOPEN("./certs/rsa-pub-2048.pem", "rb")) != XBADFILE); + ExpectNotNull((rsa = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL))); + if (fp != XBADFILE) + XFCLOSE(fp); + ExpectIntEQ(RSA_size(rsa), 256); - AssertIntEQ(PEM_write_RSAPublicKey(XBADFILE, rsa), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_RSAPublicKey(stderr, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_RSAPublicKey(stderr, rsa), WOLFSSL_SUCCESS); + ExpectIntEQ(PEM_write_RSAPublicKey(XBADFILE, rsa), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_RSAPublicKey(stderr, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_RSAPublicKey(stderr, rsa), WOLFSSL_SUCCESS); - AssertIntEQ(PEM_write_RSA_PUBKEY(XBADFILE, rsa), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_RSA_PUBKEY(stderr, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_RSA_PUBKEY(stderr, rsa), WOLFSSL_SUCCESS); + ExpectIntEQ(PEM_write_RSA_PUBKEY(XBADFILE, rsa), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_RSA_PUBKEY(stderr, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_RSA_PUBKEY(stderr, rsa), WOLFSSL_SUCCESS); RSA_free(rsa); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && \ (defined(WOLFSSL_KEY_GEN) || WOLFSSL_CERT_GEN) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && !defined(NO_CERTS) */ @@ -36147,33 +36552,59 @@ static int test_wolfSSL_PEM_file_RSAPrivateKey(void) #if !defined(NO_RSA) && defined(OPENSSL_EXTRA) && defined(WOLFSSL_KEY_GEN) && \ !defined(HAVE_USER_RSA) && !defined(NO_FILESYSTEM) && \ (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) + EXPECT_DECLS; RSA* rsa = NULL; XFILE f = NULL; - f = XFOPEN(svrKeyFile, "r"); - AssertTrue((f != XBADFILE)); - AssertNotNull((rsa = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL))); - AssertIntEQ(RSA_size(rsa), 256); + ExpectTrue((f = XFOPEN(svrKeyFile, "r")) != XBADFILE); + ExpectNotNull((rsa = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL))); + ExpectIntEQ(RSA_size(rsa), 256); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } - AssertIntEQ(PEM_write_RSAPrivateKey(XBADFILE, rsa, NULL, NULL, 0, NULL, + ExpectIntEQ(PEM_write_RSAPrivateKey(XBADFILE, rsa, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_RSAPrivateKey(stderr, NULL, NULL, NULL, 0, NULL, + ExpectIntEQ(PEM_write_RSAPrivateKey(stderr, NULL, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_RSAPrivateKey(stderr, rsa, NULL, NULL, 0, NULL, NULL), + ExpectIntEQ(PEM_write_RSAPrivateKey(stderr, rsa, NULL, NULL, 0, NULL, NULL), WOLFSSL_SUCCESS); RSA_free(rsa); - XFCLOSE(f); #ifdef HAVE_ECC - f = XFOPEN(eccKeyFile, "r"); - AssertTrue((f != XBADFILE)); - AssertNull((rsa = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL))); - - XFCLOSE(f); + ExpectTrue((f = XFOPEN(eccKeyFile, "r")) != XBADFILE); + ExpectNull((rsa = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL))); + if (f != XBADFILE) + XFCLOSE(f); #endif /* HAVE_ECC */ - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); +#endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) */ + return res; +} + +static int test_wolfSSL_PEM_read_RSA_PUBKEY(void) +{ + int res = TEST_SKIPPED; +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ + !defined(NO_FILESYSTEM) && !defined(NO_RSA) + EXPECT_DECLS; + XFILE file = XBADFILE; + const char* fname = "./certs/client-keyPub.pem"; + RSA *rsa = NULL; + + ExpectNull(wolfSSL_PEM_read_RSA_PUBKEY(XBADFILE, NULL, NULL, NULL)); + + ExpectTrue((file = XFOPEN(fname, "rb")) != XBADFILE); + ExpectNotNull((rsa = PEM_read_RSA_PUBKEY(file, NULL, NULL, NULL))); + ExpectIntEQ(RSA_size(rsa), 256); + RSA_free(rsa); + if (file != XBADFILE) + XFCLOSE(file); + + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) */ return res; } @@ -36185,53 +36616,64 @@ static int test_wolfSSL_PEM_bio_RSAKey(void) #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && \ defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) && \ !defined(HAVE_USER_RSA) && !defined(NO_FILESYSTEM) && !defined(NO_CERTS) + EXPECT_DECLS; RSA* rsa = NULL; BIO* bio = NULL; /* PrivateKey */ - AssertNotNull(bio = BIO_new_file(svrKeyFile, "rb")); - AssertNull((rsa = PEM_read_bio_RSAPrivateKey(NULL, NULL, NULL, NULL))); - AssertNotNull(PEM_read_bio_RSAPrivateKey(bio, &rsa, NULL, NULL)); - AssertNotNull(rsa); - AssertIntEQ(RSA_size(rsa), 256); - AssertIntEQ(PEM_write_bio_RSAPrivateKey(NULL, NULL, NULL, NULL, 0, NULL, \ + ExpectNotNull(bio = BIO_new_file(svrKeyFile, "rb")); + ExpectNull((rsa = PEM_read_bio_RSAPrivateKey(NULL, NULL, NULL, NULL))); + ExpectNotNull(PEM_read_bio_RSAPrivateKey(bio, &rsa, NULL, NULL)); + ExpectNotNull(rsa); + ExpectIntEQ(RSA_size(rsa), 256); + ExpectIntEQ(PEM_write_bio_RSAPrivateKey(NULL, NULL, NULL, NULL, 0, NULL, \ NULL), WOLFSSL_FAILURE); BIO_free(bio); - AssertNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, \ + bio = NULL; + ExpectNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, \ NULL), WOLFSSL_SUCCESS); BIO_free(bio); + bio = NULL; RSA_free(rsa); + rsa = NULL; /* PUBKEY */ - AssertNotNull(bio = BIO_new_file("./certs/rsa-pub-2048.pem", "rb")); - AssertNull((rsa = PEM_read_bio_RSA_PUBKEY(NULL, NULL, NULL, NULL))); - AssertNotNull((rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL))); - AssertIntEQ(RSA_size(rsa), 256); - AssertIntEQ(PEM_write_bio_RSA_PUBKEY(NULL, NULL), WOLFSSL_FAILURE); + ExpectNotNull(bio = BIO_new_file("./certs/rsa-pub-2048.pem", "rb")); + ExpectNull((rsa = PEM_read_bio_RSA_PUBKEY(NULL, NULL, NULL, NULL))); + ExpectNotNull((rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL))); + ExpectIntEQ(RSA_size(rsa), 256); + ExpectIntEQ(PEM_write_bio_RSA_PUBKEY(NULL, NULL), WOLFSSL_FAILURE); BIO_free(bio); - AssertNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_RSA_PUBKEY(bio, rsa), WOLFSSL_SUCCESS); + bio = NULL; + ExpectNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_RSA_PUBKEY(bio, rsa), WOLFSSL_SUCCESS); BIO_free(bio); + bio = NULL; RSA_free(rsa); + rsa = NULL; /* Ensure that keys beginning with BEGIN RSA PUBLIC KEY can be read, too. */ - AssertNotNull(bio = BIO_new_file("./certs/server-keyPub.pem", "rb")); - AssertNotNull((rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_file("./certs/server-keyPub.pem", "rb")); + ExpectNotNull((rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL))); BIO_free(bio); + bio = NULL; RSA_free(rsa); + rsa = NULL; #ifdef HAVE_ECC /* ensure that non-rsa keys do not work */ - AssertNotNull(bio = BIO_new_file(eccKeyFile, "rb")); /* ecc key */ - AssertNull((rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL))); - AssertNull((rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_file(eccKeyFile, "rb")); /* ecc key */ + ExpectNull((rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL))); + ExpectNull((rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL))); BIO_free(bio); + bio = NULL; RSA_free(rsa); + rsa = NULL; #endif /* HAVE_ECC */ - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && \ (defined(WOLFSSL_KEY_GEN) || WOLFSSL_CERT_GEN) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && !defined(NO_CERTS) */ @@ -36241,24 +36683,26 @@ static int test_wolfSSL_PEM_bio_RSAKey(void) static int test_wolfSSL_PEM_bio_RSAPrivateKey(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && !defined(NO_RSA) +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ + !defined(NO_FILESYSTEM) && !defined(NO_RSA) + EXPECT_DECLS; RSA* rsa = NULL; RSA* rsa_dup = NULL; BIO* bio = NULL; - AssertNotNull(bio = BIO_new_file(svrKeyFile, "rb")); - AssertNotNull((rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL))); - AssertIntEQ(RSA_size(rsa), 256); + ExpectNotNull(bio = BIO_new_file(svrKeyFile, "rb")); + ExpectNotNull((rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL))); + ExpectIntEQ(RSA_size(rsa), 256); #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) && !defined(HAVE_USER_RSA) - AssertNull(rsa_dup = RSAPublicKey_dup(NULL)); + ExpectNull(rsa_dup = RSAPublicKey_dup(NULL)); /* Test duplicating empty key. */ - rsa_dup = RSA_new(); - AssertNull(RSAPublicKey_dup(rsa_dup)); + ExpectNotNull(rsa_dup = RSA_new()); + ExpectNull(RSAPublicKey_dup(rsa_dup)); RSA_free(rsa_dup); - AssertNotNull(rsa_dup = RSAPublicKey_dup(rsa)); - AssertPtrNE(rsa_dup, rsa); + rsa_dup = NULL; + ExpectNotNull(rsa_dup = RSAPublicKey_dup(rsa)); + ExpectPtrNE(rsa_dup, rsa); #endif /* test if valgrind complains about unreleased memory */ @@ -36266,40 +36710,20 @@ static int test_wolfSSL_PEM_bio_RSAPrivateKey(void) RSA_free(rsa); BIO_free(bio); + bio = NULL; RSA_free(rsa); + rsa = NULL; RSA_free(rsa_dup); + rsa_dup = NULL; #ifdef HAVE_ECC - AssertNotNull(bio = BIO_new_file(eccKeyFile, "rb")); - AssertNull((rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_file(eccKeyFile, "rb")); + ExpectNull((rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL))); BIO_free(bio); #endif /* HAVE_ECC */ - res = TEST_RES_CHECK(1); - #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) */ - return res; -} - -static int test_wolfSSL_PEM_read_RSA_PUBKEY(void) -{ - int res = TEST_SKIPPED; -#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && !defined(NO_RSA) - XFILE file; - const char* fname = "./certs/client-keyPub.pem"; - RSA *rsa; - - AssertNull(wolfSSL_PEM_read_RSA_PUBKEY(XBADFILE, NULL, NULL, NULL)); - - file = XFOPEN(fname, "rb"); - AssertTrue((file != XBADFILE)); - AssertNotNull((rsa = PEM_read_RSA_PUBKEY(file, NULL, NULL, NULL))); - AssertIntEQ(RSA_size(rsa), 256); - RSA_free(rsa); - XFCLOSE(file); - - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) */ return res; } @@ -36310,42 +36734,51 @@ static int test_wolfSSL_PEM_bio_DSAKey(void) #ifndef HAVE_SELFTEST #if (defined(WOLFSSL_QT) || defined(OPENSSL_ALL)) && !defined(NO_CERTS) && \ defined(WOLFSSL_KEY_GEN) && !defined(NO_FILESYSTEM) && !defined(NO_DSA) + EXPECT_DECLS; DSA* dsa = NULL; BIO* bio = NULL; /* PrivateKey */ - AssertNotNull(bio = BIO_new_file("./certs/1024/dsa1024.pem", "rb")); - AssertNull((dsa = PEM_read_bio_DSAPrivateKey(NULL, NULL, NULL, NULL))); - AssertNotNull((dsa = PEM_read_bio_DSAPrivateKey(bio, NULL, NULL, NULL))); - AssertIntEQ(BN_num_bytes(dsa->g), 128); - AssertIntEQ(PEM_write_bio_DSAPrivateKey(NULL, NULL, NULL, NULL, 0, NULL, NULL), - WOLFSSL_FAILURE); + ExpectNotNull(bio = BIO_new_file("./certs/1024/dsa1024.pem", "rb")); + ExpectNull((dsa = PEM_read_bio_DSAPrivateKey(NULL, NULL, NULL, NULL))); + ExpectNotNull((dsa = PEM_read_bio_DSAPrivateKey(bio, NULL, NULL, NULL))); + ExpectIntEQ(BN_num_bytes(dsa->g), 128); + ExpectIntEQ(PEM_write_bio_DSAPrivateKey(NULL, NULL, NULL, NULL, 0, NULL, + NULL), WOLFSSL_FAILURE); BIO_free(bio); - AssertNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_DSAPrivateKey(bio, dsa, NULL, NULL, 0, NULL, NULL), - WOLFSSL_SUCCESS); + bio = NULL; + ExpectNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_DSAPrivateKey(bio, dsa, NULL, NULL, 0, NULL, + NULL), WOLFSSL_SUCCESS); BIO_free(bio); + bio = NULL; DSA_free(dsa); + dsa = NULL; /* PUBKEY */ - AssertNotNull(bio = BIO_new_file("./certs/1024/dsa-pub-1024.pem", "rb")); - AssertNull((dsa = PEM_read_bio_DSA_PUBKEY(NULL, NULL, NULL, NULL))); - AssertNotNull((dsa = PEM_read_bio_DSA_PUBKEY(bio, NULL, NULL, NULL))); - AssertIntEQ(BN_num_bytes(dsa->g), 128); - AssertIntEQ(PEM_write_bio_DSA_PUBKEY(NULL, NULL), WOLFSSL_FAILURE); + ExpectNotNull(bio = BIO_new_file("./certs/1024/dsa-pub-1024.pem", "rb")); + ExpectNull((dsa = PEM_read_bio_DSA_PUBKEY(NULL, NULL, NULL, NULL))); + ExpectNotNull((dsa = PEM_read_bio_DSA_PUBKEY(bio, NULL, NULL, NULL))); + ExpectIntEQ(BN_num_bytes(dsa->g), 128); + ExpectIntEQ(PEM_write_bio_DSA_PUBKEY(NULL, NULL), WOLFSSL_FAILURE); BIO_free(bio); - AssertNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_DSA_PUBKEY(bio, dsa), WOLFSSL_SUCCESS); + bio = NULL; + ExpectNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_DSA_PUBKEY(bio, dsa), WOLFSSL_SUCCESS); BIO_free(bio); + bio = NULL; DSA_free(dsa); + dsa = NULL; #ifdef HAVE_ECC /* ensure that non-dsa keys do not work */ - AssertNotNull(bio = BIO_new_file(eccKeyFile, "rb")); /* ecc key */ - AssertNull((dsa = PEM_read_bio_DSAPrivateKey(bio, NULL, NULL, NULL))); - AssertNull((dsa = PEM_read_bio_DSA_PUBKEY(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_file(eccKeyFile, "rb")); /* ecc key */ + ExpectNull((dsa = PEM_read_bio_DSAPrivateKey(bio, NULL, NULL, NULL))); + ExpectNull((dsa = PEM_read_bio_DSA_PUBKEY(bio, NULL, NULL, NULL))); BIO_free(bio); + bio = NULL; DSA_free(dsa); + dsa = NULL; #endif /* HAVE_ECC */ res = TEST_RES_CHECK(1); @@ -36361,6 +36794,7 @@ static int test_wolfSSL_PEM_bio_ECKey(void) int res = TEST_SKIPPED; #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && \ defined(WOLFSSL_KEY_GEN) && !defined(NO_FILESYSTEM) && defined(HAVE_ECC) + EXPECT_DECLS; EC_KEY* ec = NULL; EC_KEY* ec2; BIO* bio = NULL; @@ -36376,106 +36810,118 @@ static int test_wolfSSL_PEM_bio_ECKey(void) "-----END EC PRIVATE KEY-----"; /* PrivateKey */ - AssertNotNull(bio = BIO_new_file("./certs/ecc-key.pem", "rb")); - AssertNull((ec = PEM_read_bio_ECPrivateKey(NULL, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_file("./certs/ecc-key.pem", "rb")); + ExpectNull((ec = PEM_read_bio_ECPrivateKey(NULL, NULL, NULL, NULL))); ec2 = NULL; - AssertNotNull((ec = PEM_read_bio_ECPrivateKey(bio, &ec2, NULL, NULL))); - AssertIntEQ(ec == ec2, 1); - AssertIntEQ(wc_ecc_size((ecc_key*)ec->internal), 32); - AssertIntEQ(PEM_write_bio_ECPrivateKey(NULL, NULL, NULL, NULL, 0, NULL, + ExpectNotNull((ec = PEM_read_bio_ECPrivateKey(bio, &ec2, NULL, NULL))); + ExpectIntEQ(ec == ec2, 1); + ExpectIntEQ(wc_ecc_size((ecc_key*)ec->internal), 32); + ExpectIntEQ(PEM_write_bio_ECPrivateKey(NULL, NULL, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_bio_ECPrivateKey(bio, NULL, NULL, NULL, 0, NULL, + ExpectIntEQ(PEM_write_bio_ECPrivateKey(bio, NULL, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_bio_ECPrivateKey(NULL, ec, NULL, NULL, 0, NULL, NULL), + ExpectIntEQ(PEM_write_bio_ECPrivateKey(NULL, ec, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); BIO_free(bio); + bio = NULL; /* Public key data - fail. */ - AssertNotNull(bio = BIO_new_file("./certs/ecc-client-keyPub.pem", "rb")); - AssertNull(PEM_read_bio_ECPrivateKey(bio, NULL, NULL, NULL)); + ExpectNotNull(bio = BIO_new_file("./certs/ecc-client-keyPub.pem", "rb")); + ExpectNull(PEM_read_bio_ECPrivateKey(bio, NULL, NULL, NULL)); BIO_free(bio); - AssertNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_ECPrivateKey(bio, ec, NULL, NULL, 0, NULL, \ + bio = NULL; + ExpectNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_ECPrivateKey(bio, ec, NULL, NULL, 0, NULL, \ NULL), WOLFSSL_SUCCESS); BIO_free(bio); + bio = NULL; - AssertIntEQ(PEM_write_ECPrivateKey(XBADFILE, NULL, NULL, NULL, 0, NULL, + ExpectIntEQ(PEM_write_ECPrivateKey(XBADFILE, NULL, NULL, NULL, 0, NULL, NULL),WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_ECPrivateKey(stderr, NULL, NULL, NULL, 0, NULL, NULL), + ExpectIntEQ(PEM_write_ECPrivateKey(stderr, NULL, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_ECPrivateKey(XBADFILE, ec, NULL, NULL, 0, NULL, NULL), + ExpectIntEQ(PEM_write_ECPrivateKey(XBADFILE, ec, NULL, NULL, 0, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_ECPrivateKey(stderr, ec, NULL, NULL, 0, NULL, NULL), + ExpectIntEQ(PEM_write_ECPrivateKey(stderr, ec, NULL, NULL, 0, NULL, NULL), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(NULL, NULL, NULL, 0, NULL, + ExpectIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(NULL, NULL, NULL, 0, NULL, NULL), 0); #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM) - AssertIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(ec, NULL, NULL, 0, NULL, + ExpectIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(ec, NULL, NULL, 0, NULL, NULL), 0); - AssertIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(NULL, NULL, NULL, 0, &pem, + ExpectIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(NULL, NULL, NULL, 0, &pem, NULL), 0); - AssertIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(NULL, NULL, NULL, 0, NULL, + ExpectIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(NULL, NULL, NULL, 0, NULL, &pLen), 0); - AssertIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(NULL, NULL, NULL, 0, &pem, + ExpectIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(NULL, NULL, NULL, 0, &pem, &pLen), 0); - AssertIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(ec, NULL, NULL, 0, NULL, + ExpectIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(ec, NULL, NULL, 0, NULL, &pLen), 0); - AssertIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(ec, NULL, NULL, 0, &pem, + ExpectIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(ec, NULL, NULL, 0, &pem, NULL), 0); - AssertIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(ec, NULL, NULL, 0, &pem, + ExpectIntEQ(wolfSSL_PEM_write_mem_ECPrivateKey(ec, NULL, NULL, 0, &pem, &pLen), 1); - AssertIntGT(pLen, 0); + ExpectIntGT(pLen, 0); XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif EC_KEY_free(ec); + ec = NULL; /* PUBKEY */ - AssertNotNull(bio = BIO_new_file("./certs/ecc-client-keyPub.pem", "rb")); - AssertNull((ec = PEM_read_bio_EC_PUBKEY(NULL, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_file("./certs/ecc-client-keyPub.pem", "rb")); + ExpectNull((ec = PEM_read_bio_EC_PUBKEY(NULL, NULL, NULL, NULL))); ec2 = NULL; - AssertNotNull((ec = PEM_read_bio_EC_PUBKEY(bio, &ec2, NULL, NULL))); - AssertIntEQ(ec == ec2, 1); - AssertIntEQ(wc_ecc_size((ecc_key*)ec->internal), 32); - AssertIntEQ(PEM_write_bio_EC_PUBKEY(NULL, NULL), WOLFSSL_FAILURE); + ExpectNotNull((ec = PEM_read_bio_EC_PUBKEY(bio, &ec2, NULL, NULL))); + ExpectIntEQ(ec == ec2, 1); + ExpectIntEQ(wc_ecc_size((ecc_key*)ec->internal), 32); + ExpectIntEQ(PEM_write_bio_EC_PUBKEY(NULL, NULL), WOLFSSL_FAILURE); BIO_free(bio); + bio = NULL; /* Test 0x30, 0x00 fails. */ - AssertNotNull(bio = BIO_new_mem_buf((unsigned char*)ec_key_bad_1, + ExpectNotNull(bio = BIO_new_mem_buf((unsigned char*)ec_key_bad_1, sizeof(ec_key_bad_1))); - AssertNull(PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL)); + ExpectNull(PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL)); BIO_free(bio); + bio = NULL; /* Private key data - fail. */ - AssertNotNull(bio = BIO_new_file("./certs/ecc-key.pem", "rb")); - AssertNull(PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL)); + ExpectNotNull(bio = BIO_new_file("./certs/ecc-key.pem", "rb")); + ExpectNull(PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL)); BIO_free(bio); - AssertNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_EC_PUBKEY(bio, ec), WOLFSSL_SUCCESS); + bio = NULL; + ExpectNotNull(bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_EC_PUBKEY(bio, ec), WOLFSSL_SUCCESS); BIO_free(bio); + bio = NULL; /* Same test as above, but with a file pointer rather than a BIO. */ - AssertIntEQ(PEM_write_EC_PUBKEY(NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_EC_PUBKEY(NULL, ec), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_EC_PUBKEY(stderr, NULL), WOLFSSL_FAILURE); - AssertIntEQ(PEM_write_EC_PUBKEY(stderr, ec), WOLFSSL_SUCCESS); + ExpectIntEQ(PEM_write_EC_PUBKEY(NULL, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_EC_PUBKEY(NULL, ec), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_EC_PUBKEY(stderr, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(PEM_write_EC_PUBKEY(stderr, ec), WOLFSSL_SUCCESS); EC_KEY_free(ec); + ec = NULL; #ifndef NO_RSA /* ensure that non-ec keys do not work */ - AssertNotNull(bio = BIO_new_file(svrKeyFile, "rb")); /* rsa key */ - AssertNull((ec = PEM_read_bio_ECPrivateKey(bio, NULL, NULL, NULL))); - AssertNull((ec = PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_file(svrKeyFile, "rb")); /* rsa key */ + ExpectNull((ec = PEM_read_bio_ECPrivateKey(bio, NULL, NULL, NULL))); + ExpectNull((ec = PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL))); BIO_free(bio); + bio = NULL; EC_KEY_free(ec); - #endif /* HAVE_ECC */ + ec = NULL; + #endif /* !NO_RSA */ /* Test 0x30, 0x00 fails. */ - AssertNotNull(bio = BIO_new_mem_buf((unsigned char*)ec_priv_key_bad_1, + ExpectNotNull(bio = BIO_new_mem_buf((unsigned char*)ec_priv_key_bad_1, sizeof(ec_priv_key_bad_1))); - AssertNull(PEM_read_bio_ECPrivateKey(bio, NULL, NULL, NULL)); + ExpectNull(PEM_read_bio_ECPrivateKey(bio, NULL, NULL, NULL)); BIO_free(bio); + bio = NULL; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) */ return res; } @@ -36484,49 +36930,52 @@ static int test_wolfSSL_PEM_PUBKEY(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) + EXPECT_DECLS; BIO* bio = NULL; EVP_PKEY* pkey = NULL; /* test creating new EVP_PKEY with bad arg */ - AssertNull((pkey = PEM_read_bio_PUBKEY(NULL, NULL, NULL, NULL))); + ExpectNull((pkey = PEM_read_bio_PUBKEY(NULL, NULL, NULL, NULL))); /* test loading ECC key using BIO */ #if defined(HAVE_ECC) && !defined(NO_FILESYSTEM) { - XFILE file; + XFILE file = XBADFILE; const char* fname = "./certs/ecc-client-keyPub.pem"; size_t sz; - byte* buf; + byte* buf = NULL; - EVP_PKEY* pkey2; - EC_KEY* ec_key; + EVP_PKEY* pkey2 = NULL; + EC_KEY* ec_key = NULL; - file = XFOPEN(fname, "rb"); - AssertTrue((file != XBADFILE)); - AssertIntEQ(XFSEEK(file, 0, XSEEK_END), 0); - sz = XFTELL(file); - AssertIntEQ(XFSEEK(file, 0, XSEEK_SET), 0); - AssertNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); - if (buf) - AssertIntEQ(XFREAD(buf, 1, sz, file), sz); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(fname, "rb")) != XBADFILE); + ExpectIntEQ(XFSEEK(file, 0, XSEEK_END), 0); + ExpectIntGT(sz = XFTELL(file), 0); + ExpectIntEQ(XFSEEK(file, 0, XSEEK_SET), 0); + ExpectNotNull(buf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE)); + if (buf != NULL) { + ExpectIntEQ(XFREAD(buf, 1, sz, file), sz); + } + if (file != XBADFILE) { + XFCLOSE(file); + } /* Test using BIO new mem and loading PEM private key */ - AssertNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); - AssertNotNull((pkey = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL))); + ExpectNotNull(bio = BIO_new_mem_buf(buf, (int)sz)); + ExpectNotNull((pkey = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL))); XFREE(buf, NULL, DYNAMIC_TYPE_FILE); BIO_free(bio); bio = NULL; /* Qt unit test case*/ - AssertNotNull(pkey2 = EVP_PKEY_new()); - AssertNotNull(ec_key = EVP_PKEY_get1_EC_KEY(pkey)); - AssertIntEQ(EVP_PKEY_set1_EC_KEY(pkey2, ec_key), WOLFSSL_SUCCESS); - #ifdef WOLFSSL_ERROR_CODE_OPENSSL - AssertIntEQ(EVP_PKEY_cmp(pkey, pkey2), 1/* match */); - #else - AssertIntEQ(EVP_PKEY_cmp(pkey, pkey2), 0); - #endif + ExpectNotNull(pkey2 = EVP_PKEY_new()); + ExpectNotNull(ec_key = EVP_PKEY_get1_EC_KEY(pkey)); + ExpectIntEQ(EVP_PKEY_set1_EC_KEY(pkey2, ec_key), WOLFSSL_SUCCESS); + #ifdef WOLFSSL_ERROR_CODE_OPENSSL + ExpectIntEQ(EVP_PKEY_cmp(pkey, pkey2), 1/* match */); + #else + ExpectIntEQ(EVP_PKEY_cmp(pkey, pkey2), 0); + #endif EC_KEY_free(ec_key); EVP_PKEY_free(pkey2); @@ -36538,7 +36987,7 @@ static int test_wolfSSL_PEM_PUBKEY(void) (void)bio; (void)pkey; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -36551,49 +37000,52 @@ static int test_DSA_do_sign_verify(void) #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) #if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) && \ !defined(NO_DSA) + EXPECT_DECLS; unsigned char digest[WC_SHA_DIGEST_SIZE]; - DSA_SIG* sig; - DSA* dsa; + DSA_SIG* sig = NULL; + DSA* dsa = NULL; word32 bytes; byte sigBin[DSA_SIG_SIZE]; int dsacheck; #ifdef USE_CERT_BUFFERS_1024 byte tmp[ONEK_BUF]; + XMEMSET(tmp, 0, sizeof(tmp)); XMEMCPY(tmp, dsa_key_der_1024, sizeof_dsa_key_der_1024); bytes = sizeof_dsa_key_der_1024; #elif defined(USE_CERT_BUFFERS_2048) byte tmp[TWOK_BUF]; + XMEMSET(tmp, 0, sizeof(tmp)); XMEMCPY(tmp, dsa_key_der_2048, sizeof_dsa_key_der_2048); bytes = sizeof_dsa_key_der_2048; #else byte tmp[TWOK_BUF]; + XFILE fp = XBADFILE; + XMEMSET(tmp, 0, sizeof(tmp)); - XFILE fp = XFOPEN("./certs/dsa2048.der", "rb"); - if (fp == XBADFILE) { - return WOLFSSL_BAD_FILE; - } - bytes = (word32) XFREAD(tmp, 1, sizeof(tmp), fp); - XFCLOSE(fp); + ExpectTrue((fp = XFOPEN("./certs/dsa2048.der", "rb") != XBADFILE); + ExpectIntGT(bytes = (word32) XFREAD(tmp, 1, sizeof(tmp), fp), 0); + if (fp != XBADFILE) + XFCLOSE(fp); #endif /* END USE_CERT_BUFFERS_1024 */ XMEMSET(digest, 202, sizeof(digest)); - AssertNotNull(dsa = DSA_new()); - AssertIntEQ(DSA_LoadDer(dsa, tmp, bytes), 1); + ExpectNotNull(dsa = DSA_new()); + ExpectIntEQ(DSA_LoadDer(dsa, tmp, bytes), 1); - AssertIntEQ(wolfSSL_DSA_do_sign(digest, sigBin, dsa), 1); - AssertIntEQ(wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck), 1); + ExpectIntEQ(wolfSSL_DSA_do_sign(digest, sigBin, dsa), 1); + ExpectIntEQ(wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck), 1); - AssertNotNull(sig = DSA_do_sign(digest, WC_SHA_DIGEST_SIZE, dsa)); - AssertIntEQ(DSA_do_verify(digest, WC_SHA_DIGEST_SIZE, sig, dsa), 1); + ExpectNotNull(sig = DSA_do_sign(digest, WC_SHA_DIGEST_SIZE, dsa)); + ExpectIntEQ(DSA_do_verify(digest, WC_SHA_DIGEST_SIZE, sig, dsa), 1); DSA_SIG_free(sig); DSA_free(dsa); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif #endif /* !HAVE_SELFTEST && !HAVE_FIPS */ return res; @@ -36605,53 +37057,55 @@ static int test_wolfSSL_tmp_dh(void) #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) && \ !defined(NO_DSA) && !defined(NO_RSA) && !defined(NO_DH) && !defined(NO_BIO) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; byte buff[6000]; char file[] = "./certs/dsaparams.pem"; - XFILE f; - int bytes; - DSA* dsa; - DH* dh; + XFILE f = XBADFILE; + int bytes = 0; + DSA* dsa = NULL; + DH* dh = NULL; #if defined(WOLFSSL_DH_EXTRA) && \ (defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH)) - DH* dh2; + DH* dh2 = NULL; #endif - BIO* bio; - SSL* ssl; - SSL_CTX* ctx; + BIO* bio = NULL; + SSL* ssl = NULL; + SSL_CTX* ctx = NULL; - #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); - #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); - #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); +#ifndef NO_WOLFSSL_SERVER + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); +#else + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); +#endif + ExpectTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + WOLFSSL_FILETYPE_PEM)); + ExpectNotNull(ssl = SSL_new(ctx)); - f = XFOPEN(file, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(file, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) + XFCLOSE(f); - bio = BIO_new_mem_buf((void*)buff, bytes); - AssertNotNull(bio); + ExpectNotNull(bio = BIO_new_mem_buf((void*)buff, bytes)); dsa = wolfSSL_PEM_read_bio_DSAparams(bio, NULL, NULL, NULL); - AssertNotNull(dsa); + ExpectNotNull(dsa); dh = wolfSSL_DSA_dup_DH(dsa); - AssertNotNull(dh); + ExpectNotNull(dh); #if defined(WOLFSSL_DH_EXTRA) && \ (defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH)) - AssertNotNull(dh2 = wolfSSL_DH_dup(dh)); + ExpectNotNull(dh2 = wolfSSL_DH_dup(dh)); #endif - AssertIntEQ((int)SSL_CTX_set_tmp_dh(ctx, dh), WOLFSSL_SUCCESS); - #ifndef NO_WOLFSSL_SERVER - AssertIntEQ((int)SSL_set_tmp_dh(ssl, dh), WOLFSSL_SUCCESS); - #else - AssertIntEQ((int)SSL_set_tmp_dh(ssl, dh), SIDE_ERROR); - #endif + ExpectIntEQ((int)SSL_CTX_set_tmp_dh(ctx, dh), WOLFSSL_SUCCESS); +#ifndef NO_WOLFSSL_SERVER + ExpectIntEQ((int)SSL_set_tmp_dh(ssl, dh), WOLFSSL_SUCCESS); +#else + ExpectIntEQ((int)SSL_set_tmp_dh(ssl, dh), SIDE_ERROR); +#endif BIO_free(bio); DSA_free(dsa); @@ -36663,7 +37117,7 @@ static int test_wolfSSL_tmp_dh(void) SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif return res; @@ -36673,19 +37127,19 @@ static int test_wolfSSL_ctrl(void) { int res = TEST_SKIPPED; #if defined (OPENSSL_EXTRA) && !defined(NO_BIO) + EXPECT_DECLS; byte buff[6000]; - BIO* bio; + BIO* bio = NULL; int bytes; BUF_MEM* ptr = NULL; XMEMSET(buff, 0, sizeof(buff)); bytes = sizeof(buff); - bio = BIO_new_mem_buf((void*)buff, bytes); - AssertNotNull(bio); - AssertNotNull(BIO_s_socket()); + ExpectNotNull(bio = BIO_new_mem_buf((void*)buff, bytes)); + ExpectNotNull(BIO_s_socket()); - AssertIntEQ((int)wolfSSL_BIO_get_mem_ptr(bio, &ptr), WOLFSSL_SUCCESS); + ExpectIntEQ((int)wolfSSL_BIO_get_mem_ptr(bio, &ptr), WOLFSSL_SUCCESS); /* needs tested after stubs filled out @TODO SSL_ctrl @@ -36694,7 +37148,7 @@ static int test_wolfSSL_ctrl(void) BIO_free(bio); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_BIO) */ return res; } @@ -36704,48 +37158,53 @@ static int test_wolfSSL_EVP_PKEY_new_mac_key(void) { int res = TEST_SKIPPED; #ifdef OPENSSL_EXTRA + EXPECT_DECLS; static const unsigned char pw[] = "password"; static const int pwSz = sizeof(pw) - 1; size_t checkPwSz = 0; const unsigned char* checkPw = NULL; WOLFSSL_EVP_PKEY* key = NULL; - AssertNull(key = wolfSSL_EVP_PKEY_new_mac_key(0, NULL, pw, pwSz)); - AssertNull(key = wolfSSL_EVP_PKEY_new_mac_key(0, NULL, NULL, pwSz)); + ExpectNull(key = wolfSSL_EVP_PKEY_new_mac_key(0, NULL, pw, pwSz)); + ExpectNull(key = wolfSSL_EVP_PKEY_new_mac_key(0, NULL, NULL, pwSz)); - AssertNotNull(key = wolfSSL_EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, pw, pwSz)); - if (key) { - AssertIntEQ(key->type, EVP_PKEY_HMAC); - AssertIntEQ(key->save_type, EVP_PKEY_HMAC); - AssertIntEQ(key->pkey_sz, pwSz); - AssertIntEQ(XMEMCMP(key->pkey.ptr, pw, pwSz), 0); - } - AssertNotNull(checkPw = wolfSSL_EVP_PKEY_get0_hmac(key, &checkPwSz)); - AssertIntEQ((int)checkPwSz, pwSz); - if (checkPw) { - AssertIntEQ(XMEMCMP(checkPw, pw, pwSz), 0); + ExpectNotNull(key = wolfSSL_EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, pw, + pwSz)); + if (key != NULL) { + ExpectIntEQ(key->type, EVP_PKEY_HMAC); + ExpectIntEQ(key->save_type, EVP_PKEY_HMAC); + ExpectIntEQ(key->pkey_sz, pwSz); + ExpectIntEQ(XMEMCMP(key->pkey.ptr, pw, pwSz), 0); } + ExpectNotNull(checkPw = wolfSSL_EVP_PKEY_get0_hmac(key, &checkPwSz)); + ExpectIntEQ((int)checkPwSz, pwSz); + ExpectIntEQ(XMEMCMP(checkPw, pw, pwSz), 0); wolfSSL_EVP_PKEY_free(key); + key = NULL; - AssertNotNull(key = wolfSSL_EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, pw, 0)); - if (key) { - AssertIntEQ(key->pkey_sz, 0); + ExpectNotNull(key = wolfSSL_EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, pw, + 0)); + ExpectIntEQ(key->pkey_sz, 0); + if (EXPECT_SUCCESS()) { + /* Allocation for key->pkey.ptr may fail - OK key len is 0 */ + checkPw = wolfSSL_EVP_PKEY_get0_hmac(key, &checkPwSz); } - checkPw = wolfSSL_EVP_PKEY_get0_hmac(key, &checkPwSz); - (void)checkPw; - AssertIntEQ((int)checkPwSz, 0); + ExpectIntEQ((int)checkPwSz, 0); wolfSSL_EVP_PKEY_free(key); + key = NULL; - AssertNotNull(key = wolfSSL_EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, NULL, 0)); - if (key) { - AssertIntEQ(key->pkey_sz, 0); + ExpectNotNull(key = wolfSSL_EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, NULL, + 0)); + ExpectIntEQ(key->pkey_sz, 0); + if (EXPECT_SUCCESS()) { + /* Allocation for key->pkey.ptr may fail - OK key len is 0 */ + checkPw = wolfSSL_EVP_PKEY_get0_hmac(key, &checkPwSz); } - checkPw = wolfSSL_EVP_PKEY_get0_hmac(key, &checkPwSz); - (void)checkPw; - AssertIntEQ((int)checkPwSz, 0); + ExpectIntEQ((int)checkPwSz, 0); wolfSSL_EVP_PKEY_free(key); + key = NULL; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -36756,22 +37215,23 @@ static int test_wolfSSL_EVP_PKEY_new_CMAC_key(void) int res = TEST_SKIPPED; #ifdef OPENSSL_EXTRA #if defined(WOLFSSL_CMAC) && !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) + EXPECT_DECLS; const char *priv = "ABCDEFGHIJKLMNOP"; const WOLFSSL_EVP_CIPHER* cipher = EVP_aes_128_cbc(); WOLFSSL_EVP_PKEY* key = NULL; - AssertNull(key = wolfSSL_EVP_PKEY_new_CMAC_key( + ExpectNull(key = wolfSSL_EVP_PKEY_new_CMAC_key( NULL, NULL, AES_128_KEY_SIZE, cipher)); - AssertNull(key = wolfSSL_EVP_PKEY_new_CMAC_key( + ExpectNull(key = wolfSSL_EVP_PKEY_new_CMAC_key( NULL, (const unsigned char *)priv, 0, cipher)); - AssertNull(key = wolfSSL_EVP_PKEY_new_CMAC_key( + ExpectNull(key = wolfSSL_EVP_PKEY_new_CMAC_key( NULL, (const unsigned char *)priv, AES_128_KEY_SIZE, NULL)); - AssertNotNull(key = wolfSSL_EVP_PKEY_new_CMAC_key( + ExpectNotNull(key = wolfSSL_EVP_PKEY_new_CMAC_key( NULL, (const unsigned char *)priv, AES_128_KEY_SIZE, cipher)); wolfSSL_EVP_PKEY_free(key); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(WOLFSSL_CMAC) && !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) */ #endif /* OPENSSL_EXTRA */ return res; @@ -36781,8 +37241,7 @@ static int test_wolfSSL_EVP_Digest(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_SHA256) && !defined(NO_PWDBASED) - - + EXPECT_DECLS; const char* in = "abc"; int inLen = (int)XSTRLEN(in); byte out[WC_SHA256_DIGEST_SIZE]; @@ -36791,11 +37250,11 @@ static int test_wolfSSL_EVP_Digest(void) "\x23\xB0\x03\x61\xA3\x96\x17\x7A\x9C\xB4\x10\xFF\x61\xF2\x00" "\x15\xAD"; - AssertIntEQ(wolfSSL_EVP_Digest((unsigned char*)in, inLen, out, &outLen, "SHA256", NULL), 1); - AssertIntEQ(outLen, WC_SHA256_DIGEST_SIZE); - AssertIntEQ(XMEMCMP(out, expOut, WC_SHA256_DIGEST_SIZE), 0); + ExpectIntEQ(wolfSSL_EVP_Digest((unsigned char*)in, inLen, out, &outLen, "SHA256", NULL), 1); + ExpectIntEQ(outLen, WC_SHA256_DIGEST_SIZE); + ExpectIntEQ(XMEMCMP(out, expOut, WC_SHA256_DIGEST_SIZE), 0); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPEN_EXTRA && ! NO_SHA256 */ return res; } @@ -36804,6 +37263,7 @@ static int test_wolfSSL_EVP_Digest_all(void) { int res = TEST_SKIPPED; #ifdef OPENSSL_EXTRA + EXPECT_DECLS; const char* digests[] = { #ifndef NO_MD5 "MD5", @@ -36850,12 +37310,12 @@ static int test_wolfSSL_EVP_Digest_all(void) unsigned int outLen; for (d = digests; *d != NULL; d++) { - AssertIntEQ(EVP_Digest(in, inLen, out, &outLen, *d, NULL), 1); - AssertIntGT(outLen, 0); - AssertIntEQ(EVP_MD_size(*d), outLen); + ExpectIntEQ(EVP_Digest(in, inLen, out, &outLen, *d, NULL), 1); + ExpectIntGT(outLen, 0); + ExpectIntEQ(EVP_MD_size(*d), outLen); } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -36864,131 +37324,146 @@ static int test_wolfSSL_EVP_MD_size(void) { int res = TEST_SKIPPED; #ifdef OPENSSL_EXTRA - + EXPECT_DECLS; WOLFSSL_EVP_MD_CTX mdCtx; #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA3_224"), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA3_224_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA3_224_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA3_224"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA3_224_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA3_224_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif #ifndef WOLFSSL_NOSHA3_256 wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA3_256"), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA3_256_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA3_256_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA3_256"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA3_256_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA3_256_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA3_384"), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA3_384_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA3_384_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA3_384"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA3_384_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA3_384_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #ifndef WOLFSSL_NOSHA3_512 wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA3_512"), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA3_512_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA3_512_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA3_512"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA3_512_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA3_512_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif #endif /* WOLFSSL_SHA3 */ #ifndef NO_SHA256 wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA256"), 1); - AssertIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA256_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA256_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA256_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA256_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA256"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA256_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA256_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA256_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA256_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif #ifndef NO_MD5 wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "MD5"), 1); - AssertIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_MD5_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_MD5_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_MD5_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_MD5_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "MD5"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_MD5_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_MD5_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_MD5_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_MD5_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif #ifdef WOLFSSL_SHA224 wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA224"), 1); - AssertIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA224_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA224_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA224_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA224_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA224"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA224_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA224_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA224_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA224_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif #ifdef WOLFSSL_SHA384 wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA384"), 1); - AssertIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA384_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA384_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA384_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA384_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA384"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA384_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA384_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA384_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA384_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif #ifdef WOLFSSL_SHA512 wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA512"), 1); - AssertIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA512_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA512_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA512_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA512_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA512"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA512_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA512_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA512_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA512_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif #ifndef NO_SHA wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA"), 1); - AssertIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA1"), 1); - AssertIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), WC_SHA_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA_DIGEST_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA_BLOCK_SIZE); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, "SHA1"), 1); + ExpectIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_block_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + WC_SHA_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_size(&mdCtx), WC_SHA_DIGEST_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), WC_SHA_BLOCK_SIZE); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); #endif /* error case */ wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, ""), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), BAD_FUNC_ARG); - AssertIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_EVP_DigestInit(&mdCtx, ""), BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_EVP_MD_size(wolfSSL_EVP_MD_CTX_md(&mdCtx)), + BAD_FUNC_ARG); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_block_size(&mdCtx), BAD_FUNC_ARG); /* Cleanup is valid on uninit'ed struct */ - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -36997,88 +37472,92 @@ static int test_wolfSSL_EVP_MD_pkey_type(void) { int res = TEST_SKIPPED; #ifdef OPENSSL_EXTRA + EXPECT_DECLS; const WOLFSSL_EVP_MD* md; #ifndef NO_MD5 - AssertNotNull(md = EVP_md5()); - AssertIntEQ(EVP_MD_pkey_type(md), NID_md5WithRSAEncryption); + ExpectNotNull(md = EVP_md5()); + ExpectIntEQ(EVP_MD_pkey_type(md), NID_md5WithRSAEncryption); #endif #ifndef NO_SHA - AssertNotNull(md = EVP_sha1()); - AssertIntEQ(EVP_MD_pkey_type(md), NID_sha1WithRSAEncryption); + ExpectNotNull(md = EVP_sha1()); + ExpectIntEQ(EVP_MD_pkey_type(md), NID_sha1WithRSAEncryption); #endif #ifdef WOLFSSL_SHA224 - AssertNotNull(md = EVP_sha224()); - AssertIntEQ(EVP_MD_pkey_type(md), NID_sha224WithRSAEncryption); + ExpectNotNull(md = EVP_sha224()); + ExpectIntEQ(EVP_MD_pkey_type(md), NID_sha224WithRSAEncryption); #endif - AssertNotNull(md = EVP_sha256()); - AssertIntEQ(EVP_MD_pkey_type(md), NID_sha256WithRSAEncryption); + ExpectNotNull(md = EVP_sha256()); + ExpectIntEQ(EVP_MD_pkey_type(md), NID_sha256WithRSAEncryption); #ifdef WOLFSSL_SHA384 - AssertNotNull(md = EVP_sha384()); - AssertIntEQ(EVP_MD_pkey_type(md), NID_sha384WithRSAEncryption); + ExpectNotNull(md = EVP_sha384()); + ExpectIntEQ(EVP_MD_pkey_type(md), NID_sha384WithRSAEncryption); #endif #ifdef WOLFSSL_SHA512 - AssertNotNull(md = EVP_sha512()); - AssertIntEQ(EVP_MD_pkey_type(md), NID_sha512WithRSAEncryption); + ExpectNotNull(md = EVP_sha512()); + ExpectIntEQ(EVP_MD_pkey_type(md), NID_sha512WithRSAEncryption); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } #ifdef OPENSSL_EXTRA -static void test_hmac_signing(const WOLFSSL_EVP_MD *type, const byte* testKey, +static int test_hmac_signing(const WOLFSSL_EVP_MD *type, const byte* testKey, size_t testKeySz, const char* testData, size_t testDataSz, const byte* testResult, size_t testResultSz) { + EXPECT_DECLS; unsigned char check[WC_MAX_DIGEST_SIZE]; size_t checkSz = -1; - WOLFSSL_EVP_PKEY* key; + WOLFSSL_EVP_PKEY* key = NULL; WOLFSSL_EVP_MD_CTX mdCtx; - AssertNotNull(key = wolfSSL_EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, + ExpectNotNull(key = wolfSSL_EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, testKey, (int)testKeySz)); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, type, NULL, key), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, + ExpectIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, type, NULL, key), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, (unsigned int)testDataSz), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); - AssertIntEQ((int)checkSz, (int)testResultSz); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ((int)checkSz,(int)testResultSz); - AssertIntEQ(XMEMCMP(testResult, check, testResultSz), 0); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); - - AssertIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, type, NULL, key), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); + ExpectIntEQ((int)checkSz, (int)testResultSz); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ExpectIntEQ((int)checkSz,(int)testResultSz); + ExpectIntEQ(XMEMCMP(testResult, check, testResultSz), 0); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + + ExpectIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, type, NULL, key), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, (unsigned int)testDataSz), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, testResult, checkSz), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, testResult, checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, type, NULL, key), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); - AssertIntEQ((int)checkSz, (int)testResultSz); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ((int)checkSz,(int)testResultSz); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData + 4, + ExpectIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, type, NULL, key), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, 4), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); + ExpectIntEQ((int)checkSz, (int)testResultSz); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ExpectIntEQ((int)checkSz,(int)testResultSz); + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData + 4, (unsigned int)testDataSz - 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ((int)checkSz,(int)testResultSz); - AssertIntEQ(XMEMCMP(testResult, check, testResultSz), 0); - - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, type, NULL, key), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData + 4, + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ExpectIntEQ((int)checkSz,(int)testResultSz); + ExpectIntEQ(XMEMCMP(testResult, check, testResultSz), 0); + + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, type, NULL, key), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, 4), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData + 4, (unsigned int)testDataSz - 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, testResult, checkSz), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, testResult, checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); wolfSSL_EVP_PKEY_free(key); + + return EXPECT_RESULT(); } #endif @@ -37086,6 +37565,7 @@ static int test_wolfSSL_EVP_MD_hmac_signing(void) { int res = TEST_SKIPPED; #ifdef OPENSSL_EXTRA + EXPECT_DECLS; static const unsigned char testKey[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, @@ -37181,45 +37661,49 @@ static int test_wolfSSL_EVP_MD_hmac_signing(void) #endif #ifndef NO_SHA256 - test_hmac_signing(wolfSSL_EVP_sha256(), testKey, sizeof(testKey), testData, - XSTRLEN(testData), testResultSha256, sizeof(testResultSha256)); + ExpectIntEQ(test_hmac_signing(wolfSSL_EVP_sha256(), testKey, + sizeof(testKey), testData, XSTRLEN(testData), testResultSha256, + sizeof(testResultSha256)), TEST_SUCCESS); #endif #ifdef WOLFSSL_SHA224 - test_hmac_signing(wolfSSL_EVP_sha224(), testKey, sizeof(testKey), testData, - XSTRLEN(testData), testResultSha224, sizeof(testResultSha224)); + ExpectIntEQ(test_hmac_signing(wolfSSL_EVP_sha224(), testKey, + sizeof(testKey), testData, XSTRLEN(testData), testResultSha224, + sizeof(testResultSha224)), TEST_SUCCESS); #endif #ifdef WOLFSSL_SHA384 - test_hmac_signing(wolfSSL_EVP_sha384(), testKey, sizeof(testKey), testData, - XSTRLEN(testData), testResultSha384, sizeof(testResultSha384)); + ExpectIntEQ(test_hmac_signing(wolfSSL_EVP_sha384(), testKey, + sizeof(testKey), testData, XSTRLEN(testData), testResultSha384, + sizeof(testResultSha384)), TEST_SUCCESS); #endif #ifdef WOLFSSL_SHA512 - test_hmac_signing(wolfSSL_EVP_sha512(), testKey, sizeof(testKey), testData, - XSTRLEN(testData), testResultSha512, sizeof(testResultSha512)); + ExpectIntEQ(test_hmac_signing(wolfSSL_EVP_sha512(), testKey, + sizeof(testKey), testData, XSTRLEN(testData), testResultSha512, + sizeof(testResultSha512)), TEST_SUCCESS); #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - test_hmac_signing(wolfSSL_EVP_sha3_224(), testKey, sizeof(testKey), - testData, XSTRLEN(testData), testResultSha3_224, - sizeof(testResultSha3_224)); + ExpectIntEQ(test_hmac_signing(wolfSSL_EVP_sha3_224(), testKey, + sizeof(testKey), testData, XSTRLEN(testData), testResultSha3_224, + sizeof(testResultSha3_224)), TEST_SUCCESS); #endif #ifndef WOLFSSL_NOSHA3_256 - test_hmac_signing(wolfSSL_EVP_sha3_256(), testKey, sizeof(testKey), - testData, XSTRLEN(testData), testResultSha3_256, - sizeof(testResultSha3_256)); + ExpectIntEQ(test_hmac_signing(wolfSSL_EVP_sha3_256(), testKey, + sizeof(testKey), testData, XSTRLEN(testData), testResultSha3_256, + sizeof(testResultSha3_256)), TEST_SUCCESS); #endif #ifndef WOLFSSL_NOSHA3_384 - test_hmac_signing(wolfSSL_EVP_sha3_384(), testKey, sizeof(testKey), - testData, XSTRLEN(testData), testResultSha3_384, - sizeof(testResultSha3_384)); + ExpectIntEQ(test_hmac_signing(wolfSSL_EVP_sha3_384(), testKey, + sizeof(testKey), testData, XSTRLEN(testData), testResultSha3_384, + sizeof(testResultSha3_384)), TEST_SUCCESS); #endif #ifndef WOLFSSL_NOSHA3_512 - test_hmac_signing(wolfSSL_EVP_sha3_512(), testKey, sizeof(testKey), - testData, XSTRLEN(testData), testResultSha3_512, - sizeof(testResultSha3_512)); + ExpectIntEQ(test_hmac_signing(wolfSSL_EVP_sha3_512(), testKey, + sizeof(testKey), testData, XSTRLEN(testData), testResultSha3_512, + sizeof(testResultSha3_512)), TEST_SUCCESS); #endif #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -37230,12 +37714,14 @@ static int test_wolfSSL_EVP_MD_rsa_signing(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \ defined(USE_CERT_BUFFERS_2048) - WOLFSSL_EVP_PKEY* privKey; - WOLFSSL_EVP_PKEY* pubKey; - WOLFSSL_EVP_PKEY_CTX* keyCtx; + EXPECT_DECLS; + WOLFSSL_EVP_PKEY* privKey = NULL; + WOLFSSL_EVP_PKEY* pubKey = NULL; + WOLFSSL_EVP_PKEY_CTX* keyCtx = NULL; const char testData[] = "Hi There"; WOLFSSL_EVP_MD_CTX mdCtx; WOLFSSL_EVP_MD_CTX mdCtxCopy; + int ret; size_t checkSz = -1; int sz = 2048 / 8; const unsigned char* cp; @@ -37251,90 +37737,97 @@ static int test_wolfSSL_EVP_MD_rsa_signing(void) cp = client_key_der_2048; - AssertNotNull((privKey = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, &cp, + ExpectNotNull((privKey = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, &cp, sizeof_client_key_der_2048))); p = client_keypub_der_2048; - AssertNotNull((pubKey = wolfSSL_d2i_PUBKEY(NULL, &p, + ExpectNotNull((pubKey = wolfSSL_d2i_PUBKEY(NULL, &p, sizeof_client_keypub_der_2048))); wolfSSL_EVP_MD_CTX_init(&mdCtx); wolfSSL_EVP_MD_CTX_init(&mdCtxCopy); - AssertIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), + ExpectIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), NULL, privKey), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, (unsigned int)XSTRLEN(testData)), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); - AssertIntEQ((int)checkSz, sz); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ((int)checkSz,sz); - AssertIntEQ(wolfSSL_EVP_MD_CTX_copy_ex(&mdCtxCopy, &mdCtx), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_copy_ex(&mdCtxCopy, &mdCtx), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtxCopy), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); + ExpectIntEQ((int)checkSz, sz); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ExpectIntEQ((int)checkSz,sz); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_copy_ex(&mdCtxCopy, &mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_MD_CTX_copy_ex(&mdCtxCopy, &mdCtx), 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtxCopy); + ExpectIntEQ(ret, 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), + ExpectIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), NULL, pubKey), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, (unsigned int)XSTRLEN(testData)), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), + ExpectIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), NULL, privKey), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); - AssertIntEQ((int)checkSz, sz); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ((int)checkSz, sz); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData + 4, + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, 4), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); + ExpectIntEQ((int)checkSz, sz); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ExpectIntEQ((int)checkSz, sz); + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData + 4, (unsigned int)XSTRLEN(testData) - 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ((int)checkSz, sz); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ExpectIntEQ((int)checkSz, sz); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), + ExpectIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), NULL, pubKey), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData + 4, + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, 4), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData + 4, (unsigned int)XSTRLEN(testData) - 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); /* Check all signing padding types */ for (i = 0; i < sizeof(paddings)/sizeof(int); i++) { wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, &keyCtx, + ExpectIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, &keyCtx, wolfSSL_EVP_sha256(), NULL, privKey), 1); - AssertIntEQ(wolfSSL_EVP_PKEY_CTX_set_rsa_padding(keyCtx, + ExpectIntEQ(wolfSSL_EVP_PKEY_CTX_set_rsa_padding(keyCtx, paddings[i]), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, (unsigned int)XSTRLEN(testData)), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); - AssertIntEQ((int)checkSz, sz); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ((int)checkSz,sz); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); + ExpectIntEQ((int)checkSz, sz); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ExpectIntEQ((int)checkSz,sz); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, &keyCtx, + ExpectIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, &keyCtx, wolfSSL_EVP_sha256(), NULL, pubKey), 1); - AssertIntEQ(wolfSSL_EVP_PKEY_CTX_set_rsa_padding(keyCtx, + ExpectIntEQ(wolfSSL_EVP_PKEY_CTX_set_rsa_padding(keyCtx, paddings[i]), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, (unsigned int)XSTRLEN(testData)), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); } wolfSSL_EVP_PKEY_free(pubKey); wolfSSL_EVP_PKEY_free(privKey); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -37344,66 +37837,71 @@ static int test_wolfSSL_EVP_MD_ecc_signing(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) && defined(USE_CERT_BUFFERS_256) - WOLFSSL_EVP_PKEY* privKey; - WOLFSSL_EVP_PKEY* pubKey; + EXPECT_DECLS; + WOLFSSL_EVP_PKEY* privKey = NULL; + WOLFSSL_EVP_PKEY* pubKey = NULL; const char testData[] = "Hi There"; WOLFSSL_EVP_MD_CTX mdCtx; + int ret; size_t checkSz = -1; const unsigned char* cp; const unsigned char* p; unsigned char check[2048/8]; cp = ecc_clikey_der_256; - privKey = wolfSSL_d2i_PrivateKey(EVP_PKEY_EC, NULL, &cp, - sizeof_ecc_clikey_der_256); - AssertNotNull(privKey); + ExpectNotNull(privKey = wolfSSL_d2i_PrivateKey(EVP_PKEY_EC, NULL, &cp, + sizeof_ecc_clikey_der_256)); p = ecc_clikeypub_der_256; - AssertNotNull((pubKey = wolfSSL_d2i_PUBKEY(NULL, &p, + ExpectNotNull((pubKey = wolfSSL_d2i_PUBKEY(NULL, &p, sizeof_ecc_clikeypub_der_256))); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), + ExpectIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), NULL, privKey), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, (unsigned int)XSTRLEN(testData)), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), + ExpectIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), NULL, pubKey), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, (unsigned int)XSTRLEN(testData)), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), + ExpectIntEQ(wolfSSL_EVP_DigestSignInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), NULL, privKey), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData + 4, + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData, 4), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, NULL, &checkSz), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignUpdate(&mdCtx, testData + 4, (unsigned int)XSTRLEN(testData) - 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestSignFinal(&mdCtx, check, &checkSz), 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); wolfSSL_EVP_MD_CTX_init(&mdCtx); - AssertIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), + ExpectIntEQ(wolfSSL_EVP_DigestVerifyInit(&mdCtx, NULL, wolfSSL_EVP_sha256(), NULL, pubKey), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData + 4, + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData, 4), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyUpdate(&mdCtx, testData + 4, (unsigned int)XSTRLEN(testData) - 4), 1); - AssertIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); - AssertIntEQ(wolfSSL_EVP_MD_CTX_cleanup(&mdCtx), 1); + ExpectIntEQ(wolfSSL_EVP_DigestVerifyFinal(&mdCtx, check, checkSz), 1); + ret = wolfSSL_EVP_MD_CTX_cleanup(&mdCtx); + ExpectIntEQ(ret, 1); wolfSSL_EVP_PKEY_free(pubKey); wolfSSL_EVP_PKEY_free(privKey); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -37415,97 +37913,113 @@ static int test_wolfSSL_CTX_add_extra_chain_cert(void) #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && !defined(NO_BIO) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; char caFile[] = "./certs/client-ca.pem"; char clientFile[] = "./certs/client-cert.pem"; - SSL_CTX* ctx; - X509* x509; + SSL_CTX* ctx = NULL; + X509* x509 = NULL; BIO *bio = NULL; X509 *cert = NULL; - X509 *ca; + X509 *ca = NULL; STACK_OF(X509) *chain = NULL; STACK_OF(X509) *chain2 = NULL; - #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); - #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); - #endif +#ifndef NO_WOLFSSL_SERVER + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); +#else + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); +#endif - x509 = wolfSSL_X509_load_certificate_file(caFile, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); - AssertIntEQ((int)SSL_CTX_add_extra_chain_cert(ctx, x509), WOLFSSL_SUCCESS); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(caFile, + WOLFSSL_FILETYPE_PEM)); + ExpectIntEQ((int)SSL_CTX_add_extra_chain_cert(ctx, x509), WOLFSSL_SUCCESS); - x509 = wolfSSL_X509_load_certificate_file(clientFile, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(clientFile, + WOLFSSL_FILETYPE_PEM)); - #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA) +#if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA) /* additional test of getting EVP_PKEY key size from X509 * Do not run with user RSA because wolfSSL_RSA_size is not currently * allowed with user RSA */ { - EVP_PKEY* pkey; - #if defined(HAVE_ECC) - X509* ecX509; - #endif /* HAVE_ECC */ + EVP_PKEY* pkey = NULL; + #if defined(HAVE_ECC) + X509* ecX509 = NULL; + #endif /* HAVE_ECC */ - AssertNotNull(pkey = X509_get_pubkey(x509)); + ExpectNotNull(pkey = X509_get_pubkey(x509)); /* current RSA key is 2048 bit (256 bytes) */ - AssertIntEQ(EVP_PKEY_size(pkey), 256); + ExpectIntEQ(EVP_PKEY_size(pkey), 256); EVP_PKEY_free(pkey); + pkey = NULL; - #if defined(HAVE_ECC) - #if defined(USE_CERT_BUFFERS_256) - AssertNotNull(ecX509 = wolfSSL_X509_load_certificate_buffer( +#if defined(HAVE_ECC) + #if defined(USE_CERT_BUFFERS_256) + ExpectNotNull(ecX509 = wolfSSL_X509_load_certificate_buffer( cliecc_cert_der_256, sizeof_cliecc_cert_der_256, SSL_FILETYPE_ASN1)); - #else - AssertNotNull(ecX509 = wolfSSL_X509_load_certificate_file(cliEccCertFile, - SSL_FILETYPE_PEM)); - #endif + #else + ExpectNotNull(ecX509 = wolfSSL_X509_load_certificate_file( + cliEccCertFile, SSL_FILETYPE_PEM)); + #endif pkey = X509_get_pubkey(ecX509); - AssertNotNull(pkey); + ExpectNotNull(pkey); /* current ECC key is 256 bit (32 bytes) */ - AssertIntEQ(EVP_PKEY_size(pkey), 32); + ExpectIntEQ(EVP_PKEY_size(pkey), 32); X509_free(ecX509); + ecX509 = NULL; EVP_PKEY_free(pkey); - #endif /* HAVE_ECC */ + pkey = NULL; +#endif /* HAVE_ECC */ } #endif /* !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA) */ - AssertIntEQ((int)SSL_CTX_add_extra_chain_cert(ctx, x509), SSL_SUCCESS); + ExpectIntEQ((int)SSL_CTX_add_extra_chain_cert(ctx, x509), SSL_SUCCESS); + if (EXPECT_SUCCESS()) { + x509 = NULL; + } #ifdef WOLFSSL_ENCRYPTED_KEYS - AssertNull(SSL_CTX_get_default_passwd_cb(ctx)); - AssertNull(SSL_CTX_get_default_passwd_cb_userdata(ctx)); + ExpectNull(SSL_CTX_get_default_passwd_cb(ctx)); + ExpectNull(SSL_CTX_get_default_passwd_cb_userdata(ctx)); #endif SSL_CTX_free(ctx); + ctx = NULL; #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif /* Test haproxy use case */ - AssertNotNull(bio = BIO_new_file(svrCertFile, "r")); + ExpectNotNull(bio = BIO_new_file(svrCertFile, "r")); /* Read Certificate */ - AssertNotNull(cert = PEM_read_bio_X509_AUX(bio, NULL, NULL, NULL)); - AssertNotNull(ca = PEM_read_bio_X509(bio, NULL, NULL, NULL)); - AssertNotNull(chain = sk_X509_new_null()); - AssertIntEQ(sk_X509_push(chain, ca), 1); - AssertNotNull(chain2 = X509_chain_up_ref(chain)); - AssertNotNull(ca = sk_X509_shift(chain2)); - AssertIntEQ(SSL_CTX_use_certificate(ctx, cert), 1); - AssertIntEQ(SSL_CTX_add_extra_chain_cert(ctx, ca), 1); + ExpectNotNull(cert = PEM_read_bio_X509_AUX(bio, NULL, NULL, NULL)); + ExpectNotNull(ca = PEM_read_bio_X509(bio, NULL, NULL, NULL)); + ExpectNotNull(chain = sk_X509_new_null()); + ExpectIntEQ(sk_X509_push(chain, ca), 1); + if (EXPECT_SUCCESS()) { + ca = NULL; + } + ExpectNotNull(chain2 = X509_chain_up_ref(chain)); + ExpectNotNull(ca = sk_X509_shift(chain2)); + ExpectIntEQ(SSL_CTX_use_certificate(ctx, cert), 1); + ExpectIntEQ(SSL_CTX_add_extra_chain_cert(ctx, ca), 1); + if (EXPECT_SUCCESS()) { + ca = NULL; + } BIO_free(bio); X509_free(cert); + X509_free(ca); + X509_free(x509); sk_X509_pop_free(chain, X509_free); sk_X509_pop_free(chain2, X509_free); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && !defined (NO_BIO) */ @@ -37517,16 +38031,11 @@ static int test_wolfSSL_CTX_add_extra_chain_cert(void) static int test_wolfSSL_ERR_peek_last_error_line(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && defined(DEBUG_WOLFSSL) && \ - !defined(NO_OLD_TLS) && !defined(WOLFSSL_NO_TLS12) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(NO_ERROR_QUEUE) - tcp_ready ready; - func_args client_args; - func_args server_args; -#ifndef SINGLE_THREADED - THREAD_TYPE serverThread; -#endif +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ + !defined(NO_FILESYSTEM) && defined(DEBUG_WOLFSSL) && \ + !defined(NO_OLD_TLS) && !defined(WOLFSSL_NO_TLS12) && \ + defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(NO_ERROR_QUEUE) + EXPECT_DECLS; callback_functions client_cb; callback_functions server_cb; int line = 0; @@ -37535,88 +38044,49 @@ static int test_wolfSSL_ERR_peek_last_error_line(void) const char* data = NULL; /* create a failed connection and inspect the error */ -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - - StartTCP(); - InitTcpReady(&ready); - XMEMSET(&client_cb, 0, sizeof(callback_functions)); XMEMSET(&server_cb, 0, sizeof(callback_functions)); client_cb.method = wolfTLSv1_1_client_method; server_cb.method = wolfTLSv1_2_server_method; - server_args.signal = &ready; - server_args.callbacks = &server_cb; - client_args.signal = &ready; - client_args.callbacks = &client_cb; - -#ifndef SINGLE_THREADED - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); -#endif - - FreeTcpReady(&ready); + test_wolfSSL_client_server_nofail(&client_cb, &server_cb); - AssertIntGT(ERR_get_error_line_data(NULL, NULL, &data, &flag), 0); - AssertNotNull(data); + ExpectIntGT(ERR_get_error_line_data(NULL, NULL, &data, &flag), 0); + ExpectNotNull(data); /* check clearing error state */ ERR_remove_state(0); - AssertIntEQ((int)ERR_peek_last_error_line(NULL, NULL), 0); + ExpectIntEQ((int)ERR_peek_last_error_line(NULL, NULL), 0); ERR_peek_last_error_line(NULL, &line); - AssertIntEQ(line, 0); + ExpectIntEQ(line, 0); ERR_peek_last_error_line(&file, NULL); - AssertNull(file); + ExpectNull(file); /* retry connection to fill error queue */ - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - - StartTCP(); - InitTcpReady(&ready); - + XMEMSET(&client_cb, 0, sizeof(callback_functions)); + XMEMSET(&server_cb, 0, sizeof(callback_functions)); client_cb.method = wolfTLSv1_1_client_method; server_cb.method = wolfTLSv1_2_server_method; - server_args.signal = &ready; - server_args.callbacks = &server_cb; - client_args.signal = &ready; - client_args.callbacks = &client_cb; - - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); - - FreeTcpReady(&ready); + test_wolfSSL_client_server_nofail(&client_cb, &server_cb); /* check that error code was stored */ - AssertIntNE((int)ERR_peek_last_error_line(NULL, NULL), 0); + ExpectIntNE((int)ERR_peek_last_error_line(NULL, NULL), 0); ERR_peek_last_error_line(NULL, &line); - AssertIntNE(line, 0); + ExpectIntNE(line, 0); ERR_peek_last_error_line(&file, NULL); - AssertNotNull(file); - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif + ExpectNotNull(file); fprintf(stderr, "\nTesting error print out\n"); ERR_print_errors_fp(stderr); fprintf(stderr, "Done testing print out\n\n"); - res = TEST_RES_CHECK(1); - #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && !defined(DEBUG_WOLFSSL) */ + res = EXPECT_RESULT(); +#endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && + * !defined(NO_FILESYSTEM) && !defined(DEBUG_WOLFSSL) */ return res; } -#endif +#endif /* !NO_WOLFSSL_CLIENT && !NO_WOLFSSL_SERVER */ #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) @@ -37963,10 +38433,11 @@ static int test_wolfSSL_PKCS7_certs(void) int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_CERTS) && !defined(NO_BIO) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && defined(HAVE_PKCS7) + EXPECT_DECLS; STACK_OF(X509)* sk = NULL; STACK_OF(X509_INFO)* info_sk = NULL; PKCS7 *p7 = NULL; - BIO* bio; + BIO* bio = NULL; const byte* p = NULL; int buflen = 0; int i; @@ -37974,45 +38445,61 @@ static int test_wolfSSL_PKCS7_certs(void) /* Test twice. Once with d2i and once without to test * that everything is free'd correctly. */ for (i = 0; i < 2; i++) { - AssertNotNull(p7 = PKCS7_new()); - p7->version = 1; -#ifdef NO_SHA - p7->hashOID = SHA256h; -#else - p7->hashOID = SHAh; -#endif - AssertNotNull(bio = BIO_new(BIO_s_file())); - AssertIntGT(BIO_read_filename(bio, svrCertFile), 0); - AssertNotNull(info_sk = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL)); - AssertIntEQ(sk_X509_INFO_num(info_sk), 2); - AssertNotNull(sk = sk_X509_new_null()); - while (sk_X509_INFO_num(info_sk)) { - X509_INFO* info; - AssertNotNull(info = sk_X509_INFO_shift(info_sk)); - AssertIntEQ(sk_X509_push(sk, info->x509), 1); - info->x509 = NULL; + ExpectNotNull(p7 = PKCS7_new()); + if (p7 != NULL) { + p7->version = 1; + #ifdef NO_SHA + p7->hashOID = SHA256h; + #else + p7->hashOID = SHAh; + #endif + } + ExpectNotNull(bio = BIO_new(BIO_s_file())); + ExpectIntGT(BIO_read_filename(bio, svrCertFile), 0); + ExpectNotNull(info_sk = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL)); + ExpectIntEQ(sk_X509_INFO_num(info_sk), 2); + ExpectNotNull(sk = sk_X509_new_null()); + while (EXPECT_SUCCESS() && (sk_X509_INFO_num(info_sk) > 0)) { + X509_INFO* info = NULL; + ExpectNotNull(info = sk_X509_INFO_shift(info_sk)); + ExpectIntEQ(sk_X509_push(sk, info->x509), 1); + if (EXPECT_SUCCESS() && (info != NULL)) { + info->x509 = NULL; + } X509_INFO_free(info); } - sk_X509_INFO_free(info_sk); + sk_X509_INFO_pop_free(info_sk, X509_INFO_free); + info_sk = NULL; BIO_free(bio); - bio = BIO_new(BIO_s_mem()); - AssertIntEQ(wolfSSL_PKCS7_encode_certs(p7, sk, bio), 1); - AssertIntGT((buflen = BIO_get_mem_data(bio, &p)), 0); + bio = NULL; + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(wolfSSL_PKCS7_encode_certs(p7, sk, bio), 1); + if ((sk != NULL) && ((p7 == NULL) || (bio == NULL))) { + sk_X509_pop_free(sk, X509_free); + } + sk = NULL; + ExpectIntGT((buflen = BIO_get_mem_data(bio, &p)), 0); if (i == 0) { PKCS7_free(p7); - AssertNotNull(d2i_PKCS7(&p7, &p, buflen)); - /* Reset certs to force wolfSSL_PKCS7_to_stack to regenerate them */ - ((WOLFSSL_PKCS7*)p7)->certs = NULL; + p7 = NULL; + ExpectNotNull(d2i_PKCS7(&p7, &p, buflen)); + if (p7 != NULL) { + /* Reset certs to force wolfSSL_PKCS7_to_stack to regenerate + * them */ + ((WOLFSSL_PKCS7*)p7)->certs = NULL; + } /* PKCS7_free free's the certs */ - AssertNotNull(wolfSSL_PKCS7_to_stack(p7)); + ExpectNotNull(wolfSSL_PKCS7_to_stack(p7)); } BIO_free(bio); + bio = NULL; PKCS7_free(p7); + p7 = NULL; } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && defined(HAVE_PKCS7) */ return res; @@ -39285,26 +39772,8 @@ static int test_wolfSSL_Tls13_postauth(void) #if defined(HAVE_IO_TESTS_DEPENDENCIES) && \ defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) - tcp_ready ready; - func_args client_args; - func_args server_args; callback_functions server_cbf; callback_functions client_cbf; - THREAD_TYPE serverThread; - - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif - - server_args.signal = &ready; - client_args.signal = &ready; /* test version failure doing post auth with TLS 1.2 connection */ XMEMSET(&server_cbf, 0, sizeof(callback_functions)); @@ -39314,13 +39783,8 @@ static int test_wolfSSL_Tls13_postauth(void) server_cbf.on_result = post_auth_version_cb; client_cbf.ssl_ready = set_post_auth_cb; client_cbf.on_result = post_auth_version_client_cb; - server_args.callbacks = &server_cbf; - client_args.callbacks = &client_cbf; - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); + test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); /* tests on post auth with TLS 1.3 */ XMEMSET(&server_cbf, 0, sizeof(callback_functions)); @@ -39330,15 +39794,8 @@ static int test_wolfSSL_Tls13_postauth(void) client_cbf.ssl_ready = set_post_auth_cb; server_cbf.on_result = post_auth_cb; client_cbf.on_result = NULL; - server_args.callbacks = &server_cbf; - client_args.callbacks = &client_cbf; - - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); - FreeTcpReady(&ready); + test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); res = TEST_RES_CHECK(1); #endif @@ -40774,85 +41231,61 @@ static void msg_cb(int write_p, int version, int content_type, } #endif -#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && defined(DEBUG_WOLFSSL) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(NO_WOLFSSL_CLIENT) && \ - !defined(NO_WOLFSSL_SERVER) -#ifndef SINGLE_THREADED +#if defined(OPENSSL_EXTRA) && defined(DEBUG_WOLFSSL) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) #if defined(SESSION_CERTS) #include "wolfssl/internal.h" #endif static int msgCb(SSL_CTX *ctx, SSL *ssl) { - #if defined(OPENSSL_ALL) && defined(SESSION_CERTS) && !defined(NO_BIO) - STACK_OF(X509)* sk; - X509* x509; - int i, num; - BIO* bio; - #endif + EXPECT_DECLS; +#if defined(OPENSSL_ALL) && defined(SESSION_CERTS) && !defined(NO_BIO) + STACK_OF(X509)* sk = NULL; + X509* x509 = NULL; + int i, num; + BIO* bio = NULL; +#endif (void) ctx; fprintf(stderr, "\n===== msgcb called ====\n"); - #if defined(SESSION_CERTS) && defined(TEST_PEER_CERT_CHAIN) - AssertTrue(SSL_get_peer_cert_chain(ssl) != NULL); - AssertIntEQ(((WOLFSSL_X509_CHAIN *)SSL_get_peer_cert_chain(ssl))->count, 2); - AssertNotNull(SSL_get0_verified_chain(ssl)); - #else +#if defined(SESSION_CERTS) && defined(TEST_PEER_CERT_CHAIN) + ExpectTrue(SSL_get_peer_cert_chain(ssl) != NULL); + ExpectIntEQ(((WOLFSSL_X509_CHAIN *)SSL_get_peer_cert_chain(ssl))->count, 2); + ExpectNotNull(SSL_get0_verified_chain(ssl)); +#else (void) ssl; - #endif +#endif - #if defined(OPENSSL_ALL) && defined(SESSION_CERTS) && !defined(NO_BIO) - bio = BIO_new(BIO_s_file()); - BIO_set_fp(bio, stderr, BIO_NOCLOSE); - sk = SSL_get_peer_cert_chain(ssl); - AssertNotNull(sk); - if (!sk) { +#if defined(OPENSSL_ALL) && defined(SESSION_CERTS) && !defined(NO_BIO) + ExpectNotNull(bio = BIO_new_fp(stderr, BIO_NOCLOSE)); + ExpectNotNull(sk = SSL_get_peer_cert_chain(ssl)); + if (sk == NULL) { BIO_free(bio); - return SSL_FAILURE; + return TEST_FAIL; } num = sk_X509_num(sk); - AssertTrue(num > 0); + ExpectTrue(num > 0); for (i = 0; i < num; i++) { - x509 = sk_X509_value(sk,i); - AssertNotNull(x509); - if (!x509) + ExpectNotNull(x509 = sk_X509_value(sk,i)); + if (x509 == NULL) break; fprintf(stderr, "Certificate at index [%d] = :\n",i); X509_print(bio,x509); fprintf(stderr, "\n\n"); } BIO_free(bio); - #endif - return SSL_SUCCESS; -} #endif + return EXPECT_RESULT(); +} #endif static int test_wolfSSL_msgCb(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && defined(DEBUG_WOLFSSL) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(NO_WOLFSSL_CLIENT) && \ - !defined(NO_WOLFSSL_SERVER) - - tcp_ready ready; - func_args client_args; - func_args server_args; - #ifndef SINGLE_THREADED - THREAD_TYPE serverThread; - #endif - callback_functions client_cb; - callback_functions server_cb; - -/* create a failed connection and inspect the error */ -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - - StartTCP(); - InitTcpReady(&ready); +#if defined(OPENSSL_EXTRA) && defined(DEBUG_WOLFSSL) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) + EXPECT_DECLS; + test_ssl_cbf client_cb; + test_ssl_cbf server_cb; XMEMSET(&client_cb, 0, sizeof(callback_functions)); XMEMSET(&server_cb, 0, sizeof(callback_functions)); @@ -40864,31 +41297,10 @@ static int test_wolfSSL_msgCb(void) server_cb.method = wolfTLSv1_3_server_method; #endif - server_args.signal = &ready; - server_args.callbacks = &server_cb; - client_args.signal = &ready; - client_args.callbacks = &client_cb; - client_args.return_code = TEST_FAIL; + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cb, + &server_cb, msgCb), TEST_SUCCESS); -#ifndef SINGLE_THREADED - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, msgCb); - join_thread(serverThread); -#endif - - FreeTcpReady(&ready); - -#ifndef SINGLE_THREADED - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); -#endif - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40897,66 +41309,29 @@ static int test_wolfSSL_either_side(void) { int res = TEST_SKIPPED; #if (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)) && \ - !defined(NO_FILESYSTEM) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ - !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) - - tcp_ready ready; - func_args client_args; - func_args server_args; - #ifndef SINGLE_THREADED - THREAD_TYPE serverThread; - #endif - callback_functions client_cb; - callback_functions server_cb; - -/* create a failed connection and inspect the error */ -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - - StartTCP(); - InitTcpReady(&ready); + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) + EXPECT_DECLS; + test_ssl_cbf client_cb; + test_ssl_cbf server_cb; - XMEMSET(&client_cb, 0, sizeof(callback_functions)); - XMEMSET(&server_cb, 0, sizeof(callback_functions)); + XMEMSET(&client_cb, 0, sizeof(client_cb)); + XMEMSET(&server_cb, 0, sizeof(server_cb)); /* Use different CTX for client and server */ client_cb.ctx = wolfSSL_CTX_new(wolfSSLv23_method()); - AssertNotNull(client_cb.ctx); + ExpectNotNull(client_cb.ctx); server_cb.ctx = wolfSSL_CTX_new(wolfSSLv23_method()); - AssertNotNull(server_cb.ctx); + ExpectNotNull(server_cb.ctx); /* we are responsible for free'ing WOLFSSL_CTX */ server_cb.isSharedCtx = client_cb.isSharedCtx = 1; - server_args.signal = &ready; - server_args.callbacks = &server_cb; - client_args.signal = &ready; - client_args.callbacks = &client_cb; - client_args.return_code = TEST_FAIL; - -#ifndef SINGLE_THREADED - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); -#endif + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cb, + &server_cb, NULL), TEST_SUCCESS); wolfSSL_CTX_free(client_cb.ctx); wolfSSL_CTX_free(server_cb.ctx); - FreeTcpReady(&ready); - -#ifndef SINGLE_THREADED - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); -#endif -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40965,66 +41340,29 @@ static int test_wolfSSL_DTLS_either_side(void) { int res = TEST_SKIPPED; #if (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)) && \ - !defined(NO_FILESYSTEM) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ - !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) && \ - defined(WOLFSSL_DTLS) - - tcp_ready ready; - func_args client_args; - func_args server_args; - #ifndef SINGLE_THREADED - THREAD_TYPE serverThread; - #endif - callback_functions client_cb; - callback_functions server_cb; - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && defined(WOLFSSL_DTLS) + EXPECT_DECLS; + test_ssl_cbf client_cb; + test_ssl_cbf server_cb; - StartTCP(); - InitTcpReady(&ready); - - XMEMSET(&client_cb, 0, sizeof(callback_functions)); - XMEMSET(&server_cb, 0, sizeof(callback_functions)); + XMEMSET(&client_cb, 0, sizeof(client_cb)); + XMEMSET(&server_cb, 0, sizeof(server_cb)); /* Use different CTX for client and server */ client_cb.ctx = wolfSSL_CTX_new(wolfDTLS_method()); - AssertNotNull(client_cb.ctx); + ExpectNotNull(client_cb.ctx); server_cb.ctx = wolfSSL_CTX_new(wolfDTLS_method()); - AssertNotNull(server_cb.ctx); + ExpectNotNull(server_cb.ctx); /* we are responsible for free'ing WOLFSSL_CTX */ server_cb.isSharedCtx = client_cb.isSharedCtx = 1; - server_args.signal = &ready; - server_args.callbacks = &server_cb; - client_args.signal = &ready; - client_args.callbacks = &client_cb; - client_args.return_code = TEST_FAIL; - -#ifndef SINGLE_THREADED - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); -#endif + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cb, + &server_cb, NULL), TEST_SUCCESS); wolfSSL_CTX_free(client_cb.ctx); wolfSSL_CTX_free(server_cb.ctx); - FreeTcpReady(&ready); -#ifndef SINGLE_THREADED - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); -#endif - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -41064,8 +41402,9 @@ static int test_wolfSSL_set_options(void) int res = TEST_SKIPPED; #if !defined(NO_CERTS) && !defined(NO_FILESYSTEM) && !defined(NO_RSA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - WOLFSSL* ssl; - WOLFSSL_CTX* ctx; + EXPECT_DECLS; + WOLFSSL* ssl = NULL; + WOLFSSL_CTX* ctx = NULL; #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) char appData[] = "extra msg"; #endif @@ -41079,91 +41418,90 @@ static int test_wolfSSL_set_options(void) #endif #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1) + ExpectTrue(wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1); - AssertTrue(wolfSSL_CTX_get_options(ctx) == WOLFSSL_OP_NO_TLSv1); + ExpectTrue(wolfSSL_CTX_get_options(ctx) == WOLFSSL_OP_NO_TLSv1); - AssertIntGT((int)wolfSSL_CTX_set_options(ctx, (WOLFSSL_OP_COOKIE_EXCHANGE | + ExpectIntGT((int)wolfSSL_CTX_set_options(ctx, (WOLFSSL_OP_COOKIE_EXCHANGE | WOLFSSL_OP_NO_SSLv2)), 0); - AssertTrue((wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_COOKIE_EXCHANGE) & + ExpectTrue((wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_COOKIE_EXCHANGE) & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE); - AssertTrue((wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2) & + ExpectTrue((wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2) & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2); - AssertTrue((wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_COMPRESSION) & + ExpectTrue((wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_COMPRESSION) & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION); - AssertFalse((wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_COMPRESSION) & + ExpectFalse((wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_COMPRESSION) & WOLFSSL_OP_NO_COMPRESSION)); wolfSSL_CTX_free(ctx); + ctx = NULL; #ifndef NO_WOLFSSL_SERVER - ctx = wolfSSL_CTX_new(wolfSSLv23_server_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); #else - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, WOLFSSL_FILETYPE_PEM)); - AssertTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, WOLFSSL_FILETYPE_PEM)); #ifdef OPENSSL_EXTRA - AssertTrue(wolfSSL_CTX_set_msg_callback(ctx, msg_cb) == WOLFSSL_SUCCESS); + ExpectTrue(wolfSSL_CTX_set_msg_callback(ctx, msg_cb) == WOLFSSL_SUCCESS); #endif - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) #ifdef HAVE_EX_DATA - AssertIntEQ(wolfSSL_set_app_data(ssl, (void*)appData), WOLFSSL_SUCCESS); - AssertNotNull(wolfSSL_get_app_data((const WOLFSSL*)ssl)); - if (ssl) { - AssertIntEQ(XMEMCMP(wolfSSL_get_app_data((const WOLFSSL*)ssl), + ExpectIntEQ(wolfSSL_set_app_data(ssl, (void*)appData), WOLFSSL_SUCCESS); + ExpectNotNull(wolfSSL_get_app_data((const WOLFSSL*)ssl)); + if (ssl != NULL) { + ExpectIntEQ(XMEMCMP(wolfSSL_get_app_data((const WOLFSSL*)ssl), appData, sizeof(appData)), 0); } #else - AssertIntEQ(wolfSSL_set_app_data(ssl, (void*)appData), WOLFSSL_FAILURE); - AssertNull(wolfSSL_get_app_data((const WOLFSSL*)ssl)); + ExpectIntEQ(wolfSSL_set_app_data(ssl, (void*)appData), WOLFSSL_FAILURE); + ExpectNull(wolfSSL_get_app_data((const WOLFSSL*)ssl)); #endif #endif - AssertTrue(wolfSSL_set_options(ssl, WOLFSSL_OP_NO_TLSv1) == + ExpectTrue(wolfSSL_set_options(ssl, WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1); - AssertTrue(wolfSSL_get_options(ssl) == WOLFSSL_OP_NO_TLSv1); + ExpectTrue(wolfSSL_get_options(ssl) == WOLFSSL_OP_NO_TLSv1); - AssertIntGT((int)wolfSSL_set_options(ssl, (WOLFSSL_OP_COOKIE_EXCHANGE | + ExpectIntGT((int)wolfSSL_set_options(ssl, (WOLFSSL_OP_COOKIE_EXCHANGE | WOLFSSL_OP_NO_SSLv2)), 0); - AssertTrue((wolfSSL_set_options(ssl, WOLFSSL_OP_COOKIE_EXCHANGE) & + ExpectTrue((wolfSSL_set_options(ssl, WOLFSSL_OP_COOKIE_EXCHANGE) & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE); - AssertTrue((wolfSSL_set_options(ssl, WOLFSSL_OP_NO_TLSv1_2) & + ExpectTrue((wolfSSL_set_options(ssl, WOLFSSL_OP_NO_TLSv1_2) & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2); - AssertTrue((wolfSSL_set_options(ssl, WOLFSSL_OP_NO_COMPRESSION) & + ExpectTrue((wolfSSL_set_options(ssl, WOLFSSL_OP_NO_COMPRESSION) & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION); #ifdef OPENSSL_EXTRA - AssertFalse((wolfSSL_clear_options(ssl, WOLFSSL_OP_NO_COMPRESSION) & + ExpectFalse((wolfSSL_clear_options(ssl, WOLFSSL_OP_NO_COMPRESSION) & WOLFSSL_OP_NO_COMPRESSION)); #endif #ifdef OPENSSL_EXTRA - AssertTrue(wolfSSL_set_msg_callback(ssl, msg_cb) == WOLFSSL_SUCCESS); + ExpectTrue(wolfSSL_set_msg_callback(ssl, msg_cb) == WOLFSSL_SUCCESS); wolfSSL_set_msg_callback_arg(ssl, arg); #ifdef WOLFSSL_ERROR_CODE_OPENSSL - AssertTrue(wolfSSL_CTX_set_alpn_protos(ctx, protos, len) == 0); + ExpectTrue(wolfSSL_CTX_set_alpn_protos(ctx, protos, len) == 0); #else - AssertTrue(wolfSSL_CTX_set_alpn_protos(ctx, protos, len) == WOLFSSL_SUCCESS); + ExpectTrue(wolfSSL_CTX_set_alpn_protos(ctx, protos, len) == WOLFSSL_SUCCESS); #endif #endif @@ -41174,9 +41512,9 @@ static int test_wolfSSL_set_options(void) #if defined(HAVE_ALPN) && !defined(NO_BIO) #ifdef WOLFSSL_ERROR_CODE_OPENSSL - AssertTrue(wolfSSL_set_alpn_protos(ssl, protos, len) == 0); + ExpectTrue(wolfSSL_set_alpn_protos(ssl, protos, len) == 0); #else - AssertTrue(wolfSSL_set_alpn_protos(ssl, protos, len) == WOLFSSL_SUCCESS); + ExpectTrue(wolfSSL_set_alpn_protos(ssl, protos, len) == WOLFSSL_SUCCESS); #endif #endif /* HAVE_ALPN && !NO_BIO */ @@ -41185,7 +41523,7 @@ static int test_wolfSSL_set_options(void) wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* !defined(NO_CERTS) && !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ return res; @@ -41197,32 +41535,34 @@ static int test_wolfSSL_sk_SSL_CIPHER(void) #if defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - SSL* ssl; - SSL_CTX* ctx; - STACK_OF(SSL_CIPHER) *sk, *dupSk; + EXPECT_DECLS; + SSL* ssl = NULL; + SSL_CTX* ctx = NULL; + STACK_OF(SSL_CIPHER) *sk = NULL; + STACK_OF(SSL_CIPHER) *dupSk = NULL; #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); - AssertNotNull(sk = SSL_get_ciphers(ssl)); - AssertNotNull(dupSk = sk_SSL_CIPHER_dup(sk)); - AssertIntGT(sk_SSL_CIPHER_num(sk), 0); - AssertIntEQ(sk_SSL_CIPHER_num(sk), sk_SSL_CIPHER_num(dupSk)); + ExpectTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); + ExpectNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(sk = SSL_get_ciphers(ssl)); + ExpectNotNull(dupSk = sk_SSL_CIPHER_dup(sk)); + ExpectIntGT(sk_SSL_CIPHER_num(sk), 0); + ExpectIntEQ(sk_SSL_CIPHER_num(sk), sk_SSL_CIPHER_num(dupSk)); /* error case because connection has not been established yet */ - AssertIntEQ(sk_SSL_CIPHER_find(sk, SSL_get_current_cipher(ssl)), -1); + ExpectIntEQ(sk_SSL_CIPHER_find(sk, SSL_get_current_cipher(ssl)), -1); sk_SSL_CIPHER_free(dupSk); /* sk is pointer to internal struct that should be free'd in SSL_free */ SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ @@ -41234,56 +41574,57 @@ static int test_wolfSSL_set1_curves_list(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; SSL* ssl = NULL; SSL_CTX* ctx = NULL; #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, eccCertFile, + ExpectTrue(SSL_CTX_use_certificate_file(ctx, eccCertFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, SSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, SSL_FILETYPE_PEM)); + ExpectNotNull(ssl = SSL_new(ctx)); - AssertIntEQ(SSL_CTX_set1_curves_list(ctx, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_CTX_set1_curves_list(ctx, NULL), WOLFSSL_FAILURE); #ifdef HAVE_ECC - AssertIntEQ(SSL_CTX_set1_curves_list(ctx, "P-25X"), WOLFSSL_FAILURE); - AssertIntEQ(SSL_CTX_set1_curves_list(ctx, "P-256"), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_CTX_set1_curves_list(ctx, "P-25X"), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_CTX_set1_curves_list(ctx, "P-256"), WOLFSSL_SUCCESS); #endif #ifdef HAVE_CURVE25519 - AssertIntEQ(SSL_CTX_set1_curves_list(ctx, "X25519"), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_CTX_set1_curves_list(ctx, "X25519"), WOLFSSL_SUCCESS); #else - AssertIntEQ(SSL_CTX_set1_curves_list(ctx, "X25519"), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_CTX_set1_curves_list(ctx, "X25519"), WOLFSSL_FAILURE); #endif #ifdef HAVE_CURVE448 - AssertIntEQ(SSL_CTX_set1_curves_list(ctx, "X448"), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_CTX_set1_curves_list(ctx, "X448"), WOLFSSL_SUCCESS); #else - AssertIntEQ(SSL_CTX_set1_curves_list(ctx, "X448"), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_CTX_set1_curves_list(ctx, "X448"), WOLFSSL_FAILURE); #endif - AssertIntEQ(SSL_set1_curves_list(ssl, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_set1_curves_list(ssl, NULL), WOLFSSL_FAILURE); #ifdef HAVE_ECC - AssertIntEQ(SSL_set1_curves_list(ssl, "P-25X"), WOLFSSL_FAILURE); - AssertIntEQ(SSL_set1_curves_list(ssl, "P-256"), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_set1_curves_list(ssl, "P-25X"), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_set1_curves_list(ssl, "P-256"), WOLFSSL_SUCCESS); #endif #ifdef HAVE_CURVE25519 - AssertIntEQ(SSL_set1_curves_list(ssl, "X25519"), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_set1_curves_list(ssl, "X25519"), WOLFSSL_SUCCESS); #else - AssertIntEQ(SSL_set1_curves_list(ssl, "X25519"), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_set1_curves_list(ssl, "X25519"), WOLFSSL_FAILURE); #endif #ifdef HAVE_CURVE448 - AssertIntEQ(SSL_set1_curves_list(ssl, "X448"), WOLFSSL_SUCCESS); + ExpectIntEQ(SSL_set1_curves_list(ssl, "X448"), WOLFSSL_SUCCESS); #else - AssertIntEQ(SSL_set1_curves_list(ssl, "X448"), WOLFSSL_FAILURE); + ExpectIntEQ(SSL_set1_curves_list(ssl, "X448"), WOLFSSL_FAILURE); #endif SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif return res; @@ -41294,114 +41635,116 @@ static int test_wolfSSL_set1_sigalgs_list(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_RSA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - SSL* ssl; - SSL_CTX* ctx; + EXPECT_DECLS; + SSL* ssl = NULL; + SSL_CTX* ctx = NULL; #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, + ExpectTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); + ExpectNotNull(ssl = SSL_new(ctx)); - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, NULL), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_set1_sigalgs_list(NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(NULL, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_set1_sigalgs_list(NULL, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, NULL), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, ""), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, ""), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, ""), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, ""), WOLFSSL_FAILURE); #ifndef NO_RSA #ifndef NO_SHA256 - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(NULL, "RSA+SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(NULL, "RSA+SHA256"), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_set1_sigalgs_list(NULL, "RSA+SHA256"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(NULL, "RSA+SHA256"), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA+SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA+SHA256"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA+SHA256"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA+SHA256"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA-SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA-SHA256"), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA-SHA256"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA-SHA256"), WOLFSSL_FAILURE); #ifdef WC_RSA_PSS - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA-PSS+SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA-PSS+SHA256"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA-PSS+SHA256"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA-PSS+SHA256"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "PSS+SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "PSS+SHA256"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "PSS+SHA256"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "PSS+SHA256"), WOLFSSL_SUCCESS); #endif #ifdef WOLFSSL_SHA512 - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA+SHA256:RSA+SHA512"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA+SHA256:RSA+SHA512"), WOLFSSL_SUCCESS); #elif defined(WOLFSSL_SHA384) - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA+SHA256:RSA+SHA384"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA+SHA256:RSA+SHA384"), WOLFSSL_SUCCESS); #endif - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA"), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA"), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA:RSA+SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA"), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA"), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA:RSA+SHA256"), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA:RSA+SHA256"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA:RSA+SHA256"), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA+SHA256+SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "RSA+SHA256+SHA256"), WOLFSSL_FAILURE); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA+SHA256+RSA"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "RSA+SHA256+RSA"), WOLFSSL_FAILURE); #endif #endif #ifdef HAVE_ECC #ifndef NO_SHA256 - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "ECDSA+SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "ECDSA+SHA256"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "ECDSA+SHA256"), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "ECDSA+SHA256"), + WOLFSSL_SUCCESS); #ifdef WOLFSSL_SHA512 - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "ECDSA+SHA256:ECDSA+SHA512"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "ECDSA+SHA256:ECDSA+SHA512"), WOLFSSL_SUCCESS); #elif defined(WOLFSSL_SHA384) - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "ECDSA+SHA256:ECDSA+SHA384"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "ECDSA+SHA256:ECDSA+SHA384"), WOLFSSL_SUCCESS); #endif #endif #endif #ifdef HAVE_ED25519 - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "ED25519"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "ED25519"), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "ED25519"), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "ED25519"), WOLFSSL_SUCCESS); #endif #ifdef HAVE_ED448 - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "ED448"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "ED448"), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "ED448"), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "ED448"), WOLFSSL_SUCCESS); #endif #ifndef NO_DSA #ifndef NO_SHA256 - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "DSA+SHA256"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "DSA+SHA256"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "DSA+SHA256"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "DSA+SHA256"), WOLFSSL_SUCCESS); #endif #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \ defined(WOLFSSL_ALLOW_TLS_SHA1)) - AssertIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "DSA+SHA1"), + ExpectIntEQ(wolfSSL_CTX_set1_sigalgs_list(ctx, "DSA+SHA1"), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_set1_sigalgs_list(ssl, "DSA+SHA1"), + ExpectIntEQ(wolfSSL_set1_sigalgs_list(ssl, "DSA+SHA1"), WOLFSSL_SUCCESS); #endif #endif @@ -41409,7 +41752,7 @@ static int test_wolfSSL_set1_sigalgs_list(void) SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif return res; @@ -42543,93 +42886,72 @@ static int test_wolfSSL_X509_VERIFY_PARAM(void) return res; } -#if defined(OPENSSL_EXTRA) && defined(HAVE_IO_TESTS_DEPENDENCIES) +#if defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) static int test_wolfSSL_check_domain_verify_count = 0; static WC_INLINE int test_wolfSSL_check_domain_verify_cb(int preverify, WOLFSSL_X509_STORE_CTX* store) { - AssertIntEQ(X509_STORE_CTX_get_error(store), 0); - AssertIntEQ(preverify, 1); - test_wolfSSL_check_domain_verify_count++; - return 1; + EXPECT_DECLS; + ExpectIntEQ(X509_STORE_CTX_get_error(store), 0); + ExpectIntEQ(preverify, 1); + ExpectIntGT(++test_wolfSSL_check_domain_verify_count, 0); + return EXPECT_RESULT() == TEST_SUCCESS; } -static void test_wolfSSL_check_domain_client_cb(WOLFSSL* ssl) +static int test_wolfSSL_check_domain_client_cb(WOLFSSL* ssl) { - X509_VERIFY_PARAM *param = SSL_get0_param(ssl); + EXPECT_DECLS; + X509_VERIFY_PARAM *param = NULL; + + ExpectNotNull(param = SSL_get0_param(ssl)); /* Domain check should only be done on the leaf cert */ - X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); - AssertIntEQ(X509_VERIFY_PARAM_set1_host(param, + X509_VERIFY_PARAM_set_hostflags(param, + X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + ExpectIntEQ(X509_VERIFY_PARAM_set1_host(param, "wolfSSL Server Chain", 0), 1); wolfSSL_set_verify(ssl, WOLFSSL_VERIFY_PEER, - test_wolfSSL_check_domain_verify_cb); + test_wolfSSL_check_domain_verify_cb); + return EXPECT_RESULT(); } -static void test_wolfSSL_check_domain_server_cb(WOLFSSL_CTX* ctx) +static int test_wolfSSL_check_domain_server_cb(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; /* Use a cert with different domains in chain */ - AssertIntEQ(wolfSSL_CTX_use_certificate_chain_file(ctx, - "certs/intermediate/server-chain.pem"), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_use_certificate_chain_file(ctx, + "certs/intermediate/server-chain.pem"), WOLFSSL_SUCCESS); + return EXPECT_RESULT(); } static int test_wolfSSL_check_domain(void) { - tcp_ready ready; - func_args client_args; - func_args server_args; - THREAD_TYPE serverThread; - callback_functions func_cb_client; - callback_functions func_cb_server; - - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - XMEMSET(&func_cb_client, 0, sizeof(callback_functions)); - XMEMSET(&func_cb_server, 0, sizeof(callback_functions)); -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif + EXPECT_DECLS; + test_ssl_cbf func_cb_client; + test_ssl_cbf func_cb_server; - server_args.signal = &ready; - client_args.signal = &ready; + XMEMSET(&func_cb_client, 0, sizeof(func_cb_client)); + XMEMSET(&func_cb_server, 0, sizeof(func_cb_server)); func_cb_client.ssl_ready = &test_wolfSSL_check_domain_client_cb; func_cb_server.ctx_ready = &test_wolfSSL_check_domain_server_cb; - client_args.callbacks = &func_cb_client; - server_args.callbacks = &func_cb_server; - - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); - - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); - - FreeTcpReady(&ready); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, + &func_cb_server, NULL), TEST_SUCCESS); /* Should have been called once for each cert in sent chain */ #ifdef WOLFSSL_VERIFY_CB_ALL_CERTS - AssertIntEQ(test_wolfSSL_check_domain_verify_count, 3); + ExpectIntEQ(test_wolfSSL_check_domain_verify_count, 3); #else - AssertIntEQ(test_wolfSSL_check_domain_verify_count, 1); + ExpectIntEQ(test_wolfSSL_check_domain_verify_count, 1); #endif - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } -#endif /* OPENSSL_EXTRA && HAVE_IO_TESTS_DEPENDENCIES */ +#endif /* OPENSSL_EXTRA && HAVE_SSL_MEMIO_TESTS_DEPENDENCIES */ static int test_wolfSSL_X509_get_X509_PUBKEY(void) { @@ -43506,28 +43828,31 @@ static int test_wolfSSL_error_cb(const char *str, size_t len, void *u) static int test_wolfSSL_ERR_print_errors_cb(void) { int res = TEST_SKIPPED; - #if !defined(NO_ERROR_QUEUE) && defined(OPENSSL_EXTRA) && \ - defined(DEBUG_WOLFSSL) +#if !defined(NO_ERROR_QUEUE) && defined(OPENSSL_EXTRA) && \ + defined(DEBUG_WOLFSSL) + EXPECT_DECLS; BIO* bio; char buf[1024]; - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); ERR_clear_error(); /* clear out any error nodes */ ERR_put_error(0,SYS_F_ACCEPT, -173, "ssl.c", 0); ERR_put_error(0,SYS_F_BIND, -275, "asn.c", 100); ERR_print_errors_cb(test_wolfSSL_error_cb, bio); - AssertIntEQ(BIO_gets(bio, buf, sizeof(buf)), 108); - AssertIntEQ(XSTRNCMP("wolfSSL error occurred, error = 173 line:0 file:ssl.c", - buf, 53), 0); - AssertIntEQ(XSTRNCMP("wolfSSL error occurred, error = 275 line:100 file:asn.c", - buf + 53, 55), 0); - AssertIntEQ(BIO_gets(bio, buf, sizeof(buf)), 0); + ExpectIntEQ(BIO_gets(bio, buf, sizeof(buf)), 108); + ExpectIntEQ(XSTRNCMP( + "wolfSSL error occurred, error = 173 line:0 file:ssl.c", + buf, 53), 0); + ExpectIntEQ(XSTRNCMP( + "wolfSSL error occurred, error = 275 line:100 file:asn.c", + buf + 53, 55), 0); + ExpectIntEQ(BIO_gets(bio, buf, sizeof(buf)), 0); BIO_free(bio); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -43543,7 +43868,7 @@ static int test_WOLFSSL_ERROR_MSG(void) WOLFSSL_ERROR_MSG(msg); - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif return res; }/*End test_WOLFSSL_ERROR_MSG*/ @@ -43556,7 +43881,7 @@ static int test_wc_ERR_remove_state(void) #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) wc_ERR_remove_state(); - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif return res; }/*End test_wc_ERR_remove_state*/ @@ -43568,31 +43893,27 @@ static int test_wc_ERR_print_errors_fp(void) int res = TEST_SKIPPED; #if (defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)) && \ (!defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)) + EXPECT_DECLS; long sz; - XFILE fp; - int ret = 0; + XFILE fp = XBADFILE; WOLFSSL_ERROR(BAD_FUNC_ARG); - fp = XFOPEN("./tests/test-log-dump-to-file.txt", "ar"); + ExpectTrue((fp = XFOPEN("./tests/test-log-dump-to-file.txt", "ar")) != + XBADFILE); wc_ERR_print_errors_fp(fp); #if defined(DEBUG_WOLFSSL) - AssertTrue(XFSEEK(fp, 0, XSEEK_END) == 0); - sz = XFTELL(fp); + ExpectTrue(XFSEEK(fp, 0, XSEEK_END) == 0); #ifdef NO_ERROR_QUEUE - /* File should be empty when NO_ERROR_QUEUE is defined */ - if (sz != 0) { - ret = BAD_FUNC_ARG; - } + ExpectIntEQ(sz = XFTELL(fp), 0); #else - if (sz == 0) { - ret = BAD_FUNC_ARG; - } + ExpectIntNE(sz = XFTELL(fp), 0); #endif #endif - XFCLOSE(fp); + if (fp != XBADFILE) + XFCLOSE(fp); (void)sz; - res = TEST_RES_CHECK(ret == 0); + res = EXPECT_RESULT(); #endif return res; }/*End test_wc_ERR_print_errors_fp*/ @@ -43608,43 +43929,18 @@ static void Logging_cb(const int logLevel, const char *const logMessage) */ static int test_wolfSSL_GetLoggingCb(void) { - int ret = 0; + EXPECT_DECLS; #ifdef DEBUG_WOLFSSL - /* Testing without wolfSSL_SetLoggingCb() */ - if (ret == 0) { - if (wolfSSL_GetLoggingCb() == NULL) { /* Should be true */ - ret = 0; - } - if (wolfSSL_GetLoggingCb() != NULL) { /* Should not be true */ - ret = -1; - } - } + ExpectNull(wolfSSL_GetLoggingCb()); /* Testing with wolfSSL_SetLoggingCb() */ - if (ret == 0) { - ret = wolfSSL_SetLoggingCb(Logging_cb); - if (ret == 0) { - if (wolfSSL_GetLoggingCb() == NULL) { /* Should not be true */ - ret = -1; - } - if (ret == 0) { - if (wolfSSL_GetLoggingCb() == Logging_cb) { /* Should be true */ - ret = 0; - } - } - - /* reset logging callback */ - wolfSSL_SetLoggingCb(NULL); - } - } + ExpectIntEQ(wolfSSL_SetLoggingCb(Logging_cb), 0); + ExpectNotNull(wolfSSL_GetLoggingCb()); + ExpectIntEQ(wolfSSL_SetLoggingCb(NULL), 0); #endif - if (ret == 0) { - if (wolfSSL_GetLoggingCb() != NULL) { - ret = -1; - } - } + ExpectNull(wolfSSL_GetLoggingCb()); - return TEST_RES_CHECK(ret == 0); + return EXPECT_RESULT(); }/*End test_wolfSSL_GetLoggingCb*/ #endif /* !NO_BIO */ @@ -45515,7 +45811,7 @@ static int test_wolfSSL_BIO_reset(void) } #endif /* !NO_BIO */ -#if defined(OPENSSL_EXTRA) && defined(HAVE_IO_TESTS_DEPENDENCIES) +#if defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) /* test that the callback arg is correct */ static int certCbArg = 0; @@ -45533,19 +45829,21 @@ static int clientCertCb(WOLFSSL* ssl, void* arg) return 1; } -static void clientCertSetupCb(WOLFSSL_CTX* ctx) +static int clientCertSetupCb(WOLFSSL_CTX* ctx) { SSL_CTX_set_cert_cb(ctx, clientCertCb, &certCbArg); + return TEST_SUCCESS; } /** * This is only done because test_client_nofail has no way to stop * certificate and key loading */ -static void clientCertClearCb(WOLFSSL* ssl) +static int clientCertClearCb(WOLFSSL* ssl) { /* Clear the loaded certs to force the callbacks to set them up */ SSL_certs_clear(ssl); + return TEST_SUCCESS; } static int serverCertCb(WOLFSSL* ssl, void* arg) @@ -45561,19 +45859,21 @@ static int serverCertCb(WOLFSSL* ssl, void* arg) return 1; } -static void serverCertSetupCb(WOLFSSL_CTX* ctx) +static int serverCertSetupCb(WOLFSSL_CTX* ctx) { SSL_CTX_set_cert_cb(ctx, serverCertCb, &certCbArg); + return TEST_SUCCESS; } /** * This is only done because test_server_nofail has no way to stop * certificate and key loading */ -static void serverCertClearCb(WOLFSSL* ssl) +static int serverCertClearCb(WOLFSSL* ssl) { /* Clear the loaded certs to force the callbacks to set them up */ SSL_certs_clear(ssl); + return TEST_SUCCESS; } #endif @@ -45581,55 +45881,23 @@ static void serverCertClearCb(WOLFSSL* ssl) static int test_wolfSSL_cert_cb(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_EXTRA) && defined(HAVE_IO_TESTS_DEPENDENCIES) - callback_functions func_cb_client; - callback_functions func_cb_server; - tcp_ready ready; - func_args client_args; - func_args server_args; - THREAD_TYPE serverThread; +#if defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) + EXPECT_DECLS; + test_ssl_cbf func_cb_client; + test_ssl_cbf func_cb_server; - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); XMEMSET(&func_cb_client, 0, sizeof(callback_functions)); XMEMSET(&func_cb_server, 0, sizeof(callback_functions)); -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif - - server_args.signal = &ready; - client_args.signal = &ready; - client_args.callbacks = &func_cb_client; - server_args.callbacks = &func_cb_server; func_cb_client.ctx_ready = clientCertSetupCb; func_cb_client.ssl_ready = clientCertClearCb; func_cb_server.ctx_ready = serverCertSetupCb; func_cb_server.ssl_ready = serverCertClearCb; - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); - - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); - - FreeTcpReady(&ready); - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, + &func_cb_server, NULL), TEST_SUCCESS); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -45897,7 +46165,7 @@ static int test_wolfSSL_SESSION(void) return res; } -#if defined(OPENSSL_EXTRA) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ +#if defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ defined(HAVE_EX_DATA) && !defined(NO_SESSION_CACHE) static int clientSessRemCountMalloc = 0; static int serverSessRemCountMalloc = 0; @@ -45911,22 +46179,29 @@ static WOLFSSL_CTX* clientSessCtx = NULL; static WOLFSSL_SESSION* clientSess = NULL; #endif static int serverSessRemIdx = 3; +static int sessRemCtx_Server = WOLFSSL_SERVER_END; +static int sessRemCtx_Client = WOLFSSL_CLIENT_END; static void SessRemCtxCb(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *sess) { - int* mallocedData = (int*)SSL_SESSION_get_ex_data(sess, serverSessRemIdx); + int* side; + (void)ctx; - AssertNotNull(mallocedData); - if (!*mallocedData) - clientSessRemCountFree++; - else - serverSessRemCountFree++; - XFREE(mallocedData, NULL, DYNAMIC_TYPE_SESSION); - SSL_SESSION_set_ex_data(sess, serverSessRemIdx, NULL); + + side = (int*)SSL_SESSION_get_ex_data(sess, serverSessRemIdx); + if (side != NULL) { + if (*side == WOLFSSL_CLIENT_END) + clientSessRemCountFree++; + else + serverSessRemCountFree++; + + SSL_SESSION_set_ex_data(sess, serverSessRemIdx, NULL); + } } -static void SessRemCtxSetupCb(WOLFSSL_CTX* ctx) +static int SessRemCtxSetupCb(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; SSL_CTX_sess_set_remove_cb(ctx, SessRemCtxCb); #if defined(WOLFSSL_TLS13) && !defined(HAVE_SESSION_TICKET) && \ !defined(NO_SESSION_CACHE_REF) @@ -45936,116 +46211,90 @@ static void SessRemCtxSetupCb(WOLFSSL_CTX* ctx) * HAVE_SESSION_TICKET we won't have a session ID to be able to place the * session in the cache. In this case we need to downgrade to previous * versions to just use the legacy session ID field. */ - AssertIntEQ(SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION), SSL_SUCCESS); - AssertIntEQ(SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION), SSL_SUCCESS); + ExpectIntEQ(SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION), SSL_SUCCESS); + ExpectIntEQ(SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION), + SSL_SUCCESS); #endif + return EXPECT_RESULT(); } -static void SessRemSslSetupCb(WOLFSSL* ssl) +static int SessRemSslSetupCb(WOLFSSL* ssl) { - int* mallocedData = (int*)XMALLOC(sizeof(int), NULL, DYNAMIC_TYPE_SESSION); - AssertNotNull(mallocedData); - *mallocedData = SSL_is_server(ssl); - if (!*mallocedData) { - clientSessRemCountMalloc++; -#if (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) || \ - !defined(NO_SESSION_CACHE_REF) - AssertNotNull(clientSess = SSL_get1_session(ssl)); - AssertIntEQ(SSL_CTX_up_ref(clientSessCtx = SSL_get_SSL_CTX(ssl)), - SSL_SUCCESS); -#endif - } - else { - serverSessRemCountMalloc++; - AssertNotNull(serverSess = SSL_get1_session(ssl)); - AssertIntEQ(SSL_CTX_up_ref(serverSessCtx = SSL_get_SSL_CTX(ssl)), - SSL_SUCCESS); + EXPECT_DECLS; + int* side; + + if (EXPECT_SUCCESS()) { + if (SSL_is_server(ssl)) { + side = &sessRemCtx_Server; + serverSessRemCountMalloc++; + ExpectNotNull(serverSess = SSL_get1_session(ssl)); + ExpectIntEQ(SSL_CTX_up_ref(serverSessCtx = SSL_get_SSL_CTX(ssl)), + SSL_SUCCESS); + } + else { + side = &sessRemCtx_Client; + clientSessRemCountMalloc++; + #if (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) || \ + !defined(NO_SESSION_CACHE_REF) + ExpectNotNull(clientSess = SSL_get1_session(ssl)); + ExpectIntEQ(SSL_CTX_up_ref(clientSessCtx = SSL_get_SSL_CTX(ssl)), + SSL_SUCCESS); + #endif + } + ExpectIntEQ(SSL_SESSION_set_ex_data(SSL_get_session(ssl), + serverSessRemIdx, side), SSL_SUCCESS); } - AssertIntEQ(SSL_SESSION_set_ex_data(SSL_get_session(ssl), serverSessRemIdx, - mallocedData), SSL_SUCCESS); + + return EXPECT_RESULT(); } #endif static int test_wolfSSL_CTX_sess_set_remove_cb(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_EXTRA) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ +#if defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && \ defined(HAVE_EX_DATA) && !defined(NO_SESSION_CACHE) + EXPECT_DECLS; /* Check that the remove callback gets called for external data in a * session object */ - callback_functions func_cb; - tcp_ready ready; - func_args client_args; - func_args server_args; - THREAD_TYPE serverThread; + test_ssl_cbf func_cb; - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); XMEMSET(&func_cb, 0, sizeof(callback_functions)); - - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif - - server_args.signal = &ready; - client_args.signal = &ready; - client_args.callbacks = &func_cb; - server_args.callbacks = &func_cb; func_cb.ctx_ready = SessRemCtxSetupCb; func_cb.on_result = SessRemSslSetupCb; - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); - - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); - - FreeTcpReady(&ready); - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb, &func_cb, + NULL), TEST_SUCCESS); /* Both should have been allocated */ - AssertIntEQ(clientSessRemCountMalloc, 1); - AssertIntEQ(serverSessRemCountMalloc, 1); + ExpectIntEQ(clientSessRemCountMalloc, 1); + ExpectIntEQ(serverSessRemCountMalloc, 1); /* This should not be called yet. Session wasn't evicted from cache yet. */ - AssertIntEQ(clientSessRemCountFree, 0); + ExpectIntEQ(clientSessRemCountFree, 0); #if (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) || \ !defined(NO_SESSION_CACHE_REF) /* Force a cache lookup */ - AssertNotNull(SSL_SESSION_get_ex_data(clientSess, serverSessRemIdx)); + ExpectNotNull(SSL_SESSION_get_ex_data(clientSess, serverSessRemIdx)); /* Force a cache update */ - AssertNotNull(SSL_SESSION_set_ex_data(clientSess, serverSessRemIdx - 1, 0)); + ExpectNotNull(SSL_SESSION_set_ex_data(clientSess, serverSessRemIdx - 1, 0)); /* This should set the timeout to 0 and call the remove callback from within * the session cache. */ - AssertIntEQ(SSL_CTX_remove_session(clientSessCtx, clientSess), 0); - AssertNull(SSL_SESSION_get_ex_data(clientSess, serverSessRemIdx)); - AssertIntEQ(clientSessRemCountFree, 1); + ExpectIntEQ(SSL_CTX_remove_session(clientSessCtx, clientSess), 0); + ExpectNull(SSL_SESSION_get_ex_data(clientSess, serverSessRemIdx)); + ExpectIntEQ(clientSessRemCountFree, 1); #endif /* Server session is in the cache so ex_data isn't free'd with the SSL * object */ - AssertIntEQ(serverSessRemCountFree, 0); + ExpectIntEQ(serverSessRemCountFree, 0); /* Force a cache lookup */ - AssertNotNull(SSL_SESSION_get_ex_data(serverSess, serverSessRemIdx)); + ExpectNotNull(SSL_SESSION_get_ex_data(serverSess, serverSessRemIdx)); /* Force a cache update */ - AssertNotNull(SSL_SESSION_set_ex_data(serverSess, serverSessRemIdx - 1, 0)); + ExpectNotNull(SSL_SESSION_set_ex_data(serverSess, serverSessRemIdx - 1, 0)); /* This should set the timeout to 0 and call the remove callback from within * the session cache. */ - AssertIntEQ(SSL_CTX_remove_session(serverSessCtx, serverSess), 0); - AssertNull(SSL_SESSION_get_ex_data(serverSess, serverSessRemIdx)); - AssertIntEQ(serverSessRemCountFree, 1); + ExpectIntEQ(SSL_CTX_remove_session(serverSessCtx, serverSess), 0); + ExpectNull(SSL_SESSION_get_ex_data(serverSess, serverSessRemIdx)); + ExpectIntEQ(serverSessRemCountFree, 1); /* Need to free the references that we kept */ SSL_CTX_free(serverSessCtx); @@ -46056,7 +46305,7 @@ static int test_wolfSSL_CTX_sess_set_remove_cb(void) SSL_SESSION_free(clientSess); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -55054,12 +55303,10 @@ static int test_tls13_cipher_suites(void) #endif -#if defined(HAVE_PK_CALLBACKS) && (!defined(WOLFSSL_NO_TLS12) || \ - !defined(NO_OLD_TLS)) -#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ - !defined(NO_WOLFSSL_CLIENT) && !defined(NO_DH) && \ +#if defined(HAVE_PK_CALLBACKS) && !defined(WOLFSSL_NO_TLS12) +#if !defined(NO_FILESYSTEM) && !defined(NO_DH) && \ !defined(NO_AES) && defined(HAVE_AES_CBC) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(SINGLE_THREADED) + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) static int my_DhCallback(WOLFSSL* ssl, struct DhKey* key, const unsigned char* priv, unsigned int privSz, const unsigned char* pubKeyDer, unsigned int pubKeySz, @@ -55080,199 +55327,114 @@ static int my_DhCallback(WOLFSSL* ssl, struct DhKey* key, return result; } -static void test_dh_ctx_setup(WOLFSSL_CTX* ctx) { +static int test_dh_ctx_setup(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; wolfSSL_CTX_SetDhAgreeCb(ctx, my_DhCallback); #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128) - AssertIntEQ(wolfSSL_CTX_set_cipher_list(ctx, "DHE-RSA-AES128-SHA256"), + ExpectIntEQ(wolfSSL_CTX_set_cipher_list(ctx, "DHE-RSA-AES128-SHA256"), WOLFSSL_SUCCESS); #endif #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256) - AssertIntEQ(wolfSSL_CTX_set_cipher_list(ctx, "DHE-RSA-AES256-SHA256"), + ExpectIntEQ(wolfSSL_CTX_set_cipher_list(ctx, "DHE-RSA-AES256-SHA256"), WOLFSSL_SUCCESS); #endif + return EXPECT_RESULT(); } -static void test_dh_ssl_setup(WOLFSSL* ssl) +static int test_dh_ssl_setup(WOLFSSL* ssl) { + EXPECT_DECLS; static int dh_test_ctx = 1; int ret; wolfSSL_SetDhAgreeCtx(ssl, &dh_test_ctx); - AssertIntEQ(*((int*)wolfSSL_GetDhAgreeCtx(ssl)), dh_test_ctx); + ExpectIntEQ(*((int*)wolfSSL_GetDhAgreeCtx(ssl)), dh_test_ctx); ret = wolfSSL_SetTmpDH_file(ssl, dhParamFile, WOLFSSL_FILETYPE_PEM); if (ret != WOLFSSL_SUCCESS && ret != SIDE_ERROR) { - AssertIntEQ(ret, WOLFSSL_SUCCESS); + ExpectIntEQ(ret, WOLFSSL_SUCCESS); } + return EXPECT_RESULT(); } -static void test_dh_ssl_setup_fail(WOLFSSL* ssl) +static int test_dh_ssl_setup_fail(WOLFSSL* ssl) { + EXPECT_DECLS; int ret; wolfSSL_SetDhAgreeCtx(ssl, NULL); - AssertNull(wolfSSL_GetDhAgreeCtx(ssl)); + ExpectNull(wolfSSL_GetDhAgreeCtx(ssl)); ret = wolfSSL_SetTmpDH_file(ssl, dhParamFile, WOLFSSL_FILETYPE_PEM); if (ret != WOLFSSL_SUCCESS && ret != SIDE_ERROR) { - AssertIntEQ(ret, WOLFSSL_SUCCESS); + ExpectIntEQ(ret, WOLFSSL_SUCCESS); } + return EXPECT_RESULT(); } #endif static int test_DhCallbacks(void) { int res = TEST_SKIPPED; -#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && !defined(NO_RSA) && \ - !defined(NO_WOLFSSL_CLIENT) && !defined(NO_DH) && \ +#if !defined(NO_FILESYSTEM) && !defined(NO_DH) && \ !defined(NO_AES) && defined(HAVE_AES_CBC) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) && !defined(SINGLE_THREADED) - WOLFSSL_CTX *ctx; - WOLFSSL *ssl; - tcp_ready ready; - func_args server_args; - func_args client_args; - THREAD_TYPE serverThread; - callback_functions func_cb_client; - callback_functions func_cb_server; + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; int test; + test_ssl_cbf func_cb_client; + test_ssl_cbf func_cb_server; -#ifndef NO_WOLFSSL_CLIENT - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); -#else - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); -#endif - - AssertIntEQ(wolfSSL_CTX_set_cipher_list(NULL, "NONE"), WOLFSSL_FAILURE); - + /* Test that DH callback APIs work. */ + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_set_cipher_list(NULL, "NONE"), WOLFSSL_FAILURE); wolfSSL_CTX_SetDhAgreeCb(ctx, &my_DhCallback); - /* load client ca cert */ - AssertIntEQ(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0), + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0), WOLFSSL_SUCCESS); - /* test with NULL arguments */ wolfSSL_SetDhAgreeCtx(NULL, &test); - AssertNull(wolfSSL_GetDhAgreeCtx(NULL)); - + ExpectNull(wolfSSL_GetDhAgreeCtx(NULL)); /* test success case */ test = 1; - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ssl = wolfSSL_new(ctx)); wolfSSL_SetDhAgreeCtx(ssl, &test); - AssertIntEQ(*((int*)wolfSSL_GetDhAgreeCtx(ssl)), test); - + ExpectIntEQ(*((int*)wolfSSL_GetDhAgreeCtx(ssl)), test); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - /* test a connection where callback is used */ -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - XMEMSET(&server_args, 0, sizeof(func_args)); - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&func_cb_client, 0, sizeof(callback_functions)); - XMEMSET(&func_cb_server, 0, sizeof(callback_functions)); - - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif - server_args.signal = &ready; - client_args.signal = &ready; - server_args.return_code = TEST_FAIL; - client_args.return_code = TEST_FAIL; + XMEMSET(&func_cb_client, 0, sizeof(func_cb_client)); + XMEMSET(&func_cb_server, 0, sizeof(func_cb_server)); /* set callbacks to use DH functions */ func_cb_client.ctx_ready = &test_dh_ctx_setup; func_cb_client.ssl_ready = &test_dh_ssl_setup; -#ifndef WOLFSSL_NO_TLS12 func_cb_client.method = wolfTLSv1_2_client_method; -#else - func_cb_client.method = wolfTLSv1_3_client_method; -#endif - client_args.callbacks = &func_cb_client; func_cb_server.ctx_ready = &test_dh_ctx_setup; func_cb_server.ssl_ready = &test_dh_ssl_setup; -#ifndef WOLFSSL_NO_TLS12 func_cb_server.method = wolfTLSv1_2_server_method; -#else - func_cb_server.method = wolfTLSv1_3_server_method; -#endif - server_args.callbacks = &func_cb_server; - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, + &func_cb_server, NULL), TEST_SUCCESS); - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); - - FreeTcpReady(&ready); - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - /* now set user ctx to not be 1 so that the callback returns fail case */ -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - XMEMSET(&server_args, 0, sizeof(func_args)); - XMEMSET(&client_args, 0, sizeof(func_args)); + /* Test fail */ XMEMSET(&func_cb_client, 0, sizeof(callback_functions)); XMEMSET(&func_cb_server, 0, sizeof(callback_functions)); - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif - - server_args.signal = &ready; - client_args.signal = &ready; - server_args.return_code = TEST_FAIL; - client_args.return_code = TEST_FAIL; - /* set callbacks to use DH functions */ func_cb_client.ctx_ready = &test_dh_ctx_setup; func_cb_client.ssl_ready = &test_dh_ssl_setup_fail; -#ifndef WOLFSSL_NO_TLS12 func_cb_client.method = wolfTLSv1_2_client_method; -#else - func_cb_client.method = wolfTLSv1_3_client_method; -#endif - client_args.callbacks = &func_cb_client; func_cb_server.ctx_ready = &test_dh_ctx_setup; func_cb_server.ssl_ready = &test_dh_ssl_setup_fail; -#ifndef WOLFSSL_NO_TLS12 func_cb_server.method = wolfTLSv1_2_server_method; -#else - func_cb_server.method = wolfTLSv1_3_server_method; -#endif - server_args.callbacks = &func_cb_server; - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, NULL); - join_thread(serverThread); - - AssertIntEQ(client_args.return_code, TEST_FAIL); - AssertIntEQ(server_args.return_code, TEST_FAIL); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, + &func_cb_server, NULL), TEST_FAIL); - FreeTcpReady(&ready); - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -61379,7 +61541,7 @@ static int test_wolfSSL_dtls_plaintext(void) return TEST_FAIL; } - return TEST_SUCCESS; + return TEST_RES_CHECK(1); } #else static int test_wolfSSL_dtls_plaintext(void) { @@ -62467,89 +62629,58 @@ static int test_various_pathlen_chains(void) } #endif /* !NO_RSA && !NO_SHA && !NO_FILESYSTEM && !NO_CERTS */ -#if defined(HAVE_KEYING_MATERIAL) && defined(HAVE_IO_TESTS_DEPENDENCIES) +#if defined(HAVE_KEYING_MATERIAL) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) static int test_export_keying_material_cb(WOLFSSL_CTX *ctx, WOLFSSL *ssl) { + EXPECT_DECLS; byte ekm[100] = {0}; (void)ctx; /* Succes Cases */ - AssertIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), "Test label", XSTR_SIZEOF("Test label"), NULL, 0, 0), 1); - AssertIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), "Test label", XSTR_SIZEOF("Test label"), NULL, 0, 1), 1); /* Use some random context */ - AssertIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), "Test label", XSTR_SIZEOF("Test label"), ekm, 10, 1), 1); /* Failure cases */ - AssertIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), "client finished", XSTR_SIZEOF("client finished"), NULL, 0, 0), 0); - AssertIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), "server finished", XSTR_SIZEOF("server finished"), NULL, 0, 0), 0); - AssertIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), "master secret", XSTR_SIZEOF("master secret"), NULL, 0, 0), 0); - AssertIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), - "extended master secret", XSTR_SIZEOF("extended master secret"), NULL, 0, 0), 0); - AssertIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + "extended master secret", XSTR_SIZEOF("extended master secret"), + NULL, 0, 0), 0); + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), "key expansion", XSTR_SIZEOF("key expansion"), NULL, 0, 0), 0); - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } -static void test_export_keying_material_ssl_cb(WOLFSSL* ssl) +static int test_export_keying_material_ssl_cb(WOLFSSL* ssl) { wolfSSL_KeepArrays(ssl); + return TEST_SUCCESS; } static int test_export_keying_material(void) { - int res = TEST_SKIPPED; -#ifndef SINGLE_THREADED - tcp_ready ready; - callback_functions clientCb; - func_args client_args; - func_args server_args; - THREAD_TYPE serverThread; - - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - XMEMSET(&clientCb, 0, sizeof(callback_functions)); -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - StartTCP(); - InitTcpReady(&ready); - -#if defined(USE_WINDOWS_API) - /* use RNG to get random port if using windows */ - ready.port = GetRandomPort(); -#endif + EXPECT_DECLS; + test_ssl_cbf serverCb; + test_ssl_cbf clientCb; - server_args.signal = &ready; - client_args.signal = &ready; + XMEMSET(&serverCb, 0, sizeof(serverCb)); + XMEMSET(&clientCb, 0, sizeof(clientCb)); clientCb.ssl_ready = test_export_keying_material_ssl_cb; - client_args.callbacks = &clientCb; - start_thread(test_server_nofail, &server_args, &serverThread); - wait_tcp_ready(&server_args); - test_client_nofail(&client_args, test_export_keying_material_cb); - join_thread(serverThread); - - AssertTrue(client_args.return_code); - AssertTrue(server_args.return_code); - - FreeTcpReady(&ready); - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - res = TEST_RES_CHECK(1); -#endif /* !SINGLE_THREADED */ + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&clientCb, + &serverCb, test_export_keying_material_cb), TEST_SUCCESS); - return res; + return EXPECT_RESULT(); } #endif /* HAVE_KEYING_MATERIAL */ @@ -65462,21 +65593,24 @@ static int test_prioritize_psk(void) #endif #if defined(WOLFSSL_TLS13) && defined(OPENSSL_EXTRA) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_AESGCM) && \ + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && defined(HAVE_AESGCM) && \ !defined(NO_SHA256) && defined(WOLFSSL_AES_128) && \ !defined(WOLFSSL_NO_TLS12) -static void test_wolfSSL_CTX_set_ciphersuites_ctx_ready_server(WOLFSSL_CTX* ctx) +static int test_wolfSSL_CTX_set_ciphersuites_ctx_ready_server(WOLFSSL_CTX* ctx) { - AssertTrue(SSL_CTX_set_cipher_list(ctx, "DEFAULT")); + EXPECT_DECLS; + ExpectTrue(SSL_CTX_set_cipher_list(ctx, "DEFAULT")); /* Set TLS 1.3 specific suite */ - AssertTrue(SSL_CTX_set_ciphersuites(ctx, "TLS13-AES128-GCM-SHA256")); + ExpectTrue(SSL_CTX_set_ciphersuites(ctx, "TLS13-AES128-GCM-SHA256")); + return EXPECT_RESULT(); } static int test_wolfSSL_CTX_set_ciphersuites(void) { + EXPECT_DECLS; /* Test using SSL_CTX_set_cipher_list and SSL_CTX_set_ciphersuites and then * do a 1.2 connection. */ - callback_functions client_cbs, server_cbs; + test_ssl_cbf client_cbs, server_cbs; XMEMSET(&client_cbs, 0, sizeof(client_cbs)); XMEMSET(&server_cbs, 0, sizeof(server_cbs)); @@ -65486,12 +65620,10 @@ static int test_wolfSSL_CTX_set_ciphersuites(void) server_cbs.ctx_ready = test_wolfSSL_CTX_set_ciphersuites_ctx_ready_server; - test_wolfSSL_client_server_nofail(&client_cbs, &server_cbs); - - AssertIntEQ(client_cbs.return_code, TEST_SUCCESS); - AssertIntEQ(server_cbs.return_code, TEST_SUCCESS); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbs, + &server_cbs, NULL), TEST_SUCCESS); - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } #else static int test_wolfSSL_CTX_set_ciphersuites(void) @@ -65501,23 +65633,27 @@ static int test_wolfSSL_CTX_set_ciphersuites(void) #endif #if defined(HAVE_CRL) && defined(WOLFSSL_CHECK_ALERT_ON_ERR) && \ - defined(HAVE_IO_TESTS_DEPENDENCIES) -static void test_wolfSSL_CRL_CERT_REVOKED_alert_ctx_ready(WOLFSSL_CTX* ctx) + defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) +static int test_wolfSSL_CRL_CERT_REVOKED_alert_ctx_ready(WOLFSSL_CTX* ctx) { wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + return TEST_SUCCESS; } -static void test_wolfSSL_CRL_CERT_REVOKED_alert_on_cleanup(WOLFSSL* ssl) +static int test_wolfSSL_CRL_CERT_REVOKED_alert_on_cleanup(WOLFSSL* ssl) { + EXPECT_DECLS; WOLFSSL_ALERT_HISTORY h; - AssertIntEQ(wolfSSL_get_alert_history(ssl, &h), WOLFSSL_SUCCESS); - AssertIntEQ(h.last_rx.level, alert_fatal); - AssertIntEQ(h.last_rx.code, certificate_revoked); + ExpectIntEQ(wolfSSL_get_alert_history(ssl, &h), WOLFSSL_SUCCESS); + ExpectIntEQ(h.last_rx.level, alert_fatal); + ExpectIntEQ(h.last_rx.code, certificate_revoked); + return EXPECT_RESULT(); } static int test_wolfSSL_CRL_CERT_REVOKED_alert(void) { - callback_functions client_cbs, server_cbs; + EXPECT_DECLS; + test_ssl_cbf client_cbs, server_cbs; XMEMSET(&client_cbs, 0, sizeof(client_cbs)); XMEMSET(&server_cbs, 0, sizeof(server_cbs)); @@ -65529,13 +65665,10 @@ static int test_wolfSSL_CRL_CERT_REVOKED_alert(void) client_cbs.ctx_ready = test_wolfSSL_CRL_CERT_REVOKED_alert_ctx_ready; server_cbs.on_cleanup = test_wolfSSL_CRL_CERT_REVOKED_alert_on_cleanup; - test_wolfSSL_client_server_nofail(&client_cbs, &server_cbs); - - AssertIntEQ(client_cbs.return_code, TEST_FAIL); - AssertIntEQ(server_cbs.return_code, TEST_FAIL); - - return TEST_RES_CHECK(1); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbs, + &server_cbs, NULL), TEST_FAIL); + return EXPECT_RESULT(); } #else static int test_wolfSSL_CRL_CERT_REVOKED_alert(void) @@ -65545,7 +65678,7 @@ static int test_wolfSSL_CRL_CERT_REVOKED_alert(void) #endif #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) \ - && defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_AESGCM) && \ + && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) && defined(HAVE_AESGCM) && \ !defined(NO_SHA256) && defined(WOLFSSL_AES_128) && \ defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256) && \ !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) @@ -65554,60 +65687,66 @@ static WOLFSSL_CTX* test_TLS_13_ticket_different_ciphers_ctx = NULL; static WOLFSSL_SESSION* test_TLS_13_ticket_different_ciphers_session = NULL; static int test_TLS_13_ticket_different_ciphers_run = 0; -static void test_TLS_13_ticket_different_ciphers_ssl_ready(WOLFSSL* ssl) +static int test_TLS_13_ticket_different_ciphers_ssl_ready(WOLFSSL* ssl) { + EXPECT_DECLS; switch (test_TLS_13_ticket_different_ciphers_run) { case 0: /* First run */ - AssertIntEQ(wolfSSL_set_cipher_list(ssl, "TLS13-AES128-GCM-SHA256"), - WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set_cipher_list(ssl, "TLS13-AES128-GCM-SHA256"), + WOLFSSL_SUCCESS); if (wolfSSL_is_server(ssl)) { - AssertNotNull(test_TLS_13_ticket_different_ciphers_ctx = + ExpectNotNull(test_TLS_13_ticket_different_ciphers_ctx = wolfSSL_get_SSL_CTX(ssl)); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_up_ref(test_TLS_13_ticket_different_ciphers_ctx)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_up_ref( + test_TLS_13_ticket_different_ciphers_ctx)); } break; case 1: /* Second run */ - AssertIntEQ(wolfSSL_set_cipher_list(ssl, "TLS13-AES256-GCM-SHA384:" + ExpectIntEQ(wolfSSL_set_cipher_list(ssl, "TLS13-AES256-GCM-SHA384:" "TLS13-AES128-GCM-SHA256"), WOLFSSL_SUCCESS); if (!wolfSSL_is_server(ssl)) { - AssertIntEQ(wolfSSL_set_session(ssl, - test_TLS_13_ticket_different_ciphers_session), - WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set_session(ssl, + test_TLS_13_ticket_different_ciphers_session), + WOLFSSL_SUCCESS); } break; default: /* Bad state? */ Fail(("Should not enter here"), ("Should not enter here")); } + + return EXPECT_RESULT(); } -static void test_TLS_13_ticket_different_ciphers_on_result(WOLFSSL* ssl) +static int test_TLS_13_ticket_different_ciphers_on_result(WOLFSSL* ssl) { + EXPECT_DECLS; switch (test_TLS_13_ticket_different_ciphers_run) { case 0: /* First run */ - AssertNotNull(test_TLS_13_ticket_different_ciphers_session = + ExpectNotNull(test_TLS_13_ticket_different_ciphers_session = wolfSSL_get1_session(ssl)); break; case 1: /* Second run */ - AssertTrue(wolfSSL_session_reused(ssl)); + ExpectTrue(wolfSSL_session_reused(ssl)); break; default: /* Bad state? */ Fail(("Should not enter here"), ("Should not enter here")); } + return EXPECT_RESULT(); } static int test_TLS_13_ticket_different_ciphers(void) { + EXPECT_DECLS; /* Check that we handle the connection when the ticket doesn't match * the first ciphersuite. */ - callback_functions client_cbs, server_cbs; + test_ssl_cbf client_cbs, server_cbs; struct test_params { method_provider client_meth; method_provider server_meth; @@ -65639,19 +65778,15 @@ static int test_TLS_13_ticket_different_ciphers(void) server_cbs.ticNoInit = 1; - test_wolfSSL_client_server_nofail(&client_cbs, &server_cbs); - - AssertTrue(client_cbs.return_code); - AssertTrue(server_cbs.return_code); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbs, + &server_cbs, NULL), TEST_SUCCESS); test_TLS_13_ticket_different_ciphers_run++; server_cbs.ctx = test_TLS_13_ticket_different_ciphers_ctx; - test_wolfSSL_client_server_nofail(&client_cbs, &server_cbs); - - AssertTrue(client_cbs.return_code); - AssertTrue(server_cbs.return_code); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbs, + &server_cbs, NULL), TEST_SUCCESS); wolfSSL_SESSION_free(test_TLS_13_ticket_different_ciphers_session); test_TLS_13_ticket_different_ciphers_session = NULL; @@ -65659,7 +65794,7 @@ static int test_TLS_13_ticket_different_ciphers(void) test_TLS_13_ticket_different_ciphers_ctx = NULL; } - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } #else static int test_TLS_13_ticket_different_ciphers(void) @@ -66057,7 +66192,7 @@ static int test_harden_no_secure_renegotiation(void) } #endif -#if defined(HAVE_OCSP) && defined(HAVE_IO_TESTS_DEPENDENCIES) +#if defined(HAVE_OCSP) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) static int test_override_alt_cert_chain_cert_cb(int preverify, WOLFSSL_X509_STORE_CTX* store) { @@ -66097,41 +66232,48 @@ static int test_override_alt_cert_chain_ocsp_cb(void* ioCtx, const char* url, return -1; } -static void test_override_alt_cert_chain_client_ctx_ready(WOLFSSL_CTX* ctx) +static int test_override_alt_cert_chain_client_ctx_ready(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, test_override_alt_cert_chain_cert_cb); - AssertIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_CHECKALL | + ExpectIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_CHECKALL | WOLFSSL_OCSP_URL_OVERRIDE), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_SetOCSP_Cb(ctx, + ExpectIntEQ(wolfSSL_CTX_SetOCSP_Cb(ctx, test_override_alt_cert_chain_ocsp_cb, NULL, NULL), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_SetOCSP_OverrideURL(ctx, "not a url"), + ExpectIntEQ(wolfSSL_CTX_SetOCSP_OverrideURL(ctx, "not a url"), WOLFSSL_SUCCESS); + return EXPECT_RESULT(); } -static void test_override_alt_cert_chain_client_ctx_ready2(WOLFSSL_CTX* ctx) +static int test_override_alt_cert_chain_client_ctx_ready2(WOLFSSL_CTX* ctx) { + EXPECT_DECLS; wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); - AssertIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_CHECKALL | + ExpectIntEQ(wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_CHECKALL | WOLFSSL_OCSP_URL_OVERRIDE), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_SetOCSP_Cb(ctx, + ExpectIntEQ(wolfSSL_CTX_SetOCSP_Cb(ctx, test_override_alt_cert_chain_ocsp_cb, NULL, NULL), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_SetOCSP_OverrideURL(ctx, "not a url"), + ExpectIntEQ(wolfSSL_CTX_SetOCSP_OverrideURL(ctx, "not a url"), WOLFSSL_SUCCESS); + return EXPECT_RESULT(); } -static void test_override_alt_cert_chain_server_ctx_ready(WOLFSSL_CTX* ctx) +static int test_override_alt_cert_chain_server_ctx_ready(WOLFSSL_CTX* ctx) { - AssertIntEQ(wolfSSL_CTX_use_certificate_chain_file(ctx, + EXPECT_DECLS; + ExpectIntEQ(wolfSSL_CTX_use_certificate_chain_file(ctx, "./certs/intermediate/server-chain-alt.pem"), WOLFSSL_SUCCESS); + return EXPECT_RESULT(); } static int test_override_alt_cert_chain(void) { + EXPECT_DECLS; size_t i; struct test_params { - ctx_callback client_ctx_cb; - ctx_callback server_ctx_cb; + ctx_cb client_ctx_cb; + ctx_cb server_ctx_cb; int result; } params[] = { {test_override_alt_cert_chain_client_ctx_ready, @@ -66141,7 +66283,7 @@ static int test_override_alt_cert_chain(void) }; for (i = 0; i < sizeof(params)/sizeof(*params); i++) { - callback_functions client_cbs, server_cbs; + test_ssl_cbf client_cbs, server_cbs; XMEMSET(&client_cbs, 0, sizeof(client_cbs)); XMEMSET(&server_cbs, 0, sizeof(server_cbs)); @@ -66150,13 +66292,14 @@ static int test_override_alt_cert_chain(void) client_cbs.ctx_ready = params[i].client_ctx_cb; server_cbs.ctx_ready = params[i].server_ctx_cb; - test_wolfSSL_client_server_nofail(&client_cbs, &server_cbs); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbs, + &server_cbs, NULL), params[i].result); - AssertIntEQ(client_cbs.return_code, params[i].result); - AssertIntEQ(server_cbs.return_code, params[i].result); + ExpectIntEQ(client_cbs.return_code, params[i].result); + ExpectIntEQ(server_cbs.return_code, params[i].result); } - return TEST_RES_CHECK(1); + return EXPECT_RESULT(); } #else static int test_override_alt_cert_chain(void) @@ -66483,12 +66626,13 @@ static int test_dtls_ipv6_check(void) static int test_wolfSSL_configure_args(void) { + int res = TEST_SKIPPED; #if defined(LIBWOLFSSL_CONFIGURE_ARGS) && defined(HAVE_WC_INTROSPECTION) - AssertNotNull(wolfSSL_configure_args()); - return TEST_SUCCESS; -#else - return TEST_SKIPPED; + EXPECT_DECLS; + ExpectNotNull(wolfSSL_configure_args()); + res = EXPECT_RESULT(); #endif + return res; } /*----------------------------------------------------------------------------* | Main @@ -66637,8 +66781,8 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_URI), TEST_DECL(test_wolfSSL_TBS), TEST_DECL(test_wolfSSL_X509_verify), - /* Uses Assert in handshake callback. */ - TEST_DECL(test_wolfSSL_X509_TLS_version), + TEST_DECL(test_wolfSSL_X509_TLS_version_test_1), + TEST_DECL(test_wolfSSL_X509_TLS_version_test_2), TEST_DECL(test_wc_PemToDer), TEST_DECL(test_wc_AllocDer), @@ -66690,7 +66834,6 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_ASN1_TYPE), TEST_DECL(test_wolfSSL_IMPLEMENT_ASN1_FUNCTIONS), - /* Converted above to use Expect unless where stated. */ /* compatibility tests */ TEST_DECL(test_wolfSSL_lhash), TEST_DECL(test_wolfSSL_X509_NAME), @@ -66707,11 +66850,10 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_DES), TEST_DECL(test_wolfSSL_certs), TEST_DECL(test_wolfSSL_X509_check_private_key), + TEST_DECL(test_wolfSSL_private_keys), TEST_DECL(test_wolfSSL_PEM_read_PrivateKey), -#ifndef NO_BIO TEST_DECL(test_wolfSSL_PEM_read_RSA_PUBKEY), -#endif TEST_DECL(test_wolfSSL_PEM_read_PUBKEY), TEST_DECL(test_wolfSSL_PEM_PrivateKey), TEST_DECL(test_wolfSSL_PEM_file_RSAKey), @@ -66723,9 +66865,11 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_PEM_bio_RSAPrivateKey), TEST_DECL(test_wolfSSL_PEM_PUBKEY), #endif + TEST_DECL(test_DSA_do_sign_verify), TEST_DECL(test_wolfSSL_tmp_dh), TEST_DECL(test_wolfSSL_ctrl), + TEST_DECL(test_wolfSSL_EVP_MD_size), TEST_DECL(test_wolfSSL_EVP_MD_pkey_type), TEST_DECL(test_wolfSSL_EVP_Digest), @@ -66761,11 +66905,14 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_set1_curves_list), TEST_DECL(test_wolfSSL_set1_sigalgs_list), TEST_DECL(test_wolfSSL_PKCS7_certs), + /* Converted above to use Expect unless where stated. */ TEST_DECL(test_wolfSSL_X509_STORE_CTX), TEST_DECL(test_wolfSSL_X509_STORE_CTX_trusted_stack_cleanup), TEST_DECL(test_wolfSSL_X509_STORE_CTX_get0_current_issuer), TEST_DECL(test_wolfSSL_msgCb), + /* Converted to use Expect. */ TEST_DECL(test_wolfSSL_either_side), + /* Converted to use Expect. */ TEST_DECL(test_wolfSSL_DTLS_either_side), TEST_DECL(test_wolfSSL_dtls_fragments), TEST_DECL(test_wolfSSL_dtls_AEAD_limit), @@ -66820,7 +66967,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_X509_sign2), TEST_DECL(test_wolfSSL_X509_get0_tbs_sigalg), TEST_DECL(test_wolfSSL_X509_ALGOR_get0), -#if defined(OPENSSL_EXTRA) && defined(HAVE_IO_TESTS_DEPENDENCIES) +#if defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) TEST_DECL(test_wolfSSL_check_domain), #endif TEST_DECL(test_wolfSSL_X509_get_X509_PUBKEY), @@ -66882,8 +67029,11 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_BIO_tls), TEST_DECL(test_wolfSSL_BIO_reset), #endif + + /* Converted to use Expect. */ TEST_DECL(test_wolfSSL_cert_cb), TEST_DECL(test_wolfSSL_SESSION), + /* Converted to use Expect. */ TEST_DECL(test_wolfSSL_CTX_sess_set_remove_cb), TEST_DECL(test_wolfSSL_ticket_keys), TEST_DECL(test_wolfSSL_DES_ecb_encrypt), @@ -67159,12 +67309,13 @@ TEST_CASE testCases[] = { TEST_DECL(test_RsaSigFailure_cm), #endif /* NO_CERTS */ -#if defined(HAVE_PK_CALLBACKS) && (!defined(WOLFSSL_NO_TLS12) || \ - !defined(NO_OLD_TLS)) +#if defined(HAVE_PK_CALLBACKS) && !defined(WOLFSSL_NO_TLS12) + /* Converted to use Expect. */ TEST_DECL(test_DhCallbacks), #endif -#if defined(HAVE_KEYING_MATERIAL) && defined(HAVE_IO_TESTS_DEPENDENCIES) +#if defined(HAVE_KEYING_MATERIAL) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) + /* Converted to use Expect. */ TEST_DECL(test_export_keying_material), #endif @@ -67524,8 +67675,11 @@ TEST_CASE testCases[] = { #endif /* ! NO_RSA */ #endif /* defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_TLS12) && \ * !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) */ + /* Converted to use Expect. */ TEST_DECL(test_wolfSSL_CTX_set_ciphersuites), + /* Converted to use Expect. */ TEST_DECL(test_wolfSSL_CRL_CERT_REVOKED_alert), + /* Converted to use Expect. */ TEST_DECL(test_TLS_13_ticket_different_ciphers), TEST_DECL(test_WOLFSSL_dtls_version_alert), TEST_DECL(test_ForceZero), @@ -67546,6 +67700,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_extra_alerts_skip_hs), TEST_DECL(test_extra_alerts_bad_psk), TEST_DECL(test_harden_no_secure_renegotiation), + /* Converted to use Expect. */ TEST_DECL(test_override_alt_cert_chain), TEST_DECL(test_dtls13_bad_epoch_ch), TEST_DECL(test_wolfSSL_dtls13_null_cipher), diff --git a/wolfcrypt/src/pkcs7.c b/wolfcrypt/src/pkcs7.c index c301cf7eba9..ce7d77c981f 100644 --- a/wolfcrypt/src/pkcs7.c +++ b/wolfcrypt/src/pkcs7.c @@ -1085,6 +1085,12 @@ int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) /* create new Pkcs7Cert for recipient, freed during cleanup */ cert = (Pkcs7Cert*)XMALLOC(sizeof(Pkcs7Cert), pkcs7->heap, DYNAMIC_TYPE_PKCS7); + if (cert == NULL) { +#ifdef WOLFSSL_SMALL_STACK + XFREE(dCert, pkcs7->heap, DYNAMIC_TYPE_DCERT); +#endif + return MEMORY_E; + } XMEMSET(cert, 0, sizeof(Pkcs7Cert)); cert->der = derCert; cert->derSz = derCertSz; diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index 7b387e1515d..c451e8f7f44 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -77,8 +77,8 @@ #include #endif +#include #if defined(USE_WOLFSSL_MEMORY) && defined(WOLFSSL_TRACK_MEMORY) - #include #include #endif diff --git a/wolfssl/wolfcrypt/asn.h b/wolfssl/wolfcrypt/asn.h index 78bff4e196a..24d8362c8b7 100644 --- a/wolfssl/wolfcrypt/asn.h +++ b/wolfssl/wolfcrypt/asn.h @@ -1289,7 +1289,7 @@ enum KeyIdType { }; #endif -#ifdef WOLFSSL_CERT_REQ +#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL) enum CsrAttrType { UNSTRUCTURED_NAME_OID = 654, PKCS9_CONTENT_TYPE_OID = 655, From bdf2186976dd9f94d9ccd802711e7987ea395151 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 1 Jun 2023 11:12:27 -0500 Subject: [PATCH 347/391] wolfssl/wolfcrypt/types.h: conditionalize XASM_LINK() definition on !FIPS_VERSION_LT(5,3) and !WOLFSSL_NO_ASM. --- wolfssl/wolfcrypt/types.h | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 6a11c44b77e..87c0d152bc3 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -1180,8 +1180,16 @@ typedef struct w64wrapper { /* invalid device id */ #define INVALID_DEVID (-2) - #ifdef XASM_LINK + #if defined(HAVE_FIPS) && FIPS_VERSION_LT(5,3) + #ifdef XASM_LINK + #error User-supplied XASM_LINK is not compatible with this FIPS version. + #else + /* use version in FIPS <=5.2 aes.c */ + #endif + #elif defined(XASM_LINK) /* keep user-supplied definition */ + #elif defined(WOLFSSL_NO_ASM) + #define XASM_LINK(f) #elif defined(_MSC_VER) #define XASM_LINK(f) #elif defined(__APPLE__) From 4118256f14364a273690409b6db69782a9df1422 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Fri, 2 Jun 2023 11:06:16 -0500 Subject: [PATCH 348/391] tests/api.c: fixes for clang-diagnostic-embedded-directive (also warned by gcc), clang-analyzer-core.UndefinedBinaryOperatorResult, and clang-analyzer-deadcode.DeadStores. --- tests/api.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/tests/api.c b/tests/api.c index 1e2435a72aa..ff722901f8a 100644 --- a/tests/api.c +++ b/tests/api.c @@ -4652,10 +4652,12 @@ static int test_wolfSSL_EVP_EncodeUpdate(void) ); ExpectIntEQ(outl,0); + if (EXPECT_SUCCESS()) { EVP_EncodeFinal( ctx, encOutBuff + outl, &outl); + } ExpectIntEQ( outl, sizeof(enc0)-1); ExpectIntEQ( @@ -5014,10 +5016,12 @@ static int test_wolfSSL_EVP_DecodeUpdate(void) ExpectIntEQ(EVP_DecodeFinal(ctx,decOutBuff + outl, NULL), -1); ExpectIntEQ(EVP_DecodeFinal(NULL,NULL, NULL), -1); - EVP_DecodeFinal( - ctx, - decOutBuff + outl, - &outl); + if (EXPECT_SUCCESS()) { + EVP_DecodeFinal( + ctx, + decOutBuff + outl, + &outl); + } ExpectIntEQ( outl, 0); ExpectIntEQ( @@ -11616,14 +11620,13 @@ static int test_wolfSSL_X509_TLS_version_test_1(void) func_cb_server.method = wolfTLSv1_3_server_method; #endif - ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, - &func_cb_server, NULL), #ifndef OPENSSL_COMPATIBLE_DEFAULTS - TEST_FAIL + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, + &func_cb_server, NULL), TEST_FAIL); #else - TEST_SUCCESS + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&func_cb_client, + &func_cb_server, NULL), TEST_SUCCESS); #endif - ); res = EXPECT_RESULT(); #endif @@ -37189,6 +37192,7 @@ static int test_wolfSSL_EVP_PKEY_new_mac_key(void) /* Allocation for key->pkey.ptr may fail - OK key len is 0 */ checkPw = wolfSSL_EVP_PKEY_get0_hmac(key, &checkPwSz); } + ExpectTrue((checkPwSz == 0) || (checkPw != NULL)); ExpectIntEQ((int)checkPwSz, 0); wolfSSL_EVP_PKEY_free(key); key = NULL; @@ -37200,6 +37204,7 @@ static int test_wolfSSL_EVP_PKEY_new_mac_key(void) /* Allocation for key->pkey.ptr may fail - OK key len is 0 */ checkPw = wolfSSL_EVP_PKEY_get0_hmac(key, &checkPwSz); } + ExpectTrue((checkPwSz == 0) || (checkPw != NULL)); ExpectIntEQ((int)checkPwSz, 0); wolfSSL_EVP_PKEY_free(key); key = NULL; From 11338a048b94654396158bc32232ef49cf5b2fb8 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Fri, 2 Jun 2023 10:09:12 -0600 Subject: [PATCH 349/391] Read and assign err return val from _sp_mulmod_tmp --- wolfcrypt/src/sp_int.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index f5da4780e3d..91dc3b1d8fc 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -11736,7 +11736,7 @@ static int _sp_mulmod(const sp_int* a, const sp_int* b, const sp_int* m, } else { /* Do operation using temporary. */ - _sp_mulmod_tmp(a, b, m, r); + err = _sp_mulmod_tmp(a, b, m, r); } return err; From adec9bb03e22474374dbcb7c39596006dbf14c2b Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Sat, 3 Jun 2023 10:41:15 -0500 Subject: [PATCH 350/391] tests/api.c: fix a likely-spurious maybe-uninitialized from gcc-11 -m32 (all-sp-m32) in test_wolfSSL_PEM_PrivateKey(). --- tests/api.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/api.c b/tests/api.c index ff722901f8a..fee5eb3e5dd 100644 --- a/tests/api.c +++ b/tests/api.c @@ -36409,7 +36409,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) !defined(HAVE_USER_RSA) && !defined(NO_RSA) { XFILE f = XBADFILE; - wc_pem_password_cb* passwd_cb; + wc_pem_password_cb* passwd_cb = NULL; void* passwd_cb_userdata; SSL_CTX* ctx = NULL; char passwd[] = "bad password"; From d95149a188bb1d19fd9058b61c151a729abf5be2 Mon Sep 17 00:00:00 2001 From: Marco Oliverio Date: Mon, 5 Jun 2023 16:13:11 +0000 Subject: [PATCH 351/391] fix: add guards to compile w !HAVE_SUPPORTED_CURVES && NO_CERTS This configuration can be used to build a static PSK only build --- src/dtls.c | 17 ++++++++++++++++- wolfssl/test.h | 4 ++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/dtls.c b/src/dtls.c index 11de01541bf..d604b5a2fa5 100644 --- a/src/dtls.c +++ b/src/dtls.c @@ -573,6 +573,10 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) XMEMSET(&pskInfo, 0, sizeof(pskInfo)); #endif +#ifndef HAVE_SUPPORTED_CURVES + (void)doKE; +#endif /* !HAVE_SUPPORTED_CURVES */ + XMEMSET(&cs, 0, sizeof(cs)); /* We need to echo the session ID sent by the client */ @@ -602,10 +606,13 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) /* Set that this is a response extension */ parsedExts->resp = 1; +#if defined(HAVE_SUPPORTED_CURVES) ret = TLSX_SupportedCurve_Copy(ssl->extensions, &parsedExts, ssl->heap); if (ret != 0) goto dtls13_cleanup; +#endif +#if !defined(NO_CERTS) /* Signature algs */ ret = FindExtByType(&tlsx, TLSX_SIGNATURE_ALGORITHMS, ch->extension, &tlsxFound); @@ -624,7 +631,9 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) XMEMCPY(suites.hashSigAlgo, sigAlgs.elements, sigAlgs.size); haveSA = 1; } +#endif /* !defined(NO_CERTS) */ +#ifdef HAVE_SUPPORTED_CURVES /* Supported groups */ ret = FindExtByType(&tlsx, TLSX_SUPPORTED_GROUPS, ch->extension, &tlsxFound); @@ -650,6 +659,7 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) goto dtls13_cleanup; haveKS = 1; } +#endif /* HAVE_SUPPORTED_CURVES */ #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) /* Pre-shared key */ @@ -705,6 +715,7 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) ERROR_OUT(INCOMPLETE_DATA, dtls13_cleanup); } +#ifdef HAVE_SUPPORTED_CURVES if (doKE) { byte searched = 0; ret = TLSX_KeyShare_Choose(ssl, parsedExts, &cs.clientKSE, @@ -714,9 +725,10 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) if (cs.clientKSE == NULL && searched) cs.doHelloRetry = 1; } +#endif /* HAVE_SUPPORTED_CURVES */ } else -#endif +#endif /* defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) */ { /* https://datatracker.ietf.org/doc/html/rfc8446#section-9.2 */ if (!haveKS || !haveSA || !haveSG) { @@ -731,6 +743,8 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) ERROR_OUT(INCOMPLETE_DATA, dtls13_cleanup); } } + +#ifdef HAVE_SUPPORTED_CURVES if (cs.doHelloRetry) { ret = TLSX_KeyShare_SetSupported(ssl, &parsedExts); if (ret != 0) @@ -741,6 +755,7 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) * and are not doing curve negotiation. */ TLSX_Remove(&parsedExts, TLSX_KEY_SHARE, ssl->heap); } +#endif /* HAVE_SUPPORTED_CURVES */ /* This is required to correctly generate the hash */ ret = GetCipherSpec(WOLFSSL_SERVER_END, cs.cipherSuite0, diff --git a/wolfssl/test.h b/wolfssl/test.h index 49445bce6c5..fff636302cd 100644 --- a/wolfssl/test.h +++ b/wolfssl/test.h @@ -5430,9 +5430,11 @@ static WC_INLINE int test_memio_setup(struct test_memio_ctx *ctx, *ctx_c = wolfSSL_CTX_new(method_c()); if (*ctx_c == NULL) return -1; +#ifndef NO_CERTS ret = wolfSSL_CTX_load_verify_locations(*ctx_c, caCertFile, 0); if (ret != WOLFSSL_SUCCESS) return -1; +#endif /* NO_CERTS */ wolfSSL_SetIORecv(*ctx_c, test_memio_read_cb); wolfSSL_SetIOSend(*ctx_c, test_memio_write_cb); if (ctx->c_ciphers != NULL) { @@ -5446,6 +5448,7 @@ static WC_INLINE int test_memio_setup(struct test_memio_ctx *ctx, *ctx_s = wolfSSL_CTX_new(method_s()); if (*ctx_s == NULL) return -1; +#ifndef NO_CERTS ret = wolfSSL_CTX_use_PrivateKey_file(*ctx_s, svrKeyFile, WOLFSSL_FILETYPE_PEM); if (ret != WOLFSSL_SUCCESS) @@ -5454,6 +5457,7 @@ static WC_INLINE int test_memio_setup(struct test_memio_ctx *ctx, WOLFSSL_FILETYPE_PEM); if (ret != WOLFSSL_SUCCESS) return -1; +#endif wolfSSL_SetIORecv(*ctx_s, test_memio_read_cb); wolfSSL_SetIOSend(*ctx_s, test_memio_write_cb); if (ctx->s_ciphers != NULL) { From a07420864674640fb77093af3e12b699d1d02805 Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Tue, 23 May 2023 13:51:46 -0600 Subject: [PATCH 352/391] Miscellaneous fixes for sanitizer --- src/internal.c | 6 ++++++ wolfcrypt/src/dh.c | 12 +++++++----- wolfcrypt/src/hmac.c | 2 ++ wolfcrypt/src/sp_int.c | 2 +- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/internal.c b/src/internal.c index e20d2c9c89c..9c08ee7d3ff 100644 --- a/src/internal.c +++ b/src/internal.c @@ -15958,6 +15958,12 @@ static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, return PARSE_ERROR; } + if (size > MAX_HANDSHAKE_SZ) { + WOLFSSL_MSG("Handshake message too large"); + WOLFSSL_ERROR_VERBOSE(HANDSHAKE_SIZE_ERROR); + return HANDSHAKE_SIZE_ERROR; + } + return DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz); } diff --git a/wolfcrypt/src/dh.c b/wolfcrypt/src/dh.c index 4cedcae17dc..f89b552571d 100644 --- a/wolfcrypt/src/dh.c +++ b/wolfcrypt/src/dh.c @@ -2706,11 +2706,13 @@ int wc_DhCmpNamedKey(int name, int noQ, goodName = 0; } - cmp = goodName && (pSz == pCmpSz) && (gSz == gCmpSz) && - (noQ || ((qCmp != NULL) && (qSz == qCmpSz) && - XMEMCMP(q, qCmp, qCmpSz) == 0)) && - (XMEMCMP(p, pCmp, pCmpSz) == 0) && - (XMEMCMP(g, gCmp, gCmpSz) == 0); + if (goodName) { + cmp = (pSz == pCmpSz) && (gSz == gCmpSz) && + (noQ || ((qCmp != NULL) && (qSz == qCmpSz) && + XMEMCMP(q, qCmp, qCmpSz) == 0)) && + (XMEMCMP(p, pCmp, pCmpSz) == 0) && + (XMEMCMP(g, gCmp, gCmpSz) == 0); + } return cmp; } diff --git a/wolfcrypt/src/hmac.c b/wolfcrypt/src/hmac.c index ec8878fd7e8..eecd2b9b998 100644 --- a/wolfcrypt/src/hmac.c +++ b/wolfcrypt/src/hmac.c @@ -1290,6 +1290,8 @@ int wolfSSL_GetHmacMaxSize(void) return ret; } + XMEMSET(tmp, 0, WC_MAX_DIGEST_SIZE); + while (outIdx < outSz) { word32 tmpSz = (n == 1) ? 0 : hashSz; word32 left = outSz - outIdx; diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 91dc3b1d8fc..d5d85cb8d0f 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -17757,7 +17757,7 @@ int sp_tohex(const sp_int* a, char* str) d = a->dp[i]; #ifndef WC_DISABLE_RADIX_ZERO_PAD /* Find highest non-zero byte in most-significant word. */ - for (j = SP_WORD_SIZE - 8; j >= 0; j -= 8) { + for (j = SP_WORD_SIZE - 8; j >= 0 && i>=0; j -= 8) { /* When a byte at this index is not 0 break out to start * writing. */ From 681bdb0bbe3a61262157aabfe7c6ed30c32f608e Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Mon, 5 Jun 2023 16:47:11 -0600 Subject: [PATCH 353/391] Fix formatting --- wolfcrypt/src/sp_int.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index d5d85cb8d0f..85fc455b732 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -17757,7 +17757,7 @@ int sp_tohex(const sp_int* a, char* str) d = a->dp[i]; #ifndef WC_DISABLE_RADIX_ZERO_PAD /* Find highest non-zero byte in most-significant word. */ - for (j = SP_WORD_SIZE - 8; j >= 0 && i>=0; j -= 8) { + for (j = SP_WORD_SIZE - 8; j >= 0 && i >= 0; j -= 8) { /* When a byte at this index is not 0 break out to start * writing. */ From 87b30178c0842ec5c364ac4c4a8ba5f93702a919 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 5 May 2023 11:40:33 +1000 Subject: [PATCH 354/391] Fix type conversion warnings by gcc --- src/pk.c | 248 ++++++++++++++++++---------------- src/ssl_asn1.c | 97 +++++++------ src/ssl_bn.c | 7 +- src/ssl_misc.c | 6 +- wolfcrypt/src/dsa.c | 50 +++---- wolfcrypt/src/eccsi.c | 60 ++++---- wolfcrypt/src/fe_448.c | 6 +- wolfcrypt/src/fe_x25519_128.i | 16 +-- wolfcrypt/src/rsa.c | 20 +-- wolfcrypt/src/sakke.c | 49 ++++--- wolfssl/wolfcrypt/sakke.h | 4 +- 11 files changed, 302 insertions(+), 261 deletions(-) diff --git a/src/pk.c b/src/pk.c index f4665818539..4b4d996716d 100644 --- a/src/pk.c +++ b/src/pk.c @@ -242,20 +242,20 @@ static int der_to_pem_alloc(const unsigned char* der, int derSz, int type, (void)heap; - pemSz = wc_DerToPem(der, derSz, NULL, 0, type); + pemSz = wc_DerToPem(der, (word32)derSz, NULL, 0, type); if (pemSz < 0) { ret = WOLFSSL_FAILURE; } if (ret == WOLFSSL_SUCCESS) { - pem = (byte*)XMALLOC(pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER); + pem = (byte*)XMALLOC((size_t)pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER); if (pem == NULL) { ret = WOLFSSL_FAILURE; } } - if ((ret == WOLFSSL_SUCCESS) && (wc_DerToPem(der, derSz, pem, pemSz, - type) < 0)) { + if ((ret == WOLFSSL_SUCCESS) && (wc_DerToPem(der, (word32)derSz, pem, + (word32)pemSz, type) < 0)) { ret = WOLFSSL_FAILURE; XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER); pem = NULL; @@ -322,7 +322,7 @@ static int der_write_to_file_as_pem(const unsigned char* der, int derSz, ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz); if (ret == WOLFSSL_SUCCESS) { - int len = (int)XFWRITE(pem, 1, pemSz, fp); + int len = (int)XFWRITE(pem, 1, (size_t)pemSz, fp); if (len != pemSz) { WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO"); ret = WOLFSSL_FAILURE; @@ -356,7 +356,7 @@ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, byte *tmpBuf; /* Add space for padding. */ - tmpBuf = (byte*)XREALLOC(der, derSz + blockSz, heap, + tmpBuf = (byte*)XREALLOC(der, (size_t)(derSz + blockSz), heap, DYNAMIC_TYPE_TMP_BUFFER); if (tmpBuf == NULL) { WOLFSSL_ERROR_MSG("Extending DER buffer failed"); @@ -377,7 +377,7 @@ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, if (ret == 1) { /* Calculate PEM encoding size. */ - pemSz = wc_DerToPemEx(der, derSz, NULL, 0, cipherInfo, type); + pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, cipherInfo, type); if (pemSz <= 0) { WOLFSSL_ERROR_MSG("wc_DerToPemEx failed"); ret = 0; @@ -385,7 +385,7 @@ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, } if (ret == 1) { /* Allocate space for PEM encoding plus a NUL terminator. */ - tmp = (byte*)XMALLOC(pemSz + 1, NULL, DYNAMIC_TYPE_KEY); + tmp = (byte*)XMALLOC((size_t)(pemSz + 1), NULL, DYNAMIC_TYPE_KEY); if (tmp == NULL) { WOLFSSL_ERROR_MSG("malloc failed"); ret = 0; @@ -393,7 +393,8 @@ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, } if (ret == 1) { /* DER to PEM */ - pemSz = wc_DerToPemEx(der, derSz, tmp, pemSz, cipherInfo, type); + pemSz = wc_DerToPemEx(der, (word32)derSz, tmp, (word32)pemSz, + cipherInfo, type); if (pemSz <= 0) { WOLFSSL_ERROR_MSG("wc_DerToPemEx failed"); ret = 0; @@ -562,7 +563,7 @@ static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen, if (indent > 0) { /* Print indent spaces. */ - int len_wanted = XSNPRINTF(line, lineLen, "%*s", indent, " "); + int len_wanted = XSNPRINTF(line, (size_t)lineLen, "%*s", indent, " "); if (len_wanted >= lineLen) { WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation"); ret = 0; @@ -651,7 +652,7 @@ static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name, ret = 0; } if (ret == 1) { - rawKey = (byte*)XMALLOC(rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + rawKey = (byte*)XMALLOC((size_t)rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (rawKey == NULL) { WOLFSSL_ERROR_MSG("Memory allocation error"); ret = 0; @@ -697,8 +698,8 @@ static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name, /* Put out each line of numbers. */ for (i = 0; (ret == 1) && (i < rawLen); i++) { /* Encode another byte as 2 hex digits and append colon. */ - int len_wanted = XSNPRINTF(line + li, sizeof(line) - li, "%02x:", - rawKey[i]); + int len_wanted = XSNPRINTF(line + li, sizeof(line) - (size_t)li, + "%02x:", rawKey[i]); /* Check if there was room -- if not, print the current line, not * including the newest octet. */ @@ -760,7 +761,7 @@ static int wolfssl_der_length(const unsigned char* seq, int len) /* Check it is a SEQUENCE and get the length of the underlying data. * i is updated to be after SEQUENCE header bytes. */ - if (GetSequence_ex(seq, &i, &ret, len, 0) >= 0) { + if (GetSequence_ex(seq, &i, &ret, (word32)len, 0) >= 0) { /* Add SEQUENCE header length to underlying data length. */ ret += (int)i; } @@ -814,11 +815,12 @@ WOLFSSL_RSA_METHOD *wolfSSL_RSA_meth_new(const char *name, int flags) meth->dynamic = 1; name_len = (int)XSTRLEN(name); - meth->name = (char*)XMALLOC(name_len + 1, NULL, DYNAMIC_TYPE_OPENSSL); + meth->name = (char*)XMALLOC((size_t)(name_len + 1), NULL, + DYNAMIC_TYPE_OPENSSL); err = (meth->name == NULL); } if (!err) { - XMEMCPY(meth->name, name, name_len+1); + XMEMCPY(meth->name, name, (size_t)(name_len + 1)); } if (err) { @@ -1388,14 +1390,14 @@ static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out) err = 1; } /* Allocate a buffer to read DER data into. */ - if ((!err) && ((der = (unsigned char*)XMALLOC(derLen, bio->heap, + if ((!err) && ((der = (unsigned char*)XMALLOC((size_t)derLen, bio->heap, DYNAMIC_TYPE_TMP_BUFFER)) == NULL)) { WOLFSSL_ERROR_MSG("Malloc failure"); err = 1; } if (!err) { /* Calculate the unread amount. */ - int len = derLen - sizeof(seq); + int len = derLen - (int)sizeof(seq); /* Copy the previously read data into the buffer. */ XMEMCPY(der, seq, sizeof(seq)); /* Read rest of DER data from BIO. */ @@ -1512,6 +1514,7 @@ int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey, * On out, newly allocated buffer or pointer to byte * after encoding in passed in buffer. * @param [in] publicKey Whether to encode as public key. + * @param [in] heap Heap hint. * @return Encoding size on success. * @return Negative on failure. */ @@ -1565,7 +1568,8 @@ static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey, derBuf = *outBuf; if (derBuf == NULL) { /* Allocate buffer to hold DER encoded RSA key. */ - derBuf = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER); + derBuf = (byte*)XMALLOC((size_t)derSz, heap, + DYNAMIC_TYPE_TMP_BUFFER); if (derBuf == NULL) { WOLFSSL_ERROR_MSG("Memory allocation failed"); ret = MEMORY_ERROR; @@ -1573,13 +1577,15 @@ static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey, } } if ((ret == 1) && (outBuf != NULL)) { - if (publicKey) { + if (publicKey > 0) { /* RSA public key to DER. */ - derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf, derSz); + derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf, + (word32)derSz); } else { /* RSA private key to DER. */ - derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf, derSz); + derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf, + (word32)derSz); } if (derSz < 0) { WOLFSSL_ERROR_MSG("RSA key encoding failed"); @@ -1680,11 +1686,11 @@ int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf, /* Decode private or public key data. */ if (opt == WOLFSSL_RSA_LOAD_PRIVATE) { res = wc_RsaPrivateKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal, - derSz); + (word32)derSz); } else { res = wc_RsaPublicKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal, - derSz); + (word32)derSz); } /* Check for error. */ if (res < 0) { @@ -2126,7 +2132,7 @@ int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa, } } /* Write PEM to file pointer. */ - if ((ret == 1) && ((int)XFWRITE(pem, pLen, 1, fp) != 1)) { + if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) { WOLFSSL_ERROR_MSG("RSA private key file write failed"); ret = 0; } @@ -3449,9 +3455,9 @@ int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em, if (ret == 1) { /* Generate RSA PKCS#1 PSS padding for hash using wolfCrypt. */ - if (wc_RsaPad_ex(mHash, hashLen, em, emLen, RSA_BLOCK_TYPE_1, rng, - WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen, - wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) { + if (wc_RsaPad_ex(mHash, (word32)hashLen, em, (word32)emLen, + RSA_BLOCK_TYPE_1, rng, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, + saltLen, wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) { WOLFSSL_ERROR_MSG("wc_RsaPad_ex error"); ret = 0; } @@ -3568,7 +3574,7 @@ int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, if (ret == 1) { /* Allocate buffer to unpad inline with. */ - buf = (byte*)XMALLOC(emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + buf = (byte*)XMALLOC((size_t)emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { WOLFSSL_ERROR_MSG("malloc error"); ret = 0; @@ -3577,11 +3583,11 @@ int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, if (ret == 1) { /* Copy encrypted message to temp for inline unpadding. */ - XMEMCPY(buf, em, emLen); + XMEMCPY(buf, em, (size_t)emLen); /* Remove and verify the PSS padding. */ - mPrimeLen = wc_RsaUnPad_ex(buf, emLen, &mPrime, RSA_BLOCK_TYPE_1, - WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen, + mPrimeLen = wc_RsaUnPad_ex(buf, (word32)emLen, &mPrime, + RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen, wolfSSL_BN_num_bits(rsa->n), NULL); if (mPrimeLen < 0) { WOLFSSL_ERROR_MSG("wc_RsaPad_ex error"); @@ -3591,8 +3597,9 @@ int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, if (ret == 1) { /* Verify the hash is correct. */ - if (wc_RsaPSS_CheckPadding_ex(mHash, hashLen, mPrime, mPrimeLen, - hashType, saltLen, wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) { + if (wc_RsaPSS_CheckPadding_ex(mHash, (word32)hashLen, mPrime, + (word32)mPrimeLen, hashType, saltLen, + wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) { WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error"); ret = 0; } @@ -3647,7 +3654,7 @@ static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash, if ((ret == 1) && (hashAlg != NID_undef) && (padding == RSA_PKCS1_PADDING)) { /* Convert hash algorithm to hash type for PKCS#1.5 padding. */ - hType = nid2oid(hashAlg, oidHashType); + hType = (int)nid2oid(hashAlg, oidHashType); if (hType == -1) { ret = 0; } @@ -3846,7 +3853,7 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, case RSA_PKCS1_PSS_PADDING: { enum wc_HashType hType = - wc_OidGetHash(nid2oid(hashAlg, oidHashType)); + wc_OidGetHash((int)nid2oid(hashAlg, oidHashType)); #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER WOLFSSL_MSG("Using RSA-PSS with hash length salt. " "OpenSSL uses max length by default."); @@ -3999,7 +4006,7 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, /* Decrypt signature */ #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && \ !defined(HAVE_SELFTEST) - hType = wc_OidGetHash(nid2oid(hashAlg, oidHashType)); + hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType)); if ((verLen = wc_RsaSSL_Verify_ex2(sig, sigLen, (unsigned char *)sigDec, sigLen, (RsaKey*)rsa->internal, padding, hType)) <= 0) { WOLFSSL_ERROR_MSG("RSA Decrypt error"); @@ -4018,7 +4025,7 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) if (padding == RSA_PKCS1_PSS_PADDING) { /* Check PSS padding is valid. */ - if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, verLen, + if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen, hType, DEF_PSS_SALT_LEN, mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) { WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error"); @@ -4029,7 +4036,8 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS || * FIPS_VERSION >= 5.1) */ /* Compare decrypted signature to encoded signature. */ - if ((int)len != verLen || XMEMCMP(encodedSig, sigDec, verLen) != 0) { + if (((int)len != verLen) || + (XMEMCMP(encodedSig, sigDec, (size_t)verLen) != 0)) { WOLFSSL_ERROR_MSG("wolfSSL_RSA_verify_ex failed"); ret = 0; } @@ -4145,11 +4153,11 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, if (ret == 0) { /* Use wolfCrypt to public-encrypt with RSA key. */ #if !defined(HAVE_FIPS) - ret = wc_RsaPublicEncrypt_ex(from, len, to, outLen, + ret = wc_RsaPublicEncrypt_ex(from, (word32)len, to, (word32)outLen, (RsaKey*)rsa->internal, rng, pad_type, hash, mgf, NULL, 0); #else - ret = wc_RsaPublicEncrypt(from, len, to, outLen, (RsaKey*)rsa->internal, - rng); + ret = wc_RsaPublicEncrypt(from, (word32)len, to, (word32)outLen, + (RsaKey*)rsa->internal, rng); #endif } @@ -4249,10 +4257,10 @@ int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from, /* Use wolfCrypt to private-decrypt with RSA key. * Size of 'to' buffer must be size of RSA key */ #if !defined(HAVE_FIPS) - ret = wc_RsaPrivateDecrypt_ex(from, len, to, outLen, + ret = wc_RsaPrivateDecrypt_ex(from, (word32)len, to, (word32)outLen, (RsaKey*)rsa->internal, pad_type, hash, mgf, NULL, 0); #else - ret = wc_RsaPrivateDecrypt(from, len, to, outLen, + ret = wc_RsaPrivateDecrypt(from, (word32)len, to, (word32)outLen, (RsaKey*)rsa->internal); #endif } @@ -4334,11 +4342,12 @@ int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from, /* Use wolfCrypt to public-decrypt with RSA key. */ #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) /* Size of 'to' buffer must be size of RSA key. */ - ret = wc_RsaSSL_Verify_ex(from, len, to, outLen, + ret = wc_RsaSSL_Verify_ex(from, (word32)len, to, (word32)outLen, (RsaKey*)rsa->internal, pad_type); #else /* For FIPS v1/v2 only PKCSV15 padding is supported */ - ret = wc_RsaSSL_Verify(from, len, to, outLen, (RsaKey*)rsa->internal); + ret = wc_RsaSSL_Verify(from, (word32)len, to, (word32)outLen, + (RsaKey*)rsa->internal); #endif } @@ -4415,12 +4424,12 @@ int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from, /* Use wolfCrypt to private-encrypt with RSA key. * Size of output buffer must be size of RSA key. */ if (padding == RSA_PKCS1_PADDING) { - ret = wc_RsaSSL_Sign(from, (word32)len, to, wolfSSL_RSA_size(rsa), - (RsaKey*)rsa->internal, rng); + ret = wc_RsaSSL_Sign(from, (word32)len, to, + (word32)wolfSSL_RSA_size(rsa), (RsaKey*)rsa->internal, rng); } #ifdef WC_RSA_NO_PADDING else if (padding == RSA_NO_PADDING) { - word32 outLen = wolfSSL_RSA_size(rsa); + word32 outLen = (word32)wolfSSL_RSA_size(rsa); ret = wc_RsaFunction(from, (word32)len, to, &outLen, RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng); if (ret == 0) @@ -5203,13 +5212,14 @@ WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig, if (DecodeECC_DSA_Sig(*pp, (word32)length, r, s) != 0) { if (length == DSA_160_SIG_SIZE || length == DSA_256_SIG_SIZE) { /* Two raw numbers of length/2 size each */ - if (mp_read_unsigned_bin(r, *pp, (int)length/2) != 0) { + if (mp_read_unsigned_bin(r, *pp, (word32)length/2) != 0) { WOLFSSL_MSG("r mp_read_unsigned_bin error"); wolfSSL_DSA_SIG_free(ret); return NULL; } - if (mp_read_unsigned_bin(s, *pp + (length/2), (int)length/2) != 0) { + if (mp_read_unsigned_bin(s, *pp + (length/2), (word32)length/2) != + 0) { WOLFSSL_MSG("s mp_read_unsigned_bin error"); wolfSSL_DSA_SIG_free(ret); return NULL; @@ -5597,7 +5607,8 @@ int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa, /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */ der_max_len = MAX_DSA_PRIVKEY_SZ; - derBuf = (byte*)XMALLOC(der_max_len, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + derBuf = (byte*)XMALLOC((size_t)der_max_len, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); if (derBuf == NULL) { WOLFSSL_MSG("Malloc failed"); wolfSSL_EVP_PKEY_free(pkey); @@ -5605,7 +5616,7 @@ int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa, } /* convert key to der format */ - derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, der_max_len); + derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len); if (derSz < 0) { WOLFSSL_MSG("wc_DsaKeyToDer failed"); XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -5613,7 +5624,8 @@ int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa, return 0; } - pkey->pkey.ptr = (char*)XMALLOC(derSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + pkey->pkey.ptr = (char*)XMALLOC((size_t)derSz, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); if (pkey->pkey.ptr == NULL) { WOLFSSL_MSG("key malloc failed"); XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -5623,7 +5635,7 @@ int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa, /* add der info to the evp key */ pkey->pkey_sz = derSz; - XMEMCPY(pkey->pkey.ptr, derBuf, derSz); + XMEMCPY(pkey->pkey.ptr, derBuf, (size_t)derSz); XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); ret = wolfSSL_PEM_write_bio_PrivateKey(bio, pkey, cipher, passwd, len, @@ -5701,14 +5713,14 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, der_max_len = MAX_DSA_PRIVKEY_SZ; - derBuf = (byte*)XMALLOC(der_max_len, NULL, DYNAMIC_TYPE_DER); + derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL, DYNAMIC_TYPE_DER); if (derBuf == NULL) { WOLFSSL_MSG("malloc failed"); return 0; } /* Key to DER */ - derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, der_max_len); + derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len); if (derSz < 0) { WOLFSSL_MSG("wc_DsaKeyToDer failed"); XFREE(derBuf, NULL, DYNAMIC_TYPE_DER); @@ -5735,7 +5747,7 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, (int)XSTRLEN(footer) + 1; } - tmp = (byte*)XMALLOC(*pLen, NULL, DYNAMIC_TYPE_PEM); + tmp = (byte*)XMALLOC((size_t)*pLen, NULL, DYNAMIC_TYPE_PEM); if (tmp == NULL) { WOLFSSL_MSG("malloc failed"); XFREE(derBuf, NULL, DYNAMIC_TYPE_DER); @@ -5745,7 +5757,8 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, } /* DER to PEM */ - *pLen = wc_DerToPemEx(derBuf, derSz, tmp, *pLen, cipherInfo, type); + *pLen = wc_DerToPemEx(derBuf, (word32)derSz, tmp, (word32)*pLen, cipherInfo, + type); if (*pLen <= 0) { WOLFSSL_MSG("wc_DerToPemEx failed"); XFREE(derBuf, NULL, DYNAMIC_TYPE_DER); @@ -5758,15 +5771,15 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, if (cipherInfo != NULL) XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING); - *pem = (byte*)XMALLOC((*pLen)+1, NULL, DYNAMIC_TYPE_KEY); + *pem = (byte*)XMALLOC((size_t)((*pLen)+1), NULL, DYNAMIC_TYPE_KEY); if (*pem == NULL) { WOLFSSL_MSG("malloc failed"); XFREE(tmp, NULL, DYNAMIC_TYPE_PEM); return 0; } - XMEMSET(*pem, 0, (*pLen)+1); + XMEMSET(*pem, 0, (size_t)((*pLen)+1)); - if (XMEMCPY(*pem, tmp, *pLen) == NULL) { + if (XMEMCPY(*pem, tmp, (size_t)*pLen) == NULL) { WOLFSSL_MSG("XMEMCPY failed"); XFREE(pem, NULL, DYNAMIC_TYPE_KEY); XFREE(tmp, NULL, DYNAMIC_TYPE_PEM); @@ -5815,7 +5828,7 @@ int wolfSSL_PEM_write_DSAPrivateKey(XFILE fp, WOLFSSL_DSA *dsa, return 0; } - ret = (int)XFWRITE(pem, pLen, 1, fp); + ret = (int)XFWRITE(pem, (size_t)pLen, 1, fp); if (ret != 1) { WOLFSSL_MSG("DSA private key file write failed"); return 0; @@ -5935,7 +5948,8 @@ int wolfSSL_DSA_LoadDer(WOLFSSL_DSA* dsa, const unsigned char* derBuf, int derSz return -1; } - ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz); + ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, + (word32)derSz); if (ret < 0) { WOLFSSL_MSG("DsaPrivateKeyDecode failed"); return -1; @@ -5967,10 +5981,12 @@ int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf, } if (opt == WOLFSSL_DSA_LOAD_PRIVATE) { - ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz); + ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, + (word32)derSz); } else { - ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz); + ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, + (word32)derSz); } if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) { @@ -6258,7 +6274,7 @@ static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid) if (!err) { /* Set prime from data retrieved. */ - dh->p = wolfSSL_BN_bin2bn(params->p, params->p_len, NULL); + dh->p = wolfSSL_BN_bin2bn(params->p, (int)params->p_len, NULL); if (dh->p == NULL) { WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM."); err = 1; @@ -6266,7 +6282,7 @@ static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid) } if (!err) { /* Set generator from data retrieved. */ - dh->g = wolfSSL_BN_bin2bn(params->g, params->g_len, NULL); + dh->g = wolfSSL_BN_bin2bn(params->g, (int)params->g_len, NULL); if (dh->g == NULL) { WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM."); err = 1; @@ -7457,7 +7473,7 @@ static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh, } } /* Load the DER encoded DH parameters from buffer into a DH key. */ - if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, der->length) + if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, (int)der->length) != 1)) { /* Free an allocated DH key. */ if ((dh == NULL) || (localDh != *dh)) { @@ -8390,7 +8406,7 @@ int wolfSSL_DH_generate_key(WOLFSSL_DH* dh) if (ret == 1) { /* Get the size of the prime in bytes. */ - pubSz = wolfSSL_BN_num_bytes(dh->p); + pubSz = (word32)wolfSSL_BN_num_bytes(dh->p); if (pubSz == 0) { WOLFSSL_ERROR_MSG("Prime parameter invalid"); ret = 0; @@ -8399,7 +8415,7 @@ int wolfSSL_DH_generate_key(WOLFSSL_DH* dh) if (ret == 1) { /* Private key size can be as much as the size of the prime. */ if (dh->length) { - privSz = dh->length / 8; /* to bytes */ + privSz = (word32)(dh->length / 8); /* to bytes */ } else { privSz = pubSz; @@ -8438,12 +8454,14 @@ int wolfSSL_DH_generate_key(WOLFSSL_DH* dh) ret = 0; } /* Set public key from array. */ - if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, pubSz, dh->pub_key) == NULL)) { + if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, (int)pubSz, dh->pub_key) == + NULL)) { WOLFSSL_ERROR_MSG("Bad DH bn2bin error pub"); ret = 0; } /* Set private key from array. */ - if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, privSz, dh->priv_key) == NULL)) { + if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, (int)privSz, dh->priv_key) == + NULL)) { WOLFSSL_ERROR_MSG("Bad DH bn2bin error priv"); ret = 0; } @@ -8520,7 +8538,7 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, /* Validate the size of the public key. */ sz = wolfSSL_BN_num_bytes(otherPub); - if (sz > (int)pubSz) { + if (sz > pubSz) { WOLFSSL_ERROR_MSG("Bad otherPub size"); ret = -1; } @@ -8529,13 +8547,15 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, if (ret == 0) { #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for the public key array. */ - pub = (unsigned char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_PUBLIC_KEY); + pub = (unsigned char*)XMALLOC((size_t)sz, NULL, + DYNAMIC_TYPE_PUBLIC_KEY); if (pub == NULL) ret = -1; } if (ret == 0) { /* Allocate memory for the private key array. */ - priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY); + priv = (unsigned char*)XMALLOC((size_t)privSz, NULL, + DYNAMIC_TYPE_PRIVATE_KEY); if (priv == NULL) { ret = -1; } @@ -8564,7 +8584,7 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, PRIVATE_KEY_UNLOCK(); /* Calculate shared secret from private and public keys. */ if ((ret == 0) && (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv, - privSz, pub, pubSz) < 0)) { + (word32)privSz, pub, (word32)pubSz) < 0)) { WOLFSSL_ERROR_MSG("wc_DhAgree failed"); ret = -1; } @@ -8579,7 +8599,7 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, #endif { /* Zeroize sensitive data. */ - ForceZero(priv, privSz); + ForceZero(priv, (word32)privSz); } #ifdef WOLFSSL_SMALL_STACK XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY); @@ -8919,7 +8939,7 @@ static void ec_group_set_nid(WOLFSSL_EC_GROUP* group, int nid) if (ecc_sets[i].id == eccEnum) { /* Found id in wolfCrypt supported EC curves. */ group->curve_idx = i; - group->curve_oid = ecc_sets[i].oidSum; + group->curve_oid = (int)ecc_sets[i].oidSum; break; } } @@ -9746,7 +9766,7 @@ char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group, /* Hex string: allocate 2 bytes to represent each byte plus 1 for '\0'. */ - hex = (char*)XMALLOC(2 * len + 1, NULL, DYNAMIC_TYPE_ECC); + hex = (char*)XMALLOC((size_t)(2 * len + 1), NULL, DYNAMIC_TYPE_ECC); if (hex == NULL) { err = 1; } @@ -9754,7 +9774,7 @@ char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group, if (!err) { /* Make bytes all zeros to allow for ordinate values less than max size. */ - XMEMSET(hex, 0, 2 * len + 1); + XMEMSET(hex, 0, (size_t)(2 * len + 1)); /* Calculate offset as leading zeros not encoded. */ i = sz - mp_unsigned_bin_size((mp_int*)point->X->internal) + 1; @@ -11550,8 +11570,8 @@ WOLFSSL_EC_KEY *wolfSSL_o2i_ECPublicKey(WOLFSSL_EC_KEY **key, ret = *key; /* Import point into public key field. */ - if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in, len, - NULL) != 1) { + if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in, + (size_t)len, NULL) != 1) { WOLFSSL_MSG("wolfSSL_EC_POINT_oct2point error"); ret = NULL; err = 1; @@ -11755,8 +11775,8 @@ int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *key, unsigned char **out) /* Calculate the length of the private key DER encoding using internal EC * key. */ - if ((!err) && ((int)(len = wc_EccKeyDerSize((ecc_key*)key->internal, 0)) <= - 0)) { + if ((!err) && ((int)(len = (word32)wc_EccKeyDerSize((ecc_key*)key->internal, + 0)) <= 0)) { WOLFSSL_MSG("wc_EccKeyDerSize error"); err = 1; } @@ -11875,11 +11895,11 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, /* Load into internal EC key based on key type option. */ if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) { ret = wc_EccPrivateKeyDecode(derBuf, &idx, (ecc_key*)key->internal, - derSz); + (word32)derSz); } else { ret = wc_EccPublicKeyDecode(derBuf, &idx, (ecc_key*)key->internal, - derSz); + (word32)derSz); if (ret < 0) { ecc_key *tmp = (ecc_key*)XMALLOC(sizeof(ecc_key), ((ecc_key*)key->internal)->heap, DYNAMIC_TYPE_ECC); @@ -11891,7 +11911,7 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, ret = wc_ecc_init_ex(tmp, ((ecc_key*)key->internal)->heap, INVALID_DEVID); if (ret == 0) { - ret = wc_ecc_import_x963(derBuf, derSz, tmp); + ret = wc_ecc_import_x963(derBuf, (word32)derSz, tmp); if (ret == 0) { /* Take ownership of new key - set tmp to the old * key which will then be freed below. */ @@ -11899,7 +11919,7 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, key->internal = tmp; tmp = old; - idx = derSz; + idx = (word32)derSz; } wc_ecc_free(tmp); } @@ -11965,7 +11985,7 @@ static int wolfssl_ec_key_to_pubkey_der(WOLFSSL_EC_KEY* key, } if (sz > 0) { /* Allocate memory to hold encoding. */ - buf = (byte*)XMALLOC(sz, heap, DYNAMIC_TYPE_TMP_BUFFER); + buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { WOLFSSL_MSG("malloc failed"); sz = 0; @@ -11973,7 +11993,7 @@ static int wolfssl_ec_key_to_pubkey_der(WOLFSSL_EC_KEY* key, } if (sz > 0) { /* Encode public key to DER using wolfSSL. */ - sz = wc_EccPublicKeyToDer((ecc_key*)key->internal, buf, sz, 1); + sz = wc_EccPublicKeyToDer((ecc_key*)key->internal, buf, (word32)sz, 1); if (sz < 0) { WOLFSSL_MSG("wc_EccPublicKeyToDer failed"); sz = 0; @@ -12076,7 +12096,7 @@ WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_EC_PUBKEY(WOLFSSL_BIO* bio, err = 1; } /* Load the EC key with the public key from the DER encoding. */ - if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, der->length, + if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length, WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1)) { WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY"); err = 1; @@ -12141,7 +12161,7 @@ WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio, err = 1; } /* Load the EC key with the private key from the DER encoding. */ - if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, der->length, + if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length, WOLFSSL_EC_KEY_LOAD_PRIVATE) != 1)) { WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY"); err = 1; @@ -12273,7 +12293,7 @@ int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec, #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM) int ret = 1; byte* derBuf = NULL; - int der_max_len = 0; + word32 der_max_len = 0; int derSz = 0; WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey"); @@ -12298,10 +12318,12 @@ int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec, if (ret == 1) { /* Calculate maximum size of DER encoding. * 4 > size of pub, priv + ASN.1 additional information */ - der_max_len = 4 * wc_ecc_size((ecc_key*)ec->internal) + AES_BLOCK_SIZE; + der_max_len = 4 * (word32)wc_ecc_size((ecc_key*)ec->internal) + + AES_BLOCK_SIZE; /* Allocate buffer big enough to hold encoding. */ - derBuf = (byte*)XMALLOC(der_max_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); + derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (derBuf == NULL) { WOLFSSL_MSG("malloc failed"); ret = 0; @@ -12380,7 +12402,7 @@ int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec, } /* Write out to file the PEM encoding of the EC private key. */ - if ((ret == 1) && (XFWRITE(pem, pLen, 1, fp) != 1)) { + if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) { WOLFSSL_MSG("ECC private key file write failed"); ret = 0; } @@ -12526,7 +12548,7 @@ int SetECKeyExternal(WOLFSSL_EC_KEY* eckey) ecc_key* key = (ecc_key*)eckey->internal; /* Set group (OID, nid and idx) from wolfCrypt EC key. */ - eckey->group->curve_oid = key->dp->oidSum; + eckey->group->curve_oid = (int)key->dp->oidSum; eckey->group->curve_nid = EccEnumToNID(key->dp->id); eckey->group->curve_idx = key->idx; @@ -12676,7 +12698,7 @@ void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *key, int form) || form == POINT_CONVERSION_COMPRESSED #endif ) { - key->form = (char)form; + key->form = (unsigned char)form; } else { WOLFSSL_MSG("Incorrect form or HAVE_COMP_KEY not compiled in"); @@ -13249,16 +13271,16 @@ int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp) * top bit set. */ /* Get total length of r including any prepended zero. */ - word32 rLen = mp_leading_bit((mp_int*)sig->r->internal) + - mp_unsigned_bin_size((mp_int*)sig->r->internal); + word32 rLen = (word32)(mp_leading_bit((mp_int*)sig->r->internal) + + mp_unsigned_bin_size((mp_int*)sig->r->internal)); /* Get total length of s including any prepended zero. */ - word32 sLen = mp_leading_bit((mp_int*)sig->s->internal) + - mp_unsigned_bin_size((mp_int*)sig->s->internal); + word32 sLen = (word32)(mp_leading_bit((mp_int*)sig->s->internal) + + mp_unsigned_bin_size((mp_int*)sig->s->internal)); /* Calculate length of data in sequence. */ - len = 1 + ASN_LEN_SIZE(rLen) + rLen + - 1 + ASN_LEN_SIZE(sLen) + sLen; + len = (word32)1 + ASN_LEN_SIZE(rLen) + rLen + + (word32)1 + ASN_LEN_SIZE(sLen) + sLen; /* Add in the length of the SEQUENCE. */ - len += 1 + ASN_LEN_SIZE(len); + len += (word32)1 + ASN_LEN_SIZE(len); /* Encode only if there is a buffer to encode into. */ if ((pp != NULL) && (*pp != NULL)) { @@ -13489,7 +13511,7 @@ int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen, #ifndef WOLF_CRYPTO_CB_ONLY_ECC /* Verify hash using digest, r and s as MP ints and internal EC key. */ if (wc_ecc_verify_hash_ex((mp_int*)sig->r->internal, - (mp_int*)sig->s->internal, dgst, dLen, &verified, + (mp_int*)sig->s->internal, dgst, (word32)dLen, &verified, (ecc_key *)key->internal) != MP_OKAY) { WOLFSSL_MSG("wc_ecc_verify_hash failed"); ret = -1; @@ -13502,8 +13524,8 @@ int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen, signatureLen = i2d_ECDSA_SIG(sig, &p); if (signatureLen > 0) { /* verify hash. expects to call wc_CryptoCb_EccVerify internally */ - ret = wc_ecc_verify_hash(signature, signatureLen, dgst, dLen, - &verified, (ecc_key*)key->internal); + ret = wc_ecc_verify_hash(signature, signatureLen, dgst, + (word32)dLen, &verified, (ecc_key*)key->internal); if (ret != MP_OKAY) { WOLFSSL_MSG("wc_ecc_verify_hash failed"); ret = -1; @@ -13563,8 +13585,8 @@ int wolfSSL_ECDSA_sign(int type, const unsigned char *digest, int digestSz, /* Sign the digest with the key using the RNG and put signature into buffer * update sigSz to be actual length. */ - if ((ret == 1) && (wc_ecc_sign_hash(digest, digestSz, sig, sigSz, rng, - (ecc_key*)key->internal) != 0)) { + if ((ret == 1) && (wc_ecc_sign_hash(digest, (word32)digestSz, sig, sigSz, + rng, (ecc_key*)key->internal) != 0)) { ret = 0; } @@ -13606,8 +13628,8 @@ int wolfSSL_ECDSA_verify(int type, const unsigned char *digest, int digestSz, } /* Verify signature using digest and key. */ - if ((ret == 1) && (wc_ecc_verify_hash(sig, sigSz, digest, digestSz, &verify, - (ecc_key*)key->internal) != 0)) { + if ((ret == 1) && (wc_ecc_verify_hash(sig, (word32)sigSz, digest, + (word32)digestSz, &verify, (ecc_key*)key->internal) != 0)) { ret = 0; } /* When no error, verification may still have failed - check now. */ diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index d285dffea14..2e559283e31 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -181,12 +181,12 @@ static int wolfSSL_i2d_X509_ALGOR(const WOLFSSL_X509_ALGOR* algor, byte* buf) ret = 0; } else if (GetObjectId(algor->algorithm->obj, &idx, &oid, - algor->algorithm->grp, algor->algorithm->objSz) < 0) { + (word32)algor->algorithm->grp, algor->algorithm->objSz) < 0) { WOLFSSL_MSG("Issue getting OID of object"); ret = 0; } else { - ret = SetAlgoID(oid, buf, algor->algorithm->grp, 0); + ret = (int)SetAlgoID((int)oid, buf, algor->algorithm->grp, 0); } return ret; @@ -203,9 +203,9 @@ static int wolfSSL_i2d_ASN1_BIT_STRING(const WOLFSSL_ASN1_BIT_STRING* bit_str, { int len; - len = SetBitString(bit_str->length, 0, buf); + len = (int)SetBitString((word32)bit_str->length, 0, buf); if ((buf != NULL) && (bit_str->data != NULL)) { - XMEMCPY(buf + len, bit_str->data, bit_str->length); + XMEMCPY(buf + len, bit_str->data, (size_t)bit_str->length); } return len + bit_str->length; @@ -295,10 +295,11 @@ static int wolfssl_i2d_asn1_items(const void* src, byte*buf, static int i2d_ASN_SEQUENCE(const void* src, byte* buf, const WOLFSSL_ASN1_ITEM* tpl) { - int seq_len; - int len = 0; + word32 seq_len; + word32 len = 0; - seq_len = wolfssl_i2d_asn1_items(src, NULL, tpl->members, tpl->mcount); + seq_len = (word32)wolfssl_i2d_asn1_items(src, NULL, tpl->members, + tpl->mcount); if (seq_len != 0) { len = SetSequence(seq_len, buf); if (buf != NULL) { @@ -307,7 +308,7 @@ static int i2d_ASN_SEQUENCE(const void* src, byte* buf, len += seq_len; } - return len; + return (int)len; } /* Encode ASN1 template item. @@ -363,7 +364,7 @@ int wolfSSL_ASN1_item_i2d(const void* src, byte** dest, if ((ret == 1) && (dest != NULL)) { if (*dest == NULL) { - buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1); + buf = (byte*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_ASN1); if (buf == NULL) ret = 0; *dest = buf; @@ -465,13 +466,14 @@ static int wolfssl_asn1_bit_string_grow(WOLFSSL_ASN1_BIT_STRING* bitStr, byte* tmp; /* Realloc to length required. */ - tmp = (byte*)XREALLOC(bitStr->data, len, NULL, DYNAMIC_TYPE_OPENSSL); + tmp = (byte*)XREALLOC(bitStr->data, (size_t)len, NULL, + DYNAMIC_TYPE_OPENSSL); if (tmp == NULL) { ret = 0; } else { /* Clear out new, top bytes. */ - XMEMSET(tmp + bitStr->length, 0, len - bitStr->length); + XMEMSET(tmp + bitStr->length, 0, (size_t)(len - bitStr->length)); bitStr->data = tmp; bitStr->length = len; } @@ -622,7 +624,7 @@ static int wolfssl_asn1_integer_require_len(WOLFSSL_ASN1_INTEGER* a, int len, a->length = 0; if ((!a->isDynamic) && (len > (int)a->dataMax)) { /* Create a new buffer to hold large integer value. */ - data = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL); + data = (byte*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_OPENSSL); if (data == NULL) { ret = 0; } @@ -630,13 +632,13 @@ static int wolfssl_asn1_integer_require_len(WOLFSSL_ASN1_INTEGER* a, int len, /* Indicate data is dynamic and copy data over. */ a->isDynamic = 1; a->data = data; - a->dataMax = len; + a->dataMax = (word32)len; } } if (keepOldData) { if (oldData != a->data) { /* Copy old data into new buffer. */ - XMEMCPY(a->data, oldData, oldLen); + XMEMCPY(a->data, oldData, (size_t)oldLen); } /* Restore old length. */ a->length = oldLen; @@ -682,7 +684,7 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_ASN1_INTEGER_dup(const WOLFSSL_ASN1_INTEGER* src) dup = NULL; } else { - XMEMCPY(dup->data, src->data, src->length); + XMEMCPY(dup->data, src->data, (size_t)src->length); } } @@ -728,7 +730,7 @@ int wolfSSL_ASN1_INTEGER_cmp(const WOLFSSL_ASN1_INTEGER* a, } else { /* Compare data given they are the same length. */ - ret = XMEMCMP(a->data, b->data, a->length); + ret = XMEMCMP(a->data, b->data, (size_t)a->length); } /* Reverse comparison result when both negative. */ if (a->negative) { @@ -779,7 +781,7 @@ static int wolfssl_asn1_int_twos_compl(byte* data, int length, byte* neg) int len; /* Get length from DER header. */ - if (GetLength(data, &idx, &len, length) < 0) { + if (GetLength(data, &idx, &len, (word32)length) < 0) { ret = -1; } else { @@ -787,7 +789,7 @@ static int wolfssl_asn1_int_twos_compl(byte* data, int length, byte* neg) *neg = data[idx] & 0x80; } if ((neg == NULL) || (*neg != 0)) { - wolfssl_twos_compl(data + idx, length - idx); + wolfssl_twos_compl(data + idx, length - (int)idx); } } @@ -819,7 +821,8 @@ int wolfSSL_i2d_ASN1_INTEGER(const WOLFSSL_ASN1_INTEGER* a, unsigned char** out) if ((ret == 0) && (*out == NULL)) { /* Allocate buffer to hold encoding. */ - buf = (unsigned char*)XMALLOC(a->length, NULL, DYNAMIC_TYPE_ASN1); + buf = (unsigned char*)XMALLOC((size_t)a->length, NULL, + DYNAMIC_TYPE_ASN1); if (buf == NULL) { WOLFSSL_MSG("Failed to allocate output buffer."); ret = -1; @@ -829,7 +832,7 @@ int wolfSSL_i2d_ASN1_INTEGER(const WOLFSSL_ASN1_INTEGER* a, unsigned char** out) } if (ret == 0) { /* Copy the data (including tag and length) into output buffer. */ - XMEMCPY(*out, a->data, a->length); + XMEMCPY(*out, a->data, (size_t)a->length); /* Only magnitude of the number stored (i.e. the sign isn't encoded). * The "negative" field is 1 if the value must be interpreted as * negative and we need to output the 2's complement of the value in @@ -898,7 +901,8 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_d2i_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER** a, if ((!err) && ((ret = wolfSSL_ASN1_INTEGER_new()) == NULL)) { err = 1; } - if ((!err) && (wolfssl_asn1_integer_require_len(ret, idx + len, 0) != 1)) { + if ((!err) && (wolfssl_asn1_integer_require_len(ret, (int)idx + len, 0) != + 1)) { err = 1; } if (!err) { @@ -906,8 +910,8 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_d2i_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER** a, ret->type = V_ASN1_INTEGER; /* Copy DER encoding and length. */ - XMEMCPY(ret->data, *in, idx + len); - ret->length = idx + len; + XMEMCPY(ret->data, *in, (size_t)(idx + (word32)len)); + ret->length = (int)idx + len; /* Do 2's complement if number is negative. */ if (wolfssl_asn1_int_twos_compl(ret->data, ret->length, &ret->negative) != 0) { @@ -1042,12 +1046,12 @@ int wolfSSL_a2i_ASN1_INTEGER(WOLFSSL_BIO *bio, WOLFSSL_ASN1_INTEGER *asn1, if (ret == 1) { /* Decode string and append to data. */ outLen = (word32)(lineLen / 2); - (void)Base16_Decode((byte*)buf, lineLen, asn1->data + asn1->length, - &outLen); + (void)Base16_Decode((byte*)buf, (word32)lineLen, + asn1->data + asn1->length, &outLen); } if (ret == 1) { /* Update length of data. */ - asn1->length += outLen; + asn1->length += (int)outLen; } } @@ -1057,7 +1061,7 @@ int wolfSSL_a2i_ASN1_INTEGER(WOLFSSL_BIO *bio, WOLFSSL_ASN1_INTEGER *asn1, /* Get ASN.1 header length. */ idx = SetASNInt(asn1->length, asn1->data[0], NULL); /* Move data to be after ASN.1 header. */ - XMEMMOVE(asn1->data + idx, asn1->data, asn1->length); + XMEMMOVE(asn1->data + idx, asn1->data, (size_t)asn1->length); /* Encode ASN.1 header. */ SetASNInt(asn1->length, asn1->data[idx], asn1->data); /* Update length of data. */ @@ -1092,7 +1096,7 @@ int wolfSSL_i2a_ASN1_INTEGER(BIO *bp, const WOLFSSL_ASN1_INTEGER *a) if (!err) { /* Read DER length - must be at least 1 byte. */ - if (GetLength(a->data, &idx, &len, a->length) <= 0) { + if (GetLength(a->data, &idx, &len, (word32)a->length) <= 0) { err = 1; } } @@ -1100,7 +1104,7 @@ int wolfSSL_i2a_ASN1_INTEGER(BIO *bp, const WOLFSSL_ASN1_INTEGER *a) /* Keep encoding and writing while no error and bytes in data. */ while ((!err) && (idx < (word32)a->length)) { /* Number of bytes left to encode. */ - int encLen = a->length - idx; + int encLen = a->length - (int)idx; /* Reduce to maximum buffer size if necessary. */ if (encLen > (int)sizeof(buf) / 2) { encLen = (int)sizeof(buf) / 2; @@ -1108,12 +1112,12 @@ int wolfSSL_i2a_ASN1_INTEGER(BIO *bp, const WOLFSSL_ASN1_INTEGER *a) /* Encode bytes from data into buffer. */ bufLen = (int)sizeof(buf); - (void)Base16_Encode(a->data + idx, encLen, buf, &bufLen); + (void)Base16_Encode(a->data + idx, (word32)encLen, buf, &bufLen); /* Update index to next bytes to encoded. */ - idx += encLen; + idx += (word32)encLen; /* Write out characters but not NUL char. */ - if (wolfSSL_BIO_write(bp, buf, bufLen - 1) != (int)(bufLen - 1)) { + if (wolfSSL_BIO_write(bp, buf, (int)bufLen - 1) != (int)(bufLen - 1)) { err = 1; } } @@ -1233,7 +1237,7 @@ int wolfSSL_i2c_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER *a, unsigned char **pp) (*pp)[0] = padVal; } /* Copy remaining bytes into output buffer. */ - XMEMCPY(*pp + pad, a->data + idx, len - pad); + XMEMCPY(*pp + pad, a->data + idx, (size_t)(len - pad)); /* Two's complement copied bytes when negative. */ if (a->negative) { wolfssl_twos_compl(*pp + pad, len - pad); @@ -1272,7 +1276,7 @@ WOLFSSL_BIGNUM *wolfSSL_ASN1_INTEGER_to_BN(const WOLFSSL_ASN1_INTEGER *ai, if (!err) { /* Get the length of ASN.1 INTEGER number. */ if ((ai->data[0] != ASN_INTEGER) || (GetLength(ai->data, &idx, &len, - ai->length) <= 0)) { + (word32)ai->length) <= 0)) { #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY) idx = 0; len = ai->length; @@ -1423,7 +1427,7 @@ long wolfSSL_ASN1_INTEGER_get(const WOLFSSL_ASN1_INTEGER* a) } if (ret > 0) { /* Get the big number as a word. */ - ret = wolfSSL_BN_get_word(bn); + ret = (long)wolfSSL_BN_get_word(bn); /* Negate number of ASN.1 INTEGER was negative. */ if (a->negative == 1) { ret = -ret; @@ -1789,7 +1793,7 @@ int wolfSSL_i2d_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT *a, unsigned char **pp) *pp += a->objSz; } /* Return length of DER encoding. */ - len = a->objSz; + len = (int)a->objSz; } } @@ -1827,7 +1831,8 @@ WOLFSSL_ASN1_OBJECT *wolfSSL_c2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a, if (!err) { /* Allocate memory for content octets. */ - ret->obj = (const unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1); + ret->obj = (const unsigned char*)XMALLOC((size_t)len, NULL, + DYNAMIC_TYPE_ASN1); if (ret->obj == NULL) { WOLFSSL_MSG("error allocating asn data memory"); wolfSSL_ASN1_OBJECT_free(ret); @@ -1840,7 +1845,7 @@ WOLFSSL_ASN1_OBJECT *wolfSSL_c2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a, /* Content octets buffer was dynamically allocated. */ ret->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; /* Copy in content octets and set size. */ - XMEMCPY((byte*)ret->obj, *pp, len); + XMEMCPY((byte*)ret->obj, *pp, (size_t)len); ret->objSz = (unsigned int)len; /* Move pointer to after data copied out. */ @@ -2173,7 +2178,7 @@ int wolfSSL_ASN1_STRING_cmp(const WOLFSSL_ASN1_STRING *a, ret = a->length - b->length; } /* Compare data. */ - else if ((ret = XMEMCMP(a->data, b->data, a->length)) == 0) { + else if ((ret = XMEMCMP(a->data, b->data, (size_t)a->length)) == 0) { /* Compare ASN.1 types - wolfSSL_ASN1_STRING_type_new(). */ ret = a->type - b->type; } @@ -2293,14 +2298,15 @@ int wolfSSL_ASN1_STRING_to_UTF8(unsigned char **out, WOLFSSL_ASN1_STRING *asn1) } if (len != -1) { /* Allocate buffer to hold string and NUL. */ - buf = (unsigned char*)XMALLOC(len + 1, NULL, DYNAMIC_TYPE_OPENSSL); + buf = (unsigned char*)XMALLOC((size_t)(len + 1), NULL, + DYNAMIC_TYPE_OPENSSL); if (buf == NULL) { len = -1; } } if (len != -1) { /* Copy in string - NUL always put on end of stored string. */ - XMEMCPY(buf, data, len + 1); + XMEMCPY(buf, data, (size_t)(len + 1)); /* Return buffer. */ *out = buf; } @@ -2325,7 +2331,7 @@ static char* wolfssl_asn1_string_to_hex_chars(const WOLFSSL_ASN1_STRING *s) char* tmp; int tmpSz = s->length * 3; - tmp = (char*)XMALLOC(tmpSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + tmp = (char*)XMALLOC((size_t)tmpSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (tmp == NULL) { WOLFSSL_MSG("Memory Error"); } @@ -2519,7 +2525,8 @@ int wolfSSL_ASN1_STRING_set(WOLFSSL_ASN1_STRING* asn1, const void* data, int sz) /* Check string will fit - including NUL. */ if (sz + 1 > CTC_NAME_SIZE) { /* Allocate new buffer. */ - asn1->data = (char*)XMALLOC(sz + 1, NULL, DYNAMIC_TYPE_OPENSSL); + asn1->data = (char*)XMALLOC((size_t)(sz + 1), NULL, + DYNAMIC_TYPE_OPENSSL); if (asn1->data == NULL) { ret = 0; } @@ -2539,7 +2546,7 @@ int wolfSSL_ASN1_STRING_set(WOLFSSL_ASN1_STRING* asn1, const void* data, int sz) /* Check if there is a string to copy. */ if (data != NULL) { /* Copy string and append NUL. */ - XMEMCPY(asn1->data, data, sz); + XMEMCPY(asn1->data, data, (size_t)sz); asn1->data[sz] = '\0'; } /* Set size of string. */ @@ -3453,7 +3460,7 @@ int wolfSSL_ASN1_TIME_set_string(WOLFSSL_ASN1_TIME *t, const char *str) } if ((ret == 1) && (t != NULL)) { /* Copy in string including NUL terminator. */ - XMEMCPY(t->data, str, slen); + XMEMCPY(t->data, str, (size_t)slen); /* Do not include NUL terminator in length. */ t->length = slen - 1; /* Set ASN.1 type based on string length. */ diff --git a/src/ssl_bn.c b/src/ssl_bn.c index 4cdacbd6466..9102a8e03e6 100644 --- a/src/ssl_bn.c +++ b/src/ssl_bn.c @@ -509,7 +509,8 @@ WOLFSSL_BIGNUM* wolfSSL_BN_bin2bn(const unsigned char* data, int len, } else { /* Decode into big number. */ - if (mp_read_unsigned_bin((mp_int*)ret->internal, data, len) != 0) { + if (mp_read_unsigned_bin((mp_int*)ret->internal, data, (word32)len) + != 0) { WOLFSSL_MSG("mp_read_unsigned_bin failure"); /* Don't return anything on failure. bn will be freed if set. */ ret = NULL; @@ -557,7 +558,7 @@ static char* wolfssl_bn_bn2radix(const WOLFSSL_BIGNUM* bn, int radix) if (!err) { /* Allocate string. */ - str = (char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL); + str = (char*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_OPENSSL); if (str == NULL) { WOLFSSL_MSG("BN_bn2hex malloc string failure"); err = 1; @@ -1985,7 +1986,7 @@ int wolfSSL_BN_gcd(WOLFSSL_BIGNUM* r, WOLFSSL_BIGNUM* a, WOLFSSL_BIGNUM* b, int wolfSSL_BN_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) { int ret = 1; - int len = (bits + 7) / 8; + word32 len = (word32)((bits + 7) / 8); WC_RNG* rng; WOLFSSL_ENTER("wolfSSL_BN_rand"); diff --git a/src/ssl_misc.c b/src/ssl_misc.c index 6197b45f8e9..af0b99bac16 100644 --- a/src/ssl_misc.c +++ b/src/ssl_misc.c @@ -129,7 +129,7 @@ static int wolfssl_read_bio_len(WOLFSSL_BIO* bio, int sz, char** data) char* mem; /* Allocate buffer to hold data. */ - mem = (char*)XMALLOC(sz, bio->heap, DYNAMIC_TYPE_OPENSSL); + mem = (char*)XMALLOC((size_t)sz, bio->heap, DYNAMIC_TYPE_OPENSSL); if (mem == NULL) { WOLFSSL_ERROR_MSG("Memory allocation error"); ret = MEMORY_E; @@ -272,13 +272,13 @@ static int wolfssl_read_file(XFILE fp, char** data, int* dataSz) ret = wolfssl_file_len(fp, &sz); if (ret == 0) { /* Allocate memory big enough to hold whole file. */ - mem = (char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + mem = (char*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (mem == NULL) { ret = MEMORY_E; } } /* Read whole file into new buffer. */ - if ((ret == 0) && ((int)XFREAD(mem, 1, sz, fp) != sz)) { + if ((ret == 0) && ((int)XFREAD(mem, 1, (size_t)sz, fp) != sz)) { ret = WOLFSSL_BAD_FILE; } if (ret == 0) { diff --git a/wolfcrypt/src/dsa.c b/wolfcrypt/src/dsa.c index 77d1ad5aca7..1e4f59a3f07 100644 --- a/wolfcrypt/src/dsa.c +++ b/wolfcrypt/src/dsa.c @@ -160,7 +160,7 @@ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa) /* generate extra 64 bits so that bias from mod function is negligible */ cSz = qSz + (64 / WOLFSSL_BIT_SIZE); - cBuf = (byte*)XMALLOC(cSz, dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); + cBuf = (byte*)XMALLOC((size_t)cSz, dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); if (cBuf == NULL) { return MEMORY_E; } @@ -184,10 +184,10 @@ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa) * Hash_DRBG uses SHA-256 which matches maximum * requested_security_strength of (L,N). */ - err = wc_RNG_GenerateBlock(rng, cBuf, cSz); + err = wc_RNG_GenerateBlock(rng, cBuf, (word32)cSz); if (err != MP_OKAY) break; - err = mp_read_unsigned_bin(&dsa->x, cBuf, cSz); + err = mp_read_unsigned_bin(&dsa->x, cBuf, (word32)cSz); if (err != MP_OKAY) break; } while (mp_cmp_d(&dsa->x, 1) != MP_GT); @@ -209,8 +209,10 @@ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa) err = mp_add_d(&dsa->x, 1, &dsa->x); /* public key : y = g^x mod p */ - if (err == MP_OKAY) - err = mp_exptmod_ex(&dsa->g, &dsa->x, dsa->q.used, &dsa->p, &dsa->y); + if (err == MP_OKAY) { + err = mp_exptmod_ex(&dsa->g, &dsa->x, (int)dsa->q.used, &dsa->p, + &dsa->y); + } if (err == MP_OKAY) dsa->type = DSA_PRIVATE; @@ -276,14 +278,14 @@ int wc_MakeDsaParameters(WC_RNG *rng, int modulus_size, DsaKey *dsa) msize = modulus_size / WOLFSSL_BIT_SIZE; /* allocate ram */ - buf = (unsigned char *)XMALLOC(msize - qsize, + buf = (unsigned char *)XMALLOC((size_t)(msize - qsize), dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { return MEMORY_E; } /* make a random string that will be multiplied against q */ - err = wc_RNG_GenerateBlock(rng, buf, msize - qsize); + err = wc_RNG_GenerateBlock(rng, buf, (word32)(msize - qsize)); if (err != MP_OKAY) { XFREE(buf, dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); return err; @@ -293,7 +295,7 @@ int wc_MakeDsaParameters(WC_RNG *rng, int modulus_size, DsaKey *dsa) buf[0] |= 0xC0; /* force even */ - buf[msize - qsize - 1] &= ~1; + buf[msize - qsize - 1] &= (unsigned char)~1; #ifdef WOLFSSL_SMALL_STACK if (((tmp = (mp_int *)XMALLOC(sizeof(*tmp), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) || @@ -307,7 +309,7 @@ int wc_MakeDsaParameters(WC_RNG *rng, int modulus_size, DsaKey *dsa) err = mp_init_multi(tmp, tmp2, &dsa->p, &dsa->q, 0, 0); if (err == MP_OKAY) - err = mp_read_unsigned_bin(tmp2, buf, msize - qsize); + err = mp_read_unsigned_bin(tmp2, buf, (word32)(msize - qsize)); /* make our prime q */ if (err == MP_OKAY) @@ -346,7 +348,7 @@ int wc_MakeDsaParameters(WC_RNG *rng, int modulus_size, DsaKey *dsa) */ if (err == MP_OKAY) { if (loop_check_prime) - err = mp_add_d(tmp2, 2*loop_check_prime, tmp2); + err = mp_add_d(tmp2, 2 * (mp_digit)loop_check_prime, tmp2); } if (err == MP_OKAY) @@ -407,7 +409,7 @@ static int _DsaImportParamsRaw(DsaKey* dsa, const char* p, const char* q, const char* g, int trusted, WC_RNG* rng) { int err; - word32 pSz, qSz; + int pSz, qSz; if (dsa == NULL || p == NULL || q == NULL || g == NULL) return BAD_FUNC_ARG; @@ -523,9 +525,9 @@ int wc_DsaExportParamsRaw(DsaKey* dsa, byte* p, word32* pSz, return BAD_FUNC_ARG; /* get required output buffer sizes */ - pLen = mp_unsigned_bin_size(&dsa->p); - qLen = mp_unsigned_bin_size(&dsa->q); - gLen = mp_unsigned_bin_size(&dsa->g); + pLen = (word32)mp_unsigned_bin_size(&dsa->p); + qLen = (word32)mp_unsigned_bin_size(&dsa->q); + gLen = (word32)mp_unsigned_bin_size(&dsa->g); /* return buffer sizes and LENGTH_ONLY_E if buffers are NULL */ if (p == NULL && q == NULL && g == NULL) { @@ -599,8 +601,8 @@ int wc_DsaExportKeyRaw(DsaKey* dsa, byte* x, word32* xSz, byte* y, word32* ySz) return BAD_FUNC_ARG; /* get required output buffer sizes */ - xLen = mp_unsigned_bin_size(&dsa->x); - yLen = mp_unsigned_bin_size(&dsa->y); + xLen = (word32)mp_unsigned_bin_size(&dsa->x); + yLen = (word32)mp_unsigned_bin_size(&dsa->y); /* return buffer sizes and LENGTH_ONLY_E if buffers are NULL */ if (x == NULL && y == NULL) { @@ -664,7 +666,8 @@ int wc_DsaSign_ex(const byte* digest, word32 digestSz, byte* out, DsaKey* key, byte buffer[DSA_MAX_HALF_SIZE]; #endif mp_int* qMinus1; - int ret = 0, halfSz = 0; + int ret = 0; + word32 halfSz = 0; if (digest == NULL || out == NULL || key == NULL || rng == NULL) return BAD_FUNC_ARG; @@ -709,7 +712,7 @@ int wc_DsaSign_ex(const byte* digest, word32 digestSz, byte* out, DsaKey* key, break; } - halfSz = min(DSA_MAX_HALF_SIZE, mp_unsigned_bin_size(&key->q)); + halfSz = min(DSA_MAX_HALF_SIZE, (word32)mp_unsigned_bin_size(&key->q)); /* NIST FIPS 186-4: Sections 4.1 * q is a prime divisor where 2^(N-1) < q < 2^N and N is the bit length * of q. @@ -836,7 +839,8 @@ int wc_DsaSign_ex(const byte* digest, word32 digestSz, byte* out, DsaKey* key, } /* generate r, r = (g exp k mod p) mod q */ - if (mp_exptmod_ex(&key->g, k, key->q.used, &key->p, r) != MP_OKAY) { + if (mp_exptmod_ex(&key->g, k, (int)key->q.used, &key->p, r) != + MP_OKAY) { ret = MP_EXPTMOD_E; break; } @@ -905,11 +909,11 @@ int wc_DsaSign_ex(const byte* digest, word32 digestSz, byte* out, DsaKey* key, /* write out */ { - if (mp_to_unsigned_bin_len(r, out, halfSz) != MP_OKAY) + if (mp_to_unsigned_bin_len(r, out, (int)halfSz) != MP_OKAY) ret = MP_TO_E; else { out += halfSz; /* advance to s in output */ - ret = mp_to_unsigned_bin_len(s, out, halfSz); + ret = mp_to_unsigned_bin_len(s, out, (int)halfSz); } } } while (0); @@ -1027,8 +1031,8 @@ int wc_DsaVerify_ex(const byte* digest, word32 digestSz, const byte* sig, } /* set r and s from signature */ - if (mp_read_unsigned_bin(r, sig, qSz) != MP_OKAY || - mp_read_unsigned_bin(s, sig + qSz, qSz) != MP_OKAY) { + if (mp_read_unsigned_bin(r, sig, (word32)qSz) != MP_OKAY || + mp_read_unsigned_bin(s, sig + qSz, (word32)qSz) != MP_OKAY) { ret = MP_READ_E; break; } diff --git a/wolfcrypt/src/eccsi.c b/wolfcrypt/src/eccsi.c index 23c95f49b06..ed2e2b8bd9b 100644 --- a/wolfcrypt/src/eccsi.c +++ b/wolfcrypt/src/eccsi.c @@ -521,12 +521,12 @@ static int eccsi_encode_point(ecc_point* point, word32 size, byte* data, } /* Write out the point's x ordinate into key size bytes. */ - err = mp_to_unsigned_bin_len(point->x, data, size); + err = mp_to_unsigned_bin_len(point->x, data, (int)size); } if (err == 0) { data += size; /* Write out the point's y ordinate into key size bytes. */ - err = mp_to_unsigned_bin_len(point->y, data, size); + err = mp_to_unsigned_bin_len(point->y, data, (int)size); } if (err == 0) { *sz = size * 2 + !raw; @@ -646,14 +646,14 @@ int wc_ExportEccsiKey(EccsiKey* key, byte* data, word32* sz) if (err == 0) { if (data == NULL) { - *sz = key->ecc.dp->size * 3; + *sz = (word32)(key->ecc.dp->size * 3); err = LENGTH_ONLY_E; } else if (*sz < (word32)key->ecc.dp->size * 3) { err = BUFFER_E; } else { - *sz = key->ecc.dp->size * 3; + *sz = (word32)(key->ecc.dp->size * 3); } } if (err == 0) { @@ -684,12 +684,12 @@ static int eccsi_decode_key(EccsiKey* key, const byte* data) /* Read the secret value from key size bytes. */ err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data, - key->ecc.dp->size); + (word32)key->ecc.dp->size); if (err == 0) { data += key->ecc.dp->size; /* Read public key. */ err = eccsi_decode_point(&key->ecc.pubkey, (word32)key->ecc.dp->size, - data, key->ecc.dp->size * 2); + data, (word32)(key->ecc.dp->size * 2)); } return err; @@ -768,14 +768,14 @@ int wc_ExportEccsiPrivateKey(EccsiKey* key, byte* data, word32* sz) if (err == 0) { if (data == NULL) { - *sz = key->ecc.dp->size; + *sz = (word32)key->ecc.dp->size; err = LENGTH_ONLY_E; } else if (*sz < (word32)key->ecc.dp->size) { err = BUFFER_E; } else { - *sz = key->ecc.dp->size; + *sz = (word32)key->ecc.dp->size; } } if (err == 0) { @@ -814,7 +814,7 @@ int wc_ImportEccsiPrivateKey(EccsiKey* key, const byte* data, word32 sz) if (err == 0) { err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data, - key->ecc.dp->size); + (word32)key->ecc.dp->size); } return err; @@ -1007,7 +1007,7 @@ int wc_EncodeEccsiPair(const EccsiKey* key, mp_int* ssk, ecc_point* pvt, } if ((err == 0) && (data == NULL)) { - *sz = key->ecc.dp->size * 3; + *sz = (word32)(key->ecc.dp->size * 3); err = LENGTH_ONLY_E; } if ((err == 0) && (*sz < (word32)(key->ecc.dp->size * 3))) { @@ -1028,7 +1028,7 @@ int wc_EncodeEccsiPair(const EccsiKey* key, mp_int* ssk, ecc_point* pvt, err = mp_to_unsigned_bin_len(pvt->y, data, key->ecc.dp->size); } if (err == 0) { - *sz = key->ecc.dp->size * 3; + *sz = (word32)(key->ecc.dp->size * 3); } return err; @@ -1068,14 +1068,14 @@ int wc_EncodeEccsiSsk(const EccsiKey* key, mp_int* ssk, byte* data, word32* sz) if (err == 0) { if (data == NULL) { - *sz = key->ecc.dp->size; + *sz = (word32)key->ecc.dp->size; err = LENGTH_ONLY_E; } else if (*sz < (word32)key->ecc.dp->size) { err = BUFFER_E; } else { - *sz = key->ecc.dp->size; + *sz = (word32)key->ecc.dp->size; } } if (err == 0) { @@ -1114,7 +1114,7 @@ int wc_DecodeEccsiSsk(const EccsiKey* key, const byte* data, word32 sz, } if (err == 0) { - err = mp_read_unsigned_bin(ssk, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(ssk, data, (word32)key->ecc.dp->size); } return err; @@ -1191,17 +1191,17 @@ int wc_DecodeEccsiPair(const EccsiKey* key, const byte* data, word32 sz, if (err == 0) { /* Read the SSK value from key size bytes. */ - err = mp_read_unsigned_bin(ssk, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(ssk, data, (word32)key->ecc.dp->size); } if (err == 0) { data += key->ecc.dp->size; /* Read the PVT's x value from key size bytes. */ - err = mp_read_unsigned_bin(pvt->x, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(pvt->x, data, (word32)key->ecc.dp->size); } if (err == 0) { data += key->ecc.dp->size; /* Read the PVT's y value from key size bytes. */ - err = mp_read_unsigned_bin(pvt->y, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(pvt->y, data, (word32)key->ecc.dp->size); } if (err == 0) { err = mp_set(pvt->z, 1); @@ -1275,7 +1275,7 @@ int wc_DecodeEccsiPvtFromSig(const EccsiKey* key, const byte* sig, word32 sz, } if (err == 0) { - word32 rSz = key->ecc.dp->size * 2; + word32 rSz = (word32)(key->ecc.dp->size * 2); err = eccsi_decode_point(pvt, (word32)key->ecc.dp->size, sig + rSz, sz - rSz); } @@ -1811,7 +1811,7 @@ static int eccsi_compute_he(EccsiKey* key, enum wc_HashType hashType, mp_int* r, const byte* msg, word32 msgSz, byte* he, word32* heSz) { int err = 0; - word32 dataSz = key->ecc.dp->size; + word32 dataSz = (word32)key->ecc.dp->size; int hash_inited = 0; /* HE = hash( HS | r | M ) */ @@ -1822,7 +1822,7 @@ static int eccsi_compute_he(EccsiKey* key, enum wc_HashType hashType, err = wc_HashUpdate(&key->hash, hashType, key->idHash, key->idHashSz); } if (err == 0) { - err = mp_to_unsigned_bin_len(r, key->data, dataSz); + err = mp_to_unsigned_bin_len(r, key->data, (int)dataSz); } if (err == 0) { /* r */ @@ -1836,7 +1836,7 @@ static int eccsi_compute_he(EccsiKey* key, enum wc_HashType hashType, err = wc_HashFinal(&key->hash, hashType, he); } if (err == 0) { - *heSz = wc_HashGetDigestSize(hashType); + *heSz = (word32)wc_HashGetDigestSize(hashType); } if (hash_inited) { @@ -1860,14 +1860,14 @@ static int eccsi_encode_sig(const EccsiKey* key, mp_int* r, mp_int* s, byte* sig, word32* sigSz) { int err; - word32 sz = key->ecc.dp->size; + word32 sz = (word32)key->ecc.dp->size; - err = mp_to_unsigned_bin_len(r, sig, sz); + err = mp_to_unsigned_bin_len(r, sig, (int)sz); if (err == 0) { - err = mp_to_unsigned_bin_len(s, sig + sz, sz); + err = mp_to_unsigned_bin_len(s, sig + sz, (int)sz); } if (err == 0) { - *sigSz = key->ecc.dp->size * 2 + 1; + *sigSz = (word32)(key->ecc.dp->size * 2 + 1); err = wc_ecc_export_point_der(wc_ecc_get_curve_idx(key->ecc.dp->id), key->pvt, sig + sz * 2, sigSz); } @@ -1898,7 +1898,7 @@ static int eccsi_gen_sig(EccsiKey* key, WC_RNG* rng, enum wc_HashType hashType, const byte* msg, word32 msgSz, mp_int* r, mp_int* s) { int err = 0; - word32 sz = key->ecc.dp->size; + int sz = key->ecc.dp->size; word32 heSz = 0; const mp_int* jx = NULL; mp_int* he = &key->tmp; @@ -1990,7 +1990,7 @@ int wc_SignEccsiHash(EccsiKey* key, WC_RNG* rng, enum wc_HashType hashType, } if (err == 0) { - sz = key->ecc.dp->size; + sz = (word32)key->ecc.dp->size; if (sig == NULL) { *sigSz = sz * 4 + 1; err = LENGTH_ONLY_E; @@ -2024,7 +2024,7 @@ int wc_SignEccsiHash(EccsiKey* key, WC_RNG* rng, enum wc_HashType hashType, mp_forcezero(j); /* Step 6: s = s' fitted */ - err = eccsi_fit_to_octets(s, &key->params.order, sz, s); + err = eccsi_fit_to_octets(s, &key->params.order, (int)sz, s); } /* Step 7: Output Signature = ( r | s | PVT ) */ @@ -2050,7 +2050,7 @@ static int eccsi_decode_sig_s(const EccsiKey* key, const byte* sig, word32 sigSz, mp_int* s) { int err = 0; - word32 sz = key->ecc.dp->size; + word32 sz = (word32)key->ecc.dp->size; if (sigSz != sz * 4 + 1) { err = BAD_FUNC_ARG; @@ -2079,7 +2079,7 @@ static int eccsi_decode_sig_r_pvt(const EccsiKey* key, const byte* sig, word32 sigSz, mp_int* r, ecc_point* pvt) { int err = 0; - word32 sz = key->ecc.dp->size; + word32 sz = (word32)key->ecc.dp->size; if (sigSz != sz * 4 + 1) { err = BAD_FUNC_ARG; diff --git a/wolfcrypt/src/fe_448.c b/wolfcrypt/src/fe_448.c index e0fde82d363..0dd439ed7db 100644 --- a/wolfcrypt/src/fe_448.c +++ b/wolfcrypt/src/fe_448.c @@ -1836,8 +1836,6 @@ static WC_INLINE void fe448_mul_8(sword32* r, const sword32* a, const sword32* b sword64 t13 = (sword64)a[ 6] * b[ 7]; sword64 t113 = (sword64)a[ 7] * b[ 6]; sword64 t14 = (sword64)a[ 7] * b[ 7]; - sword64 o; - sword64 t15; t1 += t101; t2 += t102; t2 += t202; t3 += t103; t3 += t203; t3 += t303; @@ -1854,8 +1852,8 @@ static WC_INLINE void fe448_mul_8(sword32* r, const sword32* a, const sword32* b t11 += t111; t11 += t211; t11 += t311; t12 += t112; t12 += t212; t13 += t113; - o = t14 >> 28; - t15 = o; + sword64 o = t14 >> 28; + sword64 t15 = o; t14 -= o << 28; o = (t0 >> 28); t1 += o; t = o << 28; t0 -= t; o = (t1 >> 28); t2 += o; t = o << 28; t1 -= t; diff --git a/wolfcrypt/src/fe_x25519_128.i b/wolfcrypt/src/fe_x25519_128.i index 69e3dd42e52..eff2d408eb8 100644 --- a/wolfcrypt/src/fe_x25519_128.i +++ b/wolfcrypt/src/fe_x25519_128.i @@ -302,7 +302,7 @@ void fe_mul(fe r, const fe a, const fe b) t2 += t1 >> 51; r[1] = t1 & 0x7ffffffffffff; t3 += t2 >> 51; r[2] = t2 & 0x7ffffffffffff; t4 += t3 >> 51; r[3] = t3 & 0x7ffffffffffff; - r[0] += (t4 >> 51) * k19; + r[0] += (sword64)((t4 >> 51) * k19); r[4] = t4 & 0x7ffffffffffff; } @@ -345,7 +345,7 @@ void fe_sq(fe r, const fe a) t2 += t1 >> 51; r[1] = t1 & 0x7ffffffffffff; t3 += t2 >> 51; r[2] = t2 & 0x7ffffffffffff; t4 += t3 >> 51; r[3] = t3 & 0x7ffffffffffff; - r[0] += (t4 >> 51) * k19; + r[0] += (sword64)((t4 >> 51) * k19); r[4] = t4 & 0x7ffffffffffff; } @@ -372,7 +372,7 @@ void fe_mul121666(fe r, fe a) t2 += t1 >> 51; r[1] = t1 & 0x7ffffffffffff; t3 += t2 >> 51; r[2] = t2 & 0x7ffffffffffff; t4 += t3 >> 51; r[3] = t3 & 0x7ffffffffffff; - r[0] += (t4 >> 51) * k19; + r[0] += (sword64)((t4 >> 51) * k19); r[4] = t4 & 0x7ffffffffffff; } @@ -430,8 +430,8 @@ int curve25519(byte* r, const byte* n, const byte* a) b = n[pos / 8] >> (pos & 7); b &= 1; swap ^= b; - fe_cswap(x2, x3, swap); - fe_cswap(z2, z3, swap); + fe_cswap(x2, x3, (int)swap); + fe_cswap(z2, z3, (int)swap); swap = b; fe_sub(t0, x3, z3); @@ -453,8 +453,8 @@ int curve25519(byte* r, const byte* n, const byte* a) fe_mul(z3, x1, z2); fe_mul(z2, t1, t0); } - fe_cswap(x2, x3, swap); - fe_cswap(z2, z3, swap); + fe_cswap(x2, x3, (int)swap); + fe_cswap(z2, z3, (int)swap); fe_invert(z2, z2); fe_mul(x2, x2, z2); @@ -591,7 +591,7 @@ void fe_sq2(fe r, const fe a) t2 += t1 >> 51; r[1] = t1 & 0x7ffffffffffff; t3 += t2 >> 51; r[2] = t2 & 0x7ffffffffffff; t4 += t3 >> 51; r[3] = t3 & 0x7ffffffffffff; - r[0] += (t4 >> 51) * k19; + r[0] += (sword64)((t4 >> 51) * k19); r[4] = t4 & 0x7ffffffffffff; } diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index 33fb3bc6464..03c624fc349 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -1438,8 +1438,9 @@ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) - msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap, - DYNAMIC_TYPE_RSA_BUFFER); + msg = (byte*)XMALLOC( + (size_t)(RSA_PSS_PAD_SZ + inputLen + (word32)saltLen), + heap, DYNAMIC_TYPE_RSA_BUFFER); if (msg == NULL) { return MEMORY_E; } @@ -1451,7 +1452,7 @@ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, m += inputLen; o = (int)(m - s); if (saltLen > 0) { - ret = wc_RNG_GenerateBlock(rng, m, saltLen); + ret = wc_RNG_GenerateBlock(rng, m, (word32)saltLen); if (ret == 0) { m += saltLen; } @@ -1459,8 +1460,9 @@ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, #else if ((int)pkcsBlockLen < RSA_PSS_PAD_SZ + (int)inputLen + saltLen) { #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) - msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + (word32)saltLen, heap, - DYNAMIC_TYPE_RSA_BUFFER); + msg = (byte*)XMALLOC( + (size_t)(RSA_PSS_PAD_SZ + inputLen + (word32)saltLen), + heap, DYNAMIC_TYPE_RSA_BUFFER); if (msg == NULL) { return MEMORY_E; } @@ -4090,9 +4092,11 @@ int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, byte* sig, #ifdef WOLFSSL_PSS_LONG_SALT /* if long salt is larger then default maximum buffer then allocate a buffer */ - if (ret == 0 && sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + saltLen)) { - sigCheck = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inSz + saltLen, heap, - DYNAMIC_TYPE_RSA_BUFFER); + if ((ret == 0) && + (sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + (word32)saltLen))) { + sigCheck = (byte*)XMALLOC( + (size_t)(RSA_PSS_PAD_SZ + inSz + (word32)saltLen), + heap, DYNAMIC_TYPE_RSA_BUFFER); if (sigCheck == NULL) { ret = MEMORY_E; } diff --git a/wolfcrypt/src/sakke.c b/wolfcrypt/src/sakke.c index 3adc01dd7f9..0629652081d 100644 --- a/wolfcrypt/src/sakke.c +++ b/wolfcrypt/src/sakke.c @@ -601,7 +601,7 @@ int wc_ExportSakkeKey(SakkeKey* key, byte* data, word32* sz) } if ((err == 0) && (data == NULL)) { - *sz = 3 * key->ecc.dp->size; + *sz = (word32)(3 * key->ecc.dp->size); err = LENGTH_ONLY_E; } if ((err >= 0) && (*sz < (word32)(3 * key->ecc.dp->size))) { @@ -609,7 +609,8 @@ int wc_ExportSakkeKey(SakkeKey* key, byte* data, word32* sz) } if (err == 0) { /* Write out the secret value into key size bytes. */ - err = mp_to_unsigned_bin_len(wc_ecc_key_get_priv(&key->ecc), data, key->ecc.dp->size); + err = mp_to_unsigned_bin_len(wc_ecc_key_get_priv(&key->ecc), data, + key->ecc.dp->size); } if (err == 0) { data += key->ecc.dp->size; @@ -624,7 +625,7 @@ int wc_ExportSakkeKey(SakkeKey* key, byte* data, word32* sz) key->ecc.dp->size); } if (err == 0) { - *sz = 3 * key->ecc.dp->size; + *sz = (word32)(3 * key->ecc.dp->size); } return err; @@ -660,17 +661,19 @@ int wc_ImportSakkeKey(SakkeKey* key, const byte* data, word32 sz) if (err == 0) { /* Read the secret value from key size bytes. */ err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data, - key->ecc.dp->size); + (word32)key->ecc.dp->size); } if (err == 0) { data += key->ecc.dp->size; /* Read the public key point's x value from key size bytes. */ - err = mp_read_unsigned_bin(key->ecc.pubkey.x, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(key->ecc.pubkey.x, data, + (word32)key->ecc.dp->size); } if (err == 0) { data += key->ecc.dp->size; /* Read the public key point's y value from key size bytes. */ - err = mp_read_unsigned_bin(key->ecc.pubkey.y, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(key->ecc.pubkey.y, data, + (word32)key->ecc.dp->size); } if (err == 0) { err = mp_set(key->ecc.pubkey.z, 1); @@ -707,7 +710,7 @@ int wc_ExportSakkePrivateKey(SakkeKey* key, byte* data, word32* sz) } if ((err == 0) && (data == NULL)) { - *sz = key->ecc.dp->size; + *sz = (word32)key->ecc.dp->size; err = LENGTH_ONLY_E; } if ((err >= 0) && (*sz < (word32)key->ecc.dp->size)) { @@ -719,7 +722,7 @@ int wc_ExportSakkePrivateKey(SakkeKey* key, byte* data, word32* sz) key->ecc.dp->size); } if (err == 0) { - *sz = key->ecc.dp->size; + *sz = (word32)key->ecc.dp->size; } return err; @@ -756,7 +759,7 @@ int wc_ImportSakkePrivateKey(SakkeKey* key, const byte* data, word32 sz) if (err == 0) { /* Read the secret value from key size bytes. */ err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data, - key->ecc.dp->size); + (word32)key->ecc.dp->size); } return err; @@ -838,12 +841,12 @@ static int sakke_encode_point(ecc_point* point, word32 size, byte* data, } /* Write out the point's x ordinate into key size bytes. */ - err = mp_to_unsigned_bin_len(point->x, data, size); + err = mp_to_unsigned_bin_len(point->x, data, (int)size); } if (err == 0) { data += size; /* Write out the point's y ordinate into key size bytes. */ - err = mp_to_unsigned_bin_len(point->y, data, size); + err = mp_to_unsigned_bin_len(point->y, data, (int)size); } if (err == 0) { *sz = size * 2 + !raw; @@ -2491,7 +2494,7 @@ int wc_GetSakkeAuthSize(SakkeKey* key, word16* authSz) } if (err == 0) { word16 n = (word16)((mp_count_bits(&key->params.prime) + 7) / 8); - *authSz = 1 + 2 * n; + *authSz = (word16)(1 + 2 * n); } return err; @@ -6131,8 +6134,8 @@ static int sakke_calc_h_v(SakkeKey* key, enum wc_HashType hashType, * @param [in] idx Index to start XORing into. * @param [in] n Length of data to XOR (mask) in bytes. */ -static void sakke_xor_in_v(const byte* v, word32 hashSz, byte* out, int idx, - int n) +static void sakke_xor_in_v(const byte* v, word32 hashSz, byte* out, word32 idx, + word32 n) { int o; word32 i; @@ -6146,7 +6149,7 @@ static void sakke_xor_in_v(const byte* v, word32 hashSz, byte* out, int idx, else { i = 0; } - o = i; + o = (int)i; xorbuf(out + idx + i - o, v + i, hashSz - i); } @@ -6389,7 +6392,7 @@ int wc_GetSakkePointI(SakkeKey* key, byte* data, word32* sz) } if ((err == 0) && (data == NULL)) { - *sz = key->ecc.dp->size * 2; + *sz = (word32)(key->ecc.dp->size * 2); err = LENGTH_ONLY_E; } if ((err == 0) && (*sz < (word32)key->ecc.dp->size * 2)) { @@ -6406,7 +6409,7 @@ int wc_GetSakkePointI(SakkeKey* key, byte* data, word32* sz) err = mp_to_unsigned_bin_len(key->i.i->y, data, key->ecc.dp->size); } if (err == 0) { - *sz = key->ecc.dp->size * 2; + *sz = (word32)(key->ecc.dp->size * 2); } return err; @@ -6444,12 +6447,14 @@ int wc_SetSakkePointI(SakkeKey* key, const byte* id, word16 idSz, if (err == 0) { /* Read the x value from key size bytes. */ - err = mp_read_unsigned_bin(key->i.i->x, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(key->i.i->x, data, + (word32)key->ecc.dp->size); } if (err == 0) { data += key->ecc.dp->size; /* Read the y value from key size bytes. */ - err = mp_read_unsigned_bin(key->i.i->y, data, key->ecc.dp->size); + err = mp_read_unsigned_bin(key->i.i->y, data, + (word32)key->ecc.dp->size); } if (err == 0) { err = mp_set(key->i.i->z, 1); @@ -6687,7 +6692,7 @@ int wc_MakeSakkeEncapsulatedSSV(SakkeKey* key, enum wc_HashType hashType, n = (word16)((mp_count_bits(&key->params.prime) + 7) / 8); /* Uncompressed point */ - outSz = 1 + 2 * n; + outSz = (word16)(1 + 2 * n); if ((auth != NULL) && (*authSz < outSz)) { err = BAD_FUNC_ARG; @@ -6876,7 +6881,7 @@ int wc_DeriveSakkeSSV(SakkeKey* key, enum wc_HashType hashType, byte* ssv, if (err == 0) { r = key->tmp.p2; - err = wc_ecc_import_point_der(auth, n * 2 + 1, + err = wc_ecc_import_point_der(auth, (word32)(n * 2 + 1), wc_ecc_get_curve_idx(key->ecc.dp->id), r); } @@ -6916,7 +6921,7 @@ int wc_DeriveSakkeSSV(SakkeKey* key, enum wc_HashType hashType, byte* ssv, err = sakke_compute_point_r(key, key->id, key->idSz, ri, n, test); } - if ((err == 0) && (XMEMCMP(auth, test, 2 * n + 1) != 0)) { + if ((err == 0) && (XMEMCMP(auth, test, (size_t)(2 * n + 1)) != 0)) { err = SAKKE_VERIFY_FAIL_E; } diff --git a/wolfssl/wolfcrypt/sakke.h b/wolfssl/wolfcrypt/sakke.h index f6651279b83..173c33bb980 100644 --- a/wolfssl/wolfcrypt/sakke.h +++ b/wolfssl/wolfcrypt/sakke.h @@ -100,7 +100,7 @@ typedef struct SakkeKeyPointI { /** Table associated with point I. */ byte* table; /** Length of table */ - int tableLen; + word32 tableLen; /** Identity associated with point I. */ byte id[SAKKE_ID_MAX_SIZE]; /** Size of identity associated with point I. */ @@ -114,7 +114,7 @@ typedef struct SakkeKeyRsk { /** Table associated with point I. */ byte* table; /** Length of table */ - int tableLen; + word32 tableLen; /** Indicates whether an RSK value has been set. */ byte set:1; } SakkeKeyRsk; From 7bbe2df8b5da4cf60cb1a484f11b270eb4abe594 Mon Sep 17 00:00:00 2001 From: kaleb-himes Date: Mon, 5 Jun 2023 09:22:08 -0600 Subject: [PATCH 355/391] Update error return(s) for wc_RsaPSS_Verify --- doc/dox_comments/header_files/rsa.h | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/dox_comments/header_files/rsa.h b/doc/dox_comments/header_files/rsa.h index cc95a663ded..4b43a2991ed 100644 --- a/doc/dox_comments/header_files/rsa.h +++ b/doc/dox_comments/header_files/rsa.h @@ -426,6 +426,7 @@ int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, \return Success Length of text on no error. \return MEMORY_E memory exception. + \return MP_EXPTMOD_E - When using fastmath and FP_MAX_BITS not set to at least 2 times the keySize (Example when using 4096-bit key set FP_MAX_BITS to 8192 or greater value) \param in The byte array to be decrypted. \param inLen The length of in. From adb14f82865fb48940e68bb5ae73521ffffbcdbd Mon Sep 17 00:00:00 2001 From: jordan Date: Fri, 2 Jun 2023 22:11:44 -0500 Subject: [PATCH 356/391] Fix fastmath and heapmath invmod to be consistent with sp-math. --- wolfcrypt/src/integer.c | 17 ++++++++++++++--- wolfcrypt/src/tfm.c | 37 ++++++++++++++++++++++--------------- 2 files changed, 36 insertions(+), 18 deletions(-) diff --git a/wolfcrypt/src/integer.c b/wolfcrypt/src/integer.c index 01f07d295ab..5ea1cb5a642 100644 --- a/wolfcrypt/src/integer.c +++ b/wolfcrypt/src/integer.c @@ -1058,7 +1058,7 @@ int mp_invmod (mp_int * a, mp_int * b, mp_int * c) int fast_mp_invmod (mp_int * a, mp_int * b, mp_int * c) { mp_int x, y, u, v, B, D; - int res, neg, loop_check = 0; + int res, loop_check = 0; /* 2. [modified] b must be odd */ if (mp_iseven (b) == MP_YES) { @@ -1080,6 +1080,12 @@ int fast_mp_invmod (mp_int * a, mp_int * b, mp_int * c) goto LBL_ERR; } + if (mp_iszero (&y) == MP_YES) { + /* invmod doesn't exist for this a and b */ + res = MP_VAL; + goto LBL_ERR; + } + /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */ if ((res = mp_copy (&x, &u)) != MP_OKAY) { goto LBL_ERR; @@ -1168,7 +1174,6 @@ int fast_mp_invmod (mp_int * a, mp_int * b, mp_int * c) } /* b is now the inverse */ - neg = a->sign; while (D.sign == MP_NEG) { if ((res = mp_add (&D, b, &D)) != MP_OKAY) { goto LBL_ERR; @@ -1181,7 +1186,6 @@ int fast_mp_invmod (mp_int * a, mp_int * b, mp_int * c) } } mp_exch (&D, c); - c->sign = neg; res = MP_OKAY; LBL_ERR:mp_clear(&x); @@ -1226,6 +1230,13 @@ int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c) if ((res = mp_mod(a, b, &x)) != MP_OKAY) { goto LBL_ERR; } + + if (mp_iszero (&x) == MP_YES) { + /* invmod doesn't exist for this a and b */ + res = MP_VAL; + goto LBL_ERR; + } + if (mp_isone(&x)) { res = mp_set(c, 1); goto LBL_ERR; diff --git a/wolfcrypt/src/tfm.c b/wolfcrypt/src/tfm.c index fe8f5bffe9a..1ab156a24e9 100644 --- a/wolfcrypt/src/tfm.c +++ b/wolfcrypt/src/tfm.c @@ -1086,6 +1086,14 @@ static int fp_invmod_slow (fp_int * a, fp_int * b, fp_int * c) } fp_copy(b, y); + if (fp_iszero(x) == FP_YES) { + /* invmod doesn't exist for this a and b */ + #ifdef WOLFSSL_SMALL_STACK + XFREE(x, NULL, DYNAMIC_TYPE_BIGINT); + #endif + return FP_VAL; + } + /* 2. [modified] if x,y are both even then return an error! */ if (fp_iseven(x) == FP_YES && fp_iseven(y) == FP_YES) { #ifdef WOLFSSL_SMALL_STACK @@ -1258,7 +1266,6 @@ int fp_invmod(fp_int *a, fp_int *b, fp_int *c) #else fp_int *x, *y, *u, *v, *B, *D; #endif - int neg; int err; if (b->sign == FP_NEG || fp_iszero(b) == FP_YES) { @@ -1288,17 +1295,6 @@ int fp_invmod(fp_int *a, fp_int *b, fp_int *c) fp_init(u); fp_init(v); fp_init(B); fp_init(D); - if (fp_cmp(a, b) != MP_LT) { - err = mp_mod(a, b, y); - if (err != FP_OKAY) { - #ifdef WOLFSSL_SMALL_STACK - XFREE(x, NULL, DYNAMIC_TYPE_BIGINT); - #endif - return err; - } - a = y; - } - if (fp_iszero(a) == FP_YES) { #ifdef WOLFSSL_SMALL_STACK XFREE(x, NULL, DYNAMIC_TYPE_BIGINT); @@ -1310,7 +1306,20 @@ int fp_invmod(fp_int *a, fp_int *b, fp_int *c) fp_copy(b, x); /* we need y = |a| */ - fp_abs(a, y); + if ((err = mp_mod(a, b, y)) != FP_OKAY) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(x, NULL, DYNAMIC_TYPE_BIGINT); + #endif + return err; + } + + if (fp_iszero(y) == FP_YES) { + /* invmod doesn't exist for this a and b */ + #ifdef WOLFSSL_SMALL_STACK + XFREE(x, NULL, DYNAMIC_TYPE_BIGINT); + #endif + return FP_VAL; + } /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */ fp_copy(x, u); @@ -1408,7 +1417,6 @@ int fp_invmod(fp_int *a, fp_int *b, fp_int *c) } /* b is now the inverse */ - neg = a->sign; while (D->sign == FP_NEG) { err = fp_add (D, b, D); if (err != FP_OKAY) { @@ -1429,7 +1437,6 @@ int fp_invmod(fp_int *a, fp_int *b, fp_int *c) } } fp_copy (D, c); - c->sign = neg; #ifdef WOLFSSL_SMALL_STACK XFREE(x, NULL, DYNAMIC_TYPE_BIGINT); #endif From 383e2fccf5ff7893eb8673365250d902e4b85a4f Mon Sep 17 00:00:00 2001 From: Lealem Amedie Date: Tue, 6 Jun 2023 13:34:22 -0600 Subject: [PATCH 357/391] XCODE project: install all headers --- IDE/XCODE/user_settings.h | 4 +- .../wolfssl-FIPS.xcodeproj/project.pbxproj | 191 ++++++++- IDE/XCODE/wolfssl.xcodeproj/project.pbxproj | 400 ++++++++++++++++++ 3 files changed, 573 insertions(+), 22 deletions(-) diff --git a/IDE/XCODE/user_settings.h b/IDE/XCODE/user_settings.h index cd6b39fa027..5ac0b5c3f1c 100644 --- a/IDE/XCODE/user_settings.h +++ b/IDE/XCODE/user_settings.h @@ -17,8 +17,8 @@ /* 128-bit type */ #define HAVE___UINT128_T - /* fast math */ - #define USE_FAST_MATH + /* SP Math */ + #define WOLFSSL_SP_MATH #define HAVE_ECC /* ECC speedups */ diff --git a/IDE/XCODE/wolfssl-FIPS.xcodeproj/project.pbxproj b/IDE/XCODE/wolfssl-FIPS.xcodeproj/project.pbxproj index 00672d61eaf..a5905880eb5 100644 --- a/IDE/XCODE/wolfssl-FIPS.xcodeproj/project.pbxproj +++ b/IDE/XCODE/wolfssl-FIPS.xcodeproj/project.pbxproj @@ -96,15 +96,15 @@ 521646F51A8A7FF30062516A /* types.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646871A8993770062516A /* types.h */; }; 521646F61A8A7FF30062516A /* visibility.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646881A8993770062516A /* visibility.h */; }; 521646F71A8A7FF30062516A /* wc_port.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646891A8993770062516A /* wc_port.h */; }; - 521646F81A8A80030062516A /* callbacks.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 5216468A1A8993BB0062516A /* callbacks.h */; }; - 521646F91A8A80030062516A /* certs_test.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 5216468B1A8993BB0062516A /* certs_test.h */; }; - 521646FA1A8A80030062516A /* crl.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 5216468C1A8993BB0062516A /* crl.h */; }; - 521646FB1A8A80030062516A /* error-ssl.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 5216468D1A8993BB0062516A /* error-ssl.h */; }; - 521646FC1A8A80030062516A /* internal.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 5216468E1A8993BB0062516A /* internal.h */; }; - 521646FD1A8A80030062516A /* ocsp.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 5216468F1A8993BB0062516A /* ocsp.h */; }; - 521646FE1A8A80030062516A /* ssl.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646921A8993BB0062516A /* ssl.h */; }; - 521646FF1A8A80030062516A /* test.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646931A8993BB0062516A /* test.h */; }; - 521647001A8A80030062516A /* version.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646941A8993BB0062516A /* version.h */; }; + 521646F81A8A80030062516A /* callbacks.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 5216468A1A8993BB0062516A /* callbacks.h */; }; + 521646F91A8A80030062516A /* certs_test.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 5216468B1A8993BB0062516A /* certs_test.h */; }; + 521646FA1A8A80030062516A /* crl.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 5216468C1A8993BB0062516A /* crl.h */; }; + 521646FB1A8A80030062516A /* error-ssl.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 5216468D1A8993BB0062516A /* error-ssl.h */; }; + 521646FC1A8A80030062516A /* internal.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 5216468E1A8993BB0062516A /* internal.h */; }; + 521646FD1A8A80030062516A /* ocsp.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 5216468F1A8993BB0062516A /* ocsp.h */; }; + 521646FE1A8A80030062516A /* ssl.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 521646921A8993BB0062516A /* ssl.h */; }; + 521646FF1A8A80030062516A /* test.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 521646931A8993BB0062516A /* test.h */; }; + 521647001A8A80030062516A /* version.h in Copy Files */ = {isa = PBXBuildFile; fileRef = 521646941A8993BB0062516A /* version.h */; }; 521647011A8A80100062516A /* aes.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646951A8993F50062516A /* aes.h */; }; 521647021A8A80100062516A /* arc4.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646961A8993F50062516A /* arc4.h */; }; 521647031A8A80100062516A /* asn_public.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 521646971A8993F50062516A /* asn_public.h */; }; @@ -165,6 +165,44 @@ 525BE5BC1B3885750054BBCD /* hash.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 525BE5BB1B3885580054BBCD /* hash.h */; }; 6AC85136272CAFEC00F2B32A /* kdf.c in Sources */ = {isa = PBXBuildFile; fileRef = 6AC85135272CAFEC00F2B32A /* kdf.c */; }; 6AC85137272CAFEC00F2B32A /* kdf.c in Sources */ = {isa = PBXBuildFile; fileRef = 6AC85135272CAFEC00F2B32A /* kdf.c */; }; + 700F0CED2A2FC11300755BA7 /* async.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CCB2A2FC0D500755BA7 /* async.h */; }; + 700F0CEE2A2FC11300755BA7 /* chacha20_poly1305.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CC62A2FC0D400755BA7 /* chacha20_poly1305.h */; }; + 700F0CEF2A2FC11300755BA7 /* cmac.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD72A2FC0D500755BA7 /* cmac.h */; }; + 700F0CF02A2FC11300755BA7 /* cpuid.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CCE2A2FC0D500755BA7 /* cpuid.h */; }; + 700F0CF12A2FC11300755BA7 /* cryptocb.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CE02A2FC0D500755BA7 /* cryptocb.h */; }; + 700F0CF22A2FC11300755BA7 /* curve448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD32A2FC0D500755BA7 /* curve448.h */; }; + 700F0CF32A2FC11300755BA7 /* curve25519.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CC82A2FC0D500755BA7 /* curve25519.h */; }; + 700F0CF42A2FC11300755BA7 /* dilithium.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CE52A2FC0D500755BA7 /* dilithium.h */; }; + 700F0CF52A2FC11300755BA7 /* eccsi.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CDB2A2FC0D500755BA7 /* eccsi.h */; }; + 700F0CF62A2FC11300755BA7 /* ed448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD22A2FC0D500755BA7 /* ed448.h */; }; + 700F0CF72A2FC11300755BA7 /* ed25519.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CE12A2FC0D500755BA7 /* ed25519.h */; }; + 700F0CF82A2FC11300755BA7 /* ext_kyber.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD52A2FC0D500755BA7 /* ext_kyber.h */; }; + 700F0CF92A2FC11300755BA7 /* falcon.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CDD2A2FC0D500755BA7 /* falcon.h */; }; + 700F0CFA2A2FC11300755BA7 /* fe_448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CDE2A2FC0D500755BA7 /* fe_448.h */; }; + 700F0CFB2A2FC11300755BA7 /* fe_operations.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CC72A2FC0D400755BA7 /* fe_operations.h */; }; + 700F0CFC2A2FC11300755BA7 /* fips.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CCF2A2FC0D500755BA7 /* fips.h */; }; + 700F0CFD2A2FC11300755BA7 /* ge_448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CE22A2FC0D500755BA7 /* ge_448.h */; }; + 700F0CFE2A2FC11300755BA7 /* ge_operations.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CCA2A2FC0D500755BA7 /* ge_operations.h */; }; + 700F0CFF2A2FC11300755BA7 /* hpke.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CCD2A2FC0D500755BA7 /* hpke.h */; }; + 700F0D002A2FC11300755BA7 /* kyber.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CCC2A2FC0D500755BA7 /* kyber.h */; }; + 700F0D012A2FC11300755BA7 /* mem_track.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CDA2A2FC0D500755BA7 /* mem_track.h */; }; + 700F0D022A2FC11300755BA7 /* pkcs11.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD92A2FC0D500755BA7 /* pkcs11.h */; }; + 700F0D032A2FC11300755BA7 /* pkcs12.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CE42A2FC0D500755BA7 /* pkcs12.h */; }; + 700F0D042A2FC11300755BA7 /* rc2.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CEA2A2FC0D500755BA7 /* rc2.h */; }; + 700F0D052A2FC11300755BA7 /* sakke.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CE62A2FC0D500755BA7 /* sakke.h */; }; + 700F0D062A2FC11300755BA7 /* selftest.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CC92A2FC0D500755BA7 /* selftest.h */; }; + 700F0D072A2FC11300755BA7 /* sha3.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD02A2FC0D500755BA7 /* sha3.h */; }; + 700F0D082A2FC11300755BA7 /* signature.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CE72A2FC0D500755BA7 /* signature.h */; }; + 700F0D092A2FC11300755BA7 /* siphash.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD42A2FC0D500755BA7 /* siphash.h */; }; + 700F0D0A2A2FC11300755BA7 /* sp_int.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CDF2A2FC0D500755BA7 /* sp_int.h */; }; + 700F0D0B2A2FC11300755BA7 /* sp.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD12A2FC0D500755BA7 /* sp.h */; }; + 700F0D0C2A2FC11300755BA7 /* sphincs.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CEC2A2FC0D500755BA7 /* sphincs.h */; }; + 700F0D0D2A2FC11300755BA7 /* srp.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CDC2A2FC0D500755BA7 /* srp.h */; }; + 700F0D0E2A2FC11300755BA7 /* wc_kyber.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD82A2FC0D500755BA7 /* wc_kyber.h */; }; + 700F0D0F2A2FC11300755BA7 /* wc_pkcs11.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CE82A2FC0D500755BA7 /* wc_pkcs11.h */; }; + 700F0D102A2FC11300755BA7 /* wolfevent.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CD62A2FC0D500755BA7 /* wolfevent.h */; }; + 700F0D112A2FC11300755BA7 /* wolfmath.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0CEB2A2FC0D500755BA7 /* wolfmath.h */; }; + 700F0D122A2FC11300755BA7 /* kdf.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 6AC8513A272CB01200F2B32A /* kdf.h */; }; 9D2E31D7291CE2190082B941 /* dtls13.c in Sources */ = {isa = PBXBuildFile; fileRef = 9D2E31D6291CE2190082B941 /* dtls13.c */; }; 9D2E31D8291CE2190082B941 /* dtls13.c in Sources */ = {isa = PBXBuildFile; fileRef = 9D2E31D6291CE2190082B941 /* dtls13.c */; }; 9D2E31DA291CE2370082B941 /* dtls.c in Sources */ = {isa = PBXBuildFile; fileRef = 9D2E31D9291CE2370082B941 /* dtls.c */; }; @@ -338,6 +376,44 @@ dstPath = include/wolfssl/wolfcrypt; dstSubfolderSpec = 7; files = ( + 700F0CED2A2FC11300755BA7 /* async.h in CopyFiles */, + 700F0CEE2A2FC11300755BA7 /* chacha20_poly1305.h in CopyFiles */, + 700F0CEF2A2FC11300755BA7 /* cmac.h in CopyFiles */, + 700F0CF02A2FC11300755BA7 /* cpuid.h in CopyFiles */, + 700F0CF12A2FC11300755BA7 /* cryptocb.h in CopyFiles */, + 700F0CF22A2FC11300755BA7 /* curve448.h in CopyFiles */, + 700F0CF32A2FC11300755BA7 /* curve25519.h in CopyFiles */, + 700F0CF42A2FC11300755BA7 /* dilithium.h in CopyFiles */, + 700F0CF52A2FC11300755BA7 /* eccsi.h in CopyFiles */, + 700F0CF62A2FC11300755BA7 /* ed448.h in CopyFiles */, + 700F0CF72A2FC11300755BA7 /* ed25519.h in CopyFiles */, + 700F0CF82A2FC11300755BA7 /* ext_kyber.h in CopyFiles */, + 700F0CF92A2FC11300755BA7 /* falcon.h in CopyFiles */, + 700F0CFA2A2FC11300755BA7 /* fe_448.h in CopyFiles */, + 700F0CFB2A2FC11300755BA7 /* fe_operations.h in CopyFiles */, + 700F0CFC2A2FC11300755BA7 /* fips.h in CopyFiles */, + 700F0CFD2A2FC11300755BA7 /* ge_448.h in CopyFiles */, + 700F0CFE2A2FC11300755BA7 /* ge_operations.h in CopyFiles */, + 700F0CFF2A2FC11300755BA7 /* hpke.h in CopyFiles */, + 700F0D002A2FC11300755BA7 /* kyber.h in CopyFiles */, + 700F0D012A2FC11300755BA7 /* mem_track.h in CopyFiles */, + 700F0D022A2FC11300755BA7 /* pkcs11.h in CopyFiles */, + 700F0D032A2FC11300755BA7 /* pkcs12.h in CopyFiles */, + 700F0D042A2FC11300755BA7 /* rc2.h in CopyFiles */, + 700F0D052A2FC11300755BA7 /* sakke.h in CopyFiles */, + 700F0D062A2FC11300755BA7 /* selftest.h in CopyFiles */, + 700F0D072A2FC11300755BA7 /* sha3.h in CopyFiles */, + 700F0D082A2FC11300755BA7 /* signature.h in CopyFiles */, + 700F0D092A2FC11300755BA7 /* siphash.h in CopyFiles */, + 700F0D0A2A2FC11300755BA7 /* sp_int.h in CopyFiles */, + 700F0D0B2A2FC11300755BA7 /* sp.h in CopyFiles */, + 700F0D0C2A2FC11300755BA7 /* sphincs.h in CopyFiles */, + 700F0D0D2A2FC11300755BA7 /* srp.h in CopyFiles */, + 700F0D0E2A2FC11300755BA7 /* wc_kyber.h in CopyFiles */, + 700F0D0F2A2FC11300755BA7 /* wc_pkcs11.h in CopyFiles */, + 700F0D102A2FC11300755BA7 /* wolfevent.h in CopyFiles */, + 700F0D112A2FC11300755BA7 /* wolfmath.h in CopyFiles */, + 700F0D122A2FC11300755BA7 /* kdf.h in CopyFiles */, 522DBE131B792A190031F454 /* wc_encrypt.h in CopyFiles */, 525BE5BC1B3885750054BBCD /* hash.h in CopyFiles */, 521646CD1A8A7FF30062516A /* aes.h in CopyFiles */, @@ -384,22 +460,23 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 521646C21A8A7B3B0062516A /* CopyFiles */ = { + 521646C21A8A7B3B0062516A /* Copy Files */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = include/cyassl; dstSubfolderSpec = 7; files = ( - 521646F81A8A80030062516A /* callbacks.h in CopyFiles */, - 521646F91A8A80030062516A /* certs_test.h in CopyFiles */, - 521646FA1A8A80030062516A /* crl.h in CopyFiles */, - 521646FB1A8A80030062516A /* error-ssl.h in CopyFiles */, - 521646FC1A8A80030062516A /* internal.h in CopyFiles */, - 521646FD1A8A80030062516A /* ocsp.h in CopyFiles */, - 521646FE1A8A80030062516A /* ssl.h in CopyFiles */, - 521646FF1A8A80030062516A /* test.h in CopyFiles */, - 521647001A8A80030062516A /* version.h in CopyFiles */, + 521646F81A8A80030062516A /* callbacks.h in Copy Files */, + 521646F91A8A80030062516A /* certs_test.h in Copy Files */, + 521646FA1A8A80030062516A /* crl.h in Copy Files */, + 521646FB1A8A80030062516A /* error-ssl.h in Copy Files */, + 521646FC1A8A80030062516A /* internal.h in Copy Files */, + 521646FD1A8A80030062516A /* ocsp.h in Copy Files */, + 521646FE1A8A80030062516A /* ssl.h in Copy Files */, + 521646FF1A8A80030062516A /* test.h in Copy Files */, + 521647001A8A80030062516A /* version.h in Copy Files */, ); + name = "Copy Files"; runOnlyForDeploymentPostprocessing = 0; }; 521646C31A8A7B3D0062516A /* CopyFiles */ = { @@ -772,6 +849,43 @@ 52B1344D16F3C9E800C07B32 /* libwolfssl_fips_ios.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libwolfssl_fips_ios.a; sourceTree = BUILT_PRODUCTS_DIR; }; 6AC85135272CAFEC00F2B32A /* kdf.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = kdf.c; path = ../../wolfcrypt/src/kdf.c; sourceTree = ""; }; 6AC8513A272CB01200F2B32A /* kdf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = kdf.h; path = ../../wolfssl/wolfcrypt/kdf.h; sourceTree = ""; }; + 700F0CC62A2FC0D400755BA7 /* chacha20_poly1305.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = chacha20_poly1305.h; path = ../../wolfssl/wolfcrypt/chacha20_poly1305.h; sourceTree = ""; }; + 700F0CC72A2FC0D400755BA7 /* fe_operations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fe_operations.h; path = ../../wolfssl/wolfcrypt/fe_operations.h; sourceTree = ""; }; + 700F0CC82A2FC0D500755BA7 /* curve25519.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = curve25519.h; path = ../../wolfssl/wolfcrypt/curve25519.h; sourceTree = ""; }; + 700F0CC92A2FC0D500755BA7 /* selftest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = selftest.h; path = ../../wolfssl/wolfcrypt/selftest.h; sourceTree = ""; }; + 700F0CCA2A2FC0D500755BA7 /* ge_operations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ge_operations.h; path = ../../wolfssl/wolfcrypt/ge_operations.h; sourceTree = ""; }; + 700F0CCB2A2FC0D500755BA7 /* async.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = async.h; path = ../../wolfssl/wolfcrypt/async.h; sourceTree = ""; }; + 700F0CCC2A2FC0D500755BA7 /* kyber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = kyber.h; path = ../../wolfssl/wolfcrypt/kyber.h; sourceTree = ""; }; + 700F0CCD2A2FC0D500755BA7 /* hpke.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = hpke.h; path = ../../wolfssl/wolfcrypt/hpke.h; sourceTree = ""; }; + 700F0CCE2A2FC0D500755BA7 /* cpuid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cpuid.h; path = ../../wolfssl/wolfcrypt/cpuid.h; sourceTree = ""; }; + 700F0CCF2A2FC0D500755BA7 /* fips.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fips.h; path = ../../wolfssl/wolfcrypt/fips.h; sourceTree = ""; }; + 700F0CD02A2FC0D500755BA7 /* sha3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sha3.h; path = ../../wolfssl/wolfcrypt/sha3.h; sourceTree = ""; }; + 700F0CD12A2FC0D500755BA7 /* sp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sp.h; path = ../../wolfssl/wolfcrypt/sp.h; sourceTree = ""; }; + 700F0CD22A2FC0D500755BA7 /* ed448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ed448.h; path = ../../wolfssl/wolfcrypt/ed448.h; sourceTree = ""; }; + 700F0CD32A2FC0D500755BA7 /* curve448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = curve448.h; path = ../../wolfssl/wolfcrypt/curve448.h; sourceTree = ""; }; + 700F0CD42A2FC0D500755BA7 /* siphash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = siphash.h; path = ../../wolfssl/wolfcrypt/siphash.h; sourceTree = ""; }; + 700F0CD52A2FC0D500755BA7 /* ext_kyber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ext_kyber.h; path = ../../wolfssl/wolfcrypt/ext_kyber.h; sourceTree = ""; }; + 700F0CD62A2FC0D500755BA7 /* wolfevent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = wolfevent.h; path = ../../wolfssl/wolfcrypt/wolfevent.h; sourceTree = ""; }; + 700F0CD72A2FC0D500755BA7 /* cmac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cmac.h; path = ../../wolfssl/wolfcrypt/cmac.h; sourceTree = ""; }; + 700F0CD82A2FC0D500755BA7 /* wc_kyber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = wc_kyber.h; path = ../../wolfssl/wolfcrypt/wc_kyber.h; sourceTree = ""; }; + 700F0CD92A2FC0D500755BA7 /* pkcs11.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pkcs11.h; path = ../../wolfssl/wolfcrypt/pkcs11.h; sourceTree = ""; }; + 700F0CDA2A2FC0D500755BA7 /* mem_track.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = mem_track.h; path = ../../wolfssl/wolfcrypt/mem_track.h; sourceTree = ""; }; + 700F0CDB2A2FC0D500755BA7 /* eccsi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = eccsi.h; path = ../../wolfssl/wolfcrypt/eccsi.h; sourceTree = ""; }; + 700F0CDC2A2FC0D500755BA7 /* srp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = srp.h; path = ../../wolfssl/wolfcrypt/srp.h; sourceTree = ""; }; + 700F0CDD2A2FC0D500755BA7 /* falcon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = falcon.h; path = ../../wolfssl/wolfcrypt/falcon.h; sourceTree = ""; }; + 700F0CDE2A2FC0D500755BA7 /* fe_448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fe_448.h; path = ../../wolfssl/wolfcrypt/fe_448.h; sourceTree = ""; }; + 700F0CDF2A2FC0D500755BA7 /* sp_int.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sp_int.h; path = ../../wolfssl/wolfcrypt/sp_int.h; sourceTree = ""; }; + 700F0CE02A2FC0D500755BA7 /* cryptocb.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cryptocb.h; path = ../../wolfssl/wolfcrypt/cryptocb.h; sourceTree = ""; }; + 700F0CE12A2FC0D500755BA7 /* ed25519.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ed25519.h; path = ../../wolfssl/wolfcrypt/ed25519.h; sourceTree = ""; }; + 700F0CE22A2FC0D500755BA7 /* ge_448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ge_448.h; path = ../../wolfssl/wolfcrypt/ge_448.h; sourceTree = ""; }; + 700F0CE42A2FC0D500755BA7 /* pkcs12.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pkcs12.h; path = ../../wolfssl/wolfcrypt/pkcs12.h; sourceTree = ""; }; + 700F0CE52A2FC0D500755BA7 /* dilithium.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dilithium.h; path = ../../wolfssl/wolfcrypt/dilithium.h; sourceTree = ""; }; + 700F0CE62A2FC0D500755BA7 /* sakke.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sakke.h; path = ../../wolfssl/wolfcrypt/sakke.h; sourceTree = ""; }; + 700F0CE72A2FC0D500755BA7 /* signature.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = signature.h; path = ../../wolfssl/wolfcrypt/signature.h; sourceTree = ""; }; + 700F0CE82A2FC0D500755BA7 /* wc_pkcs11.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = wc_pkcs11.h; path = ../../wolfssl/wolfcrypt/wc_pkcs11.h; sourceTree = ""; }; + 700F0CEA2A2FC0D500755BA7 /* rc2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = rc2.h; path = ../../wolfssl/wolfcrypt/rc2.h; sourceTree = ""; }; + 700F0CEB2A2FC0D500755BA7 /* wolfmath.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = wolfmath.h; path = ../../wolfssl/wolfcrypt/wolfmath.h; sourceTree = ""; }; + 700F0CEC2A2FC0D500755BA7 /* sphincs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sphincs.h; path = ../../wolfssl/wolfcrypt/sphincs.h; sourceTree = ""; }; 9D2E31D6291CE2190082B941 /* dtls13.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = dtls13.c; path = ../../src/dtls13.c; sourceTree = ""; }; 9D2E31D9291CE2370082B941 /* dtls.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = dtls.c; path = ../../src/dtls.c; sourceTree = ""; }; 9D2E31DC291CE2740082B941 /* quic.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = quic.c; path = ../../src/quic.c; sourceTree = ""; }; @@ -877,6 +991,43 @@ 521645F81A89916A0062516A /* wolfCrypt */ = { isa = PBXGroup; children = ( + 700F0CCB2A2FC0D500755BA7 /* async.h */, + 700F0CC62A2FC0D400755BA7 /* chacha20_poly1305.h */, + 700F0CD72A2FC0D500755BA7 /* cmac.h */, + 700F0CCE2A2FC0D500755BA7 /* cpuid.h */, + 700F0CE02A2FC0D500755BA7 /* cryptocb.h */, + 700F0CD32A2FC0D500755BA7 /* curve448.h */, + 700F0CC82A2FC0D500755BA7 /* curve25519.h */, + 700F0CE52A2FC0D500755BA7 /* dilithium.h */, + 700F0CDB2A2FC0D500755BA7 /* eccsi.h */, + 700F0CD22A2FC0D500755BA7 /* ed448.h */, + 700F0CE12A2FC0D500755BA7 /* ed25519.h */, + 700F0CD52A2FC0D500755BA7 /* ext_kyber.h */, + 700F0CDD2A2FC0D500755BA7 /* falcon.h */, + 700F0CDE2A2FC0D500755BA7 /* fe_448.h */, + 700F0CC72A2FC0D400755BA7 /* fe_operations.h */, + 700F0CCF2A2FC0D500755BA7 /* fips.h */, + 700F0CE22A2FC0D500755BA7 /* ge_448.h */, + 700F0CCA2A2FC0D500755BA7 /* ge_operations.h */, + 700F0CCD2A2FC0D500755BA7 /* hpke.h */, + 700F0CCC2A2FC0D500755BA7 /* kyber.h */, + 700F0CDA2A2FC0D500755BA7 /* mem_track.h */, + 700F0CD92A2FC0D500755BA7 /* pkcs11.h */, + 700F0CE42A2FC0D500755BA7 /* pkcs12.h */, + 700F0CEA2A2FC0D500755BA7 /* rc2.h */, + 700F0CE62A2FC0D500755BA7 /* sakke.h */, + 700F0CC92A2FC0D500755BA7 /* selftest.h */, + 700F0CD02A2FC0D500755BA7 /* sha3.h */, + 700F0CE72A2FC0D500755BA7 /* signature.h */, + 700F0CD42A2FC0D500755BA7 /* siphash.h */, + 700F0CDF2A2FC0D500755BA7 /* sp_int.h */, + 700F0CD12A2FC0D500755BA7 /* sp.h */, + 700F0CEC2A2FC0D500755BA7 /* sphincs.h */, + 700F0CDC2A2FC0D500755BA7 /* srp.h */, + 700F0CD82A2FC0D500755BA7 /* wc_kyber.h */, + 700F0CE82A2FC0D500755BA7 /* wc_pkcs11.h */, + 700F0CD62A2FC0D500755BA7 /* wolfevent.h */, + 700F0CEB2A2FC0D500755BA7 /* wolfmath.h */, 5216465E1A8993770062516A /* aes.h */, 5216465F1A8993770062516A /* arc4.h */, 521646601A8993770062516A /* asn_public.h */, @@ -1059,7 +1210,7 @@ 52B1344A16F3C9E800C07B32 /* Frameworks */, 52B1344B16F3C9E800C07B32 /* CopyFiles */, 521646C11A8A7B380062516A /* CopyFiles */, - 521646C21A8A7B3B0062516A /* CopyFiles */, + 521646C21A8A7B3B0062516A /* Copy Files */, 521646C31A8A7B3D0062516A /* CopyFiles */, 52B1344916F3C9E800C07B32 /* Sources */, ); diff --git a/IDE/XCODE/wolfssl.xcodeproj/project.pbxproj b/IDE/XCODE/wolfssl.xcodeproj/project.pbxproj index 8c2173b4f83..7c135155736 100644 --- a/IDE/XCODE/wolfssl.xcodeproj/project.pbxproj +++ b/IDE/XCODE/wolfssl.xcodeproj/project.pbxproj @@ -347,6 +347,102 @@ 6AC85129272CAF2E00F2B32A /* kdf.c in Sources */ = {isa = PBXBuildFile; fileRef = 6AC85128272CAF2E00F2B32A /* kdf.c */; }; 6AC8512A272CAF2E00F2B32A /* kdf.c in Sources */ = {isa = PBXBuildFile; fileRef = 6AC85128272CAF2E00F2B32A /* kdf.c */; }; 6AC8512B272CAF2E00F2B32A /* kdf.c in Sources */ = {isa = PBXBuildFile; fileRef = 6AC85128272CAF2E00F2B32A /* kdf.c */; }; + 700F0C052A2FBC5100755BA7 /* async.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C032A2FBC1600755BA7 /* async.h */; }; + 700F0C062A2FBC5100755BA7 /* chacha20_poly1305.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BED2A2FBC1500755BA7 /* chacha20_poly1305.h */; }; + 700F0C072A2FBC5100755BA7 /* cmac.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BFC2A2FBC1600755BA7 /* cmac.h */; }; + 700F0C082A2FBC5100755BA7 /* cpuid.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF12A2FBC1600755BA7 /* cpuid.h */; }; + 700F0C092A2FBC5100755BA7 /* cryptocb.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BEE2A2FBC1500755BA7 /* cryptocb.h */; }; + 700F0C0A2A2FBC5100755BA7 /* curve448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE32A2FBC1500755BA7 /* curve448.h */; }; + 700F0C0B2A2FBC5100755BA7 /* curve25519.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE52A2FBC1500755BA7 /* curve25519.h */; }; + 700F0C0C2A2FBC5100755BA7 /* dilithium.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BEF2A2FBC1500755BA7 /* dilithium.h */; }; + 700F0C0D2A2FBC5100755BA7 /* eccsi.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF72A2FBC1600755BA7 /* eccsi.h */; }; + 700F0C0E2A2FBC5100755BA7 /* ed448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF82A2FBC1600755BA7 /* ed448.h */; }; + 700F0C0F2A2FBC5100755BA7 /* ed25519.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF42A2FBC1600755BA7 /* ed25519.h */; }; + 700F0C102A2FBC5100755BA7 /* ext_kyber.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF92A2FBC1600755BA7 /* ext_kyber.h */; }; + 700F0C112A2FBC5100755BA7 /* falcon.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C022A2FBC1600755BA7 /* falcon.h */; }; + 700F0C122A2FBC5100755BA7 /* fe_448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BEB2A2FBC1500755BA7 /* fe_448.h */; }; + 700F0C132A2FBC5100755BA7 /* fe_operations.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF62A2FBC1600755BA7 /* fe_operations.h */; }; + 700F0C142A2FBC5100755BA7 /* fips.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C002A2FBC1600755BA7 /* fips.h */; }; + 700F0C152A2FBC5100755BA7 /* ge_448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE72A2FBC1500755BA7 /* ge_448.h */; }; + 700F0C162A2FBC5100755BA7 /* ge_operations.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C012A2FBC1600755BA7 /* ge_operations.h */; }; + 700F0C172A2FBC5100755BA7 /* hpke.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE12A2FBC1500755BA7 /* hpke.h */; }; + 700F0C182A2FBC5100755BA7 /* kyber.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BEA2A2FBC1500755BA7 /* kyber.h */; }; + 700F0C192A2FBC5100755BA7 /* pkcs11.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BFD2A2FBC1600755BA7 /* pkcs11.h */; }; + 700F0C1A2A2FBC5100755BA7 /* pkcs12.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BEC2A2FBC1500755BA7 /* pkcs12.h */; }; + 700F0C1B2A2FBC5100755BA7 /* rc2.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE02A2FBC1500755BA7 /* rc2.h */; }; + 700F0C1C2A2FBC5100755BA7 /* sakke.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF02A2FBC1500755BA7 /* sakke.h */; }; + 700F0C1D2A2FBC5100755BA7 /* selftest.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF22A2FBC1600755BA7 /* selftest.h */; }; + 700F0C1E2A2FBC5100755BA7 /* sha3.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BFA2A2FBC1600755BA7 /* sha3.h */; }; + 700F0C1F2A2FBC5100755BA7 /* signature.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BFB2A2FBC1600755BA7 /* signature.h */; }; + 700F0C202A2FBC5100755BA7 /* siphash.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BFE2A2FBC1600755BA7 /* siphash.h */; }; + 700F0C212A2FBC5100755BA7 /* sp_int.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE82A2FBC1500755BA7 /* sp_int.h */; }; + 700F0C222A2FBC5100755BA7 /* sp.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE92A2FBC1500755BA7 /* sp.h */; }; + 700F0C232A2FBC5100755BA7 /* sphincs.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE22A2FBC1500755BA7 /* sphincs.h */; }; + 700F0C242A2FBC5100755BA7 /* srp.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF32A2FBC1600755BA7 /* srp.h */; }; + 700F0C252A2FBC5100755BA7 /* wc_kyber.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BFF2A2FBC1600755BA7 /* wc_kyber.h */; }; + 700F0C262A2FBC5100755BA7 /* wc_pkcs11.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BF52A2FBC1600755BA7 /* wc_pkcs11.h */; }; + 700F0C272A2FBC5100755BA7 /* wolfevent.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0BE62A2FBC1500755BA7 /* wolfevent.h */; }; + 700F0C282A2FBC5100755BA7 /* kdf.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 6AC8513B272CB04F00F2B32A /* kdf.h */; }; + 700F0C2C2A2FBD1700755BA7 /* quic.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C292A2FBCAD00755BA7 /* quic.h */; }; + 700F0C2D2A2FBD1700755BA7 /* sniffer.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C2B2A2FBCF800755BA7 /* sniffer.h */; }; + 700F0C2E2A2FBD1700755BA7 /* sniffer_error.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C2A2A2FBCAD00755BA7 /* sniffer_error.h */; }; + 700F0C8C2A2FBEF100755BA7 /* aes.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C7C2A2FBE8200755BA7 /* aes.h */; }; + 700F0C8D2A2FBEF100755BA7 /* asn1.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C512A2FBE8000755BA7 /* asn1.h */; }; + 700F0C8E2A2FBEF100755BA7 /* asn1t.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C722A2FBE8100755BA7 /* asn1t.h */; }; + 700F0C8F2A2FBEF100755BA7 /* bio.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C582A2FBE8100755BA7 /* bio.h */; }; + 700F0C902A2FBEF100755BA7 /* bn.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C692A2FBE8100755BA7 /* bn.h */; }; + 700F0C912A2FBEF100755BA7 /* buffer.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C852A2FBE8200755BA7 /* buffer.h */; }; + 700F0C922A2FBEF100755BA7 /* camellia.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C5B2A2FBE8100755BA7 /* camellia.h */; }; + 700F0C932A2FBEF100755BA7 /* cmac.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C632A2FBE8100755BA7 /* cmac.h */; }; + 700F0C942A2FBEF100755BA7 /* cms.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C5E2A2FBE8100755BA7 /* cms.h */; }; + 700F0C952A2FBEF100755BA7 /* compat_types.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C532A2FBE8100755BA7 /* compat_types.h */; }; + 700F0C962A2FBEF100755BA7 /* conf.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C662A2FBE8100755BA7 /* conf.h */; }; + 700F0C972A2FBEF100755BA7 /* crypto.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C862A2FBE8200755BA7 /* crypto.h */; }; + 700F0C982A2FBEF100755BA7 /* des.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C612A2FBE8100755BA7 /* des.h */; }; + 700F0C992A2FBEF100755BA7 /* dh.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C522A2FBE8100755BA7 /* dh.h */; }; + 700F0C9A2A2FBEF100755BA7 /* dsa.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C882A2FBE8200755BA7 /* dsa.h */; }; + 700F0C9B2A2FBEF100755BA7 /* ec.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C6F2A2FBE8100755BA7 /* ec.h */; }; + 700F0C9C2A2FBEF100755BA7 /* ec448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C672A2FBE8100755BA7 /* ec448.h */; }; + 700F0C9D2A2FBEF100755BA7 /* ec25519.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C602A2FBE8100755BA7 /* ec25519.h */; }; + 700F0C9E2A2FBEF100755BA7 /* ecdh.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C542A2FBE8100755BA7 /* ecdh.h */; }; + 700F0C9F2A2FBEF100755BA7 /* ecdsa.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C812A2FBE8200755BA7 /* ecdsa.h */; }; + 700F0CA02A2FBEF100755BA7 /* ed448.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C642A2FBE8100755BA7 /* ed448.h */; }; + 700F0CA12A2FBEF100755BA7 /* ed25519.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C7E2A2FBE8200755BA7 /* ed25519.h */; }; + 700F0CA22A2FBEF100755BA7 /* engine.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C5D2A2FBE8100755BA7 /* engine.h */; }; + 700F0CA32A2FBEF100755BA7 /* err.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C6A2A2FBE8100755BA7 /* err.h */; }; + 700F0CA42A2FBEF100755BA7 /* evp.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C5F2A2FBE8100755BA7 /* evp.h */; }; + 700F0CA52A2FBEF100755BA7 /* fips_rand.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C7F2A2FBE8200755BA7 /* fips_rand.h */; }; + 700F0CA62A2FBEF100755BA7 /* hmac.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C832A2FBE8200755BA7 /* hmac.h */; }; + 700F0CA82A2FBEF100755BA7 /* kdf.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C6E2A2FBE8100755BA7 /* kdf.h */; }; + 700F0CA92A2FBEF100755BA7 /* lhash.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C652A2FBE8100755BA7 /* lhash.h */; }; + 700F0CAA2A2FBEF100755BA7 /* md4.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C6D2A2FBE8100755BA7 /* md4.h */; }; + 700F0CAB2A2FBEF100755BA7 /* md5.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C702A2FBE8100755BA7 /* md5.h */; }; + 700F0CAC2A2FBEF100755BA7 /* modes.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C772A2FBE8200755BA7 /* modes.h */; }; + 700F0CAD2A2FBEF100755BA7 /* obj_mac.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C802A2FBE8200755BA7 /* obj_mac.h */; }; + 700F0CAE2A2FBEF100755BA7 /* objects.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C572A2FBE8100755BA7 /* objects.h */; }; + 700F0CAF2A2FBEF100755BA7 /* ocsp.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C842A2FBE8200755BA7 /* ocsp.h */; }; + 700F0CB02A2FBEF100755BA7 /* opensslconf.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C732A2FBE8100755BA7 /* opensslconf.h */; }; + 700F0CB12A2FBEF100755BA7 /* opensslv.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C7D2A2FBE8200755BA7 /* opensslv.h */; }; + 700F0CB22A2FBEF100755BA7 /* ossl_typ.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C792A2FBE8200755BA7 /* ossl_typ.h */; }; + 700F0CB32A2FBEF100755BA7 /* pem.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C6C2A2FBE8100755BA7 /* pem.h */; }; + 700F0CB42A2FBEF100755BA7 /* pkcs7.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C742A2FBE8100755BA7 /* pkcs7.h */; }; + 700F0CB52A2FBEF100755BA7 /* pkcs12.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C782A2FBE8200755BA7 /* pkcs12.h */; }; + 700F0CB62A2FBEF100755BA7 /* rand.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C7B2A2FBE8200755BA7 /* rand.h */; }; + 700F0CB72A2FBEF100755BA7 /* rc4.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C562A2FBE8100755BA7 /* rc4.h */; }; + 700F0CB82A2FBEF100755BA7 /* ripemd.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C6B2A2FBE8100755BA7 /* ripemd.h */; }; + 700F0CB92A2FBEF100755BA7 /* rsa.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C8A2A2FBE8200755BA7 /* rsa.h */; }; + 700F0CBA2A2FBEF100755BA7 /* sha.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C5C2A2FBE8100755BA7 /* sha.h */; }; + 700F0CBB2A2FBEF100755BA7 /* sha3.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C712A2FBE8100755BA7 /* sha3.h */; }; + 700F0CBC2A2FBEF100755BA7 /* srp.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C752A2FBE8100755BA7 /* srp.h */; }; + 700F0CBD2A2FBEF100755BA7 /* ssl.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C892A2FBE8200755BA7 /* ssl.h */; }; + 700F0CBE2A2FBEF100755BA7 /* ssl23.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C762A2FBE8100755BA7 /* ssl23.h */; }; + 700F0CBF2A2FBEF100755BA7 /* stack.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C5A2A2FBE8100755BA7 /* stack.h */; }; + 700F0CC02A2FBEF100755BA7 /* tls1.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C822A2FBE8200755BA7 /* tls1.h */; }; + 700F0CC12A2FBEF100755BA7 /* txt_db.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C872A2FBE8200755BA7 /* txt_db.h */; }; + 700F0CC22A2FBEF100755BA7 /* ui.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C552A2FBE8100755BA7 /* ui.h */; }; + 700F0CC32A2FBEF100755BA7 /* x509_vfy.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C7A2A2FBE8200755BA7 /* x509_vfy.h */; }; + 700F0CC42A2FBEF100755BA7 /* x509.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C682A2FBE8100755BA7 /* x509.h */; }; + 700F0CC52A2FBEF100755BA7 /* x509v3.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 700F0C622A2FBE8100755BA7 /* x509v3.h */; }; 9D01059E291CEA5000A854D3 /* armv8-sha512.c in Sources */ = {isa = PBXBuildFile; fileRef = 9D01058C291CEA4F00A854D3 /* armv8-sha512.c */; }; 9D01059F291CEA5000A854D3 /* armv8-sha512.c in Sources */ = {isa = PBXBuildFile; fileRef = 9D01058C291CEA4F00A854D3 /* armv8-sha512.c */; }; 9D0105A0291CEA5000A854D3 /* armv8-sha512.c in Sources */ = {isa = PBXBuildFile; fileRef = 9D01058C291CEA4F00A854D3 /* armv8-sha512.c */; }; @@ -740,6 +836,42 @@ dstPath = include/wolfssl/wolfcrypt; dstSubfolderSpec = 7; files = ( + 700F0C052A2FBC5100755BA7 /* async.h in CopyFiles */, + 700F0C062A2FBC5100755BA7 /* chacha20_poly1305.h in CopyFiles */, + 700F0C072A2FBC5100755BA7 /* cmac.h in CopyFiles */, + 700F0C082A2FBC5100755BA7 /* cpuid.h in CopyFiles */, + 700F0C092A2FBC5100755BA7 /* cryptocb.h in CopyFiles */, + 700F0C0A2A2FBC5100755BA7 /* curve448.h in CopyFiles */, + 700F0C0B2A2FBC5100755BA7 /* curve25519.h in CopyFiles */, + 700F0C0C2A2FBC5100755BA7 /* dilithium.h in CopyFiles */, + 700F0C0D2A2FBC5100755BA7 /* eccsi.h in CopyFiles */, + 700F0C0E2A2FBC5100755BA7 /* ed448.h in CopyFiles */, + 700F0C0F2A2FBC5100755BA7 /* ed25519.h in CopyFiles */, + 700F0C102A2FBC5100755BA7 /* ext_kyber.h in CopyFiles */, + 700F0C112A2FBC5100755BA7 /* falcon.h in CopyFiles */, + 700F0C122A2FBC5100755BA7 /* fe_448.h in CopyFiles */, + 700F0C132A2FBC5100755BA7 /* fe_operations.h in CopyFiles */, + 700F0C142A2FBC5100755BA7 /* fips.h in CopyFiles */, + 700F0C152A2FBC5100755BA7 /* ge_448.h in CopyFiles */, + 700F0C162A2FBC5100755BA7 /* ge_operations.h in CopyFiles */, + 700F0C172A2FBC5100755BA7 /* hpke.h in CopyFiles */, + 700F0C182A2FBC5100755BA7 /* kyber.h in CopyFiles */, + 700F0C192A2FBC5100755BA7 /* pkcs11.h in CopyFiles */, + 700F0C1A2A2FBC5100755BA7 /* pkcs12.h in CopyFiles */, + 700F0C1B2A2FBC5100755BA7 /* rc2.h in CopyFiles */, + 700F0C1C2A2FBC5100755BA7 /* sakke.h in CopyFiles */, + 700F0C1D2A2FBC5100755BA7 /* selftest.h in CopyFiles */, + 700F0C1E2A2FBC5100755BA7 /* sha3.h in CopyFiles */, + 700F0C1F2A2FBC5100755BA7 /* signature.h in CopyFiles */, + 700F0C202A2FBC5100755BA7 /* siphash.h in CopyFiles */, + 700F0C212A2FBC5100755BA7 /* sp_int.h in CopyFiles */, + 700F0C222A2FBC5100755BA7 /* sp.h in CopyFiles */, + 700F0C232A2FBC5100755BA7 /* sphincs.h in CopyFiles */, + 700F0C242A2FBC5100755BA7 /* srp.h in CopyFiles */, + 700F0C252A2FBC5100755BA7 /* wc_kyber.h in CopyFiles */, + 700F0C262A2FBC5100755BA7 /* wc_pkcs11.h in CopyFiles */, + 700F0C272A2FBC5100755BA7 /* wolfevent.h in CopyFiles */, + 700F0C282A2FBC5100755BA7 /* kdf.h in CopyFiles */, 520775BE2239ACFF00087711 /* mem_track.h in CopyFiles */, 520775BF2239ACFF00087711 /* wolfmath.h in CopyFiles */, 522DBE0F1B7927A50031F454 /* wc_encrypt.h in CopyFiles */, @@ -863,6 +995,9 @@ dstPath = include/wolfssl; dstSubfolderSpec = 7; files = ( + 700F0C2C2A2FBD1700755BA7 /* quic.h in CopyFiles */, + 700F0C2D2A2FBD1700755BA7 /* sniffer.h in CopyFiles */, + 700F0C2E2A2FBD1700755BA7 /* sniffer_error.h in CopyFiles */, 520775C02239B16C00087711 /* wolfio.h in CopyFiles */, 521646C41A8A7FE10062516A /* callbacks.h in CopyFiles */, 521646C51A8A7FE10062516A /* certs_test.h in CopyFiles */, @@ -876,6 +1011,72 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 700F0C8B2A2FBEB400755BA7 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = include/wolfssl/openssl; + dstSubfolderSpec = 7; + files = ( + 700F0C8C2A2FBEF100755BA7 /* aes.h in CopyFiles */, + 700F0C8D2A2FBEF100755BA7 /* asn1.h in CopyFiles */, + 700F0C8E2A2FBEF100755BA7 /* asn1t.h in CopyFiles */, + 700F0C8F2A2FBEF100755BA7 /* bio.h in CopyFiles */, + 700F0C902A2FBEF100755BA7 /* bn.h in CopyFiles */, + 700F0C912A2FBEF100755BA7 /* buffer.h in CopyFiles */, + 700F0C922A2FBEF100755BA7 /* camellia.h in CopyFiles */, + 700F0C932A2FBEF100755BA7 /* cmac.h in CopyFiles */, + 700F0C942A2FBEF100755BA7 /* cms.h in CopyFiles */, + 700F0C952A2FBEF100755BA7 /* compat_types.h in CopyFiles */, + 700F0C962A2FBEF100755BA7 /* conf.h in CopyFiles */, + 700F0C972A2FBEF100755BA7 /* crypto.h in CopyFiles */, + 700F0C982A2FBEF100755BA7 /* des.h in CopyFiles */, + 700F0C992A2FBEF100755BA7 /* dh.h in CopyFiles */, + 700F0C9A2A2FBEF100755BA7 /* dsa.h in CopyFiles */, + 700F0C9B2A2FBEF100755BA7 /* ec.h in CopyFiles */, + 700F0C9C2A2FBEF100755BA7 /* ec448.h in CopyFiles */, + 700F0C9D2A2FBEF100755BA7 /* ec25519.h in CopyFiles */, + 700F0C9E2A2FBEF100755BA7 /* ecdh.h in CopyFiles */, + 700F0C9F2A2FBEF100755BA7 /* ecdsa.h in CopyFiles */, + 700F0CA02A2FBEF100755BA7 /* ed448.h in CopyFiles */, + 700F0CA12A2FBEF100755BA7 /* ed25519.h in CopyFiles */, + 700F0CA22A2FBEF100755BA7 /* engine.h in CopyFiles */, + 700F0CA32A2FBEF100755BA7 /* err.h in CopyFiles */, + 700F0CA42A2FBEF100755BA7 /* evp.h in CopyFiles */, + 700F0CA52A2FBEF100755BA7 /* fips_rand.h in CopyFiles */, + 700F0CA62A2FBEF100755BA7 /* hmac.h in CopyFiles */, + 700F0CA82A2FBEF100755BA7 /* kdf.h in CopyFiles */, + 700F0CA92A2FBEF100755BA7 /* lhash.h in CopyFiles */, + 700F0CAA2A2FBEF100755BA7 /* md4.h in CopyFiles */, + 700F0CAB2A2FBEF100755BA7 /* md5.h in CopyFiles */, + 700F0CAC2A2FBEF100755BA7 /* modes.h in CopyFiles */, + 700F0CAD2A2FBEF100755BA7 /* obj_mac.h in CopyFiles */, + 700F0CAE2A2FBEF100755BA7 /* objects.h in CopyFiles */, + 700F0CAF2A2FBEF100755BA7 /* ocsp.h in CopyFiles */, + 700F0CB02A2FBEF100755BA7 /* opensslconf.h in CopyFiles */, + 700F0CB12A2FBEF100755BA7 /* opensslv.h in CopyFiles */, + 700F0CB22A2FBEF100755BA7 /* ossl_typ.h in CopyFiles */, + 700F0CB32A2FBEF100755BA7 /* pem.h in CopyFiles */, + 700F0CB42A2FBEF100755BA7 /* pkcs7.h in CopyFiles */, + 700F0CB52A2FBEF100755BA7 /* pkcs12.h in CopyFiles */, + 700F0CB62A2FBEF100755BA7 /* rand.h in CopyFiles */, + 700F0CB72A2FBEF100755BA7 /* rc4.h in CopyFiles */, + 700F0CB82A2FBEF100755BA7 /* ripemd.h in CopyFiles */, + 700F0CB92A2FBEF100755BA7 /* rsa.h in CopyFiles */, + 700F0CBA2A2FBEF100755BA7 /* sha.h in CopyFiles */, + 700F0CBB2A2FBEF100755BA7 /* sha3.h in CopyFiles */, + 700F0CBC2A2FBEF100755BA7 /* srp.h in CopyFiles */, + 700F0CBD2A2FBEF100755BA7 /* ssl.h in CopyFiles */, + 700F0CBE2A2FBEF100755BA7 /* ssl23.h in CopyFiles */, + 700F0CBF2A2FBEF100755BA7 /* stack.h in CopyFiles */, + 700F0CC02A2FBEF100755BA7 /* tls1.h in CopyFiles */, + 700F0CC12A2FBEF100755BA7 /* txt_db.h in CopyFiles */, + 700F0CC22A2FBEF100755BA7 /* ui.h in CopyFiles */, + 700F0CC32A2FBEF100755BA7 /* x509_vfy.h in CopyFiles */, + 700F0CC42A2FBEF100755BA7 /* x509.h in CopyFiles */, + 700F0CC52A2FBEF100755BA7 /* x509v3.h in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; A4F3187C1BC58B1700FDF2BB /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; @@ -1186,6 +1387,101 @@ 52B1344D16F3C9E800C07B32 /* libwolfssl_ios.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libwolfssl_ios.a; sourceTree = BUILT_PRODUCTS_DIR; }; 6AC85128272CAF2E00F2B32A /* kdf.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = kdf.c; path = ../../wolfcrypt/src/kdf.c; sourceTree = ""; }; 6AC8513B272CB04F00F2B32A /* kdf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = kdf.h; path = ../../wolfssl/wolfcrypt/kdf.h; sourceTree = ""; }; + 700F0BE02A2FBC1500755BA7 /* rc2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = rc2.h; path = ../../wolfssl/wolfcrypt/rc2.h; sourceTree = ""; }; + 700F0BE12A2FBC1500755BA7 /* hpke.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = hpke.h; path = ../../wolfssl/wolfcrypt/hpke.h; sourceTree = ""; }; + 700F0BE22A2FBC1500755BA7 /* sphincs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sphincs.h; path = ../../wolfssl/wolfcrypt/sphincs.h; sourceTree = ""; }; + 700F0BE32A2FBC1500755BA7 /* curve448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = curve448.h; path = ../../wolfssl/wolfcrypt/curve448.h; sourceTree = ""; }; + 700F0BE52A2FBC1500755BA7 /* curve25519.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = curve25519.h; path = ../../wolfssl/wolfcrypt/curve25519.h; sourceTree = ""; }; + 700F0BE62A2FBC1500755BA7 /* wolfevent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = wolfevent.h; path = ../../wolfssl/wolfcrypt/wolfevent.h; sourceTree = ""; }; + 700F0BE72A2FBC1500755BA7 /* ge_448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ge_448.h; path = ../../wolfssl/wolfcrypt/ge_448.h; sourceTree = ""; }; + 700F0BE82A2FBC1500755BA7 /* sp_int.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sp_int.h; path = ../../wolfssl/wolfcrypt/sp_int.h; sourceTree = ""; }; + 700F0BE92A2FBC1500755BA7 /* sp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sp.h; path = ../../wolfssl/wolfcrypt/sp.h; sourceTree = ""; }; + 700F0BEA2A2FBC1500755BA7 /* kyber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = kyber.h; path = ../../wolfssl/wolfcrypt/kyber.h; sourceTree = ""; }; + 700F0BEB2A2FBC1500755BA7 /* fe_448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fe_448.h; path = ../../wolfssl/wolfcrypt/fe_448.h; sourceTree = ""; }; + 700F0BEC2A2FBC1500755BA7 /* pkcs12.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pkcs12.h; path = ../../wolfssl/wolfcrypt/pkcs12.h; sourceTree = ""; }; + 700F0BED2A2FBC1500755BA7 /* chacha20_poly1305.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = chacha20_poly1305.h; path = ../../wolfssl/wolfcrypt/chacha20_poly1305.h; sourceTree = ""; }; + 700F0BEE2A2FBC1500755BA7 /* cryptocb.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cryptocb.h; path = ../../wolfssl/wolfcrypt/cryptocb.h; sourceTree = ""; }; + 700F0BEF2A2FBC1500755BA7 /* dilithium.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dilithium.h; path = ../../wolfssl/wolfcrypt/dilithium.h; sourceTree = ""; }; + 700F0BF02A2FBC1500755BA7 /* sakke.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sakke.h; path = ../../wolfssl/wolfcrypt/sakke.h; sourceTree = ""; }; + 700F0BF12A2FBC1600755BA7 /* cpuid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cpuid.h; path = ../../wolfssl/wolfcrypt/cpuid.h; sourceTree = ""; }; + 700F0BF22A2FBC1600755BA7 /* selftest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = selftest.h; path = ../../wolfssl/wolfcrypt/selftest.h; sourceTree = ""; }; + 700F0BF32A2FBC1600755BA7 /* srp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = srp.h; path = ../../wolfssl/wolfcrypt/srp.h; sourceTree = ""; }; + 700F0BF42A2FBC1600755BA7 /* ed25519.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ed25519.h; path = ../../wolfssl/wolfcrypt/ed25519.h; sourceTree = ""; }; + 700F0BF52A2FBC1600755BA7 /* wc_pkcs11.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = wc_pkcs11.h; path = ../../wolfssl/wolfcrypt/wc_pkcs11.h; sourceTree = ""; }; + 700F0BF62A2FBC1600755BA7 /* fe_operations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fe_operations.h; path = ../../wolfssl/wolfcrypt/fe_operations.h; sourceTree = ""; }; + 700F0BF72A2FBC1600755BA7 /* eccsi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = eccsi.h; path = ../../wolfssl/wolfcrypt/eccsi.h; sourceTree = ""; }; + 700F0BF82A2FBC1600755BA7 /* ed448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ed448.h; path = ../../wolfssl/wolfcrypt/ed448.h; sourceTree = ""; }; + 700F0BF92A2FBC1600755BA7 /* ext_kyber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ext_kyber.h; path = ../../wolfssl/wolfcrypt/ext_kyber.h; sourceTree = ""; }; + 700F0BFA2A2FBC1600755BA7 /* sha3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sha3.h; path = ../../wolfssl/wolfcrypt/sha3.h; sourceTree = ""; }; + 700F0BFB2A2FBC1600755BA7 /* signature.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = signature.h; path = ../../wolfssl/wolfcrypt/signature.h; sourceTree = ""; }; + 700F0BFC2A2FBC1600755BA7 /* cmac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cmac.h; path = ../../wolfssl/wolfcrypt/cmac.h; sourceTree = ""; }; + 700F0BFD2A2FBC1600755BA7 /* pkcs11.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pkcs11.h; path = ../../wolfssl/wolfcrypt/pkcs11.h; sourceTree = ""; }; + 700F0BFE2A2FBC1600755BA7 /* siphash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = siphash.h; path = ../../wolfssl/wolfcrypt/siphash.h; sourceTree = ""; }; + 700F0BFF2A2FBC1600755BA7 /* wc_kyber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = wc_kyber.h; path = ../../wolfssl/wolfcrypt/wc_kyber.h; sourceTree = ""; }; + 700F0C002A2FBC1600755BA7 /* fips.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fips.h; path = ../../wolfssl/wolfcrypt/fips.h; sourceTree = ""; }; + 700F0C012A2FBC1600755BA7 /* ge_operations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ge_operations.h; path = ../../wolfssl/wolfcrypt/ge_operations.h; sourceTree = ""; }; + 700F0C022A2FBC1600755BA7 /* falcon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = falcon.h; path = ../../wolfssl/wolfcrypt/falcon.h; sourceTree = ""; }; + 700F0C032A2FBC1600755BA7 /* async.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = async.h; path = ../../wolfssl/wolfcrypt/async.h; sourceTree = ""; }; + 700F0C292A2FBCAD00755BA7 /* quic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = quic.h; path = ../../wolfssl/quic.h; sourceTree = ""; }; + 700F0C2A2A2FBCAD00755BA7 /* sniffer_error.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sniffer_error.h; path = ../../wolfssl/sniffer_error.h; sourceTree = ""; }; + 700F0C2B2A2FBCF800755BA7 /* sniffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sniffer.h; path = ../../wolfssl/sniffer.h; sourceTree = ""; }; + 700F0C512A2FBE8000755BA7 /* asn1.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = asn1.h; path = ../../wolfssl/openssl/asn1.h; sourceTree = ""; }; + 700F0C522A2FBE8100755BA7 /* dh.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dh.h; path = ../../wolfssl/openssl/dh.h; sourceTree = ""; }; + 700F0C532A2FBE8100755BA7 /* compat_types.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = compat_types.h; path = ../../wolfssl/openssl/compat_types.h; sourceTree = ""; }; + 700F0C542A2FBE8100755BA7 /* ecdh.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ecdh.h; path = ../../wolfssl/openssl/ecdh.h; sourceTree = ""; }; + 700F0C552A2FBE8100755BA7 /* ui.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ui.h; path = ../../wolfssl/openssl/ui.h; sourceTree = ""; }; + 700F0C562A2FBE8100755BA7 /* rc4.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = rc4.h; path = ../../wolfssl/openssl/rc4.h; sourceTree = ""; }; + 700F0C572A2FBE8100755BA7 /* objects.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = objects.h; path = ../../wolfssl/openssl/objects.h; sourceTree = ""; }; + 700F0C582A2FBE8100755BA7 /* bio.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = bio.h; path = ../../wolfssl/openssl/bio.h; sourceTree = ""; }; + 700F0C5A2A2FBE8100755BA7 /* stack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = stack.h; path = ../../wolfssl/openssl/stack.h; sourceTree = ""; }; + 700F0C5B2A2FBE8100755BA7 /* camellia.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = camellia.h; path = ../../wolfssl/openssl/camellia.h; sourceTree = ""; }; + 700F0C5C2A2FBE8100755BA7 /* sha.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sha.h; path = ../../wolfssl/openssl/sha.h; sourceTree = ""; }; + 700F0C5D2A2FBE8100755BA7 /* engine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = engine.h; path = ../../wolfssl/openssl/engine.h; sourceTree = ""; }; + 700F0C5E2A2FBE8100755BA7 /* cms.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cms.h; path = ../../wolfssl/openssl/cms.h; sourceTree = ""; }; + 700F0C5F2A2FBE8100755BA7 /* evp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = evp.h; path = ../../wolfssl/openssl/evp.h; sourceTree = ""; }; + 700F0C602A2FBE8100755BA7 /* ec25519.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ec25519.h; path = ../../wolfssl/openssl/ec25519.h; sourceTree = ""; }; + 700F0C612A2FBE8100755BA7 /* des.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = des.h; path = ../../wolfssl/openssl/des.h; sourceTree = ""; }; + 700F0C622A2FBE8100755BA7 /* x509v3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = x509v3.h; path = ../../wolfssl/openssl/x509v3.h; sourceTree = ""; }; + 700F0C632A2FBE8100755BA7 /* cmac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cmac.h; path = ../../wolfssl/openssl/cmac.h; sourceTree = ""; }; + 700F0C642A2FBE8100755BA7 /* ed448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ed448.h; path = ../../wolfssl/openssl/ed448.h; sourceTree = ""; }; + 700F0C652A2FBE8100755BA7 /* lhash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = lhash.h; path = ../../wolfssl/openssl/lhash.h; sourceTree = ""; }; + 700F0C662A2FBE8100755BA7 /* conf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = conf.h; path = ../../wolfssl/openssl/conf.h; sourceTree = ""; }; + 700F0C672A2FBE8100755BA7 /* ec448.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ec448.h; path = ../../wolfssl/openssl/ec448.h; sourceTree = ""; }; + 700F0C682A2FBE8100755BA7 /* x509.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = x509.h; path = ../../wolfssl/openssl/x509.h; sourceTree = ""; }; + 700F0C692A2FBE8100755BA7 /* bn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = bn.h; path = ../../wolfssl/openssl/bn.h; sourceTree = ""; }; + 700F0C6A2A2FBE8100755BA7 /* err.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = err.h; path = ../../wolfssl/openssl/err.h; sourceTree = ""; }; + 700F0C6B2A2FBE8100755BA7 /* ripemd.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ripemd.h; path = ../../wolfssl/openssl/ripemd.h; sourceTree = ""; }; + 700F0C6C2A2FBE8100755BA7 /* pem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pem.h; path = ../../wolfssl/openssl/pem.h; sourceTree = ""; }; + 700F0C6D2A2FBE8100755BA7 /* md4.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = md4.h; path = ../../wolfssl/openssl/md4.h; sourceTree = ""; }; + 700F0C6E2A2FBE8100755BA7 /* kdf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = kdf.h; path = ../../wolfssl/openssl/kdf.h; sourceTree = ""; }; + 700F0C6F2A2FBE8100755BA7 /* ec.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ec.h; path = ../../wolfssl/openssl/ec.h; sourceTree = ""; }; + 700F0C702A2FBE8100755BA7 /* md5.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = md5.h; path = ../../wolfssl/openssl/md5.h; sourceTree = ""; }; + 700F0C712A2FBE8100755BA7 /* sha3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sha3.h; path = ../../wolfssl/openssl/sha3.h; sourceTree = ""; }; + 700F0C722A2FBE8100755BA7 /* asn1t.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = asn1t.h; path = ../../wolfssl/openssl/asn1t.h; sourceTree = ""; }; + 700F0C732A2FBE8100755BA7 /* opensslconf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = opensslconf.h; path = ../../wolfssl/openssl/opensslconf.h; sourceTree = ""; }; + 700F0C742A2FBE8100755BA7 /* pkcs7.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pkcs7.h; path = ../../wolfssl/openssl/pkcs7.h; sourceTree = ""; }; + 700F0C752A2FBE8100755BA7 /* srp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = srp.h; path = ../../wolfssl/openssl/srp.h; sourceTree = ""; }; + 700F0C762A2FBE8100755BA7 /* ssl23.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ssl23.h; path = ../../wolfssl/openssl/ssl23.h; sourceTree = ""; }; + 700F0C772A2FBE8200755BA7 /* modes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = modes.h; path = ../../wolfssl/openssl/modes.h; sourceTree = ""; }; + 700F0C782A2FBE8200755BA7 /* pkcs12.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pkcs12.h; path = ../../wolfssl/openssl/pkcs12.h; sourceTree = ""; }; + 700F0C792A2FBE8200755BA7 /* ossl_typ.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ossl_typ.h; path = ../../wolfssl/openssl/ossl_typ.h; sourceTree = ""; }; + 700F0C7A2A2FBE8200755BA7 /* x509_vfy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = x509_vfy.h; path = ../../wolfssl/openssl/x509_vfy.h; sourceTree = ""; }; + 700F0C7B2A2FBE8200755BA7 /* rand.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = rand.h; path = ../../wolfssl/openssl/rand.h; sourceTree = ""; }; + 700F0C7C2A2FBE8200755BA7 /* aes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = aes.h; path = ../../wolfssl/openssl/aes.h; sourceTree = ""; }; + 700F0C7D2A2FBE8200755BA7 /* opensslv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = opensslv.h; path = ../../wolfssl/openssl/opensslv.h; sourceTree = ""; }; + 700F0C7E2A2FBE8200755BA7 /* ed25519.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ed25519.h; path = ../../wolfssl/openssl/ed25519.h; sourceTree = ""; }; + 700F0C7F2A2FBE8200755BA7 /* fips_rand.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fips_rand.h; path = ../../wolfssl/openssl/fips_rand.h; sourceTree = ""; }; + 700F0C802A2FBE8200755BA7 /* obj_mac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = obj_mac.h; path = ../../wolfssl/openssl/obj_mac.h; sourceTree = ""; }; + 700F0C812A2FBE8200755BA7 /* ecdsa.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ecdsa.h; path = ../../wolfssl/openssl/ecdsa.h; sourceTree = ""; }; + 700F0C822A2FBE8200755BA7 /* tls1.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = tls1.h; path = ../../wolfssl/openssl/tls1.h; sourceTree = ""; }; + 700F0C832A2FBE8200755BA7 /* hmac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = hmac.h; path = ../../wolfssl/openssl/hmac.h; sourceTree = ""; }; + 700F0C842A2FBE8200755BA7 /* ocsp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ocsp.h; path = ../../wolfssl/openssl/ocsp.h; sourceTree = ""; }; + 700F0C852A2FBE8200755BA7 /* buffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = buffer.h; path = ../../wolfssl/openssl/buffer.h; sourceTree = ""; }; + 700F0C862A2FBE8200755BA7 /* crypto.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = crypto.h; path = ../../wolfssl/openssl/crypto.h; sourceTree = ""; }; + 700F0C872A2FBE8200755BA7 /* txt_db.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = txt_db.h; path = ../../wolfssl/openssl/txt_db.h; sourceTree = ""; }; + 700F0C882A2FBE8200755BA7 /* dsa.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dsa.h; path = ../../wolfssl/openssl/dsa.h; sourceTree = ""; }; + 700F0C892A2FBE8200755BA7 /* ssl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ssl.h; path = ../../wolfssl/openssl/ssl.h; sourceTree = ""; }; + 700F0C8A2A2FBE8200755BA7 /* rsa.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = rsa.h; path = ../../wolfssl/openssl/rsa.h; sourceTree = ""; }; 9D01058C291CEA4F00A854D3 /* armv8-sha512.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = "armv8-sha512.c"; path = "../../wolfcrypt/src/port/arm/armv8-sha512.c"; sourceTree = ""; }; 9D01058F291CEA4F00A854D3 /* armv8-sha512-asm.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = "armv8-sha512-asm.S"; path = "../../wolfcrypt/src/port/arm/armv8-sha512-asm.S"; sourceTree = ""; }; 9D010591291CEA4F00A854D3 /* armv8-sha256.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = "armv8-sha256.c"; path = "../../wolfcrypt/src/port/arm/armv8-sha256.c"; sourceTree = ""; }; @@ -1255,6 +1551,7 @@ 521645F81A89916A0062516A /* wolfCrypt */, 521645F71A8991680062516A /* CyaSSL */, 521645F61A8991640062516A /* CtaoCrypt */, + 700F0C502A2FBE3600755BA7 /* OpenSSL */, ); name = Headers; sourceTree = SOURCE_ROOT; @@ -1327,6 +1624,41 @@ 521645F81A89916A0062516A /* wolfCrypt */ = { isa = PBXGroup; children = ( + 700F0C032A2FBC1600755BA7 /* async.h */, + 700F0BED2A2FBC1500755BA7 /* chacha20_poly1305.h */, + 700F0BFC2A2FBC1600755BA7 /* cmac.h */, + 700F0BF12A2FBC1600755BA7 /* cpuid.h */, + 700F0BEE2A2FBC1500755BA7 /* cryptocb.h */, + 700F0BE32A2FBC1500755BA7 /* curve448.h */, + 700F0BE52A2FBC1500755BA7 /* curve25519.h */, + 700F0BEF2A2FBC1500755BA7 /* dilithium.h */, + 700F0BF72A2FBC1600755BA7 /* eccsi.h */, + 700F0BF82A2FBC1600755BA7 /* ed448.h */, + 700F0BF42A2FBC1600755BA7 /* ed25519.h */, + 700F0BF92A2FBC1600755BA7 /* ext_kyber.h */, + 700F0C022A2FBC1600755BA7 /* falcon.h */, + 700F0BEB2A2FBC1500755BA7 /* fe_448.h */, + 700F0BF62A2FBC1600755BA7 /* fe_operations.h */, + 700F0C002A2FBC1600755BA7 /* fips.h */, + 700F0BE72A2FBC1500755BA7 /* ge_448.h */, + 700F0C012A2FBC1600755BA7 /* ge_operations.h */, + 700F0BE12A2FBC1500755BA7 /* hpke.h */, + 700F0BEA2A2FBC1500755BA7 /* kyber.h */, + 700F0BFD2A2FBC1600755BA7 /* pkcs11.h */, + 700F0BEC2A2FBC1500755BA7 /* pkcs12.h */, + 700F0BE02A2FBC1500755BA7 /* rc2.h */, + 700F0BF02A2FBC1500755BA7 /* sakke.h */, + 700F0BF22A2FBC1600755BA7 /* selftest.h */, + 700F0BFA2A2FBC1600755BA7 /* sha3.h */, + 700F0BFB2A2FBC1600755BA7 /* signature.h */, + 700F0BFE2A2FBC1600755BA7 /* siphash.h */, + 700F0BE82A2FBC1500755BA7 /* sp_int.h */, + 700F0BE92A2FBC1500755BA7 /* sp.h */, + 700F0BE22A2FBC1500755BA7 /* sphincs.h */, + 700F0BF32A2FBC1600755BA7 /* srp.h */, + 700F0BFF2A2FBC1600755BA7 /* wc_kyber.h */, + 700F0BF52A2FBC1600755BA7 /* wc_pkcs11.h */, + 700F0BE62A2FBC1500755BA7 /* wolfevent.h */, 5216465E1A8993770062516A /* aes.h */, 5216465F1A8993770062516A /* arc4.h */, 521646601A8993770062516A /* asn_public.h */, @@ -1386,6 +1718,9 @@ 521646561A8993290062516A /* error-ssl.h */, 521646571A8993290062516A /* internal.h */, 521646581A8993290062516A /* ocsp.h */, + 700F0C292A2FBCAD00755BA7 /* quic.h */, + 700F0C2B2A2FBCF800755BA7 /* sniffer.h */, + 700F0C2A2A2FBCAD00755BA7 /* sniffer_error.h */, 5216465B1A8993290062516A /* ssl.h */, 5216465C1A8993290062516A /* test.h */, 5216465D1A8993290062516A /* version.h */, @@ -1526,6 +1861,70 @@ name = Products; sourceTree = ""; }; + 700F0C502A2FBE3600755BA7 /* OpenSSL */ = { + isa = PBXGroup; + children = ( + 700F0C7C2A2FBE8200755BA7 /* aes.h */, + 700F0C512A2FBE8000755BA7 /* asn1.h */, + 700F0C722A2FBE8100755BA7 /* asn1t.h */, + 700F0C582A2FBE8100755BA7 /* bio.h */, + 700F0C692A2FBE8100755BA7 /* bn.h */, + 700F0C852A2FBE8200755BA7 /* buffer.h */, + 700F0C5B2A2FBE8100755BA7 /* camellia.h */, + 700F0C632A2FBE8100755BA7 /* cmac.h */, + 700F0C5E2A2FBE8100755BA7 /* cms.h */, + 700F0C532A2FBE8100755BA7 /* compat_types.h */, + 700F0C662A2FBE8100755BA7 /* conf.h */, + 700F0C862A2FBE8200755BA7 /* crypto.h */, + 700F0C612A2FBE8100755BA7 /* des.h */, + 700F0C522A2FBE8100755BA7 /* dh.h */, + 700F0C882A2FBE8200755BA7 /* dsa.h */, + 700F0C6F2A2FBE8100755BA7 /* ec.h */, + 700F0C672A2FBE8100755BA7 /* ec448.h */, + 700F0C602A2FBE8100755BA7 /* ec25519.h */, + 700F0C542A2FBE8100755BA7 /* ecdh.h */, + 700F0C812A2FBE8200755BA7 /* ecdsa.h */, + 700F0C642A2FBE8100755BA7 /* ed448.h */, + 700F0C7E2A2FBE8200755BA7 /* ed25519.h */, + 700F0C5D2A2FBE8100755BA7 /* engine.h */, + 700F0C6A2A2FBE8100755BA7 /* err.h */, + 700F0C5F2A2FBE8100755BA7 /* evp.h */, + 700F0C7F2A2FBE8200755BA7 /* fips_rand.h */, + 700F0C832A2FBE8200755BA7 /* hmac.h */, + 700F0C6E2A2FBE8100755BA7 /* kdf.h */, + 700F0C652A2FBE8100755BA7 /* lhash.h */, + 700F0C6D2A2FBE8100755BA7 /* md4.h */, + 700F0C702A2FBE8100755BA7 /* md5.h */, + 700F0C772A2FBE8200755BA7 /* modes.h */, + 700F0C802A2FBE8200755BA7 /* obj_mac.h */, + 700F0C572A2FBE8100755BA7 /* objects.h */, + 700F0C842A2FBE8200755BA7 /* ocsp.h */, + 700F0C732A2FBE8100755BA7 /* opensslconf.h */, + 700F0C7D2A2FBE8200755BA7 /* opensslv.h */, + 700F0C792A2FBE8200755BA7 /* ossl_typ.h */, + 700F0C6C2A2FBE8100755BA7 /* pem.h */, + 700F0C742A2FBE8100755BA7 /* pkcs7.h */, + 700F0C782A2FBE8200755BA7 /* pkcs12.h */, + 700F0C7B2A2FBE8200755BA7 /* rand.h */, + 700F0C562A2FBE8100755BA7 /* rc4.h */, + 700F0C6B2A2FBE8100755BA7 /* ripemd.h */, + 700F0C8A2A2FBE8200755BA7 /* rsa.h */, + 700F0C5C2A2FBE8100755BA7 /* sha.h */, + 700F0C712A2FBE8100755BA7 /* sha3.h */, + 700F0C752A2FBE8100755BA7 /* srp.h */, + 700F0C892A2FBE8200755BA7 /* ssl.h */, + 700F0C762A2FBE8100755BA7 /* ssl23.h */, + 700F0C5A2A2FBE8100755BA7 /* stack.h */, + 700F0C822A2FBE8200755BA7 /* tls1.h */, + 700F0C872A2FBE8200755BA7 /* txt_db.h */, + 700F0C552A2FBE8100755BA7 /* ui.h */, + 700F0C7A2A2FBE8200755BA7 /* x509_vfy.h */, + 700F0C682A2FBE8100755BA7 /* x509.h */, + 700F0C622A2FBE8100755BA7 /* x509v3.h */, + ); + name = OpenSSL; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -1558,6 +1957,7 @@ 521646C11A8A7B380062516A /* CopyFiles */, 521646C21A8A7B3B0062516A /* CopyFiles */, 521646C31A8A7B3D0062516A /* CopyFiles */, + 700F0C8B2A2FBEB400755BA7 /* CopyFiles */, 52B1344916F3C9E800C07B32 /* Sources */, ); buildRules = ( From 87f74f58ab34056b3bc935262c28367dce5e2779 Mon Sep 17 00:00:00 2001 From: Eric Blankenhorn Date: Fri, 19 May 2023 17:08:44 -0500 Subject: [PATCH 358/391] Allow wolfSSL_RAND_Init to pass if already initialized --- src/ssl.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/ssl.c b/src/ssl.c index d321165b32a..34e3b9b50ae 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -35851,6 +35851,11 @@ int wolfSSL_RAND_Init(void) ret = WOLFSSL_SUCCESS; } } + else { + /* GlobalRNG is already initialized */ + ret = WOLFSSL_SUCCESS; + } + wc_UnLockMutex(&globalRNGMutex); } #endif From 6b27383c0907b09453e45f4590c9c11b15f3f345 Mon Sep 17 00:00:00 2001 From: Kareem Date: Mon, 5 Jun 2023 10:49:42 -0700 Subject: [PATCH 359/391] Send blank certificate message in DTLS when no client cert is loaded. --- src/internal.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/internal.c b/src/internal.c index 9c08ee7d3ff..6c926184cb6 100644 --- a/src/internal.c +++ b/src/internal.c @@ -27409,7 +27409,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, #ifdef OPENSSL_EXTRA else #else - else if (IsTLS(ssl)) + else if (IsTLS(ssl) || ssl->options.dtls) #endif { ssl->options.sendVerify = SEND_BLANK_CERT; From 13569321bac1fea2f65fef8e7a8190c012263e4f Mon Sep 17 00:00:00 2001 From: Hideki Miyazaki Date: Sat, 3 Jun 2023 08:23:39 +0900 Subject: [PATCH 360/391] fix uninit var --- tests/api.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/api.c b/tests/api.c index fee5eb3e5dd..bc60c28d4fd 100644 --- a/tests/api.c +++ b/tests/api.c @@ -36237,7 +36237,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) const char* fname = "./certs/ecc-key.pem"; const char* fname_ecc_p8 = "./certs/ecc-keyPkcs8.pem"; - size_t sz; + size_t sz = 0; byte* buf = NULL; EVP_PKEY* pkey2 = NULL; EVP_PKEY* pkey3 = NULL; From c90212d47f9d676b99b28d2a4994f4f58438327e Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 7 Jun 2023 14:38:43 +1000 Subject: [PATCH 361/391] cppcheck: fixes from scan wolfssl_sce_unit_test.c: sce_crypt_Sha_AesCbcGcm_multitest(): duplicate condition ssl_asn1.c: wolfSSL_i2t_ASN1_OBJECT(): done is not needed MonthStr(): fix bounds check on i woolfcrypt_test.c, test_main.c, wolfssl_tsip_unit_test.c, devices.c, aes.c, des3.c: Variable not used. asn.c: DecodeSubjKeyId(): sz is unsigned - check for less than zero does nothing kcapi_rsa.c: KcapiRsa_Decrypt(): fix ret check by using else KcapiRsa_Encrypt(): make same change for consistency kcapi_hash.c: KcapiHashFinal(): move ret into #ifdef where it is needed stm32.c: wc_Stm32_Hash_GetDigest(): i redeclared with different type - use ii instead bio.c, conf.c: XFREE checks for NULL Reduce scope of varialbes. Condition same. --- IDE/MCUEXPRESSO/wolfcrypt_test.c | 2 - .../e2studio/RA6M4/test/src/test_main.c | 1 - .../RA6M4/test/src/wolfssl_sce_unit_test.c | 1 - .../EnvisionKit/wolfssl_demo/wolfssl_demo.c | 2 + .../wolfssl_demo/wolfssl_tsip_unit_test.c | 6 --- IDE/iotsafe/devices.c | 2 - src/bio.c | 4 +- src/conf.c | 5 +- src/internal.c | 2 +- src/ssl.c | 13 +++-- src/ssl_asn1.c | 49 ++++++++----------- src/x509.c | 43 ++++++++-------- tests/api.c | 11 +---- wolfcrypt/src/aes.c | 2 - wolfcrypt/src/asn.c | 40 +++++++-------- wolfcrypt/src/des3.c | 4 -- wolfcrypt/src/fe_448.c | 9 ++-- wolfcrypt/src/fe_operations.c | 2 +- wolfcrypt/src/ge_low_mem.c | 2 +- wolfcrypt/src/hmac.c | 4 +- wolfcrypt/src/kdf.c | 5 +- wolfcrypt/src/port/kcapi/kcapi_hash.c | 4 +- wolfcrypt/src/port/kcapi/kcapi_rsa.c | 7 +-- wolfcrypt/src/port/st/stm32.c | 6 +-- wolfcrypt/src/random.c | 3 +- wolfcrypt/src/sakke.c | 4 +- wolfcrypt/src/wc_port.c | 22 ++++----- 27 files changed, 112 insertions(+), 143 deletions(-) diff --git a/IDE/MCUEXPRESSO/wolfcrypt_test.c b/IDE/MCUEXPRESSO/wolfcrypt_test.c index 83f3dd244fb..aea3d1d6f20 100644 --- a/IDE/MCUEXPRESSO/wolfcrypt_test.c +++ b/IDE/MCUEXPRESSO/wolfcrypt_test.c @@ -78,8 +78,6 @@ static void setup() #include "fsl_snvs_hp.h" static void setup() { - uint32_t sec; - uint8_t index; snvs_hp_rtc_datetime_t rtcDate; snvs_hp_rtc_config_t snvsRtcConfig; diff --git a/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c b/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c index d6d9394d8b5..7d7f8ee372f 100644 --- a/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c +++ b/IDE/Renesas/e2studio/RA6M4/test/src/test_main.c @@ -165,7 +165,6 @@ void sce_test(void) (defined(WOLFSSL_RENESAS_SCEPROTECT) || \ defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)) int ret = 0; - BaseType_t xRet; if ((ret = wolfCrypt_Init()) != 0) { printf("wolfCrypt_Init failed %d\n", ret); diff --git a/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c b/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c index 04509629c33..a785720fd4e 100644 --- a/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c +++ b/IDE/Renesas/e2studio/RA6M4/test/src/wolfssl_sce_unit_test.c @@ -1269,7 +1269,6 @@ int sce_crypt_Sha_AesCbcGcm_multitest() vSemaphoreDelete(exit_semaph); if ((xRet == pdPASS) && - (Aes128_Gcm_multTst_rslt == 0 && Aes256_Gcm_multTst_rslt == 0) && (Aes128_Gcm_multTst_rslt == 0 && Aes256_Gcm_multTst_rslt == 0) && (sha256_multTst_rslt1 == 0 && sha256_multTst_rslt2 == 0)) { diff --git a/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/wolfssl_demo.c b/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/wolfssl_demo.c index b9730dcc151..f32e119c4ae 100644 --- a/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/wolfssl_demo.c +++ b/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/wolfssl_demo.c @@ -494,7 +494,9 @@ static void Tls_client(void *pvParam) } } +#if defined(TLS_MULTITHREAD_TEST) out: +#endif if (ssl) { wolfSSL_shutdown(ssl); wolfSSL_free(ssl); diff --git a/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/wolfssl_tsip_unit_test.c b/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/wolfssl_tsip_unit_test.c index 48892c56d5f..35c64476533 100644 --- a/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/wolfssl_tsip_unit_test.c +++ b/IDE/Renesas/e2studio/RX72N/EnvisionKit/wolfssl_demo/wolfssl_tsip_unit_test.c @@ -361,15 +361,11 @@ static int tsip_aesgcm256_test(int prnt, tsip_aes_key_index_t* aes256_key) 0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b }; - int ivlen; - byte resultT[sizeof(t1)]; byte resultP[sizeof(p) + AES_BLOCK_SIZE]; byte resultC[sizeof(p) + AES_BLOCK_SIZE]; int result = 0; int ret; - int alen; - int plen; (void) result; @@ -950,8 +946,6 @@ int tsip_crypt_Sha_AesCbcGcm_multitest() int ret = 0; int num = 0; int i; - Info info_aes128cbc; - Info info_aes128gcm; Info info_aes256cbc; Info info_aes256gcm; BaseType_t xRet; diff --git a/IDE/iotsafe/devices.c b/IDE/iotsafe/devices.c index f71dbc86ef1..59b739cf5d0 100644 --- a/IDE/iotsafe/devices.c +++ b/IDE/iotsafe/devices.c @@ -150,7 +150,6 @@ int usart_rx(uint32_t dev, uint8_t *c) int usart_init(uint32_t dev, uint32_t bitrate, uint8_t data, char parity, uint8_t stop) { - uint32_t reg; int rtscts = 0; if (dev == USART1_BASE) { @@ -219,7 +218,6 @@ int usart_init(uint32_t dev, uint32_t bitrate, uint8_t data, char parity, uint8_ int _write(void *r, uint8_t *text, int len) { char *p = (char *)text; - int i; (void)r; while(*p && (p < (char *)(text + len))) { usart_tx(USART2_BASE, *p); diff --git a/src/bio.c b/src/bio.c index 39e542b2585..f0d518c62c1 100644 --- a/src/bio.c +++ b/src/bio.c @@ -1790,9 +1790,7 @@ WOLFSSL_BIO_METHOD *wolfSSL_BIO_meth_new(int type, const char *name) void wolfSSL_BIO_meth_free(WOLFSSL_BIO_METHOD *biom) { WOLFSSL_ENTER("wolfSSL_BIO_meth_free"); - if (biom) { - XFREE(biom, NULL, DYNAMIC_TYPE_OPENSSL); - } + XFREE(biom, NULL, DYNAMIC_TYPE_OPENSSL); } diff --git a/src/conf.c b/src/conf.c index 4693cbd8c9b..6ad5b640f80 100644 --- a/src/conf.c +++ b/src/conf.c @@ -1110,9 +1110,8 @@ void wolfSSL_CONF_CTX_free(WOLFSSL_CONF_CTX* cctx) { WOLFSSL_ENTER("wolfSSL_CONF_CTX_free"); - if (cctx) { - XFREE(cctx, NULL, DYNAMIC_TYPE_OPENSSL); - } + XFREE(cctx, NULL, DYNAMIC_TYPE_OPENSSL); + WOLFSSL_LEAVE("wolfSSL_CONF_CTX_free", 1); } /** diff --git a/src/internal.c b/src/internal.c index 6c926184cb6..8a691d707da 100644 --- a/src/internal.c +++ b/src/internal.c @@ -18790,10 +18790,10 @@ static void LogAlert(int type) { #ifdef DEBUG_WOLFSSL const char* typeStr; - char buff[60]; typeStr = AlertTypeToString(type); if (typeStr != NULL) { + char buff[60]; XSNPRINTF(buff, sizeof(buff), "Alert type: %s", typeStr); WOLFSSL_MSG(buff); } diff --git a/src/ssl.c b/src/ssl.c index 34e3b9b50ae..8c87f1baff7 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -12714,17 +12714,19 @@ static int CheckcipherList(const char* list) /* list has mixed suites */ return 0; } - } while (next++); /* ++ needed to skip ':' */ + } + while (next++); /* ++ needed to skip ':' */ if (findTLSv13Suites == 0 && findbeforeSuites == 1) { - return 1;/* only before TLSv13 suites */ + ret = 1;/* only before TLSv13 suites */ } else if (findTLSv13Suites == 1 && findbeforeSuites == 0) { - return 2;/* only TLSv13 suties */ + ret = 2;/* only TLSv13 suties */ } else { - return 0;/* handle as mixed */ + ret = 0;/* handle as mixed */ } + return ret; } /* parse some bulk lists like !eNULL / !aNULL @@ -35899,7 +35901,6 @@ const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) { #ifndef NO_FILESYSTEM char* rt; - char ap[] = "/.rnd"; WOLFSSL_ENTER("wolfSSL_RAND_file_name"); @@ -35921,6 +35922,8 @@ const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) /* $RANDFILE was not set or is too large, check $HOME */ if (rt == NULL) { + char ap[] = "/.rnd"; + WOLFSSL_MSG("Environment variable RANDFILE not set"); if ((rt = XGETENV("HOME")) == NULL) { WOLFSSL_MSG("Environment variable HOME not set"); diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 2e559283e31..24f41f81e85 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -1001,7 +1001,6 @@ int wolfSSL_a2i_ASN1_INTEGER(WOLFSSL_BIO *bio, WOLFSSL_ASN1_INTEGER *asn1, { int ret = 1; int readNextLine = 1; - int lineLen; int len; word32 outLen = 0; const int hdrSz = 1 + MAX_LENGTH_SZ; @@ -1014,6 +1013,8 @@ int wolfSSL_a2i_ASN1_INTEGER(WOLFSSL_BIO *bio, WOLFSSL_ASN1_INTEGER *asn1, } while ((ret == 1) && readNextLine) { + int lineLen; + /* Assume we won't be reading any more. */ readNextLine = 0; @@ -1048,8 +1049,6 @@ int wolfSSL_a2i_ASN1_INTEGER(WOLFSSL_BIO *bio, WOLFSSL_ASN1_INTEGER *asn1, outLen = (word32)(lineLen / 2); (void)Base16_Decode((byte*)buf, (word32)lineLen, asn1->data + asn1->length, &outLen); - } - if (ret == 1) { /* Update length of data. */ asn1->length += (int)outLen; } @@ -1455,16 +1454,17 @@ long wolfSSL_ASN1_INTEGER_get(const WOLFSSL_ASN1_INTEGER* a) int wolfSSL_ASN1_INTEGER_set(WOLFSSL_ASN1_INTEGER *a, long v) { int ret = 1; - byte j; - unsigned int i = 0; - byte tmp[sizeof(long)]; - byte pad = 0; /* Validate parameters. */ if (a == NULL) { ret = 0; } if (ret == 1) { + byte j; + unsigned int i = 0; + byte tmp[sizeof(long)]; + byte pad = 0; + wolfssl_asn1_integer_reset_data(a); /* Check for negative. */ @@ -1884,7 +1884,6 @@ int wolfSSL_i2t_ASN1_OBJECT(char *buf, int buf_len, WOLFSSL_ASN1_OBJECT *a) */ int wolfSSL_i2a_ASN1_OBJECT(WOLFSSL_BIO *bp, WOLFSSL_ASN1_OBJECT *a) { - int done = 0; int length = 0; int cLen = 0; word32 idx = 0; @@ -1896,36 +1895,26 @@ int wolfSSL_i2a_ASN1_OBJECT(WOLFSSL_BIO *bp, WOLFSSL_ASN1_OBJECT *a) /* Validate parameters. */ if (bp == NULL) { - done = 1; + /* Do nothing. */ } - /* NULL object is written as "NULL". */ - if ((!done) && (a == NULL)) { + else if (a == NULL) { /* Write "NULL" - as done in OpenSSL. */ length = wolfSSL_BIO_write(bp, null_str, (int)XSTRLEN(null_str)); - done = 1; } - /* Try getting text version and write it out. */ - if ((!done) && ((length = i2t_ASN1_OBJECT(buf, sizeof(buf), a)) > 0)) { + else if ((length = i2t_ASN1_OBJECT(buf, sizeof(buf), a)) > 0) { length = wolfSSL_BIO_write(bp, buf, length); - done = 1; } - /* Look for DER header. */ - if ((!done) && ((a->obj == NULL) || (a->obj[idx++] != ASN_OBJECT_ID))) { + else if ((a->obj == NULL) || (a->obj[idx++] != ASN_OBJECT_ID)) { WOLFSSL_MSG("Bad ASN1 Object"); - done = 1; } - /* Get length from DER header. */ - if ((!done) && (GetLength((const byte*)a->obj, &idx, &cLen, a->objSz) < 0)) - { + else if (GetLength((const byte*)a->obj, &idx, &cLen, a->objSz) < 0) { length = 0; - done = 1; } - - if (!done) { + else { /* Write out "" and dump content. */ length = wolfSSL_BIO_write(bp, invalid_str, (int)XSTRLEN(invalid_str)); length += wolfSSL_BIO_dump(bp, (const char*)(a->obj + idx), cLen); @@ -2217,7 +2206,6 @@ int wolfSSL_ASN1_UNIVERSALSTRING_to_string(WOLFSSL_ASN1_STRING *s) { int ret = 1; char* p; - char* copy; WOLFSSL_ENTER("wolfSSL_ASN1_UNIVERSALSTRING_to_string"); @@ -2252,6 +2240,8 @@ int wolfSSL_ASN1_UNIVERSALSTRING_to_string(WOLFSSL_ASN1_STRING *s) } if (ret == 1) { + char* copy; + /* Strip first three bytes of each four byte character. */ for (copy = p = s->data; p < s->data + s->length; p += 4) { *copy++ = p[3]; @@ -2813,8 +2803,6 @@ static int wolfssl_asn1_string_dump_hex(WOLFSSL_BIO *bio, { const char* hash="#"; char hex_tmp[4]; - char* p; - char* end; int str_len = 1; /* Write out hash character to indicate hex string. */ @@ -2837,6 +2825,9 @@ static int wolfssl_asn1_string_dump_hex(WOLFSSL_BIO *bio, } if (str_len != -1) { + char* p; + char* end; + /* Calculate end of string. */ end = str->data + str->length - 1; for (p = str->data; p <= end; p++) { @@ -3021,7 +3012,7 @@ static WC_INLINE const char* MonthStr(const char* n) i = (n[0] - '0') * 10 + (n[1] - '0') - 1; /* Convert string to number and index table. */ - if ((i >= 0) && (i <= 12)) { + if ((i >= 0) && (i < 12)) { month = monthStr[i]; } @@ -3844,7 +3835,6 @@ int wolfSSL_ASN1_TIME_to_tm(const WOLFSSL_ASN1_TIME* asnTime, struct tm* tm) */ int wolfSSL_ASN1_TIME_print(WOLFSSL_BIO* bio, const WOLFSSL_ASN1_TIME* asnTime) { - char buf[MAX_TIME_STRING_SZ]; int ret = 1; WOLFSSL_ENTER("wolfSSL_ASN1_TIME_print"); @@ -3856,6 +3846,7 @@ int wolfSSL_ASN1_TIME_print(WOLFSSL_BIO* bio, const WOLFSSL_ASN1_TIME* asnTime) } if (ret == 1) { + char buf[MAX_TIME_STRING_SZ]; int len; /* Create human readable string. */ diff --git a/src/x509.c b/src/x509.c index 54eccaf870a..ad03ae159da 100644 --- a/src/x509.c +++ b/src/x509.c @@ -309,9 +309,6 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_create_by_OBJ( if (err == 0) { ret->crit = crit; - } - - if (err == 0) { ret->obj = wolfSSL_ASN1_OBJECT_dup(obj); if (ret->obj == NULL) { err = 1; @@ -3278,14 +3275,9 @@ unsigned long wolfSSL_X509_issuer_name_hash(const WOLFSSL_X509* x509) */ char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) { - WOLFSSL_X509_NAME_ENTRY* entry; - int nameSz, strSz, strLen, count, i; + int count, i; int totalLen = 0; - char *str; char tmpBuf[256]; - const int tmpBufSz = sizeof(tmpBuf); - char buf[80]; - const char* sn; WOLFSSL_ENTER("wolfSSL_X509_get_name_oneline"); if (name == NULL) { @@ -3302,6 +3294,14 @@ char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) /* Loop through X509 name entries and copy new format to buffer */ count = wolfSSL_X509_NAME_entry_count(name); for (i = 0; i < count; i++) { + WOLFSSL_X509_NAME_ENTRY* entry; + int nameSz; + int strSz; + int strLen; + char *str; + const int tmpBufSz = sizeof(tmpBuf); + char buf[80]; + const char* sn; /* Get name entry and size */ entry = wolfSSL_X509_NAME_get_entry(name, i); @@ -3582,7 +3582,6 @@ int wolfSSL_X509_get_pubkey_buffer(WOLFSSL_X509* x509, #else DecodedCert cert[1]; #endif - word32 idx; const byte* der; int length = 0; int ret = 0, derSz = 0; @@ -3611,7 +3610,7 @@ int wolfSSL_X509_get_pubkey_buffer(WOLFSSL_X509* x509, InitDecodedCert(cert, der, derSz, NULL); ret = wc_GetPubX509(cert, 0, &badDate); if (ret >= 0) { - idx = cert->srcIdx; + word32 idx = cert->srcIdx; pubKeyX509 = cert->source + cert->srcIdx; ret = GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx); @@ -5599,7 +5598,6 @@ static int X509PrintSubjAltName(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) { int ret = WOLFSSL_SUCCESS; - int nameCount = 0; DNS_entry* entry; if (bio == NULL || x509 == NULL) { @@ -5620,6 +5618,8 @@ static int X509PrintSubjAltName(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, } } if (ret == WOLFSSL_SUCCESS) { + int nameCount = 0; + entry = x509->altNames; while (entry != NULL) { ++nameCount; @@ -5708,8 +5708,6 @@ static int X509PrintSubjAltName(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, static int X509PrintKeyUsage(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) { int ret = WOLFSSL_SUCCESS; - word32 i = 0; - int usageCount = 0; const int usages[] = { KEYUSE_DIGITAL_SIG, KEYUSE_CONTENT_COMMIT, @@ -5740,6 +5738,8 @@ static int X509PrintKeyUsage(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) if (ret == WOLFSSL_SUCCESS && x509->keyUsageSet && x509->keyUsage != 0) { char scratch[MAX_WIDTH]; int len; + word32 i = 0; + int usageCount = 0; len = XSNPRINTF(scratch, MAX_WIDTH, "%*s", indent, ""); if (len >= MAX_WIDTH) @@ -5776,8 +5776,6 @@ static int X509PrintExtendedKeyUsage(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) { int ret = WOLFSSL_SUCCESS; - word32 i = 0; - int usageCount = 0; const int usages[] = { EXTKEYUSE_OCSP_SIGN, EXTKEYUSE_TIMESTAMP, @@ -5803,6 +5801,8 @@ static int X509PrintExtendedKeyUsage(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, && x509->extKeyUsage != 0) { char scratch[MAX_WIDTH]; int len; + word32 i = 0; + int usageCount = 0; len = XSNPRINTF(scratch, MAX_WIDTH, "%*s", indent, ""); if (len >= MAX_WIDTH) @@ -5857,7 +5857,6 @@ static int X509PrintSerial_ex(WOLFSSL_BIO* bio, byte* serial, int sz, if (sz > (int)sizeof(byte)) { int i; - int valLen; /* serial is larger than int size so print off hex values */ if ((scratchLen = XSNPRINTF( @@ -5867,6 +5866,8 @@ static int X509PrintSerial_ex(WOLFSSL_BIO* bio, byte* serial, int sz, return WOLFSSL_FAILURE; } for (i = 0; i < sz; i++) { + int valLen; + if ((valLen = XSNPRINTF( scratch + scratchLen, scratchSz - scratchLen, "%02x%s", serial[i], (i < sz - 1) ? @@ -6158,7 +6159,6 @@ static int X509PrintSignature_ex(WOLFSSL_BIO* bio, byte* sig, int scratchLen; WOLFSSL_ASN1_OBJECT* obj = NULL; int ret = WOLFSSL_SUCCESS; - int i; char tmp[100]; int tmpLen = 0; @@ -6219,6 +6219,8 @@ static int X509PrintSignature_ex(WOLFSSL_BIO* bio, byte* sig, } if (ret == WOLFSSL_SUCCESS) { + int i; + for (i = 0; i < sigSz; i++) { char val[6]; int valLen; @@ -6394,9 +6396,10 @@ static int X509PrintPubKey(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) static int X509PrintName(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, char* type, int indent) { - char scratch[MAX_WIDTH]; - int scratchLen; if (name != NULL) { + char scratch[MAX_WIDTH]; + int scratchLen; + if ((scratchLen = XSNPRINTF(scratch, MAX_WIDTH, "%*s%s", indent, "", type)) >= MAX_WIDTH) diff --git a/tests/api.c b/tests/api.c index bc60c28d4fd..bfe4e6067f7 100644 --- a/tests/api.c +++ b/tests/api.c @@ -5501,13 +5501,6 @@ static WC_INLINE int test_ssl_memio_setup(test_ssl_memio_ctx *ctx) { ExpectIntEQ(wolfSSL_use_certificate_file(ctx->s_ssl, certFile, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); - } - if (0 -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) - || s_sharedCtx -#endif - ) - { ExpectIntEQ(wolfSSL_use_PrivateKey_file(ctx->s_ssl, keyFile, WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); } @@ -26224,7 +26217,7 @@ static int test_wc_ecc_signVerify_hash(void) if (signH == ECC_BAD_ARG_E) { signH = 0; } - else if (ret == 0) { + else { signH = WOLFSSL_FATAL_ERROR; } } @@ -26267,7 +26260,7 @@ static int test_wc_ecc_signVerify_hash(void) if (verifyH == ECC_BAD_ARG_E) { verifyH = 0; } - else if (ret == 0) { + else { verifyH = WOLFSSL_FATAL_ERROR; } } diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 9a021dbf691..8121e2a849a 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -4014,7 +4014,6 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #elif defined(FREESCALE_MMCAU) int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - int i; int offset = 0; byte *iv; byte temp_block[AES_BLOCK_SIZE]; @@ -4052,7 +4051,6 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #ifdef HAVE_AES_DECRYPT int wc_AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - int i; int offset = 0; byte* iv; byte temp_block[AES_BLOCK_SIZE]; diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index a1897c00a98..730fdf1a4ab 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -6516,7 +6516,6 @@ static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap); if (ret == 0) { - int i; /* Register variable to hold version field. */ GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version); /* Setup data to store INTEGER data in mp_int's in RSA object. */ @@ -6530,6 +6529,7 @@ static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, #define RSA_ASN_COMPLETE 1 #endif if (key != NULL) { + int i; /* Extract all public fields. */ for (i = 0; i < RSA_ASN_INTS; i++) { GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], @@ -12415,7 +12415,7 @@ static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen, XMEMCPY(dnsEntry->name, str, (size_t)strLen); dnsEntry->name[strLen] = '\0'; - #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) +#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) /* store IP addresses as a string */ if (type == ASN_IP_TYPE) { if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) { @@ -12423,10 +12423,9 @@ static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen, XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME); } } - #endif } - if (ret == 0) { +#endif ret = AddDNSEntryToList(entries, dnsEntry); } @@ -14810,9 +14809,7 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) return length; #else DECL_ASNSETDATA(dataASN, algoIdASN_Length); - int sz; int ret = 0; - int o = 0; const byte* algoName = 0; word32 algoSz = 0; @@ -14823,6 +14820,9 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) WOLFSSL_MSG("Unknown Algorithm"); } else { + int sz; + int o = 0; + /* Set the OID and OID type to encode. */ SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type); /* Hashes, signatures not ECC and keys not RSA output NULL tag. */ @@ -17081,9 +17081,7 @@ static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input, WOLFSSL_MSG("\tOut of Memory"); return MEMORY_E; } - } - if (ret == 0) { switch (oid) { #ifdef WOLFSSL_FPKI case FASCN_OID: @@ -17167,7 +17165,6 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; int length = 0; - byte current_byte; WOLFSSL_ENTER("DecodeAltNames"); @@ -17192,6 +17189,8 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) cert->weOwnAltNames = 1; while (length > 0) { + byte current_byte; + /* Verify idx can't overflow input buffer */ if (idx >= (word32)sz) { WOLFSSL_MSG("\tBad Index"); @@ -18249,12 +18248,7 @@ static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert) WOLFSSL_ENTER("DecodeSubjKeyId"); - if (sz <= 0) { - ret = ASN_PARSE_E; - } - if (ret == 0) { - ret = GetOctetString(input, &idx, &length, sz); - } + ret = GetOctetString(input, &idx, &length, sz); if (ret > 0) { #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) cert->extSubjKeyIdSrc = &input[idx]; @@ -20160,15 +20154,14 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset; issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset - dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset; - } - if (ret == 0) { + /* Get the subject name. */ subject = cert->source + dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset; subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset - dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset; } - if ((ret == 0) && (stopAtPubKey)) { + if ((ret == 0) && stopAtPubKey) { /* Return any bad date error through badDateRet and return offset of * subjectPublicKeyInfo. */ @@ -22880,7 +22873,6 @@ int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer, if (line != NULL) { word32 lineSz; char* finish; - word32 finishSz; char* start; word32 startSz; const char* newline = NULL; @@ -22914,6 +22906,8 @@ int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer, finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN)); if ((start != NULL) && (finish != NULL) && (start < finish)) { + word32 finishSz; + if (finish >= bufferEnd) { return BUFFER_E; } @@ -24291,8 +24285,8 @@ int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen, int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) { #ifndef WOLFSSL_ASN_TEMPLATE - int ret = 0, i, mpSz; - word32 j, seqSz = 0, verSz = 0, rawLen, intTotalLen = 0, outLen = 0; + int ret = 0, i; + word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0; word32 sizes[RSA_INTS]; byte seq[MAX_SEQ_SZ]; byte ver[MAX_VERSION_SZ]; @@ -24310,6 +24304,8 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) /* write all big ints from key to DER tmps */ for (i = 0; i < RSA_INTS; i++) { mp_int* keyInt = GetRsaInt(key, i); + int mpSz; + word32 rawLen; ret = mp_unsigned_bin_size(keyInt); if (ret < 0) @@ -24348,6 +24344,8 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) ret = BUFFER_E; } if (ret == 0 && output != NULL) { + word32 j; + /* write to output */ XMEMCPY(output, seq, seqSz); j = seqSz; diff --git a/wolfcrypt/src/des3.c b/wolfcrypt/src/des3.c index 672a8673b88..d932a4a2a8c 100644 --- a/wolfcrypt/src/des3.c +++ b/wolfcrypt/src/des3.c @@ -920,7 +920,6 @@ int wc_Des_CbcEncrypt(Des* des, byte* out, const byte* in, word32 sz) { - int i; int offset = 0; int len = sz; int ret = 0; @@ -966,7 +965,6 @@ int wc_Des_CbcDecrypt(Des* des, byte* out, const byte* in, word32 sz) { - int i; int offset = 0; int len = sz; int ret = 0; @@ -1013,7 +1011,6 @@ int wc_Des3_CbcEncrypt(Des3* des, byte* out, const byte* in, word32 sz) { - int i; int offset = 0; int len = sz; int ret = 0; @@ -1064,7 +1061,6 @@ int wc_Des3_CbcDecrypt(Des3* des, byte* out, const byte* in, word32 sz) { - int i; int offset = 0; int len = sz; int ret = 0; diff --git a/wolfcrypt/src/fe_448.c b/wolfcrypt/src/fe_448.c index 0dd439ed7db..cbc305d2b00 100644 --- a/wolfcrypt/src/fe_448.c +++ b/wolfcrypt/src/fe_448.c @@ -358,14 +358,13 @@ int curve448(byte* r, const byte* n, const byte* a) word8 t1[56]; int i; unsigned int swap; - unsigned int b; fe448_copy(x1, a); fe448_copy(x3, a); swap = 0; for (i = 447; i >= 0; --i) { - b = (n[i >> 3] >> (i & 7)) & 1; + unsigned int b = (n[i >> 3] >> (i & 7)) & 1; swap ^= b; fe448_cswap(x2, x3, swap); fe448_cswap(z2, z3, swap); @@ -1077,7 +1076,6 @@ int curve448(byte* r, const byte* n, const byte* a) sword64 t1[8]; int i; unsigned int swap; - unsigned int b; fe448_from_bytes(x1, a); fe448_1(x2); @@ -1087,7 +1085,7 @@ int curve448(byte* r, const byte* n, const byte* a) swap = 0; for (i = 447; i >= 0; --i) { - b = (n[i >> 3] >> (i & 7)) & 1; + unsigned int b = (n[i >> 3] >> (i & 7)) & 1; swap ^= b; fe448_cswap(x2, x3, swap); fe448_cswap(z2, z3, swap); @@ -2169,7 +2167,6 @@ int curve448(byte* r, const byte* n, const byte* a) sword32 t1[16]; int i; unsigned int swap; - unsigned int b; fe448_from_bytes(x1, a); fe448_1(x2); @@ -2179,7 +2176,7 @@ int curve448(byte* r, const byte* n, const byte* a) swap = 0; for (i = 447; i >= 0; --i) { - b = (n[i >> 3] >> (i & 7)) & 1; + unsigned int b = (n[i >> 3] >> (i & 7)) & 1; swap ^= b; fe448_cswap(x2, x3, swap); fe448_cswap(z2, z3, swap); diff --git a/wolfcrypt/src/fe_operations.c b/wolfcrypt/src/fe_operations.c index bf53da8f502..18e2b05e801 100644 --- a/wolfcrypt/src/fe_operations.c +++ b/wolfcrypt/src/fe_operations.c @@ -142,7 +142,6 @@ int curve25519(byte* q, const byte* n, const byte* p) fe tmp1 = {0}; int pos = 0; unsigned int swap = 0; - unsigned int b = 0; /* Clamp already done during key generation and import */ #if 0 @@ -163,6 +162,7 @@ int curve25519(byte* q, const byte* n, const byte* p) swap = 0; for (pos = 254;pos >= 0;--pos) { + unsigned int b; #if 0 b = e[pos / 8] >> (pos & 7); #else diff --git a/wolfcrypt/src/ge_low_mem.c b/wolfcrypt/src/ge_low_mem.c index a941ab473b7..c4fa510c898 100644 --- a/wolfcrypt/src/ge_low_mem.c +++ b/wolfcrypt/src/ge_low_mem.c @@ -133,7 +133,6 @@ static void barrett_reduce(word32* r, word32 x[64]) word32 r2[33]; word32 carry; word32 pb = 0; - word32 b; for (i = 0;i < 66;++i) q2[i] = 0; for (i = 0;i < 33;++i) r2[i] = 0; @@ -160,6 +159,7 @@ static void barrett_reduce(word32* r, word32 x[64]) for(i=0;i<32;i++) { + word32 b; pb += r2[i]; b = lt(r1[i],pb); r[i] = r1[i]-pb+(b<<8); diff --git a/wolfcrypt/src/hmac.c b/wolfcrypt/src/hmac.c index eecd2b9b998..05886875859 100644 --- a/wolfcrypt/src/hmac.c +++ b/wolfcrypt/src/hmac.c @@ -299,7 +299,7 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) #ifndef WOLFSSL_MAXQ108X byte* ip; byte* op; - word32 i, hmac_block_size = 0; + word32 hmac_block_size = 0; #endif int ret = 0; void* heap = NULL; @@ -582,6 +582,8 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) #endif if (ret == 0) { + word32 i; + if (length < hmac_block_size) XMEMSET(ip + length, 0, hmac_block_size - length); diff --git a/wolfcrypt/src/kdf.c b/wolfcrypt/src/kdf.c index f866dfcc36f..948caf6964f 100644 --- a/wolfcrypt/src/kdf.c +++ b/wolfcrypt/src/kdf.c @@ -73,8 +73,6 @@ int wc_PRF(byte* result, word32 resLen, const byte* secret, word32 times; word32 lastLen; word32 lastTime; - word32 i; - word32 idx = 0; int ret = 0; #ifdef WOLFSSL_SMALL_STACK byte* previous; @@ -164,6 +162,9 @@ int wc_PRF(byte* result, word32 resLen, const byte* secret, if (ret == 0) ret = wc_HmacFinal(hmac, previous); /* A1 */ if (ret == 0) { + word32 i; + word32 idx = 0; + for (i = 0; i < times; i++) { ret = wc_HmacUpdate(hmac, previous, len); if (ret != 0) diff --git a/wolfcrypt/src/port/kcapi/kcapi_hash.c b/wolfcrypt/src/port/kcapi/kcapi_hash.c index 215cec71ce4..72265d7b74c 100644 --- a/wolfcrypt/src/port/kcapi/kcapi_hash.c +++ b/wolfcrypt/src/port/kcapi/kcapi_hash.c @@ -167,9 +167,9 @@ static int KcapiHashFinal(wolfssl_KCAPI_Hash* hash, byte* out, word32 outSz, ret = (int)kcapi_md_update(hash->handle, hash->msg, hash->used); XFREE(hash->msg, heap, DYNAMIC_TYPE_TMP_BUFFER); hash->msg = NULL; + if (ret == 0) #endif - - if (ret == 0) { + { ret = (int)kcapi_md_final(hash->handle, out, outSz); } diff --git a/wolfcrypt/src/port/kcapi/kcapi_rsa.c b/wolfcrypt/src/port/kcapi/kcapi_rsa.c index f993f9c06b4..602c50b801e 100644 --- a/wolfcrypt/src/port/kcapi/kcapi_rsa.c +++ b/wolfcrypt/src/port/kcapi/kcapi_rsa.c @@ -136,7 +136,7 @@ static int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) { word32 seqSz, verSz, rawLen, intTotalLen = 0; word32 sizes[RSA_INTS]; - int i, j, outLen, ret = 0, mpSz; + int i, j, outLen, ret = 0; byte seq[MAX_SEQ_SZ]; byte ver[MAX_VERSION_SZ]; @@ -153,6 +153,7 @@ static int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) /* write all big ints from key to DER tmps */ for (i = 0; i < RSA_INTS; i++) { + int mpSz; mp_int* keyInt = GetRsaInt(key, i); rawLen = mp_unsigned_bin_size(keyInt) + 1; @@ -249,7 +250,7 @@ int KcapiRsa_Decrypt(RsaKey* key, const byte* in, word32 inLen, byte* out, if (ret != 0) { WOLFSSL_MSG("KcapiRsa_Decrypt: Failed initialization"); } - if (ret != 0) { + else { ret = KcapiRsa_SetPrivKey(key); } } @@ -340,7 +341,7 @@ int KcapiRsa_Encrypt(RsaKey* key, const byte* in, word32 inLen, byte* out, if (ret != 0) { WOLFSSL_MSG("KcapiRsa_Encrypt: Failed initialization"); } - if (ret == 0) { + else { ret = KcapiRsa_SetPubKey(key); } } diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index 411ee4a3f26..73b43a525f6 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -196,10 +196,10 @@ static void wc_Stm32_Hash_GetDigest(byte* hash, int digestSize) #ifdef DEBUG_STM32_HASH { - word32 i; + word32 ii; printf("STM Digest %d\n", digestSize); - for (i=0; ihash, hashType, key->heap, INVALID_DEVID); - if (err == 0) + if (err == 0) { hash_inited = 1; /* Step 1: A = hashfn( s ), where s = data | extra @@ -6230,8 +6230,8 @@ static int sakke_hash_to_range(SakkeKey* key, enum wc_HashType hashType, */ /* Step 2: h_0 = 00...00, a string of null bits of length hashlen bits */ - if (err == 0) err = wc_HashGetDigestSize(hashType); + } if (err > 0) { hashSz = (word32)err; XMEMSET(h, 0, hashSz); diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index c451e8f7f44..723abe2f769 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -599,7 +599,6 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) { int ret = WC_READDIR_NOFILE; /* default to no files found */ int pathLen = 0; - int dnameLen = 0; if (name) *name = NULL; @@ -626,7 +625,7 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) do { if (!(ctx->FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - dnameLen = (int)XSTRLEN(ctx->FindFileData.cFileName); + int dnameLen = (int)XSTRLEN(ctx->FindFileData.cFileName); if (pathLen + dnameLen + 2 > MAX_FILENAME_SZ) { return BAD_PATH_ERROR; @@ -655,7 +654,7 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) } do { - dnameLen = (int)XSTRLEN(IntimeFilename(ctx)); + int dnameLen = (int)XSTRLEN(IntimeFilename(ctx)); if (pathLen + dnameLen + 2 > MAX_FILENAME_SZ) { return BAD_PATH_ERROR; @@ -680,7 +679,7 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) ctx->dirp = &ctx->dir; while ((fs_readdir(&ctx->dir, &ctx->entry)) != 0) { - dnameLen = (int)XSTRLEN(ctx->entry.name); + int dnameLen = (int)XSTRLEN(ctx->entry.name); if (pathLen + dnameLen + 2 >= MAX_FILENAME_SZ) { ret = BAD_PATH_ERROR; @@ -707,7 +706,7 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) } while ((ctx->entry = m2mb_fs_readdir(ctx->dir)) != NULL) { - dnameLen = (int)XSTRLEN(ctx->entry->d_name); + int dnameLen = (int)XSTRLEN(ctx->entry->d_name); if (pathLen + dnameLen + 2 >= MAX_FILENAME_SZ) { ret = BAD_PATH_ERROR; @@ -735,7 +734,7 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) } while ((ctx->entry = readdir(ctx->dir)) != NULL) { - dnameLen = (int)XSTRLEN(ctx->entry->d_name); + int dnameLen = (int)XSTRLEN(ctx->entry->d_name); if (pathLen + dnameLen + 2 >= MAX_FILENAME_SZ) { ret = BAD_PATH_ERROR; @@ -765,7 +764,6 @@ int wc_ReadDirNext(ReadDirCtx* ctx, const char* path, char** name) { int ret = WC_READDIR_NOFILE; /* default to no file found */ int pathLen = 0; - int dnameLen = 0; if (name) *name = NULL; @@ -780,7 +778,7 @@ int wc_ReadDirNext(ReadDirCtx* ctx, const char* path, char** name) #ifdef USE_WINDOWS_API while (FindNextFileA(ctx->hFind, &ctx->FindFileData)) { if (!(ctx->FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - dnameLen = (int)XSTRLEN(ctx->FindFileData.cFileName); + int dnameLen = (int)XSTRLEN(ctx->FindFileData.cFileName); if (pathLen + dnameLen + 2 > MAX_FILENAME_SZ) { return BAD_PATH_ERROR; @@ -798,7 +796,7 @@ int wc_ReadDirNext(ReadDirCtx* ctx, const char* path, char** name) #elif defined(INTIME_RTOS) while (IntimeFindNext(&ctx->FindFileData)) { - dnameLen = (int)XSTRLEN(IntimeFilename(ctx)); + int dnameLen = (int)XSTRLEN(IntimeFilename(ctx)); if (pathLen + dnameLen + 2 > MAX_FILENAME_SZ) { return BAD_PATH_ERROR; @@ -817,7 +815,7 @@ int wc_ReadDirNext(ReadDirCtx* ctx, const char* path, char** name) #elif defined(WOLFSSL_ZEPHYR) while ((fs_readdir(&ctx->dir, &ctx->entry)) != 0) { - dnameLen = (int)XSTRLEN(ctx->entry.name); + int dnameLen = (int)XSTRLEN(ctx->entry.name); if (pathLen + dnameLen + 2 >= MAX_FILENAME_SZ) { ret = BAD_PATH_ERROR; @@ -838,7 +836,7 @@ int wc_ReadDirNext(ReadDirCtx* ctx, const char* path, char** name) } #elif defined(WOLFSSL_TELIT_M2MB) while ((ctx->entry = m2mb_fs_readdir(ctx->dir)) != NULL) { - dnameLen = (int)XSTRLEN(ctx->entry->d_name); + int dnameLen = (int)XSTRLEN(ctx->entry->d_name); if (pathLen + dnameLen + 2 >= MAX_FILENAME_SZ) { ret = BAD_PATH_ERROR; @@ -860,7 +858,7 @@ int wc_ReadDirNext(ReadDirCtx* ctx, const char* path, char** name) } #else while ((ctx->entry = readdir(ctx->dir)) != NULL) { - dnameLen = (int)XSTRLEN(ctx->entry->d_name); + int dnameLen = (int)XSTRLEN(ctx->entry->d_name); if (pathLen + dnameLen + 2 >= MAX_FILENAME_SZ) { ret = BAD_PATH_ERROR; From c31bfb5d5ae9a5db6c542c6dcdb5777e7f82d5ba Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 7 Jun 2023 14:00:43 +1000 Subject: [PATCH 362/391] Regression testing fixes Fix: ./configure --disable-shared --enable-smallstack --enable-all CFLAGS=-DNO_ASN_TIME Don't compile mp_test when compiling for SP Math All and RSA verification only - very few functions available. ssl.c: wolfSSL_Rehandshake(): wolfSSL_UseSessionTicket only available when not NO_WOLFSSL_CLIENT api.c: test_wolfSSL_ticket_keys(): meant to be tested on server --- src/ssl.c | 2 +- tests/api.c | 2 +- wolfcrypt/test/test.c | 19 +++++++++++++------ 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 8c87f1baff7..6d1f5ca7b43 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -4174,7 +4174,7 @@ int wolfSSL_Rehandshake(WOLFSSL* ssl) else { /* Reset resuming flag to do full secure handshake. */ ssl->options.resuming = 0; - #ifdef HAVE_SESSION_TICKET + #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_CLIENT) /* Clearing the ticket. */ ret = wolfSSL_UseSessionTicket(ssl); #endif diff --git a/tests/api.c b/tests/api.c index bfe4e6067f7..9885d797022 100644 --- a/tests/api.c +++ b/tests/api.c @@ -46316,7 +46316,7 @@ static int test_wolfSSL_ticket_keys(void) WOLFSSL_CTX* ctx; byte keys[WOLFSSL_TICKET_KEYS_SZ]; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); AssertIntEQ(wolfSSL_CTX_get_tlsext_ticket_keys(NULL, NULL, 0), WOLFSSL_FAILURE); diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index f5f08015f39..0ab018c5f49 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -579,7 +579,8 @@ WOLFSSL_TEST_SUBROUTINE int decodedCertCache_test(void); #endif WOLFSSL_TEST_SUBROUTINE int memory_test(void); #if defined(WOLFSSL_PUBLIC_MP) && \ - (defined(WOLFSSL_SP_MATH_ALL) || defined(USE_FAST_MATH)) + ((defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ + defined(USE_FAST_MATH)) WOLFSSL_TEST_SUBROUTINE int mp_test(void); #endif #if defined(WOLFSSL_PUBLIC_MP) && defined(WOLFSSL_KEY_GEN) @@ -1587,7 +1588,8 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ #endif #if defined(WOLFSSL_PUBLIC_MP) && \ - (defined(WOLFSSL_SP_MATH_ALL) || defined(USE_FAST_MATH)) + ((defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ + defined(USE_FAST_MATH)) if ( (ret = mp_test()) != 0) TEST_FAIL("mp test failed!\n", ret); else @@ -13949,12 +13951,15 @@ static void initDefaultName(void) WOLFSSL_SMALL_STACK_STATIC const char certKeyUsage[] = "digitalSignature,nonRepudiation"; #endif - #if defined(WOLFSSL_CERT_REQ) && !defined(NO_RSA) + #if !defined(NO_RSA) && defined(WOLFSSL_CERT_GEN) && \ + !defined(NO_ASN_TIME) && defined(WOLFSSL_CERT_REQ) && \ + !defined(WOLFSSL_NO_MALLOC) WOLFSSL_SMALL_STACK_STATIC const char certKeyUsage2[] = "digitalSignature,nonRepudiation,keyEncipherment,keyAgreement"; #endif #endif /* WOLFSSL_CERT_EXT */ -#endif /* WOLFSSL_CERT_GEN */ +#endif /* WOLFSSL_CERT_GEN && (!NO_RSA || HAVE_ECC) || (WOLFSSL_TEST_CERT && + * (HAVE_ED25519 || HAVE_ED448)) */ #ifndef NO_RSA @@ -40383,7 +40388,8 @@ WOLFSSL_TEST_SUBROUTINE int pkcs7signed_test(void) #endif /* HAVE_PKCS7 */ #if defined(WOLFSSL_PUBLIC_MP) && \ - (defined(WOLFSSL_SP_MATH_ALL) || defined(USE_FAST_MATH)) + ((defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ + defined(USE_FAST_MATH)) /* Maximum number of bytes in a number to test. */ #define MP_MAX_TEST_BYTE_LEN 32 @@ -43315,7 +43321,8 @@ WOLFSSL_TEST_SUBROUTINE int mp_test(void) return ret; } -#endif /* WOLFSSL_PUBLIC_MP && (WOLFSSL_SP_MATH_ALL || USE_FAST_MATH) */ +#endif /* WOLFSSL_PUBLIC_MP && ((WOLFSSL_SP_MATH_ALL && + * !WOLFSSL_RSA_VERIFY_ONLY) || USE_FAST_MATH) */ #if defined(WOLFSSL_PUBLIC_MP) && defined(WOLFSSL_KEY_GEN) From dc5c506720a080ec4bf3fdfebb21c51ca5370270 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Mon, 5 Jun 2023 17:39:39 +1000 Subject: [PATCH 363/391] Test api.c: change more tests to use Expect instead of Assert bio.c: wolfSSL_BIO_push(): handles NULL for top and append. crl.c: InitCRL_Entry(): set toBeSigned to NULL after freeing when allocation fails. AddCRL(): free CRL entry properly on error. wolfSSL_X509_STORE_add_crl(): check for NULL after wolfSSL_X509_crl_new call. ssl.c: wolfSSL_CertManagerGetCerts(): free the certificate if it didn't get pushed onto stack wolfSSL_RAND_Init(): returns success if global already initialized. ssl_asn1.c: wolfSSL_ASN1_TYPE_set now avaiable when OPENSSL_EXTRA defined for function wolfssl_dns_entry_othername_to_gn(). x509.c: Added support for creating a valid General Name of type GEN_OTHERNAME. Extracted some code out into wolfssl_x509_alt_names_to_gn(). wolfSSL_X509_set_ext(): free data correctly on errors wolfSSL_X509_PUBKEY_set(): free str if DSA parameters cannot be retrieved; wolfSSL_OBJ_nid2obj() called separately to handle when returning NULL. wolfSSL_X509_NAME_copy(): check for failure when wolfSSL_X509_NAME_add_entry() is called. x509_str.c: wolfSSL_X509_STORE_CTX_new(): check for error from calling wolfSSL_X509_STORE_CTX_init(). wolfSSL_X509_STORE_get0_objects(): don't double free x509; free memory correctly on error --- src/bio.c | 9 +- src/crl.c | 13 +- src/ssl.c | 4 +- src/ssl_asn1.c | 4 +- src/x509.c | 311 ++- src/x509_str.c | 15 +- tests/api.c | 5902 +++++++++++++++++++++++++----------------------- 7 files changed, 3278 insertions(+), 2980 deletions(-) diff --git a/src/bio.c b/src/bio.c index f0d518c62c1..595343488f0 100644 --- a/src/bio.c +++ b/src/bio.c @@ -2693,8 +2693,13 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_BIO* wolfSSL_BIO_push(WOLFSSL_BIO* top, WOLFSSL_BIO* append) { WOLFSSL_ENTER("wolfSSL_BIO_push"); - top->next = append; - append->prev = top; + if (top == NULL) { + return append; + } + top->next = append; + if (append != NULL) { + append->prev = top; + } /* SSL BIO's should use the next object in the chain for IO */ if (top->type == WOLFSSL_BIO_SSL && top->ptr) diff --git a/src/crl.c b/src/crl.c index 659a780938a..559e459c1de 100644 --- a/src/crl.c +++ b/src/crl.c @@ -142,6 +142,7 @@ static int InitCRL_Entry(CRL_Entry* crle, DecodedCRL* dcrl, const byte* buff, DYNAMIC_TYPE_CRL_ENTRY); if (crle->signature == NULL) { XFREE(crle->toBeSigned, heap, DYNAMIC_TYPE_CRL_ENTRY); + crle->toBeSigned = NULL; return -1; } XMEMCPY(crle->toBeSigned, buff + dcrl->certBegin, crle->tbsSz); @@ -529,14 +530,19 @@ static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff, if (InitCRL_Entry(crle, dcrl, buff, verified, crl->heap) < 0) { WOLFSSL_MSG("Init CRL Entry failed"); - XFREE(crle, crl->heap, DYNAMIC_TYPE_CRL_ENTRY); + FreeCRL_Entry(crle, crl->heap); + if (crle != crl->currentEntry) { + XFREE(crle, crl->heap, DYNAMIC_TYPE_CRL_ENTRY); + } return -1; } if (wc_LockMutex(&crl->crlLock) != 0) { WOLFSSL_MSG("wc_LockMutex failed"); FreeCRL_Entry(crle, crl->heap); - XFREE(crle, crl->heap, DYNAMIC_TYPE_CRL_ENTRY); + if (crle != crl->currentEntry) { + XFREE(crle, crl->heap, DYNAMIC_TYPE_CRL_ENTRY); + } return BAD_MUTEX_E; } @@ -863,6 +869,9 @@ int wolfSSL_X509_STORE_add_crl(WOLFSSL_X509_STORE *store, WOLFSSL_X509_CRL *newc if (store->cm->crl == NULL) { crl = wolfSSL_X509_crl_new(store->cm); + if (crl == NULL) { + return WOLFSSL_FAILURE; + } if (DupX509_CRL(crl, newcrl) != 0) { if (crl != NULL) FreeCRL(crl, 1); diff --git a/src/ssl.c b/src/ssl.c index 6d1f5ca7b43..a3793ac55ef 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -5322,8 +5322,10 @@ WOLFSSL_STACK* wolfSSL_CertManagerGetCerts(WOLFSSL_CERT_MANAGER* cm) if (x509 == NULL) goto error; - if (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) + if (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) { + wolfSSL_X509_free(x509); goto error; + } } for (i = 0; i < numCerts && certBuffers[i] != NULL; ++i) { diff --git a/src/ssl_asn1.c b/src/ssl_asn1.c index 24f41f81e85..fb33a254859 100644 --- a/src/ssl_asn1.c +++ b/src/ssl_asn1.c @@ -3993,7 +3993,7 @@ void wolfSSL_ASN1_TYPE_free(WOLFSSL_ASN1_TYPE* at) #endif /* OPENSSL_EXTRA */ -#if defined(OPENSSL_ALL) || defined(WOLFSSL_WPAS) +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS) /** * Set ASN.1 TYPE object with a type and value. * @@ -4046,7 +4046,7 @@ void wolfSSL_ASN1_TYPE_set(WOLFSSL_ASN1_TYPE *a, int type, void *value) } } -#endif /* OPENSSL_ALL || WOLFSSL_WPAS */ +#endif /* OPENSSL_ALL || OPENSSL_EXTRA || WOLFSSL_WPAS */ #endif /* !NO_ASN */ diff --git a/src/x509.c b/src/x509.c index ad03ae159da..c29503d76e3 100644 --- a/src/x509.c +++ b/src/x509.c @@ -527,6 +527,190 @@ int wolfSSL_X509_get_ext_by_OBJ(const WOLFSSL_X509 *x, return -1; } +/* Set a general name from the DNS entry data. + * + * @param [in] dns DNS entry. + * @param [in, out] gn General name to place data in. + * @return 1 on success. + * @return 0 on failure. + */ +static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, + WOLFSSL_GENERAL_NAME* gn) +{ + int ret = 0; + WOLFSSL_ASN1_OBJECT* obj; + WOLFSSL_ASN1_TYPE* type; + WOLFSSL_ASN1_STRING* str; + byte tag; + unsigned char* p = (unsigned char *)dns->name; + long len = dns->len; + +#ifdef WOLFSSL_FPKI + if (dns->oidSum != 0) { + /* UPN OID: 1.3.6.1.4.1.311.20.2.3 */ + static const unsigned char upn_oid[] = { + 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x14, 0x02, 0x03 + }; + const unsigned char* oid; + word32 oidSz; + + if ((oid = OidFromId(dns->oidSum, oidCertAltNameType, &oidSz)) == + NULL) { + if (dns->oidSum == UPN_OID) { + oid = upn_oid; + oidSz = (word32)sizeof(upn_oid); + } + else { + goto err; + } + } + if ((obj = wolfSSL_c2i_ASN1_OBJECT(NULL, &oid, oidSz)) == NULL) { + goto err; + } + + tag = ASN_UTF8STRING; + } + else +#endif + { + word32 idx = 0; + int nameLen; + + /* Create an object id for general name from DER encoding. */ + obj = wolfSSL_d2i_ASN1_OBJECT(NULL, (const unsigned char**)&p, len); + if (obj == NULL) { + goto err; + } + /* Pointer moved on and now update length of remaining data. */ + len -= (long)((size_t)p - (size_t)dns->name); + + /* Next is: [0]. Check tag and length. */ + if (GetASNTag(p, &idx, &tag, (word32)len) < 0) { + goto err; + } + if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)) { + wolfSSL_ASN1_OBJECT_free(obj); + goto err; + } + if (GetLength(p, &idx, &nameLen, (word32)len) <= 1) { + wolfSSL_ASN1_OBJECT_free(obj); + goto err; + } + + /* Next is a string of some type. */ + if (GetASNTag(p, &idx, &tag, (word32)len) < 0) { + wolfSSL_ASN1_OBJECT_free(obj); + goto err; + } + if (GetLength(p, &idx, &nameLen, (word32)len) <= 0) { + wolfSSL_ASN1_OBJECT_free(obj); + goto err; + } + p += idx; + len -= idx; + } + + /* Create a WOLFSSL_ASN1_STRING from the DER. */ + str = wolfSSL_ASN1_STRING_type_new(tag); + if (str == NULL) { + wolfSSL_ASN1_OBJECT_free(obj); + goto err; + } + wolfSSL_ASN1_STRING_set(str, p, (word32)len); + + /* Wrap string in a WOLFSSL_ASN1_TYPE. */ + type = wolfSSL_ASN1_TYPE_new(); + if (type == NULL) { + wolfSSL_ASN1_OBJECT_free(obj); + wolfSSL_ASN1_STRING_free(str); + goto err; + } + wolfSSL_ASN1_TYPE_set(type, tag, str); + + /* Store the object and string in general name. */ + gn->d.otherName->type_id = obj; + gn->d.otherName->value = type; + + ret = 1; +err: + return ret; +} + +static int wolfssl_x509_alt_names_to_gn(WOLFSSL_X509* x509, + WOLFSSL_X509_EXTENSION* ext) +{ + int ret = 0; + WOLFSSL_GENERAL_NAME* gn = NULL; + DNS_entry* dns = NULL; + WOLFSSL_STACK* sk; + +#ifdef OPENSSL_ALL + ret = wolfSSL_ASN1_STRING_set(&ext->value, x509->subjAltNameSrc, + x509->subjAltNameSz); + if (ret != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("ASN1_STRING_set() failed"); + goto err; + } +#endif + + sk = (WOLFSSL_GENERAL_NAMES*)XMALLOC(sizeof(WOLFSSL_GENERAL_NAMES), NULL, + DYNAMIC_TYPE_ASN1); + if (sk == NULL) { + goto err; + } + XMEMSET(sk, 0, sizeof(WOLFSSL_GENERAL_NAMES)); + sk->type = STACK_TYPE_GEN_NAME; + + if (x509->subjAltNameSet && x509->altNames != NULL) { + /* alt names are DNS_entry structs */ + dns = x509->altNames; + /* Currently only support GEN_DNS type */ + while (dns != NULL) { + gn = wolfSSL_GENERAL_NAME_new(); + if (gn == NULL) { + WOLFSSL_MSG("Error creating GENERAL_NAME"); + wolfSSL_sk_pop_free(sk, NULL); + goto err; + } + + gn->type = dns->type; + if (gn->type == GEN_OTHERNAME) { + if (!wolfssl_dns_entry_othername_to_gn(dns, gn)) { + WOLFSSL_MSG("OTHERNAME set failed"); + wolfSSL_GENERAL_NAME_free(gn); + wolfSSL_sk_pop_free(sk, NULL); + goto err; + } + } + else { + gn->d.ia5->length = dns->len; + if (wolfSSL_ASN1_STRING_set(gn->d.ia5, dns->name, + gn->d.ia5->length) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("ASN1_STRING_set failed"); + wolfSSL_GENERAL_NAME_free(gn); + wolfSSL_sk_pop_free(sk, NULL); + goto err; + } + } + + if (wolfSSL_sk_GENERAL_NAME_push(sk, gn) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error pushing onto stack"); + wolfSSL_GENERAL_NAME_free(gn); + wolfSSL_sk_pop_free(sk, NULL); + goto err; + } + + dns = dns->next; + } + } + ext->ext_sk = sk; + ext->crit = x509->subjAltNameCrit; + + ret = 1; +err: + return ret; +} + /* Pushes a new X509_EXTENSION* ext onto the stack inside WOLFSSL_X509* x509. * This is currently a helper function for wolfSSL_X509_get_ext * Caller does not free the returned WOLFSSL_X509_EXTENSION* @@ -900,17 +1084,9 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) break; case ALT_NAMES_OID: - { - WOLFSSL_GENERAL_NAME* gn = NULL; - DNS_entry* dns = NULL; if (!isSet) break; - - #ifdef OPENSSL_ALL - ret = wolfSSL_ASN1_STRING_set(&ext->value, x509->subjAltNameSrc, - x509->subjAltNameSz); - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("ASN1_STRING_set() failed"); + if (!wolfssl_x509_alt_names_to_gn(x509, ext)) { wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); #ifdef WOLFSSL_SMALL_STACK @@ -918,88 +1094,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) #endif return NULL; } - #endif - - sk = (WOLFSSL_GENERAL_NAMES*)XMALLOC( - sizeof(WOLFSSL_GENERAL_NAMES), NULL, - DYNAMIC_TYPE_ASN1); - if (sk == NULL) { - wolfSSL_X509_EXTENSION_free(ext); - FreeDecodedCert(cert); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); - #endif - return NULL; - } - XMEMSET(sk, 0, sizeof(WOLFSSL_GENERAL_NAMES)); - sk->type = STACK_TYPE_GEN_NAME; - - if (x509->subjAltNameSet && x509->altNames != NULL) { - /* alt names are DNS_entry structs */ - dns = x509->altNames; - /* Currently only support GEN_DNS type */ - while (dns != NULL) { - gn = wolfSSL_GENERAL_NAME_new(); - if (gn == NULL) { - WOLFSSL_MSG("Error creating GENERAL_NAME"); - wolfSSL_X509_EXTENSION_free(ext); - FreeDecodedCert(cert); - wolfSSL_sk_pop_free(sk, NULL); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); - #endif - return NULL; - } - - gn->type = dns->type; - gn->d.ia5->length = dns->len; - if (wolfSSL_ASN1_STRING_set(gn->d.ia5, dns->name, - gn->d.ia5->length) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("ASN1_STRING_set failed"); - wolfSSL_X509_EXTENSION_free(ext); - FreeDecodedCert(cert); - wolfSSL_GENERAL_NAME_free(gn); - wolfSSL_sk_pop_free(sk, NULL); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); - #endif - return NULL; - } - - dns = dns->next; - /* last dns in list add at end of function */ - if (dns != NULL) { - if (wolfSSL_sk_GENERAL_NAME_push(sk, gn) != - WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error pushing onto stack"); - wolfSSL_X509_EXTENSION_free(ext); - FreeDecodedCert(cert); - wolfSSL_GENERAL_NAME_free(gn); - wolfSSL_sk_pop_free(sk, NULL); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); - #endif - return NULL; - } - } - } - if (wolfSSL_sk_GENERAL_NAME_push(sk,gn) != - WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error pushing onto stack"); - wolfSSL_X509_EXTENSION_free(ext); - FreeDecodedCert(cert); - wolfSSL_GENERAL_NAME_free(gn); - wolfSSL_sk_pop_free(sk, NULL); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); - #endif - return NULL; - } - } - ext->ext_sk = sk; - ext->crit = x509->subjAltNameCrit; break; - } default: WOLFSSL_MSG("Unknown extension type found, parsing OID"); @@ -1037,6 +1132,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) if (ext->obj == NULL) { ext->obj = wolfSSL_ASN1_OBJECT_new(); if (ext->obj == NULL) { + XFREE(oidBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); #ifdef WOLFSSL_SMALL_STACK @@ -1053,7 +1149,6 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) ext->obj->objSz, NULL,DYNAMIC_TYPE_ASN1); if (ext->obj->obj == NULL) { - wolfSSL_ASN1_OBJECT_free(ext->obj); wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); XFREE(oidBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -2136,6 +2231,12 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, } break; + case ASN_OTHER_TYPE: + if (!wolfssl_dns_entry_othername_to_gn(dns, gn)) { + goto err; + } + break; + default: if (wolfSSL_ASN1_STRING_set(gn->d.dNSName, dns->name, dns->len) != WOLFSSL_SUCCESS) { @@ -2490,7 +2591,7 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, } #endif if (sk) { - wolfSSL_sk_free(sk); + wolfSSL_sk_pop_free(sk, NULL); } return NULL; } @@ -9141,6 +9242,7 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) int nid; const WOLFSSL_EC_GROUP *group; #endif + WOLFSSL_ASN1_OBJECT *keyTypeObj; WOLFSSL_ENTER("wolfSSL_X509_PUBKEY_set"); @@ -9169,9 +9271,12 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) if (str == NULL) goto error; - str->length = wolfSSL_i2d_DSAparams(key->dsa, (unsigned char **)&str->data); - if (str->length <= 0) + str->length = wolfSSL_i2d_DSAparams(key->dsa, + (unsigned char **)&str->data); + if (str->length <= 0) { + wolfSSL_ASN1_STRING_free(str); goto error; + } str->isDynamic = 1; pval = str; @@ -9205,8 +9310,17 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) goto error; } - if (!wolfSSL_X509_ALGOR_set0(pk->algor, wolfSSL_OBJ_nid2obj(key->type), ptype, pval)) { + keyTypeObj = wolfSSL_OBJ_nid2obj(key->type); + if (keyTypeObj == NULL) { + if (ptype == V_ASN1_OBJECT) + ASN1_OBJECT_free((WOLFSSL_ASN1_OBJECT *)pval); + else + ASN1_STRING_free((WOLFSSL_ASN1_STRING *)pval); + goto error; + } + if (!wolfSSL_X509_ALGOR_set0(pk->algor, keyTypeObj, ptype, pval)) { WOLFSSL_MSG("Failed to create algorithm object"); + ASN1_OBJECT_free(keyTypeObj); if (ptype == V_ASN1_OBJECT) ASN1_OBJECT_free((WOLFSSL_ASN1_OBJECT *)pval); else @@ -13274,8 +13388,11 @@ int wolfSSL_X509_NAME_copy(WOLFSSL_X509_NAME* from, WOLFSSL_X509_NAME* to) for (i = 0; i < MAX_NAME_ENTRIES; i++) { WOLFSSL_X509_NAME_ENTRY* ne = wolfSSL_X509_NAME_get_entry(from, i); - if (ne != NULL) - wolfSSL_X509_NAME_add_entry(to, ne, i, 1); + if (ne != NULL) { + if (wolfSSL_X509_NAME_add_entry(to, ne, i, 1) != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + } } to->entrySz = from->entrySz; return WOLFSSL_SUCCESS; diff --git a/src/x509_str.c b/src/x509_str.c index 52f8c775a1b..4ba0ce692dd 100644 --- a/src/x509_str.c +++ b/src/x509_str.c @@ -51,7 +51,11 @@ WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new(void) DYNAMIC_TYPE_X509_CTX); if (ctx != NULL) { ctx->param = NULL; - wolfSSL_X509_STORE_CTX_init(ctx, NULL, NULL, NULL); + if (wolfSSL_X509_STORE_CTX_init(ctx, NULL, NULL, NULL) != + WOLFSSL_SUCCESS) { + XFREE(ctx, NULL, DYNAMIC_TYPE_X509_CTX); + ctx = NULL; + } } return ctx; @@ -1261,6 +1265,7 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( } obj->type = WOLFSSL_X509_LU_X509; obj->data.x509 = x509; + x509 = NULL; } #endif @@ -1286,11 +1291,11 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( store->objs = ret; return ret; err_cleanup: - if (ret) - wolfSSL_sk_X509_OBJECT_free(ret); - if (cert_stack) + if (ret != NULL) + wolfSSL_sk_X509_OBJECT_pop_free(ret, NULL); + if (cert_stack != NULL) wolfSSL_sk_X509_pop_free(cert_stack, NULL); - if (x509) + if (x509 != NULL) wolfSSL_X509_free(x509); return NULL; } diff --git a/tests/api.c b/tests/api.c index 9885d797022..70b6f558c39 100644 --- a/tests/api.c +++ b/tests/api.c @@ -3784,41 +3784,41 @@ static int test_wolfSSL_set_minmax_proto_version(void) { int res = TEST_SKIPPED; #ifdef OPENSSL_EXTRA - WOLFSSL_CTX *ctx; - WOLFSSL *ssl; - int ret; - (void)ret; + EXPECT_DECLS; + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; + (void)ssl; #ifndef NO_WOLFSSL_CLIENT - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); - AssertNotNull(ssl = wolfSSL_new(ctx)); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); - AssertIntEQ(wolfSSL_CTX_set_min_proto_version(NULL, 0), SSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set_max_proto_version(NULL, 0), SSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set_min_proto_version(ctx, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_set_max_proto_version(ctx, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set_min_proto_version(NULL, 0), SSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_set_max_proto_version(NULL, 0), SSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_set_min_proto_version(ctx, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set_max_proto_version(ctx, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_set_min_proto_version(NULL, 0), SSL_FAILURE); - AssertIntEQ(wolfSSL_set_min_proto_version(ssl, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_set_max_proto_version(NULL, 0), SSL_FAILURE); - AssertIntEQ(wolfSSL_set_max_proto_version(ssl, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_set_min_proto_version(NULL, 0), SSL_FAILURE); + ExpectIntEQ(wolfSSL_set_min_proto_version(ssl, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_set_max_proto_version(NULL, 0), SSL_FAILURE); + ExpectIntEQ(wolfSSL_set_max_proto_version(ssl, 0), SSL_SUCCESS); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); #endif #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); - AssertIntEQ(wolfSSL_CTX_set_min_proto_version(NULL, 0), SSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set_max_proto_version(NULL, 0), SSL_FAILURE); - AssertIntEQ(wolfSSL_CTX_set_min_proto_version(ctx, 0), SSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_set_max_proto_version(ctx, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set_min_proto_version(NULL, 0), SSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_set_max_proto_version(NULL, 0), SSL_FAILURE); + ExpectIntEQ(wolfSSL_CTX_set_min_proto_version(ctx, 0), SSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set_max_proto_version(ctx, 0), SSL_SUCCESS); wolfSSL_CTX_free(ctx); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; @@ -38104,59 +38104,63 @@ static int test_wolfSSL_X509_Name_canon(void) !defined(NO_FILESYSTEM) && !defined(NO_SHA) && \ defined(WOLFSSL_CERT_GEN) && \ (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && !defined(NO_RSA) + EXPECT_DECLS; const long ex_hash1 = 0x0fdb2da4; const long ex_hash2 = 0x9f3e8c9e; X509_NAME *name = NULL; X509 *x509 = NULL; - FILE* file = NULL; + XFILE file = XBADFILE; unsigned long hash = 0; byte digest[WC_MAX_DIGEST_SIZE] = {0}; byte *pbuf = NULL; word32 len = 0; (void) ex_hash2; - file = XFOPEN(caCertFile, "rb"); - AssertNotNull(file); - AssertNotNull(x509 = PEM_read_X509(file, NULL, NULL, NULL)); - AssertNotNull(name = X509_get_issuer_name(x509)); + ExpectTrue((file = XFOPEN(caCertFile, "rb")) != XBADFILE); + ExpectNotNull(x509 = PEM_read_X509(file, NULL, NULL, NULL)); + ExpectNotNull(name = X509_get_issuer_name(x509)); /* When output buffer is NULL, should return necessary output buffer * length.*/ - AssertIntGT(wolfSSL_i2d_X509_NAME_canon(name, NULL), 0); - AssertIntGT((len = wolfSSL_i2d_X509_NAME_canon(name, &pbuf)), 0); - AssertIntEQ(wc_ShaHash((const byte*)pbuf, (word32)len, digest), 0); + ExpectIntGT(wolfSSL_i2d_X509_NAME_canon(name, NULL), 0); + ExpectIntGT((len = wolfSSL_i2d_X509_NAME_canon(name, &pbuf)), 0); + ExpectIntEQ(wc_ShaHash((const byte*)pbuf, (word32)len, digest), 0); hash = (((unsigned long)digest[3] << 24) | ((unsigned long)digest[2] << 16) | ((unsigned long)digest[1] << 8) | ((unsigned long)digest[0])); - AssertIntEQ(hash, ex_hash1); + ExpectIntEQ(hash, ex_hash1); - XFCLOSE(file); + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } X509_free(x509); + x509 = NULL; XFREE(pbuf, NULL, DYNAMIC_TYPE_OPENSSL); pbuf = NULL; - file = XFOPEN(cliCertFile, "rb"); - AssertNotNull(file); - AssertNotNull(x509 = PEM_read_X509(file, NULL, NULL, NULL)); - AssertNotNull(name = X509_get_issuer_name(x509)); + ExpectTrue((file = XFOPEN(cliCertFile, "rb")) != XBADFILE); + ExpectNotNull(x509 = PEM_read_X509(file, NULL, NULL, NULL)); + ExpectNotNull(name = X509_get_issuer_name(x509)); - AssertIntGT((len = wolfSSL_i2d_X509_NAME_canon(name, &pbuf)), 0); - AssertIntEQ(wc_ShaHash((const byte*)pbuf, (word32)len, digest), 0); + ExpectIntGT((len = wolfSSL_i2d_X509_NAME_canon(name, &pbuf)), 0); + ExpectIntEQ(wc_ShaHash((const byte*)pbuf, (word32)len, digest), 0); hash = (((unsigned long)digest[3] << 24) | ((unsigned long)digest[2] << 16) | ((unsigned long)digest[1] << 8) | ((unsigned long)digest[0])); - AssertIntEQ(hash, ex_hash2); + ExpectIntEQ(hash, ex_hash2); - XFCLOSE(file); + if (file != XBADFILE) + XFCLOSE(file); X509_free(x509); XFREE(pbuf, NULL, DYNAMIC_TYPE_OPENSSL); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -38165,6 +38169,7 @@ static int test_wolfSSL_X509_LOOKUP_ctrl_hash_dir(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) + EXPECT_DECLS; const int MAX_DIR = 4; const char paths[][32] = { "./certs/ed25519", @@ -38175,35 +38180,37 @@ static int test_wolfSSL_X509_LOOKUP_ctrl_hash_dir(void) char CertCrl_path[MAX_FILENAME_SZ]; char *p; - X509_STORE* str; - X509_LOOKUP* lookup; + X509_STORE* str = NULL; + X509_LOOKUP* lookup = NULL; WOLFSSL_STACK* sk = NULL; int len, total_len, i; - (void) sk; + (void)sk; XMEMSET(CertCrl_path, 0, MAX_FILENAME_SZ); /* illegal string */ - AssertNotNull((str = wolfSSL_X509_STORE_new())); - AssertNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); - AssertIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_ADD_DIR, "", + ExpectNotNull((str = wolfSSL_X509_STORE_new())); + ExpectNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); + ExpectIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_ADD_DIR, "", SSL_FILETYPE_PEM,NULL), 0); /* free store */ X509_STORE_free(str); + str = NULL; /* short folder string */ - AssertNotNull((str = wolfSSL_X509_STORE_new())); - AssertNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); - AssertIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_ADD_DIR, "./", + ExpectNotNull((str = wolfSSL_X509_STORE_new())); + ExpectNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); + ExpectIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_ADD_DIR, "./", SSL_FILETYPE_PEM,NULL), 1); #if defined(WOLFSSL_INT_H) /* only available when including internal.h */ - AssertNotNull(sk = lookup->dirs->dir_entry); + ExpectNotNull(sk = lookup->dirs->dir_entry); #endif /* free store */ X509_STORE_free(str); + str = NULL; /* typical function check */ p = &CertCrl_path[0]; @@ -38217,18 +38224,18 @@ static int test_wolfSSL_X509_LOOKUP_ctrl_hash_dir(void) if (i != 0) *(p++) = SEPARATOR_CHAR; } - AssertNotNull((str = wolfSSL_X509_STORE_new())); - AssertNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); - AssertIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_ADD_DIR, CertCrl_path, + ExpectNotNull((str = wolfSSL_X509_STORE_new())); + ExpectNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); + ExpectIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_ADD_DIR, CertCrl_path, SSL_FILETYPE_PEM,NULL), 1); #if defined(WOLFSSL_INT_H) /* only available when including internal.h */ - AssertNotNull(sk = lookup->dirs->dir_entry); + ExpectNotNull(sk = lookup->dirs->dir_entry); #endif X509_STORE_free(str); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -38239,22 +38246,24 @@ static int test_wolfSSL_X509_LOOKUP_ctrl_file(void) #if defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) && \ defined(WOLFSSL_SIGNER_DER_CERT) + EXPECT_DECLS; + X509_STORE_CTX* ctx = NULL; + X509_STORE* str = NULL; + X509_LOOKUP* lookup = NULL; - X509_STORE_CTX* ctx; - X509_STORE* str; - X509_LOOKUP* lookup; - - X509* cert1; - X509* x509Ca; - X509* x509Svr; - X509* issuer; + X509* cert1 = NULL; + X509* x509Ca = NULL; + X509* x509Svr = NULL; + X509* issuer = NULL; WOLFSSL_STACK* sk = NULL; - X509_NAME* caName; - X509_NAME* issuerName; + X509_NAME* caName = NULL; + X509_NAME* issuerName = NULL; - FILE* file1 = NULL; - int i, cert_count, cmp; + XFILE file1 = XBADFILE; + int i; + int cert_count = 0; + int cmp; char der[] = "certs/ca-cert.der"; @@ -38268,98 +38277,106 @@ static int test_wolfSSL_X509_LOOKUP_ctrl_file(void) "" }; #endif - AssertNotNull(file1=fopen("./certs/ca-cert.pem", "rb")); - - AssertNotNull(cert1 = wolfSSL_PEM_read_X509(file1, NULL, NULL, NULL)); - fclose(file1); + ExpectTrue((file1 = XFOPEN("./certs/ca-cert.pem", "rb")) != XBADFILE); + ExpectNotNull(cert1 = wolfSSL_PEM_read_X509(file1, NULL, NULL, NULL)); + if (file1 != XBADFILE) + XFCLOSE(file1); - AssertNotNull(ctx = X509_STORE_CTX_new()); - AssertNotNull((str = wolfSSL_X509_STORE_new())); - AssertNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); - AssertIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, caCertFile, + ExpectNotNull(ctx = X509_STORE_CTX_new()); + ExpectNotNull((str = wolfSSL_X509_STORE_new())); + ExpectNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); + ExpectIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, caCertFile, SSL_FILETYPE_PEM,NULL), 1); - AssertNotNull(sk = wolfSSL_CertManagerGetCerts(str->cm)); - AssertIntEQ((cert_count = sk_X509_num(sk)), 1); + ExpectNotNull(sk = wolfSSL_CertManagerGetCerts(str->cm)); + ExpectIntEQ((cert_count = sk_X509_num(sk)), 1); /* check if CA cert is loaded into the store */ for (i = 0; i < cert_count; i++) { x509Ca = sk_X509_value(sk, i); - AssertIntEQ(0, wolfSSL_X509_cmp(x509Ca, cert1)); + ExpectIntEQ(0, wolfSSL_X509_cmp(x509Ca, cert1)); } - AssertNotNull((x509Svr = + ExpectNotNull((x509Svr = wolfSSL_X509_load_certificate_file(svrCertFile, SSL_FILETYPE_PEM))); - AssertIntEQ(X509_STORE_CTX_init(ctx, str, x509Svr, NULL), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_CTX_init(ctx, str, x509Svr, NULL), SSL_SUCCESS); - AssertNull(X509_STORE_CTX_get0_current_issuer(NULL)); + ExpectNull(X509_STORE_CTX_get0_current_issuer(NULL)); issuer = X509_STORE_CTX_get0_current_issuer(ctx); - AssertNotNull(issuer); + ExpectNotNull(issuer); caName = X509_get_subject_name(x509Ca); - AssertNotNull(caName); + ExpectNotNull(caName); issuerName = X509_get_subject_name(issuer); - AssertNotNull(issuerName); + ExpectNotNull(issuerName); cmp = X509_NAME_cmp(caName, issuerName); - AssertIntEQ(cmp, 0); + ExpectIntEQ(cmp, 0); /* load der format */ X509_free(issuer); + issuer = NULL; X509_STORE_CTX_free(ctx); + ctx = NULL; X509_STORE_free(str); + str = NULL; sk_X509_pop_free(sk, NULL); + sk = NULL; X509_free(x509Svr); + x509Svr = NULL; - AssertNotNull((str = wolfSSL_X509_STORE_new())); - AssertNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); - AssertIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, der, + ExpectNotNull((str = wolfSSL_X509_STORE_new())); + ExpectNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); + ExpectIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, der, SSL_FILETYPE_ASN1,NULL), 1); - AssertNotNull(sk = wolfSSL_CertManagerGetCerts(str->cm)); - AssertIntEQ((cert_count = sk_X509_num(sk)), 1); + ExpectNotNull(sk = wolfSSL_CertManagerGetCerts(str->cm)); + ExpectIntEQ((cert_count = sk_X509_num(sk)), 1); /* check if CA cert is loaded into the store */ for (i = 0; i < cert_count; i++) { x509Ca = sk_X509_value(sk, i); - AssertIntEQ(0, wolfSSL_X509_cmp(x509Ca, cert1)); + ExpectIntEQ(0, wolfSSL_X509_cmp(x509Ca, cert1)); } X509_STORE_free(str); + str = NULL; sk_X509_pop_free(sk, NULL); + sk = NULL; X509_free(cert1); + cert1 = NULL; #ifdef HAVE_CRL - AssertNotNull(str = wolfSSL_X509_STORE_new()); - AssertNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); - AssertIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, caCertFile, + ExpectNotNull(str = wolfSSL_X509_STORE_new()); + ExpectNotNull(lookup = X509_STORE_add_lookup(str, X509_LOOKUP_file())); + ExpectIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, caCertFile, SSL_FILETYPE_PEM,NULL), 1); - AssertIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, + ExpectIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, "certs/server-revoked-cert.pem", SSL_FILETYPE_PEM,NULL), 1); if (str) { - AssertIntEQ(wolfSSL_CertManagerVerify(str->cm, svrCertFile, + ExpectIntEQ(wolfSSL_CertManagerVerify(str->cm, svrCertFile, WOLFSSL_FILETYPE_PEM), 1); /* since store hasn't yet known the revoked cert*/ - AssertIntEQ(wolfSSL_CertManagerVerify(str->cm, + ExpectIntEQ(wolfSSL_CertManagerVerify(str->cm, "certs/server-revoked-cert.pem", WOLFSSL_FILETYPE_PEM), 1); } for (i = 0; pem[i][0] != '\0'; i++) { - AssertIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, pem[i], + ExpectIntEQ(X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, pem[i], SSL_FILETYPE_PEM, NULL), 1); } if (str) { /* since store knows crl list */ - AssertIntEQ(wolfSSL_CertManagerVerify(str->cm, + ExpectIntEQ(wolfSSL_CertManagerVerify(str->cm, "certs/server-revoked-cert.pem", WOLFSSL_FILETYPE_PEM ), CRL_CERT_REVOKED); } - AssertIntEQ(X509_LOOKUP_ctrl(NULL, 0, NULL, 0, NULL), 0); + ExpectIntEQ(X509_LOOKUP_ctrl(NULL, 0, NULL, 0, NULL), 0); X509_STORE_free(str); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -38370,9 +38387,8 @@ static int test_wolfSSL_X509_STORE_CTX_trusted_stack_cleanup(void) #if defined(OPENSSL_EXTRA) X509_STORE_CTX_cleanup(NULL); X509_STORE_CTX_trusted_stack(NULL, NULL); - AssertTrue(1); /* to confirm previous call gives no harm */ - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif return res; } @@ -38381,39 +38397,33 @@ static int test_wolfSSL_X509_STORE_CTX_get0_current_issuer(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_RSA) - #ifdef WOLFSSL_SIGNER_DER_CERT - int cmp; - #endif - X509_STORE_CTX* ctx; - X509_STORE* str; - X509* x509Ca; - X509* x509Svr; - X509* issuer; - X509_NAME* caName; - X509_NAME* issuerName; - - AssertNotNull(ctx = X509_STORE_CTX_new()); - AssertNotNull((str = wolfSSL_X509_STORE_new())); - AssertNotNull((x509Ca = + EXPECT_DECLS; + X509_STORE_CTX* ctx = NULL; + X509_STORE* str = NULL; + X509* x509Ca = NULL; + X509* x509Svr = NULL; + X509* issuer = NULL; + X509_NAME* caName = NULL; + X509_NAME* issuerName = NULL; + + ExpectNotNull(ctx = X509_STORE_CTX_new()); + ExpectNotNull((str = wolfSSL_X509_STORE_new())); + ExpectNotNull((x509Ca = wolfSSL_X509_load_certificate_file(caCertFile, SSL_FILETYPE_PEM))); - AssertIntEQ(X509_STORE_add_cert(str, x509Ca), SSL_SUCCESS); - AssertNotNull((x509Svr = + ExpectIntEQ(X509_STORE_add_cert(str, x509Ca), SSL_SUCCESS); + ExpectNotNull((x509Svr = wolfSSL_X509_load_certificate_file(svrCertFile, SSL_FILETYPE_PEM))); - AssertIntEQ(X509_STORE_CTX_init(ctx, str, x509Svr, NULL), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_CTX_init(ctx, str, x509Svr, NULL), SSL_SUCCESS); - AssertNull(X509_STORE_CTX_get0_current_issuer(NULL)); - issuer = X509_STORE_CTX_get0_current_issuer(ctx); - AssertNotNull(issuer); + ExpectNull(X509_STORE_CTX_get0_current_issuer(NULL)); + ExpectNotNull(issuer = X509_STORE_CTX_get0_current_issuer(ctx)); - caName = X509_get_subject_name(x509Ca); - AssertNotNull(caName); - issuerName = X509_get_subject_name(issuer); - AssertNotNull(issuerName); - #ifdef WOLFSSL_SIGNER_DER_CERT - cmp = X509_NAME_cmp(caName, issuerName); - AssertIntEQ(cmp, 0); - #endif + ExpectNotNull(caName = X509_get_subject_name(x509Ca)); + ExpectNotNull(issuerName = X509_get_subject_name(issuer)); +#ifdef WOLFSSL_SIGNER_DER_CERT + ExpectIntEQ(X509_NAME_cmp(caName, issuerName), 0); +#endif X509_free(issuer); X509_STORE_CTX_free(ctx); @@ -38421,7 +38431,7 @@ static int test_wolfSSL_X509_STORE_CTX_get0_current_issuer(void) X509_STORE_free(str); X509_free(x509Ca); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -38508,114 +38518,132 @@ static int test_wolfSSL_X509_STORE_CTX(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) - - X509_STORE_CTX* ctx; - X509_STORE* str; - X509* x509; + EXPECT_DECLS; + X509_STORE_CTX* ctx = NULL; + X509_STORE* str = NULL; + X509* x509 = NULL; #ifdef OPENSSL_ALL - X509* x5092; - STACK_OF(X509) *sk, *sk2, *sk3; + X509* x5092 = NULL; + STACK_OF(X509) *sk = NULL; + STACK_OF(X509) *sk2 = NULL; + STACK_OF(X509) *sk3 = NULL; #endif - AssertNotNull(ctx = X509_STORE_CTX_new()); - AssertNotNull((str = wolfSSL_X509_STORE_new())); - AssertNotNull((x509 = + ExpectNotNull(ctx = X509_STORE_CTX_new()); + ExpectNotNull((str = wolfSSL_X509_STORE_new())); + ExpectNotNull((x509 = wolfSSL_X509_load_certificate_file(svrCertFile, SSL_FILETYPE_PEM))); - AssertIntEQ(X509_STORE_add_cert(str, x509), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_add_cert(str, x509), SSL_SUCCESS); #ifdef OPENSSL_ALL /* sk_X509_new only in OPENSSL_ALL */ sk = sk_X509_new_null(); - AssertNotNull(sk); - AssertIntEQ(X509_STORE_CTX_init(ctx, str, x509, sk), SSL_SUCCESS); + ExpectNotNull(sk); + ExpectIntEQ(X509_STORE_CTX_init(ctx, str, x509, sk), SSL_SUCCESS); #else - AssertIntEQ(X509_STORE_CTX_init(ctx, str, x509, NULL), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_CTX_init(ctx, str, x509, NULL), SSL_SUCCESS); #endif - AssertIntEQ(SSL_get_ex_data_X509_STORE_CTX_idx(), 0); + ExpectIntEQ(SSL_get_ex_data_X509_STORE_CTX_idx(), 0); X509_STORE_CTX_set_error(ctx, -5); X509_STORE_CTX_set_error(NULL, -5); X509_STORE_CTX_free(ctx); + ctx = NULL; #ifdef OPENSSL_ALL sk_X509_pop_free(sk, NULL); + sk = NULL; #endif X509_STORE_free(str); + str = NULL; X509_free(x509); + x509 = NULL; - AssertNotNull(ctx = X509_STORE_CTX_new()); + ExpectNotNull(ctx = X509_STORE_CTX_new()); X509_STORE_CTX_set_verify_cb(ctx, verify_cb); X509_STORE_CTX_free(ctx); + ctx = NULL; #ifdef OPENSSL_ALL /* test X509_STORE_CTX_get(1)_chain */ - AssertNotNull((x509 = X509_load_certificate_file(svrCertFile, + ExpectNotNull((x509 = X509_load_certificate_file(svrCertFile, SSL_FILETYPE_PEM))); - AssertNotNull((x5092 = X509_load_certificate_file(cliCertFile, + ExpectNotNull((x5092 = X509_load_certificate_file(cliCertFile, SSL_FILETYPE_PEM))); - AssertNotNull((sk = sk_X509_new_null())); - AssertIntEQ(sk_X509_push(sk, x509), 1); - AssertNotNull((str = X509_STORE_new())); - AssertNotNull((ctx = X509_STORE_CTX_new())); - AssertIntEQ(X509_STORE_CTX_init(ctx, str, x5092, sk), 1); - AssertNull((sk2 = X509_STORE_CTX_get_chain(NULL))); - AssertNotNull((sk2 = X509_STORE_CTX_get_chain(ctx))); - AssertIntEQ(sk_num(sk2), 1); /* sanity, make sure chain has 1 cert */ - AssertNull((sk3 = X509_STORE_CTX_get1_chain(NULL))); - AssertNotNull((sk3 = X509_STORE_CTX_get1_chain(ctx))); - AssertIntEQ(sk_num(sk3), 1); /* sanity, make sure chain has 1 cert */ + ExpectNotNull((sk = sk_X509_new_null())); + ExpectIntEQ(sk_X509_push(sk, x509), 1); + if (EXPECT_FAIL()) { + X509_free(x509); + x509 = NULL; + } + ExpectNotNull((str = X509_STORE_new())); + ExpectNotNull((ctx = X509_STORE_CTX_new())); + ExpectIntEQ(X509_STORE_CTX_init(ctx, str, x5092, sk), 1); + ExpectNull((sk2 = X509_STORE_CTX_get_chain(NULL))); + ExpectNotNull((sk2 = X509_STORE_CTX_get_chain(ctx))); + ExpectIntEQ(sk_num(sk2), 1); /* sanity, make sure chain has 1 cert */ + ExpectNull((sk3 = X509_STORE_CTX_get1_chain(NULL))); + ExpectNotNull((sk3 = X509_STORE_CTX_get1_chain(ctx))); + ExpectIntEQ(sk_num(sk3), 1); /* sanity, make sure chain has 1 cert */ X509_STORE_CTX_free(ctx); + ctx = NULL; X509_STORE_free(str); + str = NULL; /* CTX certs not freed yet */ X509_free(x5092); + x5092 = NULL; sk_X509_pop_free(sk, NULL); + sk = NULL; /* sk3 is dup so free here */ sk_X509_pop_free(sk3, NULL); + sk3 = NULL; #endif /* test X509_STORE_CTX_get/set_ex_data */ { int i = 0, tmpData = 5; void* tmpDataRet; - AssertNotNull(ctx = X509_STORE_CTX_new()); + ExpectNotNull(ctx = X509_STORE_CTX_new()); #ifdef HAVE_EX_DATA for (i = 0; i < MAX_EX_DATA; i++) { - AssertIntEQ(X509_STORE_CTX_set_ex_data(ctx, i, &tmpData), + ExpectIntEQ(X509_STORE_CTX_set_ex_data(ctx, i, &tmpData), WOLFSSL_SUCCESS); tmpDataRet = (int*)X509_STORE_CTX_get_ex_data(ctx, i); - AssertNotNull(tmpDataRet); - AssertIntEQ(tmpData, *(int*)tmpDataRet); + ExpectNotNull(tmpDataRet); + ExpectIntEQ(tmpData, *(int*)tmpDataRet); } #else - AssertIntEQ(X509_STORE_CTX_set_ex_data(ctx, i, &tmpData), + ExpectIntEQ(X509_STORE_CTX_set_ex_data(ctx, i, &tmpData), WOLFSSL_FAILURE); tmpDataRet = (int*)X509_STORE_CTX_get_ex_data(ctx, i); - AssertNull(tmpDataRet); + ExpectNull(tmpDataRet); #endif X509_STORE_CTX_free(ctx); + ctx = NULL; } /* test X509_STORE_get/set_ex_data */ { int i = 0, tmpData = 99; void* tmpDataRet; - AssertNotNull(str = X509_STORE_new()); + ExpectNotNull(str = X509_STORE_new()); #ifdef HAVE_EX_DATA for (i = 0; i < MAX_EX_DATA; i++) { - AssertIntEQ(X509_STORE_set_ex_data(str, i, &tmpData), + ExpectIntEQ(X509_STORE_set_ex_data(str, i, &tmpData), WOLFSSL_SUCCESS); tmpDataRet = (int*)X509_STORE_get_ex_data(str, i); - AssertNotNull(tmpDataRet); - AssertIntEQ(tmpData, *(int*)tmpDataRet); + ExpectNotNull(tmpDataRet); + ExpectIntEQ(tmpData, *(int*)tmpDataRet); } #else - AssertIntEQ(X509_STORE_set_ex_data(str, i, &tmpData), + ExpectIntEQ(X509_STORE_set_ex_data(str, i, &tmpData), WOLFSSL_FAILURE); tmpDataRet = (int*)X509_STORE_get_ex_data(str, i); - AssertNull(tmpDataRet); + ExpectNull(tmpDataRet); #endif X509_STORE_free(str); + str = NULL; } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ @@ -38625,87 +38653,90 @@ static int test_wolfSSL_X509_STORE_CTX(void) static int test_wolfSSL_X509_STORE_set_flags(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && !defined(NO_RSA) - - X509_STORE* store; - X509* x509; +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ + !defined(NO_FILESYSTEM) && !defined(NO_RSA) + EXPECT_DECLS; + X509_STORE* store = NULL; + X509* x509 = NULL; - AssertNotNull((store = wolfSSL_X509_STORE_new())); - AssertNotNull((x509 = - wolfSSL_X509_load_certificate_file(svrCertFile, WOLFSSL_FILETYPE_PEM))); - AssertIntEQ(X509_STORE_add_cert(store, x509), WOLFSSL_SUCCESS); + ExpectNotNull((store = wolfSSL_X509_STORE_new())); + ExpectNotNull((x509 = wolfSSL_X509_load_certificate_file(svrCertFile, + WOLFSSL_FILETYPE_PEM))); + ExpectIntEQ(X509_STORE_add_cert(store, x509), WOLFSSL_SUCCESS); #ifdef HAVE_CRL - AssertIntEQ(X509_STORE_set_flags(store, WOLFSSL_CRL_CHECKALL), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_set_flags(store, WOLFSSL_CRL_CHECKALL), + WOLFSSL_SUCCESS); #else - AssertIntEQ(X509_STORE_set_flags(store, WOLFSSL_CRL_CHECKALL), + ExpectIntEQ(X509_STORE_set_flags(store, WOLFSSL_CRL_CHECKALL), NOT_COMPILED_IN); #endif wolfSSL_X509_free(x509); wolfSSL_X509_STORE_free(store); - res = TEST_RES_CHECK(1); - #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ + res = EXPECT_RESULT(); +#endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && + * !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ return res; } static int test_wolfSSL_X509_LOOKUP_load_file(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && defined(HAVE_CRL) && \ - !defined(NO_FILESYSTEM) && !defined(NO_RSA) && \ - (!defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)) - WOLFSSL_X509_STORE* store; - WOLFSSL_X509_LOOKUP* lookup; +#if defined(OPENSSL_EXTRA) && defined(HAVE_CRL) && \ + !defined(NO_FILESYSTEM) && !defined(NO_RSA) && \ + (!defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)) + EXPECT_DECLS; + WOLFSSL_X509_STORE* store = NULL; + WOLFSSL_X509_LOOKUP* lookup = NULL; - AssertNotNull(store = wolfSSL_X509_STORE_new()); - AssertNotNull(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())); - AssertIntEQ(wolfSSL_X509_LOOKUP_load_file(lookup, "certs/client-ca.pem", - X509_FILETYPE_PEM), 1); - AssertIntEQ(wolfSSL_X509_LOOKUP_load_file(lookup, "certs/crl/crl2.pem", - X509_FILETYPE_PEM), 1); + ExpectNotNull(store = wolfSSL_X509_STORE_new()); + ExpectNotNull(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())); + ExpectIntEQ(wolfSSL_X509_LOOKUP_load_file(lookup, "certs/client-ca.pem", + X509_FILETYPE_PEM), 1); + ExpectIntEQ(wolfSSL_X509_LOOKUP_load_file(lookup, "certs/crl/crl2.pem", + X509_FILETYPE_PEM), 1); - if (store) { - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, cliCertFile, - WOLFSSL_FILETYPE_PEM), 1); - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, svrCertFile, - WOLFSSL_FILETYPE_PEM), ASN_NO_SIGNER_E); + if (store != NULL) { + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, cliCertFile, + WOLFSSL_FILETYPE_PEM), 1); + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, svrCertFile, + WOLFSSL_FILETYPE_PEM), ASN_NO_SIGNER_E); } - AssertIntEQ(wolfSSL_X509_LOOKUP_load_file(lookup, "certs/ca-cert.pem", - X509_FILETYPE_PEM), 1); - if (store) { - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, svrCertFile, - WOLFSSL_FILETYPE_PEM), 1); + ExpectIntEQ(wolfSSL_X509_LOOKUP_load_file(lookup, "certs/ca-cert.pem", + X509_FILETYPE_PEM), 1); + if (store != NULL) { + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, svrCertFile, + WOLFSSL_FILETYPE_PEM), 1); } wolfSSL_X509_STORE_free(store); - res = TEST_RES_CHECK(1); - #endif /* defined(OPENSSL_EXTRA) && defined(HAVE_CRL) && \ - !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ + res = EXPECT_RESULT(); +#endif /* defined(OPENSSL_EXTRA) && defined(HAVE_CRL) && + * !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ return res; } static int test_wolfSSL_X509_STORE_CTX_set_time(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) - WOLFSSL_X509_STORE_CTX* ctx; +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; + WOLFSSL_X509_STORE_CTX* ctx = NULL; time_t c_time; - AssertNotNull(ctx = wolfSSL_X509_STORE_CTX_new()); + ExpectNotNull(ctx = wolfSSL_X509_STORE_CTX_new()); c_time = 365*24*60*60; wolfSSL_X509_STORE_CTX_set_time(ctx, 0, c_time); - AssertTrue( - (ctx->param->flags & WOLFSSL_USE_CHECK_TIME) == WOLFSSL_USE_CHECK_TIME); - AssertTrue(ctx->param->check_time == c_time); + ExpectTrue((ctx->param->flags & WOLFSSL_USE_CHECK_TIME) == + WOLFSSL_USE_CHECK_TIME); + ExpectTrue(ctx->param->check_time == c_time); wolfSSL_X509_STORE_CTX_free(ctx); - res = TEST_RES_CHECK(1); - #endif /* OPENSSL_EXTRA */ + res = EXPECT_RESULT(); +#endif /* OPENSSL_EXTRA */ return res; } @@ -38714,49 +38745,48 @@ static int test_wolfSSL_CTX_get0_set1_param(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - int ret; - SSL_CTX* ctx; - WOLFSSL_X509_VERIFY_PARAM* pParam; - WOLFSSL_X509_VERIFY_PARAM* pvpm; + EXPECT_DECLS; + SSL_CTX* ctx = NULL; + WOLFSSL_X509_VERIFY_PARAM* pParam = NULL; + WOLFSSL_X509_VERIFY_PARAM* pvpm = NULL; char testIPv4[] = "127.0.0.1"; char testhostName[] = "foo.hoge.com"; - #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); - #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); - #endif +#ifndef NO_WOLFSSL_SERVER + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); +#else + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); +#endif - AssertNull(SSL_CTX_get0_param(NULL)); - AssertNotNull(pParam = SSL_CTX_get0_param(ctx)); + ExpectNull(SSL_CTX_get0_param(NULL)); + ExpectNotNull(pParam = SSL_CTX_get0_param(ctx)); - pvpm = (WOLFSSL_X509_VERIFY_PARAM *)XMALLOC( - sizeof(WOLFSSL_X509_VERIFY_PARAM), NULL, DYNAMIC_TYPE_OPENSSL); - AssertNotNull(pvpm); - XMEMSET(pvpm, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); + ExpectNotNull(pvpm = (WOLFSSL_X509_VERIFY_PARAM *)XMALLOC( + sizeof(WOLFSSL_X509_VERIFY_PARAM), NULL, DYNAMIC_TYPE_OPENSSL)); + ExpectNotNull(XMEMSET(pvpm, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM))); - wolfSSL_X509_VERIFY_PARAM_set1_host(pvpm, testhostName, - (int)XSTRLEN(testhostName)); - wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(pvpm, testIPv4); + ExpectIntEQ(wolfSSL_X509_VERIFY_PARAM_set1_host(pvpm, testhostName, + (int)XSTRLEN(testhostName)), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(pvpm, testIPv4), + WOLFSSL_SUCCESS); wolfSSL_X509_VERIFY_PARAM_set_hostflags(pvpm, 0x01); - ret = SSL_CTX_set1_param(ctx, pvpm); - AssertIntEQ(1, ret); - AssertIntEQ(0, XSTRNCMP(pParam->hostName, testhostName, - (int)XSTRLEN(testhostName))); - AssertIntEQ(0x01, pParam->hostFlags); - AssertIntEQ(0, XSTRNCMP(pParam->ipasc, testIPv4, WOLFSSL_MAX_IPSTR)); + ExpectIntEQ(SSL_CTX_set1_param(ctx, pvpm), 1); + ExpectIntEQ(0, XSTRNCMP(pParam->hostName, testhostName, + (int)XSTRLEN(testhostName))); + ExpectIntEQ(0x01, pParam->hostFlags); + ExpectIntEQ(0, XSTRNCMP(pParam->ipasc, testIPv4, WOLFSSL_MAX_IPSTR)); /* test for incorrect patameter */ - AssertIntEQ(1,SSL_CTX_set1_param(ctx, NULL)); - AssertIntEQ(1,SSL_CTX_set1_param(NULL, pvpm)); - AssertIntEQ(1,SSL_CTX_set1_param(NULL, NULL)); + ExpectIntEQ(1,SSL_CTX_set1_param(ctx, NULL)); + ExpectIntEQ(1,SSL_CTX_set1_param(NULL, pvpm)); + ExpectIntEQ(1,SSL_CTX_set1_param(NULL, NULL)); SSL_CTX_free(ctx); XFREE(pvpm, NULL, DYNAMIC_TYPE_OPENSSL); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* OPENSSL_EXTRA && !defined(NO_RSA)*/ return res; @@ -38767,27 +38797,26 @@ static int test_wolfSSL_get0_param(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_RSA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - SSL_CTX* ctx; - SSL* ssl; - WOLFSSL_X509_VERIFY_PARAM* pParam; - - #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); - #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); - #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); + EXPECT_DECLS; + SSL_CTX* ctx = NULL; + SSL* ssl = NULL; - pParam = SSL_get0_param(ssl); +#ifndef NO_WOLFSSL_SERVER + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); +#else + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); +#endif + ExpectTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, + SSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); + ExpectNotNull(ssl = SSL_new(ctx)); - (void)pParam; + ExpectNotNull(SSL_get0_param(ssl)); SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* OPENSSL_EXTRA && !defined(NO_RSA)*/ return res; @@ -38797,26 +38826,27 @@ static int test_wolfSSL_X509_VERIFY_PARAM_set1_host(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) + EXPECT_DECLS; const char host[] = "www.example.com"; - WOLFSSL_X509_VERIFY_PARAM* pParam; - - AssertNotNull(pParam = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC( - sizeof(WOLFSSL_X509_VERIFY_PARAM), - HEAP_HINT, DYNAMIC_TYPE_OPENSSL)); + WOLFSSL_X509_VERIFY_PARAM* pParam = NULL; - XMEMSET(pParam, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); + ExpectNotNull(pParam = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC( + sizeof(WOLFSSL_X509_VERIFY_PARAM), HEAP_HINT, DYNAMIC_TYPE_OPENSSL)); + if (pParam != NULL) { + XMEMSET(pParam, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); - X509_VERIFY_PARAM_set1_host(pParam, host, sizeof(host)); + X509_VERIFY_PARAM_set1_host(pParam, host, sizeof(host)); - AssertIntEQ(XMEMCMP(pParam->hostName, host, sizeof(host)), 0); + ExpectIntEQ(XMEMCMP(pParam->hostName, host, sizeof(host)), 0); - XMEMSET(pParam, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); + XMEMSET(pParam, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); - AssertIntNE(XMEMCMP(pParam->hostName, host, sizeof(host)), 0); + ExpectIntNE(XMEMCMP(pParam->hostName, host, sizeof(host)), 0); - XFREE(pParam, HEAP_HINT, DYNAMIC_TYPE_OPENSSL); + XFREE(pParam, HEAP_HINT, DYNAMIC_TYPE_OPENSSL); + } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -38826,43 +38856,45 @@ static int test_wolfSSL_set1_host(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_RSA) #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + EXPECT_DECLS; const char host[] = "www.test_wolfSSL_set1_host.com"; const char emptyStr[] = ""; - SSL_CTX* ctx; - SSL* ssl; - WOLFSSL_X509_VERIFY_PARAM* pParam; + SSL_CTX* ctx = NULL; + SSL* ssl = NULL; + WOLFSSL_X509_VERIFY_PARAM* pParam = NULL; - #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); - #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); - #endif - AssertTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); +#ifndef NO_WOLFSSL_SERVER + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); +#else + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); +#endif + ExpectTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, + SSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); + ExpectNotNull(ssl = SSL_new(ctx)); pParam = SSL_get0_param(ssl); /* we should get back host string */ - SSL_set1_host(ssl, host); - AssertIntEQ(XMEMCMP(pParam->hostName, host, sizeof(host)), 0); + ExpectIntEQ(SSL_set1_host(ssl, host), WOLFSSL_SUCCESS); + ExpectIntEQ(XMEMCMP(pParam->hostName, host, sizeof(host)), 0); /* we should get back empty string */ - SSL_set1_host(ssl, emptyStr); - AssertIntEQ(XMEMCMP(pParam->hostName, emptyStr, sizeof(emptyStr)), 0); + ExpectIntEQ(SSL_set1_host(ssl, emptyStr), WOLFSSL_SUCCESS); + ExpectIntEQ(XMEMCMP(pParam->hostName, emptyStr, sizeof(emptyStr)), 0); /* we should get back host string */ - SSL_set1_host(ssl, host); - AssertIntEQ(XMEMCMP(pParam->hostName, host, sizeof(host)), 0); + ExpectIntEQ(SSL_set1_host(ssl, host), WOLFSSL_SUCCESS); + ExpectIntEQ(XMEMCMP(pParam->hostName, host, sizeof(host)), 0); /* we should get back empty string */ - SSL_set1_host(ssl, NULL); - AssertIntEQ(XMEMCMP(pParam->hostName, emptyStr, sizeof(emptyStr)), 0); + ExpectIntEQ(SSL_set1_host(ssl, NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(XMEMCMP(pParam->hostName, emptyStr, sizeof(emptyStr)), 0); SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ #endif /* OPENSSL_EXTRA */ return res; @@ -38872,23 +38904,24 @@ static int test_wolfSSL_X509_VERIFY_PARAM_set1_ip(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) + EXPECT_DECLS; unsigned char buf[16] = {0}; - WOLFSSL_X509_VERIFY_PARAM* param; + WOLFSSL_X509_VERIFY_PARAM* param = NULL; - AssertNotNull(param = X509_VERIFY_PARAM_new()); + ExpectNotNull(param = X509_VERIFY_PARAM_new()); /* test 127.0.0.1 */ buf[0] =0x7f; buf[1] = 0; buf[2] = 0; buf[3] = 1; - AssertIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 4), SSL_SUCCESS); - AssertIntEQ(XSTRNCMP(param->ipasc, "127.0.0.1", sizeof(param->ipasc)), 0); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 4), SSL_SUCCESS); + ExpectIntEQ(XSTRNCMP(param->ipasc, "127.0.0.1", sizeof(param->ipasc)), 0); /* test 2001:db8:3333:4444:5555:6666:7777:8888 */ buf[0]=32;buf[1]=1;buf[2]=13;buf[3]=184; buf[4]=51;buf[5]=51;buf[6]=68;buf[7]=68; buf[8]=85;buf[9]=85;buf[10]=102;buf[11]=102; buf[12]=119;buf[13]=119;buf[14]=136;buf[15]=136; - AssertIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); - AssertIntEQ(XSTRNCMP(param->ipasc, + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); + ExpectIntEQ(XSTRNCMP(param->ipasc, "2001:db8:3333:4444:5555:6666:7777:8888", sizeof(param->ipasc)), 0); /* test 2001:db8:: */ @@ -38896,16 +38929,16 @@ static int test_wolfSSL_X509_VERIFY_PARAM_set1_ip(void) buf[4]=0;buf[5]=0;buf[6]=0;buf[7]=0; buf[8]=0;buf[9]=0;buf[10]=0;buf[11]=0; buf[12]=0;buf[13]=0;buf[14]=0;buf[15]=0; - AssertIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); - AssertIntEQ(XSTRNCMP(param->ipasc, "2001:db8::", sizeof(param->ipasc)), 0); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); + ExpectIntEQ(XSTRNCMP(param->ipasc, "2001:db8::", sizeof(param->ipasc)), 0); /* test ::1234:5678 */ buf[0]=0;buf[1]=0;buf[2]=0;buf[3]=0; buf[4]=0;buf[5]=0;buf[6]=0;buf[7]=0; buf[8]=0;buf[9]=0;buf[10]=0;buf[11]=0; buf[12]=18;buf[13]=52;buf[14]=86;buf[15]=120; - AssertIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); - AssertIntEQ(XSTRNCMP(param->ipasc, "::1234:5678", sizeof(param->ipasc)), 0); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); + ExpectIntEQ(XSTRNCMP(param->ipasc, "::1234:5678", sizeof(param->ipasc)), 0); /* test 2001:db8::1234:5678 */ @@ -38913,8 +38946,8 @@ static int test_wolfSSL_X509_VERIFY_PARAM_set1_ip(void) buf[4]=0;buf[5]=0;buf[6]=0;buf[7]=0; buf[8]=0;buf[9]=0;buf[10]=0;buf[11]=0; buf[12]=18;buf[13]=52;buf[14]=86;buf[15]=120; - AssertIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); - AssertIntEQ(XSTRNCMP(param->ipasc, "2001:db8::1234:5678", + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); + ExpectIntEQ(XSTRNCMP(param->ipasc, "2001:db8::1234:5678", sizeof(param->ipasc)), 0); /* test 2001:0db8:0001:0000:0000:0ab9:c0a8:0102*/ @@ -38923,13 +38956,13 @@ static int test_wolfSSL_X509_VERIFY_PARAM_set1_ip(void) buf[4]=0;buf[5]=1;buf[6]=0;buf[7]=0; buf[8]=0;buf[9]=0;buf[10]=10;buf[11]=185; buf[12]=192;buf[13]=168;buf[14]=1;buf[15]=2; - AssertIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); - AssertIntEQ(XSTRNCMP(param->ipasc, "2001:db8:1::ab9:c0a8:102", + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip(param, &buf[0], 16), SSL_SUCCESS); + ExpectIntEQ(XSTRNCMP(param->ipasc, "2001:db8:1::ab9:c0a8:102", sizeof(param->ipasc)), 0); XFREE(param, HEAP_HINT, DYNAMIC_TYPE_OPENSSL); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -38937,27 +38970,28 @@ static int test_wolfSSL_X509_VERIFY_PARAM_set1_ip(void) static int test_wolfSSL_X509_STORE_CTX_get0_store(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) - X509_STORE* store; - X509_STORE_CTX* ctx; - X509_STORE_CTX* ctx_no_init; +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; + X509_STORE* store = NULL; + X509_STORE_CTX* ctx = NULL; + X509_STORE_CTX* ctx_no_init = NULL; - AssertNotNull((store = X509_STORE_new())); - AssertNotNull(ctx = X509_STORE_CTX_new()); - AssertNotNull(ctx_no_init = X509_STORE_CTX_new()); - AssertIntEQ(X509_STORE_CTX_init(ctx, store, NULL, NULL), SSL_SUCCESS); + ExpectNotNull((store = X509_STORE_new())); + ExpectNotNull(ctx = X509_STORE_CTX_new()); + ExpectNotNull(ctx_no_init = X509_STORE_CTX_new()); + ExpectIntEQ(X509_STORE_CTX_init(ctx, store, NULL, NULL), SSL_SUCCESS); - AssertNull(X509_STORE_CTX_get0_store(NULL)); + ExpectNull(X509_STORE_CTX_get0_store(NULL)); /* should return NULL if ctx has not bee initialized */ - AssertNull(X509_STORE_CTX_get0_store(ctx_no_init)); - AssertNotNull(X509_STORE_CTX_get0_store(ctx)); + ExpectNull(X509_STORE_CTX_get0_store(ctx_no_init)); + ExpectNotNull(X509_STORE_CTX_get0_store(ctx)); wolfSSL_X509_STORE_CTX_free(ctx); wolfSSL_X509_STORE_CTX_free(ctx_no_init); X509_STORE_free(store); - res = TEST_RES_CHECK(1); - #endif /* OPENSSL_EXTRA */ + res = EXPECT_RESULT(); +#endif /* OPENSSL_EXTRA */ return res; } @@ -38966,47 +39000,56 @@ static int test_wolfSSL_CTX_set_client_CA_list(void) int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_RSA) && !defined(NO_CERTS) && \ !defined(NO_WOLFSSL_CLIENT) && !defined(NO_BIO) - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; X509_NAME* name = NULL; STACK_OF(X509_NAME)* names = NULL; STACK_OF(X509_NAME)* ca_list = NULL; - int i, names_len; + int names_len = 0; + int i; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); /* Send two X501 names in cert request */ names = SSL_load_client_CA_file(cliCertFile); - AssertNotNull(names); + ExpectNotNull(names); ca_list = SSL_load_client_CA_file(caCertFile); - AssertNotNull(ca_list); - AssertIntEQ(sk_X509_NAME_push(names, sk_X509_NAME_value(ca_list, 0)), 1); + ExpectNotNull(ca_list); + ExpectNotNull(name = sk_X509_NAME_value(ca_list, 0)); + ExpectIntEQ(sk_X509_NAME_push(names, name), 1); + if (EXPECT_FAIL()) { + wolfSSL_X509_NAME_free(name); + name = NULL; + } SSL_CTX_set_client_CA_list(ctx, names); /* This should only free the stack structure */ sk_X509_NAME_free(ca_list); - AssertNotNull(ca_list = SSL_CTX_get_client_CA_list(ctx)); - AssertIntEQ(sk_X509_NAME_num(ca_list), sk_X509_NAME_num(names)); + ca_list = NULL; + ExpectNotNull(ca_list = SSL_CTX_get_client_CA_list(ctx)); + ExpectIntEQ(sk_X509_NAME_num(ca_list), sk_X509_NAME_num(names)); - AssertIntGT((names_len = sk_X509_NAME_num(names)), 0); - for (i=0; iport, 0, 0, NULL); - AssertNotNull(ctx_client = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_load_verify_locations(ctx_client, caCertFile, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_certificate_file(ctx_client, cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_PrivateKey_file(ctx_client, cliKeyFile, SSL_FILETYPE_PEM)); - - AssertNotNull(ssl_client = wolfSSL_new(ctx_client)); - AssertIntEQ(wolfSSL_set_fd(ssl_client, sockfd), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_connect(ssl_client), WOLFSSL_SUCCESS); - - AssertNotNull(ca_list = SSL_get_client_CA_list(ssl_client)); + ExpectNotNull(ctx_client = + wolfSSL_CTX_new(wolfTLSv1_2_client_method())); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_load_verify_locations( + ctx_client, caCertFile, 0)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file( + ctx_client, cliCertFile, SSL_FILETYPE_PEM)); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_PrivateKey_file( + ctx_client, cliKeyFile, SSL_FILETYPE_PEM)); + + ExpectNotNull(ssl_client = wolfSSL_new(ctx_client)); + ExpectIntEQ(wolfSSL_set_fd(ssl_client, sockfd), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_connect(ssl_client), WOLFSSL_SUCCESS); + + ExpectNotNull(ca_list = SSL_get_client_CA_list(ssl_client)); /* We are expecting two cert names to be sent */ - AssertIntEQ(sk_X509_NAME_num(ca_list), 2); + ExpectIntEQ(sk_X509_NAME_num(ca_list), 2); - AssertNotNull(names = SSL_CTX_get_client_CA_list(ctx)); + ExpectNotNull(names = SSL_CTX_get_client_CA_list(ctx)); for (i=0; icallbacks; - WOLFSSL_CTX* ctx = wolfSSL_CTX_new(callbacks->method()); - WOLFSSL* ssl = NULL; - SOCKET_T sfd = 0; - SOCKET_T cfd = 0; - word16 port; - char msg[] = "I hear you fa shizzle!"; - int len = (int) XSTRLEN(msg); - char input[1024]; - int idx; - int ret, err = 0; - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - ((func_args*)args)->return_code = TEST_FAIL; - port = ((func_args*)args)->signal->port; - - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_load_verify_locations(ctx, cliCertFile, 0)); - - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, - WOLFSSL_FILETYPE_PEM)); - - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, - WOLFSSL_FILETYPE_PEM)); - - if (callbacks->ctx_ready) - callbacks->ctx_ready(ctx); - - ssl = wolfSSL_new(ctx); - tcp_accept(&sfd, &cfd, (func_args*)args, port, 0, 0, 0, 0, 1, NULL, NULL); - CloseSocket(sfd); - AssertIntEQ(WOLFSSL_SUCCESS, wolfSSL_set_fd(ssl, cfd)); - - if (callbacks->ssl_ready) - callbacks->ssl_ready(ssl); - - do { - err = 0; /* Reset error */ - ret = wolfSSL_accept(ssl); - if (ret != WOLFSSL_SUCCESS) { - err = wolfSSL_get_error(ssl, 0); - } - } while (ret != WOLFSSL_SUCCESS && err == WC_PENDING_E); - - if (ret != WOLFSSL_SUCCESS) { - char buff[WOLFSSL_MAX_ERROR_SZ]; - fprintf(stderr, "error = %d, %s\n", err, - wolfSSL_ERR_error_string(err, buff)); - } - else { - if (0 < (idx = wolfSSL_read(ssl, input, sizeof(input)-1))) { - input[idx] = 0; - fprintf(stderr, "Client message: %s\n", input); - } - - AssertIntEQ(len, wolfSSL_write(ssl, msg, len)); -#ifdef WOLFSSL_TIRTOS - Task_yield(); -#endif - ((func_args*)args)->return_code = TEST_SUCCESS; - } - - if (callbacks->on_result) - callbacks->on_result(ssl); - - wolfSSL_shutdown(ssl); - wolfSSL_free(ssl); - wolfSSL_CTX_free(ctx); - CloseSocket(cfd); - -#ifdef WOLFSSL_TIRTOS - fdCloseSession(Task_self()); -#endif -#ifndef WOLFSSL_TIRTOS - return 0; -#endif -} - static void keyLog_callback(const WOLFSSL* ssl, const char* line ) { @@ -39305,14 +39264,15 @@ static int test_wolfSSL_CTX_set_keylog_callback(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK) && \ !defined(NO_WOLFSSL_CLIENT) - SSL_CTX* ctx; + EXPECT_DECLS; + SSL_CTX* ctx = NULL; - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); SSL_CTX_set_keylog_callback(ctx, keyLog_callback ); SSL_CTX_free(ctx); SSL_CTX_set_keylog_callback(NULL, NULL); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK && !NO_WOLFSSL_CLIENT */ return res; } @@ -39321,20 +39281,31 @@ static int test_wolfSSL_CTX_get_keylog_callback(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK) && \ !defined(NO_WOLFSSL_CLIENT) - SSL_CTX* ctx; + EXPECT_DECLS; + SSL_CTX* ctx = NULL; - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); - AssertPtrEq(SSL_CTX_get_keylog_callback(ctx),NULL); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectPtrEq(SSL_CTX_get_keylog_callback(ctx),NULL); SSL_CTX_set_keylog_callback(ctx, keyLog_callback ); - AssertPtrEq(SSL_CTX_get_keylog_callback(ctx),keyLog_callback); + ExpectPtrEq(SSL_CTX_get_keylog_callback(ctx),keyLog_callback); SSL_CTX_set_keylog_callback(ctx, NULL ); - AssertPtrEq(SSL_CTX_get_keylog_callback(ctx),NULL); + ExpectPtrEq(SSL_CTX_get_keylog_callback(ctx),NULL); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK && !NO_WOLFSSL_CLIENT */ return res; } + +#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK) +static int test_wolfSSL_Tls12_Key_Logging_client_ctx_ready(WOLFSSL_CTX* ctx) +{ + /* set keylog callback */ + wolfSSL_CTX_set_keylog_callback(ctx, keyLog_callback); + return TEST_SUCCESS; +} +#endif + static int test_wolfSSL_Tls12_Key_Logging_test(void) { int res = TEST_SKIPPED; @@ -39342,105 +39313,60 @@ static int test_wolfSSL_Tls12_Key_Logging_test(void) /* This test is intended for checking whether keylog callback is called * in client during TLS handshake between the client and a server. */ + EXPECT_DECLS; + test_ssl_cbf server_cbf; + test_ssl_cbf client_cbf; + XFILE fp = XBADFILE; - tcp_ready ready; - func_args client_args; - func_args server_args; - THREAD_TYPE serverThread; - callback_functions server_cbf; - callback_functions client_cbf; - SOCKET_T sockfd = 0; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; - XFILE fp; - char msg[64] = "hello wolfssl!"; - char reply[1024]; - int msgSz = (int)XSTRLEN(msg); - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - InitTcpReady(&ready); - ready.port = 22222; - - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - XMEMSET(&server_cbf, 0, sizeof(callback_functions)); - XMEMSET(&client_cbf, 0, sizeof(callback_functions)); + XMEMSET(&server_cbf, 0, sizeof(test_ssl_cbf)); + XMEMSET(&client_cbf, 0, sizeof(test_ssl_cbf)); server_cbf.method = wolfTLSv1_2_server_method; - - server_args.callbacks = &server_cbf; - server_args.signal = &ready; + client_cbf.ctx_ready = &test_wolfSSL_Tls12_Key_Logging_client_ctx_ready; /* clean up keylog file */ - fp = XFOPEN("./MyKeyLog.txt", "w"); - XFCLOSE(fp); - - /* start server task */ - start_thread(server_task, &server_args, &serverThread); - wait_tcp_ready(&server_args); - - - /* run as a TLS1.2 client */ - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); - - tcp_connect(&sockfd, wolfSSLIP, server_args.signal->port, 0, 0, NULL); - - /* set keylog callback */ - wolfSSL_CTX_set_keylog_callback(ctx,keyLog_callback); - - /* get connected the server task */ - AssertNotNull(ssl = wolfSSL_new(ctx)); - AssertIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); - - - AssertIntEQ(wolfSSL_connect(ssl), WOLFSSL_SUCCESS); - - AssertIntEQ(wolfSSL_write(ssl, msg, msgSz), msgSz); - AssertIntGT(wolfSSL_read(ssl, reply, sizeof(reply)), 0); - wolfSSL_shutdown(ssl); - wolfSSL_free(ssl); - wolfSSL_CTX_free(ctx); - CloseSocket(sockfd); - join_thread(serverThread); - - FreeTcpReady(&ready); + ExpectTrue((fp = XFOPEN("./MyKeyLog.txt", "w")) != XBADFILE); + if (fp != XBADFILE) { + XFCLOSE(fp); + fp = XBADFILE; + } -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, NULL), TEST_SUCCESS); /* check if the keylog file exists */ char buff[300] = {0}; int found = 0; - fp = XFOPEN("./MyKeyLog.txt", "r"); + ExpectTrue((fp = XFOPEN("./MyKeyLog.txt", "r")) != XBADFILE); - AssertNotNull(fp); - - while (XFGETS( buff, (int)sizeof(buff),fp) != NULL ) { - if (0 == strncmp(buff,"CLIENT_RANDOM ", - sizeof("CLIENT_RANDOM ")-1)) { + while (EXPECT_SUCCESS() && XFGETS(buff, (int)sizeof(buff), fp) != NULL) { + if (0 == strncmp(buff,"CLIENT_RANDOM ", sizeof("CLIENT_RANDOM ")-1)) { found = 1; break; } } - XFCLOSE(fp); + if (fp != XBADFILE) { + XFCLOSE(fp); + } /* a log starting with "CLIENT_RANDOM " should exit in the file */ - AssertNotNull( found ); + ExpectIntEQ(found, 1); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */ return res; } + +#if defined(WOLFSSL_TLS13) && defined(OPENSSL_EXTRA) && \ + defined(HAVE_SECRET_CALLBACK) +static int test_wolfSSL_Tls13_Key_Logging_client_ctx_ready(WOLFSSL_CTX* ctx) +{ + /* set keylog callback */ + wolfSSL_CTX_set_keylog_callback(ctx, keyLog_callback); + return TEST_SUCCESS; +} +#endif + static int test_wolfSSL_Tls13_Key_Logging_test(void) { int res = TEST_SKIPPED; @@ -39449,76 +39375,25 @@ static int test_wolfSSL_Tls13_Key_Logging_test(void) /* This test is intended for checking whether keylog callback is called * in client during TLS handshake between the client and a server. */ + EXPECT_DECLS; + test_ssl_cbf server_cbf; + test_ssl_cbf client_cbf; + XFILE fp = XBADFILE; - tcp_ready ready; - func_args client_args; - func_args server_args; - THREAD_TYPE serverThread; - callback_functions server_cbf; - callback_functions client_cbf; - SOCKET_T sockfd = 0; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; - XFILE fp; - char msg[64] = "hello wolfssl!"; - char reply[1024]; - int msgSz = (int)XSTRLEN(msg); - -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif - - InitTcpReady(&ready); - ready.port = 22222; - - XMEMSET(&client_args, 0, sizeof(func_args)); - XMEMSET(&server_args, 0, sizeof(func_args)); - XMEMSET(&server_cbf, 0, sizeof(callback_functions)); - XMEMSET(&client_cbf, 0, sizeof(callback_functions)); - server_cbf.method = wolfTLSv1_3_server_method; /* TLS1.3 */ - - server_args.callbacks = &server_cbf; - server_args.signal = &ready; + XMEMSET(&server_cbf, 0, sizeof(test_ssl_cbf)); + XMEMSET(&client_cbf, 0, sizeof(test_ssl_cbf)); + server_cbf.method = wolfTLSv1_3_server_method; /* TLS1.3 */ + client_cbf.ctx_ready = &test_wolfSSL_Tls13_Key_Logging_client_ctx_ready; /* clean up keylog file */ - fp = XFOPEN("./MyKeyLog.txt", "w"); - XFCLOSE(fp); - - /* start server task */ - start_thread(server_task, &server_args, &serverThread); - wait_tcp_ready(&server_args); - - - /* run as a TLS1.3 client */ - AssertNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(WOLFSSL_SUCCESS, - wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); - - tcp_connect(&sockfd, wolfSSLIP, server_args.signal->port, 0, 0, NULL); - - /* set keylog callback */ - wolfSSL_CTX_set_keylog_callback(ctx,keyLog_callback); - - /* get connected the server task */ - AssertNotNull(ssl = wolfSSL_new(ctx)); - AssertIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_connect(ssl), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_write(ssl, msg, msgSz), msgSz); - AssertIntGT(wolfSSL_read(ssl, reply, sizeof(reply)), 0); - wolfSSL_free(ssl); - wolfSSL_CTX_free(ctx); - - join_thread(serverThread); - - FreeTcpReady(&ready); + ExpectTrue((fp = XFOPEN("./MyKeyLog.txt", "w")) != XBADFILE); + if (fp != XBADFILE) { + XFCLOSE(fp); + fp = XBADFILE; + } -#ifdef WOLFSSL_TIRTOS - fdOpenSession(Task_self()); -#endif + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, NULL), TEST_SUCCESS); /* check if the keylog file exists */ { @@ -39527,41 +39402,41 @@ static int test_wolfSSL_Tls13_Key_Logging_test(void) int numfnd = 0; int i; - fp = XFOPEN("./MyKeyLog.txt", "r"); - - AssertNotNull(fp); + ExpectTrue((fp = XFOPEN("./MyKeyLog.txt", "r")) != XBADFILE); - while (XFGETS( buff, (int)sizeof(buff),fp) != NULL ) { - if (0 == strncmp(buff,"CLIENT_HANDSHAKE_TRAFFIC_SECRET ", - sizeof("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")-1)) { + while (EXPECT_SUCCESS() && + XFGETS(buff, (int)sizeof(buff), fp) != NULL) { + if (0 == strncmp(buff, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", + sizeof("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")-1)) { found[0] = 1; continue; } - else if (0 == strncmp(buff,"SERVER_HANDSHAKE_TRAFFIC_SECRET ", - sizeof("SERVER_HANDSHAKE_TRAFFIC_SECRET ")-1)) { + else if (0 == strncmp(buff, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", + sizeof("SERVER_HANDSHAKE_TRAFFIC_SECRET ")-1)) { found[1] = 1; continue; } - else if (0 == strncmp(buff,"CLIENT_TRAFFIC_SECRET_0 ", - sizeof("CLIENT_TRAFFIC_SECRET_0 ")-1)) { + else if (0 == strncmp(buff, "CLIENT_TRAFFIC_SECRET_0 ", + sizeof("CLIENT_TRAFFIC_SECRET_0 ")-1)) { found[2] = 1; continue; } - else if (0 == strncmp(buff,"SERVER_TRAFFIC_SECRET_0 ", - sizeof("SERVER_TRAFFIC_SECRET_0 ")-1)) { + else if (0 == strncmp(buff, "SERVER_TRAFFIC_SECRET_0 ", + sizeof("SERVER_TRAFFIC_SECRET_0 ")-1)) { found[3] = 1; continue; } } - XFCLOSE(fp); + if (fp != XBADFILE) + XFCLOSE(fp); for (i = 0; i < 4; i++) { if (found[i] != 0) numfnd++; } - AssertIntEQ(numfnd, 4); + ExpectIntEQ(numfnd, 4); } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK && WOLFSSL_TLS13 */ return res; } @@ -39719,48 +39594,56 @@ static int test_wolfSSL_Tls13_ECH(void) #if defined(HAVE_IO_TESTS_DEPENDENCIES) && \ defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) -static void post_auth_version_cb(WOLFSSL* ssl) +static int post_auth_version_cb(WOLFSSL* ssl) { + EXPECT_DECLS; /* do handshake and then test version error */ - AssertIntEQ(wolfSSL_accept(ssl), WOLFSSL_SUCCESS); - AssertStrEQ("TLSv1.2", wolfSSL_get_version(ssl)); + ExpectIntEQ(wolfSSL_accept(ssl), WOLFSSL_SUCCESS); + ExpectStrEQ("TLSv1.2", wolfSSL_get_version(ssl)); + return EXPECT_RESULT(); } -static void post_auth_version_client_cb(WOLFSSL* ssl) +static int post_auth_version_client_cb(WOLFSSL* ssl) { + EXPECT_DECLS; /* do handshake and then test version error */ - AssertIntEQ(wolfSSL_connect(ssl), WOLFSSL_SUCCESS); - AssertStrEQ("TLSv1.2", wolfSSL_get_version(ssl)); - AssertIntEQ(wolfSSL_verify_client_post_handshake(ssl), WOLFSSL_FAILURE); + ExpectIntEQ(wolfSSL_connect(ssl), WOLFSSL_SUCCESS); + ExpectStrEQ("TLSv1.2", wolfSSL_get_version(ssl)); + ExpectIntEQ(wolfSSL_verify_client_post_handshake(ssl), WOLFSSL_FAILURE); #if defined(OPENSSL_ALL) && !defined(NO_ERROR_QUEUE) /* check was added to error queue */ - AssertIntEQ(wolfSSL_ERR_get_error(), -UNSUPPORTED_PROTO_VERSION); + ExpectIntEQ(wolfSSL_ERR_get_error(), -UNSUPPORTED_PROTO_VERSION); /* check the string matches expected string */ - AssertStrEQ(wolfSSL_ERR_error_string(-UNSUPPORTED_PROTO_VERSION, NULL), + ExpectStrEQ(wolfSSL_ERR_error_string(-UNSUPPORTED_PROTO_VERSION, NULL), "WRONG_SSL_VERSION"); #endif + return EXPECT_RESULT(); } -static void post_auth_cb(WOLFSSL* ssl) +static int post_auth_cb(WOLFSSL* ssl) { - WOLFSSL_X509* x509; + EXPECT_DECLS; + WOLFSSL_X509* x509 = NULL; /* do handshake and then test version error */ - AssertIntEQ(wolfSSL_accept(ssl), WOLFSSL_SUCCESS); - AssertStrEQ("TLSv1.3", wolfSSL_get_version(ssl)); - AssertNull(x509 = wolfSSL_get_peer_certificate(ssl)); + ExpectIntEQ(wolfSSL_accept(ssl), WOLFSSL_SUCCESS); + ExpectStrEQ("TLSv1.3", wolfSSL_get_version(ssl)); + ExpectNull(x509 = wolfSSL_get_peer_certificate(ssl)); wolfSSL_X509_free(x509); - AssertIntEQ(wolfSSL_verify_client_post_handshake(ssl), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_verify_client_post_handshake(ssl), WOLFSSL_SUCCESS); + return EXPECT_RESULT(); } -static void set_post_auth_cb(WOLFSSL* ssl) +static int set_post_auth_cb(WOLFSSL* ssl) { + EXPECT_DECLS; if (!wolfSSL_is_server(ssl)) { - AssertIntEQ(wolfSSL_allow_post_handshake_auth(ssl), 0); + ExpectIntEQ(wolfSSL_allow_post_handshake_auth(ssl), 0); } else { wolfSSL_set_verify(ssl, WOLFSSL_VERIFY_POST_HANDSHAKE, NULL); } + return EXPECT_RESULT(); } #endif @@ -39770,8 +39653,9 @@ static int test_wolfSSL_Tls13_postauth(void) #if defined(HAVE_IO_TESTS_DEPENDENCIES) && \ defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) - callback_functions server_cbf; - callback_functions client_cbf; + EXPECT_DECLS; + test_ssl_cbf server_cbf; + test_ssl_cbf client_cbf; /* test version failure doing post auth with TLS 1.2 connection */ XMEMSET(&server_cbf, 0, sizeof(callback_functions)); @@ -39782,7 +39666,8 @@ static int test_wolfSSL_Tls13_postauth(void) client_cbf.ssl_ready = set_post_auth_cb; client_cbf.on_result = post_auth_version_client_cb; - test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, NULL), TEST_SUCCESS); /* tests on post auth with TLS 1.3 */ XMEMSET(&server_cbf, 0, sizeof(callback_functions)); @@ -39793,9 +39678,10 @@ static int test_wolfSSL_Tls13_postauth(void) server_cbf.on_result = post_auth_cb; client_cbf.on_result = NULL; - test_wolfSSL_client_server_nofail(&client_cbf, &server_cbf); + ExpectIntEQ(test_wolfSSL_client_server_nofail_memio(&client_cbf, + &server_cbf, NULL), TEST_SUCCESS); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -39806,12 +39692,13 @@ static int test_wolfSSL_X509_NID(void) int res = TEST_SKIPPED; #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ !defined(NO_RSA) && defined(USE_CERT_BUFFERS_2048) && !defined(NO_ASN) + EXPECT_DECLS; int sigType; int nameSz; - X509* cert; - EVP_PKEY* pubKeyTmp; - X509_NAME* name; + X509* cert = NULL; + EVP_PKEY* pubKeyTmp = NULL; + X509_NAME* name = NULL; char commonName[80]; char countryName[80]; @@ -39823,56 +39710,56 @@ static int test_wolfSSL_X509_NID(void) /* ------ PARSE ORIGINAL SELF-SIGNED CERTIFICATE ------ */ /* convert cert from DER to internal WOLFSSL_X509 struct */ - AssertNotNull(cert = wolfSSL_X509_d2i(&cert, client_cert_der_2048, + ExpectNotNull(cert = wolfSSL_X509_d2i(&cert, client_cert_der_2048, sizeof_client_cert_der_2048)); /* ------ EXTRACT CERTIFICATE ELEMENTS ------ */ /* extract PUBLIC KEY from cert */ - AssertNotNull(pubKeyTmp = X509_get_pubkey(cert)); + ExpectNotNull(pubKeyTmp = X509_get_pubkey(cert)); /* extract signatureType */ - AssertIntNE((sigType = wolfSSL_X509_get_signature_type(cert)), 0); + ExpectIntNE((sigType = wolfSSL_X509_get_signature_type(cert)), 0); /* extract subjectName info */ - AssertNotNull(name = X509_get_subject_name(cert)); - AssertIntEQ(X509_NAME_get_text_by_NID(name, -1, NULL, 0), -1); - AssertIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_commonName, - NULL, 0)), 0); - AssertIntEQ(nameSz, 15); - AssertIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_commonName, - commonName, sizeof(commonName))), 0); - AssertIntEQ(nameSz, 15); - AssertIntEQ(XMEMCMP(commonName, "www.wolfssl.com", nameSz), 0); - AssertIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_commonName, - commonName, 9)), 0); - AssertIntEQ(nameSz, 8); - AssertIntEQ(XMEMCMP(commonName, "www.wolf", nameSz), 0); - - AssertIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_countryName, - countryName, sizeof(countryName))), 0); - AssertIntEQ(XMEMCMP(countryName, "US", nameSz), 0); - - AssertIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_localityName, - localityName, sizeof(localityName))), 0); - AssertIntEQ(XMEMCMP(localityName, "Bozeman", nameSz), 0); - - AssertIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_stateOrProvinceName, - stateName, sizeof(stateName))), 0); - AssertIntEQ(XMEMCMP(stateName, "Montana", nameSz), 0); - - AssertIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_organizationName, - orgName, sizeof(orgName))), 0); - AssertIntEQ(XMEMCMP(orgName, "wolfSSL_2048", nameSz), 0); - - AssertIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_organizationalUnitName, - orgUnit, sizeof(orgUnit))), 0); - AssertIntEQ(XMEMCMP(orgUnit, "Programming-2048", nameSz), 0); + ExpectNotNull(name = X509_get_subject_name(cert)); + ExpectIntEQ(X509_NAME_get_text_by_NID(name, -1, NULL, 0), -1); + ExpectIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_commonName, + NULL, 0)), 0); + ExpectIntEQ(nameSz, 15); + ExpectIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_commonName, + commonName, sizeof(commonName))), 0); + ExpectIntEQ(nameSz, 15); + ExpectIntEQ(XMEMCMP(commonName, "www.wolfssl.com", nameSz), 0); + ExpectIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_commonName, + commonName, 9)), 0); + ExpectIntEQ(nameSz, 8); + ExpectIntEQ(XMEMCMP(commonName, "www.wolf", nameSz), 0); + + ExpectIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_countryName, + countryName, sizeof(countryName))), 0); + ExpectIntEQ(XMEMCMP(countryName, "US", nameSz), 0); + + ExpectIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_localityName, + localityName, sizeof(localityName))), 0); + ExpectIntEQ(XMEMCMP(localityName, "Bozeman", nameSz), 0); + + ExpectIntGT((nameSz = X509_NAME_get_text_by_NID(name, + NID_stateOrProvinceName, stateName, sizeof(stateName))), 0); + ExpectIntEQ(XMEMCMP(stateName, "Montana", nameSz), 0); + + ExpectIntGT((nameSz = X509_NAME_get_text_by_NID(name, NID_organizationName, + orgName, sizeof(orgName))), 0); + ExpectIntEQ(XMEMCMP(orgName, "wolfSSL_2048", nameSz), 0); + + ExpectIntGT((nameSz = X509_NAME_get_text_by_NID(name, + NID_organizationalUnitName, orgUnit, sizeof(orgUnit))), 0); + ExpectIntEQ(XMEMCMP(orgUnit, "Programming-2048", nameSz), 0); EVP_PKEY_free(pubKeyTmp); X509_free(cert); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -39882,34 +39769,32 @@ static int test_wolfSSL_CTX_set_srp_username(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \ && !defined(NO_SHA256) && !defined(WC_NO_RNG) && !defined(NO_WOLFSSL_CLIENT) - - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; const char *username = "TESTUSER"; const char *password = "TESTPASSWORD"; - int r; - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); - r = wolfSSL_CTX_set_srp_username(ctx, (char *)username); - AssertIntEQ(r,SSL_SUCCESS); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_set_srp_username(ctx, (char *)username), + SSL_SUCCESS); wolfSSL_CTX_free(ctx); + ctx = NULL; - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); - r = wolfSSL_CTX_set_srp_password(ctx, (char *)password); - AssertIntEQ(r,SSL_SUCCESS); - r = wolfSSL_CTX_set_srp_username(ctx, (char *)username); - AssertIntEQ(r,SSL_SUCCESS); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_set_srp_password(ctx, (char *)password), + SSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set_srp_username(ctx, (char *)username), + SSL_SUCCESS); - AssertNotNull(ssl = SSL_new(ctx)); - AssertNotNull(SSL_get_srp_username(ssl)); - AssertStrEQ(SSL_get_srp_username(ssl), username); + ExpectNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(SSL_get_srp_username(ssl)); + ExpectStrEQ(SSL_get_srp_username(ssl), username); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && WOLFCRYPT_HAVE_SRP */ /* && !NO_SHA256 && !WC_NO_RNG && !NO_WOLFSSL_CLIENT */ return res; @@ -39918,28 +39803,27 @@ static int test_wolfSSL_CTX_set_srp_username(void) static int test_wolfSSL_CTX_set_srp_password(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \ - && !defined(NO_SHA256) && !defined(WC_NO_RNG) && !defined(NO_WOLFSSL_CLIENT) - WOLFSSL_CTX* ctx; +#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) && \ + !defined(NO_SHA256) && !defined(WC_NO_RNG) && !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; + WOLFSSL_CTX* ctx = NULL; const char *username = "TESTUSER"; const char *password = "TESTPASSWORD"; - int r; - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); - r = wolfSSL_CTX_set_srp_password(ctx, (char *)password); - AssertIntEQ(r,SSL_SUCCESS); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_set_srp_password(ctx, (char *)password), + SSL_SUCCESS); wolfSSL_CTX_free(ctx); + ctx = NULL; - ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); - AssertNotNull(ctx); - r = wolfSSL_CTX_set_srp_username(ctx, (char *)username); - AssertIntEQ(r,SSL_SUCCESS); - r = wolfSSL_CTX_set_srp_password(ctx, (char *)password); - AssertIntEQ(r,SSL_SUCCESS); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_set_srp_username(ctx, (char *)username), + SSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set_srp_password(ctx, (char *)password), + SSL_SUCCESS); wolfSSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && WOLFCRYPT_HAVE_SRP */ /* && !NO_SHA256 && !WC_NO_RNG && !NO_WOLFSSL_CLIENT */ return res; @@ -39949,95 +39833,113 @@ static int test_wolfSSL_X509_STORE(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_RSA) - X509_STORE *store; + EXPECT_DECLS; + X509_STORE *store = NULL; - #ifdef HAVE_CRL - X509_STORE_CTX *storeCtx; - X509_CRL *crl; - X509 *ca, *cert; +#ifdef HAVE_CRL + X509_STORE_CTX *storeCtx = NULL; + X509_CRL *crl = NULL; + X509 *ca = NULL; + X509 *cert = NULL; const char crlPem[] = "./certs/crl/crl.revoked"; const char srvCert[] = "./certs/server-revoked-cert.pem"; const char caCert[] = "./certs/ca-cert.pem"; - XFILE fp; + XFILE fp = XBADFILE; - AssertNotNull(store = (X509_STORE *)X509_STORE_new()); - AssertNotNull((ca = wolfSSL_X509_load_certificate_file(caCert, + ExpectNotNull(store = (X509_STORE *)X509_STORE_new()); + ExpectNotNull((ca = wolfSSL_X509_load_certificate_file(caCert, SSL_FILETYPE_PEM))); - AssertIntEQ(X509_STORE_add_cert(store, ca), SSL_SUCCESS); - AssertNotNull((cert = wolfSSL_X509_load_certificate_file(srvCert, + ExpectIntEQ(X509_STORE_add_cert(store, ca), SSL_SUCCESS); + ExpectNotNull((cert = wolfSSL_X509_load_certificate_file(srvCert, SSL_FILETYPE_PEM))); - AssertNotNull((storeCtx = X509_STORE_CTX_new())); - AssertIntEQ(X509_STORE_CTX_init(storeCtx, store, cert, NULL), SSL_SUCCESS); - AssertIntEQ(X509_verify_cert(storeCtx), SSL_SUCCESS); + ExpectNotNull((storeCtx = X509_STORE_CTX_new())); + ExpectIntEQ(X509_STORE_CTX_init(storeCtx, store, cert, NULL), SSL_SUCCESS); + ExpectIntEQ(X509_verify_cert(storeCtx), SSL_SUCCESS); X509_STORE_free(store); + store = NULL; X509_STORE_CTX_free(storeCtx); + storeCtx = NULL; X509_free(cert); + cert = NULL; X509_free(ca); + ca = NULL; /* should fail to verify now after adding in CRL */ - AssertNotNull(store = (X509_STORE *)X509_STORE_new()); - AssertNotNull((ca = wolfSSL_X509_load_certificate_file(caCert, + ExpectNotNull(store = (X509_STORE *)X509_STORE_new()); + ExpectNotNull((ca = wolfSSL_X509_load_certificate_file(caCert, SSL_FILETYPE_PEM))); - AssertIntEQ(X509_STORE_add_cert(store, ca), SSL_SUCCESS); - fp = XFOPEN(crlPem, "rb"); - AssertTrue((fp != XBADFILE)); - AssertNotNull(crl = (X509_CRL *)PEM_read_X509_CRL(fp, (X509_CRL **)NULL, + ExpectIntEQ(X509_STORE_add_cert(store, ca), SSL_SUCCESS); + ExpectTrue((fp = XFOPEN(crlPem, "rb")) != XBADFILE); + ExpectNotNull(crl = (X509_CRL *)PEM_read_X509_CRL(fp, (X509_CRL **)NULL, NULL, NULL)); - XFCLOSE(fp); - AssertIntEQ(X509_STORE_add_crl(store, crl), SSL_SUCCESS); - AssertIntEQ(X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK),SSL_SUCCESS); - AssertNotNull((storeCtx = X509_STORE_CTX_new())); - AssertNotNull((cert = wolfSSL_X509_load_certificate_file(srvCert, + if (fp != XBADFILE) + XFCLOSE(fp); + ExpectIntEQ(X509_STORE_add_crl(store, crl), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK),SSL_SUCCESS); + ExpectNotNull((storeCtx = X509_STORE_CTX_new())); + ExpectNotNull((cert = wolfSSL_X509_load_certificate_file(srvCert, SSL_FILETYPE_PEM))); - AssertIntEQ(X509_STORE_CTX_init(storeCtx, store, cert, NULL), SSL_SUCCESS); - AssertIntNE(X509_verify_cert(storeCtx), SSL_SUCCESS); - AssertIntEQ(X509_STORE_CTX_get_error(storeCtx), CRL_CERT_REVOKED); + ExpectIntEQ(X509_STORE_CTX_init(storeCtx, store, cert, NULL), SSL_SUCCESS); + ExpectIntNE(X509_verify_cert(storeCtx), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_CTX_get_error(storeCtx), CRL_CERT_REVOKED); X509_CRL_free(crl); + crl = NULL; X509_STORE_free(store); + store = NULL; X509_STORE_CTX_free(storeCtx); + storeCtx = NULL; X509_free(cert); + cert = NULL; X509_free(ca); - #endif /* HAVE_CRL */ + ca = NULL; +#endif /* HAVE_CRL */ - #ifndef WOLFCRYPT_ONLY +#ifndef WOLFCRYPT_ONLY { - #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) - SSL_CTX* ctx; - SSL* ssl; + #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) + SSL_CTX* ctx = NULL; + SSL* ssl = NULL; int i; for (i = 0; i < 2; i++) { #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_client_method())); #endif - AssertNotNull(store = (X509_STORE *)X509_STORE_new()); + ExpectNotNull(store = (X509_STORE *)X509_STORE_new()); SSL_CTX_set_cert_store(ctx, store); - AssertNotNull(store = (X509_STORE *)X509_STORE_new()); + ExpectNotNull(store = (X509_STORE *)X509_STORE_new()); SSL_CTX_set_cert_store(ctx, store); - AssertNotNull(store = (X509_STORE *)X509_STORE_new()); - AssertIntEQ(SSL_CTX_use_certificate_file(ctx, svrCertFile, + ExpectNotNull(store = (X509_STORE *)X509_STORE_new()); + ExpectIntEQ(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM), SSL_SUCCESS); - AssertIntEQ(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + ExpectIntEQ(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM), SSL_SUCCESS); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); if (i == 0) { - AssertIntEQ(SSL_set0_verify_cert_store(ssl, store), SSL_SUCCESS); + ExpectIntEQ(SSL_set0_verify_cert_store(ssl, store), + SSL_SUCCESS); } else { - AssertIntEQ(SSL_set1_verify_cert_store(ssl, store), SSL_SUCCESS); + ExpectIntEQ(SSL_set1_verify_cert_store(ssl, store), + SSL_SUCCESS); + } + if (EXPECT_FAIL() || (i == 1)) { X509_STORE_free(store); + store = NULL; } SSL_free(ssl); + ssl = NULL; SSL_CTX_free(ctx); + ctx = NULL; } - #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ + #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */ } - #endif +#endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40047,8 +39949,9 @@ static int test_wolfSSL_X509_STORE_load_locations(void) int res = TEST_SKIPPED; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)) && \ !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) && !defined(NO_RSA) - SSL_CTX *ctx; - X509_STORE *store; + EXPECT_DECLS; + SSL_CTX *ctx = NULL; + X509_STORE *store = NULL; const char ca_file[] = "./certs/ca-cert.pem"; const char client_pem_file[] = "./certs/client-cert.pem"; @@ -40062,32 +39965,42 @@ static int test_wolfSSL_X509_STORE_load_locations(void) #endif #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(SSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(SSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(SSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(SSLv23_client_method())); #endif - AssertNotNull(store = SSL_CTX_get_cert_store(ctx)); - AssertIntEQ(wolfSSL_CertManagerLoadCA(store->cm, ca_file, NULL), WOLFSSL_SUCCESS); + ExpectNotNull(store = SSL_CTX_get_cert_store(ctx)); + ExpectIntEQ(wolfSSL_CertManagerLoadCA(store->cm, ca_file, NULL), + WOLFSSL_SUCCESS); /* Test bad arguments */ - AssertIntEQ(X509_STORE_load_locations(NULL, ca_file, NULL), WOLFSSL_FAILURE); - AssertIntEQ(X509_STORE_load_locations(store, NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(X509_STORE_load_locations(store, client_der_file, NULL), WOLFSSL_FAILURE); - AssertIntEQ(X509_STORE_load_locations(store, ecc_file, NULL), WOLFSSL_FAILURE); - AssertIntEQ(X509_STORE_load_locations(store, NULL, bad_path), WOLFSSL_FAILURE); + ExpectIntEQ(X509_STORE_load_locations(NULL, ca_file, NULL), + WOLFSSL_FAILURE); + ExpectIntEQ(X509_STORE_load_locations(store, NULL, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(X509_STORE_load_locations(store, client_der_file, NULL), + WOLFSSL_FAILURE); + ExpectIntEQ(X509_STORE_load_locations(store, ecc_file, NULL), + WOLFSSL_FAILURE); + ExpectIntEQ(X509_STORE_load_locations(store, NULL, bad_path), + WOLFSSL_FAILURE); #ifdef HAVE_CRL /* Test with CRL */ - AssertIntEQ(X509_STORE_load_locations(store, crl_file, NULL), WOLFSSL_SUCCESS); - AssertIntEQ(X509_STORE_load_locations(store, NULL, crl_path), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_load_locations(store, crl_file, NULL), + WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_load_locations(store, NULL, crl_path), + WOLFSSL_SUCCESS); #endif /* Test with CA */ - AssertIntEQ(X509_STORE_load_locations(store, ca_file, NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_load_locations(store, ca_file, NULL), + WOLFSSL_SUCCESS); /* Test with client_cert and certs path */ - AssertIntEQ(X509_STORE_load_locations(store, client_pem_file, NULL), WOLFSSL_SUCCESS); - AssertIntEQ(X509_STORE_load_locations(store, NULL, certs_path), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_load_locations(store, client_pem_file, NULL), + WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_load_locations(store, NULL, certs_path), + WOLFSSL_SUCCESS); #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) /* Clear nodes */ @@ -40096,7 +40009,7 @@ static int test_wolfSSL_X509_STORE_load_locations(void) SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40106,58 +40019,67 @@ static int test_X509_STORE_get0_objects(void) int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && \ !defined(NO_WOLFSSL_DIR) && !defined(NO_RSA) - X509_STORE *store; - X509_STORE *store_cpy; - SSL_CTX *ctx; - X509_OBJECT *obj; - STACK_OF(X509_OBJECT) *objs; + EXPECT_DECLS; + X509_STORE *store = NULL; + X509_STORE *store_cpy = NULL; + SSL_CTX *ctx = NULL; + X509_OBJECT *obj = NULL; + STACK_OF(X509_OBJECT) *objs = NULL; int i; /* Setup store */ #ifndef NO_WOLFSSL_SERVER - AssertNotNull(ctx = SSL_CTX_new(SSLv23_server_method())); + ExpectNotNull(ctx = SSL_CTX_new(SSLv23_server_method())); #else - AssertNotNull(ctx = SSL_CTX_new(SSLv23_client_method())); + ExpectNotNull(ctx = SSL_CTX_new(SSLv23_client_method())); #endif - AssertNotNull(store_cpy = X509_STORE_new()); - AssertNotNull(store = SSL_CTX_get_cert_store(ctx)); - AssertIntEQ(X509_STORE_load_locations(store, cliCertFile, NULL), WOLFSSL_SUCCESS); - AssertIntEQ(X509_STORE_load_locations(store, caCertFile, NULL), WOLFSSL_SUCCESS); - AssertIntEQ(X509_STORE_load_locations(store, svrCertFile, NULL), WOLFSSL_SUCCESS); + ExpectNotNull(store_cpy = X509_STORE_new()); + ExpectNotNull(store = SSL_CTX_get_cert_store(ctx)); + ExpectIntEQ(X509_STORE_load_locations(store, cliCertFile, NULL), + WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_load_locations(store, caCertFile, NULL), + WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_load_locations(store, svrCertFile, NULL), + WOLFSSL_SUCCESS); #ifdef HAVE_CRL - AssertIntEQ(X509_STORE_load_locations(store, NULL, crlPemDir), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_STORE_load_locations(store, NULL, crlPemDir), + WOLFSSL_SUCCESS); #endif /* Store ready */ /* Similar to HaProxy ssl_set_cert_crl_file use case */ - AssertNotNull(objs = X509_STORE_get0_objects(store)); + ExpectNotNull(objs = X509_STORE_get0_objects(store)); #ifdef HAVE_CRL #ifdef WOLFSSL_SIGNER_DER_CERT - AssertIntEQ(sk_X509_OBJECT_num(objs), 4); + ExpectIntEQ(sk_X509_OBJECT_num(objs), 4); #else - AssertIntEQ(sk_X509_OBJECT_num(objs), 1); + ExpectIntEQ(sk_X509_OBJECT_num(objs), 1); #endif #else #ifdef WOLFSSL_SIGNER_DER_CERT - AssertIntEQ(sk_X509_OBJECT_num(objs), 3); + ExpectIntEQ(sk_X509_OBJECT_num(objs), 3); #else - AssertIntEQ(sk_X509_OBJECT_num(objs), 0); + ExpectIntEQ(sk_X509_OBJECT_num(objs), 0); #endif #endif for (i = 0; i < sk_X509_OBJECT_num(objs); i++) { obj = (X509_OBJECT*)sk_X509_OBJECT_value(objs, i); switch (X509_OBJECT_get_type(obj)) { case X509_LU_X509: - AssertNotNull(X509_OBJECT_get0_X509(obj)); - AssertIntEQ(X509_STORE_add_cert(store_cpy, - X509_OBJECT_get0_X509(obj)), WOLFSSL_SUCCESS); + { + WOLFSSL_X509* x509; + ExpectNotNull(x509 = X509_OBJECT_get0_X509(obj)); + ExpectIntEQ(X509_STORE_add_cert(store_cpy, x509), WOLFSSL_SUCCESS); break; + } case X509_LU_CRL: #ifdef HAVE_CRL - AssertNotNull(X509_OBJECT_get0_X509_CRL(obj)); - AssertIntEQ(X509_STORE_add_crl(store_cpy, - X509_OBJECT_get0_X509_CRL(obj)), WOLFSSL_SUCCESS); + { + WOLFSSL_CRL* crl = NULL; + ExpectNotNull(crl = X509_OBJECT_get0_X509_CRL(obj)); + ExpectIntEQ(X509_STORE_add_crl(store_cpy, crl), WOLFSSL_SUCCESS); break; + } #endif case X509_LU_NONE: default: @@ -40170,7 +40092,7 @@ static int test_X509_STORE_get0_objects(void) X509_STORE_free(store_cpy); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40180,17 +40102,18 @@ static int test_wolfSSL_BN_CTX(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) - WOLFSSL_BN_CTX* bn_ctx; - WOLFSSL_BIGNUM* t; + EXPECT_DECLS; + WOLFSSL_BN_CTX* bn_ctx = NULL; + WOLFSSL_BIGNUM* t = NULL; - AssertNotNull(bn_ctx = wolfSSL_BN_CTX_new()); + ExpectNotNull(bn_ctx = wolfSSL_BN_CTX_new()); /* No implementation. */ BN_CTX_init(NULL); - AssertNotNull(t = BN_CTX_get(NULL)); + ExpectNotNull(t = BN_CTX_get(NULL)); BN_free(t); - AssertNotNull(t = BN_CTX_get(bn_ctx)); + ExpectNotNull(t = BN_CTX_get(bn_ctx)); BN_free(t); #ifndef NO_WOLFSSL_STUB @@ -40202,7 +40125,7 @@ static int test_wolfSSL_BN_CTX(void) BN_CTX_free(NULL); BN_CTX_free(bn_ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_ASN) */ return res; } @@ -40212,111 +40135,113 @@ static int test_wolfSSL_BN(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) - BIGNUM* a; - BIGNUM* b; - BIGNUM* c; - BIGNUM* d; + EXPECT_DECLS; + BIGNUM* a = NULL; + BIGNUM* b = NULL; + BIGNUM* c = NULL; + BIGNUM* d = NULL; BIGNUM emptyBN; /* Setup */ XMEMSET(&emptyBN, 0, sizeof(emptyBN)); /* internal not set emptyBN. */ - AssertNotNull(a = BN_new()); - AssertNotNull(b = BN_new()); - AssertNotNull(c = BN_dup(b)); - AssertNotNull(d = BN_new()); + ExpectNotNull(a = BN_new()); + ExpectNotNull(b = BN_new()); + ExpectNotNull(c = BN_dup(b)); + ExpectNotNull(d = BN_new()); /* Invalid parameter testing. */ BN_free(NULL); - AssertNull(BN_dup(NULL)); - AssertNull(BN_dup(&emptyBN)); + ExpectNull(BN_dup(NULL)); + ExpectNull(BN_dup(&emptyBN)); - AssertNull(BN_copy(NULL, NULL)); - AssertNull(BN_copy(b, NULL)); - AssertNull(BN_copy(NULL, c)); - AssertNull(BN_copy(b, &emptyBN)); - AssertNull(BN_copy(&emptyBN, c)); + ExpectNull(BN_copy(NULL, NULL)); + ExpectNull(BN_copy(b, NULL)); + ExpectNull(BN_copy(NULL, c)); + ExpectNull(BN_copy(b, &emptyBN)); + ExpectNull(BN_copy(&emptyBN, c)); BN_clear(NULL); BN_clear(&emptyBN); - AssertIntEQ(BN_num_bytes(NULL), 0); - AssertIntEQ(BN_num_bytes(&emptyBN), 0); + ExpectIntEQ(BN_num_bytes(NULL), 0); + ExpectIntEQ(BN_num_bytes(&emptyBN), 0); - AssertIntEQ(BN_num_bits(NULL), 0); - AssertIntEQ(BN_num_bits(&emptyBN), 0); + ExpectIntEQ(BN_num_bits(NULL), 0); + ExpectIntEQ(BN_num_bits(&emptyBN), 0); - AssertIntEQ(BN_is_negative(NULL), 0); - AssertIntEQ(BN_is_negative(&emptyBN), 0); + ExpectIntEQ(BN_is_negative(NULL), 0); + ExpectIntEQ(BN_is_negative(&emptyBN), 0); /* END Invalid Parameters */ - AssertIntEQ(BN_set_word(a, 3), SSL_SUCCESS); - AssertIntEQ(BN_set_word(b, 2), SSL_SUCCESS); - AssertIntEQ(BN_set_word(c, 5), SSL_SUCCESS); + ExpectIntEQ(BN_set_word(a, 3), SSL_SUCCESS); + ExpectIntEQ(BN_set_word(b, 2), SSL_SUCCESS); + ExpectIntEQ(BN_set_word(c, 5), SSL_SUCCESS); - AssertIntEQ(BN_num_bits(a), 2); - AssertIntEQ(BN_num_bytes(a), 1); + ExpectIntEQ(BN_num_bits(a), 2); + ExpectIntEQ(BN_num_bytes(a), 1); #if !defined(WOLFSSL_SP_MATH) && (!defined(WOLFSSL_SP_MATH_ALL) || \ defined(WOLFSSL_SP_INT_NEGATIVE)) - AssertIntEQ(BN_set_word(a, 1), SSL_SUCCESS); - AssertIntEQ(BN_set_word(b, 5), SSL_SUCCESS); - AssertIntEQ(BN_is_word(a, (WOLFSSL_BN_ULONG)BN_get_word(a)), SSL_SUCCESS); - AssertIntEQ(BN_is_word(a, 3), SSL_FAILURE); - AssertIntEQ(BN_sub(c, a, b), SSL_SUCCESS); + ExpectIntEQ(BN_set_word(a, 1), SSL_SUCCESS); + ExpectIntEQ(BN_set_word(b, 5), SSL_SUCCESS); + ExpectIntEQ(BN_is_word(a, (WOLFSSL_BN_ULONG)BN_get_word(a)), SSL_SUCCESS); + ExpectIntEQ(BN_is_word(a, 3), SSL_FAILURE); + ExpectIntEQ(BN_sub(c, a, b), SSL_SUCCESS); #if defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) { /* Do additional tests on negative BN conversions. */ - char * ret; - ASN1_INTEGER * asn1; - BIGNUM * tmp; + char* ret = NULL; + ASN1_INTEGER* asn1 = NULL; + BIGNUM* tmp = NULL; /* Sanity check we have a negative BN. */ - AssertIntEQ(BN_is_negative(c), 1); - AssertNotNull(ret = BN_bn2dec(c)); - AssertIntEQ(XMEMCMP(ret, "-4", sizeof("-4")), 0); + ExpectIntEQ(BN_is_negative(c), 1); + ExpectNotNull(ret = BN_bn2dec(c)); + ExpectIntEQ(XMEMCMP(ret, "-4", sizeof("-4")), 0); XFREE(ret, NULL, DYNAMIC_TYPE_OPENSSL); + ret = NULL; /* Convert to ASN1_INTEGER and back to BN. */ - AssertNotNull(asn1 = BN_to_ASN1_INTEGER(c, NULL)); - AssertNotNull(tmp = ASN1_INTEGER_to_BN(asn1, NULL)); + ExpectNotNull(asn1 = BN_to_ASN1_INTEGER(c, NULL)); + ExpectNotNull(tmp = ASN1_INTEGER_to_BN(asn1, NULL)); /* After converting back BN should be negative and correct. */ - AssertIntEQ(BN_is_negative(tmp), 1); - AssertNotNull(ret = BN_bn2dec(tmp)); - AssertIntEQ(XMEMCMP(ret, "-4", sizeof("-4")), 0); + ExpectIntEQ(BN_is_negative(tmp), 1); + ExpectNotNull(ret = BN_bn2dec(tmp)); + ExpectIntEQ(XMEMCMP(ret, "-4", sizeof("-4")), 0); XFREE(ret, NULL, DYNAMIC_TYPE_OPENSSL); ASN1_INTEGER_free(asn1); BN_free(tmp); } #endif - AssertIntEQ(BN_get_word(c), 4); + ExpectIntEQ(BN_get_word(c), 4); #endif - AssertIntEQ(BN_set_word(a, 3), 1); - AssertIntEQ(BN_set_word(b, 3), 1); - AssertIntEQ(BN_set_word(c, 4), 1); + ExpectIntEQ(BN_set_word(a, 3), 1); + ExpectIntEQ(BN_set_word(b, 3), 1); + ExpectIntEQ(BN_set_word(c, 4), 1); /* NULL == NULL, NULL < num, num > NULL */ - AssertIntEQ(BN_cmp(NULL, NULL), 0); - AssertIntEQ(BN_cmp(&emptyBN, &emptyBN), 0); - AssertIntLT(BN_cmp(NULL, b), 0); - AssertIntLT(BN_cmp(&emptyBN, b), 0); - AssertIntGT(BN_cmp(a, NULL), 0); - AssertIntGT(BN_cmp(a, &emptyBN), 0); + ExpectIntEQ(BN_cmp(NULL, NULL), 0); + ExpectIntEQ(BN_cmp(&emptyBN, &emptyBN), 0); + ExpectIntLT(BN_cmp(NULL, b), 0); + ExpectIntLT(BN_cmp(&emptyBN, b), 0); + ExpectIntGT(BN_cmp(a, NULL), 0); + ExpectIntGT(BN_cmp(a, &emptyBN), 0); - AssertIntEQ(BN_cmp(a, b), 0); - AssertIntLT(BN_cmp(a, c), 0); - AssertIntGT(BN_cmp(c, b), 0); + ExpectIntEQ(BN_cmp(a, b), 0); + ExpectIntLT(BN_cmp(a, c), 0); + ExpectIntGT(BN_cmp(c, b), 0); - AssertIntEQ(BN_print_fp(XBADFILE, NULL), 0); - AssertIntEQ(BN_print_fp(XBADFILE, &emptyBN), 0); - AssertIntEQ(BN_print_fp(stderr, NULL), 0); - AssertIntEQ(BN_print_fp(stderr, &emptyBN), 0); - AssertIntEQ(BN_print_fp(XBADFILE, a), 0); + ExpectIntEQ(BN_print_fp(XBADFILE, NULL), 0); + ExpectIntEQ(BN_print_fp(XBADFILE, &emptyBN), 0); + ExpectIntEQ(BN_print_fp(stderr, NULL), 0); + ExpectIntEQ(BN_print_fp(stderr, &emptyBN), 0); + ExpectIntEQ(BN_print_fp(XBADFILE, a), 0); - AssertIntEQ(BN_print_fp(stderr, a), 1); + ExpectIntEQ(BN_print_fp(stderr, a), 1); BN_clear(a); @@ -40325,7 +40250,7 @@ static int test_wolfSSL_BN(void) BN_free(c); BN_clear_free(d); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_ASN) */ return res; } @@ -40336,42 +40261,43 @@ static int test_wolfSSL_BN_init(void) #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) #if !defined(USE_INTEGER_HEAP_MATH) && !defined(HAVE_WOLF_BIGINT) - BIGNUM* ap; + EXPECT_DECLS; + BIGNUM* ap = NULL; BIGNUM bv; BIGNUM cv; BIGNUM dv; - AssertNotNull(ap = BN_new()); + ExpectNotNull(ap = BN_new()); BN_init(NULL); XMEMSET(&bv, 0, sizeof(bv)); - AssertNull(BN_dup(&bv)); + ExpectNull(BN_dup(&bv)); BN_init(&bv); BN_init(&cv); BN_init(&dv); - AssertIntEQ(BN_set_word(ap, 3), SSL_SUCCESS); - AssertIntEQ(BN_set_word(&bv, 2), SSL_SUCCESS); - AssertIntEQ(BN_set_word(&cv, 5), SSL_SUCCESS); + ExpectIntEQ(BN_set_word(ap, 3), SSL_SUCCESS); + ExpectIntEQ(BN_set_word(&bv, 2), SSL_SUCCESS); + ExpectIntEQ(BN_set_word(&cv, 5), SSL_SUCCESS); /* a^b mod c = */ - AssertIntEQ(BN_mod_exp(&dv, NULL, &bv, &cv, NULL), WOLFSSL_FAILURE); - AssertIntEQ(BN_mod_exp(&dv, ap, &bv, &cv, NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(BN_mod_exp(&dv, NULL, &bv, &cv, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(BN_mod_exp(&dv, ap, &bv, &cv, NULL), WOLFSSL_SUCCESS); /* check result 3^2 mod 5 */ - AssertIntEQ(BN_get_word(&dv), 4); + ExpectIntEQ(BN_get_word(&dv), 4); /* a*b mod c = */ - AssertIntEQ(BN_mod_mul(&dv, NULL, &bv, &cv, NULL), SSL_FAILURE); - AssertIntEQ(BN_mod_mul(&dv, ap, &bv, &cv, NULL), SSL_SUCCESS); + ExpectIntEQ(BN_mod_mul(&dv, NULL, &bv, &cv, NULL), SSL_FAILURE); + ExpectIntEQ(BN_mod_mul(&dv, ap, &bv, &cv, NULL), SSL_SUCCESS); /* check result 3*2 mod 5 */ - AssertIntEQ(BN_get_word(&dv), 1); + ExpectIntEQ(BN_get_word(&dv), 1); BN_free(ap); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif #endif /* defined(OPENSSL_EXTRA) && !defined(NO_ASN) */ return res; @@ -40381,11 +40307,12 @@ static int test_wolfSSL_BN_enc_dec(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && !defined(WOLFSSL_SP_MATH) - BIGNUM* a; - BIGNUM* b; + EXPECT_DECLS; + BIGNUM* a = NULL; + BIGNUM* b = NULL; BIGNUM* c = NULL; BIGNUM emptyBN; - char* str; + char* str = NULL; const char* emptyStr = ""; const char* numberStr = "12345"; const char* badStr = "g12345"; @@ -40397,78 +40324,80 @@ static int test_wolfSSL_BN_enc_dec(void) /* Setup */ XMEMSET(&emptyBN, 0, sizeof(emptyBN)); - AssertNotNull(a = BN_new()); - AssertNotNull(b = BN_new()); - AssertIntEQ(BN_set_word(a, 2), 1); + ExpectNotNull(a = BN_new()); + ExpectNotNull(b = BN_new()); + ExpectIntEQ(BN_set_word(a, 2), 1); /* Invalid parameters */ - AssertIntEQ(BN_bn2bin(NULL, NULL), -1); - AssertIntEQ(BN_bn2bin(&emptyBN, NULL), -1); - AssertIntEQ(BN_bn2bin(NULL, outNum), -1); - AssertIntEQ(BN_bn2bin(&emptyBN, outNum), -1); - AssertNull(BN_bn2hex(NULL)); - AssertNull(BN_bn2hex(&emptyBN)); - AssertNull(BN_bn2dec(NULL)); - AssertNull(BN_bn2dec(&emptyBN)); - - AssertNull(BN_bin2bn(NULL, sizeof(binNum), NULL)); - AssertNull(BN_bin2bn(NULL, sizeof(binNum), a)); - AssertNull(BN_bin2bn(binNum, -1, a)); - AssertNull(BN_bin2bn(binNum, -1, NULL)); - AssertNull(BN_bin2bn(binNum, sizeof(binNum), &emptyBN)); - - AssertIntEQ(BN_hex2bn(NULL, NULL), 0); - AssertIntEQ(BN_hex2bn(NULL, numberStr), 0); - AssertIntEQ(BN_hex2bn(&a, NULL), 0); - AssertIntEQ(BN_hex2bn(&a, emptyStr), 0); - AssertIntEQ(BN_hex2bn(&a, badStr), 0); - AssertIntEQ(BN_hex2bn(&c, badStr), 0); - - AssertIntEQ(BN_dec2bn(NULL, NULL), 0); - AssertIntEQ(BN_dec2bn(NULL, numberStr), 0); - AssertIntEQ(BN_dec2bn(&a, NULL), 0); - AssertIntEQ(BN_dec2bn(&a, emptyStr), 0); - AssertIntEQ(BN_dec2bn(&a, badStr), 0); - AssertIntEQ(BN_dec2bn(&c, badStr), 0); - - AssertIntEQ(BN_set_word(a, 2), 1); - - AssertIntEQ(BN_bn2bin(a, NULL), 1); - AssertIntEQ(BN_bn2bin(a, outNum), 1); - AssertNotNull(BN_bin2bn(outNum, 1, b)); - AssertIntEQ(BN_cmp(a, b), 0); - AssertNotNull(BN_bin2bn(binNum, sizeof(binNum), b)); - AssertIntEQ(BN_cmp(a, b), -1); - - AssertNotNull(str = BN_bn2hex(a)); - AssertNotNull(BN_hex2bn(&b, str)); - AssertIntEQ(BN_cmp(a, b), 0); - AssertNotNull(BN_hex2bn(&b, numberStr)); - AssertIntEQ(BN_cmp(a, b), -1); + ExpectIntEQ(BN_bn2bin(NULL, NULL), -1); + ExpectIntEQ(BN_bn2bin(&emptyBN, NULL), -1); + ExpectIntEQ(BN_bn2bin(NULL, outNum), -1); + ExpectIntEQ(BN_bn2bin(&emptyBN, outNum), -1); + ExpectNull(BN_bn2hex(NULL)); + ExpectNull(BN_bn2hex(&emptyBN)); + ExpectNull(BN_bn2dec(NULL)); + ExpectNull(BN_bn2dec(&emptyBN)); + + ExpectNull(BN_bin2bn(NULL, sizeof(binNum), NULL)); + ExpectNull(BN_bin2bn(NULL, sizeof(binNum), a)); + ExpectNull(BN_bin2bn(binNum, -1, a)); + ExpectNull(BN_bin2bn(binNum, -1, NULL)); + ExpectNull(BN_bin2bn(binNum, sizeof(binNum), &emptyBN)); + + ExpectIntEQ(BN_hex2bn(NULL, NULL), 0); + ExpectIntEQ(BN_hex2bn(NULL, numberStr), 0); + ExpectIntEQ(BN_hex2bn(&a, NULL), 0); + ExpectIntEQ(BN_hex2bn(&a, emptyStr), 0); + ExpectIntEQ(BN_hex2bn(&a, badStr), 0); + ExpectIntEQ(BN_hex2bn(&c, badStr), 0); + + ExpectIntEQ(BN_dec2bn(NULL, NULL), 0); + ExpectIntEQ(BN_dec2bn(NULL, numberStr), 0); + ExpectIntEQ(BN_dec2bn(&a, NULL), 0); + ExpectIntEQ(BN_dec2bn(&a, emptyStr), 0); + ExpectIntEQ(BN_dec2bn(&a, badStr), 0); + ExpectIntEQ(BN_dec2bn(&c, badStr), 0); + + ExpectIntEQ(BN_set_word(a, 2), 1); + + ExpectIntEQ(BN_bn2bin(a, NULL), 1); + ExpectIntEQ(BN_bn2bin(a, outNum), 1); + ExpectNotNull(BN_bin2bn(outNum, 1, b)); + ExpectIntEQ(BN_cmp(a, b), 0); + ExpectNotNull(BN_bin2bn(binNum, sizeof(binNum), b)); + ExpectIntEQ(BN_cmp(a, b), -1); + + ExpectNotNull(str = BN_bn2hex(a)); + ExpectNotNull(BN_hex2bn(&b, str)); + ExpectIntEQ(BN_cmp(a, b), 0); + ExpectNotNull(BN_hex2bn(&b, numberStr)); + ExpectIntEQ(BN_cmp(a, b), -1); XFREE(str, NULL, DYNAMIC_TYPE_OPENSSL); #if defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) - AssertNotNull(str = BN_bn2dec(a)); - AssertStrEQ(str, twoStr); + ExpectNotNull(str = BN_bn2dec(a)); + ExpectStrEQ(str, twoStr); XFREE(str, NULL, DYNAMIC_TYPE_OPENSSL); + str = NULL; #ifndef NO_RSA - AssertNotNull(str = BN_bn2dec(a)); - AssertNotNull(BN_dec2bn(&b, str)); - AssertIntEQ(BN_cmp(a, b), 0); - AssertNotNull(BN_dec2bn(&b, numberStr)); - AssertIntEQ(BN_cmp(a, b), -1); + ExpectNotNull(str = BN_bn2dec(a)); + ExpectNotNull(BN_dec2bn(&b, str)); + ExpectIntEQ(BN_cmp(a, b), 0); + ExpectNotNull(BN_dec2bn(&b, numberStr)); + ExpectIntEQ(BN_cmp(a, b), -1); XFREE(str, NULL, DYNAMIC_TYPE_OPENSSL); + str = NULL; #else /* No implementation - fail with good parameters. */ - AssertIntEQ(BN_dec2bn(&a, numberStr), 0); + ExpectIntEQ(BN_dec2bn(&a, numberStr), 0); #endif #endif BN_free(b); BN_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_ASN) */ return res; } @@ -40477,85 +40406,86 @@ static int test_wolfSSL_BN_word(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && !defined(WOLFSSL_SP_MATH) - BIGNUM* a; - BIGNUM* b; - BIGNUM* c; + EXPECT_DECLS; + BIGNUM* a = NULL; + BIGNUM* b = NULL; + BIGNUM* c = NULL; BIGNUM av; - AssertNotNull(a = BN_new()); - AssertNotNull(b = BN_new()); - AssertNotNull(c = BN_new()); + ExpectNotNull(a = BN_new()); + ExpectNotNull(b = BN_new()); + ExpectNotNull(c = BN_new()); XMEMSET(&av, 0, sizeof(av)); /* Invalid parameter. */ - AssertIntEQ(BN_add_word(NULL, 3), 0); - AssertIntEQ(BN_add_word(&av, 3), 0); - AssertIntEQ(BN_sub_word(NULL, 3), 0); - AssertIntEQ(BN_sub_word(&av, 3), 0); - AssertIntEQ(BN_set_word(NULL, 3), 0); - AssertIntEQ(BN_set_word(&av, 3), 0); - AssertIntEQ(BN_get_word(NULL), 0); - AssertIntEQ(BN_get_word(&av), 0); - AssertIntEQ(BN_is_word(NULL, 3), 0); - AssertIntEQ(BN_is_word(&av, 3), 0); + ExpectIntEQ(BN_add_word(NULL, 3), 0); + ExpectIntEQ(BN_add_word(&av, 3), 0); + ExpectIntEQ(BN_sub_word(NULL, 3), 0); + ExpectIntEQ(BN_sub_word(&av, 3), 0); + ExpectIntEQ(BN_set_word(NULL, 3), 0); + ExpectIntEQ(BN_set_word(&av, 3), 0); + ExpectIntEQ(BN_get_word(NULL), 0); + ExpectIntEQ(BN_get_word(&av), 0); + ExpectIntEQ(BN_is_word(NULL, 3), 0); + ExpectIntEQ(BN_is_word(&av, 3), 0); #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_RSA) || !defined(NO_DH) || \ !defined(NO_DSA)) - AssertIntEQ(BN_mod_word(NULL, 3), -1); - AssertIntEQ(BN_mod_word(&av, 3), -1); + ExpectIntEQ(BN_mod_word(NULL, 3), -1); + ExpectIntEQ(BN_mod_word(&av, 3), -1); #endif - AssertIntEQ(BN_one(NULL), 0); - AssertIntEQ(BN_one(&av), 0); + ExpectIntEQ(BN_one(NULL), 0); + ExpectIntEQ(BN_one(&av), 0); BN_zero(NULL); BN_zero(&av); - AssertIntEQ(BN_is_one(NULL), 0); - AssertIntEQ(BN_is_one(&av), 0); - AssertIntEQ(BN_is_zero(NULL), 0); - AssertIntEQ(BN_is_zero(&av), 0); + ExpectIntEQ(BN_is_one(NULL), 0); + ExpectIntEQ(BN_is_one(&av), 0); + ExpectIntEQ(BN_is_zero(NULL), 0); + ExpectIntEQ(BN_is_zero(&av), 0); - AssertIntEQ(BN_set_word(a, 3), 1); - AssertIntEQ(BN_set_word(b, 2), 1); - AssertIntEQ(BN_set_word(c, 5), 1); + ExpectIntEQ(BN_set_word(a, 3), 1); + ExpectIntEQ(BN_set_word(b, 2), 1); + ExpectIntEQ(BN_set_word(c, 5), 1); /* a + 3 = */ - AssertIntEQ(BN_add_word(a, 3), 1); + ExpectIntEQ(BN_add_word(a, 3), 1); /* check result 3 + 3*/ - AssertIntEQ(BN_get_word(a), 6); - AssertIntEQ(BN_is_word(a, 6), 1); - AssertIntEQ(BN_is_word(a, 5), 0); + ExpectIntEQ(BN_get_word(a), 6); + ExpectIntEQ(BN_is_word(a, 6), 1); + ExpectIntEQ(BN_is_word(a, 5), 0); /* set a back to 3 */ - AssertIntEQ(BN_set_word(a, 3), 1); + ExpectIntEQ(BN_set_word(a, 3), 1); /* a - 3 = */ - AssertIntEQ(BN_sub_word(a, 3), 1); + ExpectIntEQ(BN_sub_word(a, 3), 1); /* check result 3 - 3*/ - AssertIntEQ(BN_get_word(a), 0); + ExpectIntEQ(BN_get_word(a), 0); - AssertIntEQ(BN_one(a), 1); - AssertIntEQ(BN_is_word(a, 1), 1); - AssertIntEQ(BN_is_word(a, 0), 0); - AssertIntEQ(BN_is_one(a), 1); - AssertIntEQ(BN_is_zero(a), 0); + ExpectIntEQ(BN_one(a), 1); + ExpectIntEQ(BN_is_word(a, 1), 1); + ExpectIntEQ(BN_is_word(a, 0), 0); + ExpectIntEQ(BN_is_one(a), 1); + ExpectIntEQ(BN_is_zero(a), 0); BN_zero(a); - AssertIntEQ(BN_is_word(a, 0), 1); - AssertIntEQ(BN_is_word(a, 1), 0); - AssertIntEQ(BN_is_zero(a), 1); - AssertIntEQ(BN_is_one(a), 0); + ExpectIntEQ(BN_is_word(a, 0), 1); + ExpectIntEQ(BN_is_word(a, 1), 0); + ExpectIntEQ(BN_is_zero(a), 1); + ExpectIntEQ(BN_is_one(a), 0); #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_RSA) || !defined(NO_DH) || \ !defined(NO_DSA)) - AssertIntEQ(BN_set_word(a, 5), 1); - AssertIntEQ(BN_mod_word(a, 3), 2); - AssertIntEQ(BN_mod_word(a, 0), -1); + ExpectIntEQ(BN_set_word(a, 5), 1); + ExpectIntEQ(BN_mod_word(a, 3), 2); + ExpectIntEQ(BN_mod_word(a, 0), -1); #endif BN_free(c); BN_free(b); BN_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* defined(OPENSSL_EXTRA) && !defined(NO_ASN) */ return res; } @@ -40565,52 +40495,53 @@ static int test_wolfSSL_BN_bits(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) - BIGNUM* a; + EXPECT_DECLS; + BIGNUM* a = NULL; BIGNUM emptyBN; /* Setup */ XMEMSET(&emptyBN, 0, sizeof(emptyBN)); - AssertNotNull(a = BN_new()); + ExpectNotNull(a = BN_new()); /* Invalid parameters. */ - AssertIntEQ(BN_set_bit(NULL, 1), 0); - AssertIntEQ(BN_set_bit(&emptyBN, 1), 0); - AssertIntEQ(BN_set_bit(a, -1), 0); - AssertIntEQ(BN_clear_bit(NULL, 1), 0); - AssertIntEQ(BN_clear_bit(&emptyBN, 1), 0); - AssertIntEQ(BN_clear_bit(a, -1), 0); - AssertIntEQ(BN_is_bit_set(NULL, 1), 0); - AssertIntEQ(BN_is_bit_set(&emptyBN, 1), 0); - AssertIntEQ(BN_is_bit_set(a, -1), 0); - AssertIntEQ(BN_is_odd(NULL), 0); - AssertIntEQ(BN_is_odd(&emptyBN), 0); - - AssertIntEQ(BN_set_word(a, 0), 1); - AssertIntEQ(BN_is_zero(a), 1); - AssertIntEQ(BN_set_bit(a, 0x45), 1); - AssertIntEQ(BN_is_zero(a), 0); - AssertIntEQ(BN_is_bit_set(a, 0x45), 1); - AssertIntEQ(BN_clear_bit(a, 0x45), 1); - AssertIntEQ(BN_is_bit_set(a, 0x45), 0); - AssertIntEQ(BN_is_zero(a), 1); - - AssertIntEQ(BN_set_bit(a, 0), 1); - AssertIntEQ(BN_is_odd(a), 1); - AssertIntEQ(BN_clear_bit(a, 0), 1); - AssertIntEQ(BN_is_odd(a), 0); - AssertIntEQ(BN_set_bit(a, 1), 1); - AssertIntEQ(BN_is_odd(a), 0); - - AssertIntEQ(BN_set_bit(a, 129), 1); - AssertIntEQ(BN_get_word(a), WOLFSSL_BN_MAX_VAL); + ExpectIntEQ(BN_set_bit(NULL, 1), 0); + ExpectIntEQ(BN_set_bit(&emptyBN, 1), 0); + ExpectIntEQ(BN_set_bit(a, -1), 0); + ExpectIntEQ(BN_clear_bit(NULL, 1), 0); + ExpectIntEQ(BN_clear_bit(&emptyBN, 1), 0); + ExpectIntEQ(BN_clear_bit(a, -1), 0); + ExpectIntEQ(BN_is_bit_set(NULL, 1), 0); + ExpectIntEQ(BN_is_bit_set(&emptyBN, 1), 0); + ExpectIntEQ(BN_is_bit_set(a, -1), 0); + ExpectIntEQ(BN_is_odd(NULL), 0); + ExpectIntEQ(BN_is_odd(&emptyBN), 0); + + ExpectIntEQ(BN_set_word(a, 0), 1); + ExpectIntEQ(BN_is_zero(a), 1); + ExpectIntEQ(BN_set_bit(a, 0x45), 1); + ExpectIntEQ(BN_is_zero(a), 0); + ExpectIntEQ(BN_is_bit_set(a, 0x45), 1); + ExpectIntEQ(BN_clear_bit(a, 0x45), 1); + ExpectIntEQ(BN_is_bit_set(a, 0x45), 0); + ExpectIntEQ(BN_is_zero(a), 1); + + ExpectIntEQ(BN_set_bit(a, 0), 1); + ExpectIntEQ(BN_is_odd(a), 1); + ExpectIntEQ(BN_clear_bit(a, 0), 1); + ExpectIntEQ(BN_is_odd(a), 0); + ExpectIntEQ(BN_set_bit(a, 1), 1); + ExpectIntEQ(BN_is_odd(a), 0); + + ExpectIntEQ(BN_set_bit(a, 129), 1); + ExpectIntEQ(BN_get_word(a), WOLFSSL_BN_MAX_VAL); #ifndef NO_WOLFSSL_STUB - AssertIntEQ(BN_mask_bits(a, 1), 0); + ExpectIntEQ(BN_mask_bits(a, 1), 0); #endif BN_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40620,48 +40551,49 @@ static int test_wolfSSL_BN_shift(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) - BIGNUM* a; - BIGNUM* b; + EXPECT_DECLS; + BIGNUM* a = NULL; + BIGNUM* b = NULL; BIGNUM emptyBN; /* Setup */ XMEMSET(&emptyBN, 0, sizeof(emptyBN)); - AssertNotNull(a = BN_new()); - AssertNotNull(b = BN_new()); + ExpectNotNull(a = BN_new()); + ExpectNotNull(b = BN_new()); /* Invalid parameters. */ - AssertIntEQ(BN_lshift(NULL, NULL, 1), 0); - AssertIntEQ(BN_lshift(&emptyBN, NULL, 1), 0); - AssertIntEQ(BN_lshift(NULL, &emptyBN, 1), 0); - AssertIntEQ(BN_lshift(b, NULL, 1), 0); - AssertIntEQ(BN_lshift(b, &emptyBN, 1), 0); - AssertIntEQ(BN_lshift(NULL, a, 1), 0); - AssertIntEQ(BN_lshift(&emptyBN, a, 1), 0); - AssertIntEQ(BN_lshift(b, a, -1), 0); - - AssertIntEQ(BN_rshift(NULL, NULL, 1), 0); - AssertIntEQ(BN_rshift(&emptyBN, NULL, 1), 0); - AssertIntEQ(BN_rshift(NULL, &emptyBN, 1), 0); - AssertIntEQ(BN_rshift(b, NULL, 1), 0); - AssertIntEQ(BN_rshift(b, &emptyBN, 1), 0); - AssertIntEQ(BN_rshift(NULL, a, 1), 0); - AssertIntEQ(BN_rshift(&emptyBN, a, 1), 0); - AssertIntEQ(BN_rshift(b, a, -1), 0); - - AssertIntEQ(BN_set_word(a, 1), 1); - AssertIntEQ(BN_lshift(b, a, 1), 1); - AssertIntEQ(BN_is_word(b, 2), 1); - AssertIntEQ(BN_lshift(a, a, 1), 1); - AssertIntEQ(BN_is_word(a, 2), 1); - AssertIntEQ(BN_rshift(b, a, 1), 1); - AssertIntEQ(BN_is_word(b, 1), 1); - AssertIntEQ(BN_rshift(a, a, 1), 1); - AssertIntEQ(BN_is_word(a, 1), 1); + ExpectIntEQ(BN_lshift(NULL, NULL, 1), 0); + ExpectIntEQ(BN_lshift(&emptyBN, NULL, 1), 0); + ExpectIntEQ(BN_lshift(NULL, &emptyBN, 1), 0); + ExpectIntEQ(BN_lshift(b, NULL, 1), 0); + ExpectIntEQ(BN_lshift(b, &emptyBN, 1), 0); + ExpectIntEQ(BN_lshift(NULL, a, 1), 0); + ExpectIntEQ(BN_lshift(&emptyBN, a, 1), 0); + ExpectIntEQ(BN_lshift(b, a, -1), 0); + + ExpectIntEQ(BN_rshift(NULL, NULL, 1), 0); + ExpectIntEQ(BN_rshift(&emptyBN, NULL, 1), 0); + ExpectIntEQ(BN_rshift(NULL, &emptyBN, 1), 0); + ExpectIntEQ(BN_rshift(b, NULL, 1), 0); + ExpectIntEQ(BN_rshift(b, &emptyBN, 1), 0); + ExpectIntEQ(BN_rshift(NULL, a, 1), 0); + ExpectIntEQ(BN_rshift(&emptyBN, a, 1), 0); + ExpectIntEQ(BN_rshift(b, a, -1), 0); + + ExpectIntEQ(BN_set_word(a, 1), 1); + ExpectIntEQ(BN_lshift(b, a, 1), 1); + ExpectIntEQ(BN_is_word(b, 2), 1); + ExpectIntEQ(BN_lshift(a, a, 1), 1); + ExpectIntEQ(BN_is_word(a, 2), 1); + ExpectIntEQ(BN_rshift(b, a, 1), 1); + ExpectIntEQ(BN_is_word(b, 1), 1); + ExpectIntEQ(BN_rshift(a, a, 1), 1); + ExpectIntEQ(BN_is_word(a, 1), 1); BN_free(b); BN_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40671,129 +40603,130 @@ static int test_wolfSSL_BN_math(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) - BIGNUM* a; - BIGNUM* b; - BIGNUM* r; - BIGNUM* rem; + EXPECT_DECLS; + BIGNUM* a = NULL; + BIGNUM* b = NULL; + BIGNUM* r = NULL; + BIGNUM* rem = NULL; BIGNUM emptyBN; BN_ULONG val1; BN_ULONG val2; /* Setup */ XMEMSET(&emptyBN, 0, sizeof(emptyBN)); - AssertNotNull(a = BN_new()); - AssertNotNull(b = BN_new()); - AssertNotNull(r = BN_new()); - AssertNotNull(rem = BN_new()); + ExpectNotNull(a = BN_new()); + ExpectNotNull(b = BN_new()); + ExpectNotNull(r = BN_new()); + ExpectNotNull(rem = BN_new()); /* Invalid parameters. */ - AssertIntEQ(BN_add(NULL, NULL, NULL), 0); - AssertIntEQ(BN_add(r, NULL, NULL), 0); - AssertIntEQ(BN_add(NULL, a, NULL), 0); - AssertIntEQ(BN_add(NULL, NULL, b), 0); - AssertIntEQ(BN_add(r, a, NULL), 0); - AssertIntEQ(BN_add(r, NULL, b), 0); - AssertIntEQ(BN_add(NULL, a, b), 0); - - AssertIntEQ(BN_add(&emptyBN, &emptyBN, &emptyBN), 0); - AssertIntEQ(BN_add(r, &emptyBN, &emptyBN), 0); - AssertIntEQ(BN_add(&emptyBN, a, &emptyBN), 0); - AssertIntEQ(BN_add(&emptyBN, &emptyBN, b), 0); - AssertIntEQ(BN_add(r, a, &emptyBN), 0); - AssertIntEQ(BN_add(r, &emptyBN, b), 0); - AssertIntEQ(BN_add(&emptyBN, a, b), 0); - - AssertIntEQ(BN_sub(NULL, NULL, NULL), 0); - AssertIntEQ(BN_sub(r, NULL, NULL), 0); - AssertIntEQ(BN_sub(NULL, a, NULL), 0); - AssertIntEQ(BN_sub(NULL, NULL, b), 0); - AssertIntEQ(BN_sub(r, a, NULL), 0); - AssertIntEQ(BN_sub(r, NULL, b), 0); - AssertIntEQ(BN_sub(NULL, a, b), 0); - - AssertIntEQ(BN_sub(&emptyBN, &emptyBN, &emptyBN), 0); - AssertIntEQ(BN_sub(r, &emptyBN, &emptyBN), 0); - AssertIntEQ(BN_sub(&emptyBN, a, &emptyBN), 0); - AssertIntEQ(BN_sub(&emptyBN, &emptyBN, b), 0); - AssertIntEQ(BN_sub(r, a, &emptyBN), 0); - AssertIntEQ(BN_sub(r, &emptyBN, b), 0); - AssertIntEQ(BN_sub(&emptyBN, a, b), 0); - - AssertIntEQ(BN_mul(NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mul(r, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mul(NULL, a, NULL, NULL), 0); - AssertIntEQ(BN_mul(NULL, NULL, b, NULL), 0); - AssertIntEQ(BN_mul(r, a, NULL, NULL), 0); - AssertIntEQ(BN_mul(r, NULL, b, NULL), 0); - AssertIntEQ(BN_mul(NULL, a, b, NULL), 0); - - AssertIntEQ(BN_mul(&emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mul(r, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mul(&emptyBN, a, &emptyBN, NULL), 0); - AssertIntEQ(BN_mul(&emptyBN, &emptyBN, b, NULL), 0); - AssertIntEQ(BN_mul(r, a, &emptyBN, NULL), 0); - AssertIntEQ(BN_mul(r, &emptyBN, b, NULL), 0); - AssertIntEQ(BN_mul(&emptyBN, a, b, NULL), 0); - - AssertIntEQ(BN_div(NULL, NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_div(r, NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_div(NULL, rem, NULL, NULL, NULL), 0); - AssertIntEQ(BN_div(NULL, NULL, a, NULL, NULL), 0); - AssertIntEQ(BN_div(NULL, NULL, NULL, b, NULL), 0); - AssertIntEQ(BN_div(NULL, rem, a, b, NULL), 0); - AssertIntEQ(BN_div(r, NULL, a, b, NULL), 0); - AssertIntEQ(BN_div(r, rem, NULL, b, NULL), 0); - AssertIntEQ(BN_div(r, rem, a, NULL, NULL), 0); - - AssertIntEQ(BN_div(&emptyBN, &emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_div(r, &emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_div(&emptyBN, rem, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_div(&emptyBN, &emptyBN, a, &emptyBN, NULL), 0); - AssertIntEQ(BN_div(&emptyBN, &emptyBN, &emptyBN, b, NULL), 0); - AssertIntEQ(BN_div(&emptyBN, rem, a, b, NULL), 0); - AssertIntEQ(BN_div(r, &emptyBN, a, b, NULL), 0); - AssertIntEQ(BN_div(r, rem, &emptyBN, b, NULL), 0); - AssertIntEQ(BN_div(r, rem, a, &emptyBN, NULL), 0); - - AssertIntEQ(BN_mod(NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod(r, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod(NULL, a, NULL, NULL), 0); - AssertIntEQ(BN_mod(NULL, NULL, b, NULL), 0); - AssertIntEQ(BN_mod(r, a, NULL, NULL), 0); - AssertIntEQ(BN_mod(r, NULL, b, NULL), 0); - AssertIntEQ(BN_mod(NULL, a, b, NULL), 0); - - AssertIntEQ(BN_mod(&emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod(r, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod(&emptyBN, a, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod(&emptyBN, &emptyBN, b, NULL), 0); - AssertIntEQ(BN_mod(r, a, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod(r, &emptyBN, b, NULL), 0); - AssertIntEQ(BN_mod(&emptyBN, a, b, NULL), 0); + ExpectIntEQ(BN_add(NULL, NULL, NULL), 0); + ExpectIntEQ(BN_add(r, NULL, NULL), 0); + ExpectIntEQ(BN_add(NULL, a, NULL), 0); + ExpectIntEQ(BN_add(NULL, NULL, b), 0); + ExpectIntEQ(BN_add(r, a, NULL), 0); + ExpectIntEQ(BN_add(r, NULL, b), 0); + ExpectIntEQ(BN_add(NULL, a, b), 0); + + ExpectIntEQ(BN_add(&emptyBN, &emptyBN, &emptyBN), 0); + ExpectIntEQ(BN_add(r, &emptyBN, &emptyBN), 0); + ExpectIntEQ(BN_add(&emptyBN, a, &emptyBN), 0); + ExpectIntEQ(BN_add(&emptyBN, &emptyBN, b), 0); + ExpectIntEQ(BN_add(r, a, &emptyBN), 0); + ExpectIntEQ(BN_add(r, &emptyBN, b), 0); + ExpectIntEQ(BN_add(&emptyBN, a, b), 0); + + ExpectIntEQ(BN_sub(NULL, NULL, NULL), 0); + ExpectIntEQ(BN_sub(r, NULL, NULL), 0); + ExpectIntEQ(BN_sub(NULL, a, NULL), 0); + ExpectIntEQ(BN_sub(NULL, NULL, b), 0); + ExpectIntEQ(BN_sub(r, a, NULL), 0); + ExpectIntEQ(BN_sub(r, NULL, b), 0); + ExpectIntEQ(BN_sub(NULL, a, b), 0); + + ExpectIntEQ(BN_sub(&emptyBN, &emptyBN, &emptyBN), 0); + ExpectIntEQ(BN_sub(r, &emptyBN, &emptyBN), 0); + ExpectIntEQ(BN_sub(&emptyBN, a, &emptyBN), 0); + ExpectIntEQ(BN_sub(&emptyBN, &emptyBN, b), 0); + ExpectIntEQ(BN_sub(r, a, &emptyBN), 0); + ExpectIntEQ(BN_sub(r, &emptyBN, b), 0); + ExpectIntEQ(BN_sub(&emptyBN, a, b), 0); + + ExpectIntEQ(BN_mul(NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mul(r, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mul(NULL, a, NULL, NULL), 0); + ExpectIntEQ(BN_mul(NULL, NULL, b, NULL), 0); + ExpectIntEQ(BN_mul(r, a, NULL, NULL), 0); + ExpectIntEQ(BN_mul(r, NULL, b, NULL), 0); + ExpectIntEQ(BN_mul(NULL, a, b, NULL), 0); + + ExpectIntEQ(BN_mul(&emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mul(r, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mul(&emptyBN, a, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mul(&emptyBN, &emptyBN, b, NULL), 0); + ExpectIntEQ(BN_mul(r, a, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mul(r, &emptyBN, b, NULL), 0); + ExpectIntEQ(BN_mul(&emptyBN, a, b, NULL), 0); + + ExpectIntEQ(BN_div(NULL, NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_div(r, NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_div(NULL, rem, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_div(NULL, NULL, a, NULL, NULL), 0); + ExpectIntEQ(BN_div(NULL, NULL, NULL, b, NULL), 0); + ExpectIntEQ(BN_div(NULL, rem, a, b, NULL), 0); + ExpectIntEQ(BN_div(r, NULL, a, b, NULL), 0); + ExpectIntEQ(BN_div(r, rem, NULL, b, NULL), 0); + ExpectIntEQ(BN_div(r, rem, a, NULL, NULL), 0); + + ExpectIntEQ(BN_div(&emptyBN, &emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_div(r, &emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_div(&emptyBN, rem, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_div(&emptyBN, &emptyBN, a, &emptyBN, NULL), 0); + ExpectIntEQ(BN_div(&emptyBN, &emptyBN, &emptyBN, b, NULL), 0); + ExpectIntEQ(BN_div(&emptyBN, rem, a, b, NULL), 0); + ExpectIntEQ(BN_div(r, &emptyBN, a, b, NULL), 0); + ExpectIntEQ(BN_div(r, rem, &emptyBN, b, NULL), 0); + ExpectIntEQ(BN_div(r, rem, a, &emptyBN, NULL), 0); + + ExpectIntEQ(BN_mod(NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod(r, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod(NULL, a, NULL, NULL), 0); + ExpectIntEQ(BN_mod(NULL, NULL, b, NULL), 0); + ExpectIntEQ(BN_mod(r, a, NULL, NULL), 0); + ExpectIntEQ(BN_mod(r, NULL, b, NULL), 0); + ExpectIntEQ(BN_mod(NULL, a, b, NULL), 0); + + ExpectIntEQ(BN_mod(&emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod(r, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod(&emptyBN, a, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod(&emptyBN, &emptyBN, b, NULL), 0); + ExpectIntEQ(BN_mod(r, a, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod(r, &emptyBN, b, NULL), 0); + ExpectIntEQ(BN_mod(&emptyBN, a, b, NULL), 0); /* END Invalid parameters. */ val1 = 8; val2 = 3; - AssertIntEQ(BN_set_word(a, val1), 1); - AssertIntEQ(BN_set_word(b, val2), 1); - AssertIntEQ(BN_add(r, a, b), 1); - AssertIntEQ(BN_is_word(r, val1 + val2), 1); - AssertIntEQ(BN_sub(r, a, b), 1); - AssertIntEQ(BN_is_word(r, val1 - val2), 1); - AssertIntEQ(BN_mul(r, a, b, NULL), 1); - AssertIntEQ(BN_is_word(r, val1 * val2), 1); - AssertIntEQ(BN_div(r, rem, a, b, NULL), 1); - AssertIntEQ(BN_is_word(r, val1 / val2), 1); - AssertIntEQ(BN_is_word(rem, val1 % val2), 1); - AssertIntEQ(BN_mod(r, a, b, NULL), 1); - AssertIntEQ(BN_is_word(r, val1 % val2), 1); + ExpectIntEQ(BN_set_word(a, val1), 1); + ExpectIntEQ(BN_set_word(b, val2), 1); + ExpectIntEQ(BN_add(r, a, b), 1); + ExpectIntEQ(BN_is_word(r, val1 + val2), 1); + ExpectIntEQ(BN_sub(r, a, b), 1); + ExpectIntEQ(BN_is_word(r, val1 - val2), 1); + ExpectIntEQ(BN_mul(r, a, b, NULL), 1); + ExpectIntEQ(BN_is_word(r, val1 * val2), 1); + ExpectIntEQ(BN_div(r, rem, a, b, NULL), 1); + ExpectIntEQ(BN_is_word(r, val1 / val2), 1); + ExpectIntEQ(BN_is_word(rem, val1 % val2), 1); + ExpectIntEQ(BN_mod(r, a, b, NULL), 1); + ExpectIntEQ(BN_is_word(r, val1 % val2), 1); BN_free(rem); BN_free(r); BN_free(b); BN_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40803,11 +40736,12 @@ static int test_wolfSSL_BN_math_mod(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) - BIGNUM* a; - BIGNUM* b; - BIGNUM* m; - BIGNUM* r; - BIGNUM* t; + EXPECT_DECLS; + BIGNUM* a = NULL; + BIGNUM* b = NULL; + BIGNUM* m = NULL; + BIGNUM* r = NULL; + BIGNUM* t = NULL; BIGNUM emptyBN; BN_ULONG val1; BN_ULONG val2; @@ -40815,122 +40749,122 @@ static int test_wolfSSL_BN_math_mod(void) /* Setup */ XMEMSET(&emptyBN, 0, sizeof(emptyBN)); - AssertNotNull(a = BN_new()); - AssertNotNull(b = BN_new()); - AssertNotNull(m = BN_new()); - AssertNotNull(r = BN_new()); + ExpectNotNull(a = BN_new()); + ExpectNotNull(b = BN_new()); + ExpectNotNull(m = BN_new()); + ExpectNotNull(r = BN_new()); /* Invalid parameters. */ - AssertIntEQ(BN_mod_add(NULL, NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_add(r, NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_add(NULL, a, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_add(NULL, NULL, b, NULL, NULL), 0); - AssertIntEQ(BN_mod_add(NULL, NULL, NULL, m, NULL), 0); - AssertIntEQ(BN_mod_add(NULL, a, b, m, NULL), 0); - AssertIntEQ(BN_mod_add(r, NULL, b, m, NULL), 0); - AssertIntEQ(BN_mod_add(r, a, NULL, m, NULL), 0); - AssertIntEQ(BN_mod_add(r, a, m, NULL, NULL), 0); - - AssertIntEQ(BN_mod_add(&emptyBN, &emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_add(r, &emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_add(&emptyBN, a, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_add(&emptyBN, &emptyBN, b, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_add(&emptyBN, &emptyBN, &emptyBN, m, NULL), 0); - AssertIntEQ(BN_mod_add(&emptyBN, a, b, m, NULL), 0); - AssertIntEQ(BN_mod_add(r, &emptyBN, b, m, NULL), 0); - AssertIntEQ(BN_mod_add(r, a, &emptyBN, m, NULL), 0); - AssertIntEQ(BN_mod_add(r, a, m, &emptyBN, NULL), 0); - - AssertIntEQ(BN_mod_mul(NULL, NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_mul(r, NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_mul(NULL, a, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_mul(NULL, NULL, b, NULL, NULL), 0); - AssertIntEQ(BN_mod_mul(NULL, NULL, NULL, m, NULL), 0); - AssertIntEQ(BN_mod_mul(NULL, a, b, m, NULL), 0); - AssertIntEQ(BN_mod_mul(r, NULL, b, m, NULL), 0); - AssertIntEQ(BN_mod_mul(r, a, NULL, m, NULL), 0); - AssertIntEQ(BN_mod_mul(r, a, m, NULL, NULL), 0); - - AssertIntEQ(BN_mod_mul(&emptyBN, &emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_mul(r, &emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_mul(&emptyBN, a, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_mul(&emptyBN, &emptyBN, b, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_mul(&emptyBN, &emptyBN, &emptyBN, m, NULL), 0); - AssertIntEQ(BN_mod_mul(&emptyBN, a, b, m, NULL), 0); - AssertIntEQ(BN_mod_mul(r, &emptyBN, b, m, NULL), 0); - AssertIntEQ(BN_mod_mul(r, a, &emptyBN, m, NULL), 0); - AssertIntEQ(BN_mod_mul(r, a, m, &emptyBN, NULL), 0); - - AssertIntEQ(BN_mod_exp(NULL, NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_exp(r, NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_exp(NULL, a, NULL, NULL, NULL), 0); - AssertIntEQ(BN_mod_exp(NULL, NULL, b, NULL, NULL), 0); - AssertIntEQ(BN_mod_exp(NULL, NULL, NULL, m, NULL), 0); - AssertIntEQ(BN_mod_exp(NULL, a, b, m, NULL), 0); - AssertIntEQ(BN_mod_exp(r, NULL, b, m, NULL), 0); - AssertIntEQ(BN_mod_exp(r, a, NULL, m, NULL), 0); - AssertIntEQ(BN_mod_exp(r, a, m, NULL, NULL), 0); - - AssertIntEQ(BN_mod_exp(&emptyBN, &emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_exp(r, &emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_exp(&emptyBN, a, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_exp(&emptyBN, &emptyBN, b, &emptyBN, NULL), 0); - AssertIntEQ(BN_mod_exp(&emptyBN, &emptyBN, &emptyBN, m, NULL), 0); - AssertIntEQ(BN_mod_exp(&emptyBN, a, b, m, NULL), 0); - AssertIntEQ(BN_mod_exp(r, &emptyBN, b, m, NULL), 0); - AssertIntEQ(BN_mod_exp(r, a, &emptyBN, m, NULL), 0); - AssertIntEQ(BN_mod_exp(r, a, m, &emptyBN, NULL), 0); - - AssertNull(BN_mod_inverse(r, NULL, NULL, NULL)); - AssertNull(BN_mod_inverse(r, a, NULL, NULL)); - AssertNull(BN_mod_inverse(r, NULL, m, NULL)); - AssertNull(BN_mod_inverse(r, NULL, m, NULL)); - AssertNull(BN_mod_inverse(r, a, NULL, NULL)); - - AssertNull(BN_mod_inverse(&emptyBN, &emptyBN, &emptyBN, NULL)); - AssertNull(BN_mod_inverse(r, &emptyBN, &emptyBN, NULL)); - AssertNull(BN_mod_inverse(&emptyBN, a, &emptyBN, NULL)); - AssertNull(BN_mod_inverse(&emptyBN, &emptyBN, m, NULL)); - AssertNull(BN_mod_inverse(&emptyBN, a, m, NULL)); - AssertNull(BN_mod_inverse(r, &emptyBN, m, NULL)); - AssertNull(BN_mod_inverse(r, a, &emptyBN, NULL)); + ExpectIntEQ(BN_mod_add(NULL, NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_add(r, NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_add(NULL, a, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_add(NULL, NULL, b, NULL, NULL), 0); + ExpectIntEQ(BN_mod_add(NULL, NULL, NULL, m, NULL), 0); + ExpectIntEQ(BN_mod_add(NULL, a, b, m, NULL), 0); + ExpectIntEQ(BN_mod_add(r, NULL, b, m, NULL), 0); + ExpectIntEQ(BN_mod_add(r, a, NULL, m, NULL), 0); + ExpectIntEQ(BN_mod_add(r, a, m, NULL, NULL), 0); + + ExpectIntEQ(BN_mod_add(&emptyBN, &emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_add(r, &emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_add(&emptyBN, a, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_add(&emptyBN, &emptyBN, b, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_add(&emptyBN, &emptyBN, &emptyBN, m, NULL), 0); + ExpectIntEQ(BN_mod_add(&emptyBN, a, b, m, NULL), 0); + ExpectIntEQ(BN_mod_add(r, &emptyBN, b, m, NULL), 0); + ExpectIntEQ(BN_mod_add(r, a, &emptyBN, m, NULL), 0); + ExpectIntEQ(BN_mod_add(r, a, m, &emptyBN, NULL), 0); + + ExpectIntEQ(BN_mod_mul(NULL, NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_mul(r, NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_mul(NULL, a, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_mul(NULL, NULL, b, NULL, NULL), 0); + ExpectIntEQ(BN_mod_mul(NULL, NULL, NULL, m, NULL), 0); + ExpectIntEQ(BN_mod_mul(NULL, a, b, m, NULL), 0); + ExpectIntEQ(BN_mod_mul(r, NULL, b, m, NULL), 0); + ExpectIntEQ(BN_mod_mul(r, a, NULL, m, NULL), 0); + ExpectIntEQ(BN_mod_mul(r, a, m, NULL, NULL), 0); + + ExpectIntEQ(BN_mod_mul(&emptyBN, &emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_mul(r, &emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_mul(&emptyBN, a, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_mul(&emptyBN, &emptyBN, b, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_mul(&emptyBN, &emptyBN, &emptyBN, m, NULL), 0); + ExpectIntEQ(BN_mod_mul(&emptyBN, a, b, m, NULL), 0); + ExpectIntEQ(BN_mod_mul(r, &emptyBN, b, m, NULL), 0); + ExpectIntEQ(BN_mod_mul(r, a, &emptyBN, m, NULL), 0); + ExpectIntEQ(BN_mod_mul(r, a, m, &emptyBN, NULL), 0); + + ExpectIntEQ(BN_mod_exp(NULL, NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_exp(r, NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_exp(NULL, a, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_mod_exp(NULL, NULL, b, NULL, NULL), 0); + ExpectIntEQ(BN_mod_exp(NULL, NULL, NULL, m, NULL), 0); + ExpectIntEQ(BN_mod_exp(NULL, a, b, m, NULL), 0); + ExpectIntEQ(BN_mod_exp(r, NULL, b, m, NULL), 0); + ExpectIntEQ(BN_mod_exp(r, a, NULL, m, NULL), 0); + ExpectIntEQ(BN_mod_exp(r, a, m, NULL, NULL), 0); + + ExpectIntEQ(BN_mod_exp(&emptyBN, &emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_exp(r, &emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_exp(&emptyBN, a, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_exp(&emptyBN, &emptyBN, b, &emptyBN, NULL), 0); + ExpectIntEQ(BN_mod_exp(&emptyBN, &emptyBN, &emptyBN, m, NULL), 0); + ExpectIntEQ(BN_mod_exp(&emptyBN, a, b, m, NULL), 0); + ExpectIntEQ(BN_mod_exp(r, &emptyBN, b, m, NULL), 0); + ExpectIntEQ(BN_mod_exp(r, a, &emptyBN, m, NULL), 0); + ExpectIntEQ(BN_mod_exp(r, a, m, &emptyBN, NULL), 0); + + ExpectNull(BN_mod_inverse(r, NULL, NULL, NULL)); + ExpectNull(BN_mod_inverse(r, a, NULL, NULL)); + ExpectNull(BN_mod_inverse(r, NULL, m, NULL)); + ExpectNull(BN_mod_inverse(r, NULL, m, NULL)); + ExpectNull(BN_mod_inverse(r, a, NULL, NULL)); + + ExpectNull(BN_mod_inverse(&emptyBN, &emptyBN, &emptyBN, NULL)); + ExpectNull(BN_mod_inverse(r, &emptyBN, &emptyBN, NULL)); + ExpectNull(BN_mod_inverse(&emptyBN, a, &emptyBN, NULL)); + ExpectNull(BN_mod_inverse(&emptyBN, &emptyBN, m, NULL)); + ExpectNull(BN_mod_inverse(&emptyBN, a, m, NULL)); + ExpectNull(BN_mod_inverse(r, &emptyBN, m, NULL)); + ExpectNull(BN_mod_inverse(r, a, &emptyBN, NULL)); /* END Invalid parameters. */ val1 = 9; val2 = 13; val3 = 5; - AssertIntEQ(BN_set_word(a, val1), 1); - AssertIntEQ(BN_set_word(b, val2), 1); - AssertIntEQ(BN_set_word(m, val3), 1); - AssertIntEQ(BN_mod_add(r, a, b, m, NULL), 1); - AssertIntEQ(BN_is_word(r, (val1 + val2) % val3), 1); - AssertIntEQ(BN_mod_mul(r, a, b, m, NULL), 1); - AssertIntEQ(BN_is_word(r, (val1 * val2) % val3), 1); - - AssertIntEQ(BN_set_word(a, 2), 1); - AssertIntEQ(BN_set_word(b, 3), 1); - AssertIntEQ(BN_set_word(m, 5), 1); + ExpectIntEQ(BN_set_word(a, val1), 1); + ExpectIntEQ(BN_set_word(b, val2), 1); + ExpectIntEQ(BN_set_word(m, val3), 1); + ExpectIntEQ(BN_mod_add(r, a, b, m, NULL), 1); + ExpectIntEQ(BN_is_word(r, (val1 + val2) % val3), 1); + ExpectIntEQ(BN_mod_mul(r, a, b, m, NULL), 1); + ExpectIntEQ(BN_is_word(r, (val1 * val2) % val3), 1); + + ExpectIntEQ(BN_set_word(a, 2), 1); + ExpectIntEQ(BN_set_word(b, 3), 1); + ExpectIntEQ(BN_set_word(m, 5), 1); /* (2 ^ 3) % 5 = 8 % 5 = 3 */ - AssertIntEQ(BN_mod_exp(r, a, b, m, NULL), 1); - AssertIntEQ(BN_is_word(r, 3), 1); + ExpectIntEQ(BN_mod_exp(r, a, b, m, NULL), 1); + ExpectIntEQ(BN_is_word(r, 3), 1); /* (2 * 3) % 5 = 6 % 5 = 1 => inv = 3 */ - AssertNotNull(BN_mod_inverse(r, a, m, NULL)); - AssertIntEQ(BN_is_word(r, 3), 1); - AssertNotNull(t = BN_mod_inverse(NULL, a, m, NULL)); - AssertIntEQ(BN_is_word(t, 3), 1); + ExpectNotNull(BN_mod_inverse(r, a, m, NULL)); + ExpectIntEQ(BN_is_word(r, 3), 1); + ExpectNotNull(t = BN_mod_inverse(NULL, a, m, NULL)); + ExpectIntEQ(BN_is_word(t, 3), 1); BN_free(t); /* No inverse case. No inverse when a divides b. */ - AssertIntEQ(BN_set_word(a, 3), 1); - AssertIntEQ(BN_set_word(m, 9), 1); - AssertNull(BN_mod_inverse(r, a, m, NULL)); + ExpectIntEQ(BN_set_word(a, 3), 1); + ExpectIntEQ(BN_set_word(m, 9), 1); + ExpectNull(BN_mod_inverse(r, a, m, NULL)); BN_free(r); BN_free(m); BN_free(b); BN_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -40941,56 +40875,57 @@ static int test_wolfSSL_BN_math_other(void) #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) - BIGNUM* a; - BIGNUM* b; - BIGNUM* r; + EXPECT_DECLS; + BIGNUM* a = NULL; + BIGNUM* b = NULL; + BIGNUM* r = NULL; BIGNUM emptyBN; /* Setup */ XMEMSET(&emptyBN, 0, sizeof(emptyBN)); - AssertNotNull(a = BN_new()); - AssertNotNull(b = BN_new()); - AssertNotNull(r = BN_new()); + ExpectNotNull(a = BN_new()); + ExpectNotNull(b = BN_new()); + ExpectNotNull(r = BN_new()); /* Invalid parameters. */ - AssertIntEQ(BN_gcd(NULL, NULL, NULL, NULL), 0); - AssertIntEQ(BN_gcd(r, NULL, NULL, NULL), 0); - AssertIntEQ(BN_gcd(NULL, a, NULL, NULL), 0); - AssertIntEQ(BN_gcd(NULL, NULL, b, NULL), 0); - AssertIntEQ(BN_gcd(NULL, a, b, NULL), 0); - AssertIntEQ(BN_gcd(r, NULL, b, NULL), 0); - AssertIntEQ(BN_gcd(r, a, NULL, NULL), 0); - - AssertIntEQ(BN_gcd(&emptyBN, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_gcd(r, &emptyBN, &emptyBN, NULL), 0); - AssertIntEQ(BN_gcd(&emptyBN, a, &emptyBN, NULL), 0); - AssertIntEQ(BN_gcd(&emptyBN, &emptyBN, b, NULL), 0); - AssertIntEQ(BN_gcd(&emptyBN, a, b, NULL), 0); - AssertIntEQ(BN_gcd(r, &emptyBN, b, NULL), 0); - AssertIntEQ(BN_gcd(r, a, &emptyBN, NULL), 0); + ExpectIntEQ(BN_gcd(NULL, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_gcd(r, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_gcd(NULL, a, NULL, NULL), 0); + ExpectIntEQ(BN_gcd(NULL, NULL, b, NULL), 0); + ExpectIntEQ(BN_gcd(NULL, a, b, NULL), 0); + ExpectIntEQ(BN_gcd(r, NULL, b, NULL), 0); + ExpectIntEQ(BN_gcd(r, a, NULL, NULL), 0); + + ExpectIntEQ(BN_gcd(&emptyBN, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_gcd(r, &emptyBN, &emptyBN, NULL), 0); + ExpectIntEQ(BN_gcd(&emptyBN, a, &emptyBN, NULL), 0); + ExpectIntEQ(BN_gcd(&emptyBN, &emptyBN, b, NULL), 0); + ExpectIntEQ(BN_gcd(&emptyBN, a, b, NULL), 0); + ExpectIntEQ(BN_gcd(r, &emptyBN, b, NULL), 0); + ExpectIntEQ(BN_gcd(r, a, &emptyBN, NULL), 0); /* END Invalid parameters. */ /* No comman factors between 2 and 3. */ - AssertIntEQ(BN_set_word(a, 2), 1); - AssertIntEQ(BN_set_word(b, 3), 1); - AssertIntEQ(BN_gcd(r, a, b, NULL), 1); - AssertIntEQ(BN_is_word(r, 1), 1); + ExpectIntEQ(BN_set_word(a, 2), 1); + ExpectIntEQ(BN_set_word(b, 3), 1); + ExpectIntEQ(BN_gcd(r, a, b, NULL), 1); + ExpectIntEQ(BN_is_word(r, 1), 1); /* 3 is largest value that divides both 6 and 9. */ - AssertIntEQ(BN_set_word(a, 6), 1); - AssertIntEQ(BN_set_word(b, 9), 1); - AssertIntEQ(BN_gcd(r, a, b, NULL), 1); - AssertIntEQ(BN_is_word(r, 3), 1); + ExpectIntEQ(BN_set_word(a, 6), 1); + ExpectIntEQ(BN_set_word(b, 9), 1); + ExpectIntEQ(BN_gcd(r, a, b, NULL), 1); + ExpectIntEQ(BN_is_word(r, 3), 1); /* GCD of 0 and 0 is undefined. */ - AssertIntEQ(BN_set_word(a, 0), 1); - AssertIntEQ(BN_set_word(b, 0), 1); - AssertIntEQ(BN_gcd(r, a, b, NULL), 0); + ExpectIntEQ(BN_set_word(a, 0), 1); + ExpectIntEQ(BN_set_word(b, 0), 1); + ExpectIntEQ(BN_gcd(r, a, b, NULL), 0); /* Teardown */ BN_free(r); BN_free(b); BN_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif #endif return res; @@ -41000,146 +40935,147 @@ static int test_wolfSSL_BN_rand(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_NO_BN) - BIGNUM* bn; - BIGNUM* range; + EXPECT_DECLS; + BIGNUM* bn = NULL; + BIGNUM* range = NULL; BIGNUM emptyBN; XMEMSET(&emptyBN, 0, sizeof(emptyBN)); - AssertNotNull(bn = BN_new()); - AssertNotNull(range = BN_new()); + ExpectNotNull(bn = BN_new()); + ExpectNotNull(range = BN_new()); /* Invalid parameters. */ - AssertIntEQ(BN_rand(NULL, -1, 0, 0), 0); - AssertIntEQ(BN_rand(bn, -1, 0, 0), 0); - AssertIntEQ(BN_rand(NULL, 1, 0, 0), 0); - AssertIntEQ(BN_rand(&emptyBN, -1, 0, 0), 0); - AssertIntEQ(BN_rand(bn, -1, 0, 0), 0); - AssertIntEQ(BN_rand(&emptyBN, 1, 0, 0), 0); - - AssertIntEQ(BN_pseudo_rand(NULL, -1, 0, 0), 0); - AssertIntEQ(BN_pseudo_rand(bn, -1, 0, 0), 0); - AssertIntEQ(BN_pseudo_rand(NULL, 1, 0, 0), 0); - AssertIntEQ(BN_pseudo_rand(&emptyBN, -1, 0, 0), 0); - AssertIntEQ(BN_pseudo_rand(bn, -1, 0, 0), 0); - AssertIntEQ(BN_pseudo_rand(&emptyBN, 1, 0, 0), 0); - - AssertIntEQ(BN_rand_range(NULL, NULL), 0); - AssertIntEQ(BN_rand_range(bn, NULL), 0); - AssertIntEQ(BN_rand_range(NULL, range), 0); - AssertIntEQ(BN_rand_range(&emptyBN, &emptyBN), 0); - AssertIntEQ(BN_rand_range(bn, &emptyBN), 0); - AssertIntEQ(BN_rand_range(&emptyBN, range), 0); + ExpectIntEQ(BN_rand(NULL, -1, 0, 0), 0); + ExpectIntEQ(BN_rand(bn, -1, 0, 0), 0); + ExpectIntEQ(BN_rand(NULL, 1, 0, 0), 0); + ExpectIntEQ(BN_rand(&emptyBN, -1, 0, 0), 0); + ExpectIntEQ(BN_rand(bn, -1, 0, 0), 0); + ExpectIntEQ(BN_rand(&emptyBN, 1, 0, 0), 0); + + ExpectIntEQ(BN_pseudo_rand(NULL, -1, 0, 0), 0); + ExpectIntEQ(BN_pseudo_rand(bn, -1, 0, 0), 0); + ExpectIntEQ(BN_pseudo_rand(NULL, 1, 0, 0), 0); + ExpectIntEQ(BN_pseudo_rand(&emptyBN, -1, 0, 0), 0); + ExpectIntEQ(BN_pseudo_rand(bn, -1, 0, 0), 0); + ExpectIntEQ(BN_pseudo_rand(&emptyBN, 1, 0, 0), 0); + + ExpectIntEQ(BN_rand_range(NULL, NULL), 0); + ExpectIntEQ(BN_rand_range(bn, NULL), 0); + ExpectIntEQ(BN_rand_range(NULL, range), 0); + ExpectIntEQ(BN_rand_range(&emptyBN, &emptyBN), 0); + ExpectIntEQ(BN_rand_range(bn, &emptyBN), 0); + ExpectIntEQ(BN_rand_range(&emptyBN, range), 0); /* 0 bit random value must be 0 and so cannot set bit in any position. */ - AssertIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ODD), 0); - AssertIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ODD), 0); - AssertIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ANY, + ExpectIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ANY, WOLFSSL_BN_RAND_BOTTOM_ODD), 0); - AssertIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ANY), 0); - AssertIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ANY), 0); - AssertIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ODD), 0); - AssertIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ODD), 0); - AssertIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ANY, + ExpectIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ANY, WOLFSSL_BN_RAND_BOTTOM_ODD), 0); - AssertIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ANY), 0); - AssertIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ANY), 0); /* 1 bit random value must have no more than one top bit set. */ - AssertIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ANY), 0); - AssertIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ODD), 0); - AssertIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ANY), 0); - AssertIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ODD), 0); /* END Invalid parameters. */ /* 0 bit random: 0. */ - AssertIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ANY, + ExpectIntEQ(BN_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ANY, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_is_zero(bn), 1); + ExpectIntEQ(BN_is_zero(bn), 1); - AssertIntEQ(BN_set_word(bn, 2), 1); /* Make sure not zero. */ - AssertIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ANY, + ExpectIntEQ(BN_set_word(bn, 2), 1); /* Make sure not zero. */ + ExpectIntEQ(BN_pseudo_rand(bn, 0, WOLFSSL_BN_RAND_TOP_ANY, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_is_zero(bn), 1); + ExpectIntEQ(BN_is_zero(bn), 1); /* 1 bit random: 0 or 1. */ - AssertIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ANY, + ExpectIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ANY, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntLT(BN_get_word(bn), 2); /* Make sure valid range. */ - AssertIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntLT(BN_get_word(bn), 2); /* Make sure valid range. */ + ExpectIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_get_word(bn), 1); - AssertIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_get_word(bn), 1); + ExpectIntEQ(BN_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ODD), 1); - AssertIntEQ(BN_get_word(bn), 1); + ExpectIntEQ(BN_get_word(bn), 1); - AssertIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ANY, + ExpectIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ANY, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntLT(BN_get_word(bn), 2); /* Make sure valid range. */ - AssertIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntLT(BN_get_word(bn), 2); /* Make sure valid range. */ + ExpectIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_get_word(bn), 1); - AssertIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_get_word(bn), 1); + ExpectIntEQ(BN_pseudo_rand(bn, 1, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ODD), 1); - AssertIntEQ(BN_get_word(bn), 1); + ExpectIntEQ(BN_get_word(bn), 1); - AssertIntEQ(BN_rand(bn, 8, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_rand(bn, 8, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_num_bits(bn), 8); - AssertIntEQ(BN_is_bit_set(bn, 7), 1); - AssertIntEQ(BN_pseudo_rand(bn, 8, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_num_bits(bn), 8); + ExpectIntEQ(BN_is_bit_set(bn, 7), 1); + ExpectIntEQ(BN_pseudo_rand(bn, 8, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_num_bits(bn), 8); - AssertIntEQ(BN_is_bit_set(bn, 7), 1); + ExpectIntEQ(BN_num_bits(bn), 8); + ExpectIntEQ(BN_is_bit_set(bn, 7), 1); - AssertIntEQ(BN_rand(bn, 8, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_rand(bn, 8, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_is_bit_set(bn, 7), 1); - AssertIntEQ(BN_is_bit_set(bn, 6), 1); - AssertIntEQ(BN_pseudo_rand(bn, 8, WOLFSSL_BN_RAND_TOP_TWO, + ExpectIntEQ(BN_is_bit_set(bn, 7), 1); + ExpectIntEQ(BN_is_bit_set(bn, 6), 1); + ExpectIntEQ(BN_pseudo_rand(bn, 8, WOLFSSL_BN_RAND_TOP_TWO, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_is_bit_set(bn, 7), 1); - AssertIntEQ(BN_is_bit_set(bn, 6), 1); + ExpectIntEQ(BN_is_bit_set(bn, 7), 1); + ExpectIntEQ(BN_is_bit_set(bn, 6), 1); - AssertIntEQ(BN_rand(bn, 8, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_rand(bn, 8, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ODD), 1); - AssertIntEQ(BN_is_bit_set(bn, 0), 1); - AssertIntEQ(BN_pseudo_rand(bn, 8, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_is_bit_set(bn, 0), 1); + ExpectIntEQ(BN_pseudo_rand(bn, 8, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ODD), 1); - AssertIntEQ(BN_is_bit_set(bn, 0), 1); + ExpectIntEQ(BN_is_bit_set(bn, 0), 1); /* Regression test: Older versions of wolfSSL_BN_rand would round the * requested number of bits up to the nearest multiple of 8. E.g. in this * case, requesting a 13-bit random number would actually return a 16-bit * random number. */ - AssertIntEQ(BN_rand(bn, 13, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_rand(bn, 13, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_num_bits(bn), 13); + ExpectIntEQ(BN_num_bits(bn), 13); - AssertIntEQ(BN_rand(range, 64, WOLFSSL_BN_RAND_TOP_ONE, + ExpectIntEQ(BN_rand(range, 64, WOLFSSL_BN_RAND_TOP_ONE, WOLFSSL_BN_RAND_BOTTOM_ANY), 1); - AssertIntEQ(BN_rand_range(bn, range), 1); + ExpectIntEQ(BN_rand_range(bn, range), 1); - AssertIntEQ(BN_set_word(range, 0), 1); - AssertIntEQ(BN_rand_range(bn, range), 1); - AssertIntEQ(BN_set_word(range, 1), 1); - AssertIntEQ(BN_rand_range(bn, range), 1); + ExpectIntEQ(BN_set_word(range, 0), 1); + ExpectIntEQ(BN_rand_range(bn, range), 1); + ExpectIntEQ(BN_set_word(range, 1), 1); + ExpectIntEQ(BN_rand_range(bn, range), 1); BN_free(bn); BN_free(range); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -41150,15 +41086,16 @@ static int test_wolfSSL_BN_prime(void) #if defined(OPENSSL_EXTRA) && !defined(NO_ASN) && \ !defined(OPENSSL_EXTRA_NO_BN) && !defined(WOLFSSL_SP_MATH) #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_RSA) || !defined(NO_DH) || !defined(NO_DSA)) - BIGNUM* a; - BIGNUM* add; - BIGNUM* rem; + EXPECT_DECLS; + BIGNUM* a = NULL; + BIGNUM* add = NULL; + BIGNUM* rem = NULL; BIGNUM emptyBN; XMEMSET(&emptyBN, 0, sizeof(emptyBN)); - AssertNotNull(a = BN_new()); - AssertNotNull(add = BN_new()); - AssertNotNull(rem = BN_new()); + ExpectNotNull(a = BN_new()); + ExpectNotNull(add = BN_new()); + ExpectNotNull(rem = BN_new()); /* Invalid parameters. */ /* BN_generate_prime_ex() @@ -41169,44 +41106,44 @@ static int test_wolfSSL_BN_prime(void) * rem - not supported, must be NULL * cb - anything */ - AssertIntEQ(BN_generate_prime_ex(NULL, -1, 1, add, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(&emptyBN, -1, 1, add, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(a, -1, 1, add, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(NULL, 2, 1, add, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(&emptyBN, 2, 1, add, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(NULL, -1, 0, add, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(&emptyBN, -1, 0, add, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(NULL, -1, 1, NULL, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(&emptyBN, -1, 1, NULL, rem, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(NULL, -1, 1, add, NULL, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(&emptyBN, -1, 1, add, NULL, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(NULL, 2, 0, NULL, NULL, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(&emptyBN, 2, 0, NULL, NULL, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(a, -1, 0, NULL, NULL, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(a, 0, 0, NULL, NULL, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(a, 2, 1, NULL, NULL, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(a, 2, 0, add, NULL, NULL), 0); - AssertIntEQ(BN_generate_prime_ex(a, 2, 0, NULL, rem, NULL), 0); - - AssertIntEQ(BN_is_prime_ex(NULL, -1, NULL, NULL), -1); - AssertIntEQ(BN_is_prime_ex(&emptyBN, -1, NULL, NULL), -1); - AssertIntEQ(BN_is_prime_ex(a, -1, NULL, NULL), -1); - AssertIntEQ(BN_is_prime_ex(a, 2048, NULL, NULL), -1); - AssertIntEQ(BN_is_prime_ex(NULL, 1, NULL, NULL), -1); - AssertIntEQ(BN_is_prime_ex(&emptyBN, 1, NULL, NULL), -1); + ExpectIntEQ(BN_generate_prime_ex(NULL, -1, 1, add, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(&emptyBN, -1, 1, add, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(a, -1, 1, add, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(NULL, 2, 1, add, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(&emptyBN, 2, 1, add, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(NULL, -1, 0, add, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(&emptyBN, -1, 0, add, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(NULL, -1, 1, NULL, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(&emptyBN, -1, 1, NULL, rem, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(NULL, -1, 1, add, NULL, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(&emptyBN, -1, 1, add, NULL, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(NULL, 2, 0, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(&emptyBN, 2, 0, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(a, -1, 0, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(a, 0, 0, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(a, 2, 1, NULL, NULL, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(a, 2, 0, add, NULL, NULL), 0); + ExpectIntEQ(BN_generate_prime_ex(a, 2, 0, NULL, rem, NULL), 0); + + ExpectIntEQ(BN_is_prime_ex(NULL, -1, NULL, NULL), -1); + ExpectIntEQ(BN_is_prime_ex(&emptyBN, -1, NULL, NULL), -1); + ExpectIntEQ(BN_is_prime_ex(a, -1, NULL, NULL), -1); + ExpectIntEQ(BN_is_prime_ex(a, 2048, NULL, NULL), -1); + ExpectIntEQ(BN_is_prime_ex(NULL, 1, NULL, NULL), -1); + ExpectIntEQ(BN_is_prime_ex(&emptyBN, 1, NULL, NULL), -1); /* END Invalid parameters. */ - AssertIntEQ(BN_generate_prime_ex(a, 512, 0, NULL, NULL, NULL), 1); - AssertIntEQ(BN_is_prime_ex(a, 8, NULL, NULL), 1); + ExpectIntEQ(BN_generate_prime_ex(a, 512, 0, NULL, NULL, NULL), 1); + ExpectIntEQ(BN_is_prime_ex(a, 8, NULL, NULL), 1); - AssertIntEQ(BN_clear_bit(a, 0), 1); - AssertIntEQ(BN_is_prime_ex(a, 8, NULL, NULL), 0); + ExpectIntEQ(BN_clear_bit(a, 0), 1); + ExpectIntEQ(BN_is_prime_ex(a, 8, NULL, NULL), 0); BN_free(rem); BN_free(add); BN_free(a); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif #endif /* defined(OPENSSL_EXTRA) && !defined(NO_ASN) */ return res; @@ -41369,28 +41306,29 @@ static int test_generate_cookie(void) { int res = TEST_SKIPPED; #if defined(WOLFSSL_DTLS) && defined(OPENSSL_EXTRA) && defined(USE_WOLFSSL_IO) - SSL_CTX* ctx; - SSL* ssl; + EXPECT_DECLS; + SSL_CTX* ctx = NULL; + SSL* ssl = NULL; byte buf[FOURK_BUF] = {0}; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfDTLS_method())); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfDTLS_method())); + ExpectNotNull(ssl = SSL_new(ctx)); /* Test unconnected */ - AssertIntEQ(EmbedGenerateCookie(ssl, buf, FOURK_BUF, NULL), GEN_COOKIE_E); + ExpectIntEQ(EmbedGenerateCookie(ssl, buf, FOURK_BUF, NULL), GEN_COOKIE_E); wolfSSL_CTX_SetGenCookie(ctx, EmbedGenerateCookie); wolfSSL_SetCookieCtx(ssl, ctx); - AssertNotNull(wolfSSL_GetCookieCtx(ssl)); + ExpectNotNull(wolfSSL_GetCookieCtx(ssl)); - AssertNull(wolfSSL_GetCookieCtx(NULL)); + ExpectNull(wolfSSL_GetCookieCtx(NULL)); SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -41762,23 +41700,25 @@ static int test_wolfSSL_set1_sigalgs_list(void) static int test_wolfSSL_set_tlsext_status_type(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \ +#if defined(OPENSSL_EXTRA) && defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \ !defined(NO_RSA) && !defined(NO_WOLFSSL_SERVER) - SSL* ssl; - SSL_CTX* ctx; + EXPECT_DECLS; + SSL* ssl = NULL; + SSL_CTX* ctx = NULL; - AssertNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); - AssertTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM)); - AssertTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); - AssertNotNull(ssl = SSL_new(ctx)); - AssertIntEQ(SSL_set_tlsext_status_type(ssl,TLSEXT_STATUSTYPE_ocsp), - SSL_SUCCESS); - AssertIntEQ(SSL_get_tlsext_status_type(ssl), TLSEXT_STATUSTYPE_ocsp); + ExpectNotNull(ctx = SSL_CTX_new(wolfSSLv23_server_method())); + ExpectTrue(SSL_CTX_use_certificate_file(ctx, svrCertFile, + SSL_FILETYPE_PEM)); + ExpectTrue(SSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM)); + ExpectNotNull(ssl = SSL_new(ctx)); + ExpectIntEQ(SSL_set_tlsext_status_type(ssl,TLSEXT_STATUSTYPE_ocsp), + SSL_SUCCESS); + ExpectIntEQ(SSL_get_tlsext_status_type(ssl), TLSEXT_STATUSTYPE_ocsp); SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); - #endif /* OPENSSL_EXTRA && HAVE_CERTIFICATE_STATUS_REQUEST && !NO_RSA */ + res = EXPECT_RESULT(); +#endif /* OPENSSL_EXTRA && HAVE_CERTIFICATE_STATUS_REQUEST && !NO_RSA */ return res; } @@ -41787,38 +41727,39 @@ static int test_wolfSSL_set_tlsext_status_type(void) static int test_wolfSSL_PEM_read_bio(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && !defined(NO_RSA) +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ + !defined(NO_FILESYSTEM) && !defined(NO_RSA) + EXPECT_DECLS; byte buff[6000]; - XFILE f; + XFILE f = XBADFILE; int bytes; - X509* x509; + X509* x509 = NULL; BIO* bio = NULL; - BUF_MEM* buf; + BUF_MEM* buf = NULL; - f = XFOPEN(cliCertFile, "rb"); - AssertTrue((f != XBADFILE)); - bytes = (int)XFREAD(buff, 1, sizeof(buff), f); - XFCLOSE(f); + ExpectTrue((f = XFOPEN(cliCertFile, "rb")) != XBADFILE); + ExpectIntGT(bytes = (int)XFREAD(buff, 1, sizeof(buff), f), 0); + if (f != XBADFILE) + XFCLOSE(f); - AssertNull(x509 = PEM_read_bio_X509_AUX(bio, NULL, NULL, NULL)); - AssertNotNull(bio = BIO_new_mem_buf((void*)buff, bytes)); - AssertIntEQ(BIO_set_mem_eof_return(bio, -0xDEAD), 1); - AssertNotNull(x509 = PEM_read_bio_X509_AUX(bio, NULL, NULL, NULL)); - AssertIntEQ((int)BIO_set_fd(bio, 0, BIO_CLOSE), 1); + ExpectNull(x509 = PEM_read_bio_X509_AUX(bio, NULL, NULL, NULL)); + ExpectNotNull(bio = BIO_new_mem_buf((void*)buff, bytes)); + ExpectIntEQ(BIO_set_mem_eof_return(bio, -0xDEAD), 1); + ExpectNotNull(x509 = PEM_read_bio_X509_AUX(bio, NULL, NULL, NULL)); + ExpectIntEQ((int)BIO_set_fd(bio, 0, BIO_CLOSE), 1); /* BIO should return the set EOF value */ - AssertIntEQ(BIO_read(bio, buff, sizeof(buff)), -0xDEAD); - AssertIntEQ(BIO_set_close(bio, BIO_NOCLOSE), 1); - AssertIntEQ(BIO_set_close(NULL, BIO_NOCLOSE), 1); - AssertIntEQ(SSL_SUCCESS, BIO_get_mem_ptr(bio, &buf)); + ExpectIntEQ(BIO_read(bio, buff, sizeof(buff)), -0xDEAD); + ExpectIntEQ(BIO_set_close(bio, BIO_NOCLOSE), 1); + ExpectIntEQ(BIO_set_close(NULL, BIO_NOCLOSE), 1); + ExpectIntEQ(SSL_SUCCESS, BIO_get_mem_ptr(bio, &buf)); BIO_free(bio); BUF_MEM_free(buf); X509_free(x509); - res = TEST_RES_CHECK(1); - #endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ + res = EXPECT_RESULT(); +#endif /* defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && + * !defined(NO_FILESYSTEM) && !defined(NO_RSA) */ return res; } @@ -41840,152 +41781,156 @@ static long bioCallback(BIO *bio, int cmd, const char* argp, int argi, static int test_wolfSSL_BIO(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) - const unsigned char* p; +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; + const unsigned char* p = NULL; byte buff[20]; - BIO* bio1; - BIO* bio2; - BIO* bio3; - char* bufPt; + BIO* bio1 = NULL; + BIO* bio2 = NULL; + BIO* bio3 = NULL; + char* bufPt = NULL; int i; for (i = 0; i < 20; i++) { buff[i] = i; } /* test BIO_free with NULL */ - AssertIntEQ(BIO_free(NULL), WOLFSSL_FAILURE); + ExpectIntEQ(BIO_free(NULL), WOLFSSL_FAILURE); /* Creating and testing type BIO_s_bio */ - AssertNotNull(bio1 = BIO_new(BIO_s_bio())); - AssertNotNull(bio2 = BIO_new(BIO_s_bio())); - AssertNotNull(bio3 = BIO_new(BIO_s_bio())); + ExpectNotNull(bio1 = BIO_new(BIO_s_bio())); + ExpectNotNull(bio2 = BIO_new(BIO_s_bio())); + ExpectNotNull(bio3 = BIO_new(BIO_s_bio())); /* read/write before set up */ - AssertIntEQ(BIO_read(bio1, buff, 2), WOLFSSL_BIO_UNSET); - AssertIntEQ(BIO_write(bio1, buff, 2), WOLFSSL_BIO_UNSET); + ExpectIntEQ(BIO_read(bio1, buff, 2), WOLFSSL_BIO_UNSET); + ExpectIntEQ(BIO_write(bio1, buff, 2), WOLFSSL_BIO_UNSET); - AssertIntEQ(BIO_set_nbio(bio1, 1), 1); - AssertIntEQ(BIO_set_write_buf_size(bio1, 20), WOLFSSL_SUCCESS); - AssertIntEQ(BIO_set_write_buf_size(bio2, 8), WOLFSSL_SUCCESS); - AssertIntEQ(BIO_make_bio_pair(bio1, bio2), WOLFSSL_SUCCESS); + ExpectIntEQ(BIO_set_nbio(bio1, 1), 1); + ExpectIntEQ(BIO_set_write_buf_size(bio1, 20), WOLFSSL_SUCCESS); + ExpectIntEQ(BIO_set_write_buf_size(bio2, 8), WOLFSSL_SUCCESS); + ExpectIntEQ(BIO_make_bio_pair(bio1, bio2), WOLFSSL_SUCCESS); - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 10), 10); - XMEMCPY(bufPt, buff, 10); - AssertIntEQ(BIO_write(bio1, buff + 10, 10), 10); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 10), 10); + ExpectNotNull(XMEMCPY(bufPt, buff, 10)); + ExpectIntEQ(BIO_write(bio1, buff + 10, 10), 10); /* write buffer full */ - AssertIntEQ(BIO_write(bio1, buff, 10), WOLFSSL_BIO_ERROR); - AssertIntEQ(BIO_flush(bio1), WOLFSSL_SUCCESS); - AssertIntEQ((int)BIO_ctrl_pending(bio1), 0); + ExpectIntEQ(BIO_write(bio1, buff, 10), WOLFSSL_BIO_ERROR); + ExpectIntEQ(BIO_flush(bio1), WOLFSSL_SUCCESS); + ExpectIntEQ((int)BIO_ctrl_pending(bio1), 0); /* write the other direction with pair */ - AssertIntEQ((int)BIO_nwrite(bio2, &bufPt, 10), 8); - XMEMCPY(bufPt, buff, 8); - AssertIntEQ(BIO_write(bio2, buff, 10), WOLFSSL_BIO_ERROR); + ExpectIntEQ((int)BIO_nwrite(bio2, &bufPt, 10), 8); + ExpectNotNull(XMEMCPY(bufPt, buff, 8)); + ExpectIntEQ(BIO_write(bio2, buff, 10), WOLFSSL_BIO_ERROR); /* try read */ - AssertIntEQ((int)BIO_ctrl_pending(bio1), 8); - AssertIntEQ((int)BIO_ctrl_pending(bio2), 20); + ExpectIntEQ((int)BIO_ctrl_pending(bio1), 8); + ExpectIntEQ((int)BIO_ctrl_pending(bio2), 20); /* try read using ctrl function */ - AssertIntEQ((int)BIO_ctrl(bio1, BIO_CTRL_WPENDING, 0, NULL), 8); - AssertIntEQ((int)BIO_ctrl(bio1, BIO_CTRL_PENDING, 0, NULL), 8); - AssertIntEQ((int)BIO_ctrl(bio2, BIO_CTRL_WPENDING, 0, NULL), 20); - AssertIntEQ((int)BIO_ctrl(bio2, BIO_CTRL_PENDING, 0, NULL), 20); + ExpectIntEQ((int)BIO_ctrl(bio1, BIO_CTRL_WPENDING, 0, NULL), 8); + ExpectIntEQ((int)BIO_ctrl(bio1, BIO_CTRL_PENDING, 0, NULL), 8); + ExpectIntEQ((int)BIO_ctrl(bio2, BIO_CTRL_WPENDING, 0, NULL), 20); + ExpectIntEQ((int)BIO_ctrl(bio2, BIO_CTRL_PENDING, 0, NULL), 20); - AssertIntEQ(BIO_nread(bio2, &bufPt, (int)BIO_ctrl_pending(bio2)), 20); + ExpectIntEQ(BIO_nread(bio2, &bufPt, (int)BIO_ctrl_pending(bio2)), 20); for (i = 0; i < 20; i++) { - AssertIntEQ((int)bufPt[i], i); + ExpectIntEQ((int)bufPt[i], i); } - AssertIntEQ(BIO_nread(bio2, &bufPt, 1), WOLFSSL_BIO_ERROR); - AssertIntEQ(BIO_nread(bio1, &bufPt, (int)BIO_ctrl_pending(bio1)), 8); + ExpectIntEQ(BIO_nread(bio2, &bufPt, 1), WOLFSSL_BIO_ERROR); + ExpectIntEQ(BIO_nread(bio1, &bufPt, (int)BIO_ctrl_pending(bio1)), 8); for (i = 0; i < 8; i++) { - AssertIntEQ((int)bufPt[i], i); + ExpectIntEQ((int)bufPt[i], i); } - AssertIntEQ(BIO_nread(bio1, &bufPt, 1), WOLFSSL_BIO_ERROR); - AssertIntEQ(BIO_ctrl_reset_read_request(bio1), 1); + ExpectIntEQ(BIO_nread(bio1, &bufPt, 1), WOLFSSL_BIO_ERROR); + ExpectIntEQ(BIO_ctrl_reset_read_request(bio1), 1); /* new pair */ - AssertIntEQ(BIO_make_bio_pair(bio1, bio3), WOLFSSL_FAILURE); + ExpectIntEQ(BIO_make_bio_pair(bio1, bio3), WOLFSSL_FAILURE); BIO_free(bio2); /* free bio2 and automatically remove from pair */ - AssertIntEQ(BIO_make_bio_pair(bio1, bio3), WOLFSSL_SUCCESS); - AssertIntEQ((int)BIO_ctrl_pending(bio3), 0); - AssertIntEQ(BIO_nread(bio3, &bufPt, 10), WOLFSSL_BIO_ERROR); + bio2 = NULL; + ExpectIntEQ(BIO_make_bio_pair(bio1, bio3), WOLFSSL_SUCCESS); + ExpectIntEQ((int)BIO_ctrl_pending(bio3), 0); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 10), WOLFSSL_BIO_ERROR); /* test wrap around... */ - AssertIntEQ(BIO_reset(bio1), 0); - AssertIntEQ(BIO_reset(bio3), 0); + ExpectIntEQ(BIO_reset(bio1), 0); + ExpectIntEQ(BIO_reset(bio3), 0); /* fill write buffer, read only small amount then write again */ - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 20), 20); - XMEMCPY(bufPt, buff, 20); - AssertIntEQ(BIO_nread(bio3, &bufPt, 4), 4); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 20), 20); + ExpectNotNull(XMEMCPY(bufPt, buff, 20)); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 4), 4); for (i = 0; i < 4; i++) { - AssertIntEQ(bufPt[i], i); + ExpectIntEQ(bufPt[i], i); } /* try writing over read index */ - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 5), 4); - XMEMSET(bufPt, 0, 4); - AssertIntEQ((int)BIO_ctrl_pending(bio3), 20); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 5), 4); + ExpectNotNull(XMEMSET(bufPt, 0, 4)); + ExpectIntEQ((int)BIO_ctrl_pending(bio3), 20); /* read and write 0 bytes */ - AssertIntEQ(BIO_nread(bio3, &bufPt, 0), 0); - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 0), 0); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 0), 0); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 0), 0); /* should read only to end of write buffer then need to read again */ - AssertIntEQ(BIO_nread(bio3, &bufPt, 20), 16); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 20), 16); for (i = 0; i < 16; i++) { - AssertIntEQ(bufPt[i], buff[4 + i]); + ExpectIntEQ(bufPt[i], buff[4 + i]); } - AssertIntEQ(BIO_nread(bio3, NULL, 0), WOLFSSL_FAILURE); - AssertIntEQ(BIO_nread0(bio3, &bufPt), 4); + ExpectIntEQ(BIO_nread(bio3, NULL, 0), WOLFSSL_FAILURE); + ExpectIntEQ(BIO_nread0(bio3, &bufPt), 4); for (i = 0; i < 4; i++) { - AssertIntEQ(bufPt[i], 0); + ExpectIntEQ(bufPt[i], 0); } /* read index should not have advanced with nread0 */ - AssertIntEQ(BIO_nread(bio3, &bufPt, 5), 4); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 5), 4); for (i = 0; i < 4; i++) { - AssertIntEQ(bufPt[i], 0); + ExpectIntEQ(bufPt[i], 0); } /* write and fill up buffer checking reset of index state */ - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 20), 20); - XMEMCPY(bufPt, buff, 20); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 20), 20); + ExpectNotNull(XMEMCPY(bufPt, buff, 20)); /* test reset on data in bio1 write buffer */ - AssertIntEQ(BIO_reset(bio1), 0); - AssertIntEQ((int)BIO_ctrl_pending(bio3), 0); - AssertIntEQ(BIO_nread(bio3, &bufPt, 3), WOLFSSL_BIO_ERROR); - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 20), 20); - AssertIntEQ((int)BIO_ctrl(bio1, BIO_CTRL_INFO, 0, &p), 20); - AssertNotNull(p); - XMEMCPY(bufPt, buff, 20); - AssertIntEQ(BIO_nread(bio3, &bufPt, 6), 6); + ExpectIntEQ(BIO_reset(bio1), 0); + ExpectIntEQ((int)BIO_ctrl_pending(bio3), 0); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 3), WOLFSSL_BIO_ERROR); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 20), 20); + ExpectIntEQ((int)BIO_ctrl(bio1, BIO_CTRL_INFO, 0, &p), 20); + ExpectNotNull(p); + ExpectNotNull(XMEMCPY(bufPt, buff, 20)); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 6), 6); for (i = 0; i < 6; i++) { - AssertIntEQ(bufPt[i], i); + ExpectIntEQ(bufPt[i], i); } /* test case of writing twice with offset read index */ - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 3), 3); - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 4), 3); /* try overwriting */ - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 4), WOLFSSL_BIO_ERROR); - AssertIntEQ(BIO_nread(bio3, &bufPt, 0), 0); - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 4), WOLFSSL_BIO_ERROR); - AssertIntEQ(BIO_nread(bio3, &bufPt, 1), 1); - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 4), 1); - AssertIntEQ(BIO_nwrite(bio1, &bufPt, 4), WOLFSSL_BIO_ERROR); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 3), 3); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 4), 3); /* try overwriting */ + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 4), WOLFSSL_BIO_ERROR); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 0), 0); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 4), WOLFSSL_BIO_ERROR); + ExpectIntEQ(BIO_nread(bio3, &bufPt, 1), 1); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 4), 1); + ExpectIntEQ(BIO_nwrite(bio1, &bufPt, 4), WOLFSSL_BIO_ERROR); BIO_free(bio1); + bio1 = NULL; BIO_free(bio3); + bio3 = NULL; #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) { BIO* bioA = NULL; BIO* bioB = NULL; - AssertIntEQ(BIO_new_bio_pair(NULL, 256, NULL, 256), BAD_FUNC_ARG); - AssertIntEQ(BIO_new_bio_pair(&bioA, 256, &bioB, 256), WOLFSSL_SUCCESS); + ExpectIntEQ(BIO_new_bio_pair(NULL, 256, NULL, 256), BAD_FUNC_ARG); + ExpectIntEQ(BIO_new_bio_pair(&bioA, 256, &bioB, 256), WOLFSSL_SUCCESS); BIO_free(bioA); bioA = NULL; BIO_free(bioB); @@ -41996,77 +41941,79 @@ static int test_wolfSSL_BIO(void) /* BIOs with file pointers */ #if !defined(NO_FILESYSTEM) { - XFILE f1; - XFILE f2; - BIO* f_bio1; - BIO* f_bio2; + XFILE f1 = XBADFILE; + XFILE f2 = XBADFILE; + BIO* f_bio1 = NULL; + BIO* f_bio2 = NULL; unsigned char cert[300]; char testFile[] = "tests/bio_write_test.txt"; char msg[] = "bio_write_test.txt contains the first 300 bytes of certs/server-cert.pem\ncreated by tests/unit.test\n\n"; - AssertNotNull(f_bio1 = BIO_new(BIO_s_file())); - AssertNotNull(f_bio2 = BIO_new(BIO_s_file())); + ExpectNotNull(f_bio1 = BIO_new(BIO_s_file())); + ExpectNotNull(f_bio2 = BIO_new(BIO_s_file())); /* Failure due to wrong BIO type */ - AssertIntEQ((int)BIO_set_mem_eof_return(f_bio1, -1), 0); - AssertIntEQ((int)BIO_set_mem_eof_return(NULL, -1), 0); + ExpectIntEQ((int)BIO_set_mem_eof_return(f_bio1, -1), 0); + ExpectIntEQ((int)BIO_set_mem_eof_return(NULL, -1), 0); - f1 = XFOPEN(svrCertFile, "rwb"); - AssertTrue((f1 != XBADFILE)); - AssertIntEQ((int)BIO_set_fp(f_bio1, f1, BIO_CLOSE), WOLFSSL_SUCCESS); - AssertIntEQ(BIO_write_filename(f_bio2, testFile), + ExpectTrue((f1 = XFOPEN(svrCertFile, "rwb")) != XBADFILE); + ExpectIntEQ((int)BIO_set_fp(f_bio1, f1, BIO_CLOSE), WOLFSSL_SUCCESS); + ExpectIntEQ(BIO_write_filename(f_bio2, testFile), WOLFSSL_SUCCESS); - AssertIntEQ(BIO_read(f_bio1, cert, sizeof(cert)), sizeof(cert)); - AssertIntEQ(BIO_tell(f_bio1),sizeof(cert)); - AssertIntEQ(BIO_write(f_bio2, msg, sizeof(msg)), sizeof(msg)); - AssertIntEQ(BIO_tell(f_bio2),sizeof(msg)); - AssertIntEQ(BIO_write(f_bio2, cert, sizeof(cert)), sizeof(cert)); - AssertIntEQ(BIO_tell(f_bio2),sizeof(cert) + sizeof(msg)); + ExpectIntEQ(BIO_read(f_bio1, cert, sizeof(cert)), sizeof(cert)); + ExpectIntEQ(BIO_tell(f_bio1),sizeof(cert)); + ExpectIntEQ(BIO_write(f_bio2, msg, sizeof(msg)), sizeof(msg)); + ExpectIntEQ(BIO_tell(f_bio2),sizeof(msg)); + ExpectIntEQ(BIO_write(f_bio2, cert, sizeof(cert)), sizeof(cert)); + ExpectIntEQ(BIO_tell(f_bio2),sizeof(cert) + sizeof(msg)); - AssertIntEQ((int)BIO_get_fp(f_bio2, &f2), WOLFSSL_SUCCESS); - AssertIntEQ(BIO_reset(f_bio2), 0); - AssertIntEQ(BIO_tell(NULL),-1); - AssertIntEQ(BIO_tell(f_bio2),0); - AssertIntEQ(BIO_seek(f_bio2, 4), 0); - AssertIntEQ(BIO_tell(f_bio2),4); + ExpectIntEQ((int)BIO_get_fp(f_bio2, &f2), WOLFSSL_SUCCESS); + ExpectIntEQ(BIO_reset(f_bio2), 0); + ExpectIntEQ(BIO_tell(NULL),-1); + ExpectIntEQ(BIO_tell(f_bio2),0); + ExpectIntEQ(BIO_seek(f_bio2, 4), 0); + ExpectIntEQ(BIO_tell(f_bio2),4); BIO_free(f_bio1); + f_bio1 = NULL; BIO_free(f_bio2); + f_bio2 = NULL; - AssertNotNull(f_bio1 = BIO_new_file(svrCertFile, "rwb")); - AssertIntEQ((int)BIO_set_mem_eof_return(f_bio1, -1), 0); - AssertIntEQ(BIO_read(f_bio1, cert, sizeof(cert)), sizeof(cert)); + ExpectNotNull(f_bio1 = BIO_new_file(svrCertFile, "rwb")); + ExpectIntEQ((int)BIO_set_mem_eof_return(f_bio1, -1), 0); + ExpectIntEQ(BIO_read(f_bio1, cert, sizeof(cert)), sizeof(cert)); BIO_free(f_bio1); - + f_bio1 = NULL; } #endif /* !defined(NO_FILESYSTEM) */ /* BIO info callback */ { const char* testArg = "test"; - BIO* cb_bio; - AssertNotNull(cb_bio = BIO_new(BIO_s_mem())); + BIO* cb_bio = NULL; + ExpectNotNull(cb_bio = BIO_new(BIO_s_mem())); BIO_set_callback(cb_bio, bioCallback); - AssertNotNull(BIO_get_callback(cb_bio)); + ExpectNotNull(BIO_get_callback(cb_bio)); BIO_set_callback(cb_bio, NULL); - AssertNull(BIO_get_callback(cb_bio)); + ExpectNull(BIO_get_callback(cb_bio)); BIO_set_callback_arg(cb_bio, (char*)testArg); - AssertStrEQ(BIO_get_callback_arg(cb_bio), testArg); - AssertNull(BIO_get_callback_arg(NULL)); + ExpectStrEQ(BIO_get_callback_arg(cb_bio), testArg); + ExpectNull(BIO_get_callback_arg(NULL)); BIO_free(cb_bio); + cb_bio = NULL; } /* BIO_vfree */ - AssertNotNull(bio1 = BIO_new(BIO_s_bio())); + ExpectNotNull(bio1 = BIO_new(BIO_s_bio())); BIO_vfree(NULL); BIO_vfree(bio1); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -42077,9 +42024,10 @@ static int test_wolfSSL_a2i_IPADDRESS(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && !defined(WOLFSSL_USER_IO) - const unsigned char* data; + EXPECT_DECLS; + const unsigned char* data = NULL; int dataSz = 0; - ASN1_OCTET_STRING *st; + ASN1_OCTET_STRING *st = NULL; const unsigned char ipv4_exp[] = {0x7F, 0, 0, 1}; const unsigned char ipv6_exp[] = { @@ -42091,29 +42039,26 @@ static int test_wolfSSL_a2i_IPADDRESS(void) 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; - AssertNull(st = a2i_IPADDRESS("127.0.0.1bad")); - AssertNotNull(st = a2i_IPADDRESS("127.0.0.1")); - data = ASN1_STRING_get0_data(st); - dataSz = ASN1_STRING_length(st); - AssertIntEQ(dataSz, WOLFSSL_IP4_ADDR_LEN); - AssertIntEQ(XMEMCMP(data, ipv4_exp, dataSz), 0); + ExpectNull(st = a2i_IPADDRESS("127.0.0.1bad")); + ExpectNotNull(st = a2i_IPADDRESS("127.0.0.1")); + ExpectNotNull(data = ASN1_STRING_get0_data(st)); + ExpectIntEQ(dataSz = ASN1_STRING_length(st), WOLFSSL_IP4_ADDR_LEN); + ExpectIntEQ(XMEMCMP(data, ipv4_exp, dataSz), 0); ASN1_STRING_free(st); - AssertNotNull(st = a2i_IPADDRESS("::1")); - data = ASN1_STRING_get0_data(st); - dataSz = ASN1_STRING_length(st); - AssertIntEQ(dataSz, WOLFSSL_IP6_ADDR_LEN); - AssertIntEQ(XMEMCMP(data, ipv6_home, dataSz), 0); + ExpectNotNull(st = a2i_IPADDRESS("::1")); + ExpectNotNull(data = ASN1_STRING_get0_data(st)); + ExpectIntEQ(dataSz = ASN1_STRING_length(st), WOLFSSL_IP6_ADDR_LEN); + ExpectIntEQ(XMEMCMP(data, ipv6_home, dataSz), 0); ASN1_STRING_free(st); - AssertNotNull(st = a2i_IPADDRESS("2021:db8::ff00:42:7777")); - data = ASN1_STRING_get0_data(st); - dataSz = ASN1_STRING_length(st); - AssertIntEQ(dataSz, WOLFSSL_IP6_ADDR_LEN); - AssertIntEQ(XMEMCMP(data, ipv6_exp, dataSz), 0); + ExpectNotNull(st = a2i_IPADDRESS("2021:db8::ff00:42:7777")); + ExpectNotNull(data = ASN1_STRING_get0_data(st)); + ExpectIntEQ(dataSz = ASN1_STRING_length(st), WOLFSSL_IP6_ADDR_LEN); + ExpectIntEQ(XMEMCMP(data, ipv6_exp, dataSz), 0); ASN1_STRING_free(st); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42160,17 +42105,18 @@ static int test_wolfSSL_X509_cmp_time(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_ASN_TIME) \ && !defined(USER_TIME) && !defined(TIME_OVERRIDES) + EXPECT_DECLS; WOLFSSL_ASN1_TIME asn_time; time_t t; - AssertIntEQ(0, wolfSSL_X509_cmp_time(NULL, &t)); + ExpectIntEQ(0, wolfSSL_X509_cmp_time(NULL, &t)); XMEMSET(&asn_time, 0, sizeof(WOLFSSL_ASN1_TIME)); - AssertIntEQ(0, wolfSSL_X509_cmp_time(&asn_time, &t)); + ExpectIntEQ(0, wolfSSL_X509_cmp_time(&asn_time, &t)); - AssertIntEQ(ASN1_TIME_set_string(&asn_time, "000222211515Z"), 1); - AssertIntEQ(-1, wolfSSL_X509_cmp_time(&asn_time, NULL)); + ExpectIntEQ(ASN1_TIME_set_string(&asn_time, "000222211515Z"), 1); + ExpectIntEQ(-1, wolfSSL_X509_cmp_time(&asn_time, NULL)); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42182,24 +42128,27 @@ static int test_wolfSSL_X509_time_adj(void) !defined(USER_TIME) && !defined(TIME_OVERRIDES) && \ defined(USE_CERT_BUFFERS_2048) && !defined(NO_RSA) && \ !defined(NO_ASN_TIME) - X509* x509; - time_t t, not_before, not_after; + EXPECT_DECLS; + X509* x509 = NULL; + time_t t; + time_t not_before; + time_t not_after; - AssertNotNull(x509 = wolfSSL_X509_load_certificate_buffer( + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_buffer( client_cert_der_2048, sizeof_client_cert_der_2048, WOLFSSL_FILETYPE_ASN1)); t = 0; not_before = wc_Time(0); not_after = wc_Time(0) + (60 * 24 * 30); /* 30 days after */ - AssertNotNull(X509_time_adj(X509_get_notBefore(x509), not_before, &t)); - AssertNotNull(X509_time_adj(X509_get_notAfter(x509), not_after, &t)); + ExpectNotNull(X509_time_adj(X509_get_notBefore(x509), not_before, &t)); + ExpectNotNull(X509_time_adj(X509_get_notAfter(x509), not_after, &t)); /* Check X509_gmtime_adj, too. */ - AssertNotNull(X509_gmtime_adj(X509_get_notAfter(x509), not_after)); + ExpectNotNull(X509_gmtime_adj(X509_get_notAfter(x509), not_after)); X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42208,70 +42157,76 @@ static int test_wolfSSL_X509_time_adj(void) static int test_wolfSSL_X509(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM)\ - && !defined(NO_RSA) - X509* x509; +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) && \ + !defined(NO_RSA) + EXPECT_DECLS; + X509* x509 = NULL; #ifndef NO_BIO - BIO* bio; - X509_STORE_CTX* ctx; - X509_STORE* store; + BIO* bio = NULL; + X509_STORE_CTX* ctx = NULL; + X509_STORE* store = NULL; #endif - char der[] = "certs/ca-cert.der"; - XFILE fp; + XFILE fp = XBADFILE; - AssertNotNull(x509 = X509_new()); + ExpectNotNull(x509 = X509_new()); X509_free(x509); + x509 = NULL; #ifndef NO_BIO - x509 = wolfSSL_X509_load_certificate_file(cliCertFile, SSL_FILETYPE_PEM); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + SSL_FILETYPE_PEM)); - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); #ifdef WOLFSSL_CERT_GEN - AssertIntEQ(i2d_X509_bio(bio, x509), SSL_SUCCESS); + ExpectIntEQ(i2d_X509_bio(bio, x509), SSL_SUCCESS); #endif - AssertNotNull(ctx = X509_STORE_CTX_new()); + ExpectNotNull(ctx = X509_STORE_CTX_new()); - AssertIntEQ(X509_verify_cert(ctx), SSL_FATAL_ERROR); + ExpectIntEQ(X509_verify_cert(ctx), SSL_FATAL_ERROR); - AssertNotNull(store = X509_STORE_new()); - AssertIntEQ(X509_STORE_add_cert(store, x509), SSL_SUCCESS); - AssertIntEQ(X509_STORE_CTX_init(ctx, store, x509, NULL), SSL_SUCCESS); - AssertIntEQ(X509_verify_cert(ctx), SSL_SUCCESS); + ExpectNotNull(store = X509_STORE_new()); + ExpectIntEQ(X509_STORE_add_cert(store, x509), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_CTX_init(ctx, store, x509, NULL), SSL_SUCCESS); + ExpectIntEQ(X509_verify_cert(ctx), SSL_SUCCESS); X509_STORE_CTX_free(ctx); X509_STORE_free(store); X509_free(x509); + x509 = NULL; BIO_free(bio); #endif /** d2i_X509_fp test **/ - fp = XFOPEN(der, "rb"); - AssertTrue((fp != XBADFILE)); - AssertNotNull(x509 = (X509 *)d2i_X509_fp(fp, (X509 **)NULL)); - AssertNotNull(x509); + ExpectTrue((fp = XFOPEN(der, "rb")) != XBADFILE); + ExpectNotNull(x509 = (X509 *)d2i_X509_fp(fp, (X509 **)NULL)); + ExpectNotNull(x509); X509_free(x509); - XFCLOSE(fp); - fp = XFOPEN(der, "rb"); - AssertTrue((fp != XBADFILE)); - AssertNotNull((X509 *)d2i_X509_fp(fp, (X509 **)&x509)); - AssertNotNull(x509); + x509 = NULL; + if (fp != XBADFILE) { + XFCLOSE(fp); + fp = XBADFILE; + } + ExpectTrue((fp = XFOPEN(der, "rb")) != XBADFILE); + ExpectNotNull((X509 *)d2i_X509_fp(fp, (X509 **)&x509)); + ExpectNotNull(x509); X509_free(x509); - XFCLOSE(fp); + if (fp != XBADFILE) + XFCLOSE(fp); /* X509_up_ref test */ - AssertIntEQ(X509_up_ref(NULL), 0); - AssertNotNull(x509 = X509_new()); /* refCount = 1 */ - AssertIntEQ(X509_up_ref(x509), 1); /* refCount = 2 */ - AssertIntEQ(X509_up_ref(x509), 1); /* refCount = 3 */ + ExpectIntEQ(X509_up_ref(NULL), 0); + ExpectNotNull(x509 = X509_new()); /* refCount = 1 */ + ExpectIntEQ(X509_up_ref(x509), 1); /* refCount = 2 */ + ExpectIntEQ(X509_up_ref(x509), 1); /* refCount = 3 */ X509_free(x509); /* refCount = 2 */ X509_free(x509); /* refCount = 1 */ X509_free(x509); /* refCount = 0, free */ - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42323,15 +42278,19 @@ static int test_wolfSSL_X509_sign2(void) #if defined(OPENSSL_EXTRA) && !defined(NO_RSA) && !defined(NO_CERTS) && \ defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_AKID_NAME) && \ - (defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)) - WOLFSSL_X509 *x509, *ca; - const unsigned char *der; - const unsigned char *pt; - WOLFSSL_EVP_PKEY *priv; - WOLFSSL_X509_NAME *name; + (defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \ + defined(WOLFSSL_IP_ALT_NAME)) + EXPECT_DECLS; + WOLFSSL_X509 *x509 = NULL; + WOLFSSL_X509 *ca = NULL; + const unsigned char *der = NULL; + const unsigned char *pt = NULL; + WOLFSSL_EVP_PKEY *priv = NULL; + WOLFSSL_X509_NAME *name = NULL; int derSz; #ifndef NO_ASN_TIME - WOLFSSL_ASN1_TIME *notBefore, *notAfter; + WOLFSSL_ASN1_TIME *notBefore = NULL; + WOLFSSL_ASN1_TIME *notAfter = NULL; const int year = 365*24*60*60; const int day = 24*60*60; @@ -42453,34 +42412,34 @@ static int test_wolfSSL_X509_sign2(void) }; pt = ca_key_der_2048; - AssertNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, &pt, - sizeof_ca_key_der_2048)); + ExpectNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, &pt, + sizeof_ca_key_der_2048)); pt = client_cert_der_2048; - AssertNotNull(x509 = wolfSSL_d2i_X509(NULL, &pt, - sizeof_client_cert_der_2048)); + ExpectNotNull(x509 = wolfSSL_d2i_X509(NULL, &pt, + sizeof_client_cert_der_2048)); pt = ca_cert_der_2048; - AssertNotNull(ca = wolfSSL_d2i_X509(NULL, &pt, sizeof_ca_cert_der_2048)); - AssertNotNull(name = wolfSSL_X509_get_subject_name(ca)); - AssertIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectNotNull(ca = wolfSSL_d2i_X509(NULL, &pt, sizeof_ca_cert_der_2048)); + ExpectNotNull(name = wolfSSL_X509_get_subject_name(ca)); + ExpectIntEQ(wolfSSL_X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); #ifndef NO_ASN_TIME t = (time_t)30 * year + 45 * day + 20 * hour + 30 * mini + 7 * day; - AssertNotNull(notBefore = wolfSSL_ASN1_TIME_adj(NULL, t, 0, 0)); - AssertNotNull(notAfter = wolfSSL_ASN1_TIME_adj(NULL, t, 365, 0)); - AssertIntEQ(notAfter->length, 13); + ExpectNotNull(notBefore = wolfSSL_ASN1_TIME_adj(NULL, t, 0, 0)); + ExpectNotNull(notAfter = wolfSSL_ASN1_TIME_adj(NULL, t, 365, 0)); + ExpectIntEQ(notAfter->length, 13); - AssertTrue(wolfSSL_X509_set_notBefore(x509, notBefore)); - AssertTrue(wolfSSL_X509_set_notAfter(x509, notAfter)); + ExpectTrue(wolfSSL_X509_set_notBefore(x509, notBefore)); + ExpectTrue(wolfSSL_X509_set_notAfter(x509, notAfter)); #endif - wolfSSL_X509_sign(x509, priv, EVP_sha256()); - AssertNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); + ExpectIntGT(wolfSSL_X509_sign(x509, priv, EVP_sha256()), 0); + ExpectNotNull((der = wolfSSL_X509_get_der(x509, &derSz))); - AssertIntEQ(derSz, sizeof(expected)); + ExpectIntEQ(derSz, sizeof(expected)); #ifndef NO_ASN_TIME - AssertIntEQ(XMEMCMP(der, expected, derSz), 0); + ExpectIntEQ(XMEMCMP(der, expected, derSz), 0); #endif wolfSSL_X509_free(ca); @@ -42491,7 +42450,7 @@ static int test_wolfSSL_X509_sign2(void) wolfSSL_ASN1_TIME_free(notAfter); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42502,15 +42461,17 @@ static int test_wolfSSL_X509_sign(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_ASN_TIME) && \ defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) && !defined(NO_RSA) + EXPECT_DECLS; int ret; - char *cn; + char *cn = NULL; word32 cnSz; - X509_NAME *name; - X509 *x509, *ca; + X509_NAME *name = NULL; + X509 *x509 = NULL; + X509 *ca = NULL; DecodedCert dCert; - EVP_PKEY *pub; - EVP_PKEY *priv; - EVP_MD_CTX *mctx; + EVP_PKEY *pub = NULL; + EVP_PKEY *priv = NULL; + EVP_MD_CTX *mctx = NULL; #if defined(USE_CERT_BUFFERS_1024) const unsigned char* rsaPriv = client_key_der_1024; const unsigned char* rsaPub = client_keypub_der_1024; @@ -42530,38 +42491,39 @@ static int test_wolfSSL_X509_sign(void) int snSz = sizeof(sn); /* Set X509_NAME fields */ - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "countryName", MBSTRING_UTF8, (byte*)"US", 2, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, (byte*)"support@wolfssl.com", 19, -1, 0), SSL_SUCCESS); /* Get private and public keys */ - AssertNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, &rsaPriv, + ExpectNotNull(priv = wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, NULL, &rsaPriv, clientKeySz)); - AssertNotNull(pub = wolfSSL_d2i_PUBKEY(NULL, &rsaPub, clientPubKeySz)); - AssertNotNull(x509 = X509_new()); + ExpectNotNull(pub = wolfSSL_d2i_PUBKEY(NULL, &rsaPub, clientPubKeySz)); + ExpectNotNull(x509 = X509_new()); /* Set version 3 */ - AssertIntNE(X509_set_version(x509, 2L), 0); + ExpectIntNE(X509_set_version(x509, 2L), 0); /* Set subject name, add pubkey, and sign certificate */ - AssertIntEQ(X509_set_subject_name(x509, name), SSL_SUCCESS); + ExpectIntEQ(X509_set_subject_name(x509, name), SSL_SUCCESS); X509_NAME_free(name); - AssertIntEQ(X509_set_pubkey(x509, pub), SSL_SUCCESS); + name = NULL; + ExpectIntEQ(X509_set_pubkey(x509, pub), SSL_SUCCESS); #ifdef WOLFSSL_ALT_NAMES /* Add some subject alt names */ - AssertIntNE(wolfSSL_X509_add_altname(NULL, + ExpectIntNE(wolfSSL_X509_add_altname(NULL, "ipsum", ASN_DNS_TYPE), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_add_altname(x509, + ExpectIntEQ(wolfSSL_X509_add_altname(x509, NULL, ASN_DNS_TYPE), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_add_altname(x509, + ExpectIntEQ(wolfSSL_X509_add_altname(x509, "sphygmomanometer", ASN_DNS_TYPE), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_add_altname(x509, + ExpectIntEQ(wolfSSL_X509_add_altname(x509, "supercalifragilisticexpialidocious", ASN_DNS_TYPE), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_add_altname(x509, + ExpectIntEQ(wolfSSL_X509_add_altname(x509, "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch", ASN_DNS_TYPE), SSL_SUCCESS); #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) @@ -42571,31 +42533,31 @@ static int test_wolfSSL_X509_sign(void) 0xff, 0xee, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x00, 0x33, 0x22, 0x11}; - AssertIntEQ(wolfSSL_X509_add_altname_ex(x509, (char*)ip4_type, + ExpectIntEQ(wolfSSL_X509_add_altname_ex(x509, (char*)ip4_type, sizeof(ip4_type), ASN_IP_TYPE), SSL_SUCCESS); - AssertIntEQ(wolfSSL_X509_add_altname_ex(x509, (char*)ip6_type, + ExpectIntEQ(wolfSSL_X509_add_altname_ex(x509, (char*)ip6_type, sizeof(ip6_type), ASN_IP_TYPE), SSL_SUCCESS); } #endif #endif /* WOLFSSL_ALT_NAMES */ /* test valid sign case */ - AssertIntGT(ret = X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(ret = X509_sign(x509, priv, EVP_sha256()), 0); /* test valid X509_sign_ctx case */ - AssertNotNull(mctx = EVP_MD_CTX_new()); - AssertIntEQ(EVP_DigestSignInit(mctx, NULL, EVP_sha256(), NULL, priv), 1); - AssertIntGT(X509_sign_ctx(x509, mctx), 0); + ExpectNotNull(mctx = EVP_MD_CTX_new()); + ExpectIntEQ(EVP_DigestSignInit(mctx, NULL, EVP_sha256(), NULL, priv), 1); + ExpectIntGT(X509_sign_ctx(x509, mctx), 0); #if defined(OPENSSL_ALL) && defined(WOLFSSL_ALT_NAMES) - AssertIntEQ(X509_get_ext_count(x509), 1); + ExpectIntEQ(X509_get_ext_count(x509), 1); #endif #if defined(WOLFSSL_ALT_NAMES) && (defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)) - AssertIntEQ(wolfSSL_X509_check_ip_asc(x509, "127.128.0.255", 0), 1); - AssertIntEQ(wolfSSL_X509_check_ip_asc(x509, "DDCC:BAAB:FFEE:9988:7766:5544:0033:2211", 0), 1); + ExpectIntEQ(wolfSSL_X509_check_ip_asc(x509, "127.128.0.255", 0), 1); + ExpectIntEQ(wolfSSL_X509_check_ip_asc(x509, "DDCC:BAAB:FFEE:9988:7766:5544:0033:2211", 0), 1); #endif - AssertIntEQ(wolfSSL_X509_get_serial_number(x509, sn, &snSz), + ExpectIntEQ(wolfSSL_X509_get_serial_number(x509, sn, &snSz), WOLFSSL_SUCCESS); DEBUG_WRITE_CERT_X509(x509, "signed.pem"); @@ -42605,80 +42567,83 @@ static int test_wolfSSL_X509_sign(void) #ifndef USE_CERT_BUFFERS_1024 #ifndef WOLFSSL_ALT_NAMES /* Valid case - size should be 781-786 with 16 byte serial number */ - AssertTrue((781 + snSz <= ret) && (ret <= 781 + 5 + snSz)); + ExpectTrue((781 + snSz <= ret) && (ret <= 781 + 5 + snSz)); #elif defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) /* Valid case - size should be 955-960 with 16 byte serial number */ - AssertTrue((939 + snSz <= ret) && (ret <= 939 + 5 + snSz)); + ExpectTrue((939 + snSz <= ret) && (ret <= 939 + 5 + snSz)); #else /* Valid case - size should be 926-931 with 16 byte serial number */ - AssertTrue((910 + snSz <= ret) && (ret <= 910 + 5 + snSz)); + ExpectTrue((910 + snSz <= ret) && (ret <= 910 + 5 + snSz)); #endif #else #ifndef WOLFSSL_ALT_NAMES /* Valid case - size should be 537-542 with 16 byte serial number */ - AssertTrue((521 + snSz <= ret) && (ret <= 521 + 5 + snSz)); + ExpectTrue((521 + snSz <= ret) && (ret <= 521 + 5 + snSz)); #elif defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) /* Valid case - size should be 695-670 with 16 byte serial number */ - AssertTrue((679 + snSz <= ret) && (ret <= 679 + 5 + snSz)); + ExpectTrue((679 + snSz <= ret) && (ret <= 679 + 5 + snSz)); #else /* Valid case - size should be 666-671 with 16 byte serial number */ - AssertTrue((650 + snSz <= ret) && (ret <= 650 + 5 + snSz)); + ExpectTrue((650 + snSz <= ret) && (ret <= 650 + 5 + snSz)); #endif #endif /* check that issuer name is as expected after signature */ InitDecodedCert(&dCert, certIssuer, (word32)certIssuerSz, 0); - AssertIntEQ(ParseCert(&dCert, CERT_TYPE, NO_VERIFY, NULL), 0); + ExpectIntEQ(ParseCert(&dCert, CERT_TYPE, NO_VERIFY, NULL), 0); - AssertNotNull(ca = d2i_X509(NULL, &certIssuer, (int)certIssuerSz)); - AssertNotNull(name = X509_get_subject_name(ca)); + ExpectNotNull(ca = d2i_X509(NULL, &certIssuer, (int)certIssuerSz)); + ExpectNotNull(name = X509_get_subject_name(ca)); cnSz = X509_NAME_get_sz(name); - AssertNotNull(cn = (char*)XMALLOC(cnSz, HEAP_HINT, DYNAMIC_TYPE_OPENSSL)); - AssertNotNull(cn = X509_NAME_oneline(name, cn, cnSz)); - AssertIntEQ(0, XSTRNCMP(cn, dCert.subject, XSTRLEN(cn))); + ExpectNotNull(cn = (char*)XMALLOC(cnSz, HEAP_HINT, DYNAMIC_TYPE_OPENSSL)); + ExpectNotNull(cn = X509_NAME_oneline(name, cn, cnSz)); + ExpectIntEQ(0, XSTRNCMP(cn, dCert.subject, XSTRLEN(cn))); XFREE(cn, HEAP_HINT, DYNAMIC_TYPE_OPENSSL); + cn = NULL; #ifdef WOLFSSL_MULTI_ATTRIB /* test adding multiple OU's to the signer */ - AssertNotNull(name = X509_get_subject_name(ca)); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_UTF8, + ExpectNotNull(name = X509_get_subject_name(ca)); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_UTF8, (byte*)"OU1", 3, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_UTF8, (byte*)"OU2", 3, -1, 0), SSL_SUCCESS); - AssertIntGT(X509_sign(ca, priv, EVP_sha256()), 0); + ExpectIntGT(X509_sign(ca, priv, EVP_sha256()), 0); #endif - AssertNotNull(name = X509_get_subject_name(ca)); - AssertIntEQ(X509_set_issuer_name(x509, name), SSL_SUCCESS); + ExpectNotNull(name = X509_get_subject_name(ca)); + ExpectIntEQ(X509_set_issuer_name(x509, name), SSL_SUCCESS); - AssertIntGT(X509_sign(x509, priv, EVP_sha256()), 0); - AssertNotNull(name = X509_get_issuer_name(x509)); + ExpectIntGT(X509_sign(x509, priv, EVP_sha256()), 0); + ExpectNotNull(name = X509_get_issuer_name(x509)); cnSz = X509_NAME_get_sz(name); - AssertNotNull(cn = (char*)XMALLOC(cnSz, HEAP_HINT, DYNAMIC_TYPE_OPENSSL)); - AssertNotNull(cn = X509_NAME_oneline(name, cn, cnSz)); + ExpectNotNull(cn = (char*)XMALLOC(cnSz, HEAP_HINT, DYNAMIC_TYPE_OPENSSL)); + ExpectNotNull(cn = X509_NAME_oneline(name, cn, cnSz)); /* compare and don't include the multi-attrib "/OU=OU1/OU=OU2" above */ - AssertIntEQ(0, XSTRNCMP(cn, dCert.issuer, XSTRLEN(dCert.issuer))); + ExpectIntEQ(0, XSTRNCMP(cn, dCert.issuer, XSTRLEN(dCert.issuer))); XFREE(cn, HEAP_HINT, DYNAMIC_TYPE_OPENSSL); + cn = NULL; FreeDecodedCert(&dCert); /* Test invalid parameters */ - AssertIntEQ(X509_sign(NULL, priv, EVP_sha256()), 0); - AssertIntEQ(X509_sign(x509, NULL, EVP_sha256()), 0); - AssertIntEQ(X509_sign(x509, priv, NULL), 0); + ExpectIntEQ(X509_sign(NULL, priv, EVP_sha256()), 0); + ExpectIntEQ(X509_sign(x509, NULL, EVP_sha256()), 0); + ExpectIntEQ(X509_sign(x509, priv, NULL), 0); - AssertIntEQ(X509_sign_ctx(NULL, mctx), 0); + ExpectIntEQ(X509_sign_ctx(NULL, mctx), 0); EVP_MD_CTX_free(mctx); - AssertNotNull(mctx = EVP_MD_CTX_new()); - AssertIntEQ(X509_sign_ctx(x509, mctx), 0); - AssertIntEQ(X509_sign_ctx(x509, NULL), 0); + mctx = NULL; + ExpectNotNull(mctx = EVP_MD_CTX_new()); + ExpectIntEQ(X509_sign_ctx(x509, mctx), 0); + ExpectIntEQ(X509_sign_ctx(x509, NULL), 0); /* test invalid version number */ #if defined(OPENSSL_ALL) - AssertIntNE(X509_set_version(x509, 6L), 0); - AssertIntGT(X509_sign(x509, priv, EVP_sha256()), 0); + ExpectIntNE(X509_set_version(x509, 6L), 0); + ExpectIntGT(X509_sign(x509, priv, EVP_sha256()), 0); /* uses ParseCert which fails on bad version number */ - AssertIntEQ(X509_get_ext_count(x509), SSL_FAILURE); + ExpectIntEQ(X509_get_ext_count(x509), SSL_FAILURE); #endif EVP_MD_CTX_free(mctx); @@ -42687,7 +42652,7 @@ static int test_wolfSSL_X509_sign(void) X509_free(x509); X509_free(ca); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42696,17 +42661,18 @@ static int test_wolfSSL_X509_get0_tbs_sigalg(void) { int res = TEST_SKIPPED; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)) + EXPECT_DECLS; X509* x509 = NULL; const X509_ALGOR* alg; - AssertNotNull(x509 = X509_new()); + ExpectNotNull(x509 = X509_new()); - AssertNull(alg = X509_get0_tbs_sigalg(NULL)); - AssertNotNull(alg = X509_get0_tbs_sigalg(x509)); + ExpectNull(alg = X509_get0_tbs_sigalg(NULL)); + ExpectNotNull(alg = X509_get0_tbs_sigalg(x509)); X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42716,31 +42682,32 @@ static int test_wolfSSL_X509_ALGOR_get0(void) int res = TEST_SKIPPED; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)) && \ !defined(NO_SHA256) && !defined(NO_RSA) + EXPECT_DECLS; X509* x509 = NULL; const ASN1_OBJECT* obj = NULL; - const X509_ALGOR* alg; + const X509_ALGOR* alg = NULL; int pptype = 0; const void *ppval = NULL; - AssertNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, - SSL_FILETYPE_PEM)); - AssertNotNull(alg = X509_get0_tbs_sigalg(x509)); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + SSL_FILETYPE_PEM)); + ExpectNotNull(alg = X509_get0_tbs_sigalg(x509)); /* Invalid case */ X509_ALGOR_get0(&obj, NULL, NULL, NULL); - AssertNull(obj); + ExpectNull(obj); /* Valid case */ X509_ALGOR_get0(&obj, &pptype, &ppval, alg); - AssertNotNull(obj); - AssertNull(ppval); - AssertIntNE(pptype, 0); + ExpectNotNull(obj); + ExpectNull(ppval); + ExpectIntNE(pptype, 0); /* Make sure NID of X509_ALGOR is Sha256 with RSA */ - AssertIntEQ(OBJ_obj2nid(obj), NID_sha256WithRSAEncryption); + ExpectIntEQ(OBJ_obj2nid(obj), NID_sha256WithRSAEncryption); X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42750,136 +42717,126 @@ static int test_wolfSSL_X509_VERIFY_PARAM(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) - X509_VERIFY_PARAM *paramTo; - X509_VERIFY_PARAM *paramFrom; - int ret; + EXPECT_DECLS; + X509_VERIFY_PARAM *paramTo = NULL; + X509_VERIFY_PARAM *paramFrom = NULL; char testIPv4[] = "127.0.0.1"; char testIPv6[] = "0001:0000:0000:0000:0000:0000:0000:0000/32"; char testhostName1[] = "foo.hoge.com"; char testhostName2[] = "foobar.hoge.com"; - paramTo = X509_VERIFY_PARAM_new(); - AssertNotNull(paramTo); - XMEMSET(paramTo, 0, sizeof(X509_VERIFY_PARAM )); + ExpectNotNull(paramTo = X509_VERIFY_PARAM_new()); + ExpectNotNull(XMEMSET(paramTo, 0, sizeof(X509_VERIFY_PARAM))); - paramFrom = X509_VERIFY_PARAM_new(); - AssertNotNull(paramFrom); - XMEMSET(paramFrom, 0, sizeof(X509_VERIFY_PARAM )); + ExpectNotNull(paramFrom = X509_VERIFY_PARAM_new()); + ExpectNotNull(XMEMSET(paramFrom, 0, sizeof(X509_VERIFY_PARAM))); - ret = X509_VERIFY_PARAM_set1_host(paramFrom, testhostName1, - (int)XSTRLEN(testhostName1)); - AssertIntEQ(1, ret); - AssertIntEQ(0, XSTRNCMP(paramFrom->hostName, testhostName1, - (int)XSTRLEN(testhostName1))); + ExpectIntEQ(X509_VERIFY_PARAM_set1_host(paramFrom, testhostName1, + (int)XSTRLEN(testhostName1)), 1); + ExpectIntEQ(0, XSTRNCMP(paramFrom->hostName, testhostName1, + (int)XSTRLEN(testhostName1))); X509_VERIFY_PARAM_set_hostflags(NULL, 0x00); X509_VERIFY_PARAM_set_hostflags(paramFrom, 0x01); - AssertIntEQ(0x01, paramFrom->hostFlags); + ExpectIntEQ(0x01, paramFrom->hostFlags); - ret = X509_VERIFY_PARAM_set1_ip_asc(NULL, testIPv4); - AssertIntEQ(0, ret); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip_asc(NULL, testIPv4), 0); - ret = X509_VERIFY_PARAM_set1_ip_asc(paramFrom, testIPv4); - AssertIntEQ(1, ret); - AssertIntEQ(0, XSTRNCMP(paramFrom->ipasc, testIPv4, WOLFSSL_MAX_IPSTR)); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip_asc(paramFrom, testIPv4), 1); + ExpectIntEQ(0, XSTRNCMP(paramFrom->ipasc, testIPv4, WOLFSSL_MAX_IPSTR)); - ret = X509_VERIFY_PARAM_set1_ip_asc(paramFrom, NULL); - AssertIntEQ(1, ret); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip_asc(paramFrom, NULL), 1); - ret = X509_VERIFY_PARAM_set1_ip_asc(paramFrom, testIPv6); - AssertIntEQ(1, ret); - AssertIntEQ(0, XSTRNCMP(paramFrom->ipasc, testIPv6, WOLFSSL_MAX_IPSTR)); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip_asc(paramFrom, testIPv6), 1); + ExpectIntEQ(0, XSTRNCMP(paramFrom->ipasc, testIPv6, WOLFSSL_MAX_IPSTR)); /* null pointer */ - ret = X509_VERIFY_PARAM_set1(NULL, paramFrom); - AssertIntEQ(WOLFSSL_FAILURE, ret); + ExpectIntEQ(X509_VERIFY_PARAM_set1(NULL, paramFrom), 0); /* in the case of "from" null, returns success */ - ret = X509_VERIFY_PARAM_set1(paramTo, NULL); - AssertIntEQ(WOLFSSL_SUCCESS, ret); + ExpectIntEQ(X509_VERIFY_PARAM_set1(paramTo, NULL), 1); - ret = X509_VERIFY_PARAM_set1(NULL, NULL); - AssertIntEQ(WOLFSSL_FAILURE, ret); + ExpectIntEQ(X509_VERIFY_PARAM_set1(NULL, NULL), 0); /* inherit flags test : VPARAM_DEFAULT */ - ret = X509_VERIFY_PARAM_set1(paramTo, paramFrom); - AssertIntEQ(1, ret); - AssertIntEQ(0, XSTRNCMP(paramTo->hostName, testhostName1, + ExpectIntEQ(X509_VERIFY_PARAM_set1(paramTo, paramFrom), 1); + ExpectIntEQ(0, XSTRNCMP(paramTo->hostName, testhostName1, (int)XSTRLEN(testhostName1))); - AssertIntEQ(0x01, paramTo->hostFlags); - AssertIntEQ(0, XSTRNCMP(paramTo->ipasc, testIPv6, WOLFSSL_MAX_IPSTR)); + ExpectIntEQ(0x01, paramTo->hostFlags); + ExpectIntEQ(0, XSTRNCMP(paramTo->ipasc, testIPv6, WOLFSSL_MAX_IPSTR)); /* inherit flags test : VPARAM OVERWRITE */ - X509_VERIFY_PARAM_set1_host(paramTo, testhostName2, - (int)XSTRLEN(testhostName2)); - X509_VERIFY_PARAM_set1_ip_asc(paramTo, testIPv4); + ExpectIntEQ(X509_VERIFY_PARAM_set1_host(paramTo, testhostName2, + (int)XSTRLEN(testhostName2)), 1); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip_asc(paramTo, testIPv4), 1); X509_VERIFY_PARAM_set_hostflags(paramTo, 0x00); - paramTo->inherit_flags = X509_VP_FLAG_OVERWRITE; + if (paramTo != NULL) { + paramTo->inherit_flags = X509_VP_FLAG_OVERWRITE; + } - ret = X509_VERIFY_PARAM_set1(paramTo, paramFrom); - AssertIntEQ(1, ret); - AssertIntEQ(0, XSTRNCMP(paramTo->hostName, testhostName1, - (int)XSTRLEN(testhostName1))); - AssertIntEQ(0x01, paramTo->hostFlags); - AssertIntEQ(0, XSTRNCMP(paramTo->ipasc, testIPv6, WOLFSSL_MAX_IPSTR)); + ExpectIntEQ(X509_VERIFY_PARAM_set1(paramTo, paramFrom), 1); + ExpectIntEQ(0, XSTRNCMP(paramTo->hostName, testhostName1, + (int)XSTRLEN(testhostName1))); + ExpectIntEQ(0x01, paramTo->hostFlags); + ExpectIntEQ(0, XSTRNCMP(paramTo->ipasc, testIPv6, WOLFSSL_MAX_IPSTR)); /* inherit flags test : VPARAM_RESET_FLAGS */ - X509_VERIFY_PARAM_set1_host(paramTo, testhostName2, - (int)XSTRLEN(testhostName2)); - X509_VERIFY_PARAM_set1_ip_asc(paramTo, testIPv4); + ExpectIntEQ(X509_VERIFY_PARAM_set1_host(paramTo, testhostName2, + (int)XSTRLEN(testhostName2)), 1); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip_asc(paramTo, testIPv4), 1); X509_VERIFY_PARAM_set_hostflags(paramTo, 0x10); - paramTo->inherit_flags = X509_VP_FLAG_RESET_FLAGS; + if (paramTo != NULL) { + paramTo->inherit_flags = X509_VP_FLAG_RESET_FLAGS; + } - ret = X509_VERIFY_PARAM_set1(paramTo, paramFrom); - AssertIntEQ(1, ret); - AssertIntEQ(0, XSTRNCMP(paramTo->hostName, testhostName1, + ExpectIntEQ(X509_VERIFY_PARAM_set1(paramTo, paramFrom), 1); + ExpectIntEQ(0, XSTRNCMP(paramTo->hostName, testhostName1, (int)XSTRLEN(testhostName1))); - AssertIntEQ(0x01, paramTo->hostFlags); - AssertIntEQ(0, XSTRNCMP(paramTo->ipasc, testIPv6, WOLFSSL_MAX_IPSTR)); + ExpectIntEQ(0x01, paramTo->hostFlags); + ExpectIntEQ(0, XSTRNCMP(paramTo->ipasc, testIPv6, WOLFSSL_MAX_IPSTR)); /* inherit flags test : VPARAM_LOCKED */ - X509_VERIFY_PARAM_set1_host(paramTo, testhostName2, - (int)XSTRLEN(testhostName2)); - X509_VERIFY_PARAM_set1_ip_asc(paramTo, testIPv4); + ExpectIntEQ(X509_VERIFY_PARAM_set1_host(paramTo, testhostName2, + (int)XSTRLEN(testhostName2)), 1); + ExpectIntEQ(X509_VERIFY_PARAM_set1_ip_asc(paramTo, testIPv4), 1); X509_VERIFY_PARAM_set_hostflags(paramTo, 0x00); - paramTo->inherit_flags = X509_VP_FLAG_LOCKED; + if (paramTo != NULL) { + paramTo->inherit_flags = X509_VP_FLAG_LOCKED; + } - ret = X509_VERIFY_PARAM_set1(paramTo, paramFrom); - AssertIntEQ(1, ret); - AssertIntEQ(0, XSTRNCMP(paramTo->hostName, testhostName2, + ExpectIntEQ(X509_VERIFY_PARAM_set1(paramTo, paramFrom), 1); + ExpectIntEQ(0, XSTRNCMP(paramTo->hostName, testhostName2, (int)XSTRLEN(testhostName2))); - AssertIntEQ(0x00, paramTo->hostFlags); - AssertIntEQ(0, XSTRNCMP(paramTo->ipasc, testIPv4, WOLFSSL_MAX_IPSTR)); + ExpectIntEQ(0x00, paramTo->hostFlags); + ExpectIntEQ(0, XSTRNCMP(paramTo->ipasc, testIPv4, WOLFSSL_MAX_IPSTR)); /* test for incorrect parameters */ - ret = X509_VERIFY_PARAM_set_flags(NULL, X509_V_FLAG_CRL_CHECK_ALL ); - AssertIntEQ(0, ret); + ExpectIntEQ(X509_VERIFY_PARAM_set_flags(NULL, X509_V_FLAG_CRL_CHECK_ALL), + 0); - ret = X509_VERIFY_PARAM_set_flags(NULL, 0 ); - AssertIntEQ(0, ret); + ExpectIntEQ(X509_VERIFY_PARAM_set_flags(NULL, 0), 0); /* inherit flags test : VPARAM_ONCE, not testable yet */ - ret = X509_VERIFY_PARAM_set_flags(paramTo, X509_V_FLAG_CRL_CHECK_ALL); - AssertIntEQ(1, ret); + ExpectIntEQ(X509_VERIFY_PARAM_set_flags(paramTo, X509_V_FLAG_CRL_CHECK_ALL), + 1); - ret = X509_VERIFY_PARAM_get_flags(paramTo); - AssertIntEQ(X509_V_FLAG_CRL_CHECK_ALL, ret); + ExpectIntEQ(X509_VERIFY_PARAM_get_flags(paramTo), + X509_V_FLAG_CRL_CHECK_ALL); - ret = X509_VERIFY_PARAM_clear_flags(paramTo, X509_V_FLAG_CRL_CHECK_ALL); - AssertIntEQ(1, ret); + ExpectIntEQ(X509_VERIFY_PARAM_clear_flags(paramTo, + X509_V_FLAG_CRL_CHECK_ALL), 1); - ret = X509_VERIFY_PARAM_get_flags(paramTo); - AssertIntEQ(0, ret); + ExpectIntEQ(X509_VERIFY_PARAM_get_flags(paramTo), 0); X509_VERIFY_PARAM_free(paramTo); X509_VERIFY_PARAM_free(paramFrom); X509_VERIFY_PARAM_free(NULL); /* to confirm NULL parameter gives no harm */ - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42955,17 +42912,18 @@ static int test_wolfSSL_X509_get_X509_PUBKEY(void) { int res = TEST_SKIPPED; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)) + EXPECT_DECLS; X509* x509 = NULL; X509_PUBKEY* pubKey; - AssertNotNull(x509 = X509_new()); + ExpectNotNull(x509 = X509_new()); - AssertNull(pubKey = wolfSSL_X509_get_X509_PUBKEY(NULL)); - AssertNotNull(pubKey = wolfSSL_X509_get_X509_PUBKEY(x509)); + ExpectNull(pubKey = wolfSSL_X509_get_X509_PUBKEY(NULL)); + ExpectNotNull(pubKey = wolfSSL_X509_get_X509_PUBKEY(x509)); X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -42975,48 +42933,50 @@ static int test_wolfSSL_X509_PUBKEY_RSA(void) int res = TEST_SKIPPED; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)) && \ !defined(NO_SHA256) && !defined(NO_RSA) + EXPECT_DECLS; X509* x509 = NULL; ASN1_OBJECT* obj = NULL; const ASN1_OBJECT* pa_oid = NULL; - X509_PUBKEY* pubKey; - X509_PUBKEY* pubKey2; - EVP_PKEY* evpKey; + X509_PUBKEY* pubKey = NULL; + X509_PUBKEY* pubKey2 = NULL; + EVP_PKEY* evpKey = NULL; - const unsigned char *pk; - int ppklen, pptype; - X509_ALGOR *pa; + const unsigned char *pk = NULL; + int ppklen; + int pptype; + X509_ALGOR *pa = NULL; const void *pval; - AssertNotNull(x509 = X509_load_certificate_file(cliCertFile, - SSL_FILETYPE_PEM)); + ExpectNotNull(x509 = X509_load_certificate_file(cliCertFile, + SSL_FILETYPE_PEM)); - AssertNotNull(pubKey = X509_get_X509_PUBKEY(x509)); - AssertIntEQ(X509_PUBKEY_get0_param(&obj, &pk, &ppklen, &pa, pubKey), 1); - AssertNotNull(pk); - AssertNotNull(pa); - AssertNotNull(pubKey); - AssertIntGT(ppklen, 0); - - AssertIntEQ(OBJ_obj2nid(obj), NID_rsaEncryption); - - AssertNotNull(evpKey = X509_PUBKEY_get(pubKey)); - AssertNotNull(pubKey2 = X509_PUBKEY_new()); - AssertIntEQ(X509_PUBKEY_set(&pubKey2, evpKey), 1); - AssertIntEQ(X509_PUBKEY_get0_param(&obj, &pk, &ppklen, &pa, pubKey2), 1); - AssertNotNull(pk); - AssertNotNull(pa); - AssertIntGT(ppklen, 0); + ExpectNotNull(pubKey = X509_get_X509_PUBKEY(x509)); + ExpectIntEQ(X509_PUBKEY_get0_param(&obj, &pk, &ppklen, &pa, pubKey), 1); + ExpectNotNull(pk); + ExpectNotNull(pa); + ExpectNotNull(pubKey); + ExpectIntGT(ppklen, 0); + + ExpectIntEQ(OBJ_obj2nid(obj), NID_rsaEncryption); + + ExpectNotNull(evpKey = X509_PUBKEY_get(pubKey)); + ExpectNotNull(pubKey2 = X509_PUBKEY_new()); + ExpectIntEQ(X509_PUBKEY_set(&pubKey2, evpKey), 1); + ExpectIntEQ(X509_PUBKEY_get0_param(&obj, &pk, &ppklen, &pa, pubKey2), 1); + ExpectNotNull(pk); + ExpectNotNull(pa); + ExpectIntGT(ppklen, 0); X509_ALGOR_get0(&pa_oid, &pptype, &pval, pa); - AssertNotNull(pa_oid); - AssertNull(pval); - AssertIntEQ(pptype, V_ASN1_NULL); - AssertIntEQ(OBJ_obj2nid(pa_oid), EVP_PKEY_RSA); + ExpectNotNull(pa_oid); + ExpectNull(pval); + ExpectIntEQ(pptype, V_ASN1_NULL); + ExpectIntEQ(OBJ_obj2nid(pa_oid), EVP_PKEY_RSA); X509_PUBKEY_free(pubKey2); X509_free(x509); EVP_PKEY_free(evpKey); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -43025,44 +42985,46 @@ static int test_wolfSSL_X509_PUBKEY_EC(void) { int res = TEST_SKIPPED; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)) && defined(HAVE_ECC) + EXPECT_DECLS; X509* x509 = NULL; ASN1_OBJECT* obj = NULL; - ASN1_OBJECT* poid; + ASN1_OBJECT* poid = NULL; const ASN1_OBJECT* pa_oid = NULL; - X509_PUBKEY* pubKey; - X509_PUBKEY* pubKey2; - EVP_PKEY* evpKey; + X509_PUBKEY* pubKey = NULL; + X509_PUBKEY* pubKey2 = NULL; + EVP_PKEY* evpKey = NULL; - const unsigned char *pk; - int ppklen, pptype; - X509_ALGOR *pa; + const unsigned char *pk = NULL; + int ppklen; + int pptype; + X509_ALGOR *pa = NULL; const void *pval; char buf[50]; - AssertNotNull(x509 = X509_load_certificate_file(cliEccCertFile, + ExpectNotNull(x509 = X509_load_certificate_file(cliEccCertFile, SSL_FILETYPE_PEM)); - AssertNotNull(pubKey = X509_get_X509_PUBKEY(x509)); - AssertNotNull(evpKey = X509_PUBKEY_get(pubKey)); - AssertNotNull(pubKey2 = X509_PUBKEY_new()); - AssertIntEQ(X509_PUBKEY_set(&pubKey2, evpKey), 1); - AssertIntEQ(X509_PUBKEY_get0_param(&obj, &pk, &ppklen, &pa, pubKey2), 1); - AssertNotNull(pk); - AssertNotNull(pa); - AssertIntGT(ppklen, 0); + ExpectNotNull(pubKey = X509_get_X509_PUBKEY(x509)); + ExpectNotNull(evpKey = X509_PUBKEY_get(pubKey)); + ExpectNotNull(pubKey2 = X509_PUBKEY_new()); + ExpectIntEQ(X509_PUBKEY_set(&pubKey2, evpKey), 1); + ExpectIntEQ(X509_PUBKEY_get0_param(&obj, &pk, &ppklen, &pa, pubKey2), 1); + ExpectNotNull(pk); + ExpectNotNull(pa); + ExpectIntGT(ppklen, 0); X509_ALGOR_get0(&pa_oid, &pptype, &pval, pa); - AssertNotNull(pa_oid); - AssertNotNull(pval); - AssertIntEQ(pptype, V_ASN1_OBJECT); - AssertIntEQ(OBJ_obj2nid(pa_oid), EVP_PKEY_EC); + ExpectNotNull(pa_oid); + ExpectNotNull(pval); + ExpectIntEQ(pptype, V_ASN1_OBJECT); + ExpectIntEQ(OBJ_obj2nid(pa_oid), EVP_PKEY_EC); poid = (ASN1_OBJECT *)pval; - AssertIntGT(OBJ_obj2txt(buf, (int)sizeof(buf), poid, 0), 0); - AssertIntEQ(OBJ_txt2nid(buf), NID_X9_62_prime256v1); + ExpectIntGT(OBJ_obj2txt(buf, (int)sizeof(buf), poid, 0), 0); + ExpectIntEQ(OBJ_txt2nid(buf), NID_X9_62_prime256v1); X509_PUBKEY_free(pubKey2); X509_free(x509); EVP_PKEY_free(evpKey); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -43071,6 +43033,7 @@ static int test_wolfSSL_X509_PUBKEY_DSA(void) { int res = TEST_SKIPPED; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)) && !defined(NO_DSA) + EXPECT_DECLS; word32 bytes; #ifdef USE_CERT_BUFFERS_1024 byte tmp[ONEK_BUF]; @@ -43087,9 +43050,9 @@ static int test_wolfSSL_X509_PUBKEY_DSA(void) X509_PUBKEY* pubKey = NULL; EVP_PKEY* evpKey = NULL; - const unsigned char *pk; + const unsigned char *pk = NULL; int ppklen, pptype; - X509_ALGOR *pa; + X509_ALGOR *pa = NULL; const void *pval; #ifdef USE_CERT_BUFFERS_1024 @@ -43102,87 +43065,58 @@ static int test_wolfSSL_X509_PUBKEY_DSA(void) bytes = sizeof_dsa_key_der_2048; #else { - XFILE fp; + XFILE fp = XBADFILE; XMEMSET(tmp, 0, sizeof(tmp)); - fp = XFOPEN("./certs/dsa2048.der", "rb"); - if (fp == XBADFILE) { - return WOLFSSL_BAD_FILE; - } - bytes = (word32) XFREAD(tmp, 1, sizeof(tmp), fp); - XFCLOSE(fp); + ExpectTrue((fp = XFOPEN("./certs/dsa2048.der", "rb")) != XBADFILE); + ExpectIntGT(bytes = (word32) XFREAD(tmp, 1, sizeof(tmp), fp), 0); + if (fp != XBADFILE) + XFCLOSE(fp); } #endif /* Initialize pkey with der format dsa key */ - AssertNotNull(d2i_PrivateKey(EVP_PKEY_DSA, &evpKey, &dsaKeyDer, bytes)); - - AssertNotNull(pubKey = X509_PUBKEY_new()); - AssertIntEQ(X509_PUBKEY_set(&pubKey, evpKey), 1); - AssertIntEQ(X509_PUBKEY_get0_param(&obj, &pk, &ppklen, &pa, pubKey), 1); - AssertNotNull(pk); - AssertNotNull(pa); - AssertIntGT(ppklen, 0); + ExpectNotNull(d2i_PrivateKey(EVP_PKEY_DSA, &evpKey, &dsaKeyDer, bytes)); + + ExpectNotNull(pubKey = X509_PUBKEY_new()); + ExpectIntEQ(X509_PUBKEY_set(&pubKey, evpKey), 1); + ExpectIntEQ(X509_PUBKEY_get0_param(&obj, &pk, &ppklen, &pa, pubKey), 1); + ExpectNotNull(pk); + ExpectNotNull(pa); + ExpectIntGT(ppklen, 0); X509_ALGOR_get0(&pa_oid, &pptype, &pval, pa); - AssertNotNull(pa_oid); - AssertNotNull(pval); - AssertIntEQ(pptype, V_ASN1_SEQUENCE); - AssertIntEQ(OBJ_obj2nid(pa_oid), EVP_PKEY_DSA); + ExpectNotNull(pa_oid); + ExpectNotNull(pval); + ExpectIntEQ(pptype, V_ASN1_SEQUENCE); + ExpectIntEQ(OBJ_obj2nid(pa_oid), EVP_PKEY_DSA); str = (ASN1_STRING *)pval; DEBUG_WRITE_DER(ASN1_STRING_data(str), ASN1_STRING_length(str), "str.der"); #ifdef USE_CERT_BUFFERS_1024 - AssertIntEQ(ASN1_STRING_length(str), 291); + ExpectIntEQ(ASN1_STRING_length(str), 291); #else - AssertIntEQ(ASN1_STRING_length(str), 549); + ExpectIntEQ(ASN1_STRING_length(str), 549); #endif /* END USE_CERT_BUFFERS_1024 */ X509_PUBKEY_free(pubKey); EVP_PKEY_free(evpKey); - res = TEST_RES_CHECK(1); -#endif - return res; -} - -static int test_wolfSSL_RAND(void) -{ - int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) - byte seed[16]; - - XMEMSET(seed, 0, sizeof(seed)); - - RAND_seed(seed, sizeof(seed)); - AssertIntEQ(RAND_poll(), 1); - RAND_cleanup(); - - AssertIntEQ(RAND_egd(NULL), -1); -#ifndef NO_FILESYSTEM - { - char fname[100]; - - AssertNotNull(RAND_file_name(fname, (sizeof(fname) - 1))); - AssertIntEQ(RAND_write_file(NULL), 0); - } + res = EXPECT_RESULT(); #endif - - res = TEST_RES_CHECK(1); - #endif return res; } - static int test_wolfSSL_BUF(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) - BUF_MEM* buf; - AssertNotNull(buf = BUF_MEM_new()); - AssertIntEQ(BUF_MEM_grow(buf, 10), 10); - AssertIntEQ(BUF_MEM_grow(buf, -1), 0); +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; + BUF_MEM* buf = NULL; + ExpectNotNull(buf = BUF_MEM_new()); + ExpectIntEQ(BUF_MEM_grow(buf, 10), 10); + ExpectIntEQ(BUF_MEM_grow(buf, -1), 0); BUF_MEM_free(buf); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -43257,20 +43191,22 @@ static int test_wolfSSL_RAND_set_rand_method(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB) + EXPECT_DECLS; RAND_METHOD rand_methods = {NULL, NULL, NULL, NULL, NULL, NULL}; unsigned char* buf = NULL; int num = 0; double entropy = 0; + int ret; byte* was_cleanup_called = was_stub_rand_cleanup_called(); byte* was_add_called = was_stub_rand_add_called(); - buf = (byte*)XMALLOC(32 * sizeof(byte), NULL, - DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(buf = (byte*)XMALLOC(32 * sizeof(byte), NULL, + DYNAMIC_TYPE_TMP_BUFFER)); - AssertIntNE(wolfSSL_RAND_status(), 5432); - AssertIntEQ(*was_cleanup_called, 0); + ExpectIntNE(wolfSSL_RAND_status(), 5432); + ExpectIntEQ(*was_cleanup_called, 0); RAND_cleanup(); - AssertIntEQ(*was_cleanup_called, 0); + ExpectIntEQ(*was_cleanup_called, 0); rand_methods.seed = &stub_rand_seed; @@ -43280,32 +43216,36 @@ static int test_wolfSSL_RAND_set_rand_method(void) rand_methods.pseudorand = &stub_rand_pseudo_bytes; rand_methods.status = &stub_rand_status; - AssertIntEQ(RAND_set_rand_method(&rand_methods), WOLFSSL_SUCCESS); - AssertIntEQ(RAND_seed(buf, num), 123); - AssertIntEQ(RAND_bytes(buf, num), 456); - AssertIntEQ(RAND_pseudo_bytes(buf, num), 9876); - AssertIntEQ(RAND_status(), 5432); + ExpectIntEQ(RAND_set_rand_method(&rand_methods), WOLFSSL_SUCCESS); + ExpectIntEQ(RAND_seed(buf, num), 123); + ExpectIntEQ(RAND_bytes(buf, num), 456); + ExpectIntEQ(RAND_pseudo_bytes(buf, num), 9876); + ExpectIntEQ(RAND_status(), 5432); - AssertIntEQ(*was_add_called, 0); - /* The function pointer for RAND_add returns int, but RAND_add itself returns void. */ + ExpectIntEQ(*was_add_called, 0); + /* The function pointer for RAND_add returns int, but RAND_add itself + * returns void. */ RAND_add(buf, num, entropy); - AssertIntEQ(*was_add_called, 1); + ExpectIntEQ(*was_add_called, 1); was_add_called = 0; - AssertIntEQ(*was_cleanup_called, 0); + ExpectIntEQ(*was_cleanup_called, 0); RAND_cleanup(); - AssertIntEQ(*was_cleanup_called, 1); + ExpectIntEQ(*was_cleanup_called, 1); *was_cleanup_called = 0; - AssertIntEQ(RAND_set_rand_method(NULL), WOLFSSL_SUCCESS); - AssertIntNE(RAND_status(), 5432); - AssertIntEQ(*was_cleanup_called, 0); + ret = RAND_set_rand_method(NULL); + ExpectIntEQ(ret, WOLFSSL_SUCCESS); + ExpectIntNE(RAND_status(), 5432); + ExpectIntEQ(*was_cleanup_called, 0); RAND_cleanup(); - AssertIntEQ(*was_cleanup_called, 0); + ExpectIntEQ(*was_cleanup_called, 0); + + RAND_set_rand_method(NULL); XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && !WOLFSSL_NO_OPENSSL_RAND_CB */ return res; } @@ -43313,48 +43253,79 @@ static int test_wolfSSL_RAND_set_rand_method(void) static int test_wolfSSL_RAND_bytes(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; const int size1 = RNG_MAX_BLOCK_LEN; /* in bytes */ const int size2 = RNG_MAX_BLOCK_LEN + 1; /* in bytes */ const int size3 = RNG_MAX_BLOCK_LEN * 2; /* in bytes */ const int size4 = RNG_MAX_BLOCK_LEN * 4; /* in bytes */ int max_bufsize; - byte *my_buf; + byte *my_buf = NULL; /* sanity check */ - AssertIntEQ(RAND_bytes(NULL, 16), 0); - AssertIntEQ(RAND_bytes(NULL, 0), 0); + ExpectIntEQ(RAND_bytes(NULL, 16), 0); + ExpectIntEQ(RAND_bytes(NULL, 0), 0); max_bufsize = size4; - my_buf = (byte*)XMALLOC(max_bufsize * sizeof(byte), NULL, - DYNAMIC_TYPE_TMP_BUFFER); + ExpectNotNull(my_buf = (byte*)XMALLOC(max_bufsize * sizeof(byte), NULL, + DYNAMIC_TYPE_TMP_BUFFER)); - AssertIntEQ(RAND_bytes(my_buf, 0), 1); - AssertIntEQ(RAND_bytes(my_buf, -1), 0); + ExpectIntEQ(RAND_bytes(my_buf, 0), 1); + ExpectIntEQ(RAND_bytes(my_buf, -1), 0); - AssertNotNull(my_buf); - XMEMSET(my_buf, 0, max_bufsize); - AssertIntEQ(RAND_bytes(my_buf, size1), 1); - AssertIntEQ(RAND_bytes(my_buf, size2), 1); - AssertIntEQ(RAND_bytes(my_buf, size3), 1); - AssertIntEQ(RAND_bytes(my_buf, size4), 1); + ExpectNotNull(XMEMSET(my_buf, 0, max_bufsize)); + ExpectIntEQ(RAND_bytes(my_buf, size1), 1); + ExpectIntEQ(RAND_bytes(my_buf, size2), 1); + ExpectIntEQ(RAND_bytes(my_buf, size3), 1); + ExpectIntEQ(RAND_bytes(my_buf, size4), 1); XFREE(my_buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } +static int test_wolfSSL_RAND(void) +{ + int res = TEST_SKIPPED; +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; + byte seed[16]; + + XMEMSET(seed, 0, sizeof(seed)); + + /* No global methods set. */ + ExpectIntEQ(RAND_seed(seed, sizeof(seed)), 1); + ExpectIntEQ(RAND_poll(), 1); + RAND_cleanup(); + + ExpectIntEQ(RAND_egd(NULL), -1); +#ifndef NO_FILESYSTEM + { + char fname[100]; + + ExpectNotNull(RAND_file_name(fname, (sizeof(fname) - 1))); + ExpectIntEQ(RAND_write_file(NULL), 0); + } +#endif + + res = EXPECT_RESULT(); +#endif + return res; +} + + static int test_wolfSSL_PKCS8_Compat(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) && defined(HAVE_ECC) - #ifndef NO_BIO - PKCS8_PRIV_KEY_INFO* pt; - BIO* bio; - XFILE f; +#if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) && defined(HAVE_ECC) && \ + !defined(NO_BIO) + EXPECT_DECLS; + PKCS8_PRIV_KEY_INFO* pt = NULL; + BIO* bio = NULL; + XFILE f = XBADFILE; int bytes; char pkcs8_buffer[512]; #if defined(OPENSSL_ALL) || defined(WOLFSSL_WPAS_SMALL) @@ -43362,19 +43333,20 @@ static int test_wolfSSL_PKCS8_Compat(void) #endif /* file from wolfssl/certs/ directory */ - f = XFOPEN("./certs/ecc-keyPkcs8.pem", "rb"); - AssertTrue(f != XBADFILE); - AssertIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), f)), 0); - XFCLOSE(f); - AssertNotNull(bio = BIO_new_mem_buf((void*)pkcs8_buffer, bytes)); - AssertNotNull(pt = d2i_PKCS8_PRIV_KEY_INFO_bio(bio, NULL)); + ExpectTrue((f = XFOPEN("./certs/ecc-keyPkcs8.pem", "rb")) != XBADFILE); + ExpectIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), f)), + 0); + if (f != XBADFILE) + XFCLOSE(f); + ExpectNotNull(bio = BIO_new_mem_buf((void*)pkcs8_buffer, bytes)); + ExpectNotNull(pt = d2i_PKCS8_PRIV_KEY_INFO_bio(bio, NULL)); #if defined(OPENSSL_ALL) || defined(WOLFSSL_WPAS_SMALL) - AssertNotNull(pkey = EVP_PKCS82PKEY(pt)); - AssertIntEQ(EVP_PKEY_type(pkey->type), EVP_PKEY_EC); + ExpectNotNull(pkey = EVP_PKCS82PKEY(pt)); + ExpectIntEQ(EVP_PKEY_type(pkey->type), EVP_PKEY_EC); /* gets PKCS8 pointer to pkey */ - AssertNotNull(EVP_PKEY2PKCS8(pkey)); + ExpectNotNull(EVP_PKEY2PKCS8(pkey)); EVP_PKEY_free(pkey); #endif @@ -43382,9 +43354,8 @@ static int test_wolfSSL_PKCS8_Compat(void) BIO_free(bio); PKCS8_PRIV_KEY_INFO_free(pt); - res = TEST_RES_CHECK(1); - #endif - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -43392,6 +43363,7 @@ static int test_wolfSSL_PKCS8_d2i(void) { int res = TEST_SKIPPED; #if !defined(HAVE_FIPS) && defined(OPENSSL_EXTRA) + EXPECT_DECLS; /* This test ends up using HMAC as a part of PBKDF2, and HMAC * requires a 12 byte password in FIPS mode. This test ends up * trying to use an 8 byte password. */ @@ -43400,10 +43372,10 @@ static int test_wolfSSL_PKCS8_d2i(void) unsigned char pkcs8_buffer[2048]; const unsigned char* p; int bytes; - XFILE file; + XFILE file = XBADFILE; WOLFSSL_EVP_PKEY* pkey = NULL; #ifndef NO_BIO - BIO* bio; + BIO* bio = NULL; #if defined(OPENSSL_ALL) && \ ((!defined(NO_RSA) && !defined(NO_DES3)) || \ defined(HAVE_ECC)) && \ @@ -43457,152 +43429,178 @@ static int test_wolfSSL_PKCS8_d2i(void) #ifdef OPENSSL_ALL #ifndef NO_RSA /* Try to auto-detect normal RSA private key */ - AssertNotNull(pkey = d2i_AutoPrivateKey(NULL, &rsa, rsaSz)); + ExpectNotNull(pkey = d2i_AutoPrivateKey(NULL, &rsa, rsaSz)); EVP_PKEY_free(pkey); + pkey = NULL; #endif #ifdef HAVE_ECC /* Try to auto-detect normal EC private key */ - AssertNotNull(pkey = d2i_AutoPrivateKey(NULL, &ec, ecSz)); + ExpectNotNull(pkey = d2i_AutoPrivateKey(NULL, &ec, ecSz)); EVP_PKEY_free(pkey); + pkey = NULL; #endif #endif /* OPENSSL_ALL */ #ifndef NO_FILESYSTEM #ifndef NO_RSA /* Get DER encoded RSA PKCS#8 data. */ - file = XFOPEN(rsaDerPkcs8File, "rb"); - AssertTrue(file != XBADFILE); - XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer)); - AssertIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), - file)), 0); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(rsaDerPkcs8File, "rb")) != XBADFILE); + ExpectNotNull(XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer))); + ExpectIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), + file)), 0); + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } p = pkcs8_buffer; #ifdef OPENSSL_ALL /* Try to decode - auto-detect key type. */ - AssertNotNull(pkey = d2i_AutoPrivateKey(NULL, &p, bytes)); + ExpectNotNull(pkey = d2i_AutoPrivateKey(NULL, &p, bytes)); #else - AssertNotNull(pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p, bytes)); + ExpectNotNull(pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p, bytes)); #endif /* Get PEM encoded RSA PKCS#8 data. */ - file = XFOPEN(rsaPemPkcs8File, "rb"); - AssertTrue(file != XBADFILE); - AssertIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), - file)), 0); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(rsaPemPkcs8File, "rb")) != XBADFILE); + ExpectIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), + file)), 0); + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } #if defined(OPENSSL_ALL) && \ !defined(NO_BIO) && !defined(NO_PWDBASED) && defined(HAVE_PKCS8) - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); /* Write PKCS#8 PEM to BIO. */ - AssertIntEQ(PEM_write_bio_PKCS8PrivateKey(bio, pkey, NULL, NULL, 0, NULL, - NULL), bytes); + ExpectIntEQ(PEM_write_bio_PKCS8PrivateKey(bio, pkey, NULL, NULL, 0, NULL, + NULL), bytes); /* Compare file and written data */ - AssertIntEQ(BIO_get_mem_data(bio, &p), bytes); - AssertIntEQ(XMEMCMP(p, pkcs8_buffer, bytes), 0); + ExpectIntEQ(BIO_get_mem_data(bio, &p), bytes); + ExpectIntEQ(XMEMCMP(p, pkcs8_buffer, bytes), 0); BIO_free(bio); + bio = NULL; #if !defined(NO_DES3) && !defined(NO_SHA) - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); /* Write Encrypted PKCS#8 PEM to BIO. */ bytes = 1834; - AssertIntEQ(PEM_write_bio_PKCS8PrivateKey(bio, pkey, EVP_des_ede3_cbc(), - NULL, 0, PasswordCallBack, (void*)"yassl123"), bytes); - AssertNotNull(evpPkey = PEM_read_bio_PrivateKey(bio, NULL, PasswordCallBack, - (void*)"yassl123")); + ExpectIntEQ(PEM_write_bio_PKCS8PrivateKey(bio, pkey, EVP_des_ede3_cbc(), + NULL, 0, PasswordCallBack, (void*)"yassl123"), bytes); + ExpectNotNull(evpPkey = PEM_read_bio_PrivateKey(bio, NULL, PasswordCallBack, + (void*)"yassl123")); EVP_PKEY_free(evpPkey); + evpPkey = NULL; BIO_free(bio); + bio = NULL; #endif /* !NO_DES3 && !NO_SHA */ #endif /* !NO_BIO && !NO_PWDBASED && HAVE_PKCS8 */ EVP_PKEY_free(pkey); + pkey = NULL; /* PKCS#8 encrypted RSA key */ #ifndef NO_DES3 - file = XFOPEN(rsaDerPkcs8EncFile, "rb"); - AssertTrue(file != XBADFILE); - XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer)); - AssertIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), - file)), 0); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(rsaDerPkcs8EncFile, "rb")) != XBADFILE); + ExpectNotNull(XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer))); + ExpectIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), + file)), 0); + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } #if defined(OPENSSL_ALL) && \ !defined(NO_BIO) && !defined(NO_PWDBASED) && defined(HAVE_PKCS8) - AssertNotNull(bio = BIO_new_mem_buf((void*)pkcs8_buffer, bytes)); - AssertNotNull(pkey = d2i_PKCS8PrivateKey_bio(bio, NULL, PasswordCallBack, - (void*)"yassl123")); + ExpectNotNull(bio = BIO_new_mem_buf((void*)pkcs8_buffer, bytes)); + ExpectNotNull(pkey = d2i_PKCS8PrivateKey_bio(bio, NULL, PasswordCallBack, + (void*)"yassl123")); EVP_PKEY_free(pkey); + pkey = NULL; BIO_free(bio); + bio = NULL; #endif /* OPENSSL_ALL && !NO_BIO && !NO_PWDBASED && HAVE_PKCS8 */ #endif /* !NO_DES3 */ #endif /* NO_RSA */ #ifdef HAVE_ECC /* PKCS#8 encode EC key */ - file = XFOPEN(ecDerPkcs8File, "rb"); - AssertTrue(file != XBADFILE); - XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer)); - AssertIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), - file)), 0); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(ecDerPkcs8File, "rb")) != XBADFILE); + ExpectNotNull(XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer))); + ExpectIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), + file)), 0); + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } p = pkcs8_buffer; #ifdef OPENSSL_ALL /* Try to decode - auto-detect key type. */ - AssertNotNull(pkey = d2i_AutoPrivateKey(NULL, &p, bytes)); + ExpectNotNull(pkey = d2i_AutoPrivateKey(NULL, &p, bytes)); #else - AssertNotNull(pkey = d2i_PrivateKey(EVP_PKEY_EC, NULL, &p, bytes)); + ExpectNotNull(pkey = d2i_PrivateKey(EVP_PKEY_EC, NULL, &p, bytes)); #endif /* Get PEM encoded RSA PKCS#8 data. */ - file = XFOPEN(ecPemPkcs8File, "rb"); - AssertTrue(file != XBADFILE); - XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer)); - AssertIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), - file)), 0); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(ecPemPkcs8File, "rb")) != XBADFILE); + ExpectNotNull(XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer))); + ExpectIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), + file)), 0); + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } #if defined(OPENSSL_ALL) && \ !defined(NO_BIO) && !defined(NO_PWDBASED) && defined(HAVE_PKCS8) && \ defined(HAVE_AES_CBC) - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); /* Write PKCS#8 PEM to BIO. */ - AssertIntEQ(PEM_write_bio_PKCS8PrivateKey(bio, pkey, NULL, NULL, 0, NULL, - NULL), bytes); + ExpectIntEQ(PEM_write_bio_PKCS8PrivateKey(bio, pkey, NULL, NULL, 0, NULL, + NULL), bytes); /* Compare file and written data */ - AssertIntEQ(BIO_get_mem_data(bio, &p), bytes); - AssertIntEQ(XMEMCMP(p, pkcs8_buffer, bytes), 0); + ExpectIntEQ(BIO_get_mem_data(bio, &p), bytes); + ExpectIntEQ(XMEMCMP(p, pkcs8_buffer, bytes), 0); BIO_free(bio); - AssertNotNull(bio = BIO_new(BIO_s_mem())); + bio = NULL; + ExpectNotNull(bio = BIO_new(BIO_s_mem())); /* Write Encrypted PKCS#8 PEM to BIO. */ bytes = 379; - AssertIntEQ(PEM_write_bio_PKCS8PrivateKey(bio, pkey, EVP_aes_256_cbc(), - NULL, 0, PasswordCallBack, (void*)"yassl123"), bytes); - AssertNotNull(evpPkey = PEM_read_bio_PrivateKey(bio, NULL, PasswordCallBack, - (void*)"yassl123")); + ExpectIntEQ(PEM_write_bio_PKCS8PrivateKey(bio, pkey, EVP_aes_256_cbc(), + NULL, 0, PasswordCallBack, (void*)"yassl123"), bytes); + ExpectNotNull(evpPkey = PEM_read_bio_PrivateKey(bio, NULL, PasswordCallBack, + (void*)"yassl123")); EVP_PKEY_free(evpPkey); + evpPkey = NULL; BIO_free(bio); + bio = NULL; #endif /* OPENSSL_ALL && !NO_BIO && !NO_PWDBASED && HAVE_PKCS8 && HAVE_AES_CBC */ EVP_PKEY_free(pkey); + pkey = NULL; /* PKCS#8 encrypted EC key */ #ifndef NO_DES3 - file = XFOPEN(ecDerPkcs8EncFile, "rb"); - AssertTrue(file != XBADFILE); - XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer)); - AssertIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), - file)), 0); - XFCLOSE(file); + ExpectTrue((file = XFOPEN(ecDerPkcs8EncFile, "rb")) != XBADFILE); + ExpectNotNull(XMEMSET(pkcs8_buffer, 0, sizeof(pkcs8_buffer))); + ExpectIntGT((bytes = (int)XFREAD(pkcs8_buffer, 1, sizeof(pkcs8_buffer), + file)), 0); + if (file != XBADFILE) { + XFCLOSE(file); + file = XBADFILE; + } #if defined(OPENSSL_ALL) && \ !defined(NO_BIO) && !defined(NO_PWDBASED) && defined(HAVE_PKCS8) - AssertNotNull(bio = BIO_new_mem_buf((void*)pkcs8_buffer, bytes)); - AssertNotNull(pkey = d2i_PKCS8PrivateKey_bio(bio, NULL, PasswordCallBack, + ExpectNotNull(bio = BIO_new_mem_buf((void*)pkcs8_buffer, bytes)); + ExpectNotNull(pkey = d2i_PKCS8PrivateKey_bio(bio, NULL, PasswordCallBack, (void*)"yassl123")); EVP_PKEY_free(pkey); + pkey = NULL; BIO_free(bio); + bio = NULL; #endif /* OPENSSL_ALL && !NO_BIO && !NO_PWDBASED && HAVE_PKCS8 */ #endif /* !NO_DES3 */ #endif /* HAVE_ECC */ #endif /* !NO_FILESYSTEM */ - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* HAVE_FIPS && OPENSSL_EXTRA */ return res; } @@ -43677,7 +43675,7 @@ static int test_error_queue_per_thread(void) for (i = 0; i < LOGGING_THREADS; i++) join_thread(loggingThreads[i]); - res = TEST_RES_CHECK(1); + res = TEST_SUCCESS; #endif return res; } @@ -43685,74 +43683,75 @@ static int test_error_queue_per_thread(void) static int test_wolfSSL_ERR_put_error(void) { int res = TEST_SKIPPED; - #if !defined(NO_ERROR_QUEUE) && defined(OPENSSL_EXTRA) && \ - defined(DEBUG_WOLFSSL) +#if !defined(NO_ERROR_QUEUE) && defined(OPENSSL_EXTRA) && \ + defined(DEBUG_WOLFSSL) + EXPECT_DECLS; const char* file; int line; ERR_clear_error(); /* clear out any error nodes */ ERR_put_error(0,SYS_F_ACCEPT, 0, "this file", 0); - AssertIntEQ(ERR_get_error_line(&file, &line), 0); + ExpectIntEQ(ERR_get_error_line(&file, &line), 0); ERR_put_error(0,SYS_F_BIND, 1, "this file", 1); - AssertIntEQ(ERR_get_error_line(&file, &line), 1); + ExpectIntEQ(ERR_get_error_line(&file, &line), 1); ERR_put_error(0,SYS_F_CONNECT, 2, "this file", 2); - AssertIntEQ(ERR_get_error_line(&file, &line), 2); + ExpectIntEQ(ERR_get_error_line(&file, &line), 2); ERR_put_error(0,SYS_F_FOPEN, 3, "this file", 3); - AssertIntEQ(ERR_get_error_line(&file, &line), 3); + ExpectIntEQ(ERR_get_error_line(&file, &line), 3); ERR_put_error(0,SYS_F_FREAD, 4, "this file", 4); - AssertIntEQ(ERR_get_error_line(&file, &line), 4); + ExpectIntEQ(ERR_get_error_line(&file, &line), 4); ERR_put_error(0,SYS_F_GETADDRINFO, 5, "this file", 5); - AssertIntEQ(ERR_get_error_line(&file, &line), 5); + ExpectIntEQ(ERR_get_error_line(&file, &line), 5); ERR_put_error(0,SYS_F_GETSOCKOPT, 6, "this file", 6); - AssertIntEQ(ERR_get_error_line(&file, &line), 6); + ExpectIntEQ(ERR_get_error_line(&file, &line), 6); ERR_put_error(0,SYS_F_GETSOCKNAME, 7, "this file", 7); - AssertIntEQ(ERR_get_error_line(&file, &line), 7); + ExpectIntEQ(ERR_get_error_line(&file, &line), 7); ERR_put_error(0,SYS_F_GETHOSTBYNAME, 8, "this file", 8); - AssertIntEQ(ERR_get_error_line(&file, &line), 8); + ExpectIntEQ(ERR_get_error_line(&file, &line), 8); ERR_put_error(0,SYS_F_GETNAMEINFO, 9, "this file", 9); - AssertIntEQ(ERR_get_error_line(&file, &line), 9); + ExpectIntEQ(ERR_get_error_line(&file, &line), 9); ERR_put_error(0,SYS_F_GETSERVBYNAME, 10, "this file", 10); - AssertIntEQ(ERR_get_error_line(&file, &line), 10); + ExpectIntEQ(ERR_get_error_line(&file, &line), 10); ERR_put_error(0,SYS_F_IOCTLSOCKET, 11, "this file", 11); - AssertIntEQ(ERR_get_error_line(&file, &line), 11); + ExpectIntEQ(ERR_get_error_line(&file, &line), 11); ERR_put_error(0,SYS_F_LISTEN, 12, "this file", 12); - AssertIntEQ(ERR_get_error_line(&file, &line), 12); + ExpectIntEQ(ERR_get_error_line(&file, &line), 12); ERR_put_error(0,SYS_F_OPENDIR, 13, "this file", 13); - AssertIntEQ(ERR_get_error_line(&file, &line), 13); + ExpectIntEQ(ERR_get_error_line(&file, &line), 13); ERR_put_error(0,SYS_F_SETSOCKOPT, 14, "this file", 14); - AssertIntEQ(ERR_get_error_line(&file, &line), 14); + ExpectIntEQ(ERR_get_error_line(&file, &line), 14); ERR_put_error(0,SYS_F_SOCKET, 15, "this file", 15); - AssertIntEQ(ERR_get_error_line(&file, &line), 15); + ExpectIntEQ(ERR_get_error_line(&file, &line), 15); #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) ERR_put_error(ERR_LIB_ASN1, SYS_F_ACCEPT, ASN1_R_HEADER_TOO_LONG, "this file", 100); - AssertIntEQ(wolfSSL_ERR_peek_last_error_line(&file, &line), + ExpectIntEQ(wolfSSL_ERR_peek_last_error_line(&file, &line), (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG); - AssertIntEQ(line, 100); - AssertIntEQ(wolfSSL_ERR_peek_error(), + ExpectIntEQ(line, 100); + ExpectIntEQ(wolfSSL_ERR_peek_error(), (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG); - AssertIntEQ(ERR_get_error_line(&file, &line), ASN1_R_HEADER_TOO_LONG); + ExpectIntEQ(ERR_get_error_line(&file, &line), ASN1_R_HEADER_TOO_LONG); #endif /* try reading past end of error queue */ file = NULL; - AssertIntEQ(ERR_get_error_line(&file, &line), 0); - AssertNull(file); - AssertIntEQ(ERR_get_error_line_data(&file, &line, NULL, NULL), 0); + ExpectIntEQ(ERR_get_error_line(&file, &line), 0); + ExpectNull(file); + ExpectIntEQ(ERR_get_error_line_data(&file, &line, NULL, NULL), 0); PEMerr(4,4); - AssertIntEQ(ERR_get_error(), 4); + ExpectIntEQ(ERR_get_error(), 4); /* Empty and free up all error nodes */ ERR_clear_error(); /* Verify all nodes are cleared */ ERR_put_error(0,SYS_F_ACCEPT, 0, "this file", 0); ERR_clear_error(); - AssertIntEQ(ERR_get_error_line(&file, &line), 0); + ExpectIntEQ(ERR_get_error_line(&file, &line), 0); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -43764,18 +43763,20 @@ static int test_wolfSSL_ERR_get_error_order(void) { int res = TEST_SKIPPED; #ifdef WOLFSSL_HAVE_ERROR_QUEUE + EXPECT_DECLS; + /* Empty the queue. */ wolfSSL_ERR_clear_error(); wolfSSL_ERR_put_error(0, 0, ASN_NO_SIGNER_E, "test", 0); wolfSSL_ERR_put_error(0, 0, ASN_SELF_SIGNED_E, "test", 0); - AssertIntEQ(wolfSSL_ERR_peek_error(), -ASN_NO_SIGNER_E); - AssertIntEQ(wolfSSL_ERR_get_error(), -ASN_NO_SIGNER_E); - AssertIntEQ(wolfSSL_ERR_peek_error(), -ASN_SELF_SIGNED_E); - AssertIntEQ(wolfSSL_ERR_get_error(), -ASN_SELF_SIGNED_E); + ExpectIntEQ(wolfSSL_ERR_peek_error(), -ASN_NO_SIGNER_E); + ExpectIntEQ(wolfSSL_ERR_get_error(), -ASN_NO_SIGNER_E); + ExpectIntEQ(wolfSSL_ERR_peek_error(), -ASN_SELF_SIGNED_E); + ExpectIntEQ(wolfSSL_ERR_get_error(), -ASN_SELF_SIGNED_E); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* WOLFSSL_HAVE_ERROR_QUEUE */ return res; } @@ -43785,32 +43786,35 @@ static int test_wolfSSL_ERR_get_error_order(void) static int test_wolfSSL_ERR_print_errors(void) { int res = TEST_SKIPPED; - #if !defined(NO_ERROR_QUEUE) && defined(OPENSSL_EXTRA) && \ - defined(DEBUG_WOLFSSL) && !defined(NO_ERROR_STRINGS) - BIO* bio; +#if !defined(NO_ERROR_QUEUE) && defined(OPENSSL_EXTRA) && \ + defined(DEBUG_WOLFSSL) && !defined(NO_ERROR_STRINGS) + EXPECT_DECLS; + BIO* bio = NULL; char buf[1024]; - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); ERR_clear_error(); /* clear out any error nodes */ ERR_put_error(0,SYS_F_ACCEPT, -173, "ssl.c", 0); /* Choosing -299 as an unused errno between MIN_CODE_E < x < WC_LAST_E. */ ERR_put_error(0,SYS_F_BIND, -299, "asn.c", 100); ERR_print_errors(bio); - AssertIntEQ(BIO_gets(bio, buf, sizeof(buf)), 56); - AssertIntEQ(XSTRNCMP("error:173:wolfSSL library:Bad function argument:ssl.c:0", - buf, 55), 0); - AssertIntEQ(BIO_gets(bio, buf, sizeof(buf)), 57); - AssertIntEQ(XSTRNCMP("error:299:wolfSSL library:unknown error number:asn.c:100", - buf, 56), 0); - AssertIntEQ(BIO_gets(bio, buf, sizeof(buf)), 1); - AssertIntEQ(buf[0], '\0'); - AssertIntEQ(ERR_get_error_line(NULL, NULL), 0); + ExpectIntEQ(BIO_gets(bio, buf, sizeof(buf)), 56); + ExpectIntEQ(XSTRNCMP( + "error:173:wolfSSL library:Bad function argument:ssl.c:0", + buf, 55), 0); + ExpectIntEQ(BIO_gets(bio, buf, sizeof(buf)), 57); + ExpectIntEQ(XSTRNCMP( + "error:299:wolfSSL library:unknown error number:asn.c:100", + buf, 56), 0); + ExpectIntEQ(BIO_gets(bio, buf, sizeof(buf)), 1); + ExpectIntEQ(buf[0], '\0'); + ExpectIntEQ(ERR_get_error_line(NULL, NULL), 0); BIO_free(bio); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -43829,7 +43833,7 @@ static int test_wolfSSL_ERR_print_errors_cb(void) #if !defined(NO_ERROR_QUEUE) && defined(OPENSSL_EXTRA) && \ defined(DEBUG_WOLFSSL) EXPECT_DECLS; - BIO* bio; + BIO* bio = NULL; char buf[1024]; ExpectNotNull(bio = BIO_new(BIO_s_mem())); @@ -43948,33 +43952,34 @@ static int test_wolfSSL_GetLoggingCb(void) defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA3)) static int test_openssl_hmac(const WOLFSSL_EVP_MD* md, int md_len) { + EXPECT_DECLS; static const unsigned char key[] = "simple test key"; - HMAC_CTX* hmac; + HMAC_CTX* hmac = NULL; ENGINE* e = NULL; unsigned char hash[WC_MAX_DIGEST_SIZE]; unsigned int len; - AssertNotNull(hmac = HMAC_CTX_new()); + ExpectNotNull(hmac = HMAC_CTX_new()); HMAC_CTX_init(hmac); - AssertIntEQ(HMAC_Init_ex(hmac, (void*)key, (int)sizeof(key), md, e), + ExpectIntEQ(HMAC_Init_ex(hmac, (void*)key, (int)sizeof(key), md, e), SSL_SUCCESS); /* re-using test key as data to hash */ - AssertIntEQ(HMAC_Update(hmac, key, (int)sizeof(key)), SSL_SUCCESS); - AssertIntEQ(HMAC_Update(hmac, NULL, 0), SSL_SUCCESS); - AssertIntEQ(HMAC_Final(hmac, hash, &len), SSL_SUCCESS); - AssertIntEQ(len, md_len); - AssertIntEQ(HMAC_size(hmac), md_len); - AssertStrEQ(HMAC_CTX_get_md(hmac), md); + ExpectIntEQ(HMAC_Update(hmac, key, (int)sizeof(key)), SSL_SUCCESS); + ExpectIntEQ(HMAC_Update(hmac, NULL, 0), SSL_SUCCESS); + ExpectIntEQ(HMAC_Final(hmac, hash, &len), SSL_SUCCESS); + ExpectIntEQ(len, md_len); + ExpectIntEQ(HMAC_size(hmac), md_len); + ExpectStrEQ(HMAC_CTX_get_md(hmac), md); HMAC_cleanup(hmac); HMAC_CTX_free(hmac); len = 0; - AssertNotNull(HMAC(md, key, (int)sizeof(key), NULL, 0, hash, &len)); - AssertIntEQ(len, md_len); + ExpectNotNull(HMAC(md, key, (int)sizeof(key), NULL, 0, hash, &len)); + ExpectIntEQ(len, md_len); - return 0; + return EXPECT_RESULT(); } #endif @@ -43984,37 +43989,47 @@ static int test_wolfSSL_HMAC(void) #if defined(OPENSSL_EXTRA) && (!defined(NO_SHA256) || \ defined(WOLFSSL_SHA224) || defined(WOLFSSL_SHA384) || \ defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA3)) - #ifndef NO_SHA256 - test_openssl_hmac(EVP_sha256(), (int)WC_SHA256_DIGEST_SIZE); - #endif - #ifdef WOLFSSL_SHA224 - test_openssl_hmac(EVP_sha224(), (int)WC_SHA224_DIGEST_SIZE); - #endif - #ifdef WOLFSSL_SHA384 - test_openssl_hmac(EVP_sha384(), (int)WC_SHA384_DIGEST_SIZE); + EXPECT_DECLS; +#ifndef NO_SHA256 + ExpectIntEQ(test_openssl_hmac(EVP_sha256(), (int)WC_SHA256_DIGEST_SIZE), + TEST_SUCCESS); +#endif +#ifdef WOLFSSL_SHA224 + ExpectIntEQ(test_openssl_hmac(EVP_sha224(), (int)WC_SHA224_DIGEST_SIZE), + TEST_SUCCESS); +#endif +#ifdef WOLFSSL_SHA384 + ExpectIntEQ(test_openssl_hmac(EVP_sha384(), (int)WC_SHA384_DIGEST_SIZE), + TEST_SUCCESS); +#endif +#ifdef WOLFSSL_SHA512 + ExpectIntEQ(test_openssl_hmac(EVP_sha512(), (int)WC_SHA512_DIGEST_SIZE), + TEST_SUCCESS); +#endif +#ifdef WOLFSSL_SHA3 + #ifndef WOLFSSL_NOSHA3_224 + ExpectIntEQ(test_openssl_hmac(EVP_sha3_224(), + (int)WC_SHA3_224_DIGEST_SIZE), TEST_SUCCESS); #endif - #ifdef WOLFSSL_SHA512 - test_openssl_hmac(EVP_sha512(), (int)WC_SHA512_DIGEST_SIZE); + #ifndef WOLFSSL_NOSHA3_256 + ExpectIntEQ(test_openssl_hmac(EVP_sha3_256(), + (int)WC_SHA3_256_DIGEST_SIZE), TEST_SUCCESS); #endif - #ifdef WOLFSSL_SHA3 - #ifndef WOLFSSL_NOSHA3_224 - test_openssl_hmac(EVP_sha3_224(), (int)WC_SHA3_224_DIGEST_SIZE); - #endif - #ifndef WOLFSSL_NOSHA3_256 - test_openssl_hmac(EVP_sha3_256(), (int)WC_SHA3_256_DIGEST_SIZE); - #endif - #ifndef WOLFSSL_NOSHA3_384 - test_openssl_hmac(EVP_sha3_384(), (int)WC_SHA3_384_DIGEST_SIZE); - #endif - #ifndef WOLFSSL_NOSHA3_512 - test_openssl_hmac(EVP_sha3_512(), (int)WC_SHA3_512_DIGEST_SIZE); - #endif + #ifndef WOLFSSL_NOSHA3_384 + ExpectIntEQ(test_openssl_hmac(EVP_sha3_384(), + (int)WC_SHA3_384_DIGEST_SIZE), TEST_SUCCESS); #endif - #ifndef NO_SHA - test_openssl_hmac(EVP_sha1(), (int)WC_SHA_DIGEST_SIZE); + #ifndef WOLFSSL_NOSHA3_512 + ExpectIntEQ(test_openssl_hmac(EVP_sha3_512(), + (int)WC_SHA3_512_DIGEST_SIZE), TEST_SUCCESS); #endif +#endif +#ifndef NO_SHA + ExpectIntEQ(test_openssl_hmac(EVP_sha1(), (int)WC_SHA_DIGEST_SIZE), + TEST_SUCCESS); +#endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44024,6 +44039,7 @@ static int test_wolfSSL_CMAC(void) int res = TEST_SKIPPED; #if defined(WOLFSSL_CMAC) && defined(OPENSSL_EXTRA) && \ defined(WOLFSSL_AES_DIRECT) + EXPECT_DECLS; int i; byte key[AES_128_KEY_SIZE]; CMAC_CTX* cmacCtx = NULL; @@ -44033,27 +44049,27 @@ static int test_wolfSSL_CMAC(void) for (i=0; i < AES_128_KEY_SIZE; ++i) { key[i] = i; } - AssertNotNull(cmacCtx = CMAC_CTX_new()); + ExpectNotNull(cmacCtx = CMAC_CTX_new()); /* Check CMAC_CTX_get0_cipher_ctx; return value not used. */ - AssertNotNull(CMAC_CTX_get0_cipher_ctx(cmacCtx)); - AssertIntEQ(CMAC_Init(cmacCtx, key, AES_128_KEY_SIZE, EVP_aes_128_cbc(), + ExpectNotNull(CMAC_CTX_get0_cipher_ctx(cmacCtx)); + ExpectIntEQ(CMAC_Init(cmacCtx, key, AES_128_KEY_SIZE, EVP_aes_128_cbc(), NULL), SSL_SUCCESS); /* re-using test key as data to hash */ - AssertIntEQ(CMAC_Update(cmacCtx, key, AES_128_KEY_SIZE), SSL_SUCCESS); - AssertIntEQ(CMAC_Update(cmacCtx, NULL, 0), SSL_SUCCESS); - AssertIntEQ(CMAC_Final(cmacCtx, out, &outLen), SSL_SUCCESS); - AssertIntEQ(outLen, AES_BLOCK_SIZE); + ExpectIntEQ(CMAC_Update(cmacCtx, key, AES_128_KEY_SIZE), SSL_SUCCESS); + ExpectIntEQ(CMAC_Update(cmacCtx, NULL, 0), SSL_SUCCESS); + ExpectIntEQ(CMAC_Final(cmacCtx, out, &outLen), SSL_SUCCESS); + ExpectIntEQ(outLen, AES_BLOCK_SIZE); CMAC_CTX_free(cmacCtx); /* give a key too small for the cipher, verify we get failure */ cmacCtx = NULL; - AssertNotNull(cmacCtx = CMAC_CTX_new()); - AssertNotNull(CMAC_CTX_get0_cipher_ctx(cmacCtx)); - AssertIntEQ(CMAC_Init(cmacCtx, key, AES_128_KEY_SIZE, EVP_aes_192_cbc(), + ExpectNotNull(cmacCtx = CMAC_CTX_new()); + ExpectNotNull(CMAC_CTX_get0_cipher_ctx(cmacCtx)); + ExpectIntEQ(CMAC_Init(cmacCtx, key, AES_128_KEY_SIZE, EVP_aes_192_cbc(), NULL), SSL_FAILURE); CMAC_CTX_free(cmacCtx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* WOLFSSL_CMAC && OPENSSL_EXTRA && WOLFSSL_AES_DIRECT */ return res; } @@ -44068,27 +44084,28 @@ static int test_wolfSSL_OBJ(void) #if defined(OPENSSL_EXTRA) && !defined(NO_SHA256) && !defined(NO_ASN) && \ !defined(HAVE_FIPS) && !defined(NO_SHA) && defined(WOLFSSL_CERT_EXT) && \ defined(WOLFSSL_CERT_GEN) && !defined(NO_BIO) + EXPECT_DECLS; ASN1_OBJECT *obj = NULL; ASN1_OBJECT *obj2 = NULL; char buf[50]; - XFILE fp; + XFILE fp = XBADFILE; X509 *x509 = NULL; - X509_NAME *x509Name; - X509_NAME_ENTRY *x509NameEntry; + X509_NAME *x509Name = NULL; + X509_NAME_ENTRY *x509NameEntry = NULL; ASN1_OBJECT *asn1Name = NULL; - int numNames; + int numNames = 0; BIO *bio = NULL; int nid; int i, j; const char *f[] = { - #ifndef NO_RSA + #ifndef NO_RSA "./certs/ca-cert.der", - #endif - #ifdef HAVE_ECC + #endif + #ifdef HAVE_ECC "./certs/ca-ecc-cert.der", "./certs/ca-ecc384-cert.der", - #endif + #endif NULL}; ASN1_OBJECT *field_name_obj = NULL; int lastpos = -1; @@ -44096,67 +44113,77 @@ static int test_wolfSSL_OBJ(void) ASN1_STRING *asn1 = NULL; unsigned char *buf_dyn = NULL; - AssertIntEQ(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1), SSL_FAILURE); - AssertNotNull(obj = OBJ_nid2obj(NID_any_policy)); - AssertIntEQ(OBJ_obj2nid(obj), NID_any_policy); - AssertIntEQ(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1), 11); - AssertIntGT(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 0), 0); + ExpectIntEQ(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1), SSL_FAILURE); + ExpectNotNull(obj = OBJ_nid2obj(NID_any_policy)); + ExpectIntEQ(OBJ_obj2nid(obj), NID_any_policy); + ExpectIntEQ(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1), 11); + ExpectIntGT(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 0), 0); ASN1_OBJECT_free(obj); + obj = NULL; - AssertNotNull(obj = OBJ_nid2obj(NID_sha256)); - AssertIntEQ(OBJ_obj2nid(obj), NID_sha256); - AssertIntEQ(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1), 22); + ExpectNotNull(obj = OBJ_nid2obj(NID_sha256)); + ExpectIntEQ(OBJ_obj2nid(obj), NID_sha256); + ExpectIntEQ(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1), 22); #ifdef WOLFSSL_CERT_EXT - AssertIntEQ(OBJ_txt2nid(buf), NID_sha256); + ExpectIntEQ(OBJ_txt2nid(buf), NID_sha256); #endif - AssertIntGT(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 0), 0); - AssertNotNull(obj2 = OBJ_dup(obj)); - AssertIntEQ(OBJ_cmp(obj, obj2), 0); + ExpectIntGT(OBJ_obj2txt(buf, (int)sizeof(buf), obj, 0), 0); + ExpectNotNull(obj2 = OBJ_dup(obj)); + ExpectIntEQ(OBJ_cmp(obj, obj2), 0); ASN1_OBJECT_free(obj); + obj = NULL; ASN1_OBJECT_free(obj2); + obj2 = NULL; for (i = 0; f[i] != NULL; i++) { - AssertTrue((fp = XFOPEN(f[i], "rb")) != XBADFILE); - AssertNotNull(x509 = d2i_X509_fp(fp, NULL)); - XFCLOSE(fp); - AssertNotNull(x509Name = X509_get_issuer_name(x509)); - AssertIntNE((numNames = X509_NAME_entry_count(x509Name)), 0); + ExpectTrue((fp = XFOPEN(f[i], "rb")) != XBADFILE); + ExpectNotNull(x509 = d2i_X509_fp(fp, NULL)); + if (fp != XBADFILE) { + XFCLOSE(fp); + fp = XBADFILE; + } + ExpectNotNull(x509Name = X509_get_issuer_name(x509)); + ExpectIntNE((numNames = X509_NAME_entry_count(x509Name)), 0); /* Get the Common Name by using OBJ_txt2obj */ - AssertNotNull(field_name_obj = OBJ_txt2obj("CN", 0)); + ExpectNotNull(field_name_obj = OBJ_txt2obj("CN", 0)); do { lastpos = tmp; tmp = X509_NAME_get_index_by_OBJ(x509Name, field_name_obj, lastpos); } while (tmp > -1); - AssertIntNE(lastpos, -1); + ExpectIntNE(lastpos, -1); ASN1_OBJECT_free(field_name_obj); - AssertNotNull(x509NameEntry = X509_NAME_get_entry(x509Name, lastpos)); - AssertNotNull(asn1 = X509_NAME_ENTRY_get_data(x509NameEntry)); - AssertIntGE(ASN1_STRING_to_UTF8(&buf_dyn, asn1), 0); + field_name_obj = NULL; + ExpectNotNull(x509NameEntry = X509_NAME_get_entry(x509Name, lastpos)); + ExpectNotNull(asn1 = X509_NAME_ENTRY_get_data(x509NameEntry)); + ExpectIntGE(ASN1_STRING_to_UTF8(&buf_dyn, asn1), 0); /* * All Common Names should be www.wolfssl.com * This makes testing easier as we can test for the expected value. */ - AssertStrEQ((char*)buf_dyn, "www.wolfssl.com"); + ExpectStrEQ((char*)buf_dyn, "www.wolfssl.com"); OPENSSL_free(buf_dyn); + buf_dyn = NULL; bio = BIO_new(BIO_s_mem()); - AssertTrue(bio != NULL); + ExpectTrue(bio != NULL); for (j = 0; j < numNames; j++) { - AssertNotNull(x509NameEntry = X509_NAME_get_entry(x509Name, j)); - AssertNotNull(asn1Name = X509_NAME_ENTRY_get_object(x509NameEntry)); - AssertTrue((nid = OBJ_obj2nid(asn1Name)) > 0); + ExpectNotNull(x509NameEntry = X509_NAME_get_entry(x509Name, j)); + ExpectNotNull(asn1Name = X509_NAME_ENTRY_get_object(x509NameEntry)); + ExpectTrue((nid = OBJ_obj2nid(asn1Name)) > 0); } BIO_free(bio); + bio = NULL; X509_free(x509); + x509 = NULL; } #ifdef HAVE_PKCS12 { - PKCS12 *p12; + PKCS12 *p12 = NULL; int boolRet; EVP_PKEY *pkey = NULL; const char *p12_f[] = { @@ -44167,31 +44194,37 @@ static int test_wolfSSL_OBJ(void) for (i = 0; p12_f[i] != NULL; i++) { - AssertTrue((fp = XFOPEN(p12_f[i], "rb")) != XBADFILE); - AssertNotNull(p12 = d2i_PKCS12_fp(fp, NULL)); - XFCLOSE(fp); - AssertTrue((boolRet = PKCS12_parse(p12, "wolfSSL test", + ExpectTrue((fp = XFOPEN(p12_f[i], "rb")) != XBADFILE); + ExpectNotNull(p12 = d2i_PKCS12_fp(fp, NULL)); + if (fp != XBADFILE) { + XFCLOSE(fp); + fp = XBADFILE; + } + ExpectTrue((boolRet = PKCS12_parse(p12, "wolfSSL test", &pkey, &x509, NULL)) > 0); wc_PKCS12_free(p12); + p12 = NULL; EVP_PKEY_free(pkey); x509Name = X509_get_issuer_name(x509); - AssertNotNull(x509Name); - AssertIntNE((numNames = X509_NAME_entry_count(x509Name)), 0); - AssertTrue((bio = BIO_new(BIO_s_mem())) != NULL); + ExpectNotNull(x509Name); + ExpectIntNE((numNames = X509_NAME_entry_count(x509Name)), 0); + ExpectTrue((bio = BIO_new(BIO_s_mem())) != NULL); for (j = 0; j < numNames; j++) { - AssertNotNull(x509NameEntry = X509_NAME_get_entry(x509Name, j)); - AssertNotNull(asn1Name = + ExpectNotNull(x509NameEntry = X509_NAME_get_entry(x509Name, j)); + ExpectNotNull(asn1Name = X509_NAME_ENTRY_get_object(x509NameEntry)); - AssertTrue((nid = OBJ_obj2nid(asn1Name)) > 0); + ExpectTrue((nid = OBJ_obj2nid(asn1Name)) > 0); } BIO_free(bio); + bio = NULL; X509_free(x509); + x509 = NULL; } } #endif /* HAVE_PKCS12 */ - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44200,23 +44233,24 @@ static int test_wolfSSL_OBJ_cmp(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_SHA256) + EXPECT_DECLS; ASN1_OBJECT *obj = NULL; ASN1_OBJECT *obj2 = NULL; - AssertNotNull(obj = OBJ_nid2obj(NID_any_policy)); - AssertNotNull(obj2 = OBJ_nid2obj(NID_sha256)); + ExpectNotNull(obj = OBJ_nid2obj(NID_any_policy)); + ExpectNotNull(obj2 = OBJ_nid2obj(NID_sha256)); - AssertIntEQ(OBJ_cmp(NULL, NULL), WOLFSSL_FATAL_ERROR); - AssertIntEQ(OBJ_cmp(obj, NULL), WOLFSSL_FATAL_ERROR); - AssertIntEQ(OBJ_cmp(NULL, obj2), WOLFSSL_FATAL_ERROR); - AssertIntEQ(OBJ_cmp(obj, obj2), WOLFSSL_FATAL_ERROR); - AssertIntEQ(OBJ_cmp(obj, obj), 0); - AssertIntEQ(OBJ_cmp(obj2, obj2), 0); + ExpectIntEQ(OBJ_cmp(NULL, NULL), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(OBJ_cmp(obj, NULL), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(OBJ_cmp(NULL, obj2), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(OBJ_cmp(obj, obj2), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(OBJ_cmp(obj, obj), 0); + ExpectIntEQ(OBJ_cmp(obj2, obj2), 0); ASN1_OBJECT_free(obj); ASN1_OBJECT_free(obj2); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44225,6 +44259,7 @@ static int test_wolfSSL_OBJ_txt2nid(void) { int res = TEST_SKIPPED; #if !defined(NO_WOLFSSL_STUB) && defined(WOLFSSL_APACHE_HTTPD) + EXPECT_DECLS; int i; static const struct { const char* sn; @@ -44241,17 +44276,17 @@ static int test_wolfSSL_OBJ_txt2nid(void) }; /* Invalid cases */ - AssertIntEQ(OBJ_txt2nid(NULL), NID_undef); - AssertIntEQ(OBJ_txt2nid("Bad name"), NID_undef); + ExpectIntEQ(OBJ_txt2nid(NULL), NID_undef); + ExpectIntEQ(OBJ_txt2nid("Bad name"), NID_undef); /* Valid cases */ for (i = 0; testVals[i].sn != NULL; i++) { - AssertIntEQ(OBJ_txt2nid(testVals[i].sn), testVals[i].nid); - AssertIntEQ(OBJ_txt2nid(testVals[i].ln), testVals[i].nid); - AssertIntEQ(OBJ_txt2nid(testVals[i].oid), testVals[i].nid); + ExpectIntEQ(OBJ_txt2nid(testVals[i].sn), testVals[i].nid); + ExpectIntEQ(OBJ_txt2nid(testVals[i].ln), testVals[i].nid); + ExpectIntEQ(OBJ_txt2nid(testVals[i].oid), testVals[i].nid); } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44261,9 +44296,10 @@ static int test_wolfSSL_OBJ_txt2obj(void) int res = TEST_SKIPPED; #if defined(WOLFSSL_APACHE_HTTPD) || (defined(OPENSSL_EXTRA) && \ defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)) + EXPECT_DECLS; int i; char buf[50]; - ASN1_OBJECT* obj; + ASN1_OBJECT* obj = NULL; static const struct { const char* oidStr; const char* sn; @@ -44287,47 +44323,51 @@ static int test_wolfSSL_OBJ_txt2obj(void) { NULL, NULL } }; - AssertNull(obj = OBJ_txt2obj("Bad name", 0)); - AssertNull(obj = OBJ_txt2obj(NULL, 0)); + ExpectNull(obj = OBJ_txt2obj("Bad name", 0)); + ExpectNull(obj = OBJ_txt2obj(NULL, 0)); for (i = 0; objs_list[i].oidStr != NULL; i++) { /* Test numerical value of oid (oidStr) */ - AssertNotNull(obj = OBJ_txt2obj(objs_list[i].oidStr, 1)); + ExpectNotNull(obj = OBJ_txt2obj(objs_list[i].oidStr, 1)); /* Convert object back to text to confirm oid is correct */ wolfSSL_OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1); - AssertIntEQ(XSTRNCMP(buf, objs_list[i].oidStr, (int)XSTRLEN(buf)), 0); + ExpectIntEQ(XSTRNCMP(buf, objs_list[i].oidStr, (int)XSTRLEN(buf)), 0); ASN1_OBJECT_free(obj); + obj = NULL; XMEMSET(buf, 0, sizeof(buf)); /* Test short name (sn) */ - AssertNull(obj = OBJ_txt2obj(objs_list[i].sn, 1)); - AssertNotNull(obj = OBJ_txt2obj(objs_list[i].sn, 0)); + ExpectNull(obj = OBJ_txt2obj(objs_list[i].sn, 1)); + ExpectNotNull(obj = OBJ_txt2obj(objs_list[i].sn, 0)); /* Convert object back to text to confirm oid is correct */ wolfSSL_OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1); - AssertIntEQ(XSTRNCMP(buf, objs_list[i].oidStr, (int)XSTRLEN(buf)), 0); + ExpectIntEQ(XSTRNCMP(buf, objs_list[i].oidStr, (int)XSTRLEN(buf)), 0); ASN1_OBJECT_free(obj); + obj = NULL; XMEMSET(buf, 0, sizeof(buf)); /* Test long name (ln) - should fail when no_name = 1 */ - AssertNull(obj = OBJ_txt2obj(objs_list[i].ln, 1)); - AssertNotNull(obj = OBJ_txt2obj(objs_list[i].ln, 0)); + ExpectNull(obj = OBJ_txt2obj(objs_list[i].ln, 1)); + ExpectNotNull(obj = OBJ_txt2obj(objs_list[i].ln, 0)); /* Convert object back to text to confirm oid is correct */ wolfSSL_OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1); - AssertIntEQ(XSTRNCMP(buf, objs_list[i].oidStr, (int)XSTRLEN(buf)), 0); + ExpectIntEQ(XSTRNCMP(buf, objs_list[i].oidStr, (int)XSTRLEN(buf)), 0); ASN1_OBJECT_free(obj); + obj = NULL; XMEMSET(buf, 0, sizeof(buf)); } for (i = 0; objs_named[i].numeric != NULL; i++) { - AssertNotNull(obj = OBJ_txt2obj(objs_named[i].numeric, 1)); + ExpectNotNull(obj = OBJ_txt2obj(objs_named[i].numeric, 1)); wolfSSL_OBJ_obj2txt(buf, (int)sizeof(buf), obj, 0); - AssertIntEQ(XSTRNCMP(buf, objs_named[i].name, (int)XSTRLEN(buf)), 0); + ExpectIntEQ(XSTRNCMP(buf, objs_named[i].name, (int)XSTRLEN(buf)), 0); wolfSSL_OBJ_obj2txt(buf, (int)sizeof(buf), obj, 1); - AssertIntEQ(XSTRNCMP(buf, objs_named[i].numeric, (int)XSTRLEN(buf)), 0); + ExpectIntEQ(XSTRNCMP(buf, objs_named[i].numeric, (int)XSTRLEN(buf)), 0); ASN1_OBJECT_free(obj); + obj = NULL; } - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44339,9 +44379,10 @@ static int test_wolfSSL_PEM_write_bio_X509(void) defined(WOLFSSL_AKID_NAME) && defined(WOLFSSL_CERT_EXT) && \ defined(WOLFSSL_CERT_GEN) && !defined(NO_BIO) && !defined(NO_RSA) && \ !defined(NO_FILESYSTEM) + EXPECT_DECLS; /* This test contains the hard coded expected * lengths. Update if necessary */ - FILE* fp = NULL; + XFILE fp = XBADFILE; WOLFSSL_EVP_PKEY *priv = NULL; BIO* input = NULL; @@ -44357,47 +44398,49 @@ static int test_wolfSSL_PEM_write_bio_X509(void) #endif int expectedLen; - fp = XFOPEN("certs/server-key.pem", "rb"); - AssertNotNull(fp); - priv = wolfSSL_PEM_read_PrivateKey(fp, NULL, NULL, NULL); - XFCLOSE(fp); - fp = NULL; - AssertNotNull(priv); + ExpectTrue((fp = XFOPEN("certs/server-key.pem", "rb")) != XBADFILE); + ExpectNotNull(priv = wolfSSL_PEM_read_PrivateKey(fp, NULL, NULL, NULL)); + if (fp != XBADFILE) { + XFCLOSE(fp); + fp = XBADFILE; + } - AssertNotNull(input = BIO_new_file( - "certs/test/cert-ext-multiple.pem", "rb")); - AssertIntEQ(wolfSSL_BIO_get_len(input), 2000); + ExpectNotNull(input = BIO_new_file("certs/test/cert-ext-multiple.pem", + "rb")); + ExpectIntEQ(wolfSSL_BIO_get_len(input), 2000); /* read PEM into X509 struct, get notBefore / notAfter to verify against */ - AssertNotNull(PEM_read_bio_X509(input, &x509a, NULL, NULL)); - AssertNotNull(notBeforeA = X509_get_notBefore(x509a)); - AssertNotNull(notAfterA = X509_get_notAfter(x509a)); + ExpectNotNull(PEM_read_bio_X509(input, &x509a, NULL, NULL)); + ExpectNotNull(notBeforeA = X509_get_notBefore(x509a)); + ExpectNotNull(notAfterA = X509_get_notAfter(x509a)); /* write X509 back to PEM BIO; no need to sign as nothing changed. */ - AssertNotNull(output = BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_X509(output, x509a), WOLFSSL_SUCCESS); + ExpectNotNull(output = BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_X509(output, x509a), WOLFSSL_SUCCESS); /* compare length against expected */ expectedLen = 2000; - AssertIntEQ(wolfSSL_BIO_get_len(output), expectedLen); + ExpectIntEQ(wolfSSL_BIO_get_len(output), expectedLen); #ifndef NO_ASN_TIME /* read exported X509 PEM back into struct, sanity check on export, * make sure notBefore/notAfter are the same and certs are identical. */ - AssertNotNull(PEM_read_bio_X509(output, &x509b, NULL, NULL)); - AssertNotNull(notBeforeB = X509_get_notBefore(x509b)); - AssertNotNull(notAfterB = X509_get_notAfter(x509b)); - AssertIntEQ(ASN1_TIME_compare(notBeforeA, notBeforeB), 0); - AssertIntEQ(ASN1_TIME_compare(notAfterA, notAfterB), 0); - AssertIntEQ(0, wolfSSL_X509_cmp(x509a, x509b)); + ExpectNotNull(PEM_read_bio_X509(output, &x509b, NULL, NULL)); + ExpectNotNull(notBeforeB = X509_get_notBefore(x509b)); + ExpectNotNull(notAfterB = X509_get_notAfter(x509b)); + ExpectIntEQ(ASN1_TIME_compare(notBeforeA, notBeforeB), 0); + ExpectIntEQ(ASN1_TIME_compare(notAfterA, notAfterB), 0); + ExpectIntEQ(0, wolfSSL_X509_cmp(x509a, x509b)); X509_free(x509b); + x509b = NULL; #endif /* Reset output buffer */ BIO_free(output); - AssertNotNull(output = BIO_new(wolfSSL_BIO_s_mem())); + output = NULL; + ExpectNotNull(output = BIO_new(wolfSSL_BIO_s_mem())); /* Test forcing the AKID to be generated just from KeyIdentifier */ - if (x509a->authKeyIdSrc != NULL) { + if (EXPECT_SUCCESS() && x509a->authKeyIdSrc != NULL) { XMEMMOVE(x509a->authKeyIdSrc, x509a->authKeyId, x509a->authKeyIdSz); x509a->authKeyId = x509a->authKeyIdSrc; x509a->authKeyIdSrc = NULL; @@ -44405,9 +44448,9 @@ static int test_wolfSSL_PEM_write_bio_X509(void) } /* Resign to re-generate the der */ - AssertIntGT(wolfSSL_X509_sign(x509a, priv, EVP_sha256()), 0); + ExpectIntGT(wolfSSL_X509_sign(x509a, priv, EVP_sha256()), 0); - AssertIntEQ(PEM_write_bio_X509(output, x509a), WOLFSSL_SUCCESS); + ExpectIntEQ(PEM_write_bio_X509(output, x509a), WOLFSSL_SUCCESS); /* Check that we generate a smaller output since the AKID will * only contain the KeyIdentifier without any additional @@ -44415,55 +44458,60 @@ static int test_wolfSSL_PEM_write_bio_X509(void) /* Here we copy the validity struct from the original */ expectedLen = 1688; - AssertIntEQ(wolfSSL_BIO_get_len(output), expectedLen); + ExpectIntEQ(wolfSSL_BIO_get_len(output), expectedLen); /* Reset buffers and x509 */ BIO_free(input); + input = NULL; BIO_free(output); + output = NULL; X509_free(x509a); + x509a = NULL; /* test CA and basicConstSet values are encoded when * the cert is a CA */ - AssertNotNull(input = BIO_new_file( - "certs/server-cert.pem", "rb")); + ExpectNotNull(input = BIO_new_file("certs/server-cert.pem", "rb")); /* read PEM into X509 struct */ - AssertNotNull(PEM_read_bio_X509(input, &x509a, NULL, NULL)); + ExpectNotNull(PEM_read_bio_X509(input, &x509a, NULL, NULL)); /* write X509 back to PEM BIO; no need to sign as nothing changed */ - AssertNotNull(output = BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_X509(output, x509a), WOLFSSL_SUCCESS); + ExpectNotNull(output = BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_X509(output, x509a), WOLFSSL_SUCCESS); /* read exported X509 PEM back into struct, ensure isCa and basicConstSet * values are maintained and certs are identical.*/ - AssertNotNull(PEM_read_bio_X509(output, &x509b, NULL, NULL)); - AssertIntEQ(x509b->isCa, 1); - AssertIntEQ(x509b->basicConstSet, 1); - AssertIntEQ(0, wolfSSL_X509_cmp(x509a, x509b)); + ExpectNotNull(PEM_read_bio_X509(output, &x509b, NULL, NULL)); + ExpectIntEQ(x509b->isCa, 1); + ExpectIntEQ(x509b->basicConstSet, 1); + ExpectIntEQ(0, wolfSSL_X509_cmp(x509a, x509b)); X509_free(x509a); + x509a = NULL; X509_free(x509b); + x509b = NULL; BIO_free(input); + input = NULL; BIO_free(output); + output = NULL; /* test CA and basicConstSet values are encoded when * the cert is not CA */ - AssertNotNull(input = BIO_new_file( - "certs/client-uri-cert.pem", "rb")); + ExpectNotNull(input = BIO_new_file("certs/client-uri-cert.pem", "rb")); /* read PEM into X509 struct */ - AssertNotNull(PEM_read_bio_X509(input, &x509a, NULL, NULL)); + ExpectNotNull(PEM_read_bio_X509(input, &x509a, NULL, NULL)); /* write X509 back to PEM BIO; no need to sign as nothing changed */ - AssertNotNull(output = BIO_new(wolfSSL_BIO_s_mem())); - AssertIntEQ(PEM_write_bio_X509(output, x509a), WOLFSSL_SUCCESS); + ExpectNotNull(output = BIO_new(wolfSSL_BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_X509(output, x509a), WOLFSSL_SUCCESS); /* read exported X509 PEM back into struct, ensure isCa and * basicConstSet values are maintained and certs are identical */ - AssertNotNull(PEM_read_bio_X509(output, &x509b, NULL, NULL)); - AssertIntEQ(x509b->isCa, 0); - AssertIntEQ(x509b->basicConstSet, 1); - AssertIntEQ(0, wolfSSL_X509_cmp(x509a, x509b)); + ExpectNotNull(PEM_read_bio_X509(output, &x509b, NULL, NULL)); + ExpectIntEQ(x509b->isCa, 0); + ExpectIntEQ(x509b->basicConstSet, 1); + ExpectIntEQ(0, wolfSSL_X509_cmp(x509a, x509b)); wolfSSL_EVP_PKEY_free(priv); X509_free(x509a); @@ -44471,7 +44519,7 @@ static int test_wolfSSL_PEM_write_bio_X509(void) BIO_free(input); BIO_free(output); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44481,36 +44529,38 @@ static int test_wolfSSL_X509_NAME_ENTRY(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) && \ !defined(NO_RSA) && defined(WOLFSSL_CERT_GEN) - X509* x509; + EXPECT_DECLS; + X509* x509 = NULL; #ifndef NO_BIO - BIO* bio; + BIO* bio = NULL; #endif - X509_NAME* nm; - X509_NAME_ENTRY* entry; + X509_NAME* nm = NULL; + X509_NAME_ENTRY* entry = NULL; unsigned char cn[] = "another name to add"; #ifdef OPENSSL_ALL - int i, names_len; + int i; + int names_len = 0; #endif - AssertNotNull(x509 = + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, SSL_FILETYPE_PEM)); #ifndef NO_BIO - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertIntEQ(PEM_write_bio_X509_AUX(bio, x509), SSL_SUCCESS); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_X509_AUX(bio, x509), SSL_SUCCESS); #endif #ifdef WOLFSSL_CERT_REQ { - X509_REQ* req; + X509_REQ* req = NULL; #ifndef NO_BIO - BIO* bReq; + BIO* bReq = NULL; #endif - AssertNotNull(req = + ExpectNotNull(req = wolfSSL_X509_load_certificate_file(cliCertFile, SSL_FILETYPE_PEM)); #ifndef NO_BIO - AssertNotNull(bReq = BIO_new(BIO_s_mem())); - AssertIntEQ(PEM_write_bio_X509_REQ(bReq, req), SSL_SUCCESS); + ExpectNotNull(bReq = BIO_new(BIO_s_mem())); + ExpectIntEQ(PEM_write_bio_X509_REQ(bReq, req), SSL_SUCCESS); BIO_free(bReq); #endif @@ -44518,39 +44568,42 @@ static int test_wolfSSL_X509_NAME_ENTRY(void) } #endif - AssertNotNull(nm = X509_get_subject_name(x509)); + ExpectNotNull(nm = X509_get_subject_name(x509)); /* Test add entry */ - AssertNotNull(entry = X509_NAME_ENTRY_create_by_NID(NULL, NID_commonName, + ExpectNotNull(entry = X509_NAME_ENTRY_create_by_NID(NULL, NID_commonName, 0x0c, cn, (int)sizeof(cn))); - AssertIntEQ(X509_NAME_add_entry(nm, entry, -1, 0), SSL_SUCCESS); + ExpectIntEQ(X509_NAME_add_entry(nm, entry, -1, 0), SSL_SUCCESS); #ifdef WOLFSSL_CERT_EXT - AssertIntEQ(X509_NAME_add_entry_by_txt(nm, "emailAddress", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(nm, "emailAddress", MBSTRING_UTF8, (byte*)"support@wolfssl.com", 19, -1, 1), WOLFSSL_SUCCESS); #endif X509_NAME_ENTRY_free(entry); + entry = NULL; #ifdef WOLFSSL_CERT_REQ { unsigned char srv_pkcs9p[] = "Server"; unsigned char fvrtDrnk[] = "tequila"; unsigned char* der = NULL; - char* subject; - AssertIntEQ(X509_NAME_add_entry_by_NID(nm, NID_pkcs9_contentType, + char* subject = NULL; + ExpectIntEQ(X509_NAME_add_entry_by_NID(nm, NID_pkcs9_contentType, MBSTRING_ASC, srv_pkcs9p, -1, -1, 0), SSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_NID(nm, NID_favouriteDrink, + ExpectIntEQ(X509_NAME_add_entry_by_NID(nm, NID_favouriteDrink, MBSTRING_ASC, fvrtDrnk, -1, -1, 0), SSL_SUCCESS); - AssertIntGT(wolfSSL_i2d_X509_NAME(nm, &der), 0); - AssertNotNull(der); + ExpectIntGT(wolfSSL_i2d_X509_NAME(nm, &der), 0); + ExpectNotNull(der); - subject = X509_NAME_oneline(nm, 0, 0); - AssertNotNull(XSTRSTR(subject, "favouriteDrink=tequila")); + ExpectNotNull(subject = X509_NAME_oneline(nm, 0, 0)); + ExpectNotNull(XSTRSTR(subject, "favouriteDrink=tequila")); #ifdef DEBUG_WOLFSSL - fprintf(stderr, "\n\t%s\n", subject); + if (subject != NULL) { + fprintf(stderr, "\n\t%s\n", subject); + } #endif XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL); XFREE(der, NULL, DYNAMIC_TYPE_OPENSSL); @@ -44558,25 +44611,26 @@ static int test_wolfSSL_X509_NAME_ENTRY(void) #endif /* Test add entry by text */ - AssertNotNull(entry = X509_NAME_ENTRY_create_by_txt(NULL, "commonName", + ExpectNotNull(entry = X509_NAME_ENTRY_create_by_txt(NULL, "commonName", 0x0c, cn, (int)sizeof(cn))); #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) \ || defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) - AssertNull(X509_NAME_ENTRY_create_by_txt(&entry, "unknown", + ExpectNull(X509_NAME_ENTRY_create_by_txt(&entry, "unknown", V_ASN1_UTF8STRING, cn, (int)sizeof(cn))); #endif - AssertIntEQ(X509_NAME_add_entry(nm, entry, -1, 0), SSL_SUCCESS); + ExpectIntEQ(X509_NAME_add_entry(nm, entry, -1, 0), SSL_SUCCESS); X509_NAME_ENTRY_free(entry); + entry = NULL; /* Test add entry by NID */ - AssertIntEQ(X509_NAME_add_entry_by_NID(nm, NID_commonName, MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_NID(nm, NID_commonName, MBSTRING_UTF8, cn, -1, -1, 0), SSL_SUCCESS); #ifdef OPENSSL_ALL /* stack of name entry */ - AssertIntGT((names_len = sk_X509_NAME_ENTRY_num(nm->entries)), 0); - for (i=0; ientries, i)); + ExpectIntGT((names_len = sk_X509_NAME_ENTRY_num(nm->entries)), 0); + for (i = 0; i < names_len; i++) { + ExpectNotNull(entry = sk_X509_NAME_ENTRY_value(nm->entries, i)); } #endif @@ -44585,7 +44639,7 @@ static int test_wolfSSL_X509_NAME_ENTRY(void) #endif X509_free(x509); /* free's nm */ - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44598,11 +44652,11 @@ static int test_GENERAL_NAME_set0_othername(void) { defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ALT_NAMES) && \ defined(WOLFSSL_CERT_EXT) && !defined(NO_FILESYSTEM) && \ defined(WOLFSSL_FPKI) - /* ./configure --enable-opensslall --enable-certgen --enable-certreq * --enable-certext --enable-debug 'CPPFLAGS=-DWOLFSSL_CUSTOM_OID * -DWOLFSSL_ALT_NAMES -DWOLFSSL_FPKI' */ + EXPECT_DECLS; const char * cert_fname = "./certs/server-cert.der"; const char * key_fname = "./certs/server-key.der"; X509* x509 = NULL; @@ -44617,66 +44671,63 @@ static int test_GENERAL_NAME_set0_othername(void) { byte der[4096]; int derSz = 0; EVP_PKEY* priv = NULL; - FILE* f = NULL; - /* The length of this buffer is 37 */ - const unsigned char expected_asn1[] = { - /* OID specifier and length */ - 0x06, 0x0A, - /* 1.3.6.1.4.1.311.20.2.3 */ - 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x14, 0x02, 0x03, - /* TODO */ - 0xA0, 0x17, 0x0C, 0x15, - /* othername@wolfssl.com */ - 0x6F, 0x74, 0x68, 0x65, 0x72, 0x6E, 0x61, 0x6D, 0x65, 0x40, 0x77, 0x6F, - 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D - }; + XFILE f = XBADFILE; - AssertNotNull(f = fopen(cert_fname, "rb")); - AssertNotNull(x509 = d2i_X509_fp(f, NULL)); - fclose(f); - AssertNotNull(gn = GENERAL_NAME_new()); - AssertNotNull(upn_oid = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1)); - AssertNotNull(utf8str = ASN1_UTF8STRING_new()); - AssertIntEQ(ASN1_STRING_set(utf8str, "othername@wolfssl.com", -1), 1); - AssertNotNull(value = ASN1_TYPE_new()); + ExpectTrue((f = XFOPEN(cert_fname, "rb")) != XBADFILE); + ExpectNotNull(x509 = d2i_X509_fp(f, NULL)); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } + ExpectNotNull(gn = GENERAL_NAME_new()); + ExpectNotNull(upn_oid = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1)); + ExpectNotNull(utf8str = ASN1_UTF8STRING_new()); + ExpectIntEQ(ASN1_STRING_set(utf8str, "othername@wolfssl.com", -1), 1); + ExpectNotNull(value = ASN1_TYPE_new()); ASN1_TYPE_set(value, V_ASN1_UTF8STRING, utf8str); - AssertIntEQ(GENERAL_NAME_set0_othername(gn, upn_oid, value), 1); - AssertNotNull(gns = sk_GENERAL_NAME_new(NULL)); - AssertIntEQ(sk_GENERAL_NAME_push(gns, gn), 1); - AssertNotNull(ext = X509V3_EXT_i2d(NID_subject_alt_name, 0, gns)); - AssertIntEQ(X509_add_ext(x509, ext, -1), 1); - AssertNotNull(f = fopen(key_fname, "rb")); - AssertIntGT(derSz = (int)fread(der, 1, sizeof(der), f), 0); - fclose(f); + if ((value == NULL) || (value->value.ptr != (char*)utf8str)) { + wolfSSL_ASN1_STRING_free(utf8str); + } + ExpectIntEQ(GENERAL_NAME_set0_othername(gn, upn_oid, value), 1); + if (EXPECT_FAIL()) { + ASN1_TYPE_free(value); + } + ExpectNotNull(gns = sk_GENERAL_NAME_new(NULL)); + ExpectIntEQ(sk_GENERAL_NAME_push(gns, gn), 1); + if (EXPECT_FAIL()) { + GENERAL_NAME_free(gn); + gn = NULL; + } + ExpectNotNull(ext = X509V3_EXT_i2d(NID_subject_alt_name, 0, gns)); + ExpectIntEQ(X509_add_ext(x509, ext, -1), 1); + ExpectTrue((f = XFOPEN(key_fname, "rb")) != XBADFILE); + ExpectIntGT(derSz = (int)XFREAD(der, 1, sizeof(der), f), 0); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } pt = der; - AssertNotNull(priv = d2i_PrivateKey(EVP_PKEY_RSA, NULL, - (const unsigned char**)&pt, derSz)); - AssertIntGT(X509_sign(x509, priv, EVP_sha256()), 0); + ExpectNotNull(priv = d2i_PrivateKey(EVP_PKEY_RSA, NULL, + (const unsigned char**)&pt, derSz)); + ExpectIntGT(X509_sign(x509, priv, EVP_sha256()), 0); sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); - AssertNotNull(gns = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, - NULL)); + gns = NULL; + ExpectNotNull(gns = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, + NULL)); - AssertIntEQ(sk_GENERAL_NAME_num(gns), 3); + ExpectIntEQ(sk_GENERAL_NAME_num(gns), 3); - AssertNotNull(gn = sk_GENERAL_NAME_value(gns, 2)); - AssertIntEQ(gn->type, 0); + ExpectNotNull(gn = sk_GENERAL_NAME_value(gns, 2)); + ExpectIntEQ(gn->type, 0); - /* It is odd that we are using ASN_RFC822_TYPE. It is because when we are - * parsing der, the string is not fully parsed. It is still raw der whereas - * when we encode we set the oid (for example, upn) and value. As we are - * overloading the meaning of the type, here we manually do the right thing. - */ - AssertIntEQ(ASN1_STRING_length(gn->d.rfc822Name), 37); - AssertIntEQ(XMEMCMP(ASN1_STRING_data(gn->d.rfc822Name), expected_asn1, 37), - 0); - gn->type = ASN_RFC822_TYPE; sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); ASN1_OBJECT_free(upn_oid); X509_EXTENSION_free(ext); X509_free(x509); EVP_PKEY_free(priv); - res = TEST_RES_CHECK(1); + + res = EXPECT_RESULT(); #endif return res; } @@ -44694,7 +44745,7 @@ static int test_othername_and_SID_ext(void) { * --enable-certext --enable-debug 'CPPFLAGS=-DWOLFSSL_CUSTOM_OID * -DWOLFSSL_ALT_NAMES -DWOLFSSL_FPKI' */ - + EXPECT_DECLS; const char* csr_fname = "./certs/csr.signed.der"; const char* key_fname = "./certs/server-key.der"; @@ -44732,46 +44783,69 @@ static int test_othername_and_SID_ext(void) { ASN1_OCTET_STRING *sid_data = NULL; EVP_PKEY* priv = NULL; - FILE* f = NULL; + XFILE f = XBADFILE; byte* pt = NULL; BIO* bio = NULL; - AssertNotNull(f = fopen(csr_fname, "rb")); - AssertNotNull(x509 = d2i_X509_REQ_fp(f, NULL)); - fclose(f); - AssertIntEQ(X509_REQ_set_version(x509, 2), 1); - AssertNotNull(gn = GENERAL_NAME_new()); - AssertNotNull(upn_oid = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1)); - AssertNotNull(utf8str = ASN1_UTF8STRING_new()); - AssertIntEQ(ASN1_STRING_set(utf8str, "othername@wolfssl.com", -1), 1); - AssertNotNull(value = ASN1_TYPE_new()); + ExpectTrue((f = XFOPEN(csr_fname, "rb")) != XBADFILE); + ExpectNotNull(x509 = d2i_X509_REQ_fp(f, NULL)); + if (f != XBADFILE) { + XFCLOSE(f); + f = XBADFILE; + } + ExpectIntEQ(X509_REQ_set_version(x509, 2), 1); + ExpectNotNull(gn = GENERAL_NAME_new()); + ExpectNotNull(upn_oid = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1)); + ExpectNotNull(utf8str = ASN1_UTF8STRING_new()); + ExpectIntEQ(ASN1_STRING_set(utf8str, "othername@wolfssl.com", -1), 1); + ExpectNotNull(value = ASN1_TYPE_new()); ASN1_TYPE_set(value, V_ASN1_UTF8STRING, utf8str); - AssertIntEQ(GENERAL_NAME_set0_othername(gn, upn_oid, value), 1); - AssertNotNull(gns = sk_GENERAL_NAME_new(NULL)); - AssertIntEQ(sk_GENERAL_NAME_push(gns, gn), 1); - AssertNotNull(san_ext = X509V3_EXT_i2d(NID_subject_alt_name, 0, gns)); - AssertNotNull(sid_oid = OBJ_txt2obj("1.3.6.1.4.1.311.25.2", 1)); - AssertNotNull(sid_data = ASN1_OCTET_STRING_new()); + if (EXPECT_FAIL()) { + ASN1_UTF8STRING_free(utf8str); + } + ExpectIntEQ(GENERAL_NAME_set0_othername(gn, upn_oid, value), 1); + if (EXPECT_FAIL()) { + ASN1_TYPE_free(value); + GENERAL_NAME_free(gn); + gn = NULL; + } + ExpectNotNull(gns = sk_GENERAL_NAME_new(NULL)); + ExpectIntEQ(sk_GENERAL_NAME_push(gns, gn), 1); + if (EXPECT_FAIL()) { + GENERAL_NAME_free(gn); + } + ExpectNotNull(san_ext = X509V3_EXT_i2d(NID_subject_alt_name, 0, gns)); + ExpectNotNull(sid_oid = OBJ_txt2obj("1.3.6.1.4.1.311.25.2", 1)); + ExpectNotNull(sid_data = ASN1_OCTET_STRING_new()); ASN1_OCTET_STRING_set(sid_data, SidExtension, sizeof(SidExtension)); - AssertNotNull(sid_ext = X509_EXTENSION_create_by_OBJ(NULL, sid_oid, 0, + ExpectNotNull(sid_ext = X509_EXTENSION_create_by_OBJ(NULL, sid_oid, 0, sid_data)); - AssertNotNull(exts = sk_X509_EXTENSION_new_null()); + ExpectNotNull(exts = sk_X509_EXTENSION_new_null()); /* Ensure an empty stack doesn't raise an error. */ - AssertIntEQ(X509_REQ_add_extensions(x509, exts), 1); - AssertIntEQ(sk_X509_EXTENSION_push(exts, san_ext), 1); - AssertIntEQ(sk_X509_EXTENSION_push(exts, sid_ext), 2); - AssertIntEQ(X509_REQ_add_extensions(x509, exts), 1); - AssertNotNull(f = fopen(key_fname, "rb")); - AssertIntGT(derSz = (int)fread(der, 1, sizeof(der), f), 0); - fclose(f); + ExpectIntEQ(X509_REQ_add_extensions(x509, exts), 1); + ExpectIntEQ(sk_X509_EXTENSION_push(exts, san_ext), 1); + if (EXPECT_FAIL()) { + X509_EXTENSION_free(san_ext); + } + ExpectIntEQ(sk_X509_EXTENSION_push(exts, sid_ext), 2); + if (EXPECT_FAIL()) { + X509_EXTENSION_free(sid_ext); + } + ExpectIntEQ(X509_REQ_add_extensions(x509, exts), 1); + ExpectTrue((f = XFOPEN(key_fname, "rb")) != XBADFILE); + ExpectIntGT(derSz = (int)XFREAD(der, 1, sizeof(der), f), 0); + if (f != XBADFILE) + XFCLOSE(f); pt = der; - AssertNotNull(priv = d2i_PrivateKey(EVP_PKEY_RSA, NULL, + ExpectNotNull(priv = d2i_PrivateKey(EVP_PKEY_RSA, NULL, (const unsigned char**)&pt, derSz)); - AssertIntGT(X509_REQ_sign(x509, priv, EVP_sha256()), 0); + ExpectIntGT(X509_REQ_sign(x509, priv, EVP_sha256()), 0); pt = der; - AssertIntGT(derSz = i2d_X509_REQ(x509, &pt), 0); + ExpectIntGT(derSz = i2d_X509_REQ(x509, &pt), 0); sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); + gns = NULL; sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); + exts = NULL; ASN1_OBJECT_free(upn_oid); ASN1_OBJECT_free(sid_oid); ASN1_OCTET_STRING_free(sid_data); @@ -44783,48 +44857,41 @@ static int test_othername_and_SID_ext(void) { * We now read back from der to confirm the extensions were inserted * correctly. */ bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); - AssertNotNull(bio); + ExpectNotNull(bio); - AssertIntEQ(BIO_write(bio, der, derSz), derSz); /* d2i consumes BIO */ - d2i_X509_REQ_bio(bio, &x509); - AssertNotNull(x509); + ExpectIntEQ(BIO_write(bio, der, derSz), derSz); /* d2i consumes BIO */ + ExpectNotNull(d2i_X509_REQ_bio(bio, &x509)); + ExpectNotNull(x509); BIO_free(bio); - AssertNotNull(exts = (STACK_OF(X509_EXTENSION)*) X509_REQ_get_extensions( - x509)); - AssertIntEQ(sk_X509_EXTENSION_num(exts), 2); + ExpectNotNull(exts = (STACK_OF(X509_EXTENSION)*)X509_REQ_get_extensions( + x509)); + ExpectIntEQ(sk_X509_EXTENSION_num(exts), 2); /* Check the SID extension. */ - AssertNotNull(ext = sk_X509_EXTENSION_value(exts, 0)); - AssertNotNull(extval = X509_EXTENSION_get_data(ext)); - AssertIntEQ(extval->length, sizeof(SidExtension)); - AssertIntEQ(XMEMCMP(SidExtension, extval->data, sizeof(SidExtension)), 0); + ExpectNotNull(ext = sk_X509_EXTENSION_value(exts, 0)); + ExpectNotNull(extval = X509_EXTENSION_get_data(ext)); + ExpectIntEQ(extval->length, sizeof(SidExtension)); + ExpectIntEQ(XMEMCMP(SidExtension, extval->data, sizeof(SidExtension)), 0); /* Check the AltNames extension. */ - AssertNotNull(ext = sk_X509_EXTENSION_value(exts, 1)); - AssertNotNull(extval = X509_EXTENSION_get_data(ext)); - AssertIntEQ(extval->length, sizeof(expectedAltName)); - AssertIntEQ(XMEMCMP(expectedAltName, extval->data, sizeof(expectedAltName)), + ExpectNotNull(ext = sk_X509_EXTENSION_value(exts, 1)); + ExpectNotNull(extval = X509_EXTENSION_get_data(ext)); + ExpectIntEQ(extval->length, sizeof(expectedAltName)); + ExpectIntEQ(XMEMCMP(expectedAltName, extval->data, sizeof(expectedAltName)), 0); /* Cleanup */ - AssertNotNull(gns = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, + ExpectNotNull(gns = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL)); - AssertIntEQ(sk_GENERAL_NAME_num(gns), 1); - AssertNotNull(gn = sk_GENERAL_NAME_value(gns, 0)); - AssertIntEQ(gn->type, 0); - - /* It is odd that we are using ASN_RFC822_TYPE. It is because when we are - * parsing der, the string is not fully parsed. It is still raw der whereas - * when we encode we set the oid (for example, upn) and value. As we are - * overloading the meaning of the type, here we manually do the right thing. - */ - gn->type = ASN_RFC822_TYPE; + ExpectIntEQ(sk_GENERAL_NAME_num(gns), 1); + ExpectNotNull(gn = sk_GENERAL_NAME_value(gns, 0)); + ExpectIntEQ(gn->type, 0); + sk_GENERAL_NAME_pop_free(gns, GENERAL_NAME_free); - ext->ext_sk->data.gn->type = ASN_RFC822_TYPE; sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); X509_REQ_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44834,32 +44901,33 @@ static int test_wolfSSL_X509_set_name(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) - X509* x509; - X509_NAME* name; + EXPECT_DECLS; + X509* x509 = NULL; + X509_NAME* name = NULL; - AssertNotNull(name = X509_NAME_new()); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, + ExpectNotNull(name = X509_NAME_new()); + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "commonName", MBSTRING_UTF8, (byte*)"wolfssl.com", 11, 0, 1), WOLFSSL_SUCCESS); - AssertIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, + ExpectIntEQ(X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_UTF8, (byte*)"support@wolfssl.com", 19, -1, 1), WOLFSSL_SUCCESS); - AssertNotNull(x509 = X509_new()); + ExpectNotNull(x509 = X509_new()); - AssertIntEQ(X509_set_subject_name(NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(X509_set_subject_name(x509, NULL), WOLFSSL_FAILURE); - AssertIntEQ(X509_set_subject_name(NULL, name), WOLFSSL_FAILURE); - AssertIntEQ(X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_set_subject_name(NULL, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(X509_set_subject_name(x509, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(X509_set_subject_name(NULL, name), WOLFSSL_FAILURE); + ExpectIntEQ(X509_set_subject_name(x509, name), WOLFSSL_SUCCESS); - AssertIntEQ(X509_set_issuer_name(NULL, NULL), WOLFSSL_FAILURE); - AssertIntEQ(X509_set_issuer_name(x509, NULL), WOLFSSL_FAILURE); - AssertIntEQ(X509_set_issuer_name(NULL, name), WOLFSSL_FAILURE); - AssertIntEQ(X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); + ExpectIntEQ(X509_set_issuer_name(NULL, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(X509_set_issuer_name(x509, NULL), WOLFSSL_FAILURE); + ExpectIntEQ(X509_set_issuer_name(NULL, name), WOLFSSL_FAILURE); + ExpectIntEQ(X509_set_issuer_name(x509, name), WOLFSSL_SUCCESS); X509_free(x509); X509_NAME_free(name); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_ALL && !NO_CERTS */ return res; } @@ -44873,10 +44941,11 @@ static int test_wolfSSL_X509_set_notAfter(void) defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) &&\ !defined(TIME_T_NOT_64BIT) && !defined(NO_64BIT) && !defined(NO_BIO) /* Generalized time will overflow time_t if not long */ - - X509* x; - BIO* bio; - ASN1_TIME *asn_time, *time_check; + EXPECT_DECLS; + X509* x = NULL; + BIO* bio = NULL; + ASN1_TIME *asn_time = NULL; + ASN1_TIME *time_check = NULL; const int year = 365*24*60*60; const int day = 24*60*60; const int hour = 60*60; @@ -44894,29 +44963,34 @@ static int test_wolfSSL_X509_set_notAfter(void) * Free these. */ asn_time = wolfSSL_ASN1_TIME_adj(NULL, t, offset_day, 0); - AssertNotNull(asn_time); - AssertNotNull(x = X509_new()); - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(asn_time); + ExpectNotNull(x = X509_new()); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); /* * Tests */ - AssertTrue(wolfSSL_X509_set_notAfter(x, asn_time)); + ExpectTrue(wolfSSL_X509_set_notAfter(x, asn_time)); /* time_check is simply (ANS1_TIME*)x->notAfter */ - AssertNotNull(time_check = X509_get_notAfter(x)); + ExpectNotNull(time_check = X509_get_notAfter(x)); /* ANS1_TIME_check validates by checking if argument can be parsed */ - AssertIntEQ(ASN1_TIME_check(time_check), WOLFSSL_SUCCESS); + ExpectIntEQ(ASN1_TIME_check(time_check), WOLFSSL_SUCCESS); /* Convert to human readable format and compare to intended date */ - AssertIntEQ(ASN1_TIME_print(bio, time_check), 1); - AssertIntEQ(BIO_read(bio, buf, sizeof(buf)), 24); - AssertIntEQ(XMEMCMP(buf, "Jan 20 10:30:00 2077 GMT", sizeof(buf) - 1), 0); + ExpectIntEQ(ASN1_TIME_print(bio, time_check), 1); + ExpectIntEQ(BIO_read(bio, buf, sizeof(buf)), 24); + ExpectIntEQ(XMEMCMP(buf, "Jan 20 10:30:00 2077 GMT", sizeof(buf) - 1), 0); + + ExpectFalse(wolfSSL_X509_set_notAfter(NULL, NULL)); + ExpectFalse(wolfSSL_X509_set_notAfter(x, NULL)); + ExpectFalse(wolfSSL_X509_set_notAfter(NULL, asn_time)); + /* * Cleanup */ - XFREE(asn_time,NULL,DYNAMIC_TYPE_OPENSSL); + XFREE(asn_time, NULL, DYNAMIC_TYPE_OPENSSL); X509_free(x); BIO_free(bio); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44928,10 +45002,11 @@ static int test_wolfSSL_X509_set_notBefore(void) && !defined(NO_ASN_TIME) && !defined(USER_TIME) && \ !defined(TIME_OVERRIDES) && !defined(NO_CERTS) && \ defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) && !defined(NO_BIO) - - X509* x; - BIO* bio; - ASN1_TIME *asn_time, *time_check; + EXPECT_DECLS; + X509* x = NULL; + BIO* bio = NULL; + ASN1_TIME *asn_time = NULL; + ASN1_TIME *time_check = NULL; const int year = 365*24*60*60; const int day = 24*60*60; const int hour = 60*60; @@ -44950,31 +45025,36 @@ static int test_wolfSSL_X509_set_notBefore(void) * Free these. */ asn_time = wolfSSL_ASN1_TIME_adj(NULL, t, offset_day, 0); - AssertNotNull(asn_time); - AssertNotNull(x = X509_new()); - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertIntEQ(ASN1_TIME_check(asn_time), WOLFSSL_SUCCESS); + ExpectNotNull(asn_time); + ExpectNotNull(x = X509_new()); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(ASN1_TIME_check(asn_time), WOLFSSL_SUCCESS); /* * Main Tests */ - AssertTrue(wolfSSL_X509_set_notBefore(x, asn_time)); + ExpectTrue(wolfSSL_X509_set_notBefore(x, asn_time)); /* time_check == (ANS1_TIME*)x->notBefore */ - AssertNotNull(time_check = X509_get_notBefore(x)); + ExpectNotNull(time_check = X509_get_notBefore(x)); /* ANS1_TIME_check validates by checking if argument can be parsed */ - AssertIntEQ(ASN1_TIME_check(time_check), WOLFSSL_SUCCESS); + ExpectIntEQ(ASN1_TIME_check(time_check), WOLFSSL_SUCCESS); /* Convert to human readable format and compare to intended date */ - AssertIntEQ(ASN1_TIME_print(bio, time_check), 1); - AssertIntEQ(BIO_read(bio, buf, sizeof(buf)), 24); - AssertIntEQ(XMEMCMP(buf, "May 8 20:30:00 2019 GMT", sizeof(buf) - 1), 0); + ExpectIntEQ(ASN1_TIME_print(bio, time_check), 1); + ExpectIntEQ(BIO_read(bio, buf, sizeof(buf)), 24); + ExpectIntEQ(XMEMCMP(buf, "May 8 20:30:00 2019 GMT", sizeof(buf) - 1), 0); + + ExpectFalse(wolfSSL_X509_set_notBefore(NULL, NULL)); + ExpectFalse(wolfSSL_X509_set_notBefore(x, NULL)); + ExpectFalse(wolfSSL_X509_set_notBefore(NULL, asn_time)); + /* * Cleanup */ - XFREE(asn_time,NULL,DYNAMIC_TYPE_OPENSSL); + XFREE(asn_time, NULL, DYNAMIC_TYPE_OPENSSL); X509_free(x); BIO_free(bio); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -44984,20 +45064,25 @@ static int test_wolfSSL_X509_set_version(void) int res = TEST_SKIPPED; #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)) && \ !defined(NO_CERTS) && defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) - X509* x509; + EXPECT_DECLS; + X509* x509 = NULL; long v = 2L; long maxInt = INT_MAX; - AssertNotNull(x509 = X509_new()); + ExpectNotNull(x509 = X509_new()); /* These should pass. */ - AssertTrue(wolfSSL_X509_set_version(x509, v)); - AssertIntEQ(v, wolfSSL_X509_get_version(x509)); + ExpectTrue(wolfSSL_X509_set_version(x509, v)); + ExpectIntEQ(v, wolfSSL_X509_get_version(x509)); /* Fail Case: When v(long) is greater than x509->version(int). */ v = maxInt+1; - AssertFalse(wolfSSL_X509_set_version(x509, v)); + ExpectFalse(wolfSSL_X509_set_version(x509, v)); + + ExpectFalse(wolfSSL_X509_set_version(NULL, 2L)); + ExpectFalse(wolfSSL_X509_set_version(NULL, maxInt+1)); + /* Cleanup */ X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -45007,123 +45092,137 @@ static int test_wolfSSL_X509_set_version(void) static int test_wolfSSL_BIO_gets(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) - BIO* bio; - BIO* bio2; +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; + BIO* bio = NULL; + BIO* bio2 = NULL; char msg[] = "\nhello wolfSSL\n security plus\t---...**adf\na...b.c"; char emp[] = ""; char bio_buffer[20]; int bufferSz = 20; /* try with bad args */ - AssertNull(bio = BIO_new_mem_buf(NULL, sizeof(msg))); + ExpectNull(bio = BIO_new_mem_buf(NULL, sizeof(msg))); /* try with real msg */ - AssertNotNull(bio = BIO_new_mem_buf((void*)msg, -1)); + ExpectNotNull(bio = BIO_new_mem_buf((void*)msg, -1)); XMEMSET(bio_buffer, 0, bufferSz); - AssertNotNull(BIO_push(bio, BIO_new(BIO_s_bio()))); - AssertNull(bio2 = BIO_find_type(bio, BIO_TYPE_FILE)); - AssertNotNull(bio2 = BIO_find_type(bio, BIO_TYPE_BIO)); - AssertFalse(bio2 != BIO_next(bio)); + ExpectNotNull(BIO_push(bio, BIO_new(BIO_s_bio()))); + ExpectNull(bio2 = BIO_find_type(bio, BIO_TYPE_FILE)); + ExpectNotNull(bio2 = BIO_find_type(bio, BIO_TYPE_BIO)); + ExpectFalse(bio2 != BIO_next(bio)); /* make buffer filled with no terminating characters */ XMEMSET(bio_buffer, 1, bufferSz); /* BIO_gets reads a line of data */ - AssertIntEQ(BIO_gets(bio, bio_buffer, -3), 0); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 1); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 14); - AssertStrEQ(bio_buffer, "hello wolfSSL\n"); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 19); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 8); - AssertIntEQ(BIO_gets(bio, bio_buffer, -1), 0); + ExpectIntEQ(BIO_gets(bio, bio_buffer, -3), 0); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 1); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 14); + ExpectStrEQ(bio_buffer, "hello wolfSSL\n"); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 19); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 8); + ExpectIntEQ(BIO_gets(bio, bio_buffer, -1), 0); /* check not null terminated string */ BIO_free(bio); + bio = NULL; msg[0] = 0x33; msg[1] = 0x33; msg[2] = 0x33; - AssertNotNull(bio = BIO_new_mem_buf((void*)msg, 3)); - AssertIntEQ(BIO_gets(bio, bio_buffer, 3), 2); - AssertIntEQ(bio_buffer[0], msg[0]); - AssertIntEQ(bio_buffer[1], msg[1]); - AssertIntNE(bio_buffer[2], msg[2]); + ExpectNotNull(bio = BIO_new_mem_buf((void*)msg, 3)); + ExpectIntEQ(BIO_gets(bio, bio_buffer, 3), 2); + ExpectIntEQ(bio_buffer[0], msg[0]); + ExpectIntEQ(bio_buffer[1], msg[1]); + ExpectIntNE(bio_buffer[2], msg[2]); BIO_free(bio); + bio = NULL; msg[3] = 0x33; bio_buffer[3] = 0x33; - AssertNotNull(bio = BIO_new_mem_buf((void*)msg, 3)); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 3); - AssertIntEQ(bio_buffer[0], msg[0]); - AssertIntEQ(bio_buffer[1], msg[1]); - AssertIntEQ(bio_buffer[2], msg[2]); - AssertIntNE(bio_buffer[3], 0x33); /* make sure null terminator was set */ + ExpectNotNull(bio = BIO_new_mem_buf((void*)msg, 3)); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 3); + ExpectIntEQ(bio_buffer[0], msg[0]); + ExpectIntEQ(bio_buffer[1], msg[1]); + ExpectIntEQ(bio_buffer[2], msg[2]); + ExpectIntNE(bio_buffer[3], 0x33); /* make sure null terminator was set */ /* check reading an empty string */ BIO_free(bio); - AssertNotNull(bio = BIO_new_mem_buf((void*)emp, sizeof(emp))); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 1); /* just terminator */ - AssertStrEQ(emp, bio_buffer); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 0); /* Nothing to read */ + bio = NULL; + ExpectNotNull(bio = BIO_new_mem_buf((void*)emp, sizeof(emp))); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 1); /* just terminator */ + ExpectStrEQ(emp, bio_buffer); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 0); /* Nothing to read */ /* check error cases */ BIO_free(bio); - AssertIntEQ(BIO_gets(NULL, NULL, 0), SSL_FAILURE); - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertIntEQ(BIO_gets(bio, bio_buffer, 2), 0); /* nothing to read */ + bio = NULL; + ExpectIntEQ(BIO_gets(NULL, NULL, 0), SSL_FAILURE); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(BIO_gets(bio, bio_buffer, 2), 0); /* nothing to read */ #if !defined(NO_FILESYSTEM) { - BIO* f_bio; - XFILE f; - AssertNotNull(f_bio = BIO_new(BIO_s_file())); - AssertIntLE(BIO_gets(f_bio, bio_buffer, bufferSz), 0); + BIO* f_bio = NULL; + XFILE f = XBADFILE; - f = XFOPEN(svrCertFile, "rb"); - AssertTrue((f != XBADFILE)); - AssertIntEQ((int)BIO_set_fp(f_bio, f, BIO_CLOSE), SSL_SUCCESS); - AssertIntGT(BIO_gets(f_bio, bio_buffer, bufferSz), 0); + ExpectNotNull(f_bio = BIO_new(BIO_s_file())); + ExpectIntLE(BIO_gets(f_bio, bio_buffer, bufferSz), 0); + + ExpectTrue((f = XFOPEN(svrCertFile, "rb")) != XBADFILE); + ExpectIntEQ((int)BIO_set_fp(f_bio, f, BIO_CLOSE), SSL_SUCCESS); + if (EXPECT_FAIL() && (f != XBADFILE)) { + XFCLOSE(f); + } + ExpectIntGT(BIO_gets(f_bio, bio_buffer, bufferSz), 0); BIO_free(f_bio); + f_bio = NULL; } #endif /* NO_FILESYSTEM */ BIO_free(bio); + bio = NULL; BIO_free(bio2); + bio2 = NULL; /* try with type BIO */ XMEMCPY(msg, "\nhello wolfSSL\n security plus\t---...**adf\na...b.c", - sizeof(msg)); - AssertNotNull(bio = BIO_new(BIO_s_bio())); - AssertIntEQ(BIO_gets(bio, bio_buffer, 2), 0); /* nothing to read */ - AssertNotNull(bio2 = BIO_new(BIO_s_bio())); - - AssertIntEQ(BIO_set_write_buf_size(bio, 10), SSL_SUCCESS); - AssertIntEQ(BIO_set_write_buf_size(bio2, sizeof(msg)), SSL_SUCCESS); - AssertIntEQ(BIO_make_bio_pair(bio, bio2), SSL_SUCCESS); - - AssertIntEQ(BIO_write(bio2, msg, sizeof(msg)), sizeof(msg)); - AssertIntEQ(BIO_gets(bio, bio_buffer, -3), 0); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 1); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 14); - AssertStrEQ(bio_buffer, "hello wolfSSL\n"); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 19); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 8); - AssertIntEQ(BIO_gets(bio, bio_buffer, -1), 0); + sizeof(msg)); + ExpectNotNull(bio = BIO_new(BIO_s_bio())); + ExpectIntEQ(BIO_gets(bio, bio_buffer, 2), 0); /* nothing to read */ + ExpectNotNull(bio2 = BIO_new(BIO_s_bio())); + + ExpectIntEQ(BIO_set_write_buf_size(bio, 10), SSL_SUCCESS); + ExpectIntEQ(BIO_set_write_buf_size(bio2, sizeof(msg)), SSL_SUCCESS); + ExpectIntEQ(BIO_make_bio_pair(bio, bio2), SSL_SUCCESS); + + ExpectIntEQ(BIO_write(bio2, msg, sizeof(msg)), sizeof(msg)); + ExpectIntEQ(BIO_gets(bio, bio_buffer, -3), 0); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 1); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 14); + ExpectStrEQ(bio_buffer, "hello wolfSSL\n"); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 19); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 8); + ExpectIntEQ(BIO_gets(bio, bio_buffer, -1), 0); BIO_free(bio); + bio = NULL; BIO_free(bio2); + bio2 = NULL; /* check reading an empty string */ - AssertNotNull(bio = BIO_new(BIO_s_bio())); - AssertIntEQ(BIO_set_write_buf_size(bio, sizeof(emp)), SSL_SUCCESS); - AssertIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 0); /* Nothing to read */ - AssertStrEQ(emp, bio_buffer); + ExpectNotNull(bio = BIO_new(BIO_s_bio())); + ExpectIntEQ(BIO_set_write_buf_size(bio, sizeof(emp)), SSL_SUCCESS); + ExpectIntEQ(BIO_gets(bio, bio_buffer, bufferSz), 0); /* Nothing to read */ + ExpectStrEQ(emp, bio_buffer); BIO_free(bio); + bio = NULL; - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -45131,36 +45230,38 @@ static int test_wolfSSL_BIO_gets(void) static int test_wolfSSL_BIO_puts(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) - BIO* bio; +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; + BIO* bio = NULL; char input[] = "hello\0world\n.....ok\n\0"; char output[128]; XMEMSET(output, 0, sizeof(output)); - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertIntEQ(BIO_puts(bio, input), 5); - AssertIntEQ(BIO_pending(bio), 5); - AssertIntEQ(BIO_puts(bio, input + 6), 14); - AssertIntEQ(BIO_pending(bio), 19); - AssertIntEQ(BIO_gets(bio, output, sizeof(output)), 11); - AssertStrEQ(output, "helloworld\n"); - AssertIntEQ(BIO_pending(bio), 8); - AssertIntEQ(BIO_gets(bio, output, sizeof(output)), 8); - AssertStrEQ(output, ".....ok\n"); - AssertIntEQ(BIO_pending(bio), 0); - AssertIntEQ(BIO_puts(bio, ""), -1); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(BIO_puts(bio, input), 5); + ExpectIntEQ(BIO_pending(bio), 5); + ExpectIntEQ(BIO_puts(bio, input + 6), 14); + ExpectIntEQ(BIO_pending(bio), 19); + ExpectIntEQ(BIO_gets(bio, output, sizeof(output)), 11); + ExpectStrEQ(output, "helloworld\n"); + ExpectIntEQ(BIO_pending(bio), 8); + ExpectIntEQ(BIO_gets(bio, output, sizeof(output)), 8); + ExpectStrEQ(output, ".....ok\n"); + ExpectIntEQ(BIO_pending(bio), 0); + ExpectIntEQ(BIO_puts(bio, ""), -1); BIO_free(bio); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } static int test_wolfSSL_BIO_dump(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) + EXPECT_DECLS; BIO* bio; static const unsigned char data[] = { 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, @@ -45202,24 +45303,24 @@ static int test_wolfSSL_BIO_dump(void) char output[16 * 80]; int i; - AssertNotNull(bio = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); /* Example key dumped. */ - AssertIntEQ(BIO_dump(bio, (const char*)data, (int)sizeof(data)), - sizeof(expected) - 1); - AssertIntEQ(BIO_read(bio, output, sizeof(output)), sizeof(expected) - 1); - AssertIntEQ(XMEMCMP(output, expected, sizeof(expected) - 1), 0); + ExpectIntEQ(BIO_dump(bio, (const char*)data, (int)sizeof(data)), + sizeof(expected) - 1); + ExpectIntEQ(BIO_read(bio, output, sizeof(output)), sizeof(expected) - 1); + ExpectIntEQ(XMEMCMP(output, expected, sizeof(expected) - 1), 0); /* Try every possible value for a character. */ for (i = 0; i < 256; i++) output[i] = i; - AssertIntEQ(BIO_dump(bio, output, 256), sizeof(expectedAll) - 1); - AssertIntEQ(BIO_read(bio, output, sizeof(output)), sizeof(expectedAll) - 1); - AssertIntEQ(XMEMCMP(output, expectedAll, sizeof(expectedAll) - 1), 0); + ExpectIntEQ(BIO_dump(bio, output, 256), sizeof(expectedAll) - 1); + ExpectIntEQ(BIO_read(bio, output, sizeof(output)), sizeof(expectedAll) - 1); + ExpectIntEQ(XMEMCMP(output, expectedAll, sizeof(expectedAll) - 1), 0); BIO_free(bio); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -45242,17 +45343,18 @@ static int test_wolfSSL_BIO_should_retry(void) #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && \ !defined(NO_RSA) && defined(HAVE_EXT_CACHE) && \ defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(USE_WOLFSSL_IO) + EXPECT_DECLS; tcp_ready ready; func_args server_args; THREAD_TYPE serverThread; SOCKET_T sockfd = 0; - WOLFSSL_CTX* ctx; - WOLFSSL* ssl; + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; char msg[64] = "hello wolfssl!"; char reply[1024]; int msgSz = (int)XSTRLEN(msg); int ret; - BIO* bio; + BIO* bio = NULL; XMEMSET(&server_args, 0, sizeof(func_args)); #ifdef WOLFSSL_TIRTOS @@ -45272,43 +45374,46 @@ static int test_wolfSSL_BIO_should_retry(void) wait_tcp_ready(&server_args); - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); #ifdef OPENSSL_COMPATIBLE_DEFAULTS - AssertIntEQ(wolfSSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY), 0); + ExpectIntEQ(wolfSSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY), 0); #endif - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); tcp_connect(&sockfd, wolfSSLIP, server_args.signal->port, 0, 0, NULL); /* force retry */ - ssl = wolfSSL_new(ctx); - AssertNotNull(ssl); - AssertIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + ExpectIntEQ(wolfSSL_set_fd(ssl, sockfd), WOLFSSL_SUCCESS); wolfSSL_SSLSetIORecv(ssl, forceWantRead); - AssertNotNull(bio = BIO_new(BIO_f_ssl())); - BIO_set_ssl(bio, ssl, BIO_CLOSE); + ExpectNotNull(bio = BIO_new(BIO_f_ssl())); + ExpectIntEQ(BIO_set_ssl(bio, ssl, BIO_CLOSE), 1); + if (EXPECT_FAIL()) { + wolfSSL_free(ssl); + ssl = NULL; + } - AssertIntLE(BIO_write(bio, msg, msgSz), 0); - AssertIntNE(BIO_should_retry(bio), 0); + ExpectIntLE(BIO_write(bio, msg, msgSz), 0); + ExpectIntNE(BIO_should_retry(bio), 0); /* now perform successful connection */ wolfSSL_SSLSetIORecv(ssl, EmbedReceive); - AssertIntEQ(BIO_write(bio, msg, msgSz), msgSz); - BIO_read(bio, reply, sizeof(reply)); + ExpectIntEQ(BIO_write(bio, msg, msgSz), msgSz); + ExpectIntNE(BIO_read(bio, reply, sizeof(reply)), 0); ret = wolfSSL_get_error(ssl, -1); if (ret == WOLFSSL_ERROR_WANT_READ || ret == WOLFSSL_ERROR_WANT_WRITE) { - AssertIntNE(BIO_should_retry(bio), 0); + ExpectIntNE(BIO_should_retry(bio), 0); } else { - AssertIntEQ(BIO_should_retry(bio), 0); + ExpectIntEQ(BIO_should_retry(bio), 0); } - AssertIntEQ(XMEMCMP(reply, "I hear you fa shizzle!", + ExpectIntEQ(XMEMCMP(reply, "I hear you fa shizzle!", XSTRLEN("I hear you fa shizzle!")), 0); BIO_free(bio); wolfSSL_CTX_free(ctx); @@ -45320,7 +45425,7 @@ static int test_wolfSSL_BIO_should_retry(void) fdOpenSession(Task_self()); #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -45330,24 +45435,25 @@ static int test_wolfSSL_BIO_connect(void) int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ defined(HAVE_HTTP_CLIENT) && !defined(NO_WOLFSSL_CLIENT) + EXPECT_DECLS; tcp_ready ready; func_args server_args; THREAD_TYPE serverThread; - BIO *tcpBio; - BIO *sslBio; - SSL_CTX* ctx; - SSL *ssl; + BIO *tcpBio = NULL; + BIO *sslBio = NULL; + SSL_CTX* ctx = NULL; + SSL *ssl = NULL; SSL *sslPtr; char msg[] = "hello wolfssl!"; char reply[30]; char buff[10] = {0}; - AssertNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_load_verify_locations(ctx, caCertFile, 0)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(ctx, cliCertFile, SSL_FILETYPE_PEM)); - AssertIntEQ(WOLFSSL_SUCCESS, + ExpectIntEQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_PrivateKey_file(ctx, cliKeyFile, SSL_FILETYPE_PEM)); /* Setup server */ @@ -45361,31 +45467,34 @@ static int test_wolfSSL_BIO_connect(void) server_args.signal = &ready; start_thread(test_server_nofail, &server_args, &serverThread); wait_tcp_ready(&server_args); - AssertIntGT(XSPRINTF(buff, "%d", ready.port), 0); + ExpectIntGT(XSPRINTF(buff, "%d", ready.port), 0); /* Start the test proper */ /* Setup the TCP BIO */ - AssertNotNull(tcpBio = BIO_new_connect(wolfSSLIP)); - AssertIntEQ(BIO_set_conn_port(tcpBio, buff), 1); + ExpectNotNull(tcpBio = BIO_new_connect(wolfSSLIP)); + ExpectIntEQ(BIO_set_conn_port(tcpBio, buff), 1); /* Setup the SSL object */ - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ssl = SSL_new(ctx)); SSL_set_connect_state(ssl); /* Setup the SSL BIO */ - AssertNotNull(sslBio = BIO_new(BIO_f_ssl())); - AssertIntEQ(BIO_set_ssl(sslBio, ssl, BIO_CLOSE), 1); + ExpectNotNull(sslBio = BIO_new(BIO_f_ssl())); + ExpectIntEQ(BIO_set_ssl(sslBio, ssl, BIO_CLOSE), 1); + if (EXPECT_FAIL()) { + wolfSSL_free(ssl); + } /* Verify that BIO_get_ssl works. */ - AssertIntEQ(BIO_get_ssl(sslBio, &sslPtr), 1); - AssertPtrEq(ssl, sslPtr); + ExpectIntEQ(BIO_get_ssl(sslBio, &sslPtr), 1); + ExpectPtrEq(ssl, sslPtr); /* Link BIO's so that sslBio uses tcpBio for IO */ - AssertPtrEq(BIO_push(sslBio, tcpBio), sslBio); + ExpectPtrEq(BIO_push(sslBio, tcpBio), sslBio); /* Do TCP connect */ - AssertIntEQ(BIO_do_connect(sslBio), 1); + ExpectIntEQ(BIO_do_connect(sslBio), 1); /* Do TLS handshake */ - AssertIntEQ(BIO_do_handshake(sslBio), 1); + ExpectIntEQ(BIO_do_handshake(sslBio), 1); /* Test writing */ - AssertIntEQ(BIO_write(sslBio, msg, sizeof(msg)), sizeof(msg)); + ExpectIntEQ(BIO_write(sslBio, msg, sizeof(msg)), sizeof(msg)); /* Expect length of default wolfSSL reply */ - AssertIntEQ(BIO_read(sslBio, reply, sizeof(reply)), 23); + ExpectIntEQ(BIO_read(sslBio, reply, sizeof(reply)), 23); /* Clean it all up */ BIO_free_all(sslBio); @@ -45405,15 +45514,15 @@ static int test_wolfSSL_BIO_connect(void) server_args.signal = &ready; start_thread(test_server_nofail, &server_args, &serverThread); wait_tcp_ready(&server_args); - AssertIntGT(XSPRINTF(buff, "%d", ready.port), 0); - - AssertNotNull(sslBio = BIO_new_ssl_connect(ctx)); - AssertIntEQ(BIO_set_conn_hostname(sslBio, (char*)wolfSSLIP), 1); - AssertIntEQ(BIO_set_conn_port(sslBio, buff), 1); - AssertIntEQ(BIO_do_connect(sslBio), 1); - AssertIntEQ(BIO_do_handshake(sslBio), 1); - AssertIntEQ(BIO_write(sslBio, msg, sizeof(msg)), sizeof(msg)); - AssertIntEQ(BIO_read(sslBio, reply, sizeof(reply)), 23); + ExpectIntGT(XSPRINTF(buff, "%d", ready.port), 0); + + ExpectNotNull(sslBio = BIO_new_ssl_connect(ctx)); + ExpectIntEQ(BIO_set_conn_hostname(sslBio, (char*)wolfSSLIP), 1); + ExpectIntEQ(BIO_set_conn_port(sslBio, buff), 1); + ExpectIntEQ(BIO_do_connect(sslBio), 1); + ExpectIntEQ(BIO_do_handshake(sslBio), 1); + ExpectIntEQ(BIO_write(sslBio, msg, sizeof(msg)), sizeof(msg)); + ExpectIntEQ(BIO_read(sslBio, reply, sizeof(reply)), 23); /* Attempt to close the TLS connection gracefully. */ BIO_ssl_shutdown(sslBio); @@ -45427,7 +45536,7 @@ static int test_wolfSSL_BIO_connect(void) wc_ecc_fp_free(); /* free per thread cache */ #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -45437,17 +45546,19 @@ static int test_wolfSSL_BIO_tls(void) { int res = TEST_SKIPPED; #if !defined(NO_BIO) && defined(OPENSSL_EXTRA) && !defined(NO_WOLFSSL_CLIENT) - SSL_CTX* ctx; - SSL *ssl; - BIO *readBio; - BIO *writeBio; - int ret, err = 0; + EXPECT_DECLS; + SSL_CTX* ctx = NULL; + SSL *ssl = NULL; + BIO *readBio = NULL; + BIO *writeBio = NULL; + int ret; + int err = 0; - AssertNotNull(ctx = SSL_CTX_new(SSLv23_method())); - AssertNotNull(ssl = SSL_new(ctx)); + ExpectNotNull(ctx = SSL_CTX_new(SSLv23_method())); + ExpectNotNull(ssl = SSL_new(ctx)); - AssertNotNull(readBio = BIO_new(BIO_s_mem())); - AssertNotNull(writeBio = BIO_new(BIO_s_mem())); + ExpectNotNull(readBio = BIO_new(BIO_s_mem())); + ExpectNotNull(writeBio = BIO_new(BIO_s_mem())); /* Qt reads data from write-bio, * then writes the read data into plain packet. * Qt reads data from plain packet, @@ -45465,21 +45576,22 @@ static int test_wolfSSL_BIO_tls(void) ret = SSL_connect(ssl); err = SSL_get_error(ssl, 0); } while (err == WC_PENDING_E); - AssertIntEQ(ret, WOLFSSL_FATAL_ERROR); + ExpectIntEQ(ret, WOLFSSL_FATAL_ERROR); /* in this use case, should return WANT READ * so that Qt will read the data from plain packet for next state. */ - AssertIntEQ(err, SSL_ERROR_WANT_READ); + ExpectIntEQ(err, SSL_ERROR_WANT_READ); SSL_free(ssl); SSL_CTX_free(ctx); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } -#if defined(OPENSSL_ALL) && defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_HTTP_CLIENT) +#if defined(OPENSSL_ALL) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ + defined(HAVE_HTTP_CLIENT) static THREAD_RETURN WOLFSSL_THREAD test_wolfSSL_BIO_accept_client(void* args) { BIO* clientBio; @@ -45512,34 +45624,38 @@ static THREAD_RETURN WOLFSSL_THREAD test_wolfSSL_BIO_accept_client(void* args) static int test_wolfSSL_BIO_accept(void) { int res = TEST_SKIPPED; -#if defined(OPENSSL_ALL) && defined(HAVE_IO_TESTS_DEPENDENCIES) && defined(HAVE_HTTP_CLIENT) - BIO* serverBindBio; - BIO* serverAcceptBio; - SSL* sslServer; - SSL_CTX* ctx; +#if defined(OPENSSL_ALL) && defined(HAVE_IO_TESTS_DEPENDENCIES) && \ + defined(HAVE_HTTP_CLIENT) + EXPECT_DECLS; + BIO* serverBindBio = NULL; + BIO* serverAcceptBio = NULL; + SSL* sslServer = NULL; + SSL_CTX* ctx = NULL; func_args args; THREAD_TYPE thread; char port[10]; /* 10 bytes should be enough to store the string * representation of the port */ - AssertIntGT(snprintf(port, sizeof(port), "%d", wolfSSLPort), 0); - AssertNotNull(serverBindBio = BIO_new_accept(port)); + ExpectIntGT(snprintf(port, sizeof(port), "%d", wolfSSLPort), 0); + ExpectNotNull(serverBindBio = BIO_new_accept(port)); /* First BIO_do_accept binds the port */ - AssertIntEQ(BIO_do_accept(serverBindBio), 1); + ExpectIntEQ(BIO_do_accept(serverBindBio), 1); XMEMSET(&args, 0, sizeof(func_args)); start_thread(test_wolfSSL_BIO_accept_client, &args, &thread); - AssertIntEQ(BIO_do_accept(serverBindBio), 1); + ExpectIntEQ(BIO_do_accept(serverBindBio), 1); /* Let's plug it into SSL to test */ - AssertNotNull(ctx = SSL_CTX_new(SSLv23_method())); - AssertIntEQ(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, SSL_FILETYPE_PEM), WOLFSSL_SUCCESS); - AssertIntEQ(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, SSL_FILETYPE_PEM), WOLFSSL_SUCCESS); - AssertNotNull(sslServer = SSL_new(ctx)); - AssertNotNull(serverAcceptBio = BIO_pop(serverBindBio)); + ExpectNotNull(ctx = SSL_CTX_new(SSLv23_method())); + ExpectIntEQ(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + SSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + SSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + ExpectNotNull(sslServer = SSL_new(ctx)); + ExpectNotNull(serverAcceptBio = BIO_pop(serverBindBio)); SSL_set_bio(sslServer, serverAcceptBio, serverAcceptBio); - AssertIntEQ(SSL_accept(sslServer), 1); + ExpectIntEQ(SSL_accept(sslServer), 1); join_thread(thread); @@ -45551,7 +45667,7 @@ static int test_wolfSSL_BIO_accept(void) wc_ecc_fp_free(); /* free per thread cache */ #endif - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -45559,10 +45675,12 @@ static int test_wolfSSL_BIO_accept(void) static int test_wolfSSL_BIO_write(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_BASE64_ENCODE) - BIO* bio; - BIO* bio64; - BIO* ptr; +#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_BASE64_ENCODE) + EXPECT_DECLS; + BIO* bio = NULL; + BIO* bio64 = NULL; + BIO* bio_mem = NULL; + BIO* ptr = NULL; int sz; char msg[] = "conversion test"; char out[40]; @@ -45570,70 +45688,82 @@ static int test_wolfSSL_BIO_write(void) void* bufPtr = NULL; BUF_MEM* buf = NULL; - AssertNotNull(bio64 = BIO_new(BIO_f_base64())); - AssertNotNull(bio = BIO_push(bio64, BIO_new(BIO_s_mem()))); + ExpectNotNull(bio64 = BIO_new(BIO_f_base64())); + ExpectNotNull(bio = BIO_push(bio64, BIO_new(BIO_s_mem()))); + if (EXPECT_FAIL()) { + BIO_free(bio64); + } /* now should convert to base64 then write to memory */ - AssertIntEQ(BIO_write(bio, msg, sizeof(msg)), sizeof(msg)); + ExpectIntEQ(BIO_write(bio, msg, sizeof(msg)), sizeof(msg)); BIO_flush(bio); /* test BIO chain */ - AssertIntEQ(SSL_SUCCESS, (int)BIO_get_mem_ptr(bio, &buf)); - AssertNotNull(buf); - AssertIntEQ(buf->length, 25); - AssertIntEQ(BIO_get_mem_data(bio, &bufPtr), 25); - AssertPtrEq(buf->data, bufPtr); + ExpectIntEQ(SSL_SUCCESS, (int)BIO_get_mem_ptr(bio, &buf)); + ExpectNotNull(buf); + ExpectIntEQ(buf->length, 25); + ExpectIntEQ(BIO_get_mem_data(bio, &bufPtr), 25); + ExpectPtrEq(buf->data, bufPtr); - AssertNotNull(ptr = BIO_find_type(bio, BIO_TYPE_MEM)); + ExpectNotNull(ptr = BIO_find_type(bio, BIO_TYPE_MEM)); sz = sizeof(out); XMEMSET(out, 0, sz); - AssertIntEQ((sz = BIO_read(ptr, out, sz)), 25); - AssertIntEQ(XMEMCMP(out, expected, sz), 0); + ExpectIntEQ((sz = BIO_read(ptr, out, sz)), 25); + ExpectIntEQ(XMEMCMP(out, expected, sz), 0); /* write then read should return the same message */ - AssertIntEQ(BIO_write(bio, msg, sizeof(msg)), sizeof(msg)); + ExpectIntEQ(BIO_write(bio, msg, sizeof(msg)), sizeof(msg)); sz = sizeof(out); XMEMSET(out, 0, sz); - AssertIntEQ(BIO_read(bio, out, sz), 16); - AssertIntEQ(XMEMCMP(out, msg, sizeof(msg)), 0); + ExpectIntEQ(BIO_read(bio, out, sz), 16); + ExpectIntEQ(XMEMCMP(out, msg, sizeof(msg)), 0); /* now try encoding with no line ending */ BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL); - #ifdef HAVE_EX_DATA +#ifdef HAVE_EX_DATA BIO_set_ex_data(bio64, 0, (void*) "data"); - AssertIntEQ(strcmp((const char*)BIO_get_ex_data(bio64, 0), "data"), 0); - #endif - AssertIntEQ(BIO_write(bio, msg, sizeof(msg)), sizeof(msg)); + ExpectIntEQ(strcmp((const char*)BIO_get_ex_data(bio64, 0), "data"), 0); +#endif + ExpectIntEQ(BIO_write(bio, msg, sizeof(msg)), sizeof(msg)); BIO_flush(bio); sz = sizeof(out); XMEMSET(out, 0, sz); - AssertIntEQ((sz = BIO_read(ptr, out, sz)), 24); - AssertIntEQ(XMEMCMP(out, expected, sz), 0); + ExpectIntEQ((sz = BIO_read(ptr, out, sz)), 24); + ExpectIntEQ(XMEMCMP(out, expected, sz), 0); BIO_free_all(bio); /* frees bio64 also */ + bio = NULL; /* test with more than one bio64 in list */ - AssertNotNull(bio64 = BIO_new(BIO_f_base64())); - AssertNotNull(bio = BIO_push(BIO_new(BIO_f_base64()), bio64)); - AssertNotNull(BIO_push(bio64, BIO_new(BIO_s_mem()))); + ExpectNotNull(bio64 = BIO_new(BIO_f_base64())); + ExpectNotNull(bio = BIO_push(BIO_new(BIO_f_base64()), bio64)); + if (EXPECT_FAIL()) { + BIO_free(bio64); + } + ExpectNotNull(bio_mem = BIO_new(BIO_s_mem())); + ExpectNotNull(BIO_push(bio64, bio_mem)); + if (EXPECT_FAIL()) { + BIO_free(bio_mem); + } /* now should convert to base64 when stored and then decode with read */ - AssertIntEQ(BIO_write(bio, msg, sizeof(msg)), 25); + ExpectIntEQ(BIO_write(bio, msg, sizeof(msg)), 25); BIO_flush(bio); sz = sizeof(out); XMEMSET(out, 0, sz); - AssertIntEQ((sz = BIO_read(bio, out, sz)), 16); - AssertIntEQ(XMEMCMP(out, msg, sz), 0); + ExpectIntEQ((sz = BIO_read(bio, out, sz)), 16); + ExpectIntEQ(XMEMCMP(out, msg, sz), 0); BIO_clear_flags(bio64, ~0); BIO_set_retry_read(bio); BIO_free_all(bio); /* frees bio64s also */ + bio = NULL; - AssertNotNull(bio = BIO_new_mem_buf(out, 0)); - AssertIntEQ(BIO_write(bio, msg, sizeof(msg)), sizeof(msg)); + ExpectNotNull(bio = BIO_new_mem_buf(out, 0)); + ExpectIntEQ(BIO_write(bio, msg, sizeof(msg)), sizeof(msg)); BIO_free(bio); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -45641,34 +45771,37 @@ static int test_wolfSSL_BIO_write(void) static int test_wolfSSL_BIO_printf(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_ALL) - BIO* bio; +#if defined(OPENSSL_ALL) + EXPECT_DECLS; + BIO* bio = NULL; int sz = 7; char msg[] = "TLS 1.3 for the world"; char out[60]; char expected[] = "TLS 1.3 for the world : sz = 7"; XMEMSET(out, 0, sizeof(out)); - AssertNotNull(bio = BIO_new(BIO_s_mem())); - AssertIntEQ(BIO_printf(bio, "%s : sz = %d", msg, sz), 30); - AssertIntEQ(BIO_printf(NULL, ""), WOLFSSL_FATAL_ERROR); - AssertIntEQ(BIO_read(bio, out, sizeof(out)), 30); - AssertIntEQ(XSTRNCMP(out, expected, sizeof(expected)), 0); + ExpectNotNull(bio = BIO_new(BIO_s_mem())); + ExpectIntEQ(BIO_printf(bio, "%s : sz = %d", msg, sz), 30); + ExpectIntEQ(BIO_printf(NULL, ""), WOLFSSL_FATAL_ERROR); + ExpectIntEQ(BIO_read(bio, out, sizeof(out)), 30); + ExpectIntEQ(XSTRNCMP(out, expected, sizeof(expected)), 0); BIO_free(bio); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } static int test_wolfSSL_BIO_f_md(void) { int res = TEST_SKIPPED; - #if defined(OPENSSL_ALL) && !defined(NO_SHA256) - BIO *bio, *mem; +#if defined(OPENSSL_ALL) && !defined(NO_SHA256) + EXPECT_DECLS; + BIO* bio = NULL; + BIO* mem = NULL; char msg[] = "message to hash"; char out[60]; - EVP_MD_CTX* ctx; + EVP_MD_CTX* ctx = NULL; const unsigned char testKey[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, @@ -45699,67 +45832,69 @@ static int test_wolfSSL_BIO_f_md(void) }; unsigned char check[sizeof(testResult) + 1]; size_t checkSz = -1; - EVP_PKEY* key; + EVP_PKEY* key = NULL; XMEMSET(out, 0, sizeof(out)); - AssertNotNull(bio = BIO_new(BIO_f_md())); - AssertNotNull(mem = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_f_md())); + ExpectNotNull(mem = BIO_new(BIO_s_mem())); - AssertIntEQ(BIO_get_md_ctx(bio, &ctx), 1); - AssertIntEQ(EVP_DigestInit(ctx, EVP_sha256()), 1); + ExpectIntEQ(BIO_get_md_ctx(bio, &ctx), 1); + ExpectIntEQ(EVP_DigestInit(ctx, EVP_sha256()), 1); /* should not be able to write/read yet since just digest wrapper and no * data is passing through the bio */ - AssertIntEQ(BIO_write(bio, msg, 0), 0); - AssertIntEQ(BIO_pending(bio), 0); - AssertIntEQ(BIO_read(bio, out, sizeof(out)), 0); - AssertIntEQ(BIO_gets(bio, out, 3), 0); - AssertIntEQ(BIO_gets(bio, out, sizeof(out)), 32); - AssertIntEQ(XMEMCMP(emptyHash, out, 32), 0); + ExpectIntEQ(BIO_write(bio, msg, 0), 0); + ExpectIntEQ(BIO_pending(bio), 0); + ExpectIntEQ(BIO_read(bio, out, sizeof(out)), 0); + ExpectIntEQ(BIO_gets(bio, out, 3), 0); + ExpectIntEQ(BIO_gets(bio, out, sizeof(out)), 32); + ExpectIntEQ(XMEMCMP(emptyHash, out, 32), 0); BIO_reset(bio); /* append BIO mem to bio in order to read/write */ - AssertNotNull(bio = BIO_push(bio, mem)); + ExpectNotNull(bio = BIO_push(bio, mem)); XMEMSET(out, 0, sizeof(out)); - AssertIntEQ(BIO_write(mem, msg, sizeof(msg)), 16); - AssertIntEQ(BIO_pending(bio), 16); + ExpectIntEQ(BIO_write(mem, msg, sizeof(msg)), 16); + ExpectIntEQ(BIO_pending(bio), 16); /* this just reads the message and does not hash it (gets calls final) */ - AssertIntEQ(BIO_read(bio, out, sizeof(out)), 16); - AssertIntEQ(XMEMCMP(out, msg, sizeof(msg)), 0); + ExpectIntEQ(BIO_read(bio, out, sizeof(out)), 16); + ExpectIntEQ(XMEMCMP(out, msg, sizeof(msg)), 0); /* create a message digest using BIO */ XMEMSET(out, 0, sizeof(out)); - AssertIntEQ(BIO_write(bio, msg, sizeof(msg)), 16); - AssertIntEQ(BIO_pending(mem), 16); - AssertIntEQ(BIO_pending(bio), 16); - AssertIntEQ(BIO_gets(bio, out, sizeof(out)), 32); - AssertIntEQ(XMEMCMP(expectedHash, out, 32), 0); + ExpectIntEQ(BIO_write(bio, msg, sizeof(msg)), 16); + ExpectIntEQ(BIO_pending(mem), 16); + ExpectIntEQ(BIO_pending(bio), 16); + ExpectIntEQ(BIO_gets(bio, out, sizeof(out)), 32); + ExpectIntEQ(XMEMCMP(expectedHash, out, 32), 0); BIO_free(bio); + bio = NULL; BIO_free(mem); + mem = NULL; /* test with HMAC */ XMEMSET(out, 0, sizeof(out)); - AssertNotNull(bio = BIO_new(BIO_f_md())); - AssertNotNull(mem = BIO_new(BIO_s_mem())); + ExpectNotNull(bio = BIO_new(BIO_f_md())); + ExpectNotNull(mem = BIO_new(BIO_s_mem())); BIO_get_md_ctx(bio, &ctx); - AssertNotNull(key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, - testKey, (int)sizeof(testKey))); + ExpectNotNull(key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, testKey, + (int)sizeof(testKey))); EVP_DigestSignInit(ctx, NULL, EVP_sha256(), NULL, key); - AssertNotNull(bio = BIO_push(bio, mem)); + ExpectNotNull(bio = BIO_push(bio, mem)); BIO_write(bio, testData, (int)strlen(testData)); - EVP_DigestSignFinal(ctx, NULL, &checkSz); - EVP_DigestSignFinal(ctx, check, &checkSz); + ExpectIntEQ(EVP_DigestSignFinal(ctx, NULL, &checkSz), 1); + ExpectIntEQ(EVP_DigestSignFinal(ctx, check, &checkSz), 1); - AssertIntEQ(XMEMCMP(check, testResult, sizeof(testResult)), 0); + ExpectIntEQ(XMEMCMP(check, testResult, sizeof(testResult)), 0); EVP_PKEY_free(key); BIO_free(bio); BIO_free(mem); - res = TEST_RES_CHECK(1); - #endif + res = EXPECT_RESULT(); +#endif return res; } @@ -45767,17 +45902,18 @@ static int test_wolfSSL_BIO_up_ref(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) - BIO* bio; + EXPECT_DECLS; + BIO* bio = NULL; - AssertNotNull(bio = BIO_new(BIO_f_md())); - AssertIntEQ(BIO_up_ref(NULL), 0); - AssertIntEQ(BIO_up_ref(bio), 1); + ExpectNotNull(bio = BIO_new(BIO_f_md())); + ExpectIntEQ(BIO_up_ref(NULL), 0); + ExpectIntEQ(BIO_up_ref(bio), 1); BIO_free(bio); - AssertIntEQ(BIO_up_ref(bio), 1); + ExpectIntEQ(BIO_up_ref(bio), 1); BIO_free(bio); BIO_free(bio); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -45785,25 +45921,27 @@ static int test_wolfSSL_BIO_reset(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) - BIO* bio; + EXPECT_DECLS; + BIO* bio = NULL; byte buf[16]; - AssertNotNull(bio = BIO_new_mem_buf("secure your data", - (word32)XSTRLEN("secure your data"))); - AssertIntEQ(BIO_read(bio, buf, 6), 6); - AssertIntEQ(XMEMCMP(buf, "secure", 6), 0); + ExpectNotNull(bio = BIO_new_mem_buf("secure your data", + (word32)XSTRLEN("secure your data"))); + ExpectIntEQ(BIO_read(bio, buf, 6), 6); + ExpectIntEQ(XMEMCMP(buf, "secure", 6), 0); XMEMSET(buf, 0, 16); - AssertIntEQ(BIO_read(bio, buf, 16), 10); - AssertIntEQ(XMEMCMP(buf, " your data", 10), 0); + ExpectIntEQ(BIO_read(bio, buf, 16), 10); + ExpectIntEQ(XMEMCMP(buf, " your data", 10), 0); /* You cannot write to MEM BIO with read-only mode. */ - AssertIntEQ(BIO_write(bio, "WriteToReadonly", 15), 0); - AssertIntEQ(BIO_read(bio, buf, 16), -1); + ExpectIntEQ(BIO_write(bio, "WriteToReadonly", 15), 0); + ExpectIntEQ(BIO_read(bio, buf, 16), -1); XMEMSET(buf, 0, 16); - AssertIntEQ(BIO_reset(bio), 0); - AssertIntEQ(BIO_read(bio, buf, 16), 16); - AssertIntEQ(XMEMCMP(buf, "secure your data", 16), 0); + ExpectIntEQ(BIO_reset(bio), 0); + ExpectIntEQ(BIO_read(bio, buf, 16), 16); + ExpectIntEQ(XMEMCMP(buf, "secure your data", 16), 0); BIO_free(bio); - res = TEST_RES_CHECK(1); + + res = EXPECT_RESULT(); #endif return res; } @@ -55883,6 +56021,7 @@ static int test_wolfSSL_X509_load_crl_file(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(HAVE_CRL) && !defined(NO_FILESYSTEM) && \ !defined(NO_RSA) && !defined(NO_BIO) + EXPECT_DECLS; int i; char pem[][100] = { "./certs/crl/crl.pem", @@ -55897,73 +56036,75 @@ static int test_wolfSSL_X509_load_crl_file(void) "./certs/crl/crl2.der", "" }; - WOLFSSL_X509_STORE* store; - WOLFSSL_X509_LOOKUP* lookup; + WOLFSSL_X509_STORE* store = NULL; + WOLFSSL_X509_LOOKUP* lookup = NULL; - AssertNotNull(store = wolfSSL_X509_STORE_new()); - AssertNotNull(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())); + ExpectNotNull(store = wolfSSL_X509_STORE_new()); + ExpectNotNull(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())); - AssertIntEQ(X509_LOOKUP_load_file(lookup, "certs/ca-cert.pem", - X509_FILETYPE_PEM), 1); - AssertIntEQ(X509_LOOKUP_load_file(lookup, "certs/server-revoked-cert.pem", - X509_FILETYPE_PEM), 1); + ExpectIntEQ(X509_LOOKUP_load_file(lookup, "certs/ca-cert.pem", + X509_FILETYPE_PEM), 1); + ExpectIntEQ(X509_LOOKUP_load_file(lookup, "certs/server-revoked-cert.pem", + X509_FILETYPE_PEM), 1); if (store) { - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, svrCertFile, - WOLFSSL_FILETYPE_PEM), 1); + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, svrCertFile, + WOLFSSL_FILETYPE_PEM), 1); /* since store hasn't yet known the revoked cert*/ - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, "certs/server-revoked-cert.pem", - WOLFSSL_FILETYPE_PEM), 1); + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, + "certs/server-revoked-cert.pem", WOLFSSL_FILETYPE_PEM), 1); } - for (i = 0; pem[i][0] != '\0'; i++) - { - AssertIntEQ(X509_load_crl_file(lookup, pem[i], WOLFSSL_FILETYPE_PEM), 1); + for (i = 0; pem[i][0] != '\0'; i++) { + ExpectIntEQ(X509_load_crl_file(lookup, pem[i], WOLFSSL_FILETYPE_PEM), + 1); } if (store) { /* since store knows crl list */ - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, "certs/server-revoked-cert.pem", - WOLFSSL_FILETYPE_PEM ), CRL_CERT_REVOKED); + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, + "certs/server-revoked-cert.pem", WOLFSSL_FILETYPE_PEM), + CRL_CERT_REVOKED); } /* once feeing store */ X509_STORE_free(store); store = NULL; - AssertNotNull(store = wolfSSL_X509_STORE_new()); - AssertNotNull(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())); + ExpectNotNull(store = wolfSSL_X509_STORE_new()); + ExpectNotNull(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())); - AssertIntEQ(X509_LOOKUP_load_file(lookup, "certs/ca-cert.pem", - X509_FILETYPE_PEM), 1); - AssertIntEQ(X509_LOOKUP_load_file(lookup, "certs/server-revoked-cert.pem", - X509_FILETYPE_PEM), 1); + ExpectIntEQ(X509_LOOKUP_load_file(lookup, "certs/ca-cert.pem", + X509_FILETYPE_PEM), 1); + ExpectIntEQ(X509_LOOKUP_load_file(lookup, "certs/server-revoked-cert.pem", + X509_FILETYPE_PEM), 1); if (store) { - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, svrCertFile, - WOLFSSL_FILETYPE_PEM), 1); + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, svrCertFile, + WOLFSSL_FILETYPE_PEM), 1); /* since store hasn't yet known the revoked cert*/ - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, "certs/server-revoked-cert.pem", - WOLFSSL_FILETYPE_PEM), 1); + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, + "certs/server-revoked-cert.pem", WOLFSSL_FILETYPE_PEM), 1); } - for (i = 0; der[i][0] != '\0'; i++) - { - AssertIntEQ(X509_load_crl_file(lookup, der[i], WOLFSSL_FILETYPE_ASN1), 1); + for (i = 0; der[i][0] != '\0'; i++) { + ExpectIntEQ(X509_load_crl_file(lookup, der[i], WOLFSSL_FILETYPE_ASN1), + 1); } if (store) { /* since store knows crl list */ - AssertIntEQ(wolfSSL_CertManagerVerify(store->cm, "certs/server-revoked-cert.pem", - WOLFSSL_FILETYPE_PEM ), CRL_CERT_REVOKED); + ExpectIntEQ(wolfSSL_CertManagerVerify(store->cm, + "certs/server-revoked-cert.pem", WOLFSSL_FILETYPE_PEM), + CRL_CERT_REVOKED); } /* test for incorrect parameter */ - AssertIntEQ(X509_load_crl_file(NULL, pem[0], 0), 0); - AssertIntEQ(X509_load_crl_file(lookup, NULL, 0), 0); - AssertIntEQ(X509_load_crl_file(NULL, NULL, 0), 0); + ExpectIntEQ(X509_load_crl_file(NULL, pem[0], 0), 0); + ExpectIntEQ(X509_load_crl_file(lookup, NULL, 0), 0); + ExpectIntEQ(X509_load_crl_file(NULL, NULL, 0), 0); X509_STORE_free(store); store = NULL; - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -57052,25 +57193,24 @@ static int test_wolfSSL_X509_NAME_ENTRY_get_object(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) && !defined(NO_RSA) - X509 *x509; - X509_NAME* name; + EXPECT_DECLS; + X509 *x509 = NULL; + X509_NAME* name = NULL; int idx = 0; - X509_NAME_ENTRY *ne; + X509_NAME_ENTRY *ne = NULL; ASN1_OBJECT *object = NULL; - x509 = wolfSSL_X509_load_certificate_file(cliCertFile, WOLFSSL_FILETYPE_PEM); - AssertNotNull(x509); - name = X509_get_subject_name(x509); - idx = X509_NAME_get_index_by_NID(name, NID_commonName, -1); - AssertIntGE(idx, 0); + ExpectNotNull(x509 = wolfSSL_X509_load_certificate_file(cliCertFile, + WOLFSSL_FILETYPE_PEM)); + ExpectNotNull(name = X509_get_subject_name(x509)); + ExpectIntGE(idx = X509_NAME_get_index_by_NID(name, NID_commonName, -1), 0); - ne = X509_NAME_get_entry(name, idx); - AssertNotNull(ne); - AssertNotNull(object = X509_NAME_ENTRY_get_object(ne)); + ExpectNotNull(ne = X509_NAME_get_entry(name, idx)); + ExpectNotNull(object = X509_NAME_ENTRY_get_object(ne)); X509_free(x509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif return res; } @@ -57080,48 +57220,52 @@ static int test_wolfSSL_X509_STORE_get1_certs(void) int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_SIGNER_DER_CERT) && \ !defined(NO_FILESYSTEM) && !defined(NO_RSA) - X509_STORE_CTX *storeCtx; - X509_STORE *store; - X509 *caX509; - X509 *svrX509; - X509_NAME *subject; - WOLF_STACK_OF(WOLFSSL_X509) *certs; - - AssertNotNull(caX509 = - X509_load_certificate_file(caCertFile, SSL_FILETYPE_PEM)); - AssertNotNull((svrX509 = - wolfSSL_X509_load_certificate_file(svrCertFile, SSL_FILETYPE_PEM))); - AssertNotNull(storeCtx = X509_STORE_CTX_new()); - AssertNotNull(store = X509_STORE_new()); - AssertNotNull(subject = X509_get_subject_name(caX509)); + EXPECT_DECLS; + X509_STORE_CTX *storeCtx = NULL; + X509_STORE *store = NULL; + X509 *caX509 = NULL; + X509 *svrX509 = NULL; + X509_NAME *subject = NULL; + WOLF_STACK_OF(WOLFSSL_X509) *certs = NULL; + + ExpectNotNull(caX509 = X509_load_certificate_file(caCertFile, + SSL_FILETYPE_PEM)); + ExpectNotNull((svrX509 = wolfSSL_X509_load_certificate_file(svrCertFile, + SSL_FILETYPE_PEM))); + ExpectNotNull(storeCtx = X509_STORE_CTX_new()); + ExpectNotNull(store = X509_STORE_new()); + ExpectNotNull(subject = X509_get_subject_name(caX509)); /* Errors */ - AssertNull(X509_STORE_get1_certs(storeCtx, subject)); - AssertNull(X509_STORE_get1_certs(NULL, subject)); - AssertNull(X509_STORE_get1_certs(storeCtx, NULL)); + ExpectNull(X509_STORE_get1_certs(storeCtx, subject)); + ExpectNull(X509_STORE_get1_certs(NULL, subject)); + ExpectNull(X509_STORE_get1_certs(storeCtx, NULL)); - AssertIntEQ(X509_STORE_add_cert(store, caX509), SSL_SUCCESS); - AssertIntEQ(X509_STORE_CTX_init(storeCtx, store, caX509, NULL), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_add_cert(store, caX509), SSL_SUCCESS); + ExpectIntEQ(X509_STORE_CTX_init(storeCtx, store, caX509, NULL), + SSL_SUCCESS); /* Should find the cert */ - AssertNotNull(certs = X509_STORE_get1_certs(storeCtx, subject)); - AssertIntEQ(1, wolfSSL_sk_X509_num(certs)); + ExpectNotNull(certs = X509_STORE_get1_certs(storeCtx, subject)); + ExpectIntEQ(1, wolfSSL_sk_X509_num(certs)); sk_X509_pop_free(certs, NULL); + certs = NULL; /* Should not find the cert */ - AssertNotNull(subject = X509_get_subject_name(svrX509)); - AssertNotNull(certs = X509_STORE_get1_certs(storeCtx, subject)); - AssertIntEQ(0, wolfSSL_sk_X509_num(certs)); + ExpectNotNull(subject = X509_get_subject_name(svrX509)); + ExpectNotNull(certs = X509_STORE_get1_certs(storeCtx, subject)); + ExpectIntEQ(0, wolfSSL_sk_X509_num(certs)); sk_X509_pop_free(certs, NULL); + certs = NULL; X509_STORE_free(store); X509_STORE_CTX_free(storeCtx); X509_free(svrX509); X509_free(caX509); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA && WOLFSSL_SIGNER_DER_CERT && !NO_FILESYSTEM */ return res; } @@ -62684,35 +62828,34 @@ static int test_export_keying_material(void) static int test_wolfSSL_THREADID_hash(void) { - int result = TEST_SKIPPED; + int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) - unsigned long res; + EXPECT_DECLS; CRYPTO_THREADID id; CRYPTO_THREADID_current(NULL); - AssertTrue(1); - res = CRYPTO_THREADID_hash(NULL); - AssertTrue( res == 0UL); + /* Hash result is unsigned long. */ + ExpectTrue(CRYPTO_THREADID_hash(NULL) == 0UL); XMEMSET(&id, 0, sizeof(id)); - res = CRYPTO_THREADID_hash(&id); - AssertTrue( res == 0UL); + ExpectTrue(CRYPTO_THREADID_hash(&id) == 0UL); - result = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ - return result; + return res; } static int test_wolfSSL_CTX_set_ecdh_auto(void) { int res = TEST_SKIPPED; #if defined(OPENSSL_EXTRA) + EXPECT_DECLS; WOLFSSL_CTX* ctx = NULL; - AssertIntEQ( SSL_CTX_set_ecdh_auto(NULL,0),1); - AssertIntEQ( SSL_CTX_set_ecdh_auto(NULL,1),1); - AssertIntEQ( SSL_CTX_set_ecdh_auto(ctx,0),1); - AssertIntEQ( SSL_CTX_set_ecdh_auto(ctx,1),1); + ExpectIntEQ(SSL_CTX_set_ecdh_auto(NULL,0), 1); + ExpectIntEQ(SSL_CTX_set_ecdh_auto(NULL,1), 1); + ExpectIntEQ(SSL_CTX_set_ecdh_auto(ctx,0), 1); + ExpectIntEQ(SSL_CTX_set_ecdh_auto(ctx,1), 1); - res = TEST_RES_CHECK(1); + res = EXPECT_RESULT(); #endif /* OPENSSL_EXTRA */ return res; } @@ -66902,22 +67045,10 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_sk_SSL_CIPHER), TEST_DECL(test_wolfSSL_set1_curves_list), TEST_DECL(test_wolfSSL_set1_sigalgs_list), - TEST_DECL(test_wolfSSL_PKCS7_certs), - /* Converted above to use Expect unless where stated. */ + TEST_DECL(test_wolfSSL_X509_STORE_CTX), TEST_DECL(test_wolfSSL_X509_STORE_CTX_trusted_stack_cleanup), TEST_DECL(test_wolfSSL_X509_STORE_CTX_get0_current_issuer), - TEST_DECL(test_wolfSSL_msgCb), - /* Converted to use Expect. */ - TEST_DECL(test_wolfSSL_either_side), - /* Converted to use Expect. */ - TEST_DECL(test_wolfSSL_DTLS_either_side), - TEST_DECL(test_wolfSSL_dtls_fragments), - TEST_DECL(test_wolfSSL_dtls_AEAD_limit), - TEST_DECL(test_wolfSSL_ignore_alert_before_cookie), - TEST_DECL(test_wolfSSL_dtls_bad_record), - TEST_DECL(test_wolfSSL_dtls_stateless), - TEST_DECL(test_generate_cookie), TEST_DECL(test_wolfSSL_X509_STORE_set_flags), TEST_DECL(test_wolfSSL_X509_LOOKUP_load_file), TEST_DECL(test_wolfSSL_X509_Name_canon), @@ -66934,10 +67065,41 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_X509_STORE_load_locations), TEST_DECL(test_X509_STORE_get0_objects), TEST_DECL(test_wolfSSL_X509_load_crl_file), + TEST_DECL(test_wolfSSL_X509_STORE_get1_certs), + TEST_DECL(test_wolfSSL_X509_NAME_ENTRY_get_object), + TEST_DECL(test_wolfSSL_X509_cmp_time), + TEST_DECL(test_wolfSSL_X509_time_adj), + + TEST_DECL(test_wolfSSL_X509), + TEST_DECL(test_wolfSSL_X509_VERIFY_PARAM), + TEST_DECL(test_wolfSSL_X509_sign), + TEST_DECL(test_wolfSSL_X509_sign2), + TEST_DECL(test_wolfSSL_X509_get0_tbs_sigalg), + TEST_DECL(test_wolfSSL_X509_ALGOR_get0), + TEST_DECL(test_wolfSSL_X509_get_X509_PUBKEY), + TEST_DECL(test_wolfSSL_X509_PUBKEY_RSA), + TEST_DECL(test_wolfSSL_X509_PUBKEY_EC), + TEST_DECL(test_wolfSSL_X509_PUBKEY_DSA), + + TEST_DECL(test_wolfSSL_msgCb), + TEST_DECL(test_wolfSSL_either_side), + TEST_DECL(test_wolfSSL_DTLS_either_side), + /* Uses Assert in handshake callback. */ + TEST_DECL(test_wolfSSL_dtls_fragments), + /* Uses Assert in handshake callback. */ + TEST_DECL(test_wolfSSL_dtls_AEAD_limit), + /* Uses Assert in handshake callback. */ + TEST_DECL(test_wolfSSL_ignore_alert_before_cookie), + /* Uses Assert in handshake callback. */ + TEST_DECL(test_wolfSSL_dtls_bad_record), + /* Uses Assert in handshake callback. */ + TEST_DECL(test_wolfSSL_dtls_stateless), + TEST_DECL(test_generate_cookie), /* RAND compatability API */ TEST_DECL(test_wolfSSL_RAND_set_rand_method), TEST_DECL(test_wolfSSL_RAND_bytes), + TEST_DECL(test_wolfSSL_RAND), /* BN compatability API */ TEST_DECL(test_wolfSSL_BN_CTX), @@ -66959,24 +67121,9 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_BIO), #endif TEST_DECL(test_wolfSSL_a2i_IPADDRESS), - TEST_DECL(test_wolfSSL_X509), - TEST_DECL(test_wolfSSL_X509_VERIFY_PARAM), - TEST_DECL(test_wolfSSL_X509_sign), - TEST_DECL(test_wolfSSL_X509_sign2), - TEST_DECL(test_wolfSSL_X509_get0_tbs_sigalg), - TEST_DECL(test_wolfSSL_X509_ALGOR_get0), -#if defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) - TEST_DECL(test_wolfSSL_check_domain), -#endif - TEST_DECL(test_wolfSSL_X509_get_X509_PUBKEY), - TEST_DECL(test_wolfSSL_X509_PUBKEY_RSA), - TEST_DECL(test_wolfSSL_X509_PUBKEY_EC), - TEST_DECL(test_wolfSSL_X509_PUBKEY_DSA), - TEST_DECL(test_wolfSSL_RAND), TEST_DECL(test_wolfSSL_BUF), TEST_DECL(test_wolfSSL_set_tlsext_status_type), - TEST_DECL(test_wolfSSL_X509_cmp_time), - TEST_DECL(test_wolfSSL_X509_time_adj), + /* Can't memory test as server hangs. */ TEST_DECL(test_wolfSSL_CTX_set_client_CA_list), TEST_DECL(test_wolfSSL_CTX_add_client_CA), TEST_DECL(test_wolfSSL_CTX_set_srp_username), @@ -66984,6 +67131,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_CTX_set_keylog_callback), TEST_DECL(test_wolfSSL_CTX_get_keylog_callback), TEST_DECL(test_wolfSSL_Tls12_Key_Logging_test), + /* Can't memory test as server hangs. */ TEST_DECL(test_wolfSSL_Tls13_Key_Logging_test), TEST_DECL(test_wolfSSL_Tls13_postauth), TEST_DECL(test_wolfSSL_CTX_set_ecdh_auto), @@ -66992,6 +67140,7 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_THREADID_hash), TEST_DECL(test_wolfSSL_PKCS8_Compat), TEST_DECL(test_wolfSSL_PKCS8_d2i), + /* Can't memory test as callbacks use Assert. */ TEST_DECL(test_error_queue_per_thread), TEST_DECL(test_wolfSSL_ERR_put_error), TEST_DECL(test_wolfSSL_ERR_get_error_order), @@ -67012,22 +67161,30 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_X509_set_notAfter), TEST_DECL(test_wolfSSL_X509_set_notBefore), TEST_DECL(test_wolfSSL_X509_set_version), + #ifndef NO_BIO TEST_DECL(test_wolfSSL_BIO_gets), TEST_DECL(test_wolfSSL_BIO_puts), TEST_DECL(test_wolfSSL_BIO_dump), + /* Can't memory test as server hangs. */ TEST_DECL(test_wolfSSL_BIO_should_retry), - TEST_DECL(test_wolfSSL_d2i_PUBKEY), TEST_DECL(test_wolfSSL_BIO_write), + /* Can't memory test as server hangs. */ TEST_DECL(test_wolfSSL_BIO_connect), + /* Can't memory test as server Asserts in thread. */ TEST_DECL(test_wolfSSL_BIO_accept), TEST_DECL(test_wolfSSL_BIO_printf), TEST_DECL(test_wolfSSL_BIO_f_md), TEST_DECL(test_wolfSSL_BIO_up_ref), - TEST_DECL(test_wolfSSL_BIO_tls), TEST_DECL(test_wolfSSL_BIO_reset), + TEST_DECL(test_wolfSSL_BIO_tls), #endif + /* Converted above to use Expect unless where stated. */ +#if defined(OPENSSL_EXTRA) && defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) + /* Converted to use Expect. */ + TEST_DECL(test_wolfSSL_check_domain), +#endif /* Converted to use Expect. */ TEST_DECL(test_wolfSSL_cert_cb), TEST_DECL(test_wolfSSL_SESSION), @@ -67060,8 +67217,6 @@ TEST_CASE testCases[] = { #ifndef NO_BIO TEST_DECL(test_wolfSSL_PEM_X509_INFO_read_bio), #endif - TEST_DECL(test_wolfSSL_X509_STORE_get1_certs), - TEST_DECL(test_wolfSSL_X509_NAME_ENTRY_get_object), TEST_DECL(test_wolfSSL_OpenSSL_add_all_algorithms), TEST_DECL(test_wolfSSL_OPENSSL_hexstr2buf), TEST_DECL(test_wolfSSL_X509_check_ca), @@ -67151,11 +67306,14 @@ TEST_CASE testCases[] = { TEST_DECL(test_wolfSSL_TXT_DB), TEST_DECL(test_wolfSSL_NCONF), #endif /* OPENSSL_ALL */ +#ifndef NO_BIO + TEST_DECL(test_wolfSSL_d2i_PUBKEY), +#endif #if (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO)) && !defined(NO_RSA) - TEST_DECL(test_wolfSSL_CTX_use_certificate_ASN1), #ifndef NO_BIO TEST_DECL(test_wolfSSL_d2i_PrivateKeys_bio), #endif /* !NO_BIO */ + TEST_DECL(test_wolfSSL_CTX_use_certificate_ASN1), #endif /* (OPENSSL_ALL || WOLFSSL_ASIO) && !NO_RSA */ TEST_DECL(test_wolfSSL_X509_CA_num), TEST_DECL(test_wolfSSL_X509_get_version), @@ -67260,6 +67418,8 @@ TEST_CASE testCases[] = { TEST_DECL(test_X509_REQ), /* OpenSSL PKCS7 API test */ TEST_DECL(test_wolfssl_PKCS7), + /* Converted to use Expect. */ + TEST_DECL(test_wolfSSL_PKCS7_certs), TEST_DECL(test_wolfSSL_PKCS7_sign), TEST_DECL(test_wolfSSL_PKCS7_SIGNED_new), #ifndef NO_BIO From c3475382b80f79bc05b8cdf97a68feb71b18a963 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Tue, 6 Jun 2023 14:26:06 +1000 Subject: [PATCH 364/391] Kyber: allow compilation with limited sizes with liboqs --- configure.ac | 21 +++++++++++---------- wolfssl/wolfcrypt/asn_public.h | 3 ++- wolfssl/wolfcrypt/settings.h | 10 ++++++---- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/configure.ac b/configure.ac index fa65867962b..cc5be80c694 100644 --- a/configure.ac +++ b/configure.ac @@ -1115,18 +1115,19 @@ done if test "$ENABLED_KYBER" != "no" then AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HAVE_KYBER" + + if test "$ENABLED_KYBER512" = ""; then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_NO_KYBER512" + fi + if test "$ENABLED_KYBER768" = ""; then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_NO_KYBER768" + fi + if test "$ENABLED_KYBER1024" = ""; then + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_NO_KYBER1024" + fi + if test "$ENABLED_WC_KYBER" = "yes" then - if test "$ENABLED_KYBER512" = ""; then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_NO_KYBER512" - fi - if test "$ENABLED_KYBER768" = ""; then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_NO_KYBER768" - fi - if test "$ENABLED_KYBER1024" = ""; then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_NO_KYBER1024" - fi - test "$enable_sha3" = "" && enable_sha3=yes test "$enable_shake128" = "" && enable_shake128=yes test "$enable_shake256" = "" && enable_shake256=yes diff --git a/wolfssl/wolfcrypt/asn_public.h b/wolfssl/wolfcrypt/asn_public.h index 903d087389d..21399b8fbbd 100644 --- a/wolfssl/wolfcrypt/asn_public.h +++ b/wolfssl/wolfcrypt/asn_public.h @@ -761,7 +761,8 @@ WOLFSSL_API int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz); (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) || \ (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) || \ (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) || \ - (defined(HAVE_PQC))) + (defined(HAVE_PQC) && (defined(HAVE_FALCON) || \ + defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS)))) #define WC_ENABLE_ASYM_KEY_IMPORT #endif diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index d5b1553ab7c..47e3b7363af 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -2923,10 +2923,12 @@ extern void uITRON4_free(void *p) ; #define HAVE_FALCON #define HAVE_DILITHIUM #define HAVE_SPHINCS -#define WOLFSSL_HAVE_KYBER -#define WOLFSSL_KYBER512 -#define WOLFSSL_KYBER768 -#define WOLFSSL_KYBER1024 +#ifndef WOLFSSL_HAVE_KYBER + #define WOLFSSL_HAVE_KYBER + #define WOLFSSL_KYBER512 + #define WOLFSSL_KYBER768 + #define WOLFSSL_KYBER1024 +#endif #endif #ifdef HAVE_PQM4 From dfa0de71f165872c7679af0e40c6cece6f30269c Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 7 Jun 2023 13:23:43 -0600 Subject: [PATCH 365/391] set ext pointer to null after free'ing it --- src/x509.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/x509.c b/src/x509.c index c29503d76e3..dc8bc4adc7e 100644 --- a/src/x509.c +++ b/src/x509.c @@ -1218,6 +1218,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) x509->ext_sk = wolfSSL_sk_new_x509_ext(); if (wolfSSL_sk_X509_EXTENSION_push(x509->ext_sk, ext) == WOLFSSL_FAILURE) { wolfSSL_X509_EXTENSION_free(ext); + ext = NULL; } FreeDecodedCert(cert); From 4f49dc3f22734d5c88eacae93d6b4397267feffa Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 7 Jun 2023 13:29:41 -0600 Subject: [PATCH 366/391] free up memory with othername object on error --- src/x509.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/x509.c b/src/x509.c index dc8bc4adc7e..45a58b9ff0e 100644 --- a/src/x509.c +++ b/src/x509.c @@ -586,6 +586,7 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, /* Next is: [0]. Check tag and length. */ if (GetASNTag(p, &idx, &tag, (word32)len) < 0) { + wolfSSL_ASN1_OBJECT_free(obj); goto err; } if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)) { From 1216fc784a49d9e1c22bea1d3125accf1d6d08ef Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 7 Jun 2023 14:41:47 -0600 Subject: [PATCH 367/391] clear extension string and avoid potential double free --- src/x509.c | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/x509.c b/src/x509.c index 45a58b9ff0e..9caf3a62677 100644 --- a/src/x509.c +++ b/src/x509.c @@ -223,9 +223,26 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_new(void) return newExt; } + +/* Clear out and free internal pointers of ASN.1 STRING object. + * + * @param [in] asn1 ASN.1 STRING object. + */ +static void wolfSSL_ASN1_STRING_clear(WOLFSSL_ASN1_STRING* asn1) +{ + /* Check we have an object to free. */ + if (asn1 != NULL) { + /* Dispose of dynamic data. */ + if ((asn1->length > 0) && asn1->isDynamic) { + XFREE(asn1->data, NULL, DYNAMIC_TYPE_OPENSSL); + } + XMEMSET(asn1, 0, sizeof(WOLFSSL_ASN1_STRING)); + } +} + + void wolfSSL_X509_EXTENSION_free(WOLFSSL_X509_EXTENSION* x) { - WOLFSSL_ASN1_STRING asn1; WOLFSSL_ENTER("wolfSSL_X509_EXTENSION_free"); if (x == NULL) return; @@ -234,10 +251,7 @@ void wolfSSL_X509_EXTENSION_free(WOLFSSL_X509_EXTENSION* x) wolfSSL_ASN1_OBJECT_free(x->obj); } - asn1 = x->value; - if (asn1.length > 0 && asn1.data != NULL && asn1.isDynamic) - XFREE(asn1.data, NULL, DYNAMIC_TYPE_OPENSSL); - + wolfSSL_ASN1_STRING_clear(&x->value); wolfSSL_sk_pop_free(x->ext_sk, NULL); XFREE(x, NULL, DYNAMIC_TYPE_X509_EXT); @@ -304,7 +318,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_create_by_OBJ( /* Prevent potential memory leaks and dangling pointers. */ wolfSSL_ASN1_OBJECT_free(ret->obj); ret->obj = NULL; - wolfSSL_ASN1_STRING_free(&ret->value); + wolfSSL_ASN1_STRING_clear(&ret->value); } if (err == 0) { From dfce8012950da5d4d30140a44e46018ba199cafb Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 7 Jun 2023 14:59:07 -0600 Subject: [PATCH 368/391] account for null terminator with SEP serail number --- wolfcrypt/src/asn.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 730fdf1a4ab..e74209411e8 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -16694,8 +16694,8 @@ static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert) cert->hwTypeSz = (int)oidLen; /* TODO: check this is the HW serial number OID - no test data. */ - /* Allocate space for HW serial number. */ - cert->hwSerialNum = (byte*)XMALLOC(serialLen, cert->heap, + /* Allocate space for HW serial number, +1 for null terminator. */ + cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap, DYNAMIC_TYPE_X509_EXT); if (cert->hwSerialNum == NULL) { WOLFSSL_MSG("\tOut of Memory"); From 04699301e8cd3d8138ebe5b5769a6275646389cb Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 7 Jun 2023 15:05:52 -0600 Subject: [PATCH 369/391] set return bio to null after free on error --- src/bio.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bio.c b/src/bio.c index 595343488f0..5f845cf0bf0 100644 --- a/src/bio.c +++ b/src/bio.c @@ -2375,6 +2375,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (err == 1) { wolfSSL_free(ssl); wolfSSL_BIO_free(sslBio); + sslBio = NULL; wolfSSL_BIO_free(connBio); } From 33cea039dc210aa8f765add63f35b22e5b881f9d Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 7 Jun 2023 15:13:13 -0600 Subject: [PATCH 370/391] avoid use after free in error case --- src/pk.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/pk.c b/src/pk.c index 4b4d996716d..57cd5a1460c 100644 --- a/src/pk.c +++ b/src/pk.c @@ -360,8 +360,7 @@ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, DYNAMIC_TYPE_TMP_BUFFER); if (tmpBuf == NULL) { WOLFSSL_ERROR_MSG("Extending DER buffer failed"); - XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); - ret = 0; + ret = 0; /* der buffer is free'd at the end of the function */ } else { der = tmpBuf; From 09123eb6bad6f2d0fdce819ac28d2417c6cd5664 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 7 Jun 2023 15:20:23 -0600 Subject: [PATCH 371/391] check on allocation of new node before dereferencing --- src/x509.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/x509.c b/src/x509.c index 9caf3a62677..9084483203b 100644 --- a/src/x509.c +++ b/src/x509.c @@ -13965,7 +13965,9 @@ int wolfSSL_X509_REQ_add1_attr_by_NID(WOLFSSL_X509 *req, else { if (req->reqAttributes == NULL) { req->reqAttributes = wolfSSL_sk_new_node(req->heap); - req->reqAttributes->type = STACK_TYPE_X509_REQ_ATTR; + if (req->reqAttributes != NULL) { + req->reqAttributes->type = STACK_TYPE_X509_REQ_ATTR; + } } ret = wolfSSL_sk_push(req->reqAttributes, attr); } From 49cd315b589dbeb8860edb41dabfc02e720ee95a Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Mon, 5 Jun 2023 14:45:34 -0600 Subject: [PATCH 372/391] add sanity check on hash size with STM32 port --- wolfcrypt/src/port/st/stm32.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index 73b43a525f6..3b8c01411d1 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -984,8 +984,21 @@ int stm32_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, pka_ecc.pPubKeyCurvePtY = Qybin; pka_ecc.RSign = Rbin; pka_ecc.SSign = Sbin; + XMEMSET(Hashbin, 0, STM32_MAX_ECC_SIZE); - XMEMCPY(Hashbin + (size - hashlen), hash, hashlen); + if (hashlen > STM32_MAX_ECC_SIZE) { + return ECC_BAD_ARG_E; + } + else if (hashlen > size) { + /* in the case that hashlen is larger than key size place hash at + * beginning of buffer */ + XMEMCPY(Hashbin, hash, hashlen); + } + else { + /* in all other cases where hashlen is equal to or less than the key + * size pad the Hashbin buffer with leading zero's */ + XMEMCPY(Hashbin + (size - hashlen), hash, hashlen); + } pka_ecc.hash = Hashbin; status = HAL_PKA_ECDSAVerif(&hpka, &pka_ecc, HAL_MAX_DELAY); From b4edbd3d4c36be5637fc381cde519742df1b0912 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Tue, 6 Jun 2023 12:09:41 -0600 Subject: [PATCH 373/391] add additional STM32 ECC sanity check to sign --- wolfcrypt/src/port/st/stm32.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index 3b8c01411d1..34e732ae375 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -992,7 +992,7 @@ int stm32_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, else if (hashlen > size) { /* in the case that hashlen is larger than key size place hash at * beginning of buffer */ - XMEMCPY(Hashbin, hash, hashlen); + XMEMCPY(Hashbin, hash, size); } else { /* in all other cases where hashlen is equal to or less than the key @@ -1072,7 +1072,19 @@ int stm32_ecc_sign_hash_ex(const byte* hash, word32 hashlen, WC_RNG* rng, pka_ecc.primeOrder = order; XMEMSET(Hashbin, 0, STM32_MAX_ECC_SIZE); - XMEMCPY(Hashbin + (size - hashlen), hash, hashlen); + if (hashlen > STM32_MAX_ECC_SIZE) { + return ECC_BAD_ARG_E; + } + else if (hashlen > size) { + /* in the case that hashlen is larger than key size place hash at + * beginning of buffer */ + XMEMCPY(Hashbin, hash, size); + } + else { + /* in all other cases where hashlen is equal to or less than the key + * size pad the Hashbin buffer with leading zero's */ + XMEMCPY(Hashbin + (size - hashlen), hash, hashlen); + } pka_ecc.hash = Hashbin; pka_ecc.integer = Intbin; pka_ecc.privateKey = Keybin; From c7f02e0df97a01fbab44eb856260ecc633b09d3a Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 8 Jun 2023 10:47:02 +1000 Subject: [PATCH 374/391] Coverity fixes: api.c Fixes from coverity scan in the file api.c. --- tests/api.c | 145 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 97 insertions(+), 48 deletions(-) diff --git a/tests/api.c b/tests/api.c index 70b6f558c39..74099289bdf 100644 --- a/tests/api.c +++ b/tests/api.c @@ -3806,6 +3806,7 @@ static int test_wolfSSL_set_minmax_proto_version(void) wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); + ctx = NULL; #endif #ifndef NO_WOLFSSL_SERVER ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())); @@ -5414,6 +5415,9 @@ static WC_INLINE int test_ssl_memio_setup(test_ssl_memio_ctx *ctx) method = wolfSSLv23_server_method(); } ExpectNotNull(ctx->s_ctx = wolfSSL_CTX_new(method)); + if (EXPECT_FAIL()) { + XFREE(method, NULL, DYNAMIC_TYPE_METHOD); + } ctx->s_cb.isSharedCtx = 0; } if (!ctx->s_cb.ticNoInit && (ctx->s_ctx != NULL)) { @@ -5601,12 +5605,16 @@ static int test_ssl_memio_read_write(test_ssl_memio_ctx* ctx) ExpectIntEQ(wolfSSL_write(ctx->c_ssl, msg_c, msglen_c), msglen_c); ExpectIntGT(idx = wolfSSL_read(ctx->s_ssl, input, sizeof(input) - 1), 0); - input[idx] = '\0'; + if (idx >= 0) { + input[idx] = '\0'; + } ExpectIntGT(fprintf(stderr, "Client message: %s\n", input), 0); ExpectIntEQ(wolfSSL_write(ctx->s_ssl, msg_s, msglen_s), msglen_s); ctx->s_cb.return_code = EXPECT_RESULT(); ExpectIntGT(idx = wolfSSL_read(ctx->c_ssl, input, sizeof(input) - 1), 0); - input[idx] = '\0'; + if (idx >= 0) { + input[idx] = '\0'; + } ExpectIntGT(fprintf(stderr, "Server response: %s\n", input), 0); ctx->c_cb.return_code = EXPECT_RESULT(); if (ctx->c_cb.on_result != NULL) { @@ -32491,11 +32499,13 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); - tpp--; - ExpectIntEQ(*(tpp--), 128); - ExpectIntEQ(*tpp, 0); + if (tpp != NULL) { + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); + tpp--; + ExpectIntEQ(*(tpp--), 128); + ExpectIntEQ(*tpp, 0); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); pp = NULL; @@ -32510,10 +32520,12 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); - tpp--; - ExpectIntEQ(*tpp, 216); + if (tpp != NULL) { + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 216); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); pp = NULL; @@ -32528,10 +32540,12 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); - tpp--; - ExpectIntEQ(*tpp, 128); + if (tpp != NULL) { + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 128); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); pp = NULL; @@ -32546,11 +32560,13 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); - tpp--; - ExpectIntEQ(*(tpp--), 56); - ExpectIntEQ(*tpp, 255); + if (tpp != NULL) { + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); + tpp--; + ExpectIntEQ(*(tpp--), 56); + ExpectIntEQ(*tpp, 255); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); pp = NULL; @@ -32564,10 +32580,12 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); - tpp--; - ExpectIntEQ(*tpp, 0); + if (tpp != NULL) { + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 0); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); pp = NULL; @@ -32581,11 +32599,13 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 1); ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); - tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); - tpp--; - ExpectIntEQ(*tpp, 0); + if (tpp != NULL) { + tpp = pp; + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 1); + tpp--; + ExpectIntEQ(*tpp, 0); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); pp = NULL; @@ -32600,12 +32620,14 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectIntEQ(ret = i2c_ASN1_INTEGER(a, NULL), 2); ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); - tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); - tpp -= 2; - ExpectIntEQ(tpp[0], 0x01); - ExpectIntEQ(tpp[1], 0x00); + if (tpp != NULL) { + tpp = pp; + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); + tpp -= 2; + ExpectIntEQ(tpp[0], 0x01); + ExpectIntEQ(tpp[1], 0x00); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); pp = NULL; @@ -32621,11 +32643,13 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); - tpp -= 2; - ExpectIntEQ(tpp[0], 0x80); - ExpectIntEQ(tpp[1], 0x00); + if (tpp != NULL) { + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 2); + tpp -= 2; + ExpectIntEQ(tpp[0], 0x80); + ExpectIntEQ(tpp[1], 0x00); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); pp = NULL; @@ -32641,12 +32665,14 @@ static int test_wolfSSL_i2c_ASN1_INTEGER(void) ExpectNotNull(pp = (unsigned char*)XMALLOC(ret + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER)); tpp = pp; - ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); - ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 3); - tpp -= 3; - ExpectIntEQ(tpp[0], 0xFF); - ExpectIntEQ(tpp[1], 0x7F); - ExpectIntEQ(tpp[2], 0xFF); + if (tpp != NULL) { + ExpectNotNull(XMEMSET(tpp, 0, ret + 1)); + ExpectIntEQ(i2c_ASN1_INTEGER(a, &tpp), 3); + tpp -= 3; + ExpectIntEQ(tpp[0], 0xFF); + ExpectIntEQ(tpp[1], 0x7F); + ExpectIntEQ(tpp[2], 0xFF); + } XFREE(pp, NULL, DYNAMIC_TYPE_TMP_BUFFER); wolfSSL_ASN1_INTEGER_free(a); @@ -33071,9 +33097,13 @@ static int test_wolfSSL_i2s_ASN1_STRING(void) ExpectNotNull(str = ASN1_STRING_new()); - ExpectNull(wolfSSL_i2s_ASN1_STRING(NULL, NULL)); + ExpectNull(ret = wolfSSL_i2s_ASN1_STRING(NULL, NULL)); + XFREE(ret, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ret = NULL; /* No data. */ - ExpectNull(wolfSSL_i2s_ASN1_STRING(NULL, str)); + ExpectNull(ret = wolfSSL_i2s_ASN1_STRING(NULL, str)); + XFREE(ret, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ret = NULL; ExpectIntEQ(ASN1_STRING_set(str, data, 0), 1); ExpectNotNull(ret = wolfSSL_i2s_ASN1_STRING(NULL, str)); @@ -33770,6 +33800,7 @@ static int test_wolfSSL_ASN1_TIME_adj(void) date_str[CTC_DATE_SIZE] = '\0'; ExpectIntEQ(0, XMEMCMP(date_str, "000222211515Z", 13)); XFREE(asn_time, NULL, DYNAMIC_TYPE_OPENSSL); + asn_time = NULL; ExpectNotNull(asn_time = wolfSSL_ASN1_TIME_adj(NULL, t, offset_day, offset_sec)); @@ -36494,6 +36525,7 @@ static int test_wolfSSL_PEM_PrivateKey(void) EVP_PKEY_free(pkey); pkey = NULL; SSL_CTX_free(ctx); + server_key = NULL; } #endif @@ -39111,6 +39143,8 @@ static int test_wolfSSL_CTX_set_client_CA_list(void) wolfSSL_free(ssl_client); wolfSSL_CTX_free(ctx_client); + CloseSocket(sockfd); + join_thread(serverThread); FreeTcpReady(&ready); } @@ -39583,6 +39617,8 @@ static int test_wolfSSL_Tls13_ECH(void) wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); + CloseSocket(sockfd); + join_thread(serverThread); FreeTcpReady(&ready); @@ -40373,6 +40409,7 @@ static int test_wolfSSL_BN_enc_dec(void) ExpectNotNull(BN_hex2bn(&b, numberStr)); ExpectIntEQ(BN_cmp(a, b), -1); XFREE(str, NULL, DYNAMIC_TYPE_OPENSSL); + str = NULL; #if defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) ExpectNotNull(str = BN_bn2dec(a)); @@ -42045,12 +42082,14 @@ static int test_wolfSSL_a2i_IPADDRESS(void) ExpectIntEQ(dataSz = ASN1_STRING_length(st), WOLFSSL_IP4_ADDR_LEN); ExpectIntEQ(XMEMCMP(data, ipv4_exp, dataSz), 0); ASN1_STRING_free(st); + st = NULL; ExpectNotNull(st = a2i_IPADDRESS("::1")); ExpectNotNull(data = ASN1_STRING_get0_data(st)); ExpectIntEQ(dataSz = ASN1_STRING_length(st), WOLFSSL_IP6_ADDR_LEN); ExpectIntEQ(XMEMCMP(data, ipv6_home, dataSz), 0); ASN1_STRING_free(st); + st = NULL; ExpectNotNull(st = a2i_IPADDRESS("2021:db8::ff00:42:7777")); ExpectNotNull(data = ASN1_STRING_get0_data(st)); @@ -44324,7 +44363,11 @@ static int test_wolfSSL_OBJ_txt2obj(void) }; ExpectNull(obj = OBJ_txt2obj("Bad name", 0)); + ASN1_OBJECT_free(obj); + obj = NULL; ExpectNull(obj = OBJ_txt2obj(NULL, 0)); + ASN1_OBJECT_free(obj); + obj = NULL; for (i = 0; objs_list[i].oidStr != NULL; i++) { /* Test numerical value of oid (oidStr) */ @@ -45418,6 +45461,8 @@ static int test_wolfSSL_BIO_should_retry(void) BIO_free(bio); wolfSSL_CTX_free(ctx); + CloseSocket(sockfd); + join_thread(serverThread); FreeTcpReady(&ready); @@ -45739,6 +45784,7 @@ static int test_wolfSSL_BIO_write(void) ExpectNotNull(bio = BIO_push(BIO_new(BIO_f_base64()), bio64)); if (EXPECT_FAIL()) { BIO_free(bio64); + bio64 = NULL; } ExpectNotNull(bio_mem = BIO_new(BIO_s_mem())); ExpectNotNull(BIO_push(bio64, bio_mem)); @@ -66630,6 +66676,9 @@ static int test_dtls_msg_from_other_peer_cb(WOLFSSL_CTX *ctx, WOLFSSL *ssl) (void)ssl; (void)ctx; + if (ssl == NULL) + return -1; + err = test_dtls_msg_get_connected_port(wolfSSL_get_fd(ssl), &port); if (err != 0) return -1; From 4d37de40419c724fadd6eba47fd9ab4c5b5d0d74 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Thu, 8 Jun 2023 02:37:21 -0600 Subject: [PATCH 375/391] sanity check on socket return value for timeout with DTLS13 --- src/internal.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/internal.c b/src/internal.c index 8a691d707da..47d8436bb7c 100644 --- a/src/internal.c +++ b/src/internal.c @@ -10418,6 +10418,9 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, * DTLS_RECORD_HEADER_SZ */ if (ssl->buffers.inputBuffer.length - *inOutIdx < DTLS_RECORD_HEADER_SZ) { ret = GetInputData(ssl, DTLS_RECORD_HEADER_SZ); + /* Check if Dtls13RtxTimeout(ssl) returned socket error */ + if (ret == SOCKET_ERROR_E) + return ret; if (ret != 0) return LENGTH_ERROR; } From b3b8bf8141e9824a358a2ebae8072e7b373b0a63 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 8 Jun 2023 14:43:05 -0500 Subject: [PATCH 376/391] linuxkm/linuxkm_wc_port.h: override definition of __is_constexpr() from /usr/src/linux/include/linux/const.h with warning-free __builtin_constant_p(). --- linuxkm/linuxkm_wc_port.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/linuxkm/linuxkm_wc_port.h b/linuxkm/linuxkm_wc_port.h index bc17aa57f7c..2794dba68b0 100644 --- a/linuxkm/linuxkm_wc_port.h +++ b/linuxkm/linuxkm_wc_port.h @@ -199,6 +199,10 @@ _Pragma("GCC diagnostic pop"); + /* avoid -Wpointer-arith, encountered when -DCONFIG_FORTIFY_SOURCE */ + #undef __is_constexpr + #define __is_constexpr(x) __builtin_constant_p(x) + /* the kernel uses -std=c89, but not -pedantic, and makes full use of anon * structs/unions, so we should too. */ From a567f02f9688d17d14c7b0eaa91dde08b16ac185 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 9 Jun 2023 05:51:18 -0700 Subject: [PATCH 377/391] prepare for release 5.6.2 --- CMakeLists.txt | 6 +- ChangeLog.md | 133 ++++++++++++++++++ IDE/WIN10/wolfssl-fips.rc | 8 +- README | 289 ++++++++++++++++---------------------- README.md | 288 ++++++++++++++++--------------------- configure.ac | 6 +- wolfssl.rc | Bin 4918 -> 4918 bytes wolfssl/version.h | 4 +- 8 files changed, 383 insertions(+), 351 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0be34caf81d..851e8f74bd0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,16 +28,16 @@ if("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}") You must delete them, or cmake will refuse to work.") endif() -project(wolfssl VERSION 5.6.0 LANGUAGES C ASM) +project(wolfssl VERSION 5.6.2 LANGUAGES C ASM) # shared library versioning # increment if interfaces have been added, removed or changed -set(LIBTOOL_CURRENT 39) +set(LIBTOOL_CURRENT 40) # increment if source code has changed set to zero if current is incremented set(LIBTOOL_REVISION 0) # increment if interfaces have been added set to zero if interfaces have been # removed or changed -set(LIBTOOL_AGE 4) +set(LIBTOOL_AGE 5) math(EXPR LIBTOOL_SO_VERSION "${LIBTOOL_CURRENT} - ${LIBTOOL_AGE}") set(LIBTOOL_FULL_VERSION ${LIBTOOL_SO_VERSION}.${LIBTOOL_AGE}.${LIBTOOL_REVISION}) diff --git a/ChangeLog.md b/ChangeLog.md index 1199ce388bb..bc5ca406ecf 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,136 @@ +# wolfSSL Release 5.6.2 (Jun 09, 2023) + +Release 5.6.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. +https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance + +NOTE: * --enable-heapmath is being deprecated and will be removed by 2024 + +Release 5.6.2 of wolfSSL embedded TLS has bug fixes and new features including: + +## Vulnerabilities +* [Low] In cases where a malicious agent could analyze cache timing at a very detailed level, information about the AES key used could be leaked during T/S Box lookups. One such case was shown on RISC-V hardware using the MicroWalk tool (https://github.com/microwalk-project/Microwalk). A hardened version of T/S Box lookups was added in wolfSSL to help mitigate this potential attack and is now on by default with RISC-V builds and can be enabled on other builds if desired by compiling wolfSSL with the macro WOLFSSL_AES_TOUCH_LINES. Thanks to Jan Wichelmann, Christopher Peredy, Florian Sieck, Anna Pätschke, Thomas Eisenbarth (University of Lübeck): MAMBO-V: Dynamic Side-Channel Leakage Analysis on RISC-V. Fixed in the following GitHub pull request https://github.com/wolfSSL/wolfssl/pull/6309 +* [High] In previous versions of wolfSSL if a TLS 1.3 client gets neither a PSK (pre shared key) extension nor a KSE (key share extension) when connecting to a malicious server, a default predictable buffer gets used for the IKM value when generating the session master secret. Using a potentially known IKM value when generating the session master secret key compromises the key generated, allowing an eavesdropper to reconstruct it and potentially allowing surreptitious access to or meddling with message contents in the session. This issue does not affect client validation of connected servers, nor expose private key information, but could result in an insecure TLS 1.3 session when not controlling both sides of the connection. We recommend that TLS 1.3 client side users update the version of wolfSSL used. Thanks to Johannes from Sectra Communications and Linköping University for the report. Fixed in the following GitHub pull request https://github.com/wolfSSL/wolfssl/pull/6412 + +## New Feature Additions + +### New Ports and Expansions +* Add support for STM32H5 +* Add support for Renesas TSIP v1.17 +* Add Renesas SCE RSA crypto-only support +* STARCORE DSP port and example builds added +* Add the function wc_PKCS7_SetDefaultSignedAttribs for setting PKCS7 signed attributes to use with PKCS7 bundle creation +* NXP IMX6Q CAAM port with QNX and performance optimizations for AES-CTR + +### New Build Options +* ASN.1 print utility to decode ASN.1 syntax and print out human readable text --enable-asn-print. Utility app is located in the directory ./examples/asn1/ +* Add introspection for math build, wc_GetMathInfo() to get information about the math library compiled into the linked wolfSSL library +* Implement TLS recommendations from RFC 9325 for hardening TLS/DTLS security. Enabled with the autoconf flag --enable-harden-tls. +* Add option to support disabling thread local storage, --disable-threadlocal +* Added wc_DsaSign_ex() and wc_DsaVerify_ex() for handling alternative digest algorithms with DSA Sign/Verify +* Implement atomic operations interface. Macros auto-detect if atomic operations are expected to be available, can be turned off with the macro WOLFSSL_NO_ATOMICS +* Added support for DTLS 1.3 Authentication and Integrity-Only Cipher Suites +* Expand crypto callback to have a device ID find callback function with wc_CryptoCb_SetDeviceFindCb. Enabled with the macro WOLF_CRYPTO_CB_FIND + +## Enhancements and Optimizations + +### Optimizations +* Increased performance with ChaCha20 C implementation and general XOR operations +* Added integer type to the ASN.1 sequencing with ASN.1 Integer sequence +* With wolfSSL_get_x509_next_altname reset alt name list to head once cycled through if compiling with the macro WOLFSSL_MULTICIRCULATE_ALTNAMELIST +* Additional key validity sanity checks on input to wolfSSL_EC_KEY_set_private_key +* adds support for TLSv1.3 stateful session tickets when using SSL_OP_NO_TICKET + +### Memory Optimizations +* Improvements to stack usage and management with SP int math library +* Optimization to TLS 1.3 server to remove caching messages for Ed25519/Ed448 +* Added a HAVE_CURL macro build for building a subset of the wolfSSL library when linking with cURL +* Memory usage improvement with reducing the size of alignment needed with AES +* Reduce run time memory used with ECC operations and ALT_ECC_SIZE +* Fixes and improvements for building edge cases such as crypto callback without hash-drbg with low footprint options +* Support HAVE_SESSION_TICKET build option without depending on realloc + +### Documentation +* Instructions for GPDMA on STM32 configuration added +* Add in instructions for compiling with zephyr on STM32 +* Documentation fixup for wolfSSL_get_chain_cert() +* Fix the file pointed to in the TI RTOS documentation that we maintain +* Documentation for wolfSSL_CertManagerFreeCRL +* Updates made to AES and Chacha documentation +* Update Japanese comments for Ed25519, AES, and other miscellaneous items + +### Tests +* Add in an option for easily testing malloc failures when building with WOLFSSL_MEM_FAIL_COUNT macro +* Updated in process for using Expect vs Assert to facilitate more malloc failure tests +* Enhance wolfCrypt test for builds that do not have ECC SECP curves enabled +* ESP32 platform-specific VisualGDB test & benchmark projects +* Update to dependencies in docker container file used for tests +* Fix up for base 10 output with bundled benchmark application + +### Port Updates +* Zephyr port update, compile time warning fixes, misc. fixes when used with TLS and update of includes +* Update RIOT-OS to not compile out use of writev by default +* Update Micrium port to enable use of STM32_RNG +* Micrium updates for XMEMOVE and XSTRTOK use +* Various Espressif HW crypto, SHA2, AES, MP updates +* Added in ASIO build option with CMake builds + +### General Enhancements +* Global codebase cleanup for C89 compliance and wolfCrypt -Wconversion hygiene +* PKCS#11 enhancement adding a callback for RSA key size when using a hardware key, by default 2048 bit key is used +* Allow for unknown OIDs in extensions in wolfSSL_X509_set_ext() +* Allow user to override XSTAT by defining the macro XSTAT when compiling +* Support UPN and SID with x509 certificate extensions and custom OID build +* Write next IV in wolfSSL_DES_ede3_cbc_encrypt for better handling of inline encryption +* Adding NO_ASN_TIME_CHECK build option for compiling out certificate before/after checks +* Improve different peer recvfrom handling and error reporting with ipv4 vs ipv6 + +## Fixes +* Fix for STM32 ECC sign and verify out of bounds buffer write when the hash length passed in is larger than the key size. Thanks to Maximilian for the report. +* Fix to skip Async_DevCtxInit when using init rsa/ecc label/id api's +* Revert WOLFSSL_NO_ASN_STRICT macro guard around alternate names directory list +* In async mode, don't retry decrypting if a valid error is encountered on a packet parse attempt +* Add additional sanity check on PKCS7 index value in wc_PKCS7_DecryptKekri +* Fix for padding when using an AuthEnvelope PKCS7 type with GCM/CCM stream ciphers +* Fix siphash assembly so that no register is left behind +* Fix to not send a TLS 1.3 session ID resume response when resuming and downgrading to a protocol less than TLS 1.3 +* Fix overwriting serialNumber by favouriteDrink when generating a certificate using Cert struct +* Fix for the default realloc used with EspressIf builds +* Track SetDigest usage to avoid invalid free under error conditions +* DTLS v1.3 fix for epoch 0 check on plaintext message +* Fix for session ticket memory leak in wolfSSL_Cleanup +* Fixes for propagating SendAlert errors when the peer disconnects +* Replace XMEMCPY with XMEMMOVE to fix valgrind-3.15.0 reports "Source and destination overlap in memcpy" when using --enable-aesgcm-stream +* Fix for potential out-of-bounds write edge case in fp_mod_2d with --enable-fastmath math library +* Fix getting ECC key size in stm32_ecc_sign_hash_ex +* Fix for case where wc_PeekErrorNodeLineData was not unlocking error queue on error +* Fix for async ECC shared secret state +* Fix for better error checking with sp_gcd with SP int math library +* Fix memory leak in TLSX_KeyShare_Setup when handling an error case +* Fix for double free edge case in InitOCSPRequest when handling a memory allocation failure +* X509 NAME Entry fix for leaking memory on error case +* Fix wolfssl_asn1_time_to_tm setting unexpected fields in tm struct +* Fix for FIPS ECC integrity check with crypto callback set +* BN_to_ASN1_INTEGER fix for handling leading zero byte padding when needed +* Fix a typo in PP macro and add a ceiling to guard against implementation bugs +* DTLS 1.3 fix for using the correct label when deriving the resumption key +* OCSP fix for GetDateInfo edge case with non ASN template builds +* Allow a user set certificate callback function to override the skipAddCA flag when parsing a certificate +* SP int: sp_radix_size when radix 10 fix temp size for handling edge case +* Fixes and improvements for handling failures with memory allocations +* Fix for DecodeECC_DSA_Sig to handle r and s being initialized +* Fix for wc_ecc_is_point to ensure that the x and y are in range [0, p-1] and z is one (affine ordinates) + +### Build Fixes +* Fix for building on Windows with CMake and using USER_SETTINGS and fix for options.h creation with CMake when using USER_SETTINGS +* CMake fixes and improvements for use with mingw32 +* Fix for building with wpas and x509 small options +* Check if colrm is available for options.h creation when using autoconf +* Clean up NO_BIG_INT build, removing WOLFSSL_SP_MATH macro and heapmath compile +* Fix PKCS#7 build with NO_PKCS7_STREAM +* Fix compilation error in CC-RX and remove unnecessary public key import +* SP Build fixes for ARM assembly with ARMv6 clz and ARM thumb debug build +* For to not advertise support for RSA in TLS extensions when compiled with NO_RSA + # wolfSSL Release 5.6.0 (Mar 24, 2023) Release 5.6.0 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. diff --git a/IDE/WIN10/wolfssl-fips.rc b/IDE/WIN10/wolfssl-fips.rc index 20e7e68f290..39640bbf99e 100644 --- a/IDE/WIN10/wolfssl-fips.rc +++ b/IDE/WIN10/wolfssl-fips.rc @@ -51,8 +51,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 5,6,0,0 - PRODUCTVERSION 5,6,0,0 + FILEVERSION 5,6,2,0 + PRODUCTVERSION 5,6,2,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -69,12 +69,12 @@ BEGIN BEGIN VALUE "CompanyName", "wolfSSL Inc." VALUE "FileDescription", "The wolfSSL FIPS embedded SSL library is a lightweight, portable, C-language-based SSL/TLS library targeted at IoT, embedded, and RTOS environments primarily because of its size, speed, and feature set." - VALUE "FileVersion", "5.6.0.0" + VALUE "FileVersion", "5.6.2.0" VALUE "InternalName", "wolfssl-fips" VALUE "LegalCopyright", "Copyright (C) 2022" VALUE "OriginalFilename", "wolfssl-fips.dll" VALUE "ProductName", "wolfSSL FIPS" - VALUE "ProductVersion", "5.6.0.0" + VALUE "ProductVersion", "5.6.2.0" END END BLOCK "VarFileInfo" diff --git a/README b/README index 3fee55a4f70..0e89dd08842 100644 --- a/README +++ b/README @@ -70,189 +70,138 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.6.0 (Mar 24, 2023) +# wolfSSL Release 5.6.2 (Jun 09, 2023) -Release 5.6.0 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. +Release 5.6.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance NOTE: * --enable-heapmath is being deprecated and will be removed by 2024 - * This release makes ASN Template the default with ./configure, the previous ASN parsing can be built with --enable-asn=original -Release 5.6.0 of wolfSSL embedded TLS has bug fixes and new features including: +Release 5.6.2 of wolfSSL embedded TLS has bug fixes and new features including: -## New Feature Additions - -* ASN template is now the default ASN parsing implementation when compiling with configure -* Added in support for TLS v1.3 Encrypted Client Hello (ECH) and HPKE (Hybrid Public Key Encryption) -* DTLS 1.3 stateless server ClientHello parsing support added - -### Ports -* Add RX64/RX71 SHA hardware support -* Port to RT1170 and expand NXP CAAM driver support -* Add NuttX integration files for ease of use -* Updated Stunnel support for version 5.67 -Compatibility Layer -* Add in support for AES-CCM with EVP -* BN compatibility API refactoring and separate API created -* Expanding public key type cipher suite list strings support +## Vulnerabilities +* [Low] In cases where a malicious agent could analyze cache timing at a very detailed level, information about the AES key used could be leaked during T/S Box lookups. One such case was shown on RISC-V hardware using the MicroWalk tool (https://github.com/microwalk-project/Microwalk). A hardened version of T/S Box lookups was added in wolfSSL to help mitigate this potential attack and is now on by default with RISC-V builds and can be enabled on other builds if desired by compiling wolfSSL with the macro WOLFSSL_AES_TOUCH_LINES. Thanks to Jan Wichelmann, Christopher Peredy, Florian Sieck, Anna Pätschke, Thomas Eisenbarth (University of Lübeck): MAMBO-V: Dynamic Side-Channel Leakage Analysis on RISC-V. Fixed in the following GitHub pull request https://github.com/wolfSSL/wolfssl/pull/6309 +* [High] In previous versions of wolfSSL if a TLS 1.3 client gets neither a PSK (pre shared key) extension nor a KSE (key share extension) when connecting to a malicious server, a default predictable buffer gets used for the IKM value when generating the session master secret. Using a potentially known IKM value when generating the session master secret key compromises the key generated, allowing an eavesdropper to reconstruct it and potentially allowing surreptitious access to or meddling with message contents in the session. This issue does not affect client validation of connected servers, nor expose private key information, but could result in an insecure TLS 1.3 session when not controlling both sides of the connection. We recommend that TLS 1.3 client side users update the version of wolfSSL used. Thanks to Johannes from Sectra Communications and Linköping University for the report. Fixed in the following GitHub pull request https://github.com/wolfSSL/wolfssl/pull/6412 -### Misc. -* Support pthread_rwlock and add enable option -* Add wolfSSL_CertManagerLoadCABuffer_ex() that takes a user certificate chain flag and additional verify flag options -* Docker build additions for wolfSSL library and wolfCLU application -* Add favorite drink pilot attribute type to get it from the encoding -* Added in support for indefinite length BER parsing with PKCS12 -* Add dynamic session cache which allocates sessions from the heap with macro SESSION_CACHE_DYNAMIC_MEM +## New Feature Additions +### New Ports and Expansions +* Add support for STM32H5 +* Add support for Renesas TSIP v1.17 +* Add Renesas SCE RSA crypto-only support +* STARCORE DSP port and example builds added +* Add the function wc_PKCS7_SetDefaultSignedAttribs for setting PKCS7 signed attributes to use with PKCS7 bundle creation +* NXP IMX6Q CAAM port with QNX and performance optimizations for AES-CTR + +### New Build Options +* ASN.1 print utility to decode ASN.1 syntax and print out human readable text --enable-asn-print. Utility app is located in the directory ./examples/asn1/ +* Add introspection for math build, wc_GetMathInfo() to get information about the math library compiled into the linked wolfSSL library +* Implement TLS recommendations from RFC 9325 for hardening TLS/DTLS security. Enabled with the autoconf flag --enable-harden-tls. +* Add option to support disabling thread local storage, --disable-threadlocal +* Added wc_DsaSign_ex() and wc_DsaVerify_ex() for handling alternative digest algorithms with DSA Sign/Verify +* Implement atomic operations interface. Macros auto-detect if atomic operations are expected to be available, can be turned off with the macro WOLFSSL_NO_ATOMICS +* Added support for DTLS 1.3 Authentication and Integrity-Only Cipher Suites +* Expand crypto callback to have a device ID find callback function with wc_CryptoCb_SetDeviceFindCb. Enabled with the macro WOLF_CRYPTO_CB_FIND + +## Enhancements and Optimizations -## Improvements / Optimizations +### Optimizations +* Increased performance with ChaCha20 C implementation and general XOR operations +* Added integer type to the ASN.1 sequencing with ASN.1 Integer sequence +* With wolfSSL_get_x509_next_altname reset alt name list to head once cycled through if compiling with the macro WOLFSSL_MULTICIRCULATE_ALTNAMELIST +* Additional key validity sanity checks on input to wolfSSL_EC_KEY_set_private_key +* adds support for TLSv1.3 stateful session tickets when using SSL_OP_NO_TICKET + +### Memory Optimizations +* Improvements to stack usage and management with SP int math library +* Optimization to TLS 1.3 server to remove caching messages for Ed25519/Ed448 +* Added a HAVE_CURL macro build for building a subset of the wolfSSL library when linking with cURL +* Memory usage improvement with reducing the size of alignment needed with AES +* Reduce run time memory used with ECC operations and ALT_ECC_SIZE +* Fixes and improvements for building edge cases such as crypto callback without hash-drbg with low footprint options +* Support HAVE_SESSION_TICKET build option without depending on realloc + +### Documentation +* Instructions for GPDMA on STM32 configuration added +* Add in instructions for compiling with zephyr on STM32 +* Documentation fixup for wolfSSL_get_chain_cert() +* Fix the file pointed to in the TI RTOS documentation that we maintain +* Documentation for wolfSSL_CertManagerFreeCRL +* Updates made to AES and Chacha documentation +* Update Japanese comments for Ed25519, AES, and other miscellaneous items ### Tests -* Additional CI (continuous integration) testing and leveraging of GitHub workflows -* Add CI testing for wpa_supplicant, OpenWrt and OpenVPN using GitHub workflows -* Add compilation of Espressif to GitHub workflows tests -* Refactoring and improving error results with wolfCrypt unit test application -* Minor warning fixes from Coverity static analysis scan -* Add new SHA-512/224 and SHA-512/256 tests -* Used codespell and fixed some minor typos - -### Ports -* Improve TLS1.2 client authentication to use TSIP -* Updated Kyber macro to be WOLFSSL_HAVE_KYBER and made changes that make Kyber work on STM32 -* AES-GCM Windows assembly additions -* CRLF line endings, trailing spaces for C# Wrapper Projects -Compatibility Layer -* Update `PubKey` and `Key` PEM-to-DER APIs to support return of needed DER size -* Allow reading ENC EC PRIVATE KEY as well via wolfSSL_PEM_read_bio_ECPrivateKey -* Improve wolfSSL_EC_POINT_cmp to handle Jacobian ordinates -* Fix issue with BIO_reset() and add BIO_FLAGS_MEM_RDONLY flag support for read only BIOs - -### SP -* In SP math library rework mod 3 and use count leading zero instruction -* Fix with SP ECC sign to reject the random k generated when r is 0 -* With SP math add better detection of when add won't work and double is needed with point_add_qz1 internal function -* With SP int fail when buffer writing to is too small for number rather than discarding the extra values - -### Builds -* Define WOLFSSL_SP_SMALL_STACK if wolfSSL is build with --enable-smallstack -* Fix CMake to exclude libm when DH is not enabled -* Allow building of SAKKE as external non-FIPS algorithm with wolfmikey product -* Add option to add library suffix, --with-libsuffix -* ASN template compile option WOLFSSL_ASN_INT_LEAD_0_ANY to allow leading zeros -* Add user_settings.h template for wolfTPM to examples/configs/user_settings_wolftpm.h -* Purge the AES variant of Dilithium -* Expand WOLFSSL_NO_ASN_STRICT to allow parsing of explicit ECC public key -* Remove relocatable text in ARMv7a AES assembly for use with FIPS builds -* Expand checking for hardware that supports ARMv7a neon with autotools configure -* Sanity check on allocation fails with DSA and FP_ECC build when zeroizing internal buffer -* Additional TLS alerts sent when compiling with WOLFSSL_EXTRA_ALERTS macro defined - -### Benchmarking -* Update wolfCrypt benchmark Windows build files to support x64 Platform -* Add SHA512/224 and SHA512/256 benchmarks, fixed CVS macro and display sizes -* Separate AES-GCM streaming runs when benchmarked -* No longer call external implementation of Kyber from benchmark -* Fix for benchmarking shake with custom block size -* Fixes for benchmark help `-alg` list and block format -Documentation/Examples -* Document use of wc_AesFree() and update documentation of Ed25519 with Doxygen -* Move the wolfSSL Configuration section higher in QUIC.md -* Add Japanese Doxygen documentation for cmac.h, quic.h and remove incomplete Japanese doxygen in asn_public.h -* Espressif examples run with local wolfSSL now with no additional setup needed -* Added a fix for StartTLS use In the example client -* Add a base-line user_settings.h for use with FIPS 140-3 in XCode example app - -### Optimizations -* AES-NI usage added for AES modes ECB/CTR/XTS - -### Misc -* Update AES-GCM stream decryption to allow long IVs -* Internal refactor to use wolfSSL_Ref functions when incrementing or decrementing the structures reference count and fixes for static analysis reports -* Cleanup function logging making adjustments to the debug log print outs -* Remove realloc dependency in DtlsMsgCombineFragBuckets function -* Refactor to use WOLFSSL_CTX’s cipher suite list when possible -* Update internal padding of 0’s with DSA sign and additional tests with mp_to_unsigned_bin_len function -* With DTLS SRTP use wolfSSL_export_keying_material instead of wc_PRF_TLS -* Updated macro naming from HAVE_KYBER to be WOLFSSL_HAVE_KYBER -* Update AES XTS encrypt to handle in-place encryption properly -* With TLS 1.3 add option to require only PSK with DHE +* Add in an option for easily testing malloc failures when building with WOLFSSL_MEM_FAIL_COUNT macro +* Updated in process for using Expect vs Assert to facilitate more malloc failure tests +* Enhance wolfCrypt test for builds that do not have ECC SECP curves enabled +* ESP32 platform-specific VisualGDB test & benchmark projects +* Update to dependencies in docker container file used for tests +* Fix up for base 10 output with bundled benchmark application + +### Port Updates +* Zephyr port update, compile time warning fixes, misc. fixes when used with TLS and update of includes +* Update RIOT-OS to not compile out use of writev by default +* Update Micrium port to enable use of STM32_RNG +* Micrium updates for XMEMOVE and XSTRTOK use +* Various Espressif HW crypto, SHA2, AES, MP updates +* Added in ASIO build option with CMake builds + +### General Enhancements +* Global codebase cleanup for C89 compliance and wolfCrypt -Wconversion hygiene +* PKCS#11 enhancement adding a callback for RSA key size when using a hardware key, by default 2048 bit key is used +* Allow for unknown OIDs in extensions in wolfSSL_X509_set_ext() +* Allow user to override XSTAT by defining the macro XSTAT when compiling +* Support UPN and SID with x509 certificate extensions and custom OID build +* Write next IV in wolfSSL_DES_ede3_cbc_encrypt for better handling of inline encryption +* Adding NO_ASN_TIME_CHECK build option for compiling out certificate before/after checks +* Improve different peer recvfrom handling and error reporting with ipv4 vs ipv6 ## Fixes - -### Ports -* Fix for AES use with CAAM on imx8qxp with SECO builds -* Fix for PIC32 crypto HW and unused `TLSX_SetResponse` -* Fix warning if ltime is unsigned seen with QNX build -* Updates and fix for Zephyr project support -* Include sys/time.h for WOLFSSL_RIOT_OS -* Move X509_V errors from enums to defines for use with HAProxy CLI -* Fix IAR compiler warnings resolved -* Fix for STM32 Hash peripherals (like on F437) with FIFO depth = 1 -* ESP32 fix for SHA384 init with hardware acceleration - -### Builds -* Add WOLFSSL_IP_ALT_NAME macro define to --enable-curl -* Fixes for building with C++17 and avoiding clashing with byte naming -* Fixes SP math all build issue with small-stack and no hardening -* Fix for building with ASN template with `NO_ASN_TIME` defined -* Fix building FIPSv2 with WOLFSSL_ECDSA_SET_K defined -* Don't allow aesgcm-stream option with kcapi -* Fix DTLS test case for when able to read peers close notify alert on FreeBSD systems -* Fix for "expression must have a constant value" in tls13.c with Green Hills compiler -* Fixes for building KCAPI with opensslextra enabled -* Fix warnings of shadows min and subscript with i486-netbsd-gcc compiler -* Fix issue with async and `WOLFSSL_CHECK_ALERT_ON_ERR` -* Fix for PKCS7 with asynchronous crypto enabled - -### Math Library -* SP Aarch64 fix for conditional changed in asm needing "cc" and fix for ECC P256 mont reduce -* In SP builds add sanity check with DH exp. to check the output length for minimum size -* In SP math fix scalar length check with EC scalar multiply -* With SP int fix handling negative character properly with read radix -* Add error checks before setting variable err in SP int with the function sp_invmod_mont_ct -* Fix to add sanity check for malloc of zero size in fastmath builds -* In fastmath fix a possible overflow in fp_to_unsigned_bin_len length check -* Heapmath fast mod. reduce fix - -### Compatibility Layer -* Fixes for encoding/decoding ecc public keys and ensure i2d public key functions do not include any private key information -* Fix for EVP_EncryptUpdate to update outl on empty input -* Fix SE050 RSA public key loading and RSA/ECC SE050 TLS Compatibility -* Rework EC API and validate point after setting it -* Fix for X509 RSA PSS with compatibility layer functions -* Fix size of structures used with SHA operations when built with opensslextra for Espressif hardware accelerated hashing -* Added sanity check on key length with wolfSSL_CMAC_Init function -* Fix for return value type conversion of bad mutex error in logging function -* Fix NID conflict NID_givenName and NID_md5WithRSAEncryption -* Fix unguarded XFPRINTF calls with opensslextra build -* Fix wolfSSL_ASN1_INTEGER_to_BN for negative values -* Fix for potential ASN1_STRING leak in wolfSSL_X509_NAME_ENTRY_create_by_txt and wolfSSL_X509_NAME_ENTRY_create_by_NID when memory allocation fails - -### Misc. -* Add sanity check to prevent an out of bounds read with OCSP response decoding -* Sanity check to not allow 0 length with bit string and integer when parsing ASN1 syntax -* Adjust RNG sanity checks and remove error prone first byte comparison -* With PKCS7 add a fix for GetAsnTimeString() to correctly increment internal data pointer -* PKCS7 addition of sequence around algo parameters with authenvelop -* DSA fixes for clearing mp_int before re-reading data and avoid mp_clear without first calling mp_init -* Fix for SRTP setting bitfield when it is encoded for the TLS extension -* Fix for handling small http headers when doing CRL verification -* Fix for ECCSI hash function to validate the output size and curve size -* Fix for value of givenName and name being reversed with CSR generation -* Fix for error type returned (OCSP_CERT_UNKNOWN) with OCSP verification -* Fix for a potential memory leak with ProcessCSR when handling OCSP responses -* Fix for VERIFY_SKIP_DATE flag not ignoring date errors when set -* Fix for zlib decompression buffer issue with PKCS7 -* Fix for DTLS message pool send size used and DTLS server saving of the handshake sequence -* Fix to propagate WOLFSSL_TICKET_RET_CREATE error return value from DoDecryptTicket() -* Fix for handling long session IDs with TLS 1.3 session tickets -* Fix for AES-GCM streaming when caching an IV -* Fix for test case with older selftest that returns bad padding instead of salt len error -* Add fix for siphash cache and added in additional tests -* Fix potential out of bounds memset to 0 in error case with session export function used with --enable-sessionexport builds -* Fix possible NULL dereference in TLSX_CSR_Parse with TLS 1.3 -* Fix for sanity check on RSA pad length with no padding using the build macro WC_RSA_NO_PADDING - +* Fix for STM32 ECC sign and verify out of bounds buffer write when the hash length passed in is larger than the key size. Thanks to Maximilian for the report. +* Fix to skip Async_DevCtxInit when using init rsa/ecc label/id api's +* Revert WOLFSSL_NO_ASN_STRICT macro guard around alternate names directory list +* In async mode, don't retry decrypting if a valid error is encountered on a packet parse attempt +* Add additional sanity check on PKCS7 index value in wc_PKCS7_DecryptKekri +* Fix for padding when using an AuthEnvelope PKCS7 type with GCM/CCM stream ciphers +* Fix siphash assembly so that no register is left behind +* Fix to not send a TLS 1.3 session ID resume response when resuming and downgrading to a protocol less than TLS 1.3 +* Fix overwriting serialNumber by favouriteDrink when generating a certificate using Cert struct +* Fix for the default realloc used with EspressIf builds +* Track SetDigest usage to avoid invalid free under error conditions +* DTLS v1.3 fix for epoch 0 check on plaintext message +* Fix for session ticket memory leak in wolfSSL_Cleanup +* Fixes for propagating SendAlert errors when the peer disconnects +* Replace XMEMCPY with XMEMMOVE to fix valgrind-3.15.0 reports "Source and destination overlap in memcpy" when using --enable-aesgcm-stream +* Fix for potential out-of-bounds write edge case in fp_mod_2d with --enable-fastmath math library +* Fix getting ECC key size in stm32_ecc_sign_hash_ex +* Fix for case where wc_PeekErrorNodeLineData was not unlocking error queue on error +* Fix for async ECC shared secret state +* Fix for better error checking with sp_gcd with SP int math library +* Fix memory leak in TLSX_KeyShare_Setup when handling an error case +* Fix for double free edge case in InitOCSPRequest when handling a memory allocation failure +* X509 NAME Entry fix for leaking memory on error case +* Fix wolfssl_asn1_time_to_tm setting unexpected fields in tm struct +* Fix for FIPS ECC integrity check with crypto callback set +* BN_to_ASN1_INTEGER fix for handling leading zero byte padding when needed +* Fix a typo in PP macro and add a ceiling to guard against implementation bugs +* DTLS 1.3 fix for using the correct label when deriving the resumption key +* OCSP fix for GetDateInfo edge case with non ASN template builds +* Allow a user set certificate callback function to override the skipAddCA flag when parsing a certificate +* SP int: sp_radix_size when radix 10 fix temp size for handling edge case +* Fixes and improvements for handling failures with memory allocations +* Fix for DecodeECC_DSA_Sig to handle r and s being initialized +* Fix for wc_ecc_is_point to ensure that the x and y are in range [0, p-1] and z is one (affine ordinates) + +### Build Fixes +* Fix for building on Windows with CMake and using USER_SETTINGS and fix for options.h creation with CMake when using USER_SETTINGS +* CMake fixes and improvements for use with mingw32 +* Fix for building with wpas and x509 small options +* Check if colrm is available for options.h creation when using autoconf +* Clean up NO_BIG_INT build, removing WOLFSSL_SP_MATH macro and heapmath compile +* Fix PKCS#7 build with NO_PKCS7_STREAM +* Fix compilation error in CC-RX and remove unnecessary public key import +* SP Build fixes for ARM assembly with ARMv6 clz and ARM thumb debug build +* For to not advertise support for RSA in TLS extensions when compiled with NO_RSA For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/README.md b/README.md index 394863569a6..295033d5c0e 100644 --- a/README.md +++ b/README.md @@ -79,188 +79,138 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.6.0 (Mar 24, 2023) +# wolfSSL Release 5.6.2 (Jun 09, 2023) -Release 5.6.0 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. +Release 5.6.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance NOTE: * --enable-heapmath is being deprecated and will be removed by 2024 - * This release makes ASN Template the default with ./configure, the previous ASN parsing can be built with --enable-asn=original -Release 5.6.0 of wolfSSL embedded TLS has bug fixes and new features including: +Release 5.6.2 of wolfSSL embedded TLS has bug fixes and new features including: -## New Feature Additions - -* ASN template is now the default ASN parsing implementation when compiling with configure -* Added in support for TLS v1.3 Encrypted Client Hello (ECH) and HPKE (Hybrid Public Key Encryption) -* DTLS 1.3 stateless server ClientHello parsing support added +## Vulnerabilities +* [Low] In cases where a malicious agent could analyze cache timing at a very detailed level, information about the AES key used could be leaked during T/S Box lookups. One such case was shown on RISC-V hardware using the MicroWalk tool (https://github.com/microwalk-project/Microwalk). A hardened version of T/S Box lookups was added in wolfSSL to help mitigate this potential attack and is now on by default with RISC-V builds and can be enabled on other builds if desired by compiling wolfSSL with the macro WOLFSSL_AES_TOUCH_LINES. Thanks to Jan Wichelmann, Christopher Peredy, Florian Sieck, Anna Pätschke, Thomas Eisenbarth (University of Lübeck): MAMBO-V: Dynamic Side-Channel Leakage Analysis on RISC-V. Fixed in the following GitHub pull request https://github.com/wolfSSL/wolfssl/pull/6309 +* [High] In previous versions of wolfSSL if a TLS 1.3 client gets neither a PSK (pre shared key) extension nor a KSE (key share extension) when connecting to a malicious server, a default predictable buffer gets used for the IKM value when generating the session master secret. Using a potentially known IKM value when generating the session master secret key compromises the key generated, allowing an eavesdropper to reconstruct it and potentially allowing surreptitious access to or meddling with message contents in the session. This issue does not affect client validation of connected servers, nor expose private key information, but could result in an insecure TLS 1.3 session when not controlling both sides of the connection. We recommend that TLS 1.3 client side users update the version of wolfSSL used. Thanks to Johannes from Sectra Communications and Linköping University for the report. Fixed in the following GitHub pull request https://github.com/wolfSSL/wolfssl/pull/6412 -### Ports -* Add RX64/RX71 SHA hardware support -* Port to RT1170 and expand NXP CAAM driver support -* Add NuttX integration files for ease of use -* Updated Stunnel support for version 5.67 -Compatibility Layer -* Add in support for AES-CCM with EVP -* BN compatibility API refactoring and separate API created -* Expanding public key type cipher suite list strings support - -### Misc. -* Support pthread_rwlock and add enable option -* Add wolfSSL_CertManagerLoadCABuffer_ex() that takes a user certificate chain flag and additional verify flag options -* Docker build additions for wolfSSL library and wolfCLU application -* Add favorite drink pilot attribute type to get it from the encoding -* Added in support for indefinite length BER parsing with PKCS12 -* Add dynamic session cache which allocates sessions from the heap with macro SESSION_CACHE_DYNAMIC_MEM +## New Feature Additions +### New Ports and Expansions +* Add support for STM32H5 +* Add support for Renesas TSIP v1.17 +* Add Renesas SCE RSA crypto-only support +* STARCORE DSP port and example builds added +* Add the function wc_PKCS7_SetDefaultSignedAttribs for setting PKCS7 signed attributes to use with PKCS7 bundle creation +* NXP IMX6Q CAAM port with QNX and performance optimizations for AES-CTR + +### New Build Options +* ASN.1 print utility to decode ASN.1 syntax and print out human readable text --enable-asn-print. Utility app is located in the directory ./examples/asn1/ +* Add introspection for math build, wc_GetMathInfo() to get information about the math library compiled into the linked wolfSSL library +* Implement TLS recommendations from RFC 9325 for hardening TLS/DTLS security. Enabled with the autoconf flag --enable-harden-tls. +* Add option to support disabling thread local storage, --disable-threadlocal +* Added wc_DsaSign_ex() and wc_DsaVerify_ex() for handling alternative digest algorithms with DSA Sign/Verify +* Implement atomic operations interface. Macros auto-detect if atomic operations are expected to be available, can be turned off with the macro WOLFSSL_NO_ATOMICS +* Added support for DTLS 1.3 Authentication and Integrity-Only Cipher Suites +* Expand crypto callback to have a device ID find callback function with wc_CryptoCb_SetDeviceFindCb. Enabled with the macro WOLF_CRYPTO_CB_FIND + +## Enhancements and Optimizations -## Improvements / Optimizations +### Optimizations +* Increased performance with ChaCha20 C implementation and general XOR operations +* Added integer type to the ASN.1 sequencing with ASN.1 Integer sequence +* With wolfSSL_get_x509_next_altname reset alt name list to head once cycled through if compiling with the macro WOLFSSL_MULTICIRCULATE_ALTNAMELIST +* Additional key validity sanity checks on input to wolfSSL_EC_KEY_set_private_key +* adds support for TLSv1.3 stateful session tickets when using SSL_OP_NO_TICKET + +### Memory Optimizations +* Improvements to stack usage and management with SP int math library +* Optimization to TLS 1.3 server to remove caching messages for Ed25519/Ed448 +* Added a HAVE_CURL macro build for building a subset of the wolfSSL library when linking with cURL +* Memory usage improvement with reducing the size of alignment needed with AES +* Reduce run time memory used with ECC operations and ALT_ECC_SIZE +* Fixes and improvements for building edge cases such as crypto callback without hash-drbg with low footprint options +* Support HAVE_SESSION_TICKET build option without depending on realloc + +### Documentation +* Instructions for GPDMA on STM32 configuration added +* Add in instructions for compiling with zephyr on STM32 +* Documentation fixup for wolfSSL_get_chain_cert() +* Fix the file pointed to in the TI RTOS documentation that we maintain +* Documentation for wolfSSL_CertManagerFreeCRL +* Updates made to AES and Chacha documentation +* Update Japanese comments for Ed25519, AES, and other miscellaneous items ### Tests -* Additional CI (continuous integration) testing and leveraging of GitHub workflows -* Add CI testing for wpa_supplicant, OpenWrt and OpenVPN using GitHub workflows -* Add compilation of Espressif to GitHub workflows tests -* Refactoring and improving error results with wolfCrypt unit test application -* Minor warning fixes from Coverity static analysis scan -* Add new SHA-512/224 and SHA-512/256 tests -* Used codespell and fixed some minor typos - -### Ports -* Improve TLS1.2 client authentication to use TSIP -* Updated Kyber macro to be WOLFSSL_HAVE_KYBER and made changes that make Kyber work on STM32 -* AES-GCM Windows assembly additions -* CRLF line endings, trailing spaces for C# Wrapper Projects -Compatibility Layer -* Update `PubKey` and `Key` PEM-to-DER APIs to support return of needed DER size -* Allow reading ENC EC PRIVATE KEY as well via wolfSSL_PEM_read_bio_ECPrivateKey -* Improve wolfSSL_EC_POINT_cmp to handle Jacobian ordinates -* Fix issue with BIO_reset() and add BIO_FLAGS_MEM_RDONLY flag support for read only BIOs - -### SP -* In SP math library rework mod 3 and use count leading zero instruction -* Fix with SP ECC sign to reject the random k generated when r is 0 -* With SP math add better detection of when add won't work and double is needed with point_add_qz1 internal function -* With SP int fail when buffer writing to is too small for number rather than discarding the extra values - -### Builds -* Define WOLFSSL_SP_SMALL_STACK if wolfSSL is build with --enable-smallstack -* Fix CMake to exclude libm when DH is not enabled -* Allow building of SAKKE as external non-FIPS algorithm with wolfmikey product -* Add option to add library suffix, --with-libsuffix -* ASN template compile option WOLFSSL_ASN_INT_LEAD_0_ANY to allow leading zeros -* Add user_settings.h template for wolfTPM to examples/configs/user_settings_wolftpm.h -* Purge the AES variant of Dilithium -* Expand WOLFSSL_NO_ASN_STRICT to allow parsing of explicit ECC public key -* Remove relocatable text in ARMv7a AES assembly for use with FIPS builds -* Expand checking for hardware that supports ARMv7a neon with autotools configure -* Sanity check on allocation fails with DSA and FP_ECC build when zeroizing internal buffer -* Additional TLS alerts sent when compiling with WOLFSSL_EXTRA_ALERTS macro defined - -### Benchmarking -* Update wolfCrypt benchmark Windows build files to support x64 Platform -* Add SHA512/224 and SHA512/256 benchmarks, fixed CVS macro and display sizes -* Separate AES-GCM streaming runs when benchmarked -* No longer call external implementation of Kyber from benchmark -* Fix for benchmarking shake with custom block size -* Fixes for benchmark help `-alg` list and block format -Documentation/Examples -* Document use of wc_AesFree() and update documentation of Ed25519 with Doxygen -* Move the wolfSSL Configuration section higher in QUIC.md -* Add Japanese Doxygen documentation for cmac.h, quic.h and remove incomplete Japanese doxygen in asn_public.h -* Espressif examples run with local wolfSSL now with no additional setup needed -* Added a fix for StartTLS use In the example client -* Add a base-line user_settings.h for use with FIPS 140-3 in XCode example app - -### Optimizations -* AES-NI usage added for AES modes ECB/CTR/XTS - -### Misc -* Update AES-GCM stream decryption to allow long IVs -* Internal refactor to use wolfSSL_Ref functions when incrementing or decrementing the structures reference count and fixes for static analysis reports -* Cleanup function logging making adjustments to the debug log print outs -* Remove realloc dependency in DtlsMsgCombineFragBuckets function -* Refactor to use WOLFSSL_CTX’s cipher suite list when possible -* Update internal padding of 0’s with DSA sign and additional tests with mp_to_unsigned_bin_len function -* With DTLS SRTP use wolfSSL_export_keying_material instead of wc_PRF_TLS -* Updated macro naming from HAVE_KYBER to be WOLFSSL_HAVE_KYBER -* Update AES XTS encrypt to handle in-place encryption properly -* With TLS 1.3 add option to require only PSK with DHE +* Add in an option for easily testing malloc failures when building with WOLFSSL_MEM_FAIL_COUNT macro +* Updated in process for using Expect vs Assert to facilitate more malloc failure tests +* Enhance wolfCrypt test for builds that do not have ECC SECP curves enabled +* ESP32 platform-specific VisualGDB test & benchmark projects +* Update to dependencies in docker container file used for tests +* Fix up for base 10 output with bundled benchmark application + +### Port Updates +* Zephyr port update, compile time warning fixes, misc. fixes when used with TLS and update of includes +* Update RIOT-OS to not compile out use of writev by default +* Update Micrium port to enable use of STM32_RNG +* Micrium updates for XMEMOVE and XSTRTOK use +* Various Espressif HW crypto, SHA2, AES, MP updates +* Added in ASIO build option with CMake builds + +### General Enhancements +* Global codebase cleanup for C89 compliance and wolfCrypt -Wconversion hygiene +* PKCS#11 enhancement adding a callback for RSA key size when using a hardware key, by default 2048 bit key is used +* Allow for unknown OIDs in extensions in wolfSSL_X509_set_ext() +* Allow user to override XSTAT by defining the macro XSTAT when compiling +* Support UPN and SID with x509 certificate extensions and custom OID build +* Write next IV in wolfSSL_DES_ede3_cbc_encrypt for better handling of inline encryption +* Adding NO_ASN_TIME_CHECK build option for compiling out certificate before/after checks +* Improve different peer recvfrom handling and error reporting with ipv4 vs ipv6 ## Fixes - -### Ports -* Fix for AES use with CAAM on imx8qxp with SECO builds -* Fix for PIC32 crypto HW and unused `TLSX_SetResponse` -* Fix warning if ltime is unsigned seen with QNX build -* Updates and fix for Zephyr project support -* Include sys/time.h for WOLFSSL_RIOT_OS -* Move X509_V errors from enums to defines for use with HAProxy CLI -* Fix IAR compiler warnings resolved -* Fix for STM32 Hash peripherals (like on F437) with FIFO depth = 1 -* ESP32 fix for SHA384 init with hardware acceleration - -### Builds -* Add WOLFSSL_IP_ALT_NAME macro define to --enable-curl -* Fixes for building with C++17 and avoiding clashing with byte naming -* Fixes SP math all build issue with small-stack and no hardening -* Fix for building with ASN template with `NO_ASN_TIME` defined -* Fix building FIPSv2 with WOLFSSL_ECDSA_SET_K defined -* Don't allow aesgcm-stream option with kcapi -* Fix DTLS test case for when able to read peers close notify alert on FreeBSD systems -* Fix for "expression must have a constant value" in tls13.c with Green Hills compiler -* Fixes for building KCAPI with opensslextra enabled -* Fix warnings of shadows min and subscript with i486-netbsd-gcc compiler -* Fix issue with async and `WOLFSSL_CHECK_ALERT_ON_ERR` -* Fix for PKCS7 with asynchronous crypto enabled - -### Math Library -* SP Aarch64 fix for conditional changed in asm needing "cc" and fix for ECC P256 mont reduce -* In SP builds add sanity check with DH exp. to check the output length for minimum size -* In SP math fix scalar length check with EC scalar multiply -* With SP int fix handling negative character properly with read radix -* Add error checks before setting variable err in SP int with the function sp_invmod_mont_ct -* Fix to add sanity check for malloc of zero size in fastmath builds -* In fastmath fix a possible overflow in fp_to_unsigned_bin_len length check -* Heapmath fast mod. reduce fix - -### Compatibility Layer -* Fixes for encoding/decoding ecc public keys and ensure i2d public key functions do not include any private key information -* Fix for EVP_EncryptUpdate to update outl on empty input -* Fix SE050 RSA public key loading and RSA/ECC SE050 TLS Compatibility -* Rework EC API and validate point after setting it -* Fix for X509 RSA PSS with compatibility layer functions -* Fix size of structures used with SHA operations when built with opensslextra for Espressif hardware accelerated hashing -* Added sanity check on key length with wolfSSL_CMAC_Init function -* Fix for return value type conversion of bad mutex error in logging function -* Fix NID conflict NID_givenName and NID_md5WithRSAEncryption -* Fix unguarded XFPRINTF calls with opensslextra build -* Fix wolfSSL_ASN1_INTEGER_to_BN for negative values -* Fix for potential ASN1_STRING leak in wolfSSL_X509_NAME_ENTRY_create_by_txt and wolfSSL_X509_NAME_ENTRY_create_by_NID when memory allocation fails - -### Misc. -* Add sanity check to prevent an out of bounds read with OCSP response decoding -* Sanity check to not allow 0 length with bit string and integer when parsing ASN1 syntax -* Adjust RNG sanity checks and remove error prone first byte comparison -* With PKCS7 add a fix for GetAsnTimeString() to correctly increment internal data pointer -* PKCS7 addition of sequence around algo parameters with authenvelop -* DSA fixes for clearing mp_int before re-reading data and avoid mp_clear without first calling mp_init -* Fix for SRTP setting bitfield when it is encoded for the TLS extension -* Fix for handling small http headers when doing CRL verification -* Fix for ECCSI hash function to validate the output size and curve size -* Fix for value of givenName and name being reversed with CSR generation -* Fix for error type returned (OCSP_CERT_UNKNOWN) with OCSP verification -* Fix for a potential memory leak with ProcessCSR when handling OCSP responses -* Fix for VERIFY_SKIP_DATE flag not ignoring date errors when set -* Fix for zlib decompression buffer issue with PKCS7 -* Fix for DTLS message pool send size used and DTLS server saving of the handshake sequence -* Fix to propagate WOLFSSL_TICKET_RET_CREATE error return value from DoDecryptTicket() -* Fix for handling long session IDs with TLS 1.3 session tickets -* Fix for AES-GCM streaming when caching an IV -* Fix for test case with older selftest that returns bad padding instead of salt len error -* Add fix for siphash cache and added in additional tests -* Fix potential out of bounds memset to 0 in error case with session export function used with --enable-sessionexport builds -* Fix possible NULL dereference in TLSX_CSR_Parse with TLS 1.3 -* Fix for sanity check on RSA pad length with no padding using the build macro WC_RSA_NO_PADDING +* Fix for STM32 ECC sign and verify out of bounds buffer write when the hash length passed in is larger than the key size. Thanks to Maximilian for the report. +* Fix to skip Async_DevCtxInit when using init rsa/ecc label/id api's +* Revert WOLFSSL_NO_ASN_STRICT macro guard around alternate names directory list +* In async mode, don't retry decrypting if a valid error is encountered on a packet parse attempt +* Add additional sanity check on PKCS7 index value in wc_PKCS7_DecryptKekri +* Fix for padding when using an AuthEnvelope PKCS7 type with GCM/CCM stream ciphers +* Fix siphash assembly so that no register is left behind +* Fix to not send a TLS 1.3 session ID resume response when resuming and downgrading to a protocol less than TLS 1.3 +* Fix overwriting serialNumber by favouriteDrink when generating a certificate using Cert struct +* Fix for the default realloc used with EspressIf builds +* Track SetDigest usage to avoid invalid free under error conditions +* DTLS v1.3 fix for epoch 0 check on plaintext message +* Fix for session ticket memory leak in wolfSSL_Cleanup +* Fixes for propagating SendAlert errors when the peer disconnects +* Replace XMEMCPY with XMEMMOVE to fix valgrind-3.15.0 reports "Source and destination overlap in memcpy" when using --enable-aesgcm-stream +* Fix for potential out-of-bounds write edge case in fp_mod_2d with --enable-fastmath math library +* Fix getting ECC key size in stm32_ecc_sign_hash_ex +* Fix for case where wc_PeekErrorNodeLineData was not unlocking error queue on error +* Fix for async ECC shared secret state +* Fix for better error checking with sp_gcd with SP int math library +* Fix memory leak in TLSX_KeyShare_Setup when handling an error case +* Fix for double free edge case in InitOCSPRequest when handling a memory allocation failure +* X509 NAME Entry fix for leaking memory on error case +* Fix wolfssl_asn1_time_to_tm setting unexpected fields in tm struct +* Fix for FIPS ECC integrity check with crypto callback set +* BN_to_ASN1_INTEGER fix for handling leading zero byte padding when needed +* Fix a typo in PP macro and add a ceiling to guard against implementation bugs +* DTLS 1.3 fix for using the correct label when deriving the resumption key +* OCSP fix for GetDateInfo edge case with non ASN template builds +* Allow a user set certificate callback function to override the skipAddCA flag when parsing a certificate +* SP int: sp_radix_size when radix 10 fix temp size for handling edge case +* Fixes and improvements for handling failures with memory allocations +* Fix for DecodeECC_DSA_Sig to handle r and s being initialized +* Fix for wc_ecc_is_point to ensure that the x and y are in range [0, p-1] and z is one (affine ordinates) + +### Build Fixes +* Fix for building on Windows with CMake and using USER_SETTINGS and fix for options.h creation with CMake when using USER_SETTINGS +* CMake fixes and improvements for use with mingw32 +* Fix for building with wpas and x509 small options +* Check if colrm is available for options.h creation when using autoconf +* Clean up NO_BIG_INT build, removing WOLFSSL_SP_MATH macro and heapmath compile +* Fix PKCS#7 build with NO_PKCS7_STREAM +* Fix compilation error in CC-RX and remove unnecessary public key import +* SP Build fixes for ARM assembly with ARMv6 clz and ARM thumb debug build +* For to not advertise support for RSA in TLS extensions when compiled with NO_RSA For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/configure.ac b/configure.ac index cc5be80c694..b5bcc59afda 100644 --- a/configure.ac +++ b/configure.ac @@ -7,7 +7,7 @@ # AC_COPYRIGHT([Copyright (C) 2006-2020 wolfSSL Inc.]) AC_PREREQ([2.69]) -AC_INIT([wolfssl],[5.6.0],[https://github.com/wolfssl/wolfssl/issues],[wolfssl],[https://www.wolfssl.com]) +AC_INIT([wolfssl],[5.6.2],[https://github.com/wolfssl/wolfssl/issues],[wolfssl],[https://www.wolfssl.com]) AC_CONFIG_AUX_DIR([build-aux]) # The following sets CFLAGS to empty if unset on command line. We do not @@ -47,9 +47,9 @@ AC_SUBST([WOLFSSL_CONFIG_ARGS]) # The three numbers in the libwolfssl.so.*.*.* file name. Unfortunately # these numbers don't always line up nicely with the library version. WOLFSSL_LIBRARY_VERSION_FIRST=35 -WOLFSSL_LIBRARY_VERSION_SECOND=4 +WOLFSSL_LIBRARY_VERSION_SECOND=5 WOLFSSL_LIBRARY_VERSION_THIRD=0 -WOLFSSL_LIBRARY_VERSION=39:0:4 +WOLFSSL_LIBRARY_VERSION=40:0:5 # | | | # +------+ | +---+ # | | | diff --git a/wolfssl.rc b/wolfssl.rc index 17f64dc63472fd20555a9d95b07098ab204aa6be..da2d752a287766517c969a56e1678051e9fc86a1 100644 GIT binary patch delta 41 vcmdm{woPrrBo0QS$&)z@8I3j{ Date: Fri, 9 Jun 2023 09:52:01 -0700 Subject: [PATCH 378/391] add check for stdatomic.h --- configure.ac | 2 +- wolfssl/wolfcrypt/wc_port.h | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index b5bcc59afda..7c558c05426 100644 --- a/configure.ac +++ b/configure.ac @@ -100,7 +100,7 @@ else fi -AC_CHECK_HEADERS([arpa/inet.h fcntl.h limits.h netdb.h netinet/in.h stddef.h time.h sys/ioctl.h sys/socket.h sys/time.h errno.h sys/un.h]) +AC_CHECK_HEADERS([arpa/inet.h fcntl.h limits.h netdb.h netinet/in.h stddef.h time.h sys/ioctl.h sys/socket.h sys/time.h errno.h sys/un.h stdatomic.h]) AC_CHECK_LIB([network],[socket]) AC_C_BIGENDIAN AC_C___ATOMIC diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 1737c3f63ed..3f8ee4f77ce 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -307,10 +307,12 @@ #define WOLFSSL_ATOMIC_OPS #endif #else + #ifdef HAVE_STDATOMIC_H /* Default C Implementation */ #include typedef atomic_int wolfSSL_Atomic_Int; #define WOLFSSL_ATOMIC_OPS + #endif /* HAVE_STDATOMIC_H */ #endif #elif defined(_MSC_VER) /* Use MSVC compiler intrinsics for atomic ops */ From de78436396dc68ad81d9669b34de0e1e55354624 Mon Sep 17 00:00:00 2001 From: John Safranek Date: Fri, 9 Jun 2023 11:13:44 -0700 Subject: [PATCH 379/391] Implicit Type Conversion Fix 1. Typecast the return of strlen() to int for the variable used. --- tests/api.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/api.c b/tests/api.c index 74099289bdf..1511438da8d 100644 --- a/tests/api.c +++ b/tests/api.c @@ -66573,7 +66573,7 @@ static byte* test_find_string(const char *string, { int string_size, i; - string_size = XSTRLEN(string); + string_size = (int)XSTRLEN(string); for (i = 0; i < buf_size - string_size - 1; i++) { if (XSTRCMP((char*)&buf[i], string) == 0) return &buf[i]; From 37994fe50a9a5f3f651d8a30397651ae7e756f08 Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Mon, 12 Jun 2023 23:15:08 -0500 Subject: [PATCH 380/391] wolfcrypt/src/{aes.c,blake2b.c,siphash.c}: fix W64LIT() arguments to not have improper 'U' suffix; wolfssl/wolfcrypt/types.h: add 'U' suffix to W64LIT() macro defs, and add SW64LIT() macro defs (not yet used anywhere); wolfcrypt/src/asn.c: add !WOLFSSL_ECC_CURVE_STATIC gate around DataToHexStringAlloc() to resolve -Wunused; wolfcrypt/src/ecc.c: guard against zero-valued "len" arg to wc_ecc_get_curve_id_from_oid(); wolfcrypt/src/wc_port.c: fix several argument implicit sign changes in USE_WINDOWS_API paths; wolfssl/wolfcrypt/ecc.h: remove const attribute from inline buffers in WOLFSSL_ECC_CURVE_STATIC struct ecc_set_type. --- wolfcrypt/src/aes.c | 8 ++++---- wolfcrypt/src/asn.c | 2 ++ wolfcrypt/src/blake2b.c | 12 ++++++------ wolfcrypt/src/ecc.c | 8 ++++++++ wolfcrypt/src/siphash.c | 10 +++++----- wolfcrypt/src/wc_port.c | 10 +++++----- wolfssl/wolfcrypt/ecc.h | 16 ++++++++-------- wolfssl/wolfcrypt/types.h | 20 ++++++++++++++------ 8 files changed, 52 insertions(+), 34 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 8121e2a849a..7815efa324d 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -5623,10 +5623,10 @@ static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE]) a = (z8[1] >> 56) & 0xf; /* Rotate z by 4-bits */ - n3 = z8[1] & W64LIT(0xf0f0f0f0f0f0f0f0U); - n2 = z8[1] & W64LIT(0x0f0f0f0f0f0f0f0fU); - n1 = z8[0] & W64LIT(0xf0f0f0f0f0f0f0f0U); - n0 = z8[0] & W64LIT(0x0f0f0f0f0f0f0f0fU); + n3 = z8[1] & W64LIT(0xf0f0f0f0f0f0f0f0); + n2 = z8[1] & W64LIT(0x0f0f0f0f0f0f0f0f); + n1 = z8[0] & W64LIT(0xf0f0f0f0f0f0f0f0); + n0 = z8[0] & W64LIT(0x0f0f0f0f0f0f0f0f); z8[1] = (n3 >> 4) | (n2 << 12) | (n0 >> 52); z8[0] = (n1 >> 4) | (n0 << 12); diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index e74209411e8..3e00b1338e6 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -31485,6 +31485,7 @@ static void DataToHexString(const byte* input, word32 inSz, char* out) out[i * 2] = '\0'; } +#ifndef WOLFSSL_ECC_CURVE_STATIC /* Convert data to hex string and place in allocated buffer. * * Big-endian byte array is converted to big-endian hexadecimal string. @@ -31519,6 +31520,7 @@ static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out, return ret; } +#endif /* WOLFSSL_ECC_CURVE_STATIC */ /* ASN.1 template for SpecifiedECDomain. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters diff --git a/wolfcrypt/src/blake2b.c b/wolfcrypt/src/blake2b.c index 02a8d36f51a..adc60340401 100644 --- a/wolfcrypt/src/blake2b.c +++ b/wolfcrypt/src/blake2b.c @@ -48,10 +48,10 @@ static const word64 blake2b_IV[8] = { - W64LIT(0x6a09e667f3bcc908U), W64LIT(0xbb67ae8584caa73bU), - W64LIT(0x3c6ef372fe94f82bU), W64LIT(0xa54ff53a5f1d36f1U), - W64LIT(0x510e527fade682d1U), W64LIT(0x9b05688c2b3e6c1fU), - W64LIT(0x1f83d9abfb41bd6bU), W64LIT(0x5be0cd19137e2179U) + W64LIT(0x6a09e667f3bcc908), W64LIT(0xbb67ae8584caa73b), + W64LIT(0x3c6ef372fe94f82b), W64LIT(0xa54ff53a5f1d36f1), + W64LIT(0x510e527fade682d1), W64LIT(0x9b05688c2b3e6c1f), + W64LIT(0x1f83d9abfb41bd6b), W64LIT(0x5be0cd19137e2179) }; static const byte blake2b_sigma[12][16] = @@ -73,7 +73,7 @@ static const byte blake2b_sigma[12][16] = static WC_INLINE int blake2b_set_lastnode( blake2b_state *S ) { - S->f[1] = ~W64LIT(0U); + S->f[1] = ~W64LIT(0); return 0; } @@ -82,7 +82,7 @@ static WC_INLINE int blake2b_set_lastblock( blake2b_state *S ) { if( S->last_node ) blake2b_set_lastnode( S ); - S->f[0] = ~W64LIT(0U); + S->f[0] = ~W64LIT(0); return 0; } diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 9018105cbc5..7bee4b16d63 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -4311,6 +4311,14 @@ int wc_ecc_get_curve_id_from_oid(const byte* oid, word32 len) } #endif +#if !defined(HAVE_OID_ENCODING) && !defined(HAVE_OID_DECODING) + if (len == 0) { + /* SAKKE has zero oidSz and will otherwise match with len==0. */ + WOLFSSL_MSG("zero oidSz"); + return ECC_CURVE_INVALID; + } +#endif + for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) { #if defined(HAVE_OID_ENCODING) && !defined(HAVE_OID_DECODING) decOidSz = (word32)sizeof(decOid); diff --git a/wolfcrypt/src/siphash.c b/wolfcrypt/src/siphash.c index 7e93b0b5a7d..e91848a9b77 100644 --- a/wolfcrypt/src/siphash.c +++ b/wolfcrypt/src/siphash.c @@ -165,15 +165,15 @@ int wc_InitSipHash(SipHash* sipHash, const unsigned char* key, word64 k1 = GET_U64(key + 8); /* Initialize state with key. */ - sipHash->v[0] = W64LIT(0x736f6d6570736575U); + sipHash->v[0] = W64LIT(0x736f6d6570736575); if (outSz == SIPHASH_MAC_SIZE_8) { - sipHash->v[1] = W64LIT(0x646f72616e646f6dU); + sipHash->v[1] = W64LIT(0x646f72616e646f6d); } else { - sipHash->v[1] = W64LIT(0x646f72616e646f83U); + sipHash->v[1] = W64LIT(0x646f72616e646f83); } - sipHash->v[2] = W64LIT(0x6c7967656e657261U); - sipHash->v[3] = W64LIT(0x7465646279746573U); + sipHash->v[2] = W64LIT(0x6c7967656e657261); + sipHash->v[3] = W64LIT(0x7465646279746573); sipHash->v[0] ^= k0; sipHash->v[1] ^= k1; diff --git a/wolfcrypt/src/wc_port.c b/wolfcrypt/src/wc_port.c index 723abe2f769..b6b8c1fde29 100644 --- a/wolfcrypt/src/wc_port.c +++ b/wolfcrypt/src/wc_port.c @@ -615,7 +615,7 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) return BAD_PATH_ERROR; XSTRNCPY(ctx->name, path, MAX_FILENAME_SZ - 3); - XSTRNCPY(ctx->name + pathLen, "\\*", MAX_FILENAME_SZ - pathLen); + XSTRNCPY(ctx->name + pathLen, "\\*", (size_t)(MAX_FILENAME_SZ - pathLen)); ctx->hFind = FindFirstFileA(ctx->name, &ctx->FindFileData); if (ctx->hFind == INVALID_HANDLE_VALUE) { @@ -630,11 +630,11 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) if (pathLen + dnameLen + 2 > MAX_FILENAME_SZ) { return BAD_PATH_ERROR; } - XSTRNCPY(ctx->name, path, pathLen + 1); + XSTRNCPY(ctx->name, path, (size_t)pathLen + 1); ctx->name[pathLen] = '\\'; XSTRNCPY(ctx->name + pathLen + 1, ctx->FindFileData.cFileName, - MAX_FILENAME_SZ - pathLen - 1); + (size_t)(MAX_FILENAME_SZ - pathLen - 1)); if (name) *name = ctx->name; return 0; @@ -783,11 +783,11 @@ int wc_ReadDirNext(ReadDirCtx* ctx, const char* path, char** name) if (pathLen + dnameLen + 2 > MAX_FILENAME_SZ) { return BAD_PATH_ERROR; } - XSTRNCPY(ctx->name, path, pathLen + 1); + XSTRNCPY(ctx->name, path, (size_t)pathLen + 1); ctx->name[pathLen] = '\\'; XSTRNCPY(ctx->name + pathLen + 1, ctx->FindFileData.cFileName, - MAX_FILENAME_SZ - pathLen - 1); + (size_t)(MAX_FILENAME_SZ - pathLen - 1)); if (name) *name = ctx->name; return 0; diff --git a/wolfssl/wolfcrypt/ecc.h b/wolfssl/wolfcrypt/ecc.h index 09f5492bec4..1709b597aaf 100644 --- a/wolfssl/wolfcrypt/ecc.h +++ b/wolfssl/wolfcrypt/ecc.h @@ -306,14 +306,14 @@ typedef struct ecc_set_type { typedef struct ecc_set_type { int size; /* The size of the curve in octets */ int id; /* id of this curve */ - const char name[MAX_ECC_NAME]; /* name of this curve */ - const char prime[MAX_ECC_STRING]; /* prime that defines the field, curve is in (hex) */ - const char Af[MAX_ECC_STRING]; /* fields A param (hex) */ - const char Bf[MAX_ECC_STRING]; /* fields B param (hex) */ - const char order[MAX_ECC_STRING]; /* order of the curve (hex) */ - const char Gx[MAX_ECC_STRING]; /* x coordinate of the base point on curve (hex) */ - const char Gy[MAX_ECC_STRING]; /* y coordinate of the base point on curve (hex) */ - const ecc_oid_t oid[10]; + char name[MAX_ECC_NAME]; /* name of this curve */ + char prime[MAX_ECC_STRING]; /* prime that defines the field, curve is in (hex) */ + char Af[MAX_ECC_STRING]; /* fields A param (hex) */ + char Bf[MAX_ECC_STRING]; /* fields B param (hex) */ + char order[MAX_ECC_STRING]; /* order of the curve (hex) */ + char Gx[MAX_ECC_STRING]; /* x coordinate of the base point on curve (hex) */ + char Gy[MAX_ECC_STRING]; /* y coordinate of the base point on curve (hex) */ + ecc_oid_t oid[10]; word32 oidSz; word32 oidSum; /* sum of encoded OID bytes */ int cofactor; diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h index 87c0d152bc3..05943d0afb7 100644 --- a/wolfssl/wolfcrypt/types.h +++ b/wolfssl/wolfcrypt/types.h @@ -177,37 +177,45 @@ decouple library dependencies with standard string, memory and so on. #if defined(_MSC_VER) || defined(__BCPLUSPLUS__) #define WORD64_AVAILABLE #define W64LIT(x) x##ui64 + #define SW64LIT(x) x##i64 typedef __int64 sword64; typedef unsigned __int64 word64; #elif defined(__EMSCRIPTEN__) #define WORD64_AVAILABLE #define W64LIT(x) x##ull + #define SW64LIT(x) x##ll typedef long long sword64; typedef unsigned long long word64; #elif defined(SIZEOF_LONG) && SIZEOF_LONG == 8 #define WORD64_AVAILABLE #ifdef WOLF_C89 - #define W64LIT(x) x##L + #define W64LIT(x) x##UL + #define SW64LIT(x) x##L #else - #define W64LIT(x) x##LL + #define W64LIT(x) x##ULL + #define SW64LIT(x) x##LL #endif typedef long sword64; typedef unsigned long word64; #elif defined(SIZEOF_LONG_LONG) && SIZEOF_LONG_LONG == 8 #define WORD64_AVAILABLE #ifdef WOLF_C89 - #define W64LIT(x) x##L + #define W64LIT(x) x##UL + #define SW64LIT(x) x##L #else - #define W64LIT(x) x##LL + #define W64LIT(x) x##ULL + #define SW64LIT(x) x##LL #endif typedef long long sword64; typedef unsigned long long word64; #elif defined(__SIZEOF_LONG_LONG__) && __SIZEOF_LONG_LONG__ == 8 #define WORD64_AVAILABLE #ifdef WOLF_C89 - #define W64LIT(x) x##L + #define W64LIT(x) x##UL + #define SW64LIT(x) x##L #else - #define W64LIT(x) x##LL + #define W64LIT(x) x##ULL + #define SW64LIT(x) x##LL #endif typedef long long sword64; typedef unsigned long long word64; From a320db99f8a947dcdb4cb4d543d783b6cdc32b3c Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 13 Jun 2023 14:47:06 -0600 Subject: [PATCH 381/391] prepare for 5.6.3 --- CMakeLists.txt | 4 ++-- ChangeLog.md | 7 +++++++ IDE/WIN10/wolfssl-fips.rc | 8 ++++---- README | 9 +++++++++ README.md | 9 +++++++++ configure.ac | 6 +++--- wolfssl.rc | Bin 4918 -> 4918 bytes wolfssl/version.h | 4 ++-- 8 files changed, 36 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 851e8f74bd0..6605c700f16 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,13 +28,13 @@ if("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}") You must delete them, or cmake will refuse to work.") endif() -project(wolfssl VERSION 5.6.2 LANGUAGES C ASM) +project(wolfssl VERSION 5.6.3 LANGUAGES C ASM) # shared library versioning # increment if interfaces have been added, removed or changed set(LIBTOOL_CURRENT 40) # increment if source code has changed set to zero if current is incremented -set(LIBTOOL_REVISION 0) +set(LIBTOOL_REVISION 1) # increment if interfaces have been added set to zero if interfaces have been # removed or changed set(LIBTOOL_AGE 5) diff --git a/ChangeLog.md b/ChangeLog.md index bc5ca406ecf..4f9355522d4 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,10 @@ +# wolfSSL Release 5.6.3 (Jun 13, 2023) + +Release 5.6.3 of wolfSSL embedded TLS has 2 bug fixes +* Fix for setting the atomic macro options introduced in release 5.6.2. This issue affects GNU gcc autoconf builds. The fix resolves a potential mismatch of the generated macros defined in options.h file and the macros used when the wolfSSL library is compiled. In version 5.6.2 this mismatch could result in unstable runtime behavior. +* Fix for invalid suffix error with Windows build using the macro GCM_TABLE_4BIT. + + # wolfSSL Release 5.6.2 (Jun 09, 2023) Release 5.6.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. diff --git a/IDE/WIN10/wolfssl-fips.rc b/IDE/WIN10/wolfssl-fips.rc index 39640bbf99e..99d539cd62e 100644 --- a/IDE/WIN10/wolfssl-fips.rc +++ b/IDE/WIN10/wolfssl-fips.rc @@ -51,8 +51,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 5,6,2,0 - PRODUCTVERSION 5,6,2,0 + FILEVERSION 5,6,3,0 + PRODUCTVERSION 5,6,3,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -69,12 +69,12 @@ BEGIN BEGIN VALUE "CompanyName", "wolfSSL Inc." VALUE "FileDescription", "The wolfSSL FIPS embedded SSL library is a lightweight, portable, C-language-based SSL/TLS library targeted at IoT, embedded, and RTOS environments primarily because of its size, speed, and feature set." - VALUE "FileVersion", "5.6.2.0" + VALUE "FileVersion", "5.6.3.0" VALUE "InternalName", "wolfssl-fips" VALUE "LegalCopyright", "Copyright (C) 2022" VALUE "OriginalFilename", "wolfssl-fips.dll" VALUE "ProductName", "wolfSSL FIPS" - VALUE "ProductVersion", "5.6.2.0" + VALUE "ProductVersion", "5.6.3.0" END END BLOCK "VarFileInfo" diff --git a/README b/README index 0e89dd08842..e39bed22a26 100644 --- a/README +++ b/README @@ -70,6 +70,15 @@ should be used for the enum name. *** end Notes *** +# wolfSSL Release 5.6.3 (Jun 13, 2023) + +Release 5.6.3 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. + +Release 5.6.3 of wolfSSL embedded TLS has 2 bug fixes +* Fix for setting the atomic macro options introduced in release 5.6.2. This issue affects GNU gcc autoconf builds. The fix resolves a potential mismatch of the generated macros defined in options.h file and the macros used when the wolfSSL library is compiled. In version 5.6.2 this mismatch could result in unstable runtime behavior. +* Fix for invalid suffix error with Windows build using the macro GCM_TABLE_4BIT. + + # wolfSSL Release 5.6.2 (Jun 09, 2023) Release 5.6.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. diff --git a/README.md b/README.md index 295033d5c0e..29c3793f2d6 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,15 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. +# wolfSSL Release 5.6.3 (Jun 14, 2023) + +Release 5.6.3 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. + +Release 5.6.3 of wolfSSL embedded TLS has 2 bug fixes +* Fix for setting the atomic macro options introduced in release 5.6.2. This issue affects GNU gcc autoconf builds. The fix resolves a potential mismatch of the generated macros defined in options.h file and the macros used when the wolfSSL library is compiled. In version 5.6.2 this mismatch could result in unstable runtime behavior. +* Fix for invalid suffix error with Windows build using the macro GCM_TABLE_4BIT. + + # wolfSSL Release 5.6.2 (Jun 09, 2023) Release 5.6.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. diff --git a/configure.ac b/configure.ac index 7c558c05426..b7bb8c99bea 100644 --- a/configure.ac +++ b/configure.ac @@ -7,7 +7,7 @@ # AC_COPYRIGHT([Copyright (C) 2006-2020 wolfSSL Inc.]) AC_PREREQ([2.69]) -AC_INIT([wolfssl],[5.6.2],[https://github.com/wolfssl/wolfssl/issues],[wolfssl],[https://www.wolfssl.com]) +AC_INIT([wolfssl],[5.6.3],[https://github.com/wolfssl/wolfssl/issues],[wolfssl],[https://www.wolfssl.com]) AC_CONFIG_AUX_DIR([build-aux]) # The following sets CFLAGS to empty if unset on command line. We do not @@ -48,8 +48,8 @@ AC_SUBST([WOLFSSL_CONFIG_ARGS]) # these numbers don't always line up nicely with the library version. WOLFSSL_LIBRARY_VERSION_FIRST=35 WOLFSSL_LIBRARY_VERSION_SECOND=5 -WOLFSSL_LIBRARY_VERSION_THIRD=0 -WOLFSSL_LIBRARY_VERSION=40:0:5 +WOLFSSL_LIBRARY_VERSION_THIRD=1 +WOLFSSL_LIBRARY_VERSION=40:1:5 # | | | # +------+ | +---+ # | | | diff --git a/wolfssl.rc b/wolfssl.rc index da2d752a287766517c969a56e1678051e9fc86a1..d9c9a3e4b195028ce2b0c06d1457727e5cf77820 100644 GIT binary patch delta 41 vcmdm{woPrrBo0R7$&)z@8I3m| Date: Mon, 12 Jun 2023 13:48:24 -0600 Subject: [PATCH 382/391] update check for stdatomic header file --- configure.ac | 3 ++- wolfssl/wolfcrypt/wc_port.h | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/configure.ac b/configure.ac index b7bb8c99bea..e07cf7dad66 100644 --- a/configure.ac +++ b/configure.ac @@ -100,10 +100,11 @@ else fi -AC_CHECK_HEADERS([arpa/inet.h fcntl.h limits.h netdb.h netinet/in.h stddef.h time.h sys/ioctl.h sys/socket.h sys/time.h errno.h sys/un.h stdatomic.h]) +AC_CHECK_HEADERS([arpa/inet.h fcntl.h limits.h netdb.h netinet/in.h stddef.h time.h sys/ioctl.h sys/socket.h sys/time.h errno.h sys/un.h]) AC_CHECK_LIB([network],[socket]) AC_C_BIGENDIAN AC_C___ATOMIC +AC_CHECK_HEADER(stdatomic.h, [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSL_HAVE_ATOMIC_H"],[]) # check if functions of interest are linkable, but also check if # they're declared by the expected headers, and if not, supersede the diff --git a/wolfssl/wolfcrypt/wc_port.h b/wolfssl/wolfcrypt/wc_port.h index 3f8ee4f77ce..7b45284188c 100644 --- a/wolfssl/wolfcrypt/wc_port.h +++ b/wolfssl/wolfcrypt/wc_port.h @@ -307,12 +307,12 @@ #define WOLFSSL_ATOMIC_OPS #endif #else - #ifdef HAVE_STDATOMIC_H + #ifdef WOLFSSL_HAVE_ATOMIC_H /* Default C Implementation */ #include typedef atomic_int wolfSSL_Atomic_Int; #define WOLFSSL_ATOMIC_OPS - #endif /* HAVE_STDATOMIC_H */ + #endif /* WOLFSSL_HAVE_ATOMIC_H */ #endif #elif defined(_MSC_VER) /* Use MSVC compiler intrinsics for atomic ops */ From 2a332df378fb627bf3da303b2e5ec54b4029c1b6 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Thu, 15 Jun 2023 07:26:48 +1000 Subject: [PATCH 383/391] Math, Encrypted Memory: mod exp fix The modular exponentiation implementations in sp_int.c and tfm.c are not safe when using Encrypted Memory. Cannot have two pieces of memory where one changes and the other doesn't based on private value. Use extra variable to hold the two new values and assign them both back at the same time in a safe manner. Alternative implementations used when WC_PROTECT_ENCRYPTED_MEM is defined. --- wolfcrypt/src/sp_int.c | 274 +++++++++++++++++++++++++++++++++++++++++ wolfcrypt/src/tfm.c | 167 +++++++++++++++++++++++++ 2 files changed, 441 insertions(+) diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 85fc455b732..37d554bf002 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -5104,6 +5104,51 @@ int sp_copy(const sp_int* a, sp_int* r) } #endif +#if ((defined(WOLFSSL_SP_MATH_ALL) && ((!defined(WOLFSSL_RSA_VERIFY_ONLY) && \ + !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || !defined(NO_DH))) || \ + defined(OPENSSL_ALL)) && defined(WC_PROTECT_ENCRYPTED_MEM) + +/* Copy 2 numbers into two results based on y. Copy a fixed number of digits. + * + * Constant time implementation. + * When y is 0, r1 = a2 and r2 = a1. + * When y is 1, r1 = a1 and r2 = a2. + * + * @param [in] a1 First number to copy. + * @param [in] a2 Second number to copy. + * @param [out] r1 First result number to copy into. + * @param [out] r2 Second result number to copy into. + * @param [in] y Indicates which number goes into which result number. + * @param [in] used Number of digits to copy. + */ +static void _sp_copy_2_ct(const sp_int* a1, const sp_int* a2, sp_int* r1, + sp_int* r2, int y, unsigned int used) +{ + unsigned int i; + + /* Copy data - constant time. */ + for (i = 0; i < used; i++) { + r1->dp[i] = (a1->dp[i] & ((sp_digit)wc_off_on_addr[y ])) + + (a2->dp[i] & ((sp_digit)wc_off_on_addr[y^1])); + r2->dp[i] = (a1->dp[i] & ((sp_digit)wc_off_on_addr[y^1])) + + (a2->dp[i] & ((sp_digit)wc_off_on_addr[y ])); + } + /* Copy used. */ + r1->used = (a1->used & ((int)wc_off_on_addr[y ])) + + (a2->used & ((int)wc_off_on_addr[y^1])); + r2->used = (a1->used & ((int)wc_off_on_addr[y^1])) + + (a2->used & ((int)wc_off_on_addr[y ])); +#ifdef WOLFSSL_SP_INT_NEGATIVE + /* Copy sign. */ + r1->sign = (a1->sign & ((int)wc_off_on_addr[y ])) + + (a2->sign & ((int)wc_off_on_addr[y^1])); + r2->sign = (a1->sign & ((int)wc_off_on_addr[y^1])) + + (a2->sign & ((int)wc_off_on_addr[y ])); +#endif +} + +#endif + #if defined(WOLFSSL_SP_MATH_ALL) || (defined(HAVE_ECC) && defined(FP_ECC)) /* Initializes r and copies in value from a. * @@ -12483,6 +12528,9 @@ int sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, #if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || !defined(NO_DH) || \ defined(OPENSSL_ALL) + +#ifndef WC_PROTECT_ENCRYPTED_MEM + /* Internal. Exponentiates b to the power of e modulo m into r: r = b ^ e mod m * Process the exponent one bit at a time. * Is constant time and can be cache attack resistant. @@ -12614,6 +12662,105 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, FREE_SP_INT_ARRAY(t, NULL); return err; } + +#else + +/* Internal. Exponentiates b to the power of e modulo m into r: r = b ^ e mod m + * Process the exponent one bit at a time with base in Montgomery form. + * Is constant time and cache attack resistant. + * + * Based on work by Marc Joye, Sung-Ming Yen, "The Montgomery Powering Ladder", + * Cryptographic Hardware and Embedded Systems, CHES 2002 + * + * Algorithm: + * b: base, e: exponent, m: modulus, r: result, bits: #bits to use + * 1. t[1] = b mod m. + * 2. t[0] = 1 + * 3. For i in (bits-1)...0 + * 3.1. y = e[i] + * 3.2. t[2] = t[0] * t[1] + * 3.3. t[3] = t[y] ^ 2 + * 3.4. t[y] = t[3], t[y^1] = t[2] + * 4. r = t[0] + * + * @param [in] b SP integer that is the base. + * @param [in] e SP integer that is the exponent. + * @param [in] bits Number of bits in exponent to use. May be greater than + * count of bits in e. + * @param [in] m SP integer that is the modulus. + * @param [out] r SP integer to hold result. + * + * @return MP_OKAY on success. + * @return MP_MEM when dynamic memory allocation fails. + */ +static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, + const sp_int* m, sp_int* r) +{ + int err = MP_OKAY; + int done = 0; + DECL_SP_INT_ARRAY(t, m->used * 2 + 1, 4); + + /* Allocate temporaries. */ + ALLOC_SP_INT_ARRAY(t, m->used * 2 + 1, 4, err, NULL); + if (err == MP_OKAY) { + /* Initialize temporaries. */ + _sp_init_size(t[0], m->used * 2 + 1); + _sp_init_size(t[1], m->used * 2 + 1); + _sp_init_size(t[2], m->used * 2 + 1); + _sp_init_size(t[3], m->used * 2 + 1); + + /* 1. Ensure base is less than modulus. */ + if (_sp_cmp_abs(b, m) != MP_LT) { + err = sp_mod(b, m, t[1]); + /* Handle base == modulus. */ + if ((err == MP_OKAY) && sp_iszero(t[1])) { + _sp_set(r, 0); + done = 1; + } + } + else { + /* Copy base into working variable. */ + err = sp_copy(b, t[1]); + } + } + + if ((!done) && (err == MP_OKAY)) { + int i; + + /* 2. t[0] = 1 */ + _sp_set(t[0], 1); + + /* 3. For i in (bits-1)...0 */ + for (i = bits - 1; (err == MP_OKAY) && (i >= 0); i--) { + /* 3.1. y = e[i] */ + int y = (e->dp[i >> SP_WORD_SHIFT] >> (i & SP_WORD_MASK)) & 1; + + /* 3.2. t[2] = t[0] * t[1] */ + err = sp_mulmod(t[0], t[1], m, t[2]); + /* 3.3. t[3] = t[y] ^ 2 */ + if (err == MP_OKAY) { + _sp_copy((sp_int*)(((size_t)t[0] & sp_off_on_addr[y^1]) + + ((size_t)t[1] & sp_off_on_addr[y ])), + t[3]); + err = sp_sqrmod(t[3], m, t[3]); + } + /* 3.4. t[y] = t[3], t[y^1] = t[2] */ + if (err == MP_OKAY) { + _sp_copy_2_ct(t[2], t[3], t[0], t[1], y, m->used); + } + } + } + if ((!done) && (err == MP_OKAY)) { + /* 4. r = t[0] */ + err = sp_copy(t[0], r); + } + + FREE_SP_INT_ARRAY(t, NULL); + return err; +} + +#endif /* WC_PROTECT_ENCRYPTED_MEM */ + #endif #if (defined(WOLFSSL_SP_MATH_ALL) && ((!defined(WOLFSSL_RSA_VERIFY_ONLY) && \ @@ -12621,6 +12768,9 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, defined(OPENSSL_ALL) #ifndef WC_NO_HARDEN #if !defined(WC_NO_CACHE_RESISTANT) + +#ifndef WC_PROTECT_ENCRYPTED_MEM + /* Internal. Exponentiates b to the power of e modulo m into r: r = b ^ e mod m * Process the exponent one bit at a time with base in Montgomery form. * Is constant time and cache attack resistant. @@ -12759,6 +12909,130 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, FREE_SP_INT_ARRAY(t, NULL); return err; } + +#else + +/* Internal. Exponentiates b to the power of e modulo m into r: r = b ^ e mod m + * Process the exponent one bit at a time with base in Montgomery form. + * Is constant time and cache attack resistant. + * + * Based on work by Marc Joye, Sung-Ming Yen, "The Montgomery Powering Ladder", + * Cryptographic Hardware and Embedded Systems, CHES 2002 + * + * Algorithm: + * b: base, e: exponent, m: modulus, r: result, bits: #bits to use + * 1. t[1] = b mod m. + * 2. t[0] = ToMont(1) + * 3. t[1] = ToMont(t[1]) + * 4. For i in (bits-1)...0 + * 4.1. y = e[i] + * 4.2. t[2] = t[0] * t[1] + * 4.3. t[3] = t[y] ^ 2 + * 4.4. t[y] = t[3], t[y^1] = t[2] + * 5. t[0] = FromMont(t[0]) + * 6. r = t[0] + * + * @param [in] b SP integer that is the base. + * @param [in] e SP integer that is the exponent. + * @param [in] bits Number of bits in exponent to use. May be greater than + * count of bits in e. + * @param [in] m SP integer that is the modulus. + * @param [out] r SP integer to hold result. + * + * @return MP_OKAY on success. + * @return MP_MEM when dynamic memory allocation fails. + */ +static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, + const sp_int* m, sp_int* r) +{ + int err = MP_OKAY; + int done = 0; + DECL_SP_INT_ARRAY(t, m->used * 2 + 1, 4); + + /* Allocate temporaries. */ + ALLOC_SP_INT_ARRAY(t, m->used * 2 + 1, 4, err, NULL); + if (err == MP_OKAY) { + /* Initialize temporaries. */ + _sp_init_size(t[0], m->used * 2 + 1); + _sp_init_size(t[1], m->used * 2 + 1); + _sp_init_size(t[2], m->used * 2 + 1); + _sp_init_size(t[3], m->used * 2 + 1); + + /* 1. Ensure base is less than modulus. */ + if (_sp_cmp_abs(b, m) != MP_LT) { + err = sp_mod(b, m, t[1]); + /* Handle base == modulus. */ + if ((err == MP_OKAY) && sp_iszero(t[1])) { + _sp_set(r, 0); + done = 1; + } + } + else { + /* Copy base into working variable. */ + err = sp_copy(b, t[1]); + } + } + + if ((!done) && (err == MP_OKAY)) { + int i; + sp_int_digit mp; + + /* Calculate Montgomery multiplier for reduction. */ + _sp_mont_setup(m, &mp); + /* 2. t[0] = ToMont(1) + * Calculate 1 in Montgomery form. + */ + err = sp_mont_norm(t[0], m); + if (err == MP_OKAY) { + /* 3. t[1] = ToMont(t[1]) + * Convert base to Montgomery form. + */ + err = sp_mulmod(t[1], t[0], m, t[1]); + } + + /* 4. For i in (bits-1)...0 */ + for (i = bits - 1; (err == MP_OKAY) && (i >= 0); i--) { + /* 4.1. y = e[i] */ + int y = (e->dp[i >> SP_WORD_SHIFT] >> (i & SP_WORD_MASK)) & 1; + + /* 4.2. t[2] = t[0] * t[1] */ + err = sp_mul(t[0], t[1], t[2]); + if (err == MP_OKAY) { + err = _sp_mont_red(t[2], m, mp); + } + /* 4.3. t[3] = t[y] ^ 2 */ + if (err == MP_OKAY) { + _sp_copy((sp_int*)(((size_t)t[0] & sp_off_on_addr[y^1]) + + ((size_t)t[1] & sp_off_on_addr[y ])), + t[3]); + err = sp_sqr(t[3], t[3]); + } + if (err == MP_OKAY) { + err = _sp_mont_red(t[3], m, mp); + } + /* 4.4. t[y] = t[3], t[y^1] = t[2] */ + if (err == MP_OKAY) { + _sp_copy_2_ct(t[2], t[3], t[0], t[1], y, m->used); + } + } + + if (err == MP_OKAY) { + /* 5. t[0] = FromMont(t[0]) */ + err = _sp_mont_red(t[0], m, mp); + /* Reduction implementation returns number to range: 0..m-1. */ + } + } + if ((!done) && (err == MP_OKAY)) { + /* 6. r = t[0] */ + err = sp_copy(t[0], r); + } + + FREE_SP_INT_ARRAY(t, NULL); + return err; +} + +#endif /* WC_PROTECT_ENCRYPTED_MEM */ + #else #ifdef SP_ALLOC diff --git a/wolfcrypt/src/tfm.c b/wolfcrypt/src/tfm.c index 1ab156a24e9..48d6b3bcb85 100644 --- a/wolfcrypt/src/tfm.c +++ b/wolfcrypt/src/tfm.c @@ -1977,6 +1977,8 @@ int fp_exptmod_nb(exptModNb_t* nb, fp_int* G, fp_int* X, fp_int* P, fp_int* Y) #endif /* WC_RSA_NONBLOCK */ +#ifndef WC_PROTECT_ENCRYPTED_MEM + /* timing resistant montgomery ladder based exptmod Based on work by Marc Joye, Sung-Ming Yen, "The Montgomery Powering Ladder", Cryptographic Hardware and Embedded Systems, CHES 2002 @@ -2159,6 +2161,171 @@ static int _fp_exptmod_ct(fp_int * G, fp_int * X, int digits, fp_int * P, return err; } +#else + +/* Copy from a1 and a2 into r1 and r2 based on y in constant time. + * When y is 1, r1 = a1 and r2 = a2. + * When y is 0, r1 = a2 and r2 = a1. + * Always copy size digits as that is the maximum size for a1 and a2. + */ +static void fp_copy_2_ct(fp_int* a1, fp_int* a2, fp_int* r1, fp_int* r2, int y, + int size) +{ + int i; + + /* Copy data - constant time. */ + for (i = 0; i < size; i++) { + r1->dp[i] = (a1->dp[i] & ((fp_digit)wc_off_on_addr[y ])) + + (a2->dp[i] & ((fp_digit)wc_off_on_addr[y^1])); + r2->dp[i] = (a1->dp[i] & ((fp_digit)wc_off_on_addr[y^1])) + + (a2->dp[i] & ((fp_digit)wc_off_on_addr[y ])); + } + /* Copy used. */ + r1->used = (a1->used & ((int)wc_off_on_addr[y ])) + + (a2->used & ((int)wc_off_on_addr[y^1])); + r2->used = (a1->used & ((int)wc_off_on_addr[y^1])) + + (a2->used & ((int)wc_off_on_addr[y ])); + /* Copy sign. */ + r1->sign = (a1->sign & ((int)wc_off_on_addr[y ])) + + (a2->sign & ((int)wc_off_on_addr[y^1])); + r2->sign = (a1->sign & ((int)wc_off_on_addr[y^1])) + + (a2->sign & ((int)wc_off_on_addr[y ])); +} + +/* timing resistant montgomery ladder based exptmod + Based on work by Marc Joye, Sung-Ming Yen, "The Montgomery Powering Ladder", + Cryptographic Hardware and Embedded Systems, CHES 2002 +*/ +static int _fp_exptmod_ct(fp_int * G, fp_int * X, int digits, fp_int * P, + fp_int * Y) +{ +#ifndef WOLFSSL_SMALL_STACK + fp_int R[4]; /* need a temp for cache resistance */ +#else + fp_int *R; +#endif + fp_digit buf, mp; + int err, bitcnt, digidx, y; + + /* now setup montgomery */ + if ((err = fp_montgomery_setup (P, &mp)) != FP_OKAY) { + return err; + } + +#ifdef WOLFSSL_SMALL_STACK + R = (fp_int*)XMALLOC(sizeof(fp_int) * 4, NULL, DYNAMIC_TYPE_BIGINT); + if (R == NULL) + return FP_MEM; +#endif + fp_init(&R[0]); + fp_init(&R[1]); + fp_init(&R[2]); + fp_init(&R[3]); + + /* now we need R mod m */ + err = fp_montgomery_calc_normalization (&R[0], P); + if (err != FP_OKAY) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(R, NULL, DYNAMIC_TYPE_BIGINT); + #endif + return err; + } + + /* now set R[0][1] to G * R mod m */ + if (fp_cmp_mag(P, G) != FP_GT) { + /* G > P so we reduce it first */ + err = fp_mod(G, P, &R[1]); + if (err != FP_OKAY) { +#ifdef WOLFSSL_SMALL_STACK + XFREE(R, NULL, DYNAMIC_TYPE_BIGINT); +#endif + return err; + } + } else { + fp_copy(G, &R[1]); + } + err = fp_mulmod (&R[1], &R[0], P, &R[1]); + if (err != FP_OKAY) { +#ifdef WOLFSSL_SMALL_STACK + XFREE(R, NULL, DYNAMIC_TYPE_BIGINT); +#endif + return err; + } + + /* for j = t-1 downto 0 do + r_!k = R0*R1; r_k = r_k^2 + */ + + /* set initial mode and bit cnt */ + bitcnt = 1; + buf = 0; + digidx = digits - 1; + + for (;;) { + /* grab next digit as required */ + if (--bitcnt == 0) { + /* if digidx == -1 we are out of digits so break */ + if (digidx == -1) { + break; + } + /* read next digit and reset bitcnt */ + buf = X->dp[digidx--]; + bitcnt = (int)DIGIT_BIT; + } + + /* grab the next msb from the exponent */ + y = (int)(buf >> (DIGIT_BIT - 1)) & 1; + buf <<= (fp_digit)1; + + /* do ops */ + err = fp_mul(&R[0], &R[1], &R[2]); + if (err != FP_OKAY) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(R, NULL, DYNAMIC_TYPE_BIGINT); + #endif + return err; + } + err = fp_montgomery_reduce(&R[2], P, mp); + if (err != FP_OKAY) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(R, NULL, DYNAMIC_TYPE_BIGINT); + #endif + return err; + } + + /* instead of using R[y] for sqr, which leaks key bit to cache monitor, + * use R[3] as temp, make sure address calc is constant, keep + * &R[0] and &R[1] in cache */ + fp_copy((fp_int*) ( ((wc_ptr_t)&R[0] & wc_off_on_addr[y^1]) + + ((wc_ptr_t)&R[1] & wc_off_on_addr[y]) ), + &R[3]); + err = fp_sqr(&R[3], &R[3]); + if (err != FP_OKAY) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(R, NULL, DYNAMIC_TYPE_BIGINT); + #endif + return err; + } + err = fp_montgomery_reduce(&R[3], P, mp); + if (err != FP_OKAY) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(R, NULL, DYNAMIC_TYPE_BIGINT); + #endif + return err; + } + fp_copy_2_ct(&R[2], &R[3], &R[0], &R[1], y, P->used); + } + + err = fp_montgomery_reduce(&R[0], P, mp); + fp_copy(&R[0], Y); +#ifdef WOLFSSL_SMALL_STACK + XFREE(R, NULL, DYNAMIC_TYPE_BIGINT); +#endif + return err; +} + +#endif /* WC_PROTECT_ENCRYPTED_MEM */ + #endif /* TFM_TIMING_RESISTANT */ /* y = g**x (mod b) From cdb504196445a9e9203791b4f88d158868c4ea99 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 14 Jun 2023 11:08:56 -0700 Subject: [PATCH 384/391] sanity check on send fatal alert return --- src/internal.c | 31 ++++++++++++++++++++----------- wolfssl/internal.h | 2 +- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/internal.c b/src/internal.c index 47d8436bb7c..b3f57e20981 100644 --- a/src/internal.c +++ b/src/internal.c @@ -16065,13 +16065,13 @@ static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, #endif /* !WOLFSSL_NO_TLS12 */ #ifdef WOLFSSL_EXTRA_ALERTS -void SendFatalAlertOnly(WOLFSSL *ssl, int error) +int SendFatalAlertOnly(WOLFSSL *ssl, int error) { int why; /* already sent a more specific fatal alert */ if (ssl->alert_history.last_tx.level == alert_fatal) - return; + return 0; switch (error) { /* not fatal errors */ @@ -16081,12 +16081,12 @@ void SendFatalAlertOnly(WOLFSSL *ssl, int error) #ifdef WOLFSSL_ASYNC_CRYPT case WC_PENDING_E: #endif - return; + return 0; /* peer already disconnected and ssl is possibly in bad state * don't try to send an alert */ case SOCKET_ERROR_E: - return; + return error; case BUFFER_ERROR: case ASN_PARSE_E: @@ -16114,14 +16114,15 @@ void SendFatalAlertOnly(WOLFSSL *ssl, int error) break; } - SendAlert(ssl, alert_fatal, why); + return SendAlert(ssl, alert_fatal, why); } #else -void SendFatalAlertOnly(WOLFSSL *ssl, int error) +int SendFatalAlertOnly(WOLFSSL *ssl, int error) { (void)ssl; (void)error; /* no op */ + return 0; } #endif /* WOLFSSL_EXTRA_ALERTS */ @@ -16555,7 +16556,9 @@ int DtlsMsgDrain(WOLFSSL* ssl) DtlsTxMsgListClean(ssl); } else if (!IsAtLeastTLSv1_3(ssl->version)) { - SendFatalAlertOnly(ssl, ret); + if (SendFatalAlertOnly(ssl, ret) == SOCKET_ERROR_E) { + ret = SOCKET_ERROR_E; + } } #ifdef WOLFSSL_ASYNC_CRYPT if (ret == WC_PENDING_E) { @@ -19880,8 +19883,12 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->buffers.inputBuffer.buffer, &ssl->buffers.inputBuffer.idx, ssl->buffers.inputBuffer.length); - if (ret != 0) - SendFatalAlertOnly(ssl, ret); + if (ret != 0) { + if (SendFatalAlertOnly(ssl, ret) + == SOCKET_ERROR_E) { + ret = SOCKET_ERROR_E; + } + } } #endif #ifdef WOLFSSL_DTLS13 @@ -19918,8 +19925,10 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->buffers.inputBuffer.buffer, &ssl->buffers.inputBuffer.idx, ssl->buffers.inputBuffer.length); - if (ret != 0) - SendFatalAlertOnly(ssl, ret); + if (ret != 0) { + if (SendFatalAlertOnly(ssl, ret) == SOCKET_ERROR_E) + ret = SOCKET_ERROR_E; + } #else ret = BUFFER_ERROR; #endif diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 781d6c1c8ba..6679946c7d7 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -5899,7 +5899,7 @@ WOLFSSL_LOCAL int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek); WOLFSSL_LOCAL int SendFinished(WOLFSSL* ssl); WOLFSSL_LOCAL int RetrySendAlert(WOLFSSL* ssl); WOLFSSL_LOCAL int SendAlert(WOLFSSL* ssl, int severity, int type); -WOLFSSL_LOCAL void SendFatalAlertOnly(WOLFSSL *ssl, int error); +WOLFSSL_LOCAL int SendFatalAlertOnly(WOLFSSL *ssl, int error); WOLFSSL_LOCAL int ProcessReply(WOLFSSL* ssl); WOLFSSL_LOCAL int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr); From 145e855ae0a8a3deba642054199ad05b4f4b03c1 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 14 Jun 2023 12:21:52 -0700 Subject: [PATCH 385/391] adjust test case to handle error of peer closing down --- tests/api.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/api.c b/tests/api.c index 1511438da8d..73b0dd00ad3 100644 --- a/tests/api.c +++ b/tests/api.c @@ -10476,7 +10476,11 @@ static int test_tls_ext_duplicate(void) wolfSSL_SetIOReadCtx(ssl, &msg); ExpectIntNE(wolfSSL_accept(ssl), WOLFSSL_SUCCESS); - ExpectIntEQ(wolfSSL_get_error(ssl, 0), DUPLICATE_TLS_EXT_E); + /* can return duplicate ext error or socket error if the peer closed down + * while sending alert */ + if (wolfSSL_get_error(ssl, 0) != SOCKET_ERROR_E) { + ExpectIntEQ(wolfSSL_get_error(ssl, 0), DUPLICATE_TLS_EXT_E); + } wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); From bc18c98934717c9980ef0a8f60f7f81f76e74dd3 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 14 Jun 2023 21:01:12 -0700 Subject: [PATCH 386/391] adjust location used for writing to output buffer --- src/internal.c | 47 +++++++++++++++++++--------------------------- src/tls13.c | 30 ++++++++++------------------- wolfssl/internal.h | 1 + 3 files changed, 30 insertions(+), 48 deletions(-) diff --git a/src/internal.c b/src/internal.c index b3f57e20981..9211e16b913 100644 --- a/src/internal.c +++ b/src/internal.c @@ -9011,8 +9011,7 @@ int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket) return ret; } - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); if (inputSz != ENUM_LEN) sendSz = BuildMessage(ssl, output, sendSz, input, inputSz, handshake, 0, 0, 0, epochOrder); @@ -9743,8 +9742,7 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, return ret; if (ssl->buffers.outputBuffer.buffer == NULL) return MEMORY_E; - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); if (IsEncryptionOn(ssl, 1)) { /* First we need to add the fragment header ourselves. @@ -10074,6 +10072,14 @@ int SendBuffered(WOLFSSL* ssl) } +/* returns the current location in the output buffer to start writing to */ +byte* GetOutputBuffer(WOLFSSL* ssl) +{ + return ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.idx + + ssl->buffers.outputBuffer.length; +} + + /* Grow the output buffer */ static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size) { @@ -20343,8 +20349,7 @@ int SendChangeCipher(WOLFSSL* ssl) return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); AddRecordHeader(output, 1, change_cipher_spec, ssl, CUR_ORDER); @@ -21271,9 +21276,7 @@ int SendFinished(WOLFSSL* ssl) #endif /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; - + output = GetOutputBuffer(ssl); AddHandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl); /* make finished hashes */ @@ -21651,8 +21654,7 @@ int SendCertificate(WOLFSSL* ssl) return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); /* Safe to use ssl->fragOffset since it will be incremented immediately * after this block. This block needs to be entered only once to not @@ -22980,9 +22982,7 @@ static int SendAlert_ex(WOLFSSL* ssl, int severity, int type) return BUFFER_E; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; - + output = GetOutputBuffer(ssl); input[0] = (byte)severity; input[1] = (byte)type; ssl->alert_history.last_tx.code = type; @@ -30947,9 +30947,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; - + output = GetOutputBuffer(ssl); AddHeaders(output, length, server_hello, ssl); /* now write to output */ @@ -34430,9 +34428,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; - + output = GetOutputBuffer(ssl); AddHeaders(output, 0, server_hello_done, ssl); if (IsEncryptionOn(ssl, 1)) { @@ -35280,9 +35276,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; - + output = GetOutputBuffer(ssl); AddHeaders(output, length, session_ticket, ssl); /* hint */ @@ -35821,9 +35815,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; - + output = GetOutputBuffer(ssl); AddHeaders(output, 0, hello_request, ssl); if (IsEncryptionOn(ssl, 1)) { @@ -35895,8 +35887,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); /* Hello Verify Request should use the same sequence number * as the Client Hello unless we are in renegotiation then diff --git a/src/tls13.c b/src/tls13.c index f1a9e6b9400..20b720e0719 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -4212,8 +4212,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) return ret; /* Get position in output buffer to write new message to. */ - args->output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + args->output = GetOutputBuffer(ssl); /* Put the record and handshake headers on. */ AddTls13Headers(args->output, args->length, client_hello, ssl); @@ -6947,8 +6946,7 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) return ret; /* Get position in output buffer to write new message to. */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); /* Put the record and handshake headers on. */ AddTls13Headers(output, length, server_hello, ssl); @@ -7213,8 +7211,7 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) return ret; /* Get position in output buffer to write new message to. */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); /* Put the record and handshake headers on. */ AddTls13Headers(output, length, encrypted_extensions, ssl); @@ -7337,8 +7334,7 @@ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, return ret; /* Get position in output buffer to write new message to. */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); /* Put the record and handshake headers on. */ AddTls13Headers(output, reqSz, certificate_request, ssl); @@ -8061,8 +8057,7 @@ static int SendTls13Certificate(WOLFSSL* ssl) return ret; /* Get position in output buffer to write new message to. */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); if (ssl->fragOffset == 0) { AddTls13FragHeaders(output, fragSz, 0, payloadSz, certificate, ssl); @@ -8315,8 +8310,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) } /* get output buffer */ - args->output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + args->output = GetOutputBuffer(ssl); /* Advance state and proceed */ ssl->options.asyncState = TLS_ASYNC_BUILD; @@ -9544,8 +9538,7 @@ static int SendTls13Finished(WOLFSSL* ssl) return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); input = output + RECORD_HEADER_SZ; #ifdef WOLFSSL_DTLS13 @@ -9801,8 +9794,7 @@ static int SendTls13KeyUpdate(WOLFSSL* ssl) return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); input = output + RECORD_HEADER_SZ; #ifdef WOLFSSL_DTLS13 @@ -9994,8 +9986,7 @@ static int SendTls13EndOfEarlyData(WOLFSSL* ssl) return ret; /* Get position in output buffer to write new message to. */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); /* Put the record and handshake headers on. */ AddTls13Headers(output, length, end_of_early_data, ssl); @@ -10417,8 +10408,7 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) return ret; /* Get position in output buffer to write new message to. */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); /* Put the record and handshake headers on. */ AddTls13Headers(output, length, session_ticket, ssl); diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 6679946c7d7..363793e0087 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -5922,6 +5922,7 @@ WOLFSSL_LOCAL int TLSv1_3_Capable(WOLFSSL* ssl); WOLFSSL_LOCAL void FreeHandshakeResources(WOLFSSL* ssl); WOLFSSL_LOCAL void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree); WOLFSSL_LOCAL void ShrinkOutputBuffer(WOLFSSL* ssl); +WOLFSSL_LOCAL byte* GetOutputBuffer(WOLFSSL* ssl); WOLFSSL_LOCAL int VerifyClientSuite(word16 havePSK, byte cipherSuite0, byte cipherSuite); From 5902a4e1d6c62544ccc102d695e50796e65c63a6 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 16 Jun 2023 10:29:52 +1000 Subject: [PATCH 387/391] outputBuffer - use idx field dtls13.c: Change end of outputBuffer data calculations to use function GetOutputBuffer(). Use idx when calculating unused byte count of outputBuffer. internal.c: Change end of outputBuffer data calculations to use function GetOutputBuffer(). Use GetOutputBuffer() to calculate end of data in outputBuffer. GrowOutputBuffer(): Calculate new size to allocate to include already written data in case of static buffer. Copy all data including already written count (idx). CheckAvailableSize(): Don't subtract idx from length when checking MTU size. Do subtract idx from bufferSize to determine count of unused bytes in outputBuffer. --- src/dtls13.c | 18 +++++++----------- src/internal.c | 41 +++++++++++++++++------------------------ 2 files changed, 24 insertions(+), 35 deletions(-) diff --git a/src/dtls13.c b/src/dtls13.c index 2e0f68ad6a8..b5fecafd79f 100644 --- a/src/dtls13.c +++ b/src/dtls13.c @@ -419,7 +419,7 @@ static int Dtls13SendFragFromBuffer(WOLFSSL* ssl, byte* output, word16 length) if (ret != 0) return ret; - buf = ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length; + buf = GetOutputBuffer(ssl); XMEMCPY(buf, output, length); @@ -924,8 +924,7 @@ static int Dtls13SendFragmentedInternal(WOLFSSL* ssl) if (ret != 0) return ret; - output = - ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); ret = Dtls13HandshakeAddHeaderFrag(ssl, output + rlHeaderLength, (enum HandShakeType)ssl->dtls13FragHandshakeType, @@ -1509,8 +1508,7 @@ static int Dtls13RtxSendBuffered(WOLFSSL* ssl) if (ret != 0) return ret; - output = - ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); XMEMCPY(output + headerLength, r->data, r->length); @@ -2342,8 +2340,7 @@ static int Dtls13WriteAckMessage(WOLFSSL* ssl, if (ret != 0) return ret; - output = - ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); ackMessage = output + headerLength; @@ -2617,8 +2614,7 @@ int SendDtls13Ack(WOLFSSL* ssl) if (ret != 0) return ret; - output = - ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); ret = Dtls13RlAddPlaintextHeader(ssl, output, ack, (word16)length); if (ret != 0) @@ -2632,10 +2628,10 @@ int SendDtls13Ack(WOLFSSL* ssl) if (ret != 0) return ret; - output = - ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); outputSize = ssl->buffers.outputBuffer.bufferSize - + ssl->buffers.outputBuffer.idx - ssl->buffers.outputBuffer.length; headerSize = Dtls13GetRlHeaderLength(ssl, 1); diff --git a/src/internal.c b/src/internal.c index 9211e16b913..4f1b9eeabad 100644 --- a/src/internal.c +++ b/src/internal.c @@ -8967,10 +8967,7 @@ int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket) return ret; } - XMEMCPY(ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.idx + - ssl->buffers.outputBuffer.length, - pool->raw, pool->sz); + XMEMCPY(GetOutputBuffer(ssl), pool->raw, pool->sz); ssl->buffers.outputBuffer.length += pool->sz; } else { @@ -9950,6 +9947,7 @@ void ShrinkOutputBuffer(WOLFSSL* ssl) ssl->buffers.outputBuffer.bufferSize = STATIC_BUFFER_LEN; ssl->buffers.outputBuffer.dynamicFlag = 0; ssl->buffers.outputBuffer.offset = 0; + /* idx and length are assumed to be 0. */ } @@ -10091,6 +10089,8 @@ static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size) #else const byte align = WOLFSSL_GENERAL_ALIGNMENT; #endif + int newSz = size + ssl->buffers.outputBuffer.idx + + ssl->buffers.outputBuffer.length; #if WOLFSSL_GENERAL_ALIGNMENT > 0 /* the encrypted data will be offset from the front of the buffer by @@ -10101,8 +10101,7 @@ static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size) align *= 2; #endif - tmp = (byte*)XMALLOC(size + ssl->buffers.outputBuffer.length + align, - ssl->heap, DYNAMIC_TYPE_OUT_BUFFER); + tmp = (byte*)XMALLOC(newSz + align, ssl->heap, DYNAMIC_TYPE_OUT_BUFFER); WOLFSSL_MSG("growing output buffer"); if (tmp == NULL) @@ -10117,14 +10116,14 @@ static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size) /* can be from IO memory pool which does not need copy if same buffer */ if (ssl->buffers.outputBuffer.length && tmp == ssl->buffers.outputBuffer.buffer) { - ssl->buffers.outputBuffer.bufferSize = - size + ssl->buffers.outputBuffer.length; + ssl->buffers.outputBuffer.bufferSize = newSz; return 0; } #endif if (ssl->buffers.outputBuffer.length) XMEMCPY(tmp, ssl->buffers.outputBuffer.buffer, + ssl->buffers.outputBuffer.idx + ssl->buffers.outputBuffer.length); if (ssl->buffers.outputBuffer.dynamicFlag) { @@ -10142,8 +10141,7 @@ static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size) ssl->buffers.outputBuffer.offset = 0; ssl->buffers.outputBuffer.buffer = tmp; - ssl->buffers.outputBuffer.bufferSize = size + - ssl->buffers.outputBuffer.length; + ssl->buffers.outputBuffer.bufferSize = newSz; return 0; } @@ -10241,8 +10239,7 @@ int CheckAvailableSize(WOLFSSL *ssl, int size) #ifdef WOLFSSL_DTLS if (ssl->options.dtls) { - if (size + ssl->buffers.outputBuffer.length - - ssl->buffers.outputBuffer.idx > + if (size + ssl->buffers.outputBuffer.length > #if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU) ssl->dtlsMtuSz #else @@ -10274,8 +10271,9 @@ int CheckAvailableSize(WOLFSSL *ssl, int size) } #endif - if (ssl->buffers.outputBuffer.bufferSize - ssl->buffers.outputBuffer.length - < (word32)size) { + if ((ssl->buffers.outputBuffer.bufferSize - + ssl->buffers.outputBuffer.length - + ssl->buffers.outputBuffer.idx) < (word32)size) { if (GrowOutputBuffer(ssl, size) < 0) return MEMORY_E; } @@ -21896,8 +21894,7 @@ int SendCertificateRequest(WOLFSSL* ssl) return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); AddHeaders(output, reqSz, certificate_request, ssl); @@ -22055,8 +22052,7 @@ static int BuildCertificateStatus(WOLFSSL* ssl, byte type, buffer* status, ssl->options.buildingMsg = 1; if ((ret = CheckAvailableSize(ssl, sendSz)) == 0) { - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); AddHeaders(output, length, certificate_status, ssl); @@ -22652,8 +22648,7 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) return ssl->error = ret; /* get output buffer */ - out = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + out = GetOutputBuffer(ssl); #ifdef HAVE_LIBZ if (ssl->options.usingCompression) { @@ -26444,8 +26439,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, return ret; /* get output buffer */ - output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + output = GetOutputBuffer(ssl); AddHeaders(output, length, client_hello, ssl); @@ -29941,8 +29935,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) goto exit_scke; /* get output buffer */ - args->output = ssl->buffers.outputBuffer.buffer + - ssl->buffers.outputBuffer.length; + args->output = GetOutputBuffer(ssl); AddHeaders(args->output, args->encSz + tlsSz, client_key_exchange, ssl); From 2faf98c2a80ea5bf8e0880874a8e026b9326f8c5 Mon Sep 17 00:00:00 2001 From: John Safranek Date: Fri, 16 Jun 2023 09:47:35 -0700 Subject: [PATCH 388/391] Update read-me and change-log for the release. --- ChangeLog.md | 7 +++++-- README | 5 ++++- README.md | 5 ++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 4f9355522d4..440c52d0a4a 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,8 +1,11 @@ -# wolfSSL Release 5.6.3 (Jun 13, 2023) +# wolfSSL Release 5.6.3 (Jun 16, 2023) + +Release 5.6.3 of wolfSSL embedded TLS has 4 bug fixes: -Release 5.6.3 of wolfSSL embedded TLS has 2 bug fixes * Fix for setting the atomic macro options introduced in release 5.6.2. This issue affects GNU gcc autoconf builds. The fix resolves a potential mismatch of the generated macros defined in options.h file and the macros used when the wolfSSL library is compiled. In version 5.6.2 this mismatch could result in unstable runtime behavior. * Fix for invalid suffix error with Windows build using the macro GCM_TABLE_4BIT. +* Improvements to Encrypted Memory support (WC_PROTECT_ENCRYPTED_MEM) implementations for modular exponentiation in SP math-all (sp_int.c) and TFM (tfm.c). +* Improvements to SendAlert for getting output buffer. # wolfSSL Release 5.6.2 (Jun 09, 2023) diff --git a/README b/README index e39bed22a26..0593c7a02f2 100644 --- a/README +++ b/README @@ -74,9 +74,12 @@ should be used for the enum name. Release 5.6.3 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. -Release 5.6.3 of wolfSSL embedded TLS has 2 bug fixes +Release 5.6.3 of wolfSSL embedded TLS has 2 bug fixes: + * Fix for setting the atomic macro options introduced in release 5.6.2. This issue affects GNU gcc autoconf builds. The fix resolves a potential mismatch of the generated macros defined in options.h file and the macros used when the wolfSSL library is compiled. In version 5.6.2 this mismatch could result in unstable runtime behavior. * Fix for invalid suffix error with Windows build using the macro GCM_TABLE_4BIT. +* Improvements to Encrypted Memory support (WC_PROTECT_ENCRYPTED_MEM) implementations for modular exponentiation in SP math-all (sp_int.c) and TFM (tfm.c). +* Improvements to SendAlert for getting output buffer. # wolfSSL Release 5.6.2 (Jun 09, 2023) diff --git a/README.md b/README.md index 29c3793f2d6..262a1f71983 100644 --- a/README.md +++ b/README.md @@ -83,9 +83,12 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a Release 5.6.3 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. -Release 5.6.3 of wolfSSL embedded TLS has 2 bug fixes +Release 5.6.3 of wolfSSL embedded TLS has 4 bug fixes: + * Fix for setting the atomic macro options introduced in release 5.6.2. This issue affects GNU gcc autoconf builds. The fix resolves a potential mismatch of the generated macros defined in options.h file and the macros used when the wolfSSL library is compiled. In version 5.6.2 this mismatch could result in unstable runtime behavior. * Fix for invalid suffix error with Windows build using the macro GCM_TABLE_4BIT. +* Improvements to Encrypted Memory support (WC_PROTECT_ENCRYPTED_MEM) implementations for modular exponentiation in SP math-all (sp_int.c) and TFM (tfm.c). +* Improvements to SendAlert for getting output buffer. # wolfSSL Release 5.6.2 (Jun 09, 2023) From 7242720cd416ebcc28dede46b1cc5282d72fc191 Mon Sep 17 00:00:00 2001 From: John Safranek Date: Sun, 18 Jun 2023 20:24:28 -0700 Subject: [PATCH 389/391] update readme --- README | 4 ++-- README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README b/README index 0593c7a02f2..9b870f5ba4d 100644 --- a/README +++ b/README @@ -70,11 +70,11 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.6.3 (Jun 13, 2023) +# wolfSSL Release 5.6.3 (Jun 20, 2023) Release 5.6.3 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. -Release 5.6.3 of wolfSSL embedded TLS has 2 bug fixes: +Release 5.6.3 of wolfSSL embedded TLS has 4 bug fixes: * Fix for setting the atomic macro options introduced in release 5.6.2. This issue affects GNU gcc autoconf builds. The fix resolves a potential mismatch of the generated macros defined in options.h file and the macros used when the wolfSSL library is compiled. In version 5.6.2 this mismatch could result in unstable runtime behavior. * Fix for invalid suffix error with Windows build using the macro GCM_TABLE_4BIT. diff --git a/README.md b/README.md index 262a1f71983..18b3665ff57 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.6.3 (Jun 14, 2023) +# wolfSSL Release 5.6.3 (Jun 20, 2023) Release 5.6.3 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. From 06064371c35f78a767494bc05a653d04a984e68d Mon Sep 17 00:00:00 2001 From: joeftiger Date: Sun, 3 Sep 2023 15:45:54 +0200 Subject: [PATCH 390/391] fix: benchmark for client/server extensions --- src/tls.c | 6 ------ src/tls13.c | 6 ++++++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/tls.c b/src/tls.c index 1e836cdd7d8..bd825e68f30 100644 --- a/src/tls.c +++ b/src/tls.c @@ -11845,11 +11845,8 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, byte isRequest = (msgType == client_hello || msgType == certificate_request); - struct timespec start, end; struct timespec ra_start, ra_end; - clock_gettime(CLOCK_MONOTONIC, &start); - while ((extension = list)) { list = extension->next; @@ -12061,12 +12058,9 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, *pOffset += offset; - clock_gettime(CLOCK_MONOTONIC, &end); if (msgType == encrypted_extensions) { - timespec_subtract(&start, &end, &ssl->benchmark.server_extensions); timespec_subtract(&ra_start, &ra_end, &ssl->benchmark.server_att_request); } else { - timespec_subtract(&start, &end, &ssl->benchmark.client_extensions); timespec_subtract(&ra_start, &ra_end, &ssl->benchmark.client_att_request); } diff --git a/src/tls13.c b/src/tls13.c index 20b720e0719..5808f393419 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -4005,6 +4005,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND); WOLFSSL_ENTER("SendTls13ClientHello"); struct timespec start, end; + struct timespec extensions_start, extensions_end; clock_gettime(CLOCK_MONOTONIC, &start); if (ssl == NULL) { @@ -4310,6 +4311,8 @@ int SendTls13ClientHello(WOLFSSL* ssl) args->output[args->idx++] = COMP_LEN; args->output[args->idx++] = NO_COMPRESSION; + + clock_gettime(CLOCK_MONOTONIC, &extensions_start); #if defined(HAVE_ECH) /* write inner then outer */ if (ssl->options.useEch == 1) { @@ -4368,6 +4371,8 @@ int SendTls13ClientHello(WOLFSSL* ssl) if (ret != 0) return ret; + clock_gettime(CLOCK_MONOTONIC, &extensions_end); + args->idx += args->length; #if defined(HAVE_ECH) @@ -4465,6 +4470,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) #endif clock_gettime(CLOCK_MONOTONIC, &end); + timespec_subtract(&extensions_start, &extensions_end, &ssl->benchmark.client_extensions); timespec_subtract(&start, &end, &ssl->benchmark.client_hello); WOLFSSL_LEAVE("SendTls13ClientHello", ret); From 6e4d09d18200d52b2c0c5b756ebe5be0e40cedc3 Mon Sep 17 00:00:00 2001 From: joeftiger Date: Tue, 5 Sep 2023 19:24:08 +0200 Subject: [PATCH 391/391] fix: remove commented out code --- wolfssl/ssl.h | 31 ------------------------------- 1 file changed, 31 deletions(-) diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index e753cdb3a3c..c8fee4af74f 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -5291,19 +5291,6 @@ typedef struct Benchmark { WOLFSSL_API Benchmark *wolfSSL_GetBenchmark(WOLFSSL *ssl); WOLFSSL_API static void timespec_subtract(struct timespec *start, struct timespec *end, struct timespec *result) { - /* - if start.ns < end.ns: - result.ns = end.ns - start.ns - result.s = end.s - start.s - else if start.ns > end.ns: - dt = start.ns - end.ns - result.ns = 1'000'000'000 - dt // nanoseconds - result.s = end.s - start.s - 1 // offset due to underflow - else: - result.ns = 0 - result.s = end.s - start.s - */ - if (start->tv_nsec < end->tv_nsec) { result->tv_nsec = end->tv_nsec - start->tv_nsec; result->tv_sec = end->tv_sec - start->tv_sec; @@ -5314,24 +5301,6 @@ WOLFSSL_API static void timespec_subtract(struct timespec *start, struct timespe result->tv_nsec = 0; result->tv_sec = end->tv_sec - start->tv_sec; } - - /* - // Perform the carrend for the later subtraction bend updating end. - if (start->tv_nsec < end->tv_nsec) { - __syscall_slong_t nsec = (end->tv_nsec - start->tv_nsec) / 1000000000L + 1; - end->tv_nsec -= 1000000000L * nsec; - end->tv_sec += nsec; - } - if (start->tv_nsec - end->tv_nsec > 1000000000L) { - __syscall_slong_t nsec = (start->tv_nsec - end->tv_nsec) / 1000000000L; - end->tv_nsec += 1000000000L * nsec; - end->tv_sec -= nsec; - } - - // Compute the time remaining to wait. tv_nsec is certainly positive. - result->tv_sec = start->tv_sec - end->tv_sec; - result->tv_nsec = start->tv_nsec - end->tv_nsec; - */ } #ifdef __cplusplus