]> git.zerfleddert.de Git - proxmark3-svn/blob - client/cmdhfmf.c
Ndef and MAD (#801)
[proxmark3-svn] / client / cmdhfmf.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2011,2012 Merlok
3 //
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
6 // the license.
7 //-----------------------------------------------------------------------------
8 // High frequency MIFARE commands
9 //-----------------------------------------------------------------------------
10
11 #include "cmdhfmf.h"
12
13 #include <inttypes.h>
14 #include <string.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <ctype.h>
18 #include "comms.h"
19 #include "cmdmain.h"
20 #include "cmdhfmfhard.h"
21 #include "parity.h"
22 #include "util.h"
23 #include "util_posix.h"
24 #include "usb_cmd.h"
25 #include "ui.h"
26 #include "mifare/mifarehost.h"
27 #include "mifare.h"
28 #include "mifare/mfkey.h"
29 #include "hardnested/hardnested_bf_core.h"
30 #include "cliparser/cliparser.h"
31 #include "cmdhf14a.h"
32 #include "mifare/mifare4.h"
33 #include "mifare/mad.h"
34 #include "mifare/ndef.h"
35 #include "emv/dump.h"
36
37 #define NESTED_SECTOR_RETRY 10 // how often we try mfested() until we give up
38
39 static int CmdHelp(const char *Cmd);
40
41 int CmdHF14AMifare(const char *Cmd)
42 {
43 int isOK = 0;
44 uint64_t key = 0;
45 isOK = mfDarkside(&key);
46 switch (isOK) {
47 case -1 : PrintAndLog("Button pressed. Aborted."); return 1;
48 case -2 : PrintAndLog("Card is not vulnerable to Darkside attack (doesn't send NACK on authentication requests)."); return 1;
49 case -3 : PrintAndLog("Card is not vulnerable to Darkside attack (its random number generator is not predictable)."); return 1;
50 case -4 : PrintAndLog("Card is not vulnerable to Darkside attack (its random number generator seems to be based on the wellknown");
51 PrintAndLog("generating polynomial with 16 effective bits only, but shows unexpected behaviour."); return 1;
52 case -5 : PrintAndLog("Aborted via keyboard."); return 1;
53 default : PrintAndLog("Found valid key:%012" PRIx64 "\n", key);
54 }
55
56 PrintAndLog("");
57 return 0;
58 }
59
60
61 int CmdHF14AMfWrBl(const char *Cmd)
62 {
63 uint8_t blockNo = 0;
64 uint8_t keyType = 0;
65 uint8_t key[6] = {0, 0, 0, 0, 0, 0};
66 uint8_t bldata[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
67
68 char cmdp = 0x00;
69
70 if (strlen(Cmd)<3) {
71 PrintAndLog("Usage: hf mf wrbl <block number> <key A/B> <key (12 hex symbols)> <block data (32 hex symbols)>");
72 PrintAndLog(" sample: hf mf wrbl 0 A FFFFFFFFFFFF 000102030405060708090A0B0C0D0E0F");
73 return 0;
74 }
75
76 blockNo = param_get8(Cmd, 0);
77 cmdp = param_getchar(Cmd, 1);
78 if (cmdp == 0x00) {
79 PrintAndLog("Key type must be A or B");
80 return 1;
81 }
82 if (cmdp != 'A' && cmdp != 'a') keyType = 1;
83 if (param_gethex(Cmd, 2, key, 12)) {
84 PrintAndLog("Key must include 12 HEX symbols");
85 return 1;
86 }
87 if (param_gethex(Cmd, 3, bldata, 32)) {
88 PrintAndLog("Block data must include 32 HEX symbols");
89 return 1;
90 }
91 PrintAndLog("--block no:%d, key type:%c, key:%s", blockNo, keyType?'B':'A', sprint_hex(key, 6));
92 PrintAndLog("--data: %s", sprint_hex(bldata, 16));
93
94 UsbCommand c = {CMD_MIFARE_WRITEBL, {blockNo, keyType, 0}};
95 memcpy(c.d.asBytes, key, 6);
96 memcpy(c.d.asBytes + 10, bldata, 16);
97 SendCommand(&c);
98
99 UsbCommand resp;
100 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
101 uint8_t isOK = resp.arg[0] & 0xff;
102 PrintAndLog("isOk:%02x", isOK);
103 } else {
104 PrintAndLog("Command execute timeout");
105 }
106
107 return 0;
108 }
109
110 int CmdHF14AMfRdBl(const char *Cmd)
111 {
112 uint8_t blockNo = 0;
113 uint8_t keyType = 0;
114 uint8_t key[6] = {0, 0, 0, 0, 0, 0};
115
116 char cmdp = 0x00;
117
118
119 if (strlen(Cmd)<3) {
120 PrintAndLog("Usage: hf mf rdbl <block number> <key A/B> <key (12 hex symbols)>");
121 PrintAndLog(" sample: hf mf rdbl 0 A FFFFFFFFFFFF ");
122 return 0;
123 }
124
125 blockNo = param_get8(Cmd, 0);
126 cmdp = param_getchar(Cmd, 1);
127 if (cmdp == 0x00) {
128 PrintAndLog("Key type must be A or B");
129 return 1;
130 }
131 if (cmdp != 'A' && cmdp != 'a') keyType = 1;
132 if (param_gethex(Cmd, 2, key, 12)) {
133 PrintAndLog("Key must include 12 HEX symbols");
134 return 1;
135 }
136 PrintAndLog("--block no:%d, key type:%c, key:%s ", blockNo, keyType?'B':'A', sprint_hex(key, 6));
137
138 UsbCommand c = {CMD_MIFARE_READBL, {blockNo, keyType, 0}};
139 memcpy(c.d.asBytes, key, 6);
140 SendCommand(&c);
141
142 UsbCommand resp;
143 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
144 uint8_t isOK = resp.arg[0] & 0xff;
145 uint8_t *data = resp.d.asBytes;
146
147 if (isOK) {
148 PrintAndLog("isOk:%02x data:%s", isOK, sprint_hex(data, 16));
149 } else {
150 PrintAndLog("isOk:%02x", isOK);
151 return 1;
152 }
153
154 if (mfIsSectorTrailer(blockNo) && (data[6] || data[7] || data[8])) {
155 PrintAndLogEx(NORMAL, "Trailer decoded:");
156 int bln = mfFirstBlockOfSector(mfSectorNum(blockNo));
157 int blinc = (mfNumBlocksPerSector(mfSectorNum(blockNo)) > 4) ? 5 : 1;
158 for (int i = 0; i < 4; i++) {
159 PrintAndLogEx(NORMAL, "Access block %d%s: %s", bln, ((blinc > 1) && (i < 3) ? "+" : "") , mfGetAccessConditionsDesc(i, &data[6]));
160 bln += blinc;
161 }
162 PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&data[9], 1));
163 }
164 } else {
165 PrintAndLog("Command execute timeout");
166 return 2;
167 }
168
169 return 0;
170 }
171
172 int CmdHF14AMfRdSc(const char *Cmd)
173 {
174 int i;
175 uint8_t sectorNo = 0;
176 uint8_t keyType = 0;
177 uint8_t key[6] = {0, 0, 0, 0, 0, 0};
178 uint8_t isOK = 0;
179 uint8_t *data = NULL;
180 char cmdp = 0x00;
181
182 if (strlen(Cmd)<3) {
183 PrintAndLog("Usage: hf mf rdsc <sector number> <key A/B> <key (12 hex symbols)>");
184 PrintAndLog(" sample: hf mf rdsc 0 A FFFFFFFFFFFF ");
185 return 0;
186 }
187
188 sectorNo = param_get8(Cmd, 0);
189 if (sectorNo > 39) {
190 PrintAndLog("Sector number must be less than 40");
191 return 1;
192 }
193 cmdp = param_getchar(Cmd, 1);
194 if (cmdp != 'a' && cmdp != 'A' && cmdp != 'b' && cmdp != 'B') {
195 PrintAndLog("Key type must be A or B");
196 return 1;
197 }
198 if (cmdp != 'A' && cmdp != 'a') keyType = 1;
199 if (param_gethex(Cmd, 2, key, 12)) {
200 PrintAndLog("Key must include 12 HEX symbols");
201 return 1;
202 }
203 PrintAndLog("--sector no:%d key type:%c key:%s ", sectorNo, keyType?'B':'A', sprint_hex(key, 6));
204
205 UsbCommand c = {CMD_MIFARE_READSC, {sectorNo, keyType, 0}};
206 memcpy(c.d.asBytes, key, 6);
207 SendCommand(&c);
208 PrintAndLog(" ");
209
210 UsbCommand resp;
211 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
212 isOK = resp.arg[0] & 0xff;
213 data = resp.d.asBytes;
214
215 PrintAndLog("isOk:%02x", isOK);
216 if (isOK) {
217 for (i = 0; i < (sectorNo<32?3:15); i++) {
218 PrintAndLog("data : %s", sprint_hex(data + i * 16, 16));
219 }
220 PrintAndLog("trailer: %s", sprint_hex(data + (sectorNo<32?3:15) * 16, 16));
221
222 PrintAndLogEx(NORMAL, "Trailer decoded:");
223 int bln = mfFirstBlockOfSector(sectorNo);
224 int blinc = (mfNumBlocksPerSector(sectorNo) > 4) ? 5 : 1;
225 for (i = 0; i < 4; i++) {
226 PrintAndLogEx(NORMAL, "Access block %d%s: %s", bln, ((blinc > 1) && (i < 3) ? "+" : "") , mfGetAccessConditionsDesc(i, &(data + (sectorNo<32?3:15) * 16)[6]));
227 bln += blinc;
228 }
229 PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&(data + (sectorNo<32?3:15) * 16)[9], 1));
230 }
231 } else {
232 PrintAndLog("Command execute timeout");
233 }
234
235 return 0;
236 }
237
238 uint8_t FirstBlockOfSector(uint8_t sectorNo)
239 {
240 if (sectorNo < 32) {
241 return sectorNo * 4;
242 } else {
243 return 32 * 4 + (sectorNo - 32) * 16;
244 }
245 }
246
247 uint8_t NumBlocksPerSector(uint8_t sectorNo)
248 {
249 if (sectorNo < 32) {
250 return 4;
251 } else {
252 return 16;
253 }
254 }
255
256 static int ParamCardSizeSectors(const char c) {
257 int numBlocks = 16;
258 switch (c) {
259 case '0' : numBlocks = 5; break;
260 case '2' : numBlocks = 32; break;
261 case '4' : numBlocks = 40; break;
262 default: numBlocks = 16;
263 }
264 return numBlocks;
265 }
266
267 static int ParamCardSizeBlocks(const char c) {
268 int numBlocks = 16 * 4;
269 switch (c) {
270 case '0' : numBlocks = 5 * 4; break;
271 case '2' : numBlocks = 32 * 4; break;
272 case '4' : numBlocks = 32 * 4 + 8 * 16; break;
273 default: numBlocks = 16 * 4;
274 }
275 return numBlocks;
276 }
277
278 int CmdHF14AMfDump(const char *Cmd)
279 {
280 uint8_t sectorNo, blockNo;
281
282 uint8_t keys[2][40][6];
283 uint8_t rights[40][4];
284 uint8_t carddata[256][16];
285 uint8_t numSectors = 16;
286
287 FILE *fin;
288 FILE *fout;
289
290 UsbCommand resp;
291
292 char cmdp = param_getchar(Cmd, 0);
293 numSectors = ParamCardSizeSectors(cmdp);
294
295 if (strlen(Cmd) > 3 || cmdp == 'h' || cmdp == 'H') {
296 PrintAndLog("Usage: hf mf dump [card memory] [k|m]");
297 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
298 PrintAndLog(" k: Always try using both Key A and Key B for each sector, even if access bits would prohibit it");
299 PrintAndLog(" m: When missing access bits or keys, replace that block with NULL");
300 PrintAndLog("");
301 PrintAndLog("Samples: hf mf dump");
302 PrintAndLog(" hf mf dump 4");
303 PrintAndLog(" hf mf dump 4 m");
304 return 0;
305 }
306
307 char opts = param_getchar(Cmd, 1);
308 bool useBothKeysAlways = false;
309 if (opts == 'k' || opts == 'K') useBothKeysAlways = true;
310 bool nullMissingKeys = false;
311 if (opts == 'm' || opts == 'M') nullMissingKeys = true;
312
313 if ((fin = fopen("dumpkeys.bin","rb")) == NULL) {
314 PrintAndLog("Could not find file dumpkeys.bin");
315 return 1;
316 }
317
318 // Read keys from file
319 for (int group=0; group<=1; group++) {
320 for (sectorNo=0; sectorNo<numSectors; sectorNo++) {
321 size_t bytes_read = fread(keys[group][sectorNo], 1, 6, fin);
322 if (bytes_read != 6) {
323 PrintAndLog("File reading error.");
324 fclose(fin);
325 return 2;
326 }
327 }
328 }
329
330 fclose(fin);
331
332 PrintAndLog("|-----------------------------------------|");
333 PrintAndLog("|------ Reading sector access bits...-----|");
334 PrintAndLog("|-----------------------------------------|");
335 uint8_t tries = 0;
336 for (sectorNo = 0; sectorNo < numSectors; sectorNo++) {
337 for (tries = 0; tries < 3; tries++) {
338 UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 0, 0}};
339 // At least the Access Conditions can always be read with key A.
340 memcpy(c.d.asBytes, keys[0][sectorNo], 6);
341 SendCommand(&c);
342
343 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
344 uint8_t isOK = resp.arg[0] & 0xff;
345 uint8_t *data = resp.d.asBytes;
346 if (isOK){
347 rights[sectorNo][0] = ((data[7] & 0x10)>>2) | ((data[8] & 0x1)<<1) | ((data[8] & 0x10)>>4); // C1C2C3 for data area 0
348 rights[sectorNo][1] = ((data[7] & 0x20)>>3) | ((data[8] & 0x2)<<0) | ((data[8] & 0x20)>>5); // C1C2C3 for data area 1
349 rights[sectorNo][2] = ((data[7] & 0x40)>>4) | ((data[8] & 0x4)>>1) | ((data[8] & 0x40)>>6); // C1C2C3 for data area 2
350 rights[sectorNo][3] = ((data[7] & 0x80)>>5) | ((data[8] & 0x8)>>2) | ((data[8] & 0x80)>>7); // C1C2C3 for sector trailer
351 break;
352 } else if (tries == 2) { // on last try set defaults
353 PrintAndLog("Could not get access rights for sector %2d. Trying with defaults...", sectorNo);
354 rights[sectorNo][0] = rights[sectorNo][1] = rights[sectorNo][2] = 0x00;
355 rights[sectorNo][3] = 0x01;
356 }
357 } else {
358 PrintAndLog("Command execute timeout when trying to read access rights for sector %2d. Trying with defaults...", sectorNo);
359 rights[sectorNo][0] = rights[sectorNo][1] = rights[sectorNo][2] = 0x00;
360 rights[sectorNo][3] = 0x01;
361 }
362 }
363 }
364
365 PrintAndLog("|-----------------------------------------|");
366 PrintAndLog("|----- Dumping all blocks to file... -----|");
367 PrintAndLog("|-----------------------------------------|");
368
369 bool isOK = true;
370 for (sectorNo = 0; isOK && sectorNo < numSectors; sectorNo++) {
371 for (blockNo = 0; isOK && blockNo < NumBlocksPerSector(sectorNo); blockNo++) {
372 bool received = false;
373 for (tries = 0; tries < 3; tries++) {
374 if (blockNo == NumBlocksPerSector(sectorNo) - 1) { // sector trailer. At least the Access Conditions can always be read with key A.
375 UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 0, 0}};
376 memcpy(c.d.asBytes, keys[0][sectorNo], 6);
377 SendCommand(&c);
378 received = WaitForResponseTimeout(CMD_ACK,&resp,1500);
379 } else if (useBothKeysAlways) {
380 // Always try both keys, even if access conditions wouldn't work.
381 for (int k=0; k<=1; k++) {
382 UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 1, 0}};
383 memcpy(c.d.asBytes, keys[k][sectorNo], 6);
384 SendCommand(&c);
385 received = WaitForResponseTimeout(CMD_ACK,&resp,1500);
386
387 // Don't try the other one on success.
388 if (resp.arg[0] & 0xff) break;
389 }
390 } else { // data block. Check if it can be read with key A or key B
391 uint8_t data_area = sectorNo<32?blockNo:blockNo/5;
392 if ((rights[sectorNo][data_area] == 0x03) || (rights[sectorNo][data_area] == 0x05)) { // only key B would work
393 UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 1, 0}};
394 memcpy(c.d.asBytes, keys[1][sectorNo], 6);
395 SendCommand(&c);
396 received = WaitForResponseTimeout(CMD_ACK,&resp,1500);
397 } else if (rights[sectorNo][data_area] == 0x07) { // no key would work
398 PrintAndLog("Access rights do not allow reading of sector %2d block %3d", sectorNo, blockNo);
399 if (nullMissingKeys) {
400 memset(resp.d.asBytes, 0, 16);
401 resp.arg[0] = 1;
402 PrintAndLog(" ... filling the block with NULL");
403 received = true;
404 } else {
405 isOK = false;
406 tries = 2;
407 }
408 } else { // key A would work
409 UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 0, 0}};
410 memcpy(c.d.asBytes, keys[0][sectorNo], 6);
411 SendCommand(&c);
412 received = WaitForResponseTimeout(CMD_ACK,&resp,1500);
413 }
414 }
415 if (received) {
416 isOK = resp.arg[0] & 0xff;
417 if (isOK) break;
418 }
419 }
420
421 if (received) {
422 isOK = resp.arg[0] & 0xff;
423 uint8_t *data = resp.d.asBytes;
424 if (blockNo == NumBlocksPerSector(sectorNo) - 1) { // sector trailer. Fill in the keys.
425 memcpy(data, keys[0][sectorNo], 6);
426 memcpy(data + 10, keys[1][sectorNo], 6);
427 }
428 if (isOK) {
429 memcpy(carddata[FirstBlockOfSector(sectorNo) + blockNo], data, 16);
430 PrintAndLog("Successfully read block %2d of sector %2d.", blockNo, sectorNo);
431 } else {
432 PrintAndLog("Could not read block %2d of sector %2d", blockNo, sectorNo);
433 break;
434 }
435 }
436 else {
437 isOK = false;
438 PrintAndLog("Command execute timeout when trying to read block %2d of sector %2d.", blockNo, sectorNo);
439 break;
440 }
441 }
442 }
443
444 if (isOK) {
445 if ((fout = fopen("dumpdata.bin","wb")) == NULL) {
446 PrintAndLog("Could not create file name dumpdata.bin");
447 return 1;
448 }
449 uint16_t numblocks = FirstBlockOfSector(numSectors - 1) + NumBlocksPerSector(numSectors - 1);
450 fwrite(carddata, 1, 16*numblocks, fout);
451 fclose(fout);
452 PrintAndLog("Dumped %d blocks (%d bytes) to file dumpdata.bin", numblocks, 16*numblocks);
453 }
454
455 return 0;
456 }
457
458 int CmdHF14AMfRestore(const char *Cmd)
459 {
460 uint8_t sectorNo,blockNo;
461 uint8_t keyType = 0;
462 uint8_t key[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
463 uint8_t bldata[16] = {0x00};
464 uint8_t keyA[40][6];
465 uint8_t keyB[40][6];
466 uint8_t numSectors;
467
468 FILE *fdump;
469 FILE *fkeys;
470
471 char cmdp = param_getchar(Cmd, 0);
472 switch (cmdp) {
473 case '0' : numSectors = 5; break;
474 case '1' :
475 case '\0': numSectors = 16; break;
476 case '2' : numSectors = 32; break;
477 case '4' : numSectors = 40; break;
478 default: numSectors = 16;
479 }
480
481 if (strlen(Cmd) > 1 || cmdp == 'h' || cmdp == 'H') {
482 PrintAndLog("Usage: hf mf restore [card memory]");
483 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
484 PrintAndLog("");
485 PrintAndLog("Samples: hf mf restore");
486 PrintAndLog(" hf mf restore 4");
487 return 0;
488 }
489
490 if ((fkeys = fopen("dumpkeys.bin","rb")) == NULL) {
491 PrintAndLog("Could not find file dumpkeys.bin");
492 return 1;
493 }
494
495 for (sectorNo = 0; sectorNo < numSectors; sectorNo++) {
496 size_t bytes_read = fread(keyA[sectorNo], 1, 6, fkeys);
497 if (bytes_read != 6) {
498 PrintAndLog("File reading error (dumpkeys.bin).");
499 fclose(fkeys);
500 return 2;
501 }
502 }
503
504 for (sectorNo = 0; sectorNo < numSectors; sectorNo++) {
505 size_t bytes_read = fread(keyB[sectorNo], 1, 6, fkeys);
506 if (bytes_read != 6) {
507 PrintAndLog("File reading error (dumpkeys.bin).");
508 fclose(fkeys);
509 return 2;
510 }
511 }
512
513 fclose(fkeys);
514
515 if ((fdump = fopen("dumpdata.bin","rb")) == NULL) {
516 PrintAndLog("Could not find file dumpdata.bin");
517 return 1;
518 }
519 PrintAndLog("Restoring dumpdata.bin to card");
520
521 for (sectorNo = 0; sectorNo < numSectors; sectorNo++) {
522 for(blockNo = 0; blockNo < NumBlocksPerSector(sectorNo); blockNo++) {
523 UsbCommand c = {CMD_MIFARE_WRITEBL, {FirstBlockOfSector(sectorNo) + blockNo, keyType, 0}};
524 memcpy(c.d.asBytes, key, 6);
525
526 size_t bytes_read = fread(bldata, 1, 16, fdump);
527 if (bytes_read != 16) {
528 PrintAndLog("File reading error (dumpdata.bin).");
529 fclose(fdump);
530 return 2;
531 }
532
533 if (blockNo == NumBlocksPerSector(sectorNo) - 1) { // sector trailer
534 bldata[0] = (keyA[sectorNo][0]);
535 bldata[1] = (keyA[sectorNo][1]);
536 bldata[2] = (keyA[sectorNo][2]);
537 bldata[3] = (keyA[sectorNo][3]);
538 bldata[4] = (keyA[sectorNo][4]);
539 bldata[5] = (keyA[sectorNo][5]);
540 bldata[10] = (keyB[sectorNo][0]);
541 bldata[11] = (keyB[sectorNo][1]);
542 bldata[12] = (keyB[sectorNo][2]);
543 bldata[13] = (keyB[sectorNo][3]);
544 bldata[14] = (keyB[sectorNo][4]);
545 bldata[15] = (keyB[sectorNo][5]);
546 }
547
548 PrintAndLog("Writing to block %3d: %s", FirstBlockOfSector(sectorNo) + blockNo, sprint_hex(bldata, 16));
549
550 memcpy(c.d.asBytes + 10, bldata, 16);
551 SendCommand(&c);
552
553 UsbCommand resp;
554 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
555 uint8_t isOK = resp.arg[0] & 0xff;
556 PrintAndLog("isOk:%02x", isOK);
557 } else {
558 PrintAndLog("Command execute timeout");
559 }
560 }
561 }
562
563 fclose(fdump);
564 return 0;
565 }
566
567 //----------------------------------------------
568 // Nested
569 //----------------------------------------------
570
571 static void parseParamTDS(const char *Cmd, const uint8_t indx, bool *paramT, bool *paramD, uint8_t *timeout) {
572 char ctmp3[4] = {0};
573 int len = param_getlength(Cmd, indx);
574 if (len > 0 && len < 4){
575 param_getstr(Cmd, indx, ctmp3, sizeof(ctmp3));
576
577 *paramT |= (ctmp3[0] == 't' || ctmp3[0] == 'T');
578 *paramD |= (ctmp3[0] == 'd' || ctmp3[0] == 'D');
579 bool paramS1 = *paramT || *paramD;
580
581 // slow and very slow
582 if (ctmp3[0] == 's' || ctmp3[0] == 'S' || ctmp3[1] == 's' || ctmp3[1] == 'S') {
583 *timeout = 11; // slow
584
585 if (!paramS1 && (ctmp3[1] == 's' || ctmp3[1] == 'S')) {
586 *timeout = 53; // very slow
587 }
588 if (paramS1 && (ctmp3[2] == 's' || ctmp3[2] == 'S')) {
589 *timeout = 53; // very slow
590 }
591 }
592 }
593 }
594
595 int CmdHF14AMfNested(const char *Cmd)
596 {
597 int i, j, res, iterations;
598 sector_t *e_sector = NULL;
599 uint8_t blockNo = 0;
600 uint8_t keyType = 0;
601 uint8_t trgBlockNo = 0;
602 uint8_t trgKeyType = 0;
603 uint8_t SectorsCnt = 0;
604 uint8_t key[6] = {0, 0, 0, 0, 0, 0};
605 uint8_t keyBlock[MifareDefaultKeysSize * 6];
606 uint64_t key64 = 0;
607 // timeout in units. (ms * 106)/10 or us*0.0106
608 uint8_t btimeout14a = MF_CHKKEYS_DEFTIMEOUT; // fast by default
609
610 bool autosearchKey = false;
611
612 bool transferToEml = false;
613 bool createDumpFile = false;
614 FILE *fkeys;
615 uint8_t standart[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
616 uint8_t tempkey[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
617
618 char cmdp, ctmp;
619
620 if (strlen(Cmd)<3) {
621 PrintAndLog("Usage:");
622 PrintAndLog(" all sectors: hf mf nested <card memory> <block number> <key A/B> <key (12 hex symbols)> [t|d|s|ss]");
623 PrintAndLog(" all sectors autosearch key: hf mf nested <card memory> * [t|d|s|ss]");
624 PrintAndLog(" one sector: hf mf nested o <block number> <key A/B> <key (12 hex symbols)>");
625 PrintAndLog(" <target block number> <target key A/B> [t]");
626 PrintAndLog(" ");
627 PrintAndLog("card memory - 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other> - 1K");
628 PrintAndLog("t - transfer keys to emulator memory");
629 PrintAndLog("d - write keys to binary file dumpkeys.bin");
630 PrintAndLog("s - Slow (1ms) check keys (required by some non standard cards)");
631 PrintAndLog("ss - Very slow (5ms) check keys");
632 PrintAndLog(" ");
633 PrintAndLog(" sample1: hf mf nested 1 0 A FFFFFFFFFFFF ");
634 PrintAndLog(" sample2: hf mf nested 1 0 A FFFFFFFFFFFF t ");
635 PrintAndLog(" sample3: hf mf nested 1 0 A FFFFFFFFFFFF d ");
636 PrintAndLog(" sample4: hf mf nested o 0 A FFFFFFFFFFFF 4 A");
637 PrintAndLog(" sample5: hf mf nested 1 * t");
638 PrintAndLog(" sample6: hf mf nested 1 * ss");
639 return 0;
640 }
641
642 // <card memory>
643 cmdp = param_getchar(Cmd, 0);
644 if (cmdp == 'o' || cmdp == 'O') {
645 cmdp = 'o';
646 SectorsCnt = 1;
647 } else {
648 SectorsCnt = ParamCardSizeSectors(cmdp);
649 }
650
651 // <block number>. number or autosearch key (*)
652 if (param_getchar(Cmd, 1) == '*') {
653 autosearchKey = true;
654
655 parseParamTDS(Cmd, 2, &transferToEml, &createDumpFile, &btimeout14a);
656
657 PrintAndLog("--nested. sectors:%2d, block no:*, eml:%c, dmp=%c checktimeout=%d us",
658 SectorsCnt, transferToEml?'y':'n', createDumpFile?'y':'n', ((int)btimeout14a * 10000) / 106);
659 } else {
660 blockNo = param_get8(Cmd, 1);
661
662 ctmp = param_getchar(Cmd, 2);
663 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {
664 PrintAndLog("Key type must be A or B");
665 return 1;
666 }
667
668 if (ctmp != 'A' && ctmp != 'a')
669 keyType = 1;
670
671 if (param_gethex(Cmd, 3, key, 12)) {
672 PrintAndLog("Key must include 12 HEX symbols");
673 return 1;
674 }
675
676 // check if we can authenticate to sector
677 res = mfCheckKeys(blockNo, keyType, true, 1, key, &key64);
678 if (res) {
679 PrintAndLog("Can't authenticate to block:%3d key type:%c key:%s", blockNo, keyType?'B':'A', sprint_hex(key, 6));
680 return 3;
681 }
682
683 // one sector nested
684 if (cmdp == 'o') {
685 trgBlockNo = param_get8(Cmd, 4);
686
687 ctmp = param_getchar(Cmd, 5);
688 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {
689 PrintAndLog("Target key type must be A or B");
690 return 1;
691 }
692 if (ctmp != 'A' && ctmp != 'a')
693 trgKeyType = 1;
694
695 parseParamTDS(Cmd, 6, &transferToEml, &createDumpFile, &btimeout14a);
696 } else {
697 parseParamTDS(Cmd, 4, &transferToEml, &createDumpFile, &btimeout14a);
698 }
699
700 PrintAndLog("--nested. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us",
701 SectorsCnt, blockNo, keyType?'B':'A', transferToEml?'y':'n', createDumpFile?'y':'n', ((int)btimeout14a * 10000) / 106);
702 }
703
704 // one-sector nested
705 if (cmdp == 'o') { // ------------------------------------ one sector working
706 PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo, trgKeyType?'B':'A');
707 int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true);
708 if (isOK) {
709 switch (isOK) {
710 case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
711 case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;
712 case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;
713 default : PrintAndLog("Unknown Error.\n");
714 }
715 return 2;
716 }
717 key64 = bytes_to_num(keyBlock, 6);
718 if (key64) {
719 PrintAndLog("Found valid key:%012" PRIx64, key64);
720
721 // transfer key to the emulator
722 if (transferToEml) {
723 uint8_t sectortrailer;
724 if (trgBlockNo < 32*4) { // 4 block sector
725 sectortrailer = trgBlockNo | 0x03;
726 } else { // 16 block sector
727 sectortrailer = trgBlockNo | 0x0f;
728 }
729 mfEmlGetMem(keyBlock, sectortrailer, 1);
730
731 if (!trgKeyType)
732 num_to_bytes(key64, 6, keyBlock);
733 else
734 num_to_bytes(key64, 6, &keyBlock[10]);
735 mfEmlSetMem(keyBlock, sectortrailer, 1);
736 PrintAndLog("Key transferred to emulator memory.");
737 }
738 } else {
739 PrintAndLog("No valid key found");
740 }
741 }
742 else { // ------------------------------------ multiple sectors working
743 uint64_t msclock1;
744 msclock1 = msclock();
745
746 e_sector = calloc(SectorsCnt, sizeof(sector_t));
747 if (e_sector == NULL) return 1;
748
749 //test current key and additional standard keys first
750 for (int defaultKeyCounter = 0; defaultKeyCounter < MifareDefaultKeysSize; defaultKeyCounter++){
751 num_to_bytes(MifareDefaultKeys[defaultKeyCounter], 6, (uint8_t*)(keyBlock + defaultKeyCounter * 6));
752 }
753
754 PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt);
755 mfCheckKeysSec(SectorsCnt, 2, btimeout14a, true, MifareDefaultKeysSize, keyBlock, e_sector);
756
757 // get known key from array
758 bool keyFound = false;
759 if (autosearchKey) {
760 for (i = 0; i < SectorsCnt; i++) {
761 for (j = 0; j < 2; j++) {
762 if (e_sector[i].foundKey[j]) {
763 // get known key
764 blockNo = i * 4;
765 keyType = j;
766 num_to_bytes(e_sector[i].Key[j], 6, key);
767 keyFound = true;
768 break;
769 }
770 }
771 if (keyFound) break;
772 }
773
774 // Can't found a key....
775 if (!keyFound) {
776 PrintAndLog("Can't found any of the known keys.");
777 free(e_sector);
778 return 4;
779 }
780 PrintAndLog("--auto key. block no:%3d, key type:%c key:%s", blockNo, keyType?'B':'A', sprint_hex(key, 6));
781 }
782
783 // nested sectors
784 iterations = 0;
785 PrintAndLog("nested...");
786 bool calibrate = true;
787 for (i = 0; i < NESTED_SECTOR_RETRY; i++) {
788 for (uint8_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) {
789 for (trgKeyType = 0; trgKeyType < 2; trgKeyType++) {
790 if (e_sector[sectorNo].foundKey[trgKeyType]) continue;
791 PrintAndLog("-----------------------------------------------");
792 int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate);
793 if(isOK) {
794 switch (isOK) {
795 case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
796 case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;
797 case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;
798 default : PrintAndLog("Unknown Error.\n");
799 }
800 free(e_sector);
801 return 2;
802 } else {
803 calibrate = false;
804 }
805
806 iterations++;
807
808 key64 = bytes_to_num(keyBlock, 6);
809 if (key64) {
810 PrintAndLog("Found valid key:%012" PRIx64, key64);
811 e_sector[sectorNo].foundKey[trgKeyType] = 1;
812 e_sector[sectorNo].Key[trgKeyType] = key64;
813
814 // try to check this key as a key to the other sectors
815 mfCheckKeysSec(SectorsCnt, 2, btimeout14a, true, 1, keyBlock, e_sector);
816 }
817 }
818 }
819 }
820
821 // print nested statistic
822 PrintAndLog("\n\n-----------------------------------------------\nNested statistic:\nIterations count: %d", iterations);
823 PrintAndLog("Time in nested: %1.3f (%1.3f sec per key)", ((float)(msclock() - msclock1))/1000.0, ((float)(msclock() - msclock1))/iterations/1000.0);
824
825 // print result
826 PrintAndLog("|---|----------------|---|----------------|---|");
827 PrintAndLog("|sec|key A |res|key B |res|");
828 PrintAndLog("|---|----------------|---|----------------|---|");
829 for (i = 0; i < SectorsCnt; i++) {
830 PrintAndLog("|%03d| %012" PRIx64 " | %d | %012" PRIx64 " | %d |", i,
831 e_sector[i].Key[0], e_sector[i].foundKey[0], e_sector[i].Key[1], e_sector[i].foundKey[1]);
832 }
833 PrintAndLog("|---|----------------|---|----------------|---|");
834
835 // transfer keys to the emulator memory
836 if (transferToEml) {
837 for (i = 0; i < SectorsCnt; i++) {
838 mfEmlGetMem(keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);
839 if (e_sector[i].foundKey[0])
840 num_to_bytes(e_sector[i].Key[0], 6, keyBlock);
841 if (e_sector[i].foundKey[1])
842 num_to_bytes(e_sector[i].Key[1], 6, &keyBlock[10]);
843 mfEmlSetMem(keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);
844 }
845 PrintAndLog("Keys transferred to emulator memory.");
846 }
847
848 // Create dump file
849 if (createDumpFile) {
850 if ((fkeys = fopen("dumpkeys.bin","wb")) == NULL) {
851 PrintAndLog("Could not create file dumpkeys.bin");
852 free(e_sector);
853 return 1;
854 }
855 PrintAndLog("Printing keys to binary file dumpkeys.bin...");
856 for(i=0; i<SectorsCnt; i++) {
857 if (e_sector[i].foundKey[0]){
858 num_to_bytes(e_sector[i].Key[0], 6, tempkey);
859 fwrite ( tempkey, 1, 6, fkeys );
860 }
861 else{
862 fwrite ( &standart, 1, 6, fkeys );
863 }
864 }
865 for(i=0; i<SectorsCnt; i++) {
866 if (e_sector[i].foundKey[1]){
867 num_to_bytes(e_sector[i].Key[1], 6, tempkey);
868 fwrite ( tempkey, 1, 6, fkeys );
869 }
870 else{
871 fwrite ( &standart, 1, 6, fkeys );
872 }
873 }
874 fclose(fkeys);
875 }
876
877 free(e_sector);
878 }
879 return 0;
880 }
881
882
883 int CmdHF14AMfNestedHard(const char *Cmd)
884 {
885 uint8_t blockNo = 0;
886 uint8_t keyType = 0;
887 uint8_t trgBlockNo = 0;
888 uint8_t trgKeyType = 0;
889 uint8_t key[6] = {0, 0, 0, 0, 0, 0};
890 uint8_t trgkey[6] = {0, 0, 0, 0, 0, 0};
891
892 char ctmp;
893 ctmp = param_getchar(Cmd, 0);
894
895 if (ctmp != 'R' && ctmp != 'r' && ctmp != 'T' && ctmp != 't' && strlen(Cmd) < 20) {
896 PrintAndLog("Usage:");
897 PrintAndLog(" hf mf hardnested <block number> <key A|B> <key (12 hex symbols)>");
898 PrintAndLog(" <target block number> <target key A|B> [known target key (12 hex symbols)] [w] [s]");
899 PrintAndLog(" or hf mf hardnested r [known target key]");
900 PrintAndLog(" ");
901 PrintAndLog("Options: ");
902 PrintAndLog(" w: Acquire nonces and write them to binary file nonces.bin");
903 PrintAndLog(" s: Slower acquisition (required by some non standard cards)");
904 PrintAndLog(" r: Read nonces.bin and start attack");
905 PrintAndLog(" iX: set type of SIMD instructions. Without this flag programs autodetect it.");
906 PrintAndLog(" i5: AVX512");
907 PrintAndLog(" i2: AVX2");
908 PrintAndLog(" ia: AVX");
909 PrintAndLog(" is: SSE2");
910 PrintAndLog(" im: MMX");
911 PrintAndLog(" in: none (use CPU regular instruction set)");
912 PrintAndLog(" ");
913 PrintAndLog(" sample1: hf mf hardnested 0 A FFFFFFFFFFFF 4 A");
914 PrintAndLog(" sample2: hf mf hardnested 0 A FFFFFFFFFFFF 4 A w");
915 PrintAndLog(" sample3: hf mf hardnested 0 A FFFFFFFFFFFF 4 A w s");
916 PrintAndLog(" sample4: hf mf hardnested r");
917 PrintAndLog(" ");
918 PrintAndLog("Add the known target key to check if it is present in the remaining key space:");
919 PrintAndLog(" sample5: hf mf hardnested 0 A A0A1A2A3A4A5 4 A FFFFFFFFFFFF");
920 return 0;
921 }
922
923 bool know_target_key = false;
924 bool nonce_file_read = false;
925 bool nonce_file_write = false;
926 bool slow = false;
927 int tests = 0;
928
929
930 uint16_t iindx = 0;
931 if (ctmp == 'R' || ctmp == 'r') {
932 nonce_file_read = true;
933 iindx = 1;
934 if (!param_gethex(Cmd, 1, trgkey, 12)) {
935 know_target_key = true;
936 iindx = 2;
937 }
938 } else if (ctmp == 'T' || ctmp == 't') {
939 tests = param_get32ex(Cmd, 1, 100, 10);
940 iindx = 2;
941 if (!param_gethex(Cmd, 2, trgkey, 12)) {
942 know_target_key = true;
943 iindx = 3;
944 }
945 } else {
946 blockNo = param_get8(Cmd, 0);
947 ctmp = param_getchar(Cmd, 1);
948 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {
949 PrintAndLog("Key type must be A or B");
950 return 1;
951 }
952 if (ctmp != 'A' && ctmp != 'a') {
953 keyType = 1;
954 }
955
956 if (param_gethex(Cmd, 2, key, 12)) {
957 PrintAndLog("Key must include 12 HEX symbols");
958 return 1;
959 }
960
961 trgBlockNo = param_get8(Cmd, 3);
962 ctmp = param_getchar(Cmd, 4);
963 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {
964 PrintAndLog("Target key type must be A or B");
965 return 1;
966 }
967 if (ctmp != 'A' && ctmp != 'a') {
968 trgKeyType = 1;
969 }
970
971 uint16_t i = 5;
972
973 if (!param_gethex(Cmd, 5, trgkey, 12)) {
974 know_target_key = true;
975 i++;
976 }
977 iindx = i;
978
979 while ((ctmp = param_getchar(Cmd, i))) {
980 if (ctmp == 's' || ctmp == 'S') {
981 slow = true;
982 } else if (ctmp == 'w' || ctmp == 'W') {
983 nonce_file_write = true;
984 } else if (param_getlength(Cmd, i) == 2 && ctmp == 'i') {
985 iindx = i;
986 } else {
987 PrintAndLog("Possible options are w , s and/or iX");
988 return 1;
989 }
990 i++;
991 }
992 }
993
994 SetSIMDInstr(SIMD_AUTO);
995 if (iindx > 0) {
996 while ((ctmp = param_getchar(Cmd, iindx))) {
997 if (param_getlength(Cmd, iindx) == 2 && ctmp == 'i') {
998 switch(param_getchar_indx(Cmd, 1, iindx)) {
999 case '5':
1000 SetSIMDInstr(SIMD_AVX512);
1001 break;
1002 case '2':
1003 SetSIMDInstr(SIMD_AVX2);
1004 break;
1005 case 'a':
1006 SetSIMDInstr(SIMD_AVX);
1007 break;
1008 case 's':
1009 SetSIMDInstr(SIMD_SSE2);
1010 break;
1011 case 'm':
1012 SetSIMDInstr(SIMD_MMX);
1013 break;
1014 case 'n':
1015 SetSIMDInstr(SIMD_NONE);
1016 break;
1017 default:
1018 PrintAndLog("Unknown SIMD type. %c", param_getchar_indx(Cmd, 1, iindx));
1019 return 1;
1020 }
1021 }
1022 iindx++;
1023 }
1024 }
1025
1026 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 ",
1027 trgBlockNo,
1028 trgKeyType?'B':'A',
1029 trgkey[0], trgkey[1], trgkey[2], trgkey[3], trgkey[4], trgkey[5],
1030 know_target_key?"":" (not set)",
1031 nonce_file_write?"write":nonce_file_read?"read":"none",
1032 slow?"Yes":"No",
1033 tests);
1034
1035 int16_t isOK = mfnestedhard(blockNo, keyType, key, trgBlockNo, trgKeyType, know_target_key?trgkey:NULL, nonce_file_read, nonce_file_write, slow, tests);
1036
1037 if (isOK) {
1038 switch (isOK) {
1039 case 1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
1040 case 2 : PrintAndLog("Button pressed. Aborted.\n"); break;
1041 default : break;
1042 }
1043 return 2;
1044 }
1045
1046 return 0;
1047 }
1048
1049
1050 int CmdHF14AMfChk(const char *Cmd)
1051 {
1052 if (strlen(Cmd)<3) {
1053 PrintAndLog("Usage: hf mf chk <block number>|<*card memory> <key type (A/B/?)> [t|d|s|ss] [<key (12 hex symbols)>] [<dic (*.dic)>]");
1054 PrintAndLog(" * - all sectors");
1055 PrintAndLog("card memory - 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other> - 1K");
1056 PrintAndLog("d - write keys to binary file\n");
1057 PrintAndLog("t - write keys to emulator memory");
1058 PrintAndLog("s - slow execute. timeout 1ms");
1059 PrintAndLog("ss - very slow execute. timeout 5ms");
1060 PrintAndLog(" sample: hf mf chk 0 A 1234567890ab keys.dic");
1061 PrintAndLog(" hf mf chk *1 ? t");
1062 PrintAndLog(" hf mf chk *1 ? d");
1063 PrintAndLog(" hf mf chk *1 ? s");
1064 PrintAndLog(" hf mf chk *1 ? dss");
1065 return 0;
1066 }
1067
1068 FILE * f;
1069 char filename[FILE_PATH_SIZE]={0};
1070 char buf[13];
1071 uint8_t *keyBlock = NULL, *p;
1072 uint16_t stKeyBlock = 20;
1073
1074 int i, res;
1075 int keycnt = 0;
1076 char ctmp = 0x00;
1077 int clen = 0;
1078 uint8_t blockNo = 0;
1079 uint8_t SectorsCnt = 0;
1080 uint8_t keyType = 0;
1081 uint64_t key64 = 0;
1082 // timeout in units. (ms * 106)/10 or us*0.0106
1083 uint8_t btimeout14a = MF_CHKKEYS_DEFTIMEOUT; // fast by default
1084 bool param3InUse = false;
1085
1086 bool transferToEml = 0;
1087 bool createDumpFile = 0;
1088
1089 sector_t *e_sector = NULL;
1090
1091 keyBlock = calloc(stKeyBlock, 6);
1092 if (keyBlock == NULL) return 1;
1093
1094 int defaultKeysSize = MifareDefaultKeysSize;
1095 for (int defaultKeyCounter = 0; defaultKeyCounter < defaultKeysSize; defaultKeyCounter++){
1096 num_to_bytes(MifareDefaultKeys[defaultKeyCounter], 6, (uint8_t*)(keyBlock + defaultKeyCounter * 6));
1097 }
1098
1099 if (param_getchar(Cmd, 0)=='*') {
1100 SectorsCnt = ParamCardSizeSectors(param_getchar(Cmd + 1, 0));
1101 }
1102 else
1103 blockNo = param_get8(Cmd, 0);
1104
1105 ctmp = param_getchar(Cmd, 1);
1106 clen = param_getlength(Cmd, 1);
1107 if (clen == 1) {
1108 switch (ctmp) {
1109 case 'a': case 'A':
1110 keyType = 0;
1111 break;
1112 case 'b': case 'B':
1113 keyType = 1;
1114 break;
1115 case '?':
1116 keyType = 2;
1117 break;
1118 default:
1119 PrintAndLog("Key type must be A , B or ?");
1120 free(keyBlock);
1121 return 1;
1122 };
1123 }
1124
1125 parseParamTDS(Cmd, 2, &transferToEml, &createDumpFile, &btimeout14a);
1126
1127 param3InUse = transferToEml | createDumpFile | (btimeout14a != MF_CHKKEYS_DEFTIMEOUT);
1128
1129 PrintAndLog("--chk keys. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us",
1130 SectorsCnt, blockNo, keyType?'B':'A', transferToEml?'y':'n', createDumpFile?'y':'n', ((int)btimeout14a * 10000) / 106);
1131
1132 for (i = param3InUse; param_getchar(Cmd, 2 + i); i++) {
1133 if (!param_gethex(Cmd, 2 + i, keyBlock + 6 * keycnt, 12)) {
1134 if ( stKeyBlock - keycnt < 2) {
1135 p = realloc(keyBlock, 6*(stKeyBlock+=10));
1136 if (!p) {
1137 PrintAndLog("Cannot allocate memory for Keys");
1138 free(keyBlock);
1139 return 2;
1140 }
1141 keyBlock = p;
1142 }
1143 PrintAndLog("chk key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,
1144 (keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2],
1145 (keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6);
1146 keycnt++;
1147 } else {
1148 // May be a dic file
1149 if ( param_getstr(Cmd, 2 + i, filename, sizeof(filename)) >= FILE_PATH_SIZE ) {
1150 PrintAndLog("File name too long");
1151 free(keyBlock);
1152 return 2;
1153 }
1154
1155 if ( (f = fopen( filename , "r")) ) {
1156 while( fgets(buf, sizeof(buf), f) ){
1157 if (strlen(buf) < 12 || buf[11] == '\n')
1158 continue;
1159
1160 while (fgetc(f) != '\n' && !feof(f)) ; //goto next line
1161
1162 if( buf[0]=='#' ) continue; //The line start with # is comment, skip
1163
1164 if (!isxdigit((unsigned char)buf[0])){
1165 PrintAndLog("File content error. '%s' must include 12 HEX symbols",buf);
1166 continue;
1167 }
1168
1169 buf[12] = 0;
1170
1171 if ( stKeyBlock - keycnt < 2) {
1172 p = realloc(keyBlock, 6*(stKeyBlock+=10));
1173 if (!p) {
1174 PrintAndLog("Cannot allocate memory for defKeys");
1175 free(keyBlock);
1176 fclose(f);
1177 return 2;
1178 }
1179 keyBlock = p;
1180 }
1181 memset(keyBlock + 6 * keycnt, 0, 6);
1182 num_to_bytes(strtoll(buf, NULL, 16), 6, keyBlock + 6*keycnt);
1183 PrintAndLog("chk custom key[%2d] %012" PRIx64 , keycnt, bytes_to_num(keyBlock + 6*keycnt, 6));
1184 keycnt++;
1185 memset(buf, 0, sizeof(buf));
1186 }
1187 fclose(f);
1188 } else {
1189 PrintAndLog("File: %s: not found or locked.", filename);
1190 free(keyBlock);
1191 return 1;
1192
1193 }
1194 }
1195 }
1196
1197 // fill with default keys
1198 if (keycnt == 0) {
1199 PrintAndLog("No key specified, trying default keys");
1200 for (;keycnt < defaultKeysSize; keycnt++)
1201 PrintAndLog("chk default key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,
1202 (keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2],
1203 (keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6);
1204 }
1205
1206 // initialize storage for found keys
1207 e_sector = calloc(SectorsCnt, sizeof(sector_t));
1208 if (e_sector == NULL) {
1209 free(keyBlock);
1210 return 1;
1211 }
1212 for (uint8_t keyAB = 0; keyAB < 2; keyAB++) {
1213 for (uint16_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) {
1214 e_sector[sectorNo].Key[keyAB] = 0xffffffffffff;
1215 e_sector[sectorNo].foundKey[keyAB] = 0;
1216 }
1217 }
1218 printf("\n");
1219
1220 bool foundAKey = false;
1221 uint32_t max_keys = keycnt > USB_CMD_DATA_SIZE / 6 ? USB_CMD_DATA_SIZE / 6 : keycnt;
1222 if (SectorsCnt) {
1223 PrintAndLog("To cancel this operation press the button on the proxmark...");
1224 printf("--");
1225 for (uint32_t c = 0; c < keycnt; c += max_keys) {
1226
1227 uint32_t size = keycnt-c > max_keys ? max_keys : keycnt-c;
1228 res = mfCheckKeysSec(SectorsCnt, keyType, btimeout14a, true, size, &keyBlock[6 * c], e_sector); // timeout is (ms * 106)/10 or us*0.0106
1229
1230 if (res != 1) {
1231 if (!res) {
1232 printf("o");
1233 foundAKey = true;
1234 } else {
1235 printf(".");
1236 }
1237 } else {
1238 printf("\n");
1239 PrintAndLog("Command execute timeout");
1240 }
1241 }
1242 } else {
1243 int keyAB = keyType;
1244 do {
1245 for (uint32_t c = 0; c < keycnt; c+=max_keys) {
1246
1247 uint32_t size = keycnt-c > max_keys ? max_keys : keycnt-c;
1248 res = mfCheckKeys(blockNo, keyAB & 0x01, true, size, &keyBlock[6 * c], &key64);
1249
1250 if (res != 1) {
1251 if (!res) {
1252 PrintAndLog("Found valid key:[%d:%c]%012" PRIx64, blockNo, (keyAB & 0x01)?'B':'A', key64);
1253 foundAKey = true;
1254 }
1255 } else {
1256 PrintAndLog("Command execute timeout");
1257 }
1258 }
1259 } while(--keyAB > 0);
1260 }
1261
1262 // print result
1263 if (foundAKey) {
1264 if (SectorsCnt) {
1265 PrintAndLog("");
1266 PrintAndLog("|---|----------------|---|----------------|---|");
1267 PrintAndLog("|sec|key A |res|key B |res|");
1268 PrintAndLog("|---|----------------|---|----------------|---|");
1269 for (i = 0; i < SectorsCnt; i++) {
1270 PrintAndLog("|%03d| %012" PRIx64 " | %d | %012" PRIx64 " | %d |", i,
1271 e_sector[i].Key[0], e_sector[i].foundKey[0], e_sector[i].Key[1], e_sector[i].foundKey[1]);
1272 }
1273 PrintAndLog("|---|----------------|---|----------------|---|");
1274 }
1275 } else {
1276 PrintAndLog("");
1277 PrintAndLog("No valid keys found.");
1278 }
1279
1280 if (transferToEml) {
1281 uint8_t block[16];
1282 for (uint16_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) {
1283 if (e_sector[sectorNo].foundKey[0] || e_sector[sectorNo].foundKey[1]) {
1284 mfEmlGetMem(block, FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 1);
1285 for (uint16_t t = 0; t < 2; t++) {
1286 if (e_sector[sectorNo].foundKey[t]) {
1287 num_to_bytes(e_sector[sectorNo].Key[t], 6, block + t * 10);
1288 }
1289 }
1290 mfEmlSetMem(block, FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 1);
1291 }
1292 }
1293 PrintAndLog("Found keys have been transferred to the emulator memory");
1294 }
1295
1296 if (createDumpFile) {
1297 FILE *fkeys = fopen("dumpkeys.bin","wb");
1298 if (fkeys == NULL) {
1299 PrintAndLog("Could not create file dumpkeys.bin");
1300 free(e_sector);
1301 free(keyBlock);
1302 return 1;
1303 }
1304 uint8_t mkey[6];
1305 for (uint8_t t = 0; t < 2; t++) {
1306 for (uint8_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) {
1307 num_to_bytes(e_sector[sectorNo].Key[t], 6, mkey);
1308 fwrite(mkey, 1, 6, fkeys);
1309 }
1310 }
1311 fclose(fkeys);
1312 PrintAndLog("Found keys have been dumped to file dumpkeys.bin. 0xffffffffffff has been inserted for unknown keys.");
1313 }
1314
1315 free(e_sector);
1316 free(keyBlock);
1317 PrintAndLog("");
1318 return 0;
1319 }
1320
1321 void readerAttack(nonces_t ar_resp[], bool setEmulatorMem, bool doStandardAttack) {
1322 #define ATTACK_KEY_COUNT 7 // keep same as define in iso14443a.c -> Mifare1ksim()
1323 // cannot be more than 7 or it will overrun c.d.asBytes(512)
1324 uint64_t key = 0;
1325 typedef struct {
1326 uint64_t keyA;
1327 uint64_t keyB;
1328 } st_t;
1329 st_t sector_trailer[ATTACK_KEY_COUNT];
1330 memset(sector_trailer, 0x00, sizeof(sector_trailer));
1331
1332 uint8_t stSector[ATTACK_KEY_COUNT];
1333 memset(stSector, 0x00, sizeof(stSector));
1334 uint8_t key_cnt[ATTACK_KEY_COUNT];
1335 memset(key_cnt, 0x00, sizeof(key_cnt));
1336
1337 for (uint8_t i = 0; i<ATTACK_KEY_COUNT; i++) {
1338 if (ar_resp[i].ar2 > 0) {
1339 //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);
1340 if (doStandardAttack && mfkey32(ar_resp[i], &key)) {
1341 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));
1342
1343 for (uint8_t ii = 0; ii<ATTACK_KEY_COUNT; ii++) {
1344 if (key_cnt[ii]==0 || stSector[ii]==ar_resp[i].sector) {
1345 if (ar_resp[i].keytype==0) {
1346 //keyA
1347 sector_trailer[ii].keyA = key;
1348 stSector[ii] = ar_resp[i].sector;
1349 key_cnt[ii]++;
1350 break;
1351 } else {
1352 //keyB
1353 sector_trailer[ii].keyB = key;
1354 stSector[ii] = ar_resp[i].sector;
1355 key_cnt[ii]++;
1356 break;
1357 }
1358 }
1359 }
1360 } else if (mfkey32_moebius(ar_resp[i+ATTACK_KEY_COUNT], &key)) {
1361 uint8_t sectorNum = ar_resp[i+ATTACK_KEY_COUNT].sector;
1362 uint8_t keyType = ar_resp[i+ATTACK_KEY_COUNT].keytype;
1363
1364 PrintAndLog("M-Found Key%s for sector %02d: [%012" PRIx64 "]"
1365 , keyType ? "B" : "A"
1366 , sectorNum
1367 , key
1368 );
1369
1370 for (uint8_t ii = 0; ii<ATTACK_KEY_COUNT; ii++) {
1371 if (key_cnt[ii]==0 || stSector[ii]==sectorNum) {
1372 if (keyType==0) {
1373 //keyA
1374 sector_trailer[ii].keyA = key;
1375 stSector[ii] = sectorNum;
1376 key_cnt[ii]++;
1377 break;
1378 } else {
1379 //keyB
1380 sector_trailer[ii].keyB = key;
1381 stSector[ii] = sectorNum;
1382 key_cnt[ii]++;
1383 break;
1384 }
1385 }
1386 }
1387 continue;
1388 }
1389 }
1390 }
1391 //set emulator memory for keys
1392 if (setEmulatorMem) {
1393 for (uint8_t i = 0; i<ATTACK_KEY_COUNT; i++) {
1394 if (key_cnt[i]>0) {
1395 uint8_t memBlock[16];
1396 memset(memBlock, 0x00, sizeof(memBlock));
1397 char cmd1[36];
1398 memset(cmd1,0x00,sizeof(cmd1));
1399 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));
1400 PrintAndLog("Setting Emulator Memory Block %02d: [%s]",stSector[i]*4+3, cmd1);
1401 if (param_gethex(cmd1, 0, memBlock, 32)) {
1402 PrintAndLog("block data must include 32 HEX symbols");
1403 return;
1404 }
1405
1406 UsbCommand c = {CMD_MIFARE_EML_MEMSET, {(stSector[i]*4+3), 1, 0}};
1407 memcpy(c.d.asBytes, memBlock, 16);
1408 clearCommandBuffer();
1409 SendCommand(&c);
1410 }
1411 }
1412 }
1413 /*
1414 //un-comment to use as well moebius attack
1415 for (uint8_t i = ATTACK_KEY_COUNT; i<ATTACK_KEY_COUNT*2; i++) {
1416 if (ar_resp[i].ar2 > 0) {
1417 if (tryMfk32_moebius(ar_resp[i], &key)) {
1418 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));
1419 }
1420 }
1421 }*/
1422 }
1423
1424 int usage_hf14_mf1ksim(void) {
1425 PrintAndLog("Usage: hf mf sim h u <uid (8, 14, or 20 hex symbols)> n <numreads> i x");
1426 PrintAndLog("options:");
1427 PrintAndLog(" h this help");
1428 PrintAndLog(" u (Optional) UID 4,7 or 10 bytes. If not specified, the UID 4B from emulator memory will be used");
1429 PrintAndLog(" n (Optional) Automatically exit simulation after <numreads> blocks have been read by reader. 0 = infinite");
1430 PrintAndLog(" i (Optional) Interactive, means that console will not be returned until simulation finishes or is aborted");
1431 PrintAndLog(" x (Optional) Crack, performs the 'reader attack', nr/ar attack against a legitimate reader, fishes out the key(s)");
1432 PrintAndLog(" e (Optional) set keys found from 'reader attack' to emulator memory (implies x and i)");
1433 PrintAndLog(" f (Optional) get UIDs to use for 'reader attack' from file 'f <filename.txt>' (implies x and i)");
1434 PrintAndLog(" r (Optional) Generate random nonces instead of sequential nonces. Standard reader attack won't work with this option, only moebius attack works.");
1435 PrintAndLog("samples:");
1436 PrintAndLog(" hf mf sim u 0a0a0a0a");
1437 PrintAndLog(" hf mf sim u 11223344556677");
1438 PrintAndLog(" hf mf sim u 112233445566778899AA");
1439 PrintAndLog(" hf mf sim f uids.txt");
1440 PrintAndLog(" hf mf sim u 0a0a0a0a e");
1441
1442 return 0;
1443 }
1444
1445 int CmdHF14AMf1kSim(const char *Cmd) {
1446 UsbCommand resp;
1447 uint8_t uid[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1448 uint8_t exitAfterNReads = 0;
1449 uint8_t flags = 0;
1450 int uidlen = 0;
1451 uint8_t pnr = 0;
1452 bool setEmulatorMem = false;
1453 bool attackFromFile = false;
1454 FILE *f;
1455 char filename[FILE_PATH_SIZE];
1456 memset(filename, 0x00, sizeof(filename));
1457 int len = 0;
1458 char buf[64];
1459
1460 uint8_t cmdp = 0;
1461 bool errors = false;
1462
1463 while(param_getchar(Cmd, cmdp) != 0x00) {
1464 switch(param_getchar(Cmd, cmdp)) {
1465 case 'e':
1466 case 'E':
1467 setEmulatorMem = true;
1468 //implies x and i
1469 flags |= FLAG_INTERACTIVE;
1470 flags |= FLAG_NR_AR_ATTACK;
1471 cmdp++;
1472 break;
1473 case 'f':
1474 case 'F':
1475 len = param_getstr(Cmd, cmdp+1, filename, sizeof(filename));
1476 if (len < 1) {
1477 PrintAndLog("error no filename found");
1478 return 0;
1479 }
1480 attackFromFile = true;
1481 //implies x and i
1482 flags |= FLAG_INTERACTIVE;
1483 flags |= FLAG_NR_AR_ATTACK;
1484 cmdp += 2;
1485 break;
1486 case 'h':
1487 case 'H':
1488 return usage_hf14_mf1ksim();
1489 case 'i':
1490 case 'I':
1491 flags |= FLAG_INTERACTIVE;
1492 cmdp++;
1493 break;
1494 case 'n':
1495 case 'N':
1496 exitAfterNReads = param_get8(Cmd, pnr+1);
1497 cmdp += 2;
1498 break;
1499 case 'r':
1500 case 'R':
1501 flags |= FLAG_RANDOM_NONCE;
1502 cmdp++;
1503 break;
1504 case 'u':
1505 case 'U':
1506 param_gethex_ex(Cmd, cmdp+1, uid, &uidlen);
1507 switch(uidlen) {
1508 case 20: flags = FLAG_10B_UID_IN_DATA; break; //not complete
1509 case 14: flags = FLAG_7B_UID_IN_DATA; break;
1510 case 8: flags = FLAG_4B_UID_IN_DATA; break;
1511 default: return usage_hf14_mf1ksim();
1512 }
1513 cmdp += 2;
1514 break;
1515 case 'x':
1516 case 'X':
1517 flags |= FLAG_NR_AR_ATTACK;
1518 cmdp++;
1519 break;
1520 default:
1521 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
1522 errors = true;
1523 break;
1524 }
1525 if(errors) break;
1526 }
1527 //Validations
1528 if(errors) return usage_hf14_mf1ksim();
1529
1530 //get uid from file
1531 if (attackFromFile) {
1532 int count = 0;
1533 // open file
1534 f = fopen(filename, "r");
1535 if (f == NULL) {
1536 PrintAndLog("File %s not found or locked", filename);
1537 return 1;
1538 }
1539 PrintAndLog("Loading file and simulating. Press keyboard to abort");
1540 while(!feof(f) && !ukbhit()){
1541 memset(buf, 0, sizeof(buf));
1542 memset(uid, 0, sizeof(uid));
1543
1544 if (fgets(buf, sizeof(buf), f) == NULL) {
1545 if (count > 0) break;
1546
1547 PrintAndLog("File reading error.");
1548 fclose(f);
1549 return 2;
1550 }
1551 if(!strlen(buf) && feof(f)) break;
1552
1553 uidlen = strlen(buf)-1;
1554 switch(uidlen) {
1555 case 20: flags |= FLAG_10B_UID_IN_DATA; break; //not complete
1556 case 14: flags |= FLAG_7B_UID_IN_DATA; break;
1557 case 8: flags |= FLAG_4B_UID_IN_DATA; break;
1558 default:
1559 PrintAndLog("uid in file wrong length at %d (length: %d) [%s]",count, uidlen, buf);
1560 fclose(f);
1561 return 2;
1562 }
1563
1564 for (uint8_t i = 0; i < uidlen; i += 2) {
1565 sscanf(&buf[i], "%02x", (unsigned int *)&uid[i / 2]);
1566 }
1567
1568 PrintAndLog("mf 1k sim uid: %s, numreads:%d, flags:%d (0x%02x) - press button to abort",
1569 flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4):
1570 flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7):
1571 flags & FLAG_10B_UID_IN_DATA ? sprint_hex(uid,10): "N/A"
1572 , exitAfterNReads, flags, flags);
1573
1574 UsbCommand c = {CMD_SIMULATE_MIFARE_CARD, {flags, exitAfterNReads,0}};
1575 memcpy(c.d.asBytes, uid, sizeof(uid));
1576 clearCommandBuffer();
1577 SendCommand(&c);
1578
1579 while(! WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
1580 //We're waiting only 1.5 s at a time, otherwise we get the
1581 // annoying message about "Waiting for a response... "
1582 }
1583 //got a response
1584 nonces_t ar_resp[ATTACK_KEY_COUNT*2];
1585 memcpy(ar_resp, resp.d.asBytes, sizeof(ar_resp));
1586 // We can skip the standard attack if we have RANDOM_NONCE set.
1587 readerAttack(ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE));
1588 if ((bool)resp.arg[1]) {
1589 PrintAndLog("Device button pressed - quitting");
1590 fclose(f);
1591 return 4;
1592 }
1593 count++;
1594 }
1595 fclose(f);
1596 } else { //not from file
1597
1598 PrintAndLog("mf 1k sim uid: %s, numreads:%d, flags:%d (0x%02x) ",
1599 flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4):
1600 flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7):
1601 flags & FLAG_10B_UID_IN_DATA ? sprint_hex(uid,10): "N/A"
1602 , exitAfterNReads, flags, flags);
1603
1604 UsbCommand c = {CMD_SIMULATE_MIFARE_CARD, {flags, exitAfterNReads,0}};
1605 memcpy(c.d.asBytes, uid, sizeof(uid));
1606 clearCommandBuffer();
1607 SendCommand(&c);
1608
1609 if(flags & FLAG_INTERACTIVE) {
1610 PrintAndLog("Press pm3-button to abort simulation");
1611 while(! WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
1612 //We're waiting only 1.5 s at a time, otherwise we get the
1613 // annoying message about "Waiting for a response... "
1614 }
1615 //got a response
1616 if (flags & FLAG_NR_AR_ATTACK) {
1617 nonces_t ar_resp[ATTACK_KEY_COUNT*2];
1618 memcpy(ar_resp, resp.d.asBytes, sizeof(ar_resp));
1619 // We can skip the standard attack if we have RANDOM_NONCE set.
1620 readerAttack(ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE));
1621 }
1622 }
1623 }
1624
1625 return 0;
1626 }
1627
1628 int CmdHF14AMfDbg(const char *Cmd)
1629 {
1630 int dbgMode = param_get32ex(Cmd, 0, 0, 10);
1631 if (dbgMode > 4) {
1632 PrintAndLog("Max debug mode parameter is 4 \n");
1633 }
1634
1635 if (strlen(Cmd) < 1 || !param_getchar(Cmd, 0) || dbgMode > 4) {
1636 PrintAndLog("Usage: hf mf dbg <debug level>");
1637 PrintAndLog(" 0 - no debug messages");
1638 PrintAndLog(" 1 - error messages");
1639 PrintAndLog(" 2 - plus information messages");
1640 PrintAndLog(" 3 - plus debug messages");
1641 PrintAndLog(" 4 - print even debug messages in timing critical functions");
1642 PrintAndLog(" Note: this option therefore may cause malfunction itself");
1643 return 0;
1644 }
1645
1646 UsbCommand c = {CMD_MIFARE_SET_DBGMODE, {dbgMode, 0, 0}};
1647 SendCommand(&c);
1648
1649 return 0;
1650 }
1651
1652 int CmdHF14AMfEGet(const char *Cmd)
1653 {
1654 uint8_t blockNo = 0;
1655 uint8_t data[16] = {0x00};
1656
1657 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
1658 PrintAndLog("Usage: hf mf eget <block number>");
1659 PrintAndLog(" sample: hf mf eget 0 ");
1660 return 0;
1661 }
1662
1663 blockNo = param_get8(Cmd, 0);
1664
1665 PrintAndLog(" ");
1666 if (!mfEmlGetMem(data, blockNo, 1)) {
1667 PrintAndLog("data[%3d]:%s", blockNo, sprint_hex(data, 16));
1668 } else {
1669 PrintAndLog("Command execute timeout");
1670 }
1671
1672 return 0;
1673 }
1674
1675 int CmdHF14AMfEClear(const char *Cmd)
1676 {
1677 if (param_getchar(Cmd, 0) == 'h') {
1678 PrintAndLog("Usage: hf mf eclr");
1679 PrintAndLog("It set card emulator memory to empty data blocks and key A/B FFFFFFFFFFFF \n");
1680 return 0;
1681 }
1682
1683 UsbCommand c = {CMD_MIFARE_EML_MEMCLR, {0, 0, 0}};
1684 SendCommand(&c);
1685 return 0;
1686 }
1687
1688
1689 int CmdHF14AMfESet(const char *Cmd)
1690 {
1691 uint8_t memBlock[16];
1692 uint8_t blockNo = 0;
1693
1694 memset(memBlock, 0x00, sizeof(memBlock));
1695
1696 if (strlen(Cmd) < 3 || param_getchar(Cmd, 0) == 'h') {
1697 PrintAndLog("Usage: hf mf eset <block number> <block data (32 hex symbols)>");
1698 PrintAndLog(" sample: hf mf eset 1 000102030405060708090a0b0c0d0e0f ");
1699 return 0;
1700 }
1701
1702 blockNo = param_get8(Cmd, 0);
1703
1704 if (param_gethex(Cmd, 1, memBlock, 32)) {
1705 PrintAndLog("block data must include 32 HEX symbols");
1706 return 1;
1707 }
1708
1709 // 1 - blocks count
1710 return mfEmlSetMem(memBlock, blockNo, 1);
1711 }
1712
1713
1714 int CmdHF14AMfELoad(const char *Cmd)
1715 {
1716 FILE * f;
1717 char filename[FILE_PATH_SIZE];
1718 char *fnameptr = filename;
1719 char buf[64] = {0x00};
1720 uint8_t buf8[64] = {0x00};
1721 int i, len, blockNum, numBlocks;
1722 int nameParamNo = 1;
1723
1724 char ctmp = param_getchar(Cmd, 0);
1725
1726 if ( ctmp == 'h' || ctmp == 0x00) {
1727 PrintAndLog("It loads emul dump from the file `filename.eml`");
1728 PrintAndLog("Usage: hf mf eload [card memory] <file name w/o `.eml`>");
1729 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1730 PrintAndLog("");
1731 PrintAndLog(" sample: hf mf eload filename");
1732 PrintAndLog(" hf mf eload 4 filename");
1733 return 0;
1734 }
1735
1736 switch (ctmp) {
1737 case '0' : numBlocks = 5*4; break;
1738 case '1' :
1739 case '\0': numBlocks = 16*4; break;
1740 case '2' : numBlocks = 32*4; break;
1741 case '4' : numBlocks = 256; break;
1742 default: {
1743 numBlocks = 16*4;
1744 nameParamNo = 0;
1745 }
1746 }
1747
1748 len = param_getstr(Cmd,nameParamNo,filename,sizeof(filename));
1749
1750 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
1751
1752 fnameptr += len;
1753
1754 sprintf(fnameptr, ".eml");
1755
1756 // open file
1757 f = fopen(filename, "r");
1758 if (f == NULL) {
1759 PrintAndLog("File %s not found or locked", filename);
1760 return 1;
1761 }
1762
1763 blockNum = 0;
1764 while(!feof(f)){
1765 memset(buf, 0, sizeof(buf));
1766
1767 if (fgets(buf, sizeof(buf), f) == NULL) {
1768
1769 if (blockNum >= numBlocks) break;
1770
1771 PrintAndLog("File reading error.");
1772 fclose(f);
1773 return 2;
1774 }
1775
1776 if (strlen(buf) < 32){
1777 if(strlen(buf) && feof(f))
1778 break;
1779 PrintAndLog("File content error. Block data must include 32 HEX symbols");
1780 fclose(f);
1781 return 2;
1782 }
1783
1784 for (i = 0; i < 32; i += 2) {
1785 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
1786 }
1787
1788 if (mfEmlSetMem(buf8, blockNum, 1)) {
1789 PrintAndLog("Cant set emul block: %3d", blockNum);
1790 fclose(f);
1791 return 3;
1792 }
1793 printf(".");
1794 blockNum++;
1795
1796 if (blockNum >= numBlocks) break;
1797 }
1798 fclose(f);
1799 printf("\n");
1800
1801 if ((blockNum != numBlocks)) {
1802 PrintAndLog("File content error. Got %d must be %d blocks.",blockNum, numBlocks);
1803 return 4;
1804 }
1805 PrintAndLog("Loaded %d blocks from file: %s", blockNum, filename);
1806 return 0;
1807 }
1808
1809
1810 int CmdHF14AMfESave(const char *Cmd)
1811 {
1812 FILE * f;
1813 char filename[FILE_PATH_SIZE];
1814 char * fnameptr = filename;
1815 uint8_t buf[64];
1816 int i, j, len, numBlocks;
1817 int nameParamNo = 1;
1818
1819 memset(filename, 0, sizeof(filename));
1820 memset(buf, 0, sizeof(buf));
1821
1822 char ctmp = param_getchar(Cmd, 0);
1823
1824 if ( ctmp == 'h' || ctmp == 'H') {
1825 PrintAndLog("It saves emul dump into the file `filename.eml` or `cardID.eml`");
1826 PrintAndLog(" Usage: hf mf esave [card memory] [file name w/o `.eml`]");
1827 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1828 PrintAndLog("");
1829 PrintAndLog(" sample: hf mf esave ");
1830 PrintAndLog(" hf mf esave 4");
1831 PrintAndLog(" hf mf esave 4 filename");
1832 return 0;
1833 }
1834
1835 switch (ctmp) {
1836 case '0' : numBlocks = 5*4; break;
1837 case '1' :
1838 case '\0': numBlocks = 16*4; break;
1839 case '2' : numBlocks = 32*4; break;
1840 case '4' : numBlocks = 256; break;
1841 default: {
1842 numBlocks = 16*4;
1843 nameParamNo = 0;
1844 }
1845 }
1846
1847 len = param_getstr(Cmd,nameParamNo,filename,sizeof(filename));
1848
1849 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
1850
1851 // user supplied filename?
1852 if (len < 1) {
1853 // get filename (UID from memory)
1854 if (mfEmlGetMem(buf, 0, 1)) {
1855 PrintAndLog("Can\'t get UID from block: %d", 0);
1856 len = sprintf(fnameptr, "dump");
1857 fnameptr += len;
1858 }
1859 else {
1860 for (j = 0; j < 7; j++, fnameptr += 2)
1861 sprintf(fnameptr, "%02X", buf[j]);
1862 }
1863 } else {
1864 fnameptr += len;
1865 }
1866
1867 // add file extension
1868 sprintf(fnameptr, ".eml");
1869
1870 // open file
1871 f = fopen(filename, "w+");
1872
1873 if ( !f ) {
1874 PrintAndLog("Can't open file %s ", filename);
1875 return 1;
1876 }
1877
1878 // put hex
1879 for (i = 0; i < numBlocks; i++) {
1880 if (mfEmlGetMem(buf, i, 1)) {
1881 PrintAndLog("Cant get block: %d", i);
1882 break;
1883 }
1884 for (j = 0; j < 16; j++)
1885 fprintf(f, "%02X", buf[j]);
1886 fprintf(f,"\n");
1887 }
1888 fclose(f);
1889
1890 PrintAndLog("Saved %d blocks to file: %s", numBlocks, filename);
1891
1892 return 0;
1893 }
1894
1895
1896 int CmdHF14AMfECFill(const char *Cmd)
1897 {
1898 uint8_t keyType = 0;
1899 uint8_t numSectors = 16;
1900
1901 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
1902 PrintAndLog("Usage: hf mf ecfill <key A/B> [card memory]");
1903 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1904 PrintAndLog("");
1905 PrintAndLog("samples: hf mf ecfill A");
1906 PrintAndLog(" hf mf ecfill A 4");
1907 PrintAndLog("Read card and transfer its data to emulator memory.");
1908 PrintAndLog("Keys must be laid in the emulator memory. \n");
1909 return 0;
1910 }
1911
1912 char ctmp = param_getchar(Cmd, 0);
1913 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {
1914 PrintAndLog("Key type must be A or B");
1915 return 1;
1916 }
1917 if (ctmp != 'A' && ctmp != 'a') keyType = 1;
1918
1919 ctmp = param_getchar(Cmd, 1);
1920 switch (ctmp) {
1921 case '0' : numSectors = 5; break;
1922 case '1' :
1923 case '\0': numSectors = 16; break;
1924 case '2' : numSectors = 32; break;
1925 case '4' : numSectors = 40; break;
1926 default: numSectors = 16;
1927 }
1928
1929 printf("--params: numSectors: %d, keyType:%d\n", numSectors, keyType);
1930 UsbCommand c = {CMD_MIFARE_EML_CARDLOAD, {numSectors, keyType, 0}};
1931 SendCommand(&c);
1932 return 0;
1933 }
1934
1935 int CmdHF14AMfEKeyPrn(const char *Cmd)
1936 {
1937 int i;
1938 uint8_t numSectors;
1939 uint8_t data[16];
1940 uint64_t keyA, keyB;
1941
1942 if (param_getchar(Cmd, 0) == 'h') {
1943 PrintAndLog("It prints the keys loaded in the emulator memory");
1944 PrintAndLog("Usage: hf mf ekeyprn [card memory]");
1945 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1946 PrintAndLog("");
1947 PrintAndLog(" sample: hf mf ekeyprn 1");
1948 return 0;
1949 }
1950
1951 char cmdp = param_getchar(Cmd, 0);
1952
1953 switch (cmdp) {
1954 case '0' : numSectors = 5; break;
1955 case '1' :
1956 case '\0': numSectors = 16; break;
1957 case '2' : numSectors = 32; break;
1958 case '4' : numSectors = 40; break;
1959 default: numSectors = 16;
1960 }
1961
1962 PrintAndLog("|---|----------------|----------------|");
1963 PrintAndLog("|sec|key A |key B |");
1964 PrintAndLog("|---|----------------|----------------|");
1965 for (i = 0; i < numSectors; i++) {
1966 if (mfEmlGetMem(data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) {
1967 PrintAndLog("error get block %d", FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1);
1968 break;
1969 }
1970 keyA = bytes_to_num(data, 6);
1971 keyB = bytes_to_num(data + 10, 6);
1972 PrintAndLog("|%03d| %012" PRIx64 " | %012" PRIx64 " |", i, keyA, keyB);
1973 }
1974 PrintAndLog("|---|----------------|----------------|");
1975
1976 return 0;
1977 }
1978
1979 int CmdHF14AMfCSetUID(const char *Cmd)
1980 {
1981 uint8_t uid[8] = {0x00};
1982 uint8_t oldUid[8] = {0x00};
1983 uint8_t atqa[2] = {0x00};
1984 uint8_t sak[1] = {0x00};
1985 uint8_t atqaPresent = 0;
1986 int res;
1987
1988 uint8_t needHelp = 0;
1989 char cmdp = 1;
1990
1991 if (param_getchar(Cmd, 0) && param_gethex(Cmd, 0, uid, 8)) {
1992 PrintAndLog("UID must include 8 HEX symbols");
1993 return 1;
1994 }
1995
1996 if (param_getlength(Cmd, 1) > 1 && param_getlength(Cmd, 2) > 1) {
1997 atqaPresent = 1;
1998 cmdp = 3;
1999
2000 if (param_gethex(Cmd, 1, atqa, 4)) {
2001 PrintAndLog("ATQA must include 4 HEX symbols");
2002 return 1;
2003 }
2004
2005 if (param_gethex(Cmd, 2, sak, 2)) {
2006 PrintAndLog("SAK must include 2 HEX symbols");
2007 return 1;
2008 }
2009 }
2010
2011 while(param_getchar(Cmd, cmdp) != 0x00)
2012 {
2013 switch(param_getchar(Cmd, cmdp))
2014 {
2015 case 'h':
2016 case 'H':
2017 needHelp = 1;
2018 break;
2019 default:
2020 PrintAndLog("ERROR: Unknown parameter '%c'", param_getchar(Cmd, cmdp));
2021 needHelp = 1;
2022 break;
2023 }
2024 cmdp++;
2025 }
2026
2027 if (strlen(Cmd) < 1 || needHelp) {
2028 PrintAndLog("");
2029 PrintAndLog("Usage: hf mf csetuid <UID 8 hex symbols> [ATQA 4 hex symbols SAK 2 hex symbols]");
2030 PrintAndLog("sample: hf mf csetuid 01020304");
2031 PrintAndLog("sample: hf mf csetuid 01020304 0004 08");
2032 PrintAndLog("Set UID, ATQA, and SAK for magic Chinese card (only works with such cards)");
2033 return 0;
2034 }
2035
2036 PrintAndLog("uid:%s", sprint_hex(uid, 4));
2037 if (atqaPresent) {
2038 PrintAndLog("--atqa:%s sak:%02x", sprint_hex(atqa, 2), sak[0]);
2039 }
2040
2041 res = mfCSetUID(uid, (atqaPresent)?atqa:NULL, (atqaPresent)?sak:NULL, oldUid);
2042 if (res) {
2043 PrintAndLog("Can't set UID. Error=%d", res);
2044 return 1;
2045 }
2046
2047 PrintAndLog("old UID:%s", sprint_hex(oldUid, 4));
2048 PrintAndLog("new UID:%s", sprint_hex(uid, 4));
2049 return 0;
2050 }
2051
2052 int CmdHF14AMfCWipe(const char *Cmd)
2053 {
2054 int res, gen = 0;
2055 int numBlocks = 16 * 4;
2056 bool wipeCard = false;
2057 bool fillCard = false;
2058
2059 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
2060 PrintAndLog("Usage: hf mf cwipe [card size] [w] [f]");
2061 PrintAndLog("sample: hf mf cwipe 1 w f");
2062 PrintAndLog("[card size]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
2063 PrintAndLog("w - Wipe magic Chinese card (only works with gen:1a cards)");
2064 PrintAndLog("f - Fill the card with default data and keys (works with gen:1a and gen:1b cards only)");
2065 return 0;
2066 }
2067
2068 gen = mfCIdentify();
2069 if ((gen != 1) && (gen != 2))
2070 return 1;
2071
2072 numBlocks = ParamCardSizeBlocks(param_getchar(Cmd, 0));
2073
2074 char cmdp = 0;
2075 while(param_getchar(Cmd, cmdp) != 0x00){
2076 switch(param_getchar(Cmd, cmdp)) {
2077 case 'w':
2078 case 'W':
2079 wipeCard = 1;
2080 break;
2081 case 'f':
2082 case 'F':
2083 fillCard = 1;
2084 break;
2085 default:
2086 break;
2087 }
2088 cmdp++;
2089 }
2090
2091 if (!wipeCard && !fillCard)
2092 wipeCard = true;
2093
2094 PrintAndLog("--blocks count:%2d wipe:%c fill:%c", numBlocks, (wipeCard)?'y':'n', (fillCard)?'y':'n');
2095
2096 if (gen == 2) {
2097 /* generation 1b magic card */
2098 if (wipeCard) {
2099 PrintAndLog("WARNING: can't wipe magic card 1b generation");
2100 }
2101 res = mfCWipe(numBlocks, true, false, fillCard);
2102 } else {
2103 /* generation 1a magic card by default */
2104 res = mfCWipe(numBlocks, false, wipeCard, fillCard);
2105 }
2106
2107 if (res) {
2108 PrintAndLog("Can't wipe. error=%d", res);
2109 return 1;
2110 }
2111 PrintAndLog("OK");
2112 return 0;
2113 }
2114
2115 int CmdHF14AMfCSetBlk(const char *Cmd)
2116 {
2117 uint8_t memBlock[16] = {0x00};
2118 uint8_t blockNo = 0;
2119 bool wipeCard = false;
2120 int res, gen = 0;
2121
2122 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
2123 PrintAndLog("Usage: hf mf csetblk <block number> <block data (32 hex symbols)> [w]");
2124 PrintAndLog("sample: hf mf csetblk 1 01020304050607080910111213141516");
2125 PrintAndLog("Set block data for magic Chinese card (only works with such cards)");
2126 PrintAndLog("If you also want wipe the card then add 'w' at the end of the command line");
2127 return 0;
2128 }
2129
2130 gen = mfCIdentify();
2131 if ((gen != 1) && (gen != 2))
2132 return 1;
2133
2134 blockNo = param_get8(Cmd, 0);
2135
2136 if (param_gethex(Cmd, 1, memBlock, 32)) {
2137 PrintAndLog("block data must include 32 HEX symbols");
2138 return 1;
2139 }
2140
2141 char ctmp = param_getchar(Cmd, 2);
2142 wipeCard = (ctmp == 'w' || ctmp == 'W');
2143 PrintAndLog("--block number:%2d data:%s", blockNo, sprint_hex(memBlock, 16));
2144
2145 if (gen == 2) {
2146 /* generation 1b magic card */
2147 res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B);
2148 } else {
2149 /* generation 1a magic card by default */
2150 res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER);
2151 }
2152
2153 if (res) {
2154 PrintAndLog("Can't write block. error=%d", res);
2155 return 1;
2156 }
2157 return 0;
2158 }
2159
2160
2161 int CmdHF14AMfCLoad(const char *Cmd)
2162 {
2163 FILE * f;
2164 char filename[FILE_PATH_SIZE] = {0x00};
2165 char * fnameptr = filename;
2166 char buf[256] = {0x00};
2167 uint8_t buf8[256] = {0x00};
2168 uint8_t fillFromEmulator = 0;
2169 int i, len, blockNum, flags = 0, gen = 0, numblock = 64;
2170
2171 if (param_getchar(Cmd, 0) == 'h' || param_getchar(Cmd, 0)== 0x00) {
2172 PrintAndLog("It loads magic Chinese card from the file `filename.eml`");
2173 PrintAndLog("or from emulator memory (option `e`). 4K card: (option `4`)");
2174 PrintAndLog("Usage: hf mf cload [file name w/o `.eml`][e][4]");
2175 PrintAndLog(" or: hf mf cload e [4]");
2176 PrintAndLog("Sample: hf mf cload filename");
2177 PrintAndLog(" hf mf cload filname 4");
2178 PrintAndLog(" hf mf cload e");
2179 PrintAndLog(" hf mf cload e 4");
2180 return 0;
2181 }
2182
2183 char ctmp = param_getchar(Cmd, 0);
2184 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;
2185 ctmp = param_getchar(Cmd, 1);
2186 if (ctmp == '4') numblock = 256;
2187
2188 gen = mfCIdentify();
2189 PrintAndLog("Loading magic mifare %dK", numblock == 256 ? 4:1);
2190
2191 if (fillFromEmulator) {
2192 for (blockNum = 0; blockNum < numblock; blockNum += 1) {
2193 if (mfEmlGetMem(buf8, blockNum, 1)) {
2194 PrintAndLog("Cant get block: %d", blockNum);
2195 return 2;
2196 }
2197 if (blockNum == 0) flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC; // switch on field and send magic sequence
2198 if (blockNum == 1) flags = 0; // just write
2199 if (blockNum == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD; // Done. Magic Halt and switch off field.
2200
2201 if (gen == 2)
2202 /* generation 1b magic card */
2203 flags |= CSETBLOCK_MAGIC_1B;
2204 if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) {
2205 PrintAndLog("Cant set magic card block: %d", blockNum);
2206 return 3;
2207 }
2208 }
2209 return 0;
2210 } else {
2211 param_getstr(Cmd, 0, filename, sizeof(filename));
2212
2213 len = strlen(filename);
2214 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
2215
2216 //memcpy(filename, Cmd, len);
2217 fnameptr += len;
2218
2219 sprintf(fnameptr, ".eml");
2220
2221 // open file
2222 f = fopen(filename, "r");
2223 if (f == NULL) {
2224 PrintAndLog("File not found or locked.");
2225 return 1;
2226 }
2227
2228 blockNum = 0;
2229 while(!feof(f)){
2230
2231 memset(buf, 0, sizeof(buf));
2232
2233 if (fgets(buf, sizeof(buf), f) == NULL) {
2234 fclose(f);
2235 PrintAndLog("File reading error.");
2236 return 2;
2237 }
2238
2239 if (strlen(buf) < 32) {
2240 if(strlen(buf) && feof(f))
2241 break;
2242 PrintAndLog("File content error. Block data must include 32 HEX symbols");
2243 fclose(f);
2244 return 2;
2245 }
2246 for (i = 0; i < 32; i += 2)
2247 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
2248
2249 if (blockNum == 0) flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC; // switch on field and send magic sequence
2250 if (blockNum == 1) flags = 0; // just write
2251 if (blockNum == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD; // Done. Switch off field.
2252
2253 if (gen == 2)
2254 /* generation 1b magic card */
2255 flags |= CSETBLOCK_MAGIC_1B;
2256 if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) {
2257 PrintAndLog("Can't set magic card block: %d", blockNum);
2258 fclose(f);
2259 return 3;
2260 }
2261 blockNum++;
2262
2263 if (blockNum >= numblock) break; // magic card type - mifare 1K 64 blocks, mifare 4k 256 blocks
2264 }
2265 fclose(f);
2266
2267 //if (blockNum != 16 * 4 && blockNum != 32 * 4 + 8 * 16){
2268 if (blockNum != numblock){
2269 PrintAndLog("File content error. There must be %d blocks", numblock);
2270 return 4;
2271 }
2272 PrintAndLog("Loaded from file: %s", filename);
2273 return 0;
2274 }
2275 return 0;
2276 }
2277
2278 int CmdHF14AMfCGetBlk(const char *Cmd) {
2279 uint8_t memBlock[16];
2280 uint8_t blockNo = 0;
2281 int res, gen = 0;
2282 memset(memBlock, 0x00, sizeof(memBlock));
2283
2284 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
2285 PrintAndLog("Usage: hf mf cgetblk <block number>");
2286 PrintAndLog("sample: hf mf cgetblk 1");
2287 PrintAndLog("Get block data from magic Chinese card (only works with such cards)\n");
2288 return 0;
2289 }
2290
2291 gen = mfCIdentify();
2292
2293 blockNo = param_get8(Cmd, 0);
2294
2295 PrintAndLog("--block number:%2d ", blockNo);
2296
2297 if (gen == 2) {
2298 /* generation 1b magic card */
2299 res = mfCGetBlock(blockNo, memBlock, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B);
2300 } else {
2301 /* generation 1a magic card by default */
2302 res = mfCGetBlock(blockNo, memBlock, CSETBLOCK_SINGLE_OPER);
2303 }
2304 if (res) {
2305 PrintAndLog("Can't read block. error=%d", res);
2306 return 1;
2307 }
2308
2309 PrintAndLog("block data:%s", sprint_hex(memBlock, 16));
2310
2311 if (mfIsSectorTrailer(blockNo)) {
2312 PrintAndLogEx(NORMAL, "Trailer decoded:");
2313 PrintAndLogEx(NORMAL, "Key A: %s", sprint_hex_inrow(memBlock, 6));
2314 PrintAndLogEx(NORMAL, "Key B: %s", sprint_hex_inrow(&memBlock[10], 6));
2315 int bln = mfFirstBlockOfSector(mfSectorNum(blockNo));
2316 int blinc = (mfNumBlocksPerSector(mfSectorNum(blockNo)) > 4) ? 5 : 1;
2317 for (int i = 0; i < 4; i++) {
2318 PrintAndLogEx(NORMAL, "Access block %d%s: %s", bln, ((blinc > 1) && (i < 3) ? "+" : "") , mfGetAccessConditionsDesc(i, &memBlock[6]));
2319 bln += blinc;
2320 }
2321 PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&memBlock[9], 1));
2322 }
2323
2324 return 0;
2325 }
2326
2327 int CmdHF14AMfCGetSc(const char *Cmd) {
2328 uint8_t memBlock[16] = {0x00};
2329 uint8_t sectorNo = 0;
2330 int i, res, flags, gen = 0, baseblock = 0, sect_size = 4;
2331
2332 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
2333 PrintAndLog("Usage: hf mf cgetsc <sector number>");
2334 PrintAndLog("sample: hf mf cgetsc 0");
2335 PrintAndLog("Get sector data from magic Chinese card (only works with such cards)\n");
2336 return 0;
2337 }
2338
2339 sectorNo = param_get8(Cmd, 0);
2340
2341 if (sectorNo > 39) {
2342 PrintAndLog("Sector number must be in [0..15] in MIFARE classic 1k and [0..39] in MIFARE classic 4k.");
2343 return 1;
2344 }
2345
2346 PrintAndLog("--sector number:%d ", sectorNo);
2347
2348 gen = mfCIdentify();
2349
2350 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;
2351 if (sectorNo < 32 ) {
2352 baseblock = sectorNo * 4;
2353 } else {
2354 baseblock = 128 + 16 * (sectorNo - 32);
2355
2356 }
2357 if (sectorNo > 31) sect_size = 16;
2358
2359 for (i = 0; i < sect_size; i++) {
2360 if (i == 1) flags = 0;
2361 if (i == sect_size - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;
2362
2363 if (gen == 2)
2364 /* generation 1b magic card */
2365 flags |= CSETBLOCK_MAGIC_1B;
2366
2367 res = mfCGetBlock(baseblock + i, memBlock, flags);
2368 if (res) {
2369 PrintAndLog("Can't read block. %d error=%d", baseblock + i, res);
2370 return 1;
2371 }
2372
2373 PrintAndLog("block %3d data:%s", baseblock + i, sprint_hex(memBlock, 16));
2374
2375 if (mfIsSectorTrailer(baseblock + i)) {
2376 PrintAndLogEx(NORMAL, "Trailer decoded:");
2377 PrintAndLogEx(NORMAL, "Key A: %s", sprint_hex_inrow(memBlock, 6));
2378 PrintAndLogEx(NORMAL, "Key B: %s", sprint_hex_inrow(&memBlock[10], 6));
2379 int bln = baseblock;
2380 int blinc = (mfNumBlocksPerSector(sectorNo) > 4) ? 5 : 1;
2381 for (int i = 0; i < 4; i++) {
2382 PrintAndLogEx(NORMAL, "Access block %d%s: %s", bln, ((blinc > 1) && (i < 3) ? "+" : "") , mfGetAccessConditionsDesc(i, &memBlock[6]));
2383 bln += blinc;
2384 }
2385 PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&memBlock[9], 1));
2386 }
2387 }
2388 return 0;
2389 }
2390
2391
2392 int CmdHF14AMfCSave(const char *Cmd) {
2393
2394 FILE * f;
2395 char filename[FILE_PATH_SIZE] = {0x00};
2396 char * fnameptr = filename;
2397 uint8_t fillFromEmulator = 0;
2398 uint8_t buf[256] = {0x00};
2399 int i, j, len, flags, gen = 0, numblock = 64;
2400
2401 // memset(filename, 0, sizeof(filename));
2402 // memset(buf, 0, sizeof(buf));
2403
2404 if (param_getchar(Cmd, 0) == 'h') {
2405 PrintAndLog("It saves `magic Chinese` card dump into the file `filename.eml` or `cardID.eml`");
2406 PrintAndLog("or into emulator memory (option `e`). 4K card: (option `4`)");
2407 PrintAndLog("Usage: hf mf csave [file name w/o `.eml`][e][4]");
2408 PrintAndLog("Sample: hf mf csave ");
2409 PrintAndLog(" hf mf csave filename");
2410 PrintAndLog(" hf mf csave e");
2411 PrintAndLog(" hf mf csave 4");
2412 PrintAndLog(" hf mf csave filename 4");
2413 PrintAndLog(" hf mf csave e 4");
2414 return 0;
2415 }
2416
2417 char ctmp = param_getchar(Cmd, 0);
2418 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;
2419 if (ctmp == '4') numblock = 256;
2420 ctmp = param_getchar(Cmd, 1);
2421 if (ctmp == '4') numblock = 256;
2422
2423 gen = mfCIdentify();
2424 PrintAndLog("Saving magic mifare %dK", numblock == 256 ? 4:1);
2425
2426 if (fillFromEmulator) {
2427 // put into emulator
2428 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;
2429 for (i = 0; i < numblock; i++) {
2430 if (i == 1) flags = 0;
2431 if (i == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;
2432
2433 if (gen == 2)
2434 /* generation 1b magic card */
2435 flags |= CSETBLOCK_MAGIC_1B;
2436
2437 if (mfCGetBlock(i, buf, flags)) {
2438 PrintAndLog("Cant get block: %d", i);
2439 break;
2440 }
2441
2442 if (mfEmlSetMem(buf, i, 1)) {
2443 PrintAndLog("Cant set emul block: %d", i);
2444 return 3;
2445 }
2446 }
2447 return 0;
2448 } else {
2449 param_getstr(Cmd, 0, filename, sizeof(filename));
2450
2451 len = strlen(filename);
2452 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
2453
2454 ctmp = param_getchar(Cmd, 0);
2455 if (len < 1 || (ctmp == '4')) {
2456 // get filename
2457
2458 flags = CSETBLOCK_SINGLE_OPER;
2459 if (gen == 2)
2460 /* generation 1b magic card */
2461 flags |= CSETBLOCK_MAGIC_1B;
2462 if (mfCGetBlock(0, buf, flags)) {
2463 PrintAndLog("Cant get block: %d", 0);
2464 len = sprintf(fnameptr, "dump");
2465 fnameptr += len;
2466 }
2467 else {
2468 for (j = 0; j < 7; j++, fnameptr += 2)
2469 sprintf(fnameptr, "%02x", buf[j]);
2470 }
2471 } else {
2472 //memcpy(filename, Cmd, len);
2473 fnameptr += len;
2474 }
2475
2476 sprintf(fnameptr, ".eml");
2477
2478 // open file
2479 f = fopen(filename, "w+");
2480
2481 if (f == NULL) {
2482 PrintAndLog("File not found or locked.");
2483 return 1;
2484 }
2485
2486 // put hex
2487 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;
2488 for (i = 0; i < numblock; i++) {
2489 if (i == 1) flags = 0;
2490 if (i == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;
2491
2492 if (gen == 2)
2493 /* generation 1b magic card */
2494 flags |= CSETBLOCK_MAGIC_1B;
2495 if (mfCGetBlock(i, buf, flags)) {
2496 PrintAndLog("Cant get block: %d", i);
2497 break;
2498 }
2499 for (j = 0; j < 16; j++)
2500 fprintf(f, "%02x", buf[j]);
2501 fprintf(f,"\n");
2502 }
2503 fclose(f);
2504
2505 PrintAndLog("Saved to file: %s", filename);
2506
2507 return 0;
2508 }
2509 }
2510
2511
2512 int CmdHF14AMfSniff(const char *Cmd){
2513
2514 bool wantLogToFile = 0;
2515 bool wantDecrypt = 0;
2516 //bool wantSaveToEml = 0; TODO
2517 bool wantSaveToEmlFile = 0;
2518
2519 //var
2520 int res = 0;
2521 int len = 0;
2522 int parlen = 0;
2523 int blockLen = 0;
2524 int pckNum = 0;
2525 int num = 0;
2526 uint8_t uid[7];
2527 uint8_t uid_len;
2528 uint8_t atqa[2] = {0x00};
2529 uint8_t sak;
2530 bool isTag;
2531 uint8_t *buf = NULL;
2532 uint16_t bufsize = 0;
2533 uint8_t *bufPtr = NULL;
2534 uint8_t parity[16];
2535
2536 char ctmp = param_getchar(Cmd, 0);
2537 if ( ctmp == 'h' || ctmp == 'H' ) {
2538 PrintAndLog("It continuously gets data from the field and saves it to: log, emulator, emulator file.");
2539 PrintAndLog("You can specify:");
2540 PrintAndLog(" l - save encrypted sequence to logfile `uid.log`");
2541 PrintAndLog(" d - decrypt sequence and put it to log file `uid.log`");
2542 PrintAndLog(" n/a e - decrypt sequence, collect read and write commands and save the result of the sequence to emulator memory");
2543 PrintAndLog(" f - decrypt sequence, collect read and write commands and save the result of the sequence to emulator dump file `uid.eml`");
2544 PrintAndLog("Usage: hf mf sniff [l][d][e][f]");
2545 PrintAndLog(" sample: hf mf sniff l d e");
2546 return 0;
2547 }
2548
2549 for (int i = 0; i < 4; i++) {
2550 ctmp = param_getchar(Cmd, i);
2551 if (ctmp == 'l' || ctmp == 'L') wantLogToFile = true;
2552 if (ctmp == 'd' || ctmp == 'D') wantDecrypt = true;
2553 //if (ctmp == 'e' || ctmp == 'E') wantSaveToEml = true; TODO
2554 if (ctmp == 'f' || ctmp == 'F') wantSaveToEmlFile = true;
2555 }
2556
2557 printf("-------------------------------------------------------------------------\n");
2558 printf("Executing command. \n");
2559 printf("Press the key on the proxmark3 device to abort both proxmark3 and client.\n");
2560 printf("Press the key on pc keyboard to abort the client.\n");
2561 printf("-------------------------------------------------------------------------\n");
2562
2563 UsbCommand c = {CMD_MIFARE_SNIFFER, {0, 0, 0}};
2564 clearCommandBuffer();
2565 SendCommand(&c);
2566
2567 // wait cycle
2568 while (true) {
2569 printf(".");
2570 fflush(stdout);
2571 if (ukbhit()) {
2572 getchar();
2573 printf("\naborted via keyboard!\n");
2574 break;
2575 }
2576
2577 UsbCommand resp;
2578 if (WaitForResponseTimeoutW(CMD_ACK, &resp, 2000, false)) {
2579 res = resp.arg[0] & 0xff;
2580 uint16_t traceLen = resp.arg[1];
2581 len = resp.arg[2];
2582
2583 if (res == 0) { // we are done
2584 break;
2585 }
2586
2587 if (res == 1) { // there is (more) data to be transferred
2588 if (pckNum == 0) { // first packet, (re)allocate necessary buffer
2589 if (traceLen > bufsize || buf == NULL) {
2590 uint8_t *p;
2591 if (buf == NULL) { // not yet allocated
2592 p = malloc(traceLen);
2593 } else { // need more memory
2594 p = realloc(buf, traceLen);
2595 }
2596 if (p == NULL) {
2597 PrintAndLog("Cannot allocate memory for trace");
2598 free(buf);
2599 return 2;
2600 }
2601 buf = p;
2602 }
2603 bufPtr = buf;
2604 bufsize = traceLen;
2605 memset(buf, 0x00, traceLen);
2606 }
2607 memcpy(bufPtr, resp.d.asBytes, len);
2608 bufPtr += len;
2609 pckNum++;
2610 }
2611
2612 if (res == 2) { // received all data, start displaying
2613 blockLen = bufPtr - buf;
2614 bufPtr = buf;
2615 printf(">\n");
2616 PrintAndLog("received trace len: %d packages: %d", blockLen, pckNum);
2617 while (bufPtr - buf < blockLen) {
2618 bufPtr += 6; // skip (void) timing information
2619 len = *((uint16_t *)bufPtr);
2620 if(len & 0x8000) {
2621 isTag = true;
2622 len &= 0x7fff;
2623 } else {
2624 isTag = false;
2625 }
2626 parlen = (len - 1) / 8 + 1;
2627 bufPtr += 2;
2628 if ((len == 14) && (bufPtr[0] == 0xff) && (bufPtr[1] == 0xff) && (bufPtr[12] == 0xff) && (bufPtr[13] == 0xff)) {
2629 memcpy(uid, bufPtr + 2, 7);
2630 memcpy(atqa, bufPtr + 2 + 7, 2);
2631 uid_len = (atqa[0] & 0xC0) == 0x40 ? 7 : 4;
2632 sak = bufPtr[11];
2633 PrintAndLog("tag select uid:%s atqa:0x%02x%02x sak:0x%02x",
2634 sprint_hex(uid + (7 - uid_len), uid_len),
2635 atqa[1],
2636 atqa[0],
2637 sak);
2638 if (wantLogToFile || wantDecrypt) {
2639 FillFileNameByUID(logHexFileName, uid + (7 - uid_len), ".log", uid_len);
2640 AddLogCurrentDT(logHexFileName);
2641 }
2642 if (wantDecrypt)
2643 mfTraceInit(uid, atqa, sak, wantSaveToEmlFile);
2644 } else {
2645 oddparitybuf(bufPtr, len, parity);
2646 PrintAndLog("%s(%d):%s [%s] c[%s]%c",
2647 isTag ? "TAG":"RDR",
2648 num,
2649 sprint_hex(bufPtr, len),
2650 printBitsPar(bufPtr + len, len),
2651 printBitsPar(parity, len),
2652 memcmp(bufPtr + len, parity, len / 8 + 1) ? '!' : ' ');
2653 if (wantLogToFile)
2654 AddLogHex(logHexFileName, isTag ? "TAG: ":"RDR: ", bufPtr, len);
2655 if (wantDecrypt)
2656 mfTraceDecode(bufPtr, len, bufPtr[len], wantSaveToEmlFile);
2657 num++;
2658 }
2659 bufPtr += len;
2660 bufPtr += parlen; // ignore parity
2661 }
2662 pckNum = 0;
2663 }
2664 } // resp not NULL
2665 } // while (true)
2666
2667 free(buf);
2668
2669 msleep(300); // wait for exiting arm side.
2670 PrintAndLog("Done.");
2671 return 0;
2672 }
2673
2674 //needs nt, ar, at, Data to decrypt
2675 int CmdDecryptTraceCmds(const char *Cmd){
2676 uint8_t data[50];
2677 int len = 0;
2678 param_gethex_ex(Cmd,3,data,&len);
2679 return tryDecryptWord(param_get32ex(Cmd,0,0,16),param_get32ex(Cmd,1,0,16),param_get32ex(Cmd,2,0,16),data,len/2);
2680 }
2681
2682 int CmdHF14AMfAuth4(const char *cmd) {
2683 uint8_t keyn[20] = {0};
2684 int keynlen = 0;
2685 uint8_t key[16] = {0};
2686 int keylen = 0;
2687
2688 CLIParserInit("hf mf auth4",
2689 "Executes AES authentication command in ISO14443-4",
2690 "Usage:\n\thf mf auth4 4000 000102030405060708090a0b0c0d0e0f -> executes authentication\n"
2691 "\thf mf auth4 9003 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -> executes authentication\n");
2692
2693 void* argtable[] = {
2694 arg_param_begin,
2695 arg_str1(NULL, NULL, "<Key Num (HEX 2 bytes)>", NULL),
2696 arg_str1(NULL, NULL, "<Key Value (HEX 16 bytes)>", NULL),
2697 arg_param_end
2698 };
2699 CLIExecWithReturn(cmd, argtable, true);
2700
2701 CLIGetHexWithReturn(1, keyn, &keynlen);
2702 CLIGetHexWithReturn(2, key, &keylen);
2703 CLIParserFree();
2704
2705 if (keynlen != 2) {
2706 PrintAndLog("ERROR: <Key Num> must be 2 bytes long instead of: %d", keynlen);
2707 return 1;
2708 }
2709
2710 if (keylen != 16) {
2711 PrintAndLog("ERROR: <Key Value> must be 16 bytes long instead of: %d", keylen);
2712 return 1;
2713 }
2714
2715 return MifareAuth4(NULL, keyn, key, true, false, true);
2716 }
2717
2718 // https://www.nxp.com/docs/en/application-note/AN10787.pdf
2719 int CmdHF14AMfMAD(const char *cmd) {
2720
2721 CLIParserInit("hf mf mad",
2722 "Checks and prints Mifare Application Directory (MAD)",
2723 "Usage:\n\thf mf mad -> shows MAD if exists\n"
2724 "\thf mf mad -a 03e1 -k ffffffffffff -b -> shows NDEF data if exists. read card with custom key and key B\n");
2725
2726 void *argtable[] = {
2727 arg_param_begin,
2728 arg_lit0("vV", "verbose", "show technical data"),
2729 arg_str0("aA", "aid", "print all sectors with aid", NULL),
2730 arg_str0("kK", "key", "key for printing sectors", NULL),
2731 arg_lit0("bB", "keyb", "use key B for access printing sectors (by default: key A)"),
2732 arg_param_end
2733 };
2734 CLIExecWithReturn(cmd, argtable, true);
2735 bool verbose = arg_get_lit(1);
2736 uint8_t aid[2] = {0};
2737 int aidlen;
2738 CLIGetHexWithReturn(2, aid, &aidlen);
2739 uint8_t key[6] = {0};
2740 int keylen;
2741 CLIGetHexWithReturn(3, key, &keylen);
2742 bool keyB = arg_get_lit(4);
2743
2744 CLIParserFree();
2745
2746 if (aidlen != 2 && keylen > 0) {
2747 PrintAndLogEx(WARNING, "do not need a key without aid.");
2748 }
2749
2750 uint8_t sector0[16 * 4] = {0};
2751 uint8_t sector10[16 * 4] = {0};
2752 if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0)) {
2753 PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");
2754 return 2;
2755 }
2756
2757 if (verbose) {
2758 for (int i = 0; i < 4; i ++)
2759 PrintAndLogEx(NORMAL, "[%d] %s", i, sprint_hex(&sector0[i * 16], 16));
2760 }
2761
2762 bool haveMAD2 = false;
2763 MAD1DecodeAndPrint(sector0, verbose, &haveMAD2);
2764
2765 if (haveMAD2) {
2766 if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10)) {
2767 PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");
2768 return 2;
2769 }
2770
2771 MAD2DecodeAndPrint(sector10, verbose);
2772 }
2773
2774 if (aidlen == 2) {
2775 uint16_t aaid = (aid[0] << 8) + aid[1];
2776 PrintAndLogEx(NORMAL, "\n-------------- AID 0x%04x ---------------", aaid);
2777
2778 uint16_t mad[7 + 8 + 8 + 8 + 8] = {0};
2779 size_t madlen = 0;
2780 if (MADDecode(sector0, sector10, mad, &madlen)) {
2781 PrintAndLogEx(ERR, "can't decode mad.");
2782 return 10;
2783 }
2784
2785 uint8_t akey[6] = {0};
2786 memcpy(akey, g_mifare_ndef_key, 6);
2787 if (keylen == 6) {
2788 memcpy(akey, key, 6);
2789 }
2790
2791 for (int i = 0; i < madlen; i++) {
2792 if (aaid == mad[i]) {
2793 uint8_t vsector[16 * 4] = {0};
2794 if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) {
2795 PrintAndLogEx(NORMAL, "");
2796 PrintAndLogEx(ERR, "read sector %d error.", i + 1);
2797 return 2;
2798 }
2799
2800 for (int j = 0; j < (verbose ? 4 : 3); j ++)
2801 PrintAndLogEx(NORMAL, " [%03d] %s", (i + 1) * 4 + j, sprint_hex(&vsector[j * 16], 16));
2802 }
2803 }
2804 }
2805
2806 return 0;
2807 }
2808
2809 int CmdHFMFNDEF(const char *cmd) {
2810
2811 CLIParserInit("hf mf ndef",
2812 "Prints NFC Data Exchange Format (NDEF)",
2813 "Usage:\n\thf mf ndef -> shows NDEF data\n"
2814 "\thf mf ndef -a 03e1 -k ffffffffffff -b -> shows NDEF data with custom AID, key and with key B\n");
2815
2816 void *argtable[] = {
2817 arg_param_begin,
2818 arg_litn("vV", "verbose", 0, 2, "show technical data"),
2819 arg_str0("aA", "aid", "replace default aid for NDEF", NULL),
2820 arg_str0("kK", "key", "replace default key for NDEF", NULL),
2821 arg_lit0("bB", "keyb", "use key B for access sectors (by default: key A)"),
2822 arg_param_end
2823 };
2824 CLIExecWithReturn(cmd, argtable, true);
2825
2826 bool verbose = arg_get_lit(1);
2827 bool verbose2 = arg_get_lit(1) > 1;
2828 uint8_t aid[2] = {0};
2829 int aidlen;
2830 CLIGetHexWithReturn(2, aid, &aidlen);
2831 uint8_t key[6] = {0};
2832 int keylen;
2833 CLIGetHexWithReturn(3, key, &keylen);
2834 bool keyB = arg_get_lit(4);
2835
2836 CLIParserFree();
2837
2838 uint16_t ndefAID = 0x03e1;
2839 if (aidlen == 2)
2840 ndefAID = (aid[0] << 8) + aid[1];
2841
2842 uint8_t ndefkey[6] = {0};
2843 memcpy(ndefkey, g_mifare_ndef_key, 6);
2844 if (keylen == 6) {
2845 memcpy(ndefkey, key, 6);
2846 }
2847
2848 uint8_t sector0[16 * 4] = {0};
2849 uint8_t sector10[16 * 4] = {0};
2850 uint8_t data[4096] = {0};
2851 int datalen = 0;
2852
2853 PrintAndLogEx(NORMAL, "");
2854
2855 if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0)) {
2856 PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");
2857 return 2;
2858 }
2859
2860 bool haveMAD2 = false;
2861 int res = MADCheck(sector0, NULL, verbose, &haveMAD2);
2862 if (res) {
2863 PrintAndLogEx(ERR, "MAD error %d.", res);
2864 return res;
2865 }
2866
2867 if (haveMAD2) {
2868 if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10)) {
2869 PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");
2870 return 2;
2871 }
2872 }
2873
2874 uint16_t mad[7 + 8 + 8 + 8 + 8] = {0};
2875 size_t madlen = 0;
2876 if (MADDecode(sector0, (haveMAD2 ? sector10 : NULL), mad, &madlen)) {
2877 PrintAndLogEx(ERR, "can't decode mad.");
2878 return 10;
2879 }
2880
2881 printf("data reading:");
2882 for (int i = 0; i < madlen; i++) {
2883 if (ndefAID == mad[i]) {
2884 uint8_t vsector[16 * 4] = {0};
2885 if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector)) {
2886 PrintAndLogEx(ERR, "read sector %d error.", i + 1);
2887 return 2;
2888 }
2889
2890 memcpy(&data[datalen], vsector, 16 * 3);
2891 datalen += 16 * 3;
2892
2893 printf(".");
2894 }
2895 }
2896 printf(" OK\n");
2897
2898 if (!datalen) {
2899 PrintAndLogEx(ERR, "no NDEF data.");
2900 return 11;
2901 }
2902
2903 if (verbose2) {
2904 PrintAndLogEx(NORMAL, "NDEF data:");
2905 dump_buffer(data, datalen, stdout, 1);
2906 }
2907
2908 NDEFDecodeAndPrint(data, datalen, verbose);
2909
2910 return 0;
2911 }
2912
2913 static command_t CommandTable[] =
2914 {
2915 {"help", CmdHelp, 1, "This help"},
2916 {"dbg", CmdHF14AMfDbg, 0, "Set default debug mode"},
2917 {"rdbl", CmdHF14AMfRdBl, 0, "Read MIFARE classic block"},
2918 {"rdsc", CmdHF14AMfRdSc, 0, "Read MIFARE classic sector"},
2919 {"dump", CmdHF14AMfDump, 0, "Dump MIFARE classic tag to binary file"},
2920 {"restore", CmdHF14AMfRestore, 0, "Restore MIFARE classic binary file to BLANK tag"},
2921 {"wrbl", CmdHF14AMfWrBl, 0, "Write MIFARE classic block"},
2922 {"auth4", CmdHF14AMfAuth4, 0, "ISO14443-4 AES authentication"},
2923 {"chk", CmdHF14AMfChk, 0, "Test block keys"},
2924 {"mifare", CmdHF14AMifare, 0, "Read parity error messages."},
2925 {"hardnested", CmdHF14AMfNestedHard, 0, "Nested attack for hardened Mifare cards"},
2926 {"nested", CmdHF14AMfNested, 0, "Test nested authentication"},
2927 {"sniff", CmdHF14AMfSniff, 0, "Sniff card-reader communication"},
2928 {"sim", CmdHF14AMf1kSim, 0, "Simulate MIFARE card"},
2929 {"eclr", CmdHF14AMfEClear, 0, "Clear simulator memory block"},
2930 {"eget", CmdHF14AMfEGet, 0, "Get simulator memory block"},
2931 {"eset", CmdHF14AMfESet, 0, "Set simulator memory block"},
2932 {"eload", CmdHF14AMfELoad, 0, "Load from file emul dump"},
2933 {"esave", CmdHF14AMfESave, 0, "Save to file emul dump"},
2934 {"ecfill", CmdHF14AMfECFill, 0, "Fill simulator memory with help of keys from simulator"},
2935 {"ekeyprn", CmdHF14AMfEKeyPrn, 0, "Print keys from simulator memory"},
2936 {"cwipe", CmdHF14AMfCWipe, 0, "Wipe magic Chinese card"},
2937 {"csetuid", CmdHF14AMfCSetUID, 0, "Set UID for magic Chinese card"},
2938 {"csetblk", CmdHF14AMfCSetBlk, 0, "Write block - Magic Chinese card"},
2939 {"cgetblk", CmdHF14AMfCGetBlk, 0, "Read block - Magic Chinese card"},
2940 {"cgetsc", CmdHF14AMfCGetSc, 0, "Read sector - Magic Chinese card"},
2941 {"cload", CmdHF14AMfCLoad, 0, "Load dump into magic Chinese card"},
2942 {"csave", CmdHF14AMfCSave, 0, "Save dump from magic Chinese card into file or emulator"},
2943 {"decrypt", CmdDecryptTraceCmds, 1, "[nt] [ar_enc] [at_enc] [data] - to decrypt snoop or trace"},
2944 {"mad", CmdHF14AMfMAD, 0, "Checks and prints MAD"},
2945 {"ndef", CmdHFMFNDEF, 0, "Prints NDEF records from card"},
2946 {NULL, NULL, 0, NULL}
2947 };
2948
2949 int CmdHFMF(const char *Cmd)
2950 {
2951 (void)WaitForResponseTimeout(CMD_ACK,NULL,100);
2952 CmdsParse(CommandTable, Cmd);
2953 return 0;
2954 }
2955
2956 int CmdHelp(const char *Cmd)
2957 {
2958 CmdsHelp(CommandTable);
2959 return 0;
2960 }
Impressum, Datenschutz