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
, uint8_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
= 11; // slow
587 if (!paramS1
&& (ctmp3
[1] == 's' || ctmp3
[1] == 'S')) {
588 *timeout
= 53; // very slow
590 if (paramS1
&& (ctmp3
[2] == 's' || ctmp3
[2] == 'S')) {
591 *timeout
= 53; // very slow
597 int CmdHF14AMfNested(const char *Cmd
)
599 int i
, j
, res
, iterations
;
600 sector_t
*e_sector
= NULL
;
603 uint8_t trgBlockNo
= 0;
604 uint8_t trgKeyType
= 0;
605 uint8_t SectorsCnt
= 0;
606 uint8_t key
[6] = {0, 0, 0, 0, 0, 0};
607 uint8_t keyBlock
[MifareDefaultKeysSize
* 6];
609 // timeout in units. (ms * 106)/10 or us*0.0106
610 uint8_t btimeout14a
= MF_CHKKEYS_DEFTIMEOUT
; // fast by default
612 bool autosearchKey
= false;
614 bool transferToEml
= false;
615 bool createDumpFile
= false;
617 uint8_t standart
[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
618 uint8_t tempkey
[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
623 PrintAndLog("Usage:");
624 PrintAndLog(" all sectors: hf mf nested <card memory> <block number> <key A/B> <key (12 hex symbols)> [t|d|s|ss]");
625 PrintAndLog(" all sectors autosearch key: hf mf nested <card memory> * [t|d|s|ss]");
626 PrintAndLog(" one sector: hf mf nested o <block number> <key A/B> <key (12 hex symbols)>");
627 PrintAndLog(" <target block number> <target key A/B> [t]");
629 PrintAndLog("card memory - 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other> - 1K");
630 PrintAndLog("t - transfer keys to emulator memory");
631 PrintAndLog("d - write keys to binary file dumpkeys.bin");
632 PrintAndLog("s - Slow (1ms) check keys (required by some non standard cards)");
633 PrintAndLog("ss - Very slow (5ms) check keys");
635 PrintAndLog(" sample1: hf mf nested 1 0 A FFFFFFFFFFFF ");
636 PrintAndLog(" sample2: hf mf nested 1 0 A FFFFFFFFFFFF t ");
637 PrintAndLog(" sample3: hf mf nested 1 0 A FFFFFFFFFFFF d ");
638 PrintAndLog(" sample4: hf mf nested o 0 A FFFFFFFFFFFF 4 A");
639 PrintAndLog(" sample5: hf mf nested 1 * t");
640 PrintAndLog(" sample6: hf mf nested 1 * ss");
645 cmdp
= param_getchar(Cmd
, 0);
646 if (cmdp
== 'o' || cmdp
== 'O') {
650 SectorsCnt
= ParamCardSizeSectors(cmdp
);
653 // <block number>. number or autosearch key (*)
654 if (param_getchar(Cmd
, 1) == '*') {
655 autosearchKey
= true;
657 parseParamTDS(Cmd
, 2, &transferToEml
, &createDumpFile
, &btimeout14a
);
659 PrintAndLog("--nested. sectors:%2d, block no:*, eml:%c, dmp=%c checktimeout=%d us",
660 SectorsCnt
, transferToEml
?'y':'n', createDumpFile
?'y':'n', ((int)btimeout14a
* 10000) / 106);
662 blockNo
= param_get8(Cmd
, 1);
664 ctmp
= param_getchar(Cmd
, 2);
665 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
666 PrintAndLog("Key type must be A or B");
670 if (ctmp
!= 'A' && ctmp
!= 'a')
673 if (param_gethex(Cmd
, 3, key
, 12)) {
674 PrintAndLog("Key must include 12 HEX symbols");
678 // check if we can authenticate to sector
679 res
= mfCheckKeys(blockNo
, keyType
, true, 1, key
, &key64
);
681 PrintAndLog("Can't authenticate to block:%3d key type:%c key:%s", blockNo
, keyType
?'B':'A', sprint_hex(key
, 6));
687 trgBlockNo
= param_get8(Cmd
, 4);
689 ctmp
= param_getchar(Cmd
, 5);
690 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
691 PrintAndLog("Target key type must be A or B");
694 if (ctmp
!= 'A' && ctmp
!= 'a')
697 parseParamTDS(Cmd
, 6, &transferToEml
, &createDumpFile
, &btimeout14a
);
699 parseParamTDS(Cmd
, 4, &transferToEml
, &createDumpFile
, &btimeout14a
);
702 PrintAndLog("--nested. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us",
703 SectorsCnt
, blockNo
, keyType
?'B':'A', transferToEml
?'y':'n', createDumpFile
?'y':'n', ((int)btimeout14a
* 10000) / 106);
707 if (cmdp
== 'o') { // ------------------------------------ one sector working
708 PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo
, trgKeyType
?'B':'A');
709 int16_t isOK
= mfnested(blockNo
, keyType
, key
, trgBlockNo
, trgKeyType
, keyBlock
, true);
712 case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
713 case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;
714 case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;
715 default : PrintAndLog("Unknown Error (%d)\n", isOK
);
719 key64
= bytes_to_num(keyBlock
, 6);
721 PrintAndLog("Found valid key:%012" PRIx64
, key64
);
723 // transfer key to the emulator
725 uint8_t sectortrailer
;
726 if (trgBlockNo
< 32*4) { // 4 block sector
727 sectortrailer
= trgBlockNo
| 0x03;
728 } else { // 16 block sector
729 sectortrailer
= trgBlockNo
| 0x0f;
731 mfEmlGetMem(keyBlock
, sectortrailer
, 1);
734 num_to_bytes(key64
, 6, keyBlock
);
736 num_to_bytes(key64
, 6, &keyBlock
[10]);
737 mfEmlSetMem(keyBlock
, sectortrailer
, 1);
738 PrintAndLog("Key transferred to emulator memory.");
741 PrintAndLog("No valid key found");
744 else { // ------------------------------------ multiple sectors working
746 msclock1
= msclock();
748 e_sector
= calloc(SectorsCnt
, sizeof(sector_t
));
749 if (e_sector
== NULL
) return 1;
751 //test current key and additional standard keys first
752 for (int defaultKeyCounter
= 0; defaultKeyCounter
< MifareDefaultKeysSize
; defaultKeyCounter
++){
753 num_to_bytes(MifareDefaultKeys
[defaultKeyCounter
], 6, (uint8_t*)(keyBlock
+ defaultKeyCounter
* 6));
756 PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt
);
757 mfCheckKeysSec(SectorsCnt
, 2, btimeout14a
, true, MifareDefaultKeysSize
, keyBlock
, e_sector
);
759 // get known key from array
760 bool keyFound
= false;
762 for (i
= 0; i
< SectorsCnt
; i
++) {
763 for (j
= 0; j
< 2; j
++) {
764 if (e_sector
[i
].foundKey
[j
]) {
768 num_to_bytes(e_sector
[i
].Key
[j
], 6, key
);
776 // Can't found a key....
778 PrintAndLog("Can't found any of the known keys.");
782 PrintAndLog("--auto key. block no:%3d, key type:%c key:%s", blockNo
, keyType
?'B':'A', sprint_hex(key
, 6));
787 PrintAndLog("nested...");
788 bool calibrate
= true;
789 for (i
= 0; i
< NESTED_SECTOR_RETRY
; i
++) {
790 for (uint8_t sectorNo
= 0; sectorNo
< SectorsCnt
; sectorNo
++) {
791 for (trgKeyType
= 0; trgKeyType
< 2; trgKeyType
++) {
792 if (e_sector
[sectorNo
].foundKey
[trgKeyType
]) continue;
793 PrintAndLog("-----------------------------------------------");
794 int16_t isOK
= mfnested(blockNo
, keyType
, key
, FirstBlockOfSector(sectorNo
), trgKeyType
, keyBlock
, calibrate
);
797 case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
798 case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;
799 case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;
800 default : PrintAndLog("Unknown Error (%d)\n", isOK
);
810 key64
= bytes_to_num(keyBlock
, 6);
812 PrintAndLog("Found valid key:%012" PRIx64
, key64
);
813 e_sector
[sectorNo
].foundKey
[trgKeyType
] = 1;
814 e_sector
[sectorNo
].Key
[trgKeyType
] = key64
;
816 // try to check this key as a key to the other sectors
817 mfCheckKeysSec(SectorsCnt
, 2, btimeout14a
, true, 1, keyBlock
, e_sector
);
823 // print nested statistic
824 PrintAndLog("\n\n-----------------------------------------------\nNested statistic:\nIterations count: %d", iterations
);
825 PrintAndLog("Time in nested: %1.3f (%1.3f sec per key)", ((float)(msclock() - msclock1
))/1000.0, ((float)(msclock() - msclock1
))/iterations
/1000.0);
828 PrintAndLog("|---|----------------|---|----------------|---|");
829 PrintAndLog("|sec|key A |res|key B |res|");
830 PrintAndLog("|---|----------------|---|----------------|---|");
831 for (i
= 0; i
< SectorsCnt
; i
++) {
832 PrintAndLog("|%03d| %012" PRIx64
" | %d | %012" PRIx64
" | %d |", i
,
833 e_sector
[i
].Key
[0], e_sector
[i
].foundKey
[0], e_sector
[i
].Key
[1], e_sector
[i
].foundKey
[1]);
835 PrintAndLog("|---|----------------|---|----------------|---|");
837 // transfer keys to the emulator memory
839 for (i
= 0; i
< SectorsCnt
; i
++) {
840 mfEmlGetMem(keyBlock
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1);
841 if (e_sector
[i
].foundKey
[0])
842 num_to_bytes(e_sector
[i
].Key
[0], 6, keyBlock
);
843 if (e_sector
[i
].foundKey
[1])
844 num_to_bytes(e_sector
[i
].Key
[1], 6, &keyBlock
[10]);
845 mfEmlSetMem(keyBlock
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1);
847 PrintAndLog("Keys transferred to emulator memory.");
851 if (createDumpFile
) {
852 if ((fkeys
= fopen("dumpkeys.bin","wb")) == NULL
) {
853 PrintAndLog("Could not create file dumpkeys.bin");
857 PrintAndLog("Printing keys to binary file dumpkeys.bin...");
858 for(i
=0; i
<SectorsCnt
; i
++) {
859 if (e_sector
[i
].foundKey
[0]){
860 num_to_bytes(e_sector
[i
].Key
[0], 6, tempkey
);
861 fwrite ( tempkey
, 1, 6, fkeys
);
864 fwrite ( &standart
, 1, 6, fkeys
);
867 for(i
=0; i
<SectorsCnt
; i
++) {
868 if (e_sector
[i
].foundKey
[1]){
869 num_to_bytes(e_sector
[i
].Key
[1], 6, tempkey
);
870 fwrite ( tempkey
, 1, 6, fkeys
);
873 fwrite ( &standart
, 1, 6, fkeys
);
885 int CmdHF14AMfNestedHard(const char *Cmd
)
889 uint8_t trgBlockNo
= 0;
890 uint8_t trgKeyType
= 0;
891 uint8_t key
[6] = {0, 0, 0, 0, 0, 0};
892 uint8_t trgkey
[6] = {0, 0, 0, 0, 0, 0};
895 ctmp
= param_getchar(Cmd
, 0);
897 if (ctmp
!= 'R' && ctmp
!= 'r' && ctmp
!= 'T' && ctmp
!= 't' && strlen(Cmd
) < 20) {
898 PrintAndLog("Usage:");
899 PrintAndLog(" hf mf hardnested <block number> <key A|B> <key (12 hex symbols)>");
900 PrintAndLog(" <target block number> <target key A|B> [known target key (12 hex symbols)] [w] [s]");
901 PrintAndLog(" or hf mf hardnested r [known target key]");
903 PrintAndLog("Options: ");
904 PrintAndLog(" w: Acquire nonces and write them to binary file nonces.bin");
905 PrintAndLog(" s: Slower acquisition (required by some non standard cards)");
906 PrintAndLog(" r: Read nonces.bin and start attack");
907 PrintAndLog(" iX: set type of SIMD instructions. Without this flag programs autodetect it.");
908 PrintAndLog(" i5: AVX512");
909 PrintAndLog(" i2: AVX2");
910 PrintAndLog(" ia: AVX");
911 PrintAndLog(" is: SSE2");
912 PrintAndLog(" im: MMX");
913 PrintAndLog(" in: none (use CPU regular instruction set)");
915 PrintAndLog(" sample1: hf mf hardnested 0 A FFFFFFFFFFFF 4 A");
916 PrintAndLog(" sample2: hf mf hardnested 0 A FFFFFFFFFFFF 4 A w");
917 PrintAndLog(" sample3: hf mf hardnested 0 A FFFFFFFFFFFF 4 A w s");
918 PrintAndLog(" sample4: hf mf hardnested r");
920 PrintAndLog("Add the known target key to check if it is present in the remaining key space:");
921 PrintAndLog(" sample5: hf mf hardnested 0 A A0A1A2A3A4A5 4 A FFFFFFFFFFFF");
925 bool know_target_key
= false;
926 bool nonce_file_read
= false;
927 bool nonce_file_write
= false;
933 if (ctmp
== 'R' || ctmp
== 'r') {
934 nonce_file_read
= true;
936 if (!param_gethex(Cmd
, 1, trgkey
, 12)) {
937 know_target_key
= true;
940 } else if (ctmp
== 'T' || ctmp
== 't') {
941 tests
= param_get32ex(Cmd
, 1, 100, 10);
943 if (!param_gethex(Cmd
, 2, trgkey
, 12)) {
944 know_target_key
= true;
948 blockNo
= param_get8(Cmd
, 0);
949 ctmp
= param_getchar(Cmd
, 1);
950 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
951 PrintAndLog("Key type must be A or B");
954 if (ctmp
!= 'A' && ctmp
!= 'a') {
958 if (param_gethex(Cmd
, 2, key
, 12)) {
959 PrintAndLog("Key must include 12 HEX symbols");
963 trgBlockNo
= param_get8(Cmd
, 3);
964 ctmp
= param_getchar(Cmd
, 4);
965 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
966 PrintAndLog("Target key type must be A or B");
969 if (ctmp
!= 'A' && ctmp
!= 'a') {
975 if (!param_gethex(Cmd
, 5, trgkey
, 12)) {
976 know_target_key
= true;
981 while ((ctmp
= param_getchar(Cmd
, i
))) {
982 if (ctmp
== 's' || ctmp
== 'S') {
984 } else if (ctmp
== 'w' || ctmp
== 'W') {
985 nonce_file_write
= true;
986 } else if (param_getlength(Cmd
, i
) == 2 && ctmp
== 'i') {
989 PrintAndLog("Possible options are w , s and/or iX");
996 SetSIMDInstr(SIMD_AUTO
);
998 while ((ctmp
= param_getchar(Cmd
, iindx
))) {
999 if (param_getlength(Cmd
, iindx
) == 2 && ctmp
== 'i') {
1000 switch(param_getchar_indx(Cmd
, 1, iindx
)) {
1002 SetSIMDInstr(SIMD_AVX512
);
1005 SetSIMDInstr(SIMD_AVX2
);
1008 SetSIMDInstr(SIMD_AVX
);
1011 SetSIMDInstr(SIMD_SSE2
);
1014 SetSIMDInstr(SIMD_MMX
);
1017 SetSIMDInstr(SIMD_NONE
);
1020 PrintAndLog("Unknown SIMD type. %c", param_getchar_indx(Cmd
, 1, iindx
));
1028 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 ",
1031 trgkey
[0], trgkey
[1], trgkey
[2], trgkey
[3], trgkey
[4], trgkey
[5],
1032 know_target_key
?"":" (not set)",
1033 nonce_file_write
?"write":nonce_file_read
?"read":"none",
1037 int16_t isOK
= mfnestedhard(blockNo
, keyType
, key
, trgBlockNo
, trgKeyType
, know_target_key
?trgkey
:NULL
, nonce_file_read
, nonce_file_write
, slow
, tests
);
1041 case 1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
1042 case 2 : PrintAndLog("Button pressed. Aborted.\n"); break;
1052 int CmdHF14AMfChk(const char *Cmd
)
1054 if (strlen(Cmd
)<3) {
1055 PrintAndLog("Usage: hf mf chk <block number>|<*card memory> <key type (A/B/?)> [t|d|s|ss] [<key (12 hex symbols)>] [<dic (*.dic)>]");
1056 PrintAndLog(" * - all sectors");
1057 PrintAndLog("card memory - 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other> - 1K");
1058 PrintAndLog("d - write keys to binary file (not used when <block number> supplied)");
1059 PrintAndLog("t - write keys to emulator memory");
1060 PrintAndLog("s - slow execute. timeout 1ms");
1061 PrintAndLog("ss - very slow execute. timeout 5ms");
1062 PrintAndLog(" sample: hf mf chk 0 A 1234567890ab keys.dic");
1063 PrintAndLog(" hf mf chk *1 ? t");
1064 PrintAndLog(" hf mf chk *1 ? d");
1065 PrintAndLog(" hf mf chk *1 ? s");
1066 PrintAndLog(" hf mf chk *1 ? dss");
1071 char filename
[FILE_PATH_SIZE
]={0};
1073 uint8_t *keyBlock
= NULL
, *p
;
1074 uint16_t stKeyBlock
= 20;
1079 uint8_t blockNo
= 0;
1080 uint8_t SectorsCnt
= 0;
1081 uint8_t keyType
= 0;
1083 // timeout in units. (ms * 106)/10 or us*0.0106
1084 uint8_t btimeout14a
= MF_CHKKEYS_DEFTIMEOUT
; // fast by default
1085 bool param3InUse
= false;
1086 bool transferToEml
= 0;
1087 bool createDumpFile
= 0;
1088 bool singleBlock
= false; // Flag to ID if a single or multi key check
1089 uint8_t keyFoundCount
= 0; // Counter to display the number of keys found/transfered to emulator
1091 sector_t
*e_sector
= NULL
;
1093 keyBlock
= calloc(stKeyBlock
, 6);
1094 if (keyBlock
== NULL
) return 1;
1096 int defaultKeysSize
= MifareDefaultKeysSize
;
1097 for (int defaultKeyCounter
= 0; defaultKeyCounter
< defaultKeysSize
; defaultKeyCounter
++){
1098 num_to_bytes(MifareDefaultKeys
[defaultKeyCounter
], 6, (uint8_t*)(keyBlock
+ defaultKeyCounter
* 6));
1101 if (param_getchar(Cmd
, 0)=='*') {
1102 SectorsCnt
= ParamCardSizeSectors(param_getchar(Cmd
+ 1, 0));
1104 blockNo
= param_get8(Cmd
, 0);
1105 // Singe Key check, so Set Sector count to cover sectors (1 to sector that contains the block)
1106 // 1 and 2 Cards : Sector = blockNo/4 + 1
1107 // Sectors 0 - 31 : 4 blocks per sector : Blocks 0 - 127
1108 // Sectors 32 - 39 : 16 blocks per sector : Blocks 128 - 255 (4K)
1109 if (blockNo
< 128) {
1110 SectorsCnt
= (blockNo
/ 4) + 1;
1112 SectorsCnt
= 32 + ((blockNo
-128)/16) + 1;
1114 singleBlock
= true; // Set flag for single key check
1117 ctmp
= param_getchar(Cmd
, 1);
1118 clen
= param_getlength(Cmd
, 1);
1131 PrintAndLog("Key type must be A , B or ?");
1137 parseParamTDS(Cmd
, 2, &transferToEml
, &createDumpFile
, &btimeout14a
);
1139 if (singleBlock
& createDumpFile
) {
1140 PrintAndLog (" block key check (<block no>) and write to dump file (d) combination is not supported ");
1141 PrintAndLog (" please remove option d and try again");
1145 param3InUse
= transferToEml
| createDumpFile
| (btimeout14a
!= MF_CHKKEYS_DEFTIMEOUT
);
1147 PrintAndLog("--chk keys. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us",
1148 SectorsCnt
, blockNo
, keyType
==0?'A':keyType
==1?'B':'?', transferToEml
?'y':'n', createDumpFile
?'y':'n', ((int)btimeout14a
* 10000) / 106);
1150 for (i
= param3InUse
; param_getchar(Cmd
, 2 + i
); i
++) {
1151 if (!param_gethex(Cmd
, 2 + i
, keyBlock
+ 6 * keycnt
, 12)) {
1152 if ( stKeyBlock
- keycnt
< 2) {
1153 p
= realloc(keyBlock
, 6*(stKeyBlock
+=10));
1155 PrintAndLog("Cannot allocate memory for Keys");
1161 PrintAndLog("chk key[%2d] %02x%02x%02x%02x%02x%02x", keycnt
,
1162 (keyBlock
+ 6*keycnt
)[0], (keyBlock
+ 6*keycnt
)[1], (keyBlock
+ 6*keycnt
)[2],
1163 (keyBlock
+ 6*keycnt
)[3], (keyBlock
+ 6*keycnt
)[4], (keyBlock
+ 6*keycnt
)[5], 6);
1166 // May be a dic file
1167 if ( param_getstr(Cmd
, 2 + i
, filename
, sizeof(filename
)) >= FILE_PATH_SIZE
) {
1168 PrintAndLog("File name too long");
1173 if ((f
= fopen( filename
, "r"))) {
1174 while (fgets(buf
, sizeof(buf
), f
)) {
1175 if (strlen(buf
) < 12 || buf
[11] == '\n')
1178 while (fgetc(f
) != '\n' && !feof(f
)) ; //goto next line
1180 if( buf
[0]=='#' ) continue; //The line start with # is comment, skip
1182 bool content_error
= false;
1183 for (int i
= 0; i
< 12; i
++) {
1184 if (!isxdigit((unsigned char)buf
[i
])) {
1185 content_error
= true;
1188 if (content_error
) {
1189 PrintAndLog("File content error. '%s' must include 12 HEX symbols", buf
);
1195 if (stKeyBlock
- keycnt
< 2) {
1196 p
= realloc(keyBlock
, 6*(stKeyBlock
+=10));
1198 PrintAndLog("Cannot allocate memory for defKeys");
1205 memset(keyBlock
+ 6 * keycnt
, 0, 6);
1206 num_to_bytes(strtoll(buf
, NULL
, 16), 6, keyBlock
+ 6*keycnt
);
1207 PrintAndLog("chk custom key[%2d] %012" PRIx64
, keycnt
, bytes_to_num(keyBlock
+ 6*keycnt
, 6));
1209 memset(buf
, 0, sizeof(buf
));
1213 PrintAndLog("File: %s: not found or locked.", filename
);
1220 // fill with default keys
1222 PrintAndLog("No key specified, trying default keys");
1223 for (;keycnt
< defaultKeysSize
; keycnt
++)
1224 PrintAndLog("chk default key[%2d] %02x%02x%02x%02x%02x%02x", keycnt
,
1225 (keyBlock
+ 6*keycnt
)[0], (keyBlock
+ 6*keycnt
)[1], (keyBlock
+ 6*keycnt
)[2],
1226 (keyBlock
+ 6*keycnt
)[3], (keyBlock
+ 6*keycnt
)[4], (keyBlock
+ 6*keycnt
)[5], 6);
1229 // initialize storage for found keys
1230 e_sector
= calloc(SectorsCnt
, sizeof(sector_t
));
1231 if (e_sector
== NULL
) {
1235 for (uint8_t keyAB
= 0; keyAB
< 2; keyAB
++) {
1236 for (uint16_t sectorNo
= 0; sectorNo
< SectorsCnt
; sectorNo
++) {
1237 e_sector
[sectorNo
].Key
[keyAB
] = 0xffffffffffff;
1238 e_sector
[sectorNo
].foundKey
[keyAB
] = 0;
1243 bool foundAKey
= false;
1244 bool clearTraceLog
= true;
1245 uint32_t max_keys
= keycnt
> USB_CMD_DATA_SIZE
/ 6 ? USB_CMD_DATA_SIZE
/ 6 : keycnt
;
1247 // !SingleKey, so all key check (if SectorsCnt > 0)
1249 PrintAndLog("To cancel this operation press the button on the proxmark...");
1251 for (uint32_t c
= 0; c
< keycnt
; c
+= max_keys
) {
1253 uint32_t size
= keycnt
-c
> max_keys
? max_keys
: keycnt
-c
;
1254 res
= mfCheckKeysSec(SectorsCnt
, keyType
, btimeout14a
, clearTraceLog
, size
, &keyBlock
[6 * c
], e_sector
); // timeout is (ms * 106)/10 or us*0.0106
1255 clearTraceLog
= false;
1266 PrintAndLog("Command execute timeout");
1270 int keyAB
= keyType
;
1272 for (uint32_t c
= 0; c
< keycnt
; c
+= max_keys
) {
1274 uint32_t size
= keycnt
-c
> max_keys
? max_keys
: keycnt
-c
;
1275 res
= mfCheckKeys(blockNo
, keyAB
& 0x01, true, size
, &keyBlock
[6 * c
], &key64
);
1276 clearTraceLog
= false;
1280 // Use the common format below
1281 // PrintAndLog("Found valid key:[%d:%c]%012" PRIx64, blockNo, (keyAB & 0x01)?'B':'A', key64);
1284 // Store the Single Key for display list
1285 // For a single block check, SectorsCnt = Sector that contains the block
1286 e_sector
[SectorsCnt
-1].foundKey
[(keyAB
& 0x01)] = true; // flag key found
1287 e_sector
[SectorsCnt
-1].Key
[(keyAB
& 0x01)] = key64
; // Save key data
1291 PrintAndLog("Command execute timeout");
1294 } while(--keyAB
> 0);
1300 PrintAndLog("|---|----------------|----------------|");
1301 PrintAndLog("|sec|key A |key B |");
1302 PrintAndLog("|---|----------------|----------------|");
1303 for (i
= 0; i
< SectorsCnt
; i
++) {
1304 // If a block key check, only print a line if a key was found.
1305 if (!singleBlock
|| e_sector
[i
].foundKey
[0] || e_sector
[i
].foundKey
[1]) {
1306 char keyAString
[13] = " ? ";
1307 char keyBString
[13] = " ? ";
1308 if (e_sector
[i
].foundKey
[0]) {
1309 sprintf(keyAString
, "%012" PRIx64
, e_sector
[i
].Key
[0]);
1311 if (e_sector
[i
].foundKey
[1]) {
1312 sprintf(keyBString
, "%012" PRIx64
, e_sector
[i
].Key
[1]);
1314 PrintAndLog("|%03d| %s | %s |", i
, keyAString
, keyBString
);
1317 PrintAndLog("|---|----------------|----------------|");
1320 PrintAndLog("No valid keys found.");
1323 if (transferToEml
) {
1325 for (uint16_t sectorNo
= 0; sectorNo
< SectorsCnt
; sectorNo
++) {
1326 if (e_sector
[sectorNo
].foundKey
[0] || e_sector
[sectorNo
].foundKey
[1]) {
1327 mfEmlGetMem(block
, FirstBlockOfSector(sectorNo
) + NumBlocksPerSector(sectorNo
) - 1, 1);
1328 for (uint16_t t
= 0; t
< 2; t
++) {
1329 if (e_sector
[sectorNo
].foundKey
[t
]) {
1330 num_to_bytes(e_sector
[sectorNo
].Key
[t
], 6, block
+ t
* 10);
1331 keyFoundCount
++; // Key found count for information
1334 mfEmlSetMem(block
, FirstBlockOfSector(sectorNo
) + NumBlocksPerSector(sectorNo
) - 1, 1);
1337 // Updated to show the actual number of keys found/transfered.
1338 PrintAndLog("%d keys(s) found have been transferred to the emulator memory",keyFoundCount
);
1341 if (createDumpFile
&& !singleBlock
) {
1342 FILE *fkeys
= fopen("dumpkeys.bin","wb");
1343 if (fkeys
== NULL
) {
1344 PrintAndLog("Could not create file dumpkeys.bin");
1350 for (uint8_t t
= 0; t
< 2; t
++) {
1351 for (uint8_t sectorNo
= 0; sectorNo
< SectorsCnt
; sectorNo
++) {
1352 num_to_bytes(e_sector
[sectorNo
].Key
[t
], 6, mkey
);
1353 fwrite(mkey
, 1, 6, fkeys
);
1357 PrintAndLog("Found keys have been dumped to file dumpkeys.bin. 0xffffffffffff has been inserted for unknown keys.");
1367 void readerAttack(nonces_t ar_resp
[], bool setEmulatorMem
, bool doStandardAttack
) {
1368 #define ATTACK_KEY_COUNT 7 // keep same as define in iso14443a.c -> Mifare1ksim()
1369 // cannot be more than 7 or it will overrun c.d.asBytes(512)
1375 st_t sector_trailer
[ATTACK_KEY_COUNT
];
1376 memset(sector_trailer
, 0x00, sizeof(sector_trailer
));
1378 uint8_t stSector
[ATTACK_KEY_COUNT
];
1379 memset(stSector
, 0x00, sizeof(stSector
));
1380 uint8_t key_cnt
[ATTACK_KEY_COUNT
];
1381 memset(key_cnt
, 0x00, sizeof(key_cnt
));
1383 for (uint8_t i
= 0; i
<ATTACK_KEY_COUNT
; i
++) {
1384 if (ar_resp
[i
].ar2
> 0) {
1385 //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);
1386 if (doStandardAttack
&& mfkey32(ar_resp
[i
], &key
)) {
1387 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));
1389 for (uint8_t ii
= 0; ii
<ATTACK_KEY_COUNT
; ii
++) {
1390 if (key_cnt
[ii
]==0 || stSector
[ii
]==ar_resp
[i
].sector
) {
1391 if (ar_resp
[i
].keytype
==0) {
1393 sector_trailer
[ii
].keyA
= key
;
1394 stSector
[ii
] = ar_resp
[i
].sector
;
1399 sector_trailer
[ii
].keyB
= key
;
1400 stSector
[ii
] = ar_resp
[i
].sector
;
1406 } else if (mfkey32_moebius(ar_resp
[i
+ATTACK_KEY_COUNT
], &key
)) {
1407 uint8_t sectorNum
= ar_resp
[i
+ATTACK_KEY_COUNT
].sector
;
1408 uint8_t keyType
= ar_resp
[i
+ATTACK_KEY_COUNT
].keytype
;
1410 PrintAndLog("M-Found Key%s for sector %02d: [%012" PRIx64
"]"
1411 , keyType
? "B" : "A"
1416 for (uint8_t ii
= 0; ii
<ATTACK_KEY_COUNT
; ii
++) {
1417 if (key_cnt
[ii
]==0 || stSector
[ii
]==sectorNum
) {
1420 sector_trailer
[ii
].keyA
= key
;
1421 stSector
[ii
] = sectorNum
;
1426 sector_trailer
[ii
].keyB
= key
;
1427 stSector
[ii
] = sectorNum
;
1437 //set emulator memory for keys
1438 if (setEmulatorMem
) {
1439 for (uint8_t i
= 0; i
<ATTACK_KEY_COUNT
; i
++) {
1441 uint8_t memBlock
[16];
1442 memset(memBlock
, 0x00, sizeof(memBlock
));
1444 memset(cmd1
,0x00,sizeof(cmd1
));
1445 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));
1446 PrintAndLog("Setting Emulator Memory Block %02d: [%s]",stSector
[i
]*4+3, cmd1
);
1447 if (param_gethex(cmd1
, 0, memBlock
, 32)) {
1448 PrintAndLog("block data must include 32 HEX symbols");
1452 UsbCommand c
= {CMD_MIFARE_EML_MEMSET
, {(stSector
[i
]*4+3), 1, 0}};
1453 memcpy(c
.d
.asBytes
, memBlock
, 16);
1454 clearCommandBuffer();
1460 //un-comment to use as well moebius attack
1461 for (uint8_t i = ATTACK_KEY_COUNT; i<ATTACK_KEY_COUNT*2; i++) {
1462 if (ar_resp[i].ar2 > 0) {
1463 if (tryMfk32_moebius(ar_resp[i], &key)) {
1464 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));
1470 int usage_hf14_mfsim(void) {
1471 PrintAndLog("Usage: hf mf sim [h] [*<card memory>] [u <uid (8, 14, or 20 hex symbols)>] [n <numreads>] [i] [x]");
1472 PrintAndLog("options:");
1473 PrintAndLog(" h (Optional) this help");
1474 PrintAndLog(" card memory: 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other, default> - 1K");
1475 PrintAndLog(" u (Optional) UID 4 or 7 bytes. If not specified, the UID 4B from emulator memory will be used");
1476 PrintAndLog(" n (Optional) Automatically exit simulation after <numreads> blocks have been read by reader. 0 = infinite");
1477 PrintAndLog(" i (Optional) Interactive, means that console will not be returned until simulation finishes or is aborted");
1478 PrintAndLog(" x (Optional) Crack, performs the 'reader attack', nr/ar attack against a legitimate reader, fishes out the key(s)");
1479 PrintAndLog(" e (Optional) set keys found from 'reader attack' to emulator memory (implies x and i)");
1480 PrintAndLog(" f (Optional) get UIDs to use for 'reader attack' from file 'f <filename.txt>' (implies x and i)");
1481 PrintAndLog(" r (Optional) Generate random nonces instead of sequential nonces. Standard reader attack won't work with this option, only moebius attack works.");
1482 PrintAndLog("samples:");
1483 PrintAndLog(" hf mf sim u 0a0a0a0a");
1484 PrintAndLog(" hf mf sim *4");
1485 PrintAndLog(" hf mf sim u 11223344556677");
1486 PrintAndLog(" hf mf sim f uids.txt");
1487 PrintAndLog(" hf mf sim u 0a0a0a0a e");
1492 int CmdHF14AMfSim(const char *Cmd
) {
1494 uint8_t uid
[7] = {0};
1495 uint8_t exitAfterNReads
= 0;
1498 bool setEmulatorMem
= false;
1499 bool attackFromFile
= false;
1501 char filename
[FILE_PATH_SIZE
];
1502 memset(filename
, 0x00, sizeof(filename
));
1507 bool errors
= false;
1508 uint8_t cardsize
= '1';
1510 while(param_getchar(Cmd
, cmdp
) != 0x00) {
1511 switch(param_getchar(Cmd
, cmdp
)) {
1513 cardsize
= param_getchar(Cmd
+ 1, cmdp
);
1519 default: cardsize
= '1';
1525 setEmulatorMem
= true;
1527 flags
|= FLAG_INTERACTIVE
;
1528 flags
|= FLAG_NR_AR_ATTACK
;
1533 len
= param_getstr(Cmd
, cmdp
+1, filename
, sizeof(filename
));
1535 PrintAndLog("error no filename found");
1538 attackFromFile
= true;
1540 flags
|= FLAG_INTERACTIVE
;
1541 flags
|= FLAG_NR_AR_ATTACK
;
1546 return usage_hf14_mfsim();
1549 flags
|= FLAG_INTERACTIVE
;
1554 exitAfterNReads
= param_get8(Cmd
, cmdp
+1);
1559 flags
|= FLAG_RANDOM_NONCE
;
1565 if (param_gethex_ex(Cmd
, cmdp
+1, uid
, &uidlen
)) {
1566 return usage_hf14_mfsim();
1569 case 14: flags
= FLAG_7B_UID_IN_DATA
; break;
1570 case 8: flags
= FLAG_4B_UID_IN_DATA
; break;
1571 default: return usage_hf14_mfsim();
1577 flags
|= FLAG_NR_AR_ATTACK
;
1581 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd
, cmdp
));
1588 if(errors
) return usage_hf14_mfsim();
1591 if (attackFromFile
) {
1594 f
= fopen(filename
, "r");
1596 PrintAndLog("File %s not found or locked", filename
);
1599 PrintAndLog("Loading file and simulating. Press keyboard to abort");
1600 while(!feof(f
) && !ukbhit()){
1601 memset(buf
, 0, sizeof(buf
));
1602 memset(uid
, 0, sizeof(uid
));
1604 if (fgets(buf
, sizeof(buf
), f
) == NULL
) {
1605 if (count
> 0) break;
1607 PrintAndLog("File reading error.");
1611 if(!strlen(buf
) && feof(f
)) break;
1613 uidlen
= strlen(buf
)-1;
1615 case 14: flags
|= FLAG_7B_UID_IN_DATA
; break;
1616 case 8: flags
|= FLAG_4B_UID_IN_DATA
; break;
1618 PrintAndLog("uid in file wrong length at %d (length: %d) [%s]",count
, uidlen
, buf
);
1623 for (uint8_t i
= 0; i
< uidlen
; i
+= 2) {
1624 sscanf(&buf
[i
], "%02x", (unsigned int *)&uid
[i
/ 2]);
1627 PrintAndLog("mf sim cardsize: %s, uid: %s, numreads:%d, flags:%d (0x%02x) - press button to abort",
1628 cardsize
== '0' ? "Mini" :
1629 cardsize
== '2' ? "2K" :
1630 cardsize
== '4' ? "4K" : "1K",
1631 flags
& FLAG_4B_UID_IN_DATA
? sprint_hex(uid
,4):
1632 flags
& FLAG_7B_UID_IN_DATA
? sprint_hex(uid
,7): "N/A",
1637 UsbCommand c
= {CMD_SIMULATE_MIFARE_CARD
, {flags
, exitAfterNReads
, cardsize
}};
1638 memcpy(c
.d
.asBytes
, uid
, sizeof(uid
));
1639 clearCommandBuffer();
1642 while (! WaitForResponseTimeout(CMD_ACK
,&resp
,1500)) {
1643 //We're waiting only 1.5 s at a time, otherwise we get the
1644 // annoying message about "Waiting for a response... "
1647 nonces_t ar_resp
[ATTACK_KEY_COUNT
*2];
1648 memcpy(ar_resp
, resp
.d
.asBytes
, sizeof(ar_resp
));
1649 // We can skip the standard attack if we have RANDOM_NONCE set.
1650 readerAttack(ar_resp
, setEmulatorMem
, !(flags
& FLAG_RANDOM_NONCE
));
1651 if ((bool)resp
.arg
[1]) {
1652 PrintAndLog("Device button pressed - quitting");
1660 } else { //not from file
1662 PrintAndLog("mf sim cardsize: %s, uid: %s, numreads:%d, flags:%d (0x%02x) ",
1663 cardsize
== '0' ? "Mini" :
1664 cardsize
== '2' ? "2K" :
1665 cardsize
== '4' ? "4K" : "1K",
1666 flags
& FLAG_4B_UID_IN_DATA
? sprint_hex(uid
,4):
1667 flags
& FLAG_7B_UID_IN_DATA
? sprint_hex(uid
,7): "N/A",
1672 UsbCommand c
= {CMD_SIMULATE_MIFARE_CARD
, {flags
, exitAfterNReads
, cardsize
}};
1673 memcpy(c
.d
.asBytes
, uid
, sizeof(uid
));
1674 clearCommandBuffer();
1677 if(flags
& FLAG_INTERACTIVE
) {
1678 PrintAndLog("Press pm3-button to abort simulation");
1679 while(! WaitForResponseTimeout(CMD_ACK
, &resp
, 1500)) {
1680 //We're waiting only 1.5 s at a time, otherwise we get the
1681 // annoying message about "Waiting for a response... "
1684 if (flags
& FLAG_NR_AR_ATTACK
) {
1685 nonces_t ar_resp
[ATTACK_KEY_COUNT
*2];
1686 memcpy(ar_resp
, resp
.d
.asBytes
, sizeof(ar_resp
));
1687 // We can skip the standard attack if we have RANDOM_NONCE set.
1688 readerAttack(ar_resp
, setEmulatorMem
, !(flags
& FLAG_RANDOM_NONCE
));
1696 int CmdHF14AMfDbg(const char *Cmd
)
1698 int dbgMode
= param_get32ex(Cmd
, 0, 0, 10);
1700 PrintAndLog("Max debug mode parameter is 4 \n");
1703 if (strlen(Cmd
) < 1 || !param_getchar(Cmd
, 0) || dbgMode
> 4) {
1704 PrintAndLog("Usage: hf mf dbg <debug level>");
1705 PrintAndLog(" 0 - no debug messages");
1706 PrintAndLog(" 1 - error messages");
1707 PrintAndLog(" 2 - plus information messages");
1708 PrintAndLog(" 3 - plus debug messages");
1709 PrintAndLog(" 4 - print even debug messages in timing critical functions");
1710 PrintAndLog(" Note: this option therefore may cause malfunction itself");
1714 UsbCommand c
= {CMD_MIFARE_SET_DBGMODE
, {dbgMode
, 0, 0}};
1720 int CmdHF14AMfEGet(const char *Cmd
)
1722 uint8_t blockNo
= 0;
1723 uint8_t data
[16] = {0x00};
1725 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
1726 PrintAndLog("Usage: hf mf eget <block number>");
1727 PrintAndLog(" sample: hf mf eget 0 ");
1731 blockNo
= param_get8(Cmd
, 0);
1734 if (!mfEmlGetMem(data
, blockNo
, 1)) {
1735 PrintAndLog("data[%3d]:%s", blockNo
, sprint_hex(data
, 16));
1737 PrintAndLog("Command execute timeout");
1743 int CmdHF14AMfEClear(const char *Cmd
)
1745 if (param_getchar(Cmd
, 0) == 'h') {
1746 PrintAndLog("Usage: hf mf eclr");
1747 PrintAndLog("It set card emulator memory to empty data blocks and key A/B FFFFFFFFFFFF \n");
1751 UsbCommand c
= {CMD_MIFARE_EML_MEMCLR
, {0, 0, 0}};
1757 int CmdHF14AMfESet(const char *Cmd
)
1759 uint8_t memBlock
[16];
1760 uint8_t blockNo
= 0;
1762 memset(memBlock
, 0x00, sizeof(memBlock
));
1764 if (strlen(Cmd
) < 3 || param_getchar(Cmd
, 0) == 'h') {
1765 PrintAndLog("Usage: hf mf eset <block number> <block data (32 hex symbols)>");
1766 PrintAndLog(" sample: hf mf eset 1 000102030405060708090a0b0c0d0e0f ");
1770 blockNo
= param_get8(Cmd
, 0);
1772 if (param_gethex(Cmd
, 1, memBlock
, 32)) {
1773 PrintAndLog("block data must include 32 HEX symbols");
1778 return mfEmlSetMem(memBlock
, blockNo
, 1);
1782 int CmdHF14AMfELoad(const char *Cmd
)
1785 char filename
[FILE_PATH_SIZE
];
1786 char *fnameptr
= filename
;
1787 char buf
[64] = {0x00};
1788 uint8_t buf8
[64] = {0x00};
1789 int i
, len
, blockNum
, numBlocks
;
1790 int nameParamNo
= 1;
1792 char ctmp
= param_getchar(Cmd
, 0);
1794 if ( ctmp
== 'h' || ctmp
== 0x00) {
1795 PrintAndLog("It loads emul dump from the file `filename.eml`");
1796 PrintAndLog("Usage: hf mf eload [card memory] <file name w/o `.eml`>");
1797 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1799 PrintAndLog(" sample: hf mf eload filename");
1800 PrintAndLog(" hf mf eload 4 filename");
1805 case '0' : numBlocks
= 5*4; break;
1807 case '\0': numBlocks
= 16*4; break;
1808 case '2' : numBlocks
= 32*4; break;
1809 case '4' : numBlocks
= 256; break;
1816 len
= param_getstr(Cmd
, nameParamNo
, filename
, sizeof(filename
));
1818 if (len
> FILE_PATH_SIZE
- 5) len
= FILE_PATH_SIZE
- 5;
1822 sprintf(fnameptr
, ".eml");
1825 f
= fopen(filename
, "r");
1827 PrintAndLog("File %s not found or locked", filename
);
1833 memset(buf
, 0, sizeof(buf
));
1835 if (fgets(buf
, sizeof(buf
), f
) == NULL
) {
1837 if (blockNum
>= numBlocks
) break;
1839 PrintAndLog("File reading error.");
1844 if (strlen(buf
) < 32){
1845 if(strlen(buf
) && feof(f
))
1847 PrintAndLog("File content error. Block data must include 32 HEX symbols");
1852 for (i
= 0; i
< 32; i
+= 2) {
1853 sscanf(&buf
[i
], "%02x", (unsigned int *)&buf8
[i
/ 2]);
1856 if (mfEmlSetMem(buf8
, blockNum
, 1)) {
1857 PrintAndLog("Cant set emul block: %3d", blockNum
);
1864 if (blockNum
>= numBlocks
) break;
1869 if ((blockNum
!= numBlocks
)) {
1870 PrintAndLog("File content error. Got %d must be %d blocks.",blockNum
, numBlocks
);
1873 PrintAndLog("Loaded %d blocks from file: %s", blockNum
, filename
);
1878 int CmdHF14AMfESave(const char *Cmd
)
1881 char filename
[FILE_PATH_SIZE
];
1882 char * fnameptr
= filename
;
1884 int i
, j
, len
, numBlocks
;
1885 int nameParamNo
= 1;
1887 memset(filename
, 0, sizeof(filename
));
1888 memset(buf
, 0, sizeof(buf
));
1890 char ctmp
= param_getchar(Cmd
, 0);
1892 if ( ctmp
== 'h' || ctmp
== 'H') {
1893 PrintAndLog("It saves emul dump into the file `filename.eml` or `cardID.eml`");
1894 PrintAndLog(" Usage: hf mf esave [card memory] [file name w/o `.eml`]");
1895 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1897 PrintAndLog(" sample: hf mf esave ");
1898 PrintAndLog(" hf mf esave 4");
1899 PrintAndLog(" hf mf esave 4 filename");
1904 case '0' : numBlocks
= 5*4; break;
1906 case '\0': numBlocks
= 16*4; break;
1907 case '2' : numBlocks
= 32*4; break;
1908 case '4' : numBlocks
= 256; break;
1915 len
= param_getstr(Cmd
,nameParamNo
,filename
,sizeof(filename
));
1917 if (len
> FILE_PATH_SIZE
- 5) len
= FILE_PATH_SIZE
- 5;
1919 // user supplied filename?
1921 // get filename (UID from memory)
1922 if (mfEmlGetMem(buf
, 0, 1)) {
1923 PrintAndLog("Can\'t get UID from block: %d", 0);
1924 len
= sprintf(fnameptr
, "dump");
1928 for (j
= 0; j
< 7; j
++, fnameptr
+= 2)
1929 sprintf(fnameptr
, "%02X", buf
[j
]);
1935 // add file extension
1936 sprintf(fnameptr
, ".eml");
1939 f
= fopen(filename
, "w+");
1942 PrintAndLog("Can't open file %s ", filename
);
1947 for (i
= 0; i
< numBlocks
; i
++) {
1948 if (mfEmlGetMem(buf
, i
, 1)) {
1949 PrintAndLog("Cant get block: %d", i
);
1952 for (j
= 0; j
< 16; j
++)
1953 fprintf(f
, "%02X", buf
[j
]);
1958 PrintAndLog("Saved %d blocks to file: %s", numBlocks
, filename
);
1964 int CmdHF14AMfECFill(const char *Cmd
)
1966 uint8_t keyType
= 0;
1967 uint8_t numSectors
= 16;
1969 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
1970 PrintAndLog("Usage: hf mf ecfill <key A/B> [card memory]");
1971 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1973 PrintAndLog("samples: hf mf ecfill A");
1974 PrintAndLog(" hf mf ecfill A 4");
1975 PrintAndLog("Read card and transfer its data to emulator memory.");
1976 PrintAndLog("Keys must be laid in the emulator memory. \n");
1980 char ctmp
= param_getchar(Cmd
, 0);
1981 if (ctmp
!= 'a' && ctmp
!= 'A' && ctmp
!= 'b' && ctmp
!= 'B') {
1982 PrintAndLog("Key type must be A or B");
1985 if (ctmp
!= 'A' && ctmp
!= 'a') keyType
= 1;
1987 ctmp
= param_getchar(Cmd
, 1);
1989 case '0' : numSectors
= 5; break;
1991 case '\0': numSectors
= 16; break;
1992 case '2' : numSectors
= 32; break;
1993 case '4' : numSectors
= 40; break;
1994 default: numSectors
= 16;
1997 printf("--params: numSectors: %d, keyType:%d\n", numSectors
, keyType
);
1998 UsbCommand c
= {CMD_MIFARE_EML_CARDLOAD
, {numSectors
, keyType
, 0}};
2004 int CmdHF14AMfEKeyPrn(const char *Cmd
)
2007 uint8_t numSectors
= 16;
2009 uint64_t keyA
, keyB
;
2010 bool createDumpFile
= false;
2012 if (param_getchar(Cmd
, 0) == 'h') {
2013 PrintAndLog("It prints the keys loaded in the emulator memory");
2014 PrintAndLog("Usage: hf mf ekeyprn [card memory] [d]");
2015 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
2016 PrintAndLog(" [d] : write keys to binary file dumpkeys.bin");
2018 PrintAndLog(" sample: hf mf ekeyprn 1");
2023 while (param_getchar(Cmd
, cmdp
) != 0x00) {
2024 switch (param_getchar(Cmd
, cmdp
)) {
2025 case '0' : numSectors
= 5; break;
2027 case '\0': numSectors
= 16; break;
2028 case '2' : numSectors
= 32; break;
2029 case '4' : numSectors
= 40; break;
2031 case 'D' : createDumpFile
= true; break;
2036 PrintAndLog("|---|----------------|----------------|");
2037 PrintAndLog("|sec|key A |key B |");
2038 PrintAndLog("|---|----------------|----------------|");
2039 for (i
= 0; i
< numSectors
; i
++) {
2040 if (mfEmlGetMem(data
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1)) {
2041 PrintAndLog("error get block %d", FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1);
2044 keyA
= bytes_to_num(data
, 6);
2045 keyB
= bytes_to_num(data
+ 10, 6);
2046 PrintAndLog("|%03d| %012" PRIx64
" | %012" PRIx64
" |", i
, keyA
, keyB
);
2048 PrintAndLog("|---|----------------|----------------|");
2051 if (createDumpFile
) {
2053 if ((fkeys
= fopen("dumpkeys.bin","wb")) == NULL
) {
2054 PrintAndLog("Could not create file dumpkeys.bin");
2057 PrintAndLog("Printing keys to binary file dumpkeys.bin...");
2058 for(i
= 0; i
< numSectors
; i
++) {
2059 if (mfEmlGetMem(data
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1)) {
2060 PrintAndLog("error get block %d", FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1);
2063 fwrite(data
+6, 1, 6, fkeys
);
2065 for(i
= 0; i
< numSectors
; i
++) {
2066 if (mfEmlGetMem(data
, FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1, 1)) {
2067 PrintAndLog("error get block %d", FirstBlockOfSector(i
) + NumBlocksPerSector(i
) - 1);
2070 fwrite(data
+10, 1, 6, fkeys
);
2079 int CmdHF14AMfCSetUID(const char *Cmd
)
2081 uint8_t uid
[8] = {0x00};
2082 uint8_t oldUid
[8] = {0x00};
2083 uint8_t atqa
[2] = {0x00};
2084 uint8_t sak
[1] = {0x00};
2085 uint8_t atqaPresent
= 0;
2088 uint8_t needHelp
= 0;
2091 if (param_getchar(Cmd
, 0) && param_gethex(Cmd
, 0, uid
, 8)) {
2092 PrintAndLog("UID must include 8 HEX symbols");
2096 if (param_getlength(Cmd
, 1) > 1 && param_getlength(Cmd
, 2) > 1) {
2100 if (param_gethex(Cmd
, 1, atqa
, 4)) {
2101 PrintAndLog("ATQA must include 4 HEX symbols");
2105 if (param_gethex(Cmd
, 2, sak
, 2)) {
2106 PrintAndLog("SAK must include 2 HEX symbols");
2111 while(param_getchar(Cmd
, cmdp
) != 0x00)
2113 switch(param_getchar(Cmd
, cmdp
))
2120 PrintAndLog("ERROR: Unknown parameter '%c'", param_getchar(Cmd
, cmdp
));
2127 if (strlen(Cmd
) < 1 || needHelp
) {
2129 PrintAndLog("Usage: hf mf csetuid <UID 8 hex symbols> [ATQA 4 hex symbols SAK 2 hex symbols]");
2130 PrintAndLog("sample: hf mf csetuid 01020304");
2131 PrintAndLog("sample: hf mf csetuid 01020304 0004 08");
2132 PrintAndLog("Set UID, ATQA, and SAK for magic Chinese card (only works with such cards)");
2136 PrintAndLog("uid:%s", sprint_hex(uid
, 4));
2138 PrintAndLog("--atqa:%s sak:%02x", sprint_hex(atqa
, 2), sak
[0]);
2141 res
= mfCSetUID(uid
, (atqaPresent
)?atqa
:NULL
, (atqaPresent
)?sak
:NULL
, oldUid
);
2143 PrintAndLog("Can't set UID. Error=%d", res
);
2147 PrintAndLog("old UID:%s", sprint_hex(oldUid
, 4));
2148 PrintAndLog("new UID:%s", sprint_hex(uid
, 4));
2152 int CmdHF14AMfCWipe(const char *Cmd
)
2155 int numBlocks
= 16 * 4;
2156 bool wipeCard
= false;
2157 bool fillCard
= false;
2159 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
2160 PrintAndLog("Usage: hf mf cwipe [card size] [w] [f]");
2161 PrintAndLog("sample: hf mf cwipe 1 w f");
2162 PrintAndLog("[card size]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
2163 PrintAndLog("w - Wipe magic Chinese card (only works with gen:1a cards)");
2164 PrintAndLog("f - Fill the card with default data and keys (works with gen:1a and gen:1b cards only)");
2168 gen
= mfCIdentify();
2169 if ((gen
!= 1) && (gen
!= 2))
2172 numBlocks
= ParamCardSizeBlocks(param_getchar(Cmd
, 0));
2175 while(param_getchar(Cmd
, cmdp
) != 0x00){
2176 switch(param_getchar(Cmd
, cmdp
)) {
2191 if (!wipeCard
&& !fillCard
)
2194 PrintAndLog("--blocks count:%2d wipe:%c fill:%c", numBlocks
, (wipeCard
)?'y':'n', (fillCard
)?'y':'n');
2197 /* generation 1b magic card */
2199 PrintAndLog("WARNING: can't wipe magic card 1b generation");
2201 res
= mfCWipe(numBlocks
, true, false, fillCard
);
2203 /* generation 1a magic card by default */
2204 res
= mfCWipe(numBlocks
, false, wipeCard
, fillCard
);
2208 PrintAndLog("Can't wipe. error=%d", res
);
2215 int CmdHF14AMfCSetBlk(const char *Cmd
)
2217 uint8_t memBlock
[16] = {0x00};
2218 uint8_t blockNo
= 0;
2219 bool wipeCard
= false;
2222 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
2223 PrintAndLog("Usage: hf mf csetblk <block number> <block data (32 hex symbols)> [w]");
2224 PrintAndLog("sample: hf mf csetblk 1 01020304050607080910111213141516");
2225 PrintAndLog("Set block data for magic Chinese card (only works with such cards)");
2226 PrintAndLog("If you also want wipe the card then add 'w' at the end of the command line");
2230 gen
= mfCIdentify();
2231 if ((gen
!= 1) && (gen
!= 2))
2234 blockNo
= param_get8(Cmd
, 0);
2236 if (param_gethex(Cmd
, 1, memBlock
, 32)) {
2237 PrintAndLog("block data must include 32 HEX symbols");
2241 char ctmp
= param_getchar(Cmd
, 2);
2242 wipeCard
= (ctmp
== 'w' || ctmp
== 'W');
2243 PrintAndLog("--block number:%2d data:%s", blockNo
, sprint_hex(memBlock
, 16));
2246 /* generation 1b magic card */
2247 res
= mfCSetBlock(blockNo
, memBlock
, NULL
, wipeCard
, CSETBLOCK_SINGLE_OPER
| CSETBLOCK_MAGIC_1B
);
2249 /* generation 1a magic card by default */
2250 res
= mfCSetBlock(blockNo
, memBlock
, NULL
, wipeCard
, CSETBLOCK_SINGLE_OPER
);
2254 PrintAndLog("Can't write block. error=%d", res
);
2261 int CmdHF14AMfCLoad(const char *Cmd
)
2264 char filename
[FILE_PATH_SIZE
] = {0x00};
2265 char * fnameptr
= filename
;
2266 char buf
[256] = {0x00};
2267 uint8_t buf8
[256] = {0x00};
2268 uint8_t fillFromEmulator
= 0;
2269 int i
, len
, blockNum
, flags
= 0, gen
= 0, numblock
= 64;
2271 if (param_getchar(Cmd
, 0) == 'h' || param_getchar(Cmd
, 0)== 0x00) {
2272 PrintAndLog("It loads magic Chinese card from the file `filename.eml`");
2273 PrintAndLog("or from emulator memory (option `e`). 4K card: (option `4`)");
2274 PrintAndLog("Usage: hf mf cload [file name w/o `.eml`][e][4]");
2275 PrintAndLog(" or: hf mf cload e [4]");
2276 PrintAndLog("Sample: hf mf cload filename");
2277 PrintAndLog(" hf mf cload filname 4");
2278 PrintAndLog(" hf mf cload e");
2279 PrintAndLog(" hf mf cload e 4");
2283 char ctmp
= param_getchar(Cmd
, 0);
2284 if (ctmp
== 'e' || ctmp
== 'E') fillFromEmulator
= 1;
2285 ctmp
= param_getchar(Cmd
, 1);
2286 if (ctmp
== '4') numblock
= 256;
2288 gen
= mfCIdentify();
2289 PrintAndLog("Loading magic mifare %dK", numblock
== 256 ? 4:1);
2291 if (fillFromEmulator
) {
2292 for (blockNum
= 0; blockNum
< numblock
; blockNum
+= 1) {
2293 if (mfEmlGetMem(buf8
, blockNum
, 1)) {
2294 PrintAndLog("Cant get block: %d", blockNum
);
2297 if (blockNum
== 0) flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
; // switch on field and send magic sequence
2298 if (blockNum
== 1) flags
= 0; // just write
2299 if (blockNum
== numblock
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
; // Done. Magic Halt and switch off field.
2302 /* generation 1b magic card */
2303 flags
|= CSETBLOCK_MAGIC_1B
;
2304 if (mfCSetBlock(blockNum
, buf8
, NULL
, 0, flags
)) {
2305 PrintAndLog("Cant set magic card block: %d", blockNum
);
2311 param_getstr(Cmd
, 0, filename
, sizeof(filename
));
2313 len
= strlen(filename
);
2314 if (len
> FILE_PATH_SIZE
- 5) len
= FILE_PATH_SIZE
- 5;
2316 //memcpy(filename, Cmd, len);
2319 sprintf(fnameptr
, ".eml");
2322 f
= fopen(filename
, "r");
2324 PrintAndLog("File not found or locked.");
2331 memset(buf
, 0, sizeof(buf
));
2333 if (fgets(buf
, sizeof(buf
), f
) == NULL
) {
2335 PrintAndLog("File reading error.");
2339 if (strlen(buf
) < 32) {
2340 if(strlen(buf
) && feof(f
))
2342 PrintAndLog("File content error. Block data must include 32 HEX symbols");
2346 for (i
= 0; i
< 32; i
+= 2)
2347 sscanf(&buf
[i
], "%02x", (unsigned int *)&buf8
[i
/ 2]);
2349 if (blockNum
== 0) flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
; // switch on field and send magic sequence
2350 if (blockNum
== 1) flags
= 0; // just write
2351 if (blockNum
== numblock
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
; // Done. Switch off field.
2354 /* generation 1b magic card */
2355 flags
|= CSETBLOCK_MAGIC_1B
;
2356 if (mfCSetBlock(blockNum
, buf8
, NULL
, 0, flags
)) {
2357 PrintAndLog("Can't set magic card block: %d", blockNum
);
2363 if (blockNum
>= numblock
) break; // magic card type - mifare 1K 64 blocks, mifare 4k 256 blocks
2367 //if (blockNum != 16 * 4 && blockNum != 32 * 4 + 8 * 16){
2368 if (blockNum
!= numblock
){
2369 PrintAndLog("File content error. There must be %d blocks", numblock
);
2372 PrintAndLog("Loaded from file: %s", filename
);
2378 int CmdHF14AMfCGetBlk(const char *Cmd
) {
2379 uint8_t memBlock
[16];
2380 uint8_t blockNo
= 0;
2382 memset(memBlock
, 0x00, sizeof(memBlock
));
2384 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
2385 PrintAndLog("Usage: hf mf cgetblk <block number>");
2386 PrintAndLog("sample: hf mf cgetblk 1");
2387 PrintAndLog("Get block data from magic Chinese card (only works with such cards)\n");
2391 gen
= mfCIdentify();
2393 blockNo
= param_get8(Cmd
, 0);
2395 PrintAndLog("--block number:%2d ", blockNo
);
2398 /* generation 1b magic card */
2399 res
= mfCGetBlock(blockNo
, memBlock
, CSETBLOCK_SINGLE_OPER
| CSETBLOCK_MAGIC_1B
);
2401 /* generation 1a magic card by default */
2402 res
= mfCGetBlock(blockNo
, memBlock
, CSETBLOCK_SINGLE_OPER
);
2405 PrintAndLog("Can't read block. error=%d", res
);
2409 PrintAndLog("block data:%s", sprint_hex(memBlock
, 16));
2411 if (mfIsSectorTrailer(blockNo
)) {
2412 PrintAndLogEx(NORMAL
, "Trailer decoded:");
2413 PrintAndLogEx(NORMAL
, "Key A: %s", sprint_hex_inrow(memBlock
, 6));
2414 PrintAndLogEx(NORMAL
, "Key B: %s", sprint_hex_inrow(&memBlock
[10], 6));
2415 int bln
= mfFirstBlockOfSector(mfSectorNum(blockNo
));
2416 int blinc
= (mfNumBlocksPerSector(mfSectorNum(blockNo
)) > 4) ? 5 : 1;
2417 for (int i
= 0; i
< 4; i
++) {
2418 PrintAndLogEx(NORMAL
, "Access block %d%s: %s", bln
, ((blinc
> 1) && (i
< 3) ? "+" : "") , mfGetAccessConditionsDesc(i
, &memBlock
[6]));
2421 PrintAndLogEx(NORMAL
, "UserData: %s", sprint_hex_inrow(&memBlock
[9], 1));
2427 int CmdHF14AMfCGetSc(const char *Cmd
) {
2428 uint8_t memBlock
[16] = {0x00};
2429 uint8_t sectorNo
= 0;
2430 int i
, res
, flags
, gen
= 0, baseblock
= 0, sect_size
= 4;
2432 if (strlen(Cmd
) < 1 || param_getchar(Cmd
, 0) == 'h') {
2433 PrintAndLog("Usage: hf mf cgetsc <sector number>");
2434 PrintAndLog("sample: hf mf cgetsc 0");
2435 PrintAndLog("Get sector data from magic Chinese card (only works with such cards)\n");
2439 sectorNo
= param_get8(Cmd
, 0);
2441 if (sectorNo
> 39) {
2442 PrintAndLog("Sector number must be in [0..15] in MIFARE classic 1k and [0..39] in MIFARE classic 4k.");
2446 PrintAndLog("--sector number:%d ", sectorNo
);
2448 gen
= mfCIdentify();
2450 flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
;
2451 if (sectorNo
< 32 ) {
2452 baseblock
= sectorNo
* 4;
2454 baseblock
= 128 + 16 * (sectorNo
- 32);
2457 if (sectorNo
> 31) sect_size
= 16;
2459 for (i
= 0; i
< sect_size
; i
++) {
2460 if (i
== 1) flags
= 0;
2461 if (i
== sect_size
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
;
2464 /* generation 1b magic card */
2465 flags
|= CSETBLOCK_MAGIC_1B
;
2467 res
= mfCGetBlock(baseblock
+ i
, memBlock
, flags
);
2469 PrintAndLog("Can't read block. %d error=%d", baseblock
+ i
, res
);
2473 PrintAndLog("block %3d data:%s", baseblock
+ i
, sprint_hex(memBlock
, 16));
2475 if (mfIsSectorTrailer(baseblock
+ i
)) {
2476 PrintAndLogEx(NORMAL
, "Trailer decoded:");
2477 PrintAndLogEx(NORMAL
, "Key A: %s", sprint_hex_inrow(memBlock
, 6));
2478 PrintAndLogEx(NORMAL
, "Key B: %s", sprint_hex_inrow(&memBlock
[10], 6));
2479 int bln
= baseblock
;
2480 int blinc
= (mfNumBlocksPerSector(sectorNo
) > 4) ? 5 : 1;
2481 for (int i
= 0; i
< 4; i
++) {
2482 PrintAndLogEx(NORMAL
, "Access block %d%s: %s", bln
, ((blinc
> 1) && (i
< 3) ? "+" : "") , mfGetAccessConditionsDesc(i
, &memBlock
[6]));
2485 PrintAndLogEx(NORMAL
, "UserData: %s", sprint_hex_inrow(&memBlock
[9], 1));
2492 int CmdHF14AMfCSave(const char *Cmd
) {
2495 char filename
[FILE_PATH_SIZE
] = {0x00};
2496 char * fnameptr
= filename
;
2497 uint8_t fillFromEmulator
= 0;
2498 uint8_t buf
[256] = {0x00};
2499 int i
, j
, len
, flags
, gen
= 0, numblock
= 64;
2501 // memset(filename, 0, sizeof(filename));
2502 // memset(buf, 0, sizeof(buf));
2504 if (param_getchar(Cmd
, 0) == 'h') {
2505 PrintAndLog("It saves `magic Chinese` card dump into the file `filename.eml` or `cardID.eml`");
2506 PrintAndLog("or into emulator memory (option `e`). 4K card: (option `4`)");
2507 PrintAndLog("Usage: hf mf csave [file name w/o `.eml`][e][4]");
2508 PrintAndLog("Sample: hf mf csave ");
2509 PrintAndLog(" hf mf csave filename");
2510 PrintAndLog(" hf mf csave e");
2511 PrintAndLog(" hf mf csave 4");
2512 PrintAndLog(" hf mf csave filename 4");
2513 PrintAndLog(" hf mf csave e 4");
2517 char ctmp
= param_getchar(Cmd
, 0);
2518 if (ctmp
== 'e' || ctmp
== 'E') fillFromEmulator
= 1;
2519 if (ctmp
== '4') numblock
= 256;
2520 ctmp
= param_getchar(Cmd
, 1);
2521 if (ctmp
== '4') numblock
= 256;
2523 gen
= mfCIdentify();
2524 PrintAndLog("Saving magic mifare %dK", numblock
== 256 ? 4:1);
2526 if (fillFromEmulator
) {
2527 // put into emulator
2528 flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
;
2529 for (i
= 0; i
< numblock
; i
++) {
2530 if (i
== 1) flags
= 0;
2531 if (i
== numblock
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
;
2534 /* generation 1b magic card */
2535 flags
|= CSETBLOCK_MAGIC_1B
;
2537 if (mfCGetBlock(i
, buf
, flags
)) {
2538 PrintAndLog("Cant get block: %d", i
);
2542 if (mfEmlSetMem(buf
, i
, 1)) {
2543 PrintAndLog("Cant set emul block: %d", i
);
2549 param_getstr(Cmd
, 0, filename
, sizeof(filename
));
2551 len
= strlen(filename
);
2552 if (len
> FILE_PATH_SIZE
- 5) len
= FILE_PATH_SIZE
- 5;
2554 ctmp
= param_getchar(Cmd
, 0);
2555 if (len
< 1 || (ctmp
== '4')) {
2558 flags
= CSETBLOCK_SINGLE_OPER
;
2560 /* generation 1b magic card */
2561 flags
|= CSETBLOCK_MAGIC_1B
;
2562 if (mfCGetBlock(0, buf
, flags
)) {
2563 PrintAndLog("Cant get block: %d", 0);
2564 len
= sprintf(fnameptr
, "dump");
2568 for (j
= 0; j
< 7; j
++, fnameptr
+= 2)
2569 sprintf(fnameptr
, "%02x", buf
[j
]);
2572 //memcpy(filename, Cmd, len);
2576 sprintf(fnameptr
, ".eml");
2579 f
= fopen(filename
, "w+");
2582 PrintAndLog("File not found or locked.");
2587 flags
= CSETBLOCK_INIT_FIELD
+ CSETBLOCK_WUPC
;
2588 for (i
= 0; i
< numblock
; i
++) {
2589 if (i
== 1) flags
= 0;
2590 if (i
== numblock
- 1) flags
= CSETBLOCK_HALT
+ CSETBLOCK_RESET_FIELD
;
2593 /* generation 1b magic card */
2594 flags
|= CSETBLOCK_MAGIC_1B
;
2595 if (mfCGetBlock(i
, buf
, flags
)) {
2596 PrintAndLog("Cant get block: %d", i
);
2599 for (j
= 0; j
< 16; j
++)
2600 fprintf(f
, "%02x", buf
[j
]);
2605 PrintAndLog("Saved to file: %s", filename
);
2612 int CmdHF14AMfSniff(const char *Cmd
){
2614 bool wantLogToFile
= 0;
2615 bool wantDecrypt
= 0;
2616 //bool wantSaveToEml = 0; TODO
2617 bool wantSaveToEmlFile
= 0;
2628 uint8_t atqa
[2] = {0x00};
2631 uint8_t *buf
= NULL
;
2632 uint16_t bufsize
= 0;
2633 uint8_t *bufPtr
= NULL
;
2636 char ctmp
= param_getchar(Cmd
, 0);
2637 if ( ctmp
== 'h' || ctmp
== 'H' ) {
2638 PrintAndLog("It continuously gets data from the field and saves it to: log, emulator, emulator file.");
2639 PrintAndLog("You can specify:");
2640 PrintAndLog(" l - save encrypted sequence to logfile `uid.log`");
2641 PrintAndLog(" d - decrypt sequence and put it to log file `uid.log`");
2642 PrintAndLog(" n/a e - decrypt sequence, collect read and write commands and save the result of the sequence to emulator memory");
2643 PrintAndLog(" f - decrypt sequence, collect read and write commands and save the result of the sequence to emulator dump file `uid.eml`");
2644 PrintAndLog("Usage: hf mf sniff [l][d][e][f]");
2645 PrintAndLog(" sample: hf mf sniff l d e");
2649 for (int i
= 0; i
< 4; i
++) {
2650 ctmp
= param_getchar(Cmd
, i
);
2651 if (ctmp
== 'l' || ctmp
== 'L') wantLogToFile
= true;
2652 if (ctmp
== 'd' || ctmp
== 'D') wantDecrypt
= true;
2653 //if (ctmp == 'e' || ctmp == 'E') wantSaveToEml = true; TODO
2654 if (ctmp
== 'f' || ctmp
== 'F') wantSaveToEmlFile
= true;
2657 printf("-------------------------------------------------------------------------\n");
2658 printf("Executing command. \n");
2659 printf("Press the key on the proxmark3 device to abort both proxmark3 and client.\n");
2660 printf("Press the key on pc keyboard to abort the client.\n");
2661 printf("-------------------------------------------------------------------------\n");
2663 UsbCommand c
= {CMD_MIFARE_SNIFFER
, {0, 0, 0}};
2664 clearCommandBuffer();
2673 printf("\naborted via keyboard!\n");
2678 if (WaitForResponseTimeoutW(CMD_ACK
, &resp
, 2000, false)) {
2679 res
= resp
.arg
[0] & 0xff;
2680 uint16_t traceLen
= resp
.arg
[1];
2683 if (res
== 0) { // we are done
2687 if (res
== 1) { // there is (more) data to be transferred
2688 if (pckNum
== 0) { // first packet, (re)allocate necessary buffer
2689 if (traceLen
> bufsize
|| buf
== NULL
) {
2691 if (buf
== NULL
) { // not yet allocated
2692 p
= malloc(traceLen
);
2693 } else { // need more memory
2694 p
= realloc(buf
, traceLen
);
2697 PrintAndLog("Cannot allocate memory for trace");
2705 memset(buf
, 0x00, traceLen
);
2707 memcpy(bufPtr
, resp
.d
.asBytes
, len
);
2712 if (res
== 2) { // received all data, start displaying
2713 blockLen
= bufPtr
- buf
;
2716 PrintAndLog("received trace len: %d packages: %d", blockLen
, pckNum
);
2717 while (bufPtr
- buf
< blockLen
) {
2718 bufPtr
+= 6; // skip (void) timing information
2719 len
= *((uint16_t *)bufPtr
);
2726 parlen
= (len
- 1) / 8 + 1;
2728 if ((len
== 14) && (bufPtr
[0] == 0xff) && (bufPtr
[1] == 0xff) && (bufPtr
[12] == 0xff) && (bufPtr
[13] == 0xff)) {
2729 memcpy(uid
, bufPtr
+ 2, 7);
2730 memcpy(atqa
, bufPtr
+ 2 + 7, 2);
2731 uid_len
= (atqa
[0] & 0xC0) == 0x40 ? 7 : 4;
2733 PrintAndLog("tag select uid:%s atqa:0x%02x%02x sak:0x%02x",
2734 sprint_hex(uid
+ (7 - uid_len
), uid_len
),
2738 if (wantLogToFile
|| wantDecrypt
) {
2739 FillFileNameByUID(logHexFileName
, uid
+ (7 - uid_len
), ".log", uid_len
);
2740 AddLogCurrentDT(logHexFileName
);
2743 mfTraceInit(uid
, atqa
, sak
, wantSaveToEmlFile
);
2745 oddparitybuf(bufPtr
, len
, parity
);
2746 PrintAndLog("%s(%d):%s [%s] c[%s]%c",
2747 isTag
? "TAG":"RDR",
2749 sprint_hex(bufPtr
, len
),
2750 printBitsPar(bufPtr
+ len
, len
),
2751 printBitsPar(parity
, len
),
2752 memcmp(bufPtr
+ len
, parity
, len
/ 8 + 1) ? '!' : ' ');
2754 AddLogHex(logHexFileName
, isTag
? "TAG: ":"RDR: ", bufPtr
, len
);
2756 mfTraceDecode(bufPtr
, len
, bufPtr
[len
], wantSaveToEmlFile
);
2760 bufPtr
+= parlen
; // ignore parity
2769 msleep(300); // wait for exiting arm side.
2770 PrintAndLog("Done.");
2774 //needs nt, ar, at, Data to decrypt
2775 int CmdDecryptTraceCmds(const char *Cmd
){
2778 param_gethex_ex(Cmd
, 3, data
, &len
);
2779 return tryDecryptWord(param_get32ex(Cmd
, 0, 0, 16), param_get32ex(Cmd
, 1, 0, 16), param_get32ex(Cmd
, 2, 0, 16), data
, len
/2);
2782 int CmdHF14AMfAuth4(const char *cmd
) {
2783 uint8_t keyn
[20] = {0};
2785 uint8_t key
[16] = {0};
2788 CLIParserInit("hf mf auth4",
2789 "Executes AES authentication command in ISO14443-4",
2790 "Usage:\n\thf mf auth4 4000 000102030405060708090a0b0c0d0e0f -> executes authentication\n"
2791 "\thf mf auth4 9003 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -> executes authentication\n");
2793 void* argtable
[] = {
2795 arg_str1(NULL
, NULL
, "<Key Num (HEX 2 bytes)>", NULL
),
2796 arg_str1(NULL
, NULL
, "<Key Value (HEX 16 bytes)>", NULL
),
2799 CLIExecWithReturn(cmd
, argtable
, true);
2801 CLIGetHexWithReturn(1, keyn
, &keynlen
);
2802 CLIGetHexWithReturn(2, key
, &keylen
);
2806 PrintAndLog("ERROR: <Key Num> must be 2 bytes long instead of: %d", keynlen
);
2811 PrintAndLog("ERROR: <Key Value> must be 16 bytes long instead of: %d", keylen
);
2815 return MifareAuth4(NULL
, keyn
, key
, true, false, true);
2818 // https://www.nxp.com/docs/en/application-note/AN10787.pdf
2819 int CmdHF14AMfMAD(const char *cmd
) {
2821 CLIParserInit("hf mf mad",
2822 "Checks and prints Mifare Application Directory (MAD)",
2823 "Usage:\n\thf mf mad -> shows MAD if exists\n"
2824 "\thf mf mad -a 03e1 -k ffffffffffff -b -> shows NDEF data if exists. read card with custom key and key B\n");
2826 void *argtable
[] = {
2828 arg_lit0("vV", "verbose", "show technical data"),
2829 arg_str0("aA", "aid", "print all sectors with aid", NULL
),
2830 arg_str0("kK", "key", "key for printing sectors", NULL
),
2831 arg_lit0("bB", "keyb", "use key B for access printing sectors (by default: key A)"),
2834 CLIExecWithReturn(cmd
, argtable
, true);
2835 bool verbose
= arg_get_lit(1);
2836 uint8_t aid
[2] = {0};
2838 CLIGetHexWithReturn(2, aid
, &aidlen
);
2839 uint8_t key
[6] = {0};
2841 CLIGetHexWithReturn(3, key
, &keylen
);
2842 bool keyB
= arg_get_lit(4);
2846 if (aidlen
!= 2 && keylen
> 0) {
2847 PrintAndLogEx(WARNING
, "do not need a key without aid.");
2850 uint8_t sector0
[16 * 4] = {0};
2851 uint8_t sector10
[16 * 4] = {0};
2852 if (mfReadSector(MF_MAD1_SECTOR
, MF_KEY_A
, (uint8_t *)g_mifare_mad_key
, sector0
)) {
2853 PrintAndLogEx(ERR
, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");
2858 for (int i
= 0; i
< 4; i
++)
2859 PrintAndLogEx(NORMAL
, "[%d] %s", i
, sprint_hex(§or0
[i
* 16], 16));
2862 bool haveMAD2
= false;
2863 MAD1DecodeAndPrint(sector0
, verbose
, &haveMAD2
);
2866 if (mfReadSector(MF_MAD2_SECTOR
, MF_KEY_A
, (uint8_t *)g_mifare_mad_key
, sector10
)) {
2867 PrintAndLogEx(ERR
, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");
2871 MAD2DecodeAndPrint(sector10
, verbose
);
2875 uint16_t aaid
= (aid
[0] << 8) + aid
[1];
2876 PrintAndLogEx(NORMAL
, "\n-------------- AID 0x%04x ---------------", aaid
);
2878 uint16_t mad
[7 + 8 + 8 + 8 + 8] = {0};
2880 if (MADDecode(sector0
, sector10
, mad
, &madlen
)) {
2881 PrintAndLogEx(ERR
, "can't decode mad.");
2885 uint8_t akey
[6] = {0};
2886 memcpy(akey
, g_mifare_ndef_key
, 6);
2888 memcpy(akey
, key
, 6);
2891 for (int i
= 0; i
< madlen
; i
++) {
2892 if (aaid
== mad
[i
]) {
2893 uint8_t vsector
[16 * 4] = {0};
2894 if (mfReadSector(i
+ 1, keyB
? MF_KEY_B
: MF_KEY_A
, akey
, vsector
)) {
2895 PrintAndLogEx(NORMAL
, "");
2896 PrintAndLogEx(ERR
, "read sector %d error.", i
+ 1);
2900 for (int j
= 0; j
< (verbose
? 4 : 3); j
++)
2901 PrintAndLogEx(NORMAL
, " [%03d] %s", (i
+ 1) * 4 + j
, sprint_hex(&vsector
[j
* 16], 16));
2909 int CmdHFMFNDEF(const char *cmd
) {
2911 CLIParserInit("hf mf ndef",
2912 "Prints NFC Data Exchange Format (NDEF)",
2913 "Usage:\n\thf mf ndef -> shows NDEF data\n"
2914 "\thf mf ndef -a 03e1 -k ffffffffffff -b -> shows NDEF data with custom AID, key and with key B\n");
2916 void *argtable
[] = {
2918 arg_litn("vV", "verbose", 0, 2, "show technical data"),
2919 arg_str0("aA", "aid", "replace default aid for NDEF", NULL
),
2920 arg_str0("kK", "key", "replace default key for NDEF", NULL
),
2921 arg_lit0("bB", "keyb", "use key B for access sectors (by default: key A)"),
2924 CLIExecWithReturn(cmd
, argtable
, true);
2926 bool verbose
= arg_get_lit(1);
2927 bool verbose2
= arg_get_lit(1) > 1;
2928 uint8_t aid
[2] = {0};
2930 CLIGetHexWithReturn(2, aid
, &aidlen
);
2931 uint8_t key
[6] = {0};
2933 CLIGetHexWithReturn(3, key
, &keylen
);
2934 bool keyB
= arg_get_lit(4);
2938 uint16_t ndefAID
= 0x03e1;
2940 ndefAID
= (aid
[0] << 8) + aid
[1];
2942 uint8_t ndefkey
[6] = {0};
2943 memcpy(ndefkey
, g_mifare_ndef_key
, 6);
2945 memcpy(ndefkey
, key
, 6);
2948 uint8_t sector0
[16 * 4] = {0};
2949 uint8_t sector10
[16 * 4] = {0};
2950 uint8_t data
[4096] = {0};
2953 PrintAndLogEx(NORMAL
, "");
2955 if (mfReadSector(MF_MAD1_SECTOR
, MF_KEY_A
, (uint8_t *)g_mifare_mad_key
, sector0
)) {
2956 PrintAndLogEx(ERR
, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");
2960 bool haveMAD2
= false;
2961 int res
= MADCheck(sector0
, NULL
, verbose
, &haveMAD2
);
2963 PrintAndLogEx(ERR
, "MAD error %d.", res
);
2968 if (mfReadSector(MF_MAD2_SECTOR
, MF_KEY_A
, (uint8_t *)g_mifare_mad_key
, sector10
)) {
2969 PrintAndLogEx(ERR
, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");
2974 uint16_t mad
[7 + 8 + 8 + 8 + 8] = {0};
2976 if (MADDecode(sector0
, (haveMAD2
? sector10
: NULL
), mad
, &madlen
)) {
2977 PrintAndLogEx(ERR
, "can't decode mad.");
2981 printf("data reading:");
2982 for (int i
= 0; i
< madlen
; i
++) {
2983 if (ndefAID
== mad
[i
]) {
2984 uint8_t vsector
[16 * 4] = {0};
2985 if (mfReadSector(i
+ 1, keyB
? MF_KEY_B
: MF_KEY_A
, ndefkey
, vsector
)) {
2986 PrintAndLogEx(ERR
, "read sector %d error.", i
+ 1);
2990 memcpy(&data
[datalen
], vsector
, 16 * 3);
2999 PrintAndLogEx(ERR
, "no NDEF data.");
3004 PrintAndLogEx(NORMAL
, "NDEF data:");
3005 dump_buffer(data
, datalen
, stdout
, 1);
3008 NDEFDecodeAndPrint(data
, datalen
, verbose
);
3013 int CmdHFMFPersonalize(const char *cmd
) {
3015 CLIParserInit("hf mf personalize",
3016 "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.",
3017 "Usage:\n\thf mf personalize UIDF0 -> double size UID according to ISO/IEC14443-3\n"
3018 "\thf mf personalize UIDF1 -> double size UID according to ISO/IEC14443-3, optional usage of selection process shortcut\n"
3019 "\thf mf personalize UIDF2 -> single size random ID according to ISO/IEC14443-3\n"
3020 "\thf mf personalize UIDF3 -> single size NUID according to ISO/IEC14443-3\n"
3021 "\thf mf personalize -t B -k B0B1B2B3B4B5 UIDF3 -> use key B = 0xB0B1B2B3B4B5 instead of default key A\n");
3023 void *argtable
[] = {
3025 arg_str0("tT", "keytype", "<A|B>", "key type (A or B) to authenticate sector 0 (default: A)"),
3026 arg_str0("kK", "key", "<key (hex 6 Bytes)>", "key to authenticate sector 0 (default: FFFFFFFFFFFF)"),
3027 arg_str1(NULL
, NULL
, "<UIDF0|UIDF1|UIDF2|UIDF3>", "Personalization Option"),
3030 CLIExecWithReturn(cmd
, argtable
, true);
3032 char keytypestr
[2] = "A";
3033 uint8_t keytype
= 0x00;
3035 int res
= CLIParamStrToBuf(arg_get_str(1), (uint8_t*)keytypestr
, 1, &keytypestr_len
);
3036 if (res
|| (keytypestr
[0] != 'a' && keytypestr
[0] != 'A' && keytypestr
[0] != 'b' && keytypestr
[0] != 'B')) {
3037 PrintAndLog("ERROR: not a valid key type. Key type must be A or B");
3041 if (keytypestr
[0] == 'B' || keytypestr
[0] == 'b') {
3045 uint8_t key
[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
3047 res
= CLIParamHexToBuf(arg_get_str(2), key
, 6, &key_len
);
3048 if (res
|| (!res
&& key_len
> 0 && key_len
!= 6)) {
3049 PrintAndLog("ERROR: not a valid key. Key must be 12 hex digits");
3054 char pers_optionstr
[6];
3056 uint8_t pers_option
;
3057 res
= CLIParamStrToBuf(arg_get_str(3), (uint8_t*)pers_optionstr
, 5, &opt_len
);
3058 if (res
|| (!res
&& opt_len
> 0 && opt_len
!= 5)
3059 || (strncmp(pers_optionstr
, "UIDF0", 5) && strncmp(pers_optionstr
, "UIDF1", 5) && strncmp(pers_optionstr
, "UIDF2", 5) && strncmp(pers_optionstr
, "UIDF3", 5))) {
3060 PrintAndLog("ERROR: invalid personalization option. Must be one of UIDF0, UIDF1, UIDF2, or UIDF3");
3064 if (!strncmp(pers_optionstr
, "UIDF0", 5)) {
3065 pers_option
= MIFARE_EV1_UIDF0
;
3066 } else if (!strncmp(pers_optionstr
, "UIDF1", 5)) {
3067 pers_option
= MIFARE_EV1_UIDF1
;
3068 } else if (!strncmp(pers_optionstr
, "UIDF2", 5)) {
3069 pers_option
= MIFARE_EV1_UIDF2
;
3071 pers_option
= MIFARE_EV1_UIDF3
;
3076 UsbCommand c
= {CMD_MIFARE_PERSONALIZE_UID
, {keytype
, pers_option
, 0}};
3077 memcpy(c
.d
.asBytes
, key
, 6);
3081 if (WaitForResponseTimeout(CMD_ACK
, &resp
, 1500)) {
3082 uint8_t isOK
= resp
.arg
[0] & 0xff;
3083 PrintAndLog("Personalization %s", isOK
? "FAILED" : "SUCCEEDED");
3085 PrintAndLog("Command execute timeout");
3092 static command_t CommandTable
[] = {
3093 {"help", CmdHelp
, 1, "This help"},
3094 {"dbg", CmdHF14AMfDbg
, 0, "Set default debug mode"},
3095 {"rdbl", CmdHF14AMfRdBl
, 0, "Read MIFARE classic block"},
3096 {"rdsc", CmdHF14AMfRdSc
, 0, "Read MIFARE classic sector"},
3097 {"dump", CmdHF14AMfDump
, 0, "Dump MIFARE classic tag to binary file"},
3098 {"restore", CmdHF14AMfRestore
, 0, "Restore MIFARE classic binary file to BLANK tag"},
3099 {"wrbl", CmdHF14AMfWrBl
, 0, "Write MIFARE classic block"},
3100 {"auth4", CmdHF14AMfAuth4
, 0, "ISO14443-4 AES authentication"},
3101 {"chk", CmdHF14AMfChk
, 0, "Test block keys"},
3102 {"mifare", CmdHF14AMifare
, 0, "Read parity error messages."},
3103 {"hardnested", CmdHF14AMfNestedHard
, 0, "Nested attack for hardened Mifare cards"},
3104 {"nested", CmdHF14AMfNested
, 0, "Test nested authentication"},
3105 {"sniff", CmdHF14AMfSniff
, 0, "Sniff card-reader communication"},
3106 {"sim", CmdHF14AMfSim
, 0, "Simulate MIFARE card"},
3107 {"eclr", CmdHF14AMfEClear
, 0, "Clear simulator memory"},
3108 {"eget", CmdHF14AMfEGet
, 0, "Get simulator memory block"},
3109 {"eset", CmdHF14AMfESet
, 0, "Set simulator memory block"},
3110 {"eload", CmdHF14AMfELoad
, 0, "Load from file emul dump"},
3111 {"esave", CmdHF14AMfESave
, 0, "Save to file emul dump"},
3112 {"ecfill", CmdHF14AMfECFill
, 0, "Fill simulator memory with help of keys from simulator"},
3113 {"ekeyprn", CmdHF14AMfEKeyPrn
, 0, "Print keys from simulator memory"},
3114 {"cwipe", CmdHF14AMfCWipe
, 0, "Wipe magic Chinese card"},
3115 {"csetuid", CmdHF14AMfCSetUID
, 0, "Set UID for magic Chinese card"},
3116 {"csetblk", CmdHF14AMfCSetBlk
, 0, "Write block - Magic Chinese card"},
3117 {"cgetblk", CmdHF14AMfCGetBlk
, 0, "Read block - Magic Chinese card"},
3118 {"cgetsc", CmdHF14AMfCGetSc
, 0, "Read sector - Magic Chinese card"},
3119 {"cload", CmdHF14AMfCLoad
, 0, "Load dump into magic Chinese card"},
3120 {"csave", CmdHF14AMfCSave
, 0, "Save dump from magic Chinese card into file or emulator"},
3121 {"decrypt", CmdDecryptTraceCmds
, 1, "[nt] [ar_enc] [at_enc] [data] - to decrypt snoop or trace"},
3122 {"mad", CmdHF14AMfMAD
, 0, "Checks and prints MAD"},
3123 {"ndef", CmdHFMFNDEF
, 0, "Prints NDEF records from card"},
3124 {"personalize", CmdHFMFPersonalize
, 0, "Personalize UID (Mifare Classic EV1 only)"},
3125 {NULL
, NULL
, 0, NULL
}
3129 int CmdHFMF(const char *Cmd
) {
3130 (void)WaitForResponseTimeout(CMD_ACK
,NULL
,100);
3131 CmdsParse(CommandTable
, Cmd
);
3136 int CmdHelp(const char *Cmd
) {
3137 CmdsHelp(CommandTable
);