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