From 16ada9dc7cddf1cb99516aea67b6752c251c94a2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Veronika=20Hanul=C3=ADkov=C3=A1?= <vhanulik@redhat.com>
Date: Fri, 12 Jul 2024 15:04:19 +0200
Subject: [PATCH] card-gids: Use actual length of reponse buffer

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

fuzz_pkcs11/11

CVE: CVE-2024-45616
Upstream-Status: Backport [https://github.com/OpenSC/OpenSC/commit/16ada9dc7cddf1cb99516aea67b6752c251c94a2]

Signed-off-by: Zhang Peng <peng.zhang1.cn@windriver.com>
---
 src/libopensc/card-gids.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/libopensc/card-gids.c b/src/libopensc/card-gids.c
index f25e37de4..91e1e0569 100644
--- a/src/libopensc/card-gids.c
+++ b/src/libopensc/card-gids.c
@@ -231,6 +231,7 @@ static int gids_get_DO(sc_card_t* card, int fileIdentifier, int dataObjectIdenti
 	size_t datasize = 0;
 	const u8* p;
 	u8 buffer[MAX_GIDS_FILE_SIZE];
+	size_t buffer_len = sizeof(buffer);
 
 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
 	sc_log(card->ctx, 
@@ -244,14 +245,15 @@ static int gids_get_DO(sc_card_t* card, int fileIdentifier, int dataObjectIdenti
 	apdu.data = data;
 	apdu.datalen = 04;
 	apdu.resp = buffer;
-	apdu.resplen = sizeof(buffer);
+	apdu.resplen = buffer_len;
 	apdu.le = 256;
 
 	r = sc_transmit_apdu(card, &apdu);
 	LOG_TEST_RET(card->ctx, r, "gids get data failed");
 	LOG_TEST_RET(card->ctx,  sc_check_sw(card, apdu.sw1, apdu.sw2), "invalid return");
+	buffer_len = apdu.resplen;
 
-	p = sc_asn1_find_tag(card->ctx, buffer, apdu.resplen, dataObjectIdentifier, &datasize);
+	p = sc_asn1_find_tag(card->ctx, buffer, buffer_len, dataObjectIdentifier, &datasize);
 	if (!p) {
 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
 	}
--
2.34.1
