From 645f678af24fc1e0f1559e0384f57f8fd35836b4 Mon Sep 17 00:00:00 2001
From: Jakub Jelen <jjelen@redhat.com>
Date: Fri, 21 Jul 2017 11:30:47 +0200
Subject: [PATCH 1/4] cac: Make the retransmitted APDU valid by restoring the
 resplen

---
 src/libopensc/card-cac.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/libopensc/card-cac.c b/src/libopensc/card-cac.c
index ed15ba0a8..47f9aaf0c 100644
--- a/src/libopensc/card-cac.c
+++ b/src/libopensc/card-cac.c
@@ -1106,6 +1106,7 @@ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc
 		r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 		if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86)   {
 			apdu.p2 = 0x00;
+			apdu.resplen = sizeof(buf);
 			if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS)
 				r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 		}

From a57407a5257b24edf313a4839c523a19cd8b0dc5 Mon Sep 17 00:00:00 2001
From: Jakub Jelen <jjelen@redhat.com>
Date: Fri, 21 Jul 2017 13:09:14 +0200
Subject: [PATCH 2/4] cac: Check SWs for all the APDUs and report the errors to
 underlying layers

---
 src/libopensc/card-cac.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/src/libopensc/card-cac.c b/src/libopensc/card-cac.c
index 47f9aaf0c..f3b64a33d 100644
--- a/src/libopensc/card-cac.c
+++ b/src/libopensc/card-cac.c
@@ -390,9 +390,7 @@ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2,
 		goto err;
 	}
 
-	if (apdu.sw1 == 0x61) {
-		r = sc_check_sw(card, apdu.sw1, apdu.sw2);
-	}
+	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 
 	if (r < 0) {
 		sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error ");
diff -up OpenSC-777e2a3751e3f6d53f056c98e9e20e42af674fb1/src/libopensc/card-cac.c.old OpenSC-777e2a3751e3f6d53f056c98e9e20e42af674fb1/src/libopensc/card-cac.c
--- OpenSC-777e2a3751e3f6d53f056c98e9e20e42af674fb1/src/libopensc/card-cac.c.old	2017-12-19 10:39:08.662925868 +0100
+++ OpenSC-777e2a3751e3f6d53f056c98e9e20e42af674fb1/src/libopensc/card-cac.c	2017-12-19 10:39:58.665293224 +0100
@@ -450,6 +450,10 @@ static int cac_read_file(sc_card_t *card
 		if (r < 0) {
 			goto fail;
 		}
+		if (len == 0) {
+			r = SC_ERROR_FILE_NOT_FOUND;
+			goto fail;
+		}
 	}
 	*out_len = size;
 	*out_buf = out;
