]> git.zerfleddert.de Git - proxmark3-svn/blob - client/mifarehost.c
`hf emv readrec` works and some changes in help
[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 "comms.h"
20 #include "usb_cmd.h"
21 #include "cmdmain.h"
22 #include "ui.h"
23 #include "parity.h"
24 #include "util.h"
25 #include "iso14443crc.h"
26
27 #include "mifare.h"
28
29 // mifare tracer flags used in mfTraceDecode()
30 #define TRACE_IDLE 0x00
31 #define TRACE_AUTH1 0x01
32 #define TRACE_AUTH2 0x02
33 #define TRACE_AUTH_OK 0x03
34 #define TRACE_READ_DATA 0x04
35 #define TRACE_WRITE_OK 0x05
36 #define TRACE_WRITE_DATA 0x06
37 #define TRACE_ERROR 0xFF
38
39
40 static int compare_uint64(const void *a, const void *b) {
41 // didn't work: (the result is truncated to 32 bits)
42 //return (*(int64_t*)b - *(int64_t*)a);
43
44 // better:
45 if (*(uint64_t*)b == *(uint64_t*)a) return 0;
46 else if (*(uint64_t*)b < *(uint64_t*)a) return 1;
47 else return -1;
48 }
49
50
51 // create the intersection (common members) of two sorted lists. Lists are terminated by -1. Result will be in list1. Number of elements is returned.
52 static uint32_t intersection(uint64_t *list1, uint64_t *list2)
53 {
54 if (list1 == NULL || list2 == NULL) {
55 return 0;
56 }
57 uint64_t *p1, *p2, *p3;
58 p1 = p3 = list1;
59 p2 = list2;
60
61 while ( *p1 != -1 && *p2 != -1 ) {
62 if (compare_uint64(p1, p2) == 0) {
63 *p3++ = *p1++;
64 p2++;
65 }
66 else {
67 while (compare_uint64(p1, p2) < 0) ++p1;
68 while (compare_uint64(p1, p2) > 0) ++p2;
69 }
70 }
71 *p3 = -1;
72 return p3 - list1;
73 }
74
75
76 // Darkside attack (hf mf mifare)
77 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) {
78 struct Crypto1State *states;
79 uint32_t i, pos;
80 uint8_t bt, ks3x[8], par[8][8];
81 uint64_t key_recovered;
82 uint64_t *keylist;
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, ar, 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, ar = 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 = (uint32_t)bytes_to_num(resp.d.asBytes + 24, 4);
163 ar = (uint32_t)bytes_to_num(resp.d.asBytes + 28, 4);
164 break;
165 }
166 }
167
168 if (par_list == 0 && c.arg[0] == true) {
169 PrintAndLog("Parity is all zero. Most likely this card sends NACK on every failed authentication.");
170 }
171 c.arg[0] = false;
172
173 keycount = nonce2key(uid, nt, nr, ar, 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+(j*6));
205 } else {
206 num_to_bytes(keylist[i*max_keys + j], 6, keyBlock+(j*6));
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
301 #ifdef __has_attribute
302 #if __has_attribute(force_align_arg_pointer)
303 __attribute__((force_align_arg_pointer))
304 #endif
305 #endif
306 *nested_worker_thread(void *arg)
307 {
308 struct Crypto1State *p1;
309 StateList_t *statelist = arg;
310
311 statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid);
312 for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; p1++);
313 statelist->len = p1 - statelist->head.slhead;
314 statelist->tail.sltail = --p1;
315 qsort(statelist->head.slhead, statelist->len, sizeof(uint64_t), Compare16Bits);
316
317 return statelist->head.slhead;
318 }
319
320
321 int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate)
322 {
323 uint16_t i;
324 uint32_t uid;
325 UsbCommand resp;
326
327 StateList_t statelists[2];
328 struct Crypto1State *p1, *p2, *p3, *p4;
329
330 // flush queue
331 (void)WaitForResponseTimeout(CMD_ACK,NULL,100);
332
333 UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}};
334 memcpy(c.d.asBytes, key, 6);
335 SendCommand(&c);
336
337 if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {
338 return -1;
339 }
340
341 if (resp.arg[0]) {
342 return resp.arg[0]; // error during nested
343 }
344
345 memcpy(&uid, resp.d.asBytes, 4);
346 PrintAndLog("uid:%08x trgbl=%d trgkey=%x", uid, (uint16_t)resp.arg[2] & 0xff, (uint16_t)resp.arg[2] >> 8);
347
348 for (i = 0; i < 2; i++) {
349 statelists[i].blockNo = resp.arg[2] & 0xff;
350 statelists[i].keyType = (resp.arg[2] >> 8) & 0xff;
351 statelists[i].uid = uid;
352 memcpy(&statelists[i].nt, (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4);
353 memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4);
354 }
355
356 // calc keys
357
358 pthread_t thread_id[2];
359
360 // create and run worker threads
361 for (i = 0; i < 2; i++) {
362 pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]);
363 }
364
365 // wait for threads to terminate:
366 for (i = 0; i < 2; i++) {
367 pthread_join(thread_id[i], (void*)&statelists[i].head.slhead);
368 }
369
370
371 // the first 16 Bits of the cryptostate already contain part of our key.
372 // Create the intersection of the two lists based on these 16 Bits and
373 // roll back the cryptostate
374 p1 = p3 = statelists[0].head.slhead;
375 p2 = p4 = statelists[1].head.slhead;
376 while (p1 <= statelists[0].tail.sltail && p2 <= statelists[1].tail.sltail) {
377 if (Compare16Bits(p1, p2) == 0) {
378 struct Crypto1State savestate, *savep = &savestate;
379 savestate = *p1;
380 while(Compare16Bits(p1, savep) == 0 && p1 <= statelists[0].tail.sltail) {
381 *p3 = *p1;
382 lfsr_rollback_word(p3, statelists[0].nt ^ statelists[0].uid, 0);
383 p3++;
384 p1++;
385 }
386 savestate = *p2;
387 while(Compare16Bits(p2, savep) == 0 && p2 <= statelists[1].tail.sltail) {
388 *p4 = *p2;
389 lfsr_rollback_word(p4, statelists[1].nt ^ statelists[1].uid, 0);
390 p4++;
391 p2++;
392 }
393 }
394 else {
395 while (Compare16Bits(p1, p2) == -1) p1++;
396 while (Compare16Bits(p1, p2) == 1) p2++;
397 }
398 }
399 *(uint64_t*)p3 = -1;
400 *(uint64_t*)p4 = -1;
401 statelists[0].len = p3 - statelists[0].head.slhead;
402 statelists[1].len = p4 - statelists[1].head.slhead;
403 statelists[0].tail.sltail=--p3;
404 statelists[1].tail.sltail=--p4;
405
406 // the statelists now contain possible keys. The key we are searching for must be in the
407 // intersection of both lists. Create the intersection:
408 qsort(statelists[0].head.keyhead, statelists[0].len, sizeof(uint64_t), compare_uint64);
409 qsort(statelists[1].head.keyhead, statelists[1].len, sizeof(uint64_t), compare_uint64);
410 statelists[0].len = intersection(statelists[0].head.keyhead, statelists[1].head.keyhead);
411
412 memset(resultKey, 0, 6);
413 // The list may still contain several key candidates. Test each of them with mfCheckKeys
414 for (i = 0; i < statelists[0].len; i++) {
415 uint8_t keyBlock[6];
416 uint64_t key64;
417 crypto1_get_lfsr(statelists[0].head.slhead + i, &key64);
418 num_to_bytes(key64, 6, keyBlock);
419 key64 = 0;
420 if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) {
421 num_to_bytes(key64, 6, resultKey);
422 break;
423 }
424 }
425
426 free(statelists[0].head.slhead);
427 free(statelists[1].head.slhead);
428
429 return 0;
430 }
431
432 // EMULATOR
433
434 int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) {
435 UsbCommand c = {CMD_MIFARE_EML_MEMGET, {blockNum, blocksCount, 0}};
436 SendCommand(&c);
437
438 UsbCommand resp;
439 if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) return 1;
440 memcpy(data, resp.d.asBytes, blocksCount * 16);
441 return 0;
442 }
443
444 int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) {
445 UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}};
446 memcpy(c.d.asBytes, data, blocksCount * 16);
447 SendCommand(&c);
448 return 0;
449 }
450
451 // "MAGIC" CARD
452
453 int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) {
454 uint8_t isOK = 0;
455
456 UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}};
457 SendCommand(&c);
458
459 UsbCommand resp;
460 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
461 isOK = resp.arg[0] & 0xff;
462 memcpy(data, resp.d.asBytes, 16);
463 if (!isOK) return 2;
464 } else {
465 PrintAndLog("Command execute timeout");
466 return 1;
467 }
468 return 0;
469 }
470
471 int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, bool wantWipe, uint8_t params) {
472
473 uint8_t isOK = 0;
474 UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}};
475 memcpy(c.d.asBytes, data, 16);
476 SendCommand(&c);
477
478 UsbCommand resp;
479 if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {
480 isOK = resp.arg[0] & 0xff;
481 if (uid != NULL)
482 memcpy(uid, resp.d.asBytes, 4);
483 if (!isOK)
484 return 2;
485 } else {
486 PrintAndLog("Command execute timeout");
487 return 1;
488 }
489
490 return 0;
491 }
492
493 int mfCWipe(uint32_t numSectors, bool gen1b, bool wantWipe, bool wantFill) {
494 uint8_t isOK = 0;
495 uint8_t cmdParams = wantWipe + wantFill * 0x02 + gen1b * 0x04;
496 UsbCommand c = {CMD_MIFARE_CWIPE, {numSectors, cmdParams, 0}};
497 SendCommand(&c);
498
499 UsbCommand resp;
500 WaitForResponse(CMD_ACK,&resp);
501 isOK = resp.arg[0] & 0xff;
502
503 return isOK;
504 }
505
506 int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID) {
507 uint8_t oldblock0[16] = {0x00};
508 uint8_t block0[16] = {0x00};
509 int gen = 0, res;
510
511 gen = mfCIdentify();
512
513 /* generation 1a magic card by default */
514 uint8_t cmdParams = CSETBLOCK_SINGLE_OPER;
515 if (gen == 2) {
516 /* generation 1b magic card */
517 cmdParams = CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B;
518 }
519
520 res = mfCGetBlock(0, oldblock0, cmdParams);
521
522 if (res == 0) {
523 memcpy(block0, oldblock0, 16);
524 PrintAndLog("old block 0: %s", sprint_hex(block0,16));
525 } else {
526 PrintAndLog("Couldn't get old data. Will write over the last bytes of Block 0.");
527 }
528
529 // fill in the new values
530 // UID
531 memcpy(block0, uid, 4);
532 // Mifare UID BCC
533 block0[4] = block0[0] ^ block0[1] ^ block0[2] ^ block0[3];
534 // mifare classic SAK(byte 5) and ATQA(byte 6 and 7, reversed)
535 if (sak != NULL)
536 block0[5] = sak[0];
537 if (atqa != NULL) {
538 block0[6] = atqa[1];
539 block0[7] = atqa[0];
540 }
541 PrintAndLog("new block 0: %s", sprint_hex(block0, 16));
542
543 res = mfCSetBlock(0, block0, oldUID, false, cmdParams);
544 if (res) {
545 PrintAndLog("Can't set block 0. Error: %d", res);
546 return res;
547 }
548
549 return 0;
550 }
551
552 int mfCIdentify() {
553 UsbCommand c = {CMD_MIFARE_CIDENT, {0, 0, 0}};
554 SendCommand(&c);
555 UsbCommand resp;
556 WaitForResponse(CMD_ACK,&resp);
557
558 uint8_t isGeneration = resp.arg[0] & 0xff;
559 switch( isGeneration ){
560 case 1: PrintAndLog("Chinese magic backdoor commands (GEN 1a) detected"); break;
561 case 2: PrintAndLog("Chinese magic backdoor command (GEN 1b) detected"); break;
562 default: PrintAndLog("No chinese magic backdoor command detected"); break;
563 }
564
565 return (int) isGeneration;
566 }
567
568
569 // SNIFFER
570
571 // constants
572 static uint8_t trailerAccessBytes[4] = {0x08, 0x77, 0x8F, 0x00};
573
574 // variables
575 char logHexFileName[FILE_PATH_SIZE] = {0x00};
576 static uint8_t traceCard[4096] = {0x00};
577 static char traceFileName[FILE_PATH_SIZE] = {0x00};
578 static int traceState = TRACE_IDLE;
579 static uint8_t traceCurBlock = 0;
580 static uint8_t traceCurKey = 0;
581
582 struct Crypto1State *traceCrypto1 = NULL;
583
584 struct Crypto1State *revstate;
585 uint64_t lfsr;
586 uint64_t ui64Key;
587 uint32_t ks2;
588 uint32_t ks3;
589
590 uint32_t uid; // serial number
591 uint32_t nt; // tag challenge
592 uint32_t nt_enc; // encrypted tag challenge
593 uint8_t nt_enc_par; // encrypted tag challenge parity
594 uint32_t nr_enc; // encrypted reader challenge
595 uint32_t ar_enc; // encrypted reader response
596 uint8_t ar_enc_par; // encrypted reader response parity
597 uint32_t at_enc; // encrypted tag response
598 uint8_t at_enc_par; // encrypted tag response parity
599
600 int isTraceCardEmpty(void) {
601 return ((traceCard[0] == 0) && (traceCard[1] == 0) && (traceCard[2] == 0) && (traceCard[3] == 0));
602 }
603
604 int isBlockEmpty(int blockN) {
605 for (int i = 0; i < 16; i++)
606 if (traceCard[blockN * 16 + i] != 0) return 0;
607
608 return 1;
609 }
610
611 int isBlockTrailer(int blockN) {
612 return ((blockN & 0x03) == 0x03);
613 }
614
615 int saveTraceCard(void) {
616 FILE * f;
617
618 if ((!strlen(traceFileName)) || (isTraceCardEmpty())) return 0;
619
620 f = fopen(traceFileName, "w+");
621 if ( !f ) return 1;
622
623 for (int i = 0; i < 64; i++) { // blocks
624 for (int j = 0; j < 16; j++) // bytes
625 fprintf(f, "%02x", *(traceCard + i * 16 + j));
626 if (i < 63)
627 fprintf(f,"\n");
628 }
629 fclose(f);
630 return 0;
631 }
632
633 int loadTraceCard(uint8_t *tuid) {
634 FILE * f;
635 char buf[64] = {0x00};
636 uint8_t buf8[64] = {0x00};
637 int i, blockNum;
638
639 if (!isTraceCardEmpty())
640 saveTraceCard();
641
642 memset(traceCard, 0x00, 4096);
643 memcpy(traceCard, tuid + 3, 4);
644
645 FillFileNameByUID(traceFileName, tuid, ".eml", 7);
646
647 f = fopen(traceFileName, "r");
648 if (!f) return 1;
649
650 blockNum = 0;
651
652 while(!feof(f)){
653
654 memset(buf, 0, sizeof(buf));
655 if (fgets(buf, sizeof(buf), f) == NULL) {
656 PrintAndLog("File reading error.");
657 fclose(f);
658 return 2;
659 }
660
661 if (strlen(buf) < 32){
662 if (feof(f)) break;
663 PrintAndLog("File content error. Block data must include 32 HEX symbols");
664 fclose(f);
665 return 2;
666 }
667 for (i = 0; i < 32; i += 2)
668 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
669
670 memcpy(traceCard + blockNum * 16, buf8, 16);
671
672 blockNum++;
673 }
674 fclose(f);
675
676 return 0;
677 }
678
679 int mfTraceInit(uint8_t *tuid, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile) {
680
681 if (traceCrypto1)
682 crypto1_destroy(traceCrypto1);
683
684 traceCrypto1 = NULL;
685
686 if (wantSaveToEmlFile)
687 loadTraceCard(tuid);
688
689 traceCard[4] = traceCard[0] ^ traceCard[1] ^ traceCard[2] ^ traceCard[3];
690 traceCard[5] = sak;
691 memcpy(&traceCard[6], atqa, 2);
692 traceCurBlock = 0;
693 uid = bytes_to_num(tuid + 3, 4);
694
695 traceState = TRACE_IDLE;
696
697 return 0;
698 }
699
700 void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted){
701 uint8_t bt = 0;
702 int i;
703
704 if (len != 1) {
705 for (i = 0; i < len; i++)
706 data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i];
707 } else {
708 bt = 0;
709 for (i = 0; i < 4; i++)
710 bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], i)) << i;
711
712 data[0] = bt;
713 }
714 return;
715 }
716
717 bool NTParityCheck(uint32_t ntx) {
718 if (
719 (oddparity8(ntx >> 8 & 0xff) ^ (ntx & 0x01) ^ ((nt_enc_par >> 5) & 0x01) ^ (nt_enc & 0x01)) ||
720 (oddparity8(ntx >> 16 & 0xff) ^ (ntx >> 8 & 0x01) ^ ((nt_enc_par >> 6) & 0x01) ^ (nt_enc >> 8 & 0x01)) ||
721 (oddparity8(ntx >> 24 & 0xff) ^ (ntx >> 16 & 0x01) ^ ((nt_enc_par >> 7) & 0x01) ^ (nt_enc >> 16 & 0x01))
722 )
723 return false;
724
725 uint32_t ar = prng_successor(ntx, 64);
726 if (
727 (oddparity8(ar >> 8 & 0xff) ^ (ar & 0x01) ^ ((ar_enc_par >> 5) & 0x01) ^ (ar_enc & 0x01)) ||
728 (oddparity8(ar >> 16 & 0xff) ^ (ar >> 8 & 0x01) ^ ((ar_enc_par >> 6) & 0x01) ^ (ar_enc >> 8 & 0x01)) ||
729 (oddparity8(ar >> 24 & 0xff) ^ (ar >> 16 & 0x01) ^ ((ar_enc_par >> 7) & 0x01) ^ (ar_enc >> 16 & 0x01))
730 )
731 return false;
732
733 uint32_t at = prng_successor(ntx, 96);
734 if (
735 (oddparity8(ar & 0xff) ^ (at >> 24 & 0x01) ^ ((ar_enc_par >> 4) & 0x01) ^ (at_enc >> 24 & 0x01)) ||
736 (oddparity8(at >> 8 & 0xff) ^ (at & 0x01) ^ ((at_enc_par >> 5) & 0x01) ^ (at_enc & 0x01)) ||
737 (oddparity8(at >> 16 & 0xff) ^ (at >> 8 & 0x01) ^ ((at_enc_par >> 6) & 0x01) ^ (at_enc >> 8 & 0x01)) ||
738 (oddparity8(at >> 24 & 0xff) ^ (at >> 16 & 0x01) ^ ((at_enc_par >> 7) & 0x01) ^ (at_enc >> 16 & 0x01))
739 )
740 return false;
741
742 return true;
743 }
744
745
746 int mfTraceDecode(uint8_t *data_src, int len, uint8_t parity, bool wantSaveToEmlFile) {
747 uint8_t data[64];
748
749 if (traceState == TRACE_ERROR) return 1;
750 if (len > 64) {
751 traceState = TRACE_ERROR;
752 return 1;
753 }
754
755 memcpy(data, data_src, len);
756 if ((traceCrypto1) && ((traceState == TRACE_IDLE) || (traceState > TRACE_AUTH_OK))) {
757 mf_crypto1_decrypt(traceCrypto1, data, len, 0);
758 uint8_t parity[16];
759 oddparitybuf(data, len, parity);
760 PrintAndLog("dec> %s [%s]", sprint_hex(data, len), printBitsPar(parity, len));
761 AddLogHex(logHexFileName, "dec> ", data, len);
762 }
763
764 switch (traceState) {
765 case TRACE_IDLE:
766 // check packet crc16!
767 if ((len >= 4) && (!CheckCrc14443(CRC_14443_A, data, len))) {
768 PrintAndLog("dec> CRC ERROR!!!");
769 AddLogLine(logHexFileName, "dec> ", "CRC ERROR!!!");
770 traceState = TRACE_ERROR; // do not decrypt the next commands
771 return 1;
772 }
773
774 // AUTHENTICATION
775 if ((len ==4) && ((data[0] == 0x60) || (data[0] == 0x61))) {
776 traceState = TRACE_AUTH1;
777 traceCurBlock = data[1];
778 traceCurKey = data[0] == 60 ? 1:0;
779 return 0;
780 }
781
782 // READ
783 if ((len ==4) && ((data[0] == 0x30))) {
784 traceState = TRACE_READ_DATA;
785 traceCurBlock = data[1];
786 return 0;
787 }
788
789 // WRITE
790 if ((len ==4) && ((data[0] == 0xA0))) {
791 traceState = TRACE_WRITE_OK;
792 traceCurBlock = data[1];
793 return 0;
794 }
795
796 // HALT
797 if ((len ==4) && ((data[0] == 0x50) && (data[1] == 0x00))) {
798 traceState = TRACE_ERROR; // do not decrypt the next commands
799 return 0;
800 }
801
802 return 0;
803 break;
804
805 case TRACE_READ_DATA:
806 if (len == 18) {
807 traceState = TRACE_IDLE;
808
809 if (isBlockTrailer(traceCurBlock)) {
810 memcpy(traceCard + traceCurBlock * 16 + 6, data + 6, 4);
811 } else {
812 memcpy(traceCard + traceCurBlock * 16, data, 16);
813 }
814 if (wantSaveToEmlFile) saveTraceCard();
815 return 0;
816 } else {
817 traceState = TRACE_ERROR;
818 return 1;
819 }
820 break;
821
822 case TRACE_WRITE_OK:
823 if ((len == 1) && (data[0] == 0x0a)) {
824 traceState = TRACE_WRITE_DATA;
825
826 return 0;
827 } else {
828 traceState = TRACE_ERROR;
829 return 1;
830 }
831 break;
832
833 case TRACE_WRITE_DATA:
834 if (len == 18) {
835 traceState = TRACE_IDLE;
836
837 memcpy(traceCard + traceCurBlock * 16, data, 16);
838 if (wantSaveToEmlFile) saveTraceCard();
839 return 0;
840 } else {
841 traceState = TRACE_ERROR;
842 return 1;
843 }
844 break;
845
846 case TRACE_AUTH1:
847 if (len == 4) {
848 traceState = TRACE_AUTH2;
849 if (!traceCrypto1) {
850 nt = bytes_to_num(data, 4);
851 } else {
852 nt_enc = bytes_to_num(data, 4);
853 nt_enc_par = parity;
854 }
855 return 0;
856 } else {
857 traceState = TRACE_ERROR;
858 return 1;
859 }
860 break;
861
862 case TRACE_AUTH2:
863 if (len == 8) {
864 traceState = TRACE_AUTH_OK;
865
866 nr_enc = bytes_to_num(data, 4);
867 ar_enc = bytes_to_num(data + 4, 4);
868 ar_enc_par = parity << 4;
869 return 0;
870 } else {
871 traceState = TRACE_ERROR;
872 return 1;
873 }
874 break;
875
876 case TRACE_AUTH_OK:
877 if (len ==4) {
878 traceState = TRACE_IDLE;
879
880 at_enc = bytes_to_num(data, 4);
881 at_enc_par = parity;
882 if (!traceCrypto1) {
883
884 // decode key here)
885 ks2 = ar_enc ^ prng_successor(nt, 64);
886 ks3 = at_enc ^ prng_successor(nt, 96);
887 revstate = lfsr_recovery64(ks2, ks3);
888 lfsr_rollback_word(revstate, 0, 0);
889 lfsr_rollback_word(revstate, 0, 0);
890 lfsr_rollback_word(revstate, nr_enc, 1);
891 lfsr_rollback_word(revstate, uid ^ nt, 0);
892
893 crypto1_get_lfsr(revstate, &lfsr);
894 crypto1_destroy(revstate);
895 ui64Key = lfsr;
896 printf("key> probable key:%x%x Prng:%s ks2:%08x ks3:%08x\n",
897 (unsigned int)((lfsr & 0xFFFFFFFF00000000) >> 32), (unsigned int)(lfsr & 0xFFFFFFFF),
898 validate_prng_nonce(nt) ? "WEAK": "HARDEND",
899 ks2,
900 ks3);
901 AddLogUint64(logHexFileName, "key> ", lfsr);
902 } else {
903 if (validate_prng_nonce(nt)) {
904 struct Crypto1State *pcs;
905 pcs = crypto1_create(ui64Key);
906 uint32_t nt1 = crypto1_word(pcs, nt_enc ^ uid, 1) ^ nt_enc;
907 uint32_t ar = prng_successor(nt1, 64);
908 uint32_t at = prng_successor(nt1, 96);
909 printf("key> nested auth uid: %08x nt: %08x nt_parity: %s ar: %08x at: %08x\n", uid, nt1, printBitsPar(&nt_enc_par, 4), ar, at);
910 uint32_t nr1 = crypto1_word(pcs, nr_enc, 1) ^ nr_enc;
911 uint32_t ar1 = crypto1_word(pcs, 0, 0) ^ ar_enc;
912 uint32_t at1 = crypto1_word(pcs, 0, 0) ^ at_enc;
913 crypto1_destroy(pcs);
914 printf("key> the same key test. nr1: %08x ar1: %08x at1: %08x \n", nr1, ar1, at1);
915
916 if (NTParityCheck(nt1))
917 printf("key> the same key test OK. key=%x%x\n", (unsigned int)((ui64Key & 0xFFFFFFFF00000000) >> 32), (unsigned int)(ui64Key & 0xFFFFFFFF));
918 else
919 printf("key> the same key test. check nt parity error.\n");
920
921 uint32_t ntc = prng_successor(nt, 90);
922 uint32_t ntx = 0;
923 int ntcnt = 0;
924 for (int i = 0; i < 16383; i++) {
925 ntc = prng_successor(ntc, 1);
926 if (NTParityCheck(ntc)){
927 if (!ntcnt)
928 ntx = ntc;
929 ntcnt++;
930 }
931 }
932 if (ntcnt)
933 printf("key> nt candidate=%08x nonce distance=%d candidates count=%d\n", ntx, nonce_distance(nt, ntx), ntcnt);
934 else
935 printf("key> don't have any nt candidate( \n");
936
937 nt = ntx;
938 ks2 = ar_enc ^ prng_successor(ntx, 64);
939 ks3 = at_enc ^ prng_successor(ntx, 96);
940
941 // decode key
942 revstate = lfsr_recovery64(ks2, ks3);
943 lfsr_rollback_word(revstate, 0, 0);
944 lfsr_rollback_word(revstate, 0, 0);
945 lfsr_rollback_word(revstate, nr_enc, 1);
946 lfsr_rollback_word(revstate, uid ^ nt, 0);
947
948 crypto1_get_lfsr(revstate, &lfsr);
949 crypto1_destroy(revstate);
950 ui64Key = lfsr;
951 printf("key> probable key:%x%x ks2:%08x ks3:%08x\n",
952 (unsigned int)((lfsr & 0xFFFFFFFF00000000) >> 32), (unsigned int)(lfsr & 0xFFFFFFFF),
953 ks2,
954 ks3);
955 AddLogUint64(logHexFileName, "key> ", lfsr);
956 } else {
957 printf("key> hardnested not implemented!\n");
958
959 crypto1_destroy(traceCrypto1);
960
961 // not implemented
962 traceState = TRACE_ERROR;
963 }
964 }
965
966 int blockShift = ((traceCurBlock & 0xFC) + 3) * 16;
967 if (isBlockEmpty((traceCurBlock & 0xFC) + 3)) memcpy(traceCard + blockShift + 6, trailerAccessBytes, 4);
968
969 if (traceCurKey) {
970 num_to_bytes(lfsr, 6, traceCard + blockShift + 10);
971 } else {
972 num_to_bytes(lfsr, 6, traceCard + blockShift);
973 }
974 if (wantSaveToEmlFile) saveTraceCard();
975
976 if (traceCrypto1) {
977 crypto1_destroy(traceCrypto1);
978 }
979
980 // set cryptosystem state
981 traceCrypto1 = lfsr_recovery64(ks2, ks3);
982 return 0;
983 } else {
984 traceState = TRACE_ERROR;
985 return 1;
986 }
987 break;
988
989 default:
990 traceState = TRACE_ERROR;
991 return 1;
992 }
993
994 return 0;
995 }
996
997 // DECODING
998
999 int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len){
1000 /*
1001 uint32_t nt; // tag challenge
1002 uint32_t ar_enc; // encrypted reader response
1003 uint32_t at_enc; // encrypted tag response
1004 */
1005 if (traceCrypto1) {
1006 crypto1_destroy(traceCrypto1);
1007 }
1008 ks2 = ar_enc ^ prng_successor(nt, 64);
1009 ks3 = at_enc ^ prng_successor(nt, 96);
1010 traceCrypto1 = lfsr_recovery64(ks2, ks3);
1011
1012 mf_crypto1_decrypt(traceCrypto1, data, len, 0);
1013
1014 PrintAndLog("Decrypted data: [%s]", sprint_hex(data,len) );
1015 crypto1_destroy(traceCrypto1);
1016 return 0;
1017 }
1018
1019 /** validate_prng_nonce
1020 * Determine if nonce is deterministic. ie: Suspectable to Darkside attack.
1021 * returns
1022 * true = weak prng
1023 * false = hardend prng
1024 */
1025 bool validate_prng_nonce(uint32_t nonce) {
1026 uint16_t *dist = 0;
1027 uint16_t x, i;
1028
1029 dist = malloc(2 << 16);
1030 if(!dist)
1031 return -1;
1032
1033 // init prng table:
1034 for (x = i = 1; i; ++i) {
1035 dist[(x & 0xff) << 8 | x >> 8] = i;
1036 x = x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15;
1037 }
1038
1039 uint32_t res = (65535 - dist[nonce >> 16] + dist[nonce & 0xffff]) % 65535;
1040
1041 free(dist);
1042 return (res == 16);
1043 }
1044
1045 /* Detect Tag Prng,
1046 * function performs a partial AUTH, where it tries to authenticate against block0, key A, but only collects tag nonce.
1047 * the tag nonce is check to see if it has a predictable PRNG.
1048 * @returns
1049 * TRUE if tag uses WEAK prng (ie Now the NACK bug also needs to be present for Darkside attack)
1050 * FALSE is tag uses HARDEND prng (ie hardnested attack possible, with known key)
1051 */
1052 int DetectClassicPrng(void){
1053
1054 UsbCommand resp, respA;
1055 uint8_t cmd[] = {0x60, 0x00}; // MIFARE_AUTH_KEYA
1056 uint32_t flags = ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_RATS;
1057
1058 UsbCommand c = {CMD_READER_ISO_14443a, {flags, sizeof(cmd), 0}};
1059 memcpy(c.d.asBytes, cmd, sizeof(cmd));
1060
1061 clearCommandBuffer();
1062 SendCommand(&c);
1063 if (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {
1064 PrintAndLog("PRNG UID: Reply timeout.");
1065 return -1;
1066 }
1067
1068 // if select tag failed.
1069 if (resp.arg[0] == 0) {
1070 PrintAndLog("PRNG error: selecting tag failed, can't detect prng.");
1071 return -1;
1072 }
1073
1074 if (!WaitForResponseTimeout(CMD_ACK, &respA, 5000)) {
1075 PrintAndLog("PRNG data: Reply timeout.");
1076 return -1;
1077 }
1078
1079 // check respA
1080 if (respA.arg[0] != 4) {
1081 PrintAndLog("PRNG data error: Wrong length: %d", respA.arg[0]);
1082 return -1;
1083 }
1084
1085 uint32_t nonce = bytes_to_num(respA.d.asBytes, respA.arg[0]);
1086 return validate_prng_nonce(nonce);
1087 }
Impressum, Datenschutz