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