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