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