]> cvs.zerfleddert.de Git - proxmark3-svn/blob - client/cmdhflegic.c
ADD: added a StopTicks functions, to disable the timer used for ticks (TC0, TC1)
[proxmark3-svn] / client / cmdhflegic.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
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 // High frequency Legic commands
9 //-----------------------------------------------------------------------------
10 #include "cmdhflegic.h"
11
12 static int CmdHelp(const char *Cmd);
13
14 #define MAX_LENGTH 1024
15
16 int usage_legic_calccrc8(void){
17 PrintAndLog("Calculates the legic crc8/crc16 on the input hexbytes.");
18 PrintAndLog("There must be an even number of hexsymbols as input.");
19 PrintAndLog("Usage: hf legic crc8 [h] b <hexbytes> u <uidcrc> c <crc type>");
20 PrintAndLog("Options:");
21 PrintAndLog(" h : this help");
22 PrintAndLog(" b <hexbytes> : hex bytes");
23 PrintAndLog(" u <uidcrc> : MCC hexbyte");
24 PrintAndLog(" c <crc type> : 8|16 bit crc size");
25 PrintAndLog("");
26 PrintAndLog("Samples:");
27 PrintAndLog(" hf legic crc8 b deadbeef1122");
28 PrintAndLog(" hf legic crc8 b deadbeef1122 u 9A c 16");
29 return 0;
30 }
31 int usage_legic_load(void){
32 PrintAndLog("It loads datasamples from the file `filename` to device memory");
33 PrintAndLog("Usage: hf legic load [h] <file name>");
34 PrintAndLog("Options:");
35 PrintAndLog(" h : this help");
36 PrintAndLog(" <filename> : Name of file to load");
37 PrintAndLog("");
38 PrintAndLog("Samples:");
39 PrintAndLog(" hf legic load filename");
40 return 0;
41 }
42 int usage_legic_rdmem(void){
43 PrintAndLog("Read data from a legic tag.");
44 PrintAndLog("Usage: hf legic rdmem [h] <offset> <length> <IV>");
45 PrintAndLog("Options:");
46 PrintAndLog(" h : this help");
47 PrintAndLog(" <offset> : offset in data array to start download from (hex)");
48 PrintAndLog(" <length> : number of bytes to read (hex)");
49 PrintAndLog(" <IV> : (optional) Initialization vector to use (hex, odd and 7bits)");
50 PrintAndLog("");
51 PrintAndLog("Samples:");
52 PrintAndLog(" hf legic rdmem 0 21 - reads from byte[0] 21 bytes(system header)");
53 PrintAndLog(" hf legic rdmem 0 4 55 - reads from byte[0] 4 bytes with IV 0x55");
54 PrintAndLog(" hf legic rdmem 0 100 55 - reads 256bytes with IV 0x55");
55 return 0;
56 }
57 int usage_legic_sim(void){
58 PrintAndLog("Missing help text.");
59 return 0;
60 }
61 int usage_legic_write(void){
62 PrintAndLog(" Write sample buffer to a legic tag. (use after load or read)");
63 PrintAndLog("Usage: hf legic write [h] <offset> <length> <IV>");
64 PrintAndLog("Options:");
65 PrintAndLog(" h : this help");
66 PrintAndLog(" <offset> : offset in data array to start writing from (hex)");
67 PrintAndLog(" <length> : number of bytes to write (hex)");
68 PrintAndLog(" <IV> : (optional) Initialization vector to use (ODD and 7bits)");
69 PrintAndLog("");
70 PrintAndLog("Samples:");
71 PrintAndLog(" hf legic write 10 4 - writes 0x4 to byte[0x10]");
72 return 0;
73 }
74 int usage_legic_reader(void){
75 PrintAndLog("Read UID and type information from a legic tag.");
76 PrintAndLog("Usage: hf legic reader [h]");
77 PrintAndLog("Options:");
78 PrintAndLog(" h : this help");
79 PrintAndLog("");
80 PrintAndLog("Samples:");
81 PrintAndLog(" hf legic reader");
82 return 0;
83 }
84 int usage_legic_info(void){
85 PrintAndLog("Reads information from a legic prime tag.");
86 PrintAndLog("Shows systemarea, user areas etc");
87 PrintAndLog("Usage: hf legic info [h]");
88 PrintAndLog("Options:");
89 PrintAndLog(" h : this help");
90 PrintAndLog("");
91 PrintAndLog("Samples:");
92 PrintAndLog(" hf legic info");
93 return 0;
94 }
95 int usage_legic_dump(void){
96 PrintAndLog("Reads all pages from LEGIC MIM22, MIM256, MIM1024");
97 PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`");
98 PrintAndLog("It autodetects card type.\n");
99 PrintAndLog("Usage: hf legic dump [h] o <filename w/o .bin>");
100 PrintAndLog("Options:");
101 PrintAndLog(" h : this help");
102 PrintAndLog(" n <FN> : filename w/o .bin to save the dump as");
103 PrintAndLog("");
104 PrintAndLog("Samples:");
105 PrintAndLog(" hf legic dump");
106 PrintAndLog(" hf legic dump o myfile");
107 return 0;
108 }
109 int usage_legic_eload(void){
110 PrintAndLog("It loads binary dump from the file `filename.bin`");
111 PrintAndLog("Usage: hf legic eload [h] [card memory] <file name w/o `.bin`>");
112 PrintAndLog("Options:");
113 PrintAndLog(" h : this help");
114 PrintAndLog(" [card memory] : 0 = MIM22");
115 PrintAndLog(" : 1 = MIM256 (default)");
116 PrintAndLog(" : 2 = MIM1024");
117 PrintAndLog(" <filename> : filename w/o .bin to load");
118 PrintAndLog("");
119 PrintAndLog("Samples:");
120 PrintAndLog(" hf legic eload filename");
121 PrintAndLog(" hf legic eload 2 filename");
122 return 0;
123 }
124 int usage_legic_esave(void){
125 PrintAndLog("It saves binary dump into the file `filename.bin` or `cardID.bin`");
126 PrintAndLog(" Usage: hf legic esave [h] [card memory] [file name w/o `.bin`]");
127 PrintAndLog("Options:");
128 PrintAndLog(" h : this help");
129 PrintAndLog(" [card memory] : 0 = MIM22");
130 PrintAndLog(" : 1 = MIM256 (default)");
131 PrintAndLog(" : 2 = MIM1024");
132 PrintAndLog(" <filename> : filename w/o .bin to load");
133 PrintAndLog("");
134 PrintAndLog("Samples:");
135 PrintAndLog(" hf legic esave ");
136 PrintAndLog(" hf legic esave 2");
137 PrintAndLog(" hf legic esave 2 filename");
138 return 0;
139 }
140
141 /*
142 * Output BigBuf and deobfuscate LEGIC RF tag data.
143 * This is based on information given in the talk held
144 * by Henryk Ploetz and Karsten Nohl at 26c3
145 */
146 int CmdLegicInfo(const char *Cmd) {
147
148 char cmdp = param_getchar(Cmd, 0);
149 if ( cmdp == 'H' || cmdp == 'h' ) return usage_legic_info();
150
151 int i = 0, k = 0, segmentNum = 0, segment_len = 0, segment_flag = 0;
152 int crc = 0, wrp = 0, wrc = 0;
153 uint8_t stamp_len = 0;
154 uint8_t data[1024]; // receiver buffer
155 char token_type[5] = {0,0,0,0,0};
156 int dcf = 0;
157 int bIsSegmented = 0;
158
159 CmdLegicRdmem("0 22 55");
160
161 // copy data from device
162 GetEMLFromBigBuf(data, sizeof(data), 0);
163 if ( !WaitForResponseTimeout(CMD_ACK, NULL, 2000)){
164 PrintAndLog("Command execute timeout");
165 return 1;
166 }
167
168 // Output CDF System area (9 bytes) plus remaining header area (12 bytes)
169 crc = data[4];
170 uint32_t calc_crc = CRC8Legic(data, 4);
171
172 PrintAndLog("\nCDF: System Area");
173 PrintAndLog("------------------------------------------------------");
174 PrintAndLog("MCD: %02x, MSN: %02x %02x %02x, MCC: %02x %s",
175 data[0],
176 data[1],
177 data[2],
178 data[3],
179 data[4],
180 (calc_crc == crc) ? "OK":"Fail"
181 );
182
183 // MCD = Manufacturer ID (should be list meaning something?)
184
185 token_type[0] = 0;
186 dcf = ((int)data[6] << 8) | (int)data[5];
187
188 // New unwritten media?
189 if(dcf == 0xFFFF) {
190
191 PrintAndLog("DCF: %d (%02x %02x), Token Type=NM (New Media)",
192 dcf,
193 data[5],
194 data[6]
195 );
196
197 } else if(dcf > 60000) { // Master token?
198
199 int fl = 0;
200
201 if(data[6] == 0xec) {
202 strncpy(token_type, "XAM", sizeof(token_type));
203 fl = 1;
204 stamp_len = 0x0c - (data[5] >> 4);
205 } else {
206 switch (data[5] & 0x7f) {
207 case 0x00 ... 0x2f:
208 strncpy(token_type, "IAM", sizeof(token_type));
209 fl = (0x2f - (data[5] & 0x7f)) + 1;
210 break;
211 case 0x30 ... 0x6f:
212 strncpy(token_type, "SAM", sizeof(token_type));
213 fl = (0x6f - (data[5] & 0x7f)) + 1;
214 break;
215 case 0x70 ... 0x7f:
216 strncpy(token_type, "GAM", sizeof(token_type));
217 fl = (0x7f - (data[5] & 0x7f)) + 1;
218 break;
219 }
220
221 stamp_len = 0xfc - data[6];
222 }
223
224 PrintAndLog("DCF: %d (%02x %02x), Token Type=%s (OLE=%01u), OL=%02u, FL=%02u",
225 dcf,
226 data[5],
227 data[6],
228 token_type,
229 (data[5] & 0x80 )>> 7,
230 stamp_len,
231 fl
232 );
233
234 } else { // Is IM(-S) type of card...
235
236 if(data[7] == 0x9F && data[8] == 0xFF) {
237 bIsSegmented = 1;
238 strncpy(token_type, "IM-S", sizeof(token_type));
239 } else {
240 strncpy(token_type, "IM", sizeof(token_type));
241 }
242
243 PrintAndLog("DCF: %d (%02x %02x), Token Type=%s (OLE=%01u)",
244 dcf,
245 data[5],
246 data[6],
247 token_type,
248 (data[5]&0x80) >> 7
249 );
250 }
251
252 // Makes no sence to show this on blank media...
253 if(dcf != 0xFFFF) {
254
255 if(bIsSegmented) {
256 PrintAndLog("WRP=%02u, WRC=%01u, RD=%01u, SSC=%02x",
257 data[7] & 0x0f,
258 (data[7] & 0x70) >> 4,
259 (data[7] & 0x80) >> 7,
260 data[8]
261 );
262 }
263
264 // Header area is only available on IM-S cards, on master tokens this data is the master token data itself
265 if(bIsSegmented || dcf > 60000) {
266 if(dcf > 60000) {
267 PrintAndLog("Master token data");
268 PrintAndLog("%s", sprint_hex(data+8, 14));
269 } else {
270 PrintAndLog("Remaining Header Area");
271 PrintAndLog("%s", sprint_hex(data+9, 13));
272 }
273 }
274 }
275
276 uint8_t segCrcBytes[8] = {0,0,0,0,0,0,0,0};
277 uint32_t segCalcCRC = 0;
278 uint32_t segCRC = 0;
279
280 // Data card?
281 if(dcf <= 60000) {
282
283 PrintAndLog("\nADF: User Area");
284 PrintAndLog("------------------------------------------------------");
285
286 if(bIsSegmented) {
287
288 // Data start point on segmented cards
289 i = 22;
290
291 // decode segments
292 for (segmentNum=1; segmentNum < 128; segmentNum++ )
293 {
294 segment_len = ((data[i+1] ^ crc) & 0x0f) * 256 + (data[i] ^ crc);
295 segment_flag = ((data[i+1] ^ crc) & 0xf0) >> 4;
296 wrp = (data[i+2] ^ crc);
297 wrc = ((data[i+3] ^ crc) & 0x70) >> 4;
298
299 bool hasWRC = (wrc > 0);
300 bool hasWRP = (wrp > wrc);
301 int wrp_len = (wrp - wrc);
302 int remain_seg_payload_len = (segment_len - wrp - 5);
303
304 // validate segment-crc
305 segCrcBytes[0]=data[0]; //uid0
306 segCrcBytes[1]=data[1]; //uid1
307 segCrcBytes[2]=data[2]; //uid2
308 segCrcBytes[3]=data[3]; //uid3
309 segCrcBytes[4]=(data[i] ^ crc); //hdr0
310 segCrcBytes[5]=(data[i+1] ^ crc); //hdr1
311 segCrcBytes[6]=(data[i+2] ^ crc); //hdr2
312 segCrcBytes[7]=(data[i+3] ^ crc); //hdr3
313
314 segCalcCRC = CRC8Legic(segCrcBytes, 8);
315 segCRC = data[i+4] ^ crc;
316
317 PrintAndLog("Segment %02u \nraw header | 0x%02X 0x%02X 0x%02X 0x%02X \nSegment len: %u, Flag: 0x%X (valid:%01u, last:%01u), WRP: %02u, WRC: %02u, RD: %01u, CRC: 0x%02X (%s)",
318 segmentNum,
319 data[i] ^ crc,
320 data[i+1] ^ crc,
321 data[i+2] ^ crc,
322 data[i+3] ^ crc,
323 segment_len,
324 segment_flag,
325 (segment_flag & 0x4) >> 2,
326 (segment_flag & 0x8) >> 3,
327 wrp,
328 wrc,
329 ((data[i+3]^crc) & 0x80) >> 7,
330 segCRC,
331 ( segCRC == segCalcCRC ) ? "OK" : "fail"
332 );
333
334 i += 5;
335
336 if ( hasWRC ) {
337 PrintAndLog("WRC protected area: (I %d | K %d| WRC %d)", i, k, wrc);
338 PrintAndLog("\nrow | data");
339 PrintAndLog("-----+------------------------------------------------");
340
341 for ( k=i; k < (i + wrc); ++k)
342 data[k] ^= crc;
343
344 print_hex_break( data+i, wrc, 16);
345
346 i += wrc;
347 }
348
349 if ( hasWRP ) {
350 PrintAndLog("Remaining write protected area: (I %d | K %d | WRC %d | WRP %d WRP_LEN %d)",i, k, wrc, wrp, wrp_len);
351 PrintAndLog("\nrow | data");
352 PrintAndLog("-----+------------------------------------------------");
353
354 for (k=i; k < (i+wrp_len); ++k)
355 data[k] ^= crc;
356
357 print_hex_break( data+i, wrp_len, 16);
358
359 i += wrp_len;
360
361 // does this one work? (Answer: Only if KGH/BGH is used with BCD encoded card number! So maybe this will show just garbage...)
362 if( wrp_len == 8 )
363 PrintAndLog("Card ID: %2X%02X%02X", data[i-4]^crc, data[i-3]^crc, data[i-2]^crc);
364 }
365
366 PrintAndLog("Remaining segment payload: (I %d | K %d | Remain LEN %d)", i, k, remain_seg_payload_len);
367 PrintAndLog("\nrow | data");
368 PrintAndLog("-----+------------------------------------------------");
369
370 for ( k=i; k < (i+remain_seg_payload_len); ++k)
371 data[k] ^= crc;
372
373 print_hex_break( data+i, remain_seg_payload_len, 16);
374
375 i += remain_seg_payload_len;
376
377 PrintAndLog("-----+------------------------------------------------\n");
378
379 // end with last segment
380 if (segment_flag & 0x8) return 0;
381
382 } // end for loop
383
384 } else {
385
386 // Data start point on unsegmented cards
387 i = 8;
388
389 wrp = data[7] & 0x0F;
390 wrc = (data[7] & 0x70) >> 4;
391
392 bool hasWRC = (wrc > 0);
393 bool hasWRP = (wrp > wrc);
394 int wrp_len = (wrp - wrc);
395 int remain_seg_payload_len = (1024 - 22 - wrp); // Any chance to get physical card size here!?
396
397 PrintAndLog("Unsegmented card - WRP: %02u, WRC: %02u, RD: %01u",
398 wrp,
399 wrc,
400 (data[7] & 0x80) >> 7
401 );
402
403 if ( hasWRC ) {
404 PrintAndLog("WRC protected area: (I %d | WRC %d)", i, wrc);
405 PrintAndLog("\nrow | data");
406 PrintAndLog("-----+------------------------------------------------");
407 print_hex_break( data+i, wrc, 16);
408 i += wrc;
409 }
410
411 if ( hasWRP ) {
412 PrintAndLog("Remaining write protected area: (I %d | WRC %d | WRP %d | WRP_LEN %d)", i, wrc, wrp, wrp_len);
413 PrintAndLog("\nrow | data");
414 PrintAndLog("-----+------------------------------------------------");
415 print_hex_break( data + i, wrp_len, 16);
416 i += wrp_len;
417
418 // does this one work? (Answer: Only if KGH/BGH is used with BCD encoded card number! So maybe this will show just garbage...)
419 if( wrp_len == 8 )
420 PrintAndLog("Card ID: %2X%02X%02X", data[i-4], data[i-3], data[i-2]);
421 }
422
423 PrintAndLog("Remaining segment payload: (I %d | Remain LEN %d)", i, remain_seg_payload_len);
424 PrintAndLog("\nrow | data");
425 PrintAndLog("-----+------------------------------------------------");
426 print_hex_break( data + i, remain_seg_payload_len, 16);
427 i += remain_seg_payload_len;
428
429 PrintAndLog("-----+------------------------------------------------\n");
430 }
431 }
432 return 0;
433 }
434
435 // params:
436 // offset in data memory
437 // number of bytes to read
438 int CmdLegicRdmem(const char *Cmd) {
439
440 char cmdp = param_getchar(Cmd, 0);
441 if ( cmdp == 'H' || cmdp == 'h' ) return usage_legic_rdmem();
442
443 uint32_t offset = 0, len = 0, IV = 1;
444 sscanf(Cmd, "%x %x %x", &offset, &len, &IV);
445
446 // OUT-OF-BOUNDS check
447 if ( len + offset > MAX_LENGTH ) {
448 len = MAX_LENGTH - offset;
449 PrintAndLog("Out-of-bound, shorten len to %d (0x%02X)", len, len);
450 }
451
452 legic_chk_iv(&IV);
453
454 UsbCommand c = {CMD_READER_LEGIC_RF, {offset, len, IV}};
455 clearCommandBuffer();
456 SendCommand(&c);
457 UsbCommand resp;
458 if ( !WaitForResponseTimeout(CMD_ACK, &resp, 3000) ) {
459 PrintAndLog("command execution time out");
460 return 1;
461 }
462
463 uint8_t isOK = resp.arg[0] & 0xFF;
464 uint16_t readlen = resp.arg[1];
465 if ( !isOK ) {
466 PrintAndLog("failed reading tag");
467 return 2;
468 }
469
470 uint8_t *data = malloc(readlen);
471 if ( !data ){
472 PrintAndLog("Cannot allocate memory");
473 return 2;
474 }
475
476 if ( readlen != len )
477 PrintAndLog("Fail, only managed to read 0x%02X bytes", readlen);
478
479 // copy data from device
480 GetEMLFromBigBuf(data, readlen, 0);
481 if ( !WaitForResponseTimeout(CMD_ACK, NULL, 2500)){
482 PrintAndLog("Command execute timeout");
483 free(data);
484 return 1;
485 }
486
487 PrintAndLog("\n ## | Data");
488 PrintAndLog("-----+-----");
489 print_hex_break( data, readlen, 32);
490 free(data);
491 return 0;
492 }
493
494 // load, filename (ascii hex textfile)
495 // uploads it to device mem
496 int CmdLegicLoad(const char *Cmd) {
497
498 // iceman: potential bug, where all filepaths or filename which starts with H or h will print the helptext :)
499 char cmdp = param_getchar(Cmd, 0);
500 if ( cmdp == 'H' || cmdp == 'h' || cmdp == 0x00) return usage_legic_load();
501
502 char filename[FILE_PATH_SIZE] = {0x00};
503 int len = strlen(Cmd);
504
505 if (len > FILE_PATH_SIZE) {
506 PrintAndLog("Filepath too long (was %s bytes), max allowed is %s ", len, FILE_PATH_SIZE);
507 return 0;
508 }
509 memcpy(filename, Cmd, len);
510
511 FILE *f = fopen(filename, "r");
512 if(!f) {
513 PrintAndLog("couldn't open '%s'", Cmd);
514 return -1;
515 }
516
517 char line[80];
518 int offset = 0;
519 uint8_t data[USB_CMD_DATA_SIZE] = {0x00};
520 int index = 0;
521 int totalbytes = 0;
522 while ( fgets(line, sizeof(line), f) ) {
523 int res = sscanf(line, "%x %x %x %x %x %x %x %x",
524 (unsigned int *)&data[index],
525 (unsigned int *)&data[index + 1],
526 (unsigned int *)&data[index + 2],
527 (unsigned int *)&data[index + 3],
528 (unsigned int *)&data[index + 4],
529 (unsigned int *)&data[index + 5],
530 (unsigned int *)&data[index + 6],
531 (unsigned int *)&data[index + 7]);
532
533 if(res != 8) {
534 PrintAndLog("Error: could not read samples");
535 fclose(f);
536 return -1;
537 }
538 index += res;
539
540 if ( index == USB_CMD_DATA_SIZE ){
541 // PrintAndLog("sent %d | %d | %d", index, offset, totalbytes);
542 UsbCommand c = { CMD_DOWNLOADED_SIM_SAMPLES_125K, {offset, 0, 0}};
543 memcpy(c.d.asBytes, data, sizeof(data));
544 clearCommandBuffer();
545 SendCommand(&c);
546 if ( !WaitForResponseTimeout(CMD_ACK, NULL, 1500)){
547 PrintAndLog("Command execute timeout");
548 fclose(f);
549 return 1;
550 }
551 offset += index;
552 totalbytes += index;
553 index = 0;
554 }
555 }
556 fclose(f);
557
558 // left over bytes?
559 if ( index != 0 ) {
560 UsbCommand c = { CMD_DOWNLOADED_SIM_SAMPLES_125K, {offset, 0, 0}};
561 memcpy(c.d.asBytes, data, 8);
562 clearCommandBuffer();
563 SendCommand(&c);
564 if ( !WaitForResponseTimeout(CMD_ACK, NULL, 1500)){
565 PrintAndLog("Command execute timeout");
566 return 1;
567 }
568 totalbytes += index;
569 }
570
571 PrintAndLog("loaded %u samples", totalbytes);
572 return 0;
573 }
574
575 // Save, filename, num of bytes, starting offset. (in decimal)
576 // ie: "hf legic save nnn.txt 100 0 (saves the first 100bytes)
577 // (ascii hex textfile)
578 int CmdLegicSave(const char *Cmd) {
579 int requested = 1024;
580 int offset = 0;
581 int delivered = 0;
582 char filename[FILE_PATH_SIZE] = {0x00};
583 uint8_t got[1024] = {0x00};
584
585 memset(filename, 0, FILE_PATH_SIZE);
586
587 sscanf(Cmd, " %s %i %i", filename, &requested, &offset);
588
589 /* If no length given save entire legic read buffer */
590 /* round up to nearest 8 bytes so the saved data can be used with legicload */
591 if (requested == 0)
592 requested = 1024;
593
594 if (requested % 8 != 0) {
595 int remainder = requested % 8;
596 requested = requested + 8 - remainder;
597 }
598
599 if (offset + requested > sizeof(got)) {
600 PrintAndLog("Tried to read past end of buffer, <bytes> + <offset> > 1024");
601 return 0;
602 }
603
604 GetFromBigBuf(got, requested, offset);
605 if ( !WaitForResponseTimeout(CMD_ACK, NULL, 2000)){
606 PrintAndLog("Command execute timeout");
607 return 1;
608 }
609
610 FILE *f = fopen(filename, "w");
611 if(!f) {
612 PrintAndLog("couldn't open '%s'", Cmd+1);
613 return -1;
614 }
615
616 for (int j = 0; j < requested; j += 8) {
617 fprintf(f, "%02x %02x %02x %02x %02x %02x %02x %02x\n",
618 got[j+0], got[j+1], got[j+2], got[j+3],
619 got[j+4], got[j+5], got[j+6], got[j+7]
620 );
621 delivered += 8;
622 if (delivered >= requested) break;
623 }
624
625 fclose(f);
626 PrintAndLog("saved %u samples", delivered);
627 return 0;
628 }
629
630 //TODO: write a help text (iceman)
631 // should say which tagtype
632 // should load a tag to device mem.
633 int CmdLegicRfSim(const char *Cmd) {
634 UsbCommand c = {CMD_SIMULATE_TAG_LEGIC_RF, {6,3,0}};
635 sscanf(Cmd, " %"lli" %"lli" %"lli, &c.arg[0], &c.arg[1], &c.arg[2]);
636 clearCommandBuffer();
637 SendCommand(&c);
638 return 0;
639 }
640
641 int CmdLegicRfWrite(const char *Cmd) {
642
643 // offset - in tag memory
644 // length - num of bytes to be written
645
646 char cmdp = param_getchar(Cmd, 0);
647 if ( cmdp == 'H' || cmdp == 'h' ) return usage_legic_write();
648
649 uint32_t offset = 0, len = 0, IV = 0;
650
651 int res = sscanf(Cmd, "%x %x %x", &offset, &len, &IV);
652 if(res < 2) {
653 PrintAndLog("Please specify the offset and length as two hex strings and, optionally, the IV also as an hex string");
654 return -1;
655 }
656
657 // tagtype
658 legic_card_select_t card;
659 if (legic_get_type(&card)) {
660 PrintAndLog("Failed to identify tagtype");
661 return -1;
662 }
663
664 legic_print_type(card.cardsize, 0);
665
666 // OUT-OF-BOUNDS check
667 if ( len + offset > card.cardsize ) {
668 PrintAndLog("Out-of-bounds, Cardsize = %d, [offset+len = %d ]", card.cardsize, len + offset);
669 return -2;
670 }
671
672 legic_chk_iv(&IV);
673
674 UsbCommand c = {CMD_WRITER_LEGIC_RF, {offset, len, IV}};
675 clearCommandBuffer();
676 SendCommand(&c);
677 UsbCommand resp;
678 if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {
679 uint8_t isOK = resp.arg[0] & 0xFF;
680 if ( !isOK )
681 PrintAndLog("failed writing tag");
682 } else {
683 PrintAndLog("command execution time out");
684 return 1;
685 }
686
687 return 0;
688 }
689
690 int CmdLegicRfRawWrite(const char *Cmd) {
691 PrintAndLog("############# DANGER !! #############");
692 PrintAndLog("# changing the DCF is irreversible #");
693 PrintAndLog("#####################################");
694 PrintAndLog("do youe really want to continue? y(es) n(o)");
695 // if (scanf(" %c", &answer) > 0 && (answer == 'y' || answer == 'Y')) {
696 // return 0;
697 // }
698 return 0;
699 }
700
701 void static calc4(uint8_t *cmd, uint8_t len){
702 }
703
704 int CmdLegicCalcCrc8(const char *Cmd){
705
706 uint8_t *data = NULL;
707 uint8_t cmdp = 0, uidcrc = 0, type=0;
708 bool errors = false;
709 int len = 0;
710 int bg, en;
711
712 while(param_getchar(Cmd, cmdp) != 0x00) {
713 switch(param_getchar(Cmd, cmdp)) {
714 case 'b':
715 case 'B':
716 // peek at length of the input string so we can
717 // figure out how many elements to malloc in "data"
718 bg=en=0;
719 if (param_getptr(Cmd, &bg, &en, cmdp+1)) {
720 errors = true;
721 break;
722 }
723 len = (en - bg + 1);
724
725 // check that user entered even number of characters
726 // for hex data string
727 if (len & 1) {
728 errors = true;
729 break;
730 }
731
732 // it's possible for user to accidentally enter "b" parameter
733 // more than once - we have to clean previous malloc
734 if (data) free(data);
735 data = malloc(len >> 1);
736 if ( data == NULL ) {
737 PrintAndLog("Can't allocate memory. exiting");
738 errors = true;
739 break;
740 }
741
742 if (param_gethex(Cmd, cmdp+1, data, len)) {
743 errors = true;
744 break;
745 }
746
747 len >>= 1;
748 cmdp += 2;
749 break;
750 case 'u':
751 case 'U':
752 uidcrc = param_get8ex(Cmd, cmdp+1, 0, 16);
753 cmdp += 2;
754 break;
755 case 'c':
756 case 'C':
757 type = param_get8ex(Cmd, cmdp+1, 0, 10);
758 cmdp += 2;
759 break;
760 case 'h':
761 case 'H':
762 errors = true;
763 break;
764 default:
765 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
766 errors = true;
767 break;
768 }
769 if (errors) break;
770 }
771 //Validations
772 if (errors){
773 if (data) free(data);
774 return usage_legic_calccrc8();
775 }
776
777 switch (type){
778 case 16:
779 PrintAndLog("Legic crc16: %X", CRC16Legic(data, len, uidcrc));
780 break;
781 case 4:
782 calc4(data, 0);
783 break;
784 default:
785 PrintAndLog("Legic crc8: %X", CRC8Legic(data, len) );
786 break;
787 }
788
789 if (data) free(data);
790 return 0;
791 }
792
793 int legic_print_type(uint32_t tagtype, uint8_t spaces){
794 char spc[11] = " ";
795 spc[10]=0x00;
796 char *spacer = spc + (10-spaces);
797
798 if ( tagtype == 22 )
799 PrintAndLog("%sTYPE : MIM%d card (outdated)", spacer, tagtype);
800 else if ( tagtype == 256 )
801 PrintAndLog("%sTYPE : MIM%d card (234 bytes)", spacer, tagtype);
802 else if ( tagtype == 1024 )
803 PrintAndLog("%sTYPE : MIM%d card (1002 bytes)", spacer, tagtype);
804 else
805 PrintAndLog("%sTYPE : Unknown %06x", spacer, tagtype);
806 return 0;
807 }
808 int legic_get_type(legic_card_select_t *card){
809
810 if ( card == NULL ) return 1;
811
812 UsbCommand c = {CMD_LEGIC_INFO, {0,0,0}};
813 clearCommandBuffer();
814 SendCommand(&c);
815 UsbCommand resp;
816 if (!WaitForResponseTimeout(CMD_ACK, &resp, 500))
817 return 2;
818
819 uint8_t isOK = resp.arg[0] & 0xFF;
820 if ( !isOK )
821 return 3;
822
823 memcpy(card, (legic_card_select_t *)resp.d.asBytes, sizeof(legic_card_select_t));
824 return 0;
825 }
826 void legic_chk_iv(uint32_t *iv){
827 if ( (*iv & 0x7F) != *iv ){
828 *iv &= 0x7F;
829 PrintAndLog("Truncating IV to 7bits, %u", *iv);
830 }
831 // IV must be odd
832 if ( (*iv & 1) == 0 ){
833 *iv |= 0x01;
834 PrintAndLog("LSB of IV must be SET %u", *iv);
835 }
836 }
837 void legic_seteml(uint8_t *src, uint32_t offset, uint32_t numofbytes) {
838 size_t len = 0;
839 UsbCommand c = {CMD_LEGIC_ESET, {0, 0, 0}};
840 for(size_t i = 0; i < numofbytes; i += USB_CMD_DATA_SIZE) {
841
842 len = MIN((numofbytes - i), USB_CMD_DATA_SIZE);
843 c.arg[0] = i; // offset
844 c.arg[1] = len; // number of bytes
845 memcpy(c.d.asBytes, src+i, len);
846 clearCommandBuffer();
847 SendCommand(&c);
848 PrintAndLog("ICE: offset %d | len %d", i, len);
849 }
850 }
851
852 int HFLegicReader(const char *Cmd, bool verbose) {
853
854 char cmdp = param_getchar(Cmd, 0);
855 if ( cmdp == 'H' || cmdp == 'h' ) return usage_legic_reader();
856
857 legic_card_select_t card;
858 switch(legic_get_type(&card)){
859 case 1:
860 if ( verbose ) PrintAndLog("command execution time out");
861 return 1;
862 case 2:
863 case 3:
864 if ( verbose ) PrintAndLog("legic card select failed");
865 return 2;
866 default: break;
867 }
868 PrintAndLog(" UID : %s", sprint_hex(card.uid, sizeof(card.uid)));
869 legic_print_type(card.cardsize, 0);
870 return 0;
871 }
872 int CmdLegicReader(const char *Cmd){
873 return HFLegicReader(Cmd, TRUE);
874 }
875
876 int CmdLegicDump(const char *Cmd){
877
878 FILE *f;
879 char filename[FILE_PATH_SIZE] = {0x00};
880 char *fnameptr = filename;
881 size_t fileNlen = 0;
882 bool errors = false;
883 uint16_t dumplen;
884 uint8_t cmdp = 0;
885
886 memset(filename, 0, sizeof(filename));
887
888 while(param_getchar(Cmd, cmdp) != 0x00) {
889 switch(param_getchar(Cmd, cmdp)) {
890 case 'h':
891 case 'H':
892 return usage_legic_dump();
893 case 'o':
894 case 'O':
895 fileNlen = param_getstr(Cmd, cmdp+1, filename);
896 if (!fileNlen)
897 errors = true;
898 if (fileNlen > FILE_PATH_SIZE-5)
899 fileNlen = FILE_PATH_SIZE-5;
900 cmdp += 2;
901 break;
902 default:
903 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
904 errors = true;
905 break;
906 }
907 if(errors) break;
908 }
909
910 //Validations
911 if(errors) return usage_legic_dump();
912
913 // tagtype
914 legic_card_select_t card;
915 if (legic_get_type(&card)) {
916 PrintAndLog("Failed to identify tagtype");
917 return -1;
918 }
919 dumplen = card.cardsize;
920
921 legic_print_type(dumplen, 0);
922 PrintAndLog("Reading tag memory...");
923
924 UsbCommand c = {CMD_READER_LEGIC_RF, {0x00, dumplen, 0x55}};
925 clearCommandBuffer();
926 SendCommand(&c);
927 UsbCommand resp;
928 if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) {
929 PrintAndLog("Command execute time-out");
930 return 1;
931 }
932
933 uint8_t isOK = resp.arg[0] & 0xFF;
934 if ( !isOK ) {
935 PrintAndLog("Failed dumping tag data");
936 return 2;
937 }
938
939 uint16_t readlen = resp.arg[1];
940 uint8_t *data = malloc(readlen);
941 if (!data) {
942 PrintAndLog("Fail, cannot allocate memory");
943 return 3;
944 }
945 memset(data, 0, readlen);
946
947 if ( readlen != dumplen )
948 PrintAndLog("Fail, only managed to read 0x%02X bytes of 0x%02X", readlen, dumplen);
949
950 // copy data from device
951 GetEMLFromBigBuf(data, readlen, 0);
952 if ( !WaitForResponseTimeout(CMD_ACK, NULL, 2500)) {
953 PrintAndLog("Fail, transfer from device time-out");
954 free(data);
955 return 4;
956 }
957
958 // user supplied filename?
959 if (fileNlen < 1)
960 sprintf(fnameptr,"%02X%02X%02X%02X.bin", data[0], data[1], data[2], data[3]);
961 else
962 sprintf(fnameptr + fileNlen,".bin");
963
964 if ((f = fopen(filename,"wb")) == NULL) {
965 PrintAndLog("Could not create file name %s", filename);
966 if (data)
967 free(data);
968 return 5;
969 }
970 fwrite(data, 1, readlen, f);
971 fclose(f);
972 free(data);
973 PrintAndLog("Wrote %d bytes to %s", readlen, filename);
974 return 0;
975 }
976
977 int CmdLegicELoad(const char *Cmd) {
978 FILE * f;
979 char filename[FILE_PATH_SIZE];
980 char *fnameptr = filename;
981 int len, numofbytes;
982 int nameParamNo = 1;
983
984 char cmdp = param_getchar(Cmd, 0);
985 if ( cmdp == 'h' || cmdp == 'H' || cmdp == 0x00)
986 return usage_legic_eload();
987
988 switch (cmdp) {
989 case '0' : numofbytes = 22; break;
990 case '1' :
991 case '\0': numofbytes = 256; break;
992 case '2' : numofbytes = 1024; break;
993 default : numofbytes = 256; nameParamNo = 0;break;
994 }
995
996 // set up buffer
997 uint8_t *data = malloc(numofbytes);
998 if (!data) {
999 PrintAndLog("Fail, cannot allocate memory");
1000 return 3;
1001 }
1002 memset(data, 0, numofbytes);
1003
1004 // set up file
1005 len = param_getstr(Cmd, nameParamNo, filename);
1006 if (len > FILE_PATH_SIZE - 5)
1007 len = FILE_PATH_SIZE - 5;
1008 fnameptr += len;
1009 sprintf(fnameptr, ".bin");
1010
1011 // open file
1012 if ((f = fopen(filename,"rb")) == NULL) {
1013 PrintAndLog("File %s not found or locked", filename);
1014 free(data);
1015 return 1;
1016 }
1017
1018 // load file
1019 size_t bytes_read = fread(data, 1, numofbytes, f);
1020 if ( bytes_read == 0){
1021 PrintAndLog("File reading error");
1022 free(data);
1023 fclose(f);
1024 return 2;
1025 }
1026 fclose(f);
1027
1028 // transfer to device
1029 legic_seteml(data, 0, numofbytes);
1030
1031 free(data);
1032 PrintAndLog("\nLoaded %d bytes from file: %s to emulator memory", numofbytes, filename);
1033 return 0;
1034 }
1035
1036 int CmdLegicESave(const char *Cmd) {
1037 FILE *f;
1038 char filename[FILE_PATH_SIZE];
1039 char *fnameptr = filename;
1040 int fileNlen, numofbytes, nameParamNo = 1;
1041
1042 memset(filename, 0, sizeof(filename));
1043
1044 char cmdp = param_getchar(Cmd, 0);
1045
1046 if ( cmdp == 'h' || cmdp == 'H' || cmdp == 0x00)
1047 return usage_legic_esave();
1048
1049 switch (cmdp) {
1050 case '0' : numofbytes = 22; break;
1051 case '1' :
1052 case '\0': numofbytes = 256; break;
1053 case '2' : numofbytes = 1024; break;
1054 default : numofbytes = 256; nameParamNo = 0; break;
1055 }
1056
1057 fileNlen = param_getstr(Cmd, nameParamNo, filename);
1058
1059 if (fileNlen > FILE_PATH_SIZE - 5)
1060 fileNlen = FILE_PATH_SIZE - 5;
1061
1062 // set up buffer
1063 uint8_t *data = malloc(numofbytes);
1064 if (!data) {
1065 PrintAndLog("Fail, cannot allocate memory");
1066 return 3;
1067 }
1068 memset(data, 0, numofbytes);
1069
1070 // download emulator memory
1071 PrintAndLog("Reading emulator memory...");
1072 GetEMLFromBigBuf(data, numofbytes, 0);
1073 if ( !WaitForResponseTimeout(CMD_ACK, NULL, 2500)) {
1074 PrintAndLog("Fail, transfer from device time-out");
1075 free(data);
1076 return 4;
1077 }
1078
1079 // user supplied filename?
1080 if (fileNlen < 1)
1081 sprintf(fnameptr,"%02X%02X%02X%02X.bin", data[0], data[1], data[2], data[3]);
1082 else
1083 sprintf(fnameptr + fileNlen,".bin");
1084
1085 // open file
1086 if ((f = fopen(filename,"wb")) == NULL) {
1087 PrintAndLog("Could not create file name %s", filename);
1088 free(data);
1089 return 1;
1090 }
1091 fwrite(data, 1, numofbytes, f);
1092 fclose(f);
1093 free(data);
1094 PrintAndLog("\nSaved %d bytes from emulator memory to file: %s", numofbytes, filename);
1095 return 0;
1096 }
1097
1098 static command_t CommandTable[] = {
1099 {"help", CmdHelp, 1, "This help"},
1100 {"reader", CmdLegicReader, 1, "LEGIC Prime Reader UID and Type tag info"},
1101 {"info", CmdLegicInfo, 0, "Display deobfuscated and decoded LEGIC Prime tag data"},
1102 {"dump", CmdLegicDump, 0, "Dump LEGIC Prime card to binary file"},
1103 {"rdmem", CmdLegicRdmem, 0, "[offset][length] <iv> -- read bytes from a LEGIC card"},
1104 {"save", CmdLegicSave, 0, "<filename> [<length>] -- Store samples"},
1105 {"load", CmdLegicLoad, 0, "<filename> -- Restore samples"},
1106 {"sim", CmdLegicRfSim, 0, "[phase drift [frame drift [req/resp drift]]] Start tag simulator (use after load or read)"},
1107 {"write", CmdLegicRfWrite, 0, "<offset> <length> <iv> -- Write sample buffer (user after load or read)"},
1108 {"crc8", CmdLegicCalcCrc8, 1, "Calculate Legic CRC8 over given hexbytes"},
1109 {"eload", CmdLegicELoad, 1, "Load binary dump to emulator memory"},
1110 {"esave", CmdLegicESave, 1, "Save emulator memory to binary file"},
1111 {NULL, NULL, 0, NULL}
1112 };
1113
1114 int CmdHFLegic(const char *Cmd) {
1115 clearCommandBuffer();
1116 CmdsParse(CommandTable, Cmd);
1117 return 0;
1118 }
1119
1120 int CmdHelp(const char *Cmd) {
1121 CmdsHelp(CommandTable);
1122 return 0;
1123 }
Impressum, Datenschutz