From 468a314d76b26f724a551f2eb339dd17c856cf18 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 11:03:46 +0200
Subject: [PATCH] iasecc-sdo: Check length of data when parsing

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

fuzz_pkcs15init/27,29

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

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

diff --git a/src/libopensc/iasecc-sdo.c b/src/libopensc/iasecc-sdo.c
index 4d6be7ad4..bdbd5ab17 100644
--- a/src/libopensc/iasecc-sdo.c
+++ b/src/libopensc/iasecc-sdo.c
@@ -334,16 +334,25 @@ iasecc_se_parse(struct sc_card *card, unsigned char *data, size_t data_len, stru
 
 	LOG_FUNC_CALLED(ctx);
 
+	if (data_len < 1)
+		LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);
+
 	if (*data == IASECC_SDO_TEMPLATE_TAG)   {
 		size_size = iasecc_parse_size(data + 1, &size);
 		LOG_TEST_RET(ctx, size_size, "parse error: invalid size data of IASECC_SDO_TEMPLATE");
 
+		if (data_len - 1 < size)
+			LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);
+
 		data += size_size + 1;
 		data_len = size;
 		sc_log(ctx,
 		       "IASECC_SDO_TEMPLATE: size %"SC_FORMAT_LEN_SIZE_T"u, size_size %"SC_FORMAT_LEN_SIZE_T"u",
 		       size, size_size);
 
+		if (data_len < 3)
+			LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);
+
 		if (*data != IASECC_SDO_TAG_HEADER)
 			LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);
 
--
2.34.1
