1 //-----------------------------------------------------------------------------
2 // Merlok - June 2011, 2012
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
6 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
7 // at your option, any later version. See the LICENSE.txt file for the text of
9 //-----------------------------------------------------------------------------
10 // Mifare Classic Card Simulation
11 //-----------------------------------------------------------------------------
13 #include "mifaresim.h"
14 #include "iso14443a.h"
15 #include "iso14443crc.h"
16 #include "crapto1/crapto1.h"
19 #include "mifareutil.h"
20 #include "fpgaloader.h"
21 #include "proxmark3.h"
24 #include "protocols.h"
27 //mifare emulator states
28 #define MFEMUL_NOFIELD 0
30 #define MFEMUL_SELECT1 2
31 #define MFEMUL_SELECT2 3
32 #define MFEMUL_SELECT3 4
33 #define MFEMUL_AUTH1 5
34 #define MFEMUL_AUTH2 6
36 #define MFEMUL_WRITEBL2 8
37 #define MFEMUL_INTREG_INC 9
38 #define MFEMUL_INTREG_DEC 10
39 #define MFEMUL_INTREG_REST 11
40 #define MFEMUL_HALTED 12
42 #define cardSTATE_TO_IDLE() { cardSTATE = MFEMUL_IDLE; LED_B_OFF(); LED_C_OFF(); }
44 #define AC_DATA_READ 0
45 #define AC_DATA_WRITE 1
47 #define AC_DATA_DEC_TRANS_REST 3
48 #define AC_KEYA_READ 0
49 #define AC_KEYA_WRITE 1
50 #define AC_KEYB_READ 2
51 #define AC_KEYB_WRITE 3
57 #define AUTHKEYNONE 0xff
60 static bool IsTrailerAccessAllowed(uint8_t blockNo
, uint8_t keytype
, uint8_t action
) {
61 uint8_t sector_trailer
[16];
62 emlGetMem(sector_trailer
, blockNo
, 1);
63 uint8_t AC
= ((sector_trailer
[7] >> 5) & 0x04)
64 | ((sector_trailer
[8] >> 2) & 0x02)
65 | ((sector_trailer
[8] >> 7) & 0x01);
72 return ((keytype
== AUTHKEYA
&& (AC
== 0x00 || AC
== 0x01))
73 || (keytype
== AUTHKEYB
&& (AC
== 0x04 || AC
== 0x03)));
77 return (keytype
== AUTHKEYA
&& (AC
== 0x00 || AC
== 0x02 || AC
== 0x01));
81 return ((keytype
== AUTHKEYA
&& (AC
== 0x00 || AC
== 0x04))
82 || (keytype
== AUTHKEYB
&& (AC
== 0x04 || AC
== 0x03)));
86 return ((keytype
== AUTHKEYA
)
87 || (keytype
== AUTHKEYB
&& !(AC
== 0x00 || AC
== 0x02 || AC
== 0x01)));
91 return ((keytype
== AUTHKEYA
&& (AC
== 0x01))
92 || (keytype
== AUTHKEYB
&& (AC
== 0x03 || AC
== 0x05)));
95 default: return false;
100 static bool IsDataAccessAllowed(uint8_t blockNo
, uint8_t keytype
, uint8_t action
)
102 uint8_t sector_trailer
[16];
103 emlGetMem(sector_trailer
, SectorTrailer(blockNo
), 1);
105 uint8_t sector_block
;
106 if (blockNo
< 32*4) {
107 sector_block
= blockNo
& 0x03;
109 sector_block
= (blockNo
& 0x0f) / 5;
113 switch (sector_block
) {
115 AC
= ((sector_trailer
[7] >> 2) & 0x04)
116 | ((sector_trailer
[8] << 1) & 0x02)
117 | ((sector_trailer
[8] >> 4) & 0x01);
121 AC
= ((sector_trailer
[7] >> 3) & 0x04)
122 | ((sector_trailer
[8] >> 0) & 0x02)
123 | ((sector_trailer
[8] >> 5) & 0x01);
127 AC
= ((sector_trailer
[7] >> 4) & 0x04)
128 | ((sector_trailer
[8] >> 1) & 0x02)
129 | ((sector_trailer
[8] >> 6) & 0x01);
138 return ((keytype
== AUTHKEYA
&& !(AC
== 0x03 || AC
== 0x05 || AC
== 0x07))
139 || (keytype
== AUTHKEYB
&& !(AC
== 0x07)));
142 case AC_DATA_WRITE
: {
143 return ((keytype
== AUTHKEYA
&& (AC
== 0x00))
144 || (keytype
== AUTHKEYB
&& (AC
== 0x00 || AC
== 0x04 || AC
== 0x06 || AC
== 0x03)));
148 return ((keytype
== AUTHKEYA
&& (AC
== 0x00))
149 || (keytype
== AUTHKEYB
&& (AC
== 0x00 || AC
== 0x06)));
152 case AC_DATA_DEC_TRANS_REST
: {
153 return ((keytype
== AUTHKEYA
&& (AC
== 0x00 || AC
== 0x06 || AC
== 0x01))
154 || (keytype
== AUTHKEYB
&& (AC
== 0x00 || AC
== 0x06 || AC
== 0x01)));
163 static bool IsAccessAllowed(uint8_t blockNo
, uint8_t keytype
, uint8_t action
) {
164 if (IsSectorTrailer(blockNo
)) {
165 return IsTrailerAccessAllowed(blockNo
, keytype
, action
);
167 return IsDataAccessAllowed(blockNo
, keytype
, action
);
172 static void MifareSimInit(uint8_t flags
, uint8_t *datain
, tag_response_info_t
**responses
, uint32_t *cuid
, uint8_t *uid_len
) {
174 #define TAG_RESPONSE_COUNT 5 // number of precompiled responses
175 static uint8_t rATQA
[] = {0x04, 0x00}; // indicate Mifare classic 1k 4Byte UID
176 static uint8_t rUIDBCC1
[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level
177 static uint8_t rUIDBCC2
[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 2nd cascade level
178 static uint8_t rSAKfinal
[]= {0x08, 0xb6, 0xdd}; // mifare 1k indicated
179 static uint8_t rSAK1
[] = {0x04, 0xda, 0x17}; // indicate UID not finished
182 // UID can be set from emulator memory or incoming data and can be 4 or 7 bytes long
183 if (flags
& FLAG_4B_UID_IN_DATA
) { // get UID from datain
184 memcpy(rUIDBCC1
, datain
, 4);
185 } else if (flags
& FLAG_7B_UID_IN_DATA
) {
187 memcpy(rUIDBCC1
+1, datain
, 3);
188 memcpy(rUIDBCC2
, datain
+3, 4);
191 uint8_t probable_atqa
;
192 emlGetMemBt(&probable_atqa
, 7, 1); // get UID from emul memory - weak guess at length
193 if (probable_atqa
== 0x00) { // ---------- 4BUID
194 emlGetMemBt(rUIDBCC1
, 0, 4);
195 } else { // ---------- 7BUID
197 emlGetMemBt(rUIDBCC1
+1, 0, 3);
198 emlGetMemBt(rUIDBCC2
, 3, 4);
205 *cuid
= bytes_to_num(rUIDBCC1
, 4);
206 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
207 if (MF_DBGLEVEL
>= 2) {
208 Dbprintf("4B UID: %02x%02x%02x%02x",
209 rUIDBCC1
[0], rUIDBCC1
[1], rUIDBCC1
[2], rUIDBCC1
[3] );
214 *cuid
= bytes_to_num(rUIDBCC2
, 4);
215 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
216 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
217 if (MF_DBGLEVEL
>= 2) {
218 Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x",
219 rUIDBCC1
[1], rUIDBCC1
[2], rUIDBCC1
[3], rUIDBCC2
[0], rUIDBCC2
[1], rUIDBCC2
[2], rUIDBCC2
[3] );
226 static tag_response_info_t responses_init
[TAG_RESPONSE_COUNT
] = {
227 { .response
= rATQA
, .response_n
= sizeof(rATQA
) }, // Answer to request - respond with card type
228 { .response
= rUIDBCC1
, .response_n
= sizeof(rUIDBCC1
) }, // Anticollision cascade1 - respond with first part of uid
229 { .response
= rUIDBCC2
, .response_n
= sizeof(rUIDBCC2
) }, // Anticollision cascade2 - respond with 2nd part of uid
230 { .response
= rSAKfinal
, .response_n
= sizeof(rSAKfinal
) }, // Acknowledge select - last cascade
231 { .response
= rSAK1
, .response_n
= sizeof(rSAK1
) } // Acknowledge select - previous cascades
234 // Prepare ("precompile") the responses of the anticollision phase. There will be not enough time to do this at the moment the reader sends its REQA or SELECT
235 // There are 7 predefined responses with a total of 18 bytes data to transmit. Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
236 // 18 * 8 data bits, 18 * 1 parity bits, 5 start bits, 5 stop bits, 5 correction bits -> need 177 bytes buffer
237 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 177 // number of bytes required for precompiled responses
239 uint8_t *free_buffer_pointer
= BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE
);
240 size_t free_buffer_size
= ALLOCATED_TAG_MODULATION_BUFFER_SIZE
;
241 for (size_t i
= 0; i
< TAG_RESPONSE_COUNT
; i
++) {
242 prepare_allocated_tag_modulation(&responses_init
[i
], &free_buffer_pointer
, &free_buffer_size
);
245 *responses
= responses_init
;
247 // indices into responses array:
257 static bool HasValidCRC(uint8_t *receivedCmd
, uint16_t receivedCmd_len
) {
258 uint8_t CRC_byte_1
, CRC_byte_2
;
259 ComputeCrc14443(CRC_14443_A
, receivedCmd
, receivedCmd_len
-2, &CRC_byte_1
, &CRC_byte_2
);
260 return (receivedCmd
[receivedCmd_len
-2] == CRC_byte_1
&& receivedCmd
[receivedCmd_len
-1] == CRC_byte_2
);
268 * FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
269 * FLAG_4B_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that
270 * FLAG_7B_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that
271 * FLAG_10B_UID_IN_DATA - use 10-byte UID in the data-section not finished
272 * FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later
273 * FLAG_RANDOM_NONCE - means we should generate some pseudo-random nonce data (only allows moebius attack)
274 *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ...
275 * (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attmpted)
277 void Mifare1ksim(uint8_t flags
, uint8_t exitAfterNReads
, uint8_t arg2
, uint8_t *datain
)
279 tag_response_info_t
*responses
;
282 uint8_t cardWRBL
= 0;
283 uint8_t cardAUTHSC
= 0;
284 uint8_t cardAUTHKEY
= AUTHKEYNONE
; // no authentication
286 //uint32_t rn_enc = 0;
288 uint32_t cardINTREG
= 0;
289 uint8_t cardINTBLOCK
= 0;
290 struct Crypto1State mpcs
= {0, 0};
291 struct Crypto1State
*pcs
;
293 uint32_t numReads
= 0;//Counts numer of times reader reads a block
294 uint8_t receivedCmd
[MAX_MIFARE_FRAME_SIZE
];
295 uint8_t receivedCmd_dec
[MAX_MIFARE_FRAME_SIZE
];
296 uint8_t receivedCmd_par
[MAX_MIFARE_PARITY_SIZE
];
297 uint16_t receivedCmd_len
;
298 uint8_t response
[MAX_MIFARE_FRAME_SIZE
];
299 uint8_t response_par
[MAX_MIFARE_PARITY_SIZE
];
301 uint8_t rAUTH_NT
[] = {0x01, 0x02, 0x03, 0x04};
302 uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
304 //Here, we collect UID,sector,keytype,NT,AR,NR,NT2,AR2,NR2
305 // This will be used in the reader-only attack.
307 //allow collecting up to 7 sets of nonces to allow recovery of up to 7 keys
308 #define ATTACK_KEY_COUNT 7 // keep same as define in cmdhfmf.c -> readerAttack() (Cannot be more than 7)
309 nonces_t ar_nr_resp
[ATTACK_KEY_COUNT
*2]; //*2 for 2 separate attack types (nml, moebius) 36 * 7 * 2 bytes = 504 bytes
310 memset(ar_nr_resp
, 0x00, sizeof(ar_nr_resp
));
312 uint8_t ar_nr_collected
[ATTACK_KEY_COUNT
*2]; //*2 for 2nd attack type (moebius)
313 memset(ar_nr_collected
, 0x00, sizeof(ar_nr_collected
));
314 uint8_t nonce1_count
= 0;
315 uint8_t nonce2_count
= 0;
316 uint8_t moebius_n_count
= 0;
317 bool gettingMoebius
= false;
318 uint8_t mM
= 0; //moebius_modifier for collection storage
320 // Authenticate response - nonce
322 if (flags
& FLAG_RANDOM_NONCE
) {
325 nonce
= bytes_to_num(rAUTH_NT
, 4);
328 // free eventually allocated BigBuf memory but keep Emulator Memory
329 BigBuf_free_keep_EM();
331 MifareSimInit(flags
, datain
, &responses
, &cuid
, &uid_len
);
333 // We need to listen to the high-frequency, peak-detected path.
334 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
341 bool finished
= false;
342 bool button_pushed
= BUTTON_PRESS();
343 int cardSTATE
= MFEMUL_NOFIELD
;
345 while (!button_pushed
&& !finished
&& !usb_poll_validate_length()) {
349 if (cardSTATE
== MFEMUL_NOFIELD
) {
350 int vHf
= (MAX_ADC_HF_VOLTAGE
* AvgAdc(ADC_CHAN_HF
)) >> 10;
351 if (vHf
> MF_MINFIELDV
) {
355 button_pushed
= BUTTON_PRESS();
360 int res
= EmGetCmd(receivedCmd
, &receivedCmd_len
, receivedCmd_par
);
362 if (res
== 2) { //Field is off!
364 cardSTATE
= MFEMUL_NOFIELD
;
366 } else if (res
== 1) { // button pressed
367 button_pushed
= true;
371 // WUPA in HALTED state or REQA or WUPA in any other state
372 if (receivedCmd_len
== 1 && ((receivedCmd
[0] == ISO14443A_CMD_REQA
&& cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == ISO14443A_CMD_WUPA
)) {
373 EmSendPrecompiledCmd(&responses
[ATQA
]);
376 crypto1_destroy(pcs
);
377 cardAUTHKEY
= AUTHKEYNONE
;
378 if (flags
& FLAG_RANDOM_NONCE
) {
383 cardSTATE
= MFEMUL_SELECT1
;
393 case MFEMUL_SELECT1
:{
394 // select all - 0x93 0x20
395 if (receivedCmd_len
== 2 && (receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& receivedCmd
[1] == 0x20)) {
396 if (MF_DBGLEVEL
>= 4) Dbprintf("SELECT ALL CL1 received");
397 EmSendPrecompiledCmd(&responses
[UIDBCC1
]);
400 // select card - 0x93 0x70 ...
401 if (receivedCmd_len
== 9 &&
402 (receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], responses
[UIDBCC1
].response
, 4) == 0)) {
403 if (MF_DBGLEVEL
>= 4) Dbprintf("SELECT CL1 %02x%02x%02x%02x received",receivedCmd
[2],receivedCmd
[3],receivedCmd
[4],receivedCmd
[5]);
405 EmSendPrecompiledCmd(&responses
[SAKfinal
]);
407 cardSTATE
= MFEMUL_WORK
;
409 } else if (uid_len
== 7) {
410 EmSendPrecompiledCmd(&responses
[SAK1
]);
411 cardSTATE
= MFEMUL_SELECT2
;
418 case MFEMUL_SELECT2
:{
419 // select all cl2 - 0x95 0x20
420 if (receivedCmd_len
== 2 && (receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& receivedCmd
[1] == 0x20)) {
421 if (MF_DBGLEVEL
>= 4) Dbprintf("SELECT ALL CL2 received");
422 EmSendPrecompiledCmd(&responses
[UIDBCC2
]);
425 // select cl2 card - 0x95 0x70 xxxxxxxxxxxx
426 if (receivedCmd_len
== 9 &&
427 (receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], responses
[UIDBCC2
].response
, 4) == 0)) {
429 if (MF_DBGLEVEL
>= 4) Dbprintf("SELECT CL2 %02x%02x%02x%02x received",receivedCmd
[2],receivedCmd
[3],receivedCmd
[4],receivedCmd
[5]);
430 EmSendPrecompiledCmd(&responses
[SAKfinal
]);
432 cardSTATE
= MFEMUL_WORK
;
440 if (receivedCmd_len
!= 4) { // all commands must have exactly 4 bytes
443 bool encrypted_data
= (cardAUTHKEY
!= AUTHKEYNONE
) ;
444 if (encrypted_data
) {
446 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, receivedCmd_dec
);
448 memcpy(receivedCmd_dec
, receivedCmd
, receivedCmd_len
);
450 if (!HasValidCRC(receivedCmd_dec
, receivedCmd_len
)) { // all commands must have a valid CRC
451 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
454 if (receivedCmd_dec
[0] == MIFARE_AUTH_KEYA
|| receivedCmd_dec
[0] == MIFARE_AUTH_KEYB
) {
455 // if authenticating to a block that shouldn't exist - as long as we are not doing the reader attack
456 if (receivedCmd_dec
[1] >= 16 * 4 && !(flags
& FLAG_NR_AR_ATTACK
)) {
457 //is this the correct response to an auth on a out of range block? marshmellow
458 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
459 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking",receivedCmd_dec
[0],receivedCmd_dec
[1],receivedCmd_dec
[1]);
462 cardAUTHSC
= receivedCmd_dec
[1] / 4; // received block num
463 cardAUTHKEY
= receivedCmd_dec
[0] & 0x01;
464 crypto1_destroy(pcs
);//Added by martin
465 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
466 if (!encrypted_data
) { // first authentication
467 if (MF_DBGLEVEL
>= 4) Dbprintf("Reader authenticating for block %d (0x%02x) with key %d",receivedCmd_dec
[1], receivedCmd_dec
[1], cardAUTHKEY
);
468 crypto1_word(pcs
, cuid
^ nonce
, 0);//Update crypto state
469 num_to_bytes(nonce
, 4, rAUTH_AT
); // Send nonce
470 } else { // nested authentication
471 if (MF_DBGLEVEL
>= 4) Dbprintf("Reader doing nested authentication for block %d (0x%02x) with key %d", receivedCmd_dec
[1], receivedCmd_dec
[1], cardAUTHKEY
);
472 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
473 num_to_bytes(ans
, 4, rAUTH_AT
);
475 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
476 cardSTATE
= MFEMUL_AUTH1
;
479 if (!encrypted_data
) { // all other commands must be encrypted (authenticated)
482 if(receivedCmd_dec
[0] == ISO14443A_CMD_READBLOCK
483 || receivedCmd_dec
[0] == ISO14443A_CMD_WRITEBLOCK
484 || receivedCmd_dec
[0] == MIFARE_CMD_INC
485 || receivedCmd_dec
[0] == MIFARE_CMD_DEC
486 || receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
487 || receivedCmd_dec
[0] == MIFARE_CMD_TRANSFER
) {
488 if (receivedCmd_dec
[1] >= 16 * 4) {
489 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
490 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking",receivedCmd_dec
[0],receivedCmd_dec
[1],receivedCmd_dec
[1]);
493 if (receivedCmd_dec
[1] / 4 != cardAUTHSC
) {
494 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
495 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader tried to operate (0x%02x) on block (0x%02x) not authenticated for (0x%02x), nacking",receivedCmd_dec
[0],receivedCmd_dec
[1],cardAUTHSC
);
499 if (receivedCmd_dec
[0] == ISO14443A_CMD_READBLOCK
) {
500 uint8_t blockNo
= receivedCmd_dec
[1];
501 if (MF_DBGLEVEL
>= 4) {
502 Dbprintf("Reader reading block %d (0x%02x)", blockNo
, blockNo
);
504 emlGetMem(response
, blockNo
, 1);
505 if (IsSectorTrailer(blockNo
)) {
506 memset(response
, 0x00, 6); // keyA can never be read
507 if (!IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_KEYB_READ
)) {
508 memset(response
+10, 0x00, 6); // keyB cannot be read
510 if (!IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_AC_READ
)) {
511 memset(response
+6, 0x00, 4); // AC bits cannot be read
514 if (!IsAccessAllowed(blockNo
, cardAUTHKEY
, AC_DATA_READ
)) {
515 memset(response
, 0x00, 16); // datablock cannot be read
518 AppendCrc14443a(response
, 16);
519 mf_crypto1_encrypt(pcs
, response
, 18, response_par
);
520 EmSendCmdPar(response
, 18, response_par
);
522 if(exitAfterNReads
> 0 && numReads
== exitAfterNReads
) {
523 Dbprintf("%d reads done, exiting", numReads
);
528 if (receivedCmd_dec
[0] == ISO14443A_CMD_WRITEBLOCK
) {
529 uint8_t blockNo
= receivedCmd_dec
[1];
530 if (MF_DBGLEVEL
>= 4) Dbprintf("RECV 0xA0 write block %d (%02x)", blockNo
, blockNo
);
531 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
533 cardSTATE
= MFEMUL_WRITEBL2
;
536 if (receivedCmd_dec
[0] == MIFARE_CMD_INC
|| receivedCmd_dec
[0] == MIFARE_CMD_DEC
|| receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
) {
537 uint8_t blockNo
= receivedCmd_dec
[1];
538 if (MF_DBGLEVEL
>= 4) Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)",receivedCmd_dec
[0], blockNo
, blockNo
);
539 if (emlCheckValBl(blockNo
)) {
540 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader tried to operate on block, but emlCheckValBl failed, nacking");
541 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
544 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
546 if (receivedCmd_dec
[0] == MIFARE_CMD_INC
)
547 cardSTATE
= MFEMUL_INTREG_INC
;
548 if (receivedCmd_dec
[0] == MIFARE_CMD_DEC
)
549 cardSTATE
= MFEMUL_INTREG_DEC
;
550 if (receivedCmd_dec
[0] == MIFARE_CMD_RESTORE
)
551 cardSTATE
= MFEMUL_INTREG_REST
;
554 if (receivedCmd_dec
[0] == MIFARE_CMD_TRANSFER
) {
555 uint8_t blockNo
= receivedCmd_dec
[1];
556 if (MF_DBGLEVEL
>= 4) Dbprintf("RECV 0x%02x transfer block %d (%02x)",receivedCmd_dec
[0], blockNo
, blockNo
);
557 if (emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd_dec
[1]))
558 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
560 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
564 if (receivedCmd_dec
[0] == ISO14443A_CMD_HALT
&& receivedCmd_dec
[1] == 0x00) {
565 if (MF_DBGLEVEL
>= 4) Dbprintf("--> HALTED.");
568 cardSTATE
= MFEMUL_HALTED
;
571 // command not allowed
572 if (MF_DBGLEVEL
>= 4) Dbprintf("Received command not allowed, nacking");
573 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
577 if (receivedCmd_len
!= 8) {
582 uint32_t nr
= bytes_to_num(receivedCmd
, 4);
583 uint32_t ar
= bytes_to_num(&receivedCmd
[4], 4);
585 // Collect AR/NR per keytype & sector
586 if(flags
& FLAG_NR_AR_ATTACK
) {
587 for (uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
588 if ( ar_nr_collected
[i
+mM
]==0 || ((cardAUTHSC
== ar_nr_resp
[i
+mM
].sector
) && (cardAUTHKEY
== ar_nr_resp
[i
+mM
].keytype
) && (ar_nr_collected
[i
+mM
] > 0)) ) {
589 // if first auth for sector, or matches sector and keytype of previous auth
590 if (ar_nr_collected
[i
+mM
] < 2) {
591 // if we haven't already collected 2 nonces for this sector
592 if (ar_nr_resp
[ar_nr_collected
[i
+mM
]].ar
!= ar
) {
593 // Avoid duplicates... probably not necessary, ar should vary.
594 if (ar_nr_collected
[i
+mM
]==0) {
595 // first nonce collect
596 ar_nr_resp
[i
+mM
].cuid
= cuid
;
597 ar_nr_resp
[i
+mM
].sector
= cardAUTHSC
;
598 ar_nr_resp
[i
+mM
].keytype
= cardAUTHKEY
;
599 ar_nr_resp
[i
+mM
].nonce
= nonce
;
600 ar_nr_resp
[i
+mM
].nr
= nr
;
601 ar_nr_resp
[i
+mM
].ar
= ar
;
603 // add this nonce to first moebius nonce
604 ar_nr_resp
[i
+ATTACK_KEY_COUNT
].cuid
= cuid
;
605 ar_nr_resp
[i
+ATTACK_KEY_COUNT
].sector
= cardAUTHSC
;
606 ar_nr_resp
[i
+ATTACK_KEY_COUNT
].keytype
= cardAUTHKEY
;
607 ar_nr_resp
[i
+ATTACK_KEY_COUNT
].nonce
= nonce
;
608 ar_nr_resp
[i
+ATTACK_KEY_COUNT
].nr
= nr
;
609 ar_nr_resp
[i
+ATTACK_KEY_COUNT
].ar
= ar
;
610 ar_nr_collected
[i
+ATTACK_KEY_COUNT
]++;
611 } else { // second nonce collect (std and moebius)
612 ar_nr_resp
[i
+mM
].nonce2
= nonce
;
613 ar_nr_resp
[i
+mM
].nr2
= nr
;
614 ar_nr_resp
[i
+mM
].ar2
= ar
;
615 if (!gettingMoebius
) {
617 // check if this was the last second nonce we need for std attack
618 if ( nonce2_count
== nonce1_count
) {
619 // done collecting std test switch to moebius
620 // first finish incrementing last sample
621 ar_nr_collected
[i
+mM
]++;
622 // switch to moebius collection
623 gettingMoebius
= true;
624 mM
= ATTACK_KEY_COUNT
;
625 if (flags
& FLAG_RANDOM_NONCE
) {
634 // if we've collected all the nonces we need - finish.
635 if (nonce1_count
== moebius_n_count
) finished
= true;
638 ar_nr_collected
[i
+mM
]++;
641 // we found right spot for this nonce stop looking
648 crypto1_word(pcs
, nr
, 1);
649 cardRr
= ar
^ crypto1_word(pcs
, 0, 0);
652 if (cardRr
!= prng_successor(nonce
, 64)){
653 if (MF_DBGLEVEL
>= 2) Dbprintf("AUTH FAILED for sector %d with key %c. cardRr=%08x, succ=%08x",
654 cardAUTHSC
, cardAUTHKEY
== AUTHKEYA
? 'A' : 'B',
655 cardRr
, prng_successor(nonce
, 64));
656 // Shouldn't we respond anything here?
657 // Right now, we don't nack or anything, which causes the
658 // reader to do a WUPA after a while. /Martin
659 // -- which is the correct response. /piwi
660 cardAUTHKEY
= AUTHKEYNONE
; // not authenticated
664 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
665 num_to_bytes(ans
, 4, rAUTH_AT
);
666 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
667 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH COMPLETED for sector %d with key %c.", cardAUTHSC
, cardAUTHKEY
== AUTHKEYA
? 'A' : 'B');
669 cardSTATE
= MFEMUL_WORK
;
672 case MFEMUL_WRITEBL2
:{
673 if (receivedCmd_len
== 18) {
674 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, receivedCmd_dec
);
675 if (HasValidCRC(receivedCmd_dec
, receivedCmd_len
)) {
676 if (IsSectorTrailer(cardWRBL
)) {
677 emlGetMem(response
, cardWRBL
, 1);
678 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_KEYA_WRITE
)) {
679 memcpy(receivedCmd_dec
, response
, 6); // don't change KeyA
681 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_KEYB_WRITE
)) {
682 memcpy(receivedCmd_dec
+10, response
+10, 6); // don't change KeyA
684 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_AC_WRITE
)) {
685 memcpy(receivedCmd_dec
+6, response
+6, 4); // don't change AC bits
688 if (!IsAccessAllowed(cardWRBL
, cardAUTHKEY
, AC_DATA_WRITE
)) {
689 memcpy(receivedCmd_dec
, response
, 16); // don't change anything
692 emlSetMem(receivedCmd_dec
, cardWRBL
, 1);
693 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
)); // always ACK?
694 cardSTATE
= MFEMUL_WORK
;
701 case MFEMUL_INTREG_INC
:{
702 if (receivedCmd_len
== 6) {
703 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t*)&ans
);
704 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
705 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
709 cardINTREG
= cardINTREG
+ ans
;
711 cardSTATE
= MFEMUL_WORK
;
714 case MFEMUL_INTREG_DEC
:{
715 if (receivedCmd_len
== 6) {
716 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t*)&ans
);
717 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
718 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
723 cardINTREG
= cardINTREG
- ans
;
724 cardSTATE
= MFEMUL_WORK
;
727 case MFEMUL_INTREG_REST
:{
728 mf_crypto1_decryptEx(pcs
, receivedCmd
, receivedCmd_len
, (uint8_t*)&ans
);
729 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
730 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
734 cardSTATE
= MFEMUL_WORK
;
738 button_pushed
= BUTTON_PRESS();
741 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
744 if(flags
& FLAG_NR_AR_ATTACK
&& MF_DBGLEVEL
>= 1) {
745 for ( uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
746 if (ar_nr_collected
[i
] == 2) {
747 Dbprintf("Collected two pairs of AR/NR which can be used to extract %s from reader for sector %d:", (i
<ATTACK_KEY_COUNT
/2) ? "keyA" : "keyB", ar_nr_resp
[i
].sector
);
748 Dbprintf("../tools/mfkey/mfkey32 %08x %08x %08x %08x %08x %08x",
749 ar_nr_resp
[i
].cuid
, //UID
750 ar_nr_resp
[i
].nonce
, //NT
751 ar_nr_resp
[i
].nr
, //NR1
752 ar_nr_resp
[i
].ar
, //AR1
753 ar_nr_resp
[i
].nr2
, //NR2
754 ar_nr_resp
[i
].ar2
//AR2
758 for ( uint8_t i
= ATTACK_KEY_COUNT
; i
< ATTACK_KEY_COUNT
*2; i
++) {
759 if (ar_nr_collected
[i
] == 2) {
760 Dbprintf("Collected two pairs of AR/NR which can be used to extract %s from reader for sector %d:", (i
<ATTACK_KEY_COUNT
/2) ? "keyA" : "keyB", ar_nr_resp
[i
].sector
);
761 Dbprintf("../tools/mfkey/mfkey32v2 %08x %08x %08x %08x %08x %08x %08x",
762 ar_nr_resp
[i
].cuid
, //UID
763 ar_nr_resp
[i
].nonce
, //NT
764 ar_nr_resp
[i
].nr
, //NR1
765 ar_nr_resp
[i
].ar
, //AR1
766 ar_nr_resp
[i
].nonce2
,//NT2
767 ar_nr_resp
[i
].nr2
, //NR2
768 ar_nr_resp
[i
].ar2
//AR2
773 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", get_tracing(), BigBuf_get_traceLen());
775 if(flags
& FLAG_INTERACTIVE
) { // Interactive mode flag, means we need to send ACK
776 //Send the collected ar_nr in the response
777 cmd_send(CMD_ACK
,CMD_SIMULATE_MIFARE_CARD
,button_pushed
,0,&ar_nr_resp
,sizeof(ar_nr_resp
));