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