1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
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
7 //-----------------------------------------------------------------------------
8 // High frequency Legic commands
9 //-----------------------------------------------------------------------------
10 #include "cmdhflegic.h"
12 static int CmdHelp(const char *Cmd
);
14 #define MAX_LENGTH 1024
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");
26 PrintAndLog("Samples:");
27 PrintAndLog(" hf legic crc8 b deadbeef1122");
28 PrintAndLog(" hf legic crc8 b deadbeef1122 u 9A c 16");
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");
38 PrintAndLog("Samples:");
39 PrintAndLog(" hf legic load filename");
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)");
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");
57 int usage_legic_sim(void){
58 PrintAndLog("Missing help text.");
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)");
70 PrintAndLog("Samples:");
71 PrintAndLog(" hf legic write 10 4 - writes 0x4 to byte[0x10]");
74 int usage_legic_rawwrite(void){
75 PrintAndLog("Write raw data direct to a specific offset on legic tag.");
76 PrintAndLog("Usage: hf legic writeraw [h] <offset> <value> <IV>");
77 PrintAndLog("Options:");
78 PrintAndLog(" h : this help");
79 PrintAndLog(" <offset> : offset to write to (hex)");
80 PrintAndLog(" <value> : value (hex)");
81 PrintAndLog(" <IV> : (optional) Initialization vector to use (hex, odd and 7bits)");
83 PrintAndLog("Samples:");
84 PrintAndLog(" hf legic writeraw 10 4 - writes 0x4 to byte[0x10]");
87 int usage_legic_reader(void){
88 PrintAndLog("Read UID and type information from a legic tag.");
89 PrintAndLog("Usage: hf legic reader [h]");
90 PrintAndLog("Options:");
91 PrintAndLog(" h : this help");
93 PrintAndLog("Samples:");
94 PrintAndLog(" hf legic reader");
97 int usage_legic_info(void){
98 PrintAndLog("Reads information from a legic prime tag.");
99 PrintAndLog("Shows systemarea, user areas etc");
100 PrintAndLog("Usage: hf legic info [h]");
101 PrintAndLog("Options:");
102 PrintAndLog(" h : this help");
104 PrintAndLog("Samples:");
105 PrintAndLog(" hf legic info");
108 int usage_legic_dump(void){
109 PrintAndLog("Reads all pages from LEGIC MIM22, MIM256, MIM1024");
110 PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`");
111 PrintAndLog("It autodetects card type.\n");
112 PrintAndLog("Usage: hf legic dump [h] o <filename w/o .bin>");
113 PrintAndLog("Options:");
114 PrintAndLog(" h : this help");
115 PrintAndLog(" n <FN> : filename w/o .bin to save the dump as");
117 PrintAndLog("Samples:");
118 PrintAndLog(" hf legic dump");
119 PrintAndLog(" hf legic dump o myfile");
123 int usage_legic_eload(void){
124 PrintAndLog("It loads binary dump from the file `filename.bin`");
125 PrintAndLog("Usage: hf legic eload [h] [card memory] <file name w/o `.bin`>");
126 PrintAndLog("Options:");
127 PrintAndLog(" h : this help");
128 PrintAndLog(" [card memory] : 0 = MIM22");
129 PrintAndLog(" : 1 = MIM256 (default)");
130 PrintAndLog(" : 2 = MIM1024");
131 PrintAndLog(" <filename> : filename w/o .bin to load");
133 PrintAndLog("Samples:");
134 PrintAndLog(" hf legic eload filename");
135 PrintAndLog(" hf legic eload 2 filename");
138 int usage_legic_esave(void){
139 PrintAndLog("It saves binary dump into the file `filename.bin` or `cardID.bin`");
140 PrintAndLog(" Usage: hf legic esave [h] [card memory] [file name w/o `.bin`]");
141 PrintAndLog("Options:");
142 PrintAndLog(" h : this help");
143 PrintAndLog(" [card memory] : 0 = MIM22");
144 PrintAndLog(" : 1 = MIM256 (default)");
145 PrintAndLog(" : 2 = MIM1024");
146 PrintAndLog(" <filename> : filename w/o .bin to load");
148 PrintAndLog("Samples:");
149 PrintAndLog(" hf legic esave ");
150 PrintAndLog(" hf legic esave 2");
151 PrintAndLog(" hf legic esave 2 filename");
157 * Output BigBuf and deobfuscate LEGIC RF tag data.
158 * This is based on information given in the talk held
159 * by Henryk Ploetz and Karsten Nohl at 26c3
161 int CmdLegicInfo(const char *Cmd
) {
163 char cmdp
= param_getchar(Cmd
, 0);
164 if ( cmdp
== 'H' || cmdp
== 'h' ) return usage_legic_info();
166 int i
= 0, k
= 0, segmentNum
= 0, segment_len
= 0, segment_flag
= 0;
167 int crc
= 0, wrp
= 0, wrc
= 0;
168 uint8_t stamp_len
= 0;
169 uint8_t data
[1024]; // receiver buffer
170 char token_type
[5] = {0,0,0,0,0};
172 int bIsSegmented
= 0;
174 CmdLegicRdmem("0 22 55");
176 // copy data from device
177 GetEMLFromBigBuf(data
, sizeof(data
), 0);
178 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 2000)){
179 PrintAndLog("Command execute timeout");
183 // Output CDF System area (9 bytes) plus remaining header area (12 bytes)
185 uint32_t calc_crc
= CRC8Legic(data
, 4);
187 PrintAndLog("\nCDF: System Area");
188 PrintAndLog("------------------------------------------------------");
189 PrintAndLog("MCD: %02x, MSN: %02x %02x %02x, MCC: %02x %s",
195 (calc_crc
== crc
) ? "OK":"Fail"
198 // MCD = Manufacturer ID (should be list meaning something?)
201 dcf
= ((int)data
[6] << 8) | (int)data
[5];
203 // New unwritten media?
206 PrintAndLog("DCF: %d (%02x %02x), Token Type=NM (New Media)",
212 } else if(dcf
> 60000) { // Master token?
216 if(data
[6] == 0xec) {
217 strncpy(token_type
, "XAM", sizeof(token_type
));
219 stamp_len
= 0x0c - (data
[5] >> 4);
221 switch (data
[5] & 0x7f) {
223 strncpy(token_type
, "IAM", sizeof(token_type
));
224 fl
= (0x2f - (data
[5] & 0x7f)) + 1;
227 strncpy(token_type
, "SAM", sizeof(token_type
));
228 fl
= (0x6f - (data
[5] & 0x7f)) + 1;
231 strncpy(token_type
, "GAM", sizeof(token_type
));
232 fl
= (0x7f - (data
[5] & 0x7f)) + 1;
236 stamp_len
= 0xfc - data
[6];
239 PrintAndLog("DCF: %d (%02x %02x), Token Type=%s (OLE=%01u), OL=%02u, FL=%02u",
244 (data
[5] & 0x80 )>> 7,
249 } else { // Is IM(-S) type of card...
251 if(data
[7] == 0x9F && data
[8] == 0xFF) {
253 strncpy(token_type
, "IM-S", sizeof(token_type
));
255 strncpy(token_type
, "IM", sizeof(token_type
));
258 PrintAndLog("DCF: %d (%02x %02x), Token Type=%s (OLE=%01u)",
267 // Makes no sence to show this on blank media...
271 PrintAndLog("WRP=%02u, WRC=%01u, RD=%01u, SSC=%02x",
273 (data
[7] & 0x70) >> 4,
274 (data
[7] & 0x80) >> 7,
279 // Header area is only available on IM-S cards, on master tokens this data is the master token data itself
280 if(bIsSegmented
|| dcf
> 60000) {
282 PrintAndLog("Master token data");
283 PrintAndLog("%s", sprint_hex(data
+8, 14));
285 PrintAndLog("Remaining Header Area");
286 PrintAndLog("%s", sprint_hex(data
+9, 13));
291 uint8_t segCrcBytes
[8] = {0,0,0,0,0,0,0,0};
292 uint32_t segCalcCRC
= 0;
298 PrintAndLog("\nADF: User Area");
299 PrintAndLog("------------------------------------------------------");
303 // Data start point on segmented cards
307 for (segmentNum
=1; segmentNum
< 128; segmentNum
++ )
309 segment_len
= ((data
[i
+1] ^ crc
) & 0x0f) * 256 + (data
[i
] ^ crc
);
310 segment_flag
= ((data
[i
+1] ^ crc
) & 0xf0) >> 4;
311 wrp
= (data
[i
+2] ^ crc
);
312 wrc
= ((data
[i
+3] ^ crc
) & 0x70) >> 4;
314 bool hasWRC
= (wrc
> 0);
315 bool hasWRP
= (wrp
> wrc
);
316 int wrp_len
= (wrp
- wrc
);
317 int remain_seg_payload_len
= (segment_len
- wrp
- 5);
319 // validate segment-crc
320 segCrcBytes
[0]=data
[0]; //uid0
321 segCrcBytes
[1]=data
[1]; //uid1
322 segCrcBytes
[2]=data
[2]; //uid2
323 segCrcBytes
[3]=data
[3]; //uid3
324 segCrcBytes
[4]=(data
[i
] ^ crc
); //hdr0
325 segCrcBytes
[5]=(data
[i
+1] ^ crc
); //hdr1
326 segCrcBytes
[6]=(data
[i
+2] ^ crc
); //hdr2
327 segCrcBytes
[7]=(data
[i
+3] ^ crc
); //hdr3
329 segCalcCRC
= CRC8Legic(segCrcBytes
, 8);
330 segCRC
= data
[i
+4] ^ crc
;
332 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)",
340 (segment_flag
& 0x4) >> 2,
341 (segment_flag
& 0x8) >> 3,
344 ((data
[i
+3]^crc
) & 0x80) >> 7,
346 ( segCRC
== segCalcCRC
) ? "OK" : "fail"
352 PrintAndLog("WRC protected area: (I %d | K %d| WRC %d)", i
, k
, wrc
);
353 PrintAndLog("\nrow | data");
354 PrintAndLog("-----+------------------------------------------------");
356 for ( k
=i
; k
< (i
+ wrc
); ++k
)
359 print_hex_break( data
+i
, wrc
, 16);
365 PrintAndLog("Remaining write protected area: (I %d | K %d | WRC %d | WRP %d WRP_LEN %d)",i
, k
, wrc
, wrp
, wrp_len
);
366 PrintAndLog("\nrow | data");
367 PrintAndLog("-----+------------------------------------------------");
369 for (k
=i
; k
< (i
+wrp_len
); ++k
)
372 print_hex_break( data
+i
, wrp_len
, 16);
376 // does this one work? (Answer: Only if KGH/BGH is used with BCD encoded card number! So maybe this will show just garbage...)
378 PrintAndLog("Card ID: %2X%02X%02X", data
[i
-4]^crc
, data
[i
-3]^crc
, data
[i
-2]^crc
);
381 PrintAndLog("Remaining segment payload: (I %d | K %d | Remain LEN %d)", i
, k
, remain_seg_payload_len
);
382 PrintAndLog("\nrow | data");
383 PrintAndLog("-----+------------------------------------------------");
385 for ( k
=i
; k
< (i
+remain_seg_payload_len
); ++k
)
388 print_hex_break( data
+i
, remain_seg_payload_len
, 16);
390 i
+= remain_seg_payload_len
;
392 PrintAndLog("-----+------------------------------------------------\n");
394 // end with last segment
395 if (segment_flag
& 0x8) return 0;
401 // Data start point on unsegmented cards
404 wrp
= data
[7] & 0x0F;
405 wrc
= (data
[7] & 0x70) >> 4;
407 bool hasWRC
= (wrc
> 0);
408 bool hasWRP
= (wrp
> wrc
);
409 int wrp_len
= (wrp
- wrc
);
410 int remain_seg_payload_len
= (1024 - 22 - wrp
); // Any chance to get physical card size here!?
412 PrintAndLog("Unsegmented card - WRP: %02u, WRC: %02u, RD: %01u",
415 (data
[7] & 0x80) >> 7
419 PrintAndLog("WRC protected area: (I %d | WRC %d)", i
, wrc
);
420 PrintAndLog("\nrow | data");
421 PrintAndLog("-----+------------------------------------------------");
422 print_hex_break( data
+i
, wrc
, 16);
427 PrintAndLog("Remaining write protected area: (I %d | WRC %d | WRP %d | WRP_LEN %d)", i
, wrc
, wrp
, wrp_len
);
428 PrintAndLog("\nrow | data");
429 PrintAndLog("-----+------------------------------------------------");
430 print_hex_break( data
+ i
, wrp_len
, 16);
433 // does this one work? (Answer: Only if KGH/BGH is used with BCD encoded card number! So maybe this will show just garbage...)
435 PrintAndLog("Card ID: %2X%02X%02X", data
[i
-4], data
[i
-3], data
[i
-2]);
438 PrintAndLog("Remaining segment payload: (I %d | Remain LEN %d)", i
, remain_seg_payload_len
);
439 PrintAndLog("\nrow | data");
440 PrintAndLog("-----+------------------------------------------------");
441 print_hex_break( data
+ i
, remain_seg_payload_len
, 16);
442 i
+= remain_seg_payload_len
;
444 PrintAndLog("-----+------------------------------------------------\n");
450 int CmdLegicRdmem(const char *Cmd
) {
453 // offset in data memory
454 // number of bytes to read
455 char cmdp
= param_getchar(Cmd
, 0);
456 if ( cmdp
== 'H' || cmdp
== 'h' ) return usage_legic_rdmem();
458 uint32_t offset
= 0, len
= 0, IV
= 1;
459 sscanf(Cmd
, "%x %x %x", &offset
, &len
, &IV
);
461 // OUT-OF-BOUNDS check
462 if ( len
+ offset
> MAX_LENGTH
) {
463 len
= MAX_LENGTH
- offset
;
464 PrintAndLog("Out-of-bound, shorten len to %d (0x%02X)", len
, len
);
469 UsbCommand c
= {CMD_READER_LEGIC_RF
, {offset
, len
, IV
}};
470 clearCommandBuffer();
473 if (WaitForResponseTimeout(CMD_ACK
, &resp
, 3000)) {
474 uint8_t isOK
= resp
.arg
[0] & 0xFF;
475 uint16_t readlen
= resp
.arg
[1];
478 uint8_t *data
= malloc(readlen
);
480 PrintAndLog("Cannot allocate memory");
484 if ( readlen
!= len
)
485 PrintAndLog("Fail, only managed to read 0x%02X bytes", readlen
);
487 // copy data from device
488 GetEMLFromBigBuf(data
, readlen
, 0);
489 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 2500)){
490 PrintAndLog("Command execute timeout");
496 PrintAndLog("\n ## | Data");
497 PrintAndLog("-----+-----");
498 print_hex_break( data
, readlen
, 32);
500 PrintAndLog("failed reading tag");
503 PrintAndLog("command execution time out");
509 // load, filename (ascii hex textfile)
510 // uploads it to device mem
511 int CmdLegicLoad(const char *Cmd
) {
513 // iceman: potential bug, where all filepaths or filename which starts with H or h will print the helptext :)
514 char cmdp
= param_getchar(Cmd
, 0);
515 if ( cmdp
== 'H' || cmdp
== 'h' || cmdp
== 0x00) return usage_legic_load();
517 char filename
[FILE_PATH_SIZE
] = {0x00};
518 int len
= strlen(Cmd
);
520 if (len
> FILE_PATH_SIZE
) {
521 PrintAndLog("Filepath too long (was %s bytes), max allowed is %s ", len
, FILE_PATH_SIZE
);
524 memcpy(filename
, Cmd
, len
);
526 FILE *f
= fopen(filename
, "r");
528 PrintAndLog("couldn't open '%s'", Cmd
);
534 uint8_t data
[USB_CMD_DATA_SIZE
] = {0x00};
537 while ( fgets(line
, sizeof(line
), f
) ) {
538 int res
= sscanf(line
, "%x %x %x %x %x %x %x %x",
539 (unsigned int *)&data
[index
],
540 (unsigned int *)&data
[index
+ 1],
541 (unsigned int *)&data
[index
+ 2],
542 (unsigned int *)&data
[index
+ 3],
543 (unsigned int *)&data
[index
+ 4],
544 (unsigned int *)&data
[index
+ 5],
545 (unsigned int *)&data
[index
+ 6],
546 (unsigned int *)&data
[index
+ 7]);
549 PrintAndLog("Error: could not read samples");
555 if ( index
== USB_CMD_DATA_SIZE
){
556 // PrintAndLog("sent %d | %d | %d", index, offset, totalbytes);
557 UsbCommand c
= { CMD_DOWNLOADED_SIM_SAMPLES_125K
, {offset
, 0, 0}};
558 memcpy(c
.d
.asBytes
, data
, sizeof(data
));
559 clearCommandBuffer();
561 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 1500)){
562 PrintAndLog("Command execute timeout");
575 UsbCommand c
= { CMD_DOWNLOADED_SIM_SAMPLES_125K
, {offset
, 0, 0}};
576 memcpy(c
.d
.asBytes
, data
, 8);
577 clearCommandBuffer();
579 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 1500)){
580 PrintAndLog("Command execute timeout");
586 PrintAndLog("loaded %u samples", totalbytes
);
590 // Save, filename, num of bytes, starting offset. (in decimal)
591 // ie: "hf legic save nnn.txt 100 0 (saves the first 100bytes)
592 // (ascii hex textfile)
593 int CmdLegicSave(const char *Cmd
) {
594 int requested
= 1024;
597 char filename
[FILE_PATH_SIZE
] = {0x00};
598 uint8_t got
[1024] = {0x00};
600 memset(filename
, 0, FILE_PATH_SIZE
);
602 sscanf(Cmd
, " %s %i %i", filename
, &requested
, &offset
);
604 /* If no length given save entire legic read buffer */
605 /* round up to nearest 8 bytes so the saved data can be used with legicload */
609 if (requested
% 8 != 0) {
610 int remainder
= requested
% 8;
611 requested
= requested
+ 8 - remainder
;
614 if (offset
+ requested
> sizeof(got
)) {
615 PrintAndLog("Tried to read past end of buffer, <bytes> + <offset> > 1024");
619 GetFromBigBuf(got
, requested
, offset
);
620 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 2000)){
621 PrintAndLog("Command execute timeout");
625 FILE *f
= fopen(filename
, "w");
627 PrintAndLog("couldn't open '%s'", Cmd
+1);
631 for (int j
= 0; j
< requested
; j
+= 8) {
632 fprintf(f
, "%02x %02x %02x %02x %02x %02x %02x %02x\n",
633 got
[j
+0], got
[j
+1], got
[j
+2], got
[j
+3],
634 got
[j
+4], got
[j
+5], got
[j
+6], got
[j
+7]
637 if (delivered
>= requested
) break;
641 PrintAndLog("saved %u samples", delivered
);
645 //TODO: write a help text (iceman)
646 // should say which tagtype
647 // should load a tag to device mem.
648 int CmdLegicRfSim(const char *Cmd
) {
649 UsbCommand c
= {CMD_SIMULATE_TAG_LEGIC_RF
, {6,3,0}};
650 sscanf(Cmd
, " %"lli
" %"lli
" %"lli
, &c
.arg
[0], &c
.arg
[1], &c
.arg
[2]);
651 clearCommandBuffer();
656 int CmdLegicRfWrite(const char *Cmd
) {
658 // offset - in tag memory
659 // length - num of bytes to be written
661 char cmdp
= param_getchar(Cmd
, 0);
662 if ( cmdp
== 'H' || cmdp
== 'h' ) return usage_legic_write();
664 uint32_t offset
= 0, len
= 0, IV
= 0;
666 int res
= sscanf(Cmd
, "%x %x %x", &offset
, &len
, &IV
);
668 PrintAndLog("Please specify the offset and length as two hex strings and, optionally, the IV also as an hex string");
673 legic_card_select_t card
;
674 if (legic_get_type(&card
)) {
675 PrintAndLog("Failed to identify tagtype");
679 legic_print_type(card
.cardsize
, 0);
681 // OUT-OF-BOUNDS check
682 if ( len
+ offset
> card
.cardsize
) {
683 PrintAndLog("Out-of-bounds, Cardsize = %d, [offset+len = %d ]", card
.cardsize
, len
+ offset
);
689 UsbCommand c
= {CMD_WRITER_LEGIC_RF
, {offset
, len
, IV
}};
690 clearCommandBuffer();
693 if (WaitForResponseTimeout(CMD_ACK
, &resp
, 2000)) {
694 uint8_t isOK
= resp
.arg
[0] & 0xFF;
696 PrintAndLog("failed writing tag");
698 PrintAndLog("command execution time out");
705 int CmdLegicRfRawWrite(const char *Cmd
) {
707 char cmdp
= param_getchar(Cmd
, 0);
708 if ( cmdp
== 'H' || cmdp
== 'h' ) return usage_legic_rawwrite();
710 uint32_t offset
= 0, data
= 0, IV
= 0;
713 int res
= sscanf(Cmd
, "%x %x %x", &offset
, &data
, &IV
);
715 return usage_legic_rawwrite();
717 // OUT-OF-BOUNDS check
718 if ( offset
> MAX_LENGTH
) {
719 PrintAndLog("Out-of-bound, offset");
723 if ( (IV
& 0x7F) != IV
){
725 PrintAndLog("Truncating IV to 7bits");
727 if ( (IV
& 1) == 0 ){
728 IV
|= 0x01; // IV must be odd
729 PrintAndLog("LSB of IV must be SET");
732 UsbCommand c
= { CMD_RAW_WRITER_LEGIC_RF
, {offset
, data
, IV
} };
734 if (c
.arg
[0] == 0x05 || c
.arg
[0] == 0x06) {
735 PrintAndLog("############# DANGER !! #############");
736 PrintAndLog("# changing the DCF is irreversible #");
737 PrintAndLog("#####################################");
738 PrintAndLog("do youe really want to continue? y(es) n(o)");
739 if (scanf(" %c", &answer
) > 0 && (answer
== 'y' || answer
== 'Y')) {
746 clearCommandBuffer();
751 void static calc4(uint8_t *cmd
, uint8_t len
){
753 //crc_init_ref(&crc, 4, 0x19 >> 1, 0x5, 0, TRUE, TRUE);
754 crc_init(&crc
, 4, 0x19 >> 1, 0x5, 0);
757 crc_update(&crc
, 1, 1); /* CMD_READ */
758 crc_update(&crc
, cmd
[0], 8);
759 crc_update(&crc
, cmd
[1], 8);
760 printf("crc4 %X\n", reflect(crc_finish(&crc
), 4) ) ;
763 crc_update(&crc
, 1, 1); /* CMD_READ */
764 crc_update(&crc
, cmd
[0], 8);
765 crc_update(&crc
, cmd
[1], 8);
766 printf("crc4 %X\n", crc_finish(&crc
) ) ;
768 printf("---- old ---\n");
769 crc_update2(&crc
, 1, 1); /* CMD_READ */
770 crc_update2(&crc
, cmd
[0], 8);
771 crc_update2(&crc
, cmd
[1], 8);
772 printf("crc4 %X \n", reflect(crc_finish(&crc
), 4) ) ;
776 crc_update2(&crc
, 1, 1); /* CMD_READ */
777 crc_update2(&crc
, cmd
[0], 8);
778 crc_update2(&crc
, cmd
[1], 8);
779 printf("crc4 %X\n", crc_finish(&crc
) ) ;
782 int CmdLegicCalcCrc8(const char *Cmd
){
784 uint8_t *data
= NULL
;
785 uint8_t cmdp
= 0, uidcrc
= 0, type
=0;
790 while(param_getchar(Cmd
, cmdp
) != 0x00) {
791 switch(param_getchar(Cmd
, cmdp
)) {
794 // peek at length of the input string so we can
795 // figure out how many elements to malloc in "data"
797 if (param_getptr(Cmd
, &bg
, &en
, cmdp
+1)) {
803 // check that user entered even number of characters
804 // for hex data string
810 // it's possible for user to accidentally enter "b" parameter
811 // more than once - we have to clean previous malloc
812 if (data
) free(data
);
813 data
= malloc(len
>> 1);
814 if ( data
== NULL
) {
815 PrintAndLog("Can't allocate memory. exiting");
820 if (param_gethex(Cmd
, cmdp
+1, data
, len
)) {
830 uidcrc
= param_get8ex(Cmd
, cmdp
+1, 0, 16);
835 type
= param_get8ex(Cmd
, cmdp
+1, 0, 10);
843 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd
, cmdp
));
851 if (data
) free(data
);
852 return usage_legic_calccrc8();
857 PrintAndLog("Legic crc16: %X", CRC16Legic(data
, len
, uidcrc
));
863 PrintAndLog("Legic crc8: %X", CRC8Legic(data
, len
) );
867 if (data
) free(data
);
871 int legic_print_type(uint32_t tagtype
, uint8_t spaces
){
874 char *spacer
= spc
+ (10-spaces
);
877 PrintAndLog("%sTYPE : MIM%d card (outdated)", spacer
, tagtype
);
878 else if ( tagtype
== 256 )
879 PrintAndLog("%sTYPE : MIM%d card (234 bytes)", spacer
, tagtype
);
880 else if ( tagtype
== 1024 )
881 PrintAndLog("%sTYPE : MIM%d card (1002 bytes)", spacer
, tagtype
);
883 PrintAndLog("%sTYPE : Unknown %06x", spacer
, tagtype
);
886 int legic_get_type(legic_card_select_t
*card
){
888 if ( card
== NULL
) return 1;
890 UsbCommand c
= {CMD_LEGIC_INFO
, {0,0,0}};
891 clearCommandBuffer();
894 if (!WaitForResponseTimeout(CMD_ACK
, &resp
, 500))
897 uint8_t isOK
= resp
.arg
[0] & 0xFF;
901 memcpy(card
, (legic_card_select_t
*)resp
.d
.asBytes
, sizeof(legic_card_select_t
));
904 void legic_chk_iv(uint32_t *iv
){
905 if ( (*iv
& 0x7F) != *iv
){
907 PrintAndLog("Truncating IV to 7bits, %u", *iv
);
910 if ( (*iv
& 1) == 0 ){
912 PrintAndLog("LSB of IV must be SET %u", *iv
);
916 void legic_seteml(uint8_t *src
, uint32_t offset
, uint32_t numofbytes
) {
919 UsbCommand c
= {CMD_LEGIC_ESET
, {0, 0, 0}};
921 for(size_t i
= 0; i
< numofbytes
; i
+= USB_CMD_DATA_SIZE
) {
923 len
= MIN((numofbytes
- i
), USB_CMD_DATA_SIZE
);
924 c
.arg
[0] = i
; // offset
925 c
.arg
[1] = len
; // number of bytes
926 memcpy(c
.d
.asBytes
, src
, len
);
927 clearCommandBuffer();
929 PrintAndLog("ICE: offset %d | len %d", i
, len
);
933 int HFLegicReader(const char *Cmd
, bool verbose
) {
935 char cmdp
= param_getchar(Cmd
, 0);
936 if ( cmdp
== 'H' || cmdp
== 'h' ) return usage_legic_reader();
938 legic_card_select_t card
;
939 switch(legic_get_type(&card
)){
941 if ( verbose
) PrintAndLog("command execution time out");
945 if ( verbose
) PrintAndLog("legic card select failed");
949 PrintAndLog(" UID : %s", sprint_hex(card
.uid
, sizeof(card
.uid
)));
950 legic_print_type(card
.cardsize
, 0);
953 int CmdLegicReader(const char *Cmd
){
954 return HFLegicReader(Cmd
, TRUE
);
957 int CmdLegicDump(const char *Cmd
){
960 char filename
[FILE_PATH_SIZE
] = {0x00};
961 char *fnameptr
= filename
;
967 memset(filename
, 0, sizeof(filename
));
969 while(param_getchar(Cmd
, cmdp
) != 0x00) {
970 switch(param_getchar(Cmd
, cmdp
)) {
973 return usage_legic_dump();
976 fileNlen
= param_getstr(Cmd
, cmdp
+1, filename
);
979 if (fileNlen
> FILE_PATH_SIZE
-5)
980 fileNlen
= FILE_PATH_SIZE
-5;
984 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd
, cmdp
));
992 if(errors
) return usage_legic_dump();
995 legic_card_select_t card
;
996 if (legic_get_type(&card
)) {
997 PrintAndLog("Failed to identify tagtype");
1000 dumplen
= card
.cardsize
;
1002 legic_print_type(dumplen
, 0);
1003 PrintAndLog("Reading tag memory...");
1005 UsbCommand c
= {CMD_READER_LEGIC_RF
, {0x00, dumplen
, 0x55}};
1006 clearCommandBuffer();
1009 if (!WaitForResponseTimeout(CMD_ACK
, &resp
, 3000)) {
1010 PrintAndLog("Command execute time-out");
1014 uint8_t isOK
= resp
.arg
[0] & 0xFF;
1016 PrintAndLog("Failed dumping tag data");
1020 uint16_t readlen
= resp
.arg
[1];
1021 uint8_t *data
= malloc(readlen
);
1023 PrintAndLog("Fail, cannot allocate memory");
1027 if ( readlen
!= dumplen
)
1028 PrintAndLog("Fail, only managed to read 0x%02X bytes of 0x%02X", readlen
, dumplen
);
1030 // copy data from device
1031 GetEMLFromBigBuf(data
, readlen
, 0);
1032 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 2500)) {
1033 PrintAndLog("Fail, transfer from device time-out");
1038 // user supplied filename?
1040 sprintf(fnameptr
,"%02X%02X%02X%02X.bin", data
[0], data
[1], data
[2], data
[3]);
1042 sprintf(fnameptr
+ fileNlen
,".bin");
1044 if ((f
= fopen(filename
,"wb")) == NULL
) {
1045 PrintAndLog("Could not create file name %s", filename
);
1050 fwrite(data
, 1, readlen
, f
);
1053 PrintAndLog("Wrote %d bytes to %s", readlen
, filename
);
1057 int CmdLegicELoad(const char *Cmd
) {
1059 char filename
[FILE_PATH_SIZE
];
1060 char *fnameptr
= filename
;
1061 int len
, numofbytes
;
1062 int nameParamNo
= 1;
1064 char cmdp
= param_getchar(Cmd
, 0);
1065 if ( cmdp
== 'h' || cmdp
== 'H' || cmdp
== 0x00)
1066 return usage_legic_eload();
1069 case '0' : numofbytes
= 22; break;
1071 case '\0': numofbytes
= 256; break;
1072 case '2' : numofbytes
= 1024; break;
1073 default : numofbytes
= 256; nameParamNo
= 0;break;
1077 uint8_t *data
= malloc(numofbytes
);
1079 PrintAndLog("Fail, cannot allocate memory");
1082 memset(data
, 0, numofbytes
);
1085 len
= param_getstr(Cmd
, nameParamNo
, filename
);
1086 if (len
> FILE_PATH_SIZE
- 5)
1087 len
= FILE_PATH_SIZE
- 5;
1089 sprintf(fnameptr
, ".bin");
1092 if ((f
= fopen(filename
,"rb")) == NULL
) {
1093 PrintAndLog("File %s not found or locked", filename
);
1099 size_t bytes_read
= fread(data
, 1, numofbytes
, f
);
1100 if ( bytes_read
== 0){
1101 PrintAndLog("File reading error");
1108 // transfer to device
1109 legic_seteml(data
, 0, numofbytes
);
1112 PrintAndLog("\nLoaded %d bytes from file: %s to emulator memory", numofbytes
, filename
);
1116 int CmdLegicESave(const char *Cmd
) {
1118 char filename
[FILE_PATH_SIZE
];
1119 char *fnameptr
= filename
;
1120 int fileNlen
, numofbytes
, nameParamNo
= 1;
1122 memset(filename
, 0, sizeof(filename
));
1124 char cmdp
= param_getchar(Cmd
, 0);
1126 if ( cmdp
== 'h' || cmdp
== 'H' || cmdp
== 0x00)
1127 return usage_legic_esave();
1130 case '0' : numofbytes
= 22; break;
1132 case '\0': numofbytes
= 256; break;
1133 case '2' : numofbytes
= 1024; break;
1134 default : numofbytes
= 256; nameParamNo
= 0; break;
1137 fileNlen
= param_getstr(Cmd
, nameParamNo
, filename
);
1139 if (fileNlen
> FILE_PATH_SIZE
- 5)
1140 fileNlen
= FILE_PATH_SIZE
- 5;
1143 uint8_t *data
= malloc(numofbytes
);
1145 PrintAndLog("Fail, cannot allocate memory");
1148 memset(data
, 0, numofbytes
);
1150 // download emulator memory
1151 PrintAndLog("Reading emulator memory...");
1153 GetEMLFromBigBuf(data
, numofbytes
, 0);
1154 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 2500)) {
1155 PrintAndLog("Fail, transfer from device time-out");
1160 // user supplied filename?
1162 sprintf(fnameptr
,"%02X%02X%02X%02X.bin", data
[0], data
[1], data
[2], data
[3]);
1164 sprintf(fnameptr
+ fileNlen
,".bin");
1167 if ((f
= fopen(filename
,"wb")) == NULL
) {
1168 PrintAndLog("Could not create file name %s", filename
);
1172 fwrite(data
, 1, numofbytes
, f
);
1175 PrintAndLog("\nSaved %d bytes from emulator memory to file: %s", numofbytes
, filename
);
1179 static command_t CommandTable
[] = {
1180 {"help", CmdHelp
, 1, "This help"},
1181 {"reader", CmdLegicReader
, 1, "LEGIC Prime Reader UID and Type tag info"},
1182 {"info", CmdLegicInfo
, 0, "Display deobfuscated and decoded LEGIC Prime tag data"},
1183 {"dump", CmdLegicDump
, 0, "Dump LEGIC Prime card to binary file"},
1184 {"rdmem", CmdLegicRdmem
, 0, "[offset][length] <iv> -- read bytes from a LEGIC card"},
1185 {"save", CmdLegicSave
, 0, "<filename> [<length>] -- Store samples"},
1186 {"load", CmdLegicLoad
, 0, "<filename> -- Restore samples"},
1187 {"sim", CmdLegicRfSim
, 0, "[phase drift [frame drift [req/resp drift]]] Start tag simulator (use after load or read)"},
1188 {"write", CmdLegicRfWrite
, 0, "<offset> <length> <iv> -- Write sample buffer (user after load or read)"},
1189 {"crc8", CmdLegicCalcCrc8
, 1, "Calculate Legic CRC8 over given hexbytes"},
1190 {"eload", CmdLegicELoad
, 1, "Load binary dump to emulator memory"},
1191 {"esave", CmdLegicESave
, 1, "Save emulator memory to binary file"},
1192 {NULL
, NULL
, 0, NULL
}
1195 int CmdHFLegic(const char *Cmd
) {
1196 clearCommandBuffer();
1197 CmdsParse(CommandTable
, Cmd
);
1201 int CmdHelp(const char *Cmd
) {
1202 CmdsHelp(CommandTable
);