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