viewing a MFC ev1 now prints the two special sectors
[RRG-proxmark3.git] / armsrc / mifarecmd.c
blob46c0320112429cf40f313014a7bed8a6ddb410b7
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Gerhard de Koning Gans - May 2008
3 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // See LICENSE.txt for the text of the license.
16 //-----------------------------------------------------------------------------
18 #include "mifarecmd.h"
20 #include "pmflash.h"
21 #include "proxmark3_arm.h"
22 #include "string.h"
23 #include "mifareutil.h"
24 #include "protocols.h"
25 #include "parity.h"
26 #include "BigBuf.h"
27 #include "cmd.h"
28 #include "flashmem.h"
29 #include "fpgaloader.h"
30 #include "iso14443a.h"
31 #include "mifaredesfire.h"
32 #include "util.h"
33 #include "commonutil.h"
34 #include "crc16.h"
35 #include "dbprint.h"
36 #include "ticks.h"
37 #include "usb_cdc.h" // usb_poll_validate_length
38 #include "spiffs.h" // spiffs
39 #include "appmain.h" // print_stack_usage
41 #ifndef HARDNESTED_AUTHENTICATION_TIMEOUT
42 # define HARDNESTED_AUTHENTICATION_TIMEOUT 848 // card times out 1ms after wrong authentication (according to NXP documentation)
43 #endif
44 #ifndef HARDNESTED_PRE_AUTHENTICATION_LEADTIME
45 # define HARDNESTED_PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication
46 #endif
48 // send an incomplete dummy response in order to trigger the card's authentication failure timeout
49 #ifndef CHK_TIMEOUT
50 # define CHK_TIMEOUT(void) { \
51 ReaderTransmit(&dummy_answer, 1, NULL); \
52 uint32_t timeout = GetCountSspClk() + HARDNESTED_AUTHENTICATION_TIMEOUT; \
53 while (GetCountSspClk() < timeout) {}; \
55 #endif
57 static uint8_t dummy_answer = 0;
59 // magic uid card generation 1 commands
60 static uint8_t wupC1[] = { MIFARE_MAGICWUPC1 };
61 static uint8_t wupC2[] = { MIFARE_MAGICWUPC2 };
62 static uint8_t wipeC[] = { MIFARE_MAGICWIPEC };
63 // GDM alt magic wakeup
64 static uint8_t wupGDM1[] = { MIFARE_MAGIC_GDM_WUPC1 };
65 static uint8_t wupGDM2[] = { MIFARE_MAGIC_GDM_WUPC2 };
67 static bool mifare_wakeup_auth(struct Crypto1State *pcs, MifareWakeupType wakeup, uint8_t key_auth_cmd, uint8_t *key, uint8_t block_no) {
68 uint32_t cuid = 0;
69 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
70 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
72 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
74 clear_trace();
75 set_tracing(true);
77 LED_A_ON();
78 LED_B_OFF();
79 LED_C_OFF();
81 switch (wakeup) {
82 case MF_WAKE_NONE:
83 break;
84 case MF_WAKE_WUPA:
85 if (!iso14443a_select_cardEx(NULL, NULL, &cuid, true, 0, true, &WUPA_POLLING_PARAMETERS)) {
86 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
87 return false;
89 break;
90 case MF_WAKE_REQA:
91 if (!iso14443a_select_cardEx(NULL, NULL, &cuid, true, 0, true, &REQA_POLLING_PARAMETERS)) {
92 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
93 return false;
95 break;
96 case MF_WAKE_GEN1A:
97 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
98 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
99 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupC1 error");
100 return false;
103 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
104 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
105 if (g_dbglevel >= DBG_INFO) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
107 break;
108 case MF_WAKE_GEN1B:
109 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
110 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
111 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupC1 error");
112 return false;
114 break;
115 case MF_WAKE_GDM_ALT:
116 ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL);
117 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
118 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM1 error");
119 return false;
121 ReaderTransmit(wupGDM2, sizeof(wupGDM2), NULL);
122 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
123 if (g_dbglevel >= DBG_INFO) Dbprintf("wupGDM2 error");
124 // maybe this is fine on some tags?
126 break;
129 if (key_auth_cmd != 0) {
130 uint64_t ui64key = bytes_to_num(key, 6);
131 if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, NULL, NULL, NULL, NULL, false, false)) {
132 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
133 return false;
137 return true;
140 //-----------------------------------------------------------------------------
141 // Select, Authenticate, Read a MIFARE tag.
142 // wakeup determines the type of wakeup
143 // key_auth_cmd is usually one of MIFARE_AUTH_KEYA, MIFARE_AUTH_KEYB, MIFARE_MAGIC_GDM_AUTH_KEY or 0 to disable auth
144 // read_cmd is usually one of ISO14443A_CMD_READBLOCK, MIFARE_MAGIC_GDM_READBLOCK, or MIFARE_MAGIC_GDM_READ_CFG
145 // block_data must be 16*count bytes large
146 // block_no through block_no+count-1 normally needs to be within the same sector
147 //-----------------------------------------------------------------------------
148 int16_t mifare_cmd_readblocks(MifareWakeupType wakeup, uint8_t key_auth_cmd, uint8_t *key, uint8_t read_cmd, uint8_t block_no, uint8_t count, uint8_t *block_data) {
149 struct Crypto1State mpcs = {0, 0};
150 struct Crypto1State *pcs = (key_auth_cmd == 0) ? NULL : &mpcs;;
152 uint32_t timeout = iso14a_get_timeout();
154 int retval = PM3_SUCCESS;
156 if (mifare_wakeup_auth(pcs, wakeup, key_auth_cmd, key, block_no) == false) {
157 retval = PM3_ESOFT;
158 goto OUT;
161 // frame waiting time (FWT) in 1/fc
162 uint32_t fwt = 256 * 16 * (1 << 7);
163 iso14a_set_timeout(fwt / (8 * 16));
165 for (uint8_t i = 0; i < count; i++) {
166 if (mifare_classic_readblock_ex(pcs, block_no + i, block_data + (i * 16), read_cmd)) {
167 if (g_dbglevel >= DBG_ERROR) Dbprintf("Read block error");
168 retval = PM3_ESOFT;
169 goto OUT;
173 if (mifare_classic_halt(pcs)) {
174 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
175 retval = PM3_ESOFT;
176 goto OUT;
179 OUT:
180 crypto1_deinit(pcs);
182 iso14a_set_timeout(timeout);
183 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
184 LEDsoff();
185 set_tracing(false);
186 BigBuf_free();
187 return retval;
190 //-----------------------------------------------------------------------------
191 // Select, Authenticate, Write a MIFARE tag.
192 // wakeup determines the type of wakeup
193 // key_auth_cmd is usually one of MIFARE_AUTH_KEYA, MIFARE_AUTH_KEYB, MIFARE_MAGIC_GDM_AUTH_KEY or 0 to disable auth
194 // write_cmd is usually one of ISO14443A_CMD_WRITEBLOCK, MIFARE_MAGIC_GDM_WRITEBLOCK, or MIFARE_MAGIC_GDM_WRITE_CFG
195 // block_data must be 16*count bytes large
196 // block_no through block_no+count-1 normally needs to be within the same sector
197 //-----------------------------------------------------------------------------
198 int16_t mifare_cmd_writeblocks(MifareWakeupType wakeup, uint8_t key_auth_cmd, uint8_t *key, uint8_t write_cmd, uint8_t block_no, uint8_t count, uint8_t *block_data) {
199 struct Crypto1State mpcs = {0, 0};
200 struct Crypto1State *pcs = (key_auth_cmd == 0) ? NULL : &mpcs;;
202 int retval = PM3_SUCCESS;
204 if (mifare_wakeup_auth(pcs, wakeup, key_auth_cmd, key, block_no) == false) {
205 retval = PM3_ESOFT;
206 goto OUT;
209 for (uint8_t i = 0; i < count; i++) {
210 int res = mifare_classic_writeblock_ex(pcs, block_no + i, block_data + (i * 16), write_cmd);
211 if (res == PM3_ETEAROFF) {
212 retval = PM3_ETEAROFF;
213 goto OUT;
214 } else if (res != PM3_SUCCESS) {
215 if (g_dbglevel >= DBG_INFO) Dbprintf("Write block error");
216 retval = PM3_ESOFT;
217 goto OUT;
221 if (mifare_classic_halt(pcs)) {
222 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
223 retval = PM3_ESOFT;
224 goto OUT;
227 OUT:
228 crypto1_deinit(pcs);
230 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
231 LEDsoff();
232 set_tracing(false);
233 BigBuf_free();
235 return retval;
238 //-----------------------------------------------------------------------------
239 // Select, Authenticate, Read a MIFARE tag.
240 // read sector (data = 4 x 16 bytes = 64 bytes, or 16 x 16 bytes = 256 bytes)
241 //-----------------------------------------------------------------------------
242 void MifareReadSector(uint8_t sector_no, uint8_t key_type, uint8_t *key) {
243 uint8_t block_no = FirstBlockOfSector(sector_no);
244 uint8_t num_blocks = NumBlocksPerSector(sector_no);
246 uint8_t outbuf[16 * 16];
247 int16_t retval = mifare_cmd_readblocks(MF_WAKE_WUPA, MIFARE_AUTH_KEYA + (key_type & 0xF), key, ISO14443A_CMD_READBLOCK, block_no, num_blocks, outbuf);
249 reply_old(CMD_ACK, retval == PM3_SUCCESS, 0, 0, outbuf, 16 * num_blocks);
252 void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes) {
254 bool turnOffField = (arg0 == 1);
256 LED_A_ON();
257 LED_B_OFF();
258 LED_C_OFF();
260 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
262 clear_trace();
263 set_tracing(true);
265 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
266 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
267 OnError(0);
268 return;
271 if (!mifare_ultra_auth(keybytes)) {
272 if (g_dbglevel >= DBG_ERROR) Dbprintf("Authentication failed");
273 OnError(1);
274 return;
277 if (turnOffField) {
278 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
279 LEDsoff();
281 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
284 void MifareUL_AES_Auth(bool turn_off_field, uint8_t keyno, uint8_t *keybytes) {
286 LED_A_ON();
287 LED_B_OFF();
288 LED_C_OFF();
290 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
292 clear_trace();
293 set_tracing(true);
295 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
296 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
297 reply_ng(CMD_HF_MIFAREULAES_AUTH, PM3_ESOFT, NULL, 0);
298 return;
301 if (!mifare_ultra_aes_auth(keyno, keybytes)) {
302 if (g_dbglevel >= DBG_ERROR) Dbprintf("Authentication failed");
303 reply_ng(CMD_HF_MIFAREULAES_AUTH, PM3_ESOFT, NULL, 0);
304 return;
307 if (turn_off_field) {
308 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
309 LEDsoff();
311 reply_ng(CMD_HF_MIFAREULAES_AUTH, PM3_SUCCESS, NULL, 0);
314 // Arg0 = BlockNo,
315 // Arg1 = UsePwd bool
316 // datain = PWD bytes,
317 void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) {
318 uint8_t blockNo = arg0;
319 uint8_t dataout[16] = {0x00};
320 bool useKey = (arg1 == 1); //UL_C
321 bool usePwd = (arg1 == 2); //UL_EV1/NTAG
323 LEDsoff();
324 LED_A_ON();
325 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
327 clear_trace();
328 set_tracing(true);
330 int len = iso14443a_select_card(NULL, NULL, NULL, true, 0, true);
331 if (!len) {
332 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card (RC:%02X)", len);
333 OnError(1);
334 return;
337 // UL-C authentication
338 if (useKey) {
339 uint8_t key[16] = {0x00};
340 memcpy(key, datain, sizeof(key));
342 if (!mifare_ultra_auth(key)) {
343 OnError(1);
344 return;
348 // UL-EV1 / NTAG authentication
349 if (usePwd) {
350 uint8_t pwd[4] = {0x00};
351 memcpy(pwd, datain, 4);
352 uint8_t pack[4] = {0, 0, 0, 0};
353 if (!mifare_ul_ev1_auth(pwd, pack)) {
354 OnError(1);
355 return;
359 if (mifare_ultra_readblock(blockNo, dataout)) {
360 if (g_dbglevel >= DBG_ERROR) Dbprintf("Read block error");
361 OnError(2);
362 return;
365 if (mifare_ultra_halt()) {
366 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
367 OnError(3);
368 return;
371 reply_mix(CMD_ACK, 1, 0, 0, dataout, 16);
372 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
373 LEDsoff();
376 // arg0 = blockNo (start)
377 // arg1 = Pages (number of blocks)
378 // arg2 = useKey
379 // datain = KEY bytes
380 void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) {
381 LEDsoff();
382 LED_A_ON();
383 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
385 // free eventually allocated BigBuf memory
386 BigBuf_free();
387 BigBuf_Clear_ext(false);
388 clear_trace();
389 set_tracing(true);
391 // params
392 uint8_t blockNo = arg0;
393 uint16_t blocks = arg1;
394 bool useKey = (arg2 == 1); // UL_C
395 bool usePwd = (arg2 == 2); // UL_EV1/NTAG
396 uint32_t countblocks = 0;
397 uint8_t *dataout = BigBuf_malloc(CARD_MEMORY_SIZE);
398 if (dataout == NULL) {
399 Dbprintf("out of memory");
400 OnError(1);
401 return;
404 int len = iso14443a_select_card(NULL, NULL, NULL, true, 0, true);
405 if (!len) {
406 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card (RC:%d)", len);
407 OnError(1);
408 return;
411 // UL-C authentication
412 if (useKey) {
413 uint8_t key[16] = {0x00};
414 memcpy(key, datain, sizeof(key));
416 if (!mifare_ultra_auth(key)) {
417 OnError(1);
418 return;
422 // UL-EV1 / NTAG authentication
423 if (usePwd) {
424 uint8_t pwd[4] = {0x00};
425 memcpy(pwd, datain, sizeof(pwd));
426 uint8_t pack[4] = {0, 0, 0, 0};
428 if (!mifare_ul_ev1_auth(pwd, pack)) {
429 OnError(1);
430 return;
434 for (int i = 0; i < blocks; i++) {
435 if ((i * 4) + 4 >= CARD_MEMORY_SIZE) {
436 Dbprintf("Data exceeds buffer!!");
437 break;
440 len = mifare_ultra_readblock(blockNo + i, dataout + (4 * i));
442 if (len) {
443 if (g_dbglevel >= DBG_ERROR) Dbprintf("Read block %d error", i);
444 // if no blocks read - error out
445 if (i == 0) {
446 OnError(2);
447 return;
448 } else {
449 //stop at last successful read block and return what we got
450 break;
452 } else {
453 countblocks++;
457 len = mifare_ultra_halt();
458 if (len) {
459 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
460 OnError(3);
461 return;
464 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("Blocks read %d", countblocks);
466 countblocks *= 4;
468 reply_mix(CMD_ACK, 1, countblocks, dataout - BigBuf_get_addr(), 0, 0);
469 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
470 LEDsoff();
471 BigBuf_free();
472 set_tracing(false);
475 void MifareValue(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) {
476 // params
477 uint8_t blockNo = arg0;
478 uint8_t keyType = arg1;
479 uint8_t transferKeyType = arg2;
480 uint64_t ui64Key = 0;
481 uint64_t transferUi64Key = 0;
482 uint8_t blockdata[16] = {0x00};
484 ui64Key = bytes_to_num(datain, 6);
485 memcpy(blockdata, datain + 11, 16);
486 transferUi64Key = bytes_to_num(datain + 27, 6);
488 // variables
489 uint8_t action = datain[9];
490 uint8_t transferBlk = datain[10];
491 bool needAuth = datain[33];
492 uint8_t isOK = 0;
493 uint8_t uid[10] = {0x00};
494 uint32_t cuid = 0;
495 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
496 uint8_t len = 0;
497 struct Crypto1State mpcs = {0, 0};
498 struct Crypto1State *pcs;
499 pcs = &mpcs;
501 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
503 clear_trace();
504 set_tracing(true);
506 LED_A_ON();
507 LED_B_OFF();
508 LED_C_OFF();
510 while (true) {
511 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
512 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
513 break;
516 if (mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) {
517 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
518 break;
521 if (mifare_classic_value(pcs, blockNo, blockdata, action) != PM3_SUCCESS) {
522 if (g_dbglevel >= DBG_INFO) Dbprintf("Write block error");
523 break;
526 if (needAuth) {
527 // transfer to other sector
528 if (mifare_classic_auth(pcs, cuid, transferBlk, transferKeyType, transferUi64Key, AUTH_NESTED)) {
529 if (g_dbglevel >= DBG_ERROR) Dbprintf("Nested auth error");
530 break;
534 // send transfer (commit the change)
535 len = mifare_sendcmd_short(pcs, 1, MIFARE_CMD_TRANSFER, (transferBlk != 0) ? transferBlk : blockNo, receivedAnswer, sizeof(receivedAnswer), NULL, NULL);
536 if (len != 1 && receivedAnswer[0] != 0x0A) { // 0x0a - ACK
537 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error in transfer: %02x", receivedAnswer[0]);
538 break;
541 if (mifare_classic_halt(pcs)) {
542 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
543 break;
546 isOK = 1;
547 break;
550 crypto1_deinit(pcs);
552 if (g_dbglevel >= 2) DbpString("WRITE BLOCK FINISHED");
554 reply_mix(CMD_ACK, isOK, 0, 0, 0, 0);
556 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
557 LEDsoff();
558 set_tracing(false);
561 // Arg0 : Block to write to.
562 // Arg1 : 0 = use no authentication.
563 // 1 = use 0x1A authentication.
564 // 2 = use 0x1B authentication.
565 // datain : 4 first bytes is data to be written.
566 // : 4/16 next bytes is authentication key.
567 static void MifareUWriteBlockEx(uint8_t arg0, uint8_t arg1, uint8_t *datain, bool reply) {
568 uint8_t blockNo = arg0;
569 bool useKey = (arg1 == 1); //UL_C
570 bool usePwd = (arg1 == 2); //UL_EV1/NTAG
571 uint8_t blockdata[4] = {0x00};
573 memcpy(blockdata, datain, 4);
575 LEDsoff();
576 LED_A_ON();
577 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
579 clear_trace();
580 set_tracing(true);
582 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
583 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
584 OnError(0);
585 return;
588 // UL-C authentication
589 if (useKey) {
590 uint8_t key[16] = {0x00};
591 memcpy(key, datain + 4, sizeof(key));
593 if (!mifare_ultra_auth(key)) {
594 OnError(1);
595 return;
599 // UL-EV1 / NTAG authentication
600 if (usePwd) {
601 uint8_t pwd[4] = {0x00};
602 memcpy(pwd, datain + 4, 4);
603 uint8_t pack[4] = {0, 0, 0, 0};
604 if (!mifare_ul_ev1_auth(pwd, pack)) {
605 OnError(1);
606 return;
610 if (mifare_ultra_writeblock(blockNo, blockdata) != PM3_SUCCESS) {
611 if (g_dbglevel >= DBG_INFO) Dbprintf("Write block error");
612 OnError(0);
613 return;
616 if (mifare_ultra_halt()) {
617 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
618 OnError(0);
619 return;
622 if (g_dbglevel >= 2) DbpString("WRITE BLOCK FINISHED");
624 if (reply)
625 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
626 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
627 LEDsoff();
628 set_tracing(false);
631 void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) {
632 MifareUWriteBlockEx(arg0, arg1, datain, true);
635 // Arg0 : Block to write to.
636 // Arg1 : 0 = use no authentication.
637 // 1 = use 0x1A authentication.
638 // 2 = use 0x1B authentication.
639 // datain : 16 first bytes is data to be written.
640 // : 4/16 next bytes is authentication key.
641 void MifareUWriteBlockCompat(uint8_t arg0, uint8_t arg1, uint8_t *datain) {
642 uint8_t blockNo = arg0;
643 bool useKey = (arg1 == 1); //UL_C
644 bool usePwd = (arg1 == 2); //UL_EV1/NTAG
645 uint8_t blockdata[16] = {0x00};
647 memcpy(blockdata, datain, 16);
649 LEDsoff();
650 LED_A_ON();
651 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
653 clear_trace();
654 set_tracing(true);
656 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
657 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
658 OnError(0);
659 return;
662 // UL-C authentication
663 if (useKey) {
664 uint8_t key[16] = {0x00};
665 memcpy(key, datain + 16, sizeof(key));
667 if (!mifare_ultra_auth(key)) {
668 OnError(1);
669 return;
673 // UL-EV1 / NTAG authentication
674 if (usePwd) {
675 uint8_t pwd[4] = {0x00};
676 memcpy(pwd, datain + 16, 4);
677 uint8_t pack[4] = {0, 0, 0, 0};
678 if (!mifare_ul_ev1_auth(pwd, pack)) {
679 OnError(1);
680 return;
684 if (mifare_ultra_writeblock_compat(blockNo, blockdata) != PM3_SUCCESS) {
685 if (g_dbglevel >= DBG_INFO) Dbprintf("Write block error");
686 OnError(0);
687 return;
690 if (mifare_ultra_halt()) {
691 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
692 OnError(0);
693 return;
696 if (g_dbglevel >= 2) DbpString("WRITE BLOCK FINISHED");
698 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
699 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
700 LEDsoff();
701 set_tracing(false);
704 void MifareUSetPwd(uint8_t arg0, uint8_t *datain) {
706 uint8_t pwd[16] = {0x00};
707 uint8_t blockdata[4] = {0x00};
709 memcpy(pwd, datain, 16);
711 LED_A_ON();
712 LED_B_OFF();
713 LED_C_OFF();
714 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
716 clear_trace();
717 set_tracing(true);
719 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
720 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
721 OnError(0);
722 return;
725 blockdata[0] = pwd[7];
726 blockdata[1] = pwd[6];
727 blockdata[2] = pwd[5];
728 blockdata[3] = pwd[4];
729 if (mifare_ultra_writeblock(44, blockdata) != PM3_SUCCESS) {
730 if (g_dbglevel >= DBG_INFO) Dbprintf("Write block error");
731 OnError(44);
732 return;
735 blockdata[0] = pwd[3];
736 blockdata[1] = pwd[2];
737 blockdata[2] = pwd[1];
738 blockdata[3] = pwd[0];
739 if (mifare_ultra_writeblock(45, blockdata) != PM3_SUCCESS) {
740 if (g_dbglevel >= DBG_INFO) Dbprintf("Write block error");
741 OnError(45);
742 return;
745 blockdata[0] = pwd[15];
746 blockdata[1] = pwd[14];
747 blockdata[2] = pwd[13];
748 blockdata[3] = pwd[12];
749 if (mifare_ultra_writeblock(46, blockdata) != PM3_SUCCESS) {
750 if (g_dbglevel >= DBG_INFO) Dbprintf("Write block error");
751 OnError(46);
752 return;
755 blockdata[0] = pwd[11];
756 blockdata[1] = pwd[10];
757 blockdata[2] = pwd[9];
758 blockdata[3] = pwd[8];
759 if (mifare_ultra_writeblock(47, blockdata) != PM3_SUCCESS) {
760 if (g_dbglevel >= DBG_INFO) Dbprintf("Write block error");
761 OnError(47);
762 return;
765 if (mifare_ultra_halt()) {
766 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
767 OnError(0);
768 return;
771 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
772 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
773 LEDsoff();
774 set_tracing(false);
777 // Return 1 if the nonce is invalid else return 0
778 static int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, const uint8_t *parity) {
779 return (
780 (oddparity8((Nt >> 24) & 0xFF) == ((parity[0]) ^ oddparity8((NtEnc >> 24) & 0xFF) ^ BIT(Ks1, 16))) && \
781 (oddparity8((Nt >> 16) & 0xFF) == ((parity[1]) ^ oddparity8((NtEnc >> 16) & 0xFF) ^ BIT(Ks1, 8))) && \
782 (oddparity8((Nt >> 8) & 0xFF) == ((parity[2]) ^ oddparity8((NtEnc >> 8) & 0xFF) ^ BIT(Ks1, 0)))
783 ) ? 1 : 0;
786 void MifareAcquireNonces(uint32_t arg0, uint32_t flags) {
788 uint8_t uid[10] = {0x00};
789 uint8_t answer[MAX_MIFARE_FRAME_SIZE] = {0x00};
790 uint8_t par[1] = {0x00};
791 uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00};
792 uint32_t cuid = 0;
793 int16_t isOK = 0;
794 uint16_t num_nonces = 0;
795 uint8_t cascade_levels = 0;
796 uint8_t blockNo = arg0 & 0xff;
797 uint8_t keyType = (arg0 >> 8) & 0xff;
798 bool initialize = flags & 0x0001;
799 bool field_off = flags & 0x0004;
800 bool have_uid = false;
802 LED_A_ON();
803 LED_C_OFF();
805 BigBuf_free();
806 BigBuf_Clear_ext(false);
807 clear_trace();
808 set_tracing(true);
810 if (initialize)
811 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
813 LED_C_ON();
815 while (num_nonces < PM3_CMD_DATA_SIZE / 4) {
817 // Test if the action was cancelled
818 if (BUTTON_PRESS()) {
819 isOK = 2;
820 field_off = true;
821 break;
824 if (!have_uid) { // need a full select cycle to get the uid first
825 iso14a_card_select_t card_info;
826 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) {
827 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireNonces: Can't select card (ALL)");
828 continue;
830 switch (card_info.uidlen) {
831 case 4 :
832 cascade_levels = 1;
833 break;
834 case 7 :
835 cascade_levels = 2;
836 break;
837 case 10:
838 cascade_levels = 3;
839 break;
840 default:
841 break;
843 have_uid = true;
844 } else { // no need for anticollision. We can directly select the card
845 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
846 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireNonces: Can't select card (UID)");
847 continue;
851 // Transmit MIFARE_CLASSIC_AUTH
852 uint8_t dcmd[4] = {0x60 + (keyType & 0x01), blockNo, 0x00, 0x00};
853 AddCrc14A(dcmd, 2);
854 ReaderTransmit(dcmd, sizeof(dcmd), NULL);
855 int len = ReaderReceive(answer, sizeof(answer), par);
857 // wait for the card to become ready again
858 CHK_TIMEOUT();
860 if (len != 4) {
861 if (g_dbglevel >= 2) Dbprintf("AcquireNonces: Auth1 error");
862 continue;
865 // Save the tag nonce (nt)
866 memcpy(buf + num_nonces * 4, answer, 4);
867 num_nonces++;
870 LED_C_OFF();
871 LED_B_ON();
872 reply_old(CMD_ACK, isOK, cuid, num_nonces, buf, sizeof(buf));
873 LED_B_OFF();
875 if (g_dbglevel >= 3) DbpString("AcquireNonces finished");
877 if (field_off) {
878 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
879 LEDsoff();
880 set_tracing(false);
884 //-----------------------------------------------------------------------------
885 // acquire encrypted nonces in order to perform the attack described in
886 // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened
887 // Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on
888 // Computer and Communications Security, 2015
889 //-----------------------------------------------------------------------------
890 void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain) {
892 struct Crypto1State mpcs = {0, 0};
893 struct Crypto1State *pcs;
894 pcs = &mpcs;
896 uint8_t uid[10] = {0x00};
897 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
898 uint8_t par_enc[1] = {0x00};
899 uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00};
901 uint64_t ui64Key = bytes_to_num(datain, 6);
902 uint32_t cuid = 0;
903 int16_t isOK = PM3_SUCCESS;
904 uint16_t num_nonces = 0;
905 uint8_t nt_par_enc = 0;
906 uint8_t cascade_levels = 0;
907 uint8_t blockNo = arg0 & 0xff;
908 uint8_t keyType = (arg0 >> 8) & 0xff;
909 uint8_t targetBlockNo = arg1 & 0xff;
910 uint8_t targetKeyType = (arg1 >> 8) & 0xff;
911 bool initialize = flags & 0x0001;
912 bool slow = flags & 0x0002;
913 bool field_off = flags & 0x0004;
914 bool have_uid = false;
916 LED_A_ON();
917 LED_C_OFF();
919 BigBuf_free();
920 BigBuf_Clear_ext(false);
921 clear_trace();
922 set_tracing(false);
924 if (initialize)
925 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
927 LED_C_ON();
929 uint8_t prev_enc_nt[] = {0, 0, 0, 0};
930 uint8_t prev_counter = 0;
932 for (uint16_t i = 0; i <= PM3_CMD_DATA_SIZE - 9;) {
934 // Test if the action was cancelled
935 if (BUTTON_PRESS()) {
936 isOK = PM3_EOPABORTED;
937 field_off = true;
938 break;
941 if (have_uid == false) { // need a full select cycle to get the uid first
942 iso14a_card_select_t card_info;
943 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) {
944 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Can't select card (ALL)");
945 continue;
947 switch (card_info.uidlen) {
948 case 4 :
949 cascade_levels = 1;
950 break;
951 case 7 :
952 cascade_levels = 2;
953 break;
954 case 10:
955 cascade_levels = 3;
956 break;
957 default:
958 break;
960 have_uid = true;
961 } else { // no need for anticollision. We can directly select the card
962 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
963 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Can't select card (UID)");
964 continue;
968 if (slow)
969 SpinDelayUs(HARDNESTED_PRE_AUTHENTICATION_LEADTIME);
971 uint32_t nt1 = 0;
972 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
973 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Auth1 error");
974 continue;
977 // nested authentication
978 uint16_t len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par_enc, NULL);
980 // wait for the card to become ready again
981 CHK_TIMEOUT();
983 if (len != 4) {
984 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Auth2 error len=%d", len);
985 continue;
988 num_nonces++;
989 if (num_nonces % 2) {
990 memcpy(buf + i, receivedAnswer, 4);
991 nt_par_enc = par_enc[0] & 0xf0;
992 } else {
993 nt_par_enc |= par_enc[0] >> 4;
994 memcpy(buf + i + 4, receivedAnswer, 4);
995 memcpy(buf + i + 8, &nt_par_enc, 1);
996 i += 9;
1000 if (prev_enc_nt[0] == receivedAnswer[0] &&
1001 prev_enc_nt[1] == receivedAnswer[1] &&
1002 prev_enc_nt[2] == receivedAnswer[2] &&
1003 prev_enc_nt[3] == receivedAnswer[3]
1005 prev_counter++;
1007 memcpy(prev_enc_nt, receivedAnswer, 4);
1008 if (prev_counter == 5) {
1009 if (g_dbglevel >= DBG_EXTENDED) {
1010 DbpString("Static encrypted nonce detected, exiting...");
1011 uint32_t a = bytes_to_num(prev_enc_nt, 4);
1012 uint32_t b = bytes_to_num(receivedAnswer, 4);
1013 Dbprintf("( %08x vs %08x )", a, b);
1015 isOK = PM3_ESTATIC_NONCE;
1016 break;
1021 LED_C_OFF();
1022 crypto1_deinit(pcs);
1023 LED_B_ON();
1024 reply_old(CMD_ACK, isOK, cuid, num_nonces, buf, sizeof(buf));
1025 LED_B_OFF();
1027 if (field_off) {
1028 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1029 LEDsoff();
1030 set_tracing(false);
1035 //-----------------------------------------------------------------------------
1036 // acquire static encrypted nonces in order to perform the attack described in
1037 // Philippe Teuwen, "MIFARE Classic: exposing the static encrypted nonce variant"
1038 //-----------------------------------------------------------------------------
1039 int MifareAcquireStaticEncryptedNonces(uint32_t flags, const uint8_t *key, bool reply, uint8_t first_block_no, uint8_t first_key_type) {
1040 struct Crypto1State mpcs = {0, 0};
1041 struct Crypto1State *pcs;
1042 pcs = &mpcs;
1044 uint8_t uid[10] = {0x00};
1045 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
1046 uint8_t par_enc[1] = {0x00};
1047 // ((MIFARE_1K_MAXSECTOR + 1) * 2) * 8 < PM3_CMD_DATA_SIZE
1048 // we're storing nonces in emulator memory at CARD_MEMORY_RF08S_OFFSET
1049 // one sector data in one 16-byte block with for each keytype:
1050 // uint16_t nt_first_half (as we can reconstruct the other half)
1051 // uint8_t nt_par_err
1052 // uint8_t flag: if 0xAA and key=000000000000 it means we don't know the key yet
1053 // uint32_t nt_enc
1054 // buf: working buffer to prepare those "blocks"
1055 uint8_t buf[MIFARE_BLOCK_SIZE] = {0x00};
1056 uint64_t ui64Key = bytes_to_num(key, 6);
1057 bool with_data = flags & 1;
1058 bool without_backdoor = (flags >> 1) & 1;
1059 if (with_data && without_backdoor) {
1060 return PM3_EINVARG;
1062 uint32_t cuid = 0;
1063 int16_t isOK = PM3_SUCCESS;
1064 uint8_t cascade_levels = 0;
1065 bool have_uid = false;
1067 LED_A_ON();
1068 LED_C_OFF();
1070 BigBuf_free();
1071 BigBuf_Clear_ext(false);
1072 clear_trace();
1073 set_tracing(false);
1075 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1077 LED_C_ON();
1079 if (without_backdoor) {
1080 uint32_t nt1 = 0;
1082 iso14a_card_select_t card_info;
1083 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) {
1084 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (ALL)");
1085 isOK = PM3_ERFTRANS;
1086 goto out;
1088 switch (card_info.uidlen) {
1089 case 4 :
1090 cascade_levels = 1;
1091 break;
1092 case 7 :
1093 cascade_levels = 2;
1094 break;
1095 case 10:
1096 cascade_levels = 3;
1097 break;
1098 default:
1099 break;
1101 if (mifare_classic_authex_cmd(pcs, cuid, first_block_no, MIFARE_AUTH_KEYA + first_key_type, ui64Key, AUTH_FIRST, &nt1, NULL, NULL, NULL, false, false)) {
1102 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1103 isOK = PM3_ESOFT;
1104 goto out;
1107 uint16_t len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + first_key_type, first_block_no, receivedAnswer, sizeof(receivedAnswer), par_enc, NULL);
1108 if (len != 4) {
1109 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len);
1110 isOK = PM3_ESOFT;
1111 goto out;
1113 uint32_t nt_enc = bytes_to_num(receivedAnswer, 4);
1115 // send some crap to fail auth
1116 CHK_TIMEOUT();
1118 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
1119 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1120 isOK = PM3_ERFTRANS;
1121 goto out;
1123 if (mifare_classic_authex_cmd(pcs, cuid, first_block_no, MIFARE_AUTH_KEYA + first_key_type, ui64Key, AUTH_FIRST, &nt1, NULL, NULL, NULL, false, false)) {
1124 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1125 isOK = PM3_ESOFT;
1126 goto out;
1128 // Recover clear nt
1129 struct Crypto1State mpcs_tmp = {0, 0};
1130 struct Crypto1State *pcs_tmp = &mpcs_tmp;
1131 crypto1_init(pcs_tmp, ui64Key);
1132 uint32_t nt = crypto1_word(pcs_tmp, nt_enc ^ cuid, 1) ^ nt_enc;
1133 int dist = nonce_distance(nt, nt1);
1134 // ref dist is not always stable. Adjust physical distance to maximise ref dist, and try values around estimated nonces...
1135 Dbprintf("Block %2i key %i nested nT=%08x first nT=%08x dist=%i", first_block_no, first_key_type, nt, nt1, dist);
1137 for (uint16_t sec = 0; sec < MIFARE_1K_MAXSECTOR + 1; sec++) {
1138 uint16_t sec_gap = sec;
1139 if (sec >= MIFARE_1K_MAXSECTOR) {
1140 // gap between user blocks and advanced verification method blocks
1141 sec_gap += 16;
1143 uint16_t blockNo = sec_gap * 4;
1144 for (uint8_t keyType = 0; keyType < 2; keyType++) {
1145 // Test if the action was cancelled
1146 if (BUTTON_PRESS()) {
1147 isOK = PM3_EOPABORTED;
1148 break;
1151 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + keyType, blockNo, receivedAnswer, sizeof(receivedAnswer), par_enc, NULL);
1152 if (len != 4) {
1153 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len);
1154 isOK = PM3_ESOFT;
1155 goto out;
1157 // store nt_enc
1158 memcpy(buf + (keyType * 8) + 4, receivedAnswer, 4);
1159 nt_enc = bytes_to_num(receivedAnswer, 4);
1160 uint8_t nt_par_err = ((((par_enc[0] >> 7) & 1) ^ oddparity8((nt_enc >> 24) & 0xFF)) << 3 |
1161 (((par_enc[0] >> 6) & 1) ^ oddparity8((nt_enc >> 16) & 0xFF)) << 2 |
1162 (((par_enc[0] >> 5) & 1) ^ oddparity8((nt_enc >> 8) & 0xFF)) << 1 |
1163 (((par_enc[0] >> 4) & 1) ^ oddparity8((nt_enc >> 0) & 0xFF)));
1164 // Dbprintf("Sec %2i key %i {nT}=%02x%02x%02x%02x perr=%x", sec, keyType, receivedAnswer[0], receivedAnswer[1], receivedAnswer[2], receivedAnswer[3], nt_par_err);
1165 // store nt_par_err
1166 buf[(keyType * 8) + 2] = nt_par_err;
1167 buf[(keyType * 8) + 3] = 0xAA; // extra check to tell we have nt/nt_enc/par_err
1169 // send some crap to fail auth
1170 CHK_TIMEOUT();
1172 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
1173 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1174 isOK = PM3_ERFTRANS;
1175 goto out;
1177 if (mifare_classic_authex_cmd(pcs, cuid, first_block_no, MIFARE_AUTH_KEYA + first_key_type, ui64Key, AUTH_FIRST, &nt1, NULL, NULL, NULL, false, false)) {
1178 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1179 isOK = PM3_ESOFT;
1180 goto out;
1182 nt1 = rewind_nonce(nt1, dist);
1183 num_to_bytes(nt1 >> 16, 2, buf + (keyType * 8));
1184 emlSetMem_xt(buf, (CARD_MEMORY_RF08S_OFFSET / MIFARE_BLOCK_SIZE) + sec, 1, MIFARE_BLOCK_SIZE);
1187 } else {
1188 for (uint16_t sec = 0; sec < MIFARE_1K_MAXSECTOR + 1; sec++) {
1189 uint16_t sec_gap = sec;
1190 if (sec >= MIFARE_1K_MAXSECTOR) {
1191 // gap between user blocks and advanced verification method blocks
1192 sec_gap += 16;
1194 uint16_t blockNo = sec_gap * 4;
1195 for (uint8_t keyType = 0; keyType < 2; keyType++) {
1196 // Test if the action was cancelled
1197 if (BUTTON_PRESS()) {
1198 isOK = PM3_EOPABORTED;
1199 break;
1201 if (have_uid == false) { // need a full select cycle to get the uid first
1202 iso14a_card_select_t card_info;
1203 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) {
1204 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (ALL)");
1205 isOK = PM3_ERFTRANS;
1206 goto out;
1208 switch (card_info.uidlen) {
1209 case 4 :
1210 cascade_levels = 1;
1211 break;
1212 case 7 :
1213 cascade_levels = 2;
1214 break;
1215 case 10:
1216 cascade_levels = 3;
1217 break;
1218 default:
1219 break;
1221 have_uid = true;
1222 } else { // no need for anticollision. We can directly select the card
1223 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
1224 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1225 isOK = PM3_ERFTRANS;
1226 goto out;
1230 uint32_t nt1 = 0;
1231 if (mifare_classic_authex_cmd(pcs, cuid, blockNo, MIFARE_AUTH_KEYA + keyType + 4, ui64Key, AUTH_FIRST, &nt1, NULL, NULL, NULL, false, false)) {
1232 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1233 isOK = PM3_ESOFT;
1234 goto out;
1236 if ((with_data) && (keyType == 0)) {
1237 uint8_t data[16];
1238 uint8_t blocks = 4;
1239 if (blockNo >= MIFARE_1K_MAXSECTOR * 4) {
1240 // special RF08S advanced authentication blocks, let's dump in emulator just in case
1241 blocks = 8;
1243 for (uint16_t tb = blockNo; tb < blockNo + blocks; tb++) {
1244 memset(data, 0x00, sizeof(data));
1245 int res = mifare_classic_readblock(pcs, tb, data);
1246 if (res == 1) {
1247 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Read error");
1248 isOK = PM3_ESOFT;
1249 goto out;
1251 emlSetMem_xt(data, tb, 1, 16);
1254 // nested authentication
1255 uint16_t len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + keyType + 4, blockNo, receivedAnswer, sizeof(receivedAnswer), par_enc, NULL);
1256 if (len != 4) {
1257 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len);
1258 isOK = PM3_ESOFT;
1259 goto out;
1261 uint32_t nt_enc = bytes_to_num(receivedAnswer, 4);
1262 crypto1_init(pcs, ui64Key);
1263 uint32_t nt = crypto1_word(pcs, nt_enc ^ cuid, 1) ^ nt_enc;
1264 // Dbprintf("Sec %2i key %i nT=%08x", sec, keyType + 4, nt);
1265 // store nt (first half)
1266 num_to_bytes(nt >> 16, 2, buf + (keyType * 8));
1267 // send some crap to fail auth
1268 CHK_TIMEOUT();
1270 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
1271 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1272 isOK = PM3_ERFTRANS;
1273 goto out;
1275 if (mifare_classic_authex_cmd(pcs, cuid, blockNo, MIFARE_AUTH_KEYA + keyType + 4, ui64Key, AUTH_FIRST, &nt1, NULL, NULL, NULL, false, false)) {
1276 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1277 isOK = PM3_ESOFT;
1278 goto out;
1281 // nested authentication on regular keytype
1282 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + keyType, blockNo, receivedAnswer, sizeof(receivedAnswer), par_enc, NULL);
1283 if (len != 4) {
1284 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len);
1285 isOK = PM3_ESOFT;
1286 goto out;
1288 // store nt_enc
1289 memcpy(buf + (keyType * 8) + 4, receivedAnswer, 4);
1290 nt_enc = bytes_to_num(receivedAnswer, 4);
1291 uint8_t nt_par_err = ((((par_enc[0] >> 7) & 1) ^ oddparity8((nt_enc >> 24) & 0xFF)) << 3 |
1292 (((par_enc[0] >> 6) & 1) ^ oddparity8((nt_enc >> 16) & 0xFF)) << 2 |
1293 (((par_enc[0] >> 5) & 1) ^ oddparity8((nt_enc >> 8) & 0xFF)) << 1 |
1294 (((par_enc[0] >> 4) & 1) ^ oddparity8((nt_enc >> 0) & 0xFF)));
1295 // Dbprintf("Sec %2i key %i {nT}=%02x%02x%02x%02x perr=%x", sec, keyType, receivedAnswer[0], receivedAnswer[1], receivedAnswer[2], receivedAnswer[3], nt_par_err);
1296 // store nt_par_err
1297 buf[(keyType * 8) + 2] = nt_par_err;
1298 buf[(keyType * 8) + 3] = 0xAA; // extra check to tell we have nt/nt_enc/par_err
1299 emlSetMem_xt(buf, (CARD_MEMORY_RF08S_OFFSET / MIFARE_BLOCK_SIZE) + sec, 1, MIFARE_BLOCK_SIZE);
1300 // send some crap to fail auth
1301 CHK_TIMEOUT();
1305 out:
1306 LED_C_OFF();
1307 crypto1_deinit(pcs);
1308 LED_B_ON();
1309 if (reply) {
1310 reply_mix(CMD_ACK, isOK, cuid, 0, BigBuf_get_EM_addr() + CARD_MEMORY_RF08S_OFFSET, MIFARE_BLOCK_SIZE * (MIFARE_1K_MAXSECTOR + 1));
1312 LED_B_OFF();
1314 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1315 LEDsoff();
1316 set_tracing(false);
1317 return isOK;
1321 //-----------------------------------------------------------------------------
1322 // MIFARE nested authentication.
1324 //-----------------------------------------------------------------------------
1325 void MifareNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, bool calibrate, uint8_t *key) {
1326 uint64_t ui64Key = 0;
1327 ui64Key = bytes_to_num(key, 6);
1329 // variables
1330 uint16_t i, j, len;
1331 static uint16_t dmin, dmax;
1333 uint8_t par[1] = {0x00};
1334 uint8_t par_array[4] = {0x00};
1335 uint8_t uid[10] = {0x00};
1336 uint32_t cuid = 0, nt1, nt2, nttest, ks1;
1337 uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00};
1339 uint16_t ncount = 0;
1340 struct Crypto1State mpcs = {0, 0};
1341 struct Crypto1State *pcs;
1342 pcs = &mpcs;
1343 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
1345 uint32_t auth1_time, auth2_time;
1346 static uint16_t delta_time = 0;
1348 LED_A_ON();
1349 LED_C_OFF();
1350 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1352 // free eventually allocated BigBuf memory
1353 BigBuf_free();
1354 BigBuf_Clear_ext(false);
1356 if (calibrate)
1357 clear_trace();
1359 set_tracing(true);
1361 // statistics on nonce distance
1362 int16_t isOK = PM3_SUCCESS;
1363 #define NESTED_MAX_TRIES 12
1364 if (calibrate) { // calibrate: for first call only. Otherwise reuse previous calibration
1365 LED_B_ON();
1366 WDT_HIT();
1368 uint32_t prev_enc_nt = 0;
1369 uint8_t prev_counter = 0;
1371 uint16_t unsuccessful_tries = 0;
1372 uint16_t davg = 0;
1373 dmax = 0;
1374 dmin = 2000;
1375 delta_time = 0;
1376 uint16_t rtr;
1377 for (rtr = 0; rtr < 17; rtr++) {
1379 // Test if the action was cancelled
1380 if (BUTTON_PRESS() || data_available()) {
1381 isOK = PM3_EOPABORTED;
1382 break;
1385 // prepare next select. No need to power down the card.
1386 if (mifare_classic_halt(pcs)) {
1387 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Halt error");
1388 rtr--;
1389 continue;
1392 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == 0) {
1393 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Can't select card");
1394 rtr--;
1395 continue;
1398 auth1_time = 0;
1399 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) {
1400 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth1 error");
1401 rtr--;
1402 continue;
1404 auth2_time = (delta_time) ? auth1_time + delta_time : 0;
1406 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, &auth2_time)) {
1407 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth2 error");
1408 rtr--;
1409 continue;
1412 // cards with fixed nonce
1413 // NXP Mifare is typical around 840,but for some unlicensed/compatible mifare card this can be 160
1415 uint32_t nttmp = prng_successor(nt1, 100);
1416 for (i = 101; i < 1200; i++) {
1417 nttmp = prng_successor(nttmp, 1);
1418 if (nttmp == nt2) break;
1421 if (i != 1200) {
1422 if (rtr != 0) {
1423 davg += i;
1424 dmin = MIN(dmin, i);
1425 dmax = MAX(dmax, i);
1426 } else {
1427 // allow some slack for proper timing
1428 delta_time = auth2_time - auth1_time + 32;
1430 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nested: calibrating... ntdist=%d", i);
1431 } else {
1432 unsuccessful_tries++;
1433 // card isn't vulnerable to nested attack (random numbers are not predictable)
1434 if (unsuccessful_tries > NESTED_MAX_TRIES) {
1435 isOK = PM3_EFAILED;
1440 if (nt1 == nt2) {
1441 prev_counter++;
1443 prev_enc_nt = nt2;
1445 if (prev_counter == 5) {
1446 if (g_dbglevel >= DBG_EXTENDED) {
1447 DbpString("Static encrypted nonce detected, exiting...");
1448 Dbprintf("( %08x vs %08x )", prev_enc_nt, nt2);
1450 isOK = PM3_ESTATIC_NONCE;
1451 break;
1455 if (rtr > 1)
1456 davg = (davg + (rtr - 1) / 2) / (rtr - 1);
1458 if (g_dbglevel >= DBG_DEBUG) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr, isOK, dmin, dmax, davg, delta_time);
1460 dmin = davg - 2;
1461 dmax = davg + 2;
1463 LED_B_OFF();
1465 // -------------------------------------------------------------------------------------------------
1467 LED_C_ON();
1469 // get crypted nonces for target sector
1470 for (i = 0; ((i < 2) && (isOK == PM3_SUCCESS)); i++) {
1472 // look for exactly two different nonces
1474 target_nt[i] = 0;
1475 // continue until we have an unambiguous nonce
1476 while (target_nt[i] == 0) {
1478 // Test if the action was cancelled
1479 if (BUTTON_PRESS() || data_available()) {
1480 isOK = PM3_EOPABORTED;
1481 break;
1484 // prepare next select. No need to power down the card.
1485 if (mifare_classic_halt(pcs)) {
1486 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Halt error");
1487 continue;
1490 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
1491 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Can't select card");
1492 continue;
1495 auth1_time = 0;
1496 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) {
1497 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth1 error");
1498 continue;
1501 // nested authentication
1502 auth2_time = auth1_time + delta_time;
1504 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par, &auth2_time);
1505 if (len != 4) {
1506 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth2 error len=%d", len);
1507 continue;
1510 nt2 = bytes_to_num(receivedAnswer, 4);
1511 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i + 1, nt1, nt2, par[0]);
1513 // Parity validity check
1514 for (j = 0; j < 4; j++) {
1515 par_array[j] = (oddparity8(receivedAnswer[j]) != ((par[0] >> (7 - j)) & 0x01));
1518 ncount = 0;
1519 nttest = prng_successor(nt1, dmin - 1);
1520 for (j = dmin; j < dmax + 1; j++) {
1521 nttest = prng_successor(nttest, 1);
1522 ks1 = nt2 ^ nttest;
1524 if (valid_nonce(nttest, nt2, ks1, par_array)) {
1525 if (ncount > 0) { // we are only interested in disambiguous nonces, try again
1526 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nonce#%d: dismissed (ambiguous), ntdist=%d", i + 1, j);
1527 target_nt[i] = 0;
1528 break;
1530 target_nt[i] = nttest;
1531 target_ks[i] = ks1;
1532 ncount++;
1533 if (i == 1 && target_nt[1] == target_nt[0]) { // we need two different nonces
1534 target_nt[i] = 0;
1535 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nonce#2: dismissed (= nonce#1), ntdist=%d", j);
1536 break;
1538 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nonce#%d: valid, ntdist=%d", i + 1, j);
1541 if (target_nt[i] == 0 && j == dmax + 1 && g_dbglevel >= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i + 1);
1545 LED_C_OFF();
1547 crypto1_deinit(pcs);
1549 struct p {
1550 int16_t isOK;
1551 uint8_t block;
1552 uint8_t keytype;
1553 uint8_t cuid[4];
1554 uint8_t nt_a[4];
1555 uint8_t ks_a[4];
1556 uint8_t nt_b[4];
1557 uint8_t ks_b[4];
1558 } PACKED payload;
1559 payload.isOK = isOK;
1560 payload.block = targetBlockNo;
1561 payload.keytype = targetKeyType;
1563 memcpy(payload.cuid, &cuid, 4);
1564 memcpy(payload.nt_a, &target_nt[0], 4);
1565 memcpy(payload.ks_a, &target_ks[0], 4);
1566 memcpy(payload.nt_b, &target_nt[1], 4);
1567 memcpy(payload.ks_b, &target_ks[1], 4);
1569 LED_B_ON();
1570 reply_ng(CMD_HF_MIFARE_NESTED, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload));
1571 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1572 LEDsoff();
1573 set_tracing(false);
1576 void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, uint8_t *key) {
1578 LEDsoff();
1580 uint64_t ui64Key = bytes_to_num(key, 6);
1581 uint16_t len, dist1 = 160, dist2 = 320;
1582 uint8_t uid[10] = { 0x00 };
1583 uint32_t cuid = 0, nt1 = 0, nt2 = 0, nt3 = 0;
1584 uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00};
1585 uint8_t par[1] = { 0x00 };
1586 uint8_t receivedAnswer[10] = { 0x00 };
1588 struct Crypto1State mpcs = { 0, 0 };
1589 struct Crypto1State *pcs;
1590 pcs = &mpcs;
1592 LED_A_ON();
1593 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1595 // free eventually allocated BigBuf memory
1596 BigBuf_free();
1597 BigBuf_Clear_ext(false);
1598 clear_trace();
1599 set_tracing(true);
1601 int16_t isOK = PM3_ESOFT;
1602 LED_C_ON();
1604 // Main loop - get crypted nonces for target sector
1605 for (uint8_t rtr = 0; rtr < 2; rtr++) {
1607 // distance measurement
1608 if (mifare_classic_halt(pcs)) {
1609 continue;
1612 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
1613 continue;
1616 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
1617 continue;
1620 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, NULL)) {
1621 continue;
1624 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt3, NULL)) {
1625 continue;
1628 dist1 = nonce_distance(nt1, nt2);
1629 dist2 = nonce_distance(nt1, nt3);
1631 if (mifare_classic_halt(pcs)) {
1632 continue;
1635 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
1636 continue;
1639 // first collection
1640 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
1641 continue;
1644 // pre-generate nonces
1645 if (targetKeyType == 1 && nt1 == 0x009080A2) {
1646 target_nt[0] = prng_successor(nt1, 161);
1647 target_nt[1] = prng_successor(nt1, 321);
1648 } else {
1649 target_nt[0] = prng_successor(nt1, dist1);
1650 target_nt[1] = prng_successor(nt1, dist2);
1653 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par, NULL);
1654 if (len != 4) {
1655 continue;
1658 nt2 = bytes_to_num(receivedAnswer, 4);
1659 target_ks[0] = nt2 ^ target_nt[0];
1661 // second collection
1662 if (mifare_classic_halt(pcs)) {
1663 continue;
1666 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
1667 continue;
1670 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
1671 continue;
1674 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, NULL, NULL)) {
1675 continue;
1678 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par, NULL);
1679 if (len != 4) {
1680 continue;
1683 nt3 = bytes_to_num(receivedAnswer, 4);
1684 target_ks[1] = nt3 ^ target_nt[1];
1686 isOK = PM3_SUCCESS;
1689 LED_C_OFF();
1691 crypto1_deinit(pcs);
1693 struct p {
1694 uint8_t block;
1695 uint8_t keytype;
1696 uint8_t cuid[4];
1697 uint8_t nt_a[4];
1698 uint8_t ks_a[4];
1699 uint8_t nt_b[4];
1700 uint8_t ks_b[4];
1701 } PACKED payload;
1702 payload.block = targetBlockNo;
1703 payload.keytype = targetKeyType;
1705 memcpy(payload.cuid, &cuid, 4);
1706 memcpy(payload.nt_a, &target_nt[0], 4);
1707 memcpy(payload.ks_a, &target_ks[0], 4);
1708 memcpy(payload.nt_b, &target_nt[1], 4);
1709 memcpy(payload.ks_b, &target_ks[1], 4);
1711 LED_B_ON();
1712 reply_ng(CMD_HF_MIFARE_STATIC_NESTED, isOK, (uint8_t *)&payload, sizeof(payload));
1713 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1714 LEDsoff();
1715 set_tracing(false);
1718 //-----------------------------------------------------------------------------
1719 // MIFARE check keys. key count up to 85.
1721 //-----------------------------------------------------------------------------
1722 typedef struct sector_t {
1723 uint8_t keyA[6];
1724 uint8_t keyB[6];
1725 } sector_t;
1727 typedef struct chk_t {
1728 uint64_t key;
1729 uint32_t cuid;
1730 uint8_t cl;
1731 uint8_t block;
1732 uint8_t keyType;
1733 uint8_t *uid;
1734 struct Crypto1State *pcs;
1735 } chk_t;
1737 // checks one key.
1738 // fast select, tries 5 times to select
1740 // return:
1741 // 2 = failed to select.
1742 // 1 = wrong key
1743 // 0 = correct key
1744 static uint8_t chkKey(struct chk_t *c) {
1745 uint8_t i = 0, res = 2;
1746 bool selected = false;
1747 while (i < 5) {
1748 // this part is from Piwi's faster nonce collecting part in Hardnested.
1749 // assume: fast select
1750 if (!iso14443a_fast_select_card(c->uid, c->cl)) {
1751 ++i;
1752 continue;
1754 selected = true;
1755 res = mifare_classic_authex(c->pcs, c->cuid, c->block, c->keyType, c->key, AUTH_FIRST, NULL, NULL);
1757 // CHK_TIMEOUT();
1759 // if successful auth, send HALT
1760 // if ( !res )
1761 // mifare_classic_halt(c->pcs);
1762 break;
1764 if (selected == false) {
1765 Dbprintf("chkKey: Failed at fast selecting the card!");
1767 return res;
1770 static uint8_t chkKey_readb(struct chk_t *c, uint8_t *keyb) {
1772 if (!iso14443a_fast_select_card(c->uid, c->cl))
1773 return 2;
1775 if (mifare_classic_authex(c->pcs, c->cuid, c->block, 0, c->key, AUTH_FIRST, NULL, NULL))
1776 return 1;
1778 uint8_t data[16] = {0x00};
1779 uint8_t res = mifare_classic_readblock(c->pcs, c->block, data);
1781 // successful read
1782 if (!res) {
1783 // data was something else than zeros.
1784 if (memcmp(data + 10, "\x00\x00\x00\x00\x00\x00", 6) != 0) {
1785 memcpy(keyb, data + 10, 6);
1786 res = 0;
1787 } else {
1788 res = 3;
1790 mifare_classic_halt(c->pcs);
1792 return res;
1795 static void chkKey_scanA(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, const uint8_t *sectorcnt, uint8_t *foundkeys) {
1796 for (uint8_t s = 0; s < *sectorcnt; s++) {
1798 // skip already found A keys
1799 if (found[(s * 2)])
1800 continue;
1802 c->block = FirstBlockOfSector(s);
1803 if (chkKey(c) == 0) {
1804 num_to_bytes(c->key, 6, k_sector[s].keyA);
1805 found[(s * 2)] = 1;
1806 ++*foundkeys;
1808 if (g_dbglevel >= 3) Dbprintf("ChkKeys_fast: Scan A found (%d)", c->block);
1813 static void chkKey_scanB(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, const uint8_t *sectorcnt, uint8_t *foundkeys) {
1814 for (uint8_t s = 0; s < *sectorcnt; s++) {
1816 // skip already found B keys
1817 if (found[(s * 2) + 1])
1818 continue;
1820 c->block = FirstBlockOfSector(s);
1821 if (chkKey(c) == 0) {
1822 num_to_bytes(c->key, 6, k_sector[s].keyB);
1823 found[(s * 2) + 1] = 1;
1824 ++*foundkeys;
1826 if (g_dbglevel >= 3) Dbprintf("ChkKeys_fast: Scan B found (%d)", c->block);
1831 // loop all A keys,
1832 // when A is found but not B, try to read B.
1833 static void chkKey_loopBonly(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) {
1835 // read Block B, if A is found.
1836 for (uint8_t s = 0; s < *sectorcnt; ++s) {
1838 if (found[(s * 2)] && found[(s * 2) + 1])
1839 continue;
1841 c->block = (FirstBlockOfSector(s) + NumBlocksPerSector(s) - 1);
1843 // A but not B
1844 if (found[(s * 2)] && !found[(s * 2) + 1]) {
1845 c->key = bytes_to_num(k_sector[s].keyA, 6);
1846 uint8_t status = chkKey_readb(c, k_sector[s].keyB);
1847 if (status == 0) {
1848 found[(s * 2) + 1] = 1;
1849 ++*foundkeys;
1851 if (g_dbglevel >= 3) Dbprintf("ChkKeys_fast: Reading B found (%d)", c->block);
1853 // try quick find all B?
1854 // assume: keys comes in groups. Find one B, test against all B.
1855 c->key = bytes_to_num(k_sector[s].keyB, 6);
1856 c->keyType = 1;
1857 chkKey_scanB(c, k_sector, found, sectorcnt, foundkeys);
1863 // get Chunks of keys, to test authentication against card.
1864 // arg0 = antal sectorer
1865 // arg0 = first time
1866 // arg1 = clear trace
1867 // arg2 = antal nycklar i keychunk
1868 // datain = keys as array
1869 void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain) {
1871 // first call or
1872 uint8_t sectorcnt = arg0 & 0xFF; // 16;
1873 uint8_t firstchunk = (arg0 >> 8) & 0xF;
1874 uint8_t lastchunk = (arg0 >> 12) & 0xF;
1875 uint16_t singleSectorParams = (arg0 >> 16) & 0xFFFF;
1876 uint8_t strategy = arg1 & 0xFF;
1877 uint8_t use_flashmem = (arg1 >> 8) & 0xFF;
1878 uint16_t keyCount = arg2 & 0xFF;
1879 uint8_t status = 0;
1880 bool singleSectorMode = (singleSectorParams >> 15) & 1;
1881 uint8_t keytype = (singleSectorParams >> 8) & 1;
1882 uint8_t blockn = singleSectorParams & 0xFF;
1884 struct Crypto1State mpcs = {0, 0};
1885 struct Crypto1State *pcs;
1886 pcs = &mpcs;
1887 struct chk_t chk_data;
1889 uint8_t allkeys = sectorcnt << 1;
1891 static uint32_t cuid = 0;
1892 static uint8_t cascade_levels = 0;
1893 static uint8_t foundkeys = 0;
1894 static sector_t k_sector[80];
1895 static uint8_t found[80];
1896 static uint8_t *uid;
1898 int oldbg = g_dbglevel;
1900 #ifdef WITH_FLASH
1901 if (use_flashmem) {
1902 BigBuf_free();
1903 uint32_t size = 0;
1904 if (exists_in_spiffs(MF_KEYS_FILE)) {
1905 size = size_in_spiffs(MF_KEYS_FILE);
1907 if (size == 0) {
1908 Dbprintf("Spiffs file: %s does not exists or empty.", MF_KEYS_FILE);
1909 goto OUT;
1912 keyCount = size / MF_KEY_LENGTH;
1914 if (keyCount == 0)
1915 goto OUT;
1917 // limit size of available for keys in bigbuff
1918 // a key is 6bytes
1919 uint16_t key_mem_available = MIN(BigBuf_get_size(), keyCount * MF_KEY_LENGTH);
1921 keyCount = key_mem_available / MF_KEY_LENGTH;
1923 datain = BigBuf_malloc(key_mem_available);
1924 if (datain == NULL)
1925 goto OUT;
1927 if (SPIFFS_OK == rdv40_spiffs_read_as_filetype(MF_KEYS_FILE, datain, keyCount * MF_KEY_LENGTH, RDV40_SPIFFS_SAFETY_SAFE)) {
1928 if (g_dbglevel >= DBG_ERROR) Dbprintf("Loaded %u keys from spiffs file: %s", keyCount, MF_KEYS_FILE);
1929 } else {
1930 Dbprintf("Spiffs file: %s cannot be read.", MF_KEYS_FILE);
1931 goto OUT;
1934 #endif
1936 if (uid == NULL || firstchunk) {
1937 uid = BigBuf_malloc(10);
1938 if (uid == NULL)
1939 goto OUT;
1942 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1944 LEDsoff();
1945 LED_A_ON();
1947 if (firstchunk) {
1948 clear_trace();
1949 set_tracing(false);
1951 memset(k_sector, 0x00, 480 + 10);
1952 memset(found, 0x00, sizeof(found));
1953 foundkeys = 0;
1955 iso14a_card_select_t card_info;
1956 if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) {
1957 if (g_dbglevel >= DBG_ERROR) Dbprintf("ChkKeys_fast: Can't select card (ALL)");
1958 goto OUT;
1961 switch (card_info.uidlen) {
1962 case 4 :
1963 cascade_levels = 1;
1964 break;
1965 case 7 :
1966 cascade_levels = 2;
1967 break;
1968 case 10:
1969 cascade_levels = 3;
1970 break;
1971 default:
1972 break;
1975 CHK_TIMEOUT();
1978 // clear debug level. We are expecting lots of authentication failures...
1979 g_dbglevel = DBG_NONE;
1981 // set check struct.
1982 chk_data.uid = uid;
1983 chk_data.cuid = cuid;
1984 chk_data.cl = cascade_levels;
1985 chk_data.pcs = pcs;
1986 chk_data.block = 0;
1988 if (singleSectorMode) {
1989 allkeys = 1;
1990 chk_data.block = blockn;
1991 chk_data.keyType = keytype;
1992 for (uint16_t i = 0; i < keyCount; ++i) {
1994 // Allow button press / usb cmd to interrupt device
1995 if (BUTTON_PRESS() || data_available()) {
1996 goto OUT;
1999 WDT_HIT();
2001 chk_data.key = bytes_to_num(datain + i * 6, 6);
2002 if (chkKey(&chk_data) == 0) {
2003 foundkeys++;
2004 reply_old(CMD_ACK, 1, 0, 0, datain + i * 6, 6);
2005 goto out;
2008 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
2009 out:
2010 LEDsoff();
2011 crypto1_deinit(pcs);
2012 if (foundkeys == allkeys || lastchunk) {
2013 set_tracing(false);
2014 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2015 BigBuf_free();
2016 BigBuf_Clear_ext(false);
2018 g_dbglevel = oldbg;
2019 return;
2023 // keychunk loop - depth first one sector.
2024 if (strategy == 1 || use_flashmem) {
2026 uint8_t newfound = foundkeys;
2028 uint16_t lastpos = 0;
2029 uint16_t s_point = 0;
2030 // Sector main loop
2031 // keep track of how many sectors on card.
2032 for (uint8_t s = 0; s < sectorcnt; ++s) {
2034 if (found[(s * 2)] && found[(s * 2) + 1])
2035 continue;
2037 for (uint16_t i = s_point; i < keyCount; ++i) {
2039 // Allow button press / usb cmd to interrupt device
2040 if (BUTTON_PRESS() || data_available()) {
2041 goto OUT;
2044 // found all keys?
2045 if (foundkeys == allkeys)
2046 goto OUT;
2048 WDT_HIT();
2050 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
2051 chk_data.block = FirstBlockOfSector(s);
2053 // new key
2054 chk_data.key = bytes_to_num(datain + i * 6, 6);
2056 // skip already found A keys
2057 if (!found[(s * 2)]) {
2058 chk_data.keyType = 0;
2059 status = chkKey(&chk_data);
2060 if (status == 0) {
2061 memcpy(k_sector[s].keyA, datain + i * 6, 6);
2062 found[(s * 2)] = 1;
2063 ++foundkeys;
2065 chkKey_scanA(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2067 // read Block B, if A is found.
2068 chkKey_loopBonly(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2070 chk_data.keyType = 1;
2071 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2073 chk_data.keyType = 0;
2074 chk_data.block = FirstBlockOfSector(s);
2076 if (use_flashmem) {
2077 if (lastpos != i && lastpos != 0) {
2078 if (i - lastpos < 0xF) {
2079 s_point = i & 0xFFF0;
2081 } else {
2082 lastpos = i;
2088 // skip already found B keys
2089 if (!found[(s * 2) + 1]) {
2090 chk_data.keyType = 1;
2091 status = chkKey(&chk_data);
2092 if (status == 0) {
2093 memcpy(k_sector[s].keyB, datain + i * 6, 6);
2094 found[(s * 2) + 1] = 1;
2095 ++foundkeys;
2097 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2099 if (use_flashmem) {
2100 if (lastpos != i && lastpos != 0) {
2102 if (i - lastpos < 0xF)
2103 s_point = i & 0xFFF0;
2104 } else {
2105 lastpos = i;
2111 if (found[(s * 2)] && found[(s * 2) + 1])
2112 break;
2114 } // end keys test loop - depth first
2116 // assume1. if no keys found in first sector, get next keychunk from client
2117 if (!use_flashmem && (newfound - foundkeys == 0))
2118 goto OUT;
2120 } // end loop - sector
2121 } // end strategy 1
2123 if (foundkeys == allkeys)
2124 goto OUT;
2126 if (strategy == 2 || use_flashmem) {
2128 // Keychunk loop
2129 for (uint16_t i = 0; i < keyCount; i++) {
2131 // Allow button press / usb cmd to interrupt device
2132 if (BUTTON_PRESS() || data_available()) break;
2134 // found all keys?
2135 if (foundkeys == allkeys)
2136 goto OUT;
2138 WDT_HIT();
2140 // new key
2141 chk_data.key = bytes_to_num(datain + i * 6, 6);
2143 // Sector main loop
2144 // keep track of how many sectors on card.
2145 for (uint8_t s = 0; s < sectorcnt; ++s) {
2147 if (found[(s * 2)] && found[(s * 2) + 1]) continue;
2149 // found all keys?
2150 if (foundkeys == allkeys)
2151 goto OUT;
2153 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
2154 chk_data.block = FirstBlockOfSector(s);
2156 // skip already found A keys
2157 if (!found[(s * 2)]) {
2158 chk_data.keyType = 0;
2159 status = chkKey(&chk_data);
2160 if (status == 0) {
2161 memcpy(k_sector[s].keyA, datain + i * 6, 6);
2162 found[(s * 2)] = 1;
2163 ++foundkeys;
2165 chkKey_scanA(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2167 // read Block B, if A is found.
2168 chkKey_loopBonly(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2170 chk_data.block = FirstBlockOfSector(s);
2174 // skip already found B keys
2175 if (!found[(s * 2) + 1]) {
2176 chk_data.keyType = 1;
2177 status = chkKey(&chk_data);
2178 if (status == 0) {
2179 memcpy(k_sector[s].keyB, datain + i * 6, 6);
2180 found[(s * 2) + 1] = 1;
2181 ++foundkeys;
2183 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2186 } // end loop sectors
2187 } // end loop keys
2188 } // end loop strategy 2
2189 OUT:
2190 LEDsoff();
2192 crypto1_deinit(pcs);
2194 // All keys found, send to client, or last keychunk from client
2195 if (foundkeys == allkeys || lastchunk) {
2197 uint64_t foo = 0;
2198 for (uint8_t m = 0; m < 64; m++) {
2199 foo |= ((uint64_t)(found[m] & 1) << m);
2202 uint16_t bar = 0;
2203 uint8_t j = 0;
2204 for (uint8_t m = 64; m < ARRAYLEN(found); m++) {
2205 bar |= ((uint16_t)(found[m] & 1) << j++);
2208 uint8_t *tmp = BigBuf_malloc(480 + 10);
2209 memcpy(tmp, k_sector, sectorcnt * sizeof(sector_t));
2210 num_to_bytes(foo, 8, tmp + 480);
2211 tmp[488] = bar & 0xFF;
2212 tmp[489] = bar >> 8 & 0xFF;
2214 reply_old(CMD_ACK, foundkeys, 0, 0, tmp, 480 + 10);
2216 set_tracing(false);
2217 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2218 BigBuf_free();
2219 BigBuf_Clear_ext(false);
2221 // special trick ecfill
2222 if (use_flashmem && foundkeys == allkeys) {
2224 uint8_t block[16] = {0};
2225 for (int i = 0; i < sectorcnt; i++) {
2227 uint8_t blockno;
2228 if (i < 32) {
2229 blockno = (i * 4) ^ 0x3;
2230 } else {
2231 blockno = (32 * 4 + (i - 32) * 16) ^ 0xF;
2233 // get ST
2234 emlGetMem(block, blockno, 1);
2236 memcpy(block, k_sector[i].keyA, 6);
2237 memcpy(block + 10, k_sector[i].keyB, 6);
2239 emlSetMem_xt(block, blockno, 1, sizeof(block));
2242 MifareECardLoad(sectorcnt, MF_KEY_A, NULL);
2243 MifareECardLoad(sectorcnt, MF_KEY_B, NULL);
2245 } else {
2246 // partial/none keys found
2247 reply_mix(CMD_ACK, foundkeys, 0, 0, 0, 0);
2250 g_dbglevel = oldbg;
2253 void MifareChkKeys(uint8_t *datain, uint8_t reserved_mem) {
2255 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2257 struct Crypto1State mpcs = {0, 0};
2258 struct Crypto1State *pcs;
2259 pcs = &mpcs;
2261 uint8_t uid[10] = {0x00};
2263 uint64_t key = 0;
2264 uint32_t cuid = 0;
2265 uint8_t cascade_levels = 0;
2266 struct {
2267 uint8_t key[6];
2268 bool found;
2269 } PACKED keyresult;
2270 keyresult.found = false;
2271 memset(keyresult.key, 0x00, sizeof(keyresult.key));
2273 bool have_uid = false;
2275 uint8_t keyType = datain[0];
2276 uint8_t blockNo = datain[1];
2277 bool clearTrace = datain[2];
2278 uint16_t key_count = (datain[3] << 8) | datain[4];
2280 uint16_t key_mem_available;
2281 if (reserved_mem)
2282 key_mem_available = key_count * 6;
2283 else
2284 key_mem_available = MIN((PM3_CMD_DATA_SIZE - 5), key_count * 6);
2286 key_count = key_mem_available / 6;
2288 datain += 5;
2290 LEDsoff();
2291 LED_A_ON();
2293 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2295 if (clearTrace)
2296 clear_trace();
2298 int oldbg = g_dbglevel;
2299 g_dbglevel = DBG_NONE;
2301 set_tracing(false);
2303 for (uint16_t i = 0; i < key_count; i++) {
2305 // Iceman: use piwi's faster nonce collecting part in hardnested.
2306 if (have_uid == false) { // need a full select cycle to get the uid first
2307 iso14a_card_select_t card_info;
2308 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == false) {
2309 if (g_dbglevel >= DBG_ERROR) Dbprintf("ChkKeys: Can't select card (ALL)");
2310 --i; // try same key once again
2311 continue;
2313 switch (card_info.uidlen) {
2314 case 4 :
2315 cascade_levels = 1;
2316 break;
2317 case 7 :
2318 cascade_levels = 2;
2319 break;
2320 case 10:
2321 cascade_levels = 3;
2322 break;
2323 default:
2324 break;
2326 have_uid = true;
2327 } else { // no need for anticollision. We can directly select the card
2328 if (iso14443a_select_card(uid, NULL, NULL, false, cascade_levels, true) == false) {
2329 if (g_dbglevel >= DBG_ERROR) Dbprintf("ChkKeys: Can't select card (UID)");
2330 --i; // try same key once again
2331 continue;
2335 key = bytes_to_num(datain + i * 6, 6);
2336 if (mifare_classic_auth(pcs, cuid, blockNo, keyType, key, AUTH_FIRST)) {
2337 // CHK_TIMEOUT();
2338 continue;
2341 memcpy(keyresult.key, datain + i * 6, 6);
2342 keyresult.found = true;
2343 break;
2346 LED_B_ON();
2347 crypto1_deinit(pcs);
2349 reply_ng(CMD_HF_MIFARE_CHKKEYS, PM3_SUCCESS, (uint8_t *)&keyresult, sizeof(keyresult));
2350 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2351 LEDsoff();
2352 set_tracing(false);
2353 g_dbglevel = oldbg;
2356 void MifareChkKeys_file(uint8_t *fn) {
2358 #ifdef WITH_FLASH
2359 BigBuf_free();
2361 SpinOff(0);
2363 int changed = rdv40_spiffs_lazy_mount();
2364 uint32_t size = size_in_spiffs((char *)fn);
2365 uint8_t *mem = BigBuf_malloc(size);
2367 rdv40_spiffs_read_as_filetype((char *)fn, mem, size, RDV40_SPIFFS_SAFETY_SAFE);
2369 if (changed) {
2370 rdv40_spiffs_lazy_unmount();
2373 SpinOff(0);
2375 MifareChkKeys(mem, true);
2377 BigBuf_free();
2378 #endif
2381 //-----------------------------------------------------------------------------
2382 // MIFARE Personalize UID. Only for Mifare Classic EV1 7Byte UID
2383 //-----------------------------------------------------------------------------
2384 void MifarePersonalizeUID(uint8_t keyType, uint8_t perso_option, uint64_t key) {
2386 uint16_t isOK = PM3_EUNDEF;
2387 uint8_t uid[10];
2388 uint32_t cuid;
2389 struct Crypto1State mpcs = {0, 0};
2390 struct Crypto1State *pcs;
2391 pcs = &mpcs;
2393 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2394 clear_trace();
2395 set_tracing(true);
2397 LED_A_ON();
2399 while (true) {
2400 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
2401 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
2402 break;
2405 uint8_t block_number = 0;
2406 if (mifare_classic_auth(pcs, cuid, block_number, keyType, key, AUTH_FIRST)) {
2407 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
2408 break;
2411 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
2412 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
2413 int len = mifare_sendcmd_short(pcs, true, MIFARE_EV1_PERSONAL_UID, perso_option, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
2414 if (len != 1 || receivedAnswer[0] != CARD_ACK) {
2415 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
2416 break;
2419 if (mifare_classic_halt(pcs)) {
2420 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
2421 break;
2423 isOK = PM3_SUCCESS;
2424 break;
2427 crypto1_deinit(pcs);
2429 LED_B_ON();
2430 reply_ng(CMD_HF_MIFARE_PERSONALIZE_UID, isOK, NULL, 0);
2431 LED_B_OFF();
2433 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2434 LEDsoff();
2438 //-----------------------------------------------------------------------------
2439 // Work with emulator memory
2441 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
2442 // involved in dealing with emulator memory. But if it is called later, it might
2443 // destroy the Emulator Memory.
2444 //-----------------------------------------------------------------------------
2446 void MifareEMemClr(void) {
2447 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
2448 emlClearMem();
2451 void MifareEMemGet(uint8_t blockno, uint8_t blockcnt) {
2452 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
2455 size_t size = blockcnt * 16;
2456 if (size > PM3_CMD_DATA_SIZE) {
2457 reply_ng(CMD_HF_MIFARE_EML_MEMGET, PM3_EMALLOC, NULL, 0);
2458 return;
2461 uint8_t *buf = BigBuf_malloc(size);
2463 emlGetMem(buf, blockno, blockcnt); // data, block num, blocks count (max 4)
2465 LED_B_ON();
2466 reply_ng(CMD_HF_MIFARE_EML_MEMGET, PM3_SUCCESS, buf, size);
2467 LED_B_OFF();
2468 BigBuf_free_keep_EM();
2471 //-----------------------------------------------------------------------------
2472 // Load a card into the emulator memory
2474 //-----------------------------------------------------------------------------
2475 int MifareECardLoadExt(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) {
2476 int retval = MifareECardLoad(sectorcnt, keytype, key);
2477 reply_ng(CMD_HF_MIFARE_EML_LOAD, retval, NULL, 0);
2478 return retval;
2481 int MifareECardLoad(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) {
2482 if ((keytype > MF_KEY_B) && (key == NULL)) {
2483 if (g_dbglevel >= DBG_ERROR) {
2484 Dbprintf("Error, missing key");
2486 return PM3_EINVARG;
2488 LED_A_ON();
2489 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2491 clear_trace();
2492 set_tracing(true);
2494 // variables
2495 bool have_uid = false;
2496 bool bd_authenticated = false;
2497 uint8_t cascade_levels = 0;
2498 uint32_t cuid = 0;
2499 uint8_t uid[10] = {0x00};
2500 struct Crypto1State mpcs = {0, 0};
2501 struct Crypto1State *pcs;
2502 pcs = &mpcs;
2504 int retval = PM3_SUCCESS;
2506 // increase time-out. Magic card etc are slow
2507 uint32_t timeout = iso14a_get_timeout();
2508 // frame waiting time (FWT) in 1/fc
2509 uint32_t fwt = 256 * 16 * (1 << 6);
2510 iso14a_set_timeout(fwt / (8 * 16));
2512 for (uint8_t s = 0; s < sectorcnt; s++) {
2514 uint64_t ui64Key = emlGetKey(s, keytype);
2516 // MIFARE Classic 1K Ev1 , MIFARE Classic MINI Ev1
2517 if (sectorcnt == 18) {
2518 // MFC 1K EV1, skip sector 16 since its lockdown
2519 if (s == 16) {
2520 // unknown sector trailer, keep the keys, set only the AC
2521 uint8_t st[16] = {0x00};
2522 emlGetMem(st, FirstBlockOfSector(s) + 3, 1);
2523 memcpy(st + 6, "\x70\xF0\xF8\x69", 4);
2524 emlSetMem_xt(st, FirstBlockOfSector(s) + 3, 1, 16);
2525 continue;
2528 // ICEMAN: ugly hack, we don't want to trigger the partial load message
2529 // MFC 1K EV1 sector 17 don't use key A.
2530 // not mention we don't save signatures in our MFC dump files.
2531 if (s == 17 && keytype == MF_KEY_A) {
2532 ui64Key = 0x4B791BEA7BCC;
2533 keytype = 1;
2537 // use fast select
2538 if (have_uid == false) { // need a full select cycle to get the uid first
2539 iso14a_card_select_t card_info;
2540 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) {
2541 if (s == 0) {
2542 // first attempt, if no card let's stop directly
2543 retval = PM3_EFAILED;
2544 if (g_dbglevel >= DBG_ERROR) {
2545 Dbprintf("Card not found");
2547 goto out;
2549 continue;
2552 switch (card_info.uidlen) {
2553 case 4 :
2554 cascade_levels = 1;
2555 break;
2556 case 7 :
2557 cascade_levels = 2;
2558 break;
2559 case 10:
2560 cascade_levels = 3;
2561 break;
2562 default:
2563 break;
2565 have_uid = true;
2566 } else { // no need for anticollision. We can directly select the card
2567 if (!bd_authenticated) { // no need to select if bd_authenticated with backdoor
2568 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
2569 continue;
2574 // Auth
2575 if (keytype > MF_KEY_B) {
2576 if (! bd_authenticated) {
2577 ui64Key = bytes_to_num(key, 6);
2578 if (mifare_classic_auth(pcs, cuid, 0, keytype, ui64Key, AUTH_FIRST)) {
2579 retval = PM3_EFAILED;
2580 if (g_dbglevel >= DBG_ERROR) {
2581 Dbprintf("Auth error");
2583 goto out;
2585 bd_authenticated = true;
2587 } else if (mifare_classic_auth(pcs, cuid, FirstBlockOfSector(s), keytype, ui64Key, AUTH_FIRST)) {
2589 ui64Key = emlGetKey(s, MF_KEY_B);
2591 if (mifare_classic_auth(pcs, cuid, FirstBlockOfSector(s), MF_KEY_B, ui64Key, AUTH_FIRST)) {
2592 retval = PM3_EPARTIAL;
2593 if (g_dbglevel >= DBG_ERROR) {
2594 Dbprintf("Sector %2d - Auth error", s);
2596 continue;
2601 #define MAX_RETRIES 2
2603 uint8_t data[16] = {0x00};
2604 for (uint8_t b = 0; b < NumBlocksPerSector(s); b++) {
2606 memset(data, 0x00, sizeof(data));
2607 uint8_t tb = FirstBlockOfSector(s) + b;
2608 uint8_t r = 0;
2609 for (; r < MAX_RETRIES; r++) {
2611 int res = mifare_classic_readblock(pcs, tb, data);
2612 if (res == 1) {
2613 retval |= PM3_EPARTIAL;
2614 if (g_dbglevel >= DBG_ERROR) {
2615 Dbprintf("Error No rights reading sector %2d block %2d", s, b);
2617 break;
2619 // retry if wrong len.
2620 if (res != 0) {
2621 continue;
2624 // No need to copy empty
2625 if (memcmp(data, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16) == 0) {
2626 break;
2629 if (IsSectorTrailer(b)) {
2630 // sector trailer, keep the keys, set only the AC
2631 uint8_t st[16] = {0x00};
2632 emlGetMem(st, tb, 1);
2633 memcpy(st + 6, data + 6, 4);
2634 emlSetMem_xt(st, tb, 1, 16);
2635 } else {
2636 emlSetMem_xt(data, tb, 1, 16);
2638 break;
2641 // if we failed all retries, notify client
2642 if (r == MAX_RETRIES) {
2643 retval |= PM3_EPARTIAL;
2647 int res;
2648 out:
2649 res = mifare_classic_halt(pcs);
2650 (void)res;
2652 iso14a_set_timeout(timeout);
2653 crypto1_deinit(pcs);
2654 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2655 LEDsoff();
2656 set_tracing(false);
2657 return retval;
2662 //-----------------------------------------------------------------------------
2663 // Work with "magic Chinese" card (email him: ouyangweidaxian@live.cn)
2665 // PARAMS - workFlags
2666 // bit 0 - need get UID
2667 // bit 1 - need wupC
2668 // bit 2 - need HALT after sequence
2669 // bit 3 - need turn on FPGA before sequence
2670 // bit 4 - need turn off FPGA
2671 // bit 5 - need to set datain instead of issuing USB reply (called via ARM for StandAloneMode14a)
2672 // bit 6 - wipe tag.
2673 // bit 7 - use USCUID/GDM (20/23) magic wakeup
2674 //-----------------------------------------------------------------------------
2676 void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) {
2678 // params
2679 uint8_t workFlags = arg0;
2680 uint8_t blockNo = arg1;
2682 // detect 1a/1b
2683 bool is1b = false;
2685 // variables
2686 bool isOK = false; //assume we will get an error
2687 uint8_t errormsg = 0x00;
2688 uint8_t uid[10] = {0x00};
2689 uint8_t data[18] = {0x00};
2690 uint32_t cuid = 0;
2692 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
2693 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
2695 if (workFlags & MAGIC_INIT) {
2696 LED_A_ON();
2697 LED_B_OFF();
2698 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2699 clear_trace();
2700 set_tracing(true);
2703 //loop doesn't loop just breaks out if error
2704 while (true) {
2705 // read UID and return to client with write
2706 if (workFlags & MAGIC_UID) {
2707 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
2708 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
2709 errormsg = MAGIC_UID;
2710 mifare_classic_halt(NULL);
2711 break;
2713 mifare_classic_halt(NULL);
2716 // wipe tag, fill it with zeros
2717 if (workFlags & MAGIC_WIPE) {
2718 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2719 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2720 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupC1 error");
2721 errormsg = MAGIC_WIPE;
2722 break;
2725 uint32_t old_timeout = iso14a_get_timeout();
2727 // 2000 ms timeout
2728 // 13560000 / 1000 / (8 * 16) * timeout
2729 iso14a_set_timeout(21190);
2731 ReaderTransmit(wipeC, sizeof(wipeC), NULL);
2732 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2733 if (g_dbglevel >= DBG_ERROR) Dbprintf("wipeC error");
2734 errormsg = MAGIC_WIPE;
2735 break;
2737 iso14a_set_timeout(old_timeout);
2739 mifare_classic_halt(NULL);
2742 if (workFlags & MAGIC_GDM_ALT_WUPC) {
2743 ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL);
2744 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2745 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM1 error");
2746 errormsg = MAGIC_WUPC;
2747 break;
2750 ReaderTransmit(wupGDM2, sizeof(wupC2), NULL);
2751 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2752 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM2 error");
2753 errormsg = MAGIC_WUPC;
2754 break;
2758 // write block
2759 if (workFlags & MAGIC_WUPC) {
2760 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2761 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2762 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupC1 error");
2763 errormsg = MAGIC_WUPC;
2764 break;
2767 if (!is1b) {
2768 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2769 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2770 if (g_dbglevel >= DBG_INFO) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2771 is1b = true;
2772 continue;
2777 if ((mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_WRITEBLOCK, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL) != 1) || (receivedAnswer[0] != 0x0a)) {
2778 if (g_dbglevel >= DBG_ERROR) Dbprintf("write block send command error");
2779 errormsg = 4;
2780 break;
2783 memcpy(data, datain, 16);
2784 AddCrc14A(data, 16);
2786 ReaderTransmit(data, sizeof(data), NULL);
2787 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) != 1) || (receivedAnswer[0] != 0x0a)) {
2788 if (g_dbglevel >= DBG_ERROR) Dbprintf("write block send data error");
2789 errormsg = 0;
2790 break;
2793 if (workFlags & MAGIC_HALT) {
2794 mifare_classic_halt(NULL);
2797 isOK = true;
2798 break;
2800 } // end while
2802 if (isOK)
2803 reply_mix(CMD_ACK, 1, 0, 0, uid, sizeof(uid));
2804 else
2805 OnErrorMagic(errormsg);
2807 if (workFlags & MAGIC_OFF)
2808 OnSuccessMagic();
2811 void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) {
2813 uint8_t workFlags = arg0;
2814 uint8_t blockNo = arg1;
2815 uint8_t errormsg = 0x00;
2816 bool isOK = false; //assume we will get an error
2818 // detect 1a/1b
2819 bool is1b = false;
2821 // variables
2822 uint8_t data[MAX_MIFARE_FRAME_SIZE];
2823 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
2824 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
2826 memset(data, 0x00, sizeof(data));
2828 if (workFlags & MAGIC_INIT) {
2829 LED_A_ON();
2830 LED_B_OFF();
2831 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2832 clear_trace();
2833 set_tracing(true);
2836 // increase time-out. Magic card etc are slow
2837 uint32_t timeout = iso14a_get_timeout();
2838 // frame waiting time (FWT) in 1/fc
2839 uint32_t fwt = 256 * 16 * (1 << 7);
2840 iso14a_set_timeout(fwt / (8 * 16));
2842 //loop doesn't loop just breaks out if error or done
2843 while (true) {
2844 if (workFlags & MAGIC_GDM_ALT_WUPC) {
2845 ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL);
2846 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2847 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM1 error");
2848 errormsg = MAGIC_WUPC;
2849 break;
2852 ReaderTransmit(wupGDM2, sizeof(wupC2), NULL);
2853 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2854 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM2 error");
2855 errormsg = MAGIC_WUPC;
2856 break;
2860 if (workFlags & MAGIC_WUPC) {
2861 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2862 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2863 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupC1 error");
2864 errormsg = MAGIC_WUPC;
2865 break;
2868 if (is1b == false) {
2869 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2870 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2871 if (g_dbglevel >= DBG_INFO) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2872 is1b = true;
2873 continue;
2878 // read block
2879 if ((mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_READBLOCK, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL) != MAX_MIFARE_FRAME_SIZE)) {
2880 if (g_dbglevel >= DBG_ERROR) Dbprintf("read block send command error");
2881 errormsg = 0;
2882 break;
2885 memcpy(data, receivedAnswer, sizeof(data));
2887 // send HALT
2888 if (workFlags & MAGIC_HALT) {
2889 mifare_classic_halt(NULL);
2892 isOK = true;
2893 break;
2895 // if MAGIC_DATAIN, the data stays on device side.
2896 if (workFlags & MAGIC_DATAIN) {
2897 if (isOK) {
2898 memcpy(datain, data, sizeof(data));
2900 } else {
2901 if (isOK) {
2902 reply_old(CMD_ACK, 1, 0, 0, data, sizeof(data));
2903 } else {
2904 OnErrorMagic(errormsg);
2908 if (workFlags & MAGIC_OFF) {
2909 OnSuccessMagic();
2912 iso14a_set_timeout(timeout);
2915 static void mf_reset_card(void) {
2916 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2917 SpinDelay(40);
2918 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2921 void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) {
2922 // variables
2923 uint8_t rec[1] = {0x00};
2924 uint8_t recpar[1] = {0x00};
2925 uint8_t rats[4] = {ISO14443A_CMD_RATS, 0x80, 0x31, 0x73};
2926 uint8_t rdblf0[4] = {ISO14443A_CMD_READBLOCK, 0xF0, 0x8D, 0x5f};
2927 uint8_t rdbl00[4] = {ISO14443A_CMD_READBLOCK, 0x00, 0x02, 0xa8};
2928 uint8_t gen4gdmAuth[4] = {MIFARE_MAGIC_GDM_AUTH_KEY, 0x00, 0x6C, 0x92};
2929 uint8_t gen4gdmGetConf[4] = {MIFARE_MAGIC_GDM_READ_CFG, 0x00, 0x39, 0xF7};
2930 uint8_t gen4gdmGetMagicBlock[4] = {MIFARE_MAGIC_GDM_READBLOCK, 0x00, 0xC2, 0x66};
2931 uint8_t gen4GetConf[8] = {GEN_4GTU_CMD, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_GETCNF, 0, 0};
2932 uint8_t superGen1[9] = {0x0A, 0x00, 0x00, 0xA6, 0xB0, 0x00, 0x10, 0x14, 0x1D};
2933 bool isGen2 = false;
2935 uint8_t *par = BigBuf_calloc(MAX_PARITY_SIZE);
2936 uint8_t *buf = BigBuf_calloc(PM3_CMD_DATA_SIZE);
2937 uint8_t *uid = BigBuf_calloc(10);
2938 uint16_t flag = MAGIC_FLAG_NONE;
2939 uint32_t cuid = 0;
2940 int res = 0;
2942 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2944 // Generation 1 test
2945 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2946 if (ReaderReceive(rec, 1, recpar) && (rec[0] == 0x0A)) {
2948 flag = MAGIC_FLAG_GEN_1A;
2949 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2950 uint16_t tmp = ReaderReceive(rec, 1, recpar);
2951 if ((tmp && (rec[0] != 0x0A)) || (tmp == 0)) {
2952 flag = MAGIC_FLAG_GEN_1B;
2955 // check for GDM config
2956 ReaderTransmit(gen4gdmGetConf, sizeof(gen4gdmGetConf), NULL);
2957 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2958 if (res > 1) {
2959 // could be ZUID or full USCUID, the magic blocks don't exist on ZUID so
2960 // a failure here indicates a feature limited chip like ZUID
2961 // check for GDM hidden block read
2962 ReaderTransmit(gen4gdmGetMagicBlock, sizeof(gen4gdmGetMagicBlock), NULL);
2963 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2964 if (res > 1) {
2965 flag |= MAGIC_FLAG_GDM_WUP_40;
2966 } else {
2967 flag |= MAGIC_FLAG_GDM_WUP_40_ZUID;
2972 mf_reset_card();
2974 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2975 if (res) {
2976 // Check for Magic Gen4 GTU with default password:
2977 // Get config should return 30 or 32 bytes
2978 AddCrc14A(gen4GetConf, sizeof(gen4GetConf) - 2);
2979 ReaderTransmit(gen4GetConf, sizeof(gen4GetConf), NULL);
2980 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2981 if (res == 32 || res == 34) {
2982 flag |= MAGIC_FLAG_GEN_4GTU;
2986 // reset card
2987 mf_reset_card();
2989 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, false);
2990 if (res) {
2991 if (cuid == 0xAA55C396) {
2992 flag |= MAGIC_FLAG_GEN_UNFUSED;
2995 ReaderTransmit(rats, sizeof(rats), NULL);
2996 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2998 if (res) {
2999 if (memcmp(buf, "\x09\x78\x00\x91\x02\xDA\xBC\x19\x10", 9) == 0) {
3000 // test for some MFC gen2
3001 isGen2 = true;
3002 flag |= MAGIC_FLAG_GEN_2;
3003 } else if (memcmp(buf, "\x0D\x78\x00\x71\x02\x88\x49\xA1\x30\x20\x15\x06\x08\x56\x3D", 15) == 0) {
3004 // test for some MFC 7b gen2
3005 isGen2 = true;
3006 flag |= MAGIC_FLAG_GEN_2;
3007 } else if (memcmp(buf, "\x0A\x78\x00\x81\x02\xDB\xA0\xC1\x19\x40\x2A\xB5", 12) == 0) {
3008 // test for Ultralight magic gen2
3009 isGen2 = true;
3010 flag |= MAGIC_FLAG_GEN_2;
3011 } else if (memcmp(buf, "\x85\x00\x00\xA0\x00\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x41\xDF", 18) == 0) {
3012 // test for Ultralight EV1 magic gen2
3013 isGen2 = true;
3014 flag |= MAGIC_FLAG_GEN_2;
3015 } else if (memcmp(buf, "\x85\x00\x00\xA0\x0A\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x16\xD7", 18) == 0) {
3016 // test for some other Ultralight EV1 magic gen2
3017 isGen2 = true;
3018 flag |= MAGIC_FLAG_GEN_2;
3019 } else if (memcmp(buf, "\x85\x00\x00\xA0\x0A\x00\x0A\xB0\x00\x00\x00\x00\x00\x00\x00\x00\x18\x4D", 18) == 0) {
3020 // test for some other Ultralight magic gen2
3021 isGen2 = true;
3022 flag |= MAGIC_FLAG_GEN_2;
3023 } else if (memcmp(buf, "\x85\x00\x00\xA0\x00\x00\x0A\xA5\x00\x04\x04\x02\x01\x00\x0F\x03\x79\x0C", 18) == 0) {
3024 // test for NTAG213 magic gen2
3025 isGen2 = true;
3026 flag |= MAGIC_FLAG_GEN_2;
3029 // test for super card
3030 ReaderTransmit(superGen1, sizeof(superGen1), NULL);
3031 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3032 if (res == 22) {
3033 uint8_t isGen = MAGIC_FLAG_SUPER_GEN1;
3035 // check for super card gen2
3036 // not available after RATS, reset card before executing
3037 mf_reset_card();
3039 iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
3040 ReaderTransmit(rdbl00, sizeof(rdbl00), NULL);
3041 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3042 if (res == 18) {
3043 isGen = MAGIC_FLAG_SUPER_GEN2;
3046 flag |= isGen;
3050 if (is_mfc == false) {
3051 // magic ntag test
3052 mf_reset_card();
3054 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
3055 if (res == 2) {
3056 ReaderTransmit(rdblf0, sizeof(rdblf0), NULL);
3057 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3058 if (res == 18) {
3059 flag |= MAGIC_FLAG_NTAG21X;
3062 } else {
3064 struct Crypto1State mpcs = {0, 0};
3065 struct Crypto1State *pcs;
3066 pcs = &mpcs;
3068 // CUID (with default sector 0 B key) test
3069 // regular cards will NAK the WRITEBLOCK(0) command, while DirectWrite will ACK it
3070 // if we do get an ACK, we immediately abort to ensure nothing is ever actually written
3071 // only perform test if we haven't already identified Gen2. No need test if we have a positive identification already
3072 if (isGen2 == false) {
3073 mf_reset_card();
3075 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
3076 if (res) {
3078 uint64_t tmpkey = bytes_to_num(key, 6);
3079 if (mifare_classic_authex(pcs, cuid, 0, keytype, tmpkey, AUTH_FIRST, NULL, NULL) == 0) {
3081 if ((mifare_sendcmd_short(pcs, 1, ISO14443A_CMD_WRITEBLOCK, 0, buf, PM3_CMD_DATA_SIZE, par, NULL) == 1) && (buf[0] == 0x0A)) {
3082 flag |= MAGIC_FLAG_GEN_2;
3083 // turn off immediately to ensure nothing ever accidentally writes to the block
3084 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3087 crypto1_deinit(pcs);
3091 // magic MFC Gen3 test 1
3092 mf_reset_card();
3094 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
3095 if (res) {
3096 ReaderTransmit(rdbl00, sizeof(rdbl00), NULL);
3097 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3098 if (res == 18) {
3099 flag |= MAGIC_FLAG_GEN_3;
3103 // magic MFC Gen4 GDM magic auth test
3104 mf_reset_card();
3106 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
3107 if (res) {
3108 ReaderTransmit(gen4gdmAuth, sizeof(gen4gdmAuth), NULL);
3109 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3110 if (res == 4) {
3111 flag |= MAGIC_FLAG_GDM_AUTH;
3115 // QL88 test
3116 mf_reset_card();
3118 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
3119 if (res) {
3120 if (mifare_classic_authex(pcs, cuid, 68, MF_KEY_B, 0x707B11FC1481, AUTH_FIRST, NULL, NULL) == 0) {
3121 flag |= MAGIC_FLAG_QL88;
3123 crypto1_deinit(pcs);
3128 // GDM alt magic wakeup (20)
3129 ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL);
3130 if (ReaderReceive(rec, 1, recpar) && (rec[0] == 0x0a)) {
3131 flag |= MAGIC_FLAG_GDM_WUP_20;
3134 reply_ng(CMD_HF_MIFARE_CIDENT, PM3_SUCCESS, (uint8_t *)&flag, sizeof(uint16_t));
3135 // turns off
3136 OnSuccessMagic();
3137 BigBuf_free();
3140 void MifareHasStaticNonce(void) {
3142 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3144 // variables
3145 int retval = PM3_SUCCESS;
3146 uint32_t nt = 0;
3147 uint8_t *uid = BigBuf_malloc(10);
3149 memset(uid, 0x00, 10);
3151 uint8_t data[1] = { NONCE_FAIL };
3152 struct Crypto1State mpcs = {0, 0};
3153 struct Crypto1State *pcs;
3154 pcs = &mpcs;
3156 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3158 uint8_t counter = 0;
3159 for (uint8_t i = 0; i < 3; i++) {
3161 if (!iso14443a_select_card(uid, NULL, NULL, true, 0, true)) {
3162 retval = PM3_ESOFT;
3163 goto OUT;
3166 uint8_t rec[4] = {0x00};
3167 uint8_t recpar[1] = {0x00};
3168 // Transmit MIFARE_CLASSIC_AUTH 0x60, block 0
3169 int len = mifare_sendcmd_short(pcs, false, MIFARE_AUTH_KEYA, 0, rec, sizeof(rec), recpar, NULL);
3170 if (len != 4) {
3171 retval = PM3_ESOFT;
3172 goto OUT;
3175 // Save the tag nonce (nt)
3176 if (nt == bytes_to_num(rec, 4)) {
3177 counter++;
3180 nt = bytes_to_num(rec, 4);
3182 // some cards with static nonce need to be reset before next query
3183 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3184 LEDsoff();
3185 CHK_TIMEOUT();
3187 memset(rec, 0x00, sizeof(rec));
3190 if (counter) {
3191 Dbprintf("Static nonce......... " _YELLOW_("%08x"), nt);
3192 data[0] = NONCE_STATIC;
3193 } else {
3194 data[0] = NONCE_NORMAL;
3197 OUT:
3198 reply_ng(CMD_HF_MIFARE_STATIC_NONCE, retval, data, sizeof(data));
3199 // turns off
3200 OnSuccessMagic();
3201 BigBuf_free();
3202 crypto1_deinit(pcs);
3205 // FUDAN card w static encrypted nonces
3206 // 2B F9 1C 1B D5 08 48 48 03 A4 B1 B1 75 FF 2D 90
3207 // ^^ ^^
3209 void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t *key, uint8_t block_no_nested, uint8_t key_type_nested, uint8_t *key_nested, uint8_t nr_nested, bool reset, bool hardreset, bool addread, bool addauth, bool incblk2, bool corruptnrar, bool corruptnrarparity) {
3210 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3212 LEDsoff();
3213 clear_trace();
3214 set_tracing(true);
3216 int retval = PM3_SUCCESS;
3218 uint8_t data[14] = { NONCE_FAIL };
3220 struct Crypto1State mpcs = {0, 0};
3221 struct Crypto1State *pcs;
3222 pcs = &mpcs;
3224 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3226 uint8_t first_nt_counter = 0;
3227 uint8_t first_nt_repetition_counter = 0;
3228 uint8_t nested_nt_session_counter = 0;
3229 uint8_t nested_nt_repetition_counter = 0;
3230 uint8_t first_and_nested_nt_repetition_counter = 0;
3231 uint8_t key_auth_cmd = MIFARE_AUTH_KEYA + key_type;
3232 uint8_t key_auth_cmd_nested = MIFARE_AUTH_KEYA + key_type_nested;
3233 uint64_t ui64key = bytes_to_num(key, 6);
3234 uint64_t ui64key_nested = bytes_to_num(key_nested, 6);
3235 uint32_t oldntenc = 0;
3236 bool need_first_auth = true;
3237 uint32_t cuid = 0;
3238 uint32_t nt = 0;
3239 uint32_t old_nt = 0;
3240 uint32_t nt_first = 0;
3241 uint32_t old_nt_first = 0;
3242 uint32_t ntenc = 0;
3243 uint8_t ntencpar = 0;
3244 bool is_last_auth_first_auth = true;
3245 if (nr_nested == 0) {
3246 cuid = 0;
3247 if (iso14443a_select_card(NULL, NULL, &cuid, true, 0, true) == false) {
3248 if (g_dbglevel >= DBG_ERROR) Dbprintf("Select error");
3249 retval = PM3_ESOFT;
3250 goto OUT;
3252 if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &nt, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) {
3253 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
3254 retval = PM3_ESOFT;
3255 goto OUT;
3257 first_nt_counter++;
3258 } else {
3259 for (uint8_t i = 0; i < nr_nested; i++) {
3260 if (need_first_auth) {
3261 cuid = 0;
3263 if (hardreset) {
3264 if (g_dbglevel >= DBG_EXTENDED) {
3265 Dbprintf("RF reset");
3267 // some cards need longer than mf_reset_card() to see effect on nT
3268 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3269 SpinDelay(150);
3270 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3272 if (g_dbglevel >= DBG_EXTENDED) {
3273 Dbprintf("select");
3275 if (iso14443a_select_card(NULL, NULL, &cuid, true, 0, true) == false) {
3276 retval = PM3_ESOFT;
3277 goto OUT;
3279 if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &nt_first, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) {
3280 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
3281 retval = PM3_ESOFT;
3282 goto OUT;
3284 is_last_auth_first_auth = true;
3285 first_nt_counter++;
3286 if ((first_nt_counter > 1) && (old_nt_first == nt_first)) {
3287 first_nt_repetition_counter++;
3289 old_nt_first = nt_first;
3290 if (!reset && !hardreset) {
3291 need_first_auth = false;
3293 if (addread) {
3294 uint8_t dataread[16] = {0x00};
3295 mifare_classic_readblock(pcs, block_no, dataread);
3297 if (addauth) {
3298 if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_NESTED, &nt, NULL, NULL, NULL, false, false)) {
3299 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
3300 retval = PM3_ESOFT;
3301 goto OUT;
3302 } else if (g_dbglevel >= DBG_EXTENDED) {
3303 Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first, nt));
3305 is_last_auth_first_auth = false;
3306 if (nt == nt_first) {
3307 first_and_nested_nt_repetition_counter++;
3309 old_nt = nt;
3313 nt = 0;
3314 ntenc = 0;
3315 if (mifare_classic_authex_cmd(pcs, cuid, incblk2 ? block_no_nested + (i * 4) : block_no_nested, key_auth_cmd_nested, ui64key_nested, AUTH_NESTED, &nt, &ntenc, &ntencpar, NULL, false, false)) {
3316 if (g_dbglevel >= DBG_ERROR) Dbprintf("Nested auth error");
3317 need_first_auth = true;
3318 } else if (g_dbglevel >= DBG_EXTENDED) {
3319 if (is_last_auth_first_auth) {
3320 Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first, nt));
3321 } else {
3322 Dbprintf("Nonce distance: %5i", nonce_distance(old_nt, nt));
3325 nested_nt_session_counter++;
3326 is_last_auth_first_auth = false;
3327 old_nt = nt;
3328 if (nt == nt_first) {
3329 first_and_nested_nt_repetition_counter++;
3331 if ((nested_nt_session_counter > 1) && (oldntenc == ntenc)) {
3332 nested_nt_repetition_counter++;
3334 oldntenc = ntenc;
3338 data[1] = (cuid >> 24) & 0xFF;
3339 data[2] = (cuid >> 16) & 0xFF;
3340 data[3] = (cuid >> 8) & 0xFF;
3341 data[4] = (cuid >> 0) & 0xFF;
3342 if (first_and_nested_nt_repetition_counter) {
3343 data[0] = NONCE_SUPERSTATIC;
3344 data[5] = (nt >> 24) & 0xFF;
3345 data[6] = (nt >> 16) & 0xFF;
3346 data[7] = (nt >> 8) & 0xFF;
3347 data[8] = (nt >> 0) & 0xFF;
3348 } else if (first_nt_repetition_counter) {
3349 data[0] = NONCE_STATIC;
3350 data[5] = (nt_first >> 24) & 0xFF;
3351 data[6] = (nt_first >> 16) & 0xFF;
3352 data[7] = (nt_first >> 8) & 0xFF;
3353 data[8] = (nt_first >> 0) & 0xFF;
3354 } else if (nested_nt_repetition_counter) {
3355 data[0] = NONCE_STATIC_ENC;
3356 data[5] = (nt >> 24) & 0xFF;
3357 data[6] = (nt >> 16) & 0xFF;
3358 data[7] = (nt >> 8) & 0xFF;
3359 data[8] = (nt >> 0) & 0xFF;
3360 data[9] = (ntenc >> 24) & 0xFF;
3361 data[10] = (ntenc >> 16) & 0xFF;
3362 data[11] = (ntenc >> 8) & 0xFF;
3363 data[12] = (ntenc >> 0) & 0xFF;
3364 data[13] = ntencpar;
3365 } else {
3366 data[0] = NONCE_NORMAL;
3367 data[5] = (nt >> 24) & 0xFF;
3368 data[6] = (nt >> 16) & 0xFF;
3369 data[7] = (nt >> 8) & 0xFF;
3370 data[8] = (nt >> 0) & 0xFF;
3371 data[9] = (ntenc >> 24) & 0xFF;
3372 data[10] = (ntenc >> 16) & 0xFF;
3373 data[11] = (ntenc >> 8) & 0xFF;
3374 data[12] = (ntenc >> 0) & 0xFF;
3375 data[13] = ntencpar;
3378 OUT:
3379 crypto1_deinit(pcs);
3381 reply_ng(CMD_HF_MIFARE_STATIC_ENCRYPTED_NONCE, retval, data, sizeof(data));
3382 // turns off
3383 OnSuccessMagic();
3384 BigBuf_free();
3387 void OnSuccessMagic(void) {
3388 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3389 LEDsoff();
3390 set_tracing(false);
3393 void OnErrorMagic(uint8_t reason) {
3394 // ACK, ISOK, reason,0,0,0
3395 reply_mix(CMD_ACK, 0, reason, 0, 0, 0);
3396 OnSuccessMagic();
3399 int DoGen3Cmd(uint8_t *cmd, uint8_t cmd_len) {
3400 int retval = PM3_SUCCESS;
3401 uint8_t *par = BigBuf_calloc(MAX_PARITY_SIZE);
3402 uint8_t *buf = BigBuf_calloc(PM3_CMD_DATA_SIZE);
3404 LED_B_ON();
3405 uint32_t save_iso14a_timeout = iso14a_get_timeout();
3406 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 2000); // 2 seconds timeout
3408 ReaderTransmit(cmd, cmd_len, NULL);
3409 int res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3410 if (res == 4 && memcmp(buf, "\x90\x00\xfd\x07", 4) == 0) {
3411 // timeout for card memory reset
3412 SpinDelay(1000);
3413 } else {
3414 if (g_dbglevel >= DBG_ERROR) Dbprintf("Card operation not completed");
3415 retval = PM3_ESOFT;
3417 iso14a_set_timeout(save_iso14a_timeout);
3418 LED_B_OFF();
3419 return retval;
3422 void MifareGen3UID(uint8_t uidlen, uint8_t *uid) {
3423 int retval = PM3_SUCCESS;
3424 uint8_t uid_cmd[5] = { 0x90, 0xfb, 0xcc, 0xcc, 0x07 };
3425 uint8_t *old_uid = BigBuf_calloc(10);
3426 uint8_t *cmd = BigBuf_calloc(sizeof(uid_cmd) + uidlen + 2);
3427 iso14a_card_select_t *card_info = (iso14a_card_select_t *) BigBuf_calloc(sizeof(iso14a_card_select_t));
3429 LEDsoff();
3430 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3431 clear_trace();
3432 set_tracing(true);
3434 if (iso14443a_select_card(old_uid, card_info, NULL, true, 0, true) == false) {
3435 retval = PM3_ESOFT;
3436 goto OUT;
3438 if (card_info->uidlen != uidlen) {
3439 if (g_dbglevel >= DBG_ERROR) Dbprintf("Wrong UID length");
3440 retval = PM3_ESOFT;
3441 goto OUT;
3444 memcpy(cmd, uid_cmd, sizeof(uid_cmd));
3445 memcpy(&cmd[sizeof(uid_cmd)], uid, uidlen);
3446 AddCrc14A(cmd, sizeof(uid_cmd) + uidlen);
3448 retval = DoGen3Cmd(cmd, sizeof(uid_cmd) + uidlen + 2);
3450 OUT:
3451 reply_ng(CMD_HF_MIFARE_GEN3UID, retval, old_uid, uidlen);
3452 // turns off
3453 OnSuccessMagic();
3454 BigBuf_free();
3457 void MifareGen3Blk(uint8_t block_len, uint8_t *block) {
3459 int retval = PM3_SUCCESS;
3460 uint8_t block_cmd[5] = { 0x90, 0xf0, 0xcc, 0xcc, 0x10 };
3461 uint8_t cmdlen = sizeof(block_cmd) + MAX_MIFARE_FRAME_SIZE;
3462 uint8_t *cmd = BigBuf_calloc(cmdlen);
3464 iso14a_card_select_t *card_info = (iso14a_card_select_t *) BigBuf_calloc(sizeof(iso14a_card_select_t));
3466 LEDsoff();
3467 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3468 clear_trace();
3469 set_tracing(true);
3471 if (iso14443a_select_card(NULL, card_info, NULL, true, 0, true) == false) {
3472 retval = PM3_ESOFT;
3473 goto OUT;
3476 bool doReselect = false;
3477 if (block_len < MIFARE_BLOCK_SIZE) {
3478 if ((mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_READBLOCK, 0, &cmd[sizeof(block_cmd)], MAX_MIFARE_FRAME_SIZE, NULL, NULL) != MAX_MIFARE_FRAME_SIZE)) {
3479 if (g_dbglevel >= DBG_ERROR) Dbprintf("Read manufacturer block failed");
3480 retval = PM3_ESOFT;
3481 goto OUT;
3483 doReselect = true;
3486 if (block_len > 0) {
3487 memcpy(cmd, block_cmd, sizeof(block_cmd));
3488 memcpy(&cmd[sizeof(block_cmd)], block, block_len);
3489 int ofs = sizeof(block_cmd);
3490 if (card_info->uidlen == 4) {
3491 cmd[ofs + 4] = cmd[ofs + 0] ^ cmd[ofs + 1] ^ cmd[ofs + 2] ^ cmd[ofs + 3];
3492 ofs += 5;
3493 } else if (card_info->uidlen == 7) {
3494 ofs += 7;
3495 } else {
3496 if (g_dbglevel >= DBG_ERROR) Dbprintf("Wrong Card UID length");
3497 retval = PM3_ESOFT;
3498 goto OUT;
3500 cmd[ofs] = block_len <= card_info->uidlen ? card_info->sak : cmd[ofs];
3501 ofs++;
3502 cmd[ofs++] = card_info->atqa[0];
3503 cmd[ofs++] = card_info->atqa[1];
3504 AddCrc14A(cmd, sizeof(block_cmd) + MIFARE_BLOCK_SIZE);
3506 if (doReselect) {
3507 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
3508 retval = PM3_ESOFT;
3509 goto OUT;
3513 retval = DoGen3Cmd(cmd, sizeof(block_cmd) + MAX_MIFARE_FRAME_SIZE);
3516 OUT:
3517 reply_ng(CMD_HF_MIFARE_GEN3BLK, retval, &cmd[sizeof(block_cmd)], MIFARE_BLOCK_SIZE);
3518 // turns off
3519 OnSuccessMagic();
3520 BigBuf_free();
3523 void MifareGen3Freez(void) {
3525 LEDsoff();
3526 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3527 clear_trace();
3528 set_tracing(true);
3530 int retval = PM3_SUCCESS;
3531 uint8_t freeze_cmd[7] = { 0x90, 0xfd, 0x11, 0x11, 0x00, 0xe7, 0x91 };
3533 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3534 retval = PM3_ESOFT;
3535 goto OUT;
3538 retval = DoGen3Cmd(freeze_cmd, sizeof(freeze_cmd));
3540 OUT:
3541 reply_ng(CMD_HF_MIFARE_GEN3FREEZ, retval, NULL, 0);
3542 // turns off
3543 OnSuccessMagic();
3544 BigBuf_free();
3547 void MifareG4ReadBlk(uint8_t blockno, uint8_t *pwd, uint8_t workFlags) {
3548 bool setup = ((workFlags & MAGIC_INIT) == MAGIC_INIT) ;
3549 bool done = ((workFlags & MAGIC_OFF) == MAGIC_OFF) ;
3551 int res = 0;
3552 int retval = PM3_SUCCESS;
3554 uint8_t *buf = BigBuf_malloc(PM3_CMD_DATA_SIZE);
3555 if (buf == NULL) {
3556 retval = PM3_EMALLOC;
3557 goto OUT;
3560 uint8_t *par = BigBuf_malloc(MAX_PARITY_SIZE);
3561 if (par == NULL) {
3562 retval = PM3_EMALLOC;
3563 goto OUT;
3566 if (setup) {
3567 LEDsoff();
3568 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3569 clear_trace();
3570 set_tracing(true);
3572 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3573 retval = PM3_ESOFT;
3574 goto OUT;
3578 LED_B_ON();
3580 static uint32_t save_iso14a_timeout;
3581 if (setup) {
3582 save_iso14a_timeout = iso14a_get_timeout();
3583 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 1000); // 2 seconds timeout
3586 uint8_t cmd[] = { GEN_4GTU_CMD, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_READ, blockno,
3587 0x00, 0x00
3590 memcpy(cmd + 1, pwd, 4);
3592 AddCrc14A(cmd, sizeof(cmd) - 2);
3594 ReaderTransmit(cmd, sizeof(cmd), NULL);
3595 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3597 if (res != 18) {
3598 retval = PM3_ESOFT;
3601 if (done || retval != 0) {
3602 iso14a_set_timeout(save_iso14a_timeout);
3605 LED_B_OFF();
3607 OUT:
3608 reply_ng(CMD_HF_MIFARE_G4_RDBL, retval, buf, res);
3610 // turns off
3611 if (done || retval != 0) {
3612 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3615 LEDsoff();
3616 if (done || retval != 0) {
3617 set_tracing(false);
3620 BigBuf_free();
3623 void MifareG4WriteBlk(uint8_t blockno, uint8_t *pwd, uint8_t *data, uint8_t workFlags) {
3624 bool setup = ((workFlags & MAGIC_INIT) == MAGIC_INIT) ;
3625 bool done = ((workFlags & MAGIC_OFF) == MAGIC_OFF) ;
3627 int res = 0;
3628 int retval = PM3_SUCCESS;
3630 uint8_t *buf = BigBuf_malloc(PM3_CMD_DATA_SIZE);
3631 if (buf == NULL) {
3632 retval = PM3_EMALLOC;
3633 goto OUT;
3636 // check args
3637 if (data == NULL) {
3638 retval = PM3_EINVARG;
3639 goto OUT;
3642 uint8_t *par = BigBuf_malloc(MAX_PARITY_SIZE);
3643 if (par == NULL) {
3644 retval = PM3_EMALLOC;
3645 goto OUT;
3648 if (setup) {
3649 LEDsoff();
3650 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3651 clear_trace();
3652 set_tracing(true);
3654 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3655 retval = PM3_ESOFT;
3656 goto OUT;
3660 LED_B_ON();
3662 static uint32_t save_iso14a_timeout;
3663 if (setup) {
3664 save_iso14a_timeout = iso14a_get_timeout();
3665 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 1000); // 2 seconds timeout
3668 uint8_t cmd[] = { GEN_4GTU_CMD, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_WRITE, blockno,
3669 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3670 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3671 0x00, 0x00
3674 memcpy(cmd + 1, pwd, 4);
3675 memcpy(cmd + 7, data, 16);
3677 AddCrc14A(cmd, sizeof(cmd) - 2);
3679 ReaderTransmit(cmd, sizeof(cmd), NULL);
3680 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3682 if ((res != 4) || (memcmp(buf, "\x90\x00\xfd\x07", 4) != 0)) {
3683 retval = PM3_ESOFT;
3686 if (done || retval != 0) {
3687 iso14a_set_timeout(save_iso14a_timeout);
3689 LED_B_OFF();
3691 OUT:
3692 reply_ng(CMD_HF_MIFARE_G4_WRBL, retval, buf, res);
3693 // turns off
3694 if (done || retval != 0) {
3695 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3698 LEDsoff();
3699 if (done || retval != 0) {
3700 set_tracing(false);
3703 BigBuf_free();
3706 void MifareSetMod(uint8_t *datain) {
3708 uint8_t mod = datain[0];
3709 uint64_t ui64Key = bytes_to_num(datain + 1, 6);
3711 // variables
3712 uint16_t isOK = PM3_EUNDEF;
3713 uint8_t *uid = BigBuf_calloc(10);
3715 uint32_t cuid = 0;
3716 struct Crypto1State mpcs = {0, 0};
3717 struct Crypto1State *pcs = &mpcs;
3719 uint8_t *buf = BigBuf_calloc(MAX_MIFARE_FRAME_SIZE);
3720 uint8_t *par = BigBuf_calloc(MAX_MIFARE_PARITY_SIZE);
3722 LEDsoff();
3723 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3725 clear_trace();
3726 set_tracing(true);
3728 LED_A_ON();
3730 while (true) {
3731 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
3732 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
3733 break;
3736 if (mifare_classic_auth(pcs, cuid, 0, 0, ui64Key, AUTH_FIRST)) {
3737 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
3738 break;
3741 int respLen;
3742 if (((respLen = mifare_sendcmd_short(pcs, CRYPT_ALL, MIFARE_EV1_SETMOD, mod, buf, MAX_MIFARE_FRAME_SIZE, par, NULL)) != 1) || (buf[0] != 0x0a)) {
3743 if (g_dbglevel >= DBG_ERROR) Dbprintf("SetMod error; response[0]: %hhX, len: %d", buf[0], respLen);
3744 break;
3747 if (mifare_classic_halt(pcs)) {
3748 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
3749 break;
3752 isOK = PM3_SUCCESS;
3753 break;
3756 crypto1_deinit(pcs);
3758 LED_B_ON();
3759 reply_ng(CMD_HF_MIFARE_SETMOD, isOK, NULL, 0);
3760 LED_B_OFF();
3762 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3763 LEDsoff();
3764 BigBuf_free();
3768 // DESFIRE
3770 void Mifare_DES_Auth1(uint8_t arg0, uint8_t *datain) {
3771 uint8_t dataout[12] = {0x00};
3772 uint32_t cuid = 0;
3774 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3775 clear_trace();
3776 set_tracing(true);
3778 int len = iso14443a_select_card(NULL, NULL, &cuid, true, 0, false);
3779 if (!len) {
3780 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
3781 OnError(1);
3782 return;
3785 if (mifare_desfire_des_auth1(cuid, dataout) != PM3_SUCCESS) {
3786 if (g_dbglevel >= DBG_ERROR) Dbprintf("Authentication part1: Fail.");
3787 OnError(4);
3788 return;
3791 if (g_dbglevel >= DBG_EXTENDED) DbpString("AUTH 1 FINISHED");
3792 reply_mix(CMD_ACK, 1, cuid, 0, dataout, sizeof(dataout));
3795 void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain) {
3796 uint32_t cuid = arg0;
3797 uint8_t key[16] = {0x00};
3798 uint8_t dataout[12] = {0x00};
3799 uint8_t isOK = 0;
3801 memcpy(key, datain, 16);
3803 isOK = mifare_desfire_des_auth2(cuid, key, dataout);
3805 if (isOK != PM3_SUCCESS) {
3806 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("Authentication part2: Failed");
3807 OnError(4);
3808 return;
3811 if (g_dbglevel >= DBG_EXTENDED) DbpString("AUTH 2 FINISHED");
3813 reply_old(CMD_ACK, isOK, 0, 0, dataout, sizeof(dataout));
3814 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3815 LEDsoff();
3816 set_tracing(false);
3820 // Tear-off attack against MFU.
3821 // - Moebius et al
3822 void MifareU_Otp_Tearoff(uint8_t blno, uint32_t tearoff_time, uint8_t *data_testwrite) {
3823 uint8_t blockNo = blno;
3825 if (g_dbglevel >= DBG_DEBUG) DbpString("Preparing OTP tear-off");
3827 if (tearoff_time > 43000) {
3828 tearoff_time = 43000;
3831 g_tearoff_delay_us = tearoff_time;
3832 g_tearoff_enabled = true;
3834 LEDsoff();
3835 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3836 clear_trace();
3837 set_tracing(true);
3839 // write cmd to send, include CRC
3840 // 1b write, 1b block, 4b data, 2 crc
3841 uint8_t cmd[] = {
3842 MIFARE_ULC_WRITE, blockNo,
3843 data_testwrite[0], data_testwrite[1], data_testwrite[2], data_testwrite[3],
3844 0, 0
3846 AddCrc14A(cmd, sizeof(cmd) - 2);
3848 // anticollision / select card
3849 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3850 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
3851 OnError(1);
3852 reply_ng(CMD_HF_MFU_OTP_TEAROFF, PM3_EFAILED, NULL, 0);
3853 return;
3855 // send
3856 LED_D_ON();
3857 ReaderTransmit(cmd, sizeof(cmd), NULL);
3858 tearoff_hook();
3859 reply_ng(CMD_HF_MFU_OTP_TEAROFF, PM3_SUCCESS, NULL, 0);
3863 // Tear-off attack against MFU counter
3864 void MifareU_Counter_Tearoff(uint8_t counter, uint32_t tearoff_time, uint8_t *datain) {
3866 if (tearoff_time > 43000) {
3867 tearoff_time = 43000;
3870 LEDsoff();
3871 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3872 clear_trace();
3873 set_tracing(true);
3875 // Send MFU counter increase cmd
3876 uint8_t cmd[] = {
3877 MIFARE_ULEV1_INCR_CNT,
3878 counter,
3879 datain[0], // lsb
3880 datain[1],
3881 datain[2], // msb
3882 datain[3], // rfu
3886 AddCrc14A(cmd, sizeof(cmd) - 2);
3888 // anticollision / select card
3889 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3890 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
3891 OnError(1);
3892 switch_off();
3893 LEDsoff();
3894 return;
3897 // send
3898 ReaderTransmit(cmd, sizeof(cmd), NULL);
3899 LED_D_ON();
3900 SpinDelayUsPrecision(tearoff_time);
3901 switch_off();
3902 LEDsoff();
3903 reply_ng(CMD_HF_MFU_COUNTER_TEAROFF, PM3_SUCCESS, NULL, 0);