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