]> git.zerfleddert.de Git - proxmark3-svn/blob - client/mifarehost.c
ADD: added the "llu" macro shortcut as format specifier.
[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 <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <pthread.h>
15 #include "mifarehost.h"
16 #include "proxmark3.h"
17
18 #define llx PRIx64
19
20 // MIFARE
21 int compar_int(const void * a, const void * b) {
22 // didn't work: (the result is truncated to 32 bits)
23 //return (*(uint64_t*)b - *(uint64_t*)a);
24
25 // better:
26 if (*(uint64_t*)b == *(uint64_t*)a) return 0;
27 else if (*(uint64_t*)b > *(uint64_t*)a) return 1;
28 else return -1;
29 }
30
31 // Compare 16 Bits out of cryptostate
32 int Compare16Bits(const void * a, const void * b) {
33 if ((*(uint64_t*)b & 0x00ff000000ff0000) == (*(uint64_t*)a & 0x00ff000000ff0000)) return 0;
34 else if ((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000)) return 1;
35 else return -1;
36 }
37
38 typedef
39 struct {
40 union {
41 struct Crypto1State *slhead;
42 uint64_t *keyhead;
43 } head;
44 union {
45 struct Crypto1State *sltail;
46 uint64_t *keytail;
47 } tail;
48 uint32_t len;
49 uint32_t uid;
50 uint32_t blockNo;
51 uint32_t keyType;
52 uint32_t nt;
53 uint32_t ks1;
54 } StateList_t;
55
56
57 // wrapper function for multi-threaded lfsr_recovery32
58 void* nested_worker_thread(void *arg)
59 {
60 struct Crypto1State *p1;
61 StateList_t *statelist = arg;
62
63 statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid);
64 for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; p1++);
65 statelist->len = p1 - statelist->head.slhead;
66 statelist->tail.sltail = --p1;
67 qsort(statelist->head.slhead, statelist->len, sizeof(uint64_t), Compare16Bits);
68
69 return statelist->head.slhead;
70 }
71
72 int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t * resultKey, bool calibrate)
73 {
74 uint16_t i;
75 uint32_t uid;
76 UsbCommand resp;
77
78 StateList_t statelists[2];
79 struct Crypto1State *p1, *p2, *p3, *p4;
80
81 // flush queue
82
83 UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}};
84 memcpy(c.d.asBytes, key, 6);
85 clearCommandBuffer();
86 SendCommand(&c);
87
88 if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1;
89
90 // error during nested
91 if (resp.arg[0]) return resp.arg[0];
92
93 memcpy(&uid, resp.d.asBytes, 4);
94 PrintAndLog("UID: %08x Block:%d Key: %c", uid, (uint16_t)resp.arg[2] & 0xff, (resp.arg[2] >> 8) ?'A':'B' );
95
96 for (i = 0; i < 2; i++) {
97 statelists[i].blockNo = resp.arg[2] & 0xff;
98 statelists[i].keyType = (resp.arg[2] >> 8) & 0xff;
99 statelists[i].uid = uid;
100 memcpy(&statelists[i].nt, (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4);
101 memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4);
102 }
103
104 // calc keys
105
106 pthread_t thread_id[2];
107
108 // create and run worker threads
109 for (i = 0; i < 2; i++) {
110 pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]);
111 }
112
113 // wait for threads to terminate:
114 for (i = 0; i < 2; i++) {
115 pthread_join(thread_id[i], (void*)&statelists[i].head.slhead);
116 }
117
118
119 // the first 16 Bits of the cryptostate already contain part of our key.
120 // Create the intersection of the two lists based on these 16 Bits and
121 // roll back the cryptostate
122 p1 = p3 = statelists[0].head.slhead;
123 p2 = p4 = statelists[1].head.slhead;
124 while (p1 <= statelists[0].tail.sltail && p2 <= statelists[1].tail.sltail) {
125 if (Compare16Bits(p1, p2) == 0) {
126 struct Crypto1State savestate, *savep = &savestate;
127 savestate = *p1;
128 while(Compare16Bits(p1, savep) == 0 && p1 <= statelists[0].tail.sltail) {
129 *p3 = *p1;
130 lfsr_rollback_word(p3, statelists[0].nt ^ statelists[0].uid, 0);
131 p3++;
132 p1++;
133 }
134 savestate = *p2;
135 while(Compare16Bits(p2, savep) == 0 && p2 <= statelists[1].tail.sltail) {
136 *p4 = *p2;
137 lfsr_rollback_word(p4, statelists[1].nt ^ statelists[1].uid, 0);
138 p4++;
139 p2++;
140 }
141 }
142 else {
143 while (Compare16Bits(p1, p2) == -1) p1++;
144 while (Compare16Bits(p1, p2) == 1) p2++;
145 }
146 }
147 p3->even = 0; p3->odd = 0;
148 p4->even = 0; p4->odd = 0;
149 statelists[0].len = p3 - statelists[0].head.slhead;
150 statelists[1].len = p4 - statelists[1].head.slhead;
151 statelists[0].tail.sltail=--p3;
152 statelists[1].tail.sltail=--p4;
153
154 // the statelists now contain possible keys. The key we are searching for must be in the
155 // intersection of both lists. Create the intersection:
156 qsort(statelists[0].head.keyhead, statelists[0].len, sizeof(uint64_t), compar_int);
157 qsort(statelists[1].head.keyhead, statelists[1].len, sizeof(uint64_t), compar_int);
158
159 uint64_t *p5, *p6, *p7;
160 p5 = p7 = statelists[0].head.keyhead;
161 p6 = statelists[1].head.keyhead;
162 while (p5 <= statelists[0].tail.keytail && p6 <= statelists[1].tail.keytail) {
163 if (compar_int(p5, p6) == 0) {
164 *p7++ = *p5++;
165 p6++;
166 }
167 else {
168 while (compar_int(p5, p6) == -1) p5++;
169 while (compar_int(p5, p6) == 1) p6++;
170 }
171 }
172 statelists[0].len = p7 - statelists[0].head.keyhead;
173 statelists[0].tail.keytail=--p7;
174
175 memset(resultKey, 0, 6);
176 // The list may still contain several key candidates. Test each of them with mfCheckKeys
177 for (i = 0; i < statelists[0].len; i++) {
178 uint8_t keyBlock[6];
179 uint64_t key64;
180 crypto1_get_lfsr(statelists[0].head.slhead + i, &key64);
181 num_to_bytes(key64, 6, keyBlock);
182 key64 = 0;
183 if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) {
184 num_to_bytes(key64, 6, resultKey);
185 break;
186 }
187 }
188
189 free(statelists[0].head.slhead);
190 free(statelists[1].head.slhead);
191 return 0;
192 }
193
194 int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){
195
196 *key = 0;
197
198 UsbCommand c = {CMD_MIFARE_CHKKEYS, {((blockNo & 0xff) | ((keyType&0xff)<<8)), clear_trace, keycnt}};
199 memcpy(c.d.asBytes, keyBlock, 6 * keycnt);
200
201 clearCommandBuffer();
202 SendCommand(&c);
203 UsbCommand resp;
204 if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) return 1;
205 if ((resp.arg[0] & 0xff) != 0x01) return 2;
206 *key = bytes_to_num(resp.d.asBytes, 6);
207 return 0;
208 }
209
210 // EMULATOR
211
212 int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) {
213 UsbCommand c = {CMD_MIFARE_EML_MEMGET, {blockNum, blocksCount, 0}};
214 clearCommandBuffer();
215 SendCommand(&c);
216 UsbCommand resp;
217 if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) return 1;
218 memcpy(data, resp.d.asBytes, blocksCount * 16);
219 return 0;
220 }
221
222 int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) {
223 return mfEmlSetMem_xt(data, blockNum, blocksCount, 16);
224 }
225
226 int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth) {
227 UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, blockBtWidth}};
228 memcpy(c.d.asBytes, data, blocksCount * blockBtWidth);
229
230 clearCommandBuffer();
231 SendCommand(&c);
232 return 0;
233 }
234
235 // "MAGIC" CARD
236
237 int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_t wipecard) {
238
239 uint8_t params = MAGIC_SINGLE;
240 uint8_t block0[16];
241 memset(block0, 0x00, sizeof(block0));
242
243
244 int old = mfCGetBlock(0, block0, params);
245 if (old == 0) {
246 PrintAndLog("old block 0: %s", sprint_hex(block0, sizeof(block0)));
247 } else {
248 PrintAndLog("Couldn't get old data. Will write over the last bytes of Block 0.");
249 }
250
251 // fill in the new values
252 // UID
253 memcpy(block0, uid, 4);
254 // Mifare UID BCC
255 block0[4] = block0[0]^block0[1]^block0[2]^block0[3];
256 // mifare classic SAK(byte 5) and ATQA(byte 6 and 7, reversed)
257 if ( sak != NULL )
258 block0[5]=sak[0];
259
260 if ( atqa != NULL ) {
261 block0[6]=atqa[1];
262 block0[7]=atqa[0];
263 }
264 PrintAndLog("new block 0: %s", sprint_hex(block0,16));
265
266 if ( wipecard ) params |= MAGIC_WIPE;
267 if ( oldUID == NULL) params |= MAGIC_UID;
268
269 return mfCSetBlock(0, block0, oldUID, params);
270 }
271
272 int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params) {
273
274 uint8_t isOK = 0;
275 UsbCommand c = {CMD_MIFARE_CSETBLOCK, {params, blockNo, 0}};
276 memcpy(c.d.asBytes, data, 16);
277 clearCommandBuffer();
278 SendCommand(&c);
279 UsbCommand resp;
280 if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {
281 isOK = resp.arg[0] & 0xff;
282 if (uid != NULL)
283 memcpy(uid, resp.d.asBytes, 4);
284 if (!isOK)
285 return 2;
286 } else {
287 PrintAndLog("Command execute timeout");
288 return 1;
289 }
290 return 0;
291 }
292
293 int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) {
294 uint8_t isOK = 0;
295 UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, blockNo, 0}};
296 clearCommandBuffer();
297 SendCommand(&c);
298 UsbCommand resp;
299 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
300 isOK = resp.arg[0] & 0xff;
301 memcpy(data, resp.d.asBytes, 16);
302 if (!isOK) return 2;
303 } else {
304 PrintAndLog("Command execute timeout");
305 return 1;
306 }
307 return 0;
308 }
309
310 // SNIFFER
311
312 // constants
313 static uint8_t trailerAccessBytes[4] = {0x08, 0x77, 0x8F, 0x00};
314
315 // variables
316 char logHexFileName[FILE_PATH_SIZE] = {0x00};
317 static uint8_t traceCard[4096] = {0x00};
318 static char traceFileName[FILE_PATH_SIZE] = {0x00};
319 static int traceState = TRACE_IDLE;
320 static uint8_t traceCurBlock = 0;
321 static uint8_t traceCurKey = 0;
322
323 struct Crypto1State *traceCrypto1 = NULL;
324
325 struct Crypto1State *revstate = NULL;
326
327 uint64_t key = 0;
328 uint32_t ks2 = 0;
329 uint32_t ks3 = 0;
330
331 uint32_t uid = 0; // serial number
332 uint32_t nt =0; // tag challenge
333 uint32_t nr_enc =0; // encrypted reader challenge
334 uint32_t ar_enc =0; // encrypted reader response
335 uint32_t at_enc =0; // encrypted tag response
336
337 int isTraceCardEmpty(void) {
338 return ((traceCard[0] == 0) && (traceCard[1] == 0) && (traceCard[2] == 0) && (traceCard[3] == 0));
339 }
340
341 int isBlockEmpty(int blockN) {
342 for (int i = 0; i < 16; i++)
343 if (traceCard[blockN * 16 + i] != 0) return 0;
344
345 return 1;
346 }
347
348 int isBlockTrailer(int blockN) {
349 return ((blockN & 0x03) == 0x03);
350 }
351
352 int loadTraceCard(uint8_t *tuid) {
353 FILE * f;
354 char buf[64] = {0x00};
355 uint8_t buf8[64] = {0x00};
356 int i, blockNum;
357
358 if (!isTraceCardEmpty())
359 saveTraceCard();
360
361 memset(traceCard, 0x00, 4096);
362 memcpy(traceCard, tuid + 3, 4);
363
364 FillFileNameByUID(traceFileName, tuid, ".eml", 7);
365
366 f = fopen(traceFileName, "r");
367 if (!f) return 1;
368
369 blockNum = 0;
370
371 while(!feof(f)){
372
373 memset(buf, 0, sizeof(buf));
374 if (fgets(buf, sizeof(buf), f) == NULL) {
375 PrintAndLog("File reading error.");
376 fclose(f);
377 return 2;
378 }
379
380 if (strlen(buf) < 32){
381 if (feof(f)) break;
382 PrintAndLog("File content error. Block data must include 32 HEX symbols");
383 fclose(f);
384 return 2;
385 }
386 for (i = 0; i < 32; i += 2)
387 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
388
389 memcpy(traceCard + blockNum * 16, buf8, 16);
390
391 blockNum++;
392 }
393 fclose(f);
394
395 return 0;
396 }
397
398 int saveTraceCard(void) {
399 FILE * f;
400
401 if ((!strlen(traceFileName)) || (isTraceCardEmpty())) return 0;
402
403 f = fopen(traceFileName, "w+");
404 if ( !f ) return 1;
405
406 for (int i = 0; i < 64; i++) { // blocks
407 for (int j = 0; j < 16; j++) // bytes
408 fprintf(f, "%02x", *(traceCard + i * 16 + j));
409 fprintf(f,"\n");
410 }
411 fclose(f);
412 return 0;
413 }
414
415 int mfTraceInit(uint8_t *tuid, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile) {
416
417 if (traceCrypto1)
418 crypto1_destroy(traceCrypto1);
419
420 traceCrypto1 = NULL;
421
422 if (wantSaveToEmlFile)
423 loadTraceCard(tuid);
424
425 traceCard[4] = traceCard[0] ^ traceCard[1] ^ traceCard[2] ^ traceCard[3];
426 traceCard[5] = sak;
427 memcpy(&traceCard[6], atqa, 2);
428 traceCurBlock = 0;
429 uid = bytes_to_num(tuid + 3, 4);
430
431 traceState = TRACE_IDLE;
432
433 return 0;
434 }
435
436 void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted){
437 uint8_t bt = 0;
438 int i;
439
440 if (len != 1) {
441 for (i = 0; i < len; i++)
442 data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i];
443 } else {
444 bt = 0;
445 for (i = 0; i < 4; i++)
446 bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], i)) << i;
447
448 data[0] = bt;
449 }
450 return;
451 }
452
453
454 int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
455 uint8_t data[64];
456
457 if (traceState == TRACE_ERROR) return 1;
458 if (len > 64) {
459 traceState = TRACE_ERROR;
460 return 1;
461 }
462
463 memcpy(data, data_src, len);
464 if ((traceCrypto1) && ((traceState == TRACE_IDLE) || (traceState > TRACE_AUTH_OK))) {
465 mf_crypto1_decrypt(traceCrypto1, data, len, 0);
466 PrintAndLog("dec> %s", sprint_hex(data, len));
467 AddLogHex(logHexFileName, "dec> ", data, len);
468 }
469
470 switch (traceState) {
471 case TRACE_IDLE:
472 // check packet crc16!
473 if ((len >= 4) && (!CheckCrc14443(CRC_14443_A, data, len))) {
474 PrintAndLog("dec> CRC ERROR!!!");
475 AddLogLine(logHexFileName, "dec> ", "CRC ERROR!!!");
476 traceState = TRACE_ERROR; // do not decrypt the next commands
477 return 1;
478 }
479
480 // AUTHENTICATION
481 if ((len == 4) && ((data[0] == 0x60) || (data[0] == 0x61))) {
482 traceState = TRACE_AUTH1;
483 traceCurBlock = data[1];
484 traceCurKey = data[0] == 60 ? 1:0;
485 return 0;
486 }
487
488 // READ
489 if ((len ==4) && ((data[0] == 0x30))) {
490 traceState = TRACE_READ_DATA;
491 traceCurBlock = data[1];
492 return 0;
493 }
494
495 // WRITE
496 if ((len ==4) && ((data[0] == 0xA0))) {
497 traceState = TRACE_WRITE_OK;
498 traceCurBlock = data[1];
499 return 0;
500 }
501
502 // HALT
503 if ((len ==4) && ((data[0] == 0x50) && (data[1] == 0x00))) {
504 traceState = TRACE_ERROR; // do not decrypt the next commands
505 return 0;
506 }
507
508 return 0;
509 break;
510
511 case TRACE_READ_DATA:
512 if (len == 18) {
513 traceState = TRACE_IDLE;
514
515 if (isBlockTrailer(traceCurBlock)) {
516 memcpy(traceCard + traceCurBlock * 16 + 6, data + 6, 4);
517 } else {
518 memcpy(traceCard + traceCurBlock * 16, data, 16);
519 }
520 if (wantSaveToEmlFile) saveTraceCard();
521 return 0;
522 } else {
523 traceState = TRACE_ERROR;
524 return 1;
525 }
526 break;
527
528 case TRACE_WRITE_OK:
529 if ((len == 1) && (data[0] == 0x0a)) {
530 traceState = TRACE_WRITE_DATA;
531
532 return 0;
533 } else {
534 traceState = TRACE_ERROR;
535 return 1;
536 }
537 break;
538
539 case TRACE_WRITE_DATA:
540 if (len == 18) {
541 traceState = TRACE_IDLE;
542
543 memcpy(traceCard + traceCurBlock * 16, data, 16);
544 if (wantSaveToEmlFile) saveTraceCard();
545 return 0;
546 } else {
547 traceState = TRACE_ERROR;
548 return 1;
549 }
550 break;
551
552 case TRACE_AUTH1:
553 if (len == 4) {
554 traceState = TRACE_AUTH2;
555 nt = bytes_to_num(data, 4);
556 return 0;
557 } else {
558 traceState = TRACE_ERROR;
559 return 1;
560 }
561 break;
562
563 case TRACE_AUTH2:
564 if (len == 8) {
565 traceState = TRACE_AUTH_OK;
566
567 nr_enc = bytes_to_num(data, 4);
568 ar_enc = bytes_to_num(data + 4, 4);
569 return 0;
570 } else {
571 traceState = TRACE_ERROR;
572 return 1;
573 }
574 break;
575
576 case TRACE_AUTH_OK:
577 if (len ==4) {
578 traceState = TRACE_IDLE;
579
580 at_enc = bytes_to_num(data, 4);
581
582 // decode key here)
583 ks2 = ar_enc ^ prng_successor(nt, 64);
584 ks3 = at_enc ^ prng_successor(nt, 96);
585 revstate = lfsr_recovery64(ks2, ks3);
586 lfsr_rollback_word(revstate, 0, 0);
587 lfsr_rollback_word(revstate, 0, 0);
588 lfsr_rollback_word(revstate, nr_enc, 1);
589 lfsr_rollback_word(revstate, uid ^ nt, 0);
590
591 crypto1_get_lfsr(revstate, &key);
592 printf("Key: %012"llx"\n",key);
593 AddLogUint64(logHexFileName, "key: ", key);
594
595 int blockShift = ((traceCurBlock & 0xFC) + 3) * 16;
596 if (isBlockEmpty((traceCurBlock & 0xFC) + 3)) memcpy(traceCard + blockShift + 6, trailerAccessBytes, 4);
597
598 if (traceCurKey) {
599 num_to_bytes(key, 6, traceCard + blockShift + 10);
600 } else {
601 num_to_bytes(key, 6, traceCard + blockShift);
602 }
603 if (wantSaveToEmlFile) saveTraceCard();
604
605 if (traceCrypto1) {
606 crypto1_destroy(traceCrypto1);
607 }
608
609 // set cryptosystem state
610 traceCrypto1 = lfsr_recovery64(ks2, ks3);
611
612 // nt = crypto1_word(traceCrypto1, nt ^ uid, 1) ^ nt;
613
614 /* traceCrypto1 = crypto1_create(key); // key in lfsr
615 crypto1_word(traceCrypto1, nt ^ uid, 0);
616 crypto1_word(traceCrypto1, ar, 1);
617 crypto1_word(traceCrypto1, 0, 0);
618 crypto1_word(traceCrypto1, 0, 0);*/
619
620 return 0;
621 } else {
622 traceState = TRACE_ERROR;
623 return 1;
624 }
625 break;
626
627 default:
628 traceState = TRACE_ERROR;
629 return 1;
630 }
631
632 return 0;
633 }
634
635 int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len){
636 /*
637 uint32_t nt; // tag challenge
638 uint32_t nr_enc; // encrypted reader challenge
639 uint32_t ar_enc; // encrypted reader response
640 uint32_t at_enc; // encrypted tag response
641 */
642
643 struct Crypto1State *pcs = NULL;
644
645 ks2 = ar_enc ^ prng_successor(nt, 64);
646 ks3 = at_enc ^ prng_successor(nt, 96);
647
648 PrintAndLog("Decrypting data with:");
649 PrintAndLog(" nt: %08x",nt);
650 PrintAndLog(" ar_enc: %08x",ar_enc);
651 PrintAndLog(" at_enc: %08x",at_enc);
652 PrintAndLog("\nEncrypted data: [%s]", sprint_hex(data,len) );
653
654 pcs = lfsr_recovery64(ks2, ks3);
655 mf_crypto1_decrypt(pcs, data, len, FALSE);
656 PrintAndLog("Decrypted data: [%s]", sprint_hex(data,len) );
657 crypto1_destroy(pcs);
658 return 0;
659 }
Impressum, Datenschutz