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