From 8632ec172beda894581d67eaa991e519a7874f7d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Veronika=20Hanul=C3=ADkov=C3=A1?= <vhanulik@redhat.com>
Date: Wed, 17 Jul 2024 11:18:52 +0200
Subject: [PATCH] pkcs15-tcos: Check return value of serial num conversion

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

fuzz_pkcs15_encode/21

CVE: CVE-2024-45618
Upstream-Status: Backport [https://github.com/OpenSC/OpenSC/commit/8632ec172beda894581d67eaa991e519a7874f7d]

Signed-off-by: Zhang Peng <peng.zhang1.cn@windriver.com>
---
 src/libopensc/pkcs15-tcos.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/src/libopensc/pkcs15-tcos.c b/src/libopensc/pkcs15-tcos.c
index a78b9aee5..9f44de6e5 100644
--- a/src/libopensc/pkcs15-tcos.c
+++ b/src/libopensc/pkcs15-tcos.c
@@ -530,10 +530,15 @@ int sc_pkcs15emu_tcos_init_ex(
 	/* get the card serial number */
 	r = sc_card_ctl(card, SC_CARDCTL_GET_SERIALNR, &serialnr);
 	if (r < 0) {
-		sc_log(ctx,  "unable to get ICCSN\n");
+		sc_log(ctx, "unable to get ICCSN");
 		return SC_ERROR_WRONG_CARD;
 	}
-	sc_bin_to_hex(serialnr.value, serialnr.len , serial, sizeof(serial), 0);
+	r = sc_bin_to_hex(serialnr.value, serialnr.len, serial, sizeof(serial), 0);
+	if (r != SC_SUCCESS) {
+		sc_log(ctx, "serial number invalid");
+		return SC_ERROR_INTERNAL;
+	}
+
 	serial[19] = '\0';
 	set_string(&p15card->tokeninfo->serial_number, serial);

--
2.34.1
