From dd554a2e1e31e6cb75c627c653652696d61e8de8 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 12:33:31 +0200
Subject: [PATCH] card-coolkey: Check length of buffer before conversion

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

fuzz_pkcs15_reader/3

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

Signed-off-by: Zhang Peng <peng.zhang1.cn@windriver.com>
---
 src/libopensc/card-coolkey.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/src/libopensc/card-coolkey.c b/src/libopensc/card-coolkey.c
index ff3ffd9a7..e0a5ae774 100644
--- a/src/libopensc/card-coolkey.c
+++ b/src/libopensc/card-coolkey.c
@@ -1684,6 +1684,7 @@ static int coolkey_rsa_op(sc_card_t *card, const u8 * data, size_t datalen,
 	u8 key_number;
 	size_t params_len;
 	u8 buf[MAX_COMPUTE_BUF + 2];
+	size_t buf_len;
 	u8 *buf_out;
 
 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
@@ -1724,8 +1725,6 @@ static int coolkey_rsa_op(sc_card_t *card, const u8 * data, size_t datalen,
 		ushort2bebytes(params.init.buf_len, 0);
 	} else {
 		/* The data fits in APDU. Copy it to the params object */
-		size_t buf_len;
-
 		params.init.location = COOLKEY_CRYPT_LOCATION_APDU;
 
 		params_len = sizeof(params.init) + datalen;
@@ -1745,6 +1744,7 @@ static int coolkey_rsa_op(sc_card_t *card, const u8 * data, size_t datalen,
 	if (r < 0) {
 		goto done;
 	}
+	buf_len = crypt_out_len_p;
 
 	if (datalen > MAX_COMPUTE_BUF) {
 		u8 len_buf[2];
@@ -1763,7 +1763,12 @@ static int coolkey_rsa_op(sc_card_t *card, const u8 * data, size_t datalen,
 					priv->nonce, sizeof(priv->nonce));
 
 	} else {
-		size_t out_length = bebytes2ushort(buf);
+		size_t out_length;
+		if (buf_len < 2) {
+			r = SC_ERROR_WRONG_LENGTH;
+			goto done;
+		}
+		out_length = bebytes2ushort(buf);
 		if (out_length > sizeof buf - 2) {
 			r = SC_ERROR_WRONG_LENGTH;
 			goto done;
--
2.34.1
