]> git.zerfleddert.de Git - proxmark3-svn/blame - client/cmdhfmf.c
fix compiler warning in cmdhflegic.c (and whitespace fixes) (#826)
[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
a39af1cb 37#define NESTED_SECTOR_RETRY 10 // how often we try mfested() until we give up\r
7cb8516c 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
a39af1cb 68 char cmdp = 0x00;\r
9ca155ba
M
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
a39af1cb 116 char cmdp = 0x00;\r
9ca155ba
M
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
a39af1cb 180 char cmdp = 0x00;\r
9ca155ba
M
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
a39af1cb 221\r
daccbcdc 222 PrintAndLogEx(NORMAL, "Trailer decoded:");\r
a39af1cb 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
a39af1cb 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 373 for (tries = 0; tries < 3; tries++) {\r
a39af1cb 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
a39af1cb 390 } else { // data block. Check if it can be read with key A or key B\r
40c6a02b 391 uint8_t data_area = sectorNo<32?blockNo:blockNo/5;\r
a39af1cb 392 if ((rights[sectorNo][data_area] == 0x03) || (rights[sectorNo][data_area] == 0x05)) { // only key B would work\r
40c6a02b 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
a39af1cb 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
a39af1cb 408 } else { // key A would work\r
40c6a02b 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
a39af1cb 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
a39af1cb 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
a39af1cb 533 if (blockNo == NumBlocksPerSector(sectorNo) - 1) { // sector trailer\r
baeaf579 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
a39af1cb 576\r
0c86cb01
OM
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
a39af1cb 584\r
0c86cb01
OM
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
a39af1cb 609\r
adf023ff 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
a39af1cb 650\r
adf023ff
OM
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
a39af1cb 657 PrintAndLog("--nested. sectors:%2d, block no:*, eml:%c, dmp=%c checktimeout=%d us",\r
0c86cb01 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 683 // one sector nested\r
a39af1cb 684 if (cmdp == 'o') {\r
adf023ff 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
a39af1cb 700 PrintAndLog("--nested. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us",\r
0c86cb01 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
a39af1cb 724 if (trgBlockNo < 32*4) { // 4 block sector\r
32e6891a 725 sectortrailer = trgBlockNo | 0x03;\r
a39af1cb 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
a39af1cb 756\r
adf023ff
OM
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
a39af1cb 772 }\r
adf023ff
OM
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
a39af1cb 813\r
275d9e61 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
a39af1cb 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
a39af1cb 993\r
362d2039 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
a39af1cb 1023 }\r
362d2039 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 1074 int i, res;\r
a39af1cb 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
a39af1cb 1088\r
275d9e61 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
a39af1cb 1126\r
5594c621 1127 param3InUse = transferToEml | createDumpFile | (btimeout14a != MF_CHKKEYS_DEFTIMEOUT);\r
7906cb41 1128\r
a39af1cb 1129 PrintAndLog("--chk keys. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us",\r
5594c621 1130 SectorsCnt, blockNo, keyType?'B':'A', transferToEml?'y':'n', createDumpFile?'y':'n', ((int)btimeout14a * 10000) / 106);\r
a39af1cb 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
a39af1cb 1145 (keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6);\r
aea4d766 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
a39af1cb 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
a39af1cb 1203 (keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6);\r
79db03ef 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
a39af1cb 1248 res = mfCheckKeys(blockNo, keyAB & 0x01, true, size, &keyBlock[6 * c], &key64);\r
275d9e61 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
a39af1cb 1261\r
275d9e61
OM
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
a39af1cb 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
a39af1cb 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
a39af1cb 1332 uint8_t stSector[ATTACK_KEY_COUNT];\r
bbd11876 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
a39af1cb 1395 uint8_t memBlock[16];\r
bbd11876 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
a39af1cb 1466 case '*':\r
a8561e35 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
a39af1cb 1583 flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): "N/A",\r
a8561e35 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
a39af1cb 1618 flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): "N/A",\r
a8561e35 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
a39af1cb 1954\r
26fdb4ab 1955int CmdHF14AMfEKeyPrn(const char *Cmd)\r
1956{\r
baeaf579 1957 int i;\r
a39af1cb 1958 uint8_t numSectors = 16;\r
8556b852
M
1959 uint8_t data[16];\r
1960 uint64_t keyA, keyB;\r
a39af1cb 1961 bool createDumpFile = false;\r
7906cb41 1962\r
b915fda3 1963 if (param_getchar(Cmd, 0) == 'h') {\r
1964 PrintAndLog("It prints the keys loaded in the emulator memory");\r
a39af1cb 1965 PrintAndLog("Usage: hf mf ekeyprn [card memory] [d]");\r
b915fda3 1966 PrintAndLog(" [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");\r
a39af1cb 1967 PrintAndLog(" [d] : write keys to binary file dumpkeys.bin");\r
b915fda3 1968 PrintAndLog("");\r
1969 PrintAndLog(" sample: hf mf ekeyprn 1");\r
1970 return 0;\r
7906cb41 1971 }\r
b915fda3 1972\r
a39af1cb 1973 uint8_t cmdp = 0;\r
1974 while (param_getchar(Cmd, cmdp) != 0x00) {\r
1975 switch (param_getchar(Cmd, cmdp)) {\r
1976 case '0' : numSectors = 5; break;\r
1977 case '1' :\r
1978 case '\0': numSectors = 16; break;\r
1979 case '2' : numSectors = 32; break;\r
1980 case '4' : numSectors = 40; break;\r
1981 case 'd' : \r
1982 case 'D' : createDumpFile = true; break;\r
1983 }\r
1984 cmdp++;\r
7906cb41
F
1985 }\r
1986\r
8556b852
M
1987 PrintAndLog("|---|----------------|----------------|");\r
1988 PrintAndLog("|sec|key A |key B |");\r
1989 PrintAndLog("|---|----------------|----------------|");\r
b915fda3 1990 for (i = 0; i < numSectors; i++) {\r
baeaf579 1991 if (mfEmlGetMem(data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) {\r
1992 PrintAndLog("error get block %d", FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1);\r
8556b852
M
1993 break;\r
1994 }\r
1995 keyA = bytes_to_num(data, 6);\r
1996 keyB = bytes_to_num(data + 10, 6);\r
43534cba 1997 PrintAndLog("|%03d| %012" PRIx64 " | %012" PRIx64 " |", i, keyA, keyB);\r
8556b852
M
1998 }\r
1999 PrintAndLog("|---|----------------|----------------|");\r
7906cb41 2000\r
a39af1cb 2001 // Create dump file\r
2002 if (createDumpFile) {\r
2003 FILE *fkeys;\r
2004 if ((fkeys = fopen("dumpkeys.bin","wb")) == NULL) {\r
2005 PrintAndLog("Could not create file dumpkeys.bin");\r
2006 return 1;\r
2007 }\r
2008 PrintAndLog("Printing keys to binary file dumpkeys.bin...");\r
2009 for(i = 0; i < numSectors; i++) {\r
2010 if (mfEmlGetMem(data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) {\r
2011 PrintAndLog("error get block %d", FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1);\r
2012 break;\r
2013 }\r
2014 fwrite(data+6, 1, 6, fkeys);\r
2015 }\r
2016 for(i = 0; i < numSectors; i++) {\r
2017 if (mfEmlGetMem(data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) {\r
2018 PrintAndLog("error get block %d", FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1);\r
2019 break;\r
2020 }\r
2021 fwrite(data+10, 1, 6, fkeys);\r
2022 }\r
2023 fclose(fkeys);\r
2024 }\r
2025\r
8556b852
M
2026 return 0;\r
2027}\r
2028\r
a39af1cb 2029\r
0675f200
M
2030int CmdHF14AMfCSetUID(const char *Cmd)\r
2031{\r
3fe4ff4f 2032 uint8_t uid[8] = {0x00};\r
2033 uint8_t oldUid[8] = {0x00};\r
3bba7dea
JH
2034 uint8_t atqa[2] = {0x00};\r
2035 uint8_t sak[1] = {0x00};\r
3a05a1e7 2036 uint8_t atqaPresent = 0;\r
0675f200 2037 int res;\r
3bba7dea 2038\r
3a05a1e7
OM
2039 uint8_t needHelp = 0;\r
2040 char cmdp = 1;\r
a39af1cb 2041\r
3a05a1e7
OM
2042 if (param_getchar(Cmd, 0) && param_gethex(Cmd, 0, uid, 8)) {\r
2043 PrintAndLog("UID must include 8 HEX symbols");\r
2044 return 1;\r
2045 }\r
2046\r
2047 if (param_getlength(Cmd, 1) > 1 && param_getlength(Cmd, 2) > 1) {\r
2048 atqaPresent = 1;\r
2049 cmdp = 3;\r
a39af1cb 2050\r
3a05a1e7
OM
2051 if (param_gethex(Cmd, 1, atqa, 4)) {\r
2052 PrintAndLog("ATQA must include 4 HEX symbols");\r
2053 return 1;\r
2054 }\r
a39af1cb 2055\r
3a05a1e7
OM
2056 if (param_gethex(Cmd, 2, sak, 2)) {\r
2057 PrintAndLog("SAK must include 2 HEX symbols");\r
2058 return 1;\r
2059 }\r
2060 }\r
2061\r
2062 while(param_getchar(Cmd, cmdp) != 0x00)\r
2063 {\r
2064 switch(param_getchar(Cmd, cmdp))\r
2065 {\r
2066 case 'h':\r
2067 case 'H':\r
2068 needHelp = 1;\r
2069 break;\r
2070 default:\r
2071 PrintAndLog("ERROR: Unknown parameter '%c'", param_getchar(Cmd, cmdp));\r
2072 needHelp = 1;\r
2073 break;\r
2074 }\r
2075 cmdp++;\r
2076 }\r
2077\r
2078 if (strlen(Cmd) < 1 || needHelp) {\r
2079 PrintAndLog("");\r
2080 PrintAndLog("Usage: hf mf csetuid <UID 8 hex symbols> [ATQA 4 hex symbols SAK 2 hex symbols]");\r
3bba7dea 2081 PrintAndLog("sample: hf mf csetuid 01020304");\r
3a05a1e7 2082 PrintAndLog("sample: hf mf csetuid 01020304 0004 08");\r
3bba7dea 2083 PrintAndLog("Set UID, ATQA, and SAK for magic Chinese card (only works with such cards)");\r
0675f200 2084 return 0;\r
3bba7dea 2085 }\r
0675f200 2086\r
3a05a1e7
OM
2087 PrintAndLog("uid:%s", sprint_hex(uid, 4));\r
2088 if (atqaPresent) {\r
2089 PrintAndLog("--atqa:%s sak:%02x", sprint_hex(atqa, 2), sak[0]);\r
0675f200 2090 }\r
3bba7dea 2091\r
3a05a1e7
OM
2092 res = mfCSetUID(uid, (atqaPresent)?atqa:NULL, (atqaPresent)?sak:NULL, oldUid);\r
2093 if (res) {\r
2094 PrintAndLog("Can't set UID. Error=%d", res);\r
2095 return 1;\r
2096 }\r
2097\r
2098 PrintAndLog("old UID:%s", sprint_hex(oldUid, 4));\r
2099 PrintAndLog("new UID:%s", sprint_hex(uid, 4));\r
2100 return 0;\r
2101}\r
2102\r
3a05a1e7
OM
2103int CmdHF14AMfCWipe(const char *Cmd)\r
2104{\r
2105 int res, gen = 0;\r
2106 int numBlocks = 16 * 4;\r
2107 bool wipeCard = false;\r
2108 bool fillCard = false;\r
a39af1cb 2109\r
3a05a1e7 2110 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {\r
6148817a 2111 PrintAndLog("Usage: hf mf cwipe [card size] [w] [f]");\r
2112 PrintAndLog("sample: hf mf cwipe 1 w f");\r
3a05a1e7
OM
2113 PrintAndLog("[card size]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K");\r
2114 PrintAndLog("w - Wipe magic Chinese card (only works with gen:1a cards)");\r
2115 PrintAndLog("f - Fill the card with default data and keys (works with gen:1a and gen:1b cards only)");\r
2116 return 0;\r
3bba7dea
JH
2117 }\r
2118\r
3a05a1e7 2119 gen = mfCIdentify();\r
a39af1cb 2120 if ((gen != 1) && (gen != 2))\r
3a05a1e7 2121 return 1;\r
a39af1cb 2122\r
adf023ff 2123 numBlocks = ParamCardSizeBlocks(param_getchar(Cmd, 0));\r
3a05a1e7
OM
2124\r
2125 char cmdp = 0;\r
2126 while(param_getchar(Cmd, cmdp) != 0x00){\r
2127 switch(param_getchar(Cmd, cmdp)) {\r
2128 case 'w':\r
2129 case 'W':\r
3bba7dea 2130 wipeCard = 1;\r
3a05a1e7
OM
2131 break;\r
2132 case 'f':\r
2133 case 'F':\r
2134 fillCard = 1;\r
2135 break;\r
2136 default:\r
2137 break;\r
3bba7dea 2138 }\r
3a05a1e7 2139 cmdp++;\r
3bba7dea 2140 }\r
0675f200 2141\r
a39af1cb 2142 if (!wipeCard && !fillCard)\r
2ce43a28 2143 wipeCard = true;\r
0675f200 2144\r
3a05a1e7
OM
2145 PrintAndLog("--blocks count:%2d wipe:%c fill:%c", numBlocks, (wipeCard)?'y':'n', (fillCard)?'y':'n');\r
2146\r
2147 if (gen == 2) {\r
2148 /* generation 1b magic card */\r
2149 if (wipeCard) {\r
2150 PrintAndLog("WARNING: can't wipe magic card 1b generation");\r
0675f200 2151 }\r
a39af1cb 2152 res = mfCWipe(numBlocks, true, false, fillCard);\r
3a05a1e7
OM
2153 } else {\r
2154 /* generation 1a magic card by default */\r
a39af1cb 2155 res = mfCWipe(numBlocks, false, wipeCard, fillCard);\r
3a05a1e7 2156 }\r
7906cb41 2157\r
3a05a1e7
OM
2158 if (res) {\r
2159 PrintAndLog("Can't wipe. error=%d", res);\r
2160 return 1;\r
2161 }\r
2162 PrintAndLog("OK");\r
0675f200
M
2163 return 0;\r
2164}\r
2165\r
2166int CmdHF14AMfCSetBlk(const char *Cmd)\r
2167{\r
5ee70129 2168 uint8_t memBlock[16] = {0x00};\r
f774db95 2169 uint8_t blockNo = 0;\r
7cb8516c 2170 bool wipeCard = false;\r
7906cb41 2171 int res, gen = 0;\r
f774db95
M
2172\r
2173 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {\r
664f6586 2174 PrintAndLog("Usage: hf mf csetblk <block number> <block data (32 hex symbols)> [w]");\r
f774db95 2175 PrintAndLog("sample: hf mf csetblk 1 01020304050607080910111213141516");\r
664f6586 2176 PrintAndLog("Set block data for magic Chinese card (only works with such cards)");\r
2177 PrintAndLog("If you also want wipe the card then add 'w' at the end of the command line");\r
f774db95 2178 return 0;\r
7906cb41
F
2179 }\r
2180\r
2181 gen = mfCIdentify();\r
a39af1cb 2182 if ((gen != 1) && (gen != 2))\r
3a05a1e7 2183 return 1;\r
f774db95
M
2184\r
2185 blockNo = param_get8(Cmd, 0);\r
f774db95
M
2186\r
2187 if (param_gethex(Cmd, 1, memBlock, 32)) {\r
2188 PrintAndLog("block data must include 32 HEX symbols");\r
2189 return 1;\r
2190 }\r
2191\r
664f6586 2192 char ctmp = param_getchar(Cmd, 2);\r
2193 wipeCard = (ctmp == 'w' || ctmp == 'W');\r
baeaf579 2194 PrintAndLog("--block number:%2d data:%s", blockNo, sprint_hex(memBlock, 16));\r
f774db95 2195\r
7906cb41
F
2196 if (gen == 2) {\r
2197 /* generation 1b magic card */\r
2198 res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B);\r
2199 } else {\r
2200 /* generation 1a magic card by default */\r
2201 res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER);\r
2202 }\r
2203\r
f774db95 2204 if (res) {\r
664f6586 2205 PrintAndLog("Can't write block. error=%d", res);\r
2206 return 1;\r
2207 }\r
0675f200
M
2208 return 0;\r
2209}\r
2210\r
baeaf579 2211\r
0675f200
M
2212int CmdHF14AMfCLoad(const char *Cmd)\r
2213{\r
208a0166 2214 FILE * f;\r
b915fda3 2215 char filename[FILE_PATH_SIZE] = {0x00};\r
208a0166 2216 char * fnameptr = filename;\r
7906cb41
F
2217 char buf[256] = {0x00};\r
2218 uint8_t buf8[256] = {0x00};\r
208a0166 2219 uint8_t fillFromEmulator = 0;\r
7906cb41
F
2220 int i, len, blockNum, flags = 0, gen = 0, numblock = 64;\r
2221\r
208a0166 2222 if (param_getchar(Cmd, 0) == 'h' || param_getchar(Cmd, 0)== 0x00) {\r
e3c23565 2223 PrintAndLog("It loads magic Chinese card from the file `filename.eml`");\r
7906cb41
F
2224 PrintAndLog("or from emulator memory (option `e`). 4K card: (option `4`)");\r
2225 PrintAndLog("Usage: hf mf cload [file name w/o `.eml`][e][4]");\r
2226 PrintAndLog(" or: hf mf cload e [4]");\r
2227 PrintAndLog("Sample: hf mf cload filename");\r
2228 PrintAndLog(" hf mf cload filname 4");\r
2229 PrintAndLog(" hf mf cload e");\r
2230 PrintAndLog(" hf mf cload e 4");\r
208a0166 2231 return 0;\r
7906cb41 2232 }\r
208a0166
M
2233\r
2234 char ctmp = param_getchar(Cmd, 0);\r
2235 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;\r
7906cb41
F
2236 ctmp = param_getchar(Cmd, 1);\r
2237 if (ctmp == '4') numblock = 256;\r
2238\r
2239 gen = mfCIdentify();\r
2240 PrintAndLog("Loading magic mifare %dK", numblock == 256 ? 4:1);\r
2241\r
208a0166 2242 if (fillFromEmulator) {\r
7906cb41 2243 for (blockNum = 0; blockNum < numblock; blockNum += 1) {\r
208a0166
M
2244 if (mfEmlGetMem(buf8, blockNum, 1)) {\r
2245 PrintAndLog("Cant get block: %d", blockNum);\r
2246 return 2;\r
2247 }\r
a39af1cb 2248 if (blockNum == 0) flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC; // switch on field and send magic sequence\r
2249 if (blockNum == 1) flags = 0; // just write\r
2250 if (blockNum == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD; // Done. Magic Halt and switch off field.\r
208a0166 2251\r
7906cb41
F
2252 if (gen == 2)\r
2253 /* generation 1b magic card */\r
2254 flags |= CSETBLOCK_MAGIC_1B;\r
208a0166
M
2255 if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) {\r
2256 PrintAndLog("Cant set magic card block: %d", blockNum);\r
2257 return 3;\r
2258 }\r
2259 }\r
2260 return 0;\r
2261 } else {\r
874572d4 2262 param_getstr(Cmd, 0, filename, sizeof(filename));\r
7906cb41
F
2263\r
2264 len = strlen(filename);\r
4c16ae80 2265 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;\r
208a0166 2266\r
7906cb41 2267 //memcpy(filename, Cmd, len);\r
292fe725 2268 fnameptr += len;\r
208a0166 2269\r
7906cb41
F
2270 sprintf(fnameptr, ".eml");\r
2271\r
208a0166
M
2272 // open file\r
2273 f = fopen(filename, "r");\r
2274 if (f == NULL) {\r
2275 PrintAndLog("File not found or locked.");\r
2276 return 1;\r
2277 }\r
7906cb41 2278\r
208a0166 2279 blockNum = 0;\r
208a0166 2280 while(!feof(f)){\r
7906cb41 2281\r
208a0166 2282 memset(buf, 0, sizeof(buf));\r
7906cb41 2283\r
759c16b3 2284 if (fgets(buf, sizeof(buf), f) == NULL) {\r
e6432f05 2285 fclose(f);\r
baeaf579 2286 PrintAndLog("File reading error.");\r
2287 return 2;\r
2288 }\r
208a0166 2289\r
16a95d76 2290 if (strlen(buf) < 32) {\r
208a0166
M
2291 if(strlen(buf) && feof(f))\r
2292 break;\r
2293 PrintAndLog("File content error. Block data must include 32 HEX symbols");\r
e6432f05 2294 fclose(f);\r
208a0166
M
2295 return 2;\r
2296 }\r
2297 for (i = 0; i < 32; i += 2)\r
2298 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);\r
2299\r
a39af1cb 2300 if (blockNum == 0) flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC; // switch on field and send magic sequence\r
2301 if (blockNum == 1) flags = 0; // just write\r
2302 if (blockNum == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD; // Done. Switch off field.\r
208a0166 2303\r
7906cb41
F
2304 if (gen == 2)\r
2305 /* generation 1b magic card */\r
2306 flags |= CSETBLOCK_MAGIC_1B;\r
208a0166 2307 if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) {\r
baeaf579 2308 PrintAndLog("Can't set magic card block: %d", blockNum);\r
4c16ae80 2309 fclose(f);\r
208a0166
M
2310 return 3;\r
2311 }\r
2312 blockNum++;\r
7906cb41
F
2313\r
2314 if (blockNum >= numblock) break; // magic card type - mifare 1K 64 blocks, mifare 4k 256 blocks\r
208a0166
M
2315 }\r
2316 fclose(f);\r
7906cb41
F
2317\r
2318 //if (blockNum != 16 * 4 && blockNum != 32 * 4 + 8 * 16){\r
2319 if (blockNum != numblock){\r
2320 PrintAndLog("File content error. There must be %d blocks", numblock);\r
208a0166
M
2321 return 4;\r
2322 }\r
2323 PrintAndLog("Loaded from file: %s", filename);\r
2324 return 0;\r
2325 }\r
e3c23565 2326 return 0;\r
0675f200
M
2327}\r
2328\r
545a1f38
M
2329int CmdHF14AMfCGetBlk(const char *Cmd) {\r
2330 uint8_t memBlock[16];\r
2331 uint8_t blockNo = 0;\r
7906cb41 2332 int res, gen = 0;\r
545a1f38
M
2333 memset(memBlock, 0x00, sizeof(memBlock));\r
2334\r
2335 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {\r
2336 PrintAndLog("Usage: hf mf cgetblk <block number>");\r
2337 PrintAndLog("sample: hf mf cgetblk 1");\r
664f6586 2338 PrintAndLog("Get block data from magic Chinese card (only works with such cards)\n");\r
545a1f38 2339 return 0;\r
7906cb41
F
2340 }\r
2341\r
2342 gen = mfCIdentify();\r
545a1f38
M
2343\r
2344 blockNo = param_get8(Cmd, 0);\r
545a1f38 2345\r
baeaf579 2346 PrintAndLog("--block number:%2d ", blockNo);\r
545a1f38 2347\r
7906cb41
F
2348 if (gen == 2) {\r
2349 /* generation 1b magic card */\r
2350 res = mfCGetBlock(blockNo, memBlock, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B);\r
2351 } else {\r
2352 /* generation 1a magic card by default */\r
2353 res = mfCGetBlock(blockNo, memBlock, CSETBLOCK_SINGLE_OPER);\r
2354 }\r
545a1f38
M
2355 if (res) {\r
2356 PrintAndLog("Can't read block. error=%d", res);\r
2357 return 1;\r
2358 }\r
7906cb41 2359\r
545a1f38 2360 PrintAndLog("block data:%s", sprint_hex(memBlock, 16));\r
a39af1cb 2361\r
ac4ecfe3
OM
2362 if (mfIsSectorTrailer(blockNo)) {\r
2363 PrintAndLogEx(NORMAL, "Trailer decoded:");\r
2364 PrintAndLogEx(NORMAL, "Key A: %s", sprint_hex_inrow(memBlock, 6));\r
2365 PrintAndLogEx(NORMAL, "Key B: %s", sprint_hex_inrow(&memBlock[10], 6));\r
2366 int bln = mfFirstBlockOfSector(mfSectorNum(blockNo));\r
2367 int blinc = (mfNumBlocksPerSector(mfSectorNum(blockNo)) > 4) ? 5 : 1;\r
2368 for (int i = 0; i < 4; i++) {\r
2369 PrintAndLogEx(NORMAL, "Access block %d%s: %s", bln, ((blinc > 1) && (i < 3) ? "+" : "") , mfGetAccessConditionsDesc(i, &memBlock[6]));\r
2370 bln += blinc;\r
2371 }\r
2372 PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&memBlock[9], 1));\r
2373 }\r
a39af1cb 2374\r
545a1f38
M
2375 return 0;\r
2376}\r
2377\r
2378int CmdHF14AMfCGetSc(const char *Cmd) {\r
5ee70129 2379 uint8_t memBlock[16] = {0x00};\r
545a1f38 2380 uint8_t sectorNo = 0;\r
7906cb41 2381 int i, res, flags, gen = 0, baseblock = 0, sect_size = 4;\r
545a1f38
M
2382\r
2383 if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') {\r
2384 PrintAndLog("Usage: hf mf cgetsc <sector number>");\r
2385 PrintAndLog("sample: hf mf cgetsc 0");\r
664f6586 2386 PrintAndLog("Get sector data from magic Chinese card (only works with such cards)\n");\r
545a1f38 2387 return 0;\r
7906cb41 2388 }\r
545a1f38
M
2389\r
2390 sectorNo = param_get8(Cmd, 0);\r
7906cb41
F
2391\r
2392 if (sectorNo > 39) {\r
2393 PrintAndLog("Sector number must be in [0..15] in MIFARE classic 1k and [0..39] in MIFARE classic 4k.");\r
545a1f38
M
2394 return 1;\r
2395 }\r
2396\r
baeaf579 2397 PrintAndLog("--sector number:%d ", sectorNo);\r
545a1f38 2398\r
7906cb41
F
2399 gen = mfCIdentify();\r
2400\r
545a1f38 2401 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;\r
7906cb41
F
2402 if (sectorNo < 32 ) {\r
2403 baseblock = sectorNo * 4;\r
2404 } else {\r
2405 baseblock = 128 + 16 * (sectorNo - 32);\r
2406\r
2407 }\r
2408 if (sectorNo > 31) sect_size = 16;\r
2409\r
2410 for (i = 0; i < sect_size; i++) {\r
545a1f38 2411 if (i == 1) flags = 0;\r
7906cb41 2412 if (i == sect_size - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;\r
545a1f38 2413\r
7906cb41
F
2414 if (gen == 2)\r
2415 /* generation 1b magic card */\r
2416 flags |= CSETBLOCK_MAGIC_1B;\r
2417\r
2418 res = mfCGetBlock(baseblock + i, memBlock, flags);\r
545a1f38 2419 if (res) {\r
7906cb41 2420 PrintAndLog("Can't read block. %d error=%d", baseblock + i, res);\r
545a1f38
M
2421 return 1;\r
2422 }\r
7906cb41
F
2423\r
2424 PrintAndLog("block %3d data:%s", baseblock + i, sprint_hex(memBlock, 16));\r
a39af1cb 2425\r
daccbcdc 2426 if (mfIsSectorTrailer(baseblock + i)) {\r
a39af1cb 2427 PrintAndLogEx(NORMAL, "Trailer decoded:");\r
2428 PrintAndLogEx(NORMAL, "Key A: %s", sprint_hex_inrow(memBlock, 6));\r
2429 PrintAndLogEx(NORMAL, "Key B: %s", sprint_hex_inrow(&memBlock[10], 6));\r
2430 int bln = baseblock;\r
2431 int blinc = (mfNumBlocksPerSector(sectorNo) > 4) ? 5 : 1;\r
2432 for (int i = 0; i < 4; i++) {\r
2433 PrintAndLogEx(NORMAL, "Access block %d%s: %s", bln, ((blinc > 1) && (i < 3) ? "+" : "") , mfGetAccessConditionsDesc(i, &memBlock[6]));\r
2434 bln += blinc;\r
2435 }\r
2436 PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&memBlock[9], 1));\r
2437 }\r
545a1f38
M
2438 }\r
2439 return 0;\r
2440}\r
2441\r
baeaf579 2442\r
545a1f38
M
2443int CmdHF14AMfCSave(const char *Cmd) {\r
2444\r
2445 FILE * f;\r
b915fda3 2446 char filename[FILE_PATH_SIZE] = {0x00};\r
545a1f38
M
2447 char * fnameptr = filename;\r
2448 uint8_t fillFromEmulator = 0;\r
7906cb41
F
2449 uint8_t buf[256] = {0x00};\r
2450 int i, j, len, flags, gen = 0, numblock = 64;\r
2451\r
b915fda3 2452 // memset(filename, 0, sizeof(filename));\r
2453 // memset(buf, 0, sizeof(buf));\r
545a1f38
M
2454\r
2455 if (param_getchar(Cmd, 0) == 'h') {\r
2456 PrintAndLog("It saves `magic Chinese` card dump into the file `filename.eml` or `cardID.eml`");\r
7906cb41 2457 PrintAndLog("or into emulator memory (option `e`). 4K card: (option `4`)");\r
a2d058f3
F
2458 PrintAndLog("Usage: hf mf csave [file name w/o `.eml`][e][4]");\r
2459 PrintAndLog("Sample: hf mf csave ");\r
2460 PrintAndLog(" hf mf csave filename");\r
2461 PrintAndLog(" hf mf csave e");\r
2462 PrintAndLog(" hf mf csave 4");\r
2463 PrintAndLog(" hf mf csave filename 4");\r
2464 PrintAndLog(" hf mf csave e 4");\r
545a1f38 2465 return 0;\r
7906cb41 2466 }\r
545a1f38
M
2467\r
2468 char ctmp = param_getchar(Cmd, 0);\r
2469 if (ctmp == 'e' || ctmp == 'E') fillFromEmulator = 1;\r
7906cb41
F
2470 if (ctmp == '4') numblock = 256;\r
2471 ctmp = param_getchar(Cmd, 1);\r
2472 if (ctmp == '4') numblock = 256;\r
2473\r
2474 gen = mfCIdentify();\r
2475 PrintAndLog("Saving magic mifare %dK", numblock == 256 ? 4:1);\r
545a1f38
M
2476\r
2477 if (fillFromEmulator) {\r
2478 // put into emulator\r
2479 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;\r
7906cb41 2480 for (i = 0; i < numblock; i++) {\r
545a1f38 2481 if (i == 1) flags = 0;\r
7906cb41
F
2482 if (i == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;\r
2483\r
2484 if (gen == 2)\r
2485 /* generation 1b magic card */\r
2486 flags |= CSETBLOCK_MAGIC_1B;\r
2487\r
545a1f38
M
2488 if (mfCGetBlock(i, buf, flags)) {\r
2489 PrintAndLog("Cant get block: %d", i);\r
2490 break;\r
2491 }\r
7906cb41 2492\r
545a1f38
M
2493 if (mfEmlSetMem(buf, i, 1)) {\r
2494 PrintAndLog("Cant set emul block: %d", i);\r
2495 return 3;\r
2496 }\r
2497 }\r
2498 return 0;\r
2499 } else {\r
874572d4 2500 param_getstr(Cmd, 0, filename, sizeof(filename));\r
7906cb41
F
2501\r
2502 len = strlen(filename);\r
4c16ae80 2503 if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;\r
7906cb41
F
2504\r
2505 ctmp = param_getchar(Cmd, 0);\r
2506 if (len < 1 || (ctmp == '4')) {\r
545a1f38 2507 // get filename\r
7906cb41
F
2508\r
2509 flags = CSETBLOCK_SINGLE_OPER;\r
2510 if (gen == 2)\r
2511 /* generation 1b magic card */\r
2512 flags |= CSETBLOCK_MAGIC_1B;\r
2513 if (mfCGetBlock(0, buf, flags)) {\r
545a1f38 2514 PrintAndLog("Cant get block: %d", 0);\r
1d537ad6
PL
2515 len = sprintf(fnameptr, "dump");\r
2516 fnameptr += len;\r
2517 }\r
2518 else {\r
2519 for (j = 0; j < 7; j++, fnameptr += 2)\r
7906cb41 2520 sprintf(fnameptr, "%02x", buf[j]);\r
545a1f38 2521 }\r
545a1f38 2522 } else {\r
7906cb41 2523 //memcpy(filename, Cmd, len);\r
545a1f38
M
2524 fnameptr += len;\r
2525 }\r
2526\r
7906cb41
F
2527 sprintf(fnameptr, ".eml");\r
2528\r
545a1f38
M
2529 // open file\r
2530 f = fopen(filename, "w+");\r
2531\r
b915fda3 2532 if (f == NULL) {\r
2533 PrintAndLog("File not found or locked.");\r
2534 return 1;\r
2535 }\r
2536\r
545a1f38
M
2537 // put hex\r
2538 flags = CSETBLOCK_INIT_FIELD + CSETBLOCK_WUPC;\r
7906cb41 2539 for (i = 0; i < numblock; i++) {\r
545a1f38 2540 if (i == 1) flags = 0;\r
7906cb41
F
2541 if (i == numblock - 1) flags = CSETBLOCK_HALT + CSETBLOCK_RESET_FIELD;\r
2542\r
2543 if (gen == 2)\r
2544 /* generation 1b magic card */\r
2545 flags |= CSETBLOCK_MAGIC_1B;\r
545a1f38
M
2546 if (mfCGetBlock(i, buf, flags)) {\r
2547 PrintAndLog("Cant get block: %d", i);\r
2548 break;\r
2549 }\r
2550 for (j = 0; j < 16; j++)\r
7906cb41 2551 fprintf(f, "%02x", buf[j]);\r
545a1f38
M
2552 fprintf(f,"\n");\r
2553 }\r
2554 fclose(f);\r
7906cb41 2555\r
545a1f38 2556 PrintAndLog("Saved to file: %s", filename);\r
7906cb41 2557\r
545a1f38
M
2558 return 0;\r
2559 }\r
2560}\r
2561\r
baeaf579 2562\r
b62a5a84 2563int CmdHF14AMfSniff(const char *Cmd){\r
3fe4ff4f 2564\r
c948cbde
M
2565 bool wantLogToFile = 0;\r
2566 bool wantDecrypt = 0;\r
eede7162 2567 //bool wantSaveToEml = 0; TODO\r
55acbb2a
M
2568 bool wantSaveToEmlFile = 0;\r
2569\r
7906cb41 2570 //var\r
39864b0b
M
2571 int res = 0;\r
2572 int len = 0;\r
a37725fa 2573 int parlen = 0;\r
39864b0b 2574 int blockLen = 0;\r
39864b0b 2575 int pckNum = 0;\r
f71f4deb 2576 int num = 0;\r
2577 uint8_t uid[7];\r
991f13f2 2578 uint8_t uid_len;\r
5ee70129 2579 uint8_t atqa[2] = {0x00};\r
39864b0b
M
2580 uint8_t sak;\r
2581 bool isTag;\r
f71f4deb 2582 uint8_t *buf = NULL;\r
2583 uint16_t bufsize = 0;\r
2584 uint8_t *bufPtr = NULL;\r
a37725fa 2585 uint8_t parity[16];\r
7906cb41 2586\r
e3c23565 2587 char ctmp = param_getchar(Cmd, 0);\r
2588 if ( ctmp == 'h' || ctmp == 'H' ) {\r
baeaf579 2589 PrintAndLog("It continuously gets data from the field and saves it to: log, emulator, emulator file.");\r
55acbb2a
M
2590 PrintAndLog("You can specify:");\r
2591 PrintAndLog(" l - save encrypted sequence to logfile `uid.log`");\r
2592 PrintAndLog(" d - decrypt sequence and put it to log file `uid.log`");\r
2593 PrintAndLog(" n/a e - decrypt sequence, collect read and write commands and save the result of the sequence to emulator memory");\r
3fe4ff4f 2594 PrintAndLog(" f - decrypt sequence, collect read and write commands and save the result of the sequence to emulator dump file `uid.eml`");\r
2595 PrintAndLog("Usage: hf mf sniff [l][d][e][f]");\r
55acbb2a 2596 PrintAndLog(" sample: hf mf sniff l d e");\r
b62a5a84 2597 return 0;\r
7906cb41
F
2598 }\r
2599\r
55acbb2a 2600 for (int i = 0; i < 4; i++) {\r
e3c23565 2601 ctmp = param_getchar(Cmd, i);\r
55acbb2a
M
2602 if (ctmp == 'l' || ctmp == 'L') wantLogToFile = true;\r
2603 if (ctmp == 'd' || ctmp == 'D') wantDecrypt = true;\r
eede7162 2604 //if (ctmp == 'e' || ctmp == 'E') wantSaveToEml = true; TODO\r
55acbb2a
M
2605 if (ctmp == 'f' || ctmp == 'F') wantSaveToEmlFile = true;\r
2606 }\r
7906cb41 2607\r
39864b0b
M
2608 printf("-------------------------------------------------------------------------\n");\r
2609 printf("Executing command. \n");\r
2610 printf("Press the key on the proxmark3 device to abort both proxmark3 and client.\n");\r
2611 printf("Press the key on pc keyboard to abort the client.\n");\r
2612 printf("-------------------------------------------------------------------------\n");\r
2613\r
d714d3ef 2614 UsbCommand c = {CMD_MIFARE_SNIFFER, {0, 0, 0}};\r
2615 clearCommandBuffer();\r
2616 SendCommand(&c);\r
b62a5a84 2617\r
39864b0b
M
2618 // wait cycle\r
2619 while (true) {\r
2620 printf(".");\r
2621 fflush(stdout);\r
2622 if (ukbhit()) {\r
2623 getchar();\r
2624 printf("\naborted via keyboard!\n");\r
2625 break;\r
2626 }\r
7906cb41 2627\r
f71f4deb 2628 UsbCommand resp;\r
8ec06f5e 2629 if (WaitForResponseTimeoutW(CMD_ACK, &resp, 2000, false)) {\r
902cb3c0 2630 res = resp.arg[0] & 0xff;\r
f71f4deb 2631 uint16_t traceLen = resp.arg[1];\r
2632 len = resp.arg[2];\r
2633\r
a39af1cb 2634 if (res == 0) { // we are done\r
8ec06f5e 2635 break;\r
4c16ae80 2636 }\r
f71f4deb 2637\r
a39af1cb 2638 if (res == 1) { // there is (more) data to be transferred\r
2639 if (pckNum == 0) { // first packet, (re)allocate necessary buffer\r
4c16ae80 2640 if (traceLen > bufsize || buf == NULL) {\r
f71f4deb 2641 uint8_t *p;\r
a39af1cb 2642 if (buf == NULL) { // not yet allocated\r
f71f4deb 2643 p = malloc(traceLen);\r
a39af1cb 2644 } else { // need more memory\r
f71f4deb 2645 p = realloc(buf, traceLen);\r
2646 }\r
2647 if (p == NULL) {\r
2648 PrintAndLog("Cannot allocate memory for trace");\r
2649 free(buf);\r
2650 return 2;\r
2651 }\r
2652 buf = p;\r
2653 }\r
39864b0b 2654 bufPtr = buf;\r
f71f4deb 2655 bufsize = traceLen;\r
2656 memset(buf, 0x00, traceLen);\r
39864b0b 2657 }\r
902cb3c0 2658 memcpy(bufPtr, resp.d.asBytes, len);\r
39864b0b
M
2659 bufPtr += len;\r
2660 pckNum++;\r
2661 }\r
f71f4deb 2662\r
a39af1cb 2663 if (res == 2) { // received all data, start displaying\r
39864b0b
M
2664 blockLen = bufPtr - buf;\r
2665 bufPtr = buf;\r
2666 printf(">\n");\r
2667 PrintAndLog("received trace len: %d packages: %d", blockLen, pckNum);\r
6a1f2d82 2668 while (bufPtr - buf < blockLen) {\r
a39af1cb 2669 bufPtr += 6; // skip (void) timing information\r
6a1f2d82 2670 len = *((uint16_t *)bufPtr);\r
2671 if(len & 0x8000) {\r
2672 isTag = true;\r
2673 len &= 0x7fff;\r
2674 } else {\r
2675 isTag = false;\r
2676 }\r
a37725fa 2677 parlen = (len - 1) / 8 + 1;\r
6a1f2d82 2678 bufPtr += 2;\r
2679 if ((len == 14) && (bufPtr[0] == 0xff) && (bufPtr[1] == 0xff) && (bufPtr[12] == 0xff) && (bufPtr[13] == 0xff)) {\r
39864b0b
M
2680 memcpy(uid, bufPtr + 2, 7);\r
2681 memcpy(atqa, bufPtr + 2 + 7, 2);\r
991f13f2 2682 uid_len = (atqa[0] & 0xC0) == 0x40 ? 7 : 4;\r
39864b0b 2683 sak = bufPtr[11];\r
7906cb41 2684 PrintAndLog("tag select uid:%s atqa:0x%02x%02x sak:0x%02x",\r
991f13f2 2685 sprint_hex(uid + (7 - uid_len), uid_len),\r
7906cb41
F
2686 atqa[1],\r
2687 atqa[0],\r
991f13f2 2688 sak);\r
d714d3ef 2689 if (wantLogToFile || wantDecrypt) {\r
991f13f2 2690 FillFileNameByUID(logHexFileName, uid + (7 - uid_len), ".log", uid_len);\r
55acbb2a 2691 AddLogCurrentDT(logHexFileName);\r
7906cb41
F
2692 }\r
2693 if (wantDecrypt)\r
3fe4ff4f 2694 mfTraceInit(uid, atqa, sak, wantSaveToEmlFile);\r
39864b0b 2695 } else {\r
a37725fa 2696 oddparitybuf(bufPtr, len, parity);\r
a39af1cb 2697 PrintAndLog("%s(%d):%s [%s] c[%s]%c",\r
2698 isTag ? "TAG":"RDR",\r
2699 num,\r
2700 sprint_hex(bufPtr, len),\r
2701 printBitsPar(bufPtr + len, len),\r
a37725fa
OM
2702 printBitsPar(parity, len),\r
2703 memcmp(bufPtr + len, parity, len / 8 + 1) ? '!' : ' ');\r
7906cb41 2704 if (wantLogToFile)\r
3fe4ff4f 2705 AddLogHex(logHexFileName, isTag ? "TAG: ":"RDR: ", bufPtr, len);\r
7906cb41 2706 if (wantDecrypt)\r
a37725fa 2707 mfTraceDecode(bufPtr, len, bufPtr[len], wantSaveToEmlFile);\r
7906cb41 2708 num++;\r
39864b0b
M
2709 }\r
2710 bufPtr += len;\r
a39af1cb 2711 bufPtr += parlen; // ignore parity\r
39864b0b 2712 }\r
f71f4deb 2713 pckNum = 0;\r
39864b0b 2714 }\r
3fe4ff4f 2715 } // resp not NULL\r
39864b0b 2716 } // while (true)\r
f71f4deb 2717\r
2718 free(buf);\r
a39af1cb 2719\r
8ec06f5e
OM
2720 msleep(300); // wait for exiting arm side.\r
2721 PrintAndLog("Done.");\r
d714d3ef 2722 return 0;\r
b62a5a84
M
2723}\r
2724\r
1a5a73ab 2725//needs nt, ar, at, Data to decrypt\r
2726int CmdDecryptTraceCmds(const char *Cmd){\r
2727 uint8_t data[50];\r
2728 int len = 0;\r
2729 param_gethex_ex(Cmd,3,data,&len);\r
2730 return tryDecryptWord(param_get32ex(Cmd,0,0,16),param_get32ex(Cmd,1,0,16),param_get32ex(Cmd,2,0,16),data,len/2);\r
2731}\r
f71f4deb 2732\r
7dadcc95
OM
2733int CmdHF14AMfAuth4(const char *cmd) {\r
2734 uint8_t keyn[20] = {0};\r
2735 int keynlen = 0;\r
2736 uint8_t key[16] = {0};\r
2737 int keylen = 0;\r
ae3340a0 2738\r
a39af1cb 2739 CLIParserInit("hf mf auth4",\r
2740 "Executes AES authentication command in ISO14443-4",\r
7dadcc95
OM
2741 "Usage:\n\thf mf auth4 4000 000102030405060708090a0b0c0d0e0f -> executes authentication\n"\r
2742 "\thf mf auth4 9003 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -> executes authentication\n");\r
2743\r
2744 void* argtable[] = {\r
2745 arg_param_begin,\r
2746 arg_str1(NULL, NULL, "<Key Num (HEX 2 bytes)>", NULL),\r
2747 arg_str1(NULL, NULL, "<Key Value (HEX 16 bytes)>", NULL),\r
2748 arg_param_end\r
2749 };\r
2750 CLIExecWithReturn(cmd, argtable, true);\r
a39af1cb 2751\r
ae3340a0
OM
2752 CLIGetHexWithReturn(1, keyn, &keynlen);\r
2753 CLIGetHexWithReturn(2, key, &keylen);\r
7dadcc95 2754 CLIParserFree();\r
a39af1cb 2755\r
7dadcc95
OM
2756 if (keynlen != 2) {\r
2757 PrintAndLog("ERROR: <Key Num> must be 2 bytes long instead of: %d", keynlen);\r
2758 return 1;\r
2759 }\r
a39af1cb 2760\r
7dadcc95
OM
2761 if (keylen != 16) {\r
2762 PrintAndLog("ERROR: <Key Value> must be 16 bytes long instead of: %d", keylen);\r
2763 return 1;\r
2764 }\r
2765\r
ae3340a0 2766 return MifareAuth4(NULL, keyn, key, true, false, true);\r
7dadcc95
OM
2767}\r
2768\r
fdd9395d
OM
2769// https://www.nxp.com/docs/en/application-note/AN10787.pdf\r
2770int CmdHF14AMfMAD(const char *cmd) {\r
2771\r
a39af1cb 2772 CLIParserInit("hf mf mad",\r
2773 "Checks and prints Mifare Application Directory (MAD)",\r
2774 "Usage:\n\thf mf mad -> shows MAD if exists\n"\r
2775 "\thf mf mad -a 03e1 -k ffffffffffff -b -> shows NDEF data if exists. read card with custom key and key B\n");\r
2776\r
2777 void *argtable[] = {\r
2778 arg_param_begin,\r
2779 arg_lit0("vV", "verbose", "show technical data"),\r
2780 arg_str0("aA", "aid", "print all sectors with aid", NULL),\r
2781 arg_str0("kK", "key", "key for printing sectors", NULL),\r
2782 arg_lit0("bB", "keyb", "use key B for access printing sectors (by default: key A)"),\r
2783 arg_param_end\r
2784 };\r
2785 CLIExecWithReturn(cmd, argtable, true);\r
2786 bool verbose = arg_get_lit(1);\r
2787 uint8_t aid[2] = {0};\r
2788 int aidlen;\r
2789 CLIGetHexWithReturn(2, aid, &aidlen);\r
2790 uint8_t key[6] = {0};\r
2791 int keylen;\r
2792 CLIGetHexWithReturn(3, key, &keylen);\r
2793 bool keyB = arg_get_lit(4);\r
2794\r
2795 CLIParserFree();\r
2796\r
2797 if (aidlen != 2 && keylen > 0) {\r
2798 PrintAndLogEx(WARNING, "do not need a key without aid.");\r
2799 }\r
2800\r
2801 uint8_t sector0[16 * 4] = {0};\r
2802 uint8_t sector10[16 * 4] = {0};\r
2803 if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0)) {\r
2804 PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");\r
2805 return 2;\r
2806 }\r
2807\r
2808 if (verbose) {\r
2809 for (int i = 0; i < 4; i ++)\r
2810 PrintAndLogEx(NORMAL, "[%d] %s", i, sprint_hex(&sector0[i * 16], 16));\r
2811 }\r
2812\r
2813 bool haveMAD2 = false;\r
2814 MAD1DecodeAndPrint(sector0, verbose, &haveMAD2);\r
2815\r
2816 if (haveMAD2) {\r
2817 if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10)) {\r
2818 PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");\r
2819 return 2;\r
2820 }\r
2821\r
2822 MAD2DecodeAndPrint(sector10, verbose);\r
2823 }\r
2824\r
2825 if (aidlen == 2) {\r
2826 uint16_t aaid = (aid[0] << 8) + aid[1];\r
2827 PrintAndLogEx(NORMAL, "\n-------------- AID 0x%04x ---------------", aaid);\r
2828\r
2829 uint16_t mad[7 + 8 + 8 + 8 + 8] = {0};\r
2830 size_t madlen = 0;\r
2831 if (MADDecode(sector0, sector10, mad, &madlen)) {\r
2832 PrintAndLogEx(ERR, "can't decode mad.");\r
2833 return 10;\r
2834 }\r
2835\r
2836 uint8_t akey[6] = {0};\r
2837 memcpy(akey, g_mifare_ndef_key, 6);\r
2838 if (keylen == 6) {\r
2839 memcpy(akey, key, 6);\r
2840 }\r
2841\r
2842 for (int i = 0; i < madlen; i++) {\r
2843 if (aaid == mad[i]) {\r
2844 uint8_t vsector[16 * 4] = {0};\r
2845 if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) {\r
2846 PrintAndLogEx(NORMAL, "");\r
2847 PrintAndLogEx(ERR, "read sector %d error.", i + 1);\r
2848 return 2;\r
2849 }\r
2850\r
2851 for (int j = 0; j < (verbose ? 4 : 3); j ++)\r
2852 PrintAndLogEx(NORMAL, " [%03d] %s", (i + 1) * 4 + j, sprint_hex(&vsector[j * 16], 16));\r
2853 }\r
2854 }\r
2855 }\r
2856\r
2857 return 0;\r
fdd9395d
OM
2858}\r
2859\r
2860int CmdHFMFNDEF(const char *cmd) {\r
2861\r
a39af1cb 2862 CLIParserInit("hf mf ndef",\r
2863 "Prints NFC Data Exchange Format (NDEF)",\r
2864 "Usage:\n\thf mf ndef -> shows NDEF data\n"\r
2865 "\thf mf ndef -a 03e1 -k ffffffffffff -b -> shows NDEF data with custom AID, key and with key B\n");\r
2866\r
2867 void *argtable[] = {\r
2868 arg_param_begin,\r
2869 arg_litn("vV", "verbose", 0, 2, "show technical data"),\r
2870 arg_str0("aA", "aid", "replace default aid for NDEF", NULL),\r
2871 arg_str0("kK", "key", "replace default key for NDEF", NULL),\r
2872 arg_lit0("bB", "keyb", "use key B for access sectors (by default: key A)"),\r
2873 arg_param_end\r
2874 };\r
2875 CLIExecWithReturn(cmd, argtable, true);\r
2876\r
2877 bool verbose = arg_get_lit(1);\r
2878 bool verbose2 = arg_get_lit(1) > 1;\r
2879 uint8_t aid[2] = {0};\r
2880 int aidlen;\r
2881 CLIGetHexWithReturn(2, aid, &aidlen);\r
2882 uint8_t key[6] = {0};\r
2883 int keylen;\r
2884 CLIGetHexWithReturn(3, key, &keylen);\r
2885 bool keyB = arg_get_lit(4);\r
2886\r
2887 CLIParserFree();\r
2888\r
2889 uint16_t ndefAID = 0x03e1;\r
2890 if (aidlen == 2)\r
2891 ndefAID = (aid[0] << 8) + aid[1];\r
2892\r
2893 uint8_t ndefkey[6] = {0};\r
2894 memcpy(ndefkey, g_mifare_ndef_key, 6);\r
2895 if (keylen == 6) {\r
2896 memcpy(ndefkey, key, 6);\r
2897 }\r
2898\r
2899 uint8_t sector0[16 * 4] = {0};\r
2900 uint8_t sector10[16 * 4] = {0};\r
2901 uint8_t data[4096] = {0};\r
2902 int datalen = 0;\r
2903\r
2904 PrintAndLogEx(NORMAL, "");\r
2905\r
2906 if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0)) {\r
2907 PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys.");\r
2908 return 2;\r
2909 }\r
2910\r
2911 bool haveMAD2 = false;\r
2912 int res = MADCheck(sector0, NULL, verbose, &haveMAD2);\r
2913 if (res) {\r
2914 PrintAndLogEx(ERR, "MAD error %d.", res);\r
2915 return res;\r
2916 }\r
2917\r
2918 if (haveMAD2) {\r
2919 if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10)) {\r
2920 PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys.");\r
2921 return 2;\r
2922 }\r
2923 }\r
2924\r
2925 uint16_t mad[7 + 8 + 8 + 8 + 8] = {0};\r
2926 size_t madlen = 0;\r
2927 if (MADDecode(sector0, (haveMAD2 ? sector10 : NULL), mad, &madlen)) {\r
2928 PrintAndLogEx(ERR, "can't decode mad.");\r
2929 return 10;\r
2930 }\r
2931\r
2932 printf("data reading:");\r
2933 for (int i = 0; i < madlen; i++) {\r
2934 if (ndefAID == mad[i]) {\r
2935 uint8_t vsector[16 * 4] = {0};\r
2936 if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector)) {\r
2937 PrintAndLogEx(ERR, "read sector %d error.", i + 1);\r
2938 return 2;\r
2939 }\r
2940\r
2941 memcpy(&data[datalen], vsector, 16 * 3);\r
2942 datalen += 16 * 3;\r
2943\r
2944 printf(".");\r
2945 }\r
2946 }\r
2947 printf(" OK\n");\r
2948\r
2949 if (!datalen) {\r
2950 PrintAndLogEx(ERR, "no NDEF data.");\r
2951 return 11;\r
2952 }\r
2953\r
2954 if (verbose2) {\r
2955 PrintAndLogEx(NORMAL, "NDEF data:");\r
2956 dump_buffer(data, datalen, stdout, 1);\r
2957 }\r
2958\r
2959 NDEFDecodeAndPrint(data, datalen, verbose);\r
2960\r
2961 return 0;\r
fdd9395d
OM
2962}\r
2963\r
26fdb4ab 2964static command_t CommandTable[] =\r
9ca155ba 2965{\r
c48c4d78 2966 {"help", CmdHelp, 1, "This help"},\r
2967 {"dbg", CmdHF14AMfDbg, 0, "Set default debug mode"},\r
2968 {"rdbl", CmdHF14AMfRdBl, 0, "Read MIFARE classic block"},\r
2969 {"rdsc", CmdHF14AMfRdSc, 0, "Read MIFARE classic sector"},\r
2970 {"dump", CmdHF14AMfDump, 0, "Dump MIFARE classic tag to binary file"},\r
a39af1cb 2971 {"restore", CmdHF14AMfRestore, 0, "Restore MIFARE classic binary file to BLANK tag"},\r
c48c4d78 2972 {"wrbl", CmdHF14AMfWrBl, 0, "Write MIFARE classic block"},\r
7dadcc95 2973 {"auth4", CmdHF14AMfAuth4, 0, "ISO14443-4 AES authentication"},\r
c48c4d78 2974 {"chk", CmdHF14AMfChk, 0, "Test block keys"},\r
2975 {"mifare", CmdHF14AMifare, 0, "Read parity error messages."},\r
2976 {"hardnested", CmdHF14AMfNestedHard, 0, "Nested attack for hardened Mifare cards"},\r
2977 {"nested", CmdHF14AMfNested, 0, "Test nested authentication"},\r
2978 {"sniff", CmdHF14AMfSniff, 0, "Sniff card-reader communication"},\r
a8561e35 2979 {"sim", CmdHF14AMfSim, 0, "Simulate MIFARE card"},\r
2980 {"eclr", CmdHF14AMfEClear, 0, "Clear simulator memory"},\r
c48c4d78 2981 {"eget", CmdHF14AMfEGet, 0, "Get simulator memory block"},\r
2982 {"eset", CmdHF14AMfESet, 0, "Set simulator memory block"},\r
2983 {"eload", CmdHF14AMfELoad, 0, "Load from file emul dump"},\r
2984 {"esave", CmdHF14AMfESave, 0, "Save to file emul dump"},\r
2985 {"ecfill", CmdHF14AMfECFill, 0, "Fill simulator memory with help of keys from simulator"},\r
2986 {"ekeyprn", CmdHF14AMfEKeyPrn, 0, "Print keys from simulator memory"},\r
3a05a1e7 2987 {"cwipe", CmdHF14AMfCWipe, 0, "Wipe magic Chinese card"},\r
c48c4d78 2988 {"csetuid", CmdHF14AMfCSetUID, 0, "Set UID for magic Chinese card"},\r
2989 {"csetblk", CmdHF14AMfCSetBlk, 0, "Write block - Magic Chinese card"},\r
2990 {"cgetblk", CmdHF14AMfCGetBlk, 0, "Read block - Magic Chinese card"},\r
2991 {"cgetsc", CmdHF14AMfCGetSc, 0, "Read sector - Magic Chinese card"},\r
2992 {"cload", CmdHF14AMfCLoad, 0, "Load dump into magic Chinese card"},\r
2993 {"csave", CmdHF14AMfCSave, 0, "Save dump from magic Chinese card into file or emulator"},\r
2994 {"decrypt", CmdDecryptTraceCmds, 1, "[nt] [ar_enc] [at_enc] [data] - to decrypt snoop or trace"},\r
fdd9395d
OM
2995 {"mad", CmdHF14AMfMAD, 0, "Checks and prints MAD"},\r
2996 {"ndef", CmdHFMFNDEF, 0, "Prints NDEF records from card"},\r
c48c4d78 2997 {NULL, NULL, 0, NULL}\r
9ca155ba
M
2998};\r
2999\r
3000int CmdHFMF(const char *Cmd)\r
3001{\r
44964fd1 3002 (void)WaitForResponseTimeout(CMD_ACK,NULL,100);\r
3003 CmdsParse(CommandTable, Cmd);\r
3004 return 0;\r
9ca155ba
M
3005}\r
3006\r
3007int CmdHelp(const char *Cmd)\r
3008{\r
3009 CmdsHelp(CommandTable);\r
3010 return 0;\r
3011}\r
Impressum, Datenschutz