]> cvs.zerfleddert.de Git - proxmark3-svn/blob - client/cmdhfmf.c
1c866dc9318d6001e37b2d90f570b3a3cc671c47
[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 // empty e_sector
1172 for(int i = 0; i < SectorsCnt; ++i){
1173 e_sector[i].Key[0] = 0xffffffffffff;
1174 e_sector[i].Key[1] = 0xffffffffffff;
1175 e_sector[i].foundKey[0] = FALSE;
1176 e_sector[i].foundKey[1] = FALSE;
1177 }
1178
1179
1180 uint8_t trgKeyType = 0;
1181 uint32_t max_keys = keycnt > (USB_CMD_DATA_SIZE/6) ? (USB_CMD_DATA_SIZE/6) : keycnt;
1182
1183 // time
1184 clock_t t1 = clock();
1185
1186 // check keys.
1187 for (trgKeyType = !keyType; trgKeyType < 2; (keyType==2) ? (++trgKeyType) : (trgKeyType=2) ) {
1188
1189 int b = blockNo;
1190 for (int i = 0; i < SectorsCnt; ++i) {
1191
1192 // skip already found keys.
1193 if (e_sector[i].foundKey[trgKeyType]) continue;
1194
1195 for (uint32_t c = 0; c < keycnt; c += max_keys) {
1196
1197 uint32_t size = keycnt-c > max_keys ? max_keys : keycnt-c;
1198
1199 res = mfCheckKeys(b, trgKeyType, true, size, &keyBlock[6*c], &key64);
1200 if (!res) {
1201 e_sector[i].Key[trgKeyType] = key64;
1202 e_sector[i].foundKey[trgKeyType] = TRUE;
1203 break;
1204 }
1205 printf(".");
1206 fflush(stdout);
1207 }
1208 b < 127 ? ( b +=4 ) : ( b += 16 );
1209 }
1210 }
1211 t1 = clock() - t1;
1212 if ( t1 > 0 )
1213 printf("\nTime in checkkeys: %.0f ticks\n", (float)t1);
1214
1215 // 20160116 If Sector A is found, but not Sector B, try just reading it of the tag?
1216 if ( keyType != 1 ) {
1217
1218 PrintAndLog("testing to read key B...");
1219 for (i = 0; i < SectorsCnt; i++) {
1220 // KEY A but not KEY B
1221 if ( e_sector[i].foundKey[0] && !e_sector[i].foundKey[1] ) {
1222
1223 uint8_t sectrail = (FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1);
1224
1225 PrintAndLog("Reading block %d", sectrail);
1226
1227 UsbCommand c = {CMD_MIFARE_READBL, {sectrail, 0, 0}};
1228 num_to_bytes(e_sector[i].Key[0], 6, c.d.asBytes); // KEY A
1229 clearCommandBuffer();
1230 SendCommand(&c);
1231
1232 UsbCommand resp;
1233 if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500)) continue;
1234
1235 uint8_t isOK = resp.arg[0] & 0xff;
1236 if (!isOK) continue;
1237
1238 uint8_t *data = resp.d.asBytes;
1239 key64 = bytes_to_num(data+10, 6);
1240 if (key64) {
1241 PrintAndLog("Data:%s", sprint_hex(data+10, 6));
1242 e_sector[i].foundKey[1] = 1;
1243 e_sector[i].Key[1] = key64;
1244 }
1245 }
1246 }
1247 }
1248
1249
1250 //print them
1251 printKeyTable( SectorsCnt, e_sector );
1252
1253 if (transferToEml) {
1254 uint8_t block[16] = {0x00};
1255 for (uint8_t i = 0; i < SectorsCnt; ++i ) {
1256 mfEmlGetMem(block, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);
1257 if (e_sector[i].foundKey[0])
1258 num_to_bytes(e_sector[i].Key[0], 6, block);
1259 if (e_sector[i].foundKey[1])
1260 num_to_bytes(e_sector[i].Key[1], 6, block+10);
1261 mfEmlSetMem(block, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);
1262 }
1263 PrintAndLog("Found keys have been transferred to the emulator memory");
1264 }
1265
1266 if (createDumpFile) {
1267 FILE *fkeys = fopen("dumpkeys.bin","wb");
1268 if (fkeys == NULL) {
1269 PrintAndLog("Could not create file dumpkeys.bin");
1270 free(keyBlock);
1271 free(e_sector);
1272 return 1;
1273 }
1274 PrintAndLog("Printing keys to binary file dumpkeys.bin...");
1275
1276 for( i=0; i<SectorsCnt; i++) {
1277 num_to_bytes(e_sector[i].Key[0], 6, tempkey);
1278 fwrite ( tempkey, 1, 6, fkeys );
1279 }
1280 for(i=0; i<SectorsCnt; i++) {
1281 num_to_bytes(e_sector[i].Key[1], 6, tempkey);
1282 fwrite ( tempkey, 1, 6, fkeys );
1283 }
1284 fclose(fkeys);
1285 PrintAndLog("Found keys have been dumped to file dumpkeys.bin. 0xffffffffffff has been inserted for unknown keys.");
1286 }
1287
1288 free(keyBlock);
1289 free(e_sector);
1290 PrintAndLog("");
1291 return 0;
1292 }
1293
1294 int CmdHF14AMf1kSim(const char *Cmd) {
1295 uint8_t uid[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1296 uint8_t exitAfterNReads = 0;
1297 uint8_t flags = (FLAG_UID_IN_EMUL | FLAG_4B_UID_IN_DATA);
1298 int uidlen = 0;
1299 uint8_t pnr = 0;
1300 uint8_t cmdp = param_getchar(Cmd, 0);
1301
1302 if (cmdp == 'h' || cmdp == 'H') return usage_hf14_mf1ksim();
1303
1304 cmdp = param_getchar(Cmd, pnr);
1305 if (cmdp == 'u' || cmdp == 'U') {
1306 param_gethex_ex(Cmd, pnr+1, uid, &uidlen);
1307 switch(uidlen){
1308 case 20: flags = FLAG_10B_UID_IN_DATA; break;
1309 case 14: flags = FLAG_7B_UID_IN_DATA; break;
1310 case 8: flags = FLAG_4B_UID_IN_DATA; break;
1311 default: return usage_hf14_mf1ksim();
1312 }
1313 pnr +=2;
1314 }
1315
1316 cmdp = param_getchar(Cmd, pnr);
1317 if (cmdp == 'n' || cmdp == 'N') {
1318 exitAfterNReads = param_get8(Cmd, pnr+1);
1319 pnr += 2;
1320 }
1321
1322 cmdp = param_getchar(Cmd, pnr);
1323 if (cmdp == 'i' || cmdp == 'I' ) {
1324 flags |= FLAG_INTERACTIVE;
1325 pnr++;
1326 }
1327
1328 cmdp = param_getchar(Cmd, pnr);
1329 if (cmdp == 'x' || cmdp == 'X') {
1330 flags |= FLAG_NR_AR_ATTACK;
1331 }
1332
1333 PrintAndLog(" uid:%s, numreads:%d, flags:%d (0x%02x) "
1334 , (uidlen == 0 ) ? "N/A" : sprint_hex(uid, uidlen>>1)
1335 , exitAfterNReads
1336 , flags
1337 , flags);
1338
1339 UsbCommand c = {CMD_SIMULATE_MIFARE_CARD, {flags, exitAfterNReads, 0}};
1340 memcpy(c.d.asBytes, uid, sizeof(uid));
1341 clearCommandBuffer();
1342 SendCommand(&c);
1343
1344 if(flags & FLAG_INTERACTIVE) {
1345 uint8_t data[32];
1346 uint64_t key;
1347 UsbCommand resp;
1348 PrintAndLog("Press pm3-button or send another cmd to abort simulation");
1349 while( !ukbhit() ){
1350 if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) continue;
1351
1352 if ( !(flags & FLAG_NR_AR_ATTACK) ) break;
1353 if ( (resp.arg[0] & 0xffff) != CMD_SIMULATE_MIFARE_CARD ) break;
1354
1355 memset(data, 0x00, sizeof(data));
1356 int len = (resp.arg[1] > sizeof(data)) ? sizeof(data) : resp.arg[1];
1357
1358 memcpy(data, resp.d.asBytes, len);
1359 key = 0;
1360 bool found = tryMfk32(data, &key);
1361 found ^= tryMfk32_moebius(data, &key);
1362 if ( found ) break;
1363 }
1364 }
1365 return 0;
1366 }
1367
1368 int CmdHF14AMfSniff(const char *Cmd){
1369 bool wantLogToFile = FALSE;
1370 bool wantDecrypt = FALSE;
1371 //bool wantSaveToEml = FALSE; TODO
1372 bool wantSaveToEmlFile = FALSE;
1373
1374 //var
1375 int tmpchar;
1376 int res = 0;
1377 int len = 0;
1378 int blockLen = 0;
1379 int pckNum = 0;
1380 int num = 0;
1381 uint8_t uid[10];
1382 uint8_t uid_len = 0;
1383 uint8_t atqa[2] = {0x00, 0x00};
1384 uint8_t sak = 0;
1385 bool isTag = FALSE;
1386 uint8_t *buf = NULL;
1387 uint16_t bufsize = 0;
1388 uint8_t *bufPtr = NULL;
1389 uint16_t traceLen = 0;
1390
1391 memset(uid, 0x00, sizeof(uid));
1392
1393 char ctmp = param_getchar(Cmd, 0);
1394 if ( ctmp == 'h' || ctmp == 'H' ) return usage_hf14_sniff();
1395
1396 for (int i = 0; i < 4; i++) {
1397 ctmp = param_getchar(Cmd, i);
1398 if (ctmp == 'l' || ctmp == 'L') wantLogToFile = true;
1399 if (ctmp == 'd' || ctmp == 'D') wantDecrypt = true;
1400 //if (ctmp == 'e' || ctmp == 'E') wantSaveToEml = true; TODO
1401 if (ctmp == 'f' || ctmp == 'F') wantSaveToEmlFile = true;
1402 }
1403
1404 printf("-------------------------------------------------------------------------\n");
1405 printf("Executing mifare sniffing command. \n");
1406 printf("Press the key on the proxmark3 device to abort both proxmark3 and client.\n");
1407 printf("Press the key on pc keyboard to abort the client.\n");
1408 printf("-------------------------------------------------------------------------\n");
1409
1410 UsbCommand c = {CMD_MIFARE_SNIFFER, {0, 0, 0}};
1411 clearCommandBuffer();
1412 SendCommand(&c);
1413
1414 // wait cycle
1415 while (true) {
1416 printf(".");
1417 fflush(stdout);
1418 if (ukbhit()) {
1419 tmpchar = getchar();
1420 (void)tmpchar;
1421 printf("\naborted via keyboard!\n");
1422 break;
1423 }
1424
1425 UsbCommand resp;
1426 if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {
1427 res = resp.arg[0] & 0xff;
1428 traceLen = resp.arg[1];
1429 len = resp.arg[2];
1430
1431 // we are done?
1432 if (res == 0) {
1433 free(buf);
1434 return 0;
1435 }
1436
1437 if (res == 1) { // there is (more) data to be transferred
1438 if (pckNum == 0) { // first packet, (re)allocate necessary buffer
1439 if (traceLen > bufsize) {
1440 uint8_t *p;
1441 if (buf == NULL) // not yet allocated
1442 p = malloc(traceLen);
1443 else // need more memory
1444 p = realloc(buf, traceLen);
1445
1446 if (p == NULL) {
1447 PrintAndLog("Cannot allocate memory for trace");
1448 free(buf);
1449 return 2;
1450 }
1451 buf = p;
1452 }
1453 bufPtr = buf;
1454 bufsize = traceLen;
1455 memset(buf, 0x00, traceLen);
1456 }
1457 if (bufPtr == NULL) {
1458 PrintAndLog("Cannot allocate memory for trace");
1459 free(buf);
1460 return 2;
1461 }
1462 // what happens if LEN is bigger then TRACELEN --iceman
1463 memcpy(bufPtr, resp.d.asBytes, len);
1464 bufPtr += len;
1465 pckNum++;
1466 }
1467
1468 if (res == 2) { // received all data, start displaying
1469 blockLen = bufPtr - buf;
1470 bufPtr = buf;
1471 printf(">\n");
1472 PrintAndLog("received trace len: %d packages: %d", blockLen, pckNum);
1473 while (bufPtr - buf < blockLen) {
1474 bufPtr += 6; // skip (void) timing information
1475 len = *((uint16_t *)bufPtr);
1476 if(len & 0x8000) {
1477 isTag = true;
1478 len &= 0x7fff;
1479 } else {
1480 isTag = false;
1481 }
1482 bufPtr += 2;
1483 if ((len == 17) && (bufPtr[0] == 0xff) && (bufPtr[1] == 0xff) && (bufPtr[15] == 0xff) && (bufPtr[16] == 0xff)) {
1484 memcpy(uid, bufPtr + 2, 10);
1485 memcpy(atqa, bufPtr + 2 + 10, 2);
1486 switch (atqa[0] & 0xC0) {
1487 case 0x80: uid_len = 10; break;
1488 case 0x40: uid_len = 7; break;
1489 default: uid_len = 4; break;
1490 }
1491 sak = bufPtr[14];
1492 PrintAndLog("tag select uid| %s atqa:0x%02x%02x sak:0x%02x",
1493 sprint_hex(uid, uid_len),
1494 atqa[1],
1495 atqa[0],
1496 sak);
1497 if (wantLogToFile || wantDecrypt) {
1498 FillFileNameByUID(logHexFileName, uid, ".log", uid_len);
1499 AddLogCurrentDT(logHexFileName);
1500 }
1501 if (wantDecrypt)
1502 mfTraceInit(uid, uid_len, atqa, sak, wantSaveToEmlFile);
1503 } else {
1504 PrintAndLog("%03d| %s |%s", num, isTag ? "TAG" : "RDR", sprint_hex(bufPtr, len));
1505 if (wantLogToFile)
1506 AddLogHex(logHexFileName, isTag ? "TAG| ":"RDR| ", bufPtr, len);
1507 if (wantDecrypt)
1508 mfTraceDecode(bufPtr, len, wantSaveToEmlFile);
1509 num++;
1510 }
1511 bufPtr += len;
1512 bufPtr += ((len-1)/8+1); // ignore parity
1513 }
1514 pckNum = 0;
1515 }
1516 } // resp not NULL
1517 } // while (true)
1518
1519 free(buf);
1520 return 0;
1521 }
1522
1523 int CmdHF14AMfDbg(const char *Cmd) {
1524
1525 char ctmp = param_getchar(Cmd, 0);
1526 if (strlen(Cmd) < 1 || ctmp == 'h'|| ctmp == 'H') return usage_hf14_dbg();
1527
1528 uint8_t dbgMode = param_get8ex(Cmd, 0, 0, 10);
1529 if (dbgMode > 4) return usage_hf14_dbg();
1530
1531 UsbCommand c = {CMD_MIFARE_SET_DBGMODE, {dbgMode, 0, 0}};
1532 SendCommand(&c);
1533 return 0;
1534 }
1535
1536 void printKeyTable( uint8_t sectorscnt, sector *e_sector ){
1537 PrintAndLog("|---|----------------|---|----------------|---|");
1538 PrintAndLog("|sec|key A |res|key B |res|");
1539 PrintAndLog("|---|----------------|---|----------------|---|");
1540 for (uint8_t i = 0; i < sectorscnt; ++i) {
1541 PrintAndLog("|%03d| %012"llx" | %d | %012"llx" | %d |", i,
1542 e_sector[i].Key[0], e_sector[i].foundKey[0],
1543 e_sector[i].Key[1], e_sector[i].foundKey[1]
1544 );
1545 }
1546 PrintAndLog("|---|----------------|---|----------------|---|");
1547 }
1548
1549 // EMULATOR COMMANDS
1550
1551 int CmdHF14AMfEGet(const char *Cmd)
1552 {
1553 uint8_t blockNo = 0;
1554 uint8_t data[16] = {0x00};
1555
1556 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
1557 PrintAndLog("Usage: hf mf eget <block number>");
1558 PrintAndLog(" sample: hf mf eget 0 ");
1559 return 0;
1560 }
1561
1562 blockNo = param_get8(Cmd, 0);
1563
1564 PrintAndLog(" ");
1565 if (!mfEmlGetMem(data, blockNo, 1)) {
1566 PrintAndLog("data[%3d]:%s", blockNo, sprint_hex(data, 16));
1567 } else {
1568 PrintAndLog("Command execute timeout");
1569 }
1570
1571 return 0;
1572 }
1573
1574 int CmdHF14AMfEClear(const char *Cmd)
1575 {
1576 if (param_getchar(Cmd, 0) == 'h') {
1577 PrintAndLog("Usage: hf mf eclr");
1578 PrintAndLog("It set card emulator memory to empty data blocks and key A/B FFFFFFFFFFFF \n");
1579 return 0;
1580 }
1581
1582 UsbCommand c = {CMD_MIFARE_EML_MEMCLR, {0, 0, 0}};
1583 SendCommand(&c);
1584 return 0;
1585 }
1586
1587 int CmdHF14AMfESet(const char *Cmd)
1588 {
1589 uint8_t memBlock[16];
1590 uint8_t blockNo = 0;
1591
1592 memset(memBlock, 0x00, sizeof(memBlock));
1593
1594 if (strlen(Cmd) < 3 || param_getchar(Cmd, 0) == 'h') {
1595 PrintAndLog("Usage: hf mf eset <block number> <block data (32 hex symbols)>");
1596 PrintAndLog(" sample: hf mf eset 1 000102030405060708090a0b0c0d0e0f ");
1597 return 0;
1598 }
1599
1600 blockNo = param_get8(Cmd, 0);
1601
1602 if (param_gethex(Cmd, 1, memBlock, 32)) {
1603 PrintAndLog("block data must include 32 HEX symbols");
1604 return 1;
1605 }
1606
1607 // 1 - blocks count
1608 UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNo, 1, 0}};
1609 memcpy(c.d.asBytes, memBlock, 16);
1610 SendCommand(&c);
1611 return 0;
1612 }
1613
1614 int CmdHF14AMfELoad(const char *Cmd)
1615 {
1616 FILE * f;
1617 char filename[FILE_PATH_SIZE];
1618 char *fnameptr = filename;
1619 char buf[64] = {0x00};
1620 uint8_t buf8[64] = {0x00};
1621 int i, len, blockNum, numBlocks;
1622 int nameParamNo = 1;
1623 uint8_t blockWidth = 32;
1624 char ctmp = param_getchar(Cmd, 0);
1625
1626 if ( ctmp == 'h' || ctmp == 'H' || ctmp == 0x00) {
1627 PrintAndLog("It loads emul dump from the file `filename.eml`");
1628 PrintAndLog("Usage: hf mf eload [card memory] <file name w/o `.eml`> [numblocks]");
1629 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K, u = UL");
1630 PrintAndLog("");
1631 PrintAndLog(" sample: hf mf eload filename");
1632 PrintAndLog(" hf mf eload 4 filename");
1633 return 0;
1634 }
1635
1636 switch (ctmp) {
1637 case '0' : numBlocks = 5*4; break;
1638 case '1' :
1639 case '\0': numBlocks = 16*4; break;
1640 case '2' : numBlocks = 32*4; break;
1641 case '4' : numBlocks = 256; break;
1642 case 'U' : // fall through
1643 case 'u' : numBlocks = 255; blockWidth = 8; break;
1644 default: {
1645 numBlocks = 16*4;
1646 nameParamNo = 0;
1647 }
1648 }
1649 uint32_t numblk2 = param_get32ex(Cmd,2,0,10);
1650 if (numblk2 > 0) numBlocks = numblk2;
1651
1652 len = param_getstr(Cmd,nameParamNo,filename);
1653
1654 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
1655
1656 fnameptr += len;
1657
1658 sprintf(fnameptr, ".eml");
1659
1660 // open file
1661 f = fopen(filename, "r");
1662 if (f == NULL) {
1663 PrintAndLog("File %s not found or locked", filename);
1664 return 1;
1665 }
1666
1667 blockNum = 0;
1668 while(!feof(f)){
1669 memset(buf, 0, sizeof(buf));
1670
1671 if (fgets(buf, sizeof(buf), f) == NULL) {
1672
1673 if (blockNum >= numBlocks) break;
1674
1675 PrintAndLog("File reading error.");
1676 fclose(f);
1677 return 2;
1678 }
1679
1680 if (strlen(buf) < blockWidth){
1681 if(strlen(buf) && feof(f))
1682 break;
1683 PrintAndLog("File content error. Block data must include %d HEX symbols", blockWidth);
1684 fclose(f);
1685 return 2;
1686 }
1687
1688 for (i = 0; i < blockWidth; i += 2) {
1689 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
1690 }
1691 if (mfEmlSetMem_xt(buf8, blockNum, 1, blockWidth/2)) {
1692 PrintAndLog("Cant set emul block: %3d", blockNum);
1693 fclose(f);
1694 return 3;
1695 }
1696 printf(".");
1697 blockNum++;
1698
1699 if (blockNum >= numBlocks) break;
1700 }
1701 fclose(f);
1702 printf("\n");
1703
1704 if ((blockNum != numBlocks)) {
1705 PrintAndLog("File content error. Got %d must be %d blocks.",blockNum, numBlocks);
1706 return 4;
1707 }
1708 PrintAndLog("Loaded %d blocks from file: %s", blockNum, filename);
1709 return 0;
1710 }
1711
1712 int CmdHF14AMfESave(const char *Cmd)
1713 {
1714 FILE * f;
1715 char filename[FILE_PATH_SIZE];
1716 char * fnameptr = filename;
1717 uint8_t buf[64];
1718 int i, j, len, numBlocks;
1719 int nameParamNo = 1;
1720
1721 memset(filename, 0, sizeof(filename));
1722 memset(buf, 0, sizeof(buf));
1723
1724 char ctmp = param_getchar(Cmd, 0);
1725
1726 if ( ctmp == 'h' || ctmp == 'H') {
1727 PrintAndLog("It saves emul dump into the file `filename.eml` or `cardID.eml`");
1728 PrintAndLog(" Usage: hf mf esave [card memory] [file name w/o `.eml`]");
1729 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1730 PrintAndLog("");
1731 PrintAndLog(" sample: hf mf esave ");
1732 PrintAndLog(" hf mf esave 4");
1733 PrintAndLog(" hf mf esave 4 filename");
1734 return 0;
1735 }
1736
1737 switch (ctmp) {
1738 case '0' : numBlocks = 5*4; break;
1739 case '1' :
1740 case '\0': numBlocks = 16*4; break;
1741 case '2' : numBlocks = 32*4; break;
1742 case '4' : numBlocks = 256; break;
1743 default: {
1744 numBlocks = 16*4;
1745 nameParamNo = 0;
1746 }
1747 }
1748
1749 len = param_getstr(Cmd,nameParamNo,filename);
1750
1751 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
1752
1753 // user supplied filename?
1754 if (len < 1) {
1755 // get filename (UID from memory)
1756 if (mfEmlGetMem(buf, 0, 1)) {
1757 PrintAndLog("Can\'t get UID from block: %d", 0);
1758 len = sprintf(fnameptr, "dump");
1759 fnameptr += len;
1760 }
1761 else {
1762 for (j = 0; j < 7; j++, fnameptr += 2)
1763 sprintf(fnameptr, "%02X", buf[j]);
1764 }
1765 } else {
1766 fnameptr += len;
1767 }
1768
1769 // add file extension
1770 sprintf(fnameptr, ".eml");
1771
1772 // open file
1773 f = fopen(filename, "w+");
1774
1775 if ( !f ) {
1776 PrintAndLog("Can't open file %s ", filename);
1777 return 1;
1778 }
1779
1780 // put hex
1781 for (i = 0; i < numBlocks; i++) {
1782 if (mfEmlGetMem(buf, i, 1)) {
1783 PrintAndLog("Cant get block: %d", i);
1784 break;
1785 }
1786 for (j = 0; j < 16; j++)
1787 fprintf(f, "%02X", buf[j]);
1788 fprintf(f,"\n");
1789 }
1790 fclose(f);
1791
1792 PrintAndLog("Saved %d blocks to file: %s", numBlocks, filename);
1793
1794 return 0;
1795 }
1796
1797 int CmdHF14AMfECFill(const char *Cmd)
1798 {
1799 uint8_t keyType = 0;
1800 uint8_t numSectors = 16;
1801
1802 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
1803 PrintAndLog("Usage: hf mf ecfill <key A/B> [card memory]");
1804 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1805 PrintAndLog("");
1806 PrintAndLog("samples: hf mf ecfill A");
1807 PrintAndLog(" hf mf ecfill A 4");
1808 PrintAndLog("Read card and transfer its data to emulator memory.");
1809 PrintAndLog("Keys must be laid in the emulator memory. \n");
1810 return 0;
1811 }
1812
1813 char ctmp = param_getchar(Cmd, 0);
1814 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {
1815 PrintAndLog("Key type must be A or B");
1816 return 1;
1817 }
1818 if (ctmp != 'A' && ctmp != 'a') keyType = 1;
1819
1820 ctmp = param_getchar(Cmd, 1);
1821 switch (ctmp) {
1822 case '0' : numSectors = 5; break;
1823 case '1' :
1824 case '\0': numSectors = 16; break;
1825 case '2' : numSectors = 32; break;
1826 case '4' : numSectors = 40; break;
1827 default: numSectors = 16;
1828 }
1829
1830 printf("--params: numSectors: %d, keyType:%d", numSectors, keyType);
1831 UsbCommand c = {CMD_MIFARE_EML_CARDLOAD, {numSectors, keyType, 0}};
1832 SendCommand(&c);
1833 return 0;
1834 }
1835
1836 int CmdHF14AMfEKeyPrn(const char *Cmd)
1837 {
1838 int i;
1839 uint8_t numSectors;
1840 uint8_t data[16];
1841 uint64_t keyA, keyB;
1842
1843 char cmdp = param_getchar(Cmd, 0);
1844
1845 if ( cmdp == 'h' || cmdp == 'H' ) {
1846 PrintAndLog("It prints the keys loaded in the emulator memory");
1847 PrintAndLog("Usage: hf mf ekeyprn [card memory]");
1848 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");
1849 PrintAndLog("");
1850 PrintAndLog(" sample: hf mf ekeyprn 1");
1851 return 0;
1852 }
1853
1854 switch (cmdp) {
1855 case '0' : numSectors = 5; break;
1856 case '1' :
1857 case '\0': numSectors = 16; break;
1858 case '2' : numSectors = 32; break;
1859 case '4' : numSectors = 40; break;
1860 default: numSectors = 16;
1861 }
1862
1863 PrintAndLog("|---|----------------|----------------|");
1864 PrintAndLog("|sec|key A |key B |");
1865 PrintAndLog("|---|----------------|----------------|");
1866 for (i = 0; i < numSectors; i++) {
1867 if (mfEmlGetMem(data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) {
1868 PrintAndLog("error get block %d", FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1);
1869 break;
1870 }
1871 keyA = bytes_to_num(data, 6);
1872 keyB = bytes_to_num(data + 10, 6);
1873 PrintAndLog("|%03d| %012"llx" | %012"llx" |", i, keyA, keyB);
1874 }
1875 PrintAndLog("|---|----------------|----------------|");
1876
1877 return 0;
1878 }
1879
1880 // CHINESE MAGIC COMMANDS
1881
1882 int CmdHF14AMfCSetUID(const char *Cmd) {
1883 uint8_t wipeCard = 0;
1884 uint8_t uid[8] = {0x00};
1885 uint8_t oldUid[8] = {0x00};
1886 uint8_t atqa[2] = {0x00};
1887 uint8_t sak[1] = {0x00};
1888 uint8_t atqaPresent = 1;
1889 int res;
1890 char ctmp;
1891 int argi=0;
1892
1893 if (strlen(Cmd) < 1 || param_getchar(Cmd, argi) == 'h') {
1894 PrintAndLog("Set UID, ATQA, and SAK for magic Chinese card (only works with such cards)");
1895 PrintAndLog("If you also want to wipe the card then add 'w' at the end of the command line.");
1896 PrintAndLog("");
1897 PrintAndLog("Usage: hf mf csetuid <UID 8 hex symbols> [ATQA 4 hex symbols SAK 2 hex symbols] [w]");
1898 PrintAndLog("");
1899 PrintAndLog("sample: hf mf csetuid 01020304");
1900 PrintAndLog(" hf mf csetuid 01020304 0004 08 w");
1901 return 0;
1902 }
1903
1904 if (param_getchar(Cmd, argi) && param_gethex(Cmd, argi, uid, 8)) {
1905 PrintAndLog("UID must include 8 HEX symbols");
1906 return 1;
1907 }
1908 argi++;
1909
1910 ctmp = param_getchar(Cmd, argi);
1911 if (ctmp == 'w' || ctmp == 'W') {
1912 wipeCard = 1;
1913 atqaPresent = 0;
1914 }
1915
1916 if (atqaPresent) {
1917 if (param_getchar(Cmd, argi)) {
1918 if (param_gethex(Cmd, argi, atqa, 4)) {
1919 PrintAndLog("ATQA must include 4 HEX symbols");
1920 return 1;
1921 }
1922 argi++;
1923 if (!param_getchar(Cmd, argi) || param_gethex(Cmd, argi, sak, 2)) {
1924 PrintAndLog("SAK must include 2 HEX symbols");
1925 return 1;
1926 }
1927 argi++;
1928 } else
1929 atqaPresent = 0;
1930 }
1931
1932 if(!wipeCard) {
1933 ctmp = param_getchar(Cmd, argi);
1934 if (ctmp == 'w' || ctmp == 'W') {
1935 wipeCard = 1;
1936 }
1937 }
1938
1939 PrintAndLog("--wipe card:%s uid:%s", (wipeCard)?"YES":"NO", sprint_hex(uid, 4));
1940
1941 res = mfCSetUID(uid, (atqaPresent) ? atqa : NULL, (atqaPresent) ? sak : NULL, oldUid, wipeCard);
1942 if (res) {
1943 PrintAndLog("Can't set UID. error=%d", res);
1944 return 1;
1945 }
1946
1947 PrintAndLog("old UID:%s", sprint_hex(oldUid, 4));
1948 PrintAndLog("new UID:%s", sprint_hex(uid, 4));
1949 return 0;
1950 }
1951
1952 int CmdHF14AMfCSetBlk(const char *Cmd) {
1953 uint8_t block[16] = {0x00};
1954 uint8_t blockNo = 0;
1955 uint8_t params = MAGIC_SINGLE;
1956 int res;
1957
1958 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {
1959 PrintAndLog("Usage: hf mf csetblk <block number> <block data (32 hex symbols)> [w]");
1960 PrintAndLog("sample: hf mf csetblk 1 01020304050607080910111213141516");
1961 PrintAndLog("Set block data for magic Chinese card (only works with such cards)");
1962 PrintAndLog("If you also want wipe the card then add 'w' at the end of the command line");
1963 return 0;
1964 }
1965
1966 blockNo = param_get8(Cmd, 0);
1967
1968 if (param_gethex(Cmd, 1, block, 32)) {
1969 PrintAndLog("block data must include 32 HEX symbols");
1970 return 1;
1971 }
1972
1973 char ctmp = param_getchar(Cmd, 2);
1974 if (ctmp == 'w' || ctmp == 'W')
1975 params |= MAGIC_WIPE;
1976
1977 PrintAndLog("--block number:%2d data:%s", blockNo, sprint_hex(block, 16));
1978
1979 res = mfCSetBlock(blockNo, block, NULL, params);
1980 if (res) {
1981 PrintAndLog("Can't write block. error=%d", res);
1982 return 1;
1983 }
1984 return 0;
1985 }
1986
1987 int CmdHF14AMfCLoad(const char *Cmd) {
1988 FILE * f;
1989 char filename[FILE_PATH_SIZE];
1990 char * fnameptr = filename;
1991 char buf[64] = {0x00};
1992 uint8_t buf8[64] = {0x00};
1993 uint8_t fillFromEmulator = 0;
1994 int i, len, blockNum, flags=0;
1995
1996 memset(filename, 0, sizeof(filename));
1997
1998 char ctmp = param_getchar(Cmd, 0);
1999
2000 if (ctmp == 'h' || ctmp == 'H' || ctmp == 0x00) {
2001 PrintAndLog("It loads magic Chinese card from the file `filename.eml`");
2002 PrintAndLog("or from emulator memory (option `e`)");
2003 PrintAndLog("Usage: hf mf cload <file name w/o `.eml`>");
2004 PrintAndLog(" or: hf mf cload e ");
2005 PrintAndLog(" sample: hf mf cload filename");
2006 return 0;
2007 }
2008
2009 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;
2010
2011 if (fillFromEmulator) {
2012 for (blockNum = 0; blockNum < 16 * 4; blockNum += 1) {
2013 if (mfEmlGetMem(buf8, blockNum, 1)) {
2014 PrintAndLog("Cant get block: %d", blockNum);
2015 return 2;
2016 }
2017 if (blockNum == 0) flags = MAGIC_INIT + MAGIC_WUPC; // switch on field and send magic sequence
2018 if (blockNum == 1) flags = 0; // just write
2019 if (blockNum == 16 * 4 - 1) flags = MAGIC_HALT + MAGIC_OFF; // Done. Magic Halt and switch off field.
2020
2021 if (mfCSetBlock(blockNum, buf8, NULL, flags)) {
2022 PrintAndLog("Cant set magic card block: %d", blockNum);
2023 return 3;
2024 }
2025 }
2026 return 0;
2027 } else {
2028 len = strlen(Cmd);
2029 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
2030
2031 memcpy(filename, Cmd, len);
2032 fnameptr += len;
2033
2034 sprintf(fnameptr, ".eml");
2035
2036 // open file
2037 f = fopen(filename, "r");
2038 if (f == NULL) {
2039 PrintAndLog("File not found or locked.");
2040 return 1;
2041 }
2042
2043 blockNum = 0;
2044 while(!feof(f)){
2045
2046 memset(buf, 0, sizeof(buf));
2047
2048 if (fgets(buf, sizeof(buf), f) == NULL) {
2049 fclose(f);
2050 PrintAndLog("File reading error.");
2051 return 2;
2052 }
2053
2054 if (strlen(buf) < 32) {
2055 if(strlen(buf) && feof(f))
2056 break;
2057 PrintAndLog("File content error. Block data must include 32 HEX symbols");
2058 fclose(f);
2059 return 2;
2060 }
2061 for (i = 0; i < 32; i += 2)
2062 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
2063
2064 if (blockNum == 0) flags = MAGIC_INIT + MAGIC_WUPC; // switch on field and send magic sequence
2065 if (blockNum == 1) flags = 0; // just write
2066 if (blockNum == 16 * 4 - 1) flags = MAGIC_HALT + MAGIC_OFF; // Done. Switch off field.
2067
2068 if (mfCSetBlock(blockNum, buf8, NULL, flags)) {
2069 PrintAndLog("Can't set magic card block: %d", blockNum);
2070 fclose(f);
2071 return 3;
2072 }
2073 blockNum++;
2074
2075 if (blockNum >= 16 * 4) break; // magic card type - mifare 1K
2076 }
2077 fclose(f);
2078
2079 // 64 or 256blocks.
2080 if (blockNum != 16 * 4 && blockNum != 32 * 4 + 8 * 16){
2081 PrintAndLog("File content error. There must be 64 blocks");
2082 return 4;
2083 }
2084 PrintAndLog("Loaded from file: %s", filename);
2085 return 0;
2086 }
2087 return 0;
2088 }
2089
2090 int CmdHF14AMfCGetBlk(const char *Cmd) {
2091 uint8_t data[16];
2092 uint8_t blockNo = 0;
2093 int res;
2094 memset(data, 0x00, sizeof(data));
2095 char ctmp = param_getchar(Cmd, 0);
2096
2097 if (strlen(Cmd) < 1 || ctmp == 'h' || ctmp == 'H') {
2098 PrintAndLog("Usage: hf mf cgetblk <block number>");
2099 PrintAndLog("sample: hf mf cgetblk 1");
2100 PrintAndLog("Get block data from magic Chinese card (only works with such cards)\n");
2101 return 0;
2102 }
2103
2104 blockNo = param_get8(Cmd, 0);
2105
2106 PrintAndLog("--block number:%2d ", blockNo);
2107
2108 res = mfCGetBlock(blockNo, data, MAGIC_SINGLE);
2109 if (res) {
2110 PrintAndLog("Can't read block. error=%d", res);
2111 return 1;
2112 }
2113
2114 PrintAndLog("data: %s", sprint_hex(data, sizeof(data)));
2115 return 0;
2116 }
2117
2118 int CmdHF14AMfCGetSc(const char *Cmd) {
2119 uint8_t data[16];
2120 uint8_t sectorNo = 0;
2121 int i, res, flags;
2122 memset(data, 0x00, sizeof(data));
2123 char ctmp = param_getchar(Cmd, 0);
2124
2125 if (strlen(Cmd) < 1 || ctmp == 'h' || ctmp == 'H') {
2126 PrintAndLog("Usage: hf mf cgetsc <sector number>");
2127 PrintAndLog("sample: hf mf cgetsc 0");
2128 PrintAndLog("Get sector data from magic Chinese card (only works with such cards)\n");
2129 return 0;
2130 }
2131
2132 sectorNo = param_get8(Cmd, 0);
2133 if (sectorNo > 15) {
2134 PrintAndLog("Sector number must be in [0..15] as in MIFARE classic.");
2135 return 1;
2136 }
2137
2138 PrintAndLog("--sector number:%d ", sectorNo);
2139 PrintAndLog("block | data");
2140
2141 flags = MAGIC_INIT + MAGIC_WUPC;
2142 for (i = 0; i < 4; i++) {
2143 if (i == 1) flags = 0;
2144 if (i == 3) flags = MAGIC_HALT + MAGIC_OFF;
2145
2146 res = mfCGetBlock(sectorNo * 4 + i, data, flags);
2147 if (res) {
2148 PrintAndLog("Can't read block. %d error=%d", sectorNo * 4 + i, res);
2149 return 1;
2150 }
2151 PrintAndLog(" %3d | %s", sectorNo * 4 + i, sprint_hex(data, sizeof(data)));
2152 }
2153 return 0;
2154 }
2155
2156 int CmdHF14AMfCSave(const char *Cmd) {
2157
2158 FILE * f;
2159 char filename[FILE_PATH_SIZE];
2160 char * fnameptr = filename;
2161 uint8_t fillFromEmulator = 0;
2162 uint8_t buf[64];
2163 int i, j, len, flags;
2164
2165 memset(filename, 0, sizeof(filename));
2166 memset(buf, 0, sizeof(buf));
2167 char ctmp = param_getchar(Cmd, 0);
2168
2169 if ( ctmp == 'h' || ctmp == 'H' ) {
2170 PrintAndLog("It saves `magic Chinese` card dump into the file `filename.eml` or `cardID.eml`");
2171 PrintAndLog("or into emulator memory (option `e`)");
2172 PrintAndLog("Usage: hf mf esave [file name w/o `.eml`][e]");
2173 PrintAndLog(" sample: hf mf esave ");
2174 PrintAndLog(" hf mf esave filename");
2175 PrintAndLog(" hf mf esave e \n");
2176 return 0;
2177 }
2178 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;
2179
2180 if (fillFromEmulator) {
2181 // put into emulator
2182 flags = MAGIC_INIT + MAGIC_WUPC;
2183 for (i = 0; i < 16 * 4; i++) {
2184 if (i == 1) flags = 0;
2185 if (i == 16 * 4 - 1) flags = MAGIC_HALT + MAGIC_OFF;
2186
2187 if (mfCGetBlock(i, buf, flags)) {
2188 PrintAndLog("Cant get block: %d", i);
2189 break;
2190 }
2191
2192 if (mfEmlSetMem(buf, i, 1)) {
2193 PrintAndLog("Cant set emul block: %d", i);
2194 return 3;
2195 }
2196 }
2197 return 0;
2198 } else {
2199 len = strlen(Cmd);
2200 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
2201
2202 // get filename based on UID
2203 if (len < 1) {
2204
2205 if (mfCGetBlock(0, buf, MAGIC_SINGLE)) {
2206 PrintAndLog("Cant get block: %d", 0);
2207 len = sprintf(fnameptr, "dump");
2208 fnameptr += len;
2209 } else {
2210 for (j = 0; j < 7; j++, fnameptr += 2)
2211 sprintf(fnameptr, "%02x", buf[j]);
2212 }
2213 } else {
2214 memcpy(filename, Cmd, len);
2215 fnameptr += len;
2216 }
2217
2218 // add .eml extension
2219 sprintf(fnameptr, ".eml");
2220
2221 // open file
2222 f = fopen(filename, "w+");
2223
2224 if (f == NULL) {
2225 PrintAndLog("File not found or locked.");
2226 return 1;
2227 }
2228
2229 // put hex
2230 flags = MAGIC_INIT + MAGIC_WUPC;
2231 for (i = 0; i < 16 * 4; i++) {
2232 if (i == 1) flags = 0;
2233 if (i == 16 * 4 - 1) flags = MAGIC_HALT + MAGIC_OFF;
2234
2235 if (mfCGetBlock(i, buf, flags)) {
2236 PrintAndLog("Cant get block: %d", i);
2237 break;
2238 }
2239 for (j = 0; j < 16; j++)
2240 fprintf(f, "%02x", buf[j]);
2241 fprintf(f,"\n");
2242 }
2243 fflush(f);
2244 fclose(f);
2245 PrintAndLog("Saved to file: %s", filename);
2246 return 0;
2247 }
2248 }
2249
2250 //needs nt, ar, at, Data to decrypt
2251 int CmdHf14MfDecryptBytes(const char *Cmd){
2252 uint8_t data[50];
2253 uint32_t nt = param_get32ex(Cmd,0,0,16);
2254 uint32_t ar_enc = param_get32ex(Cmd,1,0,16);
2255 uint32_t at_enc = param_get32ex(Cmd,2,0,16);
2256
2257 int len = 0;
2258 param_gethex_ex(Cmd, 3, data, &len);
2259
2260 len /= 2;
2261 int limit = sizeof(data) / 2;
2262
2263 if ( len >= limit )
2264 len = limit;
2265
2266 return tryDecryptWord( nt, ar_enc, at_enc, data, len);
2267 }
2268
2269 static command_t CommandTable[] = {
2270 {"help", CmdHelp, 1, "This help"},
2271 {"dbg", CmdHF14AMfDbg, 0, "Set default debug mode"},
2272 {"rdbl", CmdHF14AMfRdBl, 0, "Read MIFARE classic block"},
2273 {"rdsc", CmdHF14AMfRdSc, 0, "Read MIFARE classic sector"},
2274 {"dump", CmdHF14AMfDump, 0, "Dump MIFARE classic tag to binary file"},
2275 {"restore", CmdHF14AMfRestore, 0, "Restore MIFARE classic binary file to BLANK tag"},
2276 {"wrbl", CmdHF14AMfWrBl, 0, "Write MIFARE classic block"},
2277 {"chk", CmdHF14AMfChk, 0, "Test block keys"},
2278 {"mifare", CmdHF14AMifare, 0, "Read parity error messages."},
2279 {"nested", CmdHF14AMfNested, 0, "Test nested authentication"},
2280 {"hardnested", CmdHF14AMfNestedHard, 0, "Nested attack for hardened Mifare cards"},
2281 {"sniff", CmdHF14AMfSniff, 0, "Sniff card-reader communication"},
2282 {"sim", CmdHF14AMf1kSim, 0, "Simulate MIFARE card"},
2283 {"eclr", CmdHF14AMfEClear, 0, "Clear simulator memory block"},
2284 {"eget", CmdHF14AMfEGet, 0, "Get simulator memory block"},
2285 {"eset", CmdHF14AMfESet, 0, "Set simulator memory block"},
2286 {"eload", CmdHF14AMfELoad, 0, "Load from file emul dump"},
2287 {"esave", CmdHF14AMfESave, 0, "Save to file emul dump"},
2288 {"ecfill", CmdHF14AMfECFill, 0, "Fill simulator memory with help of keys from simulator"},
2289 {"ekeyprn", CmdHF14AMfEKeyPrn, 0, "Print keys from simulator memory"},
2290 {"csetuid", CmdHF14AMfCSetUID, 0, "Set UID for magic Chinese card"},
2291 {"csetblk", CmdHF14AMfCSetBlk, 0, "Write block - Magic Chinese card"},
2292 {"cgetblk", CmdHF14AMfCGetBlk, 0, "Read block - Magic Chinese card"},
2293 {"cgetsc", CmdHF14AMfCGetSc, 0, "Read sector - Magic Chinese card"},
2294 {"cload", CmdHF14AMfCLoad, 0, "Load dump into magic Chinese card"},
2295 {"csave", CmdHF14AMfCSave, 0, "Save dump from magic Chinese card into file or emulator"},
2296 {"decrypt", CmdHf14MfDecryptBytes, 1, "[nt] [ar_enc] [at_enc] [data] - to decrypt snoop or trace"},
2297 {NULL, NULL, 0, NULL}
2298 };
2299
2300 int CmdHFMF(const char *Cmd) {
2301 clearCommandBuffer();
2302 CmdsParse(CommandTable, Cmd);
2303 return 0;
2304 }
2305
2306 int CmdHelp(const char *Cmd) {
2307 CmdsHelp(CommandTable);
2308 return 0;
2309 }
Impressum, Datenschutz