1 //-----------------------------------------------------------------------------
2 // Copyright (C) Gerhard de Koning Gans - May 2008
3 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // See LICENSE.txt for the text of the license.
16 //-----------------------------------------------------------------------------
18 #include "mifarecmd.h"
21 #include "proxmark3_arm.h"
23 #include "mifareutil.h"
24 #include "protocols.h"
29 #include "fpgaloader.h"
30 #include "iso14443a.h"
31 #include "mifaredesfire.h"
33 #include "commonutil.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)
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
48 // send an incomplete dummy response in order to trigger the card's authentication failure timeout
50 # define CHK_TIMEOUT(void) { \
51 ReaderTransmit(&dummy_answer, 1, NULL); \
52 uint32_t timeout = GetCountSspClk() + HARDNESTED_AUTHENTICATION_TIMEOUT; \
53 while (GetCountSspClk() < timeout) {}; \
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
) {
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
);
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");
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");
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");
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]");
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");
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");
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?
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");
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) {
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");
173 if (mifare_classic_halt(pcs
)) {
174 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
182 iso14a_set_timeout(timeout
);
183 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
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) {
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
;
214 } else if (res
!= PM3_SUCCESS
) {
215 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Write block error");
221 if (mifare_classic_halt(pcs
)) {
222 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
230 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
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);
260 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
265 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
266 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
271 if (!mifare_ultra_auth(keybytes
)) {
272 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Authentication failed");
278 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
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
) {
290 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
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);
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);
307 if (turn_off_field
) {
308 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
311 reply_ng(CMD_HF_MIFAREULAES_AUTH
, PM3_SUCCESS
, NULL
, 0);
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
325 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
330 int len
= iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true);
332 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card (RC:%02X)", len
);
337 // UL-C authentication
339 uint8_t key
[16] = {0x00};
340 memcpy(key
, datain
, sizeof(key
));
342 if (!mifare_ultra_auth(key
)) {
348 // UL-EV1 / NTAG authentication
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
)) {
359 if (mifare_ultra_readblock(blockNo
, dataout
)) {
360 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Read block error");
365 if (mifare_ultra_halt()) {
366 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
371 reply_mix(CMD_ACK
, 1, 0, 0, dataout
, 16);
372 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
376 // arg0 = blockNo (start)
377 // arg1 = Pages (number of blocks)
379 // datain = KEY bytes
380 void MifareUReadCard(uint8_t arg0
, uint16_t arg1
, uint8_t arg2
, uint8_t *datain
) {
383 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
385 // free eventually allocated BigBuf memory
387 BigBuf_Clear_ext(false);
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");
404 int len
= iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true);
406 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card (RC:%d)", len
);
411 // UL-C authentication
413 uint8_t key
[16] = {0x00};
414 memcpy(key
, datain
, sizeof(key
));
416 if (!mifare_ultra_auth(key
)) {
422 // UL-EV1 / NTAG authentication
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
)) {
434 for (int i
= 0; i
< blocks
; i
++) {
435 if ((i
* 4) + 4 >= CARD_MEMORY_SIZE
) {
436 Dbprintf("Data exceeds buffer!!");
440 len
= mifare_ultra_readblock(blockNo
+ i
, dataout
+ (4 * i
));
443 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Read block %d error", i
);
444 // if no blocks read - error out
449 //stop at last successful read block and return what we got
457 len
= mifare_ultra_halt();
459 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
464 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("Blocks read %d", countblocks
);
468 reply_mix(CMD_ACK
, 1, countblocks
, dataout
- BigBuf_get_addr(), 0, 0);
469 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
475 void MifareValue(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
) {
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);
489 uint8_t action
= datain
[9];
490 uint8_t transferBlk
= datain
[10];
491 bool needAuth
= datain
[33];
493 uint8_t uid
[10] = {0x00};
495 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
497 struct Crypto1State mpcs
= {0, 0};
498 struct Crypto1State
*pcs
;
501 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
511 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
512 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
516 if (mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
517 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Auth error");
521 if (mifare_classic_value(pcs
, blockNo
, blockdata
, action
) != PM3_SUCCESS
) {
522 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Write block error");
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");
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]);
541 if (mifare_classic_halt(pcs
)) {
542 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
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
);
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);
577 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
582 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
583 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
588 // UL-C authentication
590 uint8_t key
[16] = {0x00};
591 memcpy(key
, datain
+ 4, sizeof(key
));
593 if (!mifare_ultra_auth(key
)) {
599 // UL-EV1 / NTAG authentication
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
)) {
610 if (mifare_ultra_writeblock(blockNo
, blockdata
) != PM3_SUCCESS
) {
611 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Write block error");
616 if (mifare_ultra_halt()) {
617 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
622 if (g_dbglevel
>= 2) DbpString("WRITE BLOCK FINISHED");
625 reply_mix(CMD_ACK
, 1, 0, 0, 0, 0);
626 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
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);
651 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
656 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
657 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
662 // UL-C authentication
664 uint8_t key
[16] = {0x00};
665 memcpy(key
, datain
+ 16, sizeof(key
));
667 if (!mifare_ultra_auth(key
)) {
673 // UL-EV1 / NTAG authentication
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
)) {
684 if (mifare_ultra_writeblock_compat(blockNo
, blockdata
) != PM3_SUCCESS
) {
685 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Write block error");
690 if (mifare_ultra_halt()) {
691 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
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
);
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);
714 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
719 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
720 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
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");
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");
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");
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");
765 if (mifare_ultra_halt()) {
766 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
771 reply_mix(CMD_ACK
, 1, 0, 0, 0, 0);
772 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
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
) {
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)))
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};
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;
806 BigBuf_Clear_ext(false);
811 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
815 while (num_nonces
< PM3_CMD_DATA_SIZE
/ 4) {
817 // Test if the action was cancelled
818 if (BUTTON_PRESS()) {
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)");
830 switch (card_info
.uidlen
) {
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)");
851 // Transmit MIFARE_CLASSIC_AUTH
852 uint8_t dcmd
[4] = {0x60 + (keyType
& 0x01), blockNo
, 0x00, 0x00};
854 ReaderTransmit(dcmd
, sizeof(dcmd
), NULL
);
855 int len
= ReaderReceive(answer
, sizeof(answer
), par
);
857 // wait for the card to become ready again
861 if (g_dbglevel
>= 2) Dbprintf("AcquireNonces: Auth1 error");
865 // Save the tag nonce (nt)
866 memcpy(buf
+ num_nonces
* 4, answer
, 4);
872 reply_old(CMD_ACK
, isOK
, cuid
, num_nonces
, buf
, sizeof(buf
));
875 if (g_dbglevel
>= 3) DbpString("AcquireNonces finished");
878 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
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
;
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);
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;
920 BigBuf_Clear_ext(false);
925 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
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
;
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)");
947 switch (card_info
.uidlen
) {
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)");
969 SpinDelayUs(HARDNESTED_PRE_AUTHENTICATION_LEADTIME
);
972 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
)) {
973 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireEncryptedNonces: Auth1 error");
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
984 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireEncryptedNonces: Auth2 error len=%d", len
);
989 if (num_nonces
% 2) {
990 memcpy(buf
+ i
, receivedAnswer
, 4);
991 nt_par_enc
= par_enc
[0] & 0xf0;
993 nt_par_enc
|= par_enc
[0] >> 4;
994 memcpy(buf
+ i
+ 4, receivedAnswer
, 4);
995 memcpy(buf
+ i
+ 8, &nt_par_enc
, 1);
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]
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
;
1022 crypto1_deinit(pcs
);
1024 reply_old(CMD_ACK
, isOK
, cuid
, num_nonces
, buf
, sizeof(buf
));
1028 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1035 //-----------------------------------------------------------------------------
1036 // acquire static encrypted nonces in order to perform the attack described in
1037 // Philippe Teuwen, "MIFARE Classic: exposing the static encrypted nonce variant"
1038 //-----------------------------------------------------------------------------
1039 int MifareAcquireStaticEncryptedNonces(uint32_t flags
, const uint8_t *key
, bool reply
, uint8_t first_block_no
, uint8_t first_key_type
) {
1040 struct Crypto1State mpcs
= {0, 0};
1041 struct Crypto1State
*pcs
;
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
1054 // buf: working buffer to prepare those "blocks"
1055 uint8_t buf
[MIFARE_BLOCK_SIZE
] = {0x00};
1056 uint64_t ui64Key
= bytes_to_num(key
, 6);
1057 bool with_data
= flags
& 1;
1058 bool without_backdoor
= (flags
>> 1) & 1;
1059 if (with_data
&& without_backdoor
) {
1063 int16_t isOK
= PM3_SUCCESS
;
1064 uint8_t cascade_levels
= 0;
1065 bool have_uid
= false;
1071 BigBuf_Clear_ext(false);
1075 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1079 if (without_backdoor
) {
1082 iso14a_card_select_t card_info
;
1083 if (iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true) == 0) {
1084 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (ALL)");
1085 isOK
= PM3_ERFTRANS
;
1088 switch (card_info
.uidlen
) {
1101 if (mifare_classic_authex_cmd(pcs
, cuid
, first_block_no
, MIFARE_AUTH_KEYA
+ first_key_type
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
, NULL
, NULL
, false, false)) {
1102 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1107 uint16_t len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, MIFARE_AUTH_KEYA
+ first_key_type
, first_block_no
, receivedAnswer
, sizeof(receivedAnswer
), par_enc
, NULL
);
1109 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len
);
1113 uint32_t nt_enc
= bytes_to_num(receivedAnswer
, 4);
1115 // send some crap to fail auth
1118 if (iso14443a_fast_select_card(uid
, cascade_levels
) == 0) {
1119 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1120 isOK
= PM3_ERFTRANS
;
1123 if (mifare_classic_authex_cmd(pcs
, cuid
, first_block_no
, MIFARE_AUTH_KEYA
+ first_key_type
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
, NULL
, NULL
, false, false)) {
1124 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1129 struct Crypto1State mpcs_tmp
= {0, 0};
1130 struct Crypto1State
*pcs_tmp
= &mpcs_tmp
;
1131 crypto1_init(pcs_tmp
, ui64Key
);
1132 uint32_t nt
= crypto1_word(pcs_tmp
, nt_enc
^ cuid
, 1) ^ nt_enc
;
1133 int dist
= nonce_distance(nt
, nt1
);
1134 // ref dist is not always stable. Adjust physical distance to maximise ref dist, and try values around estimated nonces...
1135 Dbprintf("Block %2i key %i nested nT=%08x first nT=%08x dist=%i", first_block_no
, first_key_type
, nt
, nt1
, dist
);
1137 for (uint16_t sec
= 0; sec
< MIFARE_1K_MAXSECTOR
+ 1; sec
++) {
1138 uint16_t sec_gap
= sec
;
1139 if (sec
>= MIFARE_1K_MAXSECTOR
) {
1140 // gap between user blocks and advanced verification method blocks
1143 uint16_t blockNo
= sec_gap
* 4;
1144 for (uint8_t keyType
= 0; keyType
< 2; keyType
++) {
1145 // Test if the action was cancelled
1146 if (BUTTON_PRESS()) {
1147 isOK
= PM3_EOPABORTED
;
1151 len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, MIFARE_AUTH_KEYA
+ keyType
, blockNo
, receivedAnswer
, sizeof(receivedAnswer
), par_enc
, NULL
);
1153 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len
);
1158 memcpy(buf
+ (keyType
* 8) + 4, receivedAnswer
, 4);
1159 nt_enc
= bytes_to_num(receivedAnswer
, 4);
1160 uint8_t nt_par_err
= ((((par_enc
[0] >> 7) & 1) ^ oddparity8((nt_enc
>> 24) & 0xFF)) << 3 |
1161 (((par_enc
[0] >> 6) & 1) ^ oddparity8((nt_enc
>> 16) & 0xFF)) << 2 |
1162 (((par_enc
[0] >> 5) & 1) ^ oddparity8((nt_enc
>> 8) & 0xFF)) << 1 |
1163 (((par_enc
[0] >> 4) & 1) ^ oddparity8((nt_enc
>> 0) & 0xFF)));
1164 // Dbprintf("Sec %2i key %i {nT}=%02x%02x%02x%02x perr=%x", sec, keyType, receivedAnswer[0], receivedAnswer[1], receivedAnswer[2], receivedAnswer[3], nt_par_err);
1166 buf
[(keyType
* 8) + 2] = nt_par_err
;
1167 buf
[(keyType
* 8) + 3] = 0xAA; // extra check to tell we have nt/nt_enc/par_err
1169 // send some crap to fail auth
1172 if (iso14443a_fast_select_card(uid
, cascade_levels
) == 0) {
1173 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1174 isOK
= PM3_ERFTRANS
;
1177 if (mifare_classic_authex_cmd(pcs
, cuid
, first_block_no
, MIFARE_AUTH_KEYA
+ first_key_type
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
, NULL
, NULL
, false, false)) {
1178 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1182 nt1
= rewind_nonce(nt1
, dist
);
1183 num_to_bytes(nt1
>> 16, 2, buf
+ (keyType
* 8));
1184 emlSetMem_xt(buf
, (CARD_MEMORY_RF08S_OFFSET
/ MIFARE_BLOCK_SIZE
) + sec
, 1, MIFARE_BLOCK_SIZE
);
1188 for (uint16_t sec
= 0; sec
< MIFARE_1K_MAXSECTOR
+ 1; sec
++) {
1189 uint16_t sec_gap
= sec
;
1190 if (sec
>= MIFARE_1K_MAXSECTOR
) {
1191 // gap between user blocks and advanced verification method blocks
1194 uint16_t blockNo
= sec_gap
* 4;
1195 for (uint8_t keyType
= 0; keyType
< 2; keyType
++) {
1196 // Test if the action was cancelled
1197 if (BUTTON_PRESS()) {
1198 isOK
= PM3_EOPABORTED
;
1201 if (have_uid
== false) { // need a full select cycle to get the uid first
1202 iso14a_card_select_t card_info
;
1203 if (iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true) == 0) {
1204 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (ALL)");
1205 isOK
= PM3_ERFTRANS
;
1208 switch (card_info
.uidlen
) {
1222 } else { // no need for anticollision. We can directly select the card
1223 if (iso14443a_fast_select_card(uid
, cascade_levels
) == 0) {
1224 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1225 isOK
= PM3_ERFTRANS
;
1231 if (mifare_classic_authex_cmd(pcs
, cuid
, blockNo
, MIFARE_AUTH_KEYA
+ keyType
+ 4, ui64Key
, AUTH_FIRST
, &nt1
, NULL
, NULL
, NULL
, false, false)) {
1232 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1236 if ((with_data
) && (keyType
== 0)) {
1239 if (blockNo
>= MIFARE_1K_MAXSECTOR
* 4) {
1240 // special RF08S advanced authentication blocks, let's dump in emulator just in case
1243 for (uint16_t tb
= blockNo
; tb
< blockNo
+ blocks
; tb
++) {
1244 memset(data
, 0x00, sizeof(data
));
1245 int res
= mifare_classic_readblock(pcs
, tb
, data
);
1247 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Read error");
1251 emlSetMem_xt(data
, tb
, 1, 16);
1254 // nested authentication
1255 uint16_t len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, MIFARE_AUTH_KEYA
+ keyType
+ 4, blockNo
, receivedAnswer
, sizeof(receivedAnswer
), par_enc
, NULL
);
1257 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len
);
1261 uint32_t nt_enc
= bytes_to_num(receivedAnswer
, 4);
1262 crypto1_init(pcs
, ui64Key
);
1263 uint32_t nt
= crypto1_word(pcs
, nt_enc
^ cuid
, 1) ^ nt_enc
;
1264 // Dbprintf("Sec %2i key %i nT=%08x", sec, keyType + 4, nt);
1265 // store nt (first half)
1266 num_to_bytes(nt
>> 16, 2, buf
+ (keyType
* 8));
1267 // send some crap to fail auth
1270 if (iso14443a_fast_select_card(uid
, cascade_levels
) == 0) {
1271 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Can't select card (UID)");
1272 isOK
= PM3_ERFTRANS
;
1275 if (mifare_classic_authex_cmd(pcs
, cuid
, blockNo
, MIFARE_AUTH_KEYA
+ keyType
+ 4, ui64Key
, AUTH_FIRST
, &nt1
, NULL
, NULL
, NULL
, false, false)) {
1276 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth1 error");
1281 // nested authentication on regular keytype
1282 len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, MIFARE_AUTH_KEYA
+ keyType
, blockNo
, receivedAnswer
, sizeof(receivedAnswer
), par_enc
, NULL
);
1284 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("AcquireStaticEncryptedNonces: Auth2 error len=%d", len
);
1289 memcpy(buf
+ (keyType
* 8) + 4, receivedAnswer
, 4);
1290 nt_enc
= bytes_to_num(receivedAnswer
, 4);
1291 uint8_t nt_par_err
= ((((par_enc
[0] >> 7) & 1) ^ oddparity8((nt_enc
>> 24) & 0xFF)) << 3 |
1292 (((par_enc
[0] >> 6) & 1) ^ oddparity8((nt_enc
>> 16) & 0xFF)) << 2 |
1293 (((par_enc
[0] >> 5) & 1) ^ oddparity8((nt_enc
>> 8) & 0xFF)) << 1 |
1294 (((par_enc
[0] >> 4) & 1) ^ oddparity8((nt_enc
>> 0) & 0xFF)));
1295 // Dbprintf("Sec %2i key %i {nT}=%02x%02x%02x%02x perr=%x", sec, keyType, receivedAnswer[0], receivedAnswer[1], receivedAnswer[2], receivedAnswer[3], nt_par_err);
1297 buf
[(keyType
* 8) + 2] = nt_par_err
;
1298 buf
[(keyType
* 8) + 3] = 0xAA; // extra check to tell we have nt/nt_enc/par_err
1299 emlSetMem_xt(buf
, (CARD_MEMORY_RF08S_OFFSET
/ MIFARE_BLOCK_SIZE
) + sec
, 1, MIFARE_BLOCK_SIZE
);
1300 // send some crap to fail auth
1307 crypto1_deinit(pcs
);
1310 reply_mix(CMD_ACK
, isOK
, cuid
, 0, BigBuf_get_EM_addr() + CARD_MEMORY_RF08S_OFFSET
, MIFARE_BLOCK_SIZE
* (MIFARE_1K_MAXSECTOR
+ 1));
1314 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1321 //-----------------------------------------------------------------------------
1322 // MIFARE nested authentication.
1324 //-----------------------------------------------------------------------------
1325 void MifareNested(uint8_t blockNo
, uint8_t keyType
, uint8_t targetBlockNo
, uint8_t targetKeyType
, bool calibrate
, uint8_t *key
) {
1326 uint64_t ui64Key
= 0;
1327 ui64Key
= bytes_to_num(key
, 6);
1331 static uint16_t dmin
, dmax
;
1333 uint8_t par
[1] = {0x00};
1334 uint8_t par_array
[4] = {0x00};
1335 uint8_t uid
[10] = {0x00};
1336 uint32_t cuid
= 0, nt1
, nt2
, nttest
, ks1
;
1337 uint32_t target_nt
[2] = {0x00}, target_ks
[2] = {0x00};
1339 uint16_t ncount
= 0;
1340 struct Crypto1State mpcs
= {0, 0};
1341 struct Crypto1State
*pcs
;
1343 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
1345 uint32_t auth1_time
, auth2_time
;
1346 static uint16_t delta_time
= 0;
1350 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1352 // free eventually allocated BigBuf memory
1354 BigBuf_Clear_ext(false);
1361 // statistics on nonce distance
1362 int16_t isOK
= PM3_SUCCESS
;
1363 #define NESTED_MAX_TRIES 12
1364 if (calibrate
) { // calibrate: for first call only. Otherwise reuse previous calibration
1368 uint32_t prev_enc_nt
= 0;
1369 uint8_t prev_counter
= 0;
1371 uint16_t unsuccessful_tries
= 0;
1377 for (rtr
= 0; rtr
< 17; rtr
++) {
1379 // Test if the action was cancelled
1380 if (BUTTON_PRESS() || data_available()) {
1381 isOK
= PM3_EOPABORTED
;
1385 // prepare next select. No need to power down the card.
1386 if (mifare_classic_halt(pcs
)) {
1387 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Nested: Halt error");
1392 if (iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true) == 0) {
1393 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Nested: Can't select card");
1399 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, &auth1_time
)) {
1400 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Nested: Auth1 error");
1404 auth2_time
= (delta_time
) ? auth1_time
+ delta_time
: 0;
1406 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_NESTED
, &nt2
, &auth2_time
)) {
1407 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Nested: Auth2 error");
1412 // cards with fixed nonce
1413 // NXP Mifare is typical around 840,but for some unlicensed/compatible mifare card this can be 160
1415 uint32_t nttmp
= prng_successor(nt1
, 100);
1416 for (i
= 101; i
< 1200; i
++) {
1417 nttmp
= prng_successor(nttmp
, 1);
1418 if (nttmp
== nt2
) break;
1424 dmin
= MIN(dmin
, i
);
1425 dmax
= MAX(dmax
, i
);
1427 // allow some slack for proper timing
1428 delta_time
= auth2_time
- auth1_time
+ 32;
1430 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Nested: calibrating... ntdist=%d", i
);
1432 unsuccessful_tries
++;
1433 // card isn't vulnerable to nested attack (random numbers are not predictable)
1434 if (unsuccessful_tries
> NESTED_MAX_TRIES
) {
1445 if (prev_counter
== 5) {
1446 if (g_dbglevel
>= DBG_EXTENDED
) {
1447 DbpString("Static encrypted nonce detected, exiting...");
1448 Dbprintf("( %08x vs %08x )", prev_enc_nt
, nt2
);
1450 isOK
= PM3_ESTATIC_NONCE
;
1456 davg
= (davg
+ (rtr
- 1) / 2) / (rtr
- 1);
1458 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr
, isOK
, dmin
, dmax
, davg
, delta_time
);
1465 // -------------------------------------------------------------------------------------------------
1469 // get crypted nonces for target sector
1470 for (i
= 0; ((i
< 2) && (isOK
== PM3_SUCCESS
)); i
++) {
1472 // look for exactly two different nonces
1475 // continue until we have an unambiguous nonce
1476 while (target_nt
[i
] == 0) {
1478 // Test if the action was cancelled
1479 if (BUTTON_PRESS() || data_available()) {
1480 isOK
= PM3_EOPABORTED
;
1484 // prepare next select. No need to power down the card.
1485 if (mifare_classic_halt(pcs
)) {
1486 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Nested: Halt error");
1490 if (iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true) == false) {
1491 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Nested: Can't select card");
1496 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, &auth1_time
)) {
1497 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Nested: Auth1 error");
1501 // nested authentication
1502 auth2_time
= auth1_time
+ delta_time
;
1504 len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, MIFARE_AUTH_KEYA
+ (targetKeyType
& 0xF), targetBlockNo
, receivedAnswer
, sizeof(receivedAnswer
), par
, &auth2_time
);
1506 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Nested: Auth2 error len=%d", len
);
1510 nt2
= bytes_to_num(receivedAnswer
, 4);
1511 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i
+ 1, nt1
, nt2
, par
[0]);
1513 // Parity validity check
1514 for (j
= 0; j
< 4; j
++) {
1515 par_array
[j
] = (oddparity8(receivedAnswer
[j
]) != ((par
[0] >> (7 - j
)) & 0x01));
1519 nttest
= prng_successor(nt1
, dmin
- 1);
1520 for (j
= dmin
; j
< dmax
+ 1; j
++) {
1521 nttest
= prng_successor(nttest
, 1);
1524 if (valid_nonce(nttest
, nt2
, ks1
, par_array
)) {
1525 if (ncount
> 0) { // we are only interested in disambiguous nonces, try again
1526 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Nonce#%d: dismissed (ambiguous), ntdist=%d", i
+ 1, j
);
1530 target_nt
[i
] = nttest
;
1533 if (i
== 1 && target_nt
[1] == target_nt
[0]) { // we need two different nonces
1535 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Nonce#2: dismissed (= nonce#1), ntdist=%d", j
);
1538 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Nonce#%d: valid, ntdist=%d", i
+ 1, j
);
1541 if (target_nt
[i
] == 0 && j
== dmax
+ 1 && g_dbglevel
>= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i
+ 1);
1547 crypto1_deinit(pcs
);
1559 payload
.isOK
= isOK
;
1560 payload
.block
= targetBlockNo
;
1561 payload
.keytype
= targetKeyType
;
1563 memcpy(payload
.cuid
, &cuid
, 4);
1564 memcpy(payload
.nt_a
, &target_nt
[0], 4);
1565 memcpy(payload
.ks_a
, &target_ks
[0], 4);
1566 memcpy(payload
.nt_b
, &target_nt
[1], 4);
1567 memcpy(payload
.ks_b
, &target_ks
[1], 4);
1570 reply_ng(CMD_HF_MIFARE_NESTED
, PM3_SUCCESS
, (uint8_t *)&payload
, sizeof(payload
));
1571 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1576 void MifareStaticNested(uint8_t blockNo
, uint8_t keyType
, uint8_t targetBlockNo
, uint8_t targetKeyType
, uint8_t *key
) {
1580 uint64_t ui64Key
= bytes_to_num(key
, 6);
1581 uint16_t len
, dist1
= 160, dist2
= 320;
1582 uint8_t uid
[10] = { 0x00 };
1583 uint32_t cuid
= 0, nt1
= 0, nt2
= 0, nt3
= 0;
1584 uint32_t target_nt
[2] = {0x00}, target_ks
[2] = {0x00};
1585 uint8_t par
[1] = { 0x00 };
1586 uint8_t receivedAnswer
[10] = { 0x00 };
1588 struct Crypto1State mpcs
= { 0, 0 };
1589 struct Crypto1State
*pcs
;
1593 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1595 // free eventually allocated BigBuf memory
1597 BigBuf_Clear_ext(false);
1601 int16_t isOK
= PM3_ESOFT
;
1604 // Main loop - get crypted nonces for target sector
1605 for (uint8_t rtr
= 0; rtr
< 2; rtr
++) {
1607 // distance measurement
1608 if (mifare_classic_halt(pcs
)) {
1612 if (iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true) == false) {
1616 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
)) {
1620 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_NESTED
, &nt2
, NULL
)) {
1624 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_NESTED
, &nt3
, NULL
)) {
1628 dist1
= nonce_distance(nt1
, nt2
);
1629 dist2
= nonce_distance(nt1
, nt3
);
1631 if (mifare_classic_halt(pcs
)) {
1635 if (iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true) == false) {
1640 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
)) {
1644 // pre-generate nonces
1645 if (targetKeyType
== 1 && nt1
== 0x009080A2) {
1646 target_nt
[0] = prng_successor(nt1
, 161);
1647 target_nt
[1] = prng_successor(nt1
, 321);
1649 target_nt
[0] = prng_successor(nt1
, dist1
);
1650 target_nt
[1] = prng_successor(nt1
, dist2
);
1653 len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, MIFARE_AUTH_KEYA
+ (targetKeyType
& 0xF), targetBlockNo
, receivedAnswer
, sizeof(receivedAnswer
), par
, NULL
);
1658 nt2
= bytes_to_num(receivedAnswer
, 4);
1659 target_ks
[0] = nt2
^ target_nt
[0];
1661 // second collection
1662 if (mifare_classic_halt(pcs
)) {
1666 if (iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true) == false) {
1670 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
)) {
1674 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_NESTED
, NULL
, NULL
)) {
1678 len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, MIFARE_AUTH_KEYA
+ (targetKeyType
& 0xF), targetBlockNo
, receivedAnswer
, sizeof(receivedAnswer
), par
, NULL
);
1683 nt3
= bytes_to_num(receivedAnswer
, 4);
1684 target_ks
[1] = nt3
^ target_nt
[1];
1691 crypto1_deinit(pcs
);
1702 payload
.block
= targetBlockNo
;
1703 payload
.keytype
= targetKeyType
;
1705 memcpy(payload
.cuid
, &cuid
, 4);
1706 memcpy(payload
.nt_a
, &target_nt
[0], 4);
1707 memcpy(payload
.ks_a
, &target_ks
[0], 4);
1708 memcpy(payload
.nt_b
, &target_nt
[1], 4);
1709 memcpy(payload
.ks_b
, &target_ks
[1], 4);
1712 reply_ng(CMD_HF_MIFARE_STATIC_NESTED
, isOK
, (uint8_t *)&payload
, sizeof(payload
));
1713 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1718 //-----------------------------------------------------------------------------
1719 // MIFARE check keys. key count up to 85.
1721 //-----------------------------------------------------------------------------
1722 typedef struct sector_t
{
1727 typedef struct chk_t
{
1734 struct Crypto1State
*pcs
;
1738 // fast select, tries 5 times to select
1741 // 2 = failed to select.
1744 static uint8_t chkKey(struct chk_t
*c
) {
1745 uint8_t i
= 0, res
= 2;
1746 bool selected
= false;
1748 // this part is from Piwi's faster nonce collecting part in Hardnested.
1749 // assume: fast select
1750 if (!iso14443a_fast_select_card(c
->uid
, c
->cl
)) {
1755 res
= mifare_classic_authex(c
->pcs
, c
->cuid
, c
->block
, c
->keyType
, c
->key
, AUTH_FIRST
, NULL
, NULL
);
1759 // if successful auth, send HALT
1761 // mifare_classic_halt(c->pcs);
1764 if (selected
== false) {
1765 Dbprintf("chkKey: Failed at fast selecting the card!");
1770 static uint8_t chkKey_readb(struct chk_t
*c
, uint8_t *keyb
) {
1772 if (!iso14443a_fast_select_card(c
->uid
, c
->cl
))
1775 if (mifare_classic_authex(c
->pcs
, c
->cuid
, c
->block
, 0, c
->key
, AUTH_FIRST
, NULL
, NULL
))
1778 uint8_t data
[16] = {0x00};
1779 uint8_t res
= mifare_classic_readblock(c
->pcs
, c
->block
, data
);
1783 // data was something else than zeros.
1784 if (memcmp(data
+ 10, "\x00\x00\x00\x00\x00\x00", 6) != 0) {
1785 memcpy(keyb
, data
+ 10, 6);
1790 mifare_classic_halt(c
->pcs
);
1795 static void chkKey_scanA(struct chk_t
*c
, struct sector_t
*k_sector
, uint8_t *found
, const uint8_t *sectorcnt
, uint8_t *foundkeys
) {
1796 for (uint8_t s
= 0; s
< *sectorcnt
; s
++) {
1798 // skip already found A keys
1802 c
->block
= FirstBlockOfSector(s
);
1803 if (chkKey(c
) == 0) {
1804 num_to_bytes(c
->key
, 6, k_sector
[s
].keyA
);
1808 if (g_dbglevel
>= 3) Dbprintf("ChkKeys_fast: Scan A found (%d)", c
->block
);
1813 static void chkKey_scanB(struct chk_t
*c
, struct sector_t
*k_sector
, uint8_t *found
, const uint8_t *sectorcnt
, uint8_t *foundkeys
) {
1814 for (uint8_t s
= 0; s
< *sectorcnt
; s
++) {
1816 // skip already found B keys
1817 if (found
[(s
* 2) + 1])
1820 c
->block
= FirstBlockOfSector(s
);
1821 if (chkKey(c
) == 0) {
1822 num_to_bytes(c
->key
, 6, k_sector
[s
].keyB
);
1823 found
[(s
* 2) + 1] = 1;
1826 if (g_dbglevel
>= 3) Dbprintf("ChkKeys_fast: Scan B found (%d)", c
->block
);
1832 // when A is found but not B, try to read B.
1833 static void chkKey_loopBonly(struct chk_t
*c
, struct sector_t
*k_sector
, uint8_t *found
, uint8_t *sectorcnt
, uint8_t *foundkeys
) {
1835 // read Block B, if A is found.
1836 for (uint8_t s
= 0; s
< *sectorcnt
; ++s
) {
1838 if (found
[(s
* 2)] && found
[(s
* 2) + 1])
1841 c
->block
= (FirstBlockOfSector(s
) + NumBlocksPerSector(s
) - 1);
1844 if (found
[(s
* 2)] && !found
[(s
* 2) + 1]) {
1845 c
->key
= bytes_to_num(k_sector
[s
].keyA
, 6);
1846 uint8_t status
= chkKey_readb(c
, k_sector
[s
].keyB
);
1848 found
[(s
* 2) + 1] = 1;
1851 if (g_dbglevel
>= 3) Dbprintf("ChkKeys_fast: Reading B found (%d)", c
->block
);
1853 // try quick find all B?
1854 // assume: keys comes in groups. Find one B, test against all B.
1855 c
->key
= bytes_to_num(k_sector
[s
].keyB
, 6);
1857 chkKey_scanB(c
, k_sector
, found
, sectorcnt
, foundkeys
);
1863 // get Chunks of keys, to test authentication against card.
1864 // arg0 = antal sectorer
1865 // arg0 = first time
1866 // arg1 = clear trace
1867 // arg2 = antal nycklar i keychunk
1868 // datain = keys as array
1869 void MifareChkKeys_fast(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
) {
1872 uint8_t sectorcnt
= arg0
& 0xFF; // 16;
1873 uint8_t firstchunk
= (arg0
>> 8) & 0xF;
1874 uint8_t lastchunk
= (arg0
>> 12) & 0xF;
1875 uint16_t singleSectorParams
= (arg0
>> 16) & 0xFFFF;
1876 uint8_t strategy
= arg1
& 0xFF;
1877 uint8_t use_flashmem
= (arg1
>> 8) & 0xFF;
1878 uint16_t keyCount
= arg2
& 0xFF;
1880 bool singleSectorMode
= (singleSectorParams
>> 15) & 1;
1881 uint8_t keytype
= (singleSectorParams
>> 8) & 1;
1882 uint8_t blockn
= singleSectorParams
& 0xFF;
1884 struct Crypto1State mpcs
= {0, 0};
1885 struct Crypto1State
*pcs
;
1887 struct chk_t chk_data
;
1889 uint8_t allkeys
= sectorcnt
<< 1;
1891 static uint32_t cuid
= 0;
1892 static uint8_t cascade_levels
= 0;
1893 static uint8_t foundkeys
= 0;
1894 static sector_t k_sector
[80];
1895 static uint8_t found
[80];
1896 static uint8_t *uid
;
1898 int oldbg
= g_dbglevel
;
1904 if (exists_in_spiffs(MF_KEYS_FILE
)) {
1905 size
= size_in_spiffs(MF_KEYS_FILE
);
1908 Dbprintf("Spiffs file: %s does not exists or empty.", MF_KEYS_FILE
);
1912 keyCount
= size
/ MF_KEY_LENGTH
;
1917 // limit size of available for keys in bigbuff
1919 uint16_t key_mem_available
= MIN(BigBuf_get_size(), keyCount
* MF_KEY_LENGTH
);
1921 keyCount
= key_mem_available
/ MF_KEY_LENGTH
;
1923 datain
= BigBuf_malloc(key_mem_available
);
1927 if (SPIFFS_OK
== rdv40_spiffs_read_as_filetype(MF_KEYS_FILE
, datain
, keyCount
* MF_KEY_LENGTH
, RDV40_SPIFFS_SAFETY_SAFE
)) {
1928 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Loaded %u keys from spiffs file: %s", keyCount
, MF_KEYS_FILE
);
1930 Dbprintf("Spiffs file: %s cannot be read.", MF_KEYS_FILE
);
1936 if (uid
== NULL
|| firstchunk
) {
1937 uid
= BigBuf_malloc(10);
1942 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1951 memset(k_sector
, 0x00, 480 + 10);
1952 memset(found
, 0x00, sizeof(found
));
1955 iso14a_card_select_t card_info
;
1956 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
1957 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("ChkKeys_fast: Can't select card (ALL)");
1961 switch (card_info
.uidlen
) {
1978 // clear debug level. We are expecting lots of authentication failures...
1979 g_dbglevel
= DBG_NONE
;
1981 // set check struct.
1983 chk_data
.cuid
= cuid
;
1984 chk_data
.cl
= cascade_levels
;
1988 if (singleSectorMode
) {
1990 chk_data
.block
= blockn
;
1991 chk_data
.keyType
= keytype
;
1992 for (uint16_t i
= 0; i
< keyCount
; ++i
) {
1994 // Allow button press / usb cmd to interrupt device
1995 if (BUTTON_PRESS() || data_available()) {
2001 chk_data
.key
= bytes_to_num(datain
+ i
* 6, 6);
2002 if (chkKey(&chk_data
) == 0) {
2004 reply_old(CMD_ACK
, 1, 0, 0, datain
+ i
* 6, 6);
2008 reply_mix(CMD_ACK
, 0, 0, 0, 0, 0);
2011 crypto1_deinit(pcs
);
2012 if (foundkeys
== allkeys
|| lastchunk
) {
2014 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2016 BigBuf_Clear_ext(false);
2023 // keychunk loop - depth first one sector.
2024 if (strategy
== 1 || use_flashmem
) {
2026 uint8_t newfound
= foundkeys
;
2028 uint16_t lastpos
= 0;
2029 uint16_t s_point
= 0;
2031 // keep track of how many sectors on card.
2032 for (uint8_t s
= 0; s
< sectorcnt
; ++s
) {
2034 if (found
[(s
* 2)] && found
[(s
* 2) + 1])
2037 for (uint16_t i
= s_point
; i
< keyCount
; ++i
) {
2039 // Allow button press / usb cmd to interrupt device
2040 if (BUTTON_PRESS() || data_available()) {
2045 if (foundkeys
== allkeys
)
2050 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
2051 chk_data
.block
= FirstBlockOfSector(s
);
2054 chk_data
.key
= bytes_to_num(datain
+ i
* 6, 6);
2056 // skip already found A keys
2057 if (!found
[(s
* 2)]) {
2058 chk_data
.keyType
= 0;
2059 status
= chkKey(&chk_data
);
2061 memcpy(k_sector
[s
].keyA
, datain
+ i
* 6, 6);
2065 chkKey_scanA(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
2067 // read Block B, if A is found.
2068 chkKey_loopBonly(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
2070 chk_data
.keyType
= 1;
2071 chkKey_scanB(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
2073 chk_data
.keyType
= 0;
2074 chk_data
.block
= FirstBlockOfSector(s
);
2077 if (lastpos
!= i
&& lastpos
!= 0) {
2078 if (i
- lastpos
< 0xF) {
2079 s_point
= i
& 0xFFF0;
2088 // skip already found B keys
2089 if (!found
[(s
* 2) + 1]) {
2090 chk_data
.keyType
= 1;
2091 status
= chkKey(&chk_data
);
2093 memcpy(k_sector
[s
].keyB
, datain
+ i
* 6, 6);
2094 found
[(s
* 2) + 1] = 1;
2097 chkKey_scanB(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
2100 if (lastpos
!= i
&& lastpos
!= 0) {
2102 if (i
- lastpos
< 0xF)
2103 s_point
= i
& 0xFFF0;
2111 if (found
[(s
* 2)] && found
[(s
* 2) + 1])
2114 } // end keys test loop - depth first
2116 // assume1. if no keys found in first sector, get next keychunk from client
2117 if (!use_flashmem
&& (newfound
- foundkeys
== 0))
2120 } // end loop - sector
2123 if (foundkeys
== allkeys
)
2126 if (strategy
== 2 || use_flashmem
) {
2129 for (uint16_t i
= 0; i
< keyCount
; i
++) {
2131 // Allow button press / usb cmd to interrupt device
2132 if (BUTTON_PRESS() || data_available()) break;
2135 if (foundkeys
== allkeys
)
2141 chk_data
.key
= bytes_to_num(datain
+ i
* 6, 6);
2144 // keep track of how many sectors on card.
2145 for (uint8_t s
= 0; s
< sectorcnt
; ++s
) {
2147 if (found
[(s
* 2)] && found
[(s
* 2) + 1]) continue;
2150 if (foundkeys
== allkeys
)
2153 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
2154 chk_data
.block
= FirstBlockOfSector(s
);
2156 // skip already found A keys
2157 if (!found
[(s
* 2)]) {
2158 chk_data
.keyType
= 0;
2159 status
= chkKey(&chk_data
);
2161 memcpy(k_sector
[s
].keyA
, datain
+ i
* 6, 6);
2165 chkKey_scanA(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
2167 // read Block B, if A is found.
2168 chkKey_loopBonly(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
2170 chk_data
.block
= FirstBlockOfSector(s
);
2174 // skip already found B keys
2175 if (!found
[(s
* 2) + 1]) {
2176 chk_data
.keyType
= 1;
2177 status
= chkKey(&chk_data
);
2179 memcpy(k_sector
[s
].keyB
, datain
+ i
* 6, 6);
2180 found
[(s
* 2) + 1] = 1;
2183 chkKey_scanB(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
2186 } // end loop sectors
2188 } // end loop strategy 2
2192 crypto1_deinit(pcs
);
2194 // All keys found, send to client, or last keychunk from client
2195 if (foundkeys
== allkeys
|| lastchunk
) {
2198 for (uint8_t m
= 0; m
< 64; m
++) {
2199 foo
|= ((uint64_t)(found
[m
] & 1) << m
);
2204 for (uint8_t m
= 64; m
< ARRAYLEN(found
); m
++) {
2205 bar
|= ((uint16_t)(found
[m
] & 1) << j
++);
2208 uint8_t *tmp
= BigBuf_malloc(480 + 10);
2209 memcpy(tmp
, k_sector
, sectorcnt
* sizeof(sector_t
));
2210 num_to_bytes(foo
, 8, tmp
+ 480);
2211 tmp
[488] = bar
& 0xFF;
2212 tmp
[489] = bar
>> 8 & 0xFF;
2214 reply_old(CMD_ACK
, foundkeys
, 0, 0, tmp
, 480 + 10);
2217 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2219 BigBuf_Clear_ext(false);
2221 // special trick ecfill
2222 if (use_flashmem
&& foundkeys
== allkeys
) {
2224 uint8_t block
[16] = {0};
2225 for (int i
= 0; i
< sectorcnt
; i
++) {
2229 blockno
= (i
* 4) ^ 0x3;
2231 blockno
= (32 * 4 + (i
- 32) * 16) ^ 0xF;
2234 emlGetMem(block
, blockno
, 1);
2236 memcpy(block
, k_sector
[i
].keyA
, 6);
2237 memcpy(block
+ 10, k_sector
[i
].keyB
, 6);
2239 emlSetMem_xt(block
, blockno
, 1, sizeof(block
));
2242 MifareECardLoad(sectorcnt
, MF_KEY_A
, NULL
);
2243 MifareECardLoad(sectorcnt
, MF_KEY_B
, NULL
);
2246 // partial/none keys found
2247 reply_mix(CMD_ACK
, foundkeys
, 0, 0, 0, 0);
2253 void MifareChkKeys(uint8_t *datain
, uint8_t reserved_mem
) {
2255 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2257 struct Crypto1State mpcs
= {0, 0};
2258 struct Crypto1State
*pcs
;
2261 uint8_t uid
[10] = {0x00};
2265 uint8_t cascade_levels
= 0;
2270 keyresult
.found
= false;
2271 memset(keyresult
.key
, 0x00, sizeof(keyresult
.key
));
2273 bool have_uid
= false;
2275 uint8_t keyType
= datain
[0];
2276 uint8_t blockNo
= datain
[1];
2277 bool clearTrace
= datain
[2];
2278 uint16_t key_count
= (datain
[3] << 8) | datain
[4];
2280 uint16_t key_mem_available
;
2282 key_mem_available
= key_count
* 6;
2284 key_mem_available
= MIN((PM3_CMD_DATA_SIZE
- 5), key_count
* 6);
2286 key_count
= key_mem_available
/ 6;
2293 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2298 int oldbg
= g_dbglevel
;
2299 g_dbglevel
= DBG_NONE
;
2303 for (uint16_t i
= 0; i
< key_count
; i
++) {
2305 // Iceman: use piwi's faster nonce collecting part in hardnested.
2306 if (have_uid
== false) { // need a full select cycle to get the uid first
2307 iso14a_card_select_t card_info
;
2308 if (iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true) == false) {
2309 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("ChkKeys: Can't select card (ALL)");
2310 --i
; // try same key once again
2313 switch (card_info
.uidlen
) {
2327 } else { // no need for anticollision. We can directly select the card
2328 if (iso14443a_select_card(uid
, NULL
, NULL
, false, cascade_levels
, true) == false) {
2329 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("ChkKeys: Can't select card (UID)");
2330 --i
; // try same key once again
2335 key
= bytes_to_num(datain
+ i
* 6, 6);
2336 if (mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, key
, AUTH_FIRST
)) {
2341 memcpy(keyresult
.key
, datain
+ i
* 6, 6);
2342 keyresult
.found
= true;
2347 crypto1_deinit(pcs
);
2349 reply_ng(CMD_HF_MIFARE_CHKKEYS
, PM3_SUCCESS
, (uint8_t *)&keyresult
, sizeof(keyresult
));
2350 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2356 void MifareChkKeys_file(uint8_t *fn
) {
2363 int changed
= rdv40_spiffs_lazy_mount();
2364 uint32_t size
= size_in_spiffs((char *)fn
);
2365 uint8_t *mem
= BigBuf_malloc(size
);
2367 rdv40_spiffs_read_as_filetype((char *)fn
, mem
, size
, RDV40_SPIFFS_SAFETY_SAFE
);
2370 rdv40_spiffs_lazy_unmount();
2375 MifareChkKeys(mem
, true);
2381 //-----------------------------------------------------------------------------
2382 // MIFARE Personalize UID. Only for Mifare Classic EV1 7Byte UID
2383 //-----------------------------------------------------------------------------
2384 void MifarePersonalizeUID(uint8_t keyType
, uint8_t perso_option
, uint64_t key
) {
2386 uint16_t isOK
= PM3_EUNDEF
;
2389 struct Crypto1State mpcs
= {0, 0};
2390 struct Crypto1State
*pcs
;
2393 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2400 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
2401 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
2405 uint8_t block_number
= 0;
2406 if (mifare_classic_auth(pcs
, cuid
, block_number
, keyType
, key
, AUTH_FIRST
)) {
2407 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Auth error");
2411 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
];
2412 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
];
2413 int len
= mifare_sendcmd_short(pcs
, true, MIFARE_EV1_PERSONAL_UID
, perso_option
, receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
, NULL
);
2414 if (len
!= 1 || receivedAnswer
[0] != CARD_ACK
) {
2415 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Cmd Error: %02x", receivedAnswer
[0]);
2419 if (mifare_classic_halt(pcs
)) {
2420 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
2427 crypto1_deinit(pcs
);
2430 reply_ng(CMD_HF_MIFARE_PERSONALIZE_UID
, isOK
, NULL
, 0);
2433 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2438 //-----------------------------------------------------------------------------
2439 // Work with emulator memory
2441 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
2442 // involved in dealing with emulator memory. But if it is called later, it might
2443 // destroy the Emulator Memory.
2444 //-----------------------------------------------------------------------------
2446 void MifareEMemClr(void) {
2447 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
2451 void MifareEMemGet(uint8_t blockno
, uint8_t blockcnt
) {
2452 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
2455 size_t size
= blockcnt
* 16;
2456 if (size
> PM3_CMD_DATA_SIZE
) {
2457 reply_ng(CMD_HF_MIFARE_EML_MEMGET
, PM3_EMALLOC
, NULL
, 0);
2461 uint8_t *buf
= BigBuf_malloc(size
);
2463 emlGetMem(buf
, blockno
, blockcnt
); // data, block num, blocks count (max 4)
2466 reply_ng(CMD_HF_MIFARE_EML_MEMGET
, PM3_SUCCESS
, buf
, size
);
2468 BigBuf_free_keep_EM();
2471 //-----------------------------------------------------------------------------
2472 // Load a card into the emulator memory
2474 //-----------------------------------------------------------------------------
2475 int MifareECardLoadExt(uint8_t sectorcnt
, uint8_t keytype
, uint8_t *key
) {
2476 int retval
= MifareECardLoad(sectorcnt
, keytype
, key
);
2477 reply_ng(CMD_HF_MIFARE_EML_LOAD
, retval
, NULL
, 0);
2481 int MifareECardLoad(uint8_t sectorcnt
, uint8_t keytype
, uint8_t *key
) {
2482 if ((keytype
> MF_KEY_B
) && (key
== NULL
)) {
2483 if (g_dbglevel
>= DBG_ERROR
) {
2484 Dbprintf("Error, missing key");
2489 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2495 bool have_uid
= false;
2496 bool bd_authenticated
= false;
2497 uint8_t cascade_levels
= 0;
2499 uint8_t uid
[10] = {0x00};
2500 struct Crypto1State mpcs
= {0, 0};
2501 struct Crypto1State
*pcs
;
2504 int retval
= PM3_SUCCESS
;
2506 // increase time-out. Magic card etc are slow
2507 uint32_t timeout
= iso14a_get_timeout();
2508 // frame waiting time (FWT) in 1/fc
2509 uint32_t fwt
= 256 * 16 * (1 << 6);
2510 iso14a_set_timeout(fwt
/ (8 * 16));
2512 for (uint8_t s
= 0; s
< sectorcnt
; s
++) {
2514 uint64_t ui64Key
= emlGetKey(s
, keytype
);
2516 // MIFARE Classic 1K Ev1 , MIFARE Classic MINI Ev1
2517 if (sectorcnt
== 18) {
2518 // MFC 1K EV1, skip sector 16 since its lockdown
2520 // unknown sector trailer, keep the keys, set only the AC
2521 uint8_t st
[16] = {0x00};
2522 emlGetMem(st
, FirstBlockOfSector(s
) + 3, 1);
2523 memcpy(st
+ 6, "\x70\xF0\xF8\x69", 4);
2524 emlSetMem_xt(st
, FirstBlockOfSector(s
) + 3, 1, 16);
2528 // ICEMAN: ugly hack, we don't want to trigger the partial load message
2529 // MFC 1K EV1 sector 17 don't use key A.
2530 // not mention we don't save signatures in our MFC dump files.
2531 if (s
== 17 && keytype
== MF_KEY_A
) {
2532 ui64Key
= 0x4B791BEA7BCC;
2538 if (have_uid
== false) { // need a full select cycle to get the uid first
2539 iso14a_card_select_t card_info
;
2540 if (iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true) == 0) {
2542 // first attempt, if no card let's stop directly
2543 retval
= PM3_EFAILED
;
2544 if (g_dbglevel
>= DBG_ERROR
) {
2545 Dbprintf("Card not found");
2552 switch (card_info
.uidlen
) {
2566 } else { // no need for anticollision. We can directly select the card
2567 if (!bd_authenticated
) { // no need to select if bd_authenticated with backdoor
2568 if (iso14443a_fast_select_card(uid
, cascade_levels
) == 0) {
2575 if (keytype
> MF_KEY_B
) {
2576 if (! bd_authenticated
) {
2577 ui64Key
= bytes_to_num(key
, 6);
2578 if (mifare_classic_auth(pcs
, cuid
, 0, keytype
, ui64Key
, AUTH_FIRST
)) {
2579 retval
= PM3_EFAILED
;
2580 if (g_dbglevel
>= DBG_ERROR
) {
2581 Dbprintf("Auth error");
2585 bd_authenticated
= true;
2587 } else if (mifare_classic_auth(pcs
, cuid
, FirstBlockOfSector(s
), keytype
, ui64Key
, AUTH_FIRST
)) {
2589 ui64Key
= emlGetKey(s
, MF_KEY_B
);
2591 if (mifare_classic_auth(pcs
, cuid
, FirstBlockOfSector(s
), MF_KEY_B
, ui64Key
, AUTH_FIRST
)) {
2592 retval
= PM3_EPARTIAL
;
2593 if (g_dbglevel
>= DBG_ERROR
) {
2594 Dbprintf("Sector %2d - Auth error", s
);
2601 #define MAX_RETRIES 2
2603 uint8_t data
[16] = {0x00};
2604 for (uint8_t b
= 0; b
< NumBlocksPerSector(s
); b
++) {
2606 memset(data
, 0x00, sizeof(data
));
2607 uint8_t tb
= FirstBlockOfSector(s
) + b
;
2609 for (; r
< MAX_RETRIES
; r
++) {
2611 int res
= mifare_classic_readblock(pcs
, tb
, data
);
2613 retval
|= PM3_EPARTIAL
;
2614 if (g_dbglevel
>= DBG_ERROR
) {
2615 Dbprintf("Error No rights reading sector %2d block %2d", s
, b
);
2619 // retry if wrong len.
2624 // No need to copy empty
2625 if (memcmp(data
, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16) == 0) {
2629 if (IsSectorTrailer(b
)) {
2630 // sector trailer, keep the keys, set only the AC
2631 uint8_t st
[16] = {0x00};
2632 emlGetMem(st
, tb
, 1);
2633 memcpy(st
+ 6, data
+ 6, 4);
2634 emlSetMem_xt(st
, tb
, 1, 16);
2636 emlSetMem_xt(data
, tb
, 1, 16);
2641 // if we failed all retries, notify client
2642 if (r
== MAX_RETRIES
) {
2643 retval
|= PM3_EPARTIAL
;
2649 res
= mifare_classic_halt(pcs
);
2652 iso14a_set_timeout(timeout
);
2653 crypto1_deinit(pcs
);
2654 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2662 //-----------------------------------------------------------------------------
2663 // Work with "magic Chinese" card (email him: ouyangweidaxian@live.cn)
2665 // PARAMS - workFlags
2666 // bit 0 - need get UID
2667 // bit 1 - need wupC
2668 // bit 2 - need HALT after sequence
2669 // bit 3 - need turn on FPGA before sequence
2670 // bit 4 - need turn off FPGA
2671 // bit 5 - need to set datain instead of issuing USB reply (called via ARM for StandAloneMode14a)
2672 // bit 6 - wipe tag.
2673 // bit 7 - use USCUID/GDM (20/23) magic wakeup
2674 //-----------------------------------------------------------------------------
2676 void MifareCSetBlock(uint32_t arg0
, uint32_t arg1
, uint8_t *datain
) {
2679 uint8_t workFlags
= arg0
;
2680 uint8_t blockNo
= arg1
;
2686 bool isOK
= false; //assume we will get an error
2687 uint8_t errormsg
= 0x00;
2688 uint8_t uid
[10] = {0x00};
2689 uint8_t data
[18] = {0x00};
2692 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
2693 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
2695 if (workFlags
& MAGIC_INIT
) {
2698 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2703 //loop doesn't loop just breaks out if error
2705 // read UID and return to client with write
2706 if (workFlags
& MAGIC_UID
) {
2707 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
2708 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
2709 errormsg
= MAGIC_UID
;
2710 mifare_classic_halt(NULL
);
2713 mifare_classic_halt(NULL
);
2716 // wipe tag, fill it with zeros
2717 if (workFlags
& MAGIC_WIPE
) {
2718 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
2719 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2720 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("wupC1 error");
2721 errormsg
= MAGIC_WIPE
;
2725 uint32_t old_timeout
= iso14a_get_timeout();
2728 // 13560000 / 1000 / (8 * 16) * timeout
2729 iso14a_set_timeout(21190);
2731 ReaderTransmit(wipeC
, sizeof(wipeC
), NULL
);
2732 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2733 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("wipeC error");
2734 errormsg
= MAGIC_WIPE
;
2737 iso14a_set_timeout(old_timeout
);
2739 mifare_classic_halt(NULL
);
2742 if (workFlags
& MAGIC_GDM_ALT_WUPC
) {
2743 ReaderTransmitBitsPar(wupGDM1
, 7, NULL
, NULL
);
2744 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2745 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("wupGDM1 error");
2746 errormsg
= MAGIC_WUPC
;
2750 ReaderTransmit(wupGDM2
, sizeof(wupC2
), NULL
);
2751 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2752 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("wupGDM2 error");
2753 errormsg
= MAGIC_WUPC
;
2759 if (workFlags
& MAGIC_WUPC
) {
2760 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
2761 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2762 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("wupC1 error");
2763 errormsg
= MAGIC_WUPC
;
2768 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
2769 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2770 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2777 if ((mifare_sendcmd_short(NULL
, CRYPT_NONE
, ISO14443A_CMD_WRITEBLOCK
, blockNo
, receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
, NULL
) != 1) || (receivedAnswer
[0] != 0x0a)) {
2778 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("write block send command error");
2783 memcpy(data
, datain
, 16);
2784 AddCrc14A(data
, 16);
2786 ReaderTransmit(data
, sizeof(data
), NULL
);
2787 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) != 1) || (receivedAnswer
[0] != 0x0a)) {
2788 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("write block send data error");
2793 if (workFlags
& MAGIC_HALT
) {
2794 mifare_classic_halt(NULL
);
2803 reply_mix(CMD_ACK
, 1, 0, 0, uid
, sizeof(uid
));
2805 OnErrorMagic(errormsg
);
2807 if (workFlags
& MAGIC_OFF
)
2811 void MifareCGetBlock(uint32_t arg0
, uint32_t arg1
, uint8_t *datain
) {
2813 uint8_t workFlags
= arg0
;
2814 uint8_t blockNo
= arg1
;
2815 uint8_t errormsg
= 0x00;
2816 bool isOK
= false; //assume we will get an error
2822 uint8_t data
[MAX_MIFARE_FRAME_SIZE
];
2823 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
2824 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
2826 memset(data
, 0x00, sizeof(data
));
2828 if (workFlags
& MAGIC_INIT
) {
2831 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2836 // increase time-out. Magic card etc are slow
2837 uint32_t timeout
= iso14a_get_timeout();
2838 // frame waiting time (FWT) in 1/fc
2839 uint32_t fwt
= 256 * 16 * (1 << 7);
2840 iso14a_set_timeout(fwt
/ (8 * 16));
2842 //loop doesn't loop just breaks out if error or done
2844 if (workFlags
& MAGIC_GDM_ALT_WUPC
) {
2845 ReaderTransmitBitsPar(wupGDM1
, 7, NULL
, NULL
);
2846 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2847 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("wupGDM1 error");
2848 errormsg
= MAGIC_WUPC
;
2852 ReaderTransmit(wupGDM2
, sizeof(wupC2
), NULL
);
2853 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2854 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("wupGDM2 error");
2855 errormsg
= MAGIC_WUPC
;
2860 if (workFlags
& MAGIC_WUPC
) {
2861 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
2862 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2863 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("wupC1 error");
2864 errormsg
= MAGIC_WUPC
;
2868 if (is1b
== false) {
2869 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
2870 if ((ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) || (receivedAnswer
[0] != 0x0a)) {
2871 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2879 if ((mifare_sendcmd_short(NULL
, CRYPT_NONE
, ISO14443A_CMD_READBLOCK
, blockNo
, receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
, NULL
) != MAX_MIFARE_FRAME_SIZE
)) {
2880 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("read block send command error");
2885 memcpy(data
, receivedAnswer
, sizeof(data
));
2888 if (workFlags
& MAGIC_HALT
) {
2889 mifare_classic_halt(NULL
);
2895 // if MAGIC_DATAIN, the data stays on device side.
2896 if (workFlags
& MAGIC_DATAIN
) {
2898 memcpy(datain
, data
, sizeof(data
));
2902 reply_old(CMD_ACK
, 1, 0, 0, data
, sizeof(data
));
2904 OnErrorMagic(errormsg
);
2908 if (workFlags
& MAGIC_OFF
) {
2912 iso14a_set_timeout(timeout
);
2915 static void mf_reset_card(void) {
2916 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2918 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2921 void MifareCIdent(bool is_mfc
, uint8_t keytype
, uint8_t *key
) {
2923 uint8_t rec
[1] = {0x00};
2924 uint8_t recpar
[1] = {0x00};
2925 uint8_t rats
[4] = {ISO14443A_CMD_RATS
, 0x80, 0x31, 0x73};
2926 uint8_t rdblf0
[4] = {ISO14443A_CMD_READBLOCK
, 0xF0, 0x8D, 0x5f};
2927 uint8_t rdbl00
[4] = {ISO14443A_CMD_READBLOCK
, 0x00, 0x02, 0xa8};
2928 uint8_t gen4gdmAuth
[4] = {MIFARE_MAGIC_GDM_AUTH_KEY
, 0x00, 0x6C, 0x92};
2929 uint8_t gen4gdmGetConf
[4] = {MIFARE_MAGIC_GDM_READ_CFG
, 0x00, 0x39, 0xF7};
2930 uint8_t gen4gdmGetMagicBlock
[4] = {MIFARE_MAGIC_GDM_READBLOCK
, 0x00, 0xC2, 0x66};
2931 uint8_t gen4GetConf
[8] = {GEN_4GTU_CMD
, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_GETCNF
, 0, 0};
2932 uint8_t superGen1
[9] = {0x0A, 0x00, 0x00, 0xA6, 0xB0, 0x00, 0x10, 0x14, 0x1D};
2933 bool isGen2
= false;
2935 uint8_t *par
= BigBuf_calloc(MAX_PARITY_SIZE
);
2936 uint8_t *buf
= BigBuf_calloc(PM3_CMD_DATA_SIZE
);
2937 uint8_t *uid
= BigBuf_calloc(10);
2938 uint16_t flag
= MAGIC_FLAG_NONE
;
2942 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2944 // Generation 1 test
2945 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
2946 if (ReaderReceive(rec
, 1, recpar
) && (rec
[0] == 0x0A)) {
2948 flag
= MAGIC_FLAG_GEN_1A
;
2949 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
2950 uint16_t tmp
= ReaderReceive(rec
, 1, recpar
);
2951 if ((tmp
&& (rec
[0] != 0x0A)) || (tmp
== 0)) {
2952 flag
= MAGIC_FLAG_GEN_1B
;
2955 // check for GDM config
2956 ReaderTransmit(gen4gdmGetConf
, sizeof(gen4gdmGetConf
), NULL
);
2957 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
2959 // could be ZUID or full USCUID, the magic blocks don't exist on ZUID so
2960 // a failure here indicates a feature limited chip like ZUID
2961 // check for GDM hidden block read
2962 ReaderTransmit(gen4gdmGetMagicBlock
, sizeof(gen4gdmGetMagicBlock
), NULL
);
2963 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
2965 flag
|= MAGIC_FLAG_GDM_WUP_40
;
2967 flag
|= MAGIC_FLAG_GDM_WUP_40_ZUID
;
2974 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
2976 // Check for Magic Gen4 GTU with default password:
2977 // Get config should return 30 or 32 bytes
2978 AddCrc14A(gen4GetConf
, sizeof(gen4GetConf
) - 2);
2979 ReaderTransmit(gen4GetConf
, sizeof(gen4GetConf
), NULL
);
2980 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
2981 if (res
== 32 || res
== 34) {
2982 flag
|= MAGIC_FLAG_GEN_4GTU
;
2989 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, false);
2991 if (cuid
== 0xAA55C396) {
2992 flag
|= MAGIC_FLAG_GEN_UNFUSED
;
2995 ReaderTransmit(rats
, sizeof(rats
), NULL
);
2996 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
2999 if (memcmp(buf
, "\x09\x78\x00\x91\x02\xDA\xBC\x19\x10", 9) == 0) {
3000 // test for some MFC gen2
3002 flag
|= MAGIC_FLAG_GEN_2
;
3003 } else if (memcmp(buf
, "\x0D\x78\x00\x71\x02\x88\x49\xA1\x30\x20\x15\x06\x08\x56\x3D", 15) == 0) {
3004 // test for some MFC 7b gen2
3006 flag
|= MAGIC_FLAG_GEN_2
;
3007 } else if (memcmp(buf
, "\x0A\x78\x00\x81\x02\xDB\xA0\xC1\x19\x40\x2A\xB5", 12) == 0) {
3008 // test for Ultralight magic gen2
3010 flag
|= MAGIC_FLAG_GEN_2
;
3011 } else if (memcmp(buf
, "\x85\x00\x00\xA0\x00\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x41\xDF", 18) == 0) {
3012 // test for Ultralight EV1 magic gen2
3014 flag
|= MAGIC_FLAG_GEN_2
;
3015 } else if (memcmp(buf
, "\x85\x00\x00\xA0\x0A\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x16\xD7", 18) == 0) {
3016 // test for some other Ultralight EV1 magic gen2
3018 flag
|= MAGIC_FLAG_GEN_2
;
3019 } else if (memcmp(buf
, "\x85\x00\x00\xA0\x0A\x00\x0A\xB0\x00\x00\x00\x00\x00\x00\x00\x00\x18\x4D", 18) == 0) {
3020 // test for some other Ultralight magic gen2
3022 flag
|= MAGIC_FLAG_GEN_2
;
3023 } else if (memcmp(buf
, "\x85\x00\x00\xA0\x00\x00\x0A\xA5\x00\x04\x04\x02\x01\x00\x0F\x03\x79\x0C", 18) == 0) {
3024 // test for NTAG213 magic gen2
3026 flag
|= MAGIC_FLAG_GEN_2
;
3029 // test for super card
3030 ReaderTransmit(superGen1
, sizeof(superGen1
), NULL
);
3031 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
3033 uint8_t isGen
= MAGIC_FLAG_SUPER_GEN1
;
3035 // check for super card gen2
3036 // not available after RATS, reset card before executing
3039 iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
3040 ReaderTransmit(rdbl00
, sizeof(rdbl00
), NULL
);
3041 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
3043 isGen
= MAGIC_FLAG_SUPER_GEN2
;
3050 if (is_mfc
== false) {
3054 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
3056 ReaderTransmit(rdblf0
, sizeof(rdblf0
), NULL
);
3057 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
3059 flag
|= MAGIC_FLAG_NTAG21X
;
3064 struct Crypto1State mpcs
= {0, 0};
3065 struct Crypto1State
*pcs
;
3068 // CUID (with default sector 0 B key) test
3069 // regular cards will NAK the WRITEBLOCK(0) command, while DirectWrite will ACK it
3070 // if we do get an ACK, we immediately abort to ensure nothing is ever actually written
3071 // only perform test if we haven't already identified Gen2. No need test if we have a positive identification already
3072 if (isGen2
== false) {
3075 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
3078 uint64_t tmpkey
= bytes_to_num(key
, 6);
3079 if (mifare_classic_authex(pcs
, cuid
, 0, keytype
, tmpkey
, AUTH_FIRST
, NULL
, NULL
) == 0) {
3081 if ((mifare_sendcmd_short(pcs
, 1, ISO14443A_CMD_WRITEBLOCK
, 0, buf
, PM3_CMD_DATA_SIZE
, par
, NULL
) == 1) && (buf
[0] == 0x0A)) {
3082 flag
|= MAGIC_FLAG_GEN_2
;
3083 // turn off immediately to ensure nothing ever accidentally writes to the block
3084 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3087 crypto1_deinit(pcs
);
3091 // magic MFC Gen3 test 1
3094 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
3096 ReaderTransmit(rdbl00
, sizeof(rdbl00
), NULL
);
3097 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
3099 flag
|= MAGIC_FLAG_GEN_3
;
3103 // magic MFC Gen4 GDM magic auth test
3106 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
3108 ReaderTransmit(gen4gdmAuth
, sizeof(gen4gdmAuth
), NULL
);
3109 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
3111 flag
|= MAGIC_FLAG_GDM_AUTH
;
3118 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
3120 if (mifare_classic_authex(pcs
, cuid
, 68, MF_KEY_B
, 0x707B11FC1481, AUTH_FIRST
, NULL
, NULL
) == 0) {
3121 flag
|= MAGIC_FLAG_QL88
;
3123 crypto1_deinit(pcs
);
3128 // GDM alt magic wakeup (20)
3129 ReaderTransmitBitsPar(wupGDM1
, 7, NULL
, NULL
);
3130 if (ReaderReceive(rec
, 1, recpar
) && (rec
[0] == 0x0a)) {
3131 flag
|= MAGIC_FLAG_GDM_WUP_20
;
3134 reply_ng(CMD_HF_MIFARE_CIDENT
, PM3_SUCCESS
, (uint8_t *)&flag
, sizeof(uint16_t));
3140 void MifareHasStaticNonce(void) {
3142 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3145 int retval
= PM3_SUCCESS
;
3147 uint8_t *uid
= BigBuf_malloc(10);
3149 memset(uid
, 0x00, 10);
3151 uint8_t data
[1] = { NONCE_FAIL
};
3152 struct Crypto1State mpcs
= {0, 0};
3153 struct Crypto1State
*pcs
;
3156 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3158 uint8_t counter
= 0;
3159 for (uint8_t i
= 0; i
< 3; i
++) {
3161 if (!iso14443a_select_card(uid
, NULL
, NULL
, true, 0, true)) {
3166 uint8_t rec
[4] = {0x00};
3167 uint8_t recpar
[1] = {0x00};
3168 // Transmit MIFARE_CLASSIC_AUTH 0x60, block 0
3169 int len
= mifare_sendcmd_short(pcs
, false, MIFARE_AUTH_KEYA
, 0, rec
, sizeof(rec
), recpar
, NULL
);
3175 // Save the tag nonce (nt)
3176 if (nt
== bytes_to_num(rec
, 4)) {
3180 nt
= bytes_to_num(rec
, 4);
3182 // some cards with static nonce need to be reset before next query
3183 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3187 memset(rec
, 0x00, sizeof(rec
));
3191 Dbprintf("Static nonce......... " _YELLOW_("%08x"), nt
);
3192 data
[0] = NONCE_STATIC
;
3194 data
[0] = NONCE_NORMAL
;
3198 reply_ng(CMD_HF_MIFARE_STATIC_NONCE
, retval
, data
, sizeof(data
));
3202 crypto1_deinit(pcs
);
3205 // FUDAN card w static encrypted nonces
3206 // 2B F9 1C 1B D5 08 48 48 03 A4 B1 B1 75 FF 2D 90
3209 void MifareHasStaticEncryptedNonce(uint8_t block_no
, uint8_t key_type
, uint8_t *key
, uint8_t block_no_nested
, uint8_t key_type_nested
, uint8_t *key_nested
, uint8_t nr_nested
, bool reset
, bool hardreset
, bool addread
, bool addauth
, bool incblk2
, bool corruptnrar
, bool corruptnrarparity
) {
3210 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3216 int retval
= PM3_SUCCESS
;
3218 uint8_t data
[14] = { NONCE_FAIL
};
3220 struct Crypto1State mpcs
= {0, 0};
3221 struct Crypto1State
*pcs
;
3224 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3226 uint8_t first_nt_counter
= 0;
3227 uint8_t first_nt_repetition_counter
= 0;
3228 uint8_t nested_nt_session_counter
= 0;
3229 uint8_t nested_nt_repetition_counter
= 0;
3230 uint8_t first_and_nested_nt_repetition_counter
= 0;
3231 uint8_t key_auth_cmd
= MIFARE_AUTH_KEYA
+ key_type
;
3232 uint8_t key_auth_cmd_nested
= MIFARE_AUTH_KEYA
+ key_type_nested
;
3233 uint64_t ui64key
= bytes_to_num(key
, 6);
3234 uint64_t ui64key_nested
= bytes_to_num(key_nested
, 6);
3235 uint32_t oldntenc
= 0;
3236 bool need_first_auth
= true;
3239 uint32_t old_nt
= 0;
3240 uint32_t nt_first
= 0;
3241 uint32_t old_nt_first
= 0;
3243 uint8_t ntencpar
= 0;
3244 bool is_last_auth_first_auth
= true;
3245 if (nr_nested
== 0) {
3247 if (iso14443a_select_card(NULL
, NULL
, &cuid
, true, 0, true) == false) {
3248 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Select error");
3252 if (mifare_classic_authex_cmd(pcs
, cuid
, block_no
, key_auth_cmd
, ui64key
, AUTH_FIRST
, &nt
, NULL
, NULL
, NULL
, corruptnrar
, corruptnrarparity
)) {
3253 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Auth error");
3259 for (uint8_t i
= 0; i
< nr_nested
; i
++) {
3260 if (need_first_auth
) {
3264 if (g_dbglevel
>= DBG_EXTENDED
) {
3265 Dbprintf("RF reset");
3267 // some cards need longer than mf_reset_card() to see effect on nT
3268 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3270 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3272 if (g_dbglevel
>= DBG_EXTENDED
) {
3275 if (iso14443a_select_card(NULL
, NULL
, &cuid
, true, 0, true) == false) {
3279 if (mifare_classic_authex_cmd(pcs
, cuid
, block_no
, key_auth_cmd
, ui64key
, AUTH_FIRST
, &nt_first
, NULL
, NULL
, NULL
, corruptnrar
, corruptnrarparity
)) {
3280 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Auth error");
3284 is_last_auth_first_auth
= true;
3286 if ((first_nt_counter
> 1) && (old_nt_first
== nt_first
)) {
3287 first_nt_repetition_counter
++;
3289 old_nt_first
= nt_first
;
3290 if (!reset
&& !hardreset
) {
3291 need_first_auth
= false;
3294 uint8_t dataread
[16] = {0x00};
3295 mifare_classic_readblock(pcs
, block_no
, dataread
);
3298 if (mifare_classic_authex_cmd(pcs
, cuid
, block_no
, key_auth_cmd
, ui64key
, AUTH_NESTED
, &nt
, NULL
, NULL
, NULL
, false, false)) {
3299 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Auth error");
3302 } else if (g_dbglevel
>= DBG_EXTENDED
) {
3303 Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first
, nt
));
3305 is_last_auth_first_auth
= false;
3306 if (nt
== nt_first
) {
3307 first_and_nested_nt_repetition_counter
++;
3315 if (mifare_classic_authex_cmd(pcs
, cuid
, incblk2
? block_no_nested
+ (i
* 4) : block_no_nested
, key_auth_cmd_nested
, ui64key_nested
, AUTH_NESTED
, &nt
, &ntenc
, &ntencpar
, NULL
, false, false)) {
3316 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Nested auth error");
3317 need_first_auth
= true;
3318 } else if (g_dbglevel
>= DBG_EXTENDED
) {
3319 if (is_last_auth_first_auth
) {
3320 Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first
, nt
));
3322 Dbprintf("Nonce distance: %5i", nonce_distance(old_nt
, nt
));
3325 nested_nt_session_counter
++;
3326 is_last_auth_first_auth
= false;
3328 if (nt
== nt_first
) {
3329 first_and_nested_nt_repetition_counter
++;
3331 if ((nested_nt_session_counter
> 1) && (oldntenc
== ntenc
)) {
3332 nested_nt_repetition_counter
++;
3338 data
[1] = (cuid
>> 24) & 0xFF;
3339 data
[2] = (cuid
>> 16) & 0xFF;
3340 data
[3] = (cuid
>> 8) & 0xFF;
3341 data
[4] = (cuid
>> 0) & 0xFF;
3342 if (first_and_nested_nt_repetition_counter
) {
3343 data
[0] = NONCE_SUPERSTATIC
;
3344 data
[5] = (nt
>> 24) & 0xFF;
3345 data
[6] = (nt
>> 16) & 0xFF;
3346 data
[7] = (nt
>> 8) & 0xFF;
3347 data
[8] = (nt
>> 0) & 0xFF;
3348 } else if (first_nt_repetition_counter
) {
3349 data
[0] = NONCE_STATIC
;
3350 data
[5] = (nt_first
>> 24) & 0xFF;
3351 data
[6] = (nt_first
>> 16) & 0xFF;
3352 data
[7] = (nt_first
>> 8) & 0xFF;
3353 data
[8] = (nt_first
>> 0) & 0xFF;
3354 } else if (nested_nt_repetition_counter
) {
3355 data
[0] = NONCE_STATIC_ENC
;
3356 data
[5] = (nt
>> 24) & 0xFF;
3357 data
[6] = (nt
>> 16) & 0xFF;
3358 data
[7] = (nt
>> 8) & 0xFF;
3359 data
[8] = (nt
>> 0) & 0xFF;
3360 data
[9] = (ntenc
>> 24) & 0xFF;
3361 data
[10] = (ntenc
>> 16) & 0xFF;
3362 data
[11] = (ntenc
>> 8) & 0xFF;
3363 data
[12] = (ntenc
>> 0) & 0xFF;
3364 data
[13] = ntencpar
;
3366 data
[0] = NONCE_NORMAL
;
3367 data
[5] = (nt
>> 24) & 0xFF;
3368 data
[6] = (nt
>> 16) & 0xFF;
3369 data
[7] = (nt
>> 8) & 0xFF;
3370 data
[8] = (nt
>> 0) & 0xFF;
3371 data
[9] = (ntenc
>> 24) & 0xFF;
3372 data
[10] = (ntenc
>> 16) & 0xFF;
3373 data
[11] = (ntenc
>> 8) & 0xFF;
3374 data
[12] = (ntenc
>> 0) & 0xFF;
3375 data
[13] = ntencpar
;
3379 crypto1_deinit(pcs
);
3381 reply_ng(CMD_HF_MIFARE_STATIC_ENCRYPTED_NONCE
, retval
, data
, sizeof(data
));
3387 void OnSuccessMagic(void) {
3388 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3393 void OnErrorMagic(uint8_t reason
) {
3394 // ACK, ISOK, reason,0,0,0
3395 reply_mix(CMD_ACK
, 0, reason
, 0, 0, 0);
3399 int DoGen3Cmd(uint8_t *cmd
, uint8_t cmd_len
) {
3400 int retval
= PM3_SUCCESS
;
3401 uint8_t *par
= BigBuf_calloc(MAX_PARITY_SIZE
);
3402 uint8_t *buf
= BigBuf_calloc(PM3_CMD_DATA_SIZE
);
3405 uint32_t save_iso14a_timeout
= iso14a_get_timeout();
3406 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 2000); // 2 seconds timeout
3408 ReaderTransmit(cmd
, cmd_len
, NULL
);
3409 int res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
3410 if (res
== 4 && memcmp(buf
, "\x90\x00\xfd\x07", 4) == 0) {
3411 // timeout for card memory reset
3414 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Card operation not completed");
3417 iso14a_set_timeout(save_iso14a_timeout
);
3422 void MifareGen3UID(uint8_t uidlen
, uint8_t *uid
) {
3423 int retval
= PM3_SUCCESS
;
3424 uint8_t uid_cmd
[5] = { 0x90, 0xfb, 0xcc, 0xcc, 0x07 };
3425 uint8_t *old_uid
= BigBuf_calloc(10);
3426 uint8_t *cmd
= BigBuf_calloc(sizeof(uid_cmd
) + uidlen
+ 2);
3427 iso14a_card_select_t
*card_info
= (iso14a_card_select_t
*) BigBuf_calloc(sizeof(iso14a_card_select_t
));
3430 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3434 if (iso14443a_select_card(old_uid
, card_info
, NULL
, true, 0, true) == false) {
3438 if (card_info
->uidlen
!= uidlen
) {
3439 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Wrong UID length");
3444 memcpy(cmd
, uid_cmd
, sizeof(uid_cmd
));
3445 memcpy(&cmd
[sizeof(uid_cmd
)], uid
, uidlen
);
3446 AddCrc14A(cmd
, sizeof(uid_cmd
) + uidlen
);
3448 retval
= DoGen3Cmd(cmd
, sizeof(uid_cmd
) + uidlen
+ 2);
3451 reply_ng(CMD_HF_MIFARE_GEN3UID
, retval
, old_uid
, uidlen
);
3457 void MifareGen3Blk(uint8_t block_len
, uint8_t *block
) {
3459 int retval
= PM3_SUCCESS
;
3460 uint8_t block_cmd
[5] = { 0x90, 0xf0, 0xcc, 0xcc, 0x10 };
3461 uint8_t cmdlen
= sizeof(block_cmd
) + MAX_MIFARE_FRAME_SIZE
;
3462 uint8_t *cmd
= BigBuf_calloc(cmdlen
);
3464 iso14a_card_select_t
*card_info
= (iso14a_card_select_t
*) BigBuf_calloc(sizeof(iso14a_card_select_t
));
3467 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3471 if (iso14443a_select_card(NULL
, card_info
, NULL
, true, 0, true) == false) {
3476 bool doReselect
= false;
3477 if (block_len
< MIFARE_BLOCK_SIZE
) {
3478 if ((mifare_sendcmd_short(NULL
, CRYPT_NONE
, ISO14443A_CMD_READBLOCK
, 0, &cmd
[sizeof(block_cmd
)], MAX_MIFARE_FRAME_SIZE
, NULL
, NULL
) != MAX_MIFARE_FRAME_SIZE
)) {
3479 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Read manufacturer block failed");
3486 if (block_len
> 0) {
3487 memcpy(cmd
, block_cmd
, sizeof(block_cmd
));
3488 memcpy(&cmd
[sizeof(block_cmd
)], block
, block_len
);
3489 int ofs
= sizeof(block_cmd
);
3490 if (card_info
->uidlen
== 4) {
3491 cmd
[ofs
+ 4] = cmd
[ofs
+ 0] ^ cmd
[ofs
+ 1] ^ cmd
[ofs
+ 2] ^ cmd
[ofs
+ 3];
3493 } else if (card_info
->uidlen
== 7) {
3496 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Wrong Card UID length");
3500 cmd
[ofs
] = block_len
<= card_info
->uidlen
? card_info
->sak
: cmd
[ofs
];
3502 cmd
[ofs
++] = card_info
->atqa
[0];
3503 cmd
[ofs
++] = card_info
->atqa
[1];
3504 AddCrc14A(cmd
, sizeof(block_cmd
) + MIFARE_BLOCK_SIZE
);
3507 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
3513 retval
= DoGen3Cmd(cmd
, sizeof(block_cmd
) + MAX_MIFARE_FRAME_SIZE
);
3517 reply_ng(CMD_HF_MIFARE_GEN3BLK
, retval
, &cmd
[sizeof(block_cmd
)], MIFARE_BLOCK_SIZE
);
3523 void MifareGen3Freez(void) {
3526 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3530 int retval
= PM3_SUCCESS
;
3531 uint8_t freeze_cmd
[7] = { 0x90, 0xfd, 0x11, 0x11, 0x00, 0xe7, 0x91 };
3533 if (iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true) == false) {
3538 retval
= DoGen3Cmd(freeze_cmd
, sizeof(freeze_cmd
));
3541 reply_ng(CMD_HF_MIFARE_GEN3FREEZ
, retval
, NULL
, 0);
3547 void MifareG4ReadBlk(uint8_t blockno
, uint8_t *pwd
, uint8_t workFlags
) {
3548 bool setup
= ((workFlags
& MAGIC_INIT
) == MAGIC_INIT
) ;
3549 bool done
= ((workFlags
& MAGIC_OFF
) == MAGIC_OFF
) ;
3552 int retval
= PM3_SUCCESS
;
3554 uint8_t *buf
= BigBuf_malloc(PM3_CMD_DATA_SIZE
);
3556 retval
= PM3_EMALLOC
;
3560 uint8_t *par
= BigBuf_malloc(MAX_PARITY_SIZE
);
3562 retval
= PM3_EMALLOC
;
3568 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3572 if (iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true) == false) {
3580 static uint32_t save_iso14a_timeout
;
3582 save_iso14a_timeout
= iso14a_get_timeout();
3583 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 1000); // 2 seconds timeout
3586 uint8_t cmd
[] = { GEN_4GTU_CMD
, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_READ
, blockno
,
3590 memcpy(cmd
+ 1, pwd
, 4);
3592 AddCrc14A(cmd
, sizeof(cmd
) - 2);
3594 ReaderTransmit(cmd
, sizeof(cmd
), NULL
);
3595 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
3601 if (done
|| retval
!= 0) {
3602 iso14a_set_timeout(save_iso14a_timeout
);
3608 reply_ng(CMD_HF_MIFARE_G4_RDBL
, retval
, buf
, res
);
3611 if (done
|| retval
!= 0) {
3612 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3616 if (done
|| retval
!= 0) {
3623 void MifareG4WriteBlk(uint8_t blockno
, uint8_t *pwd
, uint8_t *data
, uint8_t workFlags
) {
3624 bool setup
= ((workFlags
& MAGIC_INIT
) == MAGIC_INIT
) ;
3625 bool done
= ((workFlags
& MAGIC_OFF
) == MAGIC_OFF
) ;
3628 int retval
= PM3_SUCCESS
;
3630 uint8_t *buf
= BigBuf_malloc(PM3_CMD_DATA_SIZE
);
3632 retval
= PM3_EMALLOC
;
3638 retval
= PM3_EINVARG
;
3642 uint8_t *par
= BigBuf_malloc(MAX_PARITY_SIZE
);
3644 retval
= PM3_EMALLOC
;
3650 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3654 if (iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true) == false) {
3662 static uint32_t save_iso14a_timeout
;
3664 save_iso14a_timeout
= iso14a_get_timeout();
3665 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 1000); // 2 seconds timeout
3668 uint8_t cmd
[] = { GEN_4GTU_CMD
, 0x00, 0x00, 0x00, 0x00, GEN_4GTU_WRITE
, blockno
,
3669 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3670 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3674 memcpy(cmd
+ 1, pwd
, 4);
3675 memcpy(cmd
+ 7, data
, 16);
3677 AddCrc14A(cmd
, sizeof(cmd
) - 2);
3679 ReaderTransmit(cmd
, sizeof(cmd
), NULL
);
3680 res
= ReaderReceive(buf
, PM3_CMD_DATA_SIZE
, par
);
3682 if ((res
!= 4) || (memcmp(buf
, "\x90\x00\xfd\x07", 4) != 0)) {
3686 if (done
|| retval
!= 0) {
3687 iso14a_set_timeout(save_iso14a_timeout
);
3692 reply_ng(CMD_HF_MIFARE_G4_WRBL
, retval
, buf
, res
);
3694 if (done
|| retval
!= 0) {
3695 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3699 if (done
|| retval
!= 0) {
3706 void MifareSetMod(uint8_t *datain
) {
3708 uint8_t mod
= datain
[0];
3709 uint64_t ui64Key
= bytes_to_num(datain
+ 1, 6);
3712 uint16_t isOK
= PM3_EUNDEF
;
3713 uint8_t *uid
= BigBuf_calloc(10);
3716 struct Crypto1State mpcs
= {0, 0};
3717 struct Crypto1State
*pcs
= &mpcs
;
3719 uint8_t *buf
= BigBuf_calloc(MAX_MIFARE_FRAME_SIZE
);
3720 uint8_t *par
= BigBuf_calloc(MAX_MIFARE_PARITY_SIZE
);
3723 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3731 if (iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true) == false) {
3732 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
3736 if (mifare_classic_auth(pcs
, cuid
, 0, 0, ui64Key
, AUTH_FIRST
)) {
3737 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Auth error");
3742 if (((respLen
= mifare_sendcmd_short(pcs
, CRYPT_ALL
, MIFARE_EV1_SETMOD
, mod
, buf
, MAX_MIFARE_FRAME_SIZE
, par
, NULL
)) != 1) || (buf
[0] != 0x0a)) {
3743 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("SetMod error; response[0]: %hhX, len: %d", buf
[0], respLen
);
3747 if (mifare_classic_halt(pcs
)) {
3748 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Halt error");
3756 crypto1_deinit(pcs
);
3759 reply_ng(CMD_HF_MIFARE_SETMOD
, isOK
, NULL
, 0);
3762 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3770 void Mifare_DES_Auth1(uint8_t arg0
, uint8_t *datain
) {
3771 uint8_t dataout
[12] = {0x00};
3774 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3778 int len
= iso14443a_select_card(NULL
, NULL
, &cuid
, true, 0, false);
3780 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
3785 if (mifare_desfire_des_auth1(cuid
, dataout
) != PM3_SUCCESS
) {
3786 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Authentication part1: Fail.");
3791 if (g_dbglevel
>= DBG_EXTENDED
) DbpString("AUTH 1 FINISHED");
3792 reply_mix(CMD_ACK
, 1, cuid
, 0, dataout
, sizeof(dataout
));
3795 void Mifare_DES_Auth2(uint32_t arg0
, uint8_t *datain
) {
3796 uint32_t cuid
= arg0
;
3797 uint8_t key
[16] = {0x00};
3798 uint8_t dataout
[12] = {0x00};
3801 memcpy(key
, datain
, 16);
3803 isOK
= mifare_desfire_des_auth2(cuid
, key
, dataout
);
3805 if (isOK
!= PM3_SUCCESS
) {
3806 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("Authentication part2: Failed");
3811 if (g_dbglevel
>= DBG_EXTENDED
) DbpString("AUTH 2 FINISHED");
3813 reply_old(CMD_ACK
, isOK
, 0, 0, dataout
, sizeof(dataout
));
3814 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
3820 // Tear-off attack against MFU.
3822 void MifareU_Otp_Tearoff(uint8_t blno
, uint32_t tearoff_time
, uint8_t *data_testwrite
) {
3823 uint8_t blockNo
= blno
;
3825 if (g_dbglevel
>= DBG_DEBUG
) DbpString("Preparing OTP tear-off");
3827 if (tearoff_time
> 43000) {
3828 tearoff_time
= 43000;
3831 g_tearoff_delay_us
= tearoff_time
;
3832 g_tearoff_enabled
= true;
3835 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3839 // write cmd to send, include CRC
3840 // 1b write, 1b block, 4b data, 2 crc
3842 MIFARE_ULC_WRITE
, blockNo
,
3843 data_testwrite
[0], data_testwrite
[1], data_testwrite
[2], data_testwrite
[3],
3846 AddCrc14A(cmd
, sizeof(cmd
) - 2);
3848 // anticollision / select card
3849 if (iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true) == false) {
3850 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
3852 reply_ng(CMD_HF_MFU_OTP_TEAROFF
, PM3_EFAILED
, NULL
, 0);
3857 ReaderTransmit(cmd
, sizeof(cmd
), NULL
);
3859 reply_ng(CMD_HF_MFU_OTP_TEAROFF
, PM3_SUCCESS
, NULL
, 0);
3863 // Tear-off attack against MFU counter
3864 void MifareU_Counter_Tearoff(uint8_t counter
, uint32_t tearoff_time
, uint8_t *datain
) {
3866 if (tearoff_time
> 43000) {
3867 tearoff_time
= 43000;
3871 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3875 // Send MFU counter increase cmd
3877 MIFARE_ULEV1_INCR_CNT
,
3886 AddCrc14A(cmd
, sizeof(cmd
) - 2);
3888 // anticollision / select card
3889 if (iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true) == false) {
3890 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Can't select card");
3898 ReaderTransmit(cmd
, sizeof(cmd
), NULL
);
3900 SpinDelayUsPrecision(tearoff_time
);
3903 reply_ng(CMD_HF_MFU_COUNTER_TEAROFF
, PM3_SUCCESS
, NULL
, 0);