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"
20 #include "protocols.h"
23 //-----------------------------------------------------------------------------
24 // Select, Authenticate, Read a MIFARE tag.
26 //-----------------------------------------------------------------------------
27 void MifareReadBlock(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
30 uint8_t blockNo
= arg0
;
31 uint8_t keyType
= arg1
;
33 ui64Key
= bytes_to_num(datain
, 6);
37 byte_t dataoutbuf
[16] = {0x00};
38 uint8_t uid
[10] = {0x00};
40 struct Crypto1State mpcs
= {0, 0};
41 struct Crypto1State
*pcs
;
44 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
54 if(!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0)) {
55 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
59 if(mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
60 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
64 if(mifare_classic_readblock(pcs
, cuid
, blockNo
, dataoutbuf
)) {
65 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block error");
69 if(mifare_classic_halt(pcs
, cuid
)) {
70 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
80 if (MF_DBGLEVEL
>= 2) DbpString("READ BLOCK FINISHED");
83 cmd_send(CMD_ACK
,isOK
,0,0,dataoutbuf
,16);
86 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
90 void MifareUC_Auth(uint8_t arg0
, uint8_t *keybytes
){
92 bool turnOffField
= (arg0
== 1);
94 LED_A_ON(); LED_B_OFF(); LED_C_OFF();
96 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
101 if(!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0)) {
102 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Can't select card");
107 if(!mifare_ultra_auth(keybytes
)){
108 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Authentication failed");
114 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
117 cmd_send(CMD_ACK
,1,0,0,0,0);
121 // Arg1 = UsePwd bool
122 // datain = PWD bytes,
123 void MifareUReadBlock(uint8_t arg0
, uint8_t arg1
, uint8_t *datain
)
125 uint8_t blockNo
= arg0
;
126 byte_t dataout
[16] = {0x00};
127 bool useKey
= (arg1
== 1); //UL_C
128 bool usePwd
= (arg1
== 2); //UL_EV1/NTAG
132 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
137 int len
= iso14443a_select_card(NULL
, NULL
, NULL
, true, 0);
139 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Can't select card (RC:%02X)",len
);
144 // UL-C authentication
146 uint8_t key
[16] = {0x00};
147 memcpy(key
, datain
, sizeof(key
) );
149 if ( !mifare_ultra_auth(key
) ) {
155 // UL-EV1 / NTAG authentication
157 uint8_t pwd
[4] = {0x00};
158 memcpy(pwd
, datain
, 4);
159 uint8_t pack
[4] = {0,0,0,0};
160 if (!mifare_ul_ev1_auth(pwd
, pack
)) {
166 if( mifare_ultra_readblock(blockNo
, dataout
) ) {
167 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Read block error");
172 if( mifare_ultra_halt() ) {
173 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Halt error");
178 cmd_send(CMD_ACK
,1,0,0,dataout
,16);
179 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
183 //-----------------------------------------------------------------------------
184 // Select, Authenticate, Read a MIFARE tag.
185 // read sector (data = 4 x 16 bytes = 64 bytes, or 16 x 16 bytes = 256 bytes)
186 //-----------------------------------------------------------------------------
187 void MifareReadSector(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
190 uint8_t sectorNo
= arg0
;
191 uint8_t keyType
= arg1
;
192 uint64_t ui64Key
= 0;
193 ui64Key
= bytes_to_num(datain
, 6);
197 byte_t dataoutbuf
[16 * 16];
198 uint8_t uid
[10] = {0x00};
200 struct Crypto1State mpcs
= {0, 0};
201 struct Crypto1State
*pcs
;
204 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
214 if(!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0)) {
216 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
220 if(isOK
&& mifare_classic_auth(pcs
, cuid
, FirstBlockOfSector(sectorNo
), keyType
, ui64Key
, AUTH_FIRST
)) {
222 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
225 for (uint8_t blockNo
= 0; isOK
&& blockNo
< NumBlocksPerSector(sectorNo
); blockNo
++) {
226 if(mifare_classic_readblock(pcs
, cuid
, FirstBlockOfSector(sectorNo
) + blockNo
, dataoutbuf
+ 16 * blockNo
)) {
228 if (MF_DBGLEVEL
>= 1) Dbprintf("Read sector %2d block %2d error", sectorNo
, blockNo
);
233 if(mifare_classic_halt(pcs
, cuid
)) {
234 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
237 if (MF_DBGLEVEL
>= 2) DbpString("READ SECTOR FINISHED");
239 crypto1_destroy(pcs
);
242 cmd_send(CMD_ACK
,isOK
,0,0,dataoutbuf
,16*NumBlocksPerSector(sectorNo
));
245 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
250 // arg0 = blockNo (start)
251 // arg1 = Pages (number of blocks)
253 // datain = KEY bytes
254 void MifareUReadCard(uint8_t arg0
, uint16_t arg1
, uint8_t arg2
, uint8_t *datain
)
258 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
260 // free eventually allocated BigBuf memory
261 BigBuf_free(); BigBuf_Clear_ext(false);
266 uint8_t blockNo
= arg0
;
267 uint16_t blocks
= arg1
;
268 bool useKey
= (arg2
== 1); //UL_C
269 bool usePwd
= (arg2
== 2); //UL_EV1/NTAG
270 uint32_t countblocks
= 0;
271 uint8_t *dataout
= BigBuf_malloc(CARD_MEMORY_SIZE
);
272 if (dataout
== NULL
){
273 Dbprintf("out of memory");
278 int len
= iso14443a_select_card(NULL
, NULL
, NULL
, true, 0);
280 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Can't select card (RC:%d)",len
);
285 // UL-C authentication
287 uint8_t key
[16] = {0x00};
288 memcpy(key
, datain
, sizeof(key
) );
290 if ( !mifare_ultra_auth(key
) ) {
296 // UL-EV1 / NTAG authentication
298 uint8_t pwd
[4] = {0x00};
299 memcpy(pwd
, datain
, sizeof(pwd
));
300 uint8_t pack
[4] = {0,0,0,0};
302 if (!mifare_ul_ev1_auth(pwd
, pack
)){
308 for (int i
= 0; i
< blocks
; i
++){
309 if ((i
*4) + 4 >= CARD_MEMORY_SIZE
) {
310 Dbprintf("Data exceeds buffer!!");
314 len
= mifare_ultra_readblock(blockNo
+ i
, dataout
+ 4 * i
);
317 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Read block %d error",i
);
318 // if no blocks read - error out
323 //stop at last successful read block and return what we got
331 len
= mifare_ultra_halt();
333 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Halt error");
338 if (MF_DBGLEVEL
>= MF_DBG_EXTENDED
) Dbprintf("Blocks read %d", countblocks
);
342 cmd_send(CMD_ACK
, 1, countblocks
, BigBuf_max_traceLen(), 0, 0);
343 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
349 //-----------------------------------------------------------------------------
350 // Select, Authenticate, Write a MIFARE tag.
352 //-----------------------------------------------------------------------------
353 void MifareWriteBlock(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
356 uint8_t blockNo
= arg0
;
357 uint8_t keyType
= arg1
;
358 uint64_t ui64Key
= 0;
359 byte_t blockdata
[16] = {0x00};
361 ui64Key
= bytes_to_num(datain
, 6);
362 memcpy(blockdata
, datain
+ 10, 16);
366 uint8_t uid
[10] = {0x00};
368 struct Crypto1State mpcs
= {0, 0};
369 struct Crypto1State
*pcs
;
372 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
382 if(!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0)) {
383 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
387 if(mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
388 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
392 if(mifare_classic_writeblock(pcs
, cuid
, blockNo
, blockdata
)) {
393 if (MF_DBGLEVEL
>= 1) Dbprintf("Write block error");
397 if(mifare_classic_halt(pcs
, cuid
)) {
398 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
406 crypto1_destroy(pcs
);
408 if (MF_DBGLEVEL
>= 2) DbpString("WRITE BLOCK FINISHED");
410 cmd_send(CMD_ACK
,isOK
,0,0,0,0);
412 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
417 /* // Command not needed but left for future testing
418 void MifareUWriteBlockCompat(uint8_t arg0, uint8_t *datain)
420 uint8_t blockNo = arg0;
421 byte_t blockdata[16] = {0x00};
423 memcpy(blockdata, datain, 16);
425 uint8_t uid[10] = {0x00};
427 LED_A_ON(); LED_B_OFF(); LED_C_OFF();
431 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
433 if(!iso14443a_select_card(uid, NULL, NULL, true, 0)) {
434 if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card");
439 if(mifare_ultra_writeblock_compat(blockNo, blockdata)) {
440 if (MF_DBGLEVEL >= 1) Dbprintf("Write block error");
444 if(mifare_ultra_halt()) {
445 if (MF_DBGLEVEL >= 1) Dbprintf("Halt error");
450 if (MF_DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED");
452 cmd_send(CMD_ACK,1,0,0,0,0);
453 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
458 // Arg0 : Block to write to.
459 // Arg1 : 0 = use no authentication.
460 // 1 = use 0x1A authentication.
461 // 2 = use 0x1B authentication.
462 // datain : 4 first bytes is data to be written.
463 // : 4/16 next bytes is authentication key.
464 void MifareUWriteBlock(uint8_t arg0
, uint8_t arg1
, uint8_t *datain
)
466 uint8_t blockNo
= arg0
;
467 bool useKey
= (arg1
== 1); //UL_C
468 bool usePwd
= (arg1
== 2); //UL_EV1/NTAG
469 byte_t blockdata
[4] = {0x00};
471 memcpy(blockdata
, datain
,4);
475 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
480 if(!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0)) {
481 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
486 // UL-C authentication
488 uint8_t key
[16] = {0x00};
489 memcpy(key
, datain
+4, sizeof(key
) );
491 if ( !mifare_ultra_auth(key
) ) {
497 // UL-EV1 / NTAG authentication
499 uint8_t pwd
[4] = {0x00};
500 memcpy(pwd
, datain
+4, 4);
501 uint8_t pack
[4] = {0,0,0,0};
502 if (!mifare_ul_ev1_auth(pwd
, pack
)) {
508 if(mifare_ultra_writeblock(blockNo
, blockdata
)) {
509 if (MF_DBGLEVEL
>= 1) Dbprintf("Write block error");
514 if(mifare_ultra_halt()) {
515 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
520 if (MF_DBGLEVEL
>= 2) DbpString("WRITE BLOCK FINISHED");
522 cmd_send(CMD_ACK
,1,0,0,0,0);
523 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
528 void MifareUSetPwd(uint8_t arg0
, uint8_t *datain
){
530 uint8_t pwd
[16] = {0x00};
531 byte_t blockdata
[4] = {0x00};
533 memcpy(pwd
, datain
, 16);
535 LED_A_ON(); LED_B_OFF(); LED_C_OFF();
536 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
541 if(!iso14443a_select_card(NULL
, NULL
, NULL
, true, 0)) {
542 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
547 blockdata
[0] = pwd
[7];
548 blockdata
[1] = pwd
[6];
549 blockdata
[2] = pwd
[5];
550 blockdata
[3] = pwd
[4];
551 if(mifare_ultra_writeblock( 44, blockdata
)) {
552 if (MF_DBGLEVEL
>= 1) Dbprintf("Write block error");
557 blockdata
[0] = pwd
[3];
558 blockdata
[1] = pwd
[2];
559 blockdata
[2] = pwd
[1];
560 blockdata
[3] = pwd
[0];
561 if(mifare_ultra_writeblock( 45, blockdata
)) {
562 if (MF_DBGLEVEL
>= 1) Dbprintf("Write block error");
567 blockdata
[0] = pwd
[15];
568 blockdata
[1] = pwd
[14];
569 blockdata
[2] = pwd
[13];
570 blockdata
[3] = pwd
[12];
571 if(mifare_ultra_writeblock( 46, blockdata
)) {
572 if (MF_DBGLEVEL
>= 1) Dbprintf("Write block error");
577 blockdata
[0] = pwd
[11];
578 blockdata
[1] = pwd
[10];
579 blockdata
[2] = pwd
[9];
580 blockdata
[3] = pwd
[8];
581 if(mifare_ultra_writeblock( 47, blockdata
)) {
582 if (MF_DBGLEVEL
>= 1) Dbprintf("Write block error");
587 if(mifare_ultra_halt()) {
588 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
593 cmd_send(CMD_ACK
,1,0,0,0,0);
594 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
599 // Return 1 if the nonce is invalid else return 0
600 int valid_nonce(uint32_t Nt
, uint32_t NtEnc
, uint32_t Ks1
, uint8_t *parity
) {
601 return ((oddparity8((Nt
>> 24) & 0xFF) == ((parity
[0]) ^ oddparity8((NtEnc
>> 24) & 0xFF) ^ BIT(Ks1
,16))) & \
602 (oddparity8((Nt
>> 16) & 0xFF) == ((parity
[1]) ^ oddparity8((NtEnc
>> 16) & 0xFF) ^ BIT(Ks1
,8))) & \
603 (oddparity8((Nt
>> 8) & 0xFF) == ((parity
[2]) ^ oddparity8((NtEnc
>> 8) & 0xFF) ^ BIT(Ks1
,0)))) ? 1 : 0;
607 //-----------------------------------------------------------------------------
608 // acquire encrypted nonces in order to perform the attack described in
609 // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened
610 // Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on
611 // Computer and Communications Security, 2015
612 //-----------------------------------------------------------------------------
613 #define AUTHENTICATION_TIMEOUT 848 //848 // card times out 1ms after wrong authentication (according to NXP documentation)
614 #define PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication
616 void MifareAcquireEncryptedNonces(uint32_t arg0
, uint32_t arg1
, uint32_t flags
, uint8_t *datain
)
618 uint64_t ui64Key
= 0;
619 uint8_t uid
[10] = {0x00};
621 uint8_t cascade_levels
= 0;
622 struct Crypto1State mpcs
= {0, 0};
623 struct Crypto1State
*pcs
;
625 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
627 uint8_t par_enc
[1] = {0x00};
628 uint8_t nt_par_enc
= 0;
629 uint8_t buf
[USB_CMD_DATA_SIZE
] = {0x00};
630 uint32_t timeout
= 0;
632 uint8_t blockNo
= arg0
& 0xff;
633 uint8_t keyType
= (arg0
>> 8) & 0xff;
634 uint8_t targetBlockNo
= arg1
& 0xff;
635 uint8_t targetKeyType
= (arg1
>> 8) & 0xff;
636 ui64Key
= bytes_to_num(datain
, 6);
637 bool initialize
= flags
& 0x0001;
638 bool slow
= flags
& 0x0002;
639 bool field_off
= flags
& 0x0004;
645 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
651 uint16_t num_nonces
= 0;
652 bool have_uid
= false;
653 for (uint16_t i
= 0; i
<= USB_CMD_DATA_SIZE
- 9; ) {
655 // Test if the action was cancelled
662 if (!have_uid
) { // need a full select cycle to get the uid first
663 iso14a_card_select_t card_info
;
664 if(!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0)) {
665 if (MF_DBGLEVEL
>= 1) Dbprintf("AcquireNonces: Can't select card (ALL)");
668 switch (card_info
.uidlen
) {
669 case 4 : cascade_levels
= 1; break;
670 case 7 : cascade_levels
= 2; break;
671 case 10: cascade_levels
= 3; break;
675 } else { // no need for anticollision. We can directly select the card
676 if(!iso14443a_select_card(uid
, NULL
, NULL
, false, cascade_levels
)) {
677 if (MF_DBGLEVEL
>= 1) Dbprintf("AcquireNonces: Can't select card (UID)");
683 timeout
= GetCountSspClk() + PRE_AUTHENTICATION_LEADTIME
;
684 while(GetCountSspClk() < timeout
);
688 if (mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, NULL
)) {
689 if (MF_DBGLEVEL
>= 1) Dbprintf("AcquireNonces: Auth1 error");
693 // nested authentication
694 uint16_t len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, 0x60 + (targetKeyType
& 0x01), targetBlockNo
, receivedAnswer
, par_enc
, NULL
);
696 if (MF_DBGLEVEL
>= 1) Dbprintf("AcquireNonces: Auth2 error len=%d", len
);
700 // send a dummy byte as reader response in order to trigger the cards authentication timeout
701 uint8_t dummy_answer
= 0;
702 ReaderTransmit(&dummy_answer
, 1, NULL
);
703 timeout
= GetCountSspClk() + AUTHENTICATION_TIMEOUT
;
706 if (num_nonces
% 2) {
707 memcpy(buf
+i
, receivedAnswer
, 4);
708 nt_par_enc
= par_enc
[0] & 0xf0;
710 nt_par_enc
|= par_enc
[0] >> 4;
711 memcpy(buf
+i
+4, receivedAnswer
, 4);
712 memcpy(buf
+i
+8, &nt_par_enc
, 1);
715 // wait for the card to become ready again
716 while(GetCountSspClk() < timeout
);
720 crypto1_destroy(pcs
);
722 cmd_send(CMD_ACK
, isOK
, cuid
, num_nonces
, buf
, sizeof(buf
));
725 if (MF_DBGLEVEL
>= 3) DbpString("AcquireEncryptedNonces finished");
728 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
730 //set_tracing(FALSE);
735 //-----------------------------------------------------------------------------
736 // MIFARE nested authentication.
738 //-----------------------------------------------------------------------------
739 void MifareNested(uint32_t arg0
, uint32_t arg1
, uint32_t calibrate
, uint8_t *datain
)
742 uint8_t blockNo
= arg0
& 0xff;
743 uint8_t keyType
= (arg0
>> 8) & 0xff;
744 uint8_t targetBlockNo
= arg1
& 0xff;
745 uint8_t targetKeyType
= (arg1
>> 8) & 0xff;
746 uint64_t ui64Key
= 0;
748 ui64Key
= bytes_to_num(datain
, 6);
751 uint16_t rtr
, i
, j
, len
;
753 static uint16_t dmin
, dmax
;
754 uint8_t uid
[10] = {0x00};
755 uint32_t cuid
= 0, nt1
, nt2
, nttmp
, nttest
, ks1
;
756 uint8_t par
[1] = {0x00};
757 uint32_t target_nt
[2] = {0x00}, target_ks
[2] = {0x00};
759 uint8_t par_array
[4] = {0x00};
761 struct Crypto1State mpcs
= {0, 0};
762 struct Crypto1State
*pcs
;
764 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
766 uint32_t auth1_time
, auth2_time
;
767 static uint16_t delta_time
= 0;
771 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
773 // free eventually allocated BigBuf memory
774 BigBuf_free(); BigBuf_Clear_ext(false);
776 if (calibrate
) clear_trace();
779 // statistics on nonce distance
781 #define NESTED_MAX_TRIES 12
782 uint16_t unsuccessfull_tries
= 0;
783 if (calibrate
) { // for first call only. Otherwise reuse previous calibration
791 for (rtr
= 0; rtr
< 17; rtr
++) {
793 // Test if the action was cancelled
799 // prepare next select. No need to power down the card.
800 if(mifare_classic_halt(pcs
, cuid
)) {
801 if (MF_DBGLEVEL
>= 1) Dbprintf("Nested: Halt error");
806 if(!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0)) {
807 if (MF_DBGLEVEL
>= 1) Dbprintf("Nested: Can't select card");
813 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, &auth1_time
)) {
814 if (MF_DBGLEVEL
>= 1) Dbprintf("Nested: Auth1 error");
818 auth2_time
= (delta_time
) ? auth1_time
+ delta_time
: 0;
820 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_NESTED
, &nt2
, &auth2_time
)) {
821 if (MF_DBGLEVEL
>= 1) Dbprintf("Nested: Auth2 error");
826 nttmp
= prng_successor(nt1
, 100); //NXP Mifare is typical around 840,but for some unlicensed/compatible mifare card this can be 160
827 for (i
= 101; i
< 1200; i
++) {
828 nttmp
= prng_successor(nttmp
, 1);
829 if (nttmp
== nt2
) break;
839 delta_time
= auth2_time
- auth1_time
+ 32; // allow some slack for proper timing
841 if (MF_DBGLEVEL
>= 3) Dbprintf("Nested: calibrating... ntdist=%d", i
);
843 unsuccessfull_tries
++;
844 if (unsuccessfull_tries
> NESTED_MAX_TRIES
) { // card isn't vulnerable to nested attack (random numbers are not predictable)
850 davg
= (davg
+ (rtr
- 1)/2) / (rtr
- 1);
852 if (MF_DBGLEVEL
>= 3) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr
, isOK
, dmin
, dmax
, davg
, delta_time
);
859 // -------------------------------------------------------------------------------------------------
863 // get crypted nonces for target sector
864 for(i
=0; i
< 2 && !isOK
; i
++) { // look for exactly two different nonces
867 while(target_nt
[i
] == 0) { // continue until we have an unambiguous nonce
869 // prepare next select. No need to power down the card.
870 if(mifare_classic_halt(pcs
, cuid
)) {
871 if (MF_DBGLEVEL
>= 1) Dbprintf("Nested: Halt error");
875 if(!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0)) {
876 if (MF_DBGLEVEL
>= 1) Dbprintf("Nested: Can't select card");
881 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
, &auth1_time
)) {
882 if (MF_DBGLEVEL
>= 1) Dbprintf("Nested: Auth1 error");
886 // nested authentication
887 auth2_time
= auth1_time
+ delta_time
;
889 len
= mifare_sendcmd_short(pcs
, AUTH_NESTED
, 0x60 + (targetKeyType
& 0x01), targetBlockNo
, receivedAnswer
, par
, &auth2_time
);
891 if (MF_DBGLEVEL
>= 1) Dbprintf("Nested: Auth2 error len=%d", len
);
895 nt2
= bytes_to_num(receivedAnswer
, 4);
896 if (MF_DBGLEVEL
>= 3) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i
+1, nt1
, nt2
, par
[0]);
898 // Parity validity check
899 // for (j = 0; j < 4; j++) {
900 // par_array[j] = (oddparity8(receivedAnswer[j]) != ((par[0] >> (7-j)) & 0x01));
902 par_array
[0] = (oddparity8(receivedAnswer
[0]) != ((par
[0] >> (7-0)) & 0x01));
903 par_array
[1] = (oddparity8(receivedAnswer
[1]) != ((par
[0] >> (7-1)) & 0x01));
904 par_array
[2] = (oddparity8(receivedAnswer
[2]) != ((par
[0] >> (7-2)) & 0x01));
905 par_array
[3] = (oddparity8(receivedAnswer
[3]) != ((par
[0] >> (7-3)) & 0x01));
908 nttest
= prng_successor(nt1
, dmin
- 1);
909 for (j
= dmin
; j
< dmax
+ 1; j
++) {
910 nttest
= prng_successor(nttest
, 1);
913 if (valid_nonce(nttest
, nt2
, ks1
, par_array
)){
914 if (ncount
> 0) { // we are only interested in disambiguous nonces, try again
915 if (MF_DBGLEVEL
>= 3) Dbprintf("Nonce#%d: dismissed (ambigous), ntdist=%d", i
+1, j
);
919 target_nt
[i
] = nttest
;
922 if (i
== 1 && target_nt
[1] == target_nt
[0]) { // we need two different nonces
924 if (MF_DBGLEVEL
>= 3) Dbprintf("Nonce#2: dismissed (= nonce#1), ntdist=%d", j
);
927 if (MF_DBGLEVEL
>= 3) Dbprintf("Nonce#%d: valid, ntdist=%d", i
+1, j
);
930 if (target_nt
[i
] == 0 && j
== dmax
+1 && MF_DBGLEVEL
>= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i
+1);
936 crypto1_destroy(pcs
);
938 byte_t buf
[4 + 4 * 4] = {0};
939 memcpy(buf
, &cuid
, 4);
940 memcpy(buf
+4, &target_nt
[0], 4);
941 memcpy(buf
+8, &target_ks
[0], 4);
942 memcpy(buf
+12, &target_nt
[1], 4);
943 memcpy(buf
+16, &target_ks
[1], 4);
946 cmd_send(CMD_ACK
, isOK
, 0, targetBlockNo
+ (targetKeyType
* 0x100), buf
, sizeof(buf
));
949 if (MF_DBGLEVEL
>= 3) DbpString("NESTED FINISHED");
951 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
956 //-----------------------------------------------------------------------------
957 // MIFARE check keys. key count up to 85.
959 //-----------------------------------------------------------------------------
960 void MifareChkKeys(uint16_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
) {
961 uint8_t blockNo
= arg0
& 0xff;
962 uint8_t keyType
= (arg0
>> 8) & 0xff;
963 bool clearTrace
= arg1
;
964 uint8_t keyCount
= arg2
;
965 uint64_t ui64Key
= 0;
967 bool have_uid
= FALSE
;
968 uint8_t cascade_levels
= 0;
969 uint32_t timeout
= 0;
973 uint8_t uid
[10] = {0x00};
975 struct Crypto1State mpcs
= {0, 0};
976 struct Crypto1State
*pcs
;
979 // save old debuglevel, and tempory turn off dbg printing. speedissues.
980 int OLD_MF_DBGLEVEL
= MF_DBGLEVEL
;
981 MF_DBGLEVEL
= MF_DBG_NONE
;
986 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
993 for (i
= 0; i
< keyCount
; ++i
) {
995 //mifare_classic_halt(pcs, cuid);
997 // this part is from Piwi's faster nonce collecting part in Hardnested.
998 if (!have_uid
) { // need a full select cycle to get the uid first
999 iso14a_card_select_t card_info
;
1000 if(!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0)) {
1001 if (MF_DBGLEVEL
>= 1) Dbprintf("ChkKeys: Can't select card (ALL)");
1004 switch (card_info
.uidlen
) {
1005 case 4 : cascade_levels
= 1; break;
1006 case 7 : cascade_levels
= 2; break;
1007 case 10: cascade_levels
= 3; break;
1011 } else { // no need for anticollision. We can directly select the card
1012 if(!iso14443a_select_card(uid
, NULL
, NULL
, false, cascade_levels
)) {
1013 if (MF_DBGLEVEL
>= 1) Dbprintf("ChkKeys: Can't select card (UID)");
1018 ui64Key
= bytes_to_num(datain
+ i
* 6, 6);
1020 if (mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
1022 uint8_t dummy_answer
= 0;
1023 ReaderTransmit(&dummy_answer
, 1, NULL
);
1024 timeout
= GetCountSspClk() + AUTHENTICATION_TIMEOUT
;
1026 // wait for the card to become ready again
1027 while(GetCountSspClk() < timeout
);
1036 cmd_send(CMD_ACK
, isOK
, 0, 0, datain
+ i
* 6, 6);
1038 // restore debug level
1039 MF_DBGLEVEL
= OLD_MF_DBGLEVEL
;
1041 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1044 crypto1_destroy(pcs
);
1047 //-----------------------------------------------------------------------------
1048 // MIFARE commands set debug level
1050 //-----------------------------------------------------------------------------
1051 void MifareSetDbgLvl(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
){
1053 Dbprintf("Debug level: %d", MF_DBGLEVEL
);
1056 //-----------------------------------------------------------------------------
1057 // Work with emulator memory
1059 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
1060 // involved in dealing with emulator memory. But if it is called later, it might
1061 // destroy the Emulator Memory.
1062 //-----------------------------------------------------------------------------
1064 void MifareEMemClr(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
){
1065 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1069 void MifareEMemSet(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
){
1070 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1071 if (arg2
==0) arg2
= 16; // backwards compat... default bytewidth
1072 emlSetMem_xt(datain
, arg0
, arg1
, arg2
); // data, block num, blocks count, block byte width
1075 void MifareEMemGet(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
){
1076 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1077 byte_t buf
[USB_CMD_DATA_SIZE
] = {0x00};
1078 emlGetMem(buf
, arg0
, arg1
); // data, block num, blocks count (max 4)
1081 cmd_send(CMD_ACK
,arg0
,arg1
,0,buf
,USB_CMD_DATA_SIZE
);
1085 //-----------------------------------------------------------------------------
1086 // Load a card into the emulator memory
1088 //-----------------------------------------------------------------------------
1089 void MifareECardLoad(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
){
1090 uint8_t numSectors
= arg0
;
1091 uint8_t keyType
= arg1
;
1092 uint64_t ui64Key
= 0;
1094 struct Crypto1State mpcs
= {0, 0};
1095 struct Crypto1State
*pcs
;
1099 byte_t dataoutbuf
[16] = {0x00};
1100 byte_t dataoutbuf2
[16] = {0x00};
1101 uint8_t uid
[10] = {0x00};
1106 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1113 if(!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0)) {
1115 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
1118 for (uint8_t sectorNo
= 0; isOK
&& sectorNo
< numSectors
; sectorNo
++) {
1119 ui64Key
= emlGetKey(sectorNo
, keyType
);
1121 if(isOK
&& mifare_classic_auth(pcs
, cuid
, FirstBlockOfSector(sectorNo
), keyType
, ui64Key
, AUTH_FIRST
)) {
1123 if (MF_DBGLEVEL
>= 1) Dbprintf("Sector[%2d]. Auth error", sectorNo
);
1127 if(isOK
&& mifare_classic_auth(pcs
, cuid
, FirstBlockOfSector(sectorNo
), keyType
, ui64Key
, AUTH_NESTED
)) {
1129 if (MF_DBGLEVEL
>= 1) Dbprintf("Sector[%2d]. Auth nested error", sectorNo
);
1134 for (uint8_t blockNo
= 0; isOK
&& blockNo
< NumBlocksPerSector(sectorNo
); blockNo
++) {
1135 if(isOK
&& mifare_classic_readblock(pcs
, cuid
, FirstBlockOfSector(sectorNo
) + blockNo
, dataoutbuf
)) {
1137 if (MF_DBGLEVEL
>= 1) Dbprintf("Error reading sector %2d block %2d", sectorNo
, blockNo
);
1141 if (blockNo
< NumBlocksPerSector(sectorNo
) - 1) {
1142 emlSetMem(dataoutbuf
, FirstBlockOfSector(sectorNo
) + blockNo
, 1);
1143 } else { // sector trailer, keep the keys, set only the AC
1144 emlGetMem(dataoutbuf2
, FirstBlockOfSector(sectorNo
) + blockNo
, 1);
1145 memcpy(&dataoutbuf2
[6], &dataoutbuf
[6], 4);
1146 emlSetMem(dataoutbuf2
, FirstBlockOfSector(sectorNo
) + blockNo
, 1);
1153 if(mifare_classic_halt(pcs
, cuid
))
1154 if (MF_DBGLEVEL
>= 1)
1155 Dbprintf("Halt error");
1157 // ----------------------------- crypto1 destroy
1158 crypto1_destroy(pcs
);
1160 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1163 if (MF_DBGLEVEL
>= 2) DbpString("EMUL FILL SECTORS FINISHED");
1169 //-----------------------------------------------------------------------------
1170 // Work with "magic Chinese" card (email him: ouyangweidaxian@live.cn)
1172 // PARAMS - workFlags
1173 // bit 0 - need get UID
1174 // bit 1 - need wupC
1175 // bit 2 - need HALT after sequence
1176 // bit 3 - need turn on FPGA before sequence
1177 // bit 4 - need turn off FPGA
1178 // bit 5 - need to set datain instead of issuing USB reply (called via ARM for StandAloneMode14a)
1179 // bit 6 - wipe tag.
1180 //-----------------------------------------------------------------------------
1181 // magic uid card generation 1 commands
1182 uint8_t wupC1
[] = { MIFARE_MAGICWUPC1
};
1183 uint8_t wupC2
[] = { MIFARE_MAGICWUPC2
};
1184 uint8_t wipeC
[] = { MIFARE_MAGICWIPEC
};
1186 void MifareCSetBlock(uint32_t arg0
, uint32_t arg1
, uint8_t *datain
){
1189 uint8_t workFlags
= arg0
;
1190 uint8_t blockNo
= arg1
;
1193 bool isOK
= false; //assume we will get an error
1194 uint8_t errormsg
= 0x00;
1195 uint8_t uid
[10] = {0x00};
1196 uint8_t data
[18] = {0x00};
1199 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
1200 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
1202 if (workFlags
& MAGIC_INIT
) {
1205 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1210 //loop doesn't loop just breaks out if error
1212 // read UID and return to client with write
1213 if (workFlags
& MAGIC_UID
) {
1214 if(!iso14443a_select_card(uid
, NULL
, &cuid
, true, 0)) {
1215 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Can't select card");
1216 errormsg
= MAGIC_UID
;
1218 mifare_classic_halt_ex(NULL
);
1222 // wipe tag, fill it with zeros
1223 if (workFlags
& MAGIC_WIPE
){
1224 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
1225 if(!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
1226 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("wupC1 error");
1227 errormsg
= MAGIC_WIPE
;
1231 ReaderTransmit(wipeC
, sizeof(wipeC
), NULL
);
1232 if(!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
1233 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("wipeC error");
1234 errormsg
= MAGIC_WIPE
;
1238 mifare_classic_halt_ex(NULL
);
1242 if (workFlags
& MAGIC_WUPC
) {
1243 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
1244 if(!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
1245 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("wupC1 error");
1246 errormsg
= MAGIC_WUPC
;
1250 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
1251 if(!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
1252 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("wupC2 error");
1253 errormsg
= MAGIC_WUPC
;
1258 if ((mifare_sendcmd_short(NULL
, 0, ISO14443A_CMD_WRITEBLOCK
, blockNo
, receivedAnswer
, receivedAnswerPar
, NULL
) != 1) || (receivedAnswer
[0] != 0x0a)) {
1259 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("write block send command error");
1264 memcpy(data
, datain
, 16);
1265 AppendCrc14443a(data
, 16);
1267 ReaderTransmit(data
, sizeof(data
), NULL
);
1268 if ((ReaderReceive(receivedAnswer
, receivedAnswerPar
) != 1) || (receivedAnswer
[0] != 0x0a)) {
1269 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("write block send data error");
1274 if (workFlags
& MAGIC_OFF
)
1275 mifare_classic_halt_ex(NULL
);
1283 cmd_send(CMD_ACK
,1,0,0,uid
,sizeof(uid
));
1285 OnErrorMagic(errormsg
);
1287 if (workFlags
& MAGIC_OFF
)
1291 void MifareCGetBlock(uint32_t arg0
, uint32_t arg1
, uint8_t *datain
){
1293 uint8_t workFlags
= arg0
;
1294 uint8_t blockNo
= arg1
;
1295 uint8_t errormsg
= 0x00;
1296 bool isOK
= false; //assume we will get an error
1299 uint8_t data
[MAX_MIFARE_FRAME_SIZE
];
1300 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
1301 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
1303 memset(data
, 0x00, sizeof(data
));
1305 if (workFlags
& MAGIC_INIT
) {
1308 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1313 //loop doesn't loop just breaks out if error or done
1315 if (workFlags
& MAGIC_WUPC
) {
1316 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
1317 if(!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
1318 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("wupC1 error");
1319 errormsg
= MAGIC_WUPC
;
1323 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
1324 if(!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
1325 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("wupC2 error");
1326 errormsg
= MAGIC_WUPC
;
1332 if ((mifare_sendcmd_short(NULL
, 0, ISO14443A_CMD_READBLOCK
, blockNo
, receivedAnswer
, receivedAnswerPar
, NULL
) != 18)) {
1333 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("read block send command error");
1338 memcpy(data
, receivedAnswer
, sizeof(data
));
1341 if (workFlags
& MAGIC_HALT
)
1342 mifare_classic_halt_ex(NULL
);
1347 // if MAGIC_DATAIN, the data stays on device side.
1348 if (workFlags
& MAGIC_DATAIN
) {
1350 memcpy(datain
, data
, sizeof(data
));
1353 cmd_send(CMD_ACK
,1,0,0,data
,sizeof(data
));
1355 OnErrorMagic(errormsg
);
1358 if (workFlags
& MAGIC_OFF
)
1362 void MifareCIdent(){
1366 uint8_t receivedAnswer
[1] = {0x00};
1367 uint8_t receivedAnswerPar
[1] = {0x00};
1369 ReaderTransmitBitsPar(wupC1
, 7, NULL
, NULL
);
1370 if(!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
1374 ReaderTransmit(wupC2
, sizeof(wupC2
), NULL
);
1375 if(!ReaderReceive(receivedAnswer
, receivedAnswerPar
) || (receivedAnswer
[0] != 0x0a)) {
1379 // removed the if, since some magic tags misbehavies and send an answer to it.
1380 mifare_classic_halt(NULL
, 0);
1381 cmd_send(CMD_ACK
,isOK
,0,0,0,0);
1384 void OnSuccessMagic(){
1385 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1389 void OnErrorMagic(uint8_t reason
){
1390 // ACK, ISOK, reason,0,0,0
1391 cmd_send(CMD_ACK
,0,reason
,0,0,0);
1397 void Mifare_DES_Auth1(uint8_t arg0
, uint8_t *datain
){
1398 byte_t dataout
[12] = {0x00};
1399 uint8_t uid
[10] = {0x00};
1402 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
1406 int len
= iso14443a_select_card(uid
, NULL
, &cuid
, true, 0);
1408 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Can't select card");
1413 if(mifare_desfire_des_auth1(cuid
, dataout
)){
1414 if (MF_DBGLEVEL
>= MF_DBG_ERROR
) Dbprintf("Authentication part1: Fail.");
1419 if (MF_DBGLEVEL
>= MF_DBG_EXTENDED
) DbpString("AUTH 1 FINISHED");
1420 cmd_send(CMD_ACK
, 1, cuid
, 0, dataout
, sizeof(dataout
));
1423 void Mifare_DES_Auth2(uint32_t arg0
, uint8_t *datain
){
1424 uint32_t cuid
= arg0
;
1425 uint8_t key
[16] = {0x00};
1426 byte_t dataout
[12] = {0x00};
1429 memcpy(key
, datain
, 16);
1431 isOK
= mifare_desfire_des_auth2(cuid
, key
, dataout
);
1434 if (MF_DBGLEVEL
>= MF_DBG_EXTENDED
) Dbprintf("Authentication part2: Failed");
1439 if (MF_DBGLEVEL
>= MF_DBG_EXTENDED
) DbpString("AUTH 2 FINISHED");
1441 cmd_send(CMD_ACK
, isOK
, 0, 0, dataout
, sizeof(dataout
));
1442 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);