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