Commit 6a9d4acb5f for openssl.org

commit 6a9d4acb5f7c70b310d27ed494f5d626e2d3950f
Author: Sabith Saheb <shabi7204192361@gmail.com>
Date:   Thu Oct 22 16:33:18 2026 +0530

    rsa_kem: check secretlen before writing the RSASVE secret

    rsasve_generate() writes nlen = RSA_size() bytes of the random secret z
    into the caller's secret buffer and then reads them back
    for RSA_public_encrypt(), but it only checks the wrapped key buffer size
    against nlen.  EVP_PKEY_encapsulate(3) documents *genkeylen as the size
    of the provided buffer, so a caller passing a secret buffer smaller than
    the modulus, e.g. 32 bytes with an RSA-2048 key, gets a heap buffer
    overflow of up to RSA_size() - *secretlen bytes in BN_bn2binpad().

    The EC, ECX, ML-KEM and hybrid ML-KEM encapsulate paths already reject
    a *secretlen smaller than the secret they produce. Do the same for RSASVE,
    next to the existing outlen check. A NULL secretlen is still accepted
    as before.

    Add a too-short secretlen case to kem_rsa_gen_recover
    in evp_libctx_test.

    Fixes: 80f4fd18f72c "Add KEM (Key encapsulation mechanism) support to providers"
    Assisted-by: Claude:claude-opus-5-5
    Reviewed-by: Tomas Mraz <tomas@openssl.foundation>
    Reviewed-by: Eugene Syromiatnikov <esyr@openssl.org>
    Merge-date: Wed Nov 25 15:48:53 2026
    Merged-from: https://github.com/openssl/openssl/pull/33328

diff --git a/providers/implementations/kem/rsa_kem.c b/providers/implementations/kem/rsa_kem.c
index 675409ba33..2764e3268f 100644
--- a/providers/implementations/kem/rsa_kem.c
+++ b/providers/implementations/kem/rsa_kem.c
@@ -318,6 +318,15 @@ static int rsasve_generate(PROV_RSA_CTX *prsactx,
         return 0;
     }

+    /*
+     * Likewise, if secretlen is specified it must report the length of the
+     * secret buffer, which receives nlen bytes
+     */
+    if (secretlen != NULL && *secretlen < nlen) {
+        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_OUTPUT_LENGTH);
+        return 0;
+    }
+
     /*
      * Step (2): Generate a random byte string z of nlen bytes where
      *            1 < z < n - 1
diff --git a/test/evp_libctx_test.c b/test/evp_libctx_test.c
index 9a3192ad95..1372765d7a 100644
--- a/test/evp_libctx_test.c
+++ b/test/evp_libctx_test.c
@@ -615,6 +615,16 @@ static int kem_rsa_gen_recover(void)
             ret = 0;
     }

+    /* Test that providing a too short secretlen fails */
+    if (fips_provider_version_match(libctx, ">=4.2.0")) {
+        ctlen = sizeof(ct);
+        secretlen = 32;
+        if (!TEST_int_eq(EVP_PKEY_encapsulate(dctx, ct, &ctlen, secret,
+                             &secretlen),
+                0))
+            ret = 0;
+    }
+
     EVP_PKEY_free(pub);
     EVP_PKEY_free(priv);
     EVP_PKEY_CTX_free(rctx);