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