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