]> git.zerfleddert.de Git - proxmark3-svn/blame - client/cmdhfmf.c
fix hf mf sim (#812)
[proxmark3-svn] / client / cmdhfmf.c
CommitLineData
9ca155ba 1//-----------------------------------------------------------------------------\r
b62a5a84 2// Copyright (C) 2011,2012 Merlok\r
9ca155ba
M
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
c48c4d78 11#include "cmdhfmf.h"\r
12\r
43534cba 13#include <inttypes.h>\r
acf0582d 14#include <string.h>\r
7cb8516c 15#include <stdio.h>\r
16#include <stdlib.h>\r
acf0582d 17#include <ctype.h>\r
ad939de5 18#include "comms.h"\r
7cb8516c 19#include "cmdmain.h"\r
c48c4d78 20#include "cmdhfmfhard.h"\r
a37725fa 21#include "parity.h"\r
7cb8516c 22#include "util.h"\r
ec9c7112 23#include "util_posix.h"\r
c48c4d78 24#include "usb_cmd.h"\r
7cb8516c 25#include "ui.h"\r
fdd9395d 26#include "mifare/mifarehost.h"\r
7cb8516c 27#include "mifare.h"\r
fdd9395d 28#include "mifare/mfkey.h"\r
362d2039 29#include "hardnested/hardnested_bf_core.h"\r
7dadcc95
OM
30#include "cliparser/cliparser.h"\r
31#include "cmdhf14a.h"\r
fdd9395d
OM
32#include "mifare/mifare4.h"\r
33#include "mifare/mad.h"\r
34#include "mifare/ndef.h"\r
35#include "emv/dump.h"\r
7cb8516c 36\r
37#define NESTED_SECTOR_RETRY 10 // how often we try mfested() until we give up\r
38\r
9ca155ba
M
39static int CmdHelp(const char *Cmd);\r
40\r
9ca155ba
M
41int CmdHF14AMifare(const char *Cmd)\r
42{\r
7779d73c 43 int isOK = 0;\r
44 uint64_t key = 0;\r
7779d73c 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
c48c4d78 51 PrintAndLog("generating polynomial with 16 effective bits only, but shows unexpected behaviour."); return 1;\r
7779d73c 52 case -5 : PrintAndLog("Aborted via keyboard."); return 1;\r
53 default : PrintAndLog("Found valid key:%012" PRIx64 "\n", key);\r
aea4d766 54 }\r
7906cb41 55\r
3fe4ff4f 56 PrintAndLog("");\r
9ca155ba
M
57 return 0;\r
58}\r
59\r
7779d73c 60\r
9ca155ba
M
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
7906cb41 67\r
9ca155ba
M
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
7906cb41 74 }\r
9ca155ba
M
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
baeaf579 91 PrintAndLog("--block no:%d, key type:%c, key:%s", blockNo, keyType?'B':'A', sprint_hex(key, 6));\r
9ca155ba 92 PrintAndLog("--data: %s", sprint_hex(bldata, 16));\r
7906cb41 93\r
9ca155ba
M
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
9ca155ba 98\r
902cb3c0 99 UsbCommand resp;\r
100 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {\r
101 uint8_t isOK = resp.arg[0] & 0xff;\r
9ca155ba
M
102 PrintAndLog("isOk:%02x", isOK);\r
103 } else {\r
104 PrintAndLog("Command execute timeout");\r
105 }\r
106\r
d2f487af 107 return 0;\r
108}\r
109\r
d2f487af 110int CmdHF14AMfRdBl(const char *Cmd)\r
111{\r
112 uint8_t blockNo = 0;\r
9ca155ba
M
113 uint8_t keyType = 0;\r
114 uint8_t key[6] = {0, 0, 0, 0, 0, 0};\r
7906cb41 115\r
9ca155ba
M
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
7906cb41
F
123 }\r
124\r
9ca155ba
M
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
baeaf579 136 PrintAndLog("--block no:%d, key type:%c, key:%s ", blockNo, keyType?'B':'A', sprint_hex(key, 6));\r
7906cb41 137\r
9ca155ba
M
138 UsbCommand c = {CMD_MIFARE_READBL, {blockNo, keyType, 0}};\r
139 memcpy(c.d.asBytes, key, 6);\r
140 SendCommand(&c);\r
9ca155ba 141\r
902cb3c0 142 UsbCommand resp;\r
143 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {\r
baeaf579 144 uint8_t isOK = resp.arg[0] & 0xff;\r
145 uint8_t *data = resp.d.asBytes;\r
9ca155ba 146\r
ac4ecfe3 147 if (isOK) {\r
9ca155ba 148 PrintAndLog("isOk:%02x data:%s", isOK, sprint_hex(data, 16));\r
ac4ecfe3 149 } else {\r
9ca155ba 150 PrintAndLog("isOk:%02x", isOK);\r
ac4ecfe3
OM
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
9ca155ba
M
164 } else {\r
165 PrintAndLog("Command execute timeout");\r
ac4ecfe3 166 return 2;\r
9ca155ba
M
167 }\r
168\r
d2f487af 169 return 0;\r
170}\r
171\r
d2f487af 172int CmdHF14AMfRdSc(const char *Cmd)\r
173{\r
174 int i;\r
9ca155ba
M
175 uint8_t sectorNo = 0;\r
176 uint8_t keyType = 0;\r
177 uint8_t key[6] = {0, 0, 0, 0, 0, 0};\r
9ca155ba 178 uint8_t isOK = 0;\r
baeaf579 179 uint8_t *data = NULL;\r
9ca155ba
M
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
7906cb41
F
186 }\r
187\r
9ca155ba 188 sectorNo = param_get8(Cmd, 0);\r
baeaf579 189 if (sectorNo > 39) {\r
190 PrintAndLog("Sector number must be less than 40");\r
9ca155ba
M
191 return 1;\r
192 }\r
193 cmdp = param_getchar(Cmd, 1);\r
baeaf579 194 if (cmdp != 'a' && cmdp != 'A' && cmdp != 'b' && cmdp != 'B') {\r
9ca155ba
M
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
baeaf579 203 PrintAndLog("--sector no:%d key type:%c key:%s ", sectorNo, keyType?'B':'A', sprint_hex(key, 6));\r
7906cb41 204\r
baeaf579 205 UsbCommand c = {CMD_MIFARE_READSC, {sectorNo, keyType, 0}};\r
9ca155ba 206 memcpy(c.d.asBytes, key, 6);\r
baeaf579 207 SendCommand(&c);\r
9ca155ba
M
208 PrintAndLog(" ");\r
209\r
902cb3c0 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
9ca155ba
M
214\r
215 PrintAndLog("isOk:%02x", isOK);\r
baeaf579 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
9ca155ba 219 }\r
baeaf579 220 PrintAndLog("trailer: %s", sprint_hex(data + (sectorNo<32?3:15) * 16, 16));\r
daccbcdc
F
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
baeaf579 230 }\r
9ca155ba 231 } else {\r
baeaf579 232 PrintAndLog("Command execute timeout");\r
9ca155ba
M
233 }\r
234\r
baeaf579 235 return 0;\r
236}\r
9ca155ba 237\r
baeaf579 238uint8_t FirstBlockOfSector(uint8_t sectorNo)\r
239{\r
240 if (sectorNo < 32) {\r
241 return sectorNo * 4;\r
9ca155ba 242 } else {\r
baeaf579 243 return 32 * 4 + (sectorNo - 32) * 16;\r
9ca155ba 244 }\r
9ca155ba
M
245}\r
246\r
baeaf579 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
adf023ff 256static int ParamCardSizeSectors(const char c) {\r
a8561e35 257 int numSectors = 16;\r
adf023ff 258 switch (c) {\r
a8561e35 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
adf023ff 263 }\r
a8561e35 264 return numSectors;\r
adf023ff
OM
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
aea4d766 278int CmdHF14AMfDump(const char *Cmd)\r
26fdb4ab 279{\r
baeaf579 280 uint8_t sectorNo, blockNo;\r
7906cb41 281\r
4309ef8f 282 uint8_t keys[2][40][6];\r
aea4d766 283 uint8_t rights[40][4];\r
79db03ef 284 uint8_t carddata[256][16];\r
baeaf579 285 uint8_t numSectors = 16;\r
7906cb41 286\r
26fdb4ab 287 FILE *fin;\r
288 FILE *fout;\r
7906cb41 289\r
902cb3c0 290 UsbCommand resp;\r
baeaf579 291\r
292 char cmdp = param_getchar(Cmd, 0);\r
adf023ff 293 numSectors = ParamCardSizeSectors(cmdp);\r
7906cb41 294\r
4309ef8f
MF
295 if (strlen(Cmd) > 3 || cmdp == 'h' || cmdp == 'H') {\r
296 PrintAndLog("Usage: hf mf dump [card memory] [k|m]");\r
baeaf579 297 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");\r
4309ef8f
MF
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
baeaf579 300 PrintAndLog("");\r
301 PrintAndLog("Samples: hf mf dump");\r
302 PrintAndLog(" hf mf dump 4");\r
4309ef8f 303 PrintAndLog(" hf mf dump 4 m");\r
baeaf579 304 return 0;\r
305 }\r
7906cb41 306\r
4309ef8f
MF
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
26fdb4ab 313 if ((fin = fopen("dumpkeys.bin","rb")) == NULL) {\r
aea4d766 314 PrintAndLog("Could not find file dumpkeys.bin");\r
26fdb4ab 315 return 1;\r
316 }\r
7906cb41 317\r
4309ef8f
MF
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
26fdb4ab 328 }\r
7906cb41 329\r
97d582a6 330 fclose(fin);\r
baeaf579 331\r
26fdb4ab 332 PrintAndLog("|-----------------------------------------|");\r
333 PrintAndLog("|------ Reading sector access bits...-----|");\r
334 PrintAndLog("|-----------------------------------------|");\r
40c6a02b 335 uint8_t tries = 0;\r
baeaf579 336 for (sectorNo = 0; sectorNo < numSectors; sectorNo++) {\r
7906cb41 337 for (tries = 0; tries < 3; tries++) {\r
40c6a02b 338 UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 0, 0}};\r
4309ef8f
MF
339 // At least the Access Conditions can always be read with key A.\r
340 memcpy(c.d.asBytes, keys[0][sectorNo], 6);\r
40c6a02b 341 SendCommand(&c);\r
26fdb4ab 342\r
40c6a02b 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
baeaf579 357 } else {\r
40c6a02b 358 PrintAndLog("Command execute timeout when trying to read access rights for sector %2d. Trying with defaults...", sectorNo);\r
c626c56e 359 rights[sectorNo][0] = rights[sectorNo][1] = rights[sectorNo][2] = 0x00;\r
360 rights[sectorNo][3] = 0x01;\r
26fdb4ab 361 }\r
26fdb4ab 362 }\r
363 }\r
7906cb41 364\r
26fdb4ab 365 PrintAndLog("|-----------------------------------------|");\r
366 PrintAndLog("|----- Dumping all blocks to file... -----|");\r
367 PrintAndLog("|-----------------------------------------|");\r
7906cb41 368\r
79db03ef 369 bool isOK = true;\r
370 for (sectorNo = 0; isOK && sectorNo < numSectors; sectorNo++) {\r
371 for (blockNo = 0; isOK && blockNo < NumBlocksPerSector(sectorNo); blockNo++) {\r
baeaf579 372 bool received = false;\r
7906cb41
F
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
79db03ef 375 UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 0, 0}};\r
4309ef8f 376 memcpy(c.d.asBytes, keys[0][sectorNo], 6);\r
79db03ef 377 SendCommand(&c);\r
378 received = WaitForResponseTimeout(CMD_ACK,&resp,1500);\r
4309ef8f
MF
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
40c6a02b 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
4309ef8f 394 memcpy(c.d.asBytes, keys[1][sectorNo], 6);\r
40c6a02b 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
40c6a02b 398 PrintAndLog("Access rights do not allow reading of sector %2d block %3d", sectorNo, blockNo);\r
4309ef8f
MF
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
40c6a02b 408 } else { // key A would work\r
409 UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 0, 0}};\r
4309ef8f 410 memcpy(c.d.asBytes, keys[0][sectorNo], 6);\r
40c6a02b 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
26fdb4ab 418 }\r
419 }\r
420\r
902cb3c0 421 if (received) {\r
79db03ef 422 isOK = resp.arg[0] & 0xff;\r
902cb3c0 423 uint8_t *data = resp.d.asBytes;\r
baeaf579 424 if (blockNo == NumBlocksPerSector(sectorNo) - 1) { // sector trailer. Fill in the keys.\r
4309ef8f
MF
425 memcpy(data, keys[0][sectorNo], 6);\r
426 memcpy(data + 10, keys[1][sectorNo], 6);\r
3d77fdfa 427 }\r
26fdb4ab 428 if (isOK) {\r
79db03ef 429 memcpy(carddata[FirstBlockOfSector(sectorNo) + blockNo], data, 16);\r
430 PrintAndLog("Successfully read block %2d of sector %2d.", blockNo, sectorNo);\r
baeaf579 431 } else {\r
432 PrintAndLog("Could not read block %2d of sector %2d", blockNo, sectorNo);\r
79db03ef 433 break;\r
26fdb4ab 434 }\r
435 }\r
436 else {\r
79db03ef 437 isOK = false;\r
438 PrintAndLog("Command execute timeout when trying to read block %2d of sector %2d.", blockNo, sectorNo);\r
439 break;\r
26fdb4ab 440 }\r
441 }\r
442 }\r
79db03ef 443\r
444 if (isOK) {\r
7906cb41 445 if ((fout = fopen("dumpdata.bin","wb")) == NULL) {\r
79db03ef 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
7906cb41 454\r
baeaf579 455 return 0;\r
26fdb4ab 456}\r
457\r
aea4d766 458int CmdHF14AMfRestore(const char *Cmd)\r
26fdb4ab 459{\r
baeaf579 460 uint8_t sectorNo,blockNo;\r
26fdb4ab 461 uint8_t keyType = 0;\r
83602aff 462 uint8_t key[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};\r
b915fda3 463 uint8_t bldata[16] = {0x00};\r
baeaf579 464 uint8_t keyA[40][6];\r
465 uint8_t keyB[40][6];\r
466 uint8_t numSectors;\r
7906cb41 467\r
26fdb4ab 468 FILE *fdump;\r
469 FILE *fkeys;\r
baeaf579 470\r
471 char cmdp = param_getchar(Cmd, 0);\r
472 switch (cmdp) {\r
473 case '0' : numSectors = 5; break;\r
7906cb41 474 case '1' :\r
baeaf579 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
7906cb41 479 }\r
baeaf579 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
26fdb4ab 490 if ((fkeys = fopen("dumpkeys.bin","rb")) == NULL) {\r
aea4d766 491 PrintAndLog("Could not find file dumpkeys.bin");\r
26fdb4ab 492 return 1;\r
493 }\r
7906cb41 494\r
baeaf579 495 for (sectorNo = 0; sectorNo < numSectors; sectorNo++) {\r
4c16ae80 496 size_t bytes_read = fread(keyA[sectorNo], 1, 6, fkeys);\r
497 if (bytes_read != 6) {\r
baeaf579 498 PrintAndLog("File reading error (dumpkeys.bin).");\r
31d1caa5 499 fclose(fkeys);\r
759c16b3 500 return 2;\r
baeaf579 501 }\r
26fdb4ab 502 }\r
baeaf579 503\r
504 for (sectorNo = 0; sectorNo < numSectors; sectorNo++) {\r
4c16ae80 505 size_t bytes_read = fread(keyB[sectorNo], 1, 6, fkeys);\r
506 if (bytes_read != 6) {\r
baeaf579 507 PrintAndLog("File reading error (dumpkeys.bin).");\r
31d1caa5 508 fclose(fkeys);\r
759c16b3 509 return 2;\r
baeaf579 510 }\r
26fdb4ab 511 }\r
b915fda3 512\r
ca4714cd 513 fclose(fkeys);\r
79db03ef 514\r
b915fda3 515 if ((fdump = fopen("dumpdata.bin","rb")) == NULL) {\r
516 PrintAndLog("Could not find file dumpdata.bin");\r
517 return 1;\r
7906cb41 518 }\r
9d710943 519 PrintAndLog("Restoring dumpdata.bin to card");\r
26fdb4ab 520\r
baeaf579 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
26fdb4ab 524 memcpy(c.d.asBytes, key, 6);\r
7906cb41 525\r
4c16ae80 526 size_t bytes_read = fread(bldata, 1, 16, fdump);\r
527 if (bytes_read != 16) {\r
baeaf579 528 PrintAndLog("File reading error (dumpdata.bin).");\r
ca4714cd 529 fclose(fdump);\r
baeaf579 530 return 2;\r
531 }\r
7906cb41 532\r
baeaf579 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
7906cb41
F
546 }\r
547\r
baeaf579 548 PrintAndLog("Writing to block %3d: %s", FirstBlockOfSector(sectorNo) + blockNo, sprint_hex(bldata, 16));\r
7906cb41 549\r
26fdb4ab 550 memcpy(c.d.asBytes + 10, bldata, 16);\r
551 SendCommand(&c);\r
26fdb4ab 552\r
902cb3c0 553 UsbCommand resp;\r
baeaf579 554 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {\r
902cb3c0 555 uint8_t isOK = resp.arg[0] & 0xff;\r
26fdb4ab 556 PrintAndLog("isOk:%02x", isOK);\r
557 } else {\r
558 PrintAndLog("Command execute timeout");\r
559 }\r
560 }\r
561 }\r
7906cb41 562\r
26fdb4ab 563 fclose(fdump);\r
26fdb4ab 564 return 0;\r
565}\r
566\r
0c86cb01
OM
567//----------------------------------------------\r
568// Nested\r
569//----------------------------------------------\r
0c86cb01
OM
570\r
571static void parseParamTDS(const char *Cmd, const uint8_t indx, bool *paramT, bool *paramD, uint8_t *timeout) {\r
5594c621 572 char ctmp3[4] = {0};\r
0c86cb01
OM
573 int len = param_getlength(Cmd, indx);\r
574 if (len > 0 && len < 4){\r
874572d4 575 param_getstr(Cmd, indx, ctmp3, sizeof(ctmp3));\r
0c86cb01
OM
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
9ca155ba
M
595int CmdHF14AMfNested(const char *Cmd)\r
596{\r
597 int i, j, res, iterations;\r
7cb8516c 598 sector_t *e_sector = NULL;\r
9ca155ba
M
599 uint8_t blockNo = 0;\r
600 uint8_t keyType = 0;\r
601 uint8_t trgBlockNo = 0;\r
602 uint8_t trgKeyType = 0;\r
baeaf579 603 uint8_t SectorsCnt = 0;\r
9ca155ba 604 uint8_t key[6] = {0, 0, 0, 0, 0, 0};\r
e537c3e8 605 uint8_t keyBlock[MifareDefaultKeysSize * 6];\r
9ca155ba 606 uint64_t key64 = 0;\r
0c86cb01
OM
607 // timeout in units. (ms * 106)/10 or us*0.0106\r
608 uint8_t btimeout14a = MF_CHKKEYS_DEFTIMEOUT; // fast by default\r
adf023ff
OM
609 \r
610 bool autosearchKey = false;\r
7906cb41 611\r
adf023ff 612 bool transferToEml = false;\r
baeaf579 613 bool createDumpFile = false;\r
26fdb4ab 614 FILE *fkeys;\r
21156267 615 uint8_t standart[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};\r
616 uint8_t tempkey[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};\r
7906cb41 617\r
9ca155ba
M
618 char cmdp, ctmp;\r
619\r
620 if (strlen(Cmd)<3) {\r
621 PrintAndLog("Usage:");\r
0c86cb01
OM
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
0014cb46
M
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
adf023ff 626 PrintAndLog(" ");\r
9ca155ba 627 PrintAndLog("card memory - 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other> - 1K");\r
adf023ff
OM
628 PrintAndLog("t - transfer keys to emulator memory");\r
629 PrintAndLog("d - write keys to binary file dumpkeys.bin");\r
0c86cb01
OM
630 PrintAndLog("s - Slow (1ms) check keys (required by some non standard cards)");\r
631 PrintAndLog("ss - Very slow (5ms) check keys");\r
9ca155ba
M
632 PrintAndLog(" ");\r
633 PrintAndLog(" sample1: hf mf nested 1 0 A FFFFFFFFFFFF ");\r
79db03ef 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
adf023ff 637 PrintAndLog(" sample5: hf mf nested 1 * t");\r
0c86cb01 638 PrintAndLog(" sample6: hf mf nested 1 * ss");\r
9ca155ba 639 return 0;\r
7906cb41
F
640 }\r
641\r
adf023ff 642 // <card memory>\r
9ca155ba 643 cmdp = param_getchar(Cmd, 0);\r
adf023ff
OM
644 if (cmdp == 'o' || cmdp == 'O') {\r
645 cmdp = 'o';\r
646 SectorsCnt = 1;\r
647 } else {\r
648 SectorsCnt = ParamCardSizeSectors(cmdp);\r
9ca155ba 649 }\r
adf023ff
OM
650 \r
651 // <block number>. number or autosearch key (*)\r
652 if (param_getchar(Cmd, 1) == '*') {\r
653 autosearchKey = true;\r
7906cb41 654\r
0c86cb01 655 parseParamTDS(Cmd, 2, &transferToEml, &createDumpFile, &btimeout14a);\r
7906cb41 656\r
0c86cb01
OM
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
adf023ff
OM
659 } else {\r
660 blockNo = param_get8(Cmd, 1);\r
7906cb41 661\r
adf023ff 662 ctmp = param_getchar(Cmd, 2);\r
baeaf579 663 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {\r
adf023ff 664 PrintAndLog("Key type must be A or B");\r
9ca155ba
M
665 return 1;\r
666 }\r
adf023ff 667\r
7906cb41 668 if (ctmp != 'A' && ctmp != 'a')\r
adf023ff
OM
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
7906cb41 675\r
adf023ff
OM
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
9ca155ba 681 }\r
8556b852 682\r
adf023ff
OM
683 // one sector nested\r
684 if (cmdp == 'o') { \r
685 trgBlockNo = param_get8(Cmd, 4);\r
7906cb41 686\r
adf023ff
OM
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
7906cb41 694\r
0c86cb01 695 parseParamTDS(Cmd, 6, &transferToEml, &createDumpFile, &btimeout14a);\r
adf023ff 696 } else {\r
0c86cb01 697 parseParamTDS(Cmd, 4, &transferToEml, &createDumpFile, &btimeout14a);\r
adf023ff
OM
698 }\r
699\r
0c86cb01
OM
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
adf023ff
OM
702 }\r
703\r
704 // one-sector nested\r
705 if (cmdp == 'o') { // ------------------------------------ one sector working\r
baeaf579 706 PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo, trgKeyType?'B':'A');\r
dc8ba239 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
9ca155ba
M
715 return 2;\r
716 }\r
9492e0b0 717 key64 = bytes_to_num(keyBlock, 6);\r
718 if (key64) {\r
43534cba 719 PrintAndLog("Found valid key:%012" PRIx64, key64);\r
8556b852
M
720\r
721 // transfer key to the emulator\r
722 if (transferToEml) {\r
baeaf579 723 uint8_t sectortrailer;\r
724 if (trgBlockNo < 32*4) { // 4 block sector\r
32e6891a 725 sectortrailer = trgBlockNo | 0x03;\r
baeaf579 726 } else { // 16 block sector\r
32e6891a 727 sectortrailer = trgBlockNo | 0x0f;\r
baeaf579 728 }\r
729 mfEmlGetMem(keyBlock, sectortrailer, 1);\r
7906cb41 730\r
8556b852
M
731 if (!trgKeyType)\r
732 num_to_bytes(key64, 6, keyBlock);\r
733 else\r
734 num_to_bytes(key64, 6, &keyBlock[10]);\r
7906cb41 735 mfEmlSetMem(keyBlock, sectortrailer, 1);\r
adf023ff 736 PrintAndLog("Key transferred to emulator memory.");\r
8556b852
M
737 }\r
738 } else {\r
9ca155ba 739 PrintAndLog("No valid key found");\r
8556b852 740 }\r
21156267 741 }\r
742 else { // ------------------------------------ multiple sectors working\r
acf0582d 743 uint64_t msclock1;\r
744 msclock1 = msclock();\r
9492e0b0 745\r
7cb8516c 746 e_sector = calloc(SectorsCnt, sizeof(sector_t));\r
9ca155ba 747 if (e_sector == NULL) return 1;\r
7906cb41 748\r
baeaf579 749 //test current key and additional standard keys first\r
275d9e61
OM
750 for (int defaultKeyCounter = 0; defaultKeyCounter < MifareDefaultKeysSize; defaultKeyCounter++){\r
751 num_to_bytes(MifareDefaultKeys[defaultKeyCounter], 6, (uint8_t*)(keyBlock + defaultKeyCounter * 6));\r
752 }\r
9ca155ba
M
753\r
754 PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt);\r
e537c3e8 755 mfCheckKeysSec(SectorsCnt, 2, btimeout14a, true, MifareDefaultKeysSize, keyBlock, e_sector);\r
adf023ff
OM
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
adf023ff
OM
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
44964fd1 777 free(e_sector);\r
adf023ff
OM
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
7906cb41 782\r
9ca155ba
M
783 // nested sectors\r
784 iterations = 0;\r
785 PrintAndLog("nested...");\r
9492e0b0 786 bool calibrate = true;\r
9ca155ba 787 for (i = 0; i < NESTED_SECTOR_RETRY; i++) {\r
baeaf579 788 for (uint8_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) {\r
7906cb41 789 for (trgKeyType = 0; trgKeyType < 2; trgKeyType++) {\r
baeaf579 790 if (e_sector[sectorNo].foundKey[trgKeyType]) continue;\r
9492e0b0 791 PrintAndLog("-----------------------------------------------");\r
dc8ba239 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
3fe4ff4f 800 free(e_sector);\r
dc8ba239 801 return 2;\r
802 } else {\r
9492e0b0 803 calibrate = false;\r
804 }\r
7906cb41 805\r
9ca155ba 806 iterations++;\r
9492e0b0 807\r
808 key64 = bytes_to_num(keyBlock, 6);\r
809 if (key64) {\r
43534cba 810 PrintAndLog("Found valid key:%012" PRIx64, key64);\r
baeaf579 811 e_sector[sectorNo].foundKey[trgKeyType] = 1;\r
812 e_sector[sectorNo].Key[trgKeyType] = key64;\r
275d9e61
OM
813 \r
814 // try to check this key as a key to the other sectors\r
0c86cb01 815 mfCheckKeysSec(SectorsCnt, 2, btimeout14a, true, 1, keyBlock, e_sector);\r
9ca155ba
M
816 }\r
817 }\r
9492e0b0 818 }\r
9ca155ba
M
819 }\r
820\r
adf023ff
OM
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
adf023ff 825 // print result\r
9ca155ba
M
826 PrintAndLog("|---|----------------|---|----------------|---|");\r
827 PrintAndLog("|sec|key A |res|key B |res|");\r
828 PrintAndLog("|---|----------------|---|----------------|---|");\r
829 for (i = 0; i < SectorsCnt; i++) {\r
43534cba 830 PrintAndLog("|%03d| %012" PRIx64 " | %d | %012" PRIx64 " | %d |", i,\r
9ca155ba
M
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
7906cb41 834\r
adf023ff 835 // transfer keys to the emulator memory\r
8556b852
M
836 if (transferToEml) {\r
837 for (i = 0; i < SectorsCnt; i++) {\r
baeaf579 838 mfEmlGetMem(keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);\r
8556b852 839 if (e_sector[i].foundKey[0])\r
ab8b654e 840 num_to_bytes(e_sector[i].Key[0], 6, keyBlock);\r
8556b852
M
841 if (e_sector[i].foundKey[1])\r
842 num_to_bytes(e_sector[i].Key[1], 6, &keyBlock[10]);\r
baeaf579 843 mfEmlSetMem(keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);\r
7906cb41 844 }\r
adf023ff 845 PrintAndLog("Keys transferred to emulator memory.");\r
8556b852 846 }\r
7906cb41 847\r
21156267 848 // Create dump file\r
26fdb4ab 849 if (createDumpFile) {\r
7906cb41 850 if ((fkeys = fopen("dumpkeys.bin","wb")) == NULL) {\r
aea4d766 851 PrintAndLog("Could not create file dumpkeys.bin");\r
26fdb4ab 852 free(e_sector);\r
853 return 1;\r
854 }\r
baeaf579 855 PrintAndLog("Printing keys to binary file dumpkeys.bin...");\r
856 for(i=0; i<SectorsCnt; i++) {\r
21156267 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
26fdb4ab 864 }\r
baeaf579 865 for(i=0; i<SectorsCnt; i++) {\r
21156267 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
26fdb4ab 873 }\r
874 fclose(fkeys);\r
875 }\r
7906cb41 876\r
9ca155ba
M
877 free(e_sector);\r
878 }\r
9ca155ba
M
879 return 0;\r
880}\r
881\r
c48c4d78 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
7906cb41 891\r
c48c4d78 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
362d2039 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
c48c4d78 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
7906cb41
F
921 }\r
922\r
c48c4d78 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
7906cb41
F
928\r
929\r
362d2039 930 uint16_t iindx = 0;\r
c48c4d78 931 if (ctmp == 'R' || ctmp == 'r') {\r
932 nonce_file_read = true;\r
362d2039 933 iindx = 1;\r
c48c4d78 934 if (!param_gethex(Cmd, 1, trgkey, 12)) {\r
935 know_target_key = true;\r
362d2039 936 iindx = 2;\r
c48c4d78 937 }\r
938 } else if (ctmp == 'T' || ctmp == 't') {\r
939 tests = param_get32ex(Cmd, 1, 100, 10);\r
362d2039 940 iindx = 2;\r
c48c4d78 941 if (!param_gethex(Cmd, 2, trgkey, 12)) {\r
942 know_target_key = true;\r
362d2039 943 iindx = 3;\r
c48c4d78 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
7906cb41 952 if (ctmp != 'A' && ctmp != 'a') {\r
c48c4d78 953 keyType = 1;\r
954 }\r
7906cb41 955\r
c48c4d78 956 if (param_gethex(Cmd, 2, key, 12)) {\r
957 PrintAndLog("Key must include 12 HEX symbols");\r
958 return 1;\r
959 }\r
7906cb41 960\r
c48c4d78 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
362d2039 977 iindx = i;\r
c48c4d78 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
362d2039 984 } else if (param_getlength(Cmd, i) == 2 && ctmp == 'i') {\r
985 iindx = i;\r
c48c4d78 986 } else {\r
362d2039 987 PrintAndLog("Possible options are w , s and/or iX");\r
c48c4d78 988 return 1;\r
989 }\r
990 i++;\r
991 }\r
992 }\r
362d2039 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
c48c4d78 1025\r
7906cb41
F
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
c48c4d78 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
9ca155ba
M
1050int CmdHF14AMfChk(const char *Cmd)\r
1051{\r
90e278d3 1052 if (strlen(Cmd)<3) {\r
275d9e61 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
90e278d3
MHS
1054 PrintAndLog(" * - all sectors");\r
1055 PrintAndLog("card memory - 0 - MINI(320 bytes), 1 - 1K, 2 - 2K, 4 - 4K, <other> - 1K");\r
5594c621 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
90e278d3
MHS
1060 PrintAndLog(" sample: hf mf chk 0 A 1234567890ab keys.dic");\r
1061 PrintAndLog(" hf mf chk *1 ? t");\r
e3c23565 1062 PrintAndLog(" hf mf chk *1 ? d");\r
275d9e61
OM
1063 PrintAndLog(" hf mf chk *1 ? s");\r
1064 PrintAndLog(" hf mf chk *1 ? dss");\r
90e278d3 1065 return 0;\r
7906cb41 1066 }\r
90e278d3 1067\r
aea4d766 1068 FILE * f;\r
b915fda3 1069 char filename[FILE_PATH_SIZE]={0};\r
83613803 1070 char buf[13];\r
aea4d766 1071 uint8_t *keyBlock = NULL, *p;\r
1e11e5d7 1072 uint16_t stKeyBlock = 20;\r
7906cb41 1073\r
9ca155ba
M
1074 int i, res;\r
1075 int keycnt = 0;\r
1076 char ctmp = 0x00;\r
55b700a0 1077 int clen = 0;\r
9ca155ba 1078 uint8_t blockNo = 0;\r
275d9e61 1079 uint8_t SectorsCnt = 0;\r
9ca155ba 1080 uint8_t keyType = 0;\r
9ca155ba 1081 uint64_t key64 = 0;\r
5594c621 1082 // timeout in units. (ms * 106)/10 or us*0.0106\r
1083 uint8_t btimeout14a = MF_CHKKEYS_DEFTIMEOUT; // fast by default\r
275d9e61 1084 bool param3InUse = false;\r
7906cb41 1085\r
5594c621 1086 bool transferToEml = 0;\r
1087 bool createDumpFile = 0;\r
275d9e61
OM
1088 \r
1089 sector_t *e_sector = NULL;\r
9ca155ba 1090\r
aea4d766 1091 keyBlock = calloc(stKeyBlock, 6);\r
1092 if (keyBlock == NULL) return 1;\r
1093\r
275d9e61
OM
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
0c12504a 1097 }\r
7906cb41 1098\r
aea4d766 1099 if (param_getchar(Cmd, 0)=='*') {\r
adf023ff 1100 SectorsCnt = ParamCardSizeSectors(param_getchar(Cmd + 1, 0));\r
aea4d766 1101 }\r
1102 else\r
1103 blockNo = param_get8(Cmd, 0);\r
7906cb41 1104\r
9ca155ba 1105 ctmp = param_getchar(Cmd, 1);\r
55b700a0 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
7906cb41 1124\r
5594c621 1125 parseParamTDS(Cmd, 2, &transferToEml, &createDumpFile, &btimeout14a);\r
275d9e61 1126 \r
5594c621 1127 param3InUse = transferToEml | createDumpFile | (btimeout14a != MF_CHKKEYS_DEFTIMEOUT);\r
7906cb41 1128\r
5594c621 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
275d9e61 1132 for (i = param3InUse; param_getchar(Cmd, 2 + i); i++) {\r
aea4d766 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
baeaf579 1143 PrintAndLog("chk key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,\r
aea4d766 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
874572d4 1149 if ( param_getstr(Cmd, 2 + i, filename, sizeof(filename)) >= FILE_PATH_SIZE ) {\r
aea4d766 1150 PrintAndLog("File name too long");\r
1151 free(keyBlock);\r
1152 return 2;\r
1153 }\r
7906cb41 1154\r
aea4d766 1155 if ( (f = fopen( filename , "r")) ) {\r
0c12504a 1156 while( fgets(buf, sizeof(buf), f) ){\r
99a71a0d 1157 if (strlen(buf) < 12 || buf[11] == '\n')\r
1158 continue;\r
7906cb41 1159\r
99a71a0d 1160 while (fgetc(f) != '\n' && !feof(f)) ; //goto next line\r
7906cb41 1161\r
9492e0b0 1162 if( buf[0]=='#' ) continue; //The line start with # is comment, skip\r
9ca155ba 1163\r
3ded0f97 1164 if (!isxdigit((unsigned char)buf[0])){\r
99a71a0d 1165 PrintAndLog("File content error. '%s' must include 12 HEX symbols",buf);\r
aea4d766 1166 continue;\r
1167 }\r
7906cb41 1168\r
99a71a0d 1169 buf[12] = 0;\r
aea4d766 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
4c16ae80 1176 fclose(f);\r
aea4d766 1177 return 2;\r
1178 }\r
1179 keyBlock = p;\r
1180 }\r
1181 memset(keyBlock + 6 * keycnt, 0, 6);\r
99a71a0d 1182 num_to_bytes(strtoll(buf, NULL, 16), 6, keyBlock + 6*keycnt);\r
43534cba 1183 PrintAndLog("chk custom key[%2d] %012" PRIx64 , keycnt, bytes_to_num(keyBlock + 6*keycnt, 6));\r
aea4d766 1184 keycnt++;\r
0c12504a 1185 memset(buf, 0, sizeof(buf));\r
aea4d766 1186 }\r
90e278d3 1187 fclose(f);\r
aea4d766 1188 } else {\r
1189 PrintAndLog("File: %s: not found or locked.", filename);\r
1190 free(keyBlock);\r
1191 return 1;\r
7906cb41 1192\r
aea4d766 1193 }\r
9ca155ba 1194 }\r
9ca155ba 1195 }\r
7906cb41 1196\r
275d9e61 1197 // fill with default keys\r
9ca155ba 1198 if (keycnt == 0) {\r
baeaf579 1199 PrintAndLog("No key specified, trying default keys");\r
0c12504a 1200 for (;keycnt < defaultKeysSize; keycnt++)\r
baeaf579 1201 PrintAndLog("chk default key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,\r
79db03ef 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
7906cb41 1205\r
79db03ef 1206 // initialize storage for found keys\r
275d9e61 1207 e_sector = calloc(SectorsCnt, sizeof(sector_t));\r
44964fd1 1208 if (e_sector == NULL) {\r
1209 free(keyBlock);\r
1210 return 1;\r
1211 }\r
275d9e61 1212 for (uint8_t keyAB = 0; keyAB < 2; keyAB++) {\r
79db03ef 1213 for (uint16_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) {\r
275d9e61
OM
1214 e_sector[sectorNo].Key[keyAB] = 0xffffffffffff;\r
1215 e_sector[sectorNo].foundKey[keyAB] = 0;\r
79db03ef 1216 }\r
9ca155ba 1217 }\r
275d9e61
OM
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
5594c621 1228 res = mfCheckKeysSec(SectorsCnt, keyType, btimeout14a, true, size, &keyBlock[6 * c], e_sector); // timeout is (ms * 106)/10 or us*0.0106\r
7906cb41 1229\r
275d9e61
OM
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
9492e0b0 1245 for (uint32_t c = 0; c < keycnt; c+=max_keys) {\r
275d9e61
OM
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
baeaf579 1250 if (res != 1) {\r
aea4d766 1251 if (!res) {\r
275d9e61
OM
1252 PrintAndLog("Found valid key:[%d:%c]%012" PRIx64, blockNo, (keyAB & 0x01)?'B':'A', key64);\r
1253 foundAKey = true;\r
7906cb41 1254 }\r
aea4d766 1255 } else {\r
1256 PrintAndLog("Command execute timeout");\r
1257 }\r
1258 }\r
275d9e61 1259 } while(--keyAB > 0);\r
9ca155ba 1260 }\r
275d9e61
OM
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
79db03ef 1280 if (transferToEml) {\r
1281 uint8_t block[16];\r
1282 for (uint16_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) {\r
275d9e61 1283 if (e_sector[sectorNo].foundKey[0] || e_sector[sectorNo].foundKey[1]) {\r
79db03ef 1284 mfEmlGetMem(block, FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 1);\r
1285 for (uint16_t t = 0; t < 2; t++) {\r
275d9e61
OM
1286 if (e_sector[sectorNo].foundKey[t]) {\r
1287 num_to_bytes(e_sector[sectorNo].Key[t], 6, block + t * 10);\r
79db03ef 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
aea4d766 1296 if (createDumpFile) {\r
79db03ef 1297 FILE *fkeys = fopen("dumpkeys.bin","wb");\r
7906cb41 1298 if (fkeys == NULL) {\r
aea4d766 1299 PrintAndLog("Could not create file dumpkeys.bin");\r
275d9e61 1300 free(e_sector);\r
79db03ef 1301 free(keyBlock);\r
aea4d766 1302 return 1;\r
1303 }\r
275d9e61
OM
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
aea4d766 1310 }\r
1311 fclose(fkeys);\r
79db03ef 1312 PrintAndLog("Found keys have been dumped to file dumpkeys.bin. 0xffffffffffff has been inserted for unknown keys.");\r
aea4d766 1313 }\r
79db03ef 1314\r
275d9e61 1315 free(e_sector);\r
79db03ef 1316 free(keyBlock);\r
3fe4ff4f 1317 PrintAndLog("");\r
79db03ef 1318 return 0;\r
9ca155ba
M
1319}\r
1320\r
5b5489ba 1321void readerAttack(nonces_t ar_resp[], bool setEmulatorMem, bool doStandardAttack) {\r
3d542a3d 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
bbd11876 1324 uint64_t key = 0;\r
1325 typedef struct {\r
1326 uint64_t keyA;\r
bbd11876 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
76ef5273 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
5b5489ba 1340 if (doStandardAttack && mfkey32(ar_resp[i], &key)) {\r
76ef5273 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
bbd11876 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
7779d73c 1360 } else if (mfkey32_moebius(ar_resp[i+ATTACK_KEY_COUNT], &key)) {\r
5b5489ba
MF
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
43534cba 1364 PrintAndLog("M-Found Key%s for sector %02d: [%012" PRIx64 "]"\r
5b5489ba
MF
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
bbd11876 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
bbd11876 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
7906cb41 1405\r
bbd11876 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
7906cb41 1409 SendCommand(&c);\r
bbd11876 1410 }\r
1411 }\r
1412 }\r
ef3f88bc 1413 /*\r
1414 //un-comment to use as well moebius attack\r
bbd11876 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
ef3f88bc 1421 }*/\r
bbd11876 1422}\r
1423\r
a8561e35 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
c872d8c1 1426 PrintAndLog("options:");\r
a8561e35 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
c872d8c1 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
76ef5273 1433 PrintAndLog(" e (Optional) set keys found from 'reader attack' to emulator memory (implies x and i)");\r
73ab92d1 1434 PrintAndLog(" f (Optional) get UIDs to use for 'reader attack' from file 'f <filename.txt>' (implies x and i)");\r
5b5489ba 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
c872d8c1 1436 PrintAndLog("samples:");\r
1437 PrintAndLog(" hf mf sim u 0a0a0a0a");\r
a8561e35 1438 PrintAndLog(" hf mf sim *4");\r
c872d8c1 1439 PrintAndLog(" hf mf sim u 11223344556677");\r
76ef5273 1440 PrintAndLog(" hf mf sim f uids.txt");\r
1441 PrintAndLog(" hf mf sim u 0a0a0a0a e");\r
7906cb41 1442\r
c872d8c1 1443 return 0;\r
1444}\r
1445\r
a8561e35 1446int CmdHF14AMfSim(const char *Cmd) {\r
73ab92d1 1447 UsbCommand resp;\r
a8561e35 1448 uint8_t uid[7] = {0};\r
d2f487af 1449 uint8_t exitAfterNReads = 0;\r
1450 uint8_t flags = 0;\r
c872d8c1 1451 int uidlen = 0;\r
c872d8c1 1452 bool setEmulatorMem = false;\r
bbd11876 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
bbd11876 1459\r
1460 uint8_t cmdp = 0;\r
1461 bool errors = false;\r
a8561e35 1462 uint8_t cardsize = '1';\r
bbd11876 1463\r
1464 while(param_getchar(Cmd, cmdp) != 0x00) {\r
1465 switch(param_getchar(Cmd, cmdp)) {\r
a8561e35 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
bbd11876 1477 case 'e':\r
1478 case 'E':\r
1479 setEmulatorMem = true;\r
76ef5273 1480 //implies x and i\r
1481 flags |= FLAG_INTERACTIVE;\r
1482 flags |= FLAG_NR_AR_ATTACK;\r
bbd11876 1483 cmdp++;\r
1484 break;\r
1485 case 'f':\r
1486 case 'F':\r
874572d4 1487 len = param_getstr(Cmd, cmdp+1, filename, sizeof(filename));\r
bbd11876 1488 if (len < 1) {\r
1489 PrintAndLog("error no filename found");\r
1490 return 0;\r
1491 }\r
1492 attackFromFile = true;\r
76ef5273 1493 //implies x and i\r
1494 flags |= FLAG_INTERACTIVE;\r
1495 flags |= FLAG_NR_AR_ATTACK;\r
1496 cmdp += 2;\r
bbd11876 1497 break;\r
1498 case 'h':\r
1499 case 'H':\r
a8561e35 1500 return usage_hf14_mfsim();\r
bbd11876 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
a8561e35 1508 exitAfterNReads = param_get8(Cmd, cmdp+1);\r
bbd11876 1509 cmdp += 2;\r
1510 break;\r
f9c1dcd9
MF
1511 case 'r':\r
1512 case 'R':\r
1513 flags |= FLAG_RANDOM_NONCE;\r
1514 cmdp++;\r
1515 break;\r
bbd11876 1516 case 'u':\r
1517 case 'U':\r
1518 param_gethex_ex(Cmd, cmdp+1, uid, &uidlen);\r
1519 switch(uidlen) {\r
bbd11876 1520 case 14: flags = FLAG_7B_UID_IN_DATA; break;\r
1521 case 8: flags = FLAG_4B_UID_IN_DATA; break;\r
a8561e35 1522 default: return usage_hf14_mfsim();\r
bbd11876 1523 }\r
76ef5273 1524 cmdp += 2;\r
bbd11876 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
d2f487af 1535 }\r
bbd11876 1536 if(errors) break;\r
d2f487af 1537 }\r
bbd11876 1538 //Validations\r
a8561e35 1539 if(errors) return usage_hf14_mfsim();\r
c872d8c1 1540\r
bbd11876 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
73ab92d1 1550 PrintAndLog("Loading file and simulating. Press keyboard to abort");\r
1551 while(!feof(f) && !ukbhit()){\r
bbd11876 1552 memset(buf, 0, sizeof(buf));\r
91f4d531 1553 memset(uid, 0, sizeof(uid));\r
d2f487af 1554\r
7906cb41 1555 if (fgets(buf, sizeof(buf), f) == NULL) {\r
bbd11876 1556 if (count > 0) break;\r
7906cb41 1557\r
bbd11876 1558 PrintAndLog("File reading error.");\r
1559 fclose(f);\r
1560 return 2;\r
1561 }\r
91f4d531 1562 if(!strlen(buf) && feof(f)) break;\r
73ab92d1 1563\r
91f4d531 1564 uidlen = strlen(buf)-1;\r
73ab92d1 1565 switch(uidlen) {\r
91f4d531 1566 case 14: flags |= FLAG_7B_UID_IN_DATA; break;\r
1567 case 8: flags |= FLAG_4B_UID_IN_DATA; break;\r
7906cb41 1568 default:\r
91f4d531 1569 PrintAndLog("uid in file wrong length at %d (length: %d) [%s]",count, uidlen, buf);\r
73ab92d1 1570 fclose(f);\r
1571 return 2;\r
bbd11876 1572 }\r
73ab92d1 1573\r
bbd11876 1574 for (uint8_t i = 0; i < uidlen; i += 2) {\r
91f4d531 1575 sscanf(&buf[i], "%02x", (unsigned int *)&uid[i / 2]);\r
bbd11876 1576 }\r
7906cb41 1577\r
a8561e35 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
bbd11876 1587\r
a8561e35 1588 UsbCommand c = {CMD_SIMULATE_MIFARE_CARD, {flags, exitAfterNReads, cardsize}};\r
bbd11876 1589 memcpy(c.d.asBytes, uid, sizeof(uid));\r
1590 clearCommandBuffer();\r
1591 SendCommand(&c);\r
c872d8c1 1592\r
a8561e35 1593 while (! WaitForResponseTimeout(CMD_ACK,&resp,1500)) {\r
73ab92d1 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
5b5489ba
MF
1600 // We can skip the standard attack if we have RANDOM_NONCE set.\r
1601 readerAttack(ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE));\r
76ef5273 1602 if ((bool)resp.arg[1]) {\r
73ab92d1 1603 PrintAndLog("Device button pressed - quitting");\r
1604 fclose(f);\r
1605 return 4;\r
bbd11876 1606 }\r
bbd11876 1607 count++;\r
1608 }\r
1609 fclose(f);\r
d2f487af 1610\r
a8561e35 1611 } else { //not from file\r
d2f487af 1612\r
a8561e35 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
bbd11876 1624 memcpy(c.d.asBytes, uid, sizeof(uid));\r
1625 clearCommandBuffer();\r
1626 SendCommand(&c);\r
d2f487af 1627\r
bbd11876 1628 if(flags & FLAG_INTERACTIVE) {\r
1629 PrintAndLog("Press pm3-button to abort simulation");\r
a8561e35 1630 while(! WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {\r
bbd11876 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
79dcb9e0 1633 }\r
bbd11876 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
5b5489ba
MF
1638 // We can skip the standard attack if we have RANDOM_NONCE set.\r
1639 readerAttack(ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE));\r
79dcb9e0 1640 }\r
79dcb9e0 1641 }\r
baeaf579 1642 }\r
bbd11876 1643\r
baeaf579 1644 return 0;\r
9ca155ba
M
1645}\r
1646\r
1647int CmdHF14AMfDbg(const char *Cmd)\r
1648{\r
8556b852
M
1649 int dbgMode = param_get32ex(Cmd, 0, 0, 10);\r
1650 if (dbgMode > 4) {\r
baeaf579 1651 PrintAndLog("Max debug mode parameter is 4 \n");\r
8556b852
M
1652 }\r
1653\r
1654 if (strlen(Cmd) < 1 || !param_getchar(Cmd, 0) || dbgMode > 4) {\r
9ca155ba
M
1655 PrintAndLog("Usage: hf mf dbg <debug level>");\r
1656 PrintAndLog(" 0 - no debug messages");\r
1657 PrintAndLog(" 1 - error messages");\r
b03c0f2d 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
9ca155ba 1662 return 0;\r
7906cb41 1663 }\r
9ca155ba 1664\r
8556b852
M
1665 UsbCommand c = {CMD_MIFARE_SET_DBGMODE, {dbgMode, 0, 0}};\r
1666 SendCommand(&c);\r
1667\r
9ca155ba
M
1668 return 0;\r
1669}\r
1670\r
1671int CmdHF14AMfEGet(const char *Cmd)\r
1672{\r
8556b852 1673 uint8_t blockNo = 0;\r
5ee70129 1674 uint8_t data[16] = {0x00};\r
8556b852
M
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
7906cb41
F
1680 }\r
1681\r
8556b852 1682 blockNo = param_get8(Cmd, 0);\r
8556b852
M
1683\r
1684 PrintAndLog(" ");\r
baeaf579 1685 if (!mfEmlGetMem(data, blockNo, 1)) {\r
1686 PrintAndLog("data[%3d]:%s", blockNo, sprint_hex(data, 16));\r
8556b852
M
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
7906cb41 1700 }\r
8556b852
M
1701\r
1702 UsbCommand c = {CMD_MIFARE_EML_MEMCLR, {0, 0, 0}};\r
1703 SendCommand(&c);\r
9ca155ba
M
1704 return 0;\r
1705}\r
1706\r
baeaf579 1707\r
9ca155ba
M
1708int CmdHF14AMfESet(const char *Cmd)\r
1709{\r
8556b852
M
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
7906cb41
F
1719 }\r
1720\r
8556b852 1721 blockNo = param_get8(Cmd, 0);\r
7906cb41 1722\r
8556b852
M
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
7906cb41 1727\r
8556b852 1728 // 1 - blocks count\r
36545f0a 1729 return mfEmlSetMem(memBlock, blockNo, 1);\r
9ca155ba
M
1730}\r
1731\r
baeaf579 1732\r
9ca155ba
M
1733int CmdHF14AMfELoad(const char *Cmd)\r
1734{\r
ab8b654e 1735 FILE * f;\r
b915fda3 1736 char filename[FILE_PATH_SIZE];\r
baeaf579 1737 char *fnameptr = filename;\r
5ee70129 1738 char buf[64] = {0x00};\r
1739 uint8_t buf8[64] = {0x00};\r
b915fda3 1740 int i, len, blockNum, numBlocks;\r
1741 int nameParamNo = 1;\r
7906cb41 1742\r
b915fda3 1743 char ctmp = param_getchar(Cmd, 0);\r
7906cb41 1744\r
b915fda3 1745 if ( ctmp == 'h' || ctmp == 0x00) {\r
ab8b654e 1746 PrintAndLog("It loads emul dump from the file `filename.eml`");\r
b915fda3 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
ab8b654e 1750 PrintAndLog(" sample: hf mf eload filename");\r
b915fda3 1751 PrintAndLog(" hf mf eload 4 filename");\r
ab8b654e 1752 return 0;\r
7906cb41 1753 }\r
ab8b654e 1754\r
b915fda3 1755 switch (ctmp) {\r
1756 case '0' : numBlocks = 5*4; break;\r
7906cb41 1757 case '1' :\r
b915fda3 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
a8561e35 1767 len = param_getstr(Cmd, nameParamNo, filename, sizeof(filename));\r
7906cb41 1768\r
4c16ae80 1769 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;\r
ab8b654e 1770\r
0b14440d 1771 fnameptr += len;\r
ab8b654e 1772\r
7906cb41
F
1773 sprintf(fnameptr, ".eml");\r
1774\r
ab8b654e
M
1775 // open file\r
1776 f = fopen(filename, "r");\r
1777 if (f == NULL) {\r
3fe4ff4f 1778 PrintAndLog("File %s not found or locked", filename);\r
ab8b654e
M
1779 return 1;\r
1780 }\r
7906cb41 1781\r
ab8b654e
M
1782 blockNum = 0;\r
1783 while(!feof(f)){\r
1784 memset(buf, 0, sizeof(buf));\r
7906cb41 1785\r
759c16b3 1786 if (fgets(buf, sizeof(buf), f) == NULL) {\r
7906cb41 1787\r
b915fda3 1788 if (blockNum >= numBlocks) break;\r
7906cb41 1789\r
d2f487af 1790 PrintAndLog("File reading error.");\r
97d582a6 1791 fclose(f);\r
759c16b3 1792 return 2;\r
baeaf579 1793 }\r
7906cb41 1794\r
ab8b654e 1795 if (strlen(buf) < 32){\r
aea4d766 1796 if(strlen(buf) && feof(f))\r
1797 break;\r
ab8b654e 1798 PrintAndLog("File content error. Block data must include 32 HEX symbols");\r
97d582a6 1799 fclose(f);\r
ab8b654e
M
1800 return 2;\r
1801 }\r
7906cb41 1802\r
baeaf579 1803 for (i = 0; i < 32; i += 2) {\r
1804 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);\r
baeaf579 1805 }\r
7906cb41 1806\r
ab8b654e 1807 if (mfEmlSetMem(buf8, blockNum, 1)) {\r
baeaf579 1808 PrintAndLog("Cant set emul block: %3d", blockNum);\r
97d582a6 1809 fclose(f);\r
ab8b654e
M
1810 return 3;\r
1811 }\r
5ee70129 1812 printf(".");\r
ab8b654e 1813 blockNum++;\r
7906cb41 1814\r
b915fda3 1815 if (blockNum >= numBlocks) break;\r
ab8b654e
M
1816 }\r
1817 fclose(f);\r
5ee70129 1818 printf("\n");\r
7906cb41 1819\r
b915fda3 1820 if ((blockNum != numBlocks)) {\r
1821 PrintAndLog("File content error. Got %d must be %d blocks.",blockNum, numBlocks);\r
ab8b654e
M
1822 return 4;\r
1823 }\r
d2f487af 1824 PrintAndLog("Loaded %d blocks from file: %s", blockNum, filename);\r
baeaf579 1825 return 0;\r
9ca155ba
M
1826}\r
1827\r
baeaf579 1828\r
9ca155ba
M
1829int CmdHF14AMfESave(const char *Cmd)\r
1830{\r
ab8b654e 1831 FILE * f;\r
b915fda3 1832 char filename[FILE_PATH_SIZE];\r
ab8b654e
M
1833 char * fnameptr = filename;\r
1834 uint8_t buf[64];\r
b915fda3 1835 int i, j, len, numBlocks;\r
1836 int nameParamNo = 1;\r
7906cb41 1837\r
ab8b654e
M
1838 memset(filename, 0, sizeof(filename));\r
1839 memset(buf, 0, sizeof(buf));\r
1840\r
b915fda3 1841 char ctmp = param_getchar(Cmd, 0);\r
7906cb41 1842\r
b915fda3 1843 if ( ctmp == 'h' || ctmp == 'H') {\r
ab8b654e 1844 PrintAndLog("It saves emul dump into the file `filename.eml` or `cardID.eml`");\r
b915fda3 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
ab8b654e 1848 PrintAndLog(" sample: hf mf esave ");\r
b915fda3 1849 PrintAndLog(" hf mf esave 4");\r
1850 PrintAndLog(" hf mf esave 4 filename");\r
ab8b654e 1851 return 0;\r
7906cb41 1852 }\r
ab8b654e 1853\r
b915fda3 1854 switch (ctmp) {\r
1855 case '0' : numBlocks = 5*4; break;\r
7906cb41 1856 case '1' :\r
b915fda3 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
874572d4 1866 len = param_getstr(Cmd,nameParamNo,filename,sizeof(filename));\r
7906cb41 1867\r
4c16ae80 1868 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;\r
7906cb41 1869\r
b915fda3 1870 // user supplied filename?\r
ab8b654e 1871 if (len < 1) {\r
b915fda3 1872 // get filename (UID from memory)\r
ab8b654e 1873 if (mfEmlGetMem(buf, 0, 1)) {\r
b915fda3 1874 PrintAndLog("Can\'t get UID from block: %d", 0);\r
0b14440d
PL
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
ab8b654e 1881 }\r
ab8b654e 1882 } else {\r
0b14440d 1883 fnameptr += len;\r
ab8b654e
M
1884 }\r
1885\r
b915fda3 1886 // add file extension\r
7906cb41
F
1887 sprintf(fnameptr, ".eml");\r
1888\r
ab8b654e
M
1889 // open file\r
1890 f = fopen(filename, "w+");\r
1891\r
b915fda3 1892 if ( !f ) {\r
1893 PrintAndLog("Can't open file %s ", filename);\r
1894 return 1;\r
1895 }\r
7906cb41 1896\r
ab8b654e 1897 // put hex\r
b915fda3 1898 for (i = 0; i < numBlocks; i++) {\r
ab8b654e
M
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
7906cb41 1904 fprintf(f, "%02X", buf[j]);\r
ab8b654e
M
1905 fprintf(f,"\n");\r
1906 }\r
1907 fclose(f);\r
7906cb41 1908\r
b915fda3 1909 PrintAndLog("Saved %d blocks to file: %s", numBlocks, filename);\r
7906cb41 1910\r
9ca155ba
M
1911 return 0;\r
1912}\r
1913\r
baeaf579 1914\r
26fdb4ab 1915int CmdHF14AMfECFill(const char *Cmd)\r
1916{\r
8556b852 1917 uint8_t keyType = 0;\r
baeaf579 1918 uint8_t numSectors = 16;\r
7906cb41 1919\r
8556b852 1920 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {\r
baeaf579 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
8556b852 1928 return 0;\r
7906cb41 1929 }\r
8556b852
M
1930\r
1931 char ctmp = param_getchar(Cmd, 0);\r
baeaf579 1932 if (ctmp != 'a' && ctmp != 'A' && ctmp != 'b' && ctmp != 'B') {\r
8556b852
M
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
baeaf579 1938 ctmp = param_getchar(Cmd, 1);\r
1939 switch (ctmp) {\r
1940 case '0' : numSectors = 5; break;\r
7906cb41 1941 case '1' :\r
baeaf579 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
7906cb41 1946 }\r
baeaf579 1947\r
4e002980 1948 printf("--params: numSectors: %d, keyType:%d\n", numSectors, keyType);\r
baeaf579 1949 UsbCommand c = {CMD_MIFARE_EML_CARDLOAD, {numSectors, keyType, 0}};\r
1950 SendCommand(&c);\r
1951 return 0;\r
8556b852
M
1952}\r
1953\r
26fdb4ab 1954int CmdHF14AMfEKeyPrn(const char *Cmd)\r
1955{\r
baeaf579 1956 int i;\r
b915fda3 1957 uint8_t numSectors;\r
8556b852
M
1958 uint8_t data[16];\r
1959 uint64_t keyA, keyB;\r
7906cb41 1960\r
b915fda3 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
7906cb41 1968 }\r
b915fda3 1969\r
1970 char cmdp = param_getchar(Cmd, 0);\r
7906cb41 1971\r
b915fda3 1972 switch (cmdp) {\r
1973 case '0' : numSectors = 5; break;\r
7906cb41 1974 case '1' :\r
b915fda3 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
7906cb41
F
1979 }\r
1980\r
8556b852
M
1981 PrintAndLog("|---|----------------|----------------|");\r
1982 PrintAndLog("|sec|key A |key B |");\r
1983 PrintAndLog("|---|----------------|----------------|");\r
b915fda3 1984 for (i = 0; i < numSectors; i++) {\r
baeaf579 1985 if (mfEmlGetMem(data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) {\r
1986 PrintAndLog("error get block %d", FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1);\r
8556b852
M
1987 break;\r
1988 }\r
1989 keyA = bytes_to_num(data, 6);\r
1990 keyB = bytes_to_num(data + 10, 6);\r
43534cba 1991 PrintAndLog("|%03d| %012" PRIx64 " | %012" PRIx64 " |", i, keyA, keyB);\r
8556b852
M
1992 }\r
1993 PrintAndLog("|---|----------------|----------------|");\r
7906cb41 1994\r
8556b852
M
1995 return 0;\r
1996}\r
1997\r
0675f200
M
1998int CmdHF14AMfCSetUID(const char *Cmd)\r
1999{\r
3fe4ff4f 2000 uint8_t uid[8] = {0x00};\r
2001 uint8_t oldUid[8] = {0x00};\r
3bba7dea
JH
2002 uint8_t atqa[2] = {0x00};\r
2003 uint8_t sak[1] = {0x00};\r
3a05a1e7 2004 uint8_t atqaPresent = 0;\r
0675f200 2005 int res;\r
3bba7dea 2006\r
3a05a1e7
OM
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
3bba7dea 2049 PrintAndLog("sample: hf mf csetuid 01020304");\r
3a05a1e7 2050 PrintAndLog("sample: hf mf csetuid 01020304 0004 08");\r
3bba7dea 2051 PrintAndLog("Set UID, ATQA, and SAK for magic Chinese card (only works with such cards)");\r
0675f200 2052 return 0;\r
3bba7dea 2053 }\r
0675f200 2054\r
3a05a1e7
OM
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
0675f200 2058 }\r
3bba7dea 2059\r
3a05a1e7
OM
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
3a05a1e7
OM
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
6148817a 2079 PrintAndLog("Usage: hf mf cwipe [card size] [w] [f]");\r
2080 PrintAndLog("sample: hf mf cwipe 1 w f");\r
3a05a1e7
OM
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
3bba7dea
JH
2085 }\r
2086\r
3a05a1e7
OM
2087 gen = mfCIdentify();\r
2088 if ((gen != 1) && (gen != 2)) \r
2089 return 1;\r
2090 \r
adf023ff 2091 numBlocks = ParamCardSizeBlocks(param_getchar(Cmd, 0));\r
3a05a1e7
OM
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
3bba7dea 2098 wipeCard = 1;\r
3a05a1e7
OM
2099 break;\r
2100 case 'f':\r
2101 case 'F':\r
2102 fillCard = 1;\r
2103 break;\r
2104 default:\r
2105 break;\r
3bba7dea 2106 }\r
3a05a1e7 2107 cmdp++;\r
3bba7dea 2108 }\r
0675f200 2109\r
3a05a1e7 2110 if (!wipeCard && !fillCard) \r
2ce43a28 2111 wipeCard = true;\r
0675f200 2112\r
3a05a1e7
OM
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
0675f200 2119 }\r
3a05a1e7
OM
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
7906cb41 2125\r
3a05a1e7
OM
2126 if (res) {\r
2127 PrintAndLog("Can't wipe. error=%d", res);\r
2128 return 1;\r
2129 }\r
2130 PrintAndLog("OK");\r
0675f200
M
2131 return 0;\r
2132}\r
2133\r
2134int CmdHF14AMfCSetBlk(const char *Cmd)\r
2135{\r
5ee70129 2136 uint8_t memBlock[16] = {0x00};\r
f774db95 2137 uint8_t blockNo = 0;\r
7cb8516c 2138 bool wipeCard = false;\r
7906cb41 2139 int res, gen = 0;\r
f774db95
M
2140\r
2141 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {\r
664f6586 2142 PrintAndLog("Usage: hf mf csetblk <block number> <block data (32 hex symbols)> [w]");\r
f774db95 2143 PrintAndLog("sample: hf mf csetblk 1 01020304050607080910111213141516");\r
664f6586 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
f774db95 2146 return 0;\r
7906cb41
F
2147 }\r
2148\r
2149 gen = mfCIdentify();\r
3a05a1e7
OM
2150 if ((gen != 1) && (gen != 2)) \r
2151 return 1;\r
f774db95
M
2152\r
2153 blockNo = param_get8(Cmd, 0);\r
f774db95
M
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
664f6586 2160 char ctmp = param_getchar(Cmd, 2);\r
2161 wipeCard = (ctmp == 'w' || ctmp == 'W');\r
baeaf579 2162 PrintAndLog("--block number:%2d data:%s", blockNo, sprint_hex(memBlock, 16));\r
f774db95 2163\r
7906cb41
F
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
f774db95 2172 if (res) {\r
664f6586 2173 PrintAndLog("Can't write block. error=%d", res);\r
2174 return 1;\r
2175 }\r
0675f200
M
2176 return 0;\r
2177}\r
2178\r
baeaf579 2179\r
0675f200
M
2180int CmdHF14AMfCLoad(const char *Cmd)\r
2181{\r
208a0166 2182 FILE * f;\r
b915fda3 2183 char filename[FILE_PATH_SIZE] = {0x00};\r
208a0166 2184 char * fnameptr = filename;\r
7906cb41
F
2185 char buf[256] = {0x00};\r
2186 uint8_t buf8[256] = {0x00};\r
208a0166 2187 uint8_t fillFromEmulator = 0;\r
7906cb41
F
2188 int i, len, blockNum, flags = 0, gen = 0, numblock = 64;\r
2189\r
208a0166 2190 if (param_getchar(Cmd, 0) == 'h' || param_getchar(Cmd, 0)== 0x00) {\r
e3c23565 2191 PrintAndLog("It loads magic Chinese card from the file `filename.eml`");\r
7906cb41
F
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
208a0166 2199 return 0;\r
7906cb41 2200 }\r
208a0166
M
2201\r
2202 char ctmp = param_getchar(Cmd, 0);\r
2203 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;\r
7906cb41
F
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
208a0166 2210 if (fillFromEmulator) {\r
7906cb41 2211 for (blockNum = 0; blockNum < numblock; blockNum += 1) {\r
208a0166
M
2212 if (mfEmlGetMem(buf8, blockNum, 1)) {\r
2213 PrintAndLog("Cant get block: %d", blockNum);\r
2214 return 2;\r
2215 }\r
16a95d76 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
7906cb41 2218 if (blockNum == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD; // Done. Magic Halt and switch off field.\r
208a0166 2219\r
7906cb41
F
2220 if (gen == 2)\r
2221 /* generation 1b magic card */\r
2222 flags |= CSETBLOCK_MAGIC_1B;\r
208a0166
M
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
874572d4 2230 param_getstr(Cmd, 0, filename, sizeof(filename));\r
7906cb41
F
2231\r
2232 len = strlen(filename);\r
4c16ae80 2233 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;\r
208a0166 2234\r
7906cb41 2235 //memcpy(filename, Cmd, len);\r
292fe725 2236 fnameptr += len;\r
208a0166 2237\r
7906cb41
F
2238 sprintf(fnameptr, ".eml");\r
2239\r
208a0166
M
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
7906cb41 2246\r
208a0166 2247 blockNum = 0;\r
208a0166 2248 while(!feof(f)){\r
7906cb41 2249\r
208a0166 2250 memset(buf, 0, sizeof(buf));\r
7906cb41 2251\r
759c16b3 2252 if (fgets(buf, sizeof(buf), f) == NULL) {\r
e6432f05 2253 fclose(f);\r
baeaf579 2254 PrintAndLog("File reading error.");\r
2255 return 2;\r
2256 }\r
208a0166 2257\r
16a95d76 2258 if (strlen(buf) < 32) {\r
208a0166
M
2259 if(strlen(buf) && feof(f))\r
2260 break;\r
2261 PrintAndLog("File content error. Block data must include 32 HEX symbols");\r
e6432f05 2262 fclose(f);\r
208a0166
M
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
16a95d76 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
7906cb41 2270 if (blockNum == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD; // Done. Switch off field.\r
208a0166 2271\r
7906cb41
F
2272 if (gen == 2)\r
2273 /* generation 1b magic card */\r
2274 flags |= CSETBLOCK_MAGIC_1B;\r
208a0166 2275 if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) {\r
baeaf579 2276 PrintAndLog("Can't set magic card block: %d", blockNum);\r
4c16ae80 2277 fclose(f);\r
208a0166
M
2278 return 3;\r
2279 }\r
2280 blockNum++;\r
7906cb41
F
2281\r
2282 if (blockNum >= numblock) break; // magic card type - mifare 1K 64 blocks, mifare 4k 256 blocks\r
208a0166
M
2283 }\r
2284 fclose(f);\r
7906cb41
F
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
208a0166
M
2289 return 4;\r
2290 }\r
2291 PrintAndLog("Loaded from file: %s", filename);\r
2292 return 0;\r
2293 }\r
e3c23565 2294 return 0;\r
0675f200
M
2295}\r
2296\r
545a1f38
M
2297int CmdHF14AMfCGetBlk(const char *Cmd) {\r
2298 uint8_t memBlock[16];\r
2299 uint8_t blockNo = 0;\r
7906cb41 2300 int res, gen = 0;\r
545a1f38
M
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
664f6586 2306 PrintAndLog("Get block data from magic Chinese card (only works with such cards)\n");\r
545a1f38 2307 return 0;\r
7906cb41
F
2308 }\r
2309\r
2310 gen = mfCIdentify();\r
545a1f38
M
2311\r
2312 blockNo = param_get8(Cmd, 0);\r
545a1f38 2313\r
baeaf579 2314 PrintAndLog("--block number:%2d ", blockNo);\r
545a1f38 2315\r
7906cb41
F
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
545a1f38
M
2323 if (res) {\r
2324 PrintAndLog("Can't read block. error=%d", res);\r
2325 return 1;\r
2326 }\r
7906cb41 2327\r
545a1f38 2328 PrintAndLog("block data:%s", sprint_hex(memBlock, 16));\r
ac4ecfe3
OM
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
545a1f38
M
2343 return 0;\r
2344}\r
2345\r
2346int CmdHF14AMfCGetSc(const char *Cmd) {\r
5ee70129 2347 uint8_t memBlock[16] = {0x00};\r
545a1f38 2348 uint8_t sectorNo = 0;\r
7906cb41 2349 int i, res, flags, gen = 0, baseblock = 0, sect_size = 4;\r
545a1f38
M
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
664f6586 2354 PrintAndLog("Get sector data from magic Chinese card (only works with such cards)\n");\r
545a1f38 2355 return 0;\r
7906cb41 2356 }\r
545a1f38
M
2357\r
2358 sectorNo = param_get8(Cmd, 0);\r
7906cb41
F
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
545a1f38
M
2362 return 1;\r
2363 }\r
2364\r
baeaf579 2365 PrintAndLog("--sector number:%d ", sectorNo);\r
545a1f38 2366\r
7906cb41
F
2367 gen = mfCIdentify();\r
2368\r
545a1f38 2369 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;\r
7906cb41
F
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
545a1f38 2379 if (i == 1) flags = 0;\r
7906cb41 2380 if (i == sect_size - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;\r
545a1f38 2381\r
7906cb41
F
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
545a1f38 2387 if (res) {\r
7906cb41 2388 PrintAndLog("Can't read block. %d error=%d", baseblock + i, res);\r
545a1f38
M
2389 return 1;\r
2390 }\r
7906cb41
F
2391\r
2392 PrintAndLog("block %3d data:%s", baseblock + i, sprint_hex(memBlock, 16));\r
daccbcdc
F
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
545a1f38
M
2406 }\r
2407 return 0;\r
2408}\r
2409\r
baeaf579 2410\r
545a1f38
M
2411int CmdHF14AMfCSave(const char *Cmd) {\r
2412\r
2413 FILE * f;\r
b915fda3 2414 char filename[FILE_PATH_SIZE] = {0x00};\r
545a1f38
M
2415 char * fnameptr = filename;\r
2416 uint8_t fillFromEmulator = 0;\r
7906cb41
F
2417 uint8_t buf[256] = {0x00};\r
2418 int i, j, len, flags, gen = 0, numblock = 64;\r
2419\r
b915fda3 2420 // memset(filename, 0, sizeof(filename));\r
2421 // memset(buf, 0, sizeof(buf));\r
545a1f38
M
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
7906cb41 2425 PrintAndLog("or into emulator memory (option `e`). 4K card: (option `4`)");\r
a2d058f3
F
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
545a1f38 2433 return 0;\r
7906cb41 2434 }\r
545a1f38
M
2435\r
2436 char ctmp = param_getchar(Cmd, 0);\r
2437 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;\r
7906cb41
F
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
545a1f38
M
2444\r
2445 if (fillFromEmulator) {\r
2446 // put into emulator\r
2447 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;\r
7906cb41 2448 for (i = 0; i < numblock; i++) {\r
545a1f38 2449 if (i == 1) flags = 0;\r
7906cb41
F
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
545a1f38
M
2456 if (mfCGetBlock(i, buf, flags)) {\r
2457 PrintAndLog("Cant get block: %d", i);\r
2458 break;\r
2459 }\r
7906cb41 2460\r
545a1f38
M
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
874572d4 2468 param_getstr(Cmd, 0, filename, sizeof(filename));\r
7906cb41
F
2469\r
2470 len = strlen(filename);\r
4c16ae80 2471 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;\r
7906cb41
F
2472\r
2473 ctmp = param_getchar(Cmd, 0);\r
2474 if (len < 1 || (ctmp == '4')) {\r
545a1f38 2475 // get filename\r
7906cb41
F
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
545a1f38 2482 PrintAndLog("Cant get block: %d", 0);\r
1d537ad6
PL
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
7906cb41 2488 sprintf(fnameptr, "%02x", buf[j]);\r
545a1f38 2489 }\r
545a1f38 2490 } else {\r
7906cb41 2491 //memcpy(filename, Cmd, len);\r
545a1f38
M
2492 fnameptr += len;\r
2493 }\r
2494\r
7906cb41
F
2495 sprintf(fnameptr, ".eml");\r
2496\r
545a1f38
M
2497 // open file\r
2498 f = fopen(filename, "w+");\r
2499\r
b915fda3 2500 if (f == NULL) {\r
2501 PrintAndLog("File not found or locked.");\r
2502 return 1;\r
2503 }\r
2504\r
545a1f38
M
2505 // put hex\r
2506 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;\r
7906cb41 2507 for (i = 0; i < numblock; i++) {\r
545a1f38 2508 if (i == 1) flags = 0;\r
7906cb41
F
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
545a1f38
M
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
7906cb41 2519 fprintf(f, "%02x", buf[j]);\r
545a1f38
M
2520 fprintf(f,"\n");\r
2521 }\r
2522 fclose(f);\r
7906cb41 2523\r
545a1f38 2524 PrintAndLog("Saved to file: %s", filename);\r
7906cb41 2525\r
545a1f38
M
2526 return 0;\r
2527 }\r
2528}\r
2529\r
baeaf579 2530\r
b62a5a84 2531int CmdHF14AMfSniff(const char *Cmd){\r
3fe4ff4f 2532\r
c948cbde
M
2533 bool wantLogToFile = 0;\r
2534 bool wantDecrypt = 0;\r
eede7162 2535 //bool wantSaveToEml = 0; TODO\r
55acbb2a
M
2536 bool wantSaveToEmlFile = 0;\r
2537\r
7906cb41 2538 //var\r
39864b0b
M
2539 int res = 0;\r
2540 int len = 0;\r
a37725fa 2541 int parlen = 0;\r
39864b0b 2542 int blockLen = 0;\r
39864b0b 2543 int pckNum = 0;\r
f71f4deb 2544 int num = 0;\r
2545 uint8_t uid[7];\r
991f13f2 2546 uint8_t uid_len;\r
5ee70129 2547 uint8_t atqa[2] = {0x00};\r
39864b0b
M
2548 uint8_t sak;\r
2549 bool isTag;\r
f71f4deb 2550 uint8_t *buf = NULL;\r
2551 uint16_t bufsize = 0;\r
2552 uint8_t *bufPtr = NULL;\r
a37725fa 2553 uint8_t parity[16];\r
7906cb41 2554\r
e3c23565 2555 char ctmp = param_getchar(Cmd, 0);\r
2556 if ( ctmp == 'h' || ctmp == 'H' ) {\r
baeaf579 2557 PrintAndLog("It continuously gets data from the field and saves it to: log, emulator, emulator file.");\r
55acbb2a
M
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
3fe4ff4f 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
55acbb2a 2564 PrintAndLog(" sample: hf mf sniff l d e");\r
b62a5a84 2565 return 0;\r
7906cb41
F
2566 }\r
2567\r
55acbb2a 2568 for (int i = 0; i < 4; i++) {\r
e3c23565 2569 ctmp = param_getchar(Cmd, i);\r
55acbb2a
M
2570 if (ctmp == 'l' || ctmp == 'L') wantLogToFile = true;\r
2571 if (ctmp == 'd' || ctmp == 'D') wantDecrypt = true;\r
eede7162 2572 //if (ctmp == 'e' || ctmp == 'E') wantSaveToEml = true; TODO\r
55acbb2a
M
2573 if (ctmp == 'f' || ctmp == 'F') wantSaveToEmlFile = true;\r
2574 }\r
7906cb41 2575\r
39864b0b
M
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
d714d3ef 2582 UsbCommand c = {CMD_MIFARE_SNIFFER, {0, 0, 0}};\r
2583 clearCommandBuffer();\r
2584 SendCommand(&c);\r
b62a5a84 2585\r
39864b0b
M
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
7906cb41 2595\r
f71f4deb 2596 UsbCommand resp;\r
8ec06f5e 2597 if (WaitForResponseTimeoutW(CMD_ACK, &resp, 2000, false)) {\r
902cb3c0 2598 res = resp.arg[0] & 0xff;\r
f71f4deb 2599 uint16_t traceLen = resp.arg[1];\r
2600 len = resp.arg[2];\r
2601\r
4c16ae80 2602 if (res == 0) { // we are done\r
8ec06f5e 2603 break;\r
4c16ae80 2604 }\r
f71f4deb 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
4c16ae80 2608 if (traceLen > bufsize || buf == NULL) {\r
f71f4deb 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
39864b0b 2622 bufPtr = buf;\r
f71f4deb 2623 bufsize = traceLen;\r
2624 memset(buf, 0x00, traceLen);\r
39864b0b 2625 }\r
902cb3c0 2626 memcpy(bufPtr, resp.d.asBytes, len);\r
39864b0b
M
2627 bufPtr += len;\r
2628 pckNum++;\r
2629 }\r
f71f4deb 2630\r
2631 if (res == 2) { // received all data, start displaying\r
39864b0b
M
2632 blockLen = bufPtr - buf;\r
2633 bufPtr = buf;\r
2634 printf(">\n");\r
2635 PrintAndLog("received trace len: %d packages: %d", blockLen, pckNum);\r
6a1f2d82 2636 while (bufPtr - buf < blockLen) {\r
f71f4deb 2637 bufPtr += 6; // skip (void) timing information\r
6a1f2d82 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
a37725fa 2645 parlen = (len - 1) / 8 + 1;\r
6a1f2d82 2646 bufPtr += 2;\r
2647 if ((len == 14) && (bufPtr[0] == 0xff) && (bufPtr[1] == 0xff) && (bufPtr[12] == 0xff) && (bufPtr[13] == 0xff)) {\r
39864b0b
M
2648 memcpy(uid, bufPtr + 2, 7);\r
2649 memcpy(atqa, bufPtr + 2 + 7, 2);\r
991f13f2 2650 uid_len = (atqa[0] & 0xC0) == 0x40 ? 7 : 4;\r
39864b0b 2651 sak = bufPtr[11];\r
7906cb41 2652 PrintAndLog("tag select uid:%s atqa:0x%02x%02x sak:0x%02x",\r
991f13f2 2653 sprint_hex(uid + (7 - uid_len), uid_len),\r
7906cb41
F
2654 atqa[1],\r
2655 atqa[0],\r
991f13f2 2656 sak);\r
d714d3ef 2657 if (wantLogToFile || wantDecrypt) {\r
991f13f2 2658 FillFileNameByUID(logHexFileName, uid + (7 - uid_len), ".log", uid_len);\r
55acbb2a 2659 AddLogCurrentDT(logHexFileName);\r
7906cb41
F
2660 }\r
2661 if (wantDecrypt)\r
3fe4ff4f 2662 mfTraceInit(uid, atqa, sak, wantSaveToEmlFile);\r
39864b0b 2663 } else {\r
a37725fa
OM
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
7906cb41 2672 if (wantLogToFile)\r
3fe4ff4f 2673 AddLogHex(logHexFileName, isTag ? "TAG: ":"RDR: ", bufPtr, len);\r
7906cb41 2674 if (wantDecrypt)\r
a37725fa 2675 mfTraceDecode(bufPtr, len, bufPtr[len], wantSaveToEmlFile);\r
7906cb41 2676 num++;\r
39864b0b
M
2677 }\r
2678 bufPtr += len;\r
a37725fa 2679 bufPtr += parlen; // ignore parity\r
39864b0b 2680 }\r
f71f4deb 2681 pckNum = 0;\r
39864b0b 2682 }\r
3fe4ff4f 2683 } // resp not NULL\r
39864b0b 2684 } // while (true)\r
f71f4deb 2685\r
2686 free(buf);\r
8ec06f5e
OM
2687 \r
2688 msleep(300); // wait for exiting arm side.\r
2689 PrintAndLog("Done.");\r
d714d3ef 2690 return 0;\r
b62a5a84
M
2691}\r
2692\r
1a5a73ab 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
f71f4deb 2700\r
7dadcc95
OM
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
ae3340a0 2706\r
7dadcc95
OM
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
ae3340a0
OM
2720 CLIGetHexWithReturn(1, keyn, &keynlen);\r
2721 CLIGetHexWithReturn(2, key, &keylen);\r
7dadcc95
OM
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
ae3340a0 2734 return MifareAuth4(NULL, keyn, key, true, false, true);\r
7dadcc95
OM
2735}\r
2736\r
fdd9395d
OM
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
26fdb4ab 2932static command_t CommandTable[] =\r
9ca155ba 2933{\r
c48c4d78 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
7dadcc95 2941 {"auth4", CmdHF14AMfAuth4, 0, "ISO14443-4 AES authentication"},\r
c48c4d78 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
a8561e35 2947 {"sim", CmdHF14AMfSim, 0, "Simulate MIFARE card"},\r
2948 {"eclr", CmdHF14AMfEClear, 0, "Clear simulator memory"},\r
c48c4d78 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
3a05a1e7 2955 {"cwipe", CmdHF14AMfCWipe, 0, "Wipe magic Chinese card"},\r
c48c4d78 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
fdd9395d
OM
2963 {"mad", CmdHF14AMfMAD, 0, "Checks and prints MAD"},\r
2964 {"ndef", CmdHFMFNDEF, 0, "Prints NDEF records from card"},\r
c48c4d78 2965 {NULL, NULL, 0, NULL}\r
9ca155ba
M
2966};\r
2967\r
2968int CmdHFMF(const char *Cmd)\r
2969{\r
44964fd1 2970 (void)WaitForResponseTimeout(CMD_ACK,NULL,100);\r
2971 CmdsParse(CommandTable, Cmd);\r
2972 return 0;\r
9ca155ba
M
2973}\r
2974\r
2975int CmdHelp(const char *Cmd)\r
2976{\r
2977 CmdsHelp(CommandTable);\r
2978 return 0;\r
2979}\r
Impressum, Datenschutz