From: pwpiwi <pwpiwi@users.noreply.github.com>
Date: Tue, 24 Oct 2017 05:49:14 +0000 (+0200)
Subject: fix hf mf sim:
X-Git-Tag: v3.1.0~132^2~1
X-Git-Url: https://git.zerfleddert.de/cgi-bin/gitweb.cgi/proxmark3-svn/commitdiff_plain/b35e04a7c6a8b6c99fcdc8f45e387437cbae4f08

fix hf mf sim:
* more timing fixes
* correctly determine correction bit (taken from iceman's fork)
* add checking of Access Conditions for Read command
* never allow reading KeyA
---

diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c
index 026b177a..af810b74 100644
--- a/armsrc/iso14443a.c
+++ b/armsrc/iso14443a.c
@@ -900,11 +900,11 @@ static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int
 }
 
 
-static int EmSend4bitEx(uint8_t resp, bool correctionNeeded);
+static int EmSend4bitEx(uint8_t resp);
 int EmSend4bit(uint8_t resp);
-static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, bool correctionNeeded, uint8_t *par);
-int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool correctionNeeded);
-int EmSendPrecompiledCmd(tag_response_info_t *response_info, bool correctionNeeded);
+static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
+int EmSendCmdEx(uint8_t *resp, uint16_t respLen);
+int EmSendPrecompiledCmd(tag_response_info_t *response_info);
 
 
 static bool prepare_tag_modulation(tag_response_info_t* response_info, size_t max_buffer_size) {
@@ -1138,7 +1138,7 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data)
 		} else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x95) {	// Received a SELECT (cascade 2)
 			p_response = &responses[4]; order = 30;
 		} else if(receivedCmd[0] == 0x30) {	// Received a (plain) READ
-			EmSendCmdEx(data+(4*receivedCmd[1]),16,false);
+			EmSendCmdEx(data+(4*receivedCmd[1]),16);
 			// Dbprintf("Read request from reader: %x %x",receivedCmd[0],receivedCmd[1]);
 			// We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
 			p_response = NULL;
@@ -1231,7 +1231,7 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data)
 		cmdsRecvd++;
 
 		if (p_response != NULL) {
-			EmSendPrecompiledCmd(p_response, receivedCmd[0] == 0x52);
+			EmSendPrecompiledCmd(p_response);
 		}
 		
 		if (!tracing) {
@@ -1413,12 +1413,6 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity)
 	int analogCnt = 0;
 	int analogAVG = 0;
 
-	// Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
-	// only, since we are receiving, not transmitting).
-	// Signal field is off with the appropriate LED
-	LED_D_OFF();
-	FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
-
 	// Set ADC to read field strength
 	AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
 	AT91C_BASE_ADC->ADC_MR =
@@ -1429,12 +1423,23 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity)
 	// start ADC
 	AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
 	
-	// Now run a 'software UART' on the stream of incoming samples.
+	// Run a 'software UART' on the stream of incoming samples.
 	UartInit(received, parity);
 
-	// Clear RXRDY:
-    uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
-	
+	// Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN
+	do {
+		if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
+			AT91C_BASE_SSC->SSC_THR = SEC_F;
+			uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; (void) b;
+		}
+	} while (GetCountSspClk() < LastTimeProxToAirStart + LastProxToAirDuration + (FpgaSendQueueDelay>>3));
+
+	// Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
+	// only, since we are receiving, not transmitting).
+	// Signal field is off with the appropriate LED
+	LED_D_OFF();
+	FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
+
 	for(;;) {
 		WDT_HIT();
 
@@ -1460,7 +1465,7 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity)
 
 		// receive and test the miller decoding
         if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
-            b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
+            uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
 			if(MillerDecoding(b, 0)) {
 				*len = Uart.len;
 				EmLogTraceReader();
@@ -1472,18 +1477,27 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity)
 }
 
 
-static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen, bool correctionNeeded)
+static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen)
 {
 	uint8_t b;
 	uint16_t i = 0;
-	
+	bool correctionNeeded;
+
 	// Modulate Manchester
 	FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
 
 	// include correction bit if necessary
-	if (Uart.parityBits & 0x01) {
-		correctionNeeded = true;
+	if (Uart.bitCount == 7)
+	{
+		// Short tags (7 bits) don't have parity, determine the correct value from MSB
+		correctionNeeded = Uart.output[0] & 0x40;
+	}
+	else
+	{
+		// Look at the last parity bit
+		correctionNeeded = Uart.parity[(Uart.len-1)/8] & (0x80 >> ((Uart.len-1) & 7));
 	}
+
 	if(correctionNeeded) {
 		// 1236, so correction bit needed
 		i = 0;
@@ -1517,23 +1531,13 @@ static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen, bool correctionNe
 		}
 	}
 
-	// Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
-	uint8_t fpga_queued_bits = FpgaSendQueueDelay >> 3;
-	for (i = 0; i < fpga_queued_bits/8; ) {
-		if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
-			AT91C_BASE_SSC->SSC_THR = SEC_F;
-			FpgaSendQueueDelay = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
-			i++;
-		}
-	}
-
 	return 0;
 }
 
 
-static int EmSend4bitEx(uint8_t resp, bool correctionNeeded){
+static int EmSend4bitEx(uint8_t resp){
 	Code4bitAnswerAsTag(resp);
-	int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
+	int res = EmSendCmd14443aRaw(ToSend, ToSendMax);
 	// do the tracing for the previous reader request and this tag answer:
 	EmLogTraceTag(&resp, 1, NULL, LastProxToAirDuration);
 	return res;
@@ -1541,40 +1545,40 @@ static int EmSend4bitEx(uint8_t resp, bool correctionNeeded){
 
 
 int EmSend4bit(uint8_t resp){
-	return EmSend4bitEx(resp, false);
+	return EmSend4bitEx(resp);
 }
 
 
-static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, bool correctionNeeded, uint8_t *par){
+static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, uint8_t *par){
 	CodeIso14443aAsTagPar(resp, respLen, par);
-	int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
+	int res = EmSendCmd14443aRaw(ToSend, ToSendMax);
 	// do the tracing for the previous reader request and this tag answer:
 	EmLogTraceTag(resp, respLen, par, LastProxToAirDuration);
 	return res;
 }
 
 
-int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool correctionNeeded){
+int EmSendCmdEx(uint8_t *resp, uint16_t respLen){
 	uint8_t par[MAX_PARITY_SIZE];
 	GetParity(resp, respLen, par);
-	return EmSendCmdExPar(resp, respLen, correctionNeeded, par);
+	return EmSendCmdExPar(resp, respLen, par);
 }
 
 
 int EmSendCmd(uint8_t *resp, uint16_t respLen){
 	uint8_t par[MAX_PARITY_SIZE];
 	GetParity(resp, respLen, par);
-	return EmSendCmdExPar(resp, respLen, false, par);
+	return EmSendCmdExPar(resp, respLen, par);
 }
 
 
 int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par){
-	return EmSendCmdExPar(resp, respLen, false, par);
+	return EmSendCmdExPar(resp, respLen, par);
 }
 
 
-int EmSendPrecompiledCmd(tag_response_info_t *response_info, bool correctionNeeded) {
-	int ret = EmSendCmd14443aRaw(response_info->modulation, response_info->modulation_n, correctionNeeded);
+int EmSendPrecompiledCmd(tag_response_info_t *response_info) {
+	int ret = EmSendCmd14443aRaw(response_info->modulation, response_info->modulation_n);
 	// do the tracing for the previous reader request and this tag answer:
 	EmLogTraceTag(response_info->response, response_info->response_n, &(response_info->par), response_info->ProxToAirDuration);
 	return ret;
diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h
index 8bd80510..8796edf5 100644
--- a/armsrc/iso14443a.h
+++ b/armsrc/iso14443a.h
@@ -41,10 +41,10 @@ extern void ReaderMifare(bool first_try);
 
 extern int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity);
 extern int EmSendCmd(uint8_t *resp, uint16_t respLen);
-extern int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool correctionNeeded);
+extern int EmSendCmdEx(uint8_t *resp, uint16_t respLen);
 extern int EmSend4bit(uint8_t resp);
 extern int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
-extern int EmSendPrecompiledCmd(tag_response_info_t *response_info, bool correctionNeeded);
+extern int EmSendPrecompiledCmd(tag_response_info_t *response_info);
 
 extern bool prepare_allocated_tag_modulation(tag_response_info_t *response_info, uint8_t **buffer, size_t *buffer_size);
 
diff --git a/armsrc/mifaresim.c b/armsrc/mifaresim.c
index 91f45efd..1fdf99d6 100644
--- a/armsrc/mifaresim.c
+++ b/armsrc/mifaresim.c
@@ -41,6 +41,132 @@
 
 #define cardSTATE_TO_IDLE() { cardSTATE = MFEMUL_IDLE; LED_B_OFF(); LED_C_OFF(); }
 
+#define AC_DATA_READ             0
+#define AC_DATA_WRITE            1
+#define AC_DATA_INC				 2
+#define AC_DATA_DEC_TRANS_REST	 3
+#define AC_KEYA_READ             0
+#define AC_KEYA_WRITE            1
+#define AC_KEYB_READ             2
+#define AC_KEYB_WRITE            3
+#define AC_AC_READ               4
+#define AC_AC_WRITE              5
+
+#define AUTHKEYA                 0
+#define AUTHKEYB                 1
+#define AUTHKEYNONE              0xff
+
+
+static bool IsTrailerAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
+	uint8_t sector_trailer[16];
+	emlGetMem(sector_trailer, blockNo, 1);
+	uint8_t AC = ((sector_trailer[7] >> 5) & 0x04)
+	           | ((sector_trailer[8] >> 2) & 0x02)
+			   | ((sector_trailer[8] >> 7) & 0x01);
+	switch (action) {
+		case AC_KEYA_READ: {
+			return false;
+			break;
+		}
+		case AC_KEYA_WRITE: {
+			return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x01)) 
+			     || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
+			break;
+		}
+		case AC_KEYB_READ: {
+			return (keytype == AUTHKEYA && (AC == 0x00 || AC == 0x02 || AC == 0x01));
+			break;
+		}
+		case AC_KEYB_WRITE: {
+			return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x04))
+			     || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
+			break;
+		}
+		case AC_AC_READ: {
+			return ((keytype == AUTHKEYA)
+			     || (keytype == AUTHKEYB && !(AC == 0x00 || AC == 0x02 || AC == 0x01)));
+			break;
+		}
+		case AC_AC_WRITE: {
+			return ((keytype == AUTHKEYA && (AC == 0x01))
+			     || (keytype == AUTHKEYB && (AC == 0x03 || AC == 0x05)));
+			break;
+		}
+		default: return false;
+	}
+}
+
+
+static bool IsDataAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action)
+{
+	uint8_t sector_trailer[16];
+	emlGetMem(sector_trailer, SectorTrailer(blockNo), 1);
+
+	uint8_t sector_block;
+	if (blockNo < 32*4) {
+		sector_block = blockNo & 0x03;
+	} else {
+		sector_block = (blockNo & 0x0f) / 5;
+	}
+
+	uint8_t AC;
+	switch (sector_block) {
+		case 0x00: {
+			AC = ((sector_trailer[7] >> 2) & 0x04)
+			   | ((sector_trailer[8] << 1) & 0x02)
+			   | ((sector_trailer[8] >> 4) & 0x01);
+			break;
+		}
+		case 0x01: {
+			AC = ((sector_trailer[7] >> 3) & 0x04)
+			   | ((sector_trailer[8] >> 0) & 0x02)
+			   | ((sector_trailer[8] >> 5) & 0x01);
+			break;
+		}
+		case 0x02: {
+			AC = ((sector_trailer[7] >> 4) & 0x04)
+			   | ((sector_trailer[8] >> 1) & 0x02)
+			   | ((sector_trailer[8] >> 6) & 0x01);
+			break;
+		}
+		default: 
+			return false;
+	}
+	
+	switch (action) {
+		case AC_DATA_READ: {
+			return ((keytype == AUTHKEYA && !(AC == 0x03 || AC == 0x05 || AC == 0x07))
+			     || (keytype == AUTHKEYB && !(AC == 0x07)));
+			break;
+		}
+		case AC_DATA_WRITE: {
+			return ((keytype == AUTHKEYA && (AC == 0x00))
+			     || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x04 || AC == 0x06 || AC == 0x03)));
+			break;
+		}
+		case AC_DATA_INC: {
+			return ((keytype == AUTHKEYA && (AC == 0x00))
+			     || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06)));
+			break;
+		}
+		case AC_DATA_DEC_TRANS_REST: {
+			return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x06 || AC == 0x01))
+			     || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06 || AC == 0x01)));
+			break;
+		}
+	}
+	
+	return false;
+}
+
+
+static bool IsAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
+	if (IsSectorTrailer(blockNo)) {
+		return IsTrailerAccessAllowed(blockNo, keytype, action);
+	} else {
+		return IsDataAccessAllowed(blockNo, keytype, action);
+	}
+}
 
 
 static void MifareSimInit(uint8_t flags, uint8_t *datain, tag_response_info_t **responses, uint32_t *cuid, uint8_t *uid_len) {
@@ -155,7 +281,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 	uint32_t cuid = 0;
 	uint8_t cardWRBL = 0;
 	uint8_t cardAUTHSC = 0;
-	uint8_t cardAUTHKEY = 0xff;  // no authentication
+	uint8_t cardAUTHKEY = AUTHKEYNONE;  // no authentication
 	uint32_t cardRr = 0;
 	//uint32_t rn_enc = 0;
 	uint32_t ans = 0;
@@ -244,11 +370,11 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 
 		// WUPA in HALTED state or REQA or WUPA in any other state
 		if (receivedCmd_len == 1 && ((receivedCmd[0] == ISO14443A_CMD_REQA && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == ISO14443A_CMD_WUPA)) {
-			EmSendPrecompiledCmd(&responses[ATQA], (receivedCmd[0] == ISO14443A_CMD_WUPA));
+			EmSendPrecompiledCmd(&responses[ATQA]);
 
 			// init crypto block
 			crypto1_destroy(pcs);
-			cardAUTHKEY = 0xff;
+			cardAUTHKEY = AUTHKEYNONE;
 			if (flags & FLAG_RANDOM_NONCE) {
 				nonce = prand();
 			}
@@ -268,7 +394,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 				// select all - 0x93 0x20
 				if (receivedCmd_len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && receivedCmd[1] == 0x20)) {
 					if (MF_DBGLEVEL >= 4)	Dbprintf("SELECT ALL CL1 received");
-					EmSendPrecompiledCmd(&responses[UIDBCC1], false);
+					EmSendPrecompiledCmd(&responses[UIDBCC1]);
 					break;
 				}
 				// select card - 0x93 0x70 ...
@@ -276,12 +402,12 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 						(receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], responses[UIDBCC1].response, 4) == 0)) {
 					if (MF_DBGLEVEL >= 4) Dbprintf("SELECT CL1 %02x%02x%02x%02x received",receivedCmd[2],receivedCmd[3],receivedCmd[4],receivedCmd[5]);
 					if (uid_len == 4) {
-						EmSendPrecompiledCmd(&responses[SAKfinal], false);
+						EmSendPrecompiledCmd(&responses[SAKfinal]);
 						LED_B_ON();
 						cardSTATE = MFEMUL_WORK;
 						break;
 					} else if (uid_len == 7) {
-						EmSendPrecompiledCmd(&responses[SAK1], false);
+						EmSendPrecompiledCmd(&responses[SAK1]);
 						cardSTATE	= MFEMUL_SELECT2;
 						break;
 					}
@@ -293,7 +419,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 				// select all cl2 - 0x95 0x20
 				if (receivedCmd_len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && receivedCmd[1] == 0x20)) {
 					if (MF_DBGLEVEL >= 4)	Dbprintf("SELECT ALL CL2 received");
-					EmSendPrecompiledCmd(&responses[UIDBCC2], false);
+					EmSendPrecompiledCmd(&responses[UIDBCC2]);
 					break;
 				}
 				// select cl2 card - 0x95 0x70 xxxxxxxxxxxx
@@ -301,7 +427,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 						(receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], responses[UIDBCC2].response, 4) == 0)) {
 					if (uid_len == 7) {
 						if (MF_DBGLEVEL >= 4) Dbprintf("SELECT CL2 %02x%02x%02x%02x received",receivedCmd[2],receivedCmd[3],receivedCmd[4],receivedCmd[5]);
-						EmSendPrecompiledCmd(&responses[SAKfinal], false);
+						EmSendPrecompiledCmd(&responses[SAKfinal]);
 						LED_B_ON();
 						cardSTATE = MFEMUL_WORK;
 						break;
@@ -314,7 +440,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 				if (receivedCmd_len != 4) {	// all commands must have exactly 4 bytes
 					break;
 				}
-				bool encrypted_data = (cardAUTHKEY != 0xFF) ;
+				bool encrypted_data = (cardAUTHKEY != AUTHKEYNONE) ;
 				if (encrypted_data) {
 					// decrypt seqence
 					mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
@@ -371,10 +497,24 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 					}
 				}
 				if (receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK) {
+					uint8_t blockNo = receivedCmd_dec[1];
 					if (MF_DBGLEVEL >= 4) {
-						Dbprintf("Reader reading block %d (0x%02x)",receivedCmd_dec[1],receivedCmd_dec[1]);
+						Dbprintf("Reader reading block %d (0x%02x)", blockNo, blockNo);
+					}
+					emlGetMem(response, blockNo, 1);
+					if (IsSectorTrailer(blockNo)) {
+						memset(response, 0x00, 6); 	// keyA can never be read
+						if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_KEYB_READ)) {
+							memset(response+10, 0x00, 6); 	// keyB cannot be read
+						}
+						if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_AC_READ)) {
+							memset(response+6, 0x00, 4); 	// AC bits cannot be read
+						}
+					} else {
+						if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_DATA_READ)) {
+							memset(response, 0x00, 16);		// datablock cannot be read
+						}
 					}
-					emlGetMem(response, receivedCmd_dec[1], 1);
 					AppendCrc14443a(response, 16);
 					mf_crypto1_encrypt(pcs, response, 18, response_par);
 					EmSendCmdPar(response, 18, response_par);
@@ -386,21 +526,23 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 					break;
 				}
 				if (receivedCmd_dec[0] == ISO14443A_CMD_WRITEBLOCK) {
-					if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0xA0 write block %d (%02x)",receivedCmd_dec[1],receivedCmd_dec[1]);
+					uint8_t blockNo = receivedCmd_dec[1];
+					if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0xA0 write block %d (%02x)", blockNo, blockNo);
 					EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
-					cardWRBL = receivedCmd_dec[1];
+					cardWRBL = blockNo;
 					cardSTATE = MFEMUL_WRITEBL2;
 					break;
 				}
 				if (receivedCmd_dec[0] == MIFARE_CMD_INC || receivedCmd_dec[0] == MIFARE_CMD_DEC || receivedCmd_dec[0] == MIFARE_CMD_RESTORE) {
-					if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)",receivedCmd_dec[0],receivedCmd_dec[1],receivedCmd_dec[1]);
-					if (emlCheckValBl(receivedCmd_dec[1])) {
+					uint8_t blockNo = receivedCmd_dec[1];
+					if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)",receivedCmd_dec[0], blockNo, blockNo);
+					if (emlCheckValBl(blockNo)) {
 						if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate on block, but emlCheckValBl failed, nacking");
 						EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
 						break;
 					}
 					EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
-					cardWRBL = receivedCmd_dec[1];
+					cardWRBL = blockNo;
 					if (receivedCmd_dec[0] == MIFARE_CMD_INC)
 						cardSTATE = MFEMUL_INTREG_INC;
 					if (receivedCmd_dec[0] == MIFARE_CMD_DEC)
@@ -410,7 +552,8 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 					break;
 				}
 				if (receivedCmd_dec[0] == MIFARE_CMD_TRANSFER) {
-					if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x transfer block %d (%02x)",receivedCmd_dec[0],receivedCmd_dec[1],receivedCmd_dec[1]);
+					uint8_t blockNo = receivedCmd_dec[1];
+					if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x transfer block %d (%02x)",receivedCmd_dec[0], blockNo, blockNo);
 					if (emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd_dec[1]))
 						EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
 					else
@@ -508,20 +651,20 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 				// test if auth OK
 				if (cardRr != prng_successor(nonce, 64)){
 					if (MF_DBGLEVEL >= 2) Dbprintf("AUTH FAILED for sector %d with key %c. cardRr=%08x, succ=%08x",
-							cardAUTHSC, cardAUTHKEY == 0 ? 'A' : 'B',
+							cardAUTHSC, cardAUTHKEY == AUTHKEYA ? 'A' : 'B',
 							cardRr, prng_successor(nonce, 64));
 					// Shouldn't we respond anything here?
 					// Right now, we don't nack or anything, which causes the
 					// reader to do a WUPA after a while. /Martin
 					// -- which is the correct response. /piwi
-					cardAUTHKEY = 0xff;	// not authenticated
+					cardAUTHKEY = AUTHKEYNONE;	// not authenticated
 					cardSTATE_TO_IDLE();
 					break;
 				}
 				ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
 				num_to_bytes(ans, 4, rAUTH_AT);
 				EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
-				if (MF_DBGLEVEL >= 4)	Dbprintf("AUTH COMPLETED for sector %d with key %c.", cardAUTHSC, cardAUTHKEY == 0 ? 'A' : 'B');
+				if (MF_DBGLEVEL >= 4)	Dbprintf("AUTH COMPLETED for sector %d with key %c.", cardAUTHSC, cardAUTHKEY == AUTHKEYA ? 'A' : 'B');
 				LED_C_ON();
 				cardSTATE = MFEMUL_WORK;
 				break;
@@ -530,8 +673,24 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *
 				if (receivedCmd_len == 18) {
 					mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
 					if (HasValidCRC(receivedCmd_dec, receivedCmd_len)) {
+						if (IsSectorTrailer(cardWRBL)) {
+							emlGetMem(response, cardWRBL, 1);
+							if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYA_WRITE)) {
+								memcpy(receivedCmd_dec, response, 6);	// don't change KeyA
+							}
+							if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYB_WRITE)) {
+								memcpy(receivedCmd_dec+10, response+10, 6);	// don't change KeyA
+							}
+							if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_AC_WRITE)) {
+								memcpy(receivedCmd_dec+6, response+6, 4);	// don't change AC bits
+							}
+						} else {
+							if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_DATA_WRITE)) {
+								memcpy(receivedCmd_dec, response, 16);	// don't change anything
+							}
+						}
 						emlSetMem(receivedCmd_dec, cardWRBL, 1);
-						EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
+						EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));	// always ACK?
 						cardSTATE = MFEMUL_WORK;
 						break;
 					}
diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c
index e5ef6c19..38ca934a 100644
--- a/armsrc/mifareutil.c
+++ b/armsrc/mifareutil.c
@@ -9,13 +9,15 @@
 // Work with mifare cards.
 //-----------------------------------------------------------------------------
 
-#include <string.h>
 #include "mifareutil.h"
+
+#include <string.h>
+#include <stdbool.h>
+
 #include "proxmark3.h"
 #include "apps.h"
 #include "util.h"
 #include "parity.h"
-
 #include "iso14443crc.h"
 #include "iso14443a.h"
 #include "crapto1/crapto1.h"
@@ -585,6 +587,19 @@ uint8_t FirstBlockOfSector(uint8_t sectorNo)
 		
 }
 
+uint8_t SectorTrailer(uint8_t blockNo)
+{
+	if (blockNo < 32*4) {
+		return (blockNo | 0x03);
+	} else {
+		return (blockNo | 0x0f);
+	}
+}
+
+bool IsSectorTrailer(uint8_t blockNo)
+{
+	return (blockNo == SectorTrailer(blockNo));
+}
 
 // work with emulator memory
 void emlSetMem(uint8_t *data, int blockNum, int blocksCount) {
diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h
index 645d0e7d..c34dc8f4 100644
--- a/armsrc/mifareutil.h
+++ b/armsrc/mifareutil.h
@@ -12,6 +12,9 @@
 #ifndef __MIFAREUTIL_H
 #define __MIFAREUTIL_H
 
+#include <stdint.h>
+#include <stdbool.h>
+
 #include "crapto1/crapto1.h"
 #include "usb_cdc.h"
 
@@ -75,6 +78,8 @@ uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data);
 // Mifare memory structure
 uint8_t NumBlocksPerSector(uint8_t sectorNo);
 uint8_t FirstBlockOfSector(uint8_t sectorNo);
+bool IsSectorTrailer(uint8_t blockNo);
+uint8_t SectorTrailer(uint8_t blockNo);
 
 // emulator functions
 void emlClearMem(void);
diff --git a/fpga/fpga_hf.bit b/fpga/fpga_hf.bit
index b9f2e629..229151df 100644
Binary files a/fpga/fpga_hf.bit and b/fpga/fpga_hf.bit differ
diff --git a/fpga/hi_iso14443a.v b/fpga/hi_iso14443a.v
index ccb51d8f..b1b7b141 100644
--- a/fpga/hi_iso14443a.v
+++ b/fpga/hi_iso14443a.v
@@ -311,9 +311,13 @@ reg [3:0] sub_carrier_cnt;
 
 // The ARM must not send too early, otherwise the mod_sig_buf will overflow, therefore signal that we are ready
 // with fdt_indicator. The mod_sig_buf can buffer 29 excess data bits, i.e. a maximum delay of 29 * 16 = 464 adc_clk ticks.
-// fdt_indicator could appear at ssp_din after 1 tick, the transfer needs 16 ticks, the ARM can send 128 ticks later.
-// 1128 - 464 - 1 - 128 - 8 = 535
-`define FDT_INDICATOR_COUNT 11'd535
+// fdt_indicator is assigned to sendbit after at least 1 tick, the transfer to ARM needs minimum 8 ticks. Response from
+// ARM could appear at ssp_dout 8 ticks later.
+// 1128 - 464 - 1 - 8 - 8 = 647
+`define FDT_INDICATOR_COUNT 11'd647
+// Note: worst case, assignment to sendbit takes 15 ticks more, and transfer to ARM needs 7*16 = 112 ticks more.
+//       When the ARM's response then appears, the fdt_count is already 647 + 15 + 112 = 774, which still allows the ARM a possible
+//       response window of 1128 - 774 = 354 ticks. 
 
 // reset on a pause in listen mode. I.e. the counter starts when the pause is over:
 assign fdt_reset = ~after_hysteresis && mod_type == `TAGSIM_LISTEN;