Merge pull request #2616 from jmichelp/fix14b
[RRG-proxmark3.git] / armsrc / mifarecmd.c
blob167e1d64082bd4df6e0d4f3086b5d08bf46a3801
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) {
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 uint32_t cuid = 0;
1059 int16_t isOK = PM3_SUCCESS;
1060 uint8_t cascade_levels = 0;
1061 bool have_uid = false;
1063 LED_A_ON();
1064 LED_C_OFF();
1066 BigBuf_free();
1067 BigBuf_Clear_ext(false);
1068 clear_trace();
1069 set_tracing(false);
1071 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1073 LED_C_ON();
1075 for (uint16_t sec = 0; sec < MIFARE_1K_MAXSECTOR + 1; sec++) {
1076 uint16_t sec_gap = sec;
1077 if (sec >= MIFARE_1K_MAXSECTOR) {
1078 // gap between user blocks and advanced verification method blocks
1079 sec_gap += 16;
1081 uint16_t blockNo = sec_gap * 4;
1082 for (uint8_t keyType = 0; keyType < 2; keyType++) {
1083 // Test if the action was cancelled
1084 if (BUTTON_PRESS()) {
1085 isOK = PM3_EOPABORTED;
1086 break;
1088 if (have_uid == false) { // need a full select cycle to get the uid first
1089 iso14a_card_select_t card_info;
1090 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) {
1091 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (ALL)");
1092 isOK = PM3_ERFTRANS;
1093 goto out;
1095 switch (card_info.uidlen) {
1096 case 4 :
1097 cascade_levels = 1;
1098 break;
1099 case 7 :
1100 cascade_levels = 2;
1101 break;
1102 case 10:
1103 cascade_levels = 3;
1104 break;
1105 default:
1106 break;
1108 have_uid = true;
1109 } else { // no need for anticollision. We can directly select the card
1110 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
1111 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1112 isOK = PM3_ERFTRANS;
1113 goto out;
1117 uint32_t nt1 = 0;
1118 if (mifare_classic_authex_cmd(pcs, cuid, blockNo, MIFARE_AUTH_KEYA + keyType + 4, ui64Key, AUTH_FIRST, &nt1, NULL, NULL, NULL, false, false)) {
1119 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1120 isOK = PM3_ESOFT;
1121 goto out;
1123 if ((with_data) && (keyType == 0)) {
1124 uint8_t data[16];
1125 uint8_t blocks = 4;
1126 if (blockNo >= MIFARE_1K_MAXSECTOR * 4) {
1127 // special RF08S advanced authentication blocks, let's dump in emulator just in case
1128 blocks = 8;
1130 for (uint16_t tb = blockNo; tb < blockNo + blocks; tb++) {
1131 memset(data, 0x00, sizeof(data));
1132 int res = mifare_classic_readblock(pcs, tb, data);
1133 if (res == 1) {
1134 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Read error");
1135 isOK = PM3_ESOFT;
1136 goto out;
1138 emlSetMem_xt(data, tb, 1, 16);
1141 // nested authentication
1142 uint16_t len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + keyType + 4, blockNo, receivedAnswer, sizeof(receivedAnswer), par_enc, NULL);
1143 if (len != 4) {
1144 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len);
1145 isOK = PM3_ESOFT;
1146 goto out;
1148 uint32_t nt_enc = bytes_to_num(receivedAnswer, 4);
1149 crypto1_init(pcs, ui64Key);
1150 uint32_t nt = crypto1_word(pcs, nt_enc ^ cuid, 1) ^ nt_enc;
1151 // Dbprintf("Sec %2i key %i nT=%08x", sec, keyType + 4, nt);
1152 // store nt (first half)
1153 num_to_bytes(nt >> 16, 2, buf + (keyType * 8));
1154 // send some crap to fail auth
1155 uint8_t nack[] = {0x04};
1156 ReaderTransmit(nack, sizeof(nack), NULL);
1158 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
1159 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1160 isOK = PM3_ERFTRANS;
1161 goto out;
1163 if (mifare_classic_authex_cmd(pcs, cuid, blockNo, MIFARE_AUTH_KEYA + keyType + 4, ui64Key, AUTH_FIRST, &nt1, NULL, NULL, NULL, false, false)) {
1164 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1165 isOK = PM3_ESOFT;
1166 goto out;
1169 // nested authentication on regular keytype
1170 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + keyType, blockNo, receivedAnswer, sizeof(receivedAnswer), par_enc, NULL);
1171 if (len != 4) {
1172 if (g_dbglevel >= DBG_ERROR) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len);
1173 isOK = PM3_ESOFT;
1174 goto out;
1176 // store nt_enc
1177 memcpy(buf + (keyType * 8) + 4, receivedAnswer, 4);
1178 nt_enc = bytes_to_num(receivedAnswer, 4);
1179 uint8_t nt_par_err = ((((par_enc[0] >> 7) & 1) ^ oddparity8((nt_enc >> 24) & 0xFF)) << 3 |
1180 (((par_enc[0] >> 6) & 1) ^ oddparity8((nt_enc >> 16) & 0xFF)) << 2 |
1181 (((par_enc[0] >> 5) & 1) ^ oddparity8((nt_enc >> 8) & 0xFF)) << 1 |
1182 (((par_enc[0] >> 4) & 1) ^ oddparity8((nt_enc >> 0) & 0xFF)));
1183 // 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);
1184 // store nt_par_err
1185 buf[(keyType * 8) + 2] = nt_par_err;
1186 buf[(keyType * 8) + 3] = 0xAA; // extra check to tell we have nt/nt_enc/par_err
1187 emlSetMem_xt(buf, (CARD_MEMORY_RF08S_OFFSET / MIFARE_BLOCK_SIZE) + sec, 1, MIFARE_BLOCK_SIZE);
1188 // send some crap to fail auth
1189 ReaderTransmit(nack, sizeof(nack), NULL);
1192 out:
1193 LED_C_OFF();
1194 crypto1_deinit(pcs);
1195 LED_B_ON();
1196 if (reply) {
1197 reply_old(CMD_ACK, isOK, cuid, 0, BigBuf_get_EM_addr() + CARD_MEMORY_RF08S_OFFSET, MIFARE_BLOCK_SIZE * (MIFARE_1K_MAXSECTOR + 1));
1199 LED_B_OFF();
1201 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1202 LEDsoff();
1203 set_tracing(false);
1204 return isOK;
1208 //-----------------------------------------------------------------------------
1209 // MIFARE nested authentication.
1211 //-----------------------------------------------------------------------------
1212 void MifareNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, bool calibrate, uint8_t *key) {
1213 uint64_t ui64Key = 0;
1214 ui64Key = bytes_to_num(key, 6);
1216 // variables
1217 uint16_t i, j, len;
1218 static uint16_t dmin, dmax;
1220 uint8_t par[1] = {0x00};
1221 uint8_t par_array[4] = {0x00};
1222 uint8_t uid[10] = {0x00};
1223 uint32_t cuid = 0, nt1, nt2, nttest, ks1;
1224 uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00};
1226 uint16_t ncount = 0;
1227 struct Crypto1State mpcs = {0, 0};
1228 struct Crypto1State *pcs;
1229 pcs = &mpcs;
1230 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
1232 uint32_t auth1_time, auth2_time;
1233 static uint16_t delta_time = 0;
1235 LED_A_ON();
1236 LED_C_OFF();
1237 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1239 // free eventually allocated BigBuf memory
1240 BigBuf_free();
1241 BigBuf_Clear_ext(false);
1243 if (calibrate)
1244 clear_trace();
1246 set_tracing(true);
1248 // statistics on nonce distance
1249 int16_t isOK = PM3_SUCCESS;
1250 #define NESTED_MAX_TRIES 12
1251 if (calibrate) { // calibrate: for first call only. Otherwise reuse previous calibration
1252 LED_B_ON();
1253 WDT_HIT();
1255 uint32_t prev_enc_nt = 0;
1256 uint8_t prev_counter = 0;
1258 uint16_t unsuccessful_tries = 0;
1259 uint16_t davg = 0;
1260 dmax = 0;
1261 dmin = 2000;
1262 delta_time = 0;
1263 uint16_t rtr;
1264 for (rtr = 0; rtr < 17; rtr++) {
1266 // Test if the action was cancelled
1267 if (BUTTON_PRESS() || data_available()) {
1268 isOK = PM3_EOPABORTED;
1269 break;
1272 // prepare next select. No need to power down the card.
1273 if (mifare_classic_halt(pcs)) {
1274 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Halt error");
1275 rtr--;
1276 continue;
1279 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == 0) {
1280 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Can't select card");
1281 rtr--;
1282 continue;
1285 auth1_time = 0;
1286 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) {
1287 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth1 error");
1288 rtr--;
1289 continue;
1291 auth2_time = (delta_time) ? auth1_time + delta_time : 0;
1293 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, &auth2_time)) {
1294 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth2 error");
1295 rtr--;
1296 continue;
1299 // cards with fixed nonce
1300 // NXP Mifare is typical around 840,but for some unlicensed/compatible mifare card this can be 160
1302 uint32_t nttmp = prng_successor(nt1, 100);
1303 for (i = 101; i < 1200; i++) {
1304 nttmp = prng_successor(nttmp, 1);
1305 if (nttmp == nt2) break;
1308 if (i != 1200) {
1309 if (rtr != 0) {
1310 davg += i;
1311 dmin = MIN(dmin, i);
1312 dmax = MAX(dmax, i);
1313 } else {
1314 // allow some slack for proper timing
1315 delta_time = auth2_time - auth1_time + 32;
1317 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nested: calibrating... ntdist=%d", i);
1318 } else {
1319 unsuccessful_tries++;
1320 // card isn't vulnerable to nested attack (random numbers are not predictable)
1321 if (unsuccessful_tries > NESTED_MAX_TRIES) {
1322 isOK = PM3_EFAILED;
1327 if (nt1 == nt2) {
1328 prev_counter++;
1330 prev_enc_nt = nt2;
1332 if (prev_counter == 5) {
1333 if (g_dbglevel >= DBG_EXTENDED) {
1334 DbpString("Static encrypted nonce detected, exiting...");
1335 Dbprintf("( %08x vs %08x )", prev_enc_nt, nt2);
1337 isOK = PM3_ESTATIC_NONCE;
1338 break;
1342 if (rtr > 1)
1343 davg = (davg + (rtr - 1) / 2) / (rtr - 1);
1345 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);
1347 dmin = davg - 2;
1348 dmax = davg + 2;
1350 LED_B_OFF();
1352 // -------------------------------------------------------------------------------------------------
1354 LED_C_ON();
1356 // get crypted nonces for target sector
1357 for (i = 0; ((i < 2) && (isOK == PM3_SUCCESS)); i++) {
1359 // look for exactly two different nonces
1361 target_nt[i] = 0;
1362 // continue until we have an unambiguous nonce
1363 while (target_nt[i] == 0) {
1365 // Test if the action was cancelled
1366 if (BUTTON_PRESS() || data_available()) {
1367 isOK = PM3_EOPABORTED;
1368 break;
1371 // prepare next select. No need to power down the card.
1372 if (mifare_classic_halt(pcs)) {
1373 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Halt error");
1374 continue;
1377 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
1378 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Can't select card");
1379 continue;
1382 auth1_time = 0;
1383 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) {
1384 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth1 error");
1385 continue;
1388 // nested authentication
1389 auth2_time = auth1_time + delta_time;
1391 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par, &auth2_time);
1392 if (len != 4) {
1393 if (g_dbglevel >= DBG_INFO) Dbprintf("Nested: Auth2 error len=%d", len);
1394 continue;
1397 nt2 = bytes_to_num(receivedAnswer, 4);
1398 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i + 1, nt1, nt2, par[0]);
1400 // Parity validity check
1401 for (j = 0; j < 4; j++) {
1402 par_array[j] = (oddparity8(receivedAnswer[j]) != ((par[0] >> (7 - j)) & 0x01));
1405 ncount = 0;
1406 nttest = prng_successor(nt1, dmin - 1);
1407 for (j = dmin; j < dmax + 1; j++) {
1408 nttest = prng_successor(nttest, 1);
1409 ks1 = nt2 ^ nttest;
1411 if (valid_nonce(nttest, nt2, ks1, par_array)) {
1412 if (ncount > 0) { // we are only interested in disambiguous nonces, try again
1413 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nonce#%d: dismissed (ambiguous), ntdist=%d", i + 1, j);
1414 target_nt[i] = 0;
1415 break;
1417 target_nt[i] = nttest;
1418 target_ks[i] = ks1;
1419 ncount++;
1420 if (i == 1 && target_nt[1] == target_nt[0]) { // we need two different nonces
1421 target_nt[i] = 0;
1422 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nonce#2: dismissed (= nonce#1), ntdist=%d", j);
1423 break;
1425 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Nonce#%d: valid, ntdist=%d", i + 1, j);
1428 if (target_nt[i] == 0 && j == dmax + 1 && g_dbglevel >= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i + 1);
1432 LED_C_OFF();
1434 crypto1_deinit(pcs);
1436 struct p {
1437 int16_t isOK;
1438 uint8_t block;
1439 uint8_t keytype;
1440 uint8_t cuid[4];
1441 uint8_t nt_a[4];
1442 uint8_t ks_a[4];
1443 uint8_t nt_b[4];
1444 uint8_t ks_b[4];
1445 } PACKED payload;
1446 payload.isOK = isOK;
1447 payload.block = targetBlockNo;
1448 payload.keytype = targetKeyType;
1450 memcpy(payload.cuid, &cuid, 4);
1451 memcpy(payload.nt_a, &target_nt[0], 4);
1452 memcpy(payload.ks_a, &target_ks[0], 4);
1453 memcpy(payload.nt_b, &target_nt[1], 4);
1454 memcpy(payload.ks_b, &target_ks[1], 4);
1456 LED_B_ON();
1457 reply_ng(CMD_HF_MIFARE_NESTED, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload));
1458 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1459 LEDsoff();
1460 set_tracing(false);
1463 void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, uint8_t *key) {
1465 LEDsoff();
1467 uint64_t ui64Key = bytes_to_num(key, 6);
1468 uint16_t len, dist1 = 160, dist2 = 320;
1469 uint8_t uid[10] = { 0x00 };
1470 uint32_t cuid = 0, nt1 = 0, nt2 = 0, nt3 = 0;
1471 uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00};
1472 uint8_t par[1] = { 0x00 };
1473 uint8_t receivedAnswer[10] = { 0x00 };
1475 struct Crypto1State mpcs = { 0, 0 };
1476 struct Crypto1State *pcs;
1477 pcs = &mpcs;
1479 LED_A_ON();
1480 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1482 // free eventually allocated BigBuf memory
1483 BigBuf_free();
1484 BigBuf_Clear_ext(false);
1485 clear_trace();
1486 set_tracing(true);
1488 int16_t isOK = PM3_ESOFT;
1489 LED_C_ON();
1491 // Main loop - get crypted nonces for target sector
1492 for (uint8_t rtr = 0; rtr < 2; rtr++) {
1494 // distance measurement
1495 if (mifare_classic_halt(pcs)) {
1496 continue;
1499 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
1500 continue;
1503 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
1504 continue;
1507 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, NULL)) {
1508 continue;
1511 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt3, NULL)) {
1512 continue;
1515 dist1 = nonce_distance(nt1, nt2);
1516 dist2 = nonce_distance(nt1, nt3);
1518 if (mifare_classic_halt(pcs)) {
1519 continue;
1522 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
1523 continue;
1526 // first collection
1527 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
1528 continue;
1531 // pre-generate nonces
1532 if (targetKeyType == 1 && nt1 == 0x009080A2) {
1533 target_nt[0] = prng_successor(nt1, 161);
1534 target_nt[1] = prng_successor(nt1, 321);
1535 } else {
1536 target_nt[0] = prng_successor(nt1, dist1);
1537 target_nt[1] = prng_successor(nt1, dist2);
1540 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par, NULL);
1541 if (len != 4) {
1542 continue;
1545 nt2 = bytes_to_num(receivedAnswer, 4);
1546 target_ks[0] = nt2 ^ target_nt[0];
1548 // second collection
1549 if (mifare_classic_halt(pcs)) {
1550 continue;
1553 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
1554 continue;
1557 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
1558 continue;
1561 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, NULL, NULL)) {
1562 continue;
1565 len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par, NULL);
1566 if (len != 4) {
1567 continue;
1570 nt3 = bytes_to_num(receivedAnswer, 4);
1571 target_ks[1] = nt3 ^ target_nt[1];
1573 isOK = PM3_SUCCESS;
1576 LED_C_OFF();
1578 crypto1_deinit(pcs);
1580 struct p {
1581 uint8_t block;
1582 uint8_t keytype;
1583 uint8_t cuid[4];
1584 uint8_t nt_a[4];
1585 uint8_t ks_a[4];
1586 uint8_t nt_b[4];
1587 uint8_t ks_b[4];
1588 } PACKED payload;
1589 payload.block = targetBlockNo;
1590 payload.keytype = targetKeyType;
1592 memcpy(payload.cuid, &cuid, 4);
1593 memcpy(payload.nt_a, &target_nt[0], 4);
1594 memcpy(payload.ks_a, &target_ks[0], 4);
1595 memcpy(payload.nt_b, &target_nt[1], 4);
1596 memcpy(payload.ks_b, &target_ks[1], 4);
1598 LED_B_ON();
1599 reply_ng(CMD_HF_MIFARE_STATIC_NESTED, isOK, (uint8_t *)&payload, sizeof(payload));
1600 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1601 LEDsoff();
1602 set_tracing(false);
1605 //-----------------------------------------------------------------------------
1606 // MIFARE check keys. key count up to 85.
1608 //-----------------------------------------------------------------------------
1609 typedef struct sector_t {
1610 uint8_t keyA[6];
1611 uint8_t keyB[6];
1612 } sector_t;
1614 typedef struct chk_t {
1615 uint64_t key;
1616 uint32_t cuid;
1617 uint8_t cl;
1618 uint8_t block;
1619 uint8_t keyType;
1620 uint8_t *uid;
1621 struct Crypto1State *pcs;
1622 } chk_t;
1624 // checks one key.
1625 // fast select, tries 5 times to select
1627 // return:
1628 // 2 = failed to select.
1629 // 1 = wrong key
1630 // 0 = correct key
1631 static uint8_t chkKey(struct chk_t *c) {
1632 uint8_t i = 0, res = 2;
1633 bool selected = false;
1634 while (i < 5) {
1635 // this part is from Piwi's faster nonce collecting part in Hardnested.
1636 // assume: fast select
1637 if (!iso14443a_fast_select_card(c->uid, c->cl)) {
1638 ++i;
1639 continue;
1641 selected = true;
1642 res = mifare_classic_authex(c->pcs, c->cuid, c->block, c->keyType, c->key, AUTH_FIRST, NULL, NULL);
1644 // CHK_TIMEOUT();
1646 // if successful auth, send HALT
1647 // if ( !res )
1648 // mifare_classic_halt(c->pcs);
1649 break;
1651 if (selected == false) {
1652 Dbprintf("chkKey: Failed at fast selecting the card!");
1654 return res;
1657 static uint8_t chkKey_readb(struct chk_t *c, uint8_t *keyb) {
1659 if (!iso14443a_fast_select_card(c->uid, c->cl))
1660 return 2;
1662 if (mifare_classic_authex(c->pcs, c->cuid, c->block, 0, c->key, AUTH_FIRST, NULL, NULL))
1663 return 1;
1665 uint8_t data[16] = {0x00};
1666 uint8_t res = mifare_classic_readblock(c->pcs, c->block, data);
1668 // successful read
1669 if (!res) {
1670 // data was something else than zeros.
1671 if (memcmp(data + 10, "\x00\x00\x00\x00\x00\x00", 6) != 0) {
1672 memcpy(keyb, data + 10, 6);
1673 res = 0;
1674 } else {
1675 res = 3;
1677 mifare_classic_halt(c->pcs);
1679 return res;
1682 static void chkKey_scanA(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, const uint8_t *sectorcnt, uint8_t *foundkeys) {
1683 for (uint8_t s = 0; s < *sectorcnt; s++) {
1685 // skip already found A keys
1686 if (found[(s * 2)])
1687 continue;
1689 c->block = FirstBlockOfSector(s);
1690 if (chkKey(c) == 0) {
1691 num_to_bytes(c->key, 6, k_sector[s].keyA);
1692 found[(s * 2)] = 1;
1693 ++*foundkeys;
1695 if (g_dbglevel >= 3) Dbprintf("ChkKeys_fast: Scan A found (%d)", c->block);
1700 static void chkKey_scanB(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, const uint8_t *sectorcnt, uint8_t *foundkeys) {
1701 for (uint8_t s = 0; s < *sectorcnt; s++) {
1703 // skip already found B keys
1704 if (found[(s * 2) + 1])
1705 continue;
1707 c->block = FirstBlockOfSector(s);
1708 if (chkKey(c) == 0) {
1709 num_to_bytes(c->key, 6, k_sector[s].keyB);
1710 found[(s * 2) + 1] = 1;
1711 ++*foundkeys;
1713 if (g_dbglevel >= 3) Dbprintf("ChkKeys_fast: Scan B found (%d)", c->block);
1718 // loop all A keys,
1719 // when A is found but not B, try to read B.
1720 static void chkKey_loopBonly(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) {
1722 // read Block B, if A is found.
1723 for (uint8_t s = 0; s < *sectorcnt; ++s) {
1725 if (found[(s * 2)] && found[(s * 2) + 1])
1726 continue;
1728 c->block = (FirstBlockOfSector(s) + NumBlocksPerSector(s) - 1);
1730 // A but not B
1731 if (found[(s * 2)] && !found[(s * 2) + 1]) {
1732 c->key = bytes_to_num(k_sector[s].keyA, 6);
1733 uint8_t status = chkKey_readb(c, k_sector[s].keyB);
1734 if (status == 0) {
1735 found[(s * 2) + 1] = 1;
1736 ++*foundkeys;
1738 if (g_dbglevel >= 3) Dbprintf("ChkKeys_fast: Reading B found (%d)", c->block);
1740 // try quick find all B?
1741 // assume: keys comes in groups. Find one B, test against all B.
1742 c->key = bytes_to_num(k_sector[s].keyB, 6);
1743 c->keyType = 1;
1744 chkKey_scanB(c, k_sector, found, sectorcnt, foundkeys);
1750 // get Chunks of keys, to test authentication against card.
1751 // arg0 = antal sectorer
1752 // arg0 = first time
1753 // arg1 = clear trace
1754 // arg2 = antal nycklar i keychunk
1755 // datain = keys as array
1756 void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain) {
1758 // first call or
1759 uint8_t sectorcnt = arg0 & 0xFF; // 16;
1760 uint8_t firstchunk = (arg0 >> 8) & 0xF;
1761 uint8_t lastchunk = (arg0 >> 12) & 0xF;
1762 uint16_t singleSectorParams = (arg0 >> 16) & 0xFFFF;
1763 uint8_t strategy = arg1 & 0xFF;
1764 uint8_t use_flashmem = (arg1 >> 8) & 0xFF;
1765 uint16_t keyCount = arg2 & 0xFF;
1766 uint8_t status = 0;
1767 bool singleSectorMode = (singleSectorParams >> 15) & 1;
1768 uint8_t keytype = (singleSectorParams >> 8) & 1;
1769 uint8_t blockn = singleSectorParams & 0xFF;
1771 struct Crypto1State mpcs = {0, 0};
1772 struct Crypto1State *pcs;
1773 pcs = &mpcs;
1774 struct chk_t chk_data;
1776 uint8_t allkeys = sectorcnt << 1;
1778 static uint32_t cuid = 0;
1779 static uint8_t cascade_levels = 0;
1780 static uint8_t foundkeys = 0;
1781 static sector_t k_sector[80];
1782 static uint8_t found[80];
1783 static uint8_t *uid;
1785 int oldbg = g_dbglevel;
1787 #ifdef WITH_FLASH
1788 if (use_flashmem) {
1789 BigBuf_free();
1790 uint16_t isok = 0;
1791 uint8_t size[2] = {0x00, 0x00};
1792 isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET, size, 2);
1793 if (isok != 2)
1794 goto OUT;
1796 keyCount = size[1] << 8 | size[0];
1798 if (keyCount == 0)
1799 goto OUT;
1801 // limit size of available for keys in bigbuff
1802 // a key is 6bytes
1803 uint16_t key_mem_available = MIN(BigBuf_get_size(), keyCount * 6);
1805 keyCount = key_mem_available / 6;
1807 datain = BigBuf_malloc(key_mem_available);
1808 if (datain == NULL)
1809 goto OUT;
1811 isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET + 2, datain, key_mem_available);
1812 if (isok != key_mem_available)
1813 goto OUT;
1816 #endif
1818 if (uid == NULL || firstchunk) {
1819 uid = BigBuf_malloc(10);
1820 if (uid == NULL)
1821 goto OUT;
1824 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1826 LEDsoff();
1827 LED_A_ON();
1829 if (firstchunk) {
1830 clear_trace();
1831 set_tracing(false);
1833 memset(k_sector, 0x00, 480 + 10);
1834 memset(found, 0x00, sizeof(found));
1835 foundkeys = 0;
1837 iso14a_card_select_t card_info;
1838 if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) {
1839 if (g_dbglevel >= DBG_ERROR) Dbprintf("ChkKeys_fast: Can't select card (ALL)");
1840 goto OUT;
1843 switch (card_info.uidlen) {
1844 case 4 :
1845 cascade_levels = 1;
1846 break;
1847 case 7 :
1848 cascade_levels = 2;
1849 break;
1850 case 10:
1851 cascade_levels = 3;
1852 break;
1853 default:
1854 break;
1857 CHK_TIMEOUT();
1860 // clear debug level. We are expecting lots of authentication failures...
1861 g_dbglevel = DBG_NONE;
1863 // set check struct.
1864 chk_data.uid = uid;
1865 chk_data.cuid = cuid;
1866 chk_data.cl = cascade_levels;
1867 chk_data.pcs = pcs;
1868 chk_data.block = 0;
1870 if (singleSectorMode) {
1871 allkeys = 1;
1872 chk_data.block = blockn;
1873 chk_data.keyType = keytype;
1874 for (uint16_t i = 0; i < keyCount; ++i) {
1876 // Allow button press / usb cmd to interrupt device
1877 if (BUTTON_PRESS() || data_available()) {
1878 goto OUT;
1881 WDT_HIT();
1883 chk_data.key = bytes_to_num(datain + i * 6, 6);
1884 if (chkKey(&chk_data) == 0) {
1885 foundkeys++;
1886 reply_old(CMD_ACK, 1, 0, 0, datain + i * 6, 6);
1887 goto out;
1890 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
1891 out:
1892 LEDsoff();
1893 crypto1_deinit(pcs);
1894 if (foundkeys == allkeys || lastchunk) {
1895 set_tracing(false);
1896 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1897 BigBuf_free();
1898 BigBuf_Clear_ext(false);
1900 g_dbglevel = oldbg;
1901 return;
1905 // keychunk loop - depth first one sector.
1906 if (strategy == 1 || use_flashmem) {
1908 uint8_t newfound = foundkeys;
1910 uint16_t lastpos = 0;
1911 uint16_t s_point = 0;
1912 // Sector main loop
1913 // keep track of how many sectors on card.
1914 for (uint8_t s = 0; s < sectorcnt; ++s) {
1916 if (found[(s * 2)] && found[(s * 2) + 1])
1917 continue;
1919 for (uint16_t i = s_point; i < keyCount; ++i) {
1921 // Allow button press / usb cmd to interrupt device
1922 if (BUTTON_PRESS() || data_available()) {
1923 goto OUT;
1926 // found all keys?
1927 if (foundkeys == allkeys)
1928 goto OUT;
1930 WDT_HIT();
1932 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
1933 chk_data.block = FirstBlockOfSector(s);
1935 // new key
1936 chk_data.key = bytes_to_num(datain + i * 6, 6);
1938 // skip already found A keys
1939 if (!found[(s * 2)]) {
1940 chk_data.keyType = 0;
1941 status = chkKey(&chk_data);
1942 if (status == 0) {
1943 memcpy(k_sector[s].keyA, datain + i * 6, 6);
1944 found[(s * 2)] = 1;
1945 ++foundkeys;
1947 chkKey_scanA(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1949 // read Block B, if A is found.
1950 chkKey_loopBonly(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1952 chk_data.keyType = 1;
1953 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1955 chk_data.keyType = 0;
1956 chk_data.block = FirstBlockOfSector(s);
1958 if (use_flashmem) {
1959 if (lastpos != i && lastpos != 0) {
1960 if (i - lastpos < 0xF) {
1961 s_point = i & 0xFFF0;
1963 } else {
1964 lastpos = i;
1970 // skip already found B keys
1971 if (!found[(s * 2) + 1]) {
1972 chk_data.keyType = 1;
1973 status = chkKey(&chk_data);
1974 if (status == 0) {
1975 memcpy(k_sector[s].keyB, datain + i * 6, 6);
1976 found[(s * 2) + 1] = 1;
1977 ++foundkeys;
1979 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1981 if (use_flashmem) {
1982 if (lastpos != i && lastpos != 0) {
1984 if (i - lastpos < 0xF)
1985 s_point = i & 0xFFF0;
1986 } else {
1987 lastpos = i;
1993 if (found[(s * 2)] && found[(s * 2) + 1])
1994 break;
1996 } // end keys test loop - depth first
1998 // assume1. if no keys found in first sector, get next keychunk from client
1999 if (!use_flashmem && (newfound - foundkeys == 0))
2000 goto OUT;
2002 } // end loop - sector
2003 } // end strategy 1
2005 if (foundkeys == allkeys)
2006 goto OUT;
2008 if (strategy == 2 || use_flashmem) {
2010 // Keychunk loop
2011 for (uint16_t i = 0; i < keyCount; i++) {
2013 // Allow button press / usb cmd to interrupt device
2014 if (BUTTON_PRESS() || data_available()) break;
2016 // found all keys?
2017 if (foundkeys == allkeys)
2018 goto OUT;
2020 WDT_HIT();
2022 // new key
2023 chk_data.key = bytes_to_num(datain + i * 6, 6);
2025 // Sector main loop
2026 // keep track of how many sectors on card.
2027 for (uint8_t s = 0; s < sectorcnt; ++s) {
2029 if (found[(s * 2)] && found[(s * 2) + 1]) continue;
2031 // found all keys?
2032 if (foundkeys == allkeys)
2033 goto OUT;
2035 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
2036 chk_data.block = FirstBlockOfSector(s);
2038 // skip already found A keys
2039 if (!found[(s * 2)]) {
2040 chk_data.keyType = 0;
2041 status = chkKey(&chk_data);
2042 if (status == 0) {
2043 memcpy(k_sector[s].keyA, datain + i * 6, 6);
2044 found[(s * 2)] = 1;
2045 ++foundkeys;
2047 chkKey_scanA(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2049 // read Block B, if A is found.
2050 chkKey_loopBonly(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2052 chk_data.block = FirstBlockOfSector(s);
2056 // skip already found B keys
2057 if (!found[(s * 2) + 1]) {
2058 chk_data.keyType = 1;
2059 status = chkKey(&chk_data);
2060 if (status == 0) {
2061 memcpy(k_sector[s].keyB, datain + i * 6, 6);
2062 found[(s * 2) + 1] = 1;
2063 ++foundkeys;
2065 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
2068 } // end loop sectors
2069 } // end loop keys
2070 } // end loop strategy 2
2071 OUT:
2072 LEDsoff();
2074 crypto1_deinit(pcs);
2076 // All keys found, send to client, or last keychunk from client
2077 if (foundkeys == allkeys || lastchunk) {
2079 uint64_t foo = 0;
2080 for (uint8_t m = 0; m < 64; m++) {
2081 foo |= ((uint64_t)(found[m] & 1) << m);
2084 uint16_t bar = 0;
2085 uint8_t j = 0;
2086 for (uint8_t m = 64; m < ARRAYLEN(found); m++) {
2087 bar |= ((uint16_t)(found[m] & 1) << j++);
2090 uint8_t *tmp = BigBuf_malloc(480 + 10);
2091 memcpy(tmp, k_sector, sectorcnt * sizeof(sector_t));
2092 num_to_bytes(foo, 8, tmp + 480);
2093 tmp[488] = bar & 0xFF;
2094 tmp[489] = bar >> 8 & 0xFF;
2096 reply_old(CMD_ACK, foundkeys, 0, 0, tmp, 480 + 10);
2098 set_tracing(false);
2099 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2100 BigBuf_free();
2101 BigBuf_Clear_ext(false);
2103 // special trick ecfill
2104 if (use_flashmem && foundkeys == allkeys) {
2106 uint8_t block[16] = {0};
2107 for (int i = 0; i < sectorcnt; i++) {
2109 uint8_t blockno;
2110 if (i < 32) {
2111 blockno = (i * 4) ^ 0x3;
2112 } else {
2113 blockno = (32 * 4 + (i - 32) * 16) ^ 0xF;
2115 // get ST
2116 emlGetMem(block, blockno, 1);
2118 memcpy(block, k_sector[i].keyA, 6);
2119 memcpy(block + 10, k_sector[i].keyB, 6);
2121 emlSetMem_xt(block, blockno, 1, sizeof(block));
2124 MifareECardLoad(sectorcnt, MF_KEY_A, NULL);
2125 MifareECardLoad(sectorcnt, MF_KEY_B, NULL);
2127 } else {
2128 // partial/none keys found
2129 reply_mix(CMD_ACK, foundkeys, 0, 0, 0, 0);
2132 g_dbglevel = oldbg;
2135 void MifareChkKeys(uint8_t *datain, uint8_t reserved_mem) {
2137 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2139 struct Crypto1State mpcs = {0, 0};
2140 struct Crypto1State *pcs;
2141 pcs = &mpcs;
2143 uint8_t uid[10] = {0x00};
2145 uint64_t key = 0;
2146 uint32_t cuid = 0;
2147 uint8_t cascade_levels = 0;
2148 struct {
2149 uint8_t key[6];
2150 bool found;
2151 } PACKED keyresult;
2152 keyresult.found = false;
2153 memset(keyresult.key, 0x00, sizeof(keyresult.key));
2155 bool have_uid = false;
2157 uint8_t keyType = datain[0];
2158 uint8_t blockNo = datain[1];
2159 bool clearTrace = datain[2];
2160 uint16_t key_count = (datain[3] << 8) | datain[4];
2162 uint16_t key_mem_available;
2163 if (reserved_mem)
2164 key_mem_available = key_count * 6;
2165 else
2166 key_mem_available = MIN((PM3_CMD_DATA_SIZE - 5), key_count * 6);
2168 key_count = key_mem_available / 6;
2170 datain += 5;
2172 LEDsoff();
2173 LED_A_ON();
2175 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2177 if (clearTrace)
2178 clear_trace();
2180 int oldbg = g_dbglevel;
2181 g_dbglevel = DBG_NONE;
2183 set_tracing(false);
2185 for (uint16_t i = 0; i < key_count; i++) {
2187 // Iceman: use piwi's faster nonce collecting part in hardnested.
2188 if (have_uid == false) { // need a full select cycle to get the uid first
2189 iso14a_card_select_t card_info;
2190 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == false) {
2191 if (g_dbglevel >= DBG_ERROR) Dbprintf("ChkKeys: Can't select card (ALL)");
2192 --i; // try same key once again
2193 continue;
2195 switch (card_info.uidlen) {
2196 case 4 :
2197 cascade_levels = 1;
2198 break;
2199 case 7 :
2200 cascade_levels = 2;
2201 break;
2202 case 10:
2203 cascade_levels = 3;
2204 break;
2205 default:
2206 break;
2208 have_uid = true;
2209 } else { // no need for anticollision. We can directly select the card
2210 if (iso14443a_select_card(uid, NULL, NULL, false, cascade_levels, true) == false) {
2211 if (g_dbglevel >= DBG_ERROR) Dbprintf("ChkKeys: Can't select card (UID)");
2212 --i; // try same key once again
2213 continue;
2217 key = bytes_to_num(datain + i * 6, 6);
2218 if (mifare_classic_auth(pcs, cuid, blockNo, keyType, key, AUTH_FIRST)) {
2219 // CHK_TIMEOUT();
2220 continue;
2223 memcpy(keyresult.key, datain + i * 6, 6);
2224 keyresult.found = true;
2225 break;
2228 LED_B_ON();
2229 crypto1_deinit(pcs);
2231 reply_ng(CMD_HF_MIFARE_CHKKEYS, PM3_SUCCESS, (uint8_t *)&keyresult, sizeof(keyresult));
2232 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2233 LEDsoff();
2234 set_tracing(false);
2235 g_dbglevel = oldbg;
2238 void MifareChkKeys_file(uint8_t *fn) {
2240 #ifdef WITH_FLASH
2241 BigBuf_free();
2243 SpinOff(0);
2245 int changed = rdv40_spiffs_lazy_mount();
2246 uint32_t size = size_in_spiffs((char *)fn);
2247 uint8_t *mem = BigBuf_malloc(size);
2249 rdv40_spiffs_read_as_filetype((char *)fn, mem, size, RDV40_SPIFFS_SAFETY_SAFE);
2251 if (changed) {
2252 rdv40_spiffs_lazy_unmount();
2255 SpinOff(0);
2257 MifareChkKeys(mem, true);
2259 BigBuf_free();
2260 #endif
2263 //-----------------------------------------------------------------------------
2264 // MIFARE Personalize UID. Only for Mifare Classic EV1 7Byte UID
2265 //-----------------------------------------------------------------------------
2266 void MifarePersonalizeUID(uint8_t keyType, uint8_t perso_option, uint64_t key) {
2268 uint16_t isOK = PM3_EUNDEF;
2269 uint8_t uid[10];
2270 uint32_t cuid;
2271 struct Crypto1State mpcs = {0, 0};
2272 struct Crypto1State *pcs;
2273 pcs = &mpcs;
2275 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2276 clear_trace();
2277 set_tracing(true);
2279 LED_A_ON();
2281 while (true) {
2282 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
2283 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
2284 break;
2287 uint8_t block_number = 0;
2288 if (mifare_classic_auth(pcs, cuid, block_number, keyType, key, AUTH_FIRST)) {
2289 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
2290 break;
2293 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
2294 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
2295 int len = mifare_sendcmd_short(pcs, true, MIFARE_EV1_PERSONAL_UID, perso_option, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
2296 if (len != 1 || receivedAnswer[0] != CARD_ACK) {
2297 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
2298 break;
2301 if (mifare_classic_halt(pcs)) {
2302 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
2303 break;
2305 isOK = PM3_SUCCESS;
2306 break;
2309 crypto1_deinit(pcs);
2311 LED_B_ON();
2312 reply_ng(CMD_HF_MIFARE_PERSONALIZE_UID, isOK, NULL, 0);
2313 LED_B_OFF();
2315 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2316 LEDsoff();
2320 //-----------------------------------------------------------------------------
2321 // Work with emulator memory
2323 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
2324 // involved in dealing with emulator memory. But if it is called later, it might
2325 // destroy the Emulator Memory.
2326 //-----------------------------------------------------------------------------
2328 void MifareEMemClr(void) {
2329 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
2330 emlClearMem();
2333 void MifareEMemGet(uint8_t blockno, uint8_t blockcnt) {
2334 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
2337 size_t size = blockcnt * 16;
2338 if (size > PM3_CMD_DATA_SIZE) {
2339 reply_ng(CMD_HF_MIFARE_EML_MEMGET, PM3_EMALLOC, NULL, 0);
2340 return;
2343 uint8_t *buf = BigBuf_malloc(size);
2345 emlGetMem(buf, blockno, blockcnt); // data, block num, blocks count (max 4)
2347 LED_B_ON();
2348 reply_ng(CMD_HF_MIFARE_EML_MEMGET, PM3_SUCCESS, buf, size);
2349 LED_B_OFF();
2350 BigBuf_free_keep_EM();
2353 //-----------------------------------------------------------------------------
2354 // Load a card into the emulator memory
2356 //-----------------------------------------------------------------------------
2357 int MifareECardLoadExt(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) {
2358 int retval = MifareECardLoad(sectorcnt, keytype, key);
2359 reply_ng(CMD_HF_MIFARE_EML_LOAD, retval, NULL, 0);
2360 return retval;
2363 int MifareECardLoad(uint8_t sectorcnt, uint8_t keytype, uint8_t *key) {
2364 if ((keytype > MF_KEY_B) && (key == NULL)) {
2365 if (g_dbglevel >= DBG_ERROR) {
2366 Dbprintf("Error, missing key");
2368 return PM3_EINVARG;
2370 LED_A_ON();
2371 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2373 clear_trace();
2374 set_tracing(true);
2376 // variables
2377 bool have_uid = false;
2378 bool bd_authenticated = false;
2379 uint8_t cascade_levels = 0;
2380 uint32_t cuid = 0;
2381 uint8_t uid[10] = {0x00};
2382 struct Crypto1State mpcs = {0, 0};
2383 struct Crypto1State *pcs;
2384 pcs = &mpcs;
2386 int retval = PM3_SUCCESS;
2388 // increase time-out. Magic card etc are slow
2389 uint32_t timeout = iso14a_get_timeout();
2390 // frame waiting time (FWT) in 1/fc
2391 uint32_t fwt = 256 * 16 * (1 << 6);
2392 iso14a_set_timeout(fwt / (8 * 16));
2394 for (uint8_t s = 0; s < sectorcnt; s++) {
2396 uint64_t ui64Key = emlGetKey(s, keytype);
2398 // MIFARE Classic 1K Ev1 , MIFARE Classic MINI Ev1
2399 if (sectorcnt == 18) {
2400 // MFC 1K EV1, skip sector 16 since its lockdown
2401 if (s == 16) {
2402 // unknown sector trailer, keep the keys, set only the AC
2403 uint8_t st[16] = {0x00};
2404 emlGetMem(st, FirstBlockOfSector(s) + 3, 1);
2405 memcpy(st + 6, "\x70\xF0\xF8\x69", 4);
2406 emlSetMem_xt(st, FirstBlockOfSector(s) + 3, 1, 16);
2407 continue;
2410 // ICEMAN: ugly hack, we don't want to trigger the partial load message
2411 // MFC 1K EV1 sector 17 don't use key A.
2412 // not mention we don't save signatures in our MFC dump files.
2413 if (s == 17 && keytype == MF_KEY_A) {
2414 ui64Key = 0x4B791BEA7BCC;
2415 keytype = 1;
2419 // use fast select
2420 if (have_uid == false) { // need a full select cycle to get the uid first
2421 iso14a_card_select_t card_info;
2422 if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == 0) {
2423 if (s == 0) {
2424 // first attempt, if no card let's stop directly
2425 retval = PM3_EFAILED;
2426 if (g_dbglevel >= DBG_ERROR) {
2427 Dbprintf("Card not found");
2429 goto out;
2431 continue;
2434 switch (card_info.uidlen) {
2435 case 4 :
2436 cascade_levels = 1;
2437 break;
2438 case 7 :
2439 cascade_levels = 2;
2440 break;
2441 case 10:
2442 cascade_levels = 3;
2443 break;
2444 default:
2445 break;
2447 have_uid = true;
2448 } else { // no need for anticollision. We can directly select the card
2449 if (!bd_authenticated) { // no need to select if bd_authenticated with backdoor
2450 if (iso14443a_fast_select_card(uid, cascade_levels) == 0) {
2451 continue;
2456 // Auth
2457 if (keytype > MF_KEY_B) {
2458 if (! bd_authenticated) {
2459 ui64Key = bytes_to_num(key, 6);
2460 if (mifare_classic_auth(pcs, cuid, 0, keytype, ui64Key, AUTH_FIRST)) {
2461 retval = PM3_EFAILED;
2462 if (g_dbglevel >= DBG_ERROR) {
2463 Dbprintf("Auth error");
2465 goto out;
2467 bd_authenticated = true;
2469 } else if (mifare_classic_auth(pcs, cuid, FirstBlockOfSector(s), keytype, ui64Key, AUTH_FIRST)) {
2471 ui64Key = emlGetKey(s, MF_KEY_B);
2473 if (mifare_classic_auth(pcs, cuid, FirstBlockOfSector(s), MF_KEY_B, ui64Key, AUTH_FIRST)) {
2474 retval = PM3_EPARTIAL;
2475 if (g_dbglevel >= DBG_ERROR) {
2476 Dbprintf("Sector %2d - Auth error", s);
2478 continue;
2483 #define MAX_RETRIES 2
2485 uint8_t data[16] = {0x00};
2486 for (uint8_t b = 0; b < NumBlocksPerSector(s); b++) {
2488 memset(data, 0x00, sizeof(data));
2489 uint8_t tb = FirstBlockOfSector(s) + b;
2490 uint8_t r = 0;
2491 for (; r < MAX_RETRIES; r++) {
2493 int res = mifare_classic_readblock(pcs, tb, data);
2494 if (res == 1) {
2495 retval |= PM3_EPARTIAL;
2496 if (g_dbglevel >= DBG_ERROR) {
2497 Dbprintf("Error No rights reading sector %2d block %2d", s, b);
2499 break;
2501 // retry if wrong len.
2502 if (res != 0) {
2503 continue;
2506 // No need to copy empty
2507 if (memcmp(data, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16) == 0) {
2508 break;
2511 if (IsSectorTrailer(b)) {
2512 // sector trailer, keep the keys, set only the AC
2513 uint8_t st[16] = {0x00};
2514 emlGetMem(st, tb, 1);
2515 memcpy(st + 6, data + 6, 4);
2516 emlSetMem_xt(st, tb, 1, 16);
2517 } else {
2518 emlSetMem_xt(data, tb, 1, 16);
2520 break;
2523 // if we failed all retries, notify client
2524 if (r == MAX_RETRIES) {
2525 retval |= PM3_EPARTIAL;
2529 int res;
2530 out:
2531 res = mifare_classic_halt(pcs);
2532 (void)res;
2534 iso14a_set_timeout(timeout);
2535 crypto1_deinit(pcs);
2536 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2537 LEDsoff();
2538 set_tracing(false);
2539 return retval;
2544 //-----------------------------------------------------------------------------
2545 // Work with "magic Chinese" card (email him: ouyangweidaxian@live.cn)
2547 // PARAMS - workFlags
2548 // bit 0 - need get UID
2549 // bit 1 - need wupC
2550 // bit 2 - need HALT after sequence
2551 // bit 3 - need turn on FPGA before sequence
2552 // bit 4 - need turn off FPGA
2553 // bit 5 - need to set datain instead of issuing USB reply (called via ARM for StandAloneMode14a)
2554 // bit 6 - wipe tag.
2555 // bit 7 - use USCUID/GDM (20/23) magic wakeup
2556 //-----------------------------------------------------------------------------
2558 void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) {
2560 // params
2561 uint8_t workFlags = arg0;
2562 uint8_t blockNo = arg1;
2564 // detect 1a/1b
2565 bool is1b = false;
2567 // variables
2568 bool isOK = false; //assume we will get an error
2569 uint8_t errormsg = 0x00;
2570 uint8_t uid[10] = {0x00};
2571 uint8_t data[18] = {0x00};
2572 uint32_t cuid = 0;
2574 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
2575 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
2577 if (workFlags & MAGIC_INIT) {
2578 LED_A_ON();
2579 LED_B_OFF();
2580 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2581 clear_trace();
2582 set_tracing(true);
2585 //loop doesn't loop just breaks out if error
2586 while (true) {
2587 // read UID and return to client with write
2588 if (workFlags & MAGIC_UID) {
2589 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
2590 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
2591 errormsg = MAGIC_UID;
2592 mifare_classic_halt(NULL);
2593 break;
2595 mifare_classic_halt(NULL);
2598 // wipe tag, fill it with zeros
2599 if (workFlags & MAGIC_WIPE) {
2600 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2601 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2602 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupC1 error");
2603 errormsg = MAGIC_WIPE;
2604 break;
2607 uint32_t old_timeout = iso14a_get_timeout();
2609 // 2000 ms timeout
2610 // 13560000 / 1000 / (8 * 16) * timeout
2611 iso14a_set_timeout(21190);
2613 ReaderTransmit(wipeC, sizeof(wipeC), NULL);
2614 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2615 if (g_dbglevel >= DBG_ERROR) Dbprintf("wipeC error");
2616 errormsg = MAGIC_WIPE;
2617 break;
2619 iso14a_set_timeout(old_timeout);
2621 mifare_classic_halt(NULL);
2624 if (workFlags & MAGIC_GDM_ALT_WUPC) {
2625 ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL);
2626 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2627 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM1 error");
2628 errormsg = MAGIC_WUPC;
2629 break;
2632 ReaderTransmit(wupGDM2, sizeof(wupC2), NULL);
2633 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2634 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM2 error");
2635 errormsg = MAGIC_WUPC;
2636 break;
2640 // write block
2641 if (workFlags & MAGIC_WUPC) {
2642 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2643 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2644 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupC1 error");
2645 errormsg = MAGIC_WUPC;
2646 break;
2649 if (!is1b) {
2650 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2651 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2652 if (g_dbglevel >= DBG_INFO) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2653 is1b = true;
2654 continue;
2659 if ((mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_WRITEBLOCK, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL) != 1) || (receivedAnswer[0] != 0x0a)) {
2660 if (g_dbglevel >= DBG_ERROR) Dbprintf("write block send command error");
2661 errormsg = 4;
2662 break;
2665 memcpy(data, datain, 16);
2666 AddCrc14A(data, 16);
2668 ReaderTransmit(data, sizeof(data), NULL);
2669 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) != 1) || (receivedAnswer[0] != 0x0a)) {
2670 if (g_dbglevel >= DBG_ERROR) Dbprintf("write block send data error");
2671 errormsg = 0;
2672 break;
2675 if (workFlags & MAGIC_HALT) {
2676 mifare_classic_halt(NULL);
2679 isOK = true;
2680 break;
2682 } // end while
2684 if (isOK)
2685 reply_mix(CMD_ACK, 1, 0, 0, uid, sizeof(uid));
2686 else
2687 OnErrorMagic(errormsg);
2689 if (workFlags & MAGIC_OFF)
2690 OnSuccessMagic();
2693 void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) {
2695 uint8_t workFlags = arg0;
2696 uint8_t blockNo = arg1;
2697 uint8_t errormsg = 0x00;
2698 bool isOK = false; //assume we will get an error
2700 // detect 1a/1b
2701 bool is1b = false;
2703 // variables
2704 uint8_t data[MAX_MIFARE_FRAME_SIZE];
2705 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
2706 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
2708 memset(data, 0x00, sizeof(data));
2710 if (workFlags & MAGIC_INIT) {
2711 LED_A_ON();
2712 LED_B_OFF();
2713 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2714 clear_trace();
2715 set_tracing(true);
2718 // increase time-out. Magic card etc are slow
2719 uint32_t timeout = iso14a_get_timeout();
2720 // frame waiting time (FWT) in 1/fc
2721 uint32_t fwt = 256 * 16 * (1 << 7);
2722 iso14a_set_timeout(fwt / (8 * 16));
2724 //loop doesn't loop just breaks out if error or done
2725 while (true) {
2726 if (workFlags & MAGIC_GDM_ALT_WUPC) {
2727 ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL);
2728 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2729 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM1 error");
2730 errormsg = MAGIC_WUPC;
2731 break;
2734 ReaderTransmit(wupGDM2, sizeof(wupC2), NULL);
2735 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2736 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM2 error");
2737 errormsg = MAGIC_WUPC;
2738 break;
2742 if (workFlags & MAGIC_WUPC) {
2743 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2744 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2745 if (g_dbglevel >= DBG_ERROR) Dbprintf("wupC1 error");
2746 errormsg = MAGIC_WUPC;
2747 break;
2750 if (is1b == false) {
2751 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2752 if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) {
2753 if (g_dbglevel >= DBG_INFO) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2754 is1b = true;
2755 continue;
2760 // read block
2761 if ((mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_READBLOCK, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL) != MAX_MIFARE_FRAME_SIZE)) {
2762 if (g_dbglevel >= DBG_ERROR) Dbprintf("read block send command error");
2763 errormsg = 0;
2764 break;
2767 memcpy(data, receivedAnswer, sizeof(data));
2769 // send HALT
2770 if (workFlags & MAGIC_HALT) {
2771 mifare_classic_halt(NULL);
2774 isOK = true;
2775 break;
2777 // if MAGIC_DATAIN, the data stays on device side.
2778 if (workFlags & MAGIC_DATAIN) {
2779 if (isOK) {
2780 memcpy(datain, data, sizeof(data));
2782 } else {
2783 if (isOK) {
2784 reply_old(CMD_ACK, 1, 0, 0, data, sizeof(data));
2785 } else {
2786 OnErrorMagic(errormsg);
2790 if (workFlags & MAGIC_OFF) {
2791 OnSuccessMagic();
2794 iso14a_set_timeout(timeout);
2797 static void mf_reset_card(void) {
2798 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2799 SpinDelay(40);
2800 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2803 void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) {
2804 // variables
2805 uint8_t rec[1] = {0x00};
2806 uint8_t recpar[1] = {0x00};
2807 uint8_t rats[4] = {ISO14443A_CMD_RATS, 0x80, 0x31, 0x73};
2808 uint8_t rdblf0[4] = {ISO14443A_CMD_READBLOCK, 0xF0, 0x8D, 0x5f};
2809 uint8_t rdbl00[4] = {ISO14443A_CMD_READBLOCK, 0x00, 0x02, 0xa8};
2810 uint8_t gen4gdmAuth[4] = {MIFARE_MAGIC_GDM_AUTH_KEY, 0x00, 0x6C, 0x92};
2811 uint8_t gen4gdmGetConf[4] = {MIFARE_MAGIC_GDM_READ_CFG, 0x00, 0x39, 0xF7};
2812 uint8_t gen4GetConf[8] = {GEN_4GTU_CMD, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_GETCNF, 0, 0};
2813 uint8_t superGen1[9] = {0x0A, 0x00, 0x00, 0xA6, 0xB0, 0x00, 0x10, 0x14, 0x1D};
2814 bool isGen2 = false;
2816 uint8_t *par = BigBuf_calloc(MAX_PARITY_SIZE);
2817 uint8_t *buf = BigBuf_calloc(PM3_CMD_DATA_SIZE);
2818 uint8_t *uid = BigBuf_calloc(10);
2819 uint16_t flag = MAGIC_FLAG_NONE;
2820 uint32_t cuid = 0;
2821 int res = 0;
2823 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2825 // Generation 1 test
2826 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2827 if (ReaderReceive(rec, 1, recpar) && (rec[0] == 0x0A)) {
2829 flag = MAGIC_FLAG_GEN_1A;
2830 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2831 uint16_t tmp = ReaderReceive(rec, 1, recpar);
2832 if ((tmp && (rec[0] != 0x0A)) || (tmp == 0)) {
2833 flag = MAGIC_FLAG_GEN_1B;
2836 // check for GDM config
2837 ReaderTransmit(gen4gdmGetConf, sizeof(gen4gdmGetConf), NULL);
2838 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2839 if (res > 1) {
2840 flag |= MAGIC_FLAG_GDM_WUP_40;
2844 mf_reset_card();
2846 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2847 if (res) {
2848 // Check for Magic Gen4 GTU with default password:
2849 // Get config should return 30 or 32 bytes
2850 AddCrc14A(gen4GetConf, sizeof(gen4GetConf) - 2);
2851 ReaderTransmit(gen4GetConf, sizeof(gen4GetConf), NULL);
2852 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2853 if (res == 32 || res == 34) {
2854 flag |= MAGIC_FLAG_GEN_4GTU;
2858 // reset card
2859 mf_reset_card();
2861 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, false);
2862 if (res) {
2863 if (cuid == 0xAA55C396) {
2864 flag |= MAGIC_FLAG_GEN_UNFUSED;
2867 ReaderTransmit(rats, sizeof(rats), NULL);
2868 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2870 if (res) {
2871 if (memcmp(buf, "\x09\x78\x00\x91\x02\xDA\xBC\x19\x10", 9) == 0) {
2872 // test for some MFC gen2
2873 isGen2 = true;
2874 flag |= MAGIC_FLAG_GEN_2;
2875 } else if (memcmp(buf, "\x0D\x78\x00\x71\x02\x88\x49\xA1\x30\x20\x15\x06\x08\x56\x3D", 15) == 0) {
2876 // test for some MFC 7b gen2
2877 isGen2 = true;
2878 flag |= MAGIC_FLAG_GEN_2;
2879 } else if (memcmp(buf, "\x0A\x78\x00\x81\x02\xDB\xA0\xC1\x19\x40\x2A\xB5", 12) == 0) {
2880 // test for Ultralight magic gen2
2881 isGen2 = true;
2882 flag |= MAGIC_FLAG_GEN_2;
2883 } else if (memcmp(buf, "\x85\x00\x00\xA0\x00\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x41\xDF", 18) == 0) {
2884 // test for Ultralight EV1 magic gen2
2885 isGen2 = true;
2886 flag |= MAGIC_FLAG_GEN_2;
2887 } else if (memcmp(buf, "\x85\x00\x00\xA0\x0A\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x16\xD7", 18) == 0) {
2888 // test for some other Ultralight EV1 magic gen2
2889 isGen2 = true;
2890 flag |= MAGIC_FLAG_GEN_2;
2891 } else if (memcmp(buf, "\x85\x00\x00\xA0\x0A\x00\x0A\xB0\x00\x00\x00\x00\x00\x00\x00\x00\x18\x4D", 18) == 0) {
2892 // test for some other Ultralight magic gen2
2893 isGen2 = true;
2894 flag |= MAGIC_FLAG_GEN_2;
2895 } else if (memcmp(buf, "\x85\x00\x00\xA0\x00\x00\x0A\xA5\x00\x04\x04\x02\x01\x00\x0F\x03\x79\x0C", 18) == 0) {
2896 // test for NTAG213 magic gen2
2897 isGen2 = true;
2898 flag |= MAGIC_FLAG_GEN_2;
2901 // test for super card
2902 ReaderTransmit(superGen1, sizeof(superGen1), NULL);
2903 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2904 if (res == 22) {
2905 uint8_t isGen = MAGIC_FLAG_SUPER_GEN1;
2907 // check for super card gen2
2908 // not available after RATS, reset card before executing
2909 mf_reset_card();
2911 iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2912 ReaderTransmit(rdbl00, sizeof(rdbl00), NULL);
2913 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2914 if (res == 18) {
2915 isGen = MAGIC_FLAG_SUPER_GEN2;
2918 flag |= isGen;
2922 if (is_mfc == false) {
2923 // magic ntag test
2924 mf_reset_card();
2926 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2927 if (res == 2) {
2928 ReaderTransmit(rdblf0, sizeof(rdblf0), NULL);
2929 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2930 if (res == 18) {
2931 flag |= MAGIC_FLAG_NTAG21X;
2934 } else {
2936 struct Crypto1State mpcs = {0, 0};
2937 struct Crypto1State *pcs;
2938 pcs = &mpcs;
2940 // CUID (with default sector 0 B key) test
2941 // regular cards will NAK the WRITEBLOCK(0) command, while DirectWrite will ACK it
2942 // if we do get an ACK, we immediately abort to ensure nothing is ever actually written
2943 // only perform test if we haven't already identified Gen2. No need test if we have a positive identification already
2944 if (isGen2 == false) {
2945 mf_reset_card();
2947 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2948 if (res) {
2950 uint64_t tmpkey = bytes_to_num(key, 6);
2951 if (mifare_classic_authex(pcs, cuid, 0, keytype, tmpkey, AUTH_FIRST, NULL, NULL) == 0) {
2953 if ((mifare_sendcmd_short(pcs, 1, ISO14443A_CMD_WRITEBLOCK, 0, buf, PM3_CMD_DATA_SIZE, par, NULL) == 1) && (buf[0] == 0x0A)) {
2954 flag |= MAGIC_FLAG_GEN_2;
2955 // turn off immediately to ensure nothing ever accidentally writes to the block
2956 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2959 crypto1_deinit(pcs);
2963 // magic MFC Gen3 test 1
2964 mf_reset_card();
2966 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2967 if (res) {
2968 ReaderTransmit(rdbl00, sizeof(rdbl00), NULL);
2969 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2970 if (res == 18) {
2971 flag |= MAGIC_FLAG_GEN_3;
2975 // magic MFC Gen4 GDM magic auth test
2976 mf_reset_card();
2978 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2979 if (res) {
2980 ReaderTransmit(gen4gdmAuth, sizeof(gen4gdmAuth), NULL);
2981 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
2982 if (res == 4) {
2983 flag |= MAGIC_FLAG_GDM_AUTH;
2987 // QL88 test
2988 mf_reset_card();
2990 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2991 if (res) {
2992 if (mifare_classic_authex(pcs, cuid, 68, MF_KEY_B, 0x707B11FC1481, AUTH_FIRST, NULL, NULL) == 0) {
2993 flag |= MAGIC_FLAG_QL88;
2995 crypto1_deinit(pcs);
3000 // GDM alt magic wakeup (20)
3001 ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL);
3002 if (ReaderReceive(rec, 1, recpar) && (rec[0] == 0x0a)) {
3003 flag |= MAGIC_FLAG_GDM_WUP_20;
3006 reply_ng(CMD_HF_MIFARE_CIDENT, PM3_SUCCESS, (uint8_t *)&flag, sizeof(uint16_t));
3007 // turns off
3008 OnSuccessMagic();
3009 BigBuf_free();
3012 void MifareHasStaticNonce(void) {
3014 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3016 // variables
3017 int retval = PM3_SUCCESS;
3018 uint32_t nt = 0;
3019 uint8_t *uid = BigBuf_malloc(10);
3021 memset(uid, 0x00, 10);
3023 uint8_t data[1] = { NONCE_FAIL };
3024 struct Crypto1State mpcs = {0, 0};
3025 struct Crypto1State *pcs;
3026 pcs = &mpcs;
3028 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3030 uint8_t counter = 0;
3031 for (uint8_t i = 0; i < 3; i++) {
3033 if (!iso14443a_select_card(uid, NULL, NULL, true, 0, true)) {
3034 retval = PM3_ESOFT;
3035 goto OUT;
3038 uint8_t rec[4] = {0x00};
3039 uint8_t recpar[1] = {0x00};
3040 // Transmit MIFARE_CLASSIC_AUTH 0x60, block 0
3041 int len = mifare_sendcmd_short(pcs, false, MIFARE_AUTH_KEYA, 0, rec, sizeof(rec), recpar, NULL);
3042 if (len != 4) {
3043 retval = PM3_ESOFT;
3044 goto OUT;
3047 // Save the tag nonce (nt)
3048 if (nt == bytes_to_num(rec, 4)) {
3049 counter++;
3052 nt = bytes_to_num(rec, 4);
3054 // some cards with static nonce need to be reset before next query
3055 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3056 LEDsoff();
3057 CHK_TIMEOUT();
3059 memset(rec, 0x00, sizeof(rec));
3062 if (counter) {
3063 Dbprintf("Static nonce......... " _YELLOW_("%08x"), nt);
3064 data[0] = NONCE_STATIC;
3065 } else {
3066 data[0] = NONCE_NORMAL;
3069 OUT:
3070 reply_ng(CMD_HF_MIFARE_STATIC_NONCE, retval, data, sizeof(data));
3071 // turns off
3072 OnSuccessMagic();
3073 BigBuf_free();
3074 crypto1_deinit(pcs);
3077 // FUDAN card w static encrypted nonces
3078 // 2B F9 1C 1B D5 08 48 48 03 A4 B1 B1 75 FF 2D 90
3079 // ^^ ^^
3081 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) {
3082 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3084 LEDsoff();
3085 clear_trace();
3086 set_tracing(true);
3088 int retval = PM3_SUCCESS;
3090 uint8_t data[14] = { NONCE_FAIL };
3092 struct Crypto1State mpcs = {0, 0};
3093 struct Crypto1State *pcs;
3094 pcs = &mpcs;
3096 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3098 uint8_t enc_counter = 0;
3099 uint8_t key_auth_cmd = MIFARE_AUTH_KEYA + key_type;
3100 uint8_t key_auth_cmd_nested = MIFARE_AUTH_KEYA + key_type_nested;
3101 uint64_t ui64key = bytes_to_num(key, 6);
3102 uint64_t ui64key_nested = bytes_to_num(key_nested, 6);
3103 uint32_t oldntenc = 0;
3104 bool need_first_auth = true;
3105 uint32_t cuid;
3106 uint32_t nt;
3107 uint32_t old_nt;
3108 uint32_t ntenc;
3109 uint8_t ntencpar;
3110 if (nr_nested == 0) {
3111 cuid = 0;
3112 if (iso14443a_select_card(NULL, NULL, &cuid, true, 0, true) == false) {
3113 if (g_dbglevel >= DBG_ERROR) Dbprintf("Select error");
3114 retval = PM3_ESOFT;
3115 goto OUT;
3117 if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &old_nt, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) {
3118 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
3119 retval = PM3_ESOFT;
3120 goto OUT;
3123 for (uint8_t i = 0; i < nr_nested; i++) {
3124 if (need_first_auth) {
3125 cuid = 0;
3127 if (hardreset) {
3128 if (g_dbglevel >= DBG_EXTENDED) {
3129 Dbprintf("RF reset");
3131 // some cards need longer than mf_reset_card() to see effect on nT
3132 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3133 SpinDelay(150);
3134 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3136 if (g_dbglevel >= DBG_EXTENDED) {
3137 Dbprintf("select");
3139 if (iso14443a_select_card(NULL, NULL, &cuid, true, 0, true) == false) {
3140 retval = PM3_ESOFT;
3141 goto OUT;
3143 if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &old_nt, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) {
3144 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
3145 retval = PM3_ESOFT;
3146 goto OUT;
3148 if (!reset && !hardreset) {
3149 need_first_auth = false;
3151 if (addread) {
3152 uint8_t dataread[16] = {0x00};
3153 mifare_classic_readblock(pcs, block_no, dataread);
3155 if (addauth) {
3156 if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_NESTED, &nt, NULL, NULL, NULL, false, false)) {
3157 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
3158 retval = PM3_ESOFT;
3159 goto OUT;
3160 } else if (g_dbglevel >= DBG_EXTENDED) {
3161 Dbprintf("Nonce distance: %i", nonce_distance(old_nt, nt));
3163 old_nt = nt;
3167 nt = 0;
3168 ntenc = 0;
3169 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)) {
3170 if (g_dbglevel >= DBG_ERROR) Dbprintf("Nested auth error");
3171 need_first_auth = true;
3172 } else if (g_dbglevel >= DBG_EXTENDED) {
3173 Dbprintf("Nonce distance: %i", nonce_distance(old_nt, nt));
3175 old_nt = nt;
3176 if (oldntenc == 0) {
3177 oldntenc = ntenc;
3178 } else if (ntenc == oldntenc) {
3179 enc_counter++;
3183 if (enc_counter) {
3184 data[0] = NONCE_STATIC_ENC;
3185 data[1] = (cuid >> 24) & 0xFF;
3186 data[2] = (cuid >> 16) & 0xFF;
3187 data[3] = (cuid >> 8) & 0xFF;
3188 data[4] = (cuid >> 0) & 0xFF;
3189 data[5] = (nt >> 24) & 0xFF;
3190 data[6] = (nt >> 16) & 0xFF;
3191 data[7] = (nt >> 8) & 0xFF;
3192 data[8] = (nt >> 0) & 0xFF;
3193 data[9] = (ntenc >> 24) & 0xFF;
3194 data[10] = (ntenc >> 16) & 0xFF;
3195 data[11] = (ntenc >> 8) & 0xFF;
3196 data[12] = (ntenc >> 0) & 0xFF;
3197 data[13] = ntencpar;
3198 } else {
3199 data[0] = NONCE_NORMAL;
3202 OUT:
3203 crypto1_deinit(pcs);
3205 reply_ng(CMD_HF_MIFARE_STATIC_ENCRYPTED_NONCE, retval, data, sizeof(data));
3206 // turns off
3207 OnSuccessMagic();
3208 BigBuf_free();
3211 void OnSuccessMagic(void) {
3212 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3213 LEDsoff();
3214 set_tracing(false);
3217 void OnErrorMagic(uint8_t reason) {
3218 // ACK, ISOK, reason,0,0,0
3219 reply_mix(CMD_ACK, 0, reason, 0, 0, 0);
3220 OnSuccessMagic();
3223 int DoGen3Cmd(uint8_t *cmd, uint8_t cmd_len) {
3224 int retval = PM3_SUCCESS;
3225 uint8_t *par = BigBuf_calloc(MAX_PARITY_SIZE);
3226 uint8_t *buf = BigBuf_calloc(PM3_CMD_DATA_SIZE);
3228 LED_B_ON();
3229 uint32_t save_iso14a_timeout = iso14a_get_timeout();
3230 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 2000); // 2 seconds timeout
3232 ReaderTransmit(cmd, cmd_len, NULL);
3233 int res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3234 if (res == 4 && memcmp(buf, "\x90\x00\xfd\x07", 4) == 0) {
3235 // timeout for card memory reset
3236 SpinDelay(1000);
3237 } else {
3238 if (g_dbglevel >= DBG_ERROR) Dbprintf("Card operation not completed");
3239 retval = PM3_ESOFT;
3241 iso14a_set_timeout(save_iso14a_timeout);
3242 LED_B_OFF();
3243 return retval;
3246 void MifareGen3UID(uint8_t uidlen, uint8_t *uid) {
3247 int retval = PM3_SUCCESS;
3248 uint8_t uid_cmd[5] = { 0x90, 0xfb, 0xcc, 0xcc, 0x07 };
3249 uint8_t *old_uid = BigBuf_calloc(10);
3250 uint8_t *cmd = BigBuf_calloc(sizeof(uid_cmd) + uidlen + 2);
3251 iso14a_card_select_t *card_info = (iso14a_card_select_t *) BigBuf_calloc(sizeof(iso14a_card_select_t));
3253 LEDsoff();
3254 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3255 clear_trace();
3256 set_tracing(true);
3258 if (iso14443a_select_card(old_uid, card_info, NULL, true, 0, true) == false) {
3259 retval = PM3_ESOFT;
3260 goto OUT;
3262 if (card_info->uidlen != uidlen) {
3263 if (g_dbglevel >= DBG_ERROR) Dbprintf("Wrong UID length");
3264 retval = PM3_ESOFT;
3265 goto OUT;
3268 memcpy(cmd, uid_cmd, sizeof(uid_cmd));
3269 memcpy(&cmd[sizeof(uid_cmd)], uid, uidlen);
3270 AddCrc14A(cmd, sizeof(uid_cmd) + uidlen);
3272 retval = DoGen3Cmd(cmd, sizeof(uid_cmd) + uidlen + 2);
3274 OUT:
3275 reply_ng(CMD_HF_MIFARE_GEN3UID, retval, old_uid, uidlen);
3276 // turns off
3277 OnSuccessMagic();
3278 BigBuf_free();
3281 void MifareGen3Blk(uint8_t block_len, uint8_t *block) {
3283 int retval = PM3_SUCCESS;
3284 uint8_t block_cmd[5] = { 0x90, 0xf0, 0xcc, 0xcc, 0x10 };
3285 uint8_t cmdlen = sizeof(block_cmd) + MAX_MIFARE_FRAME_SIZE;
3286 uint8_t *cmd = BigBuf_calloc(cmdlen);
3288 iso14a_card_select_t *card_info = (iso14a_card_select_t *) BigBuf_calloc(sizeof(iso14a_card_select_t));
3290 LEDsoff();
3291 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3292 clear_trace();
3293 set_tracing(true);
3295 if (iso14443a_select_card(NULL, card_info, NULL, true, 0, true) == false) {
3296 retval = PM3_ESOFT;
3297 goto OUT;
3300 bool doReselect = false;
3301 if (block_len < MIFARE_BLOCK_SIZE) {
3302 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)) {
3303 if (g_dbglevel >= DBG_ERROR) Dbprintf("Read manufacturer block failed");
3304 retval = PM3_ESOFT;
3305 goto OUT;
3307 doReselect = true;
3310 if (block_len > 0) {
3311 memcpy(cmd, block_cmd, sizeof(block_cmd));
3312 memcpy(&cmd[sizeof(block_cmd)], block, block_len);
3313 int ofs = sizeof(block_cmd);
3314 if (card_info->uidlen == 4) {
3315 cmd[ofs + 4] = cmd[ofs + 0] ^ cmd[ofs + 1] ^ cmd[ofs + 2] ^ cmd[ofs + 3];
3316 ofs += 5;
3317 } else if (card_info->uidlen == 7) {
3318 ofs += 7;
3319 } else {
3320 if (g_dbglevel >= DBG_ERROR) Dbprintf("Wrong Card UID length");
3321 retval = PM3_ESOFT;
3322 goto OUT;
3324 cmd[ofs++] = card_info->sak;
3325 cmd[ofs++] = card_info->atqa[0];
3326 cmd[ofs++] = card_info->atqa[1];
3327 AddCrc14A(cmd, sizeof(block_cmd) + MIFARE_BLOCK_SIZE);
3329 if (doReselect) {
3330 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
3331 retval = PM3_ESOFT;
3332 goto OUT;
3336 retval = DoGen3Cmd(cmd, sizeof(block_cmd) + MAX_MIFARE_FRAME_SIZE);
3339 OUT:
3340 reply_ng(CMD_HF_MIFARE_GEN3BLK, retval, &cmd[sizeof(block_cmd)], MIFARE_BLOCK_SIZE);
3341 // turns off
3342 OnSuccessMagic();
3343 BigBuf_free();
3346 void MifareGen3Freez(void) {
3348 LEDsoff();
3349 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3350 clear_trace();
3351 set_tracing(true);
3353 int retval = PM3_SUCCESS;
3354 uint8_t freeze_cmd[7] = { 0x90, 0xfd, 0x11, 0x11, 0x00, 0xe7, 0x91 };
3356 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3357 retval = PM3_ESOFT;
3358 goto OUT;
3361 retval = DoGen3Cmd(freeze_cmd, sizeof(freeze_cmd));
3363 OUT:
3364 reply_ng(CMD_HF_MIFARE_GEN3FREEZ, retval, NULL, 0);
3365 // turns off
3366 OnSuccessMagic();
3367 BigBuf_free();
3370 void MifareG4ReadBlk(uint8_t blockno, uint8_t *pwd, uint8_t workFlags) {
3371 bool setup = ((workFlags & MAGIC_INIT) == MAGIC_INIT) ;
3372 bool done = ((workFlags & MAGIC_OFF) == MAGIC_OFF) ;
3374 int res = 0;
3375 int retval = PM3_SUCCESS;
3377 uint8_t *buf = BigBuf_malloc(PM3_CMD_DATA_SIZE);
3378 if (buf == NULL) {
3379 retval = PM3_EMALLOC;
3380 goto OUT;
3383 uint8_t *par = BigBuf_malloc(MAX_PARITY_SIZE);
3384 if (par == NULL) {
3385 retval = PM3_EMALLOC;
3386 goto OUT;
3389 if (setup) {
3390 LEDsoff();
3391 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3392 clear_trace();
3393 set_tracing(true);
3395 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3396 retval = PM3_ESOFT;
3397 goto OUT;
3401 LED_B_ON();
3403 static uint32_t save_iso14a_timeout;
3404 if (setup) {
3405 save_iso14a_timeout = iso14a_get_timeout();
3406 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 1000); // 2 seconds timeout
3409 uint8_t cmd[] = { GEN_4GTU_CMD, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_READ, blockno,
3410 0x00, 0x00
3413 memcpy(cmd + 1, pwd, 4);
3415 AddCrc14A(cmd, sizeof(cmd) - 2);
3417 ReaderTransmit(cmd, sizeof(cmd), NULL);
3418 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3420 if (res != 18) {
3421 retval = PM3_ESOFT;
3424 if (done || retval != 0) {
3425 iso14a_set_timeout(save_iso14a_timeout);
3428 LED_B_OFF();
3430 OUT:
3431 reply_ng(CMD_HF_MIFARE_G4_RDBL, retval, buf, res);
3433 // turns off
3434 if (done || retval != 0) {
3435 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3438 LEDsoff();
3439 if (done || retval != 0) {
3440 set_tracing(false);
3443 BigBuf_free();
3446 void MifareG4WriteBlk(uint8_t blockno, uint8_t *pwd, uint8_t *data, uint8_t workFlags) {
3447 bool setup = ((workFlags & MAGIC_INIT) == MAGIC_INIT) ;
3448 bool done = ((workFlags & MAGIC_OFF) == MAGIC_OFF) ;
3450 int res = 0;
3451 int retval = PM3_SUCCESS;
3453 uint8_t *buf = BigBuf_malloc(PM3_CMD_DATA_SIZE);
3454 if (buf == NULL) {
3455 retval = PM3_EMALLOC;
3456 goto OUT;
3459 // check args
3460 if (data == NULL) {
3461 retval = PM3_EINVARG;
3462 goto OUT;
3465 uint8_t *par = BigBuf_malloc(MAX_PARITY_SIZE);
3466 if (par == NULL) {
3467 retval = PM3_EMALLOC;
3468 goto OUT;
3471 if (setup) {
3472 LEDsoff();
3473 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3474 clear_trace();
3475 set_tracing(true);
3477 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3478 retval = PM3_ESOFT;
3479 goto OUT;
3483 LED_B_ON();
3485 static uint32_t save_iso14a_timeout;
3486 if (setup) {
3487 save_iso14a_timeout = iso14a_get_timeout();
3488 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 1000); // 2 seconds timeout
3491 uint8_t cmd[] = { GEN_4GTU_CMD, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_WRITE, blockno,
3492 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3493 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3494 0x00, 0x00
3497 memcpy(cmd + 1, pwd, 4);
3498 memcpy(cmd + 7, data, 16);
3500 AddCrc14A(cmd, sizeof(cmd) - 2);
3502 ReaderTransmit(cmd, sizeof(cmd), NULL);
3503 res = ReaderReceive(buf, PM3_CMD_DATA_SIZE, par);
3505 if ((res != 4) || (memcmp(buf, "\x90\x00\xfd\x07", 4) != 0)) {
3506 retval = PM3_ESOFT;
3509 if (done || retval != 0) {
3510 iso14a_set_timeout(save_iso14a_timeout);
3512 LED_B_OFF();
3514 OUT:
3515 reply_ng(CMD_HF_MIFARE_G4_WRBL, retval, buf, res);
3516 // turns off
3517 if (done || retval != 0) {
3518 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3521 LEDsoff();
3522 if (done || retval != 0) {
3523 set_tracing(false);
3526 BigBuf_free();
3529 void MifareSetMod(uint8_t *datain) {
3531 uint8_t mod = datain[0];
3532 uint64_t ui64Key = bytes_to_num(datain + 1, 6);
3534 // variables
3535 uint16_t isOK = PM3_EUNDEF;
3536 uint8_t *uid = BigBuf_calloc(10);
3538 uint32_t cuid = 0;
3539 struct Crypto1State mpcs = {0, 0};
3540 struct Crypto1State *pcs = &mpcs;
3542 uint8_t *buf = BigBuf_calloc(MAX_MIFARE_FRAME_SIZE);
3543 uint8_t *par = BigBuf_calloc(MAX_MIFARE_PARITY_SIZE);
3545 LEDsoff();
3546 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3548 clear_trace();
3549 set_tracing(true);
3551 LED_A_ON();
3553 while (true) {
3554 if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) {
3555 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
3556 break;
3559 if (mifare_classic_auth(pcs, cuid, 0, 0, ui64Key, AUTH_FIRST)) {
3560 if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error");
3561 break;
3564 int respLen;
3565 if (((respLen = mifare_sendcmd_short(pcs, CRYPT_ALL, MIFARE_EV1_SETMOD, mod, buf, MAX_MIFARE_FRAME_SIZE, par, NULL)) != 1) || (buf[0] != 0x0a)) {
3566 if (g_dbglevel >= DBG_ERROR) Dbprintf("SetMod error; response[0]: %hhX, len: %d", buf[0], respLen);
3567 break;
3570 if (mifare_classic_halt(pcs)) {
3571 if (g_dbglevel >= DBG_ERROR) Dbprintf("Halt error");
3572 break;
3575 isOK = PM3_SUCCESS;
3576 break;
3579 crypto1_deinit(pcs);
3581 LED_B_ON();
3582 reply_ng(CMD_HF_MIFARE_SETMOD, isOK, NULL, 0);
3583 LED_B_OFF();
3585 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3586 LEDsoff();
3587 BigBuf_free();
3591 // DESFIRE
3593 void Mifare_DES_Auth1(uint8_t arg0, uint8_t *datain) {
3594 uint8_t dataout[12] = {0x00};
3595 uint32_t cuid = 0;
3597 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3598 clear_trace();
3599 set_tracing(true);
3601 int len = iso14443a_select_card(NULL, NULL, &cuid, true, 0, false);
3602 if (!len) {
3603 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
3604 OnError(1);
3605 return;
3608 if (mifare_desfire_des_auth1(cuid, dataout) != PM3_SUCCESS) {
3609 if (g_dbglevel >= DBG_ERROR) Dbprintf("Authentication part1: Fail.");
3610 OnError(4);
3611 return;
3614 if (g_dbglevel >= DBG_EXTENDED) DbpString("AUTH 1 FINISHED");
3615 reply_mix(CMD_ACK, 1, cuid, 0, dataout, sizeof(dataout));
3618 void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain) {
3619 uint32_t cuid = arg0;
3620 uint8_t key[16] = {0x00};
3621 uint8_t dataout[12] = {0x00};
3622 uint8_t isOK = 0;
3624 memcpy(key, datain, 16);
3626 isOK = mifare_desfire_des_auth2(cuid, key, dataout);
3628 if (isOK != PM3_SUCCESS) {
3629 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("Authentication part2: Failed");
3630 OnError(4);
3631 return;
3634 if (g_dbglevel >= DBG_EXTENDED) DbpString("AUTH 2 FINISHED");
3636 reply_old(CMD_ACK, isOK, 0, 0, dataout, sizeof(dataout));
3637 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
3638 LEDsoff();
3639 set_tracing(false);
3643 // Tear-off attack against MFU.
3644 // - Moebius et al
3645 void MifareU_Otp_Tearoff(uint8_t blno, uint32_t tearoff_time, uint8_t *data_testwrite) {
3646 uint8_t blockNo = blno;
3648 if (g_dbglevel >= DBG_DEBUG) DbpString("Preparing OTP tear-off");
3650 if (tearoff_time > 43000) {
3651 tearoff_time = 43000;
3654 g_tearoff_delay_us = tearoff_time;
3655 g_tearoff_enabled = true;
3657 LEDsoff();
3658 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3659 clear_trace();
3660 set_tracing(true);
3662 // write cmd to send, include CRC
3663 // 1b write, 1b block, 4b data, 2 crc
3664 uint8_t cmd[] = {
3665 MIFARE_ULC_WRITE, blockNo,
3666 data_testwrite[0], data_testwrite[1], data_testwrite[2], data_testwrite[3],
3667 0, 0
3669 AddCrc14A(cmd, sizeof(cmd) - 2);
3671 // anticollision / select card
3672 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3673 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
3674 OnError(1);
3675 reply_ng(CMD_HF_MFU_OTP_TEAROFF, PM3_EFAILED, NULL, 0);
3676 return;
3678 // send
3679 LED_D_ON();
3680 ReaderTransmit(cmd, sizeof(cmd), NULL);
3681 tearoff_hook();
3682 reply_ng(CMD_HF_MFU_OTP_TEAROFF, PM3_SUCCESS, NULL, 0);
3686 // Tear-off attack against MFU counter
3687 void MifareU_Counter_Tearoff(uint8_t counter, uint32_t tearoff_time, uint8_t *datain) {
3689 if (tearoff_time > 43000) {
3690 tearoff_time = 43000;
3693 LEDsoff();
3694 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
3695 clear_trace();
3696 set_tracing(true);
3698 // Send MFU counter increase cmd
3699 uint8_t cmd[] = {
3700 MIFARE_ULEV1_INCR_CNT,
3701 counter,
3702 datain[0], // lsb
3703 datain[1],
3704 datain[2], // msb
3705 datain[3], // rfu
3709 AddCrc14A(cmd, sizeof(cmd) - 2);
3711 // anticollision / select card
3712 if (iso14443a_select_card(NULL, NULL, NULL, true, 0, true) == false) {
3713 if (g_dbglevel >= DBG_ERROR) Dbprintf("Can't select card");
3714 OnError(1);
3715 switch_off();
3716 LEDsoff();
3717 return;
3720 // send
3721 ReaderTransmit(cmd, sizeof(cmd), NULL);
3722 LED_D_ON();
3723 SpinDelayUsPrecision(tearoff_time);
3724 switch_off();
3725 LEDsoff();
3726 reply_ng(CMD_HF_MFU_COUNTER_TEAROFF, PM3_SUCCESS, NULL, 0);