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