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