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