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