From b28a3cef416fcfb92fbb9ea7fd3c71df52c6c9fc Mon Sep 17 00:00:00 2001
From: Jakub Jelen <jjelen@redhat.com>
Date: Mon, 12 Aug 2024 19:02:14 +0200
Subject: [PATCH] openpgp: Do not accept non-matching key responses

When generating RSA key pair using PKCS#15 init, the driver could accept
responses relevant to ECC keys, which made further processing in the
pkcs15-init failing/accessing invalid parts of structures.

Thanks oss-fuzz!

https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=71010

Signed-off-by: Jakub Jelen <jjelen@redhat.com>

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

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

diff --git a/src/libopensc/card-openpgp.c b/src/libopensc/card-openpgp.c
index fad32f0ce..f99ec0db9 100644
--- a/src/libopensc/card-openpgp.c
+++ b/src/libopensc/card-openpgp.c
@@ -2877,6 +2877,9 @@ pgp_parse_and_set_pubkey_output(sc_card_t *card, u8* data, size_t data_len,
 
 		/* RSA modulus */
 		if (tag == 0x0081) {
+			if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA) {
+				LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
+			}
 			if ((BYTES4BITS(key_info->u.rsa.modulus_len) < len)  /* modulus_len is in bits */
 				|| key_info->u.rsa.modulus == NULL) {
 
@@ -2892,6 +2895,9 @@ pgp_parse_and_set_pubkey_output(sc_card_t *card, u8* data, size_t data_len,
 		}
 		/* RSA public exponent */
 		else if (tag == 0x0082) {
+			if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA) {
+				LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
+			}
 			if ((BYTES4BITS(key_info->u.rsa.exponent_len) < len)  /* exponent_len is in bits */
 				|| key_info->u.rsa.exponent == NULL) {
 
@@ -2907,6 +2913,10 @@ pgp_parse_and_set_pubkey_output(sc_card_t *card, u8* data, size_t data_len,
 		}
 		/* ECC public key */
 		else if (tag == 0x0086) {
+			if (key_info->algorithm != SC_OPENPGP_KEYALGO_ECDSA &&
+					key_info->algorithm != SC_OPENPGP_KEYALGO_ECDH) {
+				LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
+			}
 			/* set the output data */
 			/* len is ecpoint length + format byte
 			 * see section 7.2.14 of 3.3.1 specs */
--
2.34.1
