From e20ca25204c9c5e36f53ae92ddf017cd17d07e31 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Veronika=20Hanul=C3=ADkov=C3=A1?= <vhanulik@redhat.com>
Date: Thu, 18 Jul 2024 10:16:39 +0200
Subject: [PATCH] pkcs15-setcos: Check length of generated key

Thanks Matteo Marini for report
https://github.com/OpenSC/OpenSC/security/advisories/GHSA-p3mx-7472-h3j8

fuzz_pkcs15init/26

CVE: CVE-2024-45619
Upstream-Status: Backport [https://github.com/OpenSC/OpenSC/commit/e20ca25204c9c5e36f53ae92ddf017cd17d07e31]

Signed-off-by: Zhang Peng <peng.zhang1.cn@windriver.com>
---
 src/pkcs15init/pkcs15-setcos.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)


diff --git a/src/pkcs15init/pkcs15-setcos.c b/src/pkcs15init/pkcs15-setcos.c
index bfee78cd6..57d5e83bf 100644
--- a/src/pkcs15init/pkcs15-setcos.c
+++ b/src/pkcs15init/pkcs15-setcos.c
@@ -498,6 +498,9 @@ setcos_generate_key(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
 		r = sc_card_ctl(p15card->card, SC_CARDCTL_SETCOS_GETDATA, &data_obj);
 		LOG_TEST_RET(ctx, r, "Cannot get key modulus: 'SETCOS_GETDATA' failed");
 
+		if (data_obj.DataLen < 3 || data_obj.DataLen < pubkey->u.rsa.modulus.len)
+			LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Cannot get key modulus: wrong length of raw key");
+
 		keybits = ((raw_pubkey[0] * 256) + raw_pubkey[1]);  /* modulus bit length */
 		if (keybits != key_info->modulus_length)  {
 			sc_log(ctx, 
@@ -505,10 +508,11 @@ setcos_generate_key(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
 				 keybits, key_info->modulus_length);
 			LOG_TEST_RET(ctx, SC_ERROR_PKCS15INIT, "Failed to generate key");
 		}
-		memcpy (pubkey->u.rsa.modulus.data, &raw_pubkey[2], pubkey->u.rsa.modulus.len);
+		memcpy(pubkey->u.rsa.modulus.data, &raw_pubkey[2], pubkey->u.rsa.modulus.len);
+	} else {
+		sc_file_free(file);
 	}
 
-	sc_file_free(file);
 	return r;
 }
 
--
2.34.1
