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