]> cvs.zerfleddert.de Git - proxmark3-svn/blob - client/mifarehost.c
major USB update
[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 "mifarehost.h"
15 #include "proxmark3.h"
16
17 // MIFARE
18
19 int compar_int(const void * a, const void * b) {
20 return (*(uint64_t*)b - *(uint64_t*)a);
21 }
22
23 // Compare countKeys structure
24 int compar_special_int(const void * a, const void * b) {
25 return (((countKeys *)b)->count - ((countKeys *)a)->count);
26 }
27
28 countKeys * uniqsort(uint64_t * possibleKeys, uint32_t size) {
29 int i, j = 0;
30 int count = 0;
31 countKeys *our_counts;
32
33 qsort(possibleKeys, size, sizeof (uint64_t), compar_int);
34
35 our_counts = calloc(size, sizeof(countKeys));
36 if (our_counts == NULL) {
37 PrintAndLog("Memory allocation error for our_counts");
38 return NULL;
39 }
40
41 for (i = 0; i < size; i++) {
42 if (possibleKeys[i+1] == possibleKeys[i]) {
43 count++;
44 } else {
45 our_counts[j].key = possibleKeys[i];
46 our_counts[j].count = count;
47 j++;
48 count=0;
49 }
50 }
51 qsort(our_counts, j, sizeof(countKeys), compar_special_int);
52 return (our_counts);
53 }
54
55 int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t * resultKeys)
56 {
57 int i, m, len;
58 uint8_t isEOF;
59 uint32_t uid;
60 fnVector * vector = NULL;
61 countKeys *ck;
62 int lenVector = 0;
63 UsbCommand resp;
64
65 memset(resultKeys, 0x00, 16 * 6);
66
67 // flush queue
68 while (!WaitForResponseTimeout(CMD_ACK,NULL,500));
69
70 UsbCommand c = {CMD_MIFARE_NESTED, {blockNo, keyType, trgBlockNo + trgKeyType * 0x100}};
71 memcpy(c.d.asBytes, key, 6);
72 SendCommand(&c);
73
74 PrintAndLog("\n");
75
76 // wait cycle
77 while (true) {
78 printf(".");
79 if (ukbhit()) {
80 getchar();
81 printf("\naborted via keyboard!\n");
82 break;
83 }
84
85 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
86 isEOF = resp.arg[0] & 0xff;
87
88 if (isEOF) break;
89
90 len = resp.arg[1] & 0xff;
91 if (len == 0) continue;
92
93 memcpy(&uid, resp.d.asBytes, 4);
94 PrintAndLog("uid:%08x len=%d trgbl=%d trgkey=%x", uid, len, resp.arg[2] & 0xff, (resp.arg[2] >> 8) & 0xff);
95 vector = (fnVector *) realloc((void *)vector, (lenVector + len) * sizeof(fnVector) + 200);
96 if (vector == NULL) {
97 PrintAndLog("Memory allocation error for fnVector. len: %d bytes: %d", lenVector + len, (lenVector + len) * sizeof(fnVector));
98 break;
99 }
100
101 for (i = 0; i < len; i++) {
102 vector[lenVector + i].blockNo = resp.arg[2] & 0xff;
103 vector[lenVector + i].keyType = (resp.arg[2] >> 8) & 0xff;
104 vector[lenVector + i].uid = uid;
105
106 memcpy(&vector[lenVector + i].nt, (void *)(resp.d.asBytes + 8 + i * 8 + 0), 4);
107 memcpy(&vector[lenVector + i].ks1, (void *)(resp.d.asBytes + 8 + i * 8 + 4), 4);
108 }
109
110 lenVector += len;
111 }
112 }
113
114 if (!lenVector) {
115 PrintAndLog("Got 0 keys from proxmark.");
116 return 1;
117 }
118 printf("------------------------------------------------------------------\n");
119
120 // calc keys
121 struct Crypto1State* revstate = NULL;
122 struct Crypto1State* revstate_start = NULL;
123 uint64_t lfsr;
124 int kcount = 0;
125 pKeys *pk;
126
127 if ((pk = (void *) malloc(sizeof(pKeys))) == NULL) return 1;
128 memset(pk, 0x00, sizeof(pKeys));
129
130 for (m = 0; m < lenVector; m++) {
131 // And finally recover the first 32 bits of the key
132 revstate = lfsr_recovery32(vector[m].ks1, vector[m].nt ^ vector[m].uid);
133 if (revstate_start == NULL) revstate_start = revstate;
134
135 while ((revstate->odd != 0x0) || (revstate->even != 0x0)) {
136 lfsr_rollback_word(revstate, vector[m].nt ^ vector[m].uid, 0);
137 crypto1_get_lfsr(revstate, &lfsr);
138
139 // Allocate a new space for keys
140 if (((kcount % MEM_CHUNK) == 0) || (kcount >= pk->size)) {
141 pk->size += MEM_CHUNK;
142 //fprintf(stdout, "New chunk by %d, sizeof %d\n", kcount, pk->size * sizeof(uint64_t));
143 pk->possibleKeys = (uint64_t *) realloc((void *)pk->possibleKeys, pk->size * sizeof(uint64_t));
144 if (pk->possibleKeys == NULL) {
145 PrintAndLog("Memory allocation error for pk->possibleKeys");
146 return 1;
147 }
148 }
149 pk->possibleKeys[kcount] = lfsr;
150 kcount++;
151 revstate++;
152 }
153 free(revstate_start);
154 revstate_start = NULL;
155
156 }
157
158 // Truncate
159 if (kcount != 0) {
160 pk->size = --kcount;
161 if ((pk->possibleKeys = (uint64_t *) realloc((void *)pk->possibleKeys, pk->size * sizeof(uint64_t))) == NULL) {
162 PrintAndLog("Memory allocation error for pk->possibleKeys");
163 return 1;
164 }
165 }
166
167 PrintAndLog("Total keys count:%d", kcount);
168 ck = uniqsort(pk->possibleKeys, pk->size);
169
170 // fill key array
171 for (i = 0; i < 16 ; i++) {
172 num_to_bytes(ck[i].key, 6, (uint8_t*)(resultKeys + i * 6));
173 }
174
175 // finalize
176 free(pk->possibleKeys);
177 free(pk);
178 free(ck);
179 free(vector);
180
181 return 0;
182 }
183
184 int mfCheckKeys (uint8_t blockNo, uint8_t keyType, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){
185 *key = 0;
186
187 UsbCommand c = {CMD_MIFARE_CHKKEYS, {blockNo, keyType, keycnt}};
188 memcpy(c.d.asBytes, keyBlock, 6 * keycnt);
189 SendCommand(&c);
190
191 UsbCommand resp;
192 if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) return 1;
193 if ((resp.arg[0] & 0xff) != 0x01) return 2;
194 *key = bytes_to_num(resp.d.asBytes, 6);
195 return 0;
196 }
197
198 // EMULATOR
199
200 int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) {
201 UsbCommand c = {CMD_MIFARE_EML_MEMGET, {blockNum, blocksCount, 0}};
202 SendCommand(&c);
203
204 UsbCommand resp;
205 if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) return 1;
206 memcpy(data, resp.d.asBytes, blocksCount * 16);
207 return 0;
208 }
209
210 int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) {
211 UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}};
212 memcpy(c.d.asBytes, data, blocksCount * 16);
213 SendCommand(&c);
214 return 0;
215 }
216
217 // "MAGIC" CARD
218
219 int mfCSetUID(uint8_t *uid, uint8_t *oldUID, int wantWipe) {
220 uint8_t block0[16];
221 memset(block0, 0, 16);
222 memcpy(block0, uid, 4);
223 block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // Mifare UID BCC
224 // mifare classic SAK(byte 5) and ATQA(byte 6 and 7)
225 block0[5] = 0x88;
226 block0[6] = 0x04;
227 block0[7] = 0x00;
228
229 return mfCSetBlock(0, block0, oldUID, wantWipe, CSETBLOCK_SINGLE_OPER);
230 }
231
232 int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, int wantWipe, uint8_t params) {
233 uint8_t isOK = 0;
234
235 UsbCommand c = {CMD_MIFARE_EML_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}};
236 memcpy(c.d.asBytes, data, 16);
237 SendCommand(&c);
238
239 UsbCommand resp;
240 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
241 isOK = resp.arg[0] & 0xff;
242 if (uid != NULL) memcpy(uid, resp.d.asBytes, 4);
243 if (!isOK) return 2;
244 } else {
245 PrintAndLog("Command execute timeout");
246 return 1;
247 }
248 return 0;
249 }
250
251 int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) {
252 uint8_t isOK = 0;
253
254 UsbCommand c = {CMD_MIFARE_EML_CGETBLOCK, {params, 0, blockNo}};
255 SendCommand(&c);
256
257 UsbCommand resp;
258 if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
259 isOK = resp.arg[0] & 0xff;
260 memcpy(data, resp.d.asBytes, 16);
261 if (!isOK) return 2;
262 } else {
263 PrintAndLog("Command execute timeout");
264 return 1;
265 }
266 return 0;
267 }
268
269 // SNIFFER
270
271 // constants
272 static uint8_t trailerAccessBytes[4] = {0x08, 0x77, 0x8F, 0x00};
273
274 // variables
275 char logHexFileName[200] = {0x00};
276 static uint8_t traceCard[4096] = {0x00};
277 static char traceFileName[20];
278 static int traceState = TRACE_IDLE;
279 static uint8_t traceCurBlock = 0;
280 static uint8_t traceCurKey = 0;
281
282 struct Crypto1State *traceCrypto1 = NULL;
283
284 struct Crypto1State *revstate;
285 uint64_t lfsr;
286 uint32_t ks2;
287 uint32_t ks3;
288
289 uint32_t uid; // serial number
290 uint32_t nt; // tag challenge
291 uint32_t nt_par;
292 uint32_t nr_enc; // encrypted reader challenge
293 uint32_t ar_enc; // encrypted reader response
294 uint32_t nr_ar_par;
295 uint32_t at_enc; // encrypted tag response
296 uint32_t at_par;
297
298 int isTraceCardEmpty(void) {
299 return ((traceCard[0] == 0) && (traceCard[1] == 0) && (traceCard[2] == 0) && (traceCard[3] == 0));
300 }
301
302 int isBlockEmpty(int blockN) {
303 for (int i = 0; i < 16; i++)
304 if (traceCard[blockN * 16 + i] != 0) return 0;
305
306 return 1;
307 }
308
309 int isBlockTrailer(int blockN) {
310 return ((blockN & 0x03) == 0x03);
311 }
312
313 int loadTraceCard(uint8_t *tuid) {
314 FILE * f;
315 char buf[64];
316 uint8_t buf8[64];
317 int i, blockNum;
318
319 if (!isTraceCardEmpty()) saveTraceCard();
320 memset(traceCard, 0x00, 4096);
321 memcpy(traceCard, tuid + 3, 4);
322 FillFileNameByUID(traceFileName, tuid, ".eml", 7);
323
324 f = fopen(traceFileName, "r");
325 if (!f) return 1;
326
327 blockNum = 0;
328 while(!feof(f)){
329 memset(buf, 0, sizeof(buf));
330 fgets(buf, sizeof(buf), f);
331
332 if (strlen(buf) < 32){
333 if (feof(f)) break;
334 PrintAndLog("File content error. Block data must include 32 HEX symbols");
335 return 2;
336 }
337 for (i = 0; i < 32; i += 2)
338 sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]);
339
340 memcpy(traceCard + blockNum * 16, buf8, 16);
341
342 blockNum++;
343 }
344 fclose(f);
345
346 return 0;
347 }
348
349 int saveTraceCard(void) {
350 FILE * f;
351
352 if ((!strlen(traceFileName)) || (isTraceCardEmpty())) return 0;
353
354 f = fopen(traceFileName, "w+");
355 for (int i = 0; i < 64; i++) { // blocks
356 for (int j = 0; j < 16; j++) // bytes
357 fprintf(f, "%02x", *(traceCard + i * 16 + j));
358 fprintf(f,"\n");
359 }
360 fclose(f);
361
362 return 0;
363 }
364
365 int mfTraceInit(uint8_t *tuid, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile) {
366
367 if (traceCrypto1) crypto1_destroy(traceCrypto1);
368 traceCrypto1 = NULL;
369
370 if (wantSaveToEmlFile) loadTraceCard(tuid);
371 traceCard[4] = traceCard[0] ^ traceCard[1] ^ traceCard[2] ^ traceCard[3];
372 traceCard[5] = sak;
373 memcpy(&traceCard[6], atqa, 2);
374 traceCurBlock = 0;
375 uid = bytes_to_num(tuid + 3, 4);
376
377 traceState = TRACE_IDLE;
378
379 return 0;
380 }
381
382 void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted){
383 uint8_t bt = 0;
384 int i;
385
386 if (len != 1) {
387 for (i = 0; i < len; i++)
388 data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i];
389 } else {
390 bt = 0;
391 for (i = 0; i < 4; i++)
392 bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], i)) << i;
393
394 data[0] = bt;
395 }
396 return;
397 }
398
399
400 int mfTraceDecode(uint8_t *data_src, int len, uint32_t parity, bool wantSaveToEmlFile) {
401 uint8_t data[64];
402
403 if (traceState == TRACE_ERROR) return 1;
404 if (len > 64) {
405 traceState = TRACE_ERROR;
406 return 1;
407 }
408
409 memcpy(data, data_src, len);
410 if ((traceCrypto1) && ((traceState == TRACE_IDLE) || (traceState > TRACE_AUTH_OK))) {
411 mf_crypto1_decrypt(traceCrypto1, data, len, 0);
412 PrintAndLog("dec> %s", sprint_hex(data, len));
413 AddLogHex(logHexFileName, "dec> ", data, len);
414 }
415
416 switch (traceState) {
417 case TRACE_IDLE:
418 // check packet crc16!
419 if ((len >= 4) && (!CheckCrc14443(CRC_14443_A, data, len))) {
420 PrintAndLog("dec> CRC ERROR!!!");
421 AddLogLine(logHexFileName, "dec> ", "CRC ERROR!!!");
422 traceState = TRACE_ERROR; // do not decrypt the next commands
423 return 1;
424 }
425
426 // AUTHENTICATION
427 if ((len ==4) && ((data[0] == 0x60) || (data[0] == 0x61))) {
428 traceState = TRACE_AUTH1;
429 traceCurBlock = data[1];
430 traceCurKey = data[0] == 60 ? 1:0;
431 return 0;
432 }
433
434 // READ
435 if ((len ==4) && ((data[0] == 0x30))) {
436 traceState = TRACE_READ_DATA;
437 traceCurBlock = data[1];
438 return 0;
439 }
440
441 // WRITE
442 if ((len ==4) && ((data[0] == 0xA0))) {
443 traceState = TRACE_WRITE_OK;
444 traceCurBlock = data[1];
445 return 0;
446 }
447
448 // HALT
449 if ((len ==4) && ((data[0] == 0x50) && (data[1] == 0x00))) {
450 traceState = TRACE_ERROR; // do not decrypt the next commands
451 return 0;
452 }
453
454 return 0;
455 break;
456
457 case TRACE_READ_DATA:
458 if (len == 18) {
459 traceState = TRACE_IDLE;
460
461 if (isBlockTrailer(traceCurBlock)) {
462 memcpy(traceCard + traceCurBlock * 16 + 6, data + 6, 4);
463 } else {
464 memcpy(traceCard + traceCurBlock * 16, data, 16);
465 }
466 if (wantSaveToEmlFile) saveTraceCard();
467 return 0;
468 } else {
469 traceState = TRACE_ERROR;
470 return 1;
471 }
472 break;
473
474 case TRACE_WRITE_OK:
475 if ((len == 1) && (data[0] = 0x0a)) {
476 traceState = TRACE_WRITE_DATA;
477
478 return 0;
479 } else {
480 traceState = TRACE_ERROR;
481 return 1;
482 }
483 break;
484
485 case TRACE_WRITE_DATA:
486 if (len == 18) {
487 traceState = TRACE_IDLE;
488
489 memcpy(traceCard + traceCurBlock * 16, data, 16);
490 if (wantSaveToEmlFile) saveTraceCard();
491 return 0;
492 } else {
493 traceState = TRACE_ERROR;
494 return 1;
495 }
496 break;
497
498 case TRACE_AUTH1:
499 if (len == 4) {
500 traceState = TRACE_AUTH2;
501
502 nt = bytes_to_num(data, 4);
503 nt_par = parity;
504 return 0;
505 } else {
506 traceState = TRACE_ERROR;
507 return 1;
508 }
509 break;
510
511 case TRACE_AUTH2:
512 if (len == 8) {
513 traceState = TRACE_AUTH_OK;
514
515 nr_enc = bytes_to_num(data, 4);
516 ar_enc = bytes_to_num(data + 4, 4);
517 nr_ar_par = parity;
518 return 0;
519 } else {
520 traceState = TRACE_ERROR;
521 return 1;
522 }
523 break;
524
525 case TRACE_AUTH_OK:
526 if (len ==4) {
527 traceState = TRACE_IDLE;
528
529 at_enc = bytes_to_num(data, 4);
530 at_par = parity;
531
532 // decode key here)
533 if (!traceCrypto1) {
534 ks2 = ar_enc ^ prng_successor(nt, 64);
535 ks3 = at_enc ^ prng_successor(nt, 96);
536 revstate = lfsr_recovery64(ks2, ks3);
537 lfsr_rollback_word(revstate, 0, 0);
538 lfsr_rollback_word(revstate, 0, 0);
539 lfsr_rollback_word(revstate, nr_enc, 1);
540 lfsr_rollback_word(revstate, uid ^ nt, 0);
541 }else{
542 ks2 = ar_enc ^ prng_successor(nt, 64);
543 ks3 = at_enc ^ prng_successor(nt, 96);
544 revstate = lfsr_recovery64(ks2, ks3);
545 lfsr_rollback_word(revstate, 0, 0);
546 lfsr_rollback_word(revstate, 0, 0);
547 lfsr_rollback_word(revstate, nr_enc, 1);
548 lfsr_rollback_word(revstate, uid ^ nt, 0);
549 }
550 crypto1_get_lfsr(revstate, &lfsr);
551 printf("key> %x%x\n", (unsigned int)((lfsr & 0xFFFFFFFF00000000) >> 32), (unsigned int)(lfsr & 0xFFFFFFFF));
552 AddLogUint64(logHexFileName, "key> ", lfsr);
553
554 int blockShift = ((traceCurBlock & 0xFC) + 3) * 16;
555 if (isBlockEmpty((traceCurBlock & 0xFC) + 3)) memcpy(traceCard + blockShift + 6, trailerAccessBytes, 4);
556
557 if (traceCurKey) {
558 num_to_bytes(lfsr, 6, traceCard + blockShift + 10);
559 } else {
560 num_to_bytes(lfsr, 6, traceCard + blockShift);
561 }
562 if (wantSaveToEmlFile) saveTraceCard();
563
564 if (traceCrypto1) {
565 crypto1_destroy(traceCrypto1);
566 }
567
568 // set cryptosystem state
569 traceCrypto1 = lfsr_recovery64(ks2, ks3);
570
571 // nt = crypto1_word(traceCrypto1, nt ^ uid, 1) ^ nt;
572
573 /* traceCrypto1 = crypto1_create(lfsr); // key in lfsr
574 crypto1_word(traceCrypto1, nt ^ uid, 0);
575 crypto1_word(traceCrypto1, ar, 1);
576 crypto1_word(traceCrypto1, 0, 0);
577 crypto1_word(traceCrypto1, 0, 0);*/
578
579 return 0;
580 } else {
581 traceState = TRACE_ERROR;
582 return 1;
583 }
584 break;
585
586 default:
587 traceState = TRACE_ERROR;
588 return 1;
589 }
590
591 return 0;
592 }
Impressum, Datenschutz