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