From f1993dc4e0b33050b8f72a3558ee88b24c4063b2 Mon Sep 17 00:00:00 2001
From: Peter Popovec <popovec.peter@gmail.com>
Date: Tue, 27 Jun 2023 09:50:42 +0200
Subject: [PATCH] myeid: fixed CID 380538  Out-of-bounds read (OVERRUN)

also fixes output buffer size checking
---
 src/libopensc/card-myeid.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/src/libopensc/card-myeid.c b/src/libopensc/card-myeid.c
index 4ee4246840..50e78ff1d8 100644
--- a/src/libopensc/card-myeid.c
+++ b/src/libopensc/card-myeid.c
@@ -1986,18 +1986,20 @@ myeid_enc_dec_sym(struct sc_card *card, const u8 *data, size_t datalen,
 				sc_log(ctx, "Found padding byte %02x", pad_byte);
 				if (pad_byte == 0 || pad_byte > block_size)
 					LOG_FUNC_RETURN(ctx, SC_ERROR_WRONG_PADDING);
-				sdata = priv->sym_plain_buffer + block_size - pad_byte;
+				sdata = priv->sym_plain_buffer + block_size;
 				for (i = 0; i < pad_byte; i++)
-					if (sdata[i] != pad_byte)
+					if (*(--sdata) != pad_byte)
 						LOG_FUNC_RETURN(ctx, SC_ERROR_WRONG_PADDING);
 				return_len = block_size - pad_byte;
 			}
-			*outlen = return_len;
 			/* application can request buffer size or actual buffer size is too small */
-			if (out == NULL)
+			if (out == NULL) {
+				*outlen = return_len;
 				LOG_FUNC_RETURN(ctx, SC_SUCCESS);
+			}
 			if (return_len > *outlen)
 				LOG_FUNC_RETURN(ctx, SC_ERROR_BUFFER_TOO_SMALL);
+			*outlen = return_len;
 			memcpy(out, priv->sym_plain_buffer, return_len);
 			sc_log(ctx, "C_DecryptFinal %zu bytes", *outlen);
 			return SC_SUCCESS;
