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