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