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