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