1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2011,2012 Merlok
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
7 //-----------------------------------------------------------------------------
8 // High frequency MIFARE commands
9 //-----------------------------------------------------------------------------
20 #include "cmdhfmfhard.h"
23 #include "util_posix.h"
26 #include "mifare/mifarehost.h"
28 #include "mifare/mfkey.h"
29 #include "hardnested/hardnested_bf_core.h"
30 #include "cliparser/cliparser.h"
32 #include "mifare/mifaredefault.h"
33 #include "mifare/mifare4.h"
34 #include "mifare/mad.h"
35 #include "mifare/ndef.h"
37 #include "protocols.h"
39 #define NESTED_SECTOR_RETRY 10 // how often we try mfested() until we give up
41 static int CmdHelp(const char *Cmd
);
43 int CmdHF14AMifare(const char *Cmd
)
47 isOK
= mfDarkside(&key
);
49 case -1 : PrintAndLog("Button pressed. Aborted."); return 1;
50 case -2 : PrintAndLog("Card is not vulnerable to Darkside attack (doesn't send NACK on authentication requests)."); return 1;
51 case -3 : PrintAndLog("Card is not vulnerable to Darkside attack (its random number generator is not predictable)."); return 1;
52 case -4 : PrintAndLog("Card is not vulnerable to Darkside attack (its random number generator seems to be based on the wellknown");
53 PrintAndLog("generating polynomial with 16 effective bits only, but shows unexpected behaviour."); return 1;
54 case -5 : PrintAndLog("Aborted via keyboard."); return 1;
55 default : PrintAndLog("Found valid key:%012" PRIx64
"\n", key
);
63 int CmdHF14AMfWrBl(const char *Cmd
)
67 uint8_t key
[6] = {0, 0, 0, 0, 0, 0};
68 uint8_t bldata
[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
73 PrintAndLog("Usage: hf mf wrbl <block number> <key A/B> <key (12 hex symbols)> <block data (32 hex symbols)>");
74 PrintAndLog(" sample: hf mf wrbl 0 A FFFFFFFFFFFF 000102030405060708090A0B0C0D0E0F");
78 blockNo
= param_get8(Cmd
, 0);
79 cmdp
= param_getchar(Cmd
, 1);
81 PrintAndLog("Key type must be A or B");
84 if (cmdp
!= 'A' && cmdp
!= 'a') keyType
= 1;
85 if (param_gethex(Cmd
, 2, key
, 12)) {
86 PrintAndLog("Key must include 12 HEX symbols");
89 if (param_gethex(Cmd
, 3, bldata
, 32)) {
90 PrintAndLog("Block data must include 32 HEX symbols");
93 PrintAndLog("--block no:%d, key type:%c, key:%s", blockNo
, keyType
?'B':'A', sprint_hex(key
, 6));
94 PrintAndLog("--data: %s", sprint_hex(bldata
, 16));
96 UsbCommand c
= {CMD_MIFARE_WRITEBL
, {blockNo
, keyType
, 0}};
97 memcpy(c
.d
.asBytes
, key
, 6);
98 memcpy(c
.d
.asBytes
+ 10, bldata
, 16);
102 if (WaitForResponseTimeout(CMD_ACK
,&resp
,1500)) {
103 uint8_t isOK
= resp
.arg
[0] & 0xff;
104 PrintAndLog("isOk:%02x", isOK
);
106 PrintAndLog("Command execute timeout");
112 int CmdHF14AMfRdBl(const char *Cmd
)
116 uint8_t key
[6] = {0, 0, 0, 0, 0, 0};
122 PrintAndLog("Usage: hf mf rdbl <block number> <key A/B> <key (12 hex symbols)>");
123 PrintAndLog(" sample: hf mf rdbl 0 A FFFFFFFFFFFF ");
127 blockNo
= param_get8(Cmd
, 0);
128 cmdp
= param_getchar(Cmd
, 1);
130 PrintAndLog("Key type must be A or B");
133 if (cmdp
!= 'A' && cmdp
!= 'a') keyType
= 1;
134 if (param_gethex(Cmd
, 2, key
, 12)) {
135 PrintAndLog("Key must include 12 HEX symbols");
138 PrintAndLog("--block no:%d, key type:%c, key:%s ", blockNo
, keyType
?'B':'A', sprint_hex(key
, 6));
140 UsbCommand c
= {CMD_MIFARE_READBL
, {blockNo
, keyType
, 0}};
141 memcpy(c
.d
.asBytes
, key
, 6);
145 if (WaitForResponseTimeout(CMD_ACK
,&resp
,1500)) {
146 uint8_t isOK
= resp
.arg
[0] & 0xff;
147 uint8_t *data
= resp
.d
.asBytes
;
150 PrintAndLog("isOk:%02x data:%s", isOK
, sprint_hex(data
, 16));
152 PrintAndLog("isOk:%02x", isOK
);
156 if (mfIsSectorTrailer(blockNo
) && (data
[6] || data
[7] || data
[8])) {
157 PrintAndLogEx(NORMAL
, "Trailer decoded:");
158 int bln
= mfFirstBlockOfSector(mfSectorNum(blockNo
));
159 int blinc
= (mfNumBlocksPerSector(mfSectorNum(blockNo
)) > 4) ? 5 : 1;
160 for (int i
= 0; i
< 4; i
++) {
161 PrintAndLogEx(NORMAL
, "Access block %d%s: %s", bln
, ((blinc
> 1) && (i
< 3) ? "+" : "") , mfGetAccessConditionsDesc(i
, &data
[6]));
164 PrintAndLogEx(NORMAL
, "UserData: %s", sprint_hex_inrow(&data
[9], 1));
167 PrintAndLog("Command execute timeout");
174 int CmdHF14AMfRdSc(const char *Cmd
)
177 uint8_t sectorNo
= 0;
179 uint8_t key
[6] = {0, 0, 0, 0, 0, 0};
181 uint8_t *data
= NULL
;
185 PrintAndLog("Usage: hf mf rdsc <sector number> <key A/B> <key (12 hex symbols)>");
186 PrintAndLog(" sample: hf mf rdsc 0 A FFFFFFFFFFFF ");
190 sectorNo
= param_get8(Cmd
, 0);
192 PrintAndLog("Sector number must be less than 40");
195 cmdp
= param_getchar(Cmd
, 1);
196 if (cmdp
!= 'a' && cmdp
!= 'A' && cmdp
!= 'b' && cmdp
!= 'B') {
197 PrintAndLog("Key type must be A or B");
200 if (cmdp
!= 'A' && cmdp
!= 'a') keyType
= 1;
201 if (param_gethex(Cmd
, 2, key
, 12)) {
202 PrintAndLog("Key must include 12 HEX symbols");
205 PrintAndLog("--sector no:%d key type:%c key:%s ", sectorNo
, keyType
?'B':'A', sprint_hex(key
, 6));
207 UsbCommand c
= {CMD_MIFARE_READSC
, {sectorNo
, keyType
, 0}};
208 memcpy(c
.d
.asBytes
, key
, 6);
213 if (WaitForResponseTimeout(CMD_ACK
,&resp
,1500)) {
214 isOK
= resp
.arg
[0] & 0xff;
215 data
= resp
.d
.asBytes
;
217 PrintAndLog("isOk:%02x", isOK
);
219 for (i
= 0; i
< (sectorNo
<32?3:15); i
++) {
220 PrintAndLog("data : %s", sprint_hex(data
+ i
* 16, 16));
222 PrintAndLog("trailer: %s", sprint_hex(data
+ (sectorNo
<32?3:15) * 16, 16));
224 PrintAndLogEx(NORMAL
, "Trailer decoded:");
225 int bln
= mfFirstBlockOfSector(sectorNo
);
226 int blinc
= (mfNumBlocksPerSector(sectorNo
) > 4) ? 5 : 1;
227 for (i
= 0; i
< 4; i
++) {
228 PrintAndLogEx(NORMAL
, "Access block %d%s: %s", bln
, ((blinc
> 1) && (i
< 3) ? "+" : "") , mfGetAccessConditionsDesc(i
, &(data
+ (sectorNo
<32?3:15) * 16)[6]));
231 PrintAndLogEx(NORMAL
, "UserData: %s", sprint_hex_inrow(&(data
+ (sectorNo
<32?3:15) * 16)[9], 1));
234 PrintAndLog("Command execute timeout");
240 uint8_t FirstBlockOfSector(uint8_t sectorNo
)
245 return 32 * 4 + (sectorNo
- 32) * 16;
249 uint8_t NumBlocksPerSector(uint8_t sectorNo
)
258 static int ParamCardSizeSectors(const char c
) {
261 case '0' : numSectors
= 5; break;
262 case '2' : numSectors
= 32; break;
263 case '4' : numSectors
= 40; break;
264 default: numSectors
= 16;
269 static int ParamCardSizeBlocks(const char c
) {
270 int numBlocks
= 16 * 4;
272 case '0' : numBlocks
= 5 * 4; break;
273 case '2' : numBlocks
= 32 * 4; break;
274 case '4' : numBlocks
= 32 * 4 + 8 * 16; break;
275 default: numBlocks
= 16 * 4;
280 int CmdHF14AMfDump(const char *Cmd
)
282 uint8_t sectorNo
, blockNo
;
284 uint8_t keys
[2][40][6];
285 uint8_t rights
[40][4];
286 uint8_t carddata
[256][16];
287 uint8_t numSectors
= 16;
294 char cmdp
= param_getchar(Cmd
, 0);
295 numSectors
= ParamCardSizeSectors(cmdp
);
297 if (strlen(Cmd
) > 3 || cmdp
== 'h' || cmdp
== 'H') {
298 PrintAndLog("Usage: hf mf dump [card memory] [k|m]");
299 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
300 PrintAndLog(" k: Always try using both Key A and Key B for each sector, even if access bits would prohibit it");
301 PrintAndLog(" m: When missing access bits or keys, replace that block with NULL");
303 PrintAndLog("Samples: hf mf dump");
304 PrintAndLog(" hf mf dump 4");
305 PrintAndLog(" hf mf dump 4 m");
309 char opts
= param_getchar(Cmd
, 1);
310 bool useBothKeysAlways
= false;
311 if (opts
== 'k' || opts
== 'K') useBothKeysAlways
= true;
312 bool nullMissingKeys
= false;
313 if (opts
== 'm' || opts
== 'M') nullMissingKeys
= true;
315 if ((fin
= fopen("dumpkeys.bin","rb")) == NULL
) {
316 PrintAndLog("Could not find file dumpkeys.bin");
320 // Read keys from file
321 for (int group
=0; group
<=1; group
++) {
322 for (sectorNo
=0; sectorNo
<numSectors
; sectorNo
++) {
323 size_t bytes_read
= fread(keys
[group
][sectorNo
], 1, 6, fin
);
324 if (bytes_read
!= 6) {
325 PrintAndLog("File reading error.");
334 PrintAndLog("|-----------------------------------------|");
335 PrintAndLog("|------ Reading sector access bits...-----|");
336 PrintAndLog("|-----------------------------------------|");
338 for (sectorNo
= 0; sectorNo
< numSectors
; sectorNo
++) {
339 for (tries
= 0; tries
< 3; tries
++) {
340 UsbCommand c
= {CMD_MIFARE_READBL
, {FirstBlockOfSector(sectorNo
) + NumBlocksPerSector(sectorNo
) - 1, 0, 0}};
341 // At least the Access Conditions can always be read with key A.
342 memcpy(c
.d
.asBytes
, keys
[0][sectorNo
], 6);
345 if (WaitForResponseTimeout(CMD_ACK
,&resp
,1500)) {
346 uint8_t isOK
= resp
.arg
[0] & 0xff;
347 uint8_t *data
= resp
.d
.asBytes
;
349 rights
[sectorNo
][0] = ((data
[7] & 0x10)>>2) | ((data
[8] & 0x1)<<1) | ((data
[8] & 0x10)>>4); // C1C2C3 for data area 0
350 rights
[sectorNo
][1] = ((data
[7] & 0x20)>>3) | ((data
[8] & 0x2)<<0) | ((data
[8] & 0x20)>>5); // C1C2C3 for data area 1
351 rights
[sectorNo
][2] = ((data
[7] & 0x40)>>4) | ((data
[8] & 0x4)>>1) | ((data
[8] & 0x40)>>6); // C1C2C3 for data area 2
352 rights
[sectorNo
][3] = ((data
[7] & 0x80)>>5) | ((data
[8] & 0x8)>>2) | ((data
[8] & 0x80)>>7); // C1C2C3 for sector trailer
354 } else if (tries
== 2) { // on last try set defaults
355 PrintAndLog("Could not get access rights for sector %2d. Trying with defaults...", sectorNo
);
356 rights
[sectorNo
][0] = rights
[sectorNo
][1] = rights
[sectorNo
][2] = 0x00;
357 rights
[sectorNo
][3] = 0x01;
360 PrintAndLog("Command execute timeout when trying to read access rights for sector %2d. Trying with defaults...", sectorNo
);
361 rights
[sectorNo
][0] = rights
[sectorNo
][1] = rights
[sectorNo
][2] = 0x00;
362 rights
[sectorNo
][3] = 0x01;
367 PrintAndLog("|-----------------------------------------|");
368 PrintAndLog("|----- Dumping all blocks to file... -----|");
369 PrintAndLog("|-----------------------------------------|");
372 for (sectorNo
= 0; isOK
&& sectorNo
< numSectors
; sectorNo
++) {
373 for (blockNo
= 0; isOK
&& blockNo
< NumBlocksPerSector(sectorNo
); blockNo
++) {
374 bool received
= false;
375 for (tries
= 0; tries
< 3; tries
++) {
376 if (blockNo
== NumBlocksPerSector(sectorNo
) - 1) { // sector trailer. At least the Access Conditions can always be read with key A.
377 UsbCommand c
= {CMD_MIFARE_READBL
, {FirstBlockOfSector(sectorNo
) + blockNo
, 0, 0}};
378 memcpy(c
.d
.asBytes
, keys
[0][sectorNo
], 6);
380 received
= WaitForResponseTimeout(CMD_ACK
,&resp
,1500);
381 } else if (useBothKeysAlways
) {
382 // Always try both keys, even if access conditions wouldn't work.
383 for (int k
=0; k
<=1; k
++) {
384 UsbCommand c
= {CMD_MIFARE_READBL
, {FirstBlockOfSector(sectorNo
) + blockNo
, 1, 0}};
385 memcpy(c
.d
.asBytes
, keys
[k
][sectorNo
], 6);
387 received
= WaitForResponseTimeout(CMD_ACK
,&resp
,1500);
389 // Don't try the other one on success.
390 if (resp
.arg
[0] & 0xff) break;
392 } else { // data block. Check if it can be read with key A or key B
393 uint8_t data_area
= sectorNo
<32?blockNo
:blockNo
/5;
394 if ((rights
[sectorNo
][data_area
] == 0x03) || (rights
[sectorNo
][data_area
] == 0x05)) { // only key B would work
395 UsbCommand c
= {CMD_MIFARE_READBL
, {FirstBlockOfSector(sectorNo
) + blockNo
, 1, 0}};
396 memcpy(c
.d
.asBytes
, keys
[1][sectorNo
], 6);
398 received
= WaitForResponseTimeout(CMD_ACK
,&resp
,1500);
399 } else if (rights
[sectorNo
][data_area
] == 0x07) { // no key would work
400 PrintAndLog("Access rights do not allow reading of sector %2d block %3d", sectorNo
, blockNo
);
401 if (nullMissingKeys
) {
402 memset(resp
.d
.asBytes
, 0, 16);
404 PrintAndLog(" ... filling the block with NULL");
410 } else { // key A would work
411 UsbCommand c
= {CMD_MIFARE_READBL
, {FirstBlockOfSector(sectorNo
) + blockNo
, 0, 0}};
412 memcpy(c
.d
.asBytes
, keys
[0][sectorNo
], 6);
414 received
= WaitForResponseTimeout(CMD_ACK
,&resp
,1500);
418 isOK
= resp
.arg
[0] & 0xff;
424 isOK
= resp
.arg
[0] & 0xff;
425 uint8_t *data
= resp
.d
.asBytes
;
426 if (blockNo
== NumBlocksPerSector(sectorNo
) - 1) { // sector trailer. Fill in the keys.
427 memcpy(data
, keys
[0][sectorNo
], 6);
428 memcpy(data
+ 10, keys
[1][sectorNo
], 6);
431 memcpy(carddata
[FirstBlockOfSector(sectorNo
) + blockNo
], data
, 16);
432 PrintAndLog("Successfully read block %2d of sector %2d.", blockNo
, sectorNo
);
434 PrintAndLog("Could not read block %2d of sector %2d", blockNo
, sectorNo
);
440 PrintAndLog("Command execute timeout when trying to read block %2d of sector %2d.", blockNo
, sectorNo
);
447 if ((fout
= fopen("dumpdata.bin","wb")) == NULL
) {
448 PrintAndLog("Could not create file name dumpdata.bin");
451 uint16_t numblocks
= FirstBlockOfSector(numSectors
- 1) + NumBlocksPerSector(numSectors
- 1);
452 fwrite(carddata
, 1, 16*numblocks
, fout
);
454 PrintAndLog("Dumped %d blocks (%d bytes) to file dumpdata.bin", numblocks
, 16*numblocks
);
460 int CmdHF14AMfRestore(const char *Cmd
)
462 uint8_t sectorNo
,blockNo
;
464 uint8_t key
[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
465 uint8_t bldata
[16] = {0x00};
473 char cmdp
= param_getchar(Cmd
, 0);
475 case '0' : numSectors
= 5; break;
477 case '\0': numSectors
= 16; break;
478 case '2' : numSectors
= 32; break;
479 case '4' : numSectors
= 40; break;
480 default: numSectors
= 16;
483 if (strlen(Cmd
) > 1 || cmdp
== 'h' || cmdp
== 'H') {
484 PrintAndLog("Usage: hf mf restore [card memory]");
485 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
487 PrintAndLog("Samples: hf mf restore");
488 PrintAndLog(" hf mf restore 4");
492 if ((fkeys
= fopen("dumpkeys.bin","rb")) == NULL
) {
493 PrintAndLog("Could not find file dumpkeys.bin");
497 for (sectorNo
= 0; sectorNo
< numSectors
; sectorNo
++) {
498 size_t bytes_read
= fread(keyA
[sectorNo
], 1, 6, fkeys
);
499 if (bytes_read
!= 6) {
500 PrintAndLog("File reading error (dumpkeys.bin).");
506 for (sectorNo
= 0; sectorNo
< numSectors
; sectorNo
++) {
507 size_t bytes_read
= fread(keyB
[sectorNo
], 1, 6, fkeys
);
508 if (bytes_read
!= 6) {
509 PrintAndLog("File reading error (dumpkeys.bin).");
517 if ((fdump
= fopen("dumpdata.bin","rb")) == NULL
) {
518 PrintAndLog("Could not find file dumpdata.bin");
521 PrintAndLog("Restoring dumpdata.bin to card");
523 for (sectorNo
= 0; sectorNo
< numSectors
; sectorNo
++) {
524 for(blockNo
= 0; blockNo
< NumBlocksPerSector(sectorNo
); blockNo
++) {
525 UsbCommand c
= {CMD_MIFARE_WRITEBL
, {FirstBlockOfSector(sectorNo
) + blockNo
, keyType
, 0}};
526 memcpy(c
.d
.asBytes
, key
, 6);
528 size_t bytes_read
= fread(bldata
, 1, 16, fdump
);
529 if (bytes_read
!= 16) {
530 PrintAndLog("File reading error (dumpdata.bin).");
535 if (blockNo
== NumBlocksPerSector(sectorNo
) - 1) { // sector trailer
536 bldata
[0] = (keyA
[sectorNo
][0]);
537 bldata
[1] = (keyA
[sectorNo
][1]);
538 bldata
[2] = (keyA
[sectorNo
][2]);
539 bldata
[3] = (keyA
[sectorNo
][3]);
540 bldata
[4] = (keyA
[sectorNo
][4]);
541 bldata
[5] = (keyA
[sectorNo
][5]);
542 bldata
[10] = (keyB
[sectorNo
][0]);
543 bldata
[11] = (keyB
[sectorNo
][1]);
544 bldata
[12] = (keyB
[sectorNo
][2]);
545 bldata
[13] = (keyB
[sectorNo
][3]);
546 bldata
[14] = (keyB
[sectorNo
][4]);
547 bldata
[15] = (keyB
[sectorNo
][5]);
550 PrintAndLog("Writing to block %3d: %s", FirstBlockOfSector(sectorNo
) + blockNo
, sprint_hex(bldata
, 16));
552 memcpy(c
.d
.asBytes
+ 10, bldata
, 16);
556 if (WaitForResponseTimeout(CMD_ACK
,&resp
,1500)) {
557 uint8_t isOK
= resp
.arg
[0] & 0xff;
558 PrintAndLog("isOk:%02x", isOK
);
560 PrintAndLog("Command execute timeout");
569 //----------------------------------------------
571 //----------------------------------------------
573 static void parseParamTDS(const char *Cmd
, const uint8_t indx
, bool *paramT
, bool *paramD
, uint16_t *timeout
) {
575 int len
= param_getlength(Cmd
, indx
);
576 if (len
> 0 && len
< 4){
577 param_getstr(Cmd
, indx
, ctmp3
, sizeof(ctmp3
));
579 *paramT
|= (ctmp3
[0] == 't' || ctmp3
[0] == 'T');
580 *paramD
|= (ctmp3
[0] == 'd' || ctmp3
[0] == 'D');
581 bool paramS1
= *paramT
|| *paramD
;
583 // slow and very slow
584 if (ctmp3
[0] == 's' || ctmp3
[0] == 'S' || ctmp3
[1] == 's' || ctmp3
[1] == 'S') {
585 *timeout
= MF_CHKKEYS_SLOWTIMEOUT
; // slow
587 if (!paramS1
&& (ctmp3
[1] == 's' || ctmp3
[1] == 'S')) {
588 *timeout
= MF_CHKKEYS_VERYSLOWTIMEOUT
; // very slow
590 if (paramS1
&& (ctmp3
[2] == 's' || ctmp3
[2] == 'S')) {
591 *timeout
= MF_CHKKEYS_VERYSLOWTIMEOUT
; // very slow
597 int CmdHF14AMfNested(const char *Cmd
) {
598 int i
, j
, res
, iterations
;
599 sector_t
*e_sector
= NULL
;
602 uint8_t trgBlockNo
= 0;
603 uint8_t trgKeyType
= 0;
604 uint8_t SectorsCnt
= 0;
605 uint8_t key
[6] = {0, 0, 0, 0, 0, 0};
606 uint8_t keyBlock
[MifareDefaultKeysSize
* 6];
608 // timeout in units. (ms * 106) or us*0.106
609 uint16_t timeout14a
= MF_CHKKEYS_DEFTIMEOUT
; // fast by default
611 bool autosearchKey
= false;
613 bool transferToEml
= false;
614 bool createDumpFile
= false;
616 uint8_t standart
[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
617 uint8_t tempkey
[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
622 PrintAndLog("Usage:");
623 PrintAndLog(" all sectors: hf mf nested <card memory> <block number> <key A/B> <key (12 hex symbols)> [t|d|s|ss]");
624 PrintAndLog(" all sectors autosearch key: hf mf nested <card memory> * [t|d|s|ss]");
625 PrintAndLog(" one sector: hf mf nested o <block number> <key A/B> <key (12 hex symbols)>");
626 PrintAndLog(" <target block number> <target key A/B> [t]");
628 PrintAndLog("card memory - 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other> - 1K");
629 PrintAndLog("t - transfer keys to emulator memory");
630 PrintAndLog("d - write keys to binary file dumpkeys.bin");
631 PrintAndLog("s - Slow (1ms) check keys (required by some non standard cards)");
632 PrintAndLog("ss - Very slow (5ms) check keys");
634 PrintAndLog(" sample1: hf mf nested 1 0 A FFFFFFFFFFFF ");
635 PrintAndLog(" sample2: hf mf nested 1 0 A FFFFFFFFFFFF t ");
636 PrintAndLog(" sample3: hf mf nested 1 0 A FFFFFFFFFFFF d ");
637 PrintAndLog(" sample4: hf mf nested o 0 A FFFFFFFFFFFF 4 A");
638 PrintAndLog(" sample5: hf mf nested 1 * t");
639 PrintAndLog(" sample6: hf mf nested 1 * ss");
644 cmdp
= param_getchar(Cmd
, 0);
645 if (cmdp
== 'o' || cmdp
== 'O') {
649 SectorsCnt
= ParamCardSizeSectors(cmdp
);
652 // <block number>. number or autosearch key (*)
653 if (param_getchar(Cmd
, 1) == '*') {
654 autosearchKey
= true;
656 parseParamTDS(Cmd
, 2, &transferToEml
, &createDumpFile
, &timeout14a
);
658 PrintAndLog("--nested. sectors:%2d, block no:*, eml:%c, dmp=%c checktimeout=%d us",
659 SectorsCnt
, transferToEml
?'y':'n', createDumpFile
?'y':'n', ((uint32_t)timeout14a
* 1000) / 106);
661 blockNo
= param_get8(Cmd
, 1);
663 ctmp
= param_getchar(Cmd
, 2);
664 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
665 PrintAndLog("Key type must be A or B");
669 if (ctmp
!= 'A' && ctmp
!= 'a')
672 if (param_gethex(Cmd
, 3, key
, 12)) {
673 PrintAndLog("Key must include 12 HEX symbols");
677 // check if we can authenticate to sector
678 res
= mfCheckKeys(blockNo
, keyType
, timeout14a
, true, 1, key
, &key64
);
680 PrintAndLog("Can't authenticate to block %d, key type %c, key %s", blockNo
, keyType
?'B':'A', sprint_hex(key
, 6));
686 trgBlockNo
= param_get8(Cmd
, 4);
688 ctmp
= param_getchar(Cmd
, 5);
689 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
690 PrintAndLog("Target key type must be A or B");
693 if (ctmp
!= 'A' && ctmp
!= 'a')
696 parseParamTDS(Cmd
, 6, &transferToEml
, &createDumpFile
, &timeout14a
);
698 parseParamTDS(Cmd
, 4, &transferToEml
, &createDumpFile
, &timeout14a
);
701 PrintAndLog("--nested. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us",
702 SectorsCnt
, blockNo
, keyType
?'B':'A', transferToEml
?'y':'n', createDumpFile
?'y':'n', ((uint32_t)timeout14a
* 1000) / 106);
706 if (cmdp
== 'o') { // ------------------------------------ one sector working
707 PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo
, trgKeyType
?'B':'A');
708 int16_t isOK
= mfnested(blockNo
, keyType
, timeout14a
, key
, trgBlockNo
, trgKeyType
, keyBlock
, true);
711 case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
712 case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;
713 case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;
714 default : PrintAndLog("Unknown Error (%d)\n", isOK
);
718 key64
= bytes_to_num(keyBlock
, 6);
720 PrintAndLog("Found valid key:%012" PRIx64
, key64
);
722 // transfer key to the emulator
724 uint8_t sectortrailer
;
725 if (trgBlockNo
< 32*4) { // 4 block sector
726 sectortrailer
= trgBlockNo
| 0x03;
727 } else { // 16 block sector
728 sectortrailer
= trgBlockNo
| 0x0f;
730 mfEmlGetMem(keyBlock
, sectortrailer
, 1);
733 num_to_bytes(key64
, 6, keyBlock
);
735 num_to_bytes(key64
, 6, &keyBlock
[10]);
736 mfEmlSetMem(keyBlock
, sectortrailer
, 1);
737 PrintAndLog("Key transferred to emulator memory.");
740 PrintAndLog("No valid key found");
743 else { // ------------------------------------ multiple sectors working
745 msclock1
= msclock();
747 e_sector
= calloc(SectorsCnt
, sizeof(sector_t
));
748 if (e_sector
== NULL
) return 1;
750 //test current key and additional standard keys first
751 for (int defaultKeyCounter
= 0; defaultKeyCounter
< MifareDefaultKeysSize
; defaultKeyCounter
++){
752 num_to_bytes(MifareDefaultKeys
[defaultKeyCounter
], 6, (uint8_t*)(keyBlock
+ defaultKeyCounter
* 6));
755 PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt
);
756 mfCheckKeysSec(SectorsCnt
, 2, timeout14a
, true, true, true, MifareDefaultKeysSize
, keyBlock
, e_sector
);
758 // get known key from array
759 bool keyFound
= false;
761 for (i
= 0; i
< SectorsCnt
; i
++) {
762 for (j
= 0; j
< 2; j
++) {
763 if (e_sector
[i
].foundKey
[j
]) {
767 num_to_bytes(e_sector
[i
].Key
[j
], 6, key
);
775 // Can't found a key....
777 PrintAndLog("Can't found any of the known keys.");
781 PrintAndLog("--auto key. block no:%3d, key type:%c key:%s", blockNo
, keyType
?'B':'A', sprint_hex(key
, 6));
786 PrintAndLog("nested...");
787 bool calibrate
= true;
788 for (i
= 0; i
< NESTED_SECTOR_RETRY
; i
++) {
789 for (uint8_t sectorNo
= 0; sectorNo
< SectorsCnt
; sectorNo
++) {
790 for (trgKeyType
= 0; trgKeyType
< 2; trgKeyType
++) {
791 if (e_sector
[sectorNo
].foundKey
[trgKeyType
]) continue;
792 PrintAndLog("-----------------------------------------------");
793 int16_t isOK
= mfnested(blockNo
, keyType
, timeout14a
, key
, FirstBlockOfSector(sectorNo
), trgKeyType
, keyBlock
, calibrate
);
796 case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
797 case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;
798 case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;
799 default : PrintAndLog("Unknown Error (%d)\n", isOK
);
809 key64
= bytes_to_num(keyBlock
, 6);
811 PrintAndLog("Found valid key:%012" PRIx64
, key64
);
812 e_sector
[sectorNo
].foundKey
[trgKeyType
] = 1;
813 e_sector
[sectorNo
].Key
[trgKeyType
] = key64
;
815 // try to check this key as a key to the other sectors
816 mfCheckKeysSec(SectorsCnt
, 2, timeout14a
, true, true, true, 1, keyBlock
, e_sector
);
822 // print nested statistic
823 PrintAndLog("\n\n-----------------------------------------------\nNested statistic:\nIterations count: %d", iterations
);
824 PrintAndLog("Time in nested: %1.3f (%1.3f sec per key)", ((float)(msclock() - msclock1
))/1000.0, ((float)(msclock() - msclock1
))/iterations
/1000.0);
827 PrintAndLog("|---|----------------|---|----------------|---|");
828 PrintAndLog("|sec|key A |res|key B |res|");
829 PrintAndLog("|---|----------------|---|----------------|---|");
830 for (i
= 0; i
< SectorsCnt
; i
++) {
831 PrintAndLog("|%03d| %012" PRIx64
" | %d | %012" PRIx64
" | %d |", i
,
832 e_sector
[i
].Key
[0], e_sector
[i
].foundKey
[0], e_sector
[i
].Key
[1], e_sector
[i
].foundKey
[1]);
834 PrintAndLog("|---|----------------|---|----------------|---|");
836 // transfer keys to the emulator memory
838 for (i
= 0; i
< SectorsCnt
; i
++) {
839 mfEmlGetMem(keyBlock
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1);
840 if (e_sector
[i
].foundKey
[0])
841 num_to_bytes(e_sector
[i
].Key
[0], 6, keyBlock
);
842 if (e_sector
[i
].foundKey
[1])
843 num_to_bytes(e_sector
[i
].Key
[1], 6, &keyBlock
[10]);
844 mfEmlSetMem(keyBlock
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1);
846 PrintAndLog("Keys transferred to emulator memory.");
850 if (createDumpFile
) {
851 if ((fkeys
= fopen("dumpkeys.bin","wb")) == NULL
) {
852 PrintAndLog("Could not create file dumpkeys.bin");
856 PrintAndLog("Printing keys to binary file dumpkeys.bin...");
857 for(i
=0; i
<SectorsCnt
; i
++) {
858 if (e_sector
[i
].foundKey
[0]){
859 num_to_bytes(e_sector
[i
].Key
[0], 6, tempkey
);
860 fwrite ( tempkey
, 1, 6, fkeys
);
863 fwrite ( &standart
, 1, 6, fkeys
);
866 for(i
=0; i
<SectorsCnt
; i
++) {
867 if (e_sector
[i
].foundKey
[1]){
868 num_to_bytes(e_sector
[i
].Key
[1], 6, tempkey
);
869 fwrite ( tempkey
, 1, 6, fkeys
);
872 fwrite ( &standart
, 1, 6, fkeys
);
884 int CmdHF14AMfNestedHard(const char *Cmd
)
888 uint8_t trgBlockNo
= 0;
889 uint8_t trgKeyType
= 0;
890 uint8_t key
[6] = {0, 0, 0, 0, 0, 0};
891 uint8_t trgkey
[6] = {0, 0, 0, 0, 0, 0};
894 ctmp
= param_getchar(Cmd
, 0);
896 if (ctmp
!= 'R' && ctmp
!= 'r' && ctmp
!= 'T' && ctmp
!= 't' && strlen(Cmd
) < 20) {
897 PrintAndLog("Usage:");
898 PrintAndLog(" hf mf hardnested <block number> <key A|B> <key (12 hex symbols)>");
899 PrintAndLog(" <target block number> <target key A|B> [known target key (12 hex symbols)] [w] [s]");
900 PrintAndLog(" or hf mf hardnested r [known target key]");
902 PrintAndLog("Options: ");
903 PrintAndLog(" w: Acquire nonces and write them to binary file nonces.bin");
904 PrintAndLog(" s: Slower acquisition (required by some non standard cards)");
905 PrintAndLog(" r: Read nonces.bin and start attack");
906 PrintAndLog(" iX: set type of SIMD instructions. Without this flag programs autodetect it.");
907 PrintAndLog(" i5: AVX512");
908 PrintAndLog(" i2: AVX2");
909 PrintAndLog(" ia: AVX");
910 PrintAndLog(" is: SSE2");
911 PrintAndLog(" im: MMX");
912 PrintAndLog(" in: none (use CPU regular instruction set)");
914 PrintAndLog(" sample1: hf mf hardnested 0 A FFFFFFFFFFFF 4 A");
915 PrintAndLog(" sample2: hf mf hardnested 0 A FFFFFFFFFFFF 4 A w");
916 PrintAndLog(" sample3: hf mf hardnested 0 A FFFFFFFFFFFF 4 A w s");
917 PrintAndLog(" sample4: hf mf hardnested r");
919 PrintAndLog("Add the known target key to check if it is present in the remaining key space:");
920 PrintAndLog(" sample5: hf mf hardnested 0 A A0A1A2A3A4A5 4 A FFFFFFFFFFFF");
924 bool know_target_key
= false;
925 bool nonce_file_read
= false;
926 bool nonce_file_write
= false;
932 if (ctmp
== 'R' || ctmp
== 'r') {
933 nonce_file_read
= true;
935 if (!param_gethex(Cmd
, 1, trgkey
, 12)) {
936 know_target_key
= true;
939 } else if (ctmp
== 'T' || ctmp
== 't') {
940 tests
= param_get32ex(Cmd
, 1, 100, 10);
942 if (!param_gethex(Cmd
, 2, trgkey
, 12)) {
943 know_target_key
= true;
947 blockNo
= param_get8(Cmd
, 0);
948 ctmp
= param_getchar(Cmd
, 1);
949 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
950 PrintAndLog("Key type must be A or B");
953 if (ctmp
!= 'A' && ctmp
!= 'a') {
957 if (param_gethex(Cmd
, 2, key
, 12)) {
958 PrintAndLog("Key must include 12 HEX symbols");
962 trgBlockNo
= param_get8(Cmd
, 3);
963 ctmp
= param_getchar(Cmd
, 4);
964 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
965 PrintAndLog("Target key type must be A or B");
968 if (ctmp
!= 'A' && ctmp
!= 'a') {
974 if (!param_gethex(Cmd
, 5, trgkey
, 12)) {
975 know_target_key
= true;
980 while ((ctmp
= param_getchar(Cmd
, i
))) {
981 if (ctmp
== 's' || ctmp
== 'S') {
983 } else if (ctmp
== 'w' || ctmp
== 'W') {
984 nonce_file_write
= true;
985 } else if (param_getlength(Cmd
, i
) == 2 && ctmp
== 'i') {
988 PrintAndLog("Possible options are w , s and/or iX");
995 SetSIMDInstr(SIMD_AUTO
);
997 while ((ctmp
= param_getchar(Cmd
, iindx
))) {
998 if (param_getlength(Cmd
, iindx
) == 2 && ctmp
== 'i') {
999 switch(param_getchar_indx(Cmd
, 1, iindx
)) {
1001 SetSIMDInstr(SIMD_AVX512
);
1004 SetSIMDInstr(SIMD_AVX2
);
1007 SetSIMDInstr(SIMD_AVX
);
1010 SetSIMDInstr(SIMD_SSE2
);
1013 SetSIMDInstr(SIMD_MMX
);
1016 SetSIMDInstr(SIMD_NONE
);
1019 PrintAndLog("Unknown SIMD type. %c", param_getchar_indx(Cmd
, 1, iindx
));
1027 PrintAndLog("--target block no:%3d, target key type:%c, known target key: 0x%02x%02x%02x%02x%02x%02x%s, file action: %s, Slow: %s, Tests: %d ",
1030 trgkey
[0], trgkey
[1], trgkey
[2], trgkey
[3], trgkey
[4], trgkey
[5],
1031 know_target_key
?"":" (not set)",
1032 nonce_file_write
?"write":nonce_file_read
?"read":"none",
1036 int16_t isOK
= mfnestedhard(blockNo
, keyType
, key
, trgBlockNo
, trgKeyType
, know_target_key
?trgkey
:NULL
, nonce_file_read
, nonce_file_write
, slow
, tests
);
1040 case 1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
1041 case 2 : PrintAndLog("Button pressed. Aborted.\n"); break;
1051 int CmdHF14AMfChk(const char *Cmd
) {
1053 if (strlen(Cmd
)<3) {
1054 PrintAndLog("Usage: hf mf chk <block number>|<*card memory> <key type (A/B/?)> [t|d|s|ss] [<key (12 hex symbols)>] [<dic (*.dic)>]");
1055 PrintAndLog(" * - all sectors");
1056 PrintAndLog("card memory - 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other> - 1K");
1057 PrintAndLog("d - write keys to binary file (not used when <block number> supplied)");
1058 PrintAndLog("t - write keys to emulator memory");
1059 PrintAndLog("s - slow execute. timeout 1ms");
1060 PrintAndLog("ss - very slow execute. timeout 5ms");
1061 PrintAndLog(" sample: hf mf chk 0 A 1234567890ab keys.dic");
1062 PrintAndLog(" hf mf chk *1 ? t");
1063 PrintAndLog(" hf mf chk *1 ? d");
1064 PrintAndLog(" hf mf chk *1 ? s");
1065 PrintAndLog(" hf mf chk *1 ? dss");
1070 char filename
[FILE_PATH_SIZE
]={0};
1072 uint8_t *keyBlock
= NULL
, *p
;
1073 uint16_t stKeyBlock
= 20;
1078 uint8_t blockNo
= 0;
1079 uint8_t SectorsCnt
= 0;
1080 uint8_t keyType
= 0;
1082 // timeout in units. (ms * 106)/10 or us*0.0106
1083 uint16_t timeout14a
= MF_CHKKEYS_DEFTIMEOUT
; // fast by default
1084 bool param3InUse
= false;
1085 bool transferToEml
= 0;
1086 bool createDumpFile
= 0;
1087 bool singleBlock
= false; // Flag to ID if a single or multi key check
1088 uint8_t keyFoundCount
= 0; // Counter to display the number of keys found/transfered to emulator
1090 sector_t
*e_sector
= NULL
;
1092 keyBlock
= calloc(stKeyBlock
, 6);
1093 if (keyBlock
== NULL
) return 1;
1095 int defaultKeysSize
= MifareDefaultKeysSize
;
1096 for (int defaultKeyCounter
= 0; defaultKeyCounter
< defaultKeysSize
; defaultKeyCounter
++){
1097 num_to_bytes(MifareDefaultKeys
[defaultKeyCounter
], 6, (uint8_t*)(keyBlock
+ defaultKeyCounter
* 6));
1100 if (param_getchar(Cmd
, 0)=='*') {
1101 SectorsCnt
= ParamCardSizeSectors(param_getchar(Cmd
+ 1, 0));
1103 blockNo
= param_get8(Cmd
, 0);
1104 // Singe Key check, so Set Sector count to cover sectors (1 to sector that contains the block)
1105 // 1 and 2 Cards : Sector = blockNo/4 + 1
1106 // Sectors 0 - 31 : 4 blocks per sector : Blocks 0 - 127
1107 // Sectors 32 - 39 : 16 blocks per sector : Blocks 128 - 255 (4K)
1108 if (blockNo
< 128) {
1109 SectorsCnt
= (blockNo
/ 4) + 1;
1111 SectorsCnt
= 32 + ((blockNo
-128)/16) + 1;
1113 singleBlock
= true; // Set flag for single key check
1116 ctmp
= param_getchar(Cmd
, 1);
1117 clen
= param_getlength(Cmd
, 1);
1130 PrintAndLog("Key type must be A , B or ?");
1136 parseParamTDS(Cmd
, 2, &transferToEml
, &createDumpFile
, &timeout14a
);
1138 if (singleBlock
& createDumpFile
) {
1139 PrintAndLog (" block key check (<block no>) and write to dump file (d) combination is not supported ");
1140 PrintAndLog (" please remove option d and try again");
1144 param3InUse
= transferToEml
| createDumpFile
| (timeout14a
!= MF_CHKKEYS_DEFTIMEOUT
);
1146 PrintAndLog("--chk keys. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us",
1147 SectorsCnt
, blockNo
, keyType
==0?'A':keyType
==1?'B':'?', transferToEml
?'y':'n', createDumpFile
?'y':'n', ((uint32_t)timeout14a
* 1000) / 106);
1149 for (i
= param3InUse
; param_getchar(Cmd
, 2 + i
); i
++) {
1150 if (!param_gethex(Cmd
, 2 + i
, keyBlock
+ 6 * keycnt
, 12)) {
1151 if ( stKeyBlock
- keycnt
< 2) {
1152 p
= realloc(keyBlock
, 6*(stKeyBlock
+=10));
1154 PrintAndLog("Cannot allocate memory for Keys");
1160 PrintAndLog("chk key[%2d] %02x%02x%02x%02x%02x%02x", keycnt
,
1161 (keyBlock
+ 6*keycnt
)[0], (keyBlock
+ 6*keycnt
)[1], (keyBlock
+ 6*keycnt
)[2],
1162 (keyBlock
+ 6*keycnt
)[3], (keyBlock
+ 6*keycnt
)[4], (keyBlock
+ 6*keycnt
)[5], 6);
1165 // May be a dic file
1166 if ( param_getstr(Cmd
, 2 + i
, filename
, sizeof(filename
)) >= FILE_PATH_SIZE
) {
1167 PrintAndLog("File name too long");
1172 if ((f
= fopen( filename
, "r"))) {
1173 while (fgets(buf
, sizeof(buf
), f
)) {
1174 if (strlen(buf
) < 12 || buf
[11] == '\n')
1177 while (fgetc(f
) != '\n' && !feof(f
)) ; //goto next line
1179 if( buf
[0]=='#' ) continue; //The line start with # is comment, skip
1181 bool content_error
= false;
1182 for (int i
= 0; i
< 12; i
++) {
1183 if (!isxdigit((unsigned char)buf
[i
])) {
1184 content_error
= true;
1187 if (content_error
) {
1188 PrintAndLog("File content error. '%s' must include 12 HEX symbols", buf
);
1194 if (stKeyBlock
- keycnt
< 2) {
1195 p
= realloc(keyBlock
, 6*(stKeyBlock
+=10));
1197 PrintAndLog("Cannot allocate memory for defKeys");
1204 memset(keyBlock
+ 6 * keycnt
, 0, 6);
1205 num_to_bytes(strtoll(buf
, NULL
, 16), 6, keyBlock
+ 6*keycnt
);
1206 PrintAndLog("chk custom key[%2d] %012" PRIx64
, keycnt
, bytes_to_num(keyBlock
+ 6*keycnt
, 6));
1208 memset(buf
, 0, sizeof(buf
));
1212 PrintAndLog("File: %s: not found or locked.", filename
);
1219 // fill with default keys
1221 PrintAndLog("No key specified, trying default keys");
1222 for (;keycnt
< defaultKeysSize
; keycnt
++)
1223 PrintAndLog("chk default key[%2d] %02x%02x%02x%02x%02x%02x", keycnt
,
1224 (keyBlock
+ 6*keycnt
)[0], (keyBlock
+ 6*keycnt
)[1], (keyBlock
+ 6*keycnt
)[2],
1225 (keyBlock
+ 6*keycnt
)[3], (keyBlock
+ 6*keycnt
)[4], (keyBlock
+ 6*keycnt
)[5], 6);
1228 // initialize storage for found keys
1229 e_sector
= calloc(SectorsCnt
, sizeof(sector_t
));
1230 if (e_sector
== NULL
) {
1234 for (uint8_t keyAB
= 0; keyAB
< 2; keyAB
++) {
1235 for (uint16_t sectorNo
= 0; sectorNo
< SectorsCnt
; sectorNo
++) {
1236 e_sector
[sectorNo
].Key
[keyAB
] = 0xffffffffffff;
1237 e_sector
[sectorNo
].foundKey
[keyAB
] = 0;
1242 bool foundAKey
= false;
1243 bool clearTraceLog
= true;
1244 uint32_t max_keys
= keycnt
> USB_CMD_DATA_SIZE
/ 6 ? USB_CMD_DATA_SIZE
/ 6 : keycnt
;
1246 // !SingleKey, so all key check (if SectorsCnt > 0)
1248 PrintAndLog("To cancel this operation press the button on the proxmark...");
1250 for (uint32_t c
= 0; c
< keycnt
; c
+= max_keys
) {
1252 uint32_t size
= keycnt
-c
> max_keys
? max_keys
: keycnt
-c
;
1253 bool init
= (c
== 0);
1254 bool drop_field
= (c
+ size
== keycnt
);
1255 res
= mfCheckKeysSec(SectorsCnt
, keyType
, timeout14a
, clearTraceLog
, init
, drop_field
, size
, &keyBlock
[6 * c
], e_sector
); // timeout is (ms * 106)/10 or us*0.0106
1256 clearTraceLog
= false;
1267 PrintAndLog("Command execute timeout");
1271 int keyAB
= keyType
;
1273 res
= mfCheckKeys(blockNo
, keyAB
& 0x01, timeout14a
, true, keycnt
, keyBlock
, &key64
);
1274 clearTraceLog
= false;
1278 // Use the common format below
1279 // PrintAndLog("Found valid key:[%d:%c]%012" PRIx64, blockNo, (keyAB & 0x01)?'B':'A', key64);
1282 // Store the Single Key for display list
1283 // For a single block check, SectorsCnt = Sector that contains the block
1284 e_sector
[SectorsCnt
-1].foundKey
[(keyAB
& 0x01)] = true; // flag key found
1285 e_sector
[SectorsCnt
-1].Key
[(keyAB
& 0x01)] = key64
; // Save key data
1289 PrintAndLog("Command execute timeout");
1291 } while(--keyAB
> 0);
1297 PrintAndLog("|---|----------------|----------------|");
1298 PrintAndLog("|sec|key A |key B |");
1299 PrintAndLog("|---|----------------|----------------|");
1300 for (i
= 0; i
< SectorsCnt
; i
++) {
1301 // If a block key check, only print a line if a key was found.
1302 if (!singleBlock
|| e_sector
[i
].foundKey
[0] || e_sector
[i
].foundKey
[1]) {
1303 char keyAString
[13] = " ? ";
1304 char keyBString
[13] = " ? ";
1305 if (e_sector
[i
].foundKey
[0]) {
1306 sprintf(keyAString
, "%012" PRIx64
, e_sector
[i
].Key
[0]);
1308 if (e_sector
[i
].foundKey
[1]) {
1309 sprintf(keyBString
, "%012" PRIx64
, e_sector
[i
].Key
[1]);
1311 PrintAndLog("|%03d| %s | %s |", i
, keyAString
, keyBString
);
1314 PrintAndLog("|---|----------------|----------------|");
1317 PrintAndLog("No valid keys found.");
1320 if (transferToEml
) {
1322 for (uint16_t sectorNo
= 0; sectorNo
< SectorsCnt
; sectorNo
++) {
1323 if (e_sector
[sectorNo
].foundKey
[0] || e_sector
[sectorNo
].foundKey
[1]) {
1324 mfEmlGetMem(block
, FirstBlockOfSector(sectorNo
) + NumBlocksPerSector(sectorNo
) - 1, 1);
1325 for (uint16_t t
= 0; t
< 2; t
++) {
1326 if (e_sector
[sectorNo
].foundKey
[t
]) {
1327 num_to_bytes(e_sector
[sectorNo
].Key
[t
], 6, block
+ t
* 10);
1328 keyFoundCount
++; // Key found count for information
1331 mfEmlSetMem(block
, FirstBlockOfSector(sectorNo
) + NumBlocksPerSector(sectorNo
) - 1, 1);
1334 // Updated to show the actual number of keys found/transfered.
1335 PrintAndLog("%d keys(s) found have been transferred to the emulator memory",keyFoundCount
);
1338 if (createDumpFile
&& !singleBlock
) {
1339 FILE *fkeys
= fopen("dumpkeys.bin","wb");
1340 if (fkeys
== NULL
) {
1341 PrintAndLog("Could not create file dumpkeys.bin");
1347 for (uint8_t t
= 0; t
< 2; t
++) {
1348 for (uint8_t sectorNo
= 0; sectorNo
< SectorsCnt
; sectorNo
++) {
1349 num_to_bytes(e_sector
[sectorNo
].Key
[t
], 6, mkey
);
1350 fwrite(mkey
, 1, 6, fkeys
);
1354 PrintAndLog("Found keys have been dumped to file dumpkeys.bin. 0xffffffffffff has been inserted for unknown keys.");
1364 void readerAttack(nonces_t ar_resp
[], bool setEmulatorMem
, bool doStandardAttack
) {
1365 #define ATTACK_KEY_COUNT 7 // keep same as define in iso14443a.c -> Mifare1ksim()
1366 // cannot be more than 7 or it will overrun c.d.asBytes(512)
1372 st_t sector_trailer
[ATTACK_KEY_COUNT
];
1373 memset(sector_trailer
, 0x00, sizeof(sector_trailer
));
1375 uint8_t stSector
[ATTACK_KEY_COUNT
];
1376 memset(stSector
, 0x00, sizeof(stSector
));
1377 uint8_t key_cnt
[ATTACK_KEY_COUNT
];
1378 memset(key_cnt
, 0x00, sizeof(key_cnt
));
1380 for (uint8_t i
= 0; i
<ATTACK_KEY_COUNT
; i
++) {
1381 if (ar_resp
[i
].ar2
> 0) {
1382 //PrintAndLog("DEBUG: Trying sector %d, cuid %08x, nt %08x, ar %08x, nr %08x, ar2 %08x, nr2 %08x",ar_resp[i].sector, ar_resp[i].cuid,ar_resp[i].nonce,ar_resp[i].ar,ar_resp[i].nr,ar_resp[i].ar2,ar_resp[i].nr2);
1383 if (doStandardAttack
&& mfkey32(ar_resp
[i
], &key
)) {
1384 PrintAndLog(" Found Key%s for sector %02d: [%04x%08x]", (ar_resp
[i
].keytype
) ? "B" : "A", ar_resp
[i
].sector
, (uint32_t) (key
>>32), (uint32_t) (key
&0xFFFFFFFF));
1386 for (uint8_t ii
= 0; ii
<ATTACK_KEY_COUNT
; ii
++) {
1387 if (key_cnt
[ii
]==0 || stSector
[ii
]==ar_resp
[i
].sector
) {
1388 if (ar_resp
[i
].keytype
==0) {
1390 sector_trailer
[ii
].keyA
= key
;
1391 stSector
[ii
] = ar_resp
[i
].sector
;
1396 sector_trailer
[ii
].keyB
= key
;
1397 stSector
[ii
] = ar_resp
[i
].sector
;
1403 } else if (mfkey32_moebius(ar_resp
[i
+ATTACK_KEY_COUNT
], &key
)) {
1404 uint8_t sectorNum
= ar_resp
[i
+ATTACK_KEY_COUNT
].sector
;
1405 uint8_t keyType
= ar_resp
[i
+ATTACK_KEY_COUNT
].keytype
;
1407 PrintAndLog("M-Found Key%s for sector %02d: [%012" PRIx64
"]"
1408 , keyType
? "B" : "A"
1413 for (uint8_t ii
= 0; ii
<ATTACK_KEY_COUNT
; ii
++) {
1414 if (key_cnt
[ii
]==0 || stSector
[ii
]==sectorNum
) {
1417 sector_trailer
[ii
].keyA
= key
;
1418 stSector
[ii
] = sectorNum
;
1423 sector_trailer
[ii
].keyB
= key
;
1424 stSector
[ii
] = sectorNum
;
1434 //set emulator memory for keys
1435 if (setEmulatorMem
) {
1436 for (uint8_t i
= 0; i
<ATTACK_KEY_COUNT
; i
++) {
1438 uint8_t memBlock
[16];
1439 memset(memBlock
, 0x00, sizeof(memBlock
));
1441 memset(cmd1
,0x00,sizeof(cmd1
));
1442 snprintf(cmd1
,sizeof(cmd1
),"%04x%08xFF078069%04x%08x",(uint32_t) (sector_trailer
[i
].keyA
>>32), (uint32_t) (sector_trailer
[i
].keyA
&0xFFFFFFFF),(uint32_t) (sector_trailer
[i
].keyB
>>32), (uint32_t) (sector_trailer
[i
].keyB
&0xFFFFFFFF));
1443 PrintAndLog("Setting Emulator Memory Block %02d: [%s]",stSector
[i
]*4+3, cmd1
);
1444 if (param_gethex(cmd1
, 0, memBlock
, 32)) {
1445 PrintAndLog("block data must include 32 HEX symbols");
1449 UsbCommand c
= {CMD_MIFARE_EML_MEMSET
, {(stSector
[i
]*4+3), 1, 0}};
1450 memcpy(c
.d
.asBytes
, memBlock
, 16);
1451 clearCommandBuffer();
1457 //un-comment to use as well moebius attack
1458 for (uint8_t i = ATTACK_KEY_COUNT; i<ATTACK_KEY_COUNT*2; i++) {
1459 if (ar_resp[i].ar2 > 0) {
1460 if (tryMfk32_moebius(ar_resp[i], &key)) {
1461 PrintAndLog("M-Found Key%s for sector %02d: [%04x%08x]", (ar_resp[i].keytype) ? "B" : "A", ar_resp[i].sector, (uint32_t) (key>>32), (uint32_t) (key &0xFFFFFFFF));
1467 int usage_hf14_mfsim(void) {
1468 PrintAndLog("Usage: hf mf sim [h] [*<card memory>] [u <uid (8, 14, or 20 hex symbols)>] [n <numreads>] [i] [x]");
1469 PrintAndLog("options:");
1470 PrintAndLog(" h (Optional) this help");
1471 PrintAndLog(" card memory: 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other, default> - 1K");
1472 PrintAndLog(" u (Optional) UID 4 or 7 bytes. If not specified, the UID 4B from emulator memory will be used");
1473 PrintAndLog(" n (Optional) Automatically exit simulation after <numreads> blocks have been read by reader. 0 = infinite");
1474 PrintAndLog(" i (Optional) Interactive, means that console will not be returned until simulation finishes or is aborted");
1475 PrintAndLog(" x (Optional) Crack, performs the 'reader attack', nr/ar attack against a legitimate reader, fishes out the key(s)");
1476 PrintAndLog(" e (Optional) set keys found from 'reader attack' to emulator memory (implies x and i)");
1477 PrintAndLog(" f (Optional) get UIDs to use for 'reader attack' from file 'f <filename.txt>' (implies x and i)");
1478 PrintAndLog(" r (Optional) Generate random nonces instead of sequential nonces. Standard reader attack won't work with this option, only moebius attack works.");
1479 PrintAndLog("samples:");
1480 PrintAndLog(" hf mf sim u 0a0a0a0a");
1481 PrintAndLog(" hf mf sim *4");
1482 PrintAndLog(" hf mf sim u 11223344556677");
1483 PrintAndLog(" hf mf sim f uids.txt");
1484 PrintAndLog(" hf mf sim u 0a0a0a0a e");
1489 int CmdHF14AMfSim(const char *Cmd
) {
1491 uint8_t uid
[7] = {0};
1492 uint8_t exitAfterNReads
= 0;
1495 bool setEmulatorMem
= false;
1496 bool attackFromFile
= false;
1498 char filename
[FILE_PATH_SIZE
];
1499 memset(filename
, 0x00, sizeof(filename
));
1504 bool errors
= false;
1505 uint8_t cardsize
= '1';
1507 while(param_getchar(Cmd
, cmdp
) != 0x00) {
1508 switch(param_getchar(Cmd
, cmdp
)) {
1510 cardsize
= param_getchar(Cmd
+ 1, cmdp
);
1516 default: cardsize
= '1';
1522 setEmulatorMem
= true;
1524 flags
|= FLAG_INTERACTIVE
;
1525 flags
|= FLAG_NR_AR_ATTACK
;
1530 len
= param_getstr(Cmd
, cmdp
+1, filename
, sizeof(filename
));
1532 PrintAndLog("error no filename found");
1535 attackFromFile
= true;
1537 flags
|= FLAG_INTERACTIVE
;
1538 flags
|= FLAG_NR_AR_ATTACK
;
1543 return usage_hf14_mfsim();
1546 flags
|= FLAG_INTERACTIVE
;
1551 exitAfterNReads
= param_get8(Cmd
, cmdp
+1);
1556 flags
|= FLAG_RANDOM_NONCE
;
1562 if (param_gethex_ex(Cmd
, cmdp
+1, uid
, &uidlen
)) {
1563 return usage_hf14_mfsim();
1566 case 14: flags
= FLAG_7B_UID_IN_DATA
; break;
1567 case 8: flags
= FLAG_4B_UID_IN_DATA
; break;
1568 default: return usage_hf14_mfsim();
1574 flags
|= FLAG_NR_AR_ATTACK
;
1578 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd
, cmdp
));
1585 if(errors
) return usage_hf14_mfsim();
1588 if (attackFromFile
) {
1591 f
= fopen(filename
, "r");
1593 PrintAndLog("File %s not found or locked", filename
);
1596 PrintAndLog("Loading file and simulating. Press keyboard to abort");
1597 while(!feof(f
) && !ukbhit()){
1598 memset(buf
, 0, sizeof(buf
));
1599 memset(uid
, 0, sizeof(uid
));
1601 if (fgets(buf
, sizeof(buf
), f
) == NULL
) {
1602 if (count
> 0) break;
1604 PrintAndLog("File reading error.");
1608 if(!strlen(buf
) && feof(f
)) break;
1610 uidlen
= strlen(buf
)-1;
1612 case 14: flags
|= FLAG_7B_UID_IN_DATA
; break;
1613 case 8: flags
|= FLAG_4B_UID_IN_DATA
; break;
1615 PrintAndLog("uid in file wrong length at %d (length: %d) [%s]",count
, uidlen
, buf
);
1620 for (uint8_t i
= 0; i
< uidlen
; i
+= 2) {
1621 sscanf(&buf
[i
], "%02x", (unsigned int *)&uid
[i
/ 2]);
1624 PrintAndLog("mf sim cardsize: %s, uid: %s, numreads:%d, flags:%d (0x%02x) - press button to abort",
1625 cardsize
== '0' ? "Mini" :
1626 cardsize
== '2' ? "2K" :
1627 cardsize
== '4' ? "4K" : "1K",
1628 flags
& FLAG_4B_UID_IN_DATA
? sprint_hex(uid
,4):
1629 flags
& FLAG_7B_UID_IN_DATA
? sprint_hex(uid
,7): "N/A",
1634 UsbCommand c
= {CMD_SIMULATE_MIFARE_CARD
, {flags
, exitAfterNReads
, cardsize
}};
1635 memcpy(c
.d
.asBytes
, uid
, sizeof(uid
));
1636 clearCommandBuffer();
1639 while (! WaitForResponseTimeout(CMD_ACK
,&resp
,1500)) {
1640 //We're waiting only 1.5 s at a time, otherwise we get the
1641 // annoying message about "Waiting for a response... "
1644 nonces_t ar_resp
[ATTACK_KEY_COUNT
*2];
1645 memcpy(ar_resp
, resp
.d
.asBytes
, sizeof(ar_resp
));
1646 // We can skip the standard attack if we have RANDOM_NONCE set.
1647 readerAttack(ar_resp
, setEmulatorMem
, !(flags
& FLAG_RANDOM_NONCE
));
1648 if ((bool)resp
.arg
[1]) {
1649 PrintAndLog("Device button pressed - quitting");
1657 } else { //not from file
1659 PrintAndLog("mf sim cardsize: %s, uid: %s, numreads:%d, flags:%d (0x%02x) ",
1660 cardsize
== '0' ? "Mini" :
1661 cardsize
== '2' ? "2K" :
1662 cardsize
== '4' ? "4K" : "1K",
1663 flags
& FLAG_4B_UID_IN_DATA
? sprint_hex(uid
,4):
1664 flags
& FLAG_7B_UID_IN_DATA
? sprint_hex(uid
,7): "N/A",
1669 UsbCommand c
= {CMD_SIMULATE_MIFARE_CARD
, {flags
, exitAfterNReads
, cardsize
}};
1670 memcpy(c
.d
.asBytes
, uid
, sizeof(uid
));
1671 clearCommandBuffer();
1674 if(flags
& FLAG_INTERACTIVE
) {
1675 PrintAndLog("Press pm3-button to abort simulation");
1676 while(! WaitForResponseTimeout(CMD_ACK
, &resp
, 1500)) {
1677 //We're waiting only 1.5 s at a time, otherwise we get the
1678 // annoying message about "Waiting for a response... "
1681 if (flags
& FLAG_NR_AR_ATTACK
) {
1682 nonces_t ar_resp
[ATTACK_KEY_COUNT
*2];
1683 memcpy(ar_resp
, resp
.d
.asBytes
, sizeof(ar_resp
));
1684 // We can skip the standard attack if we have RANDOM_NONCE set.
1685 readerAttack(ar_resp
, setEmulatorMem
, !(flags
& FLAG_RANDOM_NONCE
));
1693 int CmdHF14AMfDbg(const char *Cmd
)
1695 int dbgMode
= param_get32ex(Cmd
, 0, 0, 10);
1697 PrintAndLog("Max debug mode parameter is 4 \n");
1700 if (strlen(Cmd
) < 1 || !param_getchar(Cmd
, 0) || dbgMode
> 4) {
1701 PrintAndLog("Usage: hf mf dbg <debug level>");
1702 PrintAndLog(" 0 - no debug messages");
1703 PrintAndLog(" 1 - error messages");
1704 PrintAndLog(" 2 - plus information messages");
1705 PrintAndLog(" 3 - plus debug messages");
1706 PrintAndLog(" 4 - print even debug messages in timing critical functions");
1707 PrintAndLog(" Note: this option therefore may cause malfunction itself");
1711 UsbCommand c
= {CMD_MIFARE_SET_DBGMODE
, {dbgMode
, 0, 0}};
1717 int CmdHF14AMfEGet(const char *Cmd
)
1719 uint8_t blockNo
= 0;
1720 uint8_t data
[16] = {0x00};
1722 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
1723 PrintAndLog("Usage: hf mf eget <block number>");
1724 PrintAndLog(" sample: hf mf eget 0 ");
1728 blockNo
= param_get8(Cmd
, 0);
1731 if (!mfEmlGetMem(data
, blockNo
, 1)) {
1732 PrintAndLog("data[%3d]:%s", blockNo
, sprint_hex(data
, 16));
1734 PrintAndLog("Command execute timeout");
1740 int CmdHF14AMfEClear(const char *Cmd
)
1742 if (param_getchar(Cmd
, 0) == 'h') {
1743 PrintAndLog("Usage: hf mf eclr");
1744 PrintAndLog("It set card emulator memory to empty data blocks and key A/B FFFFFFFFFFFF \n");
1748 UsbCommand c
= {CMD_MIFARE_EML_MEMCLR
, {0, 0, 0}};
1754 int CmdHF14AMfESet(const char *Cmd
)
1756 uint8_t memBlock
[16];
1757 uint8_t blockNo
= 0;
1759 memset(memBlock
, 0x00, sizeof(memBlock
));
1761 if (strlen(Cmd
) < 3 || param_getchar(Cmd
, 0) == 'h') {
1762 PrintAndLog("Usage: hf mf eset <block number> <block data (32 hex symbols)>");
1763 PrintAndLog(" sample: hf mf eset 1 000102030405060708090a0b0c0d0e0f ");
1767 blockNo
= param_get8(Cmd
, 0);
1769 if (param_gethex(Cmd
, 1, memBlock
, 32)) {
1770 PrintAndLog("block data must include 32 HEX symbols");
1775 return mfEmlSetMem(memBlock
, blockNo
, 1);
1779 int CmdHF14AMfELoad(const char *Cmd
)
1782 char filename
[FILE_PATH_SIZE
];
1783 char *fnameptr
= filename
;
1784 char buf
[64] = {0x00};
1785 uint8_t buf8
[64] = {0x00};
1786 int i
, len
, blockNum
, numBlocks
;
1787 int nameParamNo
= 1;
1789 char ctmp
= param_getchar(Cmd
, 0);
1791 if ( ctmp
== 'h' || ctmp
== 0x00) {
1792 PrintAndLog("It loads emul dump from the file `filename.eml`");
1793 PrintAndLog("Usage: hf mf eload [card memory] <file name w/o `.eml`>");
1794 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1796 PrintAndLog(" sample: hf mf eload filename");
1797 PrintAndLog(" hf mf eload 4 filename");
1802 case '0' : numBlocks
= 5*4; break;
1804 case '\0': numBlocks
= 16*4; break;
1805 case '2' : numBlocks
= 32*4; break;
1806 case '4' : numBlocks
= 256; break;
1813 len
= param_getstr(Cmd
, nameParamNo
, filename
, sizeof(filename
));
1815 if (len
> FILE_PATH_SIZE
- 5) len
= FILE_PATH_SIZE
- 5;
1819 sprintf(fnameptr
, ".eml");
1822 f
= fopen(filename
, "r");
1824 PrintAndLog("File %s not found or locked", filename
);
1830 memset(buf
, 0, sizeof(buf
));
1832 if (fgets(buf
, sizeof(buf
), f
) == NULL
) {
1834 if (blockNum
>= numBlocks
) break;
1836 PrintAndLog("File reading error.");
1841 if (strlen(buf
) < 32){
1842 if(strlen(buf
) && feof(f
))
1844 PrintAndLog("File content error. Block data must include 32 HEX symbols");
1849 for (i
= 0; i
< 32; i
+= 2) {
1850 sscanf(&buf
[i
], "%02x", (unsigned int *)&buf8
[i
/ 2]);
1853 if (mfEmlSetMem(buf8
, blockNum
, 1)) {
1854 PrintAndLog("Cant set emul block: %3d", blockNum
);
1861 if (blockNum
>= numBlocks
) break;
1866 if ((blockNum
!= numBlocks
)) {
1867 PrintAndLog("File content error. Got %d must be %d blocks.",blockNum
, numBlocks
);
1870 PrintAndLog("Loaded %d blocks from file: %s", blockNum
, filename
);
1875 int CmdHF14AMfESave(const char *Cmd
)
1878 char filename
[FILE_PATH_SIZE
];
1879 char * fnameptr
= filename
;
1881 int i
, j
, len
, numBlocks
;
1882 int nameParamNo
= 1;
1884 memset(filename
, 0, sizeof(filename
));
1885 memset(buf
, 0, sizeof(buf
));
1887 char ctmp
= param_getchar(Cmd
, 0);
1889 if ( ctmp
== 'h' || ctmp
== 'H') {
1890 PrintAndLog("It saves emul dump into the file `filename.eml` or `cardID.eml`");
1891 PrintAndLog(" Usage: hf mf esave [card memory] [file name w/o `.eml`]");
1892 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1894 PrintAndLog(" sample: hf mf esave ");
1895 PrintAndLog(" hf mf esave 4");
1896 PrintAndLog(" hf mf esave 4 filename");
1901 case '0' : numBlocks
= 5*4; break;
1903 case '\0': numBlocks
= 16*4; break;
1904 case '2' : numBlocks
= 32*4; break;
1905 case '4' : numBlocks
= 256; break;
1912 len
= param_getstr(Cmd
,nameParamNo
,filename
,sizeof(filename
));
1914 if (len
> FILE_PATH_SIZE
- 5) len
= FILE_PATH_SIZE
- 5;
1916 // user supplied filename?
1918 // get filename (UID from memory)
1919 if (mfEmlGetMem(buf
, 0, 1)) {
1920 PrintAndLog("Can\'t get UID from block: %d", 0);
1921 len
= sprintf(fnameptr
, "dump");
1925 for (j
= 0; j
< 7; j
++, fnameptr
+= 2)
1926 sprintf(fnameptr
, "%02X", buf
[j
]);
1932 // add file extension
1933 sprintf(fnameptr
, ".eml");
1936 f
= fopen(filename
, "w+");
1939 PrintAndLog("Can't open file %s ", filename
);
1944 for (i
= 0; i
< numBlocks
; i
++) {
1945 if (mfEmlGetMem(buf
, i
, 1)) {
1946 PrintAndLog("Cant get block: %d", i
);
1949 for (j
= 0; j
< 16; j
++)
1950 fprintf(f
, "%02X", buf
[j
]);
1955 PrintAndLog("Saved %d blocks to file: %s", numBlocks
, filename
);
1961 int CmdHF14AMfECFill(const char *Cmd
)
1963 uint8_t keyType
= 0;
1964 uint8_t numSectors
= 16;
1966 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
1967 PrintAndLog("Usage: hf mf ecfill <key A/B> [card memory]");
1968 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1970 PrintAndLog("samples: hf mf ecfill A");
1971 PrintAndLog(" hf mf ecfill A 4");
1972 PrintAndLog("Read card and transfer its data to emulator memory.");
1973 PrintAndLog("Keys must be laid in the emulator memory. \n");
1977 char ctmp
= param_getchar(Cmd
, 0);
1978 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
1979 PrintAndLog("Key type must be A or B");
1982 if (ctmp
!= 'A' && ctmp
!= 'a') keyType
= 1;
1984 ctmp
= param_getchar(Cmd
, 1);
1986 case '0' : numSectors
= 5; break;
1988 case '\0': numSectors
= 16; break;
1989 case '2' : numSectors
= 32; break;
1990 case '4' : numSectors
= 40; break;
1991 default: numSectors
= 16;
1994 printf("--params: numSectors: %d, keyType:%d\n", numSectors
, keyType
);
1995 UsbCommand c
= {CMD_MIFARE_EML_CARDLOAD
, {numSectors
, keyType
, 0}};
2001 int CmdHF14AMfEKeyPrn(const char *Cmd
)
2004 uint8_t numSectors
= 16;
2006 uint64_t keyA
, keyB
;
2007 bool createDumpFile
= false;
2009 if (param_getchar(Cmd
, 0) == 'h') {
2010 PrintAndLog("It prints the keys loaded in the emulator memory");
2011 PrintAndLog("Usage: hf mf ekeyprn [card memory] [d]");
2012 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
2013 PrintAndLog(" [d] : write keys to binary file dumpkeys.bin");
2015 PrintAndLog(" sample: hf mf ekeyprn 1");
2020 while (param_getchar(Cmd
, cmdp
) != 0x00) {
2021 switch (param_getchar(Cmd
, cmdp
)) {
2022 case '0' : numSectors
= 5; break;
2024 case '\0': numSectors
= 16; break;
2025 case '2' : numSectors
= 32; break;
2026 case '4' : numSectors
= 40; break;
2028 case 'D' : createDumpFile
= true; break;
2033 PrintAndLog("|---|----------------|----------------|");
2034 PrintAndLog("|sec|key A |key B |");
2035 PrintAndLog("|---|----------------|----------------|");
2036 for (i
= 0; i
< numSectors
; i
++) {
2037 if (mfEmlGetMem(data
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1)) {
2038 PrintAndLog("error get block %d", FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1);
2041 keyA
= bytes_to_num(data
, 6);
2042 keyB
= bytes_to_num(data
+ 10, 6);
2043 PrintAndLog("|%03d| %012" PRIx64
" | %012" PRIx64
" |", i
, keyA
, keyB
);
2045 PrintAndLog("|---|----------------|----------------|");
2048 if (createDumpFile
) {
2050 if ((fkeys
= fopen("dumpkeys.bin","wb")) == NULL
) {
2051 PrintAndLog("Could not create file dumpkeys.bin");
2054 PrintAndLog("Printing keys to binary file dumpkeys.bin...");
2055 for(i
= 0; i
< numSectors
; i
++) {
2056 if (mfEmlGetMem(data
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1)) {
2057 PrintAndLog("error get block %d", FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1);
2060 fwrite(data
, 1, 6, fkeys
);
2062 for(i
= 0; i
< numSectors
; i
++) {
2063 if (mfEmlGetMem(data
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1)) {
2064 PrintAndLog("error get block %d", FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1);
2067 fwrite(data
+10, 1, 6, fkeys
);
2076 int CmdHF14AMfCSetUID(const char *Cmd
)
2078 uint8_t uid
[8] = {0x00};
2079 uint8_t oldUid
[8] = {0x00};
2080 uint8_t atqa
[2] = {0x00};
2081 uint8_t sak
[1] = {0x00};
2082 uint8_t atqaPresent
= 0;
2085 uint8_t needHelp
= 0;
2088 if (param_getchar(Cmd
, 0) && param_gethex(Cmd
, 0, uid
, 8)) {
2089 PrintAndLog("UID must include 8 HEX symbols");
2093 if (param_getlength(Cmd
, 1) > 1 && param_getlength(Cmd
, 2) > 1) {
2097 if (param_gethex(Cmd
, 1, atqa
, 4)) {
2098 PrintAndLog("ATQA must include 4 HEX symbols");
2102 if (param_gethex(Cmd
, 2, sak
, 2)) {
2103 PrintAndLog("SAK must include 2 HEX symbols");
2108 while(param_getchar(Cmd
, cmdp
) != 0x00)
2110 switch(param_getchar(Cmd
, cmdp
))
2117 PrintAndLog("ERROR: Unknown parameter '%c'", param_getchar(Cmd
, cmdp
));
2124 if (strlen(Cmd
) < 1 || needHelp
) {
2126 PrintAndLog("Usage: hf mf csetuid <UID 8 hex symbols> [ATQA 4 hex symbols SAK 2 hex symbols]");
2127 PrintAndLog("sample: hf mf csetuid 01020304");
2128 PrintAndLog("sample: hf mf csetuid 01020304 0004 08");
2129 PrintAndLog("Set UID, ATQA, and SAK for magic Chinese card (only works with such cards)");
2133 PrintAndLog("uid:%s", sprint_hex(uid
, 4));
2135 PrintAndLog("--atqa:%s sak:%02x", sprint_hex(atqa
, 2), sak
[0]);
2138 res
= mfCSetUID(uid
, (atqaPresent
)?atqa
:NULL
, (atqaPresent
)?sak
:NULL
, oldUid
);
2140 PrintAndLog("Can't set UID. Error=%d", res
);
2144 PrintAndLog("old UID:%s", sprint_hex(oldUid
, 4));
2145 PrintAndLog("new UID:%s", sprint_hex(uid
, 4));
2149 int CmdHF14AMfCWipe(const char *Cmd
)
2152 int numBlocks
= 16 * 4;
2153 bool wipeCard
= false;
2154 bool fillCard
= false;
2156 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
2157 PrintAndLog("Usage: hf mf cwipe [card size] [w] [f]");
2158 PrintAndLog("sample: hf mf cwipe 1 w f");
2159 PrintAndLog("[card size]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
2160 PrintAndLog("w - Wipe magic Chinese card (only works with gen:1a cards)");
2161 PrintAndLog("f - Fill the card with default data and keys (works with gen:1a and gen:1b cards only)");
2165 gen
= mfCIdentify();
2166 if ((gen
!= 1) && (gen
!= 2))
2169 numBlocks
= ParamCardSizeBlocks(param_getchar(Cmd
, 0));
2172 while(param_getchar(Cmd
, cmdp
) != 0x00){
2173 switch(param_getchar(Cmd
, cmdp
)) {
2188 if (!wipeCard
&& !fillCard
)
2191 PrintAndLog("--blocks count:%2d wipe:%c fill:%c", numBlocks
, (wipeCard
)?'y':'n', (fillCard
)?'y':'n');
2194 /* generation 1b magic card */
2196 PrintAndLog("WARNING: can't wipe magic card 1b generation");
2198 res
= mfCWipe(numBlocks
, true, false, fillCard
);
2200 /* generation 1a magic card by default */
2201 res
= mfCWipe(numBlocks
, false, wipeCard
, fillCard
);
2205 PrintAndLog("Can't wipe. error=%d", res
);
2212 int CmdHF14AMfCSetBlk(const char *Cmd
)
2214 uint8_t memBlock
[16] = {0x00};
2215 uint8_t blockNo
= 0;
2216 bool wipeCard
= false;
2219 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
2220 PrintAndLog("Usage: hf mf csetblk <block number> <block data (32 hex symbols)> [w]");
2221 PrintAndLog("sample: hf mf csetblk 1 01020304050607080910111213141516");
2222 PrintAndLog("Set block data for magic Chinese card (only works with such cards)");
2223 PrintAndLog("If you also want wipe the card then add 'w' at the end of the command line");
2227 gen
= mfCIdentify();
2228 if ((gen
!= 1) && (gen
!= 2))
2231 blockNo
= param_get8(Cmd
, 0);
2233 if (param_gethex(Cmd
, 1, memBlock
, 32)) {
2234 PrintAndLog("block data must include 32 HEX symbols");
2238 char ctmp
= param_getchar(Cmd
, 2);
2239 wipeCard
= (ctmp
== 'w' || ctmp
== 'W');
2240 PrintAndLog("--block number:%2d data:%s", blockNo
, sprint_hex(memBlock
, 16));
2243 /* generation 1b magic card */
2244 res
= mfCSetBlock(blockNo
, memBlock
, NULL
, wipeCard
, CSETBLOCK_SINGLE_OPER
| CSETBLOCK_MAGIC_1B
);
2246 /* generation 1a magic card by default */
2247 res
= mfCSetBlock(blockNo
, memBlock
, NULL
, wipeCard
, CSETBLOCK_SINGLE_OPER
);
2251 PrintAndLog("Can't write block. error=%d", res
);
2258 int CmdHF14AMfCLoad(const char *Cmd
)
2261 char filename
[FILE_PATH_SIZE
] = {0x00};
2262 char * fnameptr
= filename
;
2263 char buf
[256] = {0x00};
2264 uint8_t buf8
[256] = {0x00};
2265 uint8_t fillFromEmulator
= 0;
2266 int i
, len
, blockNum
, flags
= 0, gen
= 0, numblock
= 64;
2268 if (param_getchar(Cmd
, 0) == 'h' || param_getchar(Cmd
, 0)== 0x00) {
2269 PrintAndLog("It loads magic Chinese card from the file `filename.eml`");
2270 PrintAndLog("or from emulator memory (option `e`). 4K card: (option `4`)");
2271 PrintAndLog("Usage: hf mf cload [file name w/o `.eml`][e][4]");
2272 PrintAndLog(" or: hf mf cload e [4]");
2273 PrintAndLog("Sample: hf mf cload filename");
2274 PrintAndLog(" hf mf cload filname 4");
2275 PrintAndLog(" hf mf cload e");
2276 PrintAndLog(" hf mf cload e 4");
2280 char ctmp
= param_getchar(Cmd
, 0);
2281 if (ctmp
== 'e' || ctmp
== 'E') fillFromEmulator
= 1;
2282 ctmp
= param_getchar(Cmd
, 1);
2283 if (ctmp
== '4') numblock
= 256;
2285 gen
= mfCIdentify();
2286 PrintAndLog("Loading magic mifare %dK", numblock
== 256 ? 4:1);
2288 if (fillFromEmulator
) {
2289 for (blockNum
= 0; blockNum
< numblock
; blockNum
+= 1) {
2290 if (mfEmlGetMem(buf8
, blockNum
, 1)) {
2291 PrintAndLog("Cant get block: %d", blockNum
);
2294 if (blockNum
== 0) flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
; // switch on field and send magic sequence
2295 if (blockNum
== 1) flags
= 0; // just write
2296 if (blockNum
== numblock
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
; // Done. Magic Halt and switch off field.
2299 /* generation 1b magic card */
2300 flags
|= CSETBLOCK_MAGIC_1B
;
2301 if (mfCSetBlock(blockNum
, buf8
, NULL
, 0, flags
)) {
2302 PrintAndLog("Cant set magic card block: %d", blockNum
);
2308 param_getstr(Cmd
, 0, filename
, sizeof(filename
));
2310 len
= strlen(filename
);
2311 if (len
> FILE_PATH_SIZE
- 5) len
= FILE_PATH_SIZE
- 5;
2313 //memcpy(filename, Cmd, len);
2316 sprintf(fnameptr
, ".eml");
2319 f
= fopen(filename
, "r");
2321 PrintAndLog("File not found or locked.");
2328 memset(buf
, 0, sizeof(buf
));
2330 if (fgets(buf
, sizeof(buf
), f
) == NULL
) {
2332 PrintAndLog("File reading error.");
2336 if (strlen(buf
) < 32) {
2337 if(strlen(buf
) && feof(f
))
2339 PrintAndLog("File content error. Block data must include 32 HEX symbols");
2343 for (i
= 0; i
< 32; i
+= 2)
2344 sscanf(&buf
[i
], "%02x", (unsigned int *)&buf8
[i
/ 2]);
2346 if (blockNum
== 0) flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
; // switch on field and send magic sequence
2347 if (blockNum
== 1) flags
= 0; // just write
2348 if (blockNum
== numblock
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
; // Done. Switch off field.
2351 /* generation 1b magic card */
2352 flags
|= CSETBLOCK_MAGIC_1B
;
2353 if (mfCSetBlock(blockNum
, buf8
, NULL
, 0, flags
)) {
2354 PrintAndLog("Can't set magic card block: %d", blockNum
);
2360 if (blockNum
>= numblock
) break; // magic card type - mifare 1K 64 blocks, mifare 4k 256 blocks
2364 //if (blockNum != 16 * 4 && blockNum != 32 * 4 + 8 * 16){
2365 if (blockNum
!= numblock
){
2366 PrintAndLog("File content error. There must be %d blocks", numblock
);
2369 PrintAndLog("Loaded from file: %s", filename
);
2375 int CmdHF14AMfCGetBlk(const char *Cmd
) {
2376 uint8_t memBlock
[16];
2377 uint8_t blockNo
= 0;
2379 memset(memBlock
, 0x00, sizeof(memBlock
));
2381 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
2382 PrintAndLog("Usage: hf mf cgetblk <block number>");
2383 PrintAndLog("sample: hf mf cgetblk 1");
2384 PrintAndLog("Get block data from magic Chinese card (only works with such cards)\n");
2388 gen
= mfCIdentify();
2390 blockNo
= param_get8(Cmd
, 0);
2392 PrintAndLog("--block number:%2d ", blockNo
);
2395 /* generation 1b magic card */
2396 res
= mfCGetBlock(blockNo
, memBlock
, CSETBLOCK_SINGLE_OPER
| CSETBLOCK_MAGIC_1B
);
2398 /* generation 1a magic card by default */
2399 res
= mfCGetBlock(blockNo
, memBlock
, CSETBLOCK_SINGLE_OPER
);
2402 PrintAndLog("Can't read block. error=%d", res
);
2406 PrintAndLog("block data:%s", sprint_hex(memBlock
, 16));
2408 if (mfIsSectorTrailer(blockNo
)) {
2409 PrintAndLogEx(NORMAL
, "Trailer decoded:");
2410 PrintAndLogEx(NORMAL
, "Key A: %s", sprint_hex_inrow(memBlock
, 6));
2411 PrintAndLogEx(NORMAL
, "Key B: %s", sprint_hex_inrow(&memBlock
[10], 6));
2412 int bln
= mfFirstBlockOfSector(mfSectorNum(blockNo
));
2413 int blinc
= (mfNumBlocksPerSector(mfSectorNum(blockNo
)) > 4) ? 5 : 1;
2414 for (int i
= 0; i
< 4; i
++) {
2415 PrintAndLogEx(NORMAL
, "Access block %d%s: %s", bln
, ((blinc
> 1) && (i
< 3) ? "+" : "") , mfGetAccessConditionsDesc(i
, &memBlock
[6]));
2418 PrintAndLogEx(NORMAL
, "UserData: %s", sprint_hex_inrow(&memBlock
[9], 1));
2424 int CmdHF14AMfCGetSc(const char *Cmd
) {
2425 uint8_t memBlock
[16] = {0x00};
2426 uint8_t sectorNo
= 0;
2427 int i
, res
, flags
, gen
= 0, baseblock
= 0, sect_size
= 4;
2429 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
2430 PrintAndLog("Usage: hf mf cgetsc <sector number>");
2431 PrintAndLog("sample: hf mf cgetsc 0");
2432 PrintAndLog("Get sector data from magic Chinese card (only works with such cards)\n");
2436 sectorNo
= param_get8(Cmd
, 0);
2438 if (sectorNo
> 39) {
2439 PrintAndLog("Sector number must be in [0..15] in MIFARE classic 1k and [0..39] in MIFARE classic 4k.");
2443 PrintAndLog("--sector number:%d ", sectorNo
);
2445 gen
= mfCIdentify();
2447 flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
;
2448 if (sectorNo
< 32 ) {
2449 baseblock
= sectorNo
* 4;
2451 baseblock
= 128 + 16 * (sectorNo
- 32);
2454 if (sectorNo
> 31) sect_size
= 16;
2456 for (i
= 0; i
< sect_size
; i
++) {
2457 if (i
== 1) flags
= 0;
2458 if (i
== sect_size
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
;
2461 /* generation 1b magic card */
2462 flags
|= CSETBLOCK_MAGIC_1B
;
2464 res
= mfCGetBlock(baseblock
+ i
, memBlock
, flags
);
2466 PrintAndLog("Can't read block. %d error=%d", baseblock
+ i
, res
);
2470 PrintAndLog("block %3d data:%s", baseblock
+ i
, sprint_hex(memBlock
, 16));
2472 if (mfIsSectorTrailer(baseblock
+ i
)) {
2473 PrintAndLogEx(NORMAL
, "Trailer decoded:");
2474 PrintAndLogEx(NORMAL
, "Key A: %s", sprint_hex_inrow(memBlock
, 6));
2475 PrintAndLogEx(NORMAL
, "Key B: %s", sprint_hex_inrow(&memBlock
[10], 6));
2476 int bln
= baseblock
;
2477 int blinc
= (mfNumBlocksPerSector(sectorNo
) > 4) ? 5 : 1;
2478 for (int i
= 0; i
< 4; i
++) {
2479 PrintAndLogEx(NORMAL
, "Access block %d%s: %s", bln
, ((blinc
> 1) && (i
< 3) ? "+" : "") , mfGetAccessConditionsDesc(i
, &memBlock
[6]));
2482 PrintAndLogEx(NORMAL
, "UserData: %s", sprint_hex_inrow(&memBlock
[9], 1));
2489 int CmdHF14AMfCSave(const char *Cmd
) {
2492 char filename
[FILE_PATH_SIZE
] = {0x00};
2493 char * fnameptr
= filename
;
2494 uint8_t fillFromEmulator
= 0;
2495 uint8_t buf
[256] = {0x00};
2496 int i
, j
, len
, flags
, gen
= 0, numblock
= 64;
2498 // memset(filename, 0, sizeof(filename));
2499 // memset(buf, 0, sizeof(buf));
2501 if (param_getchar(Cmd
, 0) == 'h') {
2502 PrintAndLog("It saves `magic Chinese` card dump into the file `filename.eml` or `cardID.eml`");
2503 PrintAndLog("or into emulator memory (option `e`). 4K card: (option `4`)");
2504 PrintAndLog("Usage: hf mf csave [file name w/o `.eml`][e][4]");
2505 PrintAndLog("Sample: hf mf csave ");
2506 PrintAndLog(" hf mf csave filename");
2507 PrintAndLog(" hf mf csave e");
2508 PrintAndLog(" hf mf csave 4");
2509 PrintAndLog(" hf mf csave filename 4");
2510 PrintAndLog(" hf mf csave e 4");
2514 char ctmp
= param_getchar(Cmd
, 0);
2515 if (ctmp
== 'e' || ctmp
== 'E') fillFromEmulator
= 1;
2516 if (ctmp
== '4') numblock
= 256;
2517 ctmp
= param_getchar(Cmd
, 1);
2518 if (ctmp
== '4') numblock
= 256;
2520 gen
= mfCIdentify();
2521 PrintAndLog("Saving magic mifare %dK", numblock
== 256 ? 4:1);
2523 if (fillFromEmulator
) {
2524 // put into emulator
2525 flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
;
2526 for (i
= 0; i
< numblock
; i
++) {
2527 if (i
== 1) flags
= 0;
2528 if (i
== numblock
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
;
2531 /* generation 1b magic card */
2532 flags
|= CSETBLOCK_MAGIC_1B
;
2534 if (mfCGetBlock(i
, buf
, flags
)) {
2535 PrintAndLog("Cant get block: %d", i
);
2539 if (mfEmlSetMem(buf
, i
, 1)) {
2540 PrintAndLog("Cant set emul block: %d", i
);
2546 param_getstr(Cmd
, 0, filename
, sizeof(filename
));
2548 len
= strlen(filename
);
2549 if (len
> FILE_PATH_SIZE
- 5) len
= FILE_PATH_SIZE
- 5;
2551 ctmp
= param_getchar(Cmd
, 0);
2552 if (len
< 1 || (ctmp
== '4')) {
2555 flags
= CSETBLOCK_SINGLE_OPER
;
2557 /* generation 1b magic card */
2558 flags
|= CSETBLOCK_MAGIC_1B
;
2559 if (mfCGetBlock(0, buf
, flags
)) {
2560 PrintAndLog("Cant get block: %d", 0);
2561 len
= sprintf(fnameptr
, "dump");
2565 for (j
= 0; j
< 7; j
++, fnameptr
+= 2)
2566 sprintf(fnameptr
, "%02x", buf
[j
]);
2569 //memcpy(filename, Cmd, len);
2573 sprintf(fnameptr
, ".eml");
2576 f
= fopen(filename
, "w+");
2579 PrintAndLog("File not found or locked.");
2584 flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
;
2585 for (i
= 0; i
< numblock
; i
++) {
2586 if (i
== 1) flags
= 0;
2587 if (i
== numblock
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
;
2590 /* generation 1b magic card */
2591 flags
|= CSETBLOCK_MAGIC_1B
;
2592 if (mfCGetBlock(i
, buf
, flags
)) {
2593 PrintAndLog("Cant get block: %d", i
);
2596 for (j
= 0; j
< 16; j
++)
2597 fprintf(f
, "%02x", buf
[j
]);
2602 PrintAndLog("Saved to file: %s", filename
);
2609 int CmdHF14AMfSniff(const char *Cmd
){
2611 bool wantLogToFile
= 0;
2612 bool wantDecrypt
= 0;
2613 //bool wantSaveToEml = 0; TODO
2614 bool wantSaveToEmlFile
= 0;
2625 uint8_t atqa
[2] = {0x00};
2628 uint8_t *buf
= NULL
;
2629 uint16_t bufsize
= 0;
2630 uint8_t *bufPtr
= NULL
;
2633 char ctmp
= param_getchar(Cmd
, 0);
2634 if ( ctmp
== 'h' || ctmp
== 'H' ) {
2635 PrintAndLog("It continuously gets data from the field and saves it to: log, emulator, emulator file.");
2636 PrintAndLog("You can specify:");
2637 PrintAndLog(" l - save encrypted sequence to logfile `uid.log`");
2638 PrintAndLog(" d - decrypt sequence and put it to log file `uid.log`");
2639 PrintAndLog(" n/a e - decrypt sequence, collect read and write commands and save the result of the sequence to emulator memory");
2640 PrintAndLog(" f - decrypt sequence, collect read and write commands and save the result of the sequence to emulator dump file `uid.eml`");
2641 PrintAndLog("Usage: hf mf sniff [l][d][e][f]");
2642 PrintAndLog(" sample: hf mf sniff l d e");
2646 for (int i
= 0; i
< 4; i
++) {
2647 ctmp
= param_getchar(Cmd
, i
);
2648 if (ctmp
== 'l' || ctmp
== 'L') wantLogToFile
= true;
2649 if (ctmp
== 'd' || ctmp
== 'D') wantDecrypt
= true;
2650 //if (ctmp == 'e' || ctmp == 'E') wantSaveToEml = true; TODO
2651 if (ctmp
== 'f' || ctmp
== 'F') wantSaveToEmlFile
= true;
2654 printf("-------------------------------------------------------------------------\n");
2655 printf("Executing command. \n");
2656 printf("Press the key on the proxmark3 device to abort both proxmark3 and client.\n");
2657 printf("Press the key on pc keyboard to abort the client.\n");
2658 printf("-------------------------------------------------------------------------\n");
2660 UsbCommand c
= {CMD_MIFARE_SNIFFER
, {0, 0, 0}};
2661 clearCommandBuffer();
2670 printf("\naborted via keyboard!\n");
2675 if (WaitForResponseTimeoutW(CMD_UNKNOWN
, &resp
, 2000, false)) {
2676 res
= resp
.arg
[0] & 0xff;
2677 uint16_t traceLen
= resp
.arg
[1];
2680 if (res
== 0) { // we are done
2684 if (res
== 1) { // there is (more) data to be transferred
2685 if (pckNum
== 0) { // first packet, (re)allocate necessary buffer
2686 if (traceLen
> bufsize
|| buf
== NULL
) {
2688 if (buf
== NULL
) { // not yet allocated
2689 p
= malloc(traceLen
);
2690 } else { // need more memory
2691 p
= realloc(buf
, traceLen
);
2694 PrintAndLog("Cannot allocate memory for trace");
2702 memset(buf
, 0x00, traceLen
);
2704 memcpy(bufPtr
, resp
.d
.asBytes
, len
);
2709 if (res
== 2) { // received all data, start displaying
2710 blockLen
= bufPtr
- buf
;
2713 PrintAndLog("received trace len: %d packages: %d", blockLen
, pckNum
);
2714 while (bufPtr
- buf
< blockLen
) {
2715 bufPtr
+= 6; // skip (void) timing information
2716 len
= *((uint16_t *)bufPtr
);
2723 parlen
= (len
- 1) / 8 + 1;
2725 if ((len
== 14) && (bufPtr
[0] == 0xff) && (bufPtr
[1] == 0xff) && (bufPtr
[12] == 0xff) && (bufPtr
[13] == 0xff)) {
2726 memcpy(uid
, bufPtr
+ 2, 7);
2727 memcpy(atqa
, bufPtr
+ 2 + 7, 2);
2728 uid_len
= (atqa
[0] & 0xC0) == 0x40 ? 7 : 4;
2730 PrintAndLog("tag select uid:%s atqa:0x%02x%02x sak:0x%02x",
2731 sprint_hex(uid
+ (7 - uid_len
), uid_len
),
2735 if (wantLogToFile
|| wantDecrypt
) {
2736 FillFileNameByUID(logHexFileName
, uid
+ (7 - uid_len
), ".log", uid_len
);
2737 AddLogCurrentDT(logHexFileName
);
2740 mfTraceInit(uid
, atqa
, sak
, wantSaveToEmlFile
);
2742 oddparitybuf(bufPtr
, len
, parity
);
2743 PrintAndLog("%s(%d):%s [%s] c[%s]%c",
2744 isTag
? "TAG":"RDR",
2746 sprint_hex(bufPtr
, len
),
2747 printBitsPar(bufPtr
+ len
, len
),
2748 printBitsPar(parity
, len
),
2749 memcmp(bufPtr
+ len
, parity
, len
/ 8 + 1) ? '!' : ' ');
2751 AddLogHex(logHexFileName
, isTag
? "TAG: ":"RDR: ", bufPtr
, len
);
2753 mfTraceDecode(bufPtr
, len
, bufPtr
[len
], wantSaveToEmlFile
);
2757 bufPtr
+= parlen
; // ignore parity
2766 msleep(300); // wait for exiting arm side.
2767 PrintAndLog("Done.");
2771 //needs nt, ar, at, Data to decrypt
2772 int CmdDecryptTraceCmds(const char *Cmd
){
2775 param_gethex_ex(Cmd
, 3, data
, &len
);
2776 return tryDecryptWord(param_get32ex(Cmd
, 0, 0, 16), param_get32ex(Cmd
, 1, 0, 16), param_get32ex(Cmd
, 2, 0, 16), data
, len
/2);
2779 int CmdHF14AMfAuth4(const char *cmd
) {
2780 uint8_t keyn
[20] = {0};
2782 uint8_t key
[16] = {0};
2785 CLIParserInit("hf mf auth4",
2786 "Executes AES authentication command in ISO14443-4",
2787 "Usage:\n\thf mf auth4 4000 000102030405060708090a0b0c0d0e0f -> executes authentication\n"
2788 "\thf mf auth4 9003 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -> executes authentication\n");
2790 void* argtable
[] = {
2792 arg_str1(NULL
, NULL
, "<Key Num (HEX 2 bytes)>", NULL
),
2793 arg_str1(NULL
, NULL
, "<Key Value (HEX 16 bytes)>", NULL
),
2796 CLIExecWithReturn(cmd
, argtable
, true);
2798 CLIGetHexWithReturn(1, keyn
, &keynlen
);
2799 CLIGetHexWithReturn(2, key
, &keylen
);
2803 PrintAndLog("ERROR: <Key Num> must be 2 bytes long instead of: %d", keynlen
);
2808 PrintAndLog("ERROR: <Key Value> must be 16 bytes long instead of: %d", keylen
);
2812 return MifareAuth4(NULL
, keyn
, key
, true, false, true);
2815 // https://www.nxp.com/docs/en/application-note/AN10787.pdf
2816 int CmdHF14AMfMAD(const char *cmd
) {
2818 CLIParserInit("hf mf mad",
2819 "Checks and prints Mifare Application Directory (MAD)",
2820 "Usage:\n\thf mf mad -> shows MAD if exists\n"
2821 "\thf mf mad -a 03e1 -k ffffffffffff -b -> shows NDEF data if exists. read card with custom key and key B\n");
2823 void *argtable
[] = {
2825 arg_lit0("vV", "verbose", "show technical data"),
2826 arg_str0("aA", "aid", "print all sectors with aid", NULL
),
2827 arg_str0("kK", "key", "key for printing sectors", NULL
),
2828 arg_lit0("bB", "keyb", "use key B for access printing sectors (by default: key A)"),
2831 CLIExecWithReturn(cmd
, argtable
, true);
2832 bool verbose
= arg_get_lit(1);
2833 uint8_t aid
[2] = {0};
2835 CLIGetHexWithReturn(2, aid
, &aidlen
);
2836 uint8_t key
[6] = {0};
2838 CLIGetHexWithReturn(3, key
, &keylen
);
2839 bool keyB
= arg_get_lit(4);
2843 if (aidlen
!= 2 && keylen
> 0) {
2844 PrintAndLogEx(WARNING
, "do not need a key without aid.");
2847 uint8_t sector0
[16 * 4] = {0};
2848 uint8_t sector10
[16 * 4] = {0};
2849 if (mfReadSector(MF_MAD1_SECTOR
, MF_KEY_A
, (uint8_t *)g_mifare_mad_key
, sector0
)) {
2850 PrintAndLogEx(ERR
, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");
2855 for (int i
= 0; i
< 4; i
++)
2856 PrintAndLogEx(NORMAL
, "[%d] %s", i
, sprint_hex(§or0
[i
* 16], 16));
2859 bool haveMAD2
= false;
2860 MAD1DecodeAndPrint(sector0
, verbose
, &haveMAD2
);
2863 if (mfReadSector(MF_MAD2_SECTOR
, MF_KEY_A
, (uint8_t *)g_mifare_mad_key
, sector10
)) {
2864 PrintAndLogEx(ERR
, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");
2868 MAD2DecodeAndPrint(sector10
, verbose
);
2872 uint16_t aaid
= (aid
[0] << 8) + aid
[1];
2873 PrintAndLogEx(NORMAL
, "\n-------------- AID 0x%04x ---------------", aaid
);
2875 uint16_t mad
[7 + 8 + 8 + 8 + 8] = {0};
2877 if (MADDecode(sector0
, sector10
, mad
, &madlen
)) {
2878 PrintAndLogEx(ERR
, "can't decode mad.");
2882 uint8_t akey
[6] = {0};
2883 memcpy(akey
, g_mifare_ndef_key
, 6);
2885 memcpy(akey
, key
, 6);
2888 for (int i
= 0; i
< madlen
; i
++) {
2889 if (aaid
== mad
[i
]) {
2890 uint8_t vsector
[16 * 4] = {0};
2891 if (mfReadSector(i
+ 1, keyB
? MF_KEY_B
: MF_KEY_A
, akey
, vsector
)) {
2892 PrintAndLogEx(NORMAL
, "");
2893 PrintAndLogEx(ERR
, "read sector %d error.", i
+ 1);
2897 for (int j
= 0; j
< (verbose
? 4 : 3); j
++)
2898 PrintAndLogEx(NORMAL
, " [%03d] %s", (i
+ 1) * 4 + j
, sprint_hex(&vsector
[j
* 16], 16));
2906 int CmdHFMFNDEF(const char *cmd
) {
2908 CLIParserInit("hf mf ndef",
2909 "Prints NFC Data Exchange Format (NDEF)",
2910 "Usage:\n\thf mf ndef -> shows NDEF data\n"
2911 "\thf mf ndef -a 03e1 -k ffffffffffff -b -> shows NDEF data with custom AID, key and with key B\n");
2913 void *argtable
[] = {
2915 arg_litn("vV", "verbose", 0, 2, "show technical data"),
2916 arg_str0("aA", "aid", "replace default aid for NDEF", NULL
),
2917 arg_str0("kK", "key", "replace default key for NDEF", NULL
),
2918 arg_lit0("bB", "keyb", "use key B for access sectors (by default: key A)"),
2921 CLIExecWithReturn(cmd
, argtable
, true);
2923 bool verbose
= arg_get_lit(1);
2924 bool verbose2
= arg_get_lit(1) > 1;
2925 uint8_t aid
[2] = {0};
2927 CLIGetHexWithReturn(2, aid
, &aidlen
);
2928 uint8_t key
[6] = {0};
2930 CLIGetHexWithReturn(3, key
, &keylen
);
2931 bool keyB
= arg_get_lit(4);
2935 uint16_t ndefAID
= 0x03e1;
2937 ndefAID
= (aid
[0] << 8) + aid
[1];
2939 uint8_t ndefkey
[6] = {0};
2940 memcpy(ndefkey
, g_mifare_ndef_key
, 6);
2942 memcpy(ndefkey
, key
, 6);
2945 uint8_t sector0
[16 * 4] = {0};
2946 uint8_t sector10
[16 * 4] = {0};
2947 uint8_t data
[4096] = {0};
2950 PrintAndLogEx(NORMAL
, "");
2952 if (mfReadSector(MF_MAD1_SECTOR
, MF_KEY_A
, (uint8_t *)g_mifare_mad_key
, sector0
)) {
2953 PrintAndLogEx(ERR
, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");
2957 bool haveMAD2
= false;
2958 int res
= MADCheck(sector0
, NULL
, verbose
, &haveMAD2
);
2960 PrintAndLogEx(ERR
, "MAD error %d.", res
);
2965 if (mfReadSector(MF_MAD2_SECTOR
, MF_KEY_A
, (uint8_t *)g_mifare_mad_key
, sector10
)) {
2966 PrintAndLogEx(ERR
, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");
2971 uint16_t mad
[7 + 8 + 8 + 8 + 8] = {0};
2973 if (MADDecode(sector0
, (haveMAD2
? sector10
: NULL
), mad
, &madlen
)) {
2974 PrintAndLogEx(ERR
, "can't decode mad.");
2978 printf("data reading:");
2979 for (int i
= 0; i
< madlen
; i
++) {
2980 if (ndefAID
== mad
[i
]) {
2981 uint8_t vsector
[16 * 4] = {0};
2982 if (mfReadSector(i
+ 1, keyB
? MF_KEY_B
: MF_KEY_A
, ndefkey
, vsector
)) {
2983 PrintAndLogEx(ERR
, "read sector %d error.", i
+ 1);
2987 memcpy(&data
[datalen
], vsector
, 16 * 3);
2996 PrintAndLogEx(ERR
, "no NDEF data.");
3001 PrintAndLogEx(NORMAL
, "NDEF data:");
3002 dump_buffer(data
, datalen
, stdout
, 1);
3005 NDEFDecodeAndPrint(data
, datalen
, verbose
);
3010 int CmdHFMFPersonalize(const char *cmd
) {
3012 CLIParserInit("hf mf personalize",
3013 "Personalize the UID of a Mifare Classic EV1 card. This is only possible if it is a 7Byte UID card and if it is not already personalized.",
3014 "Usage:\n\thf mf personalize UIDF0 -> double size UID according to ISO/IEC14443-3\n"
3015 "\thf mf personalize UIDF1 -> double size UID according to ISO/IEC14443-3, optional usage of selection process shortcut\n"
3016 "\thf mf personalize UIDF2 -> single size random ID according to ISO/IEC14443-3\n"
3017 "\thf mf personalize UIDF3 -> single size NUID according to ISO/IEC14443-3\n"
3018 "\thf mf personalize -t B -k B0B1B2B3B4B5 UIDF3 -> use key B = 0xB0B1B2B3B4B5 instead of default key A\n");
3020 void *argtable
[] = {
3022 arg_str0("tT", "keytype", "<A|B>", "key type (A or B) to authenticate sector 0 (default: A)"),
3023 arg_str0("kK", "key", "<key (hex 6 Bytes)>", "key to authenticate sector 0 (default: FFFFFFFFFFFF)"),
3024 arg_str1(NULL
, NULL
, "<UIDF0|UIDF1|UIDF2|UIDF3>", "Personalization Option"),
3027 CLIExecWithReturn(cmd
, argtable
, true);
3029 char keytypestr
[2] = "A";
3030 uint8_t keytype
= 0x00;
3032 int res
= CLIParamStrToBuf(arg_get_str(1), (uint8_t*)keytypestr
, 1, &keytypestr_len
);
3033 if (res
|| (keytypestr
[0] != 'a' && keytypestr
[0] != 'A' && keytypestr
[0] != 'b' && keytypestr
[0] != 'B')) {
3034 PrintAndLog("ERROR: not a valid key type. Key type must be A or B");
3038 if (keytypestr
[0] == 'B' || keytypestr
[0] == 'b') {
3042 uint8_t key
[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
3044 res
= CLIParamHexToBuf(arg_get_str(2), key
, 6, &key_len
);
3045 if (res
|| (!res
&& key_len
> 0 && key_len
!= 6)) {
3046 PrintAndLog("ERROR: not a valid key. Key must be 12 hex digits");
3051 char pers_optionstr
[6];
3053 uint8_t pers_option
;
3054 res
= CLIParamStrToBuf(arg_get_str(3), (uint8_t*)pers_optionstr
, 5, &opt_len
);
3055 if (res
|| (!res
&& opt_len
> 0 && opt_len
!= 5)
3056 || (strncmp(pers_optionstr
, "UIDF0", 5) && strncmp(pers_optionstr
, "UIDF1", 5) && strncmp(pers_optionstr
, "UIDF2", 5) && strncmp(pers_optionstr
, "UIDF3", 5))) {
3057 PrintAndLog("ERROR: invalid personalization option. Must be one of UIDF0, UIDF1, UIDF2, or UIDF3");
3061 if (!strncmp(pers_optionstr
, "UIDF0", 5)) {
3062 pers_option
= MIFARE_EV1_UIDF0
;
3063 } else if (!strncmp(pers_optionstr
, "UIDF1", 5)) {
3064 pers_option
= MIFARE_EV1_UIDF1
;
3065 } else if (!strncmp(pers_optionstr
, "UIDF2", 5)) {
3066 pers_option
= MIFARE_EV1_UIDF2
;
3068 pers_option
= MIFARE_EV1_UIDF3
;
3073 UsbCommand c
= {CMD_MIFARE_PERSONALIZE_UID
, {keytype
, pers_option
, 0}};
3074 memcpy(c
.d
.asBytes
, key
, 6);
3078 if (WaitForResponseTimeout(CMD_ACK
, &resp
, 1500)) {
3079 bool isOK
= resp
.arg
[0];
3080 PrintAndLog("Personalization %s", isOK
? "SUCCEEDED" : "FAILED");
3082 PrintAndLog("Command execute timeout");
3089 static command_t CommandTable
[] = {
3090 {"help", CmdHelp
, 1, "This help"},
3091 {"dbg", CmdHF14AMfDbg
, 0, "Set default debug mode"},
3092 {"rdbl", CmdHF14AMfRdBl
, 0, "Read MIFARE classic block"},
3093 {"rdsc", CmdHF14AMfRdSc
, 0, "Read MIFARE classic sector"},
3094 {"dump", CmdHF14AMfDump
, 0, "Dump MIFARE classic tag to binary file"},
3095 {"restore", CmdHF14AMfRestore
, 0, "Restore MIFARE classic binary file to BLANK tag"},
3096 {"wrbl", CmdHF14AMfWrBl
, 0, "Write MIFARE classic block"},
3097 {"auth4", CmdHF14AMfAuth4
, 0, "ISO14443-4 AES authentication"},
3098 {"chk", CmdHF14AMfChk
, 0, "Test block keys"},
3099 {"mifare", CmdHF14AMifare
, 0, "Read parity error messages."},
3100 {"hardnested", CmdHF14AMfNestedHard
, 0, "Nested attack for hardened Mifare cards"},
3101 {"nested", CmdHF14AMfNested
, 0, "Test nested authentication"},
3102 {"sniff", CmdHF14AMfSniff
, 0, "Sniff card-reader communication"},
3103 {"sim", CmdHF14AMfSim
, 0, "Simulate MIFARE card"},
3104 {"eclr", CmdHF14AMfEClear
, 0, "Clear simulator memory"},
3105 {"eget", CmdHF14AMfEGet
, 0, "Get simulator memory block"},
3106 {"eset", CmdHF14AMfESet
, 0, "Set simulator memory block"},
3107 {"eload", CmdHF14AMfELoad
, 0, "Load from file emul dump"},
3108 {"esave", CmdHF14AMfESave
, 0, "Save to file emul dump"},
3109 {"ecfill", CmdHF14AMfECFill
, 0, "Fill simulator memory with help of keys from simulator"},
3110 {"ekeyprn", CmdHF14AMfEKeyPrn
, 0, "Print keys from simulator memory"},
3111 {"cwipe", CmdHF14AMfCWipe
, 0, "Wipe magic Chinese card"},
3112 {"csetuid", CmdHF14AMfCSetUID
, 0, "Set UID for magic Chinese card"},
3113 {"csetblk", CmdHF14AMfCSetBlk
, 0, "Write block - Magic Chinese card"},
3114 {"cgetblk", CmdHF14AMfCGetBlk
, 0, "Read block - Magic Chinese card"},
3115 {"cgetsc", CmdHF14AMfCGetSc
, 0, "Read sector - Magic Chinese card"},
3116 {"cload", CmdHF14AMfCLoad
, 0, "Load dump into magic Chinese card"},
3117 {"csave", CmdHF14AMfCSave
, 0, "Save dump from magic Chinese card into file or emulator"},
3118 {"decrypt", CmdDecryptTraceCmds
, 1, "[nt] [ar_enc] [at_enc] [data] - to decrypt snoop or trace"},
3119 {"mad", CmdHF14AMfMAD
, 0, "Checks and prints MAD"},
3120 {"ndef", CmdHFMFNDEF
, 0, "Prints NDEF records from card"},
3121 {"personalize", CmdHFMFPersonalize
, 0, "Personalize UID (Mifare Classic EV1 only)"},
3122 {NULL
, NULL
, 0, NULL
}
3126 int CmdHFMF(const char *Cmd
) {
3127 (void)WaitForResponseTimeout(CMD_ACK
,NULL
,100);
3128 CmdsParse(CommandTable
, Cmd
);
3133 int CmdHelp(const char *Cmd
) {
3134 CmdsHelp(CommandTable
);