Origin: https://github.com/OpenSC/OpenSC/commit/c449a181a6988cc1e8dc8764d23574e48cdc3fa6
From: =?UTF-8?q?Veronika=20Hanul=C3=ADkov=C3=A1?= <vhanulik@redhat.com>
Date: Mon, 19 Jun 2023 16:14:51 +0200
Subject: pkcs15-cflex: check path length to prevent underflow

Thanks OSS-Fuzz
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=58932
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-cflex.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/src/pkcs15init/pkcs15-cflex.c b/src/pkcs15init/pkcs15-cflex.c
index d06568073d..ce1d48e62c 100644
--- a/src/pkcs15init/pkcs15-cflex.c
+++ b/src/pkcs15init/pkcs15-cflex.c
@@ -56,6 +56,9 @@
         int             r = 0;
         /* Select the parent DF */
         path = df->path;
+		if (path.len < 2) {
+			return SC_ERROR_INVALID_ARGUMENTS;
+		}
         path.len -= 2;
         r = sc_select_file(p15card->card, &path, &parent);
         if (r < 0)

