From a1bcc6516f43d570899820d259b71c53f8049168 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 09:23:20 +0200
Subject: [PATCH] pkcs15-starcos: Check length of file to be non-zero

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

fuzz_pkcs15init/20

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

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

diff --git a/src/pkcs15init/pkcs15-starcos.c b/src/pkcs15init/pkcs15-starcos.c
index bde7413a46..267ad2b04a 100644
--- a/src/pkcs15init/pkcs15-starcos.c
+++ b/src/pkcs15init/pkcs15-starcos.c
@@ -670,6 +670,8 @@ static int starcos_write_pukey(sc_profile_t *profile, sc_card_t *card,
 		return r;
 	len = tfile->size;
 	sc_file_free(tfile);
+	if (len == 0)
+		return SC_ERROR_INTERNAL;
 	buf = malloc(len);
 	if (!buf)
 		return SC_ERROR_OUT_OF_MEMORY;
@@ -682,7 +684,7 @@ static int starcos_write_pukey(sc_profile_t *profile, sc_card_t *card,
 	if (num_keys == 0xff)
 		num_keys = 0;
 	/* encode public key */
-	keylen  = starcos_encode_pukey(rsa, NULL, kinfo);
+	keylen = starcos_encode_pukey(rsa, NULL, kinfo);
 	if (!keylen) {
 		free(buf);
 		return SC_ERROR_INTERNAL;
--
2.34.1
