Merge pull request #115 from marshmellow42/master
[legacy-proxmark3.git] / client / mifarehost.c
blob237979c1bfaaefc13ca0940093c2a47d5b954f40
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 //-----------------------------------------------------------------------------
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <pthread.h>
15 #include "mifarehost.h"
16 #include "proxmark3.h"
18 // MIFARE
19 int compar_int(const void * a, const void * b) {
20 // didn't work: (the result is truncated to 32 bits)
21 //return (*(uint64_t*)b - *(uint64_t*)a);
23 // better:
24 if (*(uint64_t*)b == *(uint64_t*)a) return 0;
25 else if (*(uint64_t*)b > *(uint64_t*)a) return 1;
26 else return -1;
29 // Compare 16 Bits out of cryptostate
30 int Compare16Bits(const void * a, const void * b) {
31 if ((*(uint64_t*)b & 0x00ff000000ff0000) == (*(uint64_t*)a & 0x00ff000000ff0000)) return 0;
32 else if ((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000)) return 1;
33 else return -1;
36 typedef
37 struct {
38 union {
39 struct Crypto1State *slhead;
40 uint64_t *keyhead;
41 } head;
42 union {
43 struct Crypto1State *sltail;
44 uint64_t *keytail;
45 } tail;
46 uint32_t len;
47 uint32_t uid;
48 uint32_t blockNo;
49 uint32_t keyType;
50 uint32_t nt;
51 uint32_t ks1;
52 } StateList_t;
55 // wrapper function for multi-threaded lfsr_recovery32
56 void* nested_worker_thread(void *arg)
58 struct Crypto1State *p1;
59 StateList_t *statelist = arg;
61 statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid);
62 for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; p1++);
63 statelist->len = p1 - statelist->head.slhead;
64 statelist->tail.sltail = --p1;
65 qsort(statelist->head.slhead, statelist->len, sizeof(uint64_t), Compare16Bits);
67 return statelist->head.slhead;
70 int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t * resultKey, bool calibrate)
72 uint16_t i, len;
73 uint32_t uid;
74 UsbCommand resp;
76 StateList_t statelists[2];
77 struct Crypto1State *p1, *p2, *p3, *p4;
79 // flush queue
80 WaitForResponseTimeout(CMD_ACK,NULL,100);
82 UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}};
83 memcpy(c.d.asBytes, key, 6);
84 SendCommand(&c);
86 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
87 len = resp.arg[1];
88 if (len == 2) {
89 memcpy(&uid, resp.d.asBytes, 4);
90 PrintAndLog("uid:%08x len=%d trgbl=%d trgkey=%x", uid, len, (uint16_t)resp.arg[2] & 0xff, (uint16_t)resp.arg[2] >> 8);
92 for (i = 0; i < 2; i++) {
93 statelists[i].blockNo = resp.arg[2] & 0xff;
94 statelists[i].keyType = (resp.arg[2] >> 8) & 0xff;
95 statelists[i].uid = uid;
97 memcpy(&statelists[i].nt, (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4);
98 memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4);
101 else {
102 PrintAndLog("Got 0 keys from proxmark.");
103 return 1;
107 // calc keys
109 pthread_t thread_id[2];
111 // create and run worker threads
112 for (i = 0; i < 2; i++) {
113 pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]);
116 // wait for threads to terminate:
117 for (i = 0; i < 2; i++) {
118 pthread_join(thread_id[i], (void*)&statelists[i].head.slhead);
122 // the first 16 Bits of the cryptostate already contain part of our key.
123 // Create the intersection of the two lists based on these 16 Bits and
124 // roll back the cryptostate
125 p1 = p3 = statelists[0].head.slhead;
126 p2 = p4 = statelists[1].head.slhead;
127 while (p1 <= statelists[0].tail.sltail && p2 <= statelists[1].tail.sltail) {
128 if (Compare16Bits(p1, p2) == 0) {
129 struct Crypto1State savestate, *savep = &savestate;
130 savestate = *p1;
131 while(Compare16Bits(p1, savep) == 0 && p1 <= statelists[0].tail.sltail) {
132 *p3 = *p1;
133 lfsr_rollback_word(p3, statelists[0].nt ^ statelists[0].uid, 0);
134 p3++;
135 p1++;
137 savestate = *p2;
138 while(Compare16Bits(p2, savep) == 0 && p2 <= statelists[1].tail.sltail) {
139 *p4 = *p2;
140 lfsr_rollback_word(p4, statelists[1].nt ^ statelists[1].uid, 0);
141 p4++;
142 p2++;
145 else {
146 while (Compare16Bits(p1, p2) == -1) p1++;
147 while (Compare16Bits(p1, p2) == 1) p2++;
150 p3->even = 0; p3->odd = 0;
151 p4->even = 0; p4->odd = 0;
152 statelists[0].len = p3 - statelists[0].head.slhead;
153 statelists[1].len = p4 - statelists[1].head.slhead;
154 statelists[0].tail.sltail=--p3;
155 statelists[1].tail.sltail=--p4;
157 // the statelists now contain possible keys. The key we are searching for must be in the
158 // intersection of both lists. Create the intersection:
159 qsort(statelists[0].head.keyhead, statelists[0].len, sizeof(uint64_t), compar_int);
160 qsort(statelists[1].head.keyhead, statelists[1].len, sizeof(uint64_t), compar_int);
162 uint64_t *p5, *p6, *p7;
163 p5 = p7 = statelists[0].head.keyhead;
164 p6 = statelists[1].head.keyhead;
165 while (p5 <= statelists[0].tail.keytail && p6 <= statelists[1].tail.keytail) {
166 if (compar_int(p5, p6) == 0) {
167 *p7++ = *p5++;
168 p6++;
170 else {
171 while (compar_int(p5, p6) == -1) p5++;
172 while (compar_int(p5, p6) == 1) p6++;
175 statelists[0].len = p7 - statelists[0].head.keyhead;
176 statelists[0].tail.keytail=--p7;
178 memset(resultKey, 0, 6);
179 // The list may still contain several key candidates. Test each of them with mfCheckKeys
180 for (i = 0; i < statelists[0].len; i++) {
181 uint8_t keyBlock[6];
182 uint64_t key64;
183 crypto1_get_lfsr(statelists[0].head.slhead + i, &key64);
184 num_to_bytes(key64, 6, keyBlock);
185 key64 = 0;
186 if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, 1, keyBlock, &key64)) {
187 num_to_bytes(key64, 6, resultKey);
188 break;
192 free(statelists[0].head.slhead);
193 free(statelists[1].head.slhead);
195 return 0;
198 int mfCheckKeys (uint8_t blockNo, uint8_t keyType, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){
200 *key = 0;
202 UsbCommand c = {CMD_MIFARE_CHKKEYS, {blockNo, keyType, keycnt}};
203 memcpy(c.d.asBytes, keyBlock, 6 * keycnt);
204 SendCommand(&c);
206 UsbCommand resp;
207 if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) return 1;
208 if ((resp.arg[0] & 0xff) != 0x01) return 2;
209 *key = bytes_to_num(resp.d.asBytes, 6);
210 return 0;
213 // EMULATOR
215 int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) {
216 UsbCommand c = {CMD_MIFARE_EML_MEMGET, {blockNum, blocksCount, 0}};
217 SendCommand(&c);
219 UsbCommand resp;
220 if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) return 1;
221 memcpy(data, resp.d.asBytes, blocksCount * 16);
222 return 0;
225 int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) {
226 UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}};
227 memcpy(c.d.asBytes, data, blocksCount * 16);
228 SendCommand(&c);
229 return 0;
232 // "MAGIC" CARD
234 int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, bool wantWipe) {
235 uint8_t oldblock0[16] = {0x00};
236 uint8_t block0[16] = {0x00};
238 int old = mfCGetBlock(0, oldblock0, CSETBLOCK_SINGLE_OPER);
239 if (old == 0) {
240 memcpy(block0, oldblock0, 16);
241 PrintAndLog("old block 0: %s", sprint_hex(block0,16));
242 } else {
243 PrintAndLog("Couldn't get old data. Will write over the last bytes of Block 0.");
246 // fill in the new values
247 // UID
248 memcpy(block0, uid, 4);
249 // Mifare UID BCC
250 block0[4] = block0[0]^block0[1]^block0[2]^block0[3];
251 // mifare classic SAK(byte 5) and ATQA(byte 6 and 7, reversed)
252 if (sak!=NULL)
253 block0[5]=sak[0];
254 if (atqa!=NULL) {
255 block0[6]=atqa[1];
256 block0[7]=atqa[0];
258 PrintAndLog("new block 0: %s", sprint_hex(block0,16));
259 return mfCSetBlock(0, block0, oldUID, wantWipe, CSETBLOCK_SINGLE_OPER);
262 int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, bool wantWipe, uint8_t params) {
264 uint8_t isOK = 0;
265 UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}};
266 memcpy(c.d.asBytes, data, 16);
267 SendCommand(&c);
269 UsbCommand resp;
270 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
271 isOK = resp.arg[0] & 0xff;
272 if (uid != NULL)
273 memcpy(uid, resp.d.asBytes, 4);
274 if (!isOK)
275 return 2;
276 } else {
277 PrintAndLog("Command execute timeout");
278 return 1;
280 return 0;
283 int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) {
284 uint8_t isOK = 0;
286 UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}};
287 SendCommand(&c);
289 UsbCommand resp;
290 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
291 isOK = resp.arg[0] & 0xff;
292 memcpy(data, resp.d.asBytes, 16);
293 if (!isOK) return 2;
294 } else {
295 PrintAndLog("Command execute timeout");
296 return 1;
298 return 0;
301 // SNIFFER
303 // constants
304 static uint8_t trailerAccessBytes[4] = {0x08, 0x77, 0x8F, 0x00};
306 // variables
307 char logHexFileName[FILE_PATH_SIZE] = {0x00};
308 static uint8_t traceCard[4096] = {0x00};
309 static char traceFileName[FILE_PATH_SIZE] = {0x00};
310 static int traceState = TRACE_IDLE;
311 static uint8_t traceCurBlock = 0;
312 static uint8_t traceCurKey = 0;
314 struct Crypto1State *traceCrypto1 = NULL;
316 struct Crypto1State *revstate;
317 uint64_t lfsr;
318 uint32_t ks2;
319 uint32_t ks3;
321 uint32_t uid; // serial number
322 uint32_t nt; // tag challenge
323 uint32_t nr_enc; // encrypted reader challenge
324 uint32_t ar_enc; // encrypted reader response
325 uint32_t at_enc; // encrypted tag response
327 int isTraceCardEmpty(void) {
328 return ((traceCard[0] == 0) && (traceCard[1] == 0) && (traceCard[2] == 0) && (traceCard[3] == 0));
331 int isBlockEmpty(int blockN) {
332 for (int i = 0; i < 16; i++)
333 if (traceCard[blockN * 16 + i] != 0) return 0;
335 return 1;
338 int isBlockTrailer(int blockN) {
339 return ((blockN & 0x03) == 0x03);
342 int loadTraceCard(uint8_t *tuid) {
343 FILE * f;
344 char buf[64] = {0x00};
345 uint8_t buf8[64] = {0x00};
346 int i, blockNum;
348 if (!isTraceCardEmpty())
349 saveTraceCard();
351 memset(traceCard, 0x00, 4096);
352 memcpy(traceCard, tuid + 3, 4);
354 FillFileNameByUID(traceFileName, tuid, ".eml", 7);
356 f = fopen(traceFileName, "r");
357 if (!f) return 1;
359 blockNum = 0;
361 while(!feof(f)){
363 memset(buf, 0, sizeof(buf));
364 if (fgets(buf, sizeof(buf), f) == NULL) {
365 PrintAndLog("File reading error.");
366 fclose(f);
367 return 2;
370 if (strlen(buf) < 32){
371 if (feof(f)) break;
372 PrintAndLog("File content error. Block data must include 32 HEX symbols");
373 fclose(f);
374 return 2;
376 for (i = 0; i < 32; i += 2)
377 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
379 memcpy(traceCard + blockNum * 16, buf8, 16);
381 blockNum++;
383 fclose(f);
385 return 0;
388 int saveTraceCard(void) {
389 FILE * f;
391 if ((!strlen(traceFileName)) || (isTraceCardEmpty())) return 0;
393 f = fopen(traceFileName, "w+");
394 if ( !f ) return 1;
396 for (int i = 0; i < 64; i++) { // blocks
397 for (int j = 0; j < 16; j++) // bytes
398 fprintf(f, "%02x", *(traceCard + i * 16 + j));
399 fprintf(f,"\n");
401 fclose(f);
402 return 0;
405 int mfTraceInit(uint8_t *tuid, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile) {
407 if (traceCrypto1)
408 crypto1_destroy(traceCrypto1);
410 traceCrypto1 = NULL;
412 if (wantSaveToEmlFile)
413 loadTraceCard(tuid);
415 traceCard[4] = traceCard[0] ^ traceCard[1] ^ traceCard[2] ^ traceCard[3];
416 traceCard[5] = sak;
417 memcpy(&traceCard[6], atqa, 2);
418 traceCurBlock = 0;
419 uid = bytes_to_num(tuid + 3, 4);
421 traceState = TRACE_IDLE;
423 return 0;
426 void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted){
427 uint8_t bt = 0;
428 int i;
430 if (len != 1) {
431 for (i = 0; i < len; i++)
432 data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i];
433 } else {
434 bt = 0;
435 for (i = 0; i < 4; i++)
436 bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], i)) << i;
438 data[0] = bt;
440 return;
444 int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
445 uint8_t data[64];
447 if (traceState == TRACE_ERROR) return 1;
448 if (len > 64) {
449 traceState = TRACE_ERROR;
450 return 1;
453 memcpy(data, data_src, len);
454 if ((traceCrypto1) && ((traceState == TRACE_IDLE) || (traceState > TRACE_AUTH_OK))) {
455 mf_crypto1_decrypt(traceCrypto1, data, len, 0);
456 PrintAndLog("dec> %s", sprint_hex(data, len));
457 AddLogHex(logHexFileName, "dec> ", data, len);
460 switch (traceState) {
461 case TRACE_IDLE:
462 // check packet crc16!
463 if ((len >= 4) && (!CheckCrc14443(CRC_14443_A, data, len))) {
464 PrintAndLog("dec> CRC ERROR!!!");
465 AddLogLine(logHexFileName, "dec> ", "CRC ERROR!!!");
466 traceState = TRACE_ERROR; // do not decrypt the next commands
467 return 1;
470 // AUTHENTICATION
471 if ((len ==4) && ((data[0] == 0x60) || (data[0] == 0x61))) {
472 traceState = TRACE_AUTH1;
473 traceCurBlock = data[1];
474 traceCurKey = data[0] == 60 ? 1:0;
475 return 0;
478 // READ
479 if ((len ==4) && ((data[0] == 0x30))) {
480 traceState = TRACE_READ_DATA;
481 traceCurBlock = data[1];
482 return 0;
485 // WRITE
486 if ((len ==4) && ((data[0] == 0xA0))) {
487 traceState = TRACE_WRITE_OK;
488 traceCurBlock = data[1];
489 return 0;
492 // HALT
493 if ((len ==4) && ((data[0] == 0x50) && (data[1] == 0x00))) {
494 traceState = TRACE_ERROR; // do not decrypt the next commands
495 return 0;
498 return 0;
499 break;
501 case TRACE_READ_DATA:
502 if (len == 18) {
503 traceState = TRACE_IDLE;
505 if (isBlockTrailer(traceCurBlock)) {
506 memcpy(traceCard + traceCurBlock * 16 + 6, data + 6, 4);
507 } else {
508 memcpy(traceCard + traceCurBlock * 16, data, 16);
510 if (wantSaveToEmlFile) saveTraceCard();
511 return 0;
512 } else {
513 traceState = TRACE_ERROR;
514 return 1;
516 break;
518 case TRACE_WRITE_OK:
519 if ((len == 1) && (data[0] == 0x0a)) {
520 traceState = TRACE_WRITE_DATA;
522 return 0;
523 } else {
524 traceState = TRACE_ERROR;
525 return 1;
527 break;
529 case TRACE_WRITE_DATA:
530 if (len == 18) {
531 traceState = TRACE_IDLE;
533 memcpy(traceCard + traceCurBlock * 16, data, 16);
534 if (wantSaveToEmlFile) saveTraceCard();
535 return 0;
536 } else {
537 traceState = TRACE_ERROR;
538 return 1;
540 break;
542 case TRACE_AUTH1:
543 if (len == 4) {
544 traceState = TRACE_AUTH2;
545 nt = bytes_to_num(data, 4);
546 return 0;
547 } else {
548 traceState = TRACE_ERROR;
549 return 1;
551 break;
553 case TRACE_AUTH2:
554 if (len == 8) {
555 traceState = TRACE_AUTH_OK;
557 nr_enc = bytes_to_num(data, 4);
558 ar_enc = bytes_to_num(data + 4, 4);
559 return 0;
560 } else {
561 traceState = TRACE_ERROR;
562 return 1;
564 break;
566 case TRACE_AUTH_OK:
567 if (len ==4) {
568 traceState = TRACE_IDLE;
570 at_enc = bytes_to_num(data, 4);
572 // decode key here)
573 ks2 = ar_enc ^ prng_successor(nt, 64);
574 ks3 = at_enc ^ prng_successor(nt, 96);
575 revstate = lfsr_recovery64(ks2, ks3);
576 lfsr_rollback_word(revstate, 0, 0);
577 lfsr_rollback_word(revstate, 0, 0);
578 lfsr_rollback_word(revstate, nr_enc, 1);
579 lfsr_rollback_word(revstate, uid ^ nt, 0);
581 crypto1_get_lfsr(revstate, &lfsr);
582 printf("key> %x%x\n", (unsigned int)((lfsr & 0xFFFFFFFF00000000) >> 32), (unsigned int)(lfsr & 0xFFFFFFFF));
583 AddLogUint64(logHexFileName, "key> ", lfsr);
585 int blockShift = ((traceCurBlock & 0xFC) + 3) * 16;
586 if (isBlockEmpty((traceCurBlock & 0xFC) + 3)) memcpy(traceCard + blockShift + 6, trailerAccessBytes, 4);
588 if (traceCurKey) {
589 num_to_bytes(lfsr, 6, traceCard + blockShift + 10);
590 } else {
591 num_to_bytes(lfsr, 6, traceCard + blockShift);
593 if (wantSaveToEmlFile) saveTraceCard();
595 if (traceCrypto1) {
596 crypto1_destroy(traceCrypto1);
599 // set cryptosystem state
600 traceCrypto1 = lfsr_recovery64(ks2, ks3);
602 // nt = crypto1_word(traceCrypto1, nt ^ uid, 1) ^ nt;
604 /* traceCrypto1 = crypto1_create(lfsr); // key in lfsr
605 crypto1_word(traceCrypto1, nt ^ uid, 0);
606 crypto1_word(traceCrypto1, ar, 1);
607 crypto1_word(traceCrypto1, 0, 0);
608 crypto1_word(traceCrypto1, 0, 0);*/
610 return 0;
611 } else {
612 traceState = TRACE_ERROR;
613 return 1;
615 break;
617 default:
618 traceState = TRACE_ERROR;
619 return 1;
622 return 0;