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