Origin: https://github.com/OpenSC/OpenSC/commit/440ca666eff10cc7011901252d20f3fc4ea23651
From: Jakub Jelen <jjelen@redhat.com>
Date: Thu, 17 Aug 2023 13:41:36 +0200
Subject: setcos: Avoid buffer underflow

Thanks oss-fuzz

https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=60672
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/pkcs15init/pkcs15-setcos.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/pkcs15init/pkcs15-setcos.c b/src/pkcs15init/pkcs15-setcos.c
index 1b56afe6d9..1907b47f9d 100644
--- a/src/pkcs15init/pkcs15-setcos.c
+++ b/src/pkcs15init/pkcs15-setcos.c
@@ -346,6 +346,10 @@
 
 	/* Replace the path of instantiated key template by the path from the object data. */
         memcpy(&file->path, &key_info->path, sizeof(file->path));
+	if (file->path.len < 2) {
+		sc_file_free(file);
+		LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid path");
+	}
         file->id = file->path.value[file->path.len - 2] * 0x100
 		+ file->path.value[file->path.len - 1];
 

