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