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 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
) {
189 uint8_t uid_tmp
[10] = {0};
190 // SPEC: https://www.nxp.com/docs/en/application-note/AN10833.pdf
192 static uint8_t rATQA_Mini
[] = {0x04, 0x00}; // indicate Mifare classic Mini 4Byte UID
193 static uint8_t rATQA_1k
[] = {0x04, 0x00}; // indicate Mifare classic 1k 4Byte UID
194 static uint8_t rATQA_2k
[] = {0x04, 0x00}; // indicate Mifare classic 2k 4Byte UID
195 static uint8_t rATQA_4k
[] = {0x02, 0x00}; // indicate Mifare classic 4k 4Byte UID
198 static uint8_t rSAK_Mini
= 0x09; // mifare Mini
199 static uint8_t rSAK_1k
= 0x08; // mifare 1k
200 static uint8_t rSAK_2k
= 0x08; // mifare 2k with RATS support
201 static uint8_t rSAK_4k
= 0x18; // mifare 4k
203 static uint8_t rUIDBCC1
[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level
204 static uint8_t rUIDBCC1b4
[] = {0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level, last 4 bytes
205 static uint8_t rUIDBCC1b3
[] = {0x00, 0x00, 0x00}; // UID 1st cascade level, last 3 bytes
206 static uint8_t rUIDBCC1b2
[] = {0x00, 0x00}; // UID 1st cascade level, last 2 bytes
207 static uint8_t rUIDBCC1b1
[] = {0x00}; // UID 1st cascade level, last byte
208 static uint8_t rUIDBCC2
[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 2nd cascade level
209 static uint8_t rUIDBCC2b4
[] = {0x00, 0x00, 0x00, 0x00}; // UID 2st cascade level, last 4 bytes
210 static uint8_t rUIDBCC2b3
[] = {0x00, 0x00, 0x00}; // UID 2st cascade level, last 3 bytes
211 static uint8_t rUIDBCC2b2
[] = {0x00, 0x00}; // UID 2st cascade level, last 2 bytes
212 static uint8_t rUIDBCC2b1
[] = {0x00}; // UID 2st cascade level, last byte
213 static uint8_t rUIDBCC3
[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 3nd cascade level
214 static uint8_t rUIDBCC3b4
[] = {0x00, 0x00, 0x00, 0x00}; // UID 3st cascade level, last 4 bytes
215 static uint8_t rUIDBCC3b3
[] = {0x00, 0x00, 0x00}; // UID 3st cascade level, last 3 bytes
216 static uint8_t rUIDBCC3b2
[] = {0x00, 0x00}; // UID 3st cascade level, last 2 bytes
217 static uint8_t rUIDBCC3b1
[] = {0x00}; // UID 3st cascade level, last byte
219 static uint8_t rATQA
[] = {0x00, 0x00}; // Current ATQA
220 static uint8_t rSAK
[] = {0x00, 0x00, 0x00}; // Current SAK, CRC
221 static uint8_t rSAKuid
[] = {0x04, 0xda, 0x17}; // UID incomplete cascade bit, CRC
223 // RATS answer for 2K NXP mifare classic (with CRC)
224 static uint8_t rRATS
[] = {0x0c, 0x75, 0x77, 0x80, 0x02, 0xc1, 0x05, 0x2f, 0x2f, 0x01, 0xbc, 0xd6, 0x60, 0xd3};
228 // By default use 1K tag
229 memcpy(rATQA
, rATQA_1k
, sizeof(rATQA
));
232 //by default RATS not supported
236 // -- Determine the UID
237 // Can be set from emulator memory or incoming data
238 // Length: 4,7,or 10 bytes
240 if (IS_FLAG_UID_IN_EMUL(flags
)) {
244 // Get UID, SAK, ATQA from EMUL
246 emlGet(block0
, 0, 16);
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 FLAG_SET_UID_IN_DATA(flags
, 4);
250 memcpy(uid
, block0
, 4);
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 FLAG_SET_UID_IN_DATA(flags
, 7);
257 memcpy(uid
, block0
, 7);
259 memcpy(rATQA
, &block0
[8], sizeof(rATQA
));
261 Dbprintf("ERROR: " _RED_("Invalid dump. UID/SAK/ATQA not found"));
266 Dbprintf("ERROR: " _RED_("Missing UID"));
271 // Tune tag type, if defined directly
272 // Otherwise use defined by default or extracted from EMUL
273 if (IS_FLAG_MF_SIZE(flags
, MIFARE_MINI_MAX_BYTES
)) {
274 memcpy(rATQA
, rATQA_Mini
, sizeof(rATQA
));
276 if (g_dbglevel
> DBG_NONE
) Dbprintf("Enforcing Mifare Mini ATQA/SAK");
277 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_1K_MAX_BYTES
)) {
278 memcpy(rATQA
, rATQA_1k
, sizeof(rATQA
));
280 if (g_dbglevel
> DBG_NONE
) Dbprintf("Enforcing Mifare 1K ATQA/SAK");
281 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_2K_MAX_BYTES
)) {
282 memcpy(rATQA
, rATQA_2k
, sizeof(rATQA
));
285 *rats_len
= sizeof(rRATS
);
286 if (g_dbglevel
> DBG_NONE
) Dbprintf("Enforcing Mifare 2K ATQA/SAK with RATS support");
287 } else if (IS_FLAG_MF_SIZE(flags
, MIFARE_4K_MAX_BYTES
)) {
288 memcpy(rATQA
, rATQA_4k
, sizeof(rATQA
));
290 if (g_dbglevel
> DBG_NONE
) Dbprintf("Enforcing Mifare 4K ATQA/SAK");
293 // Prepare UID arrays
294 if (IS_FLAG_UID_IN_DATA(flags
, 4)) {
295 memcpy(rUIDBCC1
, uid
, 4);
298 *cuid
= bytes_to_num(rUIDBCC1
, 4);
300 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
301 if (g_dbglevel
>= DBG_EXTENDED
)
302 Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X", flags
, rUIDBCC1
[4]);
303 if (g_dbglevel
> DBG_NONE
) {
304 Dbprintf("4B UID: %02x%02x%02x%02x", rUIDBCC1
[0], rUIDBCC1
[1], rUIDBCC1
[2], rUIDBCC1
[3]);
307 // Correct uid size bits in ATQA
308 rATQA
[0] = (rATQA
[0] & 0x3f); // single size uid
309 } else if (IS_FLAG_UID_IN_DATA(flags
, 7)) {
310 memcpy(&rUIDBCC1
[1], uid
, 3);
311 memcpy(rUIDBCC2
, uid
+ 3, 4);
314 *cuid
= bytes_to_num(rUIDBCC2
, 4);
316 rUIDBCC1
[0] = MIFARE_SELECT_CT
;
318 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
319 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
320 if (g_dbglevel
>= DBG_EXTENDED
)
321 Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X - BCC2: %02X", flags
, rUIDBCC1
[4], rUIDBCC2
[4]);
322 if (g_dbglevel
> DBG_NONE
) {
323 Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x",
324 rUIDBCC1
[1], rUIDBCC1
[2], rUIDBCC1
[3], rUIDBCC2
[0], rUIDBCC2
[1], rUIDBCC2
[2], rUIDBCC2
[3]);
327 // Correct uid size bits in ATQA
328 rATQA
[0] = (rATQA
[0] & 0x3f) | 0x40; // double size uid
329 } else if (IS_FLAG_UID_IN_DATA(flags
, 10)) {
330 memcpy(&rUIDBCC1
[1], uid
, 3);
331 memcpy(&rUIDBCC2
[1], uid
+ 3, 3);
332 memcpy(rUIDBCC3
, uid
+ 6, 4);
335 *cuid
= bytes_to_num(rUIDBCC3
, 4);
337 rUIDBCC1
[0] = MIFARE_SELECT_CT
;
338 rUIDBCC2
[0] = MIFARE_SELECT_CT
;
340 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
341 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
342 rUIDBCC3
[4] = rUIDBCC3
[0] ^ rUIDBCC3
[1] ^ rUIDBCC3
[2] ^ rUIDBCC3
[3];
343 if (g_dbglevel
>= DBG_EXTENDED
)
344 Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X - BCC2: %02X - BCC3: %02X", flags
, rUIDBCC1
[4], rUIDBCC2
[4], rUIDBCC3
[4]);
345 if (g_dbglevel
> DBG_NONE
) {
346 Dbprintf("10B UID: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
347 rUIDBCC1
[1], rUIDBCC1
[2], rUIDBCC1
[3],
348 rUIDBCC2
[1], rUIDBCC2
[2], rUIDBCC2
[3],
349 rUIDBCC3
[0], rUIDBCC3
[1], rUIDBCC3
[2], rUIDBCC3
[3]
353 // Correct uid size bits in ATQA
354 rATQA
[0] = (rATQA
[0] & 0x3f) | 0x80; // triple size uid
356 Dbprintf("ERROR: " _RED_("UID size not defined"));
359 if (flags
& FLAG_ATQA_IN_DATA
) {
360 rATQA
[0] = atqa
>> 8;
361 rATQA
[1] = atqa
& 0xff;
363 if (flags
& FLAG_SAK_IN_DATA
) {
366 if (g_dbglevel
> DBG_NONE
) {
367 Dbprintf("ATQA : %02X %02X", rATQA
[1], rATQA
[0]);
368 Dbprintf("SAK : %02X", rSAK
[0]);
371 // clone UIDs for byte-frame anti-collision multiple tag selection procedure
372 memcpy(rUIDBCC1b4
, &rUIDBCC1
[1], 4);
373 memcpy(rUIDBCC1b3
, &rUIDBCC1
[2], 3);
374 memcpy(rUIDBCC1b2
, &rUIDBCC1
[3], 2);
375 memcpy(rUIDBCC1b1
, &rUIDBCC1
[4], 1);
377 memcpy(rUIDBCC2b4
, &rUIDBCC2
[1], 4);
378 memcpy(rUIDBCC2b3
, &rUIDBCC2
[2], 3);
379 memcpy(rUIDBCC2b2
, &rUIDBCC2
[3], 2);
380 memcpy(rUIDBCC2b1
, &rUIDBCC2
[4], 1);
382 if (*uid_len
== 10) {
383 memcpy(rUIDBCC3b4
, &rUIDBCC3
[1], 4);
384 memcpy(rUIDBCC3b3
, &rUIDBCC3
[2], 3);
385 memcpy(rUIDBCC3b2
, &rUIDBCC3
[3], 2);
386 memcpy(rUIDBCC3b1
, &rUIDBCC3
[4], 1);
389 // Calculate actual CRC
390 AddCrc14A(rSAK
, sizeof(rSAK
) - 2);
392 #define TAG_RESPONSE_COUNT 18
393 static tag_response_info_t responses_init
[TAG_RESPONSE_COUNT
] = {
394 { .response
= rATQA
, .response_n
= sizeof(rATQA
) }, // Answer to request - respond with card type
395 { .response
= rSAK
, .response_n
= sizeof(rSAK
) }, //
396 { .response
= rSAKuid
, .response_n
= sizeof(rSAKuid
) }, //
397 // Do not reorder. Block used via relative index of rUIDBCC1
398 { .response
= rUIDBCC1
, .response_n
= sizeof(rUIDBCC1
) }, // Anticollision cascade1 - respond with first part of uid
399 { .response
= rUIDBCC1b4
, .response_n
= sizeof(rUIDBCC1b4
)},
400 { .response
= rUIDBCC1b3
, .response_n
= sizeof(rUIDBCC1b3
)},
401 { .response
= rUIDBCC1b2
, .response_n
= sizeof(rUIDBCC1b2
)},
402 { .response
= rUIDBCC1b1
, .response_n
= sizeof(rUIDBCC1b1
)},
403 // Do not reorder. Block used via relative index of rUIDBCC2
404 { .response
= rUIDBCC2
, .response_n
= sizeof(rUIDBCC2
) }, // Anticollision cascade2 - respond with 2nd part of uid
405 { .response
= rUIDBCC2b4
, .response_n
= sizeof(rUIDBCC2b4
)},
406 { .response
= rUIDBCC2b3
, .response_n
= sizeof(rUIDBCC2b3
)},
407 { .response
= rUIDBCC2b2
, .response_n
= sizeof(rUIDBCC2b2
)},
408 { .response
= rUIDBCC2b1
, .response_n
= sizeof(rUIDBCC2b1
)},
409 // Do not reorder. Block used via relative index of rUIDBCC3
410 { .response
= rUIDBCC3
, .response_n
= sizeof(rUIDBCC3
) }, // Anticollision cascade3 - respond with 3th part of uid
411 { .response
= rUIDBCC3b4
, .response_n
= sizeof(rUIDBCC3b4
)},
412 { .response
= rUIDBCC3b3
, .response_n
= sizeof(rUIDBCC3b3
)},
413 { .response
= rUIDBCC3b2
, .response_n
= sizeof(rUIDBCC3b2
)},
414 { .response
= rUIDBCC3b1
, .response_n
= sizeof(rUIDBCC3b1
)}
417 // Prepare ("precompile") the responses of the anticollision phase.
418 // There will be not enough time to do this at the moment the reader sends its REQA or SELECT
419 // There are 18 predefined responses with a total of 53 bytes data to transmit.
420 // Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
421 // 53 * 8 data bits, 53 * 1 parity bits, 18 start bits, 18 stop bits, 18 correction bits -> need 571 bytes buffer
422 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 571
424 uint8_t *free_buffer
= BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE
);
425 // modulation buffer pointer and current buffer free space size
426 uint8_t *free_buffer_pointer
= free_buffer
;
427 size_t free_buffer_size
= ALLOCATED_TAG_MODULATION_BUFFER_SIZE
;
429 for (size_t i
= 0; i
< TAG_RESPONSE_COUNT
; i
++) {
430 if (prepare_allocated_tag_modulation(&responses_init
[i
], &free_buffer_pointer
, &free_buffer_size
) == false) {
431 Dbprintf("Not enough modulation buffer size, exit after %d elements", i
);
436 *responses
= responses_init
;
438 // indices into responses array:
452 *@param flags: See pm3_cmd.h for the full definitions
453 *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ...
454 * (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attempted)
456 void Mifare1ksim(uint16_t flags
, uint8_t exitAfterNReads
, uint8_t *uid
, uint16_t atqa
, uint8_t sak
) {
457 tag_response_info_t
*responses
;
458 uint8_t cardSTATE
= MFEMUL_NOFIELD
;
459 uint8_t uid_len
= 0; // 4, 7, 10
460 uint32_t cuid
= 0, selTimer
= 0, authTimer
= 0;
465 uint8_t cardWRBL
= 0;
466 uint8_t cardAUTHSC
= 0;
467 uint8_t cardAUTHKEY
= AUTHKEYNONE
; // no authentication
470 uint32_t cardINTREG
= 0;
471 uint8_t cardINTBLOCK
= 0;
473 struct Crypto1State mpcs
= {0, 0};
474 struct Crypto1State
*pcs
;
477 uint32_t numReads
= 0; //Counts numer of times reader reads a block
478 uint8_t receivedCmd
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
479 uint8_t receivedCmd_dec
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
480 uint8_t receivedCmd_par
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
481 uint16_t receivedCmd_len
;
483 uint8_t response
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
484 uint8_t response_par
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
486 uint8_t *rats
= NULL
;
487 uint8_t rats_len
= 0;
490 //Here, we collect UID,sector,keytype,NT,AR,NR,NT2,AR2,NR2
491 // This will be used in the reader-only attack.
493 //allow collecting up to 16 sets of nonces to allow recovery of up to 16 keys
494 #define ATTACK_KEY_COUNT 16
495 nonces_t ar_nr_resp
[ATTACK_KEY_COUNT
]; // for moebius attack type
496 memset(ar_nr_resp
, 0x00, sizeof(ar_nr_resp
));
498 // Authenticate response - nonce
499 uint8_t rAUTH_NT
[4] = {0, 0, 0, 1};
500 uint8_t rAUTH_NT_keystream
[4];
503 const tUart14a
*uart
= GetUart14a();
505 // free eventually allocated BigBuf memory but keep Emulator Memory
506 BigBuf_free_keep_EM();
508 if (MifareSimInit(flags
, uid
, atqa
, sak
, &responses
, &cuid
, &uid_len
, &rats
, &rats_len
) == false) {
509 BigBuf_free_keep_EM();
513 // We need to listen to the high-frequency, peak-detected path.
514 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
522 uint8_t *p_em
= BigBuf_get_EM_addr();
523 uint8_t cve_flipper
= 0;
526 bool finished
= false;
527 bool running_nested_auth_attack
= false;
528 bool button_pushed
= BUTTON_PRESS();
529 while ((button_pushed
== false) && (finished
== false)) {
533 if (counter
== 1000) {
534 if (data_available()) {
535 Dbprintf("----------- " _GREEN_("BREAKING") " ----------");
545 if (cardSTATE == MFEMUL_NOFIELD) {
547 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
549 if (vHf > MF_MINFIELDV) {
553 button_pushed = BUTTON_PRESS();
560 int res
= EmGetCmd(receivedCmd
, sizeof(receivedCmd
), &receivedCmd_len
, receivedCmd_par
);
562 if (res
== 2) { //Field is off!
563 //FpgaDisableTracing();
564 if ((flags
& FLAG_CVE21_0430
) == FLAG_CVE21_0430
) {
569 cardSTATE
= MFEMUL_NOFIELD
;
570 if (g_dbglevel
>= DBG_EXTENDED
)
571 Dbprintf("cardSTATE = MFEMUL_NOFIELD");
573 } else if (res
== 1) { // button pressed
574 FpgaDisableTracing();
575 button_pushed
= true;
576 if (g_dbglevel
>= DBG_EXTENDED
)
577 Dbprintf("Button pressed");
581 // WUPA in HALTED state or REQA or WUPA in any other state
582 if (receivedCmd_len
== 1 && ((receivedCmd
[0] == ISO14443A_CMD_REQA
&& cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == ISO14443A_CMD_WUPA
)) {
583 selTimer
= GetTickCount();
584 if (g_dbglevel
>= DBG_EXTENDED
) {
585 //Dbprintf("EmSendPrecompiledCmd(&responses[ATQA]);");
587 EmSendPrecompiledCmd(&responses
[ATQA
]);
589 FpgaDisableTracing();
593 cardAUTHKEY
= AUTHKEYNONE
;
594 nonce
= prng_successor(selTimer
, 32);
595 // prepare NT for nested authentication
596 num_to_bytes(nonce
, 4, rAUTH_NT
);
597 num_to_bytes(cuid
^ nonce
, 4, rAUTH_NT_keystream
);
601 cardSTATE
= MFEMUL_SELECT
;
603 if ((flags
& FLAG_CVE21_0430
) == FLAG_CVE21_0430
) {
611 case MFEMUL_NOFIELD
: {
612 if (g_dbglevel
>= DBG_EXTENDED
)
613 Dbprintf("MFEMUL_NOFIELD");
616 case MFEMUL_HALTED
: {
617 if (g_dbglevel
>= DBG_EXTENDED
)
618 Dbprintf("MFEMUL_HALTED");
622 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
623 if (g_dbglevel
>= DBG_EXTENDED
)
624 Dbprintf("MFEMUL_IDLE");
628 // The anti-collision sequence, which is a mandatory part of the card activation sequence.
629 // It auto with 4-byte UID (= Single Size UID),
630 // 7 -byte UID (= Double Size UID) or 10-byte UID (= Triple Size UID).
631 // For details see chapter 2 of AN10927.pdf
633 // This case is used for all Cascade Levels, because:
634 // 1) Any devices (under Android for example) after full select procedure completed,
635 // when UID is known, uses "fast-selection" method. In this case reader ignores
636 // first cascades and tries to select tag by last bytes of UID of last cascade
637 // 2) Any readers (like ACR122U) uses bit oriented anti-collision frames during selectin,
638 // same as multiple tags. For details see chapter 6.1.5.3 of ISO/IEC 14443-3
639 case MFEMUL_SELECT
: {
641 // Extract cascade level
642 if (receivedCmd_len
>= 2) {
643 switch (receivedCmd
[0]) {
644 case ISO14443A_CMD_ANTICOLL_OR_SELECT
:
647 case ISO14443A_CMD_ANTICOLL_OR_SELECT_2
:
650 case ISO14443A_CMD_ANTICOLL_OR_SELECT_3
:
656 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
658 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] Incorrect cascade level received");
662 // Incoming SELECT ALL for any cascade level
663 if (receivedCmd_len
== 2 && receivedCmd
[1] == 0x20) {
664 EmSendPrecompiledCmd(&responses
[uid_index
]);
665 FpgaDisableTracing();
667 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("SELECT ALL - EmSendPrecompiledCmd(%02x)", &responses
[uid_index
]);
671 // Incoming SELECT CLx for any cascade level
672 if (receivedCmd_len
== 9 && receivedCmd
[1] == 0x70) {
673 if (memcmp(&receivedCmd
[2], responses
[uid_index
].response
, 4) == 0) {
674 bool cl_finished
= (uid_len
== 4 && uid_index
== UIDBCC1
) ||
675 (uid_len
== 7 && uid_index
== UIDBCC2
) ||
676 (uid_len
== 10 && uid_index
== UIDBCC3
);
677 EmSendPrecompiledCmd(&responses
[cl_finished
? SAK
: SAKuid
]);
678 FpgaDisableTracing();
680 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("SELECT CLx %02x%02x%02x%02x received", receivedCmd
[2], receivedCmd
[3], receivedCmd
[4], receivedCmd
[5]);
683 cardSTATE
= MFEMUL_WORK
;
684 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_WORK");
688 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
690 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_IDLE");
695 // Incoming anti-collision frame
696 // receivedCmd[1] indicates number of byte and bit collision, supports only for bit collision is zero
697 if (receivedCmd_len
>= 3 && receivedCmd_len
<= 6 && (receivedCmd
[1] & 0x0f) == 0) {
698 // we can process only full-byte frame anti-collision procedure
699 if (memcmp(&receivedCmd
[2], responses
[uid_index
].response
, receivedCmd_len
- 2) == 0) {
700 // response missing part of UID via relative array index
701 EmSendPrecompiledCmd(&responses
[uid_index
+ receivedCmd_len
- 2]);
702 FpgaDisableTracing();
704 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("SELECT ANTICOLLISION - EmSendPrecompiledCmd(%02x)", &responses
[uid_index
]);
706 // IDLE, not our UID or split-byte frame anti-collision (not supports)
707 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
709 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] cardSTATE = MFEMUL_IDLE");
714 // Unknown selection procedure
715 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
717 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_SELECT] Unknown selection procedure");
724 if (g_dbglevel
>= DBG_EXTENDED
) {
725 // Dbprintf("[MFEMUL_WORK] Enter in case");
728 if (receivedCmd_len
== 0) {
729 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] NO CMD received");
733 encrypted_data
= (cardAUTHKEY
!= AUTHKEYNONE
);
734 if (encrypted_data
) {
736 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, receivedCmd_dec
);
737 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] Decrypt sequence");
740 memcpy(receivedCmd_dec
, receivedCmd
, receivedCmd_len
);
743 // all commands must have a valid CRC
744 if (CheckCrc14A(receivedCmd_dec
, receivedCmd_len
) == false) {
745 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
746 FpgaDisableTracing();
748 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] All commands must have a valid CRC %02X (%d)", receivedCmd_dec
, receivedCmd_len
);
752 if (receivedCmd_len
== 4 && (receivedCmd_dec
[0] == MIFARE_AUTH_KEYA
|| receivedCmd_dec
[0] == MIFARE_AUTH_KEYB
)) {
754 // Reader asks for AUTH: 6X XX
755 // RCV: 60 XX => Using KEY A
756 // RCV: 61 XX => Using KEY B
759 authTimer
= GetTickCount();
761 // received block num -> sector
763 // 4K tags have 16 blocks per sector 32..39
764 cardAUTHSC
= MifareBlockToSector(receivedCmd_dec
[1]);
766 // cardAUTHKEY: 60 => Auth use Key A
767 // cardAUTHKEY: 61 => Auth use Key B
768 cardAUTHKEY
= receivedCmd_dec
[0] & 0x01;
770 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] KEY %c: %012" PRIx64
, (cardAUTHKEY
== 0) ? 'A' : 'B', emlGetKey(cardAUTHSC
, cardAUTHKEY
));
772 // first authentication
775 // Load key into crypto
776 crypto1_init(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
777 running_nested_auth_attack
= false;
778 if (!encrypted_data
) {
779 // Receive Cmd in clear txt
780 // Update crypto state (UID ^ NONCE)
781 crypto1_word(pcs
, cuid
^ nonce
, 0);
782 // rAUTH_NT contains prepared nonce for authenticate
783 EmSendCmd(rAUTH_NT
, sizeof(rAUTH_NT
));
784 FpgaDisableTracing();
786 if (g_dbglevel
>= DBG_EXTENDED
) {
787 Dbprintf("[MFEMUL_WORK] Reader authenticating for block %d (0x%02x) with key %c - nonce: %08X - cuid: %08X",
790 (cardAUTHKEY
== 0) ? 'A' : 'B',
796 // nested authentication
798 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
799 num_to_bytes(ans, 4, rAUTH_AT);
802 // if key not known and FLAG_NESTED_AUTH_ATTACK and we have nt/nt_enc/parity, send recorded nt_enc and parity
803 if ((flags
& FLAG_NESTED_AUTH_ATTACK
) == FLAG_NESTED_AUTH_ATTACK
) {
804 if (emlGetKey(cardAUTHSC
, cardAUTHKEY
) == 0) {
805 uint8_t buf
[16] = {0};
806 emlGetMem(buf
, (CARD_MEMORY_RF08S_OFFSET
/ MIFARE_BLOCK_SIZE
) + cardAUTHSC
, 1);
807 if (buf
[(cardAUTHKEY
* 8) + 3] == 0xAA) { // extra check to tell we have nt/nt_enc/par_err
808 running_nested_auth_attack
= true;
810 nonce
= bytes_to_num(buf
+ (cardAUTHKEY
* 8), 2);
811 nonce
= nonce
<< 16 | prng_successor(nonce
, 16);
813 memcpy(response
, buf
+ (cardAUTHKEY
* 8) + 4, 4);
814 uint8_t nt_par_err
= buf
[(cardAUTHKEY
* 8) + 2];
815 uint32_t nt_enc
= bytes_to_num(response
, 4);
816 response_par
[0] = ((((nt_par_err
>> 3) & 1) ^ oddparity8((nt_enc
>> 24) & 0xFF)) << 7 |
817 (((nt_par_err
>> 2) & 1) ^ oddparity8((nt_enc
>> 16) & 0xFF)) << 6 |
818 (((nt_par_err
>> 1) & 1) ^ oddparity8((nt_enc
>> 8) & 0xFF)) << 5 |
819 (((nt_par_err
>> 0) & 1) ^ oddparity8((nt_enc
>> 0) & 0xFF)) << 4);
820 ar_nr_resp
[0].cuid
= cuid
;
821 ar_nr_resp
[0].sector
= cardAUTHSC
;
822 ar_nr_resp
[0].keytype
= cardAUTHKEY
;
823 ar_nr_resp
[0].nonce
= nonce
;
824 ar_nr_resp
[0].nonce2
= nt_enc
;
828 if (running_nested_auth_attack
== false) {
829 // rAUTH_NT, rAUTH_NT_keystream contains prepared nonce and keystream for nested authentication
830 // we need calculate parity bits for non-encrypted sequence
831 mf_crypto1_encryptEx(pcs
, rAUTH_NT
, rAUTH_NT_keystream
, response
, 4, response_par
);
833 EmSendCmdPar(response
, 4, response_par
);
834 FpgaDisableTracing();
836 if (g_dbglevel
>= DBG_EXTENDED
) {
837 Dbprintf("[MFEMUL_WORK] Reader doing nested authentication for block %d (0x%02x) with key %c",
840 (cardAUTHKEY
== 0) ? 'A' : 'B'
845 cardSTATE
= MFEMUL_AUTH1
;
846 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_AUTH1 - rAUTH_NT: %02X", rAUTH_NT
);
850 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
851 // BUT... ACK --> NACK
852 if (receivedCmd_len
== 1 && receivedCmd_dec
[0] == CARD_ACK
) {
853 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
854 FpgaDisableTracing();
858 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
859 if (receivedCmd_len
== 1 && receivedCmd_dec
[0] == CARD_NACK_NA
) {
860 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_ACK
) : CARD_ACK
);
861 FpgaDisableTracing();
865 // case MFEMUL_WORK => if Cmd is Read, Write, Inc, Dec, Restore, Transfer
866 if (receivedCmd_len
== 4 && (receivedCmd_dec
[0] == ISO14443A_CMD_READBLOCK
867 || receivedCmd_dec
[0] == ISO14443A_CMD_WRITEBLOCK
868 || receivedCmd_dec
[0] == MIFARE_CMD_INC
869 || receivedCmd_dec
[0] == MIFARE_CMD_DEC
870 || receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
871 || receivedCmd_dec
[0] == MIFARE_CMD_TRANSFER
)) {
872 // all other commands must be encrypted (authenticated)
873 if (!encrypted_data
) {
874 EmSend4bit(CARD_NACK_NA
);
875 FpgaDisableTracing();
877 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] Commands must be encrypted (authenticated)");
881 // iceman, u8 can never be larger the MIFARE_4K_MAXBLOCK (256)
882 // Check if Block num is not too far
884 if (receivedCmd_dec[1] > MIFARE_4K_MAXBLOCK) {
885 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
886 FpgaDisableTracing();
887 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]);
891 blockNo
= receivedCmd_dec
[1];
892 if (MifareBlockToSector(blockNo
) != cardAUTHSC
) {
893 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
894 FpgaDisableTracing();
896 if (g_dbglevel
>= DBG_ERROR
)
897 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
);
901 // Compliance of MIFARE Classic EV1 1K Datasheet footnote of Table 8
902 // If access bits show that key B is Readable, any subsequent memory access will be refused.
903 // Some cards don't respect it so we can also skip it with FLAG_MF_USE_READ_KEYB
904 if ((flags
& FLAG_MF_USE_READ_KEYB
) != FLAG_MF_USE_READ_KEYB
) {
905 if (cardAUTHKEY
== AUTHKEYB
&& IsKeyBReadable(blockNo
)) {
906 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
907 FpgaDisableTracing();
909 if (g_dbglevel
>= DBG_ERROR
)
910 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
);
916 // case MFEMUL_WORK => CMD READ block
917 if (receivedCmd_len
== 4 && receivedCmd_dec
[0] == ISO14443A_CMD_READBLOCK
) {
918 blockNo
= receivedCmd_dec
[1];
919 if (g_dbglevel
>= DBG_EXTENDED
)
920 Dbprintf("[MFEMUL_WORK] Reader reading block %d (0x%02x)", blockNo
, blockNo
);
922 // android CVE 2021_0430
923 // Simulate a MFC 1K, with a NDEF message.
924 // these values uses the standard LIBNFC NDEF message
926 // In short, first a value read of block 4,
927 // update the length byte before second read of block 4.
928 // on iphone etc there might even be 3 reads of block 4.
929 // fiddling with when to flip the byte or not, has different effects
930 if ((flags
& FLAG_CVE21_0430
) == FLAG_CVE21_0430
) {
935 p_em
+= blockNo
* 16;
936 // TLV in NDEF, flip length between
937 // 4 | 03 21 D1 02 1C 53 70 91 01 09 54 02 65 6E 4C 69
938 // 0xFF means long length
939 // 0xFE mean max short length
941 // We could also have a go at message len byte at p_em[4]...
942 if (p_em
[1] == 0x21 && cve_flipper
== 1) {
950 emlGetMem(response
, blockNo
, 1);
952 if (g_dbglevel
>= DBG_EXTENDED
) {
953 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
,
954 response
[0], response
[1], response
[2], response
[3], response
[4], response
[5], response
[6],
955 response
[7], response
[8], response
[9], response
[10], response
[11], response
[12], response
[13],
956 response
[14], response
[15]);
959 // Access permission management:
969 // If permission is not allowed, data is cleared (00) in emulator memory.
970 // ex: a0a1a2a3a4a561e789c1b0b1b2b3b4b5 => 00000000000061e789c1b0b1b2b3b4b5
973 // Check if selected Block is a Sector Trailer
974 if (IsSectorTrailer(blockNo
)) {
976 if (IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_KEYA_READ
) == false) {
977 memset(response
, 0x00, 6); // keyA can never be read
978 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyA can never be read - block %d (0x%02x)", blockNo
, blockNo
);
980 if (IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_KEYB_READ
) == false) {
981 memset(response
+ 10, 0x00, 6); // keyB cannot be read
982 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK - IsSectorTrailer] keyB cannot be read - block %d (0x%02x)", blockNo
, blockNo
);
984 if (IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_AC_READ
) == false) {
985 memset(response
+ 6, 0x00, 4); // AC bits cannot be read
986 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] AC bits cannot be read - block %d (0x%02x)", blockNo
, blockNo
);
989 if (IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_DATA_READ
) == false) {
990 memset(response
, 0x00, 16); // datablock cannot be read
991 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK - IsAccessAllowed] Data block %d (0x%02x) cannot be read", blockNo
, blockNo
);
994 AddCrc14A(response
, 16);
995 mf_crypto1_encrypt(pcs
, response
, MAX_MIFARE_FRAME_SIZE
, response_par
);
996 EmSendCmdPar(response
, MAX_MIFARE_FRAME_SIZE
, response_par
);
997 FpgaDisableTracing();
999 if (g_dbglevel
>= DBG_EXTENDED
) {
1000 Dbprintf("[MFEMUL_WORK - EmSendCmdPar] Data Block[%d]: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", blockNo
,
1001 response
[0], response
[1], response
[2], response
[3], response
[4], response
[5], response
[6],
1002 response
[7], response
[8], response
[9], response
[10], response
[11], response
[12], response
[13],
1003 response
[14], response
[15]);
1007 if (exitAfterNReads
> 0 && numReads
== exitAfterNReads
) {
1008 Dbprintf("[MFEMUL_WORK] %d reads done, exiting", numReads
);
1013 } // End receivedCmd_dec[0] == ISO14443A_CMD_READBLOCK
1015 // case MFEMUL_WORK => CMD WRITEBLOCK
1016 if (receivedCmd_len
== 4 && receivedCmd_dec
[0] == ISO14443A_CMD_WRITEBLOCK
) {
1017 blockNo
= receivedCmd_dec
[1];
1018 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] RECV 0xA0 write block %d (%02x)", blockNo
, blockNo
);
1019 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
1020 FpgaDisableTracing();
1023 cardSTATE
= MFEMUL_WRITEBL2
;
1024 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_WRITEBL2");
1028 // case MFEMUL_WORK => CMD INC/DEC/REST
1029 if (receivedCmd_len
== 4 && (receivedCmd_dec
[0] == MIFARE_CMD_INC
|| receivedCmd_dec
[0] == MIFARE_CMD_DEC
|| receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
)) {
1030 blockNo
= receivedCmd_dec
[1];
1031 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
);
1032 if (emlCheckValBl(blockNo
) == false) {
1033 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("[MFEMUL_WORK] Reader tried to operate on block, but emlCheckValBl failed, nacking");
1034 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
1035 FpgaDisableTracing();
1038 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
1039 FpgaDisableTracing();
1043 if (receivedCmd_dec
[0] == MIFARE_CMD_INC
) {
1044 cardSTATE
= MFEMUL_INTREG_INC
;
1045 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_INC");
1049 if (receivedCmd_dec
[0] == MIFARE_CMD_DEC
) {
1050 cardSTATE
= MFEMUL_INTREG_DEC
;
1051 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_DEC");
1055 if (receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
) {
1056 cardSTATE
= MFEMUL_INTREG_REST
;
1057 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_INTREG_REST");
1061 } // End case MFEMUL_WORK => CMD INC/DEC/REST
1064 // case MFEMUL_WORK => CMD TRANSFER
1065 if (receivedCmd_len
== 4 && receivedCmd_dec
[0] == MIFARE_CMD_TRANSFER
) {
1066 blockNo
= receivedCmd_dec
[1];
1067 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WORK] RECV 0x%02x transfer block %d (%02x)", receivedCmd_dec
[0], blockNo
, blockNo
);
1068 emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd_dec
[1]);
1069 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
1070 FpgaDisableTracing();
1074 // case MFEMUL_WORK => CMD HALT
1075 if (receivedCmd_len
> 1 && receivedCmd_dec
[0] == ISO14443A_CMD_HALT
&& receivedCmd_dec
[1] == 0x00) {
1076 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1079 cardSTATE
= MFEMUL_HALTED
;
1080 cardAUTHKEY
= AUTHKEYNONE
;
1081 if (g_dbglevel
>= DBG_EXTENDED
) {
1082 Dbprintf("[MFEMUL_WORK] cardSTATE = MFEMUL_HALTED");
1087 // case MFEMUL_WORK => CMD RATS
1088 if (receivedCmd_len
== 4 && receivedCmd_dec
[0] == ISO14443A_CMD_RATS
&& (receivedCmd_dec
[1] & 0xF0) <= 0x80 && (receivedCmd_dec
[1] & 0x0F) <= 0x0e) {
1089 if (rats
&& rats_len
) {
1090 if (encrypted_data
) {
1091 memcpy(response
, rats
, rats_len
);
1092 mf_crypto1_encrypt(pcs
, response
, rats_len
, response_par
);
1093 EmSendCmdPar(response
, rats_len
, response_par
);
1095 EmSendCmd(rats
, rats_len
);
1097 FpgaDisableTracing();
1098 if (g_dbglevel
>= DBG_EXTENDED
)
1099 Dbprintf("[MFEMUL_WORK] RCV RATS => ACK");
1101 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
1102 FpgaDisableTracing();
1103 cardSTATE_TO_IDLE();
1104 if (g_dbglevel
>= DBG_EXTENDED
)
1105 Dbprintf("[MFEMUL_WORK] RCV RATS => NACK");
1110 // case MFEMUL_WORK => ISO14443A_CMD_NXP_DESELECT
1111 if (receivedCmd_len
== 3 && receivedCmd_dec
[0] == ISO14443A_CMD_NXP_DESELECT
) {
1112 if (rats
&& rats_len
) {
1113 // response back NXP_DESELECT
1114 if (encrypted_data
) {
1115 memcpy(response
, receivedCmd_dec
, receivedCmd_len
);
1116 mf_crypto1_encrypt(pcs
, response
, receivedCmd_len
, response_par
);
1117 EmSendCmdPar(response
, receivedCmd_len
, response_par
);
1119 EmSendCmd(receivedCmd_dec
, receivedCmd_len
);
1121 FpgaDisableTracing();
1122 if (g_dbglevel
>= DBG_EXTENDED
)
1123 Dbprintf("[MFEMUL_WORK] RCV NXP DESELECT => ACK");
1125 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
1126 FpgaDisableTracing();
1127 cardSTATE_TO_IDLE();
1128 if (g_dbglevel
>= DBG_EXTENDED
)
1129 Dbprintf("[MFEMUL_WORK] RCV NXP DESELECT => NACK");
1134 // case MFEMUL_WORK => command not allowed
1135 if (g_dbglevel
>= DBG_EXTENDED
)
1136 Dbprintf("Received command not allowed, nacking");
1137 EmSend4bit(encrypted_data
? mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
) : CARD_NACK_NA
);
1138 FpgaDisableTracing();
1143 case MFEMUL_AUTH1
: {
1144 if (g_dbglevel
>= DBG_EXTENDED
)
1145 Dbprintf("[MFEMUL_AUTH1] Enter case");
1147 if (receivedCmd_len
!= 8) {
1148 cardSTATE_TO_IDLE();
1149 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1150 if (g_dbglevel
>= DBG_EXTENDED
)
1151 Dbprintf("MFEMUL_AUTH1: receivedCmd_len != 8 (%d) => cardSTATE_TO_IDLE())", receivedCmd_len
);
1155 nr
= bytes_to_num(receivedCmd
, 4);
1156 ar
= bytes_to_num(&receivedCmd
[4], 4);
1159 crypto1_word(pcs
, nr
, 1);
1160 cardRr
= ar
^ crypto1_word(pcs
, 0, 0);
1163 if (cardRr
!= prng_successor(nonce
, 64)) {
1164 // Collect AR/NR per keytype & sector
1165 if (running_nested_auth_attack
) {
1166 ar_nr_resp
[0].nr
= nr
;
1167 ar_nr_resp
[0].ar
= ar
;
1168 ar_nr_resp
[0].state
= NESTED
;
1171 if ((flags
& FLAG_NR_AR_ATTACK
) == FLAG_NR_AR_ATTACK
) {
1173 for (uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
1174 if (ar_nr_resp
[i
].state
== EMPTY
||
1176 (ar_nr_resp
[i
].state
!= EMPTY
) &&
1177 (cardAUTHSC
== ar_nr_resp
[i
].sector
) &&
1178 (cardAUTHKEY
== ar_nr_resp
[i
].keytype
)
1181 // if first auth for sector, or matches sector and keytype of previous auth
1182 if (ar_nr_resp
[i
].state
!= SECOND
) {
1183 // if we haven't already collected 2 nonces for this sector
1184 if (ar_nr_resp
[i
].state
== EMPTY
) {
1185 // first nonce collect
1186 ar_nr_resp
[i
].cuid
= cuid
;
1187 ar_nr_resp
[i
].sector
= cardAUTHSC
;
1188 ar_nr_resp
[i
].keytype
= cardAUTHKEY
;
1189 ar_nr_resp
[i
].nonce
= nonce
;
1190 ar_nr_resp
[i
].nr
= nr
;
1191 ar_nr_resp
[i
].ar
= ar
;
1192 ar_nr_resp
[i
].state
= FIRST
;
1193 } else { // second nonce collect
1194 // make sure we have different nonces for moebius attack
1195 if (ar_nr_resp
[i
].nonce
!= nonce
) {
1196 ar_nr_resp
[i
].nonce2
= nonce
;
1197 ar_nr_resp
[i
].nr2
= nr
;
1198 ar_nr_resp
[i
].ar2
= ar
;
1199 ar_nr_resp
[i
].state
= SECOND
;
1204 // we found right spot for this nonce stop looking
1209 if (g_dbglevel
>= DBG_EXTENDED
) {
1210 Dbprintf("[MFEMUL_AUTH1] AUTH FAILED for sector %d with key %c. [nr=%08x cardRr=%08x] [nt=%08x succ=%08x]"
1212 , (cardAUTHKEY
== 0) ? 'A' : 'B'
1216 , prng_successor(nonce
, 64)
1219 cardAUTHKEY
= AUTHKEYNONE
; // not authenticated
1220 cardSTATE_TO_IDLE();
1221 // Really tags not respond NACK on invalid authentication
1222 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1226 ans
= prng_successor(nonce
, 96);
1227 num_to_bytes(ans
, 4, response
);
1228 mf_crypto1_encrypt(pcs
, response
, 4, response_par
);
1229 EmSendCmdPar(response
, 4, response_par
);
1230 FpgaDisableTracing();
1232 if (g_dbglevel
>= DBG_EXTENDED
) {
1233 Dbprintf("[MFEMUL_AUTH1] AUTH COMPLETED for sector %d with key %c. time=%d",
1235 cardAUTHKEY
== 0 ? 'A' : 'B',
1236 GetTickCountDelta(authTimer
)
1240 cardSTATE
= MFEMUL_WORK
;
1241 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_AUTH1] cardSTATE = MFEMUL_WORK");
1246 case MFEMUL_WRITEBL2
: {
1247 if (receivedCmd_len
== MAX_MIFARE_FRAME_SIZE
) {
1248 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, receivedCmd_dec
);
1249 if (CheckCrc14A(receivedCmd_dec
, receivedCmd_len
)) {
1250 if (IsSectorTrailer(cardWRBL
)) {
1251 emlGetMem(response
, cardWRBL
, 1);
1252 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_KEYA_WRITE
)) {
1253 memcpy(receivedCmd_dec
, response
, 6); // don't change KeyA
1255 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_KEYB_WRITE
)) {
1256 memcpy(receivedCmd_dec
+ 10, response
+ 10, 6); // don't change KeyA
1258 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_AC_WRITE
)) {
1259 memcpy(receivedCmd_dec
+ 6, response
+ 6, 4); // don't change AC bits
1262 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_DATA_WRITE
)) {
1263 memcpy(receivedCmd_dec
, response
, 16); // don't change anything
1266 emlSetMem_xt(receivedCmd_dec
, cardWRBL
, 1, 16);
1267 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
)); // always ACK?
1268 FpgaDisableTracing();
1270 cardSTATE
= MFEMUL_WORK
;
1271 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_WORK");
1275 cardSTATE_TO_IDLE();
1276 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_WRITEBL2] cardSTATE = MFEMUL_IDLE");
1277 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1282 case MFEMUL_INTREG_INC
: {
1283 if (receivedCmd_len
== 6) {
1284 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t *)&ans
);
1285 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
) != PM3_SUCCESS
) {
1286 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
1287 FpgaDisableTracing();
1289 cardSTATE_TO_IDLE();
1292 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1293 cardINTREG
= cardINTREG
+ ans
;
1295 cardSTATE
= MFEMUL_WORK
;
1296 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_INTREG_INC] cardSTATE = MFEMUL_WORK");
1302 case MFEMUL_INTREG_DEC
: {
1303 if (receivedCmd_len
== 6) { // Data is encrypted
1305 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t *)&ans
);
1306 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
) != PM3_SUCCESS
) {
1307 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
1308 FpgaDisableTracing();
1310 cardSTATE_TO_IDLE();
1314 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1315 cardINTREG
= cardINTREG
- ans
;
1316 cardSTATE
= MFEMUL_WORK
;
1317 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_INTREG_DEC] cardSTATE = MFEMUL_WORK");
1322 case MFEMUL_INTREG_REST
: {
1323 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t *)&ans
);
1324 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
) != PM3_SUCCESS
) {
1325 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
1326 FpgaDisableTracing();
1328 cardSTATE_TO_IDLE();
1331 LogTrace(uart
->output
, uart
->len
, uart
->startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, uart
->parity
, true);
1332 cardSTATE
= MFEMUL_WORK
;
1333 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("[MFEMUL_INTREG_REST] cardSTATE = MFEMUL_WORK");
1337 } // End Switch Loop
1339 button_pushed
= BUTTON_PRESS();
1343 FpgaDisableTracing();
1346 if (running_nested_auth_attack
) {
1347 if ((nonce_state
)ar_nr_resp
[0].state
== NESTED
) {
1348 running_nested_auth_attack
= false;
1349 if (g_dbglevel
>= DBG_INFO
) {
1350 Dbprintf("Collected nested AR/NR which can be used to extract sector %d " _YELLOW_("%s")
1351 , ar_nr_resp
[0].sector
1352 , (ar_nr_resp
[0].keytype
== AUTHKEYA
) ? "key A" : "key B"
1354 Dbprintf("../tools/mfc/card_reader/mfkey32nested %08x %08x %08x %08x %08x",
1355 ar_nr_resp
[0].cuid
, //UID
1356 ar_nr_resp
[0].nonce
, //NT
1357 ar_nr_resp
[0].nonce2
,//NT_ENC
1358 ar_nr_resp
[0].nr
, //NR1
1359 ar_nr_resp
[0].ar
//AR1
1365 if ((flags
& FLAG_NR_AR_ATTACK
) == FLAG_NR_AR_ATTACK
) {
1366 for (uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
1367 if ((nonce_state
)ar_nr_resp
[i
].state
== SECOND
) {
1369 if (g_dbglevel
>= DBG_INFO
) {
1370 Dbprintf("Collected two pairs of AR/NR which can be used to extract sector %d " _YELLOW_("%s")
1371 , ar_nr_resp
[i
].sector
1372 , (ar_nr_resp
[i
].keytype
== AUTHKEYA
) ? "key A" : "key B"
1374 Dbprintf("../tools/mfc/card_reader/mfkey32v2 %08x %08x %08x %08x %08x %08x %08x",
1375 ar_nr_resp
[i
].cuid
, //UID
1376 ar_nr_resp
[i
].nonce
, //NT
1377 ar_nr_resp
[i
].nr
, //NR1
1378 ar_nr_resp
[i
].ar
, //AR1
1379 ar_nr_resp
[i
].nonce2
,//NT2
1380 ar_nr_resp
[i
].nr2
, //NR2
1381 ar_nr_resp
[i
].ar2
//AR2
1388 if (g_dbglevel
>= DBG_ERROR
) {
1389 Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", get_tracing(), BigBuf_get_traceLen());
1392 if ((flags
& FLAG_INTERACTIVE
) == FLAG_INTERACTIVE
) { // Interactive mode flag, means we need to send ACK
1393 //Send the collected ar_nr in the response
1394 reply_ng(CMD_HF_MIFARE_SIMULATE
, button_pushed
? PM3_EOPABORTED
: PM3_SUCCESS
, (uint8_t *)&ar_nr_resp
[index
], sizeof(nonces_t
));
1397 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1400 BigBuf_free_keep_EM();