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