1 //-----------------------------------------------------------------------------
2 // Copyright (C) Gerhard de Koning Gans - May 2008
3 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
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.
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 //-----------------------------------------------------------------------------
27 // /!\ Printing Debug message is disrupting emulation,
28 // Only use with caution during debugging
30 #include "mifaresim.h"
34 #include "iso14443a.h"
37 #include "mifareutil.h"
38 #include "fpgaloader.h"
39 #include "proxmark3_arm.h"
41 #include "protocols.h"
44 #include "commonutil.h"
50 static bool IsKeyBReadable(uint8_t blockNo
) {
51 uint8_t sector_trailer
[16];
52 emlGetMem(sector_trailer
, SectorTrailer(blockNo
), 1);
53 uint8_t AC
= ((sector_trailer
[7] >> 5) & 0x04)
54 | ((sector_trailer
[8] >> 2) & 0x02)
55 | ((sector_trailer
[8] >> 7) & 0x01);
56 return (AC
== 0x00 || AC
== 0x01 || AC
== 0x02);
59 static bool IsTrailerAccessAllowed(uint8_t blockNo
, uint8_t keytype
, uint8_t action
) {
60 uint8_t sector_trailer
[16];
61 emlGetMem(sector_trailer
, blockNo
, 1);
62 uint8_t AC
= ((sector_trailer
[7] >> 5) & 0x04)
63 | ((sector_trailer
[8] >> 2) & 0x02)
64 | ((sector_trailer
[8] >> 7) & 0x01);
67 if (g_dbglevel
>= DBG_EXTENDED
)
68 Dbprintf("IsTrailerAccessAllowed: AC_KEYA_READ");
72 if (g_dbglevel
>= DBG_EXTENDED
)
73 Dbprintf("IsTrailerAccessAllowed: AC_KEYA_WRITE");
74 return ((keytype
== AUTHKEYA
&& (AC
== 0x00 || AC
== 0x01))
75 || (keytype
== AUTHKEYB
&& (AC
== 0x04 || AC
== 0x03)));
78 if (g_dbglevel
>= DBG_EXTENDED
)
79 Dbprintf("IsTrailerAccessAllowed: AC_KEYB_READ");
80 return (keytype
== AUTHKEYA
&& (AC
== 0x00 || AC
== 0x02 || AC
== 0x01));
83 if (g_dbglevel
>= DBG_EXTENDED
)
84 Dbprintf("IsTrailerAccessAllowed: AC_KEYB_WRITE");
85 return ((keytype
== AUTHKEYA
&& (AC
== 0x00 || AC
== 0x01))
86 || (keytype
== AUTHKEYB
&& (AC
== 0x04 || AC
== 0x03)));
89 if (g_dbglevel
>= DBG_EXTENDED
)
90 Dbprintf("IsTrailerAccessAllowed: AC_AC_READ");
91 return ((keytype
== AUTHKEYA
)
92 || (keytype
== AUTHKEYB
&& !(AC
== 0x00 || AC
== 0x02 || AC
== 0x01)));
95 if (g_dbglevel
>= DBG_EXTENDED
)
96 Dbprintf("IsTrailerAccessAllowed: AC_AC_WRITE");
97 return ((keytype
== AUTHKEYA
&& (AC
== 0x01))
98 || (keytype
== AUTHKEYB
&& (AC
== 0x03 || AC
== 0x05)));
105 static bool IsDataAccessAllowed(uint8_t blockNo
, uint8_t keytype
, uint8_t action
) {
107 uint8_t sector_trailer
[16];
108 emlGetMem(sector_trailer
, SectorTrailer(blockNo
), 1);
110 uint8_t sector_block
;
111 if (blockNo
<= MIFARE_2K_MAXBLOCK
) {
112 sector_block
= blockNo
& 0x03;
114 sector_block
= (blockNo
& 0x0f) / 5;
118 switch (sector_block
) {
120 AC
= ((sector_trailer
[7] >> 2) & 0x04)
121 | ((sector_trailer
[8] << 1) & 0x02)
122 | ((sector_trailer
[8] >> 4) & 0x01);
123 if (g_dbglevel
>= DBG_EXTENDED
)
124 Dbprintf("IsDataAccessAllowed: case 0x00 - %02x", AC
);
128 AC
= ((sector_trailer
[7] >> 3) & 0x04)
129 | ((sector_trailer
[8] >> 0) & 0x02)
130 | ((sector_trailer
[8] >> 5) & 0x01);
131 if (g_dbglevel
>= DBG_EXTENDED
)
132 Dbprintf("IsDataAccessAllowed: case 0x01 - %02x", AC
);
136 AC
= ((sector_trailer
[7] >> 4) & 0x04)
137 | ((sector_trailer
[8] >> 1) & 0x02)
138 | ((sector_trailer
[8] >> 6) & 0x01);
139 if (g_dbglevel
>= DBG_EXTENDED
)
140 Dbprintf("IsDataAccessAllowed: case 0x02 - %02x", AC
);
144 if (g_dbglevel
>= DBG_EXTENDED
)
145 Dbprintf("IsDataAccessAllowed: Error");
151 if (g_dbglevel
>= DBG_EXTENDED
)
152 Dbprintf("IsDataAccessAllowed - AC_DATA_READ: OK");
153 return ((keytype
== AUTHKEYA
&& !(AC
== 0x03 || AC
== 0x05 || AC
== 0x07))
154 || (keytype
== AUTHKEYB
&& !(AC
== 0x07)));
156 case AC_DATA_WRITE
: {
157 if (g_dbglevel
>= DBG_EXTENDED
)
158 Dbprintf("IsDataAccessAllowed - AC_DATA_WRITE: OK");
159 return ((keytype
== AUTHKEYA
&& (AC
== 0x00))
160 || (keytype
== AUTHKEYB
&& (AC
== 0x00 || AC
== 0x04 || AC
== 0x06 || AC
== 0x03)));
163 if (g_dbglevel
>= DBG_EXTENDED
)
164 Dbprintf("IsDataAccessAllowed - AC_DATA_INC: OK");
165 return ((keytype
== AUTHKEYA
&& (AC
== 0x00))
166 || (keytype
== AUTHKEYB
&& (AC
== 0x00 || AC
== 0x06)));
168 case AC_DATA_DEC_TRANS_REST
: {
169 if (g_dbglevel
>= DBG_EXTENDED
)
170 Dbprintf("AC_DATA_DEC_TRANS_REST: OK");
171 return ((keytype
== AUTHKEYA
&& (AC
== 0x00 || AC
== 0x06 || AC
== 0x01))
172 || (keytype
== AUTHKEYB
&& (AC
== 0x00 || AC
== 0x06 || AC
== 0x01)));
179 static bool IsAccessAllowed(uint8_t blockNo
, uint8_t keytype
, uint8_t action
) {
180 if (IsSectorTrailer(blockNo
)) {
181 return IsTrailerAccessAllowed(blockNo
, keytype
, action
);
183 return IsDataAccessAllowed(blockNo
, keytype
, action
);
187 static uint8_t MifareMaxSector(uint16_t flags
) {
188 if (IS_FLAG_MF_SIZE(flags
, MIFARE_MINI_MAX_BYTES
)) {
189 return MIFARE_MINI_MAXSECTOR
;
190 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_1K_MAX_BYTES
)) {
191 return MIFARE_1K_MAXSECTOR
;
192 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_2K_MAX_BYTES
)) {
193 return MIFARE_2K_MAXSECTOR
;
194 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_4K_MAX_BYTES
)) {
195 return MIFARE_4K_MAXSECTOR
;
197 return MIFARE_4K_MAXSECTOR
;
201 static bool MifareSimInit(uint16_t flags
, uint8_t *uid
, 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
) {
203 uint8_t uid_tmp
[10] = {0};
204 // SPEC: https://www.nxp.com/docs/en/application-note/AN10833.pdf
206 static uint8_t rATQA_Mini
[] = {0x04, 0x00}; // indicate Mifare classic Mini 4Byte UID
207 static uint8_t rATQA_1k
[] = {0x04, 0x00}; // indicate Mifare classic 1k 4Byte UID
208 static uint8_t rATQA_2k
[] = {0x04, 0x00}; // indicate Mifare classic 2k 4Byte UID
209 static uint8_t rATQA_4k
[] = {0x02, 0x00}; // indicate Mifare classic 4k 4Byte UID
212 static uint8_t rSAK_Mini
= 0x09; // mifare Mini
213 static uint8_t rSAK_1k
= 0x08; // mifare 1k
214 static uint8_t rSAK_2k
= 0x08; // mifare 2k with RATS support
215 static uint8_t rSAK_4k
= 0x18; // mifare 4k
217 static uint8_t rUIDBCC1
[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level
218 static uint8_t rUIDBCC1b4
[] = {0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level, last 4 bytes
219 static uint8_t rUIDBCC1b3
[] = {0x00, 0x00, 0x00}; // UID 1st cascade level, last 3 bytes
220 static uint8_t rUIDBCC1b2
[] = {0x00, 0x00}; // UID 1st cascade level, last 2 bytes
221 static uint8_t rUIDBCC1b1
[] = {0x00}; // UID 1st cascade level, last byte
222 static uint8_t rUIDBCC2
[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 2nd cascade level
223 static uint8_t rUIDBCC2b4
[] = {0x00, 0x00, 0x00, 0x00}; // UID 2st cascade level, last 4 bytes
224 static uint8_t rUIDBCC2b3
[] = {0x00, 0x00, 0x00}; // UID 2st cascade level, last 3 bytes
225 static uint8_t rUIDBCC2b2
[] = {0x00, 0x00}; // UID 2st cascade level, last 2 bytes
226 static uint8_t rUIDBCC2b1
[] = {0x00}; // UID 2st cascade level, last byte
227 static uint8_t rUIDBCC3
[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 3nd cascade level
228 static uint8_t rUIDBCC3b4
[] = {0x00, 0x00, 0x00, 0x00}; // UID 3st cascade level, last 4 bytes
229 static uint8_t rUIDBCC3b3
[] = {0x00, 0x00, 0x00}; // UID 3st cascade level, last 3 bytes
230 static uint8_t rUIDBCC3b2
[] = {0x00, 0x00}; // UID 3st cascade level, last 2 bytes
231 static uint8_t rUIDBCC3b1
[] = {0x00}; // UID 3st cascade level, last byte
233 static uint8_t rATQA
[] = {0x00, 0x00}; // Current ATQA
234 static uint8_t rSAK
[] = {0x00, 0x00, 0x00}; // Current SAK, CRC
235 static uint8_t rSAKuid
[] = {0x04, 0xda, 0x17}; // UID incomplete cascade bit, CRC
237 // RATS answer for 2K NXP mifare classic (with CRC)
238 static uint8_t rRATS
[] = {0x0c, 0x75, 0x77, 0x80, 0x02, 0xc1, 0x05, 0x2f, 0x2f, 0x01, 0xbc, 0xd6, 0x60, 0xd3};
242 // By default use 1K tag
243 memcpy(rATQA
, rATQA_1k
, sizeof(rATQA
));
246 //by default RATS not supported
250 // -- Determine the UID
251 // Can be set from emulator memory or incoming data
252 // Length: 4,7,or 10 bytes
254 if (IS_FLAG_UID_IN_EMUL(flags
)) {
258 // Get UID, SAK, ATQA from EMUL
260 emlGet(block0
, 0, 16);
261 // Check for 4 bytes uid: bcc corrected and single size uid bits in ATQA
262 if ((block0
[0] ^ block0
[1] ^ block0
[2] ^ block0
[3]) == block0
[4] && (block0
[6] & 0xc0) == 0) {
263 FLAG_SET_UID_IN_DATA(flags
, 4);
264 memcpy(uid
, block0
, 4);
266 memcpy(rATQA
, &block0
[6], sizeof(rATQA
));
268 // Check for 7 bytes UID: double size uid bits in ATQA
269 else if ((block0
[8] & 0xc0) == 0x40) {
270 FLAG_SET_UID_IN_DATA(flags
, 7);
271 memcpy(uid
, block0
, 7);
273 memcpy(rATQA
, &block0
[8], sizeof(rATQA
));
275 Dbprintf("ERROR: " _RED_("Invalid dump. UID/SAK/ATQA not found"));
280 Dbprintf("ERROR: " _RED_("Missing UID"));
285 // Tune tag type, if defined directly
286 // Otherwise use defined by default or extracted from EMUL
287 if (IS_FLAG_MF_SIZE(flags
, MIFARE_MINI_MAX_BYTES
)) {
288 memcpy(rATQA
, rATQA_Mini
, sizeof(rATQA
));
290 if (g_dbglevel
> DBG_NONE
) Dbprintf("Enforcing Mifare Mini ATQA/SAK");
291 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_1K_MAX_BYTES
)) {
292 memcpy(rATQA
, rATQA_1k
, sizeof(rATQA
));
294 if (g_dbglevel
> DBG_NONE
) Dbprintf("Enforcing Mifare 1K ATQA/SAK");
295 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_2K_MAX_BYTES
)) {
296 memcpy(rATQA
, rATQA_2k
, sizeof(rATQA
));
299 *rats_len
= sizeof(rRATS
);
300 if (g_dbglevel
> DBG_NONE
) Dbprintf("Enforcing Mifare 2K ATQA/SAK with RATS support");
301 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_4K_MAX_BYTES
)) {
302 memcpy(rATQA
, rATQA_4k
, sizeof(rATQA
));
304 if (g_dbglevel
> DBG_NONE
) Dbprintf("Enforcing Mifare 4K ATQA/SAK");
307 // Prepare UID arrays
308 if (IS_FLAG_UID_IN_DATA(flags
, 4)) {
309 memcpy(rUIDBCC1
, uid
, 4);
312 *cuid
= bytes_to_num(rUIDBCC1
, 4);
314 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
315 if (g_dbglevel
>= DBG_EXTENDED
)
316 Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X", flags
, rUIDBCC1
[4]);
317 if (g_dbglevel
> DBG_NONE
) {
318 Dbprintf("4B UID: %02x%02x%02x%02x", rUIDBCC1
[0], rUIDBCC1
[1], rUIDBCC1
[2], rUIDBCC1
[3]);
321 // Correct uid size bits in ATQA
322 rATQA
[0] = (rATQA
[0] & 0x3f); // single size uid
323 } else if (IS_FLAG_UID_IN_DATA(flags
, 7)) {
324 memcpy(&rUIDBCC1
[1], uid
, 3);
325 memcpy(rUIDBCC2
, uid
+ 3, 4);
328 *cuid
= bytes_to_num(rUIDBCC2
, 4);
330 rUIDBCC1
[0] = MIFARE_SELECT_CT
;
332 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
333 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
334 if (g_dbglevel
>= DBG_EXTENDED
)
335 Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X - BCC2: %02X", flags
, rUIDBCC1
[4], rUIDBCC2
[4]);
336 if (g_dbglevel
> DBG_NONE
) {
337 Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x",
338 rUIDBCC1
[1], rUIDBCC1
[2], rUIDBCC1
[3], rUIDBCC2
[0], rUIDBCC2
[1], rUIDBCC2
[2], rUIDBCC2
[3]);
341 // Correct uid size bits in ATQA
342 rATQA
[0] = (rATQA
[0] & 0x3f) | 0x40; // double size uid
343 } else if (IS_FLAG_UID_IN_DATA(flags
, 10)) {
344 memcpy(&rUIDBCC1
[1], uid
, 3);
345 memcpy(&rUIDBCC2
[1], uid
+ 3, 3);
346 memcpy(rUIDBCC3
, uid
+ 6, 4);
349 *cuid
= bytes_to_num(rUIDBCC3
, 4);
351 rUIDBCC1
[0] = MIFARE_SELECT_CT
;
352 rUIDBCC2
[0] = MIFARE_SELECT_CT
;
354 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
355 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
356 rUIDBCC3
[4] = rUIDBCC3
[0] ^ rUIDBCC3
[1] ^ rUIDBCC3
[2] ^ rUIDBCC3
[3];
357 if (g_dbglevel
>= DBG_EXTENDED
)
358 Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X - BCC2: %02X - BCC3: %02X", flags
, rUIDBCC1
[4], rUIDBCC2
[4], rUIDBCC3
[4]);
359 if (g_dbglevel
> DBG_NONE
) {
360 Dbprintf("10B UID: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
361 rUIDBCC1
[1], rUIDBCC1
[2], rUIDBCC1
[3],
362 rUIDBCC2
[1], rUIDBCC2
[2], rUIDBCC2
[3],
363 rUIDBCC3
[0], rUIDBCC3
[1], rUIDBCC3
[2], rUIDBCC3
[3]
367 // Correct uid size bits in ATQA
368 rATQA
[0] = (rATQA
[0] & 0x3f) | 0x80; // triple size uid
370 Dbprintf("ERROR: " _RED_("UID size not defined"));
373 if (flags
& FLAG_ATQA_IN_DATA
) {
374 rATQA
[0] = atqa
>> 8;
375 rATQA
[1] = atqa
& 0xff;
377 if (flags
& FLAG_SAK_IN_DATA
) {
380 if (g_dbglevel
> DBG_NONE
) {
381 Dbprintf("ATQA : %02X %02X", rATQA
[1], rATQA
[0]);
382 Dbprintf("SAK : %02X", rSAK
[0]);
385 // clone UIDs for byte-frame anti-collision multiple tag selection procedure
386 memcpy(rUIDBCC1b4
, &rUIDBCC1
[1], 4);
387 memcpy(rUIDBCC1b3
, &rUIDBCC1
[2], 3);
388 memcpy(rUIDBCC1b2
, &rUIDBCC1
[3], 2);
389 memcpy(rUIDBCC1b1
, &rUIDBCC1
[4], 1);
391 memcpy(rUIDBCC2b4
, &rUIDBCC2
[1], 4);
392 memcpy(rUIDBCC2b3
, &rUIDBCC2
[2], 3);
393 memcpy(rUIDBCC2b2
, &rUIDBCC2
[3], 2);
394 memcpy(rUIDBCC2b1
, &rUIDBCC2
[4], 1);
396 if (*uid_len
== 10) {
397 memcpy(rUIDBCC3b4
, &rUIDBCC3
[1], 4);
398 memcpy(rUIDBCC3b3
, &rUIDBCC3
[2], 3);
399 memcpy(rUIDBCC3b2
, &rUIDBCC3
[3], 2);
400 memcpy(rUIDBCC3b1
, &rUIDBCC3
[4], 1);
403 // Calculate actual CRC
404 AddCrc14A(rSAK
, sizeof(rSAK
) - 2);
406 #define TAG_RESPONSE_COUNT 18
407 static tag_response_info_t responses_init
[TAG_RESPONSE_COUNT
] = {
408 { .response
= rATQA
, .response_n
= sizeof(rATQA
) }, // Answer to request - respond with card type
409 { .response
= rSAK
, .response_n
= sizeof(rSAK
) }, //
410 { .response
= rSAKuid
, .response_n
= sizeof(rSAKuid
) }, //
411 // Do not reorder. Block used via relative index of rUIDBCC1
412 { .response
= rUIDBCC1
, .response_n
= sizeof(rUIDBCC1
) }, // Anticollision cascade1 - respond with first part of uid
413 { .response
= rUIDBCC1b4
, .response_n
= sizeof(rUIDBCC1b4
)},
414 { .response
= rUIDBCC1b3
, .response_n
= sizeof(rUIDBCC1b3
)},
415 { .response
= rUIDBCC1b2
, .response_n
= sizeof(rUIDBCC1b2
)},
416 { .response
= rUIDBCC1b1
, .response_n
= sizeof(rUIDBCC1b1
)},
417 // Do not reorder. Block used via relative index of rUIDBCC2
418 { .response
= rUIDBCC2
, .response_n
= sizeof(rUIDBCC2
) }, // Anticollision cascade2 - respond with 2nd part of uid
419 { .response
= rUIDBCC2b4
, .response_n
= sizeof(rUIDBCC2b4
)},
420 { .response
= rUIDBCC2b3
, .response_n
= sizeof(rUIDBCC2b3
)},
421 { .response
= rUIDBCC2b2
, .response_n
= sizeof(rUIDBCC2b2
)},
422 { .response
= rUIDBCC2b1
, .response_n
= sizeof(rUIDBCC2b1
)},
423 // Do not reorder. Block used via relative index of rUIDBCC3
424 { .response
= rUIDBCC3
, .response_n
= sizeof(rUIDBCC3
) }, // Anticollision cascade3 - respond with 3th part of uid
425 { .response
= rUIDBCC3b4
, .response_n
= sizeof(rUIDBCC3b4
)},
426 { .response
= rUIDBCC3b3
, .response_n
= sizeof(rUIDBCC3b3
)},
427 { .response
= rUIDBCC3b2
, .response_n
= sizeof(rUIDBCC3b2
)},
428 { .response
= rUIDBCC3b1
, .response_n
= sizeof(rUIDBCC3b1
)}
431 // Prepare ("precompile") the responses of the anticollision phase.
432 // There will be not enough time to do this at the moment the reader sends its REQA or SELECT
433 // There are 18 predefined responses with a total of 53 bytes data to transmit.
434 // Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
435 // 53 * 8 data bits, 53 * 1 parity bits, 18 start bits, 18 stop bits, 18 correction bits -> need 571 bytes buffer
436 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 571
438 uint8_t *free_buffer
= BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE
);
439 // modulation buffer pointer and current buffer free space size
440 uint8_t *free_buffer_pointer
= free_buffer
;
441 size_t free_buffer_size
= ALLOCATED_TAG_MODULATION_BUFFER_SIZE
;
443 for (size_t i
= 0; i
< TAG_RESPONSE_COUNT
; i
++) {
444 if (prepare_allocated_tag_modulation(&responses_init
[i
], &free_buffer_pointer
, &free_buffer_size
) == false) {
445 Dbprintf("Not enough modulation buffer size, exit after %d elements", i
);
450 *responses
= responses_init
;
452 // indices into responses array:
466 *@param flags: See pm3_cmd.h for the full definitions
467 *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ...
468 * (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attempted)
470 void Mifare1ksim(uint16_t flags
, uint8_t exitAfterNReads
, uint8_t *uid
, uint16_t atqa
, uint8_t sak
) {
471 tag_response_info_t
*responses
;
472 uint8_t cardSTATE
= MFEMUL_NOFIELD
;
473 uint8_t uid_len
= 0; // 4, 7, 10
474 uint32_t cuid
= 0, selTimer
= 0, authTimer
= 0;
479 uint8_t cardWRBL
= 0;
480 uint8_t cardAUTHSC
= 0;
481 uint8_t cardMaxSEC
= MifareMaxSector(flags
);
482 uint8_t cardAUTHKEY
= AUTHKEYNONE
; // no authentication
485 uint32_t cardINTREG
= 0;
486 uint8_t cardINTBLOCK
= 0;
488 struct Crypto1State mpcs
= {0, 0};
489 struct Crypto1State
*pcs
;
492 uint32_t numReads
= 0; //Counts numer of times reader reads a block
493 uint8_t receivedCmd
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
494 uint8_t receivedCmd_dec
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
495 uint8_t receivedCmd_par
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
496 uint16_t receivedCmd_len
;
498 uint8_t response
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
499 uint8_t response_par
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
501 uint8_t *rats
= NULL
;
502 uint8_t rats_len
= 0;
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 16 sets of nonces to allow recovery of up to 16 keys
509 #define ATTACK_KEY_COUNT 16
510 nonces_t ar_nr_resp
[ATTACK_KEY_COUNT
]; // for moebius attack type
511 memset(ar_nr_resp
, 0x00, sizeof(ar_nr_resp
));
513 // Authenticate response - nonce
514 uint8_t rAUTH_NT
[4] = {0, 0, 0, 1};
515 uint8_t rAUTH_NT_keystream
[4];
518 const tUart14a
*uart
= GetUart14a();
520 // free eventually allocated BigBuf memory but keep Emulator Memory
521 BigBuf_free_keep_EM();
523 if (MifareSimInit(flags
, uid
, atqa
, sak
, &responses
, &cuid
, &uid_len
, &rats
, &rats_len
) == false) {
524 BigBuf_free_keep_EM();
528 // We need to listen to the high-frequency, peak-detected path.
529 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
537 uint8_t *p_em
= BigBuf_get_EM_addr();
538 uint8_t cve_flipper
= 0;
541 bool finished
= false;
542 bool running_nested_auth_attack
= false;
543 bool button_pushed
= BUTTON_PRESS();
544 while ((button_pushed
== false) && (finished
== false)) {
548 if (counter
== 1000) {
549 if (data_available()) {
550 Dbprintf("----------- " _GREEN_("BREAKING") " ----------");
560 if (cardSTATE == MFEMUL_NOFIELD) {
562 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
564 if (vHf > MF_MINFIELDV) {
568 button_pushed = BUTTON_PRESS();
575 int res
= EmGetCmd(receivedCmd
, sizeof(receivedCmd
), &receivedCmd_len
, receivedCmd_par
);
577 if (res
== 2) { //Field is off!
578 //FpgaDisableTracing();
579 if ((flags
& FLAG_CVE21_0430
) == FLAG_CVE21_0430
) {
584 cardSTATE
= MFEMUL_NOFIELD
;
585 if (g_dbglevel
>= DBG_EXTENDED
)
586 Dbprintf("cardSTATE = MFEMUL_NOFIELD");
588 } else if (res
== 1) { // button pressed
589 FpgaDisableTracing();
590 button_pushed
= true;
591 if (g_dbglevel
>= DBG_EXTENDED
)
592 Dbprintf("Button pressed");
596 // WUPA in HALTED state or REQA or WUPA in any other state
597 if (receivedCmd_len
== 1 && ((receivedCmd
[0] == ISO14443A_CMD_REQA
&& cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == ISO14443A_CMD_WUPA
)) {
598 selTimer
= GetTickCount();
599 if (g_dbglevel
>= DBG_EXTENDED
) {
600 //Dbprintf("EmSendPrecompiledCmd(&responses[ATQA]);");
602 EmSendPrecompiledCmd(&responses
[ATQA
]);
604 FpgaDisableTracing();
608 cardAUTHKEY
= AUTHKEYNONE
;
609 nonce
= prng_successor(selTimer
, 32);
610 // prepare NT for nested authentication
611 num_to_bytes(nonce
, 4, rAUTH_NT
);
612 num_to_bytes(cuid
^ nonce
, 4, rAUTH_NT_keystream
);
616 cardSTATE
= MFEMUL_SELECT
;
618 if ((flags
& FLAG_CVE21_0430
) == FLAG_CVE21_0430
) {
626 case MFEMUL_NOFIELD
: {
627 if (g_dbglevel
>= DBG_EXTENDED
)
628 Dbprintf("MFEMUL_NOFIELD");
631 case MFEMUL_HALTED
: {
632 if (g_dbglevel
>= DBG_EXTENDED
)
633 Dbprintf("MFEMUL_HALTED");
637 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
638 if (g_dbglevel
>= DBG_EXTENDED
)
639 Dbprintf("MFEMUL_IDLE");
643 // The anti-collision sequence, which is a mandatory part of the card activation sequence.
644 // It auto with 4-byte UID (= Single Size UID),
645 // 7 -byte UID (= Double Size UID) or 10-byte UID (= Triple Size UID).
646 // For details see chapter 2 of AN10927.pdf
648 // This case is used for all Cascade Levels, because:
649 // 1) Any devices (under Android for example) after full select procedure completed,
650 // when UID is known, uses "fast-selection" method. In this case reader ignores
651 // first cascades and tries to select tag by last bytes of UID of last cascade
652 // 2) Any readers (like ACR122U) uses bit oriented anti-collision frames during selectin,
653 // same as multiple tags. For details see chapter 6.1.5.3 of ISO/IEC 14443-3
654 case MFEMUL_SELECT
: {
656 // Extract cascade level
657 if (receivedCmd_len
>= 2) {
658 switch (receivedCmd
[0]) {
659 case ISO14443A_CMD_ANTICOLL_OR_SELECT
:
662 case ISO14443A_CMD_ANTICOLL_OR_SELECT_2
:
665 case ISO14443A_CMD_ANTICOLL_OR_SELECT_3
:
671 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
673 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] Incorrect cascade level received");
677 // Incoming SELECT ALL for any cascade level
678 if (receivedCmd_len
== 2 && receivedCmd
[1] == 0x20) {
679 EmSendPrecompiledCmd(&responses
[uid_index
]);
680 FpgaDisableTracing();
682 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("SELECT ALL - EmSendPrecompiledCmd(%02x)", &responses
[uid_index
]);
686 // Incoming SELECT CLx for any cascade level
687 if (receivedCmd_len
== 9 && receivedCmd
[1] == 0x70) {
688 if (memcmp(&receivedCmd
[2], responses
[uid_index
].response
, 4) == 0) {
689 bool cl_finished
= (uid_len
== 4 && uid_index
== UIDBCC1
) ||
690 (uid_len
== 7 && uid_index
== UIDBCC2
) ||
691 (uid_len
== 10 && uid_index
== UIDBCC3
);
692 EmSendPrecompiledCmd(&responses
[cl_finished
? SAK
: SAKuid
]);
693 FpgaDisableTracing();
695 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("SELECT CLx %02x%02x%02x%02x received", receivedCmd
[2], receivedCmd
[3], receivedCmd
[4], receivedCmd
[5]);
698 cardSTATE
= MFEMUL_WORK
;
699 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_WORK");
703 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
705 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_IDLE");
710 // Incoming anti-collision frame
711 // receivedCmd[1] indicates number of byte and bit collision, supports only for bit collision is zero
712 if (receivedCmd_len
>= 3 && receivedCmd_len
<= 6 && (receivedCmd
[1] & 0x0f) == 0) {
713 // we can process only full-byte frame anti-collision procedure
714 if (memcmp(&receivedCmd
[2], responses
[uid_index
].response
, receivedCmd_len
- 2) == 0) {
715 // response missing part of UID via relative array index
716 EmSendPrecompiledCmd(&responses
[uid_index
+ receivedCmd_len
- 2]);
717 FpgaDisableTracing();
719 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("SELECT ANTICOLLISION - EmSendPrecompiledCmd(%02x)", &responses
[uid_index
]);
721 // IDLE, not our UID or split-byte frame anti-collision (not supports)
722 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
724 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_IDLE");
729 // Unknown selection procedure
730 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
732 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] Unknown selection procedure");
739 if (g_dbglevel
>= DBG_EXTENDED
) {
740 // Dbprintf("[MFEMUL_WORK] Enter in case");
743 if (receivedCmd_len
== 0) {
744 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] NO CMD received");
748 encrypted_data
= (cardAUTHKEY
!= AUTHKEYNONE
);
749 if (encrypted_data
) {
751 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, receivedCmd_dec
);
752 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] Decrypt sequence");
755 memcpy(receivedCmd_dec
, receivedCmd
, receivedCmd_len
);
758 // all commands must have a valid CRC
759 if (CheckCrc14A(receivedCmd_dec
, receivedCmd_len
) == false) {
760 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
761 FpgaDisableTracing();
763 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] All commands must have a valid CRC %02X (%d)", receivedCmd_dec
, receivedCmd_len
);
767 if (receivedCmd_len
== 4 && (receivedCmd_dec
[0] == MIFARE_AUTH_KEYA
|| receivedCmd_dec
[0] == MIFARE_AUTH_KEYB
)) {
769 // Reader asks for AUTH: 6X XX
770 // RCV: 60 XX => Using KEY A
771 // RCV: 61 XX => Using KEY B
774 authTimer
= GetTickCount();
776 // received block num -> sector
778 // 4K tags have 16 blocks per sector 32..39
779 cardAUTHSC
= MifareBlockToSector(receivedCmd_dec
[1]);
781 // cardAUTHKEY: 60 => Auth use Key A
782 // cardAUTHKEY: 61 => Auth use Key B
783 cardAUTHKEY
= receivedCmd_dec
[0] & 0x01;
785 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] KEY %c: %012" PRIx64
, (cardAUTHKEY
== 0) ? 'A' : 'B', emlGetKey(cardAUTHSC
, cardAUTHKEY
));
787 // sector out of range - do not respond
788 if (cardAUTHSC
>= cardMaxSEC
) {
789 cardAUTHKEY
= AUTHKEYNONE
; // not authenticated
791 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] Out of range sector %d(0x%02x)", cardAUTHSC
, cardAUTHSC
);
795 // first authentication
798 // Load key into crypto
799 crypto1_init(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
800 running_nested_auth_attack
= false;
801 if (!encrypted_data
) {
802 // Receive Cmd in clear txt
803 // Update crypto state (UID ^ NONCE)
804 crypto1_word(pcs
, cuid
^ nonce
, 0);
805 // rAUTH_NT contains prepared nonce for authenticate
806 EmSendCmd(rAUTH_NT
, sizeof(rAUTH_NT
));
807 FpgaDisableTracing();
809 if (g_dbglevel
>= DBG_EXTENDED
) {
810 Dbprintf("[MFEMUL_WORK] Reader authenticating for block %d (0x%02x) with key %c - nonce: %08X - cuid: %08X",
813 (cardAUTHKEY
== 0) ? 'A' : 'B',
819 // nested authentication
821 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
822 num_to_bytes(ans, 4, rAUTH_AT);
825 // if key not known and FLAG_NESTED_AUTH_ATTACK and we have nt/nt_enc/parity, send recorded nt_enc and parity
826 if ((flags
& FLAG_NESTED_AUTH_ATTACK
) == FLAG_NESTED_AUTH_ATTACK
) {
827 if (emlGetKey(cardAUTHSC
, cardAUTHKEY
) == 0) {
828 uint8_t buf
[16] = {0};
829 emlGetMem(buf
, (CARD_MEMORY_RF08S_OFFSET
/ MIFARE_BLOCK_SIZE
) + cardAUTHSC
, 1);
830 if (buf
[(cardAUTHKEY
* 8) + 3] == 0xAA) { // extra check to tell we have nt/nt_enc/par_err
831 running_nested_auth_attack
= true;
833 nonce
= bytes_to_num(buf
+ (cardAUTHKEY
* 8), 2);
834 nonce
= nonce
<< 16 | prng_successor(nonce
, 16);
836 memcpy(response
, buf
+ (cardAUTHKEY
* 8) + 4, 4);
837 uint8_t nt_par_err
= buf
[(cardAUTHKEY
* 8) + 2];
838 uint32_t nt_enc
= bytes_to_num(response
, 4);
839 response_par
[0] = ((((nt_par_err
>> 3) & 1) ^ oddparity8((nt_enc
>> 24) & 0xFF)) << 7 |
840 (((nt_par_err
>> 2) & 1) ^ oddparity8((nt_enc
>> 16) & 0xFF)) << 6 |
841 (((nt_par_err
>> 1) & 1) ^ oddparity8((nt_enc
>> 8) & 0xFF)) << 5 |
842 (((nt_par_err
>> 0) & 1) ^ oddparity8((nt_enc
>> 0) & 0xFF)) << 4);
843 ar_nr_resp
[0].cuid
= cuid
;
844 ar_nr_resp
[0].sector
= cardAUTHSC
;
845 ar_nr_resp
[0].keytype
= cardAUTHKEY
;
846 ar_nr_resp
[0].nonce
= nonce
;
847 ar_nr_resp
[0].nonce2
= nt_enc
;
851 if (running_nested_auth_attack
== false) {
852 // rAUTH_NT, rAUTH_NT_keystream contains prepared nonce and keystream for nested authentication
853 // we need calculate parity bits for non-encrypted sequence
854 mf_crypto1_encryptEx(pcs
, rAUTH_NT
, rAUTH_NT_keystream
, response
, 4, response_par
);
856 EmSendCmdPar(response
, 4, response_par
);
857 FpgaDisableTracing();
859 if (g_dbglevel
>= DBG_EXTENDED
) {
860 Dbprintf("[MFEMUL_WORK] Reader doing nested authentication for block %d (0x%02x) with key %c",
863 (cardAUTHKEY
== 0) ? 'A' : 'B'
868 cardSTATE
= MFEMUL_AUTH1
;
869 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_AUTH1 - rAUTH_NT: %02X", rAUTH_NT
);
873 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
874 // BUT... ACK --> NACK
875 if (receivedCmd_len
== 1 && receivedCmd_dec
[0] == CARD_ACK
) {
876 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
877 FpgaDisableTracing();
881 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
882 if (receivedCmd_len
== 1 && receivedCmd_dec
[0] == CARD_NACK_NA
) {
883 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_ACK
) : CARD_ACK
);
884 FpgaDisableTracing();
888 // case MFEMUL_WORK => if Cmd is Read, Write, Inc, Dec, Restore, Transfer
889 if (receivedCmd_len
== 4 && (receivedCmd_dec
[0] == ISO14443A_CMD_READBLOCK
890 || receivedCmd_dec
[0] == ISO14443A_CMD_WRITEBLOCK
891 || receivedCmd_dec
[0] == MIFARE_CMD_INC
892 || receivedCmd_dec
[0] == MIFARE_CMD_DEC
893 || receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
894 || receivedCmd_dec
[0] == MIFARE_CMD_TRANSFER
)) {
895 // all other commands must be encrypted (authenticated)
896 if (!encrypted_data
) {
897 EmSend4bit(CARD_NACK_NA
);
898 FpgaDisableTracing();
900 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] Commands must be encrypted (authenticated)");
904 // iceman, u8 can never be larger the MIFARE_4K_MAXBLOCK (256)
905 // Check if Block num is not too far
907 if (receivedCmd_dec[1] > MIFARE_4K_MAXBLOCK) {
908 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
909 FpgaDisableTracing();
910 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]);
914 blockNo
= receivedCmd_dec
[1];
915 if (MifareBlockToSector(blockNo
) != cardAUTHSC
) {
916 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
917 FpgaDisableTracing();
919 if (g_dbglevel
>= DBG_ERROR
)
920 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
);
924 // Compliance of MIFARE Classic EV1 1K Datasheet footnote of Table 8
925 // If access bits show that key B is Readable, any subsequent memory access will be refused.
926 // Some cards don't respect it so we can also skip it with FLAG_MF_USE_READ_KEYB
927 if ((flags
& FLAG_MF_USE_READ_KEYB
) != FLAG_MF_USE_READ_KEYB
) {
928 if (cardAUTHKEY
== AUTHKEYB
&& IsKeyBReadable(blockNo
)) {
929 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
930 FpgaDisableTracing();
932 if (g_dbglevel
>= DBG_ERROR
)
933 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
);
939 // case MFEMUL_WORK => CMD READ block
940 if (receivedCmd_len
== 4 && receivedCmd_dec
[0] == ISO14443A_CMD_READBLOCK
) {
941 blockNo
= receivedCmd_dec
[1];
942 if (g_dbglevel
>= DBG_EXTENDED
)
943 Dbprintf("[MFEMUL_WORK] Reader reading block %d (0x%02x)", blockNo
, blockNo
);
945 // android CVE 2021_0430
946 // Simulate a MFC 1K, with a NDEF message.
947 // these values uses the standard LIBNFC NDEF message
949 // In short, first a value read of block 4,
950 // update the length byte before second read of block 4.
951 // on iphone etc there might even be 3 reads of block 4.
952 // fiddling with when to flip the byte or not, has different effects
953 if ((flags
& FLAG_CVE21_0430
) == FLAG_CVE21_0430
) {
958 p_em
+= blockNo
* 16;
959 // TLV in NDEF, flip length between
960 // 4 | 03 21 D1 02 1C 53 70 91 01 09 54 02 65 6E 4C 69
961 // 0xFF means long length
962 // 0xFE mean max short length
964 // We could also have a go at message len byte at p_em[4]...
965 if (p_em
[1] == 0x21 && cve_flipper
== 1) {
973 emlGetMem(response
, blockNo
, 1);
975 if (g_dbglevel
>= DBG_EXTENDED
) {
976 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
,
977 response
[0], response
[1], response
[2], response
[3], response
[4], response
[5], response
[6],
978 response
[7], response
[8], response
[9], response
[10], response
[11], response
[12], response
[13],
979 response
[14], response
[15]);
982 // Access permission management:
992 // If permission is not allowed, data is cleared (00) in emulator memory.
993 // ex: a0a1a2a3a4a561e789c1b0b1b2b3b4b5 => 00000000000061e789c1b0b1b2b3b4b5
996 // Check if selected Block is a Sector Trailer
997 if (IsSectorTrailer(blockNo
)) {
999 if (IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_KEYA_READ
) == false) {
1000 memset(response
, 0x00, 6); // keyA can never be read
1001 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyA can never be read - block %d (0x%02x)", blockNo
, blockNo
);
1003 if (IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_KEYB_READ
) == false) {
1004 memset(response
+ 10, 0x00, 6); // keyB cannot be read
1005 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyB cannot be read - block %d (0x%02x)", blockNo
, blockNo
);
1007 if (IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_AC_READ
) == false) {
1008 memset(response
+ 6, 0x00, 4); // AC bits cannot be read
1009 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] AC bits cannot be read - block %d (0x%02x)", blockNo
, blockNo
);
1012 if (IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_DATA_READ
) == false) {
1013 memset(response
, 0x00, 16); // datablock cannot be read
1014 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] Data block %d (0x%02x) cannot be read", blockNo
, blockNo
);
1017 AddCrc14A(response
, 16);
1018 mf_crypto1_encrypt(pcs
, response
, MAX_MIFARE_FRAME_SIZE
, response_par
);
1019 EmSendCmdPar(response
, MAX_MIFARE_FRAME_SIZE
, response_par
);
1020 FpgaDisableTracing();
1022 if (g_dbglevel
>= DBG_EXTENDED
) {
1023 Dbprintf("[MFEMUL_WORK - EmSendCmdPar] Data Block[%d]: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", blockNo
,
1024 response
[0], response
[1], response
[2], response
[3], response
[4], response
[5], response
[6],
1025 response
[7], response
[8], response
[9], response
[10], response
[11], response
[12], response
[13],
1026 response
[14], response
[15]);
1030 if (exitAfterNReads
> 0 && numReads
== exitAfterNReads
) {
1031 Dbprintf("[MFEMUL_WORK] %d reads done, exiting", numReads
);
1036 } // End receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK
1038 // case MFEMUL_WORK => CMD WRITEBLOCK
1039 if (receivedCmd_len
== 4 && receivedCmd_dec
[0] == ISO14443A_CMD_WRITEBLOCK
) {
1040 blockNo
= receivedCmd_dec
[1];
1041 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] RECV 0xA0 write block %d (%02x)", blockNo
, blockNo
);
1042 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
1043 FpgaDisableTracing();
1046 cardSTATE
= MFEMUL_WRITEBL2
;
1047 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_WRITEBL2");
1051 // case MFEMUL_WORK => CMD INC/DEC/REST
1052 if (receivedCmd_len
== 4 && (receivedCmd_dec
[0] == MIFARE_CMD_INC
|| receivedCmd_dec
[0] == MIFARE_CMD_DEC
|| receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
)) {
1053 blockNo
= receivedCmd_dec
[1];
1054 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
);
1055 if (emlCheckValBl(blockNo
) == false) {
1056 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("[MFEMUL_WORK] Reader tried to operate on block, but emlCheckValBl failed, nacking");
1057 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
1058 FpgaDisableTracing();
1061 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
1062 FpgaDisableTracing();
1066 if (receivedCmd_dec
[0] == MIFARE_CMD_INC
) {
1067 cardSTATE
= MFEMUL_INTREG_INC
;
1068 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_INC");
1072 if (receivedCmd_dec
[0] == MIFARE_CMD_DEC
) {
1073 cardSTATE
= MFEMUL_INTREG_DEC
;
1074 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_DEC");
1078 if (receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
) {
1079 cardSTATE
= MFEMUL_INTREG_REST
;
1080 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_REST");
1084 } // End case MFEMUL_WORK => CMD INC/DEC/REST
1087 // case MFEMUL_WORK => CMD TRANSFER
1088 if (receivedCmd_len
== 4 && receivedCmd_dec
[0] == MIFARE_CMD_TRANSFER
) {
1089 blockNo
= receivedCmd_dec
[1];
1090 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] RECV 0x%02x transfer block %d (%02x)", receivedCmd_dec
[0], blockNo
, blockNo
);
1091 emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd_dec
[1]);
1092 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
1093 FpgaDisableTracing();
1097 // case MFEMUL_WORK => CMD HALT
1098 if (receivedCmd_len
> 1 && receivedCmd_dec
[0] == ISO14443A_CMD_HALT
&& receivedCmd_dec
[1] == 0x00) {
1099 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1102 cardSTATE
= MFEMUL_HALTED
;
1103 cardAUTHKEY
= AUTHKEYNONE
;
1104 if (g_dbglevel
>= DBG_EXTENDED
) {
1105 Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_HALTED");
1110 // case MFEMUL_WORK => CMD RATS
1111 if (receivedCmd_len
== 4 && receivedCmd_dec
[0] == ISO14443A_CMD_RATS
&& (receivedCmd_dec
[1] & 0xF0) <= 0x80 && (receivedCmd_dec
[1] & 0x0F) <= 0x0e) {
1112 if (rats
&& rats_len
) {
1113 if (encrypted_data
) {
1114 memcpy(response
, rats
, rats_len
);
1115 mf_crypto1_encrypt(pcs
, response
, rats_len
, response_par
);
1116 EmSendCmdPar(response
, rats_len
, response_par
);
1118 EmSendCmd(rats
, rats_len
);
1120 FpgaDisableTracing();
1121 if (g_dbglevel
>= DBG_EXTENDED
)
1122 Dbprintf("[MFEMUL_WORK] RCV RATS => ACK");
1124 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
1125 FpgaDisableTracing();
1126 cardSTATE_TO_IDLE();
1127 if (g_dbglevel
>= DBG_EXTENDED
)
1128 Dbprintf("[MFEMUL_WORK] RCV RATS => NACK");
1133 // case MFEMUL_WORK => ISO14443A_CMD_NXP_DESELECT
1134 if (receivedCmd_len
== 3 && receivedCmd_dec
[0] == ISO14443A_CMD_NXP_DESELECT
) {
1135 if (rats
&& rats_len
) {
1136 // response back NXP_DESELECT
1137 if (encrypted_data
) {
1138 memcpy(response
, receivedCmd_dec
, receivedCmd_len
);
1139 mf_crypto1_encrypt(pcs
, response
, receivedCmd_len
, response_par
);
1140 EmSendCmdPar(response
, receivedCmd_len
, response_par
);
1142 EmSendCmd(receivedCmd_dec
, receivedCmd_len
);
1144 FpgaDisableTracing();
1145 if (g_dbglevel
>= DBG_EXTENDED
)
1146 Dbprintf("[MFEMUL_WORK] RCV NXP DESELECT => ACK");
1148 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
1149 FpgaDisableTracing();
1150 cardSTATE_TO_IDLE();
1151 if (g_dbglevel
>= DBG_EXTENDED
)
1152 Dbprintf("[MFEMUL_WORK] RCV NXP DESELECT => NACK");
1157 // case MFEMUL_WORK => command not allowed
1158 if (g_dbglevel
>= DBG_EXTENDED
)
1159 Dbprintf("Received command not allowed, nacking");
1160 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
1161 FpgaDisableTracing();
1166 case MFEMUL_AUTH1
: {
1167 if (g_dbglevel
>= DBG_EXTENDED
)
1168 Dbprintf("[MFEMUL_AUTH1] Enter case");
1170 if (receivedCmd_len
!= 8) {
1171 cardSTATE_TO_IDLE();
1172 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1173 if (g_dbglevel
>= DBG_EXTENDED
)
1174 Dbprintf("MFEMUL_AUTH1: receivedCmd_len != 8 (%d) => cardSTATE_TO_IDLE())", receivedCmd_len
);
1178 nr
= bytes_to_num(receivedCmd
, 4);
1179 ar
= bytes_to_num(&receivedCmd
[4], 4);
1182 crypto1_word(pcs
, nr
, 1);
1183 cardRr
= ar
^ crypto1_word(pcs
, 0, 0);
1186 if (cardRr
!= prng_successor(nonce
, 64)) {
1187 // Collect AR/NR per keytype & sector
1188 if (running_nested_auth_attack
) {
1189 ar_nr_resp
[0].nr
= nr
;
1190 ar_nr_resp
[0].ar
= ar
;
1191 ar_nr_resp
[0].state
= NESTED
;
1194 if ((flags
& FLAG_NR_AR_ATTACK
) == FLAG_NR_AR_ATTACK
) {
1196 for (uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
1197 if (ar_nr_resp
[i
].state
== EMPTY
||
1199 (ar_nr_resp
[i
].state
!= EMPTY
) &&
1200 (cardAUTHSC
== ar_nr_resp
[i
].sector
) &&
1201 (cardAUTHKEY
== ar_nr_resp
[i
].keytype
)
1204 // if first auth for sector, or matches sector and keytype of previous auth
1205 if (ar_nr_resp
[i
].state
!= SECOND
) {
1206 // if we haven't already collected 2 nonces for this sector
1207 if (ar_nr_resp
[i
].state
== EMPTY
) {
1208 // first nonce collect
1209 ar_nr_resp
[i
].cuid
= cuid
;
1210 ar_nr_resp
[i
].sector
= cardAUTHSC
;
1211 ar_nr_resp
[i
].keytype
= cardAUTHKEY
;
1212 ar_nr_resp
[i
].nonce
= nonce
;
1213 ar_nr_resp
[i
].nr
= nr
;
1214 ar_nr_resp
[i
].ar
= ar
;
1215 ar_nr_resp
[i
].state
= FIRST
;
1216 } else { // second nonce collect
1217 // make sure we have different nonces for moebius attack
1218 if (ar_nr_resp
[i
].nonce
!= nonce
) {
1219 ar_nr_resp
[i
].nonce2
= nonce
;
1220 ar_nr_resp
[i
].nr2
= nr
;
1221 ar_nr_resp
[i
].ar2
= ar
;
1222 ar_nr_resp
[i
].state
= SECOND
;
1227 // we found right spot for this nonce stop looking
1232 if (g_dbglevel
>= DBG_EXTENDED
) {
1233 Dbprintf("[MFEMUL_AUTH1] AUTH FAILED for sector %d with key %c. [nr=%08x cardRr=%08x] [nt=%08x succ=%08x]"
1235 , (cardAUTHKEY
== 0) ? 'A' : 'B'
1239 , prng_successor(nonce
, 64)
1242 cardAUTHKEY
= AUTHKEYNONE
; // not authenticated
1243 cardSTATE_TO_IDLE();
1244 // Really tags not respond NACK on invalid authentication
1245 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1249 ans
= prng_successor(nonce
, 96);
1250 num_to_bytes(ans
, 4, response
);
1251 mf_crypto1_encrypt(pcs
, response
, 4, response_par
);
1252 EmSendCmdPar(response
, 4, response_par
);
1253 FpgaDisableTracing();
1255 if (g_dbglevel
>= DBG_EXTENDED
) {
1256 Dbprintf("[MFEMUL_AUTH1] AUTH COMPLETED for sector %d with key %c. time=%d",
1258 cardAUTHKEY
== 0 ? 'A' : 'B',
1259 GetTickCountDelta(authTimer
)
1263 cardSTATE
= MFEMUL_WORK
;
1264 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_AUTH1] cardSTATE = MFEMUL_WORK");
1269 case MFEMUL_WRITEBL2
: {
1270 if (receivedCmd_len
== MAX_MIFARE_FRAME_SIZE
) {
1271 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, receivedCmd_dec
);
1272 if (CheckCrc14A(receivedCmd_dec
, receivedCmd_len
)) {
1273 if (IsSectorTrailer(cardWRBL
)) {
1274 emlGetMem(response
, cardWRBL
, 1);
1275 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_KEYA_WRITE
)) {
1276 memcpy(receivedCmd_dec
, response
, 6); // don't change KeyA
1278 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_KEYB_WRITE
)) {
1279 memcpy(receivedCmd_dec
+ 10, response
+ 10, 6); // don't change KeyA
1281 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_AC_WRITE
)) {
1282 memcpy(receivedCmd_dec
+ 6, response
+ 6, 4); // don't change AC bits
1285 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_DATA_WRITE
)) {
1286 memcpy(receivedCmd_dec
, response
, 16); // don't change anything
1289 emlSetMem_xt(receivedCmd_dec
, cardWRBL
, 1, 16);
1290 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
)); // always ACK?
1291 FpgaDisableTracing();
1293 cardSTATE
= MFEMUL_WORK
;
1294 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_WORK");
1298 cardSTATE_TO_IDLE();
1299 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_IDLE");
1300 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1305 case MFEMUL_INTREG_INC
: {
1306 if (receivedCmd_len
== 6) {
1307 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t *)&ans
);
1308 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
) != PM3_SUCCESS
) {
1309 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
1310 FpgaDisableTracing();
1312 cardSTATE_TO_IDLE();
1315 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1316 cardINTREG
= cardINTREG
+ ans
;
1318 cardSTATE
= MFEMUL_WORK
;
1319 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_INTREG_INC] cardSTATE = MFEMUL_WORK");
1325 case MFEMUL_INTREG_DEC
: {
1326 if (receivedCmd_len
== 6) { // Data is encrypted
1328 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t *)&ans
);
1329 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
) != PM3_SUCCESS
) {
1330 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
1331 FpgaDisableTracing();
1333 cardSTATE_TO_IDLE();
1337 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1338 cardINTREG
= cardINTREG
- ans
;
1339 cardSTATE
= MFEMUL_WORK
;
1340 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_INTREG_DEC] cardSTATE = MFEMUL_WORK");
1345 case MFEMUL_INTREG_REST
: {
1346 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t *)&ans
);
1347 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
) != PM3_SUCCESS
) {
1348 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
1349 FpgaDisableTracing();
1351 cardSTATE_TO_IDLE();
1354 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1355 cardSTATE
= MFEMUL_WORK
;
1356 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_INTREG_REST] cardSTATE = MFEMUL_WORK");
1360 } // End Switch Loop
1362 button_pushed
= BUTTON_PRESS();
1366 FpgaDisableTracing();
1369 if (running_nested_auth_attack
) {
1370 if ((nonce_state
)ar_nr_resp
[0].state
== NESTED
) {
1371 running_nested_auth_attack
= false;
1372 if (g_dbglevel
>= DBG_INFO
) {
1373 Dbprintf("Collected nested AR/NR which can be used to extract sector %d " _YELLOW_("%s")
1374 , ar_nr_resp
[0].sector
1375 , (ar_nr_resp
[0].keytype
== AUTHKEYA
) ? "key A" : "key B"
1377 Dbprintf("../tools/mfc/card_reader/mfkey32nested %08x %08x %08x %08x %08x",
1378 ar_nr_resp
[0].cuid
, //UID
1379 ar_nr_resp
[0].nonce
, //NT
1380 ar_nr_resp
[0].nonce2
,//NT_ENC
1381 ar_nr_resp
[0].nr
, //NR1
1382 ar_nr_resp
[0].ar
//AR1
1388 if ((flags
& FLAG_NR_AR_ATTACK
) == FLAG_NR_AR_ATTACK
) {
1389 for (uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
1390 if ((nonce_state
)ar_nr_resp
[i
].state
== SECOND
) {
1392 if (g_dbglevel
>= DBG_INFO
) {
1393 Dbprintf("Collected two pairs of AR/NR which can be used to extract sector %d " _YELLOW_("%s")
1394 , ar_nr_resp
[i
].sector
1395 , (ar_nr_resp
[i
].keytype
== AUTHKEYA
) ? "key A" : "key B"
1397 Dbprintf("../tools/mfc/card_reader/mfkey32v2 %08x %08x %08x %08x %08x %08x %08x",
1398 ar_nr_resp
[i
].cuid
, //UID
1399 ar_nr_resp
[i
].nonce
, //NT
1400 ar_nr_resp
[i
].nr
, //NR1
1401 ar_nr_resp
[i
].ar
, //AR1
1402 ar_nr_resp
[i
].nonce2
,//NT2
1403 ar_nr_resp
[i
].nr2
, //NR2
1404 ar_nr_resp
[i
].ar2
//AR2
1411 if (g_dbglevel
>= DBG_ERROR
) {
1412 Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", get_tracing(), BigBuf_get_traceLen());
1415 if ((flags
& FLAG_INTERACTIVE
) == FLAG_INTERACTIVE
) { // Interactive mode flag, means we need to send ACK
1416 //Send the collected ar_nr in the response
1417 reply_ng(CMD_HF_MIFARE_SIMULATE
, button_pushed
? PM3_EOPABORTED
: PM3_SUCCESS
, (uint8_t *)&ar_nr_resp
[index
], sizeof(nonces_t
));
1420 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1423 BigBuf_free_keep_EM();