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