fix: prevent hf mf mifare from always running twice
[proxmark3-svn] / client / mifarehost.c
CommitLineData
b62a5a84 1// Merlok, 2011, 2012\r
f397b5cc
M
2// people from mifare@nethemba.com, 2010\r
3//\r
4// This code is licensed to you under the terms of the GNU GPL, version 2 or,\r
5// at your option, any later version. See the LICENSE.txt file for the text of\r
6// the license.\r
7//-----------------------------------------------------------------------------\r
55acbb2a 8// mifare commands\r
f397b5cc
M
9//-----------------------------------------------------------------------------\r
10\r
4cb4b588 11#include "mifarehost.h"\r
12\r
f397b5cc 13#include <stdio.h>\r
7906cb41 14#include <stdlib.h>\r
31b6e9af 15#include <string.h>\r
9492e0b0 16#include <pthread.h>\r
7cb8516c 17\r
33443e7c 18#include "crapto1/crapto1.h"\r
902cb3c0 19#include "proxmark3.h"\r
7cb8516c 20#include "usb_cmd.h"\r
21#include "cmdmain.h"\r
22#include "ui.h"\r
23#include "util.h"\r
24#include "iso14443crc.h"\r
7cb8516c 25\r
7906cb41
F
26#include "mifare.h"\r
27\r
7cb8516c 28// mifare tracer flags used in mfTraceDecode()\r
29#define TRACE_IDLE 0x00\r
30#define TRACE_AUTH1 0x01\r
31#define TRACE_AUTH2 0x02\r
32#define TRACE_AUTH_OK 0x03\r
33#define TRACE_READ_DATA 0x04\r
34#define TRACE_WRITE_OK 0x05\r
35#define TRACE_WRITE_DATA 0x06\r
36#define TRACE_ERROR 0xFF\r
37\r
f397b5cc 38\r
7779d73c 39static int compare_uint64(const void *a, const void *b) {\r
40 // didn't work: (the result is truncated to 32 bits)\r
41 //return (*(int64_t*)b - *(int64_t*)a);\r
42\r
43 // better:\r
44 if (*(uint64_t*)b == *(uint64_t*)a) return 0;\r
45 else if (*(uint64_t*)b < *(uint64_t*)a) return 1;\r
46 else return -1;\r
47}\r
48\r
49\r
50// create the intersection (common members) of two sorted lists. Lists are terminated by -1. Result will be in list1. Number of elements is returned.\r
51static uint32_t intersection(uint64_t *list1, uint64_t *list2)\r
52{\r
53 if (list1 == NULL || list2 == NULL) {\r
54 return 0;\r
55 }\r
56 uint64_t *p1, *p2, *p3;\r
7906cb41 57 p1 = p3 = list1;\r
7779d73c 58 p2 = list2;\r
59\r
60 while ( *p1 != -1 && *p2 != -1 ) {\r
61 if (compare_uint64(p1, p2) == 0) {\r
62 *p3++ = *p1++;\r
63 p2++;\r
64 }\r
65 else {\r
66 while (compare_uint64(p1, p2) < 0) ++p1;\r
67 while (compare_uint64(p1, p2) > 0) ++p2;\r
68 }\r
69 }\r
70 *p3 = -1;\r
71 return p3 - list1;\r
72}\r
73\r
74\r
75// Darkside attack (hf mf mifare)\r
76static uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint64_t par_info, uint64_t ks_info, uint64_t **keys) {\r
77 struct Crypto1State *states;\r
78 uint32_t i, pos, rr; //nr_diff;\r
79 uint8_t bt, ks3x[8], par[8][8];\r
80 uint64_t key_recovered;\r
81 static uint64_t *keylist;\r
82 rr = 0;\r
83\r
84 // Reset the last three significant bits of the reader nonce\r
85 nr &= 0xffffff1f;\r
86\r
87 for (pos=0; pos<8; pos++) {\r
88 ks3x[7-pos] = (ks_info >> (pos*8)) & 0x0f;\r
89 bt = (par_info >> (pos*8)) & 0xff;\r
90 for (i=0; i<8; i++) {\r
91 par[7-pos][i] = (bt >> i) & 0x01;\r
92 }\r
93 }\r
94\r
95 states = lfsr_common_prefix(nr, rr, ks3x, par, (par_info == 0));\r
96\r
97 if (states == NULL) {\r
98 *keys = NULL;\r
99 return 0;\r
100 }\r
101\r
102 keylist = (uint64_t*)states;\r
7906cb41 103\r
7779d73c 104 for (i = 0; keylist[i]; i++) {\r
105 lfsr_rollback_word(states+i, uid^nt, 0);\r
106 crypto1_get_lfsr(states+i, &key_recovered);\r
107 keylist[i] = key_recovered;\r
108 }\r
109 keylist[i] = -1;\r
110\r
111 *keys = keylist;\r
112 return i;\r
113}\r
114\r
115\r
116int mfDarkside(uint64_t *key)\r
117{\r
118 uint32_t uid = 0;\r
119 uint32_t nt = 0, nr = 0;\r
120 uint64_t par_list = 0, ks_list = 0;\r
121 uint64_t *keylist = NULL, *last_keylist = NULL;\r
122 uint32_t keycount = 0;\r
123 int16_t isOK = 0;\r
124\r
125 UsbCommand c = {CMD_READER_MIFARE, {true, 0, 0}};\r
126\r
127 // message\r
128 printf("-------------------------------------------------------------------------\n");\r
129 printf("Executing command. Expected execution time: 25sec on average\n");\r
130 printf("Press button on the proxmark3 device to abort both proxmark3 and client.\n");\r
131 printf("-------------------------------------------------------------------------\n");\r
132\r
7906cb41 133\r
7779d73c 134 while (true) {\r
135 clearCommandBuffer();\r
136 SendCommand(&c);\r
7906cb41 137\r
7779d73c 138 //flush queue\r
139 while (ukbhit()) {\r
140 int c = getchar(); (void) c;\r
141 }\r
7906cb41 142\r
7779d73c 143 // wait cycle\r
144 while (true) {\r
145 printf(".");\r
146 fflush(stdout);\r
147 if (ukbhit()) {\r
148 return -5;\r
149 break;\r
150 }\r
7906cb41 151\r
7779d73c 152 UsbCommand resp;\r
153 if (WaitForResponseTimeout(CMD_ACK, &resp, 1000)) {\r
154 isOK = resp.arg[0];\r
155 if (isOK < 0) {\r
156 return isOK;\r
157 }\r
158 uid = (uint32_t)bytes_to_num(resp.d.asBytes + 0, 4);\r
159 nt = (uint32_t)bytes_to_num(resp.d.asBytes + 4, 4);\r
160 par_list = bytes_to_num(resp.d.asBytes + 8, 8);\r
161 ks_list = bytes_to_num(resp.d.asBytes + 16, 8);\r
162 nr = bytes_to_num(resp.d.asBytes + 24, 4);\r
163 break;\r
164 }\r
7906cb41 165 }\r
7779d73c 166\r
167 if (par_list == 0 && c.arg[0] == true) {\r
168 PrintAndLog("Parity is all zero. Most likely this card sends NACK on every failed authentication.");\r
169 PrintAndLog("Attack will take a few seconds longer because we need two consecutive successful runs.");\r
170 }\r
171 c.arg[0] = false;\r
172\r
173 keycount = nonce2key(uid, nt, nr, par_list, ks_list, &keylist);\r
174\r
175 if (keycount == 0) {\r
7906cb41 176 PrintAndLog("Key not found (lfsr_common_prefix list is null). Nt=%08x", nt);\r
7779d73c 177 PrintAndLog("This is expected to happen in 25%% of all cases. Trying again with a different reader nonce...");\r
178 continue;\r
179 }\r
180\r
d86ee73d 181 if (par_list == 0) {\r
182 qsort(keylist, keycount, sizeof(*keylist), compare_uint64);\r
183 keycount = intersection(last_keylist, keylist);\r
184 if (keycount == 0) {\r
185 free(last_keylist);\r
186 last_keylist = keylist;\r
187 continue;\r
188 }\r
7779d73c 189 }\r
190\r
191 if (keycount > 1) {\r
192 PrintAndLog("Found %u possible keys. Trying to authenticate with each of them ...\n", keycount);\r
193 } else {\r
194 PrintAndLog("Found a possible key. Trying to authenticate...\n");\r
7906cb41 195 }\r
7779d73c 196\r
197 *key = -1;\r
198 uint8_t keyBlock[USB_CMD_DATA_SIZE];\r
199 int max_keys = USB_CMD_DATA_SIZE/6;\r
200 for (int i = 0; i < keycount; i += max_keys) {\r
201 int size = keycount - i > max_keys ? max_keys : keycount - i;\r
202 for (int j = 0; j < size; j++) {\r
d86ee73d 203 if (par_list == 0) {\r
7779d73c 204 num_to_bytes(last_keylist[i*max_keys + j], 6, keyBlock);\r
d86ee73d 205 } else {\r
206 num_to_bytes(keylist[i*max_keys + j], 6, keyBlock);\r
7779d73c 207 }\r
208 }\r
209 if (!mfCheckKeys(0, 0, false, size, keyBlock, key)) {\r
210 break;\r
211 }\r
7906cb41
F
212 }\r
213\r
7779d73c 214 if (*key != -1) {\r
215 free(last_keylist);\r
216 free(keylist);\r
217 break;\r
218 } else {\r
219 PrintAndLog("Authentication failed. Trying again...");\r
220 free(last_keylist);\r
221 last_keylist = keylist;\r
222 }\r
223 }\r
7906cb41 224\r
7779d73c 225 return 0;\r
226}\r
227\r
228\r
7cb8516c 229int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){\r
230\r
84ca27b3 231 *key = -1;\r
7cb8516c 232\r
275d9e61 233 UsbCommand c = {CMD_MIFARE_CHKKEYS, {((blockNo & 0xff) | ((keyType & 0xff) << 8)), clear_trace, keycnt}}; \r
7cb8516c 234 memcpy(c.d.asBytes, keyBlock, 6 * keycnt);\r
235 SendCommand(&c);\r
236\r
237 UsbCommand resp;\r
275d9e61 238 if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) return 1; \r
7cb8516c 239 if ((resp.arg[0] & 0xff) != 0x01) return 2;\r
240 *key = bytes_to_num(resp.d.asBytes, 6);\r
241 return 0;\r
242}\r
243\r
275d9e61
OM
244int mfCheckKeysSec(uint8_t sectorCnt, uint8_t keyType, uint8_t timeout14a, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector){\r
245\r
246 uint8_t keyPtr = 0;\r
247\r
248 if (e_sector == NULL)\r
249 return -1;\r
250\r
251 UsbCommand c = {CMD_MIFARE_CHKKEYS, {((sectorCnt & 0xff) | ((keyType & 0xff) << 8)), (clear_trace | 0x02)|((timeout14a & 0xff) << 8), keycnt}}; \r
252 memcpy(c.d.asBytes, keyBlock, 6 * keycnt);\r
253 SendCommand(&c);\r
254\r
255 UsbCommand resp;\r
256 if (!WaitForResponseTimeoutW(CMD_ACK, &resp, MAX(3000, 1000 + 13 * sectorCnt * keycnt * (keyType == 2 ? 2 : 1)), false)) return 1; // timeout: 13 ms / fail auth\r
257 if ((resp.arg[0] & 0xff) != 0x01) return 2;\r
258 \r
259 bool foundAKey = false;\r
260 for(int sec = 0; sec < sectorCnt; sec++){\r
261 for(int keyAB = 0; keyAB < 2; keyAB++){\r
262 keyPtr = *(resp.d.asBytes + keyAB * 40 + sec);\r
263 if (keyPtr){\r
264 e_sector[sec].foundKey[keyAB] = true;\r
265 e_sector[sec].Key[keyAB] = bytes_to_num(keyBlock + (keyPtr - 1) * 6, 6);\r
266 foundAKey = true;\r
267 }\r
268 }\r
269 }\r
270 return foundAKey ? 0 : 3;\r
271}\r
272\r
9492e0b0 273// Compare 16 Bits out of cryptostate\r
274int Compare16Bits(const void * a, const void * b) {\r
275 if ((*(uint64_t*)b & 0x00ff000000ff0000) == (*(uint64_t*)a & 0x00ff000000ff0000)) return 0;\r
276 else if ((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000)) return 1;\r
277 else return -1;\r
f397b5cc
M
278}\r
279\r
7906cb41 280typedef\r
9492e0b0 281 struct {\r
282 union {\r
283 struct Crypto1State *slhead;\r
284 uint64_t *keyhead;\r
3f7c993d 285 } head;\r
9492e0b0 286 union {\r
287 struct Crypto1State *sltail;\r
288 uint64_t *keytail;\r
3f7c993d 289 } tail;\r
9492e0b0 290 uint32_t len;\r
291 uint32_t uid;\r
292 uint32_t blockNo;\r
293 uint32_t keyType;\r
294 uint32_t nt;\r
295 uint32_t ks1;\r
296 } StateList_t;\r
297\r
298\r
299// wrapper function for multi-threaded lfsr_recovery32\r
300void* nested_worker_thread(void *arg)\r
301{\r
302 struct Crypto1State *p1;\r
303 StateList_t *statelist = arg;\r
304\r
3f7c993d 305 statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid);\r
306 for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; p1++);\r
307 statelist->len = p1 - statelist->head.slhead;\r
308 statelist->tail.sltail = --p1;\r
309 qsort(statelist->head.slhead, statelist->len, sizeof(uint64_t), Compare16Bits);\r
7906cb41 310\r
3f7c993d 311 return statelist->head.slhead;\r
f397b5cc
M
312}\r
313\r
7906cb41 314int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate)\r
f397b5cc 315{\r
dc8ba239 316 uint16_t i;\r
f397b5cc 317 uint32_t uid;\r
902cb3c0 318 UsbCommand resp;\r
f397b5cc 319\r
9492e0b0 320 StateList_t statelists[2];\r
321 struct Crypto1State *p1, *p2, *p3, *p4;\r
7906cb41 322\r
f397b5cc 323 // flush queue\r
dc8ba239 324 WaitForResponseTimeout(CMD_ACK, NULL, 100);\r
7906cb41 325\r
9492e0b0 326 UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}};\r
f397b5cc 327 memcpy(c.d.asBytes, key, 6);\r
9492e0b0 328 SendCommand(&c);\r
f397b5cc 329\r
dc8ba239 330 if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {\r
331 return -1;\r
332 }\r
f397b5cc 333\r
dc8ba239 334 if (resp.arg[0]) {\r
335 return resp.arg[0]; // error during nested\r
336 }\r
7906cb41 337\r
dc8ba239 338 memcpy(&uid, resp.d.asBytes, 4);\r
339 PrintAndLog("uid:%08x trgbl=%d trgkey=%x", uid, (uint16_t)resp.arg[2] & 0xff, (uint16_t)resp.arg[2] >> 8);\r
7906cb41 340\r
dc8ba239 341 for (i = 0; i < 2; i++) {\r
342 statelists[i].blockNo = resp.arg[2] & 0xff;\r
343 statelists[i].keyType = (resp.arg[2] >> 8) & 0xff;\r
344 statelists[i].uid = uid;\r
345 memcpy(&statelists[i].nt, (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4);\r
346 memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4);\r
f397b5cc 347 }\r
7906cb41 348\r
f397b5cc 349 // calc keys\r
7906cb41 350\r
9492e0b0 351 pthread_t thread_id[2];\r
7906cb41 352\r
9492e0b0 353 // create and run worker threads\r
354 for (i = 0; i < 2; i++) {\r
355 pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]);\r
f397b5cc 356 }\r
7906cb41 357\r
9492e0b0 358 // wait for threads to terminate:\r
359 for (i = 0; i < 2; i++) {\r
3f7c993d 360 pthread_join(thread_id[i], (void*)&statelists[i].head.slhead);\r
f397b5cc
M
361 }\r
362\r
f397b5cc 363\r
9492e0b0 364 // the first 16 Bits of the cryptostate already contain part of our key.\r
365 // Create the intersection of the two lists based on these 16 Bits and\r
366 // roll back the cryptostate\r
7906cb41 367 p1 = p3 = statelists[0].head.slhead;\r
3f7c993d 368 p2 = p4 = statelists[1].head.slhead;\r
369 while (p1 <= statelists[0].tail.sltail && p2 <= statelists[1].tail.sltail) {\r
9492e0b0 370 if (Compare16Bits(p1, p2) == 0) {\r
371 struct Crypto1State savestate, *savep = &savestate;\r
372 savestate = *p1;\r
3f7c993d 373 while(Compare16Bits(p1, savep) == 0 && p1 <= statelists[0].tail.sltail) {\r
9492e0b0 374 *p3 = *p1;\r
375 lfsr_rollback_word(p3, statelists[0].nt ^ statelists[0].uid, 0);\r
376 p3++;\r
377 p1++;\r
378 }\r
379 savestate = *p2;\r
3f7c993d 380 while(Compare16Bits(p2, savep) == 0 && p2 <= statelists[1].tail.sltail) {\r
9492e0b0 381 *p4 = *p2;\r
382 lfsr_rollback_word(p4, statelists[1].nt ^ statelists[1].uid, 0);\r
383 p4++;\r
384 p2++;\r
385 }\r
386 }\r
387 else {\r
388 while (Compare16Bits(p1, p2) == -1) p1++;\r
389 while (Compare16Bits(p1, p2) == 1) p2++;\r
390 }\r
f397b5cc 391 }\r
7779d73c 392 *(uint64_t*)p3 = -1;\r
393 *(uint64_t*)p4 = -1;\r
3f7c993d 394 statelists[0].len = p3 - statelists[0].head.slhead;\r
395 statelists[1].len = p4 - statelists[1].head.slhead;\r
396 statelists[0].tail.sltail=--p3;\r
397 statelists[1].tail.sltail=--p4;\r
9492e0b0 398\r
399 // the statelists now contain possible keys. The key we are searching for must be in the\r
400 // intersection of both lists. Create the intersection:\r
7779d73c 401 qsort(statelists[0].head.keyhead, statelists[0].len, sizeof(uint64_t), compare_uint64);\r
402 qsort(statelists[1].head.keyhead, statelists[1].len, sizeof(uint64_t), compare_uint64);\r
403 statelists[0].len = intersection(statelists[0].head.keyhead, statelists[1].head.keyhead);\r
9492e0b0 404\r
405 memset(resultKey, 0, 6);\r
406 // The list may still contain several key candidates. Test each of them with mfCheckKeys\r
407 for (i = 0; i < statelists[0].len; i++) {\r
408 uint8_t keyBlock[6];\r
409 uint64_t key64;\r
3f7c993d 410 crypto1_get_lfsr(statelists[0].head.slhead + i, &key64);\r
9492e0b0 411 num_to_bytes(key64, 6, keyBlock);\r
412 key64 = 0;\r
5330f532 413 if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) {\r
9492e0b0 414 num_to_bytes(key64, 6, resultKey);\r
415 break;\r
416 }\r
417 }\r
7906cb41 418\r
3f7c993d 419 free(statelists[0].head.slhead);\r
420 free(statelists[1].head.slhead);\r
7906cb41 421\r
f397b5cc
M
422 return 0;\r
423}\r
424\r
55acbb2a
M
425// EMULATOR\r
426\r
8556b852 427int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) {\r
545a1f38 428 UsbCommand c = {CMD_MIFARE_EML_MEMGET, {blockNum, blocksCount, 0}};\r
902cb3c0 429 SendCommand(&c);\r
3a05a1e7
OM
430\r
431 UsbCommand resp;\r
902cb3c0 432 if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) return 1;\r
433 memcpy(data, resp.d.asBytes, blocksCount * 16);\r
8556b852
M
434 return 0;\r
435}\r
436\r
437int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) {\r
545a1f38 438 UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}};\r
7906cb41 439 memcpy(c.d.asBytes, data, blocksCount * 16);\r
545a1f38 440 SendCommand(&c);\r
8556b852
M
441 return 0;\r
442}\r
443\r
55acbb2a
M
444// "MAGIC" CARD\r
445\r
7cb8516c 446int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) {\r
447 uint8_t isOK = 0;\r
3bba7dea 448\r
7cb8516c 449 UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}};\r
450 SendCommand(&c);\r
3a05a1e7 451\r
14d76577 452 UsbCommand resp;\r
7cb8516c 453 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {\r
454 isOK = resp.arg[0] & 0xff;\r
455 memcpy(data, resp.d.asBytes, 16);\r
456 if (!isOK) return 2;\r
457 } else {\r
458 PrintAndLog("Command execute timeout");\r
459 return 1;\r
80b1b53f 460 }\r
7cb8516c 461 return 0;\r
f774db95
M
462}\r
463\r
6a1f2d82 464int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, bool wantWipe, uint8_t params) {\r
0675f200 465\r
3fe4ff4f 466 uint8_t isOK = 0;\r
467 UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}};\r
7906cb41 468 memcpy(c.d.asBytes, data, 16);\r
545a1f38 469 SendCommand(&c);\r
3a05a1e7 470\r
14d76577 471 UsbCommand resp;\r
3a05a1e7 472 if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {\r
902cb3c0 473 isOK = resp.arg[0] & 0xff;\r
7906cb41 474 if (uid != NULL)\r
80b1b53f 475 memcpy(uid, resp.d.asBytes, 4);\r
7906cb41 476 if (!isOK)\r
80b1b53f 477 return 2;\r
0675f200
M
478 } else {\r
479 PrintAndLog("Command execute timeout");\r
480 return 1;\r
481 }\r
3a05a1e7 482\r
0675f200
M
483 return 0;\r
484}\r
545a1f38 485\r
3a05a1e7
OM
486int mfCWipe(uint32_t numSectors, bool gen1b, bool wantWipe, bool wantFill) {\r
487 uint8_t isOK = 0;\r
488 uint8_t cmdParams = wantWipe + wantFill * 0x02 + gen1b * 0x04;\r
489 UsbCommand c = {CMD_MIFARE_CWIPE, {numSectors, cmdParams, 0}};\r
490 SendCommand(&c);\r
491\r
492 UsbCommand resp;\r
493 WaitForResponse(CMD_ACK,&resp);\r
494 isOK = resp.arg[0] & 0xff;\r
495 \r
496 return isOK;\r
497}\r
498\r
499int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID) {\r
7cb8516c 500 uint8_t oldblock0[16] = {0x00};\r
501 uint8_t block0[16] = {0x00};\r
3a05a1e7 502 int gen = 0, res;\r
7906cb41
F
503\r
504 gen = mfCIdentify();\r
505\r
3a05a1e7
OM
506 /* generation 1a magic card by default */\r
507 uint8_t cmdParams = CSETBLOCK_SINGLE_OPER;\r
7906cb41
F
508 if (gen == 2) {\r
509 /* generation 1b magic card */\r
3a05a1e7 510 cmdParams = CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B;\r
7906cb41 511 }\r
3a05a1e7
OM
512 \r
513 res = mfCGetBlock(0, oldblock0, cmdParams);\r
545a1f38 514\r
3a05a1e7 515 if (res == 0) {\r
7cb8516c 516 memcpy(block0, oldblock0, 16);\r
517 PrintAndLog("old block 0: %s", sprint_hex(block0,16));\r
545a1f38 518 } else {\r
7cb8516c 519 PrintAndLog("Couldn't get old data. Will write over the last bytes of Block 0.");\r
545a1f38 520 }\r
7cb8516c 521\r
522 // fill in the new values\r
523 // UID\r
7906cb41 524 memcpy(block0, uid, 4);\r
7cb8516c 525 // Mifare UID BCC\r
3a05a1e7 526 block0[4] = block0[0] ^ block0[1] ^ block0[2] ^ block0[3];\r
7cb8516c 527 // mifare classic SAK(byte 5) and ATQA(byte 6 and 7, reversed)\r
3a05a1e7
OM
528 if (sak != NULL)\r
529 block0[5] = sak[0];\r
530 if (atqa != NULL) {\r
531 block0[6] = atqa[1];\r
532 block0[7] = atqa[0];\r
7cb8516c 533 }\r
3a05a1e7 534 PrintAndLog("new block 0: %s", sprint_hex(block0, 16));\r
7906cb41 535\r
3a05a1e7
OM
536 res = mfCSetBlock(0, block0, oldUID, false, cmdParams);\r
537 if (res) {\r
538 PrintAndLog("Can't set block 0. Error: %d", res);\r
539 return res;\r
7906cb41 540 }\r
3a05a1e7
OM
541 \r
542 return 0;\r
543}\r
544\r
e17660d5
OM
545int mfCIdentify() {\r
546 UsbCommand c = {CMD_MIFARE_CIDENT, {0, 0, 0}};\r
3a05a1e7 547 SendCommand(&c);\r
e17660d5 548 UsbCommand resp;\r
3a05a1e7
OM
549 WaitForResponse(CMD_ACK,&resp);\r
550\r
551 uint8_t isGeneration = resp.arg[0] & 0xff;\r
552 switch( isGeneration ){\r
553 case 1: PrintAndLog("Chinese magic backdoor commands (GEN 1a) detected"); break;\r
554 case 2: PrintAndLog("Chinese magic backdoor command (GEN 1b) detected"); break;\r
555 default: PrintAndLog("No chinese magic backdoor command detected"); break;\r
556 }\r
557\r
3a05a1e7 558 return (int) isGeneration;\r
545a1f38 559}\r
55acbb2a 560\r
3a05a1e7 561\r
55acbb2a
M
562// SNIFFER\r
563\r
e0c635d1
M
564// constants\r
565static uint8_t trailerAccessBytes[4] = {0x08, 0x77, 0x8F, 0x00};\r
566\r
55acbb2a 567// variables\r
e4691591 568char logHexFileName[FILE_PATH_SIZE] = {0x00};\r
e0c635d1 569static uint8_t traceCard[4096] = {0x00};\r
e4691591 570static char traceFileName[FILE_PATH_SIZE] = {0x00};\r
55acbb2a
M
571static int traceState = TRACE_IDLE;\r
572static uint8_t traceCurBlock = 0;\r
573static uint8_t traceCurKey = 0;\r
574\r
575struct Crypto1State *traceCrypto1 = NULL;\r
576\r
577struct Crypto1State *revstate;\r
578uint64_t lfsr;\r
579uint32_t ks2;\r
580uint32_t ks3;\r
581\r
582uint32_t uid; // serial number\r
583uint32_t nt; // tag challenge\r
584uint32_t nr_enc; // encrypted reader challenge\r
585uint32_t ar_enc; // encrypted reader response\r
586uint32_t at_enc; // encrypted tag response\r
587\r
e0c635d1
M
588int isTraceCardEmpty(void) {\r
589 return ((traceCard[0] == 0) && (traceCard[1] == 0) && (traceCard[2] == 0) && (traceCard[3] == 0));\r
590}\r
55acbb2a 591\r
e0c635d1 592int isBlockEmpty(int blockN) {\r
7906cb41 593 for (int i = 0; i < 16; i++)\r
e0c635d1 594 if (traceCard[blockN * 16 + i] != 0) return 0;\r
55acbb2a 595\r
e0c635d1
M
596 return 1;\r
597}\r
598\r
599int isBlockTrailer(int blockN) {\r
3a05a1e7 600 return ((blockN & 0x03) == 0x03);\r
e0c635d1
M
601}\r
602\r
7cb8516c 603int saveTraceCard(void) {\r
604 FILE * f;\r
7906cb41 605\r
7cb8516c 606 if ((!strlen(traceFileName)) || (isTraceCardEmpty())) return 0;\r
7906cb41 607\r
7cb8516c 608 f = fopen(traceFileName, "w+");\r
609 if ( !f ) return 1;\r
7906cb41 610\r
7cb8516c 611 for (int i = 0; i < 64; i++) { // blocks\r
612 for (int j = 0; j < 16; j++) // bytes\r
7906cb41 613 fprintf(f, "%02x", *(traceCard + i * 16 + j));\r
a0349483 614 if (i < 63)\r
615 fprintf(f,"\n");\r
7cb8516c 616 }\r
617 fclose(f);\r
618 return 0;\r
619}\r
620\r
e0c635d1
M
621int loadTraceCard(uint8_t *tuid) {\r
622 FILE * f;\r
80b1b53f 623 char buf[64] = {0x00};\r
624 uint8_t buf8[64] = {0x00};\r
e0c635d1 625 int i, blockNum;\r
7906cb41
F
626\r
627 if (!isTraceCardEmpty())\r
80b1b53f 628 saveTraceCard();\r
7906cb41 629\r
55acbb2a
M
630 memset(traceCard, 0x00, 4096);\r
631 memcpy(traceCard, tuid + 3, 4);\r
80b1b53f 632\r
e0c635d1
M
633 FillFileNameByUID(traceFileName, tuid, ".eml", 7);\r
634\r
635 f = fopen(traceFileName, "r");\r
e6432f05 636 if (!f) return 1;\r
7906cb41 637\r
e0c635d1 638 blockNum = 0;\r
7906cb41 639\r
e0c635d1 640 while(!feof(f)){\r
7906cb41 641\r
e0c635d1 642 memset(buf, 0, sizeof(buf));\r
759c16b3 643 if (fgets(buf, sizeof(buf), f) == NULL) {\r
ca4714cd
MHS
644 PrintAndLog("File reading error.");\r
645 fclose(f);\r
759c16b3 646 return 2;\r
ca4714cd 647 }\r
e0c635d1
M
648\r
649 if (strlen(buf) < 32){\r
650 if (feof(f)) break;\r
651 PrintAndLog("File content error. Block data must include 32 HEX symbols");\r
ca4714cd 652 fclose(f);\r
e0c635d1
M
653 return 2;\r
654 }\r
655 for (i = 0; i < 32; i += 2)\r
656 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);\r
657\r
658 memcpy(traceCard + blockNum * 16, buf8, 16);\r
659\r
660 blockNum++;\r
661 }\r
662 fclose(f);\r
3a05a1e7 663\r
e0c635d1
M
664 return 0;\r
665}\r
666\r
e0c635d1
M
667int mfTraceInit(uint8_t *tuid, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile) {\r
668\r
7906cb41 669 if (traceCrypto1)\r
80b1b53f 670 crypto1_destroy(traceCrypto1);\r
671\r
e0c635d1
M
672 traceCrypto1 = NULL;\r
673\r
7906cb41 674 if (wantSaveToEmlFile)\r
80b1b53f 675 loadTraceCard(tuid);\r
7906cb41 676\r
55acbb2a
M
677 traceCard[4] = traceCard[0] ^ traceCard[1] ^ traceCard[2] ^ traceCard[3];\r
678 traceCard[5] = sak;\r
679 memcpy(&traceCard[6], atqa, 2);\r
680 traceCurBlock = 0;\r
681 uid = bytes_to_num(tuid + 3, 4);\r
7906cb41 682\r
55acbb2a 683 traceState = TRACE_IDLE;\r
3a05a1e7 684\r
55acbb2a
M
685 return 0;\r
686}\r
687\r
688void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted){\r
689 uint8_t bt = 0;\r
690 int i;\r
7906cb41 691\r
55acbb2a
M
692 if (len != 1) {\r
693 for (i = 0; i < len; i++)\r
694 data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i];\r
695 } else {\r
696 bt = 0;\r
697 for (i = 0; i < 4; i++)\r
698 bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], i)) << i;\r
7906cb41 699\r
55acbb2a
M
700 data[0] = bt;\r
701 }\r
702 return;\r
703}\r
704\r
705\r
6a1f2d82 706int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {\r
55acbb2a
M
707 uint8_t data[64];\r
708\r
709 if (traceState == TRACE_ERROR) return 1;\r
710 if (len > 64) {\r
711 traceState = TRACE_ERROR;\r
712 return 1;\r
713 }\r
7906cb41 714\r
55acbb2a
M
715 memcpy(data, data_src, len);\r
716 if ((traceCrypto1) && ((traceState == TRACE_IDLE) || (traceState > TRACE_AUTH_OK))) {\r
717 mf_crypto1_decrypt(traceCrypto1, data, len, 0);\r
718 PrintAndLog("dec> %s", sprint_hex(data, len));\r
7906cb41 719 AddLogHex(logHexFileName, "dec> ", data, len);\r
55acbb2a 720 }\r
7906cb41 721\r
55acbb2a 722 switch (traceState) {\r
7906cb41 723 case TRACE_IDLE:\r
8b6a93df
M
724 // check packet crc16!\r
725 if ((len >= 4) && (!CheckCrc14443(CRC_14443_A, data, len))) {\r
726 PrintAndLog("dec> CRC ERROR!!!");\r
7906cb41 727 AddLogLine(logHexFileName, "dec> ", "CRC ERROR!!!");\r
8b6a93df
M
728 traceState = TRACE_ERROR; // do not decrypt the next commands\r
729 return 1;\r
730 }\r
7906cb41 731\r
55acbb2a
M
732 // AUTHENTICATION\r
733 if ((len ==4) && ((data[0] == 0x60) || (data[0] == 0x61))) {\r
734 traceState = TRACE_AUTH1;\r
735 traceCurBlock = data[1];\r
736 traceCurKey = data[0] == 60 ? 1:0;\r
737 return 0;\r
738 }\r
739\r
740 // READ\r
741 if ((len ==4) && ((data[0] == 0x30))) {\r
742 traceState = TRACE_READ_DATA;\r
743 traceCurBlock = data[1];\r
744 return 0;\r
745 }\r
746\r
747 // WRITE\r
748 if ((len ==4) && ((data[0] == 0xA0))) {\r
749 traceState = TRACE_WRITE_OK;\r
750 traceCurBlock = data[1];\r
751 return 0;\r
752 }\r
753\r
754 // HALT\r
755 if ((len ==4) && ((data[0] == 0x50) && (data[1] == 0x00))) {\r
756 traceState = TRACE_ERROR; // do not decrypt the next commands\r
757 return 0;\r
758 }\r
7906cb41 759\r
55acbb2a
M
760 return 0;\r
761 break;\r
7906cb41
F
762\r
763 case TRACE_READ_DATA:\r
55acbb2a
M
764 if (len == 18) {\r
765 traceState = TRACE_IDLE;\r
766\r
e0c635d1
M
767 if (isBlockTrailer(traceCurBlock)) {\r
768 memcpy(traceCard + traceCurBlock * 16 + 6, data + 6, 4);\r
769 } else {\r
770 memcpy(traceCard + traceCurBlock * 16, data, 16);\r
771 }\r
772 if (wantSaveToEmlFile) saveTraceCard();\r
55acbb2a
M
773 return 0;\r
774 } else {\r
775 traceState = TRACE_ERROR;\r
776 return 1;\r
777 }\r
778 break;\r
779\r
7906cb41 780 case TRACE_WRITE_OK:\r
97d582a6 781 if ((len == 1) && (data[0] == 0x0a)) {\r
55acbb2a
M
782 traceState = TRACE_WRITE_DATA;\r
783\r
784 return 0;\r
785 } else {\r
786 traceState = TRACE_ERROR;\r
787 return 1;\r
788 }\r
789 break;\r
790\r
7906cb41 791 case TRACE_WRITE_DATA:\r
55acbb2a
M
792 if (len == 18) {\r
793 traceState = TRACE_IDLE;\r
794\r
795 memcpy(traceCard + traceCurBlock * 16, data, 16);\r
e0c635d1 796 if (wantSaveToEmlFile) saveTraceCard();\r
55acbb2a
M
797 return 0;\r
798 } else {\r
799 traceState = TRACE_ERROR;\r
800 return 1;\r
801 }\r
802 break;\r
803\r
7906cb41 804 case TRACE_AUTH1:\r
55acbb2a
M
805 if (len == 4) {\r
806 traceState = TRACE_AUTH2;\r
55acbb2a
M
807 nt = bytes_to_num(data, 4);\r
808 return 0;\r
809 } else {\r
810 traceState = TRACE_ERROR;\r
811 return 1;\r
812 }\r
813 break;\r
814\r
7906cb41 815 case TRACE_AUTH2:\r
55acbb2a
M
816 if (len == 8) {\r
817 traceState = TRACE_AUTH_OK;\r
818\r
819 nr_enc = bytes_to_num(data, 4);\r
820 ar_enc = bytes_to_num(data + 4, 4);\r
821 return 0;\r
822 } else {\r
823 traceState = TRACE_ERROR;\r
824 return 1;\r
825 }\r
826 break;\r
827\r
7906cb41 828 case TRACE_AUTH_OK:\r
55acbb2a
M
829 if (len ==4) {\r
830 traceState = TRACE_IDLE;\r
831\r
2ba37081 832 if (!traceCrypto1) {\r
833 at_enc = bytes_to_num(data, 4);\r
834\r
835 // decode key here)\r
836 ks2 = ar_enc ^ prng_successor(nt, 64);\r
837 ks3 = at_enc ^ prng_successor(nt, 96);\r
838 revstate = lfsr_recovery64(ks2, ks3);\r
839 lfsr_rollback_word(revstate, 0, 0);\r
840 lfsr_rollback_word(revstate, 0, 0);\r
841 lfsr_rollback_word(revstate, nr_enc, 1);\r
842 lfsr_rollback_word(revstate, uid ^ nt, 0);\r
843\r
844 crypto1_get_lfsr(revstate, &lfsr);\r
845 printf("key> %x%x\n", (unsigned int)((lfsr & 0xFFFFFFFF00000000) >> 32), (unsigned int)(lfsr & 0xFFFFFFFF));\r
846 AddLogUint64(logHexFileName, "key> ", lfsr);\r
847 } else {\r
848 printf("key> nested not implemented!\n");\r
849 at_enc = bytes_to_num(data, 4);\r
850 \r
851 crypto1_destroy(traceCrypto1);\r
3fe4ff4f 852\r
2ba37081 853 // not implemented\r
854 traceState = TRACE_ERROR;\r
855 }\r
7906cb41 856\r
e0c635d1
M
857 int blockShift = ((traceCurBlock & 0xFC) + 3) * 16;\r
858 if (isBlockEmpty((traceCurBlock & 0xFC) + 3)) memcpy(traceCard + blockShift + 6, trailerAccessBytes, 4);\r
7906cb41 859\r
55acbb2a 860 if (traceCurKey) {\r
e0c635d1 861 num_to_bytes(lfsr, 6, traceCard + blockShift + 10);\r
55acbb2a 862 } else {\r
e0c635d1 863 num_to_bytes(lfsr, 6, traceCard + blockShift);\r
55acbb2a 864 }\r
e0c635d1 865 if (wantSaveToEmlFile) saveTraceCard();\r
55acbb2a
M
866\r
867 if (traceCrypto1) {\r
868 crypto1_destroy(traceCrypto1);\r
869 }\r
7906cb41 870\r
55acbb2a
M
871 // set cryptosystem state\r
872 traceCrypto1 = lfsr_recovery64(ks2, ks3);\r
55acbb2a
M
873 return 0;\r
874 } else {\r
875 traceState = TRACE_ERROR;\r
876 return 1;\r
877 }\r
878 break;\r
879\r
7906cb41 880 default:\r
55acbb2a
M
881 traceState = TRACE_ERROR;\r
882 return 1;\r
883 }\r
884\r
885 return 0;\r
886}\r
1a5a73ab 887\r
3a05a1e7
OM
888// DECODING\r
889\r
1a5a73ab 890int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len){\r
891 /*\r
892 uint32_t nt; // tag challenge\r
893 uint32_t ar_enc; // encrypted reader response\r
894 uint32_t at_enc; // encrypted tag response\r
895 */\r
896 if (traceCrypto1) {\r
897 crypto1_destroy(traceCrypto1);\r
898 }\r
899 ks2 = ar_enc ^ prng_successor(nt, 64);\r
900 ks3 = at_enc ^ prng_successor(nt, 96);\r
901 traceCrypto1 = lfsr_recovery64(ks2, ks3);\r
902\r
903 mf_crypto1_decrypt(traceCrypto1, data, len, 0);\r
904\r
905 PrintAndLog("Decrypted data: [%s]", sprint_hex(data,len) );\r
906 crypto1_destroy(traceCrypto1);\r
907 return 0;\r
908}\r
7906cb41 909\r
fe6bf3c5
OM
910/** validate_prng_nonce\r
911 * Determine if nonce is deterministic. ie: Suspectable to Darkside attack.\r
912 * returns\r
913 * true = weak prng\r
914 * false = hardend prng\r
915 */\r
916bool validate_prng_nonce(uint32_t nonce) {\r
917 uint16_t *dist = 0;\r
918 uint16_t x, i;\r
919\r
920 dist = malloc(2 << 16);\r
921 if(!dist)\r
922 return -1;\r
923\r
924 // init prng table:\r
925 for (x = i = 1; i; ++i) {\r
926 dist[(x & 0xff) << 8 | x >> 8] = i;\r
927 x = x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15;\r
928 }\r
929 \r
930 uint32_t res = (65535 - dist[nonce >> 16] + dist[nonce & 0xffff]) % 65535;\r
931 \r
932 free(dist); \r
933 return (res == 16);\r
934}\r
935\r
936/* Detect Tag Prng, \r
937* function performs a partial AUTH, where it tries to authenticate against block0, key A, but only collects tag nonce.\r
938* the tag nonce is check to see if it has a predictable PRNG.\r
939* @returns \r
940* TRUE if tag uses WEAK prng (ie Now the NACK bug also needs to be present for Darkside attack)\r
941* FALSE is tag uses HARDEND prng (ie hardnested attack possible, with known key)\r
942*/\r
943int DetectClassicPrng(void){\r
944\r
945 UsbCommand resp, respA; \r
946 uint8_t cmd[] = {0x60, 0x00}; // MIFARE_AUTH_KEYA\r
947 uint32_t flags = ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_RATS;\r
948 \r
949 UsbCommand c = {CMD_READER_ISO_14443a, {flags, sizeof(cmd), 0}};\r
950 memcpy(c.d.asBytes, cmd, sizeof(cmd));\r
951\r
952 clearCommandBuffer();\r
953 SendCommand(&c);\r
954 if (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {\r
955 PrintAndLog("PRNG UID: Reply timeout.");\r
956 return -1;\r
957 }\r
958 \r
959 // if select tag failed.\r
960 if (resp.arg[0] == 0) {\r
961 PrintAndLog("PRNG error: selecting tag failed, can't detect prng.");\r
962 return -1;\r
963 }\r
964 \r
965 if (!WaitForResponseTimeout(CMD_ACK, &respA, 5000)) {\r
966 PrintAndLog("PRNG data: Reply timeout.");\r
967 return -1;\r
968 }\r
969\r
970 // check respA\r
971 if (respA.arg[0] != 4) {\r
972 PrintAndLog("PRNG data error: Wrong length: %d", respA.arg[0]);\r
973 return -1;\r
974 }\r
975\r
976 uint32_t nonce = bytes_to_num(respA.d.asBytes, respA.arg[0]);\r
977 return validate_prng_nonce(nonce);\r
978}\r
Impressum, Datenschutz