Origin: https://github.com/OpenSC/OpenSC/commit/245efe608d083fd4e4ec96793fdefd218e26fde7
From: Jakub Jelen <jjelen@redhat.com>
Date: Thu, 17 Aug 2023 13:54:42 +0200
Subject: pkcs15: Avoid buffer overflow when getting last update

Thanks oss-fuzz

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

CVE: CVE-2023-40661
Upstream-Status: Backport [https://salsa.debian.org/opensc-team/opensc/-/commit/8026fb4ca0ed53d970c6c497252eb264d4192d50]
Signed-off-by: Virendra Thakur <virendrak@kpit.com>
Comment: Hunk refreshed based on codebase.

---
 src/libopensc/pkcs15.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/src/libopensc/pkcs15.c b/src/libopensc/pkcs15.c
index eb7fc6afcd..4215b733a8 100644
--- a/src/libopensc/pkcs15.c
+++ b/src/libopensc/pkcs15.c
@@ -528,7 +528,7 @@
 	struct sc_context *ctx  = p15card->card->ctx;
 	struct sc_file *file = NULL;
 	struct sc_asn1_entry asn1_last_update[C_ASN1_LAST_UPDATE_SIZE];
-	unsigned char *content, last_update[32];
+        unsigned char *content, last_update[32] = {0};
 	size_t lupdate_len = sizeof(last_update) - 1;
 	int r, content_len;
 	size_t size;
@@ -564,9 +564,11 @@
 	if (r < 0)
 		return NULL;
 
-	p15card->tokeninfo->last_update.gtime = strdup((char *)last_update);
-	if (!p15card->tokeninfo->last_update.gtime)
-		return NULL;
+        if (asn1_last_update[0].flags & SC_ASN1_PRESENT) {
+                p15card->tokeninfo->last_update.gtime = strdup((char *)last_update);
+                if (!p15card->tokeninfo->last_update.gtime)
+                        return NULL;
+        }
 done:
 	sc_log(ctx, "lastUpdate.gtime '%s'", p15card->tokeninfo->last_update.gtime);
 	return p15card->tokeninfo->last_update.gtime;

