diff --git a/src/ssl.c b/src/ssl.c index 10fd73ca60..869af20011 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -5726,6 +5726,13 @@ int wolfSSL_export_keying_material(WOLFSSL *ssl, return WOLFSSL_FAILURE; } + /* Sanity check contextLen to prevent integer overflow when cast to word32 + * and to ensure it fits in the 2-byte length encoding (max 65535). */ + if (use_context && contextLen > WOLFSSL_MAX_16BIT) { + WOLFSSL_MSG("contextLen too large"); + return WOLFSSL_FAILURE; + } + /* clientRandom + serverRandom * OR * clientRandom + serverRandom + ctx len encoding + ctx */ diff --git a/src/tls13.c b/src/tls13.c index 101b31541a..025819bd9f 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -1023,6 +1023,11 @@ int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen, if (ret != 0) return ret; + /* Sanity check contextLen to prevent truncation when cast to word32. */ + if (contextLen > WOLFSSL_MAX_32BIT) { + return BAD_FUNC_ARG; + } + /* Hash(context_value) */ ret = wc_Hash(hashType, context, (word32)contextLen, hashOut, WC_MAX_DIGEST_SIZE); if (ret != 0) diff --git a/tests/api.c b/tests/api.c index 2cdd81c79b..d8b0677007 100644 --- a/tests/api.c +++ b/tests/api.c @@ -24070,6 +24070,11 @@ static int test_export_keying_material_cb(WOLFSSL_CTX *ctx, WOLFSSL *ssl) NULL, 0, 0), 0); ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), "key expansion", XSTR_SIZEOF("key expansion"), NULL, 0, 0), 0); + /* contextLen overflow: values exceeding UINT16_MAX must be rejected to + * prevent integer overflow in seedLen calculation (ZD #21242). */ + ExpectIntEQ(wolfSSL_export_keying_material(ssl, ekm, sizeof(ekm), + "Test label", XSTR_SIZEOF("Test label"), ekm, + (size_t)0xFFFF + 1, 1), 0); return EXPECT_RESULT(); }