From 5df913b7f57ad89b9832555d24c08d23a534311e Mon Sep 17 00:00:00 2001
From: Jakub Jelen <jjelen@redhat.com>
Date: Tue, 8 Dec 2020 14:37:39 +0100
Subject: [PATCH] tcos: Check bounds in insert_pin()

Thanks oss-fuzz

https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28383
---
 src/libopensc/pkcs15-tcos.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/libopensc/pkcs15-tcos.c b/src/libopensc/pkcs15-tcos.c
index feeb7eb39d..74ae0cb92f 100644
--- a/src/libopensc/pkcs15-tcos.c
+++ b/src/libopensc/pkcs15-tcos.c
@@ -242,13 +242,13 @@ static int insert_pin(
 			"Searching for PIN-Ref %02X\n", pin_reference);
 		while ((r = sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR)) > 0) {
 			int found = 0, fbz = -1;
-			if (buf[0] != 0xA0)
+			if (r < 2 || buf[0] != 0xA0)
 				continue;
-			for (i = 2; i < buf[1] + 2; i += 2 + buf[i + 1]) {
+			for (i = 2; i < buf[1] + 2 && (i + 2) < r; i += 2 + buf[i + 1]) {
 				if (buf[i] == 0x83 && buf[i + 1] == 1 && buf[i + 2] == pin_reference) {
 					++found;
 				}
-				if (buf[i] == 0x90) {
+				if (buf[i] == 0x90 && (i + 1 + buf[i + 1]) < r) {
 					fbz = buf[i + 1 + buf[i + 1]];
 				}
 			}
