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