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