1 //-----------------------------------------------------------------------------
2 // Merlok - June 2011, 2012
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
5 // Midnitesnake - Dec 2013
6 // Andy Davies - Apr 2014
7 // Iceman - May 2014,2015,2016
9 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
10 // at your option, any later version. See the LICENSE.txt file for the text of
12 //-----------------------------------------------------------------------------
13 // Routines to support ISO 14443 type A.
14 //-----------------------------------------------------------------------------
16 #include "mifarecmd.h"
19 #include "proxmark3_arm.h"
21 #include "mifareutil.h"
22 #include "protocols.h"
27 #include "fpgaloader.h"
28 #include "iso14443a.h"
29 #include "mifaredesfire.h"
31 #include "commonutil.h"
35 #include "usb_cdc.h" // usb_poll_validate_length
36 #include "spiffs.h" // spiffs
37 #include "appmain.h" // print_stack_usage
39 #ifndef HARDNESTED_AUTHENTICATION_TIMEOUT
40 # define HARDNESTED_AUTHENTICATION_TIMEOUT 848 // card times out 1ms after wrong authentication (according to NXP documentation)
42 #ifndef HARDNESTED_PRE_AUTHENTICATION_LEADTIME
43 # define HARDNESTED_PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication
46 // send an incomplete dummy response in order to trigger the card's authentication failure timeout
48 # define CHK_TIMEOUT(void) { \
49 ReaderTransmit(&dummy_answer, 1, NULL); \
50 uint32_t timeout = GetCountSspClk() + HARDNESTED_AUTHENTICATION_TIMEOUT; \
51 while (GetCountSspClk() < timeout) {}; \
55 static uint8_t dummy_answer
= 0;
57 //-----------------------------------------------------------------------------
58 // Select, Authenticate, Read a MIFARE tag.
60 //-----------------------------------------------------------------------------
61 void MifareReadBlock(uint8_t blockNo
, uint8_t keyType
, uint8_t *datain
) {
64 ui64Key
= bytes_to_num(datain
, 6);
67 uint8_t dataoutbuf
[16] = {0x00};
68 uint8_t uid
[10] = {0x00};
69 uint32_t cuid
= 0, status
= PM3_EOPABORTED
;
71 struct Crypto1State mpcs
= {0, 0};
72 struct Crypto1State
*pcs
;
75 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
85 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
86 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
90 if (mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
91 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Auth error");
95 if (mifare_classic_readblock(pcs
, cuid
, blockNo
, dataoutbuf
)) {
96 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Read block error");
100 if (mifare_classic_halt(pcs
, cuid
)) {
101 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
105 status
= PM3_SUCCESS
;
111 if (DBGLEVEL
>= 2) DbpString("READ BLOCK FINISHED");
114 reply_ng(CMD_HF_MIFARE_READBL
, status
, dataoutbuf
, 16);
117 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
121 void MifareUC_Auth(uint8_t arg0
, uint8_t *keybytes
) {
123 bool turnOffField
= (arg0
== 1);
129 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
134 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
135 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
140 if (!mifare_ultra_auth(keybytes
)) {
141 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Authentication failed");
147 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
150 reply_mix(CMD_ACK
, 1, 0, 0, 0, 0);
154 // Arg1 = UsePwd bool
155 // datain = PWD bytes,
156 void MifareUReadBlock(uint8_t arg0
, uint8_t arg1
, uint8_t *datain
) {
157 uint8_t blockNo
= arg0
;
158 uint8_t dataout
[16] = {0x00};
159 bool useKey
= (arg1
== 1); //UL_C
160 bool usePwd
= (arg1
== 2); //UL_EV1/NTAG
164 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
169 int len
= iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true);
171 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card (RC:%02X)", len
);
176 // UL-C authentication
178 uint8_t key
[16] = {0x00};
179 memcpy(key
, datain
, sizeof(key
));
181 if (!mifare_ultra_auth(key
)) {
187 // UL-EV1 / NTAG authentication
189 uint8_t pwd
[4] = {0x00};
190 memcpy(pwd
, datain
, 4);
191 uint8_t pack
[4] = {0, 0, 0, 0};
192 if (!mifare_ul_ev1_auth(pwd
, pack
)) {
198 if (mifare_ultra_readblock(blockNo
, dataout
)) {
199 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Read block error");
204 if (mifare_ultra_halt()) {
205 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
210 reply_mix(CMD_ACK
, 1, 0, 0, dataout
, 16);
211 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
215 //-----------------------------------------------------------------------------
216 // Select, Authenticate, Read a MIFARE tag.
217 // read sector (data = 4 x 16 bytes = 64 bytes, or 16 x 16 bytes = 256 bytes)
218 //-----------------------------------------------------------------------------
219 void MifareReadSector(uint8_t arg0
, uint8_t arg1
, uint8_t *datain
) {
221 uint8_t sectorNo
= arg0
;
222 uint8_t keyType
= arg1
;
223 uint64_t ui64Key
= 0;
224 ui64Key
= bytes_to_num(datain
, 6);
228 uint8_t dataoutbuf
[16 * 16];
229 uint8_t uid
[10] = {0x00};
231 struct Crypto1State mpcs
= {0, 0};
232 struct Crypto1State
*pcs
;
235 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
245 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
247 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
251 if (isOK
&& mifare_classic_auth(pcs
, cuid
, FirstBlockOfSector(sectorNo
), keyType
, ui64Key
, AUTH_FIRST
)) {
253 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Auth error");
256 for (uint8_t blockNo
= 0; isOK
&& blockNo
< NumBlocksPerSector(sectorNo
); blockNo
++) {
257 if (mifare_classic_readblock(pcs
, cuid
, FirstBlockOfSector(sectorNo
) + blockNo
, dataoutbuf
+ 16 * blockNo
)) {
259 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Read sector %2d block %2d error", sectorNo
, blockNo
);
264 if (mifare_classic_halt(pcs
, cuid
)) {
265 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
268 if (DBGLEVEL
>= 2) DbpString("READ SECTOR FINISHED");
273 reply_old(CMD_ACK
, isOK
, 0, 0, dataoutbuf
, 16 * NumBlocksPerSector(sectorNo
));
276 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
281 // arg0 = blockNo (start)
282 // arg1 = Pages (number of blocks)
284 // datain = KEY bytes
285 void MifareUReadCard(uint8_t arg0
, uint16_t arg1
, uint8_t arg2
, uint8_t *datain
) {
288 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
290 // free eventually allocated BigBuf memory
292 BigBuf_Clear_ext(false);
297 uint8_t blockNo
= arg0
;
298 uint16_t blocks
= arg1
;
299 bool useKey
= (arg2
== 1); //UL_C
300 bool usePwd
= (arg2
== 2); //UL_EV1/NTAG
301 uint32_t countblocks
= 0;
302 uint8_t *dataout
= BigBuf_malloc(CARD_MEMORY_SIZE
);
303 if (dataout
== NULL
) {
304 Dbprintf("out of memory");
309 int len
= iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true);
311 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card (RC:%d)", len
);
316 // UL-C authentication
318 uint8_t key
[16] = {0x00};
319 memcpy(key
, datain
, sizeof(key
));
321 if (!mifare_ultra_auth(key
)) {
327 // UL-EV1 / NTAG authentication
329 uint8_t pwd
[4] = {0x00};
330 memcpy(pwd
, datain
, sizeof(pwd
));
331 uint8_t pack
[4] = {0, 0, 0, 0};
333 if (!mifare_ul_ev1_auth(pwd
, pack
)) {
339 for (int i
= 0; i
< blocks
; i
++) {
340 if ((i
* 4) + 4 >= CARD_MEMORY_SIZE
) {
341 Dbprintf("Data exceeds buffer!!");
345 len
= mifare_ultra_readblock(blockNo
+ i
, dataout
+ 4 * i
);
348 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Read block %d error", i
);
349 // if no blocks read - error out
354 //stop at last successful read block and return what we got
362 len
= mifare_ultra_halt();
364 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
369 if (DBGLEVEL
>= DBG_EXTENDED
) Dbprintf("Blocks read %d", countblocks
);
373 reply_mix(CMD_ACK
, 1, countblocks
, dataout
- BigBuf_get_addr(), 0, 0);
374 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
380 //-----------------------------------------------------------------------------
381 // Select, Authenticate, Write a MIFARE tag.
383 //-----------------------------------------------------------------------------
384 void MifareWriteBlock(uint8_t arg0
, uint8_t arg1
, uint8_t *datain
) {
386 uint8_t blockNo
= arg0
;
387 uint8_t keyType
= arg1
;
388 uint64_t ui64Key
= 0;
389 uint8_t blockdata
[16] = {0x00};
391 ui64Key
= bytes_to_num(datain
, 6);
392 memcpy(blockdata
, datain
+ 10, 16);
396 uint8_t uid
[10] = {0x00};
398 struct Crypto1State mpcs
= {0, 0};
399 struct Crypto1State
*pcs
;
402 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
412 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
413 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
417 if (mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
418 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Auth error");
422 if (mifare_classic_writeblock(pcs
, cuid
, blockNo
, blockdata
)) {
423 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Write block error");
427 if (mifare_classic_halt(pcs
, cuid
)) {
428 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
438 if (DBGLEVEL
>= 2) DbpString("WRITE BLOCK FINISHED");
440 reply_mix(CMD_ACK
, isOK
, 0, 0, 0, 0);
442 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
447 // Arg0 : Block to write to.
448 // Arg1 : 0 = use no authentication.
449 // 1 = use 0x1A authentication.
450 // 2 = use 0x1B authentication.
451 // datain : 4 first bytes is data to be written.
452 // : 4/16 next bytes is authentication key.
453 static void MifareUWriteBlockEx(uint8_t arg0
, uint8_t arg1
, uint8_t *datain
, bool reply
) {
454 uint8_t blockNo
= arg0
;
455 bool useKey
= (arg1
== 1); //UL_C
456 bool usePwd
= (arg1
== 2); //UL_EV1/NTAG
457 uint8_t blockdata
[4] = {0x00};
459 memcpy(blockdata
, datain
, 4);
463 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
468 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
469 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
474 // UL-C authentication
476 uint8_t key
[16] = {0x00};
477 memcpy(key
, datain
+ 4, sizeof(key
));
479 if (!mifare_ultra_auth(key
)) {
485 // UL-EV1 / NTAG authentication
487 uint8_t pwd
[4] = {0x00};
488 memcpy(pwd
, datain
+ 4, 4);
489 uint8_t pack
[4] = {0, 0, 0, 0};
490 if (!mifare_ul_ev1_auth(pwd
, pack
)) {
496 if (mifare_ultra_writeblock(blockNo
, blockdata
)) {
497 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Write block error");
502 if (mifare_ultra_halt()) {
503 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
508 if (DBGLEVEL
>= 2) DbpString("WRITE BLOCK FINISHED");
511 reply_mix(CMD_ACK
, 1, 0, 0, 0, 0);
512 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
517 void MifareUWriteBlock(uint8_t arg0
, uint8_t arg1
, uint8_t *datain
) {
518 MifareUWriteBlockEx(arg0
, arg1
, datain
, true);
521 // Arg0 : Block to write to.
522 // Arg1 : 0 = use no authentication.
523 // 1 = use 0x1A authentication.
524 // 2 = use 0x1B authentication.
525 // datain : 16 first bytes is data to be written.
526 // : 4/16 next bytes is authentication key.
527 void MifareUWriteBlockCompat(uint8_t arg0
, uint8_t arg1
, uint8_t *datain
) {
528 uint8_t blockNo
= arg0
;
529 bool useKey
= (arg1
== 1); //UL_C
530 bool usePwd
= (arg1
== 2); //UL_EV1/NTAG
531 uint8_t blockdata
[16] = {0x00};
533 memcpy(blockdata
, datain
, 16);
537 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
542 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
543 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
548 // UL-C authentication
550 uint8_t key
[16] = {0x00};
551 memcpy(key
, datain
+ 16, sizeof(key
));
553 if (!mifare_ultra_auth(key
)) {
559 // UL-EV1 / NTAG authentication
561 uint8_t pwd
[4] = {0x00};
562 memcpy(pwd
, datain
+ 16, 4);
563 uint8_t pack
[4] = {0, 0, 0, 0};
564 if (!mifare_ul_ev1_auth(pwd
, pack
)) {
570 if (mifare_ultra_writeblock_compat(blockNo
, blockdata
)) {
571 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Write block error");
576 if (mifare_ultra_halt()) {
577 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
582 if (DBGLEVEL
>= 2) DbpString("WRITE BLOCK FINISHED");
584 reply_mix(CMD_ACK
, 1, 0, 0, 0, 0);
585 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
590 void MifareUSetPwd(uint8_t arg0
, uint8_t *datain
) {
592 uint8_t pwd
[16] = {0x00};
593 uint8_t blockdata
[4] = {0x00};
595 memcpy(pwd
, datain
, 16);
600 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
605 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
606 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
611 blockdata
[0] = pwd
[7];
612 blockdata
[1] = pwd
[6];
613 blockdata
[2] = pwd
[5];
614 blockdata
[3] = pwd
[4];
615 if (mifare_ultra_writeblock(44, blockdata
)) {
616 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Write block error");
621 blockdata
[0] = pwd
[3];
622 blockdata
[1] = pwd
[2];
623 blockdata
[2] = pwd
[1];
624 blockdata
[3] = pwd
[0];
625 if (mifare_ultra_writeblock(45, blockdata
)) {
626 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Write block error");
631 blockdata
[0] = pwd
[15];
632 blockdata
[1] = pwd
[14];
633 blockdata
[2] = pwd
[13];
634 blockdata
[3] = pwd
[12];
635 if (mifare_ultra_writeblock(46, blockdata
)) {
636 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Write block error");
641 blockdata
[0] = pwd
[11];
642 blockdata
[1] = pwd
[10];
643 blockdata
[2] = pwd
[9];
644 blockdata
[3] = pwd
[8];
645 if (mifare_ultra_writeblock(47, blockdata
)) {
646 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Write block error");
651 if (mifare_ultra_halt()) {
652 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
657 reply_mix(CMD_ACK
, 1, 0, 0, 0, 0);
658 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
663 // Return 1 if the nonce is invalid else return 0
664 static int valid_nonce(uint32_t Nt
, uint32_t NtEnc
, uint32_t Ks1
, uint8_t *parity
) {
666 (oddparity8((Nt
>> 24) & 0xFF) == ((parity
[0]) ^ oddparity8((NtEnc
>> 24) & 0xFF) ^ BIT(Ks1
, 16))) && \
667 (oddparity8((Nt
>> 16) & 0xFF) == ((parity
[1]) ^ oddparity8((NtEnc
>> 16) & 0xFF) ^ BIT(Ks1
, 8))) && \
668 (oddparity8((Nt
>> 8) & 0xFF) == ((parity
[2]) ^ oddparity8((NtEnc
>> 8) & 0xFF) ^ BIT(Ks1
, 0)))
672 void MifareAcquireNonces(uint32_t arg0
, uint32_t flags
) {
674 uint8_t uid
[10] = {0x00};
675 uint8_t answer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
676 uint8_t par
[1] = {0x00};
677 uint8_t buf
[PM3_CMD_DATA_SIZE
] = {0x00};
680 uint16_t num_nonces
= 0;
681 uint8_t cascade_levels
= 0;
682 uint8_t blockNo
= arg0
& 0xff;
683 uint8_t keyType
= (arg0
>> 8) & 0xff;
684 bool initialize
= flags
& 0x0001;
685 bool field_off
= flags
& 0x0004;
686 bool have_uid
= false;
692 BigBuf_Clear_ext(false);
697 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
701 while (num_nonces
< PM3_CMD_DATA_SIZE
/ 4) {
703 // Test if the action was cancelled
704 if (BUTTON_PRESS()) {
710 if (!have_uid
) { // need a full select cycle to get the uid first
711 iso14a_card_select_t card_info
;
712 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
713 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("AcquireNonces: Can't select card (ALL)");
716 switch (card_info
.uidlen
) {
730 } else { // no need for anticollision. We can directly select the card
731 if (!iso14443a_fast_select_card(uid
, cascade_levels
)) {
732 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("AcquireNonces: Can't select card (UID)");
737 // Transmit MIFARE_CLASSIC_AUTH
738 uint8_t dcmd
[4] = {0x60 + (keyType
& 0x01), blockNo
, 0x00, 0x00};
740 ReaderTransmit(dcmd
, sizeof(dcmd
), NULL
);
741 int len
= ReaderReceive(answer
, par
);
743 // wait for the card to become ready again
747 if (DBGLEVEL
>= 2) Dbprintf("AcquireNonces: Auth1 error");
751 // Save the tag nonce (nt)
752 memcpy(buf
+ num_nonces
* 4, answer
, 4);
758 reply_old(CMD_ACK
, isOK
, cuid
, num_nonces
, buf
, sizeof(buf
));
761 if (DBGLEVEL
>= 3) DbpString("AcquireNonces finished");
764 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
770 //-----------------------------------------------------------------------------
771 // acquire encrypted nonces in order to perform the attack described in
772 // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened
773 // Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on
774 // Computer and Communications Security, 2015
775 //-----------------------------------------------------------------------------
776 void MifareAcquireEncryptedNonces(uint32_t arg0
, uint32_t arg1
, uint32_t flags
, uint8_t *datain
) {
778 struct Crypto1State mpcs
= {0, 0};
779 struct Crypto1State
*pcs
;
782 uint8_t uid
[10] = {0x00};
783 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
784 uint8_t par_enc
[1] = {0x00};
785 uint8_t buf
[PM3_CMD_DATA_SIZE
] = {0x00};
787 uint64_t ui64Key
= bytes_to_num(datain
, 6);
790 uint16_t num_nonces
= 0;
791 uint8_t nt_par_enc
= 0;
792 uint8_t cascade_levels
= 0;
793 uint8_t blockNo
= arg0
& 0xff;
794 uint8_t keyType
= (arg0
>> 8) & 0xff;
795 uint8_t targetBlockNo
= arg1
& 0xff;
796 uint8_t targetKeyType
= (arg1
>> 8) & 0xff;
797 bool initialize
= flags
& 0x0001;
798 bool slow
= flags
& 0x0002;
799 bool field_off
= flags
& 0x0004;
800 bool have_uid
= false;
806 BigBuf_Clear_ext(false);
811 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
815 for (uint16_t i
= 0; i
<= PM3_CMD_DATA_SIZE
- 9;) {
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)) {
827 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("AcquireEncryptedNonces: 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
)) {
846 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("AcquireEncryptedNonces: Can't select card (UID)");
852 SpinDelayUs(HARDNESTED_PRE_AUTHENTICATION_LEADTIME
);
855 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
)) {
856 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("AcquireEncryptedNonces: Auth1 error");
860 // nested authentication
861 uint16_t len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, 0x60 + (targetKeyType
& 0x01), targetBlockNo
, receivedAnswer
, par_enc
, NULL
);
863 // wait for the card to become ready again
867 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("AcquireEncryptedNonces: Auth2 error len=%d", len
);
872 if (num_nonces
% 2) {
873 memcpy(buf
+ i
, receivedAnswer
, 4);
874 nt_par_enc
= par_enc
[0] & 0xf0;
876 nt_par_enc
|= par_enc
[0] >> 4;
877 memcpy(buf
+ i
+ 4, receivedAnswer
, 4);
878 memcpy(buf
+ i
+ 8, &nt_par_enc
, 1);
886 reply_old(CMD_ACK
, isOK
, cuid
, num_nonces
, buf
, sizeof(buf
));
889 if (DBGLEVEL
>= 3) DbpString("AcquireEncryptedNonces finished");
892 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
899 //-----------------------------------------------------------------------------
900 // MIFARE nested authentication.
902 //-----------------------------------------------------------------------------
903 void MifareNested(uint8_t blockNo
, uint8_t keyType
, uint8_t targetBlockNo
, uint8_t targetKeyType
, bool calibrate
, uint8_t *key
) {
904 uint64_t ui64Key
= 0;
905 ui64Key
= bytes_to_num(key
, 6);
909 static uint16_t dmin
, dmax
;
911 uint8_t par
[1] = {0x00};
912 uint8_t par_array
[4] = {0x00};
913 uint8_t uid
[10] = {0x00};
914 uint32_t cuid
= 0, nt1
, nt2
, nttest
, ks1
;
915 uint32_t target_nt
[2] = {0x00}, target_ks
[2] = {0x00};
918 struct Crypto1State mpcs
= {0, 0};
919 struct Crypto1State
*pcs
;
921 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
923 uint32_t auth1_time
, auth2_time
;
924 static uint16_t delta_time
= 0;
928 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
930 // free eventually allocated BigBuf memory
932 BigBuf_Clear_ext(false);
939 // statistics on nonce distance
940 int16_t isOK
= PM3_SUCCESS
;
941 #define NESTED_MAX_TRIES 12
942 if (calibrate
) { // calibrate: for first call only. Otherwise reuse previous calibration
946 uint16_t unsuccessful_tries
= 0;
952 for (rtr
= 0; rtr
< 17; rtr
++) {
954 // Test if the action was cancelled
955 if (BUTTON_PRESS() || data_available()) {
956 isOK
= PM3_EOPABORTED
;
960 // prepare next select. No need to power down the card.
961 if (mifare_classic_halt(pcs
, cuid
)) {
962 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Halt error");
967 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
968 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Can't select card");
974 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, &auth1_time
)) {
975 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Auth1 error");
979 auth2_time
= (delta_time
) ? auth1_time
+ delta_time
: 0;
981 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_NESTED
, &nt2
, &auth2_time
)) {
982 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Auth2 error");
987 // cards with fixed nonce
989 Dbprintf("Nested: %08x vs %08x", nt1
, nt2
);
993 uint32_t nttmp
= prng_successor(nt1
, 100); //NXP Mifare is typical around 840,but for some unlicensed/compatible mifare card this can be 160
994 for (i
= 101; i
< 1200; i
++) {
995 nttmp
= prng_successor(nttmp
, 1);
996 if (nttmp
== nt2
) break;
1002 dmin
= MIN(dmin
, i
);
1003 dmax
= MAX(dmax
, i
);
1005 delta_time
= auth2_time
- auth1_time
+ 32; // allow some slack for proper timing
1007 if (DBGLEVEL
>= DBG_DEBUG
) Dbprintf("Nested: calibrating... ntdist=%d", i
);
1009 unsuccessful_tries
++;
1010 if (unsuccessful_tries
> NESTED_MAX_TRIES
) { // card isn't vulnerable to nested attack (random numbers are not predictable)
1017 davg
= (davg
+ (rtr
- 1) / 2) / (rtr
- 1);
1019 if (DBGLEVEL
>= DBG_DEBUG
) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr
, isOK
, dmin
, dmax
, davg
, delta_time
);
1026 // -------------------------------------------------------------------------------------------------
1030 // get crypted nonces for target sector
1031 for (i
= 0; i
< 2 && !isOK
; i
++) { // look for exactly two different nonces
1034 while (target_nt
[i
] == 0) { // continue until we have an unambiguous nonce
1036 // Test if the action was cancelled
1037 if (BUTTON_PRESS() || data_available()) {
1038 isOK
= PM3_EOPABORTED
;
1042 // prepare next select. No need to power down the card.
1043 if (mifare_classic_halt(pcs
, cuid
)) {
1044 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Halt error");
1048 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
1049 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Can't select card");
1054 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, &auth1_time
)) {
1055 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Auth1 error");
1059 // nested authentication
1060 auth2_time
= auth1_time
+ delta_time
;
1062 len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, 0x60 + (targetKeyType
& 0x01), targetBlockNo
, receivedAnswer
, par
, &auth2_time
);
1064 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Auth2 error len=%d", len
);
1068 nt2
= bytes_to_num(receivedAnswer
, 4);
1069 if (DBGLEVEL
>= DBG_DEBUG
) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i
+ 1, nt1
, nt2
, par
[0]);
1071 // Parity validity check
1072 for (j
= 0; j
< 4; j
++) {
1073 par_array
[j
] = (oddparity8(receivedAnswer
[j
]) != ((par
[0] >> (7 - j
)) & 0x01));
1077 nttest
= prng_successor(nt1
, dmin
- 1);
1078 for (j
= dmin
; j
< dmax
+ 1; j
++) {
1079 nttest
= prng_successor(nttest
, 1);
1082 if (valid_nonce(nttest
, nt2
, ks1
, par_array
)) {
1083 if (ncount
> 0) { // we are only interested in disambiguous nonces, try again
1084 if (DBGLEVEL
>= DBG_DEBUG
) Dbprintf("Nonce#%d: dismissed (ambiguous), ntdist=%d", i
+ 1, j
);
1088 target_nt
[i
] = nttest
;
1091 if (i
== 1 && target_nt
[1] == target_nt
[0]) { // we need two different nonces
1093 if (DBGLEVEL
>= DBG_DEBUG
) Dbprintf("Nonce#2: dismissed (= nonce#1), ntdist=%d", j
);
1096 if (DBGLEVEL
>= DBG_DEBUG
) Dbprintf("Nonce#%d: valid, ntdist=%d", i
+ 1, j
);
1099 if (target_nt
[i
] == 0 && j
== dmax
+ 1 && DBGLEVEL
>= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i
+ 1);
1105 crypto1_deinit(pcs
);
1117 payload
.isOK
= isOK
;
1118 payload
.block
= targetBlockNo
;
1119 payload
.keytype
= targetKeyType
;
1121 memcpy(payload
.cuid
, &cuid
, 4);
1122 memcpy(payload
.nt_a
, &target_nt
[0], 4);
1123 memcpy(payload
.ks_a
, &target_ks
[0], 4);
1124 memcpy(payload
.nt_b
, &target_nt
[1], 4);
1125 memcpy(payload
.ks_b
, &target_ks
[1], 4);
1127 reply_ng(CMD_HF_MIFARE_NESTED
, PM3_SUCCESS
, (uint8_t *)&payload
, sizeof(payload
));
1128 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1133 void MifareStaticNested(uint8_t blockNo
, uint8_t keyType
, uint8_t targetBlockNo
, uint8_t targetKeyType
, uint8_t *key
) {
1137 uint64_t ui64Key
= 0;
1138 ui64Key
= bytes_to_num(key
, 6);
1140 uint8_t uid
[10] = {0x00};
1141 uint32_t cuid
= 0, nt1
, nt2
;
1142 uint32_t target_nt
= 0, target_ks
= 0;
1143 uint8_t par
[1] = {0x00};
1144 uint8_t receivedAnswer
[10] = {0x00};
1146 struct Crypto1State mpcs
= {0, 0};
1147 struct Crypto1State
*pcs
;
1151 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1153 // free eventually allocated BigBuf memory
1155 BigBuf_Clear_ext(false);
1162 for (uint8_t retry
= 0; retry
< 3 && (isOK
== 0); retry
++) {
1166 // prepare next select. No need to power down the card.
1167 if (mifare_classic_halt(pcs
, cuid
)) {
1168 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Halt error");
1173 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
1174 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Can't select card");
1179 // First authentication. Normal auth.
1180 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
)) {
1181 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Auth1 error");
1186 // second authentication. Nested auth
1187 len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, 0x60 + (targetKeyType
& 0x01), targetBlockNo
, receivedAnswer
, par
, NULL
);
1189 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Nested: Auth2 error len=%d", len
);
1193 nt2
= bytes_to_num(receivedAnswer
, 4);
1194 target_nt
= prng_successor(nt1
, 160);
1195 target_ks
= nt2
^ target_nt
;
1198 if (DBGLEVEL
>= DBG_DEBUG
) Dbprintf("Testing nt1=%08x nt2enc=%08x nt2par=%02x ks=%08x", nt1
, nt2
, par
[0], target_ks
);
1203 crypto1_deinit(pcs
);
1213 payload
.isOK
= isOK
;
1214 payload
.block
= targetBlockNo
;
1215 payload
.keytype
= targetKeyType
;
1217 memcpy(payload
.cuid
, &cuid
, 4);
1218 memcpy(payload
.nt
, &target_nt
, 4);
1219 memcpy(payload
.ks
, &target_ks
, 4);
1222 reply_ng(CMD_HF_MIFARE_STATIC_NESTED
, PM3_SUCCESS
, (uint8_t *)&payload
, sizeof(payload
));
1225 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1229 //-----------------------------------------------------------------------------
1230 // MIFARE check keys. key count up to 85.
1232 //-----------------------------------------------------------------------------
1233 typedef struct sector_t
{
1238 typedef struct chk_t
{
1245 struct Crypto1State
*pcs
;
1249 // fast select, tries 5 times to select
1252 // 2 = failed to select.
1255 static uint8_t chkKey(struct chk_t
*c
) {
1256 uint8_t i
= 0, res
= 2;
1258 // this part is from Piwi's faster nonce collecting part in Hardnested.
1259 // assume: fast select
1260 if (!iso14443a_fast_select_card(c
->uid
, c
->cl
)) {
1264 res
= mifare_classic_authex(c
->pcs
, c
->cuid
, c
->block
, c
->keyType
, c
->key
, AUTH_FIRST
, NULL
, NULL
);
1268 // if successful auth, send HALT
1270 // mifare_classic_halt_ex(c->pcs);
1276 static uint8_t chkKey_readb(struct chk_t
*c
, uint8_t *keyb
) {
1278 if (!iso14443a_fast_select_card(c
->uid
, c
->cl
))
1281 if (mifare_classic_authex(c
->pcs
, c
->cuid
, c
->block
, 0, c
->key
, AUTH_FIRST
, NULL
, NULL
))
1284 uint8_t data
[16] = {0x00};
1285 uint8_t res
= mifare_classic_readblock(c
->pcs
, c
->cuid
, c
->block
, data
);
1289 // data was something else than zeros.
1290 if (memcmp(data
+ 10, "\x00\x00\x00\x00\x00\x00", 6) != 0) {
1291 memcpy(keyb
, data
+ 10, 6);
1296 mifare_classic_halt_ex(c
->pcs
);
1301 static void chkKey_scanA(struct chk_t
*c
, struct sector_t
*k_sector
, uint8_t *found
, uint8_t *sectorcnt
, uint8_t *foundkeys
) {
1302 for (uint8_t s
= 0; s
< *sectorcnt
; s
++) {
1304 // skip already found A keys
1308 c
->block
= FirstBlockOfSector(s
);
1309 if (chkKey(c
) == 0) {
1310 num_to_bytes(c
->key
, 6, k_sector
[s
].keyA
);
1314 if (DBGLEVEL
>= 3) Dbprintf("ChkKeys_fast: Scan A found (%d)", c
->block
);
1319 static void chkKey_scanB(struct chk_t
*c
, struct sector_t
*k_sector
, uint8_t *found
, uint8_t *sectorcnt
, uint8_t *foundkeys
) {
1320 for (uint8_t s
= 0; s
< *sectorcnt
; s
++) {
1322 // skip already found B keys
1323 if (found
[(s
* 2) + 1])
1326 c
->block
= FirstBlockOfSector(s
);
1327 if (chkKey(c
) == 0) {
1328 num_to_bytes(c
->key
, 6, k_sector
[s
].keyB
);
1329 found
[(s
* 2) + 1] = 1;
1332 if (DBGLEVEL
>= 3) Dbprintf("ChkKeys_fast: Scan B found (%d)", c
->block
);
1338 // when A is found but not B, try to read B.
1339 static void chkKey_loopBonly(struct chk_t
*c
, struct sector_t
*k_sector
, uint8_t *found
, uint8_t *sectorcnt
, uint8_t *foundkeys
) {
1341 // read Block B, if A is found.
1342 for (uint8_t s
= 0; s
< *sectorcnt
; ++s
) {
1344 if (found
[(s
* 2)] && found
[(s
* 2) + 1])
1347 c
->block
= (FirstBlockOfSector(s
) + NumBlocksPerSector(s
) - 1);
1350 if (found
[(s
* 2)] && !found
[(s
* 2) + 1]) {
1351 c
->key
= bytes_to_num(k_sector
[s
].keyA
, 6);
1352 uint8_t status
= chkKey_readb(c
, k_sector
[s
].keyB
);
1354 found
[(s
* 2) + 1] = 1;
1357 if (DBGLEVEL
>= 3) Dbprintf("ChkKeys_fast: Reading B found (%d)", c
->block
);
1359 // try quick find all B?
1360 // assume: keys comes in groups. Find one B, test against all B.
1361 c
->key
= bytes_to_num(k_sector
[s
].keyB
, 6);
1363 chkKey_scanB(c
, k_sector
, found
, sectorcnt
, foundkeys
);
1369 // get Chunks of keys, to test authentication against card.
1370 // arg0 = antal sectorer
1371 // arg0 = first time
1372 // arg1 = clear trace
1373 // arg2 = antal nycklar i keychunk
1374 // datain = keys as array
1375 void MifareChkKeys_fast(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
) {
1378 uint8_t sectorcnt
= arg0
& 0xFF; // 16;
1379 uint8_t firstchunk
= (arg0
>> 8) & 0xF;
1380 uint8_t lastchunk
= (arg0
>> 12) & 0xF;
1381 uint8_t strategy
= arg1
& 0xFF;
1382 uint8_t use_flashmem
= (arg1
>> 8) & 0xFF;
1383 uint16_t keyCount
= arg2
& 0xFF;
1386 struct Crypto1State mpcs
= {0, 0};
1387 struct Crypto1State
*pcs
;
1389 struct chk_t chk_data
;
1391 uint8_t allkeys
= sectorcnt
<< 1;
1393 static uint32_t cuid
= 0;
1394 static uint8_t cascade_levels
= 0;
1395 static uint8_t foundkeys
= 0;
1396 static sector_t k_sector
[80];
1397 static uint8_t found
[80];
1398 static uint8_t *uid
;
1400 int oldbg
= DBGLEVEL
;
1406 uint8_t size
[2] = {0x00, 0x00};
1407 isok
= Flash_ReadData(DEFAULT_MF_KEYS_OFFSET
, size
, 2);
1411 keyCount
= size
[1] << 8 | size
[0];
1416 // limit size of availlable for keys in bigbuff
1418 uint16_t key_mem_available
= MIN(BigBuf_get_size(), keyCount
* 6);
1420 keyCount
= key_mem_available
/ 6;
1422 datain
= BigBuf_malloc(key_mem_available
);
1426 isok
= Flash_ReadData(DEFAULT_MF_KEYS_OFFSET
+ 2, datain
, key_mem_available
);
1427 if (isok
!= key_mem_available
)
1433 if (uid
== NULL
|| firstchunk
) {
1434 uid
= BigBuf_malloc(10);
1439 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1448 memset(k_sector
, 0x00, 480 + 10);
1449 memset(found
, 0x00, sizeof(found
));
1452 iso14a_card_select_t card_info
;
1453 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
1454 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("ChkKeys_fast: Can't select card (ALL)");
1458 switch (card_info
.uidlen
) {
1475 // clear debug level. We are expecting lots of authentication failures...
1476 DBGLEVEL
= DBG_NONE
;
1478 // set check struct.
1480 chk_data
.cuid
= cuid
;
1481 chk_data
.cl
= cascade_levels
;
1485 // keychunk loop - depth first one sector.
1486 if (strategy
== 1 || use_flashmem
) {
1488 uint8_t newfound
= foundkeys
;
1490 uint16_t lastpos
= 0;
1491 uint16_t s_point
= 0;
1493 // keep track of how many sectors on card.
1494 for (uint8_t s
= 0; s
< sectorcnt
; ++s
) {
1496 if (found
[(s
* 2)] && found
[(s
* 2) + 1])
1499 for (uint16_t i
= s_point
; i
< keyCount
; ++i
) {
1501 // Allow button press / usb cmd to interrupt device
1502 if (BUTTON_PRESS() || data_available()) {
1507 if (foundkeys
== allkeys
)
1512 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
1513 chk_data
.block
= FirstBlockOfSector(s
);
1516 chk_data
.key
= bytes_to_num(datain
+ i
* 6, 6);
1518 // skip already found A keys
1519 if (!found
[(s
* 2)]) {
1520 chk_data
.keyType
= 0;
1521 status
= chkKey(&chk_data
);
1523 memcpy(k_sector
[s
].keyA
, datain
+ i
* 6, 6);
1527 chkKey_scanA(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
1529 // read Block B, if A is found.
1530 chkKey_loopBonly(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
1532 chk_data
.keyType
= 1;
1533 chkKey_scanB(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
1535 chk_data
.keyType
= 0;
1536 chk_data
.block
= FirstBlockOfSector(s
);
1539 if (lastpos
!= i
&& lastpos
!= 0) {
1540 if (i
- lastpos
< 0xF) {
1541 s_point
= i
& 0xFFF0;
1550 // skip already found B keys
1551 if (!found
[(s
* 2) + 1]) {
1552 chk_data
.keyType
= 1;
1553 status
= chkKey(&chk_data
);
1555 memcpy(k_sector
[s
].keyB
, datain
+ i
* 6, 6);
1556 found
[(s
* 2) + 1] = 1;
1559 chkKey_scanB(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
1562 if (lastpos
!= i
&& lastpos
!= 0) {
1564 if (i
- lastpos
< 0xF)
1565 s_point
= i
& 0xFFF0;
1573 if (found
[(s
* 2)] && found
[(s
* 2) + 1])
1576 } // end keys test loop - depth first
1578 // assume1. if no keys found in first sector, get next keychunk from client
1579 if (!use_flashmem
&& (newfound
- foundkeys
== 0))
1582 } // end loop - sector
1585 if (foundkeys
== allkeys
)
1588 if (strategy
== 2 || use_flashmem
) {
1591 for (uint16_t i
= 0; i
< keyCount
; i
++) {
1593 // Allow button press / usb cmd to interrupt device
1594 if (BUTTON_PRESS() || data_available()) break;
1597 if (foundkeys
== allkeys
)
1603 chk_data
.key
= bytes_to_num(datain
+ i
* 6, 6);
1606 // keep track of how many sectors on card.
1607 for (uint8_t s
= 0; s
< sectorcnt
; ++s
) {
1609 if (found
[(s
* 2)] && found
[(s
* 2) + 1]) continue;
1612 if (foundkeys
== allkeys
)
1615 // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector
1616 chk_data
.block
= FirstBlockOfSector(s
);
1618 // skip already found A keys
1619 if (!found
[(s
* 2)]) {
1620 chk_data
.keyType
= 0;
1621 status
= chkKey(&chk_data
);
1623 memcpy(k_sector
[s
].keyA
, datain
+ i
* 6, 6);
1627 chkKey_scanA(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
1629 // read Block B, if A is found.
1630 chkKey_loopBonly(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
1632 chk_data
.block
= FirstBlockOfSector(s
);
1636 // skip already found B keys
1637 if (!found
[(s
* 2) + 1]) {
1638 chk_data
.keyType
= 1;
1639 status
= chkKey(&chk_data
);
1641 memcpy(k_sector
[s
].keyB
, datain
+ i
* 6, 6);
1642 found
[(s
* 2) + 1] = 1;
1645 chkKey_scanB(&chk_data
, k_sector
, found
, §orcnt
, &foundkeys
);
1648 } // end loop sectors
1650 } // end loop strategy 2
1654 crypto1_deinit(pcs
);
1656 // All keys found, send to client, or last keychunk from client
1657 if (foundkeys
== allkeys
|| lastchunk
) {
1660 for (uint8_t m
= 0; m
< 64; m
++) {
1661 foo
|= ((uint64_t)(found
[m
] & 1) << m
);
1666 for (uint8_t m
= 64; m
< ARRAYLEN(found
); m
++) {
1667 bar
|= ((uint16_t)(found
[m
] & 1) << j
++);
1670 uint8_t *tmp
= BigBuf_malloc(480 + 10);
1671 memcpy(tmp
, k_sector
, sectorcnt
* sizeof(sector_t
));
1672 num_to_bytes(foo
, 8, tmp
+ 480);
1673 tmp
[488] = bar
& 0xFF;
1674 tmp
[489] = bar
>> 8 & 0xFF;
1676 reply_old(CMD_ACK
, foundkeys
, 0, 0, tmp
, 480 + 10);
1679 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1681 BigBuf_Clear_ext(false);
1683 // special trick ecfill
1684 if (use_flashmem
&& foundkeys
== allkeys
) {
1686 uint8_t block
[16] = {0};
1687 for (int i
= 0; i
< sectorcnt
; i
++) {
1691 blockno
= (i
* 4) ^ 0x3;
1693 blockno
= (32 * 4 + (i
- 32) * 16) ^ 0xF;
1696 emlGetMem(block
, blockno
, 1);
1698 memcpy(block
, k_sector
[i
].keyA
, 6);
1699 memcpy(block
+ 10, k_sector
[i
].keyB
, 6);
1701 emlSetMem_xt(block
, blockno
, 1, sizeof(block
));
1704 MifareECardLoad(sectorcnt
, 0);
1705 MifareECardLoad(sectorcnt
, 1);
1708 // partial/none keys found
1709 reply_mix(CMD_ACK
, foundkeys
, 0, 0, 0, 0);
1715 void MifareChkKeys(uint8_t *datain
, uint8_t reserved_mem
) {
1717 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1719 struct Crypto1State mpcs
= {0, 0};
1720 struct Crypto1State
*pcs
;
1723 uint8_t uid
[10] = {0x00};
1728 uint8_t cascade_levels
= 0;
1733 keyresult
.found
= false;
1734 bool have_uid
= false;
1736 uint8_t keyType
= datain
[0];
1737 uint8_t blockNo
= datain
[1];
1738 bool clearTrace
= datain
[2];
1739 uint16_t key_count
= (datain
[3] << 8) | datain
[4];
1741 uint16_t key_mem_available
;
1743 key_mem_available
= key_count
* 6;
1745 key_mem_available
= MIN((PM3_CMD_DATA_SIZE
- 5), key_count
* 6);
1747 key_count
= key_mem_available
/ 6;
1754 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1759 int oldbg
= DBGLEVEL
;
1760 DBGLEVEL
= DBG_NONE
;
1764 for (i
= 0; i
< key_count
; i
++) {
1766 // Iceman: use piwi's faster nonce collecting part in hardnested.
1767 if (!have_uid
) { // need a full select cycle to get the uid first
1768 iso14a_card_select_t card_info
;
1769 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
1770 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("ChkKeys: Can't select card (ALL)");
1771 --i
; // try same key once again
1774 switch (card_info
.uidlen
) {
1788 } else { // no need for anticollision. We can directly select the card
1789 if (!iso14443a_select_card(uid
, NULL
, NULL
, false, cascade_levels
, true)) {
1790 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("ChkKeys: Can't select card (UID)");
1791 --i
; // try same key once again
1796 key
= bytes_to_num(datain
+ i
* 6, 6);
1797 res
= mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, key
, AUTH_FIRST
);
1804 memcpy(keyresult
.key
, datain
+ i
* 6, 6);
1805 keyresult
.found
= true;
1811 reply_ng(CMD_HF_MIFARE_CHKKEYS
, PM3_SUCCESS
, (uint8_t *)&keyresult
, sizeof(keyresult
));
1812 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1816 crypto1_deinit(pcs
);
1821 void MifareChkKeys_file(uint8_t *fn
) {
1828 int changed
= rdv40_spiffs_lazy_mount();
1829 uint32_t size
= size_in_spiffs((char *)fn
);
1830 uint8_t *mem
= BigBuf_malloc(size
);
1832 rdv40_spiffs_read_as_filetype((char *)fn
, mem
, size
, RDV40_SPIFFS_SAFETY_SAFE
);
1835 rdv40_spiffs_lazy_unmount();
1840 MifareChkKeys(mem
, true);
1846 //-----------------------------------------------------------------------------
1847 // MIFARE Personalize UID. Only for Mifare Classic EV1 7Byte UID
1848 //-----------------------------------------------------------------------------
1849 void MifarePersonalizeUID(uint8_t keyType
, uint8_t perso_option
, uint64_t key
) {
1851 uint16_t isOK
= PM3_EUNDEF
;
1854 struct Crypto1State mpcs
= {0, 0};
1855 struct Crypto1State
*pcs
;
1858 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1865 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
1866 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
1870 uint8_t block_number
= 0;
1871 if (mifare_classic_auth(pcs
, cuid
, block_number
, keyType
, key
, AUTH_FIRST
)) {
1872 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Auth error");
1876 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
];
1877 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
];
1878 int len
= mifare_sendcmd_short(pcs
, true, MIFARE_EV1_PERSONAL_UID
, perso_option
, receivedAnswer
, receivedAnswerPar
, NULL
);
1879 if (len
!= 1 || receivedAnswer
[0] != CARD_ACK
) {
1880 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Cmd Error: %02x", receivedAnswer
[0]);
1884 if (mifare_classic_halt(pcs
, cuid
)) {
1885 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
1892 crypto1_deinit(pcs
);
1895 reply_ng(CMD_HF_MIFARE_PERSONALIZE_UID
, isOK
, NULL
, 0);
1898 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1903 //-----------------------------------------------------------------------------
1904 // Work with emulator memory
1906 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
1907 // involved in dealing with emulator memory. But if it is called later, it might
1908 // destroy the Emulator Memory.
1909 //-----------------------------------------------------------------------------
1911 void MifareEMemClr(void) {
1912 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1916 void MifareEMemSet(uint8_t blockno
, uint8_t blockcnt
, uint8_t blockwidth
, uint8_t *datain
) {
1917 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1919 if (blockwidth
== 0)
1920 blockwidth
= 16; // backwards compat... default bytewidth
1922 emlSetMem_xt(datain
, blockno
, blockcnt
, blockwidth
); // data, block num, blocks count, block byte width
1925 void MifareEMemGet(uint8_t blockno
, uint8_t blockcnt
) {
1926 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1929 size_t size
= blockcnt
* 16;
1930 if (size
> PM3_CMD_DATA_SIZE
) {
1931 reply_ng(CMD_HF_MIFARE_EML_MEMGET
, PM3_EMALLOC
, NULL
, 0);
1935 uint8_t *buf
= BigBuf_malloc(size
);
1937 emlGetMem(buf
, blockno
, blockcnt
); // data, block num, blocks count (max 4)
1940 reply_ng(CMD_HF_MIFARE_EML_MEMGET
, PM3_SUCCESS
, buf
, size
);
1942 BigBuf_free_keep_EM();
1945 //-----------------------------------------------------------------------------
1946 // Load a card into the emulator memory
1948 //-----------------------------------------------------------------------------
1949 int MifareECardLoadExt(uint8_t sectorcnt
, uint8_t keytype
) {
1950 int retval
= MifareECardLoad(sectorcnt
, keytype
);
1951 reply_ng(CMD_HF_MIFARE_EML_LOAD
, retval
, NULL
, 0);
1955 int MifareECardLoad(uint8_t sectorcnt
, uint8_t keytype
) {
1958 struct Crypto1State mpcs
= {0, 0};
1959 struct Crypto1State
*pcs
;
1963 uint8_t dataoutbuf
[16] = {0x00};
1964 uint8_t dataoutbuf2
[16] = {0x00};
1965 uint8_t uid
[10] = {0x00};
1968 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1973 int retval
= PM3_SUCCESS
;
1975 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
1977 if (DBGLEVEL
> DBG_ERROR
) Dbprintf("Can't select card");
1981 for (uint8_t sectorNo
= 0; sectorNo
< sectorcnt
; sectorNo
++) {
1982 uint64_t ui64Key
= emlGetKey(sectorNo
, keytype
);
1983 if (sectorNo
== 0) {
1984 if (mifare_classic_auth(pcs
, cuid
, FirstBlockOfSector(sectorNo
), keytype
, ui64Key
, AUTH_FIRST
)) {
1985 retval
= PM3_EPARTIAL
;
1986 if (DBGLEVEL
> DBG_ERROR
) Dbprintf("Sector[%2d]. Auth error", sectorNo
);
1990 if (mifare_classic_auth(pcs
, cuid
, FirstBlockOfSector(sectorNo
), keytype
, ui64Key
, AUTH_NESTED
)) {
1991 retval
= PM3_EPARTIAL
;
1992 if (DBGLEVEL
> DBG_ERROR
) Dbprintf("Sector[%2d]. Auth nested error", sectorNo
);
1997 for (uint8_t blockNo
= 0; blockNo
< NumBlocksPerSector(sectorNo
); blockNo
++) {
1998 if (mifare_classic_readblock(pcs
, cuid
, FirstBlockOfSector(sectorNo
) + blockNo
, dataoutbuf
)) {
1999 retval
= PM3_EPARTIAL
;
2001 if (DBGLEVEL
> DBG_ERROR
) Dbprintf("Error reading sector %2d block %2d", sectorNo
, blockNo
);
2005 if (memcmp(dataoutbuf
, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16) == 0) {
2009 if (blockNo
< NumBlocksPerSector(sectorNo
) - 1) {
2010 emlSetMem(dataoutbuf
, FirstBlockOfSector(sectorNo
) + blockNo
, 1);
2011 } else { // sector trailer, keep the keys, set only the AC
2012 emlGetMem(dataoutbuf2
, FirstBlockOfSector(sectorNo
) + blockNo
, 1);
2013 memcpy(dataoutbuf2
+ 6, dataoutbuf
+ 6, 4);
2014 emlSetMem(dataoutbuf2
, FirstBlockOfSector(sectorNo
) + blockNo
, 1);
2019 int res
= mifare_classic_halt(pcs
, cuid
);
2022 if (DBGLEVEL
>= DBG_INFO
) DbpString("Emulator fill sectors finished");
2025 crypto1_deinit(pcs
);
2026 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2033 //-----------------------------------------------------------------------------
2034 // Work with "magic Chinese" card (email him: ouyangweidaxian@live.cn)
2036 // PARAMS - workFlags
2037 // bit 0 - need get UID
2038 // bit 1 - need wupC
2039 // bit 2 - need HALT after sequence
2040 // bit 3 - need turn on FPGA before sequence
2041 // bit 4 - need turn off FPGA
2042 // bit 5 - need to set datain instead of issuing USB reply (called via ARM for StandAloneMode14a)
2043 // bit 6 - wipe tag.
2044 //-----------------------------------------------------------------------------
2045 // magic uid card generation 1 commands
2046 static uint8_t wupC1
[] = { MIFARE_MAGICWUPC1
};
2047 static uint8_t wupC2
[] = { MIFARE_MAGICWUPC2
};
2048 static uint8_t wipeC
[] = { MIFARE_MAGICWIPEC
};
2050 void MifareCSetBlock(uint32_t arg0
, uint32_t arg1
, uint8_t *datain
) {
2053 uint8_t workFlags
= arg0
;
2054 uint8_t blockNo
= arg1
;
2060 bool isOK
= false; //assume we will get an error
2061 uint8_t errormsg
= 0x00;
2062 uint8_t uid
[10] = {0x00};
2063 uint8_t data
[18] = {0x00};
2066 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
2067 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
2069 if (workFlags
& MAGIC_INIT
) {
2072 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2077 //loop doesn't loop just breaks out if error
2079 // read UID and return to client with write
2080 if (workFlags
& MAGIC_UID
) {
2081 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
2082 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
2083 errormsg
= MAGIC_UID
;
2084 mifare_classic_halt_ex(NULL
);
2087 mifare_classic_halt_ex(NULL
);
2090 // wipe tag, fill it with zeros
2091 if (workFlags
& MAGIC_WIPE
) {
2092 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
2093 if (!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
2094 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("wupC1 error");
2095 errormsg
= MAGIC_WIPE
;
2099 uint32_t old_timeout
= iso14a_get_timeout();
2102 // 13560000 / 1000 / (8 * 16) * timeout
2103 iso14a_set_timeout(21190);
2105 ReaderTransmit(wipeC
, sizeof(wipeC
), NULL
);
2106 if (!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
2107 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("wipeC error");
2108 errormsg
= MAGIC_WIPE
;
2111 iso14a_set_timeout(old_timeout
);
2113 mifare_classic_halt_ex(NULL
);
2117 if (workFlags
& MAGIC_WUPC
) {
2118 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
2119 if (!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
2120 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("wupC1 error");
2121 errormsg
= MAGIC_WUPC
;
2126 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
2127 if (!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
2128 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2135 if ((mifare_sendcmd_short(NULL
, CRYPT_NONE
, ISO14443A_CMD_WRITEBLOCK
, blockNo
, receivedAnswer
, receivedAnswerPar
, NULL
) != 1) || (receivedAnswer
[0] != 0x0a)) {
2136 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("write block send command error");
2141 memcpy(data
, datain
, 16);
2142 AddCrc14A(data
, 16);
2144 ReaderTransmit(data
, sizeof(data
), NULL
);
2145 if ((ReaderReceive(receivedAnswer
, receivedAnswerPar
) != 1) || (receivedAnswer
[0] != 0x0a)) {
2146 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("write block send data error");
2151 if (workFlags
& MAGIC_HALT
)
2152 mifare_classic_halt_ex(NULL
);
2160 reply_mix(CMD_ACK
, 1, 0, 0, uid
, sizeof(uid
));
2162 OnErrorMagic(errormsg
);
2164 if (workFlags
& MAGIC_OFF
)
2168 void MifareCGetBlock(uint32_t arg0
, uint32_t arg1
, uint8_t *datain
) {
2170 uint8_t workFlags
= arg0
;
2171 uint8_t blockNo
= arg1
;
2172 uint8_t errormsg
= 0x00;
2173 bool isOK
= false; //assume we will get an error
2179 uint8_t data
[MAX_MIFARE_FRAME_SIZE
];
2180 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
2181 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
2183 memset(data
, 0x00, sizeof(data
));
2185 if (workFlags
& MAGIC_INIT
) {
2188 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2193 //loop doesn't loop just breaks out if error or done
2195 if (workFlags
& MAGIC_WUPC
) {
2196 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
2197 if (!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
2198 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("wupC1 error");
2199 errormsg
= MAGIC_WUPC
;
2204 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
2205 if (!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
2206 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]");
2214 if ((mifare_sendcmd_short(NULL
, CRYPT_NONE
, ISO14443A_CMD_READBLOCK
, blockNo
, receivedAnswer
, receivedAnswerPar
, NULL
) != 18)) {
2215 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("read block send command error");
2220 memcpy(data
, receivedAnswer
, sizeof(data
));
2223 if (workFlags
& MAGIC_HALT
)
2224 mifare_classic_halt_ex(NULL
);
2229 // if MAGIC_DATAIN, the data stays on device side.
2230 if (workFlags
& MAGIC_DATAIN
) {
2232 memcpy(datain
, data
, sizeof(data
));
2235 reply_old(CMD_ACK
, 1, 0, 0, data
, sizeof(data
));
2237 OnErrorMagic(errormsg
);
2240 if (workFlags
& MAGIC_OFF
)
2244 void MifareCIdent(bool is_mfc
) {
2247 uint8_t rec
[1] = {0x00};
2248 uint8_t recpar
[1] = {0x00};
2249 uint8_t rats
[4] = { ISO14443A_CMD_RATS
, 0x80, 0x31, 0x73 };
2250 uint8_t rdblf0
[4] = { ISO14443A_CMD_READBLOCK
, 0xF0, 0x8D, 0x5f};
2251 uint8_t rdbl00
[4] = { ISO14443A_CMD_READBLOCK
, 0x00, 0x02, 0xa8};
2252 uint8_t *par
= BigBuf_malloc(MAX_PARITY_SIZE
);
2253 uint8_t *buf
= BigBuf_malloc(PM3_CMD_DATA_SIZE
);
2254 uint8_t *uid
= BigBuf_malloc(10);
2256 memset(par
, 0x00, MAX_PARITY_SIZE
);
2257 memset(buf
, 0x00, PM3_CMD_DATA_SIZE
);
2258 memset(uid
, 0x00, 10);
2261 uint8_t data
[1] = {0x00};
2263 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2265 // Generation 1 test
2266 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
2267 if (ReaderReceive(rec
, recpar
) && (rec
[0] == 0x0a)) {
2268 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
2269 if (!ReaderReceive(rec
, recpar
) || (rec
[0] != 0x0a)) {
2270 isGen
= MAGIC_GEN_1B
;
2273 isGen
= MAGIC_GEN_1A
;
2278 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2280 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2282 int res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
2284 if (cuid
== 0xAA55C396) {
2285 isGen
= MAGIC_GEN_UNFUSED
;
2289 ReaderTransmit(rats
, sizeof(rats
), NULL
);
2290 res
= ReaderReceive(buf
, par
);
2293 // test for some MFC gen2
2294 if (memcmp(buf
, "\x09\x78\x00\x91\x02\xDA\xBC\x19\x10\xF0\x05", 11) == 0) {
2297 uint8_t super
[] = {0x0A, 0x00, 0x00, 0xA6, 0xB0, 0x00, 0x10, 0x14, 0x1D};
2298 ReaderTransmit(super
, sizeof(super
), NULL
);
2299 res
= ReaderReceive(buf
, par
);
2301 isGen
= MAGIC_SUPER
;
2305 isGen
= MAGIC_GEN_2
;
2308 // test for some MFC 7b gen2
2309 if (memcmp(buf
, "\x0D\x78\x00\x71\x02\x88\x49\xA1\x30\x20\x15\x06\x08\x56\x3D", 15) == 0) {
2310 isGen
= MAGIC_GEN_2
;
2313 // test for Ultralight magic gen2
2314 if (memcmp(buf
, "\x0A\x78\x00\x81\x02\xDB\xA0\xC1\x19\x40\x2A\xB5", 12) == 0) {
2315 isGen
= MAGIC_GEN_2
;
2318 // test for Ultralight EV1 magic gen2
2319 if (memcmp(buf
, "\x85\x00\x00\xA0\x00\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x41\xDF", 18) == 0) {
2320 isGen
= MAGIC_GEN_2
;
2323 // test for some other Ultralight EV1 magic gen2
2324 if (memcmp(buf
, "\x85\x00\x00\xA0\x0A\x00\x0A\xC3\x00\x04\x03\x01\x01\x00\x0B\x03\x16\xD7", 18) == 0) {
2325 isGen
= MAGIC_GEN_2
;
2328 // test for some other Ultralight magic gen2
2329 if (memcmp(buf
, "\x85\x00\x00\xA0\x0A\x00\x0A\xB0\x00\x00\x00\x00\x00\x00\x00\x00\x18\x4D", 18) == 0) {
2330 isGen
= MAGIC_GEN_2
;
2333 // test for NTAG213 magic gen2
2334 if (memcmp(buf
, "\x85\x00\x00\xA0\x00\x00\x0A\xA5\x00\x04\x04\x02\x01\x00\x0F\x03\x79\x0C", 18) == 0) {
2335 isGen
= MAGIC_GEN_2
;
2340 if (is_mfc
== false) {
2342 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2344 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2345 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
2347 ReaderTransmit(rdblf0
, sizeof(rdblf0
), NULL
);
2348 res
= ReaderReceive(buf
, par
);
2350 isGen
= MAGIC_NTAG21X
;
2354 // magic MFC Gen3 test
2355 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2357 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2358 res
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true);
2360 ReaderTransmit(rdbl00
, sizeof(rdbl00
), NULL
);
2361 res
= ReaderReceive(buf
, par
);
2363 isGen
= MAGIC_GEN_3
;
2372 reply_ng(CMD_HF_MIFARE_CIDENT
, PM3_SUCCESS
, data
, sizeof(data
));
2378 void MifareHasStaticNonce(void) {
2381 int retval
= PM3_SUCCESS
;
2383 uint8_t *uid
= BigBuf_malloc(10);
2385 memset(uid
, 0x00, 10);
2387 uint8_t data
[1] = { NONCE_FAIL
};
2388 struct Crypto1State mpcs
= {0, 0};
2389 struct Crypto1State
*pcs
;
2392 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2394 uint8_t counter
= 0;
2395 for (uint8_t i
= 0; i
< 3; i
++) {
2397 iso14a_card_select_t card_info
;
2398 if (!iso14443a_select_card(uid
, &card_info
, NULL
, true, 0, true)) {
2403 uint8_t rec
[4] = {0x00};
2404 uint8_t recpar
[1] = {0x00};
2405 // Transmit MIFARE_CLASSIC_AUTH 0x60, block 0
2406 int len
= mifare_sendcmd_short(pcs
, false, MIFARE_AUTH_KEYA
, 0, rec
, recpar
, NULL
);
2412 // Save the tag nonce (nt)
2413 if (nt
== bytes_to_num(rec
, 4)) {
2417 nt
= bytes_to_num(rec
, 4);
2419 // some cards with static nonce need to be reset before next query
2420 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2424 memset(rec
, 0x00, sizeof(rec
));
2428 Dbprintf("%u static nonce %08x", data
[0], nt
);
2429 data
[0] = NONCE_STATIC
;
2431 data
[0] = NONCE_NORMAL
;
2435 reply_ng(CMD_HF_MIFARE_STATIC_NONCE
, retval
, data
, sizeof(data
));
2439 crypto1_deinit(pcs
);
2442 void OnSuccessMagic(void) {
2443 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2447 void OnErrorMagic(uint8_t reason
) {
2448 // ACK, ISOK, reason,0,0,0
2449 reply_mix(CMD_ACK
, 0, reason
, 0, 0, 0);
2453 int DoGen3Cmd(uint8_t *cmd
, uint8_t cmd_len
) {
2454 int retval
= PM3_SUCCESS
;
2455 uint8_t *par
= BigBuf_malloc(MAX_PARITY_SIZE
);
2456 uint8_t *buf
= BigBuf_malloc(PM3_CMD_DATA_SIZE
);
2459 uint32_t save_iso14a_timeout
= iso14a_get_timeout();
2460 iso14a_set_timeout(13560000 / 1000 / (8 * 16) * 2000); // 2 seconds timeout
2462 ReaderTransmit(cmd
, cmd_len
, NULL
);
2463 int res
= ReaderReceive(buf
, par
);
2464 if (res
== 4 && memcmp(buf
, "\x90\x00\xfd\x07", 4) == 0) {
2465 // timeout for card memory reset
2468 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Card operation not completed");
2471 iso14a_set_timeout(save_iso14a_timeout
);
2477 void MifareGen3UID(uint8_t uidlen
, uint8_t *uid
) {
2478 int retval
= PM3_SUCCESS
;
2479 uint8_t uid_cmd
[5] = { 0x90, 0xfb, 0xcc, 0xcc, 0x07 };
2480 uint8_t *old_uid
= BigBuf_malloc(10);
2481 uint8_t *cmd
= BigBuf_malloc(sizeof(uid_cmd
) + uidlen
+ 2);
2482 iso14a_card_select_t
*card_info
= (iso14a_card_select_t
*) BigBuf_malloc(sizeof(iso14a_card_select_t
));
2484 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2488 if (iso14443a_select_card(old_uid
, card_info
, NULL
, true, 0, true) == false) {
2492 if (card_info
->uidlen
!= uidlen
) {
2493 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Wrong UID length");
2498 memcpy(cmd
, uid_cmd
, sizeof(uid_cmd
));
2499 memcpy(&cmd
[sizeof(uid_cmd
)], uid
, uidlen
);
2500 AddCrc14A(cmd
, sizeof(uid_cmd
) + uidlen
);
2502 retval
= DoGen3Cmd(cmd
, sizeof(uid_cmd
) + uidlen
+ 2);
2505 reply_ng(CMD_HF_MIFARE_GEN3UID
, retval
, old_uid
, uidlen
);
2511 void MifareGen3Blk(uint8_t block_len
, uint8_t *block
) {
2512 #define MIFARE_BLOCK_SIZE (MAX_MIFARE_FRAME_SIZE - 2)
2513 int retval
= PM3_SUCCESS
;
2514 uint8_t block_cmd
[5] = { 0x90, 0xf0, 0xcc, 0xcc, 0x10 };
2515 uint8_t *uid
= BigBuf_malloc(10);
2516 uint8_t *cmd
= BigBuf_malloc(sizeof(block_cmd
) + MAX_MIFARE_FRAME_SIZE
);
2517 iso14a_card_select_t
*card_info
= (iso14a_card_select_t
*) BigBuf_malloc(sizeof(iso14a_card_select_t
));
2519 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2523 if (iso14443a_select_card(uid
, card_info
, NULL
, true, 0, true) == false) {
2528 bool doReselect
= false;
2529 if (block_len
< MIFARE_BLOCK_SIZE
) {
2530 if ((mifare_sendcmd_short(NULL
, CRYPT_NONE
, ISO14443A_CMD_READBLOCK
, 0, &cmd
[sizeof(block_cmd
)], NULL
, NULL
) != MAX_MIFARE_FRAME_SIZE
)) {
2531 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Read manufacturer block failed");
2538 if (block_len
> 0) {
2539 memcpy(cmd
, block_cmd
, sizeof(block_cmd
));
2540 memcpy(&cmd
[sizeof(block_cmd
)], block
, block_len
);
2541 int ofs
= sizeof(block_cmd
);
2542 if (card_info
->uidlen
== 4) {
2543 cmd
[ofs
+ 4] = cmd
[ofs
+ 0] ^ cmd
[ofs
+ 1] ^ cmd
[ofs
+ 2] ^ cmd
[ofs
+ 3];
2545 } else if (card_info
->uidlen
== 7) {
2548 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Wrong Card UID length");
2552 cmd
[ofs
++] = card_info
->sak
;
2553 cmd
[ofs
++] = card_info
->atqa
[0];
2554 cmd
[ofs
++] = card_info
->atqa
[1];
2555 AddCrc14A(cmd
, sizeof(block_cmd
) + MIFARE_BLOCK_SIZE
);
2558 if (!iso14443a_select_card(uid
, NULL
, NULL
, true, 0, true)) {
2564 retval
= DoGen3Cmd(cmd
, sizeof(block_cmd
) + MAX_MIFARE_FRAME_SIZE
);
2568 reply_ng(CMD_HF_MIFARE_GEN3BLK
, retval
, &cmd
[sizeof(block_cmd
)], MIFARE_BLOCK_SIZE
);
2574 void MifareGen3Freez(void) {
2575 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2579 int retval
= PM3_SUCCESS
;
2580 uint8_t freeze_cmd
[7] = { 0x90, 0xfd, 0x11, 0x11, 0x00, 0xe7, 0x91 };
2581 uint8_t *uid
= BigBuf_malloc(10);
2583 if (iso14443a_select_card(uid
, NULL
, NULL
, true, 0, true) == false) {
2588 retval
= DoGen3Cmd(freeze_cmd
, sizeof(freeze_cmd
));
2591 reply_ng(CMD_HF_MIFARE_GEN3FREEZ
, retval
, NULL
, 0);
2597 void MifareSetMod(uint8_t *datain
) {
2599 uint8_t mod
= datain
[0];
2600 uint64_t ui64Key
= bytes_to_num(datain
+ 1, 6);
2603 uint16_t isOK
= PM3_EUNDEF
;
2604 uint8_t uid
[10] = {0};
2606 struct Crypto1State mpcs
= {0, 0};
2607 struct Crypto1State
*pcs
= &mpcs
;
2608 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0};
2609 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0};
2611 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2621 if (!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, true)) {
2622 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
2626 if (mifare_classic_auth(pcs
, cuid
, 0, 0, ui64Key
, AUTH_FIRST
)) {
2627 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Auth error");
2632 if (((respLen
= mifare_sendcmd_short(pcs
, CRYPT_ALL
, 0x43, mod
, receivedAnswer
, receivedAnswerPar
, NULL
)) != 1) || (receivedAnswer
[0] != 0x0a)) {
2633 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("SetMod error; response[0]: %hhX, len: %d", receivedAnswer
[0], respLen
);
2637 if (mifare_classic_halt(pcs
, cuid
)) {
2638 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Halt error");
2646 crypto1_deinit(pcs
);
2649 reply_ng(CMD_HF_MIFARE_SETMOD
, isOK
, NULL
, 0);
2652 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2659 void Mifare_DES_Auth1(uint8_t arg0
, uint8_t *datain
) {
2660 uint8_t dataout
[12] = {0x00};
2661 uint8_t uid
[10] = {0x00};
2664 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2668 int len
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0, false);
2670 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
2675 if (mifare_desfire_des_auth1(cuid
, dataout
)) {
2676 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Authentication part1: Fail.");
2681 if (DBGLEVEL
>= DBG_EXTENDED
) DbpString("AUTH 1 FINISHED");
2682 reply_mix(CMD_ACK
, 1, cuid
, 0, dataout
, sizeof(dataout
));
2685 void Mifare_DES_Auth2(uint32_t arg0
, uint8_t *datain
) {
2686 uint32_t cuid
= arg0
;
2687 uint8_t key
[16] = {0x00};
2688 uint8_t dataout
[12] = {0x00};
2691 memcpy(key
, datain
, 16);
2693 isOK
= mifare_desfire_des_auth2(cuid
, key
, dataout
);
2696 if (DBGLEVEL
>= DBG_EXTENDED
) Dbprintf("Authentication part2: Failed");
2701 if (DBGLEVEL
>= DBG_EXTENDED
) DbpString("AUTH 2 FINISHED");
2703 reply_old(CMD_ACK
, isOK
, 0, 0, dataout
, sizeof(dataout
));
2704 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2710 // Tear-off attack against MFU.
2712 void MifareU_Otp_Tearoff(uint8_t blno
, uint32_t tearoff_time
, uint8_t *data_testwrite
) {
2713 uint8_t blockNo
= blno
;
2715 if (DBGLEVEL
>= DBG_DEBUG
) DbpString("Preparing OTP tear-off");
2717 if (tearoff_time
> 43000)
2718 tearoff_time
= 43000;
2719 tearoff_delay_us
= tearoff_time
;
2720 tearoff_enabled
= true;
2723 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2727 // write cmd to send, include CRC
2728 // 1b write, 1b block, 4b data, 2 crc
2730 MIFARE_ULC_WRITE
, blockNo
,
2731 data_testwrite
[0], data_testwrite
[1], data_testwrite
[2], data_testwrite
[3],
2734 AddCrc14A(cmd
, sizeof(cmd
) - 2);
2736 // anticollision / select card
2737 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
2738 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
2740 reply_ng(CMD_HF_MFU_OTP_TEAROFF
, PM3_EFAILED
, NULL
, 0);
2745 ReaderTransmit(cmd
, sizeof(cmd
), NULL
);
2747 reply_ng(CMD_HF_MFU_OTP_TEAROFF
, PM3_SUCCESS
, NULL
, 0);
2751 // Tear-off attack against MFU counter
2752 void MifareU_Counter_Tearoff(uint8_t counter
, uint32_t tearoff_time
, uint8_t *datain
) {
2754 if (tearoff_time
> 43000)
2755 tearoff_time
= 43000;
2758 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2762 // Send MFU counter increase cmd
2764 MIFARE_ULEV1_INCR_CNT
,
2773 AddCrc14A(cmd
, sizeof(cmd
) - 2);
2775 // anticollision / select card
2776 if (!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0, true)) {
2777 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Can't select card");
2785 ReaderTransmit(cmd
, sizeof(cmd
), NULL
);
2787 SpinDelayUsPrecision(tearoff_time
);
2790 reply_ng(CMD_HF_MFU_COUNTER_TEAROFF
, PM3_SUCCESS
, NULL
, 0);