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