fixes entering bootload messages to be less scary
[RRG-proxmark3.git] / armsrc / mifaresim.c
blob2e16f1c960ae6c481a55eba3083ef4963c25f41c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Gerhard de Koning Gans - May 2008
3 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // See LICENSE.txt for the text of the license.
16 //-----------------------------------------------------------------------------
17 // Mifare Classic Card Simulation
18 //-----------------------------------------------------------------------------
20 // Verbose Mode:
21 // DBG_NONE 0
22 // DBG_ERROR 1
23 // DBG_INFO 2
24 // DBG_DEBUG 3
25 // DBG_EXTENDED 4
27 // /!\ Printing Debug message is disrupting emulation,
28 // Only use with caution during debugging
30 #include "mifaresim.h"
32 #include <inttypes.h>
34 #include "iso14443a.h"
35 #include "BigBuf.h"
36 #include "string.h"
37 #include "mifareutil.h"
38 #include "fpgaloader.h"
39 #include "proxmark3_arm.h"
40 #include "cmd.h"
41 #include "protocols.h"
42 #include "appmain.h"
43 #include "util.h"
44 #include "commonutil.h"
45 #include "crc16.h"
46 #include "dbprint.h"
47 #include "ticks.h"
49 static bool IsKeyBReadable(uint8_t blockNo) {
50 uint8_t sector_trailer[16];
51 emlGetMem(sector_trailer, SectorTrailer(blockNo), 1);
52 uint8_t AC = ((sector_trailer[7] >> 5) & 0x04)
53 | ((sector_trailer[8] >> 2) & 0x02)
54 | ((sector_trailer[8] >> 7) & 0x01);
55 return (AC == 0x00 || AC == 0x01 || AC == 0x02);
58 static bool IsTrailerAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
59 uint8_t sector_trailer[16];
60 emlGetMem(sector_trailer, blockNo, 1);
61 uint8_t AC = ((sector_trailer[7] >> 5) & 0x04)
62 | ((sector_trailer[8] >> 2) & 0x02)
63 | ((sector_trailer[8] >> 7) & 0x01);
64 switch (action) {
65 case AC_KEYA_READ: {
66 if (g_dbglevel >= DBG_EXTENDED)
67 Dbprintf("IsTrailerAccessAllowed: AC_KEYA_READ");
68 return false;
70 case AC_KEYA_WRITE: {
71 if (g_dbglevel >= DBG_EXTENDED)
72 Dbprintf("IsTrailerAccessAllowed: AC_KEYA_WRITE");
73 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x01))
74 || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
76 case AC_KEYB_READ: {
77 if (g_dbglevel >= DBG_EXTENDED)
78 Dbprintf("IsTrailerAccessAllowed: AC_KEYB_READ");
79 return (keytype == AUTHKEYA && (AC == 0x00 || AC == 0x02 || AC == 0x01));
81 case AC_KEYB_WRITE: {
82 if (g_dbglevel >= DBG_EXTENDED)
83 Dbprintf("IsTrailerAccessAllowed: AC_KEYB_WRITE");
84 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x01))
85 || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
87 case AC_AC_READ: {
88 if (g_dbglevel >= DBG_EXTENDED)
89 Dbprintf("IsTrailerAccessAllowed: AC_AC_READ");
90 return ((keytype == AUTHKEYA)
91 || (keytype == AUTHKEYB && !(AC == 0x00 || AC == 0x02 || AC == 0x01)));
93 case AC_AC_WRITE: {
94 if (g_dbglevel >= DBG_EXTENDED)
95 Dbprintf("IsTrailerAccessAllowed: AC_AC_WRITE");
96 return ((keytype == AUTHKEYA && (AC == 0x01))
97 || (keytype == AUTHKEYB && (AC == 0x03 || AC == 0x05)));
99 default:
100 return false;
104 static bool IsDataAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
106 uint8_t sector_trailer[16];
107 emlGetMem(sector_trailer, SectorTrailer(blockNo), 1);
109 uint8_t sector_block;
110 if (blockNo <= MIFARE_2K_MAXBLOCK) {
111 sector_block = blockNo & 0x03;
112 } else {
113 sector_block = (blockNo & 0x0f) / 5;
116 uint8_t AC;
117 switch (sector_block) {
118 case 0x00: {
119 AC = ((sector_trailer[7] >> 2) & 0x04)
120 | ((sector_trailer[8] << 1) & 0x02)
121 | ((sector_trailer[8] >> 4) & 0x01);
122 if (g_dbglevel >= DBG_EXTENDED)
123 Dbprintf("IsDataAccessAllowed: case 0x00 - %02x", AC);
124 break;
126 case 0x01: {
127 AC = ((sector_trailer[7] >> 3) & 0x04)
128 | ((sector_trailer[8] >> 0) & 0x02)
129 | ((sector_trailer[8] >> 5) & 0x01);
130 if (g_dbglevel >= DBG_EXTENDED)
131 Dbprintf("IsDataAccessAllowed: case 0x01 - %02x", AC);
132 break;
134 case 0x02: {
135 AC = ((sector_trailer[7] >> 4) & 0x04)
136 | ((sector_trailer[8] >> 1) & 0x02)
137 | ((sector_trailer[8] >> 6) & 0x01);
138 if (g_dbglevel >= DBG_EXTENDED)
139 Dbprintf("IsDataAccessAllowed: case 0x02 - %02x", AC);
140 break;
142 default:
143 if (g_dbglevel >= DBG_EXTENDED)
144 Dbprintf("IsDataAccessAllowed: Error");
145 return false;
148 switch (action) {
149 case AC_DATA_READ: {
150 if (g_dbglevel >= DBG_EXTENDED)
151 Dbprintf("IsDataAccessAllowed - AC_DATA_READ: OK");
152 return ((keytype == AUTHKEYA && !(AC == 0x03 || AC == 0x05 || AC == 0x07))
153 || (keytype == AUTHKEYB && !(AC == 0x07)));
155 case AC_DATA_WRITE: {
156 if (g_dbglevel >= DBG_EXTENDED)
157 Dbprintf("IsDataAccessAllowed - AC_DATA_WRITE: OK");
158 return ((keytype == AUTHKEYA && (AC == 0x00))
159 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x04 || AC == 0x06 || AC == 0x03)));
161 case AC_DATA_INC: {
162 if (g_dbglevel >= DBG_EXTENDED)
163 Dbprintf("IsDataAccessAllowed - AC_DATA_INC: OK");
164 return ((keytype == AUTHKEYA && (AC == 0x00))
165 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06)));
167 case AC_DATA_DEC_TRANS_REST: {
168 if (g_dbglevel >= DBG_EXTENDED)
169 Dbprintf("AC_DATA_DEC_TRANS_REST: OK");
170 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x06 || AC == 0x01))
171 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06 || AC == 0x01)));
175 return false;
178 static bool IsAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
179 if (IsSectorTrailer(blockNo)) {
180 return IsTrailerAccessAllowed(blockNo, keytype, action);
181 } else {
182 return IsDataAccessAllowed(blockNo, keytype, action);
186 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) {
188 // SPEC: https://www.nxp.com/docs/en/application-note/AN10833.pdf
189 // ATQA
190 static uint8_t rATQA_Mini[] = {0x04, 0x00}; // indicate Mifare classic Mini 4Byte UID
191 static uint8_t rATQA_1k[] = {0x04, 0x00}; // indicate Mifare classic 1k 4Byte UID
192 static uint8_t rATQA_2k[] = {0x04, 0x00}; // indicate Mifare classic 2k 4Byte UID
193 static uint8_t rATQA_4k[] = {0x02, 0x00}; // indicate Mifare classic 4k 4Byte UID
195 // SAK
196 static uint8_t rSAK_Mini = 0x09; // mifare Mini
197 static uint8_t rSAK_1k = 0x08; // mifare 1k
198 static uint8_t rSAK_2k = 0x08; // mifare 2k with RATS support
199 static uint8_t rSAK_4k = 0x18; // mifare 4k
201 static uint8_t rUIDBCC1[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level
202 static uint8_t rUIDBCC1b4[] = {0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level, last 4 bytes
203 static uint8_t rUIDBCC1b3[] = {0x00, 0x00, 0x00}; // UID 1st cascade level, last 3 bytes
204 static uint8_t rUIDBCC1b2[] = {0x00, 0x00}; // UID 1st cascade level, last 2 bytes
205 static uint8_t rUIDBCC1b1[] = {0x00}; // UID 1st cascade level, last byte
206 static uint8_t rUIDBCC2[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 2nd cascade level
207 static uint8_t rUIDBCC2b4[] = {0x00, 0x00, 0x00, 0x00}; // UID 2st cascade level, last 4 bytes
208 static uint8_t rUIDBCC2b3[] = {0x00, 0x00, 0x00}; // UID 2st cascade level, last 3 bytes
209 static uint8_t rUIDBCC2b2[] = {0x00, 0x00}; // UID 2st cascade level, last 2 bytes
210 static uint8_t rUIDBCC2b1[] = {0x00}; // UID 2st cascade level, last byte
211 static uint8_t rUIDBCC3[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 3nd cascade level
212 static uint8_t rUIDBCC3b4[] = {0x00, 0x00, 0x00, 0x00}; // UID 3st cascade level, last 4 bytes
213 static uint8_t rUIDBCC3b3[] = {0x00, 0x00, 0x00}; // UID 3st cascade level, last 3 bytes
214 static uint8_t rUIDBCC3b2[] = {0x00, 0x00}; // UID 3st cascade level, last 2 bytes
215 static uint8_t rUIDBCC3b1[] = {0x00}; // UID 3st cascade level, last byte
217 static uint8_t rATQA[] = {0x00, 0x00}; // Current ATQA
218 static uint8_t rSAK[] = {0x00, 0x00, 0x00}; // Current SAK, CRC
219 static uint8_t rSAKuid[] = {0x04, 0xda, 0x17}; // UID incomplete cascade bit, CRC
221 // RATS answer for 2K NXP mifare classic (with CRC)
222 static uint8_t rRATS[] = {0x0c, 0x75, 0x77, 0x80, 0x02, 0xc1, 0x05, 0x2f, 0x2f, 0x01, 0xbc, 0xd6, 0x60, 0xd3};
224 *uid_len = 0;
226 // By default use 1K tag
227 memcpy(rATQA, rATQA_1k, sizeof(rATQA));
228 rSAK[0] = rSAK_1k;
230 //by default RATS not supported
231 *rats_len = 0;
232 *rats = NULL;
234 // -- Determine the UID
235 // Can be set from emulator memory or incoming data
236 // Length: 4,7,or 10 bytes
238 // Get UID, SAK, ATQA from EMUL
239 if ((flags & FLAG_UID_IN_EMUL) == FLAG_UID_IN_EMUL) {
240 uint8_t block0[16];
241 emlGet(block0, 0, 16);
243 // If uid size defined, copy only uid from EMUL to use, backward compatibility for 'hf_colin.c', 'hf_mattyrun.c'
244 if ((flags & (FLAG_4B_UID_IN_DATA | FLAG_7B_UID_IN_DATA | FLAG_10B_UID_IN_DATA)) != 0) {
245 memcpy(datain, block0, 10); // load 10bytes from EMUL to the datain pointer. to be used below.
246 } else {
247 // Check for 4 bytes uid: bcc corrected and single size uid bits in ATQA
248 if ((block0[0] ^ block0[1] ^ block0[2] ^ block0[3]) == block0[4] && (block0[6] & 0xc0) == 0) {
249 flags |= FLAG_4B_UID_IN_DATA;
250 memcpy(datain, block0, 4);
251 rSAK[0] = block0[5];
252 memcpy(rATQA, &block0[6], sizeof(rATQA));
254 // Check for 7 bytes UID: double size uid bits in ATQA
255 else if ((block0[8] & 0xc0) == 0x40) {
256 flags |= FLAG_7B_UID_IN_DATA;
257 memcpy(datain, block0, 7);
258 rSAK[0] = block0[7];
259 memcpy(rATQA, &block0[8], sizeof(rATQA));
260 } else {
261 Dbprintf("ERROR: " _RED_("Invalid dump. UID/SAK/ATQA not found"));
262 return false;
268 // Tune tag type, if defined directly
269 // Otherwise use defined by default or extracted from EMUL
270 if ((flags & FLAG_MF_MINI) == FLAG_MF_MINI) {
271 memcpy(rATQA, rATQA_Mini, sizeof(rATQA));
272 rSAK[0] = rSAK_Mini;
273 if (g_dbglevel > DBG_NONE) Dbprintf("Enforcing Mifare Mini ATQA/SAK");
274 } else if ((flags & FLAG_MF_1K) == FLAG_MF_1K) {
275 memcpy(rATQA, rATQA_1k, sizeof(rATQA));
276 rSAK[0] = rSAK_1k;
277 if (g_dbglevel > DBG_NONE) Dbprintf("Enforcing Mifare 1K ATQA/SAK");
278 } else if ((flags & FLAG_MF_2K) == FLAG_MF_2K) {
279 memcpy(rATQA, rATQA_2k, sizeof(rATQA));
280 rSAK[0] = rSAK_2k;
281 *rats = rRATS;
282 *rats_len = sizeof(rRATS);
283 if (g_dbglevel > DBG_NONE) Dbprintf("Enforcing Mifare 2K ATQA/SAK with RATS support");
284 } else if ((flags & FLAG_MF_4K) == FLAG_MF_4K) {
285 memcpy(rATQA, rATQA_4k, sizeof(rATQA));
286 rSAK[0] = rSAK_4k;
287 if (g_dbglevel > DBG_NONE) Dbprintf("Enforcing Mifare 4K ATQA/SAK");
290 // Prepare UID arrays
291 if ((flags & FLAG_4B_UID_IN_DATA) == FLAG_4B_UID_IN_DATA) { // get UID from datain
292 memcpy(rUIDBCC1, datain, 4);
293 *uid_len = 4;
294 if (g_dbglevel >= DBG_EXTENDED)
295 Dbprintf("MifareSimInit - FLAG_4B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_4B_UID_IN_DATA, flags, rUIDBCC1);
298 // save CUID
299 *cuid = bytes_to_num(rUIDBCC1, 4);
300 // BCC
301 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
302 if (g_dbglevel > DBG_NONE) {
303 Dbprintf("4B UID: %02x%02x%02x%02x", rUIDBCC1[0], rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3]);
306 // Correct uid size bits in ATQA
307 rATQA[0] = (rATQA[0] & 0x3f); // single size uid
309 } else if ((flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA) {
310 memcpy(&rUIDBCC1[1], datain, 3);
311 memcpy(rUIDBCC2, datain + 3, 4);
312 *uid_len = 7;
313 if (g_dbglevel >= DBG_EXTENDED)
314 Dbprintf("MifareSimInit - FLAG_7B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_7B_UID_IN_DATA, flags, rUIDBCC1);
316 // save CUID
317 *cuid = bytes_to_num(rUIDBCC2, 4);
318 // CascadeTag, CT
319 rUIDBCC1[0] = MIFARE_SELECT_CT;
320 // BCC
321 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
322 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
323 if (g_dbglevel > DBG_NONE) {
324 Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x",
325 rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3], rUIDBCC2[0], rUIDBCC2[1], rUIDBCC2[2], rUIDBCC2[3]);
328 // Correct uid size bits in ATQA
329 rATQA[0] = (rATQA[0] & 0x3f) | 0x40; // double size uid
331 } else if ((flags & FLAG_10B_UID_IN_DATA) == FLAG_10B_UID_IN_DATA) {
332 memcpy(&rUIDBCC1[1], datain, 3);
333 memcpy(&rUIDBCC2[1], datain + 3, 3);
334 memcpy(rUIDBCC3, datain + 6, 4);
335 *uid_len = 10;
336 if (g_dbglevel >= DBG_EXTENDED)
337 Dbprintf("MifareSimInit - FLAG_10B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_10B_UID_IN_DATA, flags, rUIDBCC1);
339 // save CUID
340 *cuid = bytes_to_num(rUIDBCC3, 4);
341 // CascadeTag, CT
342 rUIDBCC1[0] = MIFARE_SELECT_CT;
343 rUIDBCC2[0] = MIFARE_SELECT_CT;
344 // BCC
345 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
346 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
347 rUIDBCC3[4] = rUIDBCC3[0] ^ rUIDBCC3[1] ^ rUIDBCC3[2] ^ rUIDBCC3[3];
349 if (g_dbglevel > DBG_NONE) {
350 Dbprintf("10B UID: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
351 rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3],
352 rUIDBCC2[1], rUIDBCC2[2], rUIDBCC2[3],
353 rUIDBCC3[0], rUIDBCC3[1], rUIDBCC3[2], rUIDBCC3[3]
357 // Correct uid size bits in ATQA
358 rATQA[0] = (rATQA[0] & 0x3f) | 0x80; // triple size uid
359 } else {
360 Dbprintf("ERROR: " _RED_("UID size not defined"));
361 return false;
363 if (flags & FLAG_FORCED_ATQA) {
364 rATQA[0] = atqa >> 8;
365 rATQA[1] = atqa & 0xff;
367 if (flags & FLAG_FORCED_SAK) {
368 rSAK[0] = sak;
370 if (g_dbglevel > DBG_NONE) {
371 Dbprintf("ATQA : %02X %02X", rATQA[1], rATQA[0]);
372 Dbprintf("SAK : %02X", rSAK[0]);
375 // clone UIDs for byte-frame anti-collision multiple tag selection procedure
376 memcpy(rUIDBCC1b4, &rUIDBCC1[1], 4);
377 memcpy(rUIDBCC1b3, &rUIDBCC1[2], 3);
378 memcpy(rUIDBCC1b2, &rUIDBCC1[3], 2);
379 memcpy(rUIDBCC1b1, &rUIDBCC1[4], 1);
380 if (*uid_len >= 7) {
381 memcpy(rUIDBCC2b4, &rUIDBCC2[1], 4);
382 memcpy(rUIDBCC2b3, &rUIDBCC2[2], 3);
383 memcpy(rUIDBCC2b2, &rUIDBCC2[3], 2);
384 memcpy(rUIDBCC2b1, &rUIDBCC2[4], 1);
386 if (*uid_len == 10) {
387 memcpy(rUIDBCC3b4, &rUIDBCC3[1], 4);
388 memcpy(rUIDBCC3b3, &rUIDBCC3[2], 3);
389 memcpy(rUIDBCC3b2, &rUIDBCC3[3], 2);
390 memcpy(rUIDBCC3b1, &rUIDBCC3[4], 1);
393 // Calculate actual CRC
394 AddCrc14A(rSAK, sizeof(rSAK) - 2);
396 #define TAG_RESPONSE_COUNT 18
397 static tag_response_info_t responses_init[TAG_RESPONSE_COUNT] = {
398 { .response = rATQA, .response_n = sizeof(rATQA) }, // Answer to request - respond with card type
399 { .response = rSAK, .response_n = sizeof(rSAK) }, //
400 { .response = rSAKuid, .response_n = sizeof(rSAKuid) }, //
401 // Do not reorder. Block used via relative index of rUIDBCC1
402 { .response = rUIDBCC1, .response_n = sizeof(rUIDBCC1) }, // Anticollision cascade1 - respond with first part of uid
403 { .response = rUIDBCC1b4, .response_n = sizeof(rUIDBCC1b4)},
404 { .response = rUIDBCC1b3, .response_n = sizeof(rUIDBCC1b3)},
405 { .response = rUIDBCC1b2, .response_n = sizeof(rUIDBCC1b2)},
406 { .response = rUIDBCC1b1, .response_n = sizeof(rUIDBCC1b1)},
407 // Do not reorder. Block used via relative index of rUIDBCC2
408 { .response = rUIDBCC2, .response_n = sizeof(rUIDBCC2) }, // Anticollision cascade2 - respond with 2nd part of uid
409 { .response = rUIDBCC2b4, .response_n = sizeof(rUIDBCC2b4)},
410 { .response = rUIDBCC2b3, .response_n = sizeof(rUIDBCC2b3)},
411 { .response = rUIDBCC2b2, .response_n = sizeof(rUIDBCC2b2)},
412 { .response = rUIDBCC2b1, .response_n = sizeof(rUIDBCC2b1)},
413 // Do not reorder. Block used via relative index of rUIDBCC3
414 { .response = rUIDBCC3, .response_n = sizeof(rUIDBCC3) }, // Anticollision cascade3 - respond with 3th part of uid
415 { .response = rUIDBCC3b4, .response_n = sizeof(rUIDBCC3b4)},
416 { .response = rUIDBCC3b3, .response_n = sizeof(rUIDBCC3b3)},
417 { .response = rUIDBCC3b2, .response_n = sizeof(rUIDBCC3b2)},
418 { .response = rUIDBCC3b1, .response_n = sizeof(rUIDBCC3b1)}
421 // Prepare ("precompile") the responses of the anticollision phase.
422 // There will be not enough time to do this at the moment the reader sends its REQA or SELECT
423 // There are 18 predefined responses with a total of 53 bytes data to transmit.
424 // Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
425 // 53 * 8 data bits, 53 * 1 parity bits, 18 start bits, 18 stop bits, 18 correction bits -> need 571 bytes buffer
426 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 571
428 uint8_t *free_buffer = BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE);
429 // modulation buffer pointer and current buffer free space size
430 uint8_t *free_buffer_pointer = free_buffer;
431 size_t free_buffer_size = ALLOCATED_TAG_MODULATION_BUFFER_SIZE;
433 for (size_t i = 0; i < TAG_RESPONSE_COUNT; i++) {
434 if (prepare_allocated_tag_modulation(&responses_init[i], &free_buffer_pointer, &free_buffer_size) == false) {
435 Dbprintf("Not enough modulation buffer size, exit after %d elements", i);
436 return false;
440 *responses = responses_init;
442 // indices into responses array:
443 #define ATQA 0
444 #define SAK 1
445 #define SAKuid 2
446 #define UIDBCC1 3
447 #define UIDBCC2 8
448 #define UIDBCC3 13
450 return true;
454 *MIFARE 1K simulate.
456 *@param flags :
457 * FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
458 * FLAG_4B_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that
459 * FLAG_7B_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that
460 * FLAG_10B_UID_IN_DATA - use 10-byte UID in the data-section not finished
461 * FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later
462 *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ...
463 * (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attmpted)
465 void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *datain, uint16_t atqa, uint8_t sak) {
466 tag_response_info_t *responses;
467 uint8_t cardSTATE = MFEMUL_NOFIELD;
468 uint8_t uid_len = 0; // 4, 7, 10
469 uint32_t cuid = 0, selTimer = 0, authTimer = 0;
470 uint32_t nr, ar;
471 uint8_t blockNo;
472 bool encrypted_data;
474 uint8_t cardWRBL = 0;
475 uint8_t cardAUTHSC = 0;
476 uint8_t cardAUTHKEY = AUTHKEYNONE; // no authentication
477 uint32_t cardRr = 0;
478 uint32_t ans = 0;
479 uint32_t cardINTREG = 0;
480 uint8_t cardINTBLOCK = 0;
482 struct Crypto1State mpcs = {0, 0};
483 struct Crypto1State *pcs;
484 pcs = &mpcs;
486 uint32_t numReads = 0; //Counts numer of times reader reads a block
487 uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00};
488 uint8_t receivedCmd_dec[MAX_MIFARE_FRAME_SIZE] = {0x00};
489 uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
490 uint16_t receivedCmd_len;
492 uint8_t response[MAX_MIFARE_FRAME_SIZE] = {0x00};
493 uint8_t response_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
495 uint8_t *rats = NULL;
496 uint8_t rats_len = 0;
499 // if fct is called with NULL we need to assign some memory since this pointer is passaed around
500 uint8_t datain_tmp[10] = {0};
501 if (datain == NULL) {
502 datain = datain_tmp;
505 //Here, we collect UID,sector,keytype,NT,AR,NR,NT2,AR2,NR2
506 // This will be used in the reader-only attack.
508 //allow collecting up to 7 sets of nonces to allow recovery of up to 7 keys
509 #define ATTACK_KEY_COUNT 7 // keep same as define in cmdhfmf.c -> readerAttack() (Cannot be more than 7)
510 nonces_t ar_nr_resp[ATTACK_KEY_COUNT * 2]; // *2 for 2 separate attack types (nml, moebius) 36 * 7 * 2 bytes = 504 bytes
511 memset(ar_nr_resp, 0x00, sizeof(ar_nr_resp));
513 uint8_t ar_nr_collected[ATTACK_KEY_COUNT * 2]; // *2 for 2nd attack type (moebius)
514 memset(ar_nr_collected, 0x00, sizeof(ar_nr_collected));
515 uint8_t nonce1_count = 0;
516 uint8_t nonce2_count = 0;
517 uint8_t moebius_n_count = 0;
518 bool gettingMoebius = false;
519 uint8_t mM = 0; //moebius_modifier for collection storage
521 // Authenticate response - nonce
522 uint8_t rAUTH_NT[4] = {0, 0, 0, 1};
523 uint8_t rAUTH_NT_keystream[4];
524 uint32_t nonce = 0;
526 const tUart14a *uart = GetUart14a();
528 // free eventually allocated BigBuf memory but keep Emulator Memory
529 BigBuf_free_keep_EM();
531 if (MifareSimInit(flags, datain, atqa, sak, &responses, &cuid, &uid_len, &rats, &rats_len) == false) {
532 BigBuf_free_keep_EM();
533 return;
536 // We need to listen to the high-frequency, peak-detected path.
537 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN);
539 // clear trace
540 clear_trace();
541 set_tracing(true);
542 LED_D_ON();
543 ResetSspClk();
545 uint8_t *p_em = BigBuf_get_EM_addr();
546 uint8_t cve_flipper = 0;
548 int counter = 0;
549 bool finished = false;
550 bool button_pushed = BUTTON_PRESS();
551 while ((button_pushed == false) && (finished == false)) {
553 WDT_HIT();
555 if (counter == 3000) {
556 if (data_available()) {
557 Dbprintf("----------- " _GREEN_("BREAKING") " ----------");
558 break;
560 counter = 0;
561 } else {
562 counter++;
566 // find reader field
567 if (cardSTATE == MFEMUL_NOFIELD) {
569 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
571 if (vHf > MF_MINFIELDV) {
572 cardSTATE_TO_IDLE();
573 LED_A_ON();
575 button_pushed = BUTTON_PRESS();
576 continue;
580 FpgaEnableTracing();
581 //Now, get data
582 int res = EmGetCmd(receivedCmd, sizeof(receivedCmd), &receivedCmd_len, receivedCmd_par);
584 if (res == 2) { //Field is off!
585 //FpgaDisableTracing();
586 if ((flags & FLAG_CVE21_0430) == FLAG_CVE21_0430) {
587 p_em[1] = 0x21;
588 cve_flipper = 0;
590 LEDsoff();
591 cardSTATE = MFEMUL_NOFIELD;
592 if (g_dbglevel >= DBG_EXTENDED)
593 Dbprintf("cardSTATE = MFEMUL_NOFIELD");
594 continue;
595 } else if (res == 1) { // button pressed
596 FpgaDisableTracing();
597 button_pushed = true;
598 if (g_dbglevel >= DBG_EXTENDED)
599 Dbprintf("Button pressed");
600 break;
603 // WUPA in HALTED state or REQA or WUPA in any other state
604 if (receivedCmd_len == 1 && ((receivedCmd[0] == ISO14443A_CMD_REQA && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == ISO14443A_CMD_WUPA)) {
605 selTimer = GetTickCount();
606 if (g_dbglevel >= DBG_EXTENDED) {
607 //Dbprintf("EmSendPrecompiledCmd(&responses[ATQA]);");
609 EmSendPrecompiledCmd(&responses[ATQA]);
611 FpgaDisableTracing();
613 // init crypto block
614 crypto1_deinit(pcs);
615 cardAUTHKEY = AUTHKEYNONE;
616 nonce = prng_successor(selTimer, 32);
617 // prepare NT for nested authentication
618 num_to_bytes(nonce, 4, rAUTH_NT);
619 num_to_bytes(cuid ^ nonce, 4, rAUTH_NT_keystream);
621 LED_B_OFF();
622 LED_C_OFF();
623 cardSTATE = MFEMUL_SELECT;
625 if ((flags & FLAG_CVE21_0430) == FLAG_CVE21_0430) {
626 p_em[1] = 0x21;
627 cve_flipper = 0;
629 continue;
632 switch (cardSTATE) {
633 case MFEMUL_NOFIELD: {
634 if (g_dbglevel >= DBG_EXTENDED)
635 Dbprintf("MFEMUL_NOFIELD");
636 break;
638 case MFEMUL_HALTED: {
639 if (g_dbglevel >= DBG_EXTENDED)
640 Dbprintf("MFEMUL_HALTED");
641 break;
643 case MFEMUL_IDLE: {
644 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
645 if (g_dbglevel >= DBG_EXTENDED)
646 Dbprintf("MFEMUL_IDLE");
647 break;
650 // The anti-collision sequence, which is a mandatory part of the card activation sequence.
651 // It auto with 4-byte UID (= Single Size UID),
652 // 7 -byte UID (= Double Size UID) or 10-byte UID (= Triple Size UID).
653 // For details see chapter 2 of AN10927.pdf
655 // This case is used for all Cascade Levels, because:
656 // 1) Any devices (under Android for example) after full select procedure completed,
657 // when UID is known, uses "fast-selection" method. In this case reader ignores
658 // first cascades and tries to select tag by last bytes of UID of last cascade
659 // 2) Any readers (like ACR122U) uses bit oriented anti-collision frames during selectin,
660 // same as multiple tags. For details see chapter 6.1.5.3 of ISO/IEC 14443-3
661 case MFEMUL_SELECT: {
662 int uid_index = -1;
663 // Extract cascade level
664 if (receivedCmd_len >= 2) {
665 switch (receivedCmd[0]) {
666 case ISO14443A_CMD_ANTICOLL_OR_SELECT:
667 uid_index = UIDBCC1;
668 break;
669 case ISO14443A_CMD_ANTICOLL_OR_SELECT_2:
670 uid_index = UIDBCC2;
671 break;
672 case ISO14443A_CMD_ANTICOLL_OR_SELECT_3:
673 uid_index = UIDBCC3;
674 break;
677 if (uid_index < 0) {
678 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
679 cardSTATE_TO_IDLE();
680 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] Incorrect cascade level received");
681 break;
684 // Incoming SELECT ALL for any cascade level
685 if (receivedCmd_len == 2 && receivedCmd[1] == 0x20) {
686 EmSendPrecompiledCmd(&responses[uid_index]);
687 FpgaDisableTracing();
689 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("SELECT ALL - EmSendPrecompiledCmd(%02x)", &responses[uid_index]);
690 break;
693 // Incoming SELECT CLx for any cascade level
694 if (receivedCmd_len == 9 && receivedCmd[1] == 0x70) {
695 if (memcmp(&receivedCmd[2], responses[uid_index].response, 4) == 0) {
696 bool cl_finished = (uid_len == 4 && uid_index == UIDBCC1) ||
697 (uid_len == 7 && uid_index == UIDBCC2) ||
698 (uid_len == 10 && uid_index == UIDBCC3);
699 EmSendPrecompiledCmd(&responses[cl_finished ? SAK : SAKuid]);
700 FpgaDisableTracing();
702 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("SELECT CLx %02x%02x%02x%02x received", receivedCmd[2], receivedCmd[3], receivedCmd[4], receivedCmd[5]);
703 if (cl_finished) {
704 LED_B_ON();
705 cardSTATE = MFEMUL_WORK;
706 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_WORK");
708 } else {
709 // IDLE, not our UID
710 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
711 cardSTATE_TO_IDLE();
712 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_IDLE");
714 break;
717 // Incoming anti-collision frame
718 // receivedCmd[1] indicates number of byte and bit collision, supports only for bit collision is zero
719 if (receivedCmd_len >= 3 && receivedCmd_len <= 6 && (receivedCmd[1] & 0x0f) == 0) {
720 // we can process only full-byte frame anti-collision procedure
721 if (memcmp(&receivedCmd[2], responses[uid_index].response, receivedCmd_len - 2) == 0) {
722 // response missing part of UID via relative array index
723 EmSendPrecompiledCmd(&responses[uid_index + receivedCmd_len - 2]);
724 FpgaDisableTracing();
726 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("SELECT ANTICOLLISION - EmSendPrecompiledCmd(%02x)", &responses[uid_index]);
727 } else {
728 // IDLE, not our UID or split-byte frame anti-collision (not supports)
729 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
730 cardSTATE_TO_IDLE();
731 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_IDLE");
733 break;
736 // Unknown selection procedure
737 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
738 cardSTATE_TO_IDLE();
739 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_SELECT] Unknown selection procedure");
740 break;
743 // WORK
744 case MFEMUL_WORK: {
746 if (g_dbglevel >= DBG_EXTENDED) {
747 // Dbprintf("[MFEMUL_WORK] Enter in case");
750 if (receivedCmd_len == 0) {
751 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] NO CMD received");
752 break;
755 encrypted_data = (cardAUTHKEY != AUTHKEYNONE);
756 if (encrypted_data) {
757 // decrypt seqence
758 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
759 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Decrypt sequence");
760 } else {
761 // Data in clear
762 memcpy(receivedCmd_dec, receivedCmd, receivedCmd_len);
765 // all commands must have a valid CRC
766 if (CheckCrc14A(receivedCmd_dec, receivedCmd_len) == false) {
767 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
768 FpgaDisableTracing();
770 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] All commands must have a valid CRC %02X (%d)", receivedCmd_dec, receivedCmd_len);
771 break;
774 if (receivedCmd_len == 4 && (receivedCmd_dec[0] == MIFARE_AUTH_KEYA || receivedCmd_dec[0] == MIFARE_AUTH_KEYB)) {
776 // Reader asks for AUTH: 6X XX
777 // RCV: 60 XX => Using KEY A
778 // RCV: 61 XX => Using KEY B
779 // XX: Block number
781 authTimer = GetTickCount();
783 // received block num -> sector
784 // Example: 6X [00]
785 // 4K tags have 16 blocks per sector 32..39
786 cardAUTHSC = MifareBlockToSector(receivedCmd_dec[1]);
788 // cardAUTHKEY: 60 => Auth use Key A
789 // cardAUTHKEY: 61 => Auth use Key B
790 cardAUTHKEY = receivedCmd_dec[0] & 0x01;
792 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] KEY %c: %012" PRIx64, (cardAUTHKEY == 0) ? 'A' : 'B', emlGetKey(cardAUTHSC, cardAUTHKEY));
794 // first authentication
795 crypto1_deinit(pcs);
797 // Load key into crypto
798 crypto1_init(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
800 if (!encrypted_data) {
801 // Receive Cmd in clear txt
802 // Update crypto state (UID ^ NONCE)
803 crypto1_word(pcs, cuid ^ nonce, 0);
804 // rAUTH_NT contains prepared nonce for authenticate
805 EmSendCmd(rAUTH_NT, sizeof(rAUTH_NT));
806 FpgaDisableTracing();
808 if (g_dbglevel >= DBG_EXTENDED) {
809 Dbprintf("[MFEMUL_WORK] Reader authenticating for block %d (0x%02x) with key %c - nonce: %08X - cuid: %08X",
810 receivedCmd_dec[1],
811 receivedCmd_dec[1],
812 (cardAUTHKEY == 0) ? 'A' : 'B',
813 nonce,
814 cuid
817 } else {
818 // nested authentication
820 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
821 num_to_bytes(ans, 4, rAUTH_AT);
823 // rAUTH_NT, rAUTH_NT_keystream contains prepared nonce and keystream for nested authentication
824 // we need calculate parity bits for non-encrypted sequence
825 mf_crypto1_encryptEx(pcs, rAUTH_NT, rAUTH_NT_keystream, response, 4, response_par);
826 EmSendCmdPar(response, 4, response_par);
827 FpgaDisableTracing();
829 if (g_dbglevel >= DBG_EXTENDED) {
830 Dbprintf("[MFEMUL_WORK] Reader doing nested authentication for block %d (0x%02x) with key %c",
831 receivedCmd_dec[1],
832 receivedCmd_dec[1],
833 (cardAUTHKEY == 0) ? 'A' : 'B'
838 cardSTATE = MFEMUL_AUTH1;
839 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_AUTH1 - rAUTH_NT: %02X", rAUTH_NT);
840 break;
843 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
844 // BUT... ACK --> NACK
845 if (receivedCmd_len == 1 && receivedCmd_dec[0] == CARD_ACK) {
846 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
847 FpgaDisableTracing();
848 break;
851 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
852 if (receivedCmd_len == 1 && receivedCmd_dec[0] == CARD_NACK_NA) {
853 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_ACK) : CARD_ACK);
854 FpgaDisableTracing();
855 break;
858 // case MFEMUL_WORK => if Cmd is Read, Write, Inc, Dec, Restore, Transfer
859 if (receivedCmd_len == 4 && (receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK
860 || receivedCmd_dec[0] == ISO14443A_CMD_WRITEBLOCK
861 || receivedCmd_dec[0] == MIFARE_CMD_INC
862 || receivedCmd_dec[0] == MIFARE_CMD_DEC
863 || receivedCmd_dec[0] == MIFARE_CMD_RESTORE
864 || receivedCmd_dec[0] == MIFARE_CMD_TRANSFER)) {
865 // all other commands must be encrypted (authenticated)
866 if (!encrypted_data) {
867 EmSend4bit(CARD_NACK_NA);
868 FpgaDisableTracing();
870 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Commands must be encrypted (authenticated)");
871 break;
874 // iceman, u8 can never be larger the MIFARE_4K_MAXBLOCK (256)
875 // Check if Block num is not too far
877 if (receivedCmd_dec[1] > MIFARE_4K_MAXBLOCK) {
878 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
879 FpgaDisableTracing();
880 if (g_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]);
881 break;
884 blockNo = receivedCmd_dec[1];
885 if (MifareBlockToSector(blockNo) != cardAUTHSC) {
886 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
887 FpgaDisableTracing();
889 if (g_dbglevel >= DBG_ERROR)
890 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);
891 break;
894 // Compliance of MIFARE Classic EV1 1K Datasheet footnote of Table 8
895 // If access bits show that key B is Readable, any subsequent memory access will be refused.
897 if (cardAUTHKEY == AUTHKEYB && IsKeyBReadable(blockNo)) {
898 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
899 FpgaDisableTracing();
901 if (g_dbglevel >= DBG_ERROR)
902 Dbprintf("[MFEMUL_WORK] Access denied: Reader tried to access memory on authentication with key B while key B is readable in sector (0x%02x)", cardAUTHSC);
903 break;
907 // case MFEMUL_WORK => CMD READ block
908 if (receivedCmd_len == 4 && receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK) {
909 blockNo = receivedCmd_dec[1];
910 if (g_dbglevel >= DBG_EXTENDED)
911 Dbprintf("[MFEMUL_WORK] Reader reading block %d (0x%02x)", blockNo, blockNo);
913 // android CVE 2021_0430
914 // Simulate a MFC 1K, with a NDEF message.
915 // these values uses the standard LIBNFC NDEF message
917 // In short, first a value read of block 4,
918 // update the length byte before second read of block 4.
919 // on iphone etc there might even be 3 reads of block 4.
920 // fiddling with when to flip the byte or not, has different effects
921 if ((flags & FLAG_CVE21_0430) == FLAG_CVE21_0430) {
923 // first block
924 if (blockNo == 4) {
926 p_em += blockNo * 16;
927 // TLV in NDEF, flip length between
928 // 4 | 03 21 D1 02 1C 53 70 91 01 09 54 02 65 6E 4C 69
929 // 0xFF means long length
930 // 0xFE mean max short length
932 // We could also have a go at message len byte at p_em[4]...
933 if (p_em[1] == 0x21 && cve_flipper == 1) {
934 p_em[1] = 0xFE;
935 } else {
936 cve_flipper++;
941 emlGetMem(response, blockNo, 1);
943 if (g_dbglevel >= DBG_EXTENDED) {
944 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,
945 response[0], response[1], response[2], response[3], response[4], response[5], response[6],
946 response[7], response[8], response[9], response[10], response[11], response[12], response[13],
947 response[14], response[15]);
950 // Access permission management:
952 // Sector Trailer:
953 // - KEY A access
954 // - KEY B access
955 // - AC bits access
957 // Data block:
958 // - Data access
960 // If permission is not allowed, data is cleared (00) in emulator memory.
961 // ex: a0a1a2a3a4a561e789c1b0b1b2b3b4b5 => 00000000000061e789c1b0b1b2b3b4b5
964 // Check if selected Block is a Sector Trailer
965 if (IsSectorTrailer(blockNo)) {
967 if (IsAccessAllowed(blockNo, cardAUTHKEY, AC_KEYA_READ) == false) {
968 memset(response, 0x00, 6); // keyA can never be read
969 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyA can never be read - block %d (0x%02x)", blockNo, blockNo);
971 if (IsAccessAllowed(blockNo, cardAUTHKEY, AC_KEYB_READ) == false) {
972 memset(response + 10, 0x00, 6); // keyB cannot be read
973 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyB cannot be read - block %d (0x%02x)", blockNo, blockNo);
975 if (IsAccessAllowed(blockNo, cardAUTHKEY, AC_AC_READ) == false) {
976 memset(response + 6, 0x00, 4); // AC bits cannot be read
977 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] AC bits cannot be read - block %d (0x%02x)", blockNo, blockNo);
979 } else {
980 if (IsAccessAllowed(blockNo, cardAUTHKEY, AC_DATA_READ) == false) {
981 memset(response, 0x00, 16); // datablock cannot be read
982 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] Data block %d (0x%02x) cannot be read", blockNo, blockNo);
985 AddCrc14A(response, 16);
986 mf_crypto1_encrypt(pcs, response, MAX_MIFARE_FRAME_SIZE, response_par);
987 EmSendCmdPar(response, MAX_MIFARE_FRAME_SIZE, response_par);
988 FpgaDisableTracing();
990 if (g_dbglevel >= DBG_EXTENDED) {
991 Dbprintf("[MFEMUL_WORK - EmSendCmdPar] Data Block[%d]: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", blockNo,
992 response[0], response[1], response[2], response[3], response[4], response[5], response[6],
993 response[7], response[8], response[9], response[10], response[11], response[12], response[13],
994 response[14], response[15]);
996 numReads++;
998 if (exitAfterNReads > 0 && numReads == exitAfterNReads) {
999 Dbprintf("[MFEMUL_WORK] %d reads done, exiting", numReads);
1000 finished = true;
1002 break;
1004 } // End receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK
1006 // case MFEMUL_WORK => CMD WRITEBLOCK
1007 if (receivedCmd_len == 4 && receivedCmd_dec[0] == ISO14443A_CMD_WRITEBLOCK) {
1008 blockNo = receivedCmd_dec[1];
1009 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0xA0 write block %d (%02x)", blockNo, blockNo);
1010 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
1011 FpgaDisableTracing();
1013 cardWRBL = blockNo;
1014 cardSTATE = MFEMUL_WRITEBL2;
1015 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_WRITEBL2");
1016 break;
1019 // case MFEMUL_WORK => CMD INC/DEC/REST
1020 if (receivedCmd_len == 4 && (receivedCmd_dec[0] == MIFARE_CMD_INC || receivedCmd_dec[0] == MIFARE_CMD_DEC || receivedCmd_dec[0] == MIFARE_CMD_RESTORE)) {
1021 blockNo = receivedCmd_dec[1];
1022 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)", receivedCmd_dec[0], blockNo, blockNo);
1023 if (emlCheckValBl(blockNo) == false) {
1024 if (g_dbglevel >= DBG_ERROR) Dbprintf("[MFEMUL_WORK] Reader tried to operate on block, but emlCheckValBl failed, nacking");
1025 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
1026 FpgaDisableTracing();
1027 break;
1029 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
1030 FpgaDisableTracing();
1031 cardWRBL = blockNo;
1033 // INC
1034 if (receivedCmd_dec[0] == MIFARE_CMD_INC) {
1035 cardSTATE = MFEMUL_INTREG_INC;
1036 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_INC");
1039 // DEC
1040 if (receivedCmd_dec[0] == MIFARE_CMD_DEC) {
1041 cardSTATE = MFEMUL_INTREG_DEC;
1042 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_DEC");
1045 // REST
1046 if (receivedCmd_dec[0] == MIFARE_CMD_RESTORE) {
1047 cardSTATE = MFEMUL_INTREG_REST;
1048 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_REST");
1050 break;
1052 } // End case MFEMUL_WORK => CMD INC/DEC/REST
1055 // case MFEMUL_WORK => CMD TRANSFER
1056 if (receivedCmd_len == 4 && receivedCmd_dec[0] == MIFARE_CMD_TRANSFER) {
1057 blockNo = receivedCmd_dec[1];
1058 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] RECV 0x%02x transfer block %d (%02x)", receivedCmd_dec[0], blockNo, blockNo);
1059 emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd_dec[1]);
1060 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
1061 FpgaDisableTracing();
1062 break;
1065 // case MFEMUL_WORK => CMD HALT
1066 if (receivedCmd_len > 1 && receivedCmd_dec[0] == ISO14443A_CMD_HALT && receivedCmd_dec[1] == 0x00) {
1067 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1068 LED_B_OFF();
1069 LED_C_OFF();
1070 cardSTATE = MFEMUL_HALTED;
1071 cardAUTHKEY = AUTHKEYNONE;
1072 if (g_dbglevel >= DBG_EXTENDED) {
1073 Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_HALTED");
1075 break;
1078 // case MFEMUL_WORK => CMD RATS
1079 if (receivedCmd_len == 4 && receivedCmd_dec[0] == ISO14443A_CMD_RATS && (receivedCmd_dec[1] & 0xF0) <= 0x80 && (receivedCmd_dec[1] & 0x0F) <= 0x0e) {
1080 if (rats && rats_len) {
1081 if (encrypted_data) {
1082 memcpy(response, rats, rats_len);
1083 mf_crypto1_encrypt(pcs, response, rats_len, response_par);
1084 EmSendCmdPar(response, rats_len, response_par);
1085 } else {
1086 EmSendCmd(rats, rats_len);
1088 FpgaDisableTracing();
1089 if (g_dbglevel >= DBG_EXTENDED)
1090 Dbprintf("[MFEMUL_WORK] RCV RATS => ACK");
1091 } else {
1092 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
1093 FpgaDisableTracing();
1094 cardSTATE_TO_IDLE();
1095 if (g_dbglevel >= DBG_EXTENDED)
1096 Dbprintf("[MFEMUL_WORK] RCV RATS => NACK");
1098 break;
1101 // case MFEMUL_WORK => ISO14443A_CMD_NXP_DESELECT
1102 if (receivedCmd_len == 3 && receivedCmd_dec[0] == ISO14443A_CMD_NXP_DESELECT) {
1103 if (rats && rats_len) {
1104 // response back NXP_DESELECT
1105 if (encrypted_data) {
1106 memcpy(response, receivedCmd_dec, receivedCmd_len);
1107 mf_crypto1_encrypt(pcs, response, receivedCmd_len, response_par);
1108 EmSendCmdPar(response, receivedCmd_len, response_par);
1109 } else
1110 EmSendCmd(receivedCmd_dec, receivedCmd_len);
1112 FpgaDisableTracing();
1113 if (g_dbglevel >= DBG_EXTENDED)
1114 Dbprintf("[MFEMUL_WORK] RCV NXP DESELECT => ACK");
1115 } else {
1116 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
1117 FpgaDisableTracing();
1118 cardSTATE_TO_IDLE();
1119 if (g_dbglevel >= DBG_EXTENDED)
1120 Dbprintf("[MFEMUL_WORK] RCV NXP DESELECT => NACK");
1122 break;
1125 // case MFEMUL_WORK => command not allowed
1126 if (g_dbglevel >= DBG_EXTENDED)
1127 Dbprintf("Received command not allowed, nacking");
1128 EmSend4bit(encrypted_data ? mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA) : CARD_NACK_NA);
1129 FpgaDisableTracing();
1130 break;
1133 // AUTH1
1134 case MFEMUL_AUTH1: {
1135 if (g_dbglevel >= DBG_EXTENDED)
1136 Dbprintf("[MFEMUL_AUTH1] Enter case");
1138 if (receivedCmd_len != 8) {
1139 cardSTATE_TO_IDLE();
1140 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1141 if (g_dbglevel >= DBG_EXTENDED)
1142 Dbprintf("MFEMUL_AUTH1: receivedCmd_len != 8 (%d) => cardSTATE_TO_IDLE())", receivedCmd_len);
1143 break;
1146 nr = bytes_to_num(receivedCmd, 4);
1147 ar = bytes_to_num(&receivedCmd[4], 4);
1149 // Collect AR/NR per keytype & sector
1150 if ((flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK) {
1152 for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
1153 if (ar_nr_collected[i + mM] == 0 ||
1155 (cardAUTHSC == ar_nr_resp[i + mM].sector) &&
1156 (cardAUTHKEY == ar_nr_resp[i + mM].keytype) &&
1157 (ar_nr_collected[i + mM] > 0)
1160 // if first auth for sector, or matches sector and keytype of previous auth
1161 if (ar_nr_collected[i + mM] < 2) {
1162 // if we haven't already collected 2 nonces for this sector
1163 if (ar_nr_resp[ar_nr_collected[i + mM]].ar != ar) {
1164 // Avoid duplicates... probably not necessary, ar should vary.
1165 if (ar_nr_collected[i + mM] == 0) {
1166 // first nonce collect
1167 ar_nr_resp[i + mM].cuid = cuid;
1168 ar_nr_resp[i + mM].sector = cardAUTHSC;
1169 ar_nr_resp[i + mM].keytype = cardAUTHKEY;
1170 ar_nr_resp[i + mM].nonce = nonce;
1171 ar_nr_resp[i + mM].nr = nr;
1172 ar_nr_resp[i + mM].ar = ar;
1173 nonce1_count++;
1174 // add this nonce to first moebius nonce
1175 ar_nr_resp[i + ATTACK_KEY_COUNT].cuid = cuid;
1176 ar_nr_resp[i + ATTACK_KEY_COUNT].sector = cardAUTHSC;
1177 ar_nr_resp[i + ATTACK_KEY_COUNT].keytype = cardAUTHKEY;
1178 ar_nr_resp[i + ATTACK_KEY_COUNT].nonce = nonce;
1179 ar_nr_resp[i + ATTACK_KEY_COUNT].nr = nr;
1180 ar_nr_resp[i + ATTACK_KEY_COUNT].ar = ar;
1181 ar_nr_collected[i + ATTACK_KEY_COUNT]++;
1182 } else { // second nonce collect (std and moebius)
1183 ar_nr_resp[i + mM].nonce2 = nonce;
1184 ar_nr_resp[i + mM].nr2 = nr;
1185 ar_nr_resp[i + mM].ar2 = ar;
1187 if (!gettingMoebius) {
1188 nonce2_count++;
1189 // check if this was the last second nonce we need for std attack
1190 if (nonce2_count == nonce1_count) {
1191 // done collecting std test switch to moebius
1192 // first finish incrementing last sample
1193 ar_nr_collected[i + mM]++;
1194 // switch to moebius collection
1195 gettingMoebius = true;
1196 mM = ATTACK_KEY_COUNT;
1197 nonce = nonce * 7;
1198 break;
1200 } else {
1201 moebius_n_count++;
1202 // if we've collected all the nonces we need - finish.
1203 if (nonce1_count == moebius_n_count)
1204 finished = true;
1207 ar_nr_collected[i + mM]++;
1210 // we found right spot for this nonce stop looking
1211 break;
1216 // --- crypto
1217 crypto1_word(pcs, nr, 1);
1218 cardRr = ar ^ crypto1_word(pcs, 0, 0);
1220 // test if auth KO
1221 if (cardRr != prng_successor(nonce, 64)) {
1222 if (g_dbglevel >= DBG_EXTENDED) {
1223 Dbprintf("[MFEMUL_AUTH1] AUTH FAILED for sector %d with key %c. [nr=%08x cardRr=%08x] [nt=%08x succ=%08x]"
1224 , cardAUTHSC
1225 , (cardAUTHKEY == 0) ? 'A' : 'B'
1226 , nr
1227 , cardRr
1228 , nonce // nt
1229 , prng_successor(nonce, 64)
1232 cardAUTHKEY = AUTHKEYNONE; // not authenticated
1233 cardSTATE_TO_IDLE();
1234 // Really tags not respond NACK on invalid authentication
1235 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1236 break;
1239 ans = prng_successor(nonce, 96);
1240 num_to_bytes(ans, 4, response);
1241 mf_crypto1_encrypt(pcs, response, 4, response_par);
1242 EmSendCmdPar(response, 4, response_par);
1243 FpgaDisableTracing();
1245 if (g_dbglevel >= DBG_EXTENDED) {
1246 Dbprintf("[MFEMUL_AUTH1] AUTH COMPLETED for sector %d with key %c. time=%d",
1247 cardAUTHSC,
1248 cardAUTHKEY == 0 ? 'A' : 'B',
1249 GetTickCountDelta(authTimer)
1252 LED_C_ON();
1253 cardSTATE = MFEMUL_WORK;
1254 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_AUTH1] cardSTATE = MFEMUL_WORK");
1255 break;
1258 // WRITE BL2
1259 case MFEMUL_WRITEBL2: {
1260 if (receivedCmd_len == MAX_MIFARE_FRAME_SIZE) {
1261 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
1262 if (CheckCrc14A(receivedCmd_dec, receivedCmd_len)) {
1263 if (IsSectorTrailer(cardWRBL)) {
1264 emlGetMem(response, cardWRBL, 1);
1265 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYA_WRITE)) {
1266 memcpy(receivedCmd_dec, response, 6); // don't change KeyA
1268 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYB_WRITE)) {
1269 memcpy(receivedCmd_dec + 10, response + 10, 6); // don't change KeyA
1271 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_AC_WRITE)) {
1272 memcpy(receivedCmd_dec + 6, response + 6, 4); // don't change AC bits
1274 } else {
1275 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_DATA_WRITE)) {
1276 memcpy(receivedCmd_dec, response, 16); // don't change anything
1279 emlSetMem_xt(receivedCmd_dec, cardWRBL, 1, 16);
1280 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK)); // always ACK?
1281 FpgaDisableTracing();
1283 cardSTATE = MFEMUL_WORK;
1284 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_WORK");
1285 break;
1288 cardSTATE_TO_IDLE();
1289 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_IDLE");
1290 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1291 break;
1294 // INC
1295 case MFEMUL_INTREG_INC: {
1296 if (receivedCmd_len == 6) {
1297 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
1298 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL) != PM3_SUCCESS) {
1299 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
1300 FpgaDisableTracing();
1302 cardSTATE_TO_IDLE();
1303 break;
1305 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1306 cardINTREG = cardINTREG + ans;
1308 cardSTATE = MFEMUL_WORK;
1309 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_INC] cardSTATE = MFEMUL_WORK");
1310 break;
1314 // DEC
1315 case MFEMUL_INTREG_DEC: {
1316 if (receivedCmd_len == 6) { // Data is encrypted
1317 // Decrypted cmd
1318 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
1319 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL) != PM3_SUCCESS) {
1320 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
1321 FpgaDisableTracing();
1323 cardSTATE_TO_IDLE();
1324 break;
1327 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1328 cardINTREG = cardINTREG - ans;
1329 cardSTATE = MFEMUL_WORK;
1330 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_DEC] cardSTATE = MFEMUL_WORK");
1331 break;
1334 // REST
1335 case MFEMUL_INTREG_REST: {
1336 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t *)&ans);
1337 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL) != PM3_SUCCESS) {
1338 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
1339 FpgaDisableTracing();
1341 cardSTATE_TO_IDLE();
1342 break;
1344 LogTrace(uart->output, uart->len, uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, uart->parity, true);
1345 cardSTATE = MFEMUL_WORK;
1346 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_INTREG_REST] cardSTATE = MFEMUL_WORK");
1347 break;
1350 } // End Switch Loop
1352 button_pushed = BUTTON_PRESS();
1354 } // End While Loop
1356 FpgaDisableTracing();
1358 // NR AR ATTACK
1359 // mfkey32
1360 if (((flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK) && (g_dbglevel >= DBG_INFO)) {
1361 for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
1362 if (ar_nr_collected[i] == 2) {
1363 Dbprintf("Collected two pairs of AR/NR which can be used to extract sector %d " _YELLOW_("%s")
1364 , ar_nr_resp[i].sector
1365 , (ar_nr_resp[i].keytype == AUTHKEYA) ? "key A" : "key B"
1367 Dbprintf("../tools/mfc/card_reader/mfkey32 %08x %08x %08x %08x %08x %08x",
1368 ar_nr_resp[i].cuid, //UID
1369 ar_nr_resp[i].nonce, //NT
1370 ar_nr_resp[i].nr, //NR1
1371 ar_nr_resp[i].ar, //AR1
1372 ar_nr_resp[i].nr2, //NR2
1373 ar_nr_resp[i].ar2 //AR2
1379 // mfkey32 v2
1380 for (uint8_t i = ATTACK_KEY_COUNT; i < ATTACK_KEY_COUNT * 2; i++) {
1381 if (ar_nr_collected[i] == 2) {
1382 Dbprintf("Collected two pairs of AR/NR which can be used to extract sector %d " _YELLOW_("%s")
1383 , ar_nr_resp[i].sector
1384 , (ar_nr_resp[i].keytype == AUTHKEYB) ? "key A" : "key B"
1386 Dbprintf("../tools/mfc/card_reader/mfkey32v2 %08x %08x %08x %08x %08x %08x %08x",
1387 ar_nr_resp[i].cuid, //UID
1388 ar_nr_resp[i].nonce, //NT
1389 ar_nr_resp[i].nr, //NR1
1390 ar_nr_resp[i].ar, //AR1
1391 ar_nr_resp[i].nonce2,//NT2
1392 ar_nr_resp[i].nr2, //NR2
1393 ar_nr_resp[i].ar2 //AR2
1398 if (g_dbglevel >= DBG_ERROR) {
1399 Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", get_tracing(), BigBuf_get_traceLen());
1402 if ((flags & FLAG_INTERACTIVE) == FLAG_INTERACTIVE) { // Interactive mode flag, means we need to send ACK
1403 //Send the collected ar_nr in the response
1404 reply_mix(CMD_ACK, CMD_HF_MIFARE_SIMULATE, button_pushed, 0, &ar_nr_resp, sizeof(ar_nr_resp));
1407 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1408 LEDsoff();
1409 set_tracing(false);
1410 BigBuf_free_keep_EM();