]> git.zerfleddert.de Git - proxmark3-svn/blob - client/cmdhfmf.c
fix hf mf sim (#812)
[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 numSectors = 16;
258 switch (c) {
259 case '0' : numSectors = 5; break;
260 case '2' : numSectors = 32; break;
261 case '4' : numSectors = 40; break;
262 default: numSectors = 16;
263 }
264 return numSectors;
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_mfsim(void) {
1425 PrintAndLog("Usage: hf mf sim [h] [*<card memory>] [u <uid (8, 14, or 20 hex symbols)>] [n <numreads>] [i] [x]");
1426 PrintAndLog("options:");
1427 PrintAndLog(" h (Optional) this help");
1428 PrintAndLog(" card memory: 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other, default> - 1K");
1429 PrintAndLog(" u (Optional) UID 4 or 7 bytes. If not specified, the UID 4B from emulator memory will be used");
1430 PrintAndLog(" n (Optional) Automatically exit simulation after <numreads> blocks have been read by reader. 0 = infinite");
1431 PrintAndLog(" i (Optional) Interactive, means that console will not be returned until simulation finishes or is aborted");
1432 PrintAndLog(" x (Optional) Crack, performs the 'reader attack', nr/ar attack against a legitimate reader, fishes out the key(s)");
1433 PrintAndLog(" e (Optional) set keys found from 'reader attack' to emulator memory (implies x and i)");
1434 PrintAndLog(" f (Optional) get UIDs to use for 'reader attack' from file 'f <filename.txt>' (implies x and i)");
1435 PrintAndLog(" r (Optional) Generate random nonces instead of sequential nonces. Standard reader attack won't work with this option, only moebius attack works.");
1436 PrintAndLog("samples:");
1437 PrintAndLog(" hf mf sim u 0a0a0a0a");
1438 PrintAndLog(" hf mf sim *4");
1439 PrintAndLog(" hf mf sim u 11223344556677");
1440 PrintAndLog(" hf mf sim f uids.txt");
1441 PrintAndLog(" hf mf sim u 0a0a0a0a e");
1442
1443 return 0;
1444 }
1445
1446 int CmdHF14AMfSim(const char *Cmd) {
1447 UsbCommand resp;
1448 uint8_t uid[7] = {0};
1449 uint8_t exitAfterNReads = 0;
1450 uint8_t flags = 0;
1451 int uidlen = 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 uint8_t cardsize = '1';
1463
1464 while(param_getchar(Cmd, cmdp) != 0x00) {
1465 switch(param_getchar(Cmd, cmdp)) {
1466 case '*':
1467 cardsize = param_getchar(Cmd + 1, cmdp);
1468 switch(cardsize) {
1469 case '0':
1470 case '1':
1471 case '2':
1472 case '4': break;
1473 default: cardsize = '1';
1474 }
1475 cmdp++;
1476 break;
1477 case 'e':
1478 case 'E':
1479 setEmulatorMem = true;
1480 //implies x and i
1481 flags |= FLAG_INTERACTIVE;
1482 flags |= FLAG_NR_AR_ATTACK;
1483 cmdp++;
1484 break;
1485 case 'f':
1486 case 'F':
1487 len = param_getstr(Cmd, cmdp+1, filename, sizeof(filename));
1488 if (len < 1) {
1489 PrintAndLog("error no filename found");
1490 return 0;
1491 }
1492 attackFromFile = true;
1493 //implies x and i
1494 flags |= FLAG_INTERACTIVE;
1495 flags |= FLAG_NR_AR_ATTACK;
1496 cmdp += 2;
1497 break;
1498 case 'h':
1499 case 'H':
1500 return usage_hf14_mfsim();
1501 case 'i':
1502 case 'I':
1503 flags |= FLAG_INTERACTIVE;
1504 cmdp++;
1505 break;
1506 case 'n':
1507 case 'N':
1508 exitAfterNReads = param_get8(Cmd, cmdp+1);
1509 cmdp += 2;
1510 break;
1511 case 'r':
1512 case 'R':
1513 flags |= FLAG_RANDOM_NONCE;
1514 cmdp++;
1515 break;
1516 case 'u':
1517 case 'U':
1518 param_gethex_ex(Cmd, cmdp+1, uid, &uidlen);
1519 switch(uidlen) {
1520 case 14: flags = FLAG_7B_UID_IN_DATA; break;
1521 case 8: flags = FLAG_4B_UID_IN_DATA; break;
1522 default: return usage_hf14_mfsim();
1523 }
1524 cmdp += 2;
1525 break;
1526 case 'x':
1527 case 'X':
1528 flags |= FLAG_NR_AR_ATTACK;
1529 cmdp++;
1530 break;
1531 default:
1532 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
1533 errors = true;
1534 break;
1535 }
1536 if(errors) break;
1537 }
1538 //Validations
1539 if(errors) return usage_hf14_mfsim();
1540
1541 //get uid from file
1542 if (attackFromFile) {
1543 int count = 0;
1544 // open file
1545 f = fopen(filename, "r");
1546 if (f == NULL) {
1547 PrintAndLog("File %s not found or locked", filename);
1548 return 1;
1549 }
1550 PrintAndLog("Loading file and simulating. Press keyboard to abort");
1551 while(!feof(f) && !ukbhit()){
1552 memset(buf, 0, sizeof(buf));
1553 memset(uid, 0, sizeof(uid));
1554
1555 if (fgets(buf, sizeof(buf), f) == NULL) {
1556 if (count > 0) break;
1557
1558 PrintAndLog("File reading error.");
1559 fclose(f);
1560 return 2;
1561 }
1562 if(!strlen(buf) && feof(f)) break;
1563
1564 uidlen = strlen(buf)-1;
1565 switch(uidlen) {
1566 case 14: flags |= FLAG_7B_UID_IN_DATA; break;
1567 case 8: flags |= FLAG_4B_UID_IN_DATA; break;
1568 default:
1569 PrintAndLog("uid in file wrong length at %d (length: %d) [%s]",count, uidlen, buf);
1570 fclose(f);
1571 return 2;
1572 }
1573
1574 for (uint8_t i = 0; i < uidlen; i += 2) {
1575 sscanf(&buf[i], "%02x", (unsigned int *)&uid[i / 2]);
1576 }
1577
1578 PrintAndLog("mf sim cardsize: %s, uid: %s, numreads:%d, flags:%d (0x%02x) - press button to abort",
1579 cardsize == '0' ? "Mini" :
1580 cardsize == '2' ? "2K" :
1581 cardsize == '4' ? "4K" : "1K",
1582 flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4):
1583 flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): "N/A",
1584 exitAfterNReads,
1585 flags,
1586 flags);
1587
1588 UsbCommand c = {CMD_SIMULATE_MIFARE_CARD, {flags, exitAfterNReads, cardsize}};
1589 memcpy(c.d.asBytes, uid, sizeof(uid));
1590 clearCommandBuffer();
1591 SendCommand(&c);
1592
1593 while (! WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
1594 //We're waiting only 1.5 s at a time, otherwise we get the
1595 // annoying message about "Waiting for a response... "
1596 }
1597 //got a response
1598 nonces_t ar_resp[ATTACK_KEY_COUNT*2];
1599 memcpy(ar_resp, resp.d.asBytes, sizeof(ar_resp));
1600 // We can skip the standard attack if we have RANDOM_NONCE set.
1601 readerAttack(ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE));
1602 if ((bool)resp.arg[1]) {
1603 PrintAndLog("Device button pressed - quitting");
1604 fclose(f);
1605 return 4;
1606 }
1607 count++;
1608 }
1609 fclose(f);
1610
1611 } else { //not from file
1612
1613 PrintAndLog("mf sim cardsize: %s, uid: %s, numreads:%d, flags:%d (0x%02x) ",
1614 cardsize == '0' ? "Mini" :
1615 cardsize == '2' ? "2K" :
1616 cardsize == '4' ? "4K" : "1K",
1617 flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4):
1618 flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): "N/A",
1619 exitAfterNReads,
1620 flags,
1621 flags);
1622
1623 UsbCommand c = {CMD_SIMULATE_MIFARE_CARD, {flags, exitAfterNReads, cardsize}};
1624 memcpy(c.d.asBytes, uid, sizeof(uid));
1625 clearCommandBuffer();
1626 SendCommand(&c);
1627
1628 if(flags & FLAG_INTERACTIVE) {
1629 PrintAndLog("Press pm3-button to abort simulation");
1630 while(! WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {
1631 //We're waiting only 1.5 s at a time, otherwise we get the
1632 // annoying message about "Waiting for a response... "
1633 }
1634 //got a response
1635 if (flags & FLAG_NR_AR_ATTACK) {
1636 nonces_t ar_resp[ATTACK_KEY_COUNT*2];
1637 memcpy(ar_resp, resp.d.asBytes, sizeof(ar_resp));
1638 // We can skip the standard attack if we have RANDOM_NONCE set.
1639 readerAttack(ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE));
1640 }
1641 }
1642 }
1643
1644 return 0;
1645 }
1646
1647 int CmdHF14AMfDbg(const char *Cmd)
1648 {
1649 int dbgMode = param_get32ex(Cmd, 0, 0, 10);
1650 if (dbgMode > 4) {
1651 PrintAndLog("Max debug mode parameter is 4 \n");
1652 }
1653
1654 if (strlen(Cmd) < 1 || !param_getchar(Cmd, 0) || dbgMode > 4) {
1655 PrintAndLog("Usage: hf mf dbg <debug level>");
1656 PrintAndLog(" 0 - no debug messages");
1657 PrintAndLog(" 1 - error messages");
1658 PrintAndLog(" 2 - plus information messages");
1659 PrintAndLog(" 3 - plus debug messages");
1660 PrintAndLog(" 4 - print even debug messages in timing critical functions");
1661 PrintAndLog(" Note: this option therefore may cause malfunction itself");
1662 return 0;
1663 }
1664
1665 UsbCommand c = {CMD_MIFARE_SET_DBGMODE, {dbgMode, 0, 0}};
1666 SendCommand(&c);
1667
1668 return 0;
1669 }
1670
1671 int CmdHF14AMfEGet(const char *Cmd)
1672 {
1673 uint8_t blockNo = 0;
1674 uint8_t data[16] = {0x00};
1675
1676 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
1677 PrintAndLog("Usage: hf mf eget <block number>");
1678 PrintAndLog(" sample: hf mf eget 0 ");
1679 return 0;
1680 }
1681
1682 blockNo = param_get8(Cmd, 0);
1683
1684 PrintAndLog(" ");
1685 if (!mfEmlGetMem(data, blockNo, 1)) {
1686 PrintAndLog("data[%3d]:%s", blockNo, sprint_hex(data, 16));
1687 } else {
1688 PrintAndLog("Command execute timeout");
1689 }
1690
1691 return 0;
1692 }
1693
1694 int CmdHF14AMfEClear(const char *Cmd)
1695 {
1696 if (param_getchar(Cmd, 0) == 'h') {
1697 PrintAndLog("Usage: hf mf eclr");
1698 PrintAndLog("It set card emulator memory to empty data blocks and key A/B FFFFFFFFFFFF \n");
1699 return 0;
1700 }
1701
1702 UsbCommand c = {CMD_MIFARE_EML_MEMCLR, {0, 0, 0}};
1703 SendCommand(&c);
1704 return 0;
1705 }
1706
1707
1708 int CmdHF14AMfESet(const char *Cmd)
1709 {
1710 uint8_t memBlock[16];
1711 uint8_t blockNo = 0;
1712
1713 memset(memBlock, 0x00, sizeof(memBlock));
1714
1715 if (strlen(Cmd) < 3 || param_getchar(Cmd, 0) == 'h') {
1716 PrintAndLog("Usage: hf mf eset <block number> <block data (32 hex symbols)>");
1717 PrintAndLog(" sample: hf mf eset 1 000102030405060708090a0b0c0d0e0f ");
1718 return 0;
1719 }
1720
1721 blockNo = param_get8(Cmd, 0);
1722
1723 if (param_gethex(Cmd, 1, memBlock, 32)) {
1724 PrintAndLog("block data must include 32 HEX symbols");
1725 return 1;
1726 }
1727
1728 // 1 - blocks count
1729 return mfEmlSetMem(memBlock, blockNo, 1);
1730 }
1731
1732
1733 int CmdHF14AMfELoad(const char *Cmd)
1734 {
1735 FILE * f;
1736 char filename[FILE_PATH_SIZE];
1737 char *fnameptr = filename;
1738 char buf[64] = {0x00};
1739 uint8_t buf8[64] = {0x00};
1740 int i, len, blockNum, numBlocks;
1741 int nameParamNo = 1;
1742
1743 char ctmp = param_getchar(Cmd, 0);
1744
1745 if ( ctmp == 'h' || ctmp == 0x00) {
1746 PrintAndLog("It loads emul dump from the file `filename.eml`");
1747 PrintAndLog("Usage: hf mf eload [card memory] <file name w/o `.eml`>");
1748 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1749 PrintAndLog("");
1750 PrintAndLog(" sample: hf mf eload filename");
1751 PrintAndLog(" hf mf eload 4 filename");
1752 return 0;
1753 }
1754
1755 switch (ctmp) {
1756 case '0' : numBlocks = 5*4; break;
1757 case '1' :
1758 case '\0': numBlocks = 16*4; break;
1759 case '2' : numBlocks = 32*4; break;
1760 case '4' : numBlocks = 256; break;
1761 default: {
1762 numBlocks = 16*4;
1763 nameParamNo = 0;
1764 }
1765 }
1766
1767 len = param_getstr(Cmd, nameParamNo, filename, sizeof(filename));
1768
1769 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
1770
1771 fnameptr += len;
1772
1773 sprintf(fnameptr, ".eml");
1774
1775 // open file
1776 f = fopen(filename, "r");
1777 if (f == NULL) {
1778 PrintAndLog("File %s not found or locked", filename);
1779 return 1;
1780 }
1781
1782 blockNum = 0;
1783 while(!feof(f)){
1784 memset(buf, 0, sizeof(buf));
1785
1786 if (fgets(buf, sizeof(buf), f) == NULL) {
1787
1788 if (blockNum >= numBlocks) break;
1789
1790 PrintAndLog("File reading error.");
1791 fclose(f);
1792 return 2;
1793 }
1794
1795 if (strlen(buf) < 32){
1796 if(strlen(buf) && feof(f))
1797 break;
1798 PrintAndLog("File content error. Block data must include 32 HEX symbols");
1799 fclose(f);
1800 return 2;
1801 }
1802
1803 for (i = 0; i < 32; i += 2) {
1804 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
1805 }
1806
1807 if (mfEmlSetMem(buf8, blockNum, 1)) {
1808 PrintAndLog("Cant set emul block: %3d", blockNum);
1809 fclose(f);
1810 return 3;
1811 }
1812 printf(".");
1813 blockNum++;
1814
1815 if (blockNum >= numBlocks) break;
1816 }
1817 fclose(f);
1818 printf("\n");
1819
1820 if ((blockNum != numBlocks)) {
1821 PrintAndLog("File content error. Got %d must be %d blocks.",blockNum, numBlocks);
1822 return 4;
1823 }
1824 PrintAndLog("Loaded %d blocks from file: %s", blockNum, filename);
1825 return 0;
1826 }
1827
1828
1829 int CmdHF14AMfESave(const char *Cmd)
1830 {
1831 FILE * f;
1832 char filename[FILE_PATH_SIZE];
1833 char * fnameptr = filename;
1834 uint8_t buf[64];
1835 int i, j, len, numBlocks;
1836 int nameParamNo = 1;
1837
1838 memset(filename, 0, sizeof(filename));
1839 memset(buf, 0, sizeof(buf));
1840
1841 char ctmp = param_getchar(Cmd, 0);
1842
1843 if ( ctmp == 'h' || ctmp == 'H') {
1844 PrintAndLog("It saves emul dump into the file `filename.eml` or `cardID.eml`");
1845 PrintAndLog(" Usage: hf mf esave [card memory] [file name w/o `.eml`]");
1846 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1847 PrintAndLog("");
1848 PrintAndLog(" sample: hf mf esave ");
1849 PrintAndLog(" hf mf esave 4");
1850 PrintAndLog(" hf mf esave 4 filename");
1851 return 0;
1852 }
1853
1854 switch (ctmp) {
1855 case '0' : numBlocks = 5*4; break;
1856 case '1' :
1857 case '\0': numBlocks = 16*4; break;
1858 case '2' : numBlocks = 32*4; break;
1859 case '4' : numBlocks = 256; break;
1860 default: {
1861 numBlocks = 16*4;
1862 nameParamNo = 0;
1863 }
1864 }
1865
1866 len = param_getstr(Cmd,nameParamNo,filename,sizeof(filename));
1867
1868 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
1869
1870 // user supplied filename?
1871 if (len < 1) {
1872 // get filename (UID from memory)
1873 if (mfEmlGetMem(buf, 0, 1)) {
1874 PrintAndLog("Can\'t get UID from block: %d", 0);
1875 len = sprintf(fnameptr, "dump");
1876 fnameptr += len;
1877 }
1878 else {
1879 for (j = 0; j < 7; j++, fnameptr += 2)
1880 sprintf(fnameptr, "%02X", buf[j]);
1881 }
1882 } else {
1883 fnameptr += len;
1884 }
1885
1886 // add file extension
1887 sprintf(fnameptr, ".eml");
1888
1889 // open file
1890 f = fopen(filename, "w+");
1891
1892 if ( !f ) {
1893 PrintAndLog("Can't open file %s ", filename);
1894 return 1;
1895 }
1896
1897 // put hex
1898 for (i = 0; i < numBlocks; i++) {
1899 if (mfEmlGetMem(buf, i, 1)) {
1900 PrintAndLog("Cant get block: %d", i);
1901 break;
1902 }
1903 for (j = 0; j < 16; j++)
1904 fprintf(f, "%02X", buf[j]);
1905 fprintf(f,"\n");
1906 }
1907 fclose(f);
1908
1909 PrintAndLog("Saved %d blocks to file: %s", numBlocks, filename);
1910
1911 return 0;
1912 }
1913
1914
1915 int CmdHF14AMfECFill(const char *Cmd)
1916 {
1917 uint8_t keyType = 0;
1918 uint8_t numSectors = 16;
1919
1920 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
1921 PrintAndLog("Usage: hf mf ecfill <key A/B> [card memory]");
1922 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1923 PrintAndLog("");
1924 PrintAndLog("samples: hf mf ecfill A");
1925 PrintAndLog(" hf mf ecfill A 4");
1926 PrintAndLog("Read card and transfer its data to emulator memory.");
1927 PrintAndLog("Keys must be laid in the emulator memory. \n");
1928 return 0;
1929 }
1930
1931 char ctmp = param_getchar(Cmd, 0);
1932 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {
1933 PrintAndLog("Key type must be A or B");
1934 return 1;
1935 }
1936 if (ctmp != 'A' && ctmp != 'a') keyType = 1;
1937
1938 ctmp = param_getchar(Cmd, 1);
1939 switch (ctmp) {
1940 case '0' : numSectors = 5; break;
1941 case '1' :
1942 case '\0': numSectors = 16; break;
1943 case '2' : numSectors = 32; break;
1944 case '4' : numSectors = 40; break;
1945 default: numSectors = 16;
1946 }
1947
1948 printf("--params: numSectors: %d, keyType:%d\n", numSectors, keyType);
1949 UsbCommand c = {CMD_MIFARE_EML_CARDLOAD, {numSectors, keyType, 0}};
1950 SendCommand(&c);
1951 return 0;
1952 }
1953
1954 int CmdHF14AMfEKeyPrn(const char *Cmd)
1955 {
1956 int i;
1957 uint8_t numSectors;
1958 uint8_t data[16];
1959 uint64_t keyA, keyB;
1960
1961 if (param_getchar(Cmd, 0) == 'h') {
1962 PrintAndLog("It prints the keys loaded in the emulator memory");
1963 PrintAndLog("Usage: hf mf ekeyprn [card memory]");
1964 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1965 PrintAndLog("");
1966 PrintAndLog(" sample: hf mf ekeyprn 1");
1967 return 0;
1968 }
1969
1970 char cmdp = param_getchar(Cmd, 0);
1971
1972 switch (cmdp) {
1973 case '0' : numSectors = 5; break;
1974 case '1' :
1975 case '\0': numSectors = 16; break;
1976 case '2' : numSectors = 32; break;
1977 case '4' : numSectors = 40; break;
1978 default: numSectors = 16;
1979 }
1980
1981 PrintAndLog("|---|----------------|----------------|");
1982 PrintAndLog("|sec|key A |key B |");
1983 PrintAndLog("|---|----------------|----------------|");
1984 for (i = 0; i < numSectors; i++) {
1985 if (mfEmlGetMem(data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) {
1986 PrintAndLog("error get block %d", FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1);
1987 break;
1988 }
1989 keyA = bytes_to_num(data, 6);
1990 keyB = bytes_to_num(data + 10, 6);
1991 PrintAndLog("|%03d| %012" PRIx64 " | %012" PRIx64 " |", i, keyA, keyB);
1992 }
1993 PrintAndLog("|---|----------------|----------------|");
1994
1995 return 0;
1996 }
1997
1998 int CmdHF14AMfCSetUID(const char *Cmd)
1999 {
2000 uint8_t uid[8] = {0x00};
2001 uint8_t oldUid[8] = {0x00};
2002 uint8_t atqa[2] = {0x00};
2003 uint8_t sak[1] = {0x00};
2004 uint8_t atqaPresent = 0;
2005 int res;
2006
2007 uint8_t needHelp = 0;
2008 char cmdp = 1;
2009
2010 if (param_getchar(Cmd, 0) && param_gethex(Cmd, 0, uid, 8)) {
2011 PrintAndLog("UID must include 8 HEX symbols");
2012 return 1;
2013 }
2014
2015 if (param_getlength(Cmd, 1) > 1 && param_getlength(Cmd, 2) > 1) {
2016 atqaPresent = 1;
2017 cmdp = 3;
2018
2019 if (param_gethex(Cmd, 1, atqa, 4)) {
2020 PrintAndLog("ATQA must include 4 HEX symbols");
2021 return 1;
2022 }
2023
2024 if (param_gethex(Cmd, 2, sak, 2)) {
2025 PrintAndLog("SAK must include 2 HEX symbols");
2026 return 1;
2027 }
2028 }
2029
2030 while(param_getchar(Cmd, cmdp) != 0x00)
2031 {
2032 switch(param_getchar(Cmd, cmdp))
2033 {
2034 case 'h':
2035 case 'H':
2036 needHelp = 1;
2037 break;
2038 default:
2039 PrintAndLog("ERROR: Unknown parameter '%c'", param_getchar(Cmd, cmdp));
2040 needHelp = 1;
2041 break;
2042 }
2043 cmdp++;
2044 }
2045
2046 if (strlen(Cmd) < 1 || needHelp) {
2047 PrintAndLog("");
2048 PrintAndLog("Usage: hf mf csetuid <UID 8 hex symbols> [ATQA 4 hex symbols SAK 2 hex symbols]");
2049 PrintAndLog("sample: hf mf csetuid 01020304");
2050 PrintAndLog("sample: hf mf csetuid 01020304 0004 08");
2051 PrintAndLog("Set UID, ATQA, and SAK for magic Chinese card (only works with such cards)");
2052 return 0;
2053 }
2054
2055 PrintAndLog("uid:%s", sprint_hex(uid, 4));
2056 if (atqaPresent) {
2057 PrintAndLog("--atqa:%s sak:%02x", sprint_hex(atqa, 2), sak[0]);
2058 }
2059
2060 res = mfCSetUID(uid, (atqaPresent)?atqa:NULL, (atqaPresent)?sak:NULL, oldUid);
2061 if (res) {
2062 PrintAndLog("Can't set UID. Error=%d", res);
2063 return 1;
2064 }
2065
2066 PrintAndLog("old UID:%s", sprint_hex(oldUid, 4));
2067 PrintAndLog("new UID:%s", sprint_hex(uid, 4));
2068 return 0;
2069 }
2070
2071 int CmdHF14AMfCWipe(const char *Cmd)
2072 {
2073 int res, gen = 0;
2074 int numBlocks = 16 * 4;
2075 bool wipeCard = false;
2076 bool fillCard = false;
2077
2078 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
2079 PrintAndLog("Usage: hf mf cwipe [card size] [w] [f]");
2080 PrintAndLog("sample: hf mf cwipe 1 w f");
2081 PrintAndLog("[card size]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
2082 PrintAndLog("w - Wipe magic Chinese card (only works with gen:1a cards)");
2083 PrintAndLog("f - Fill the card with default data and keys (works with gen:1a and gen:1b cards only)");
2084 return 0;
2085 }
2086
2087 gen = mfCIdentify();
2088 if ((gen != 1) && (gen != 2))
2089 return 1;
2090
2091 numBlocks = ParamCardSizeBlocks(param_getchar(Cmd, 0));
2092
2093 char cmdp = 0;
2094 while(param_getchar(Cmd, cmdp) != 0x00){
2095 switch(param_getchar(Cmd, cmdp)) {
2096 case 'w':
2097 case 'W':
2098 wipeCard = 1;
2099 break;
2100 case 'f':
2101 case 'F':
2102 fillCard = 1;
2103 break;
2104 default:
2105 break;
2106 }
2107 cmdp++;
2108 }
2109
2110 if (!wipeCard && !fillCard)
2111 wipeCard = true;
2112
2113 PrintAndLog("--blocks count:%2d wipe:%c fill:%c", numBlocks, (wipeCard)?'y':'n', (fillCard)?'y':'n');
2114
2115 if (gen == 2) {
2116 /* generation 1b magic card */
2117 if (wipeCard) {
2118 PrintAndLog("WARNING: can't wipe magic card 1b generation");
2119 }
2120 res = mfCWipe(numBlocks, true, false, fillCard);
2121 } else {
2122 /* generation 1a magic card by default */
2123 res = mfCWipe(numBlocks, false, wipeCard, fillCard);
2124 }
2125
2126 if (res) {
2127 PrintAndLog("Can't wipe. error=%d", res);
2128 return 1;
2129 }
2130 PrintAndLog("OK");
2131 return 0;
2132 }
2133
2134 int CmdHF14AMfCSetBlk(const char *Cmd)
2135 {
2136 uint8_t memBlock[16] = {0x00};
2137 uint8_t blockNo = 0;
2138 bool wipeCard = false;
2139 int res, gen = 0;
2140
2141 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
2142 PrintAndLog("Usage: hf mf csetblk <block number> <block data (32 hex symbols)> [w]");
2143 PrintAndLog("sample: hf mf csetblk 1 01020304050607080910111213141516");
2144 PrintAndLog("Set block data for magic Chinese card (only works with such cards)");
2145 PrintAndLog("If you also want wipe the card then add 'w' at the end of the command line");
2146 return 0;
2147 }
2148
2149 gen = mfCIdentify();
2150 if ((gen != 1) && (gen != 2))
2151 return 1;
2152
2153 blockNo = param_get8(Cmd, 0);
2154
2155 if (param_gethex(Cmd, 1, memBlock, 32)) {
2156 PrintAndLog("block data must include 32 HEX symbols");
2157 return 1;
2158 }
2159
2160 char ctmp = param_getchar(Cmd, 2);
2161 wipeCard = (ctmp == 'w' || ctmp == 'W');
2162 PrintAndLog("--block number:%2d data:%s", blockNo, sprint_hex(memBlock, 16));
2163
2164 if (gen == 2) {
2165 /* generation 1b magic card */
2166 res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B);
2167 } else {
2168 /* generation 1a magic card by default */
2169 res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER);
2170 }
2171
2172 if (res) {
2173 PrintAndLog("Can't write block. error=%d", res);
2174 return 1;
2175 }
2176 return 0;
2177 }
2178
2179
2180 int CmdHF14AMfCLoad(const char *Cmd)
2181 {
2182 FILE * f;
2183 char filename[FILE_PATH_SIZE] = {0x00};
2184 char * fnameptr = filename;
2185 char buf[256] = {0x00};
2186 uint8_t buf8[256] = {0x00};
2187 uint8_t fillFromEmulator = 0;
2188 int i, len, blockNum, flags = 0, gen = 0, numblock = 64;
2189
2190 if (param_getchar(Cmd, 0) == 'h' || param_getchar(Cmd, 0)== 0x00) {
2191 PrintAndLog("It loads magic Chinese card from the file `filename.eml`");
2192 PrintAndLog("or from emulator memory (option `e`). 4K card: (option `4`)");
2193 PrintAndLog("Usage: hf mf cload [file name w/o `.eml`][e][4]");
2194 PrintAndLog(" or: hf mf cload e [4]");
2195 PrintAndLog("Sample: hf mf cload filename");
2196 PrintAndLog(" hf mf cload filname 4");
2197 PrintAndLog(" hf mf cload e");
2198 PrintAndLog(" hf mf cload e 4");
2199 return 0;
2200 }
2201
2202 char ctmp = param_getchar(Cmd, 0);
2203 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;
2204 ctmp = param_getchar(Cmd, 1);
2205 if (ctmp == '4') numblock = 256;
2206
2207 gen = mfCIdentify();
2208 PrintAndLog("Loading magic mifare %dK", numblock == 256 ? 4:1);
2209
2210 if (fillFromEmulator) {
2211 for (blockNum = 0; blockNum < numblock; blockNum += 1) {
2212 if (mfEmlGetMem(buf8, blockNum, 1)) {
2213 PrintAndLog("Cant get block: %d", blockNum);
2214 return 2;
2215 }
2216 if (blockNum == 0) flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC; // switch on field and send magic sequence
2217 if (blockNum == 1) flags = 0; // just write
2218 if (blockNum == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD; // Done. Magic Halt and switch off field.
2219
2220 if (gen == 2)
2221 /* generation 1b magic card */
2222 flags |= CSETBLOCK_MAGIC_1B;
2223 if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) {
2224 PrintAndLog("Cant set magic card block: %d", blockNum);
2225 return 3;
2226 }
2227 }
2228 return 0;
2229 } else {
2230 param_getstr(Cmd, 0, filename, sizeof(filename));
2231
2232 len = strlen(filename);
2233 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
2234
2235 //memcpy(filename, Cmd, len);
2236 fnameptr += len;
2237
2238 sprintf(fnameptr, ".eml");
2239
2240 // open file
2241 f = fopen(filename, "r");
2242 if (f == NULL) {
2243 PrintAndLog("File not found or locked.");
2244 return 1;
2245 }
2246
2247 blockNum = 0;
2248 while(!feof(f)){
2249
2250 memset(buf, 0, sizeof(buf));
2251
2252 if (fgets(buf, sizeof(buf), f) == NULL) {
2253 fclose(f);
2254 PrintAndLog("File reading error.");
2255 return 2;
2256 }
2257
2258 if (strlen(buf) < 32) {
2259 if(strlen(buf) && feof(f))
2260 break;
2261 PrintAndLog("File content error. Block data must include 32 HEX symbols");
2262 fclose(f);
2263 return 2;
2264 }
2265 for (i = 0; i < 32; i += 2)
2266 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
2267
2268 if (blockNum == 0) flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC; // switch on field and send magic sequence
2269 if (blockNum == 1) flags = 0; // just write
2270 if (blockNum == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD; // Done. Switch off field.
2271
2272 if (gen == 2)
2273 /* generation 1b magic card */
2274 flags |= CSETBLOCK_MAGIC_1B;
2275 if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) {
2276 PrintAndLog("Can't set magic card block: %d", blockNum);
2277 fclose(f);
2278 return 3;
2279 }
2280 blockNum++;
2281
2282 if (blockNum >= numblock) break; // magic card type - mifare 1K 64 blocks, mifare 4k 256 blocks
2283 }
2284 fclose(f);
2285
2286 //if (blockNum != 16 * 4 && blockNum != 32 * 4 + 8 * 16){
2287 if (blockNum != numblock){
2288 PrintAndLog("File content error. There must be %d blocks", numblock);
2289 return 4;
2290 }
2291 PrintAndLog("Loaded from file: %s", filename);
2292 return 0;
2293 }
2294 return 0;
2295 }
2296
2297 int CmdHF14AMfCGetBlk(const char *Cmd) {
2298 uint8_t memBlock[16];
2299 uint8_t blockNo = 0;
2300 int res, gen = 0;
2301 memset(memBlock, 0x00, sizeof(memBlock));
2302
2303 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
2304 PrintAndLog("Usage: hf mf cgetblk <block number>");
2305 PrintAndLog("sample: hf mf cgetblk 1");
2306 PrintAndLog("Get block data from magic Chinese card (only works with such cards)\n");
2307 return 0;
2308 }
2309
2310 gen = mfCIdentify();
2311
2312 blockNo = param_get8(Cmd, 0);
2313
2314 PrintAndLog("--block number:%2d ", blockNo);
2315
2316 if (gen == 2) {
2317 /* generation 1b magic card */
2318 res = mfCGetBlock(blockNo, memBlock, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B);
2319 } else {
2320 /* generation 1a magic card by default */
2321 res = mfCGetBlock(blockNo, memBlock, CSETBLOCK_SINGLE_OPER);
2322 }
2323 if (res) {
2324 PrintAndLog("Can't read block. error=%d", res);
2325 return 1;
2326 }
2327
2328 PrintAndLog("block data:%s", sprint_hex(memBlock, 16));
2329
2330 if (mfIsSectorTrailer(blockNo)) {
2331 PrintAndLogEx(NORMAL, "Trailer decoded:");
2332 PrintAndLogEx(NORMAL, "Key A: %s", sprint_hex_inrow(memBlock, 6));
2333 PrintAndLogEx(NORMAL, "Key B: %s", sprint_hex_inrow(&memBlock[10], 6));
2334 int bln = mfFirstBlockOfSector(mfSectorNum(blockNo));
2335 int blinc = (mfNumBlocksPerSector(mfSectorNum(blockNo)) > 4) ? 5 : 1;
2336 for (int i = 0; i < 4; i++) {
2337 PrintAndLogEx(NORMAL, "Access block %d%s: %s", bln, ((blinc > 1) && (i < 3) ? "+" : "") , mfGetAccessConditionsDesc(i, &memBlock[6]));
2338 bln += blinc;
2339 }
2340 PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&memBlock[9], 1));
2341 }
2342
2343 return 0;
2344 }
2345
2346 int CmdHF14AMfCGetSc(const char *Cmd) {
2347 uint8_t memBlock[16] = {0x00};
2348 uint8_t sectorNo = 0;
2349 int i, res, flags, gen = 0, baseblock = 0, sect_size = 4;
2350
2351 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
2352 PrintAndLog("Usage: hf mf cgetsc <sector number>");
2353 PrintAndLog("sample: hf mf cgetsc 0");
2354 PrintAndLog("Get sector data from magic Chinese card (only works with such cards)\n");
2355 return 0;
2356 }
2357
2358 sectorNo = param_get8(Cmd, 0);
2359
2360 if (sectorNo > 39) {
2361 PrintAndLog("Sector number must be in [0..15] in MIFARE classic 1k and [0..39] in MIFARE classic 4k.");
2362 return 1;
2363 }
2364
2365 PrintAndLog("--sector number:%d ", sectorNo);
2366
2367 gen = mfCIdentify();
2368
2369 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;
2370 if (sectorNo < 32 ) {
2371 baseblock = sectorNo * 4;
2372 } else {
2373 baseblock = 128 + 16 * (sectorNo - 32);
2374
2375 }
2376 if (sectorNo > 31) sect_size = 16;
2377
2378 for (i = 0; i < sect_size; i++) {
2379 if (i == 1) flags = 0;
2380 if (i == sect_size - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;
2381
2382 if (gen == 2)
2383 /* generation 1b magic card */
2384 flags |= CSETBLOCK_MAGIC_1B;
2385
2386 res = mfCGetBlock(baseblock + i, memBlock, flags);
2387 if (res) {
2388 PrintAndLog("Can't read block. %d error=%d", baseblock + i, res);
2389 return 1;
2390 }
2391
2392 PrintAndLog("block %3d data:%s", baseblock + i, sprint_hex(memBlock, 16));
2393
2394 if (mfIsSectorTrailer(baseblock + i)) {
2395 PrintAndLogEx(NORMAL, "Trailer decoded:");
2396 PrintAndLogEx(NORMAL, "Key A: %s", sprint_hex_inrow(memBlock, 6));
2397 PrintAndLogEx(NORMAL, "Key B: %s", sprint_hex_inrow(&memBlock[10], 6));
2398 int bln = baseblock;
2399 int blinc = (mfNumBlocksPerSector(sectorNo) > 4) ? 5 : 1;
2400 for (int i = 0; i < 4; i++) {
2401 PrintAndLogEx(NORMAL, "Access block %d%s: %s", bln, ((blinc > 1) && (i < 3) ? "+" : "") , mfGetAccessConditionsDesc(i, &memBlock[6]));
2402 bln += blinc;
2403 }
2404 PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&memBlock[9], 1));
2405 }
2406 }
2407 return 0;
2408 }
2409
2410
2411 int CmdHF14AMfCSave(const char *Cmd) {
2412
2413 FILE * f;
2414 char filename[FILE_PATH_SIZE] = {0x00};
2415 char * fnameptr = filename;
2416 uint8_t fillFromEmulator = 0;
2417 uint8_t buf[256] = {0x00};
2418 int i, j, len, flags, gen = 0, numblock = 64;
2419
2420 // memset(filename, 0, sizeof(filename));
2421 // memset(buf, 0, sizeof(buf));
2422
2423 if (param_getchar(Cmd, 0) == 'h') {
2424 PrintAndLog("It saves `magic Chinese` card dump into the file `filename.eml` or `cardID.eml`");
2425 PrintAndLog("or into emulator memory (option `e`). 4K card: (option `4`)");
2426 PrintAndLog("Usage: hf mf csave [file name w/o `.eml`][e][4]");
2427 PrintAndLog("Sample: hf mf csave ");
2428 PrintAndLog(" hf mf csave filename");
2429 PrintAndLog(" hf mf csave e");
2430 PrintAndLog(" hf mf csave 4");
2431 PrintAndLog(" hf mf csave filename 4");
2432 PrintAndLog(" hf mf csave e 4");
2433 return 0;
2434 }
2435
2436 char ctmp = param_getchar(Cmd, 0);
2437 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;
2438 if (ctmp == '4') numblock = 256;
2439 ctmp = param_getchar(Cmd, 1);
2440 if (ctmp == '4') numblock = 256;
2441
2442 gen = mfCIdentify();
2443 PrintAndLog("Saving magic mifare %dK", numblock == 256 ? 4:1);
2444
2445 if (fillFromEmulator) {
2446 // put into emulator
2447 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;
2448 for (i = 0; i < numblock; i++) {
2449 if (i == 1) flags = 0;
2450 if (i == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;
2451
2452 if (gen == 2)
2453 /* generation 1b magic card */
2454 flags |= CSETBLOCK_MAGIC_1B;
2455
2456 if (mfCGetBlock(i, buf, flags)) {
2457 PrintAndLog("Cant get block: %d", i);
2458 break;
2459 }
2460
2461 if (mfEmlSetMem(buf, i, 1)) {
2462 PrintAndLog("Cant set emul block: %d", i);
2463 return 3;
2464 }
2465 }
2466 return 0;
2467 } else {
2468 param_getstr(Cmd, 0, filename, sizeof(filename));
2469
2470 len = strlen(filename);
2471 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
2472
2473 ctmp = param_getchar(Cmd, 0);
2474 if (len < 1 || (ctmp == '4')) {
2475 // get filename
2476
2477 flags = CSETBLOCK_SINGLE_OPER;
2478 if (gen == 2)
2479 /* generation 1b magic card */
2480 flags |= CSETBLOCK_MAGIC_1B;
2481 if (mfCGetBlock(0, buf, flags)) {
2482 PrintAndLog("Cant get block: %d", 0);
2483 len = sprintf(fnameptr, "dump");
2484 fnameptr += len;
2485 }
2486 else {
2487 for (j = 0; j < 7; j++, fnameptr += 2)
2488 sprintf(fnameptr, "%02x", buf[j]);
2489 }
2490 } else {
2491 //memcpy(filename, Cmd, len);
2492 fnameptr += len;
2493 }
2494
2495 sprintf(fnameptr, ".eml");
2496
2497 // open file
2498 f = fopen(filename, "w+");
2499
2500 if (f == NULL) {
2501 PrintAndLog("File not found or locked.");
2502 return 1;
2503 }
2504
2505 // put hex
2506 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;
2507 for (i = 0; i < numblock; i++) {
2508 if (i == 1) flags = 0;
2509 if (i == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;
2510
2511 if (gen == 2)
2512 /* generation 1b magic card */
2513 flags |= CSETBLOCK_MAGIC_1B;
2514 if (mfCGetBlock(i, buf, flags)) {
2515 PrintAndLog("Cant get block: %d", i);
2516 break;
2517 }
2518 for (j = 0; j < 16; j++)
2519 fprintf(f, "%02x", buf[j]);
2520 fprintf(f,"\n");
2521 }
2522 fclose(f);
2523
2524 PrintAndLog("Saved to file: %s", filename);
2525
2526 return 0;
2527 }
2528 }
2529
2530
2531 int CmdHF14AMfSniff(const char *Cmd){
2532
2533 bool wantLogToFile = 0;
2534 bool wantDecrypt = 0;
2535 //bool wantSaveToEml = 0; TODO
2536 bool wantSaveToEmlFile = 0;
2537
2538 //var
2539 int res = 0;
2540 int len = 0;
2541 int parlen = 0;
2542 int blockLen = 0;
2543 int pckNum = 0;
2544 int num = 0;
2545 uint8_t uid[7];
2546 uint8_t uid_len;
2547 uint8_t atqa[2] = {0x00};
2548 uint8_t sak;
2549 bool isTag;
2550 uint8_t *buf = NULL;
2551 uint16_t bufsize = 0;
2552 uint8_t *bufPtr = NULL;
2553 uint8_t parity[16];
2554
2555 char ctmp = param_getchar(Cmd, 0);
2556 if ( ctmp == 'h' || ctmp == 'H' ) {
2557 PrintAndLog("It continuously gets data from the field and saves it to: log, emulator, emulator file.");
2558 PrintAndLog("You can specify:");
2559 PrintAndLog(" l - save encrypted sequence to logfile `uid.log`");
2560 PrintAndLog(" d - decrypt sequence and put it to log file `uid.log`");
2561 PrintAndLog(" n/a e - decrypt sequence, collect read and write commands and save the result of the sequence to emulator memory");
2562 PrintAndLog(" f - decrypt sequence, collect read and write commands and save the result of the sequence to emulator dump file `uid.eml`");
2563 PrintAndLog("Usage: hf mf sniff [l][d][e][f]");
2564 PrintAndLog(" sample: hf mf sniff l d e");
2565 return 0;
2566 }
2567
2568 for (int i = 0; i < 4; i++) {
2569 ctmp = param_getchar(Cmd, i);
2570 if (ctmp == 'l' || ctmp == 'L') wantLogToFile = true;
2571 if (ctmp == 'd' || ctmp == 'D') wantDecrypt = true;
2572 //if (ctmp == 'e' || ctmp == 'E') wantSaveToEml = true; TODO
2573 if (ctmp == 'f' || ctmp == 'F') wantSaveToEmlFile = true;
2574 }
2575
2576 printf("-------------------------------------------------------------------------\n");
2577 printf("Executing command. \n");
2578 printf("Press the key on the proxmark3 device to abort both proxmark3 and client.\n");
2579 printf("Press the key on pc keyboard to abort the client.\n");
2580 printf("-------------------------------------------------------------------------\n");
2581
2582 UsbCommand c = {CMD_MIFARE_SNIFFER, {0, 0, 0}};
2583 clearCommandBuffer();
2584 SendCommand(&c);
2585
2586 // wait cycle
2587 while (true) {
2588 printf(".");
2589 fflush(stdout);
2590 if (ukbhit()) {
2591 getchar();
2592 printf("\naborted via keyboard!\n");
2593 break;
2594 }
2595
2596 UsbCommand resp;
2597 if (WaitForResponseTimeoutW(CMD_ACK, &resp, 2000, false)) {
2598 res = resp.arg[0] & 0xff;
2599 uint16_t traceLen = resp.arg[1];
2600 len = resp.arg[2];
2601
2602 if (res == 0) { // we are done
2603 break;
2604 }
2605
2606 if (res == 1) { // there is (more) data to be transferred
2607 if (pckNum == 0) { // first packet, (re)allocate necessary buffer
2608 if (traceLen > bufsize || buf == NULL) {
2609 uint8_t *p;
2610 if (buf == NULL) { // not yet allocated
2611 p = malloc(traceLen);
2612 } else { // need more memory
2613 p = realloc(buf, traceLen);
2614 }
2615 if (p == NULL) {
2616 PrintAndLog("Cannot allocate memory for trace");
2617 free(buf);
2618 return 2;
2619 }
2620 buf = p;
2621 }
2622 bufPtr = buf;
2623 bufsize = traceLen;
2624 memset(buf, 0x00, traceLen);
2625 }
2626 memcpy(bufPtr, resp.d.asBytes, len);
2627 bufPtr += len;
2628 pckNum++;
2629 }
2630
2631 if (res == 2) { // received all data, start displaying
2632 blockLen = bufPtr - buf;
2633 bufPtr = buf;
2634 printf(">\n");
2635 PrintAndLog("received trace len: %d packages: %d", blockLen, pckNum);
2636 while (bufPtr - buf < blockLen) {
2637 bufPtr += 6; // skip (void) timing information
2638 len = *((uint16_t *)bufPtr);
2639 if(len & 0x8000) {
2640 isTag = true;
2641 len &= 0x7fff;
2642 } else {
2643 isTag = false;
2644 }
2645 parlen = (len - 1) / 8 + 1;
2646 bufPtr += 2;
2647 if ((len == 14) && (bufPtr[0] == 0xff) && (bufPtr[1] == 0xff) && (bufPtr[12] == 0xff) && (bufPtr[13] == 0xff)) {
2648 memcpy(uid, bufPtr + 2, 7);
2649 memcpy(atqa, bufPtr + 2 + 7, 2);
2650 uid_len = (atqa[0] & 0xC0) == 0x40 ? 7 : 4;
2651 sak = bufPtr[11];
2652 PrintAndLog("tag select uid:%s atqa:0x%02x%02x sak:0x%02x",
2653 sprint_hex(uid + (7 - uid_len), uid_len),
2654 atqa[1],
2655 atqa[0],
2656 sak);
2657 if (wantLogToFile || wantDecrypt) {
2658 FillFileNameByUID(logHexFileName, uid + (7 - uid_len), ".log", uid_len);
2659 AddLogCurrentDT(logHexFileName);
2660 }
2661 if (wantDecrypt)
2662 mfTraceInit(uid, atqa, sak, wantSaveToEmlFile);
2663 } else {
2664 oddparitybuf(bufPtr, len, parity);
2665 PrintAndLog("%s(%d):%s [%s] c[%s]%c",
2666 isTag ? "TAG":"RDR",
2667 num,
2668 sprint_hex(bufPtr, len),
2669 printBitsPar(bufPtr + len, len),
2670 printBitsPar(parity, len),
2671 memcmp(bufPtr + len, parity, len / 8 + 1) ? '!' : ' ');
2672 if (wantLogToFile)
2673 AddLogHex(logHexFileName, isTag ? "TAG: ":"RDR: ", bufPtr, len);
2674 if (wantDecrypt)
2675 mfTraceDecode(bufPtr, len, bufPtr[len], wantSaveToEmlFile);
2676 num++;
2677 }
2678 bufPtr += len;
2679 bufPtr += parlen; // ignore parity
2680 }
2681 pckNum = 0;
2682 }
2683 } // resp not NULL
2684 } // while (true)
2685
2686 free(buf);
2687
2688 msleep(300); // wait for exiting arm side.
2689 PrintAndLog("Done.");
2690 return 0;
2691 }
2692
2693 //needs nt, ar, at, Data to decrypt
2694 int CmdDecryptTraceCmds(const char *Cmd){
2695 uint8_t data[50];
2696 int len = 0;
2697 param_gethex_ex(Cmd,3,data,&len);
2698 return tryDecryptWord(param_get32ex(Cmd,0,0,16),param_get32ex(Cmd,1,0,16),param_get32ex(Cmd,2,0,16),data,len/2);
2699 }
2700
2701 int CmdHF14AMfAuth4(const char *cmd) {
2702 uint8_t keyn[20] = {0};
2703 int keynlen = 0;
2704 uint8_t key[16] = {0};
2705 int keylen = 0;
2706
2707 CLIParserInit("hf mf auth4",
2708 "Executes AES authentication command in ISO14443-4",
2709 "Usage:\n\thf mf auth4 4000 000102030405060708090a0b0c0d0e0f -> executes authentication\n"
2710 "\thf mf auth4 9003 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -> executes authentication\n");
2711
2712 void* argtable[] = {
2713 arg_param_begin,
2714 arg_str1(NULL, NULL, "<Key Num (HEX 2 bytes)>", NULL),
2715 arg_str1(NULL, NULL, "<Key Value (HEX 16 bytes)>", NULL),
2716 arg_param_end
2717 };
2718 CLIExecWithReturn(cmd, argtable, true);
2719
2720 CLIGetHexWithReturn(1, keyn, &keynlen);
2721 CLIGetHexWithReturn(2, key, &keylen);
2722 CLIParserFree();
2723
2724 if (keynlen != 2) {
2725 PrintAndLog("ERROR: <Key Num> must be 2 bytes long instead of: %d", keynlen);
2726 return 1;
2727 }
2728
2729 if (keylen != 16) {
2730 PrintAndLog("ERROR: <Key Value> must be 16 bytes long instead of: %d", keylen);
2731 return 1;
2732 }
2733
2734 return MifareAuth4(NULL, keyn, key, true, false, true);
2735 }
2736
2737 // https://www.nxp.com/docs/en/application-note/AN10787.pdf
2738 int CmdHF14AMfMAD(const char *cmd) {
2739
2740 CLIParserInit("hf mf mad",
2741 "Checks and prints Mifare Application Directory (MAD)",
2742 "Usage:\n\thf mf mad -> shows MAD if exists\n"
2743 "\thf mf mad -a 03e1 -k ffffffffffff -b -> shows NDEF data if exists. read card with custom key and key B\n");
2744
2745 void *argtable[] = {
2746 arg_param_begin,
2747 arg_lit0("vV", "verbose", "show technical data"),
2748 arg_str0("aA", "aid", "print all sectors with aid", NULL),
2749 arg_str0("kK", "key", "key for printing sectors", NULL),
2750 arg_lit0("bB", "keyb", "use key B for access printing sectors (by default: key A)"),
2751 arg_param_end
2752 };
2753 CLIExecWithReturn(cmd, argtable, true);
2754 bool verbose = arg_get_lit(1);
2755 uint8_t aid[2] = {0};
2756 int aidlen;
2757 CLIGetHexWithReturn(2, aid, &aidlen);
2758 uint8_t key[6] = {0};
2759 int keylen;
2760 CLIGetHexWithReturn(3, key, &keylen);
2761 bool keyB = arg_get_lit(4);
2762
2763 CLIParserFree();
2764
2765 if (aidlen != 2 && keylen > 0) {
2766 PrintAndLogEx(WARNING, "do not need a key without aid.");
2767 }
2768
2769 uint8_t sector0[16 * 4] = {0};
2770 uint8_t sector10[16 * 4] = {0};
2771 if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0)) {
2772 PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");
2773 return 2;
2774 }
2775
2776 if (verbose) {
2777 for (int i = 0; i < 4; i ++)
2778 PrintAndLogEx(NORMAL, "[%d] %s", i, sprint_hex(&sector0[i * 16], 16));
2779 }
2780
2781 bool haveMAD2 = false;
2782 MAD1DecodeAndPrint(sector0, verbose, &haveMAD2);
2783
2784 if (haveMAD2) {
2785 if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10)) {
2786 PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");
2787 return 2;
2788 }
2789
2790 MAD2DecodeAndPrint(sector10, verbose);
2791 }
2792
2793 if (aidlen == 2) {
2794 uint16_t aaid = (aid[0] << 8) + aid[1];
2795 PrintAndLogEx(NORMAL, "\n-------------- AID 0x%04x ---------------", aaid);
2796
2797 uint16_t mad[7 + 8 + 8 + 8 + 8] = {0};
2798 size_t madlen = 0;
2799 if (MADDecode(sector0, sector10, mad, &madlen)) {
2800 PrintAndLogEx(ERR, "can't decode mad.");
2801 return 10;
2802 }
2803
2804 uint8_t akey[6] = {0};
2805 memcpy(akey, g_mifare_ndef_key, 6);
2806 if (keylen == 6) {
2807 memcpy(akey, key, 6);
2808 }
2809
2810 for (int i = 0; i < madlen; i++) {
2811 if (aaid == mad[i]) {
2812 uint8_t vsector[16 * 4] = {0};
2813 if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) {
2814 PrintAndLogEx(NORMAL, "");
2815 PrintAndLogEx(ERR, "read sector %d error.", i + 1);
2816 return 2;
2817 }
2818
2819 for (int j = 0; j < (verbose ? 4 : 3); j ++)
2820 PrintAndLogEx(NORMAL, " [%03d] %s", (i + 1) * 4 + j, sprint_hex(&vsector[j * 16], 16));
2821 }
2822 }
2823 }
2824
2825 return 0;
2826 }
2827
2828 int CmdHFMFNDEF(const char *cmd) {
2829
2830 CLIParserInit("hf mf ndef",
2831 "Prints NFC Data Exchange Format (NDEF)",
2832 "Usage:\n\thf mf ndef -> shows NDEF data\n"
2833 "\thf mf ndef -a 03e1 -k ffffffffffff -b -> shows NDEF data with custom AID, key and with key B\n");
2834
2835 void *argtable[] = {
2836 arg_param_begin,
2837 arg_litn("vV", "verbose", 0, 2, "show technical data"),
2838 arg_str0("aA", "aid", "replace default aid for NDEF", NULL),
2839 arg_str0("kK", "key", "replace default key for NDEF", NULL),
2840 arg_lit0("bB", "keyb", "use key B for access sectors (by default: key A)"),
2841 arg_param_end
2842 };
2843 CLIExecWithReturn(cmd, argtable, true);
2844
2845 bool verbose = arg_get_lit(1);
2846 bool verbose2 = arg_get_lit(1) > 1;
2847 uint8_t aid[2] = {0};
2848 int aidlen;
2849 CLIGetHexWithReturn(2, aid, &aidlen);
2850 uint8_t key[6] = {0};
2851 int keylen;
2852 CLIGetHexWithReturn(3, key, &keylen);
2853 bool keyB = arg_get_lit(4);
2854
2855 CLIParserFree();
2856
2857 uint16_t ndefAID = 0x03e1;
2858 if (aidlen == 2)
2859 ndefAID = (aid[0] << 8) + aid[1];
2860
2861 uint8_t ndefkey[6] = {0};
2862 memcpy(ndefkey, g_mifare_ndef_key, 6);
2863 if (keylen == 6) {
2864 memcpy(ndefkey, key, 6);
2865 }
2866
2867 uint8_t sector0[16 * 4] = {0};
2868 uint8_t sector10[16 * 4] = {0};
2869 uint8_t data[4096] = {0};
2870 int datalen = 0;
2871
2872 PrintAndLogEx(NORMAL, "");
2873
2874 if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0)) {
2875 PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");
2876 return 2;
2877 }
2878
2879 bool haveMAD2 = false;
2880 int res = MADCheck(sector0, NULL, verbose, &haveMAD2);
2881 if (res) {
2882 PrintAndLogEx(ERR, "MAD error %d.", res);
2883 return res;
2884 }
2885
2886 if (haveMAD2) {
2887 if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10)) {
2888 PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");
2889 return 2;
2890 }
2891 }
2892
2893 uint16_t mad[7 + 8 + 8 + 8 + 8] = {0};
2894 size_t madlen = 0;
2895 if (MADDecode(sector0, (haveMAD2 ? sector10 : NULL), mad, &madlen)) {
2896 PrintAndLogEx(ERR, "can't decode mad.");
2897 return 10;
2898 }
2899
2900 printf("data reading:");
2901 for (int i = 0; i < madlen; i++) {
2902 if (ndefAID == mad[i]) {
2903 uint8_t vsector[16 * 4] = {0};
2904 if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector)) {
2905 PrintAndLogEx(ERR, "read sector %d error.", i + 1);
2906 return 2;
2907 }
2908
2909 memcpy(&data[datalen], vsector, 16 * 3);
2910 datalen += 16 * 3;
2911
2912 printf(".");
2913 }
2914 }
2915 printf(" OK\n");
2916
2917 if (!datalen) {
2918 PrintAndLogEx(ERR, "no NDEF data.");
2919 return 11;
2920 }
2921
2922 if (verbose2) {
2923 PrintAndLogEx(NORMAL, "NDEF data:");
2924 dump_buffer(data, datalen, stdout, 1);
2925 }
2926
2927 NDEFDecodeAndPrint(data, datalen, verbose);
2928
2929 return 0;
2930 }
2931
2932 static command_t CommandTable[] =
2933 {
2934 {"help", CmdHelp, 1, "This help"},
2935 {"dbg", CmdHF14AMfDbg, 0, "Set default debug mode"},
2936 {"rdbl", CmdHF14AMfRdBl, 0, "Read MIFARE classic block"},
2937 {"rdsc", CmdHF14AMfRdSc, 0, "Read MIFARE classic sector"},
2938 {"dump", CmdHF14AMfDump, 0, "Dump MIFARE classic tag to binary file"},
2939 {"restore", CmdHF14AMfRestore, 0, "Restore MIFARE classic binary file to BLANK tag"},
2940 {"wrbl", CmdHF14AMfWrBl, 0, "Write MIFARE classic block"},
2941 {"auth4", CmdHF14AMfAuth4, 0, "ISO14443-4 AES authentication"},
2942 {"chk", CmdHF14AMfChk, 0, "Test block keys"},
2943 {"mifare", CmdHF14AMifare, 0, "Read parity error messages."},
2944 {"hardnested", CmdHF14AMfNestedHard, 0, "Nested attack for hardened Mifare cards"},
2945 {"nested", CmdHF14AMfNested, 0, "Test nested authentication"},
2946 {"sniff", CmdHF14AMfSniff, 0, "Sniff card-reader communication"},
2947 {"sim", CmdHF14AMfSim, 0, "Simulate MIFARE card"},
2948 {"eclr", CmdHF14AMfEClear, 0, "Clear simulator memory"},
2949 {"eget", CmdHF14AMfEGet, 0, "Get simulator memory block"},
2950 {"eset", CmdHF14AMfESet, 0, "Set simulator memory block"},
2951 {"eload", CmdHF14AMfELoad, 0, "Load from file emul dump"},
2952 {"esave", CmdHF14AMfESave, 0, "Save to file emul dump"},
2953 {"ecfill", CmdHF14AMfECFill, 0, "Fill simulator memory with help of keys from simulator"},
2954 {"ekeyprn", CmdHF14AMfEKeyPrn, 0, "Print keys from simulator memory"},
2955 {"cwipe", CmdHF14AMfCWipe, 0, "Wipe magic Chinese card"},
2956 {"csetuid", CmdHF14AMfCSetUID, 0, "Set UID for magic Chinese card"},
2957 {"csetblk", CmdHF14AMfCSetBlk, 0, "Write block - Magic Chinese card"},
2958 {"cgetblk", CmdHF14AMfCGetBlk, 0, "Read block - Magic Chinese card"},
2959 {"cgetsc", CmdHF14AMfCGetSc, 0, "Read sector - Magic Chinese card"},
2960 {"cload", CmdHF14AMfCLoad, 0, "Load dump into magic Chinese card"},
2961 {"csave", CmdHF14AMfCSave, 0, "Save dump from magic Chinese card into file or emulator"},
2962 {"decrypt", CmdDecryptTraceCmds, 1, "[nt] [ar_enc] [at_enc] [data] - to decrypt snoop or trace"},
2963 {"mad", CmdHF14AMfMAD, 0, "Checks and prints MAD"},
2964 {"ndef", CmdHFMFNDEF, 0, "Prints NDEF records from card"},
2965 {NULL, NULL, 0, NULL}
2966 };
2967
2968 int CmdHFMF(const char *Cmd)
2969 {
2970 (void)WaitForResponseTimeout(CMD_ACK,NULL,100);
2971 CmdsParse(CommandTable, Cmd);
2972 return 0;
2973 }
2974
2975 int CmdHelp(const char *Cmd)
2976 {
2977 CmdsHelp(CommandTable);
2978 return 0;
2979 }
Impressum, Datenschutz