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