text
[RRG-proxmark3.git] / armsrc / mifarecmd.c
blob4330f2c4f3e5182fedd8028ed9e4ce966468de7d
1 //-----------------------------------------------------------------------------
2 // Merlok - June 2011, 2012
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
5 // Midnitesnake - Dec 2013
6 // Andy Davies - Apr 2014
7 // Iceman - May 2014,2015,2016
8 //
9 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
10 // at your option, any later version. See the LICENSE.txt file for the text of
11 // the license.
12 //-----------------------------------------------------------------------------
13 // Routines to support ISO 14443 type A.
14 //-----------------------------------------------------------------------------
16 #include "mifarecmd.h"
18 #include "pmflash.h"
19 #include "proxmark3_arm.h"
20 #include "string.h"
21 #include "mifareutil.h"
22 #include "protocols.h"
23 #include "parity.h"
24 #include "BigBuf.h"
25 #include "cmd.h"
26 #include "flashmem.h"
27 #include "fpgaloader.h"
28 #include "iso14443a.h"
29 #include "mifaredesfire.h"
30 #include "util.h"
31 #include "commonutil.h"
32 #include "crc16.h"
33 #include "dbprint.h"
34 #include "ticks.h"
35 #include "usb_cdc.h" // usb_poll_validate_length
36 #include "spiffs.h" // spiffs
37 #include "appmain.h" // print_stack_usage
39 #ifndef HARDNESTED_AUTHENTICATION_TIMEOUT
40 # define HARDNESTED_AUTHENTICATION_TIMEOUT 848 // card times out 1ms after wrong authentication (according to NXP documentation)
41 #endif
42 #ifndef HARDNESTED_PRE_AUTHENTICATION_LEADTIME
43 # define HARDNESTED_PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication
44 #endif
46 // send an incomplete dummy response in order to trigger the card's authentication failure timeout
47 #ifndef CHK_TIMEOUT
48 # define CHK_TIMEOUT(void) { \
49 ReaderTransmit(&dummy_answer, 1, NULL); \
50 uint32_t timeout = GetCountSspClk() + HARDNESTED_AUTHENTICATION_TIMEOUT; \
51 while (GetCountSspClk() < timeout) {}; \
53 #endif
55 static uint8_t dummy_answer = 0;
57 //-----------------------------------------------------------------------------
58 // Select, Authenticate, Read a MIFARE tag.
59 // read block
60 //-----------------------------------------------------------------------------
61 void MifareReadBlock(uint8_t blockNo, uint8_t keyType, uint8_t *datain) {
62 // params
63 uint64_t ui64Key = 0;
64 ui64Key = bytes_to_num(datain, 6);
66 // variables
67 uint8_t dataoutbuf[16] = {0x00};
68 uint8_t uid[10] = {0x00};
69 uint32_t cuid = 0, status = PM3_EOPABORTED;
71 struct Crypto1State mpcs = {0, 0};
72 struct Crypto1State *pcs;
73 pcs = &mpcs;
75 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
77 clear_trace();
78 set_tracing(true);
80 LED_A_ON();
81 LED_B_OFF();
82 LED_C_OFF();
84 while (true) {
85 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
86 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
87 break;
90 if (mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) {
91 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Auth error");
92 break;
95 if (mifare_classic_readblock(pcs, cuid, blockNo, dataoutbuf)) {
96 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Read block error");
97 break;
100 if (mifare_classic_halt(pcs, cuid)) {
101 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
102 break;
105 status = PM3_SUCCESS;
106 break;
109 crypto1_deinit(pcs);
111 if (DBGLEVEL >= 2) DbpString("READ BLOCK FINISHED");
113 LED_B_ON();
114 reply_ng(CMD_HF_MIFARE_READBL, status, dataoutbuf, 16);
115 LED_B_OFF();
117 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
118 LEDsoff();
121 void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes) {
123 bool turnOffField = (arg0 == 1);
125 LED_A_ON();
126 LED_B_OFF();
127 LED_C_OFF();
129 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
131 clear_trace();
132 set_tracing(true);
134 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
135 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
136 OnError(0);
137 return;
140 if (!mifare_ultra_auth(keybytes)) {
141 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Authentication failed");
142 OnError(1);
143 return;
146 if (turnOffField) {
147 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
148 LEDsoff();
150 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
153 // Arg0 = BlockNo,
154 // Arg1 = UsePwd bool
155 // datain = PWD bytes,
156 void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) {
157 uint8_t blockNo = arg0;
158 uint8_t dataout[16] = {0x00};
159 bool useKey = (arg1 == 1); //UL_C
160 bool usePwd = (arg1 == 2); //UL_EV1/NTAG
162 LEDsoff();
163 LED_A_ON();
164 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
166 clear_trace();
167 set_tracing(true);
169 int len = iso14443a_select_card(NULL, NULL, NULL, true, 0, true);
170 if (!len) {
171 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card (RC:%02X)", len);
172 OnError(1);
173 return;
176 // UL-C authentication
177 if (useKey) {
178 uint8_t key[16] = {0x00};
179 memcpy(key, datain, sizeof(key));
181 if (!mifare_ultra_auth(key)) {
182 OnError(1);
183 return;
187 // UL-EV1 / NTAG authentication
188 if (usePwd) {
189 uint8_t pwd[4] = {0x00};
190 memcpy(pwd, datain, 4);
191 uint8_t pack[4] = {0, 0, 0, 0};
192 if (!mifare_ul_ev1_auth(pwd, pack)) {
193 OnError(1);
194 return;
198 if (mifare_ultra_readblock(blockNo, dataout)) {
199 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Read block error");
200 OnError(2);
201 return;
204 if (mifare_ultra_halt()) {
205 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
206 OnError(3);
207 return;
210 reply_mix(CMD_ACK, 1, 0, 0, dataout, 16);
211 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
212 LEDsoff();
215 //-----------------------------------------------------------------------------
216 // Select, Authenticate, Read a MIFARE tag.
217 // read sector (data = 4 x 16 bytes = 64 bytes, or 16 x 16 bytes = 256 bytes)
218 //-----------------------------------------------------------------------------
219 void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t *datain) {
220 // params
221 uint8_t sectorNo = arg0;
222 uint8_t keyType = arg1;
223 uint64_t ui64Key = 0;
224 ui64Key = bytes_to_num(datain, 6);
226 // variables
227 uint8_t isOK = 0;
228 uint8_t dataoutbuf[16 * 16];
229 uint8_t uid[10] = {0x00};
230 uint32_t cuid = 0;
231 struct Crypto1State mpcs = {0, 0};
232 struct Crypto1State *pcs;
233 pcs = &mpcs;
235 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
237 clear_trace();
238 set_tracing(true);
240 LED_A_ON();
241 LED_B_OFF();
242 LED_C_OFF();
244 isOK = 1;
245 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
246 isOK = 0;
247 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
251 if (isOK && mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_FIRST)) {
252 isOK = 0;
253 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Auth error");
256 for (uint8_t blockNo = 0; isOK && blockNo < NumBlocksPerSector(sectorNo); blockNo++) {
257 if (mifare_classic_readblock(pcs, cuid, FirstBlockOfSector(sectorNo) + blockNo, dataoutbuf + 16 * blockNo)) {
258 isOK = 0;
259 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Read sector %2d block %2d error", sectorNo, blockNo);
260 break;
264 if (mifare_classic_halt(pcs, cuid)) {
265 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
268 if (DBGLEVEL >= 2) DbpString("READ SECTOR FINISHED");
270 crypto1_deinit(pcs);
272 LED_B_ON();
273 reply_old(CMD_ACK, isOK, 0, 0, dataoutbuf, 16 * NumBlocksPerSector(sectorNo));
274 LED_B_OFF();
276 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
277 LEDsoff();
278 set_tracing(false);
281 // arg0 = blockNo (start)
282 // arg1 = Pages (number of blocks)
283 // arg2 = useKey
284 // datain = KEY bytes
285 void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) {
286 LEDsoff();
287 LED_A_ON();
288 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
290 // free eventually allocated BigBuf memory
291 BigBuf_free();
292 BigBuf_Clear_ext(false);
293 clear_trace();
294 set_tracing(true);
296 // params
297 uint8_t blockNo = arg0;
298 uint16_t blocks = arg1;
299 bool useKey = (arg2 == 1); //UL_C
300 bool usePwd = (arg2 == 2); //UL_EV1/NTAG
301 uint32_t countblocks = 0;
302 uint8_t *dataout = BigBuf_malloc(CARD_MEMORY_SIZE);
303 if (dataout == NULL) {
304 Dbprintf("out of memory");
305 OnError(1);
306 return;
309 int len = iso14443a_select_card(NULL, NULL, NULL, true, 0, true);
310 if (!len) {
311 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card (RC:%d)", len);
312 OnError(1);
313 return;
316 // UL-C authentication
317 if (useKey) {
318 uint8_t key[16] = {0x00};
319 memcpy(key, datain, sizeof(key));
321 if (!mifare_ultra_auth(key)) {
322 OnError(1);
323 return;
327 // UL-EV1 / NTAG authentication
328 if (usePwd) {
329 uint8_t pwd[4] = {0x00};
330 memcpy(pwd, datain, sizeof(pwd));
331 uint8_t pack[4] = {0, 0, 0, 0};
333 if (!mifare_ul_ev1_auth(pwd, pack)) {
334 OnError(1);
335 return;
339 for (int i = 0; i < blocks; i++) {
340 if ((i * 4) + 4 >= CARD_MEMORY_SIZE) {
341 Dbprintf("Data exceeds buffer!!");
342 break;
345 len = mifare_ultra_readblock(blockNo + i, dataout + 4 * i);
347 if (len) {
348 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Read block %d error", i);
349 // if no blocks read - error out
350 if (i == 0) {
351 OnError(2);
352 return;
353 } else {
354 //stop at last successful read block and return what we got
355 break;
357 } else {
358 countblocks++;
362 len = mifare_ultra_halt();
363 if (len) {
364 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
365 OnError(3);
366 return;
369 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("Blocks read %d", countblocks);
371 countblocks *= 4;
373 reply_mix(CMD_ACK, 1, countblocks, dataout - BigBuf_get_addr(), 0, 0);
374 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
375 LEDsoff();
376 BigBuf_free();
377 set_tracing(false);
380 //-----------------------------------------------------------------------------
381 // Select, Authenticate, Write a MIFARE tag.
382 // read block
383 //-----------------------------------------------------------------------------
384 void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) {
385 // params
386 uint8_t blockNo = arg0;
387 uint8_t keyType = arg1;
388 uint64_t ui64Key = 0;
389 uint8_t blockdata[16] = {0x00};
391 ui64Key = bytes_to_num(datain, 6);
392 memcpy(blockdata, datain + 10, 16);
394 // variables
395 uint8_t isOK = 0;
396 uint8_t uid[10] = {0x00};
397 uint32_t cuid = 0;
398 struct Crypto1State mpcs = {0, 0};
399 struct Crypto1State *pcs;
400 pcs = &mpcs;
402 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
404 clear_trace();
405 set_tracing(true);
407 LED_A_ON();
408 LED_B_OFF();
409 LED_C_OFF();
411 while (true) {
412 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
413 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
414 break;
417 if (mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) {
418 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Auth error");
419 break;
422 if (mifare_classic_writeblock(pcs, cuid, blockNo, blockdata)) {
423 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Write block error");
424 break;
427 if (mifare_classic_halt(pcs, cuid)) {
428 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
429 break;
432 isOK = 1;
433 break;
436 crypto1_deinit(pcs);
438 if (DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED");
440 reply_mix(CMD_ACK, isOK, 0, 0, 0, 0);
442 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
443 LEDsoff();
444 set_tracing(false);
447 // Arg0 : Block to write to.
448 // Arg1 : 0 = use no authentication.
449 // 1 = use 0x1A authentication.
450 // 2 = use 0x1B authentication.
451 // datain : 4 first bytes is data to be written.
452 // : 4/16 next bytes is authentication key.
453 static void MifareUWriteBlockEx(uint8_t arg0, uint8_t arg1, uint8_t *datain, bool reply) {
454 uint8_t blockNo = arg0;
455 bool useKey = (arg1 == 1); //UL_C
456 bool usePwd = (arg1 == 2); //UL_EV1/NTAG
457 uint8_t blockdata[4] = {0x00};
459 memcpy(blockdata, datain, 4);
461 LEDsoff();
462 LED_A_ON();
463 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
465 clear_trace();
466 set_tracing(true);
468 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
469 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
470 OnError(0);
471 return;
474 // UL-C authentication
475 if (useKey) {
476 uint8_t key[16] = {0x00};
477 memcpy(key, datain + 4, sizeof(key));
479 if (!mifare_ultra_auth(key)) {
480 OnError(1);
481 return;
485 // UL-EV1 / NTAG authentication
486 if (usePwd) {
487 uint8_t pwd[4] = {0x00};
488 memcpy(pwd, datain + 4, 4);
489 uint8_t pack[4] = {0, 0, 0, 0};
490 if (!mifare_ul_ev1_auth(pwd, pack)) {
491 OnError(1);
492 return;
496 if (mifare_ultra_writeblock(blockNo, blockdata)) {
497 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Write block error");
498 OnError(0);
499 return;
502 if (mifare_ultra_halt()) {
503 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
504 OnError(0);
505 return;
508 if (DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED");
510 if (reply)
511 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
512 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
513 LEDsoff();
514 set_tracing(false);
517 void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) {
518 MifareUWriteBlockEx(arg0, arg1, datain, true);
521 // Arg0 : Block to write to.
522 // Arg1 : 0 = use no authentication.
523 // 1 = use 0x1A authentication.
524 // 2 = use 0x1B authentication.
525 // datain : 16 first bytes is data to be written.
526 // : 4/16 next bytes is authentication key.
527 void MifareUWriteBlockCompat(uint8_t arg0, uint8_t arg1, uint8_t *datain) {
528 uint8_t blockNo = arg0;
529 bool useKey = (arg1 == 1); //UL_C
530 bool usePwd = (arg1 == 2); //UL_EV1/NTAG
531 uint8_t blockdata[16] = {0x00};
533 memcpy(blockdata, datain, 16);
535 LEDsoff();
536 LED_A_ON();
537 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
539 clear_trace();
540 set_tracing(true);
542 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
543 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
544 OnError(0);
545 return;
548 // UL-C authentication
549 if (useKey) {
550 uint8_t key[16] = {0x00};
551 memcpy(key, datain + 16, sizeof(key));
553 if (!mifare_ultra_auth(key)) {
554 OnError(1);
555 return;
559 // UL-EV1 / NTAG authentication
560 if (usePwd) {
561 uint8_t pwd[4] = {0x00};
562 memcpy(pwd, datain + 16, 4);
563 uint8_t pack[4] = {0, 0, 0, 0};
564 if (!mifare_ul_ev1_auth(pwd, pack)) {
565 OnError(1);
566 return;
570 if (mifare_ultra_writeblock_compat(blockNo, blockdata)) {
571 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Write block error");
572 OnError(0);
573 return;
576 if (mifare_ultra_halt()) {
577 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
578 OnError(0);
579 return;
582 if (DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED");
584 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
585 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
586 LEDsoff();
587 set_tracing(false);
590 void MifareUSetPwd(uint8_t arg0, uint8_t *datain) {
592 uint8_t pwd[16] = {0x00};
593 uint8_t blockdata[4] = {0x00};
595 memcpy(pwd, datain, 16);
597 LED_A_ON();
598 LED_B_OFF();
599 LED_C_OFF();
600 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
602 clear_trace();
603 set_tracing(true);
605 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
606 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
607 OnError(0);
608 return;
611 blockdata[0] = pwd[7];
612 blockdata[1] = pwd[6];
613 blockdata[2] = pwd[5];
614 blockdata[3] = pwd[4];
615 if (mifare_ultra_writeblock(44, blockdata)) {
616 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Write block error");
617 OnError(44);
618 return;
621 blockdata[0] = pwd[3];
622 blockdata[1] = pwd[2];
623 blockdata[2] = pwd[1];
624 blockdata[3] = pwd[0];
625 if (mifare_ultra_writeblock(45, blockdata)) {
626 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Write block error");
627 OnError(45);
628 return;
631 blockdata[0] = pwd[15];
632 blockdata[1] = pwd[14];
633 blockdata[2] = pwd[13];
634 blockdata[3] = pwd[12];
635 if (mifare_ultra_writeblock(46, blockdata)) {
636 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Write block error");
637 OnError(46);
638 return;
641 blockdata[0] = pwd[11];
642 blockdata[1] = pwd[10];
643 blockdata[2] = pwd[9];
644 blockdata[3] = pwd[8];
645 if (mifare_ultra_writeblock(47, blockdata)) {
646 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Write block error");
647 OnError(47);
648 return;
651 if (mifare_ultra_halt()) {
652 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
653 OnError(0);
654 return;
657 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
658 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
659 LEDsoff();
660 set_tracing(false);
663 // Return 1 if the nonce is invalid else return 0
664 static int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, uint8_t *parity) {
665 return (
666 (oddparity8((Nt >> 24) & 0xFF) == ((parity[0]) ^ oddparity8((NtEnc >> 24) & 0xFF) ^ BIT(Ks1, 16))) && \
667 (oddparity8((Nt >> 16) & 0xFF) == ((parity[1]) ^ oddparity8((NtEnc >> 16) & 0xFF) ^ BIT(Ks1, 8))) && \
668 (oddparity8((Nt >> 8) & 0xFF) == ((parity[2]) ^ oddparity8((NtEnc >> 8) & 0xFF) ^ BIT(Ks1, 0)))
669 ) ? 1 : 0;
672 void MifareAcquireNonces(uint32_t arg0, uint32_t flags) {
674 uint8_t uid[10] = {0x00};
675 uint8_t answer[MAX_MIFARE_FRAME_SIZE] = {0x00};
676 uint8_t par[1] = {0x00};
677 uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00};
678 uint32_t cuid = 0;
679 int16_t isOK = 0;
680 uint16_t num_nonces = 0;
681 uint8_t cascade_levels = 0;
682 uint8_t blockNo = arg0 & 0xff;
683 uint8_t keyType = (arg0 >> 8) & 0xff;
684 bool initialize = flags & 0x0001;
685 bool field_off = flags & 0x0004;
686 bool have_uid = false;
688 LED_A_ON();
689 LED_C_OFF();
691 BigBuf_free();
692 BigBuf_Clear_ext(false);
693 clear_trace();
694 set_tracing(true);
696 if (initialize)
697 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
699 LED_C_ON();
701 while (num_nonces < PM3_CMD_DATA_SIZE / 4) {
703 // Test if the action was cancelled
704 if (BUTTON_PRESS()) {
705 isOK = 2;
706 field_off = true;
707 break;
710 if (!have_uid) { // need a full select cycle to get the uid first
711 iso14a_card_select_t card_info;
712 if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) {
713 if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireNonces: Can't select card (ALL)");
714 continue;
716 switch (card_info.uidlen) {
717 case 4 :
718 cascade_levels = 1;
719 break;
720 case 7 :
721 cascade_levels = 2;
722 break;
723 case 10:
724 cascade_levels = 3;
725 break;
726 default:
727 break;
729 have_uid = true;
730 } else { // no need for anticollision. We can directly select the card
731 if (!iso14443a_fast_select_card(uid, cascade_levels)) {
732 if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireNonces: Can't select card (UID)");
733 continue;
737 // Transmit MIFARE_CLASSIC_AUTH
738 uint8_t dcmd[4] = {0x60 + (keyType & 0x01), blockNo, 0x00, 0x00};
739 AddCrc14A(dcmd, 2);
740 ReaderTransmit(dcmd, sizeof(dcmd), NULL);
741 int len = ReaderReceive(answer, par);
743 // wait for the card to become ready again
744 CHK_TIMEOUT();
746 if (len != 4) {
747 if (DBGLEVEL >= 2) Dbprintf("AcquireNonces: Auth1 error");
748 continue;
751 // Save the tag nonce (nt)
752 memcpy(buf + num_nonces * 4, answer, 4);
753 num_nonces++;
756 LED_C_OFF();
757 LED_B_ON();
758 reply_old(CMD_ACK, isOK, cuid, num_nonces, buf, sizeof(buf));
759 LED_B_OFF();
761 if (DBGLEVEL >= 3) DbpString("AcquireNonces finished");
763 if (field_off) {
764 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
765 LEDsoff();
766 set_tracing(false);
770 //-----------------------------------------------------------------------------
771 // acquire encrypted nonces in order to perform the attack described in
772 // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened
773 // Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on
774 // Computer and Communications Security, 2015
775 //-----------------------------------------------------------------------------
776 void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain) {
778 struct Crypto1State mpcs = {0, 0};
779 struct Crypto1State *pcs;
780 pcs = &mpcs;
782 uint8_t uid[10] = {0x00};
783 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
784 uint8_t par_enc[1] = {0x00};
785 uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00};
787 uint64_t ui64Key = bytes_to_num(datain, 6);
788 uint32_t cuid = 0;
789 int16_t isOK = 0;
790 uint16_t num_nonces = 0;
791 uint8_t nt_par_enc = 0;
792 uint8_t cascade_levels = 0;
793 uint8_t blockNo = arg0 & 0xff;
794 uint8_t keyType = (arg0 >> 8) & 0xff;
795 uint8_t targetBlockNo = arg1 & 0xff;
796 uint8_t targetKeyType = (arg1 >> 8) & 0xff;
797 bool initialize = flags & 0x0001;
798 bool slow = flags & 0x0002;
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(false);
810 if (initialize)
811 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
813 LED_C_ON();
815 for (uint16_t i = 0; i <= PM3_CMD_DATA_SIZE - 9;) {
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)) {
827 if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: 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)) {
846 if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Can't select card (UID)");
847 continue;
851 if (slow)
852 SpinDelayUs(HARDNESTED_PRE_AUTHENTICATION_LEADTIME);
854 uint32_t nt1;
855 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
856 if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Auth1 error");
857 continue;
860 // nested authentication
861 uint16_t len = mifare_sendcmd_short(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par_enc, NULL);
863 // wait for the card to become ready again
864 CHK_TIMEOUT();
866 if (len != 4) {
867 if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Auth2 error len=%d", len);
868 continue;
871 num_nonces++;
872 if (num_nonces % 2) {
873 memcpy(buf + i, receivedAnswer, 4);
874 nt_par_enc = par_enc[0] & 0xf0;
875 } else {
876 nt_par_enc |= par_enc[0] >> 4;
877 memcpy(buf + i + 4, receivedAnswer, 4);
878 memcpy(buf + i + 8, &nt_par_enc, 1);
879 i += 9;
883 LED_C_OFF();
884 crypto1_deinit(pcs);
885 LED_B_ON();
886 reply_old(CMD_ACK, isOK, cuid, num_nonces, buf, sizeof(buf));
887 LED_B_OFF();
889 if (DBGLEVEL >= 3) DbpString("AcquireEncryptedNonces finished");
891 if (field_off) {
892 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
893 LEDsoff();
894 set_tracing(false);
899 //-----------------------------------------------------------------------------
900 // MIFARE nested authentication.
902 //-----------------------------------------------------------------------------
903 void MifareNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, bool calibrate, uint8_t *key) {
904 uint64_t ui64Key = 0;
905 ui64Key = bytes_to_num(key, 6);
907 // variables
908 uint16_t i, j, len;
909 static uint16_t dmin, dmax;
911 uint8_t par[1] = {0x00};
912 uint8_t par_array[4] = {0x00};
913 uint8_t uid[10] = {0x00};
914 uint32_t cuid = 0, nt1, nt2, nttest, ks1;
915 uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00};
917 uint16_t ncount = 0;
918 struct Crypto1State mpcs = {0, 0};
919 struct Crypto1State *pcs;
920 pcs = &mpcs;
921 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
923 uint32_t auth1_time, auth2_time;
924 static uint16_t delta_time = 0;
926 LED_A_ON();
927 LED_C_OFF();
928 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
930 // free eventually allocated BigBuf memory
931 BigBuf_free();
932 BigBuf_Clear_ext(false);
934 if (calibrate)
935 clear_trace();
937 set_tracing(true);
939 // statistics on nonce distance
940 int16_t isOK = PM3_SUCCESS;
941 #define NESTED_MAX_TRIES 12
942 if (calibrate) { // calibrate: for first call only. Otherwise reuse previous calibration
943 LED_B_ON();
944 WDT_HIT();
946 uint16_t unsuccessful_tries = 0;
947 uint16_t davg = 0;
948 dmax = 0;
949 dmin = 2000;
950 delta_time = 0;
951 uint16_t rtr;
952 for (rtr = 0; rtr < 17; rtr++) {
954 // Test if the action was cancelled
955 if (BUTTON_PRESS() || data_available()) {
956 isOK = PM3_EOPABORTED;
957 break;
960 // prepare next select. No need to power down the card.
961 if (mifare_classic_halt(pcs, cuid)) {
962 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Halt error");
963 rtr--;
964 continue;
967 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
968 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Can't select card");
969 rtr--;
970 continue;
973 auth1_time = 0;
974 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) {
975 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth1 error");
976 rtr--;
977 continue;
979 auth2_time = (delta_time) ? auth1_time + delta_time : 0;
981 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, &auth2_time)) {
982 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth2 error");
983 rtr--;
984 continue;
987 // cards with fixed nonce
988 if (nt1 == nt2) {
989 Dbprintf("Nested: %08x vs %08x", nt1, nt2);
990 break;
993 uint32_t nttmp = prng_successor(nt1, 100); //NXP Mifare is typical around 840,but for some unlicensed/compatible mifare card this can be 160
994 for (i = 101; i < 1200; i++) {
995 nttmp = prng_successor(nttmp, 1);
996 if (nttmp == nt2) break;
999 if (i != 1200) {
1000 if (rtr != 0) {
1001 davg += i;
1002 dmin = MIN(dmin, i);
1003 dmax = MAX(dmax, i);
1004 } else {
1005 delta_time = auth2_time - auth1_time + 32; // allow some slack for proper timing
1007 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nested: calibrating... ntdist=%d", i);
1008 } else {
1009 unsuccessful_tries++;
1010 if (unsuccessful_tries > NESTED_MAX_TRIES) { // card isn't vulnerable to nested attack (random numbers are not predictable)
1011 isOK = PM3_EFAILED;
1016 if (rtr > 1)
1017 davg = (davg + (rtr - 1) / 2) / (rtr - 1);
1019 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr, isOK, dmin, dmax, davg, delta_time);
1021 dmin = davg - 2;
1022 dmax = davg + 2;
1024 LED_B_OFF();
1026 // -------------------------------------------------------------------------------------------------
1028 LED_C_ON();
1030 // get crypted nonces for target sector
1031 for (i = 0; i < 2 && !isOK; i++) { // look for exactly two different nonces
1033 target_nt[i] = 0;
1034 while (target_nt[i] == 0) { // continue until we have an unambiguous nonce
1036 // Test if the action was cancelled
1037 if (BUTTON_PRESS() || data_available()) {
1038 isOK = PM3_EOPABORTED;
1039 break;
1042 // prepare next select. No need to power down the card.
1043 if (mifare_classic_halt(pcs, cuid)) {
1044 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Halt error");
1045 continue;
1048 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
1049 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Can't select card");
1050 continue;
1053 auth1_time = 0;
1054 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) {
1055 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth1 error");
1056 continue;
1059 // nested authentication
1060 auth2_time = auth1_time + delta_time;
1062 len = mifare_sendcmd_short(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par, &auth2_time);
1063 if (len != 4) {
1064 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth2 error len=%d", len);
1065 continue;
1068 nt2 = bytes_to_num(receivedAnswer, 4);
1069 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i + 1, nt1, nt2, par[0]);
1071 // Parity validity check
1072 for (j = 0; j < 4; j++) {
1073 par_array[j] = (oddparity8(receivedAnswer[j]) != ((par[0] >> (7 - j)) & 0x01));
1076 ncount = 0;
1077 nttest = prng_successor(nt1, dmin - 1);
1078 for (j = dmin; j < dmax + 1; j++) {
1079 nttest = prng_successor(nttest, 1);
1080 ks1 = nt2 ^ nttest;
1082 if (valid_nonce(nttest, nt2, ks1, par_array)) {
1083 if (ncount > 0) { // we are only interested in disambiguous nonces, try again
1084 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nonce#%d: dismissed (ambiguous), ntdist=%d", i + 1, j);
1085 target_nt[i] = 0;
1086 break;
1088 target_nt[i] = nttest;
1089 target_ks[i] = ks1;
1090 ncount++;
1091 if (i == 1 && target_nt[1] == target_nt[0]) { // we need two different nonces
1092 target_nt[i] = 0;
1093 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nonce#2: dismissed (= nonce#1), ntdist=%d", j);
1094 break;
1096 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nonce#%d: valid, ntdist=%d", i + 1, j);
1099 if (target_nt[i] == 0 && j == dmax + 1 && DBGLEVEL >= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i + 1);
1103 LED_C_OFF();
1105 crypto1_deinit(pcs);
1107 struct p {
1108 int16_t isOK;
1109 uint8_t block;
1110 uint8_t keytype;
1111 uint8_t cuid[4];
1112 uint8_t nt_a[4];
1113 uint8_t ks_a[4];
1114 uint8_t nt_b[4];
1115 uint8_t ks_b[4];
1116 } PACKED payload;
1117 payload.isOK = isOK;
1118 payload.block = targetBlockNo;
1119 payload.keytype = targetKeyType;
1121 memcpy(payload.cuid, &cuid, 4);
1122 memcpy(payload.nt_a, &target_nt[0], 4);
1123 memcpy(payload.ks_a, &target_ks[0], 4);
1124 memcpy(payload.nt_b, &target_nt[1], 4);
1125 memcpy(payload.ks_b, &target_ks[1], 4);
1127 reply_ng(CMD_HF_MIFARE_NESTED, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload));
1128 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1129 LEDsoff();
1130 set_tracing(false);
1133 void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, uint8_t *key) {
1135 LEDsoff();
1137 uint64_t ui64Key = 0;
1138 ui64Key = bytes_to_num(key, 6);
1139 uint16_t len;
1140 uint8_t uid[10] = {0x00};
1141 uint32_t cuid = 0, nt1, nt2;
1142 uint32_t target_nt = 0, target_ks = 0;
1143 uint8_t par[1] = {0x00};
1144 uint8_t receivedAnswer[10] = {0x00};
1146 struct Crypto1State mpcs = {0, 0};
1147 struct Crypto1State *pcs;
1148 pcs = &mpcs;
1150 LED_A_ON();
1151 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1153 // free eventually allocated BigBuf memory
1154 BigBuf_free();
1155 BigBuf_Clear_ext(false);
1156 clear_trace();
1157 set_tracing(true);
1159 int16_t isOK = 0;
1160 LED_C_ON();
1162 for (uint8_t retry = 0; retry < 3 && (isOK == 0); retry++) {
1164 WDT_HIT();
1166 // prepare next select. No need to power down the card.
1167 if (mifare_classic_halt(pcs, cuid)) {
1168 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Halt error");
1169 retry--;
1170 continue;
1173 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
1174 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Can't select card");
1175 retry--;
1176 continue;
1179 // First authentication. Normal auth.
1180 if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) {
1181 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth1 error");
1182 retry--;
1183 continue;
1186 // second authentication. Nested auth
1187 len = mifare_sendcmd_short(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par, NULL);
1188 if (len != 4) {
1189 if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth2 error len=%d", len);
1190 continue;
1193 nt2 = bytes_to_num(receivedAnswer, 4);
1194 target_nt = prng_successor(nt1, 160);
1195 target_ks = nt2 ^ target_nt;
1196 isOK = 1;
1198 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Testing nt1=%08x nt2enc=%08x nt2par=%02x ks=%08x", nt1, nt2, par[0], target_ks);
1201 LED_C_OFF();
1203 crypto1_deinit(pcs);
1205 struct p {
1206 int16_t isOK;
1207 uint8_t block;
1208 uint8_t keytype;
1209 uint8_t cuid[4];
1210 uint8_t nt[4];
1211 uint8_t ks[4];
1212 } PACKED payload;
1213 payload.isOK = isOK;
1214 payload.block = targetBlockNo;
1215 payload.keytype = targetKeyType;
1217 memcpy(payload.cuid, &cuid, 4);
1218 memcpy(payload.nt, &target_nt, 4);
1219 memcpy(payload.ks, &target_ks, 4);
1221 LED_B_ON();
1222 reply_ng(CMD_HF_MIFARE_STATIC_NESTED, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload));
1223 LED_B_OFF();
1225 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1226 LEDsoff();
1227 set_tracing(false);
1229 //-----------------------------------------------------------------------------
1230 // MIFARE check keys. key count up to 85.
1232 //-----------------------------------------------------------------------------
1233 typedef struct sector_t {
1234 uint8_t keyA[6];
1235 uint8_t keyB[6];
1236 } sector_t;
1238 typedef struct chk_t {
1239 uint64_t key;
1240 uint32_t cuid;
1241 uint8_t cl;
1242 uint8_t block;
1243 uint8_t keyType;
1244 uint8_t *uid;
1245 struct Crypto1State *pcs;
1246 } chk_t;
1248 // checks one key.
1249 // fast select, tries 5 times to select
1251 // return:
1252 // 2 = failed to select.
1253 // 1 = wrong key
1254 // 0 = correct key
1255 static uint8_t chkKey(struct chk_t *c) {
1256 uint8_t i = 0, res = 2;
1257 while (i < 5) {
1258 // this part is from Piwi's faster nonce collecting part in Hardnested.
1259 // assume: fast select
1260 if (!iso14443a_fast_select_card(c->uid, c->cl)) {
1261 ++i;
1262 continue;
1264 res = mifare_classic_authex(c->pcs, c->cuid, c->block, c->keyType, c->key, AUTH_FIRST, NULL, NULL);
1266 // CHK_TIMEOUT();
1268 // if successful auth, send HALT
1269 // if ( !res )
1270 // mifare_classic_halt_ex(c->pcs);
1271 break;
1273 return res;
1276 static uint8_t chkKey_readb(struct chk_t *c, uint8_t *keyb) {
1278 if (!iso14443a_fast_select_card(c->uid, c->cl))
1279 return 2;
1281 if (mifare_classic_authex(c->pcs, c->cuid, c->block, 0, c->key, AUTH_FIRST, NULL, NULL))
1282 return 1;
1284 uint8_t data[16] = {0x00};
1285 uint8_t res = mifare_classic_readblock(c->pcs, c->cuid, c->block, data);
1287 // successful read
1288 if (!res) {
1289 // data was something else than zeros.
1290 if (memcmp(data + 10, "\x00\x00\x00\x00\x00\x00", 6) != 0) {
1291 memcpy(keyb, data + 10, 6);
1292 res = 0;
1293 } else {
1294 res = 3;
1296 mifare_classic_halt_ex(c->pcs);
1298 return res;
1301 static void chkKey_scanA(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) {
1302 for (uint8_t s = 0; s < *sectorcnt; s++) {
1304 // skip already found A keys
1305 if (found[(s * 2)])
1306 continue;
1308 c->block = FirstBlockOfSector(s);
1309 if (chkKey(c) == 0) {
1310 num_to_bytes(c->key, 6, k_sector[s].keyA);
1311 found[(s * 2)] = 1;
1312 ++*foundkeys;
1314 if (DBGLEVEL >= 3) Dbprintf("ChkKeys_fast: Scan A found (%d)", c->block);
1319 static void chkKey_scanB(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) {
1320 for (uint8_t s = 0; s < *sectorcnt; s++) {
1322 // skip already found B keys
1323 if (found[(s * 2) + 1])
1324 continue;
1326 c->block = FirstBlockOfSector(s);
1327 if (chkKey(c) == 0) {
1328 num_to_bytes(c->key, 6, k_sector[s].keyB);
1329 found[(s * 2) + 1] = 1;
1330 ++*foundkeys;
1332 if (DBGLEVEL >= 3) Dbprintf("ChkKeys_fast: Scan B found (%d)", c->block);
1337 // loop all A keys,
1338 // when A is found but not B, try to read B.
1339 static void chkKey_loopBonly(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) {
1341 // read Block B, if A is found.
1342 for (uint8_t s = 0; s < *sectorcnt; ++s) {
1344 if (found[(s * 2)] && found[(s * 2) + 1])
1345 continue;
1347 c->block = (FirstBlockOfSector(s) + NumBlocksPerSector(s) - 1);
1349 // A but not B
1350 if (found[(s * 2)] && !found[(s * 2) + 1]) {
1351 c->key = bytes_to_num(k_sector[s].keyA, 6);
1352 uint8_t status = chkKey_readb(c, k_sector[s].keyB);
1353 if (status == 0) {
1354 found[(s * 2) + 1] = 1;
1355 ++*foundkeys;
1357 if (DBGLEVEL >= 3) Dbprintf("ChkKeys_fast: Reading B found (%d)", c->block);
1359 // try quick find all B?
1360 // assume: keys comes in groups. Find one B, test against all B.
1361 c->key = bytes_to_num(k_sector[s].keyB, 6);
1362 c->keyType = 1;
1363 chkKey_scanB(c, k_sector, found, sectorcnt, foundkeys);
1369 // get Chunks of keys, to test authentication against card.
1370 // arg0 = antal sectorer
1371 // arg0 = first time
1372 // arg1 = clear trace
1373 // arg2 = antal nycklar i keychunk
1374 // datain = keys as array
1375 void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain) {
1377 // first call or
1378 uint8_t sectorcnt = arg0 & 0xFF; // 16;
1379 uint8_t firstchunk = (arg0 >> 8) & 0xF;
1380 uint8_t lastchunk = (arg0 >> 12) & 0xF;
1381 uint8_t strategy = arg1 & 0xFF;
1382 uint8_t use_flashmem = (arg1 >> 8) & 0xFF;
1383 uint16_t keyCount = arg2 & 0xFF;
1384 uint8_t status = 0;
1386 struct Crypto1State mpcs = {0, 0};
1387 struct Crypto1State *pcs;
1388 pcs = &mpcs;
1389 struct chk_t chk_data;
1391 uint8_t allkeys = sectorcnt << 1;
1393 static uint32_t cuid = 0;
1394 static uint8_t cascade_levels = 0;
1395 static uint8_t foundkeys = 0;
1396 static sector_t k_sector[80];
1397 static uint8_t found[80];
1398 static uint8_t *uid;
1400 int oldbg = DBGLEVEL;
1402 #ifdef WITH_FLASH
1403 if (use_flashmem) {
1404 BigBuf_free();
1405 uint16_t isok = 0;
1406 uint8_t size[2] = {0x00, 0x00};
1407 isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET, size, 2);
1408 if (isok != 2)
1409 goto OUT;
1411 keyCount = size[1] << 8 | size[0];
1413 if (keyCount == 0)
1414 goto OUT;
1416 // limit size of availlable for keys in bigbuff
1417 // a key is 6bytes
1418 uint16_t key_mem_available = MIN(BigBuf_get_size(), keyCount * 6);
1420 keyCount = key_mem_available / 6;
1422 datain = BigBuf_malloc(key_mem_available);
1423 if (datain == NULL)
1424 goto OUT;
1426 isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET + 2, datain, key_mem_available);
1427 if (isok != key_mem_available)
1428 goto OUT;
1431 #endif
1433 if (uid == NULL || firstchunk) {
1434 uid = BigBuf_malloc(10);
1435 if (uid == NULL)
1436 goto OUT;
1439 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1441 LEDsoff();
1442 LED_A_ON();
1444 if (firstchunk) {
1445 clear_trace();
1446 set_tracing(false);
1448 memset(k_sector, 0x00, 480 + 10);
1449 memset(found, 0x00, sizeof(found));
1450 foundkeys = 0;
1452 iso14a_card_select_t card_info;
1453 if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) {
1454 if (DBGLEVEL >= DBG_ERROR) Dbprintf("ChkKeys_fast: Can't select card (ALL)");
1455 goto OUT;
1458 switch (card_info.uidlen) {
1459 case 4 :
1460 cascade_levels = 1;
1461 break;
1462 case 7 :
1463 cascade_levels = 2;
1464 break;
1465 case 10:
1466 cascade_levels = 3;
1467 break;
1468 default:
1469 break;
1472 CHK_TIMEOUT();
1475 // clear debug level. We are expecting lots of authentication failures...
1476 DBGLEVEL = DBG_NONE;
1478 // set check struct.
1479 chk_data.uid = uid;
1480 chk_data.cuid = cuid;
1481 chk_data.cl = cascade_levels;
1482 chk_data.pcs = pcs;
1483 chk_data.block = 0;
1485 // keychunk loop - depth first one sector.
1486 if (strategy == 1 || use_flashmem) {
1488 uint8_t newfound = foundkeys;
1490 uint16_t lastpos = 0;
1491 uint16_t s_point = 0;
1492 // Sector main loop
1493 // keep track of how many sectors on card.
1494 for (uint8_t s = 0; s < sectorcnt; ++s) {
1496 if (found[(s * 2)] && found[(s * 2) + 1])
1497 continue;
1499 for (uint16_t i = s_point; i < keyCount; ++i) {
1501 // Allow button press / usb cmd to interrupt device
1502 if (BUTTON_PRESS() || data_available()) {
1503 goto OUT;
1506 // found all keys?
1507 if (foundkeys == allkeys)
1508 goto OUT;
1510 WDT_HIT();
1512 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
1513 chk_data.block = FirstBlockOfSector(s);
1515 // new key
1516 chk_data.key = bytes_to_num(datain + i * 6, 6);
1518 // skip already found A keys
1519 if (!found[(s * 2)]) {
1520 chk_data.keyType = 0;
1521 status = chkKey(&chk_data);
1522 if (status == 0) {
1523 memcpy(k_sector[s].keyA, datain + i * 6, 6);
1524 found[(s * 2)] = 1;
1525 ++foundkeys;
1527 chkKey_scanA(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1529 // read Block B, if A is found.
1530 chkKey_loopBonly(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1532 chk_data.keyType = 1;
1533 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1535 chk_data.keyType = 0;
1536 chk_data.block = FirstBlockOfSector(s);
1538 if (use_flashmem) {
1539 if (lastpos != i && lastpos != 0) {
1540 if (i - lastpos < 0xF) {
1541 s_point = i & 0xFFF0;
1543 } else {
1544 lastpos = i;
1550 // skip already found B keys
1551 if (!found[(s * 2) + 1]) {
1552 chk_data.keyType = 1;
1553 status = chkKey(&chk_data);
1554 if (status == 0) {
1555 memcpy(k_sector[s].keyB, datain + i * 6, 6);
1556 found[(s * 2) + 1] = 1;
1557 ++foundkeys;
1559 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1561 if (use_flashmem) {
1562 if (lastpos != i && lastpos != 0) {
1564 if (i - lastpos < 0xF)
1565 s_point = i & 0xFFF0;
1566 } else {
1567 lastpos = i;
1573 if (found[(s * 2)] && found[(s * 2) + 1])
1574 break;
1576 } // end keys test loop - depth first
1578 // assume1. if no keys found in first sector, get next keychunk from client
1579 if (!use_flashmem && (newfound - foundkeys == 0))
1580 goto OUT;
1582 } // end loop - sector
1583 } // end strategy 1
1585 if (foundkeys == allkeys)
1586 goto OUT;
1588 if (strategy == 2 || use_flashmem) {
1590 // Keychunk loop
1591 for (uint16_t i = 0; i < keyCount; i++) {
1593 // Allow button press / usb cmd to interrupt device
1594 if (BUTTON_PRESS() || data_available()) break;
1596 // found all keys?
1597 if (foundkeys == allkeys)
1598 goto OUT;
1600 WDT_HIT();
1602 // new key
1603 chk_data.key = bytes_to_num(datain + i * 6, 6);
1605 // Sector main loop
1606 // keep track of how many sectors on card.
1607 for (uint8_t s = 0; s < sectorcnt; ++s) {
1609 if (found[(s * 2)] && found[(s * 2) + 1]) continue;
1611 // found all keys?
1612 if (foundkeys == allkeys)
1613 goto OUT;
1615 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
1616 chk_data.block = FirstBlockOfSector(s);
1618 // skip already found A keys
1619 if (!found[(s * 2)]) {
1620 chk_data.keyType = 0;
1621 status = chkKey(&chk_data);
1622 if (status == 0) {
1623 memcpy(k_sector[s].keyA, datain + i * 6, 6);
1624 found[(s * 2)] = 1;
1625 ++foundkeys;
1627 chkKey_scanA(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1629 // read Block B, if A is found.
1630 chkKey_loopBonly(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1632 chk_data.block = FirstBlockOfSector(s);
1636 // skip already found B keys
1637 if (!found[(s * 2) + 1]) {
1638 chk_data.keyType = 1;
1639 status = chkKey(&chk_data);
1640 if (status == 0) {
1641 memcpy(k_sector[s].keyB, datain + i * 6, 6);
1642 found[(s * 2) + 1] = 1;
1643 ++foundkeys;
1645 chkKey_scanB(&chk_data, k_sector, found, &sectorcnt, &foundkeys);
1648 } // end loop sectors
1649 } // end loop keys
1650 } // end loop strategy 2
1651 OUT:
1652 LEDsoff();
1654 crypto1_deinit(pcs);
1656 // All keys found, send to client, or last keychunk from client
1657 if (foundkeys == allkeys || lastchunk) {
1659 uint64_t foo = 0;
1660 for (uint8_t m = 0; m < 64; m++) {
1661 foo |= ((uint64_t)(found[m] & 1) << m);
1664 uint16_t bar = 0;
1665 uint8_t j = 0;
1666 for (uint8_t m = 64; m < ARRAYLEN(found); m++) {
1667 bar |= ((uint16_t)(found[m] & 1) << j++);
1670 uint8_t *tmp = BigBuf_malloc(480 + 10);
1671 memcpy(tmp, k_sector, sectorcnt * sizeof(sector_t));
1672 num_to_bytes(foo, 8, tmp + 480);
1673 tmp[488] = bar & 0xFF;
1674 tmp[489] = bar >> 8 & 0xFF;
1676 reply_old(CMD_ACK, foundkeys, 0, 0, tmp, 480 + 10);
1678 set_tracing(false);
1679 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1680 BigBuf_free();
1681 BigBuf_Clear_ext(false);
1683 // special trick ecfill
1684 if (use_flashmem && foundkeys == allkeys) {
1686 uint8_t block[16] = {0};
1687 for (int i = 0; i < sectorcnt; i++) {
1689 uint8_t blockno;
1690 if (i < 32) {
1691 blockno = (i * 4) ^ 0x3;
1692 } else {
1693 blockno = (32 * 4 + (i - 32) * 16) ^ 0xF;
1695 // get ST
1696 emlGetMem(block, blockno, 1);
1698 memcpy(block, k_sector[i].keyA, 6);
1699 memcpy(block + 10, k_sector[i].keyB, 6);
1701 emlSetMem_xt(block, blockno, 1, sizeof(block));
1704 MifareECardLoad(sectorcnt, 0);
1705 MifareECardLoad(sectorcnt, 1);
1707 } else {
1708 // partial/none keys found
1709 reply_mix(CMD_ACK, foundkeys, 0, 0, 0, 0);
1712 DBGLEVEL = oldbg;
1715 void MifareChkKeys(uint8_t *datain, uint8_t reserved_mem) {
1717 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1719 struct Crypto1State mpcs = {0, 0};
1720 struct Crypto1State *pcs;
1721 pcs = &mpcs;
1723 uint8_t uid[10] = {0x00};
1725 uint64_t key = 0;
1726 uint32_t cuid = 0;
1727 int i, res;
1728 uint8_t cascade_levels = 0;
1729 struct {
1730 uint8_t key[6];
1731 bool found;
1732 } PACKED keyresult;
1733 keyresult.found = false;
1734 bool have_uid = false;
1736 uint8_t keyType = datain[0];
1737 uint8_t blockNo = datain[1];
1738 bool clearTrace = datain[2];
1739 uint16_t key_count = (datain[3] << 8) | datain[4];
1741 uint16_t key_mem_available;
1742 if (reserved_mem)
1743 key_mem_available = key_count * 6;
1744 else
1745 key_mem_available = MIN((PM3_CMD_DATA_SIZE - 5), key_count * 6);
1747 key_count = key_mem_available / 6;
1749 datain += 5;
1751 LEDsoff();
1752 LED_A_ON();
1754 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1756 if (clearTrace)
1757 clear_trace();
1759 int oldbg = DBGLEVEL;
1760 DBGLEVEL = DBG_NONE;
1762 set_tracing(false);
1764 for (i = 0; i < key_count; i++) {
1766 // Iceman: use piwi's faster nonce collecting part in hardnested.
1767 if (!have_uid) { // need a full select cycle to get the uid first
1768 iso14a_card_select_t card_info;
1769 if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) {
1770 if (DBGLEVEL >= DBG_ERROR) Dbprintf("ChkKeys: Can't select card (ALL)");
1771 --i; // try same key once again
1772 continue;
1774 switch (card_info.uidlen) {
1775 case 4 :
1776 cascade_levels = 1;
1777 break;
1778 case 7 :
1779 cascade_levels = 2;
1780 break;
1781 case 10:
1782 cascade_levels = 3;
1783 break;
1784 default:
1785 break;
1787 have_uid = true;
1788 } else { // no need for anticollision. We can directly select the card
1789 if (!iso14443a_select_card(uid, NULL, NULL, false, cascade_levels, true)) {
1790 if (DBGLEVEL >= DBG_ERROR) Dbprintf("ChkKeys: Can't select card (UID)");
1791 --i; // try same key once again
1792 continue;
1796 key = bytes_to_num(datain + i * 6, 6);
1797 res = mifare_classic_auth(pcs, cuid, blockNo, keyType, key, AUTH_FIRST);
1799 // CHK_TIMEOUT();
1801 if (res)
1802 continue;
1804 memcpy(keyresult.key, datain + i * 6, 6);
1805 keyresult.found = true;
1806 break;
1809 LED_B_ON();
1811 reply_ng(CMD_HF_MIFARE_CHKKEYS, PM3_SUCCESS, (uint8_t *)&keyresult, sizeof(keyresult));
1812 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1813 LEDsoff();
1815 set_tracing(false);
1816 crypto1_deinit(pcs);
1818 DBGLEVEL = oldbg;
1821 void MifareChkKeys_file(uint8_t *fn) {
1823 #ifdef WITH_FLASH
1824 BigBuf_free();
1826 SpinOff(0);
1828 int changed = rdv40_spiffs_lazy_mount();
1829 uint32_t size = size_in_spiffs((char *)fn);
1830 uint8_t *mem = BigBuf_malloc(size);
1832 rdv40_spiffs_read_as_filetype((char *)fn, mem, size, RDV40_SPIFFS_SAFETY_SAFE);
1834 if (changed) {
1835 rdv40_spiffs_lazy_unmount();
1838 SpinOff(0);
1840 MifareChkKeys(mem, true);
1842 BigBuf_free();
1843 #endif
1846 //-----------------------------------------------------------------------------
1847 // MIFARE Personalize UID. Only for Mifare Classic EV1 7Byte UID
1848 //-----------------------------------------------------------------------------
1849 void MifarePersonalizeUID(uint8_t keyType, uint8_t perso_option, uint64_t key) {
1851 uint16_t isOK = PM3_EUNDEF;
1852 uint8_t uid[10];
1853 uint32_t cuid;
1854 struct Crypto1State mpcs = {0, 0};
1855 struct Crypto1State *pcs;
1856 pcs = &mpcs;
1858 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1859 clear_trace();
1860 set_tracing(true);
1862 LED_A_ON();
1864 while (true) {
1865 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
1866 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
1867 break;
1870 uint8_t block_number = 0;
1871 if (mifare_classic_auth(pcs, cuid, block_number, keyType, key, AUTH_FIRST)) {
1872 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Auth error");
1873 break;
1876 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
1877 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
1878 int len = mifare_sendcmd_short(pcs, true, MIFARE_EV1_PERSONAL_UID, perso_option, receivedAnswer, receivedAnswerPar, NULL);
1879 if (len != 1 || receivedAnswer[0] != CARD_ACK) {
1880 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
1881 break;
1884 if (mifare_classic_halt(pcs, cuid)) {
1885 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
1886 break;
1888 isOK = PM3_SUCCESS;
1889 break;
1892 crypto1_deinit(pcs);
1894 LED_B_ON();
1895 reply_ng(CMD_HF_MIFARE_PERSONALIZE_UID, isOK, NULL, 0);
1896 LED_B_OFF();
1898 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1899 LEDsoff();
1903 //-----------------------------------------------------------------------------
1904 // Work with emulator memory
1906 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
1907 // involved in dealing with emulator memory. But if it is called later, it might
1908 // destroy the Emulator Memory.
1909 //-----------------------------------------------------------------------------
1911 void MifareEMemClr(void) {
1912 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1913 emlClearMem();
1916 void MifareEMemSet(uint8_t blockno, uint8_t blockcnt, uint8_t blockwidth, uint8_t *datain) {
1917 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1919 if (blockwidth == 0)
1920 blockwidth = 16; // backwards compat... default bytewidth
1922 emlSetMem_xt(datain, blockno, blockcnt, blockwidth); // data, block num, blocks count, block byte width
1925 void MifareEMemGet(uint8_t blockno, uint8_t blockcnt) {
1926 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1929 size_t size = blockcnt * 16;
1930 if (size > PM3_CMD_DATA_SIZE) {
1931 reply_ng(CMD_HF_MIFARE_EML_MEMGET, PM3_EMALLOC, NULL, 0);
1932 return;
1935 uint8_t *buf = BigBuf_malloc(size);
1937 emlGetMem(buf, blockno, blockcnt); // data, block num, blocks count (max 4)
1939 LED_B_ON();
1940 reply_ng(CMD_HF_MIFARE_EML_MEMGET, PM3_SUCCESS, buf, size);
1941 LED_B_OFF();
1942 BigBuf_free_keep_EM();
1945 //-----------------------------------------------------------------------------
1946 // Load a card into the emulator memory
1948 //-----------------------------------------------------------------------------
1949 int MifareECardLoadExt(uint8_t sectorcnt, uint8_t keytype) {
1950 int retval = MifareECardLoad(sectorcnt, keytype);
1951 reply_ng(CMD_HF_MIFARE_EML_LOAD, retval, NULL, 0);
1952 return retval;
1955 int MifareECardLoad(uint8_t sectorcnt, uint8_t keytype) {
1957 uint32_t cuid = 0;
1958 struct Crypto1State mpcs = {0, 0};
1959 struct Crypto1State *pcs;
1960 pcs = &mpcs;
1962 // variables
1963 uint8_t dataoutbuf[16] = {0x00};
1964 uint8_t dataoutbuf2[16] = {0x00};
1965 uint8_t uid[10] = {0x00};
1967 LED_A_ON();
1968 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
1970 clear_trace();
1971 set_tracing(true);
1973 int retval = PM3_SUCCESS;
1975 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
1976 retval = PM3_ESOFT;
1977 if (DBGLEVEL > DBG_ERROR) Dbprintf("Can't select card");
1978 goto out;
1981 for (uint8_t sectorNo = 0; sectorNo < sectorcnt; sectorNo++) {
1982 uint64_t ui64Key = emlGetKey(sectorNo, keytype);
1983 if (sectorNo == 0) {
1984 if (mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keytype, ui64Key, AUTH_FIRST)) {
1985 retval = PM3_EPARTIAL;
1986 if (DBGLEVEL > DBG_ERROR) Dbprintf("Sector[%2d]. Auth error", sectorNo);
1987 continue;
1989 } else {
1990 if (mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keytype, ui64Key, AUTH_NESTED)) {
1991 retval = PM3_EPARTIAL;
1992 if (DBGLEVEL > DBG_ERROR) Dbprintf("Sector[%2d]. Auth nested error", sectorNo);
1993 continue;
1997 for (uint8_t blockNo = 0; blockNo < NumBlocksPerSector(sectorNo); blockNo++) {
1998 if (mifare_classic_readblock(pcs, cuid, FirstBlockOfSector(sectorNo) + blockNo, dataoutbuf)) {
1999 retval = PM3_EPARTIAL;
2001 if (DBGLEVEL > DBG_ERROR) Dbprintf("Error reading sector %2d block %2d", sectorNo, blockNo);
2002 continue;
2005 if (memcmp(dataoutbuf, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16) == 0) {
2006 continue;
2009 if (blockNo < NumBlocksPerSector(sectorNo) - 1) {
2010 emlSetMem(dataoutbuf, FirstBlockOfSector(sectorNo) + blockNo, 1);
2011 } else { // sector trailer, keep the keys, set only the AC
2012 emlGetMem(dataoutbuf2, FirstBlockOfSector(sectorNo) + blockNo, 1);
2013 memcpy(dataoutbuf2 + 6, dataoutbuf + 6, 4);
2014 emlSetMem(dataoutbuf2, FirstBlockOfSector(sectorNo) + blockNo, 1);
2019 int res = mifare_classic_halt(pcs, cuid);
2020 (void)res;
2022 if (DBGLEVEL >= DBG_INFO) DbpString("Emulator fill sectors finished");
2024 out:
2025 crypto1_deinit(pcs);
2026 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2027 LEDsoff();
2028 set_tracing(false);
2029 return retval;
2033 //-----------------------------------------------------------------------------
2034 // Work with "magic Chinese" card (email him: ouyangweidaxian@live.cn)
2036 // PARAMS - workFlags
2037 // bit 0 - need get UID
2038 // bit 1 - need wupC
2039 // bit 2 - need HALT after sequence
2040 // bit 3 - need turn on FPGA before sequence
2041 // bit 4 - need turn off FPGA
2042 // bit 5 - need to set datain instead of issuing USB reply (called via ARM for StandAloneMode14a)
2043 // bit 6 - wipe tag.
2044 //-----------------------------------------------------------------------------
2045 // magic uid card generation 1 commands
2046 static uint8_t wupC1[] = { MIFARE_MAGICWUPC1 };
2047 static uint8_t wupC2[] = { MIFARE_MAGICWUPC2 };
2048 static uint8_t wipeC[] = { MIFARE_MAGICWIPEC };
2050 void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) {
2052 // params
2053 uint8_t workFlags = arg0;
2054 uint8_t blockNo = arg1;
2056 // detect 1a/1b
2057 bool is1b = false;
2059 // variables
2060 bool isOK = false; //assume we will get an error
2061 uint8_t errormsg = 0x00;
2062 uint8_t uid[10] = {0x00};
2063 uint8_t data[18] = {0x00};
2064 uint32_t cuid = 0;
2066 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
2067 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
2069 if (workFlags & MAGIC_INIT) {
2070 LED_A_ON();
2071 LED_B_OFF();
2072 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2073 clear_trace();
2074 set_tracing(true);
2077 //loop doesn't loop just breaks out if error
2078 while (true) {
2079 // read UID and return to client with write
2080 if (workFlags & MAGIC_UID) {
2081 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
2082 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
2083 errormsg = MAGIC_UID;
2084 mifare_classic_halt_ex(NULL);
2085 break;
2087 mifare_classic_halt_ex(NULL);
2090 // wipe tag, fill it with zeros
2091 if (workFlags & MAGIC_WIPE) {
2092 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2093 if (!ReaderReceive(receivedAnswer, receivedAnswerPar) || (receivedAnswer[0] != 0x0a)) {
2094 if (DBGLEVEL >= DBG_ERROR) Dbprintf("wupC1 error");
2095 errormsg = MAGIC_WIPE;
2096 break;
2099 uint32_t old_timeout = iso14a_get_timeout();
2101 // 2000 ms timeout
2102 // 13560000 / 1000 / (8 * 16) * timeout
2103 iso14a_set_timeout(21190);
2105 ReaderTransmit(wipeC, sizeof(wipeC), NULL);
2106 if (!ReaderReceive(receivedAnswer, receivedAnswerPar) || (receivedAnswer[0] != 0x0a)) {
2107 if (DBGLEVEL >= DBG_ERROR) Dbprintf("wipeC error");
2108 errormsg = MAGIC_WIPE;
2109 break;
2111 iso14a_set_timeout(old_timeout);
2113 mifare_classic_halt_ex(NULL);
2116 // write block
2117 if (workFlags & MAGIC_WUPC) {
2118 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2119 if (!ReaderReceive(receivedAnswer, receivedAnswerPar) || (receivedAnswer[0] != 0x0a)) {
2120 if (DBGLEVEL >= DBG_ERROR) Dbprintf("wupC1 error");
2121 errormsg = MAGIC_WUPC;
2122 break;
2125 if (!is1b) {
2126 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2127 if (!ReaderReceive(receivedAnswer, receivedAnswerPar) || (receivedAnswer[0] != 0x0a)) {
2128 if (DBGLEVEL >= DBG_INFO) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2129 is1b = true;
2130 continue;
2135 if ((mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_WRITEBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL) != 1) || (receivedAnswer[0] != 0x0a)) {
2136 if (DBGLEVEL >= DBG_ERROR) Dbprintf("write block send command error");
2137 errormsg = 4;
2138 break;
2141 memcpy(data, datain, 16);
2142 AddCrc14A(data, 16);
2144 ReaderTransmit(data, sizeof(data), NULL);
2145 if ((ReaderReceive(receivedAnswer, receivedAnswerPar) != 1) || (receivedAnswer[0] != 0x0a)) {
2146 if (DBGLEVEL >= DBG_ERROR) Dbprintf("write block send data error");
2147 errormsg = 0;
2148 break;
2151 if (workFlags & MAGIC_HALT)
2152 mifare_classic_halt_ex(NULL);
2154 isOK = true;
2155 break;
2157 } // end while
2159 if (isOK)
2160 reply_mix(CMD_ACK, 1, 0, 0, uid, sizeof(uid));
2161 else
2162 OnErrorMagic(errormsg);
2164 if (workFlags & MAGIC_OFF)
2165 OnSuccessMagic();
2168 void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) {
2170 uint8_t workFlags = arg0;
2171 uint8_t blockNo = arg1;
2172 uint8_t errormsg = 0x00;
2173 bool isOK = false; //assume we will get an error
2175 // detect 1a/1b
2176 bool is1b = false;
2178 // variables
2179 uint8_t data[MAX_MIFARE_FRAME_SIZE];
2180 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
2181 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
2183 memset(data, 0x00, sizeof(data));
2185 if (workFlags & MAGIC_INIT) {
2186 LED_A_ON();
2187 LED_B_OFF();
2188 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2189 clear_trace();
2190 set_tracing(true);
2193 //loop doesn't loop just breaks out if error or done
2194 while (true) {
2195 if (workFlags & MAGIC_WUPC) {
2196 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2197 if (!ReaderReceive(receivedAnswer, receivedAnswerPar) || (receivedAnswer[0] != 0x0a)) {
2198 if (DBGLEVEL >= DBG_ERROR) Dbprintf("wupC1 error");
2199 errormsg = MAGIC_WUPC;
2200 break;
2203 if (!is1b) {
2204 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2205 if (!ReaderReceive(receivedAnswer, receivedAnswerPar) || (receivedAnswer[0] != 0x0a)) {
2206 if (DBGLEVEL >= DBG_INFO) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2207 is1b = true;
2208 continue;
2213 // read block
2214 if ((mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_READBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL) != 18)) {
2215 if (DBGLEVEL >= DBG_ERROR) Dbprintf("read block send command error");
2216 errormsg = 0;
2217 break;
2220 memcpy(data, receivedAnswer, sizeof(data));
2222 // send HALT
2223 if (workFlags & MAGIC_HALT)
2224 mifare_classic_halt_ex(NULL);
2226 isOK = true;
2227 break;
2229 // if MAGIC_DATAIN, the data stays on device side.
2230 if (workFlags & MAGIC_DATAIN) {
2231 if (isOK)
2232 memcpy(datain, data, sizeof(data));
2233 } else {
2234 if (isOK)
2235 reply_old(CMD_ACK, 1, 0, 0, data, sizeof(data));
2236 else
2237 OnErrorMagic(errormsg);
2240 if (workFlags & MAGIC_OFF)
2241 OnSuccessMagic();
2244 void MifareCIdent(bool is_mfc) {
2245 // variables
2246 uint8_t isGen = 0;
2247 uint8_t rec[1] = {0x00};
2248 uint8_t recpar[1] = {0x00};
2249 uint8_t rats[4] = { ISO14443A_CMD_RATS, 0x80, 0x31, 0x73 };
2250 uint8_t rdblf0[4] = { ISO14443A_CMD_READBLOCK, 0xF0, 0x8D, 0x5f};
2251 uint8_t rdbl00[4] = { ISO14443A_CMD_READBLOCK, 0x00, 0x02, 0xa8};
2252 uint8_t *par = BigBuf_malloc(MAX_PARITY_SIZE);
2253 uint8_t *buf = BigBuf_malloc(PM3_CMD_DATA_SIZE);
2254 uint8_t *uid = BigBuf_malloc(10);
2256 memset(par, 0x00, MAX_PARITY_SIZE);
2257 memset(buf, 0x00, PM3_CMD_DATA_SIZE);
2258 memset(uid, 0x00, 10);
2260 uint32_t cuid = 0;
2261 uint8_t data[1] = {0x00};
2263 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2265 // Generation 1 test
2266 ReaderTransmitBitsPar(wupC1, 7, NULL, NULL);
2267 if (ReaderReceive(rec, recpar) && (rec[0] == 0x0a)) {
2268 ReaderTransmit(wupC2, sizeof(wupC2), NULL);
2269 if (!ReaderReceive(rec, recpar) || (rec[0] != 0x0a)) {
2270 isGen = MAGIC_GEN_1B;
2271 goto OUT;
2273 isGen = MAGIC_GEN_1A;
2274 goto OUT;
2277 // reset card
2278 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2279 SpinDelay(40);
2280 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2282 int res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2283 if (res == 2) {
2284 if (cuid == 0xAA55C396) {
2285 isGen = MAGIC_GEN_UNFUSED;
2286 goto OUT;
2289 ReaderTransmit(rats, sizeof(rats), NULL);
2290 res = ReaderReceive(buf, par);
2291 if (res) {
2293 // test for some MFC gen2
2294 if (memcmp(buf, "\x09\x78\x00\x91\x02\xDA\xBC\x19\x10\xF0\x05", 11) == 0) {
2296 // super card ident
2297 uint8_t super[] = {0x0A, 0x00, 0x00, 0xA6, 0xB0, 0x00, 0x10, 0x14, 0x1D};
2298 ReaderTransmit(super, sizeof(super), NULL);
2299 res = ReaderReceive(buf, par);
2300 if (res == 22) {
2301 isGen = MAGIC_SUPER;
2302 goto OUT;
2305 isGen = MAGIC_GEN_2;
2306 goto OUT;
2308 // test for some MFC 7b gen2
2309 if (memcmp(buf, "\x0D\x78\x00\x71\x02\x88\x49\xA1\x30\x20\x15\x06\x08\x56\x3D", 15) == 0) {
2310 isGen = MAGIC_GEN_2;
2311 goto OUT;
2313 // test for Ultralight magic gen2
2314 if (memcmp(buf, "\x0A\x78\x00\x81\x02\xDB\xA0\xC1\x19\x40\x2A\xB5", 12) == 0) {
2315 isGen = MAGIC_GEN_2;
2316 goto OUT;
2318 // test for Ultralight EV1 magic gen2
2319 if (memcmp(buf, "\x85\x00\x00\xA0\x00\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x41\xDF", 18) == 0) {
2320 isGen = MAGIC_GEN_2;
2321 goto OUT;
2323 // test for some other Ultralight EV1 magic gen2
2324 if (memcmp(buf, "\x85\x00\x00\xA0\x0A\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x16\xD7", 18) == 0) {
2325 isGen = MAGIC_GEN_2;
2326 goto OUT;
2328 // test for some other Ultralight magic gen2
2329 if (memcmp(buf, "\x85\x00\x00\xA0\x0A\x00\x0A\xB0\x00\x00\x00\x00\x00\x00\x00\x00\x18\x4D", 18) == 0) {
2330 isGen = MAGIC_GEN_2;
2331 goto OUT;
2333 // test for NTAG213 magic gen2
2334 if (memcmp(buf, "\x85\x00\x00\xA0\x00\x00\x0A\xA5\x00\x04\x04\x02\x01\x00\x0F\x03\x79\x0C", 18) == 0) {
2335 isGen = MAGIC_GEN_2;
2336 goto OUT;
2340 if (is_mfc == false) {
2341 // magic ntag test
2342 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2343 SpinDelay(40);
2344 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2345 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2346 if (res == 2) {
2347 ReaderTransmit(rdblf0, sizeof(rdblf0), NULL);
2348 res = ReaderReceive(buf, par);
2349 if (res == 18) {
2350 isGen = MAGIC_NTAG21X;
2353 } else {
2354 // magic MFC Gen3 test
2355 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2356 SpinDelay(40);
2357 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2358 res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
2359 if (res == 2) {
2360 ReaderTransmit(rdbl00, sizeof(rdbl00), NULL);
2361 res = ReaderReceive(buf, par);
2362 if (res == 18) {
2363 isGen = MAGIC_GEN_3;
2369 OUT:
2371 data[0] = isGen;
2372 reply_ng(CMD_HF_MIFARE_CIDENT, PM3_SUCCESS, data, sizeof(data));
2373 // turns off
2374 OnSuccessMagic();
2375 BigBuf_free();
2378 void MifareHasStaticNonce(void) {
2380 // variables
2381 int retval = PM3_SUCCESS;
2382 uint32_t nt = 0;
2383 uint8_t *uid = BigBuf_malloc(10);
2385 memset(uid, 0x00, 10);
2387 uint8_t data[1] = { NONCE_FAIL };
2388 struct Crypto1State mpcs = {0, 0};
2389 struct Crypto1State *pcs;
2390 pcs = &mpcs;
2392 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2394 uint8_t counter = 0;
2395 for (uint8_t i = 0; i < 3; i++) {
2397 iso14a_card_select_t card_info;
2398 if (!iso14443a_select_card(uid, &card_info, NULL, true, 0, true)) {
2399 retval = PM3_ESOFT;
2400 goto OUT;
2403 uint8_t rec[4] = {0x00};
2404 uint8_t recpar[1] = {0x00};
2405 // Transmit MIFARE_CLASSIC_AUTH 0x60, block 0
2406 int len = mifare_sendcmd_short(pcs, false, MIFARE_AUTH_KEYA, 0, rec, recpar, NULL);
2407 if (len != 4) {
2408 retval = PM3_ESOFT;
2409 goto OUT;
2412 // Save the tag nonce (nt)
2413 if (nt == bytes_to_num(rec, 4)) {
2414 counter++;
2417 nt = bytes_to_num(rec, 4);
2419 // some cards with static nonce need to be reset before next query
2420 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2421 LEDsoff();
2422 CHK_TIMEOUT();
2424 memset(rec, 0x00, sizeof(rec));
2427 if (counter) {
2428 Dbprintf("%u static nonce %08x", data[0], nt);
2429 data[0] = NONCE_STATIC;
2430 } else {
2431 data[0] = NONCE_NORMAL;
2434 OUT:
2435 reply_ng(CMD_HF_MIFARE_STATIC_NONCE, retval, data, sizeof(data));
2436 // turns off
2437 OnSuccessMagic();
2438 BigBuf_free();
2439 crypto1_deinit(pcs);
2442 void OnSuccessMagic(void) {
2443 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2444 LEDsoff();
2445 set_tracing(false);
2447 void OnErrorMagic(uint8_t reason) {
2448 // ACK, ISOK, reason,0,0,0
2449 reply_mix(CMD_ACK, 0, reason, 0, 0, 0);
2450 OnSuccessMagic();
2453 int DoGen3Cmd(uint8_t *cmd, uint8_t cmd_len) {
2454 int retval = PM3_SUCCESS;
2455 uint8_t *par = BigBuf_malloc(MAX_PARITY_SIZE);
2456 uint8_t *buf = BigBuf_malloc(PM3_CMD_DATA_SIZE);
2458 LED_B_ON();
2459 uint32_t save_iso14a_timeout = iso14a_get_timeout();
2460 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 2000); // 2 seconds timeout
2462 ReaderTransmit(cmd, cmd_len, NULL);
2463 int res = ReaderReceive(buf, par);
2464 if (res == 4 && memcmp(buf, "\x90\x00\xfd\x07", 4) == 0) {
2465 // timeout for card memory reset
2466 SpinDelay(1000);
2467 } else {
2468 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Card operation not completed");
2469 retval = PM3_ESOFT;
2471 iso14a_set_timeout(save_iso14a_timeout);
2472 LED_B_OFF();
2474 return retval;
2477 void MifareGen3UID(uint8_t uidlen, uint8_t *uid) {
2478 int retval = PM3_SUCCESS;
2479 uint8_t uid_cmd[5] = { 0x90, 0xfb, 0xcc, 0xcc, 0x07 };
2480 uint8_t *old_uid = BigBuf_malloc(10);
2481 uint8_t *cmd = BigBuf_malloc(sizeof(uid_cmd) + uidlen + 2);
2482 iso14a_card_select_t *card_info = (iso14a_card_select_t *) BigBuf_malloc(sizeof(iso14a_card_select_t));
2484 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2485 clear_trace();
2486 set_tracing(true);
2488 if (iso14443a_select_card(old_uid, card_info, NULL, true, 0, true) == false) {
2489 retval = PM3_ESOFT;
2490 goto OUT;
2492 if (card_info->uidlen != uidlen) {
2493 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Wrong UID length");
2494 retval = PM3_ESOFT;
2495 goto OUT;
2498 memcpy(cmd, uid_cmd, sizeof(uid_cmd));
2499 memcpy(&cmd[sizeof(uid_cmd)], uid, uidlen);
2500 AddCrc14A(cmd, sizeof(uid_cmd) + uidlen);
2502 retval = DoGen3Cmd(cmd, sizeof(uid_cmd) + uidlen + 2);
2504 OUT:
2505 reply_ng(CMD_HF_MIFARE_GEN3UID, retval, old_uid, uidlen);
2506 // turns off
2507 OnSuccessMagic();
2508 BigBuf_free();
2511 void MifareGen3Blk(uint8_t block_len, uint8_t *block) {
2512 #define MIFARE_BLOCK_SIZE (MAX_MIFARE_FRAME_SIZE - 2)
2513 int retval = PM3_SUCCESS;
2514 uint8_t block_cmd[5] = { 0x90, 0xf0, 0xcc, 0xcc, 0x10 };
2515 uint8_t *uid = BigBuf_malloc(10);
2516 uint8_t *cmd = BigBuf_malloc(sizeof(block_cmd) + MAX_MIFARE_FRAME_SIZE);
2517 iso14a_card_select_t *card_info = (iso14a_card_select_t *) BigBuf_malloc(sizeof(iso14a_card_select_t));
2519 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2520 clear_trace();
2521 set_tracing(true);
2523 if (iso14443a_select_card(uid, card_info, NULL, true, 0, true) == false) {
2524 retval = PM3_ESOFT;
2525 goto OUT;
2528 bool doReselect = false;
2529 if (block_len < MIFARE_BLOCK_SIZE) {
2530 if ((mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_READBLOCK, 0, &cmd[sizeof(block_cmd)], NULL, NULL) != MAX_MIFARE_FRAME_SIZE)) {
2531 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Read manufacturer block failed");
2532 retval = PM3_ESOFT;
2533 goto OUT;
2535 doReselect = true;
2538 if (block_len > 0) {
2539 memcpy(cmd, block_cmd, sizeof(block_cmd));
2540 memcpy(&cmd[sizeof(block_cmd)], block, block_len);
2541 int ofs = sizeof(block_cmd);
2542 if (card_info->uidlen == 4) {
2543 cmd[ofs + 4] = cmd[ofs + 0] ^ cmd[ofs + 1] ^ cmd[ofs + 2] ^ cmd[ofs + 3];
2544 ofs += 5;
2545 } else if (card_info->uidlen == 7) {
2546 ofs += 7;
2547 } else {
2548 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Wrong Card UID length");
2549 retval = PM3_ESOFT;
2550 goto OUT;
2552 cmd[ofs++] = card_info->sak;
2553 cmd[ofs++] = card_info->atqa[0];
2554 cmd[ofs++] = card_info->atqa[1];
2555 AddCrc14A(cmd, sizeof(block_cmd) + MIFARE_BLOCK_SIZE);
2557 if (doReselect) {
2558 if (!iso14443a_select_card(uid, NULL, NULL, true, 0, true)) {
2559 retval = PM3_ESOFT;
2560 goto OUT;
2564 retval = DoGen3Cmd(cmd, sizeof(block_cmd) + MAX_MIFARE_FRAME_SIZE);
2567 OUT:
2568 reply_ng(CMD_HF_MIFARE_GEN3BLK, retval, &cmd[sizeof(block_cmd)], MIFARE_BLOCK_SIZE);
2569 // turns off
2570 OnSuccessMagic();
2571 BigBuf_free();
2574 void MifareGen3Freez(void) {
2575 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2576 clear_trace();
2577 set_tracing(true);
2579 int retval = PM3_SUCCESS;
2580 uint8_t freeze_cmd[7] = { 0x90, 0xfd, 0x11, 0x11, 0x00, 0xe7, 0x91 };
2581 uint8_t *uid = BigBuf_malloc(10);
2583 if (iso14443a_select_card(uid, NULL, NULL, true, 0, true) == false) {
2584 retval = PM3_ESOFT;
2585 goto OUT;
2588 retval = DoGen3Cmd(freeze_cmd, sizeof(freeze_cmd));
2590 OUT:
2591 reply_ng(CMD_HF_MIFARE_GEN3FREEZ, retval, NULL, 0);
2592 // turns off
2593 OnSuccessMagic();
2594 BigBuf_free();
2597 void MifareSetMod(uint8_t *datain) {
2599 uint8_t mod = datain[0];
2600 uint64_t ui64Key = bytes_to_num(datain + 1, 6);
2602 // variables
2603 uint16_t isOK = PM3_EUNDEF;
2604 uint8_t uid[10] = {0};
2605 uint32_t cuid = 0;
2606 struct Crypto1State mpcs = {0, 0};
2607 struct Crypto1State *pcs = &mpcs;
2608 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0};
2609 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0};
2611 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2613 clear_trace();
2614 set_tracing(true);
2616 LED_A_ON();
2617 LED_B_OFF();
2618 LED_C_OFF();
2620 while (true) {
2621 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
2622 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
2623 break;
2626 if (mifare_classic_auth(pcs, cuid, 0, 0, ui64Key, AUTH_FIRST)) {
2627 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Auth error");
2628 break;
2631 int respLen;
2632 if (((respLen = mifare_sendcmd_short(pcs, CRYPT_ALL, 0x43, mod, receivedAnswer, receivedAnswerPar, NULL)) != 1) || (receivedAnswer[0] != 0x0a)) {
2633 if (DBGLEVEL >= DBG_ERROR) Dbprintf("SetMod error; response[0]: %hhX, len: %d", receivedAnswer[0], respLen);
2634 break;
2637 if (mifare_classic_halt(pcs, cuid)) {
2638 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Halt error");
2639 break;
2642 isOK = PM3_SUCCESS;
2643 break;
2646 crypto1_deinit(pcs);
2648 LED_B_ON();
2649 reply_ng(CMD_HF_MIFARE_SETMOD, isOK, NULL, 0);
2650 LED_B_OFF();
2652 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2653 LEDsoff();
2657 // DESFIRE
2659 void Mifare_DES_Auth1(uint8_t arg0, uint8_t *datain) {
2660 uint8_t dataout[12] = {0x00};
2661 uint8_t uid[10] = {0x00};
2662 uint32_t cuid = 0;
2664 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2665 clear_trace();
2666 set_tracing(true);
2668 int len = iso14443a_select_card(uid, NULL, &cuid, true, 0, false);
2669 if (!len) {
2670 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
2671 OnError(1);
2672 return;
2675 if (mifare_desfire_des_auth1(cuid, dataout)) {
2676 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Authentication part1: Fail.");
2677 OnError(4);
2678 return;
2681 if (DBGLEVEL >= DBG_EXTENDED) DbpString("AUTH 1 FINISHED");
2682 reply_mix(CMD_ACK, 1, cuid, 0, dataout, sizeof(dataout));
2685 void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain) {
2686 uint32_t cuid = arg0;
2687 uint8_t key[16] = {0x00};
2688 uint8_t dataout[12] = {0x00};
2689 uint8_t isOK = 0;
2691 memcpy(key, datain, 16);
2693 isOK = mifare_desfire_des_auth2(cuid, key, dataout);
2695 if (isOK) {
2696 if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("Authentication part2: Failed");
2697 OnError(4);
2698 return;
2701 if (DBGLEVEL >= DBG_EXTENDED) DbpString("AUTH 2 FINISHED");
2703 reply_old(CMD_ACK, isOK, 0, 0, dataout, sizeof(dataout));
2704 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2705 LEDsoff();
2706 set_tracing(false);
2710 // Tear-off attack against MFU.
2711 // - Moebius et al
2712 void MifareU_Otp_Tearoff(uint8_t blno, uint32_t tearoff_time, uint8_t *data_testwrite) {
2713 uint8_t blockNo = blno;
2715 if (DBGLEVEL >= DBG_DEBUG) DbpString("Preparing OTP tear-off");
2717 if (tearoff_time > 43000)
2718 tearoff_time = 43000;
2719 tearoff_delay_us = tearoff_time;
2720 tearoff_enabled = true;
2722 LEDsoff();
2723 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2724 clear_trace();
2725 set_tracing(true);
2727 // write cmd to send, include CRC
2728 // 1b write, 1b block, 4b data, 2 crc
2729 uint8_t cmd[] = {
2730 MIFARE_ULC_WRITE, blockNo,
2731 data_testwrite[0], data_testwrite[1], data_testwrite[2], data_testwrite[3],
2732 0, 0
2734 AddCrc14A(cmd, sizeof(cmd) - 2);
2736 // anticollision / select card
2737 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
2738 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
2739 OnError(1);
2740 reply_ng(CMD_HF_MFU_OTP_TEAROFF, PM3_EFAILED, NULL, 0);
2741 return;
2743 // send
2744 LED_D_ON();
2745 ReaderTransmit(cmd, sizeof(cmd), NULL);
2746 tearoff_hook();
2747 reply_ng(CMD_HF_MFU_OTP_TEAROFF, PM3_SUCCESS, NULL, 0);
2751 // Tear-off attack against MFU counter
2752 void MifareU_Counter_Tearoff(uint8_t counter, uint32_t tearoff_time, uint8_t *datain) {
2754 if (tearoff_time > 43000)
2755 tearoff_time = 43000;
2757 LEDsoff();
2758 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
2759 clear_trace();
2760 set_tracing(true);
2762 // Send MFU counter increase cmd
2763 uint8_t cmd[] = {
2764 MIFARE_ULEV1_INCR_CNT,
2765 counter,
2766 datain[0], // lsb
2767 datain[1],
2768 datain[2], // msb
2769 datain[3], // rfu
2773 AddCrc14A(cmd, sizeof(cmd) - 2);
2775 // anticollision / select card
2776 if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) {
2777 if (DBGLEVEL >= DBG_ERROR) Dbprintf("Can't select card");
2778 OnError(1);
2779 switch_off();
2780 LEDsoff();
2781 return;
2784 // send
2785 ReaderTransmit(cmd, sizeof(cmd), NULL);
2786 LED_D_ON();
2787 SpinDelayUsPrecision(tearoff_time);
2788 switch_off();
2789 LEDsoff();
2790 reply_ng(CMD_HF_MFU_COUNTER_TEAROFF, PM3_SUCCESS, NULL, 0);