text
[RRG-proxmark3.git] / armsrc / mifaresim.c
blob1794d754d54aca00ed0dbde8b12b098ee760c691
1 //-----------------------------------------------------------------------------
2 // Merlok - June 2011, 2012
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
5 //
6 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
7 // at your option, any later version. See the LICENSE.txt file for the text of
8 // the license.
9 //-----------------------------------------------------------------------------
10 // Mifare Classic Card Simulation
11 //-----------------------------------------------------------------------------
13 // Verbose Mode:
14 // DBG_NONE 0
15 // DBG_ERROR 1
16 // DBG_INFO 2
17 // DBG_DEBUG 3
18 // DBG_EXTENDED 4
20 // /!\ Printing Debug message is disrupting emulation,
21 // Only use with caution during debugging
23 #include "mifaresim.h"
25 #include <inttypes.h>
27 #include "iso14443a.h"
28 #include "BigBuf.h"
29 #include "string.h"
30 #include "mifareutil.h"
31 #include "fpgaloader.h"
32 #include "proxmark3_arm.h"
33 #include "cmd.h"
34 #include "protocols.h"
35 #include "appmain.h"
36 #include "util.h"
37 #include "commonutil.h"
38 #include "crc16.h"
39 #include "dbprint.h"
40 #include "ticks.h"
42 static bool IsTrailerAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
43 uint8_t sector_trailer[16];
44 emlGetMem(sector_trailer, blockNo, 1);
45 uint8_t AC = ((sector_trailer[7] >> 5) & 0x04)
46 | ((sector_trailer[8] >> 2) & 0x02)
47 | ((sector_trailer[8] >> 7) & 0x01);
48 switch (action) {
49 case AC_KEYA_READ: {
50 if (DBGLEVEL >= DBG_EXTENDED)
51 Dbprintf("IsTrailerAccessAllowed: AC_KEYA_READ");
52 return false;
54 case AC_KEYA_WRITE: {
55 if (DBGLEVEL >= DBG_EXTENDED)
56 Dbprintf("IsTrailerAccessAllowed: AC_KEYA_WRITE");
57 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x01))
58 || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
60 case AC_KEYB_READ: {
61 if (DBGLEVEL >= DBG_EXTENDED)
62 Dbprintf("IsTrailerAccessAllowed: AC_KEYB_READ");
63 return (keytype == AUTHKEYA && (AC == 0x00 || AC == 0x02 || AC == 0x01));
65 case AC_KEYB_WRITE: {
66 if (DBGLEVEL >= DBG_EXTENDED)
67 Dbprintf("IsTrailerAccessAllowed: AC_KEYB_WRITE");
68 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x01))
69 || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
71 case AC_AC_READ: {
72 if (DBGLEVEL >= DBG_EXTENDED)
73 Dbprintf("IsTrailerAccessAllowed: AC_AC_READ");
74 return ((keytype == AUTHKEYA)
75 || (keytype == AUTHKEYB && !(AC == 0x00 || AC == 0x02 || AC == 0x01)));
77 case AC_AC_WRITE: {
78 if (DBGLEVEL >= DBG_EXTENDED)
79 Dbprintf("IsTrailerAccessAllowed: AC_AC_WRITE");
80 return ((keytype == AUTHKEYA && (AC == 0x01))
81 || (keytype == AUTHKEYB && (AC == 0x03 || AC == 0x05)));
83 default:
84 return false;
88 static bool IsDataAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
90 uint8_t sector_trailer[16];
91 emlGetMem(sector_trailer, SectorTrailer(blockNo), 1);
93 uint8_t sector_block;
94 if (blockNo <= MIFARE_2K_MAXBLOCK) {
95 sector_block = blockNo & 0x03;
96 } else {
97 sector_block = (blockNo & 0x0f) / 5;
100 uint8_t AC;
101 switch (sector_block) {
102 case 0x00: {
103 AC = ((sector_trailer[7] >> 2) & 0x04)
104 | ((sector_trailer[8] << 1) & 0x02)
105 | ((sector_trailer[8] >> 4) & 0x01);
106 if (DBGLEVEL >= DBG_EXTENDED)
107 Dbprintf("IsDataAccessAllowed: case 0x00 - %02x", AC);
108 break;
110 case 0x01: {
111 AC = ((sector_trailer[7] >> 3) & 0x04)
112 | ((sector_trailer[8] >> 0) & 0x02)
113 | ((sector_trailer[8] >> 5) & 0x01);
114 if (DBGLEVEL >= DBG_EXTENDED)
115 Dbprintf("IsDataAccessAllowed: case 0x01 - %02x", AC);
116 break;
118 case 0x02: {
119 AC = ((sector_trailer[7] >> 4) & 0x04)
120 | ((sector_trailer[8] >> 1) & 0x02)
121 | ((sector_trailer[8] >> 6) & 0x01);
122 if (DBGLEVEL >= DBG_EXTENDED)
123 Dbprintf("IsDataAccessAllowed: case 0x02 - %02x", AC);
124 break;
126 default:
127 if (DBGLEVEL >= DBG_EXTENDED)
128 Dbprintf("IsDataAccessAllowed: Error");
129 return false;
132 switch (action) {
133 case AC_DATA_READ: {
134 if (DBGLEVEL >= DBG_EXTENDED)
135 Dbprintf("IsDataAccessAllowed - AC_DATA_READ: OK");
136 return ((keytype == AUTHKEYA && !(AC == 0x03 || AC == 0x05 || AC == 0x07))
137 || (keytype == AUTHKEYB && !(AC == 0x07)));
139 case AC_DATA_WRITE: {
140 if (DBGLEVEL >= DBG_EXTENDED)
141 Dbprintf("IsDataAccessAllowed - AC_DATA_WRITE: OK");
142 return ((keytype == AUTHKEYA && (AC == 0x00))
143 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x04 || AC == 0x06 || AC == 0x03)));
145 case AC_DATA_INC: {
146 if (DBGLEVEL >= DBG_EXTENDED)
147 Dbprintf("IsDataAccessAllowed - AC_DATA_INC: OK");
148 return ((keytype == AUTHKEYA && (AC == 0x00))
149 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06)));
151 case AC_DATA_DEC_TRANS_REST: {
152 if (DBGLEVEL >= DBG_EXTENDED)
153 Dbprintf("AC_DATA_DEC_TRANS_REST: OK");
154 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x06 || AC == 0x01))
155 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06 || AC == 0x01)));
159 return false;
162 static bool IsAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
163 if (IsSectorTrailer(blockNo)) {
164 return IsTrailerAccessAllowed(blockNo, keytype, action);
165 } else {
166 return IsDataAccessAllowed(blockNo, keytype, action);
170 static bool MifareSimInit(uint16_t flags, uint8_t *datain, uint16_t atqa, uint8_t sak, tag_response_info_t **responses, uint32_t *cuid, uint8_t *uid_len, uint8_t **rats, uint8_t *rats_len) {
172 // SPEC: https://www.nxp.com/docs/en/application-note/AN10833.pdf
173 // ATQA
174 static uint8_t rATQA_Mini[] = {0x04, 0x00}; // indicate Mifare classic Mini 4Byte UID
175 static uint8_t rATQA_1k[] = {0x04, 0x00}; // indicate Mifare classic 1k 4Byte UID
176 static uint8_t rATQA_2k[] = {0x04, 0x00}; // indicate Mifare classic 2k 4Byte UID
177 static uint8_t rATQA_4k[] = {0x02, 0x00}; // indicate Mifare classic 4k 4Byte UID
179 // SAK
180 static uint8_t rSAK_Mini = 0x09; // mifare Mini
181 static uint8_t rSAK_1k = 0x08; // mifare 1k
182 static uint8_t rSAK_2k = 0x08; // mifare 2k with RATS support
183 static uint8_t rSAK_4k = 0x18; // mifare 4k
185 static uint8_t rUIDBCC1[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level
186 static uint8_t rUIDBCC1b4[] = {0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level, last 4 bytes
187 static uint8_t rUIDBCC1b3[] = {0x00, 0x00, 0x00}; // UID 1st cascade level, last 3 bytes
188 static uint8_t rUIDBCC1b2[] = {0x00, 0x00}; // UID 1st cascade level, last 2 bytes
189 static uint8_t rUIDBCC1b1[] = {0x00}; // UID 1st cascade level, last byte
190 static uint8_t rUIDBCC2[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 2nd cascade level
191 static uint8_t rUIDBCC2b4[] = {0x00, 0x00, 0x00, 0x00}; // UID 2st cascade level, last 4 bytes
192 static uint8_t rUIDBCC2b3[] = {0x00, 0x00, 0x00}; // UID 2st cascade level, last 3 bytes
193 static uint8_t rUIDBCC2b2[] = {0x00, 0x00}; // UID 2st cascade level, last 2 bytes
194 static uint8_t rUIDBCC2b1[] = {0x00}; // UID 2st cascade level, last byte
195 static uint8_t rUIDBCC3[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 3nd cascade level
196 static uint8_t rUIDBCC3b4[] = {0x00, 0x00, 0x00, 0x00}; // UID 3st cascade level, last 4 bytes
197 static uint8_t rUIDBCC3b3[] = {0x00, 0x00, 0x00}; // UID 3st cascade level, last 3 bytes
198 static uint8_t rUIDBCC3b2[] = {0x00, 0x00}; // UID 3st cascade level, last 2 bytes
199 static uint8_t rUIDBCC3b1[] = {0x00}; // UID 3st cascade level, last byte
201 static uint8_t rATQA[] = {0x00, 0x00}; // Current ATQA
202 static uint8_t rSAK[] = {0x00, 0x00, 0x00}; // Current SAK, CRC
203 static uint8_t rSAKuid[] = {0x04, 0xda, 0x17}; // UID incomplete cascade bit, CRC
205 // RATS answer for 2K NXP mifare classic (with CRC)
206 static uint8_t rRATS[] = {0x0c, 0x75, 0x77, 0x80, 0x02, 0xc1, 0x05, 0x2f, 0x2f, 0x01, 0xbc, 0xd6, 0x60, 0xd3};
208 *uid_len = 0;
210 // By default use 1K tag
211 memcpy(rATQA, rATQA_1k, sizeof(rATQA));
212 rSAK[0] = rSAK_1k;
214 //by default RATS not supported
215 *rats_len = 0;
216 *rats = NULL;
218 // -- Determine the UID
219 // Can be set from emulator memory or incoming data
220 // Length: 4,7,or 10 bytes
222 // Get UID, SAK, ATQA from EMUL
223 if ((flags & FLAG_UID_IN_EMUL) == FLAG_UID_IN_EMUL) {
224 uint8_t block0[16];
225 emlGetMemBt(block0, 0, 16);
227 // If uid size defined, copy only uid from EMUL to use, backward compatibility for 'hf_colin.c', 'hf_mattyrun.c'
228 if ((flags & (FLAG_4B_UID_IN_DATA | FLAG_7B_UID_IN_DATA | FLAG_10B_UID_IN_DATA)) != 0) {
229 memcpy(datain, block0, 10); // load 10bytes from EMUL to the datain pointer. to be used below.
230 } else {
231 // Check for 4 bytes uid: bcc corrected and single size uid bits in ATQA
232 if ((block0[0] ^ block0[1] ^ block0[2] ^ block0[3]) == block0[4] && (block0[6] & 0xc0) == 0) {
233 flags |= FLAG_4B_UID_IN_DATA;
234 memcpy(datain, block0, 4);
235 rSAK[0] = block0[5];
236 memcpy(rATQA, &block0[6], sizeof(rATQA));
238 // Check for 7 bytes UID: double size uid bits in ATQA
239 else if ((block0[8] & 0xc0) == 0x40) {
240 flags |= FLAG_7B_UID_IN_DATA;
241 memcpy(datain, block0, 7);
242 rSAK[0] = block0[7];
243 memcpy(rATQA, &block0[8], sizeof(rATQA));
244 } else {
245 Dbprintf("ERROR: " _RED_("Invalid dump. UID/SAK/ATQA not found"));
246 return false;
252 // Tune tag type, if defined directly
253 // Otherwise use defined by default or extracted from EMUL
254 if ((flags & FLAG_MF_MINI) == FLAG_MF_MINI) {
255 memcpy(rATQA, rATQA_Mini, sizeof(rATQA));
256 rSAK[0] = rSAK_Mini;
257 if (DBGLEVEL > DBG_NONE) Dbprintf("Enforcing Mifare Mini ATQA/SAK");
258 } else if ((flags & FLAG_MF_1K) == FLAG_MF_1K) {
259 memcpy(rATQA, rATQA_1k, sizeof(rATQA));
260 rSAK[0] = rSAK_1k;
261 if (DBGLEVEL > DBG_NONE) Dbprintf("Enforcing Mifare 1K ATQA/SAK");
262 } else if ((flags & FLAG_MF_2K) == FLAG_MF_2K) {
263 memcpy(rATQA, rATQA_2k, sizeof(rATQA));
264 rSAK[0] = rSAK_2k;
265 *rats = rRATS;
266 *rats_len = sizeof(rRATS);
267 if (DBGLEVEL > DBG_NONE) Dbprintf("Enforcing Mifare 2K ATQA/SAK with RATS support");
268 } else if ((flags & FLAG_MF_4K) == FLAG_MF_4K) {
269 memcpy(rATQA, rATQA_4k, sizeof(rATQA));
270 rSAK[0] = rSAK_4k;
271 if (DBGLEVEL > DBG_NONE) Dbprintf("Enforcing Mifare 4K ATQA/SAK");
274 // Prepare UID arrays
275 if ((flags & FLAG_4B_UID_IN_DATA) == FLAG_4B_UID_IN_DATA) { // get UID from datain
276 memcpy(rUIDBCC1, datain, 4);
277 *uid_len = 4;
278 if (DBGLEVEL >= DBG_EXTENDED)
279 Dbprintf("MifareSimInit - FLAG_4B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_4B_UID_IN_DATA, flags, rUIDBCC1);
282 // save CUID
283 *cuid = bytes_to_num(rUIDBCC1, 4);
284 // BCC
285 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
286 if (DBGLEVEL > DBG_NONE) {
287 Dbprintf("4B UID: %02x%02x%02x%02x", rUIDBCC1[0], rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3]);
290 // Correct uid size bits in ATQA
291 rATQA[0] = (rATQA[0] & 0x3f) | 0x00; // single size uid
293 } else if ((flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA) {
294 memcpy(&rUIDBCC1[1], datain, 3);
295 memcpy(rUIDBCC2, datain + 3, 4);
296 *uid_len = 7;
297 if (DBGLEVEL >= DBG_EXTENDED)
298 Dbprintf("MifareSimInit - FLAG_7B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_7B_UID_IN_DATA, flags, rUIDBCC1);
300 // save CUID
301 *cuid = bytes_to_num(rUIDBCC2, 4);
302 // CascadeTag, CT
303 rUIDBCC1[0] = MIFARE_SELECT_CT;
304 // BCC
305 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
306 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
307 if (DBGLEVEL > DBG_NONE) {
308 Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x",
309 rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3], rUIDBCC2[0], rUIDBCC2[1], rUIDBCC2[2], rUIDBCC2[3]);
312 // Correct uid size bits in ATQA
313 rATQA[0] = (rATQA[0] & 0x3f) | 0x40; // double size uid
315 } else if ((flags & FLAG_10B_UID_IN_DATA) == FLAG_10B_UID_IN_DATA) {
316 memcpy(&rUIDBCC1[1], datain, 3);
317 memcpy(&rUIDBCC2[1], datain + 3, 3);
318 memcpy(rUIDBCC3, datain + 6, 4);
319 *uid_len = 10;
320 if (DBGLEVEL >= DBG_EXTENDED)
321 Dbprintf("MifareSimInit - FLAG_10B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_10B_UID_IN_DATA, flags, rUIDBCC1);
323 // save CUID
324 *cuid = bytes_to_num(rUIDBCC3, 4);
325 // CascadeTag, CT
326 rUIDBCC1[0] = MIFARE_SELECT_CT;
327 rUIDBCC2[0] = MIFARE_SELECT_CT;
328 // BCC
329 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
330 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
331 rUIDBCC3[4] = rUIDBCC3[0] ^ rUIDBCC3[1] ^ rUIDBCC3[2] ^ rUIDBCC3[3];
333 if (DBGLEVEL > DBG_NONE) {
334 Dbprintf("10B UID: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
335 rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3],
336 rUIDBCC2[1], rUIDBCC2[2], rUIDBCC2[3],
337 rUIDBCC3[0], rUIDBCC3[1], rUIDBCC3[2], rUIDBCC3[3]
341 // Correct uid size bits in ATQA
342 rATQA[0] = (rATQA[0] & 0x3f) | 0x80; // triple size uid
343 } else {
344 Dbprintf("ERROR: " _RED_("UID size not defined"));
345 return false;
347 if (flags & FLAG_FORCED_ATQA) {
348 rATQA[0] = atqa >> 8;
349 rATQA[1] = atqa & 0xff;
351 if (flags & FLAG_FORCED_SAK) {
352 rSAK[0] = sak;
354 if (DBGLEVEL > DBG_NONE) {
355 Dbprintf("ATQA : %02X %02X", rATQA[1], rATQA[0]);
356 Dbprintf("SAK : %02X", rSAK[0]);
359 // clone UIDs for byte-frame anti-collision multiple tag selection procedure
360 memcpy(rUIDBCC1b4, &rUIDBCC1[1], 4);
361 memcpy(rUIDBCC1b3, &rUIDBCC1[2], 3);
362 memcpy(rUIDBCC1b2, &rUIDBCC1[3], 2);
363 memcpy(rUIDBCC1b1, &rUIDBCC1[4], 1);
364 if (*uid_len >= 7) {
365 memcpy(rUIDBCC2b4, &rUIDBCC2[1], 4);
366 memcpy(rUIDBCC2b3, &rUIDBCC2[2], 3);
367 memcpy(rUIDBCC2b2, &rUIDBCC2[3], 2);
368 memcpy(rUIDBCC2b1, &rUIDBCC2[4], 1);
370 if (*uid_len == 10) {
371 memcpy(rUIDBCC3b4, &rUIDBCC3[1], 4);
372 memcpy(rUIDBCC3b3, &rUIDBCC3[2], 3);
373 memcpy(rUIDBCC3b2, &rUIDBCC3[3], 2);
374 memcpy(rUIDBCC3b1, &rUIDBCC3[4], 1);
377 // Calculate actual CRC
378 AddCrc14A(rSAK, sizeof(rSAK) - 2);
380 #define TAG_RESPONSE_COUNT 18
381 static tag_response_info_t responses_init[TAG_RESPONSE_COUNT] = {
382 { .response = rATQA, .response_n = sizeof(rATQA) }, // Answer to request - respond with card type
383 { .response = rSAK, .response_n = sizeof(rSAK) }, //
384 { .response = rSAKuid, .response_n = sizeof(rSAKuid) }, //
385 // Do not reorder. Block used via relative index of rUIDBCC1
386 { .response = rUIDBCC1, .response_n = sizeof(rUIDBCC1) }, // Anticollision cascade1 - respond with first part of uid
387 { .response = rUIDBCC1b4, .response_n = sizeof(rUIDBCC1b4)},
388 { .response = rUIDBCC1b3, .response_n = sizeof(rUIDBCC1b3)},
389 { .response = rUIDBCC1b2, .response_n = sizeof(rUIDBCC1b2)},
390 { .response = rUIDBCC1b1, .response_n = sizeof(rUIDBCC1b1)},
391 // Do not reorder. Block used via relative index of rUIDBCC2
392 { .response = rUIDBCC2, .response_n = sizeof(rUIDBCC2) }, // Anticollision cascade2 - respond with 2nd part of uid
393 { .response = rUIDBCC2b4, .response_n = sizeof(rUIDBCC2b4)},
394 { .response = rUIDBCC2b3, .response_n = sizeof(rUIDBCC2b3)},
395 { .response = rUIDBCC2b2, .response_n = sizeof(rUIDBCC2b2)},
396 { .response = rUIDBCC2b1, .response_n = sizeof(rUIDBCC2b1)},
397 // Do not reorder. Block used via relative index of rUIDBCC3
398 { .response = rUIDBCC3, .response_n = sizeof(rUIDBCC3) }, // Anticollision cascade3 - respond with 3th part of uid
399 { .response = rUIDBCC3b4, .response_n = sizeof(rUIDBCC3b4)},
400 { .response = rUIDBCC3b3, .response_n = sizeof(rUIDBCC3b3)},
401 { .response = rUIDBCC3b2, .response_n = sizeof(rUIDBCC3b2)},
402 { .response = rUIDBCC3b1, .response_n = sizeof(rUIDBCC3b1)}
405 // Prepare ("precompile") the responses of the anticollision phase.
406 // There will be not enough time to do this at the moment the reader sends its REQA or SELECT
407 // There are 18 predefined responses with a total of 53 bytes data to transmit.
408 // Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
409 // 53 * 8 data bits, 53 * 1 parity bits, 18 start bits, 18 stop bits, 18 correction bits -> need 571 bytes buffer
410 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 571
412 uint8_t *free_buffer = BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE);
413 // modulation buffer pointer and current buffer free space size
414 uint8_t *free_buffer_pointer = free_buffer;
415 size_t free_buffer_size = ALLOCATED_TAG_MODULATION_BUFFER_SIZE;
417 for (size_t i = 0; i < TAG_RESPONSE_COUNT; i++) {
418 if (prepare_allocated_tag_modulation(&responses_init[i], &free_buffer_pointer, &free_buffer_size) == false) {
419 Dbprintf("Not enough modulation buffer size, exit after %d elements", i);
420 return false;
424 *responses = responses_init;
426 // indices into responses array:
427 #define ATQA 0
428 #define SAK 1
429 #define SAKuid 2
430 #define UIDBCC1 3
431 #define UIDBCC2 8
432 #define UIDBCC3 13
434 return true;
438 *MIFARE 1K simulate.
440 *@param flags :
441 * FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
442 * FLAG_4B_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that
443 * FLAG_7B_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that
444 * FLAG_10B_UID_IN_DATA - use 10-byte UID in the data-section not finished
445 * FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later
446 *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ...
447 * (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attmpted)
449 void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *datain, uint16_t atqa, uint8_t sak) {
450 tag_response_info_t *responses;
451 uint8_t cardSTATE = MFEMUL_NOFIELD;
452 uint8_t uid_len = 0; // 4, 7, 10
453 uint32_t cuid = 0, selTimer = 0, authTimer = 0;
454 uint32_t nr, ar;
455 uint8_t blockNo;
456 bool encrypted_data;
458 uint8_t cardWRBL = 0;
459 uint8_t cardAUTHSC = 0;
460 uint8_t cardAUTHKEY = AUTHKEYNONE; // no authentication
461 uint32_t cardRr = 0;
462 uint32_t ans = 0;
463 uint32_t cardINTREG = 0;
464 uint8_t cardINTBLOCK = 0;
466 struct Crypto1State mpcs = {0, 0};
467 struct Crypto1State *pcs;
468 pcs = &mpcs;
470 uint32_t numReads = 0; //Counts numer of times reader reads a block
471 uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00};
472 uint8_t receivedCmd_dec[MAX_MIFARE_FRAME_SIZE] = {0x00};
473 uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
474 uint16_t receivedCmd_len;
476 uint8_t response[MAX_MIFARE_FRAME_SIZE] = {0x00};
477 uint8_t response_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
479 uint8_t *rats = NULL;
480 uint8_t rats_len = 0;
482 //Here, we collect UID,sector,keytype,NT,AR,NR,NT2,AR2,NR2
483 // This will be used in the reader-only attack.
485 //allow collecting up to 7 sets of nonces to allow recovery of up to 7 keys
486 #define ATTACK_KEY_COUNT 7 // keep same as define in cmdhfmf.c -> readerAttack() (Cannot be more than 7)
487 nonces_t ar_nr_resp[ATTACK_KEY_COUNT * 2]; // *2 for 2 separate attack types (nml, moebius) 36 * 7 * 2 bytes = 504 bytes
488 memset(ar_nr_resp, 0x00, sizeof(ar_nr_resp));
490 uint8_t ar_nr_collected[ATTACK_KEY_COUNT * 2]; // *2 for 2nd attack type (moebius)
491 memset(ar_nr_collected, 0x00, sizeof(ar_nr_collected));
492 uint8_t nonce1_count = 0;
493 uint8_t nonce2_count = 0;
494 uint8_t moebius_n_count = 0;
495 bool gettingMoebius = false;
496 uint8_t mM = 0; //moebius_modifier for collection storage
498 // Authenticate response - nonce
499 uint8_t rAUTH_NT[4];
500 uint8_t rAUTH_NT_keystream[4];
501 uint32_t nonce = 0;
503 tUart14a *uart = GetUart14a();
505 // free eventually allocated BigBuf memory but keep Emulator Memory
506 BigBuf_free_keep_EM();
508 if (MifareSimInit(flags, datain, atqa, sak, &responses, &cuid, &uid_len, &rats, &rats_len) == false) {
509 BigBuf_free_keep_EM();
510 return;
513 // We need to listen to the high-frequency, peak-detected path.
514 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN);
516 // clear trace
517 clear_trace();
518 set_tracing(true);
519 LED_D_ON();
520 ResetSspClk();
522 uint8_t *p_em = BigBuf_get_EM_addr();
523 uint8_t cve_flipper = 0;
525 int counter = 0;
526 bool finished = false;
527 bool button_pushed = BUTTON_PRESS();
528 while (!button_pushed && !finished) {
530 WDT_HIT();
532 if (counter == 3000) {
533 if (data_available()) {
534 Dbprintf("----------- " _GREEN_("BREAKING") " ----------");
535 break;
537 counter = 0;
538 } else {
539 counter++;
543 // find reader field
544 if (cardSTATE == MFEMUL_NOFIELD) {
546 #if defined RDV4
547 vHf = (MAX_ADC_HF_VOLTAGE_RDV40 * SumAdc(ADC_CHAN_HF_RDV40, 32)) >> 15;
548 #else
549 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
550 #endif
552 if (vHf > MF_MINFIELDV) {
553 cardSTATE_TO_IDLE();
554 LED_A_ON();
556 button_pushed = BUTTON_PRESS();
557 continue;
561 FpgaEnableTracing();
562 //Now, get data
563 int res = EmGetCmd(receivedCmd, &receivedCmd_len, receivedCmd_par);
565 if (res == 2) { //Field is off!
566 //FpgaDisableTracing();
567 if ((flags & FLAG_CVE21_0430) == FLAG_CVE21_0430) {
568 p_em[1] = 0x21;
569 cve_flipper = 0;
571 LEDsoff();
572 cardSTATE = MFEMUL_NOFIELD;
573 if (DBGLEVEL >= DBG_EXTENDED)
574 Dbprintf("cardSTATE = MFEMUL_NOFIELD");
575 continue;
576 } else if (res == 1) { // button pressed
577 FpgaDisableTracing();
578 button_pushed = true;
579 if (DBGLEVEL >= DBG_EXTENDED)
580 Dbprintf("Button pressed");
581 break;
584 // WUPA in HALTED state or REQA or WUPA in any other state
585 if (receivedCmd_len == 1 && ((receivedCmd[0] == ISO14443A_CMD_REQA && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == ISO14443A_CMD_WUPA)) {
586 selTimer = GetTickCount();
587 if (DBGLEVEL >= DBG_EXTENDED)
588 Dbprintf("EmSendPrecompiledCmd(&responses[ATQA]);");
589 EmSendPrecompiledCmd(&responses[ATQA]);
591 FpgaDisableTracing();
593 // init crypto block
594 crypto1_deinit(pcs);
595 cardAUTHKEY = AUTHKEYNONE;
596 nonce = prng_successor(selTimer, 32);
597 // prepare NT for nested authentication
598 num_to_bytes(nonce, 4, rAUTH_NT);
599 num_to_bytes(cuid ^ nonce, 4, rAUTH_NT_keystream);
601 LED_B_OFF();
602 LED_C_OFF();
603 cardSTATE = MFEMUL_SELECT;
605 if ((flags & FLAG_CVE21_0430) == FLAG_CVE21_0430) {
606 p_em[1] = 0x21;
607 cve_flipper = 0;
609 continue;
612 switch (cardSTATE) {
613 case MFEMUL_NOFIELD: {
614 if (DBGLEVEL >= DBG_EXTENDED)
615 Dbprintf("MFEMUL_NOFIELD");
616 break;
618 case MFEMUL_HALTED: {
619 if (DBGLEVEL >= DBG_EXTENDED)
620 Dbprintf("MFEMUL_HALTED");
621 break;
623 case MFEMUL_IDLE: {
624 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
625 if (DBGLEVEL >= DBG_EXTENDED)
626 Dbprintf("MFEMUL_IDLE");
627 break;
630 // The anti-collision sequence, which is a mandatory part of the card activation sequence.
631 // It auto with 4-byte UID (= Single Size UID),
632 // 7 -byte UID (= Double Size UID) or 10-byte UID (= Triple Size UID).
633 // For details see chapter 2 of AN10927.pdf
635 // This case is used for all Cascade Levels, because:
636 // 1) Any devices (under Android for example) after full select procedure completed,
637 // when UID is known, uses "fast-selection" method. In this case reader ignores
638 // first cascades and tries to select tag by last bytes of UID of last cascade
639 // 2) Any readers (like ACR122U) uses bit oriented anti-collision frames during selectin,
640 // same as multiple tags. For details see chapter 6.1.5.3 of ISO/IEC 14443-3
641 case MFEMUL_SELECT: {
642 int uid_index = -1;
643 // Extract cascade level
644 if (receivedCmd_len >= 2) {
645 switch (receivedCmd[0]) {
646 case ISO14443A_CMD_ANTICOLL_OR_SELECT:
647 uid_index = UIDBCC1;
648 break;
649 case ISO14443A_CMD_ANTICOLL_OR_SELECT_2:
650 uid_index = UIDBCC2;
651 break;
652 case ISO14443A_CMD_ANTICOLL_OR_SELECT_3:
653 uid_index = UIDBCC3;
654 break;
657 if (uid_index < 0) {
658 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
659 cardSTATE_TO_IDLE();
660 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] Incorrect cascade level received");
661 break;
664 // Incoming SELECT ALL for any cascade level
665 if (receivedCmd_len == 2 && receivedCmd[1] == 0x20) {
666 EmSendPrecompiledCmd(&responses[uid_index]);
667 FpgaDisableTracing();
669 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("SELECT ALL - EmSendPrecompiledCmd(%02x)", &responses[uid_index]);
670 break;
673 // Incoming SELECT CLx for any cascade level
674 if (receivedCmd_len == 9 && receivedCmd[1] == 0x70) {
675 if (memcmp(&receivedCmd[2], responses[uid_index].response, 4) == 0) {
676 bool cl_finished = (uid_len == 4 && uid_index == UIDBCC1) ||
677 (uid_len == 7 && uid_index == UIDBCC2) ||
678 (uid_len == 10 && uid_index == UIDBCC3);
679 EmSendPrecompiledCmd(&responses[cl_finished ? SAK : SAKuid]);
680 FpgaDisableTracing();
682 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("SELECT CLx %02x%02x%02x%02x received", receivedCmd[2], receivedCmd[3], receivedCmd[4], receivedCmd[5]);
683 if (cl_finished) {
684 LED_B_ON();
685 cardSTATE = MFEMUL_WORK;
686 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_WORK");
688 } else {
689 // IDLE, not our UID
690 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
691 cardSTATE_TO_IDLE();
692 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_IDLE");
694 break;
697 // Incoming anti-collision frame
698 // receivedCmd[1] indicates number of byte and bit collision, supports only for bit collision is zero
699 if (receivedCmd_len >= 3 && receivedCmd_len <= 6 && (receivedCmd[1] & 0x0f) == 0) {
700 // we can process only full-byte frame anti-collision procedure
701 if (memcmp(&receivedCmd[2], responses[uid_index].response, receivedCmd_len - 2) == 0) {
702 // response missing part of UID via relative array index
703 EmSendPrecompiledCmd(&responses[uid_index + receivedCmd_len - 2]);
704 FpgaDisableTracing();
706 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("SELECT ANTICOLLISION - EmSendPrecompiledCmd(%02x)", &responses[uid_index]);
707 } else {
708 // IDLE, not our UID or split-byte frame anti-collision (not supports)
709 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
710 cardSTATE_TO_IDLE();
711 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_IDLE");
713 break;
716 // Unknown selection procedure
717 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
718 cardSTATE_TO_IDLE();
719 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] Unknown selection procedure");
720 break;
723 // WORK
724 case MFEMUL_WORK: {
726 if (DBGLEVEL >= DBG_EXTENDED) {
727 Dbprintf("[MFEMUL_WORK] Enter in case");
730 if (receivedCmd_len == 0) {
731 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] NO CMD received");
732 break;
735 encrypted_data = (cardAUTHKEY != AUTHKEYNONE);
736 if (encrypted_data) {
737 // decrypt seqence
738 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
739 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Decrypt sequence");
740 } else {
741 // Data in clear
742 memcpy(receivedCmd_dec, receivedCmd, receivedCmd_len);
745 // all commands must have a valid CRC
746 if (!CheckCrc14A(receivedCmd_dec, receivedCmd_len)) {
747 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
748 FpgaDisableTracing();
750 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] All commands must have a valid CRC %02X (%d)", receivedCmd_dec, receivedCmd_len);
751 break;
754 if (receivedCmd_len == 4 && (receivedCmd_dec[0] == MIFARE_AUTH_KEYA || receivedCmd_dec[0] == MIFARE_AUTH_KEYB)) {
756 // Reader asks for AUTH: 6X XX
757 // RCV: 60 XX => Using KEY A
758 // RCV: 61 XX => Using KEY B
759 // XX: Block number
761 authTimer = GetTickCount();
763 // received block num -> sector
764 // Example: 6X [00]
765 // 4K tags have 16 blocks per sector 32..39
766 cardAUTHSC = MifareBlockToSector(receivedCmd_dec[1]);
768 // cardAUTHKEY: 60 => Auth use Key A
769 // cardAUTHKEY: 61 => Auth use Key B
770 cardAUTHKEY = receivedCmd_dec[0] & 0x01;
772 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] KEY %c: %012" PRIx64, (cardAUTHKEY == 0) ? 'A' : 'B', emlGetKey(cardAUTHSC, cardAUTHKEY));
774 // first authentication
775 crypto1_deinit(pcs);
777 // Load key into crypto
778 crypto1_init(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
780 if (!encrypted_data) {
781 // Receive Cmd in clear txt
782 // Update crypto state (UID ^ NONCE)
783 crypto1_word(pcs, cuid ^ nonce, 0);
784 // rAUTH_NT contains prepared nonce for authenticate
785 EmSendCmd(rAUTH_NT, sizeof(rAUTH_NT));
786 FpgaDisableTracing();
788 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Reader authenticating for block %d (0x%02x) with key %c - nonce: %02X - ciud: %02X", receivedCmd_dec[1], receivedCmd_dec[1], (cardAUTHKEY == 0) ? 'A' : 'B', rAUTH_NT, cuid);
789 } else {
790 // nested authentication
792 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
793 num_to_bytes(ans, 4, rAUTH_AT);
795 // rAUTH_NT, rAUTH_NT_keystream contains prepared nonce and keystream for nested authentication
796 // we need calculate parity bits for non-encrypted sequence
797 mf_crypto1_encryptEx(pcs, rAUTH_NT, rAUTH_NT_keystream, response, 4, response_par);
798 EmSendCmdPar(response, 4, response_par);
799 FpgaDisableTracing();
801 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Reader doing nested authentication for block %d (0x%02x) with key %c", receivedCmd_dec[1], receivedCmd_dec[1], (cardAUTHKEY == 0) ? 'A' : 'B');
804 cardSTATE = MFEMUL_AUTH1;
805 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_AUTH1 - rAUTH_NT: %02X", rAUTH_NT);
806 break;
809 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
810 // BUT... ACK --> NACK
811 if (receivedCmd_len == 1 && receivedCmd_dec[0] == CARD_ACK) {
812 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
813 FpgaDisableTracing();
814 break;
817 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
818 if (receivedCmd_len == 1 && receivedCmd_dec[0] == CARD_NACK_NA) {
819 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_ACK) : CARD_ACK);
820 FpgaDisableTracing();
821 break;
824 // case MFEMUL_WORK => if Cmd is Read, Write, Inc, Dec, Restore, Transfert
825 if (receivedCmd_len == 4 && (receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK
826 || receivedCmd_dec[0] == ISO14443A_CMD_WRITEBLOCK
827 || receivedCmd_dec[0] == MIFARE_CMD_INC
828 || receivedCmd_dec[0] == MIFARE_CMD_DEC
829 || receivedCmd_dec[0] == MIFARE_CMD_RESTORE
830 || receivedCmd_dec[0] == MIFARE_CMD_TRANSFER)) {
831 // all other commands must be encrypted (authenticated)
832 if (!encrypted_data) {
833 EmSend4bit(CARD_NACK_NA);
834 FpgaDisableTracing();
836 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Commands must be encrypted (authenticated)");
837 break;
840 // iceman, u8 can never be larger the MIFARE_4K_MAXBLOCK (256)
841 // Check if Block num is not too far
843 if (receivedCmd_dec[1] > MIFARE_4K_MAXBLOCK) {
844 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
845 FpgaDisableTracing();
846 if (DBGLEVEL >= DBG_ERROR) Dbprintf("[MFEMUL_WORK] Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking", receivedCmd_dec[0], receivedCmd_dec[1], receivedCmd_dec[1]);
847 break;
851 if (MifareBlockToSector(receivedCmd_dec[1]) != cardAUTHSC) {
852 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
853 FpgaDisableTracing();
855 if (DBGLEVEL >= DBG_ERROR)
856 Dbprintf("[MFEMUL_WORK] Reader tried to operate (0x%02x) on block (0x%02x) not authenticated for (0x%02x), nacking", receivedCmd_dec[0], receivedCmd_dec[1], cardAUTHSC);
857 break;
861 // case MFEMUL_WORK => CMD READ block
862 if (receivedCmd_len == 4 && receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK) {
863 blockNo = receivedCmd_dec[1];
864 if (DBGLEVEL >= DBG_EXTENDED)
865 Dbprintf("[MFEMUL_WORK] Reader reading block %d (0x%02x)", blockNo, blockNo);
867 // android CVE 2021_0430
868 // Simulate a MFC 1K, with a NDEF message.
869 // these values uses the standard LIBNFC NDEF message
871 // In short, first a value read of block 4,
872 // update the length byte before second read of block 4.
873 // on iphone etc there might even be 3 reads of block 4.
874 // fiddling with when to flip the byte or not, has different effects
875 if ((flags & FLAG_CVE21_0430) == FLAG_CVE21_0430) {
877 // first block
878 if (blockNo == 4) {
880 p_em += blockNo * 16;
881 // TLV in NDEF, flip length between
882 // 4 | 03 21 D1 02 1C 53 70 91 01 09 54 02 65 6E 4C 69
883 // 0xFF means long length
884 // 0xFE mean max short length
886 // We could also have a go at message len byte at p_em[4]...
887 if (p_em[1] == 0x21 && cve_flipper == 1) {
888 p_em[1] = 0xFE;
889 } else {
890 cve_flipper++;
895 emlGetMem(response, blockNo, 1);
897 if (DBGLEVEL >= DBG_EXTENDED) {
898 Dbprintf("[MFEMUL_WORK - ISO14443A_CMD_READBLOCK] Data Block[%d]: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", blockNo,
899 response[0], response[1], response[2], response[3], response[4], response[5], response[6],
900 response[7], response[8], response[9], response[10], response[11], response[12], response[13],
901 response[14], response[15]);
904 // Access permission managment:
906 // Sector Trailer:
907 // - KEY A access
908 // - KEY B access
909 // - AC bits access
911 // Data block:
912 // - Data access
914 // If permission is not allowed, data is cleared (00) in emulator memeory.
915 // ex: a0a1a2a3a4a561e789c1b0b1b2b3b4b5 => 00000000000061e789c1b0b1b2b3b4b5
918 // Check if selected Block is a Sector Trailer
919 if (IsSectorTrailer(blockNo)) {
921 if (IsAccessAllowed(blockNo, cardAUTHKEY, AC_KEYA_READ) == false) {
922 memset(response, 0x00, 6); // keyA can never be read
923 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyA can never be read - block %d (0x%02x)", blockNo, blockNo);
925 if (IsAccessAllowed(blockNo, cardAUTHKEY, AC_KEYB_READ) == false) {
926 memset(response + 10, 0x00, 6); // keyB cannot be read
927 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyB cannot be read - block %d (0x%02x)", blockNo, blockNo);
929 if (IsAccessAllowed(blockNo, cardAUTHKEY, AC_AC_READ) == false) {
930 memset(response + 6, 0x00, 4); // AC bits cannot be read
931 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] AC bits cannot be read - block %d (0x%02x)", blockNo, blockNo);
933 } else {
934 if (IsAccessAllowed(blockNo, cardAUTHKEY, AC_DATA_READ) == false) {
935 memset(response, 0x00, 16); // datablock cannot be read
936 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] Data block %d (0x%02x) cannot be read", blockNo, blockNo);
939 AddCrc14A(response, 16);
940 mf_crypto1_encrypt(pcs, response, MAX_MIFARE_FRAME_SIZE, response_par);
941 EmSendCmdPar(response, MAX_MIFARE_FRAME_SIZE, response_par);
942 FpgaDisableTracing();
944 if (DBGLEVEL >= DBG_EXTENDED) {
945 Dbprintf("[MFEMUL_WORK - EmSendCmdPar] Data Block[%d]: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", blockNo,
946 response[0], response[1], response[2], response[3], response[4], response[5], response[6],
947 response[7], response[8], response[9], response[10], response[11], response[12], response[13],
948 response[14], response[15]);
950 numReads++;
952 if (exitAfterNReads > 0 && numReads == exitAfterNReads) {
953 Dbprintf("[MFEMUL_WORK] %d reads done, exiting", numReads);
954 finished = true;
956 break;
958 } // End receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK
960 // case MFEMUL_WORK => CMD WRITEBLOCK
961 if (receivedCmd_len == 4 && receivedCmd_dec[0] == ISO14443A_CMD_WRITEBLOCK) {
962 blockNo = receivedCmd_dec[1];
963 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0xA0 write block %d (%02x)", blockNo, blockNo);
964 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
965 FpgaDisableTracing();
967 cardWRBL = blockNo;
968 cardSTATE = MFEMUL_WRITEBL2;
969 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_WRITEBL2");
970 break;
973 // case MFEMUL_WORK => CMD INC/DEC/REST
974 if (receivedCmd_len == 4 && (receivedCmd_dec[0] == MIFARE_CMD_INC || receivedCmd_dec[0] == MIFARE_CMD_DEC || receivedCmd_dec[0] == MIFARE_CMD_RESTORE)) {
975 blockNo = receivedCmd_dec[1];
976 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)", receivedCmd_dec[0], blockNo, blockNo);
977 if (emlCheckValBl(blockNo)) {
978 if (DBGLEVEL >= DBG_ERROR) Dbprintf("[MFEMUL_WORK] Reader tried to operate on block, but emlCheckValBl failed, nacking");
979 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
980 FpgaDisableTracing();
981 break;
983 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
984 FpgaDisableTracing();
985 cardWRBL = blockNo;
987 // INC
988 if (receivedCmd_dec[0] == MIFARE_CMD_INC) {
989 cardSTATE = MFEMUL_INTREG_INC;
990 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_INC");
993 // DEC
994 if (receivedCmd_dec[0] == MIFARE_CMD_DEC) {
995 cardSTATE = MFEMUL_INTREG_DEC;
996 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_DEC");
999 // REST
1000 if (receivedCmd_dec[0] == MIFARE_CMD_RESTORE) {
1001 cardSTATE = MFEMUL_INTREG_REST;
1002 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_REST");
1004 break;
1006 } // End case MFEMUL_WORK => CMD INC/DEC/REST
1009 // case MFEMUL_WORK => CMD TRANSFER
1010 if (receivedCmd_len == 4 && receivedCmd_dec[0] == MIFARE_CMD_TRANSFER) {
1011 blockNo = receivedCmd_dec[1];
1012 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0x%02x transfer block %d (%02x)", receivedCmd_dec[0], blockNo, blockNo);
1013 if (emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd_dec[1]))
1014 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
1015 else
1016 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
1018 FpgaDisableTracing();
1019 break;
1022 // case MFEMUL_WORK => CMD HALT
1023 if (receivedCmd_len > 1 && receivedCmd_dec[0] == ISO14443A_CMD_HALT && receivedCmd_dec[1] == 0x00) {
1024 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1025 LED_B_OFF();
1026 LED_C_OFF();
1027 cardSTATE = MFEMUL_HALTED;
1028 cardAUTHKEY = AUTHKEYNONE;
1029 if (DBGLEVEL >= DBG_EXTENDED)
1030 Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_HALTED");
1031 break;
1034 // case MFEMUL_WORK => CMD RATS
1035 if (receivedCmd_len == 4 && receivedCmd_dec[0] == ISO14443A_CMD_RATS && receivedCmd_dec[1] == 0x80) {
1036 if (rats && rats_len) {
1037 if (encrypted_data) {
1038 memcpy(response, rats, rats_len);
1039 mf_crypto1_encrypt(pcs, response, rats_len, response_par);
1040 EmSendCmdPar(response, rats_len, response_par);
1041 } else {
1042 EmSendCmd(rats, rats_len);
1044 FpgaDisableTracing();
1045 if (DBGLEVEL >= DBG_EXTENDED)
1046 Dbprintf("[MFEMUL_WORK] RCV RATS => ACK");
1047 } else {
1048 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
1049 FpgaDisableTracing();
1050 if (DBGLEVEL >= DBG_EXTENDED)
1051 Dbprintf("[MFEMUL_WORK] RCV RATS => NACK");
1053 break;
1056 // case MFEMUL_WORK => ISO14443A_CMD_NXP_DESELECT
1057 if (receivedCmd_len == 3 && receivedCmd_dec[0] == ISO14443A_CMD_NXP_DESELECT) {
1058 if (rats && rats_len) {
1059 // response back NXP_DESELECT
1060 if (encrypted_data) {
1061 memcpy(response, receivedCmd_dec, receivedCmd_len);
1062 mf_crypto1_encrypt(pcs, response, receivedCmd_len, response_par);
1063 EmSendCmdPar(response, receivedCmd_len, response_par);
1064 } else
1065 EmSendCmd(receivedCmd_dec, receivedCmd_len);
1067 FpgaDisableTracing();
1068 if (DBGLEVEL >= DBG_EXTENDED)
1069 Dbprintf("[MFEMUL_WORK] RCV NXP DESELECT => ACK");
1070 } else {
1071 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
1072 FpgaDisableTracing();
1074 if (DBGLEVEL >= DBG_EXTENDED)
1075 Dbprintf("[MFEMUL_WORK] RCV NXP DESELECT => NACK");
1077 break;
1080 // case MFEMUL_WORK => command not allowed
1081 if (DBGLEVEL >= DBG_EXTENDED)
1082 Dbprintf("Received command not allowed, nacking");
1083 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
1084 FpgaDisableTracing();
1085 break;
1088 // AUTH1
1089 case MFEMUL_AUTH1: {
1090 if (DBGLEVEL >= DBG_EXTENDED)
1091 Dbprintf("[MFEMUL_AUTH1] Enter case");
1093 if (receivedCmd_len != 8) {
1094 cardSTATE_TO_IDLE();
1095 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1096 if (DBGLEVEL >= DBG_EXTENDED)
1097 Dbprintf("MFEMUL_AUTH1: receivedCmd_len != 8 (%d) => cardSTATE_TO_IDLE())", receivedCmd_len);
1098 break;
1101 nr = bytes_to_num(receivedCmd, 4);
1102 ar = bytes_to_num(&receivedCmd[4], 4);
1104 // Collect AR/NR per keytype & sector
1105 if ((flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK) {
1107 for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
1108 if (ar_nr_collected[i + mM] == 0 || ((cardAUTHSC == ar_nr_resp[i + mM].sector) && (cardAUTHKEY == ar_nr_resp[i + mM].keytype) && (ar_nr_collected[i + mM] > 0))) {
1109 // if first auth for sector, or matches sector and keytype of previous auth
1110 if (ar_nr_collected[i + mM] < 2) {
1111 // if we haven't already collected 2 nonces for this sector
1112 if (ar_nr_resp[ar_nr_collected[i + mM]].ar != ar) {
1113 // Avoid duplicates... probably not necessary, ar should vary.
1114 if (ar_nr_collected[i + mM] == 0) {
1115 // first nonce collect
1116 ar_nr_resp[i + mM].cuid = cuid;
1117 ar_nr_resp[i + mM].sector = cardAUTHSC;
1118 ar_nr_resp[i + mM].keytype = cardAUTHKEY;
1119 ar_nr_resp[i + mM].nonce = nonce;
1120 ar_nr_resp[i + mM].nr = nr;
1121 ar_nr_resp[i + mM].ar = ar;
1122 nonce1_count++;
1123 // add this nonce to first moebius nonce
1124 ar_nr_resp[i + ATTACK_KEY_COUNT].cuid = cuid;
1125 ar_nr_resp[i + ATTACK_KEY_COUNT].sector = cardAUTHSC;
1126 ar_nr_resp[i + ATTACK_KEY_COUNT].keytype = cardAUTHKEY;
1127 ar_nr_resp[i + ATTACK_KEY_COUNT].nonce = nonce;
1128 ar_nr_resp[i + ATTACK_KEY_COUNT].nr = nr;
1129 ar_nr_resp[i + ATTACK_KEY_COUNT].ar = ar;
1130 ar_nr_collected[i + ATTACK_KEY_COUNT]++;
1131 } else { // second nonce collect (std and moebius)
1132 ar_nr_resp[i + mM].nonce2 = nonce;
1133 ar_nr_resp[i + mM].nr2 = nr;
1134 ar_nr_resp[i + mM].ar2 = ar;
1136 if (!gettingMoebius) {
1137 nonce2_count++;
1138 // check if this was the last second nonce we need for std attack
1139 if (nonce2_count == nonce1_count) {
1140 // done collecting std test switch to moebius
1141 // first finish incrementing last sample
1142 ar_nr_collected[i + mM]++;
1143 // switch to moebius collection
1144 gettingMoebius = true;
1145 mM = ATTACK_KEY_COUNT;
1146 nonce = nonce * 7;
1147 break;
1149 } else {
1150 moebius_n_count++;
1151 // if we've collected all the nonces we need - finish.
1152 if (nonce1_count == moebius_n_count)
1153 finished = true;
1156 ar_nr_collected[i + mM]++;
1159 // we found right spot for this nonce stop looking
1160 break;
1165 // --- crypto
1166 crypto1_word(pcs, nr, 1);
1167 cardRr = ar ^ crypto1_word(pcs, 0, 0);
1169 // test if auth KO
1170 if (cardRr != prng_successor(nonce, 64)) {
1171 if (DBGLEVEL >= DBG_EXTENDED) {
1172 Dbprintf("[MFEMUL_AUTH1] AUTH FAILED for sector %d with key %c. [nr=%08x cardRr=%08x] [nt=%08x succ=%08x]"
1173 , cardAUTHSC
1174 , (cardAUTHKEY == 0) ? 'A' : 'B'
1175 , nr
1176 , cardRr
1177 , nonce // nt
1178 , prng_successor(nonce, 64)
1181 cardAUTHKEY = AUTHKEYNONE; // not authenticated
1182 cardSTATE_TO_IDLE();
1183 // Really tags not respond NACK on invalid authentication
1184 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1185 break;
1188 ans = prng_successor(nonce, 96);
1189 num_to_bytes(ans, 4, response);
1190 mf_crypto1_encrypt(pcs, response, 4, response_par);
1191 EmSendCmdPar(response, 4, response_par);
1192 FpgaDisableTracing();
1194 if (DBGLEVEL >= DBG_EXTENDED) {
1195 Dbprintf("[MFEMUL_AUTH1] AUTH COMPLETED for sector %d with key %c. time=%d",
1196 cardAUTHSC,
1197 cardAUTHKEY == 0 ? 'A' : 'B',
1198 GetTickCountDelta(authTimer)
1201 LED_C_ON();
1202 cardSTATE = MFEMUL_WORK;
1203 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_AUTH1] cardSTATE = MFEMUL_WORK");
1204 break;
1207 // WRITE BL2
1208 case MFEMUL_WRITEBL2: {
1209 if (receivedCmd_len == MAX_MIFARE_FRAME_SIZE) {
1210 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
1211 if (CheckCrc14A(receivedCmd_dec, receivedCmd_len)) {
1212 if (IsSectorTrailer(cardWRBL)) {
1213 emlGetMem(response, cardWRBL, 1);
1214 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYA_WRITE)) {
1215 memcpy(receivedCmd_dec, response, 6); // don't change KeyA
1217 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYB_WRITE)) {
1218 memcpy(receivedCmd_dec + 10, response + 10, 6); // don't change KeyA
1220 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_AC_WRITE)) {
1221 memcpy(receivedCmd_dec + 6, response + 6, 4); // don't change AC bits
1223 } else {
1224 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_DATA_WRITE)) {
1225 memcpy(receivedCmd_dec, response, 16); // don't change anything
1228 emlSetMem(receivedCmd_dec, cardWRBL, 1);
1229 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK)); // always ACK?
1230 FpgaDisableTracing();
1232 cardSTATE = MFEMUL_WORK;
1233 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_WORK");
1234 break;
1237 cardSTATE_TO_IDLE();
1238 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_IDLE");
1239 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1240 break;
1243 // INC
1244 case MFEMUL_INTREG_INC: {
1245 if (receivedCmd_len == 6) {
1246 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
1247 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
1248 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
1249 FpgaDisableTracing();
1251 cardSTATE_TO_IDLE();
1252 break;
1254 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1255 cardINTREG = cardINTREG + ans;
1257 cardSTATE = MFEMUL_WORK;
1258 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_INC] cardSTATE = MFEMUL_WORK");
1259 break;
1263 // DEC
1264 case MFEMUL_INTREG_DEC: {
1265 if (receivedCmd_len == 6) { // Data is encrypted
1266 // Decrypted cmd
1267 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
1268 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
1269 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
1270 FpgaDisableTracing();
1272 cardSTATE_TO_IDLE();
1273 break;
1276 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1277 cardINTREG = cardINTREG - ans;
1278 cardSTATE = MFEMUL_WORK;
1279 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_DEC] cardSTATE = MFEMUL_WORK");
1280 break;
1283 // REST
1284 case MFEMUL_INTREG_REST: {
1285 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
1286 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
1287 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
1288 FpgaDisableTracing();
1290 cardSTATE_TO_IDLE();
1291 break;
1293 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1294 cardSTATE = MFEMUL_WORK;
1295 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_REST] cardSTATE = MFEMUL_WORK");
1296 break;
1299 } // End Switch Loop
1301 button_pushed = BUTTON_PRESS();
1303 } // End While Loop
1305 FpgaDisableTracing();
1307 // NR AR ATTACK
1308 // mfkey32
1309 if (((flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK) && (DBGLEVEL >= DBG_INFO)) {
1310 for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
1311 if (ar_nr_collected[i] == 2) {
1312 Dbprintf("Collected two pairs of AR/NR which can be used to extract %s from reader for sector %d:", (i < ATTACK_KEY_COUNT / 2) ? "keyA" : "keyB", ar_nr_resp[i].sector);
1313 Dbprintf("../tools/mfkey/mfkey32 %08x %08x %08x %08x %08x %08x",
1314 ar_nr_resp[i].cuid, //UID
1315 ar_nr_resp[i].nonce, //NT
1316 ar_nr_resp[i].nr, //NR1
1317 ar_nr_resp[i].ar, //AR1
1318 ar_nr_resp[i].nr2, //NR2
1319 ar_nr_resp[i].ar2 //AR2
1325 // mfkey32 v2
1326 for (uint8_t i = ATTACK_KEY_COUNT; i < ATTACK_KEY_COUNT * 2; i++) {
1327 if (ar_nr_collected[i] == 2) {
1328 Dbprintf("Collected two pairs of AR/NR which can be used to extract %s from reader for sector %d:", (i < ATTACK_KEY_COUNT / 2) ? "keyA" : "keyB", ar_nr_resp[i].sector);
1329 Dbprintf("../tools/mfkey/mfkey32v2 %08x %08x %08x %08x %08x %08x %08x",
1330 ar_nr_resp[i].cuid, //UID
1331 ar_nr_resp[i].nonce, //NT
1332 ar_nr_resp[i].nr, //NR1
1333 ar_nr_resp[i].ar, //AR1
1334 ar_nr_resp[i].nonce2,//NT2
1335 ar_nr_resp[i].nr2, //NR2
1336 ar_nr_resp[i].ar2 //AR2
1341 if (DBGLEVEL >= DBG_ERROR) {
1342 Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", get_tracing(), BigBuf_get_traceLen());
1345 if ((flags & FLAG_INTERACTIVE) == FLAG_INTERACTIVE) { // Interactive mode flag, means we need to send ACK
1346 //Send the collected ar_nr in the response
1347 reply_mix(CMD_ACK, CMD_HF_MIFARE_SIMULATE, button_pushed, 0, &ar_nr_resp, sizeof(ar_nr_resp));
1350 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1351 LEDsoff();
1352 set_tracing(false);
1353 BigBuf_free_keep_EM();