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