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 int usage_legic_calccrc8(void){
15 PrintAndLog("Calculates the legic crc8/crc16 on the input hexbytes.");
16 PrintAndLog("There must be an even number of hexsymbols as input.");
17 PrintAndLog("Usage: hf legic crc8 [h] b <hexbytes> u <uidcrc>");
18 PrintAndLog("Options :");
19 PrintAndLog(" b <hexbytes> : hex bytes");
20 PrintAndLog(" u <uidcrc> : MCC hexbyte");
22 PrintAndLog("Samples :");
23 PrintAndLog(" hf legic crc8 b deadbeef1122");
24 PrintAndLog(" hf legic crc8 b deadbeef1122 u 9A");
28 int usage_legic_load(void){
29 PrintAndLog("It loads datasamples from the file `filename` to device memory");
30 PrintAndLog("Usage: hf legic load <file name>");
31 PrintAndLog(" sample: hf legic load filename");
35 int usage_legic_read(void){
36 PrintAndLog("Read data from a legic tag.");
37 PrintAndLog("Usage: hf legic read <offset> <num of bytes>");
38 PrintAndLog("Options :");
39 PrintAndLog(" <offset> : offset in data array to start download from");
40 PrintAndLog(" <num of bytes> : number of bytes to download");
42 PrintAndLog(" sample: hf legic read");
47 * Output BigBuf and deobfuscate LEGIC RF tag data.
48 * This is based on information given in the talk held
49 * by Henryk Ploetz and Karsten Nohl at 26c3
51 int CmdLegicDecode(const char *Cmd
) {
52 // Index for the bytearray.
54 int k
= 0, segmentNum
;
57 uint8_t stamp_len
= 0;
61 uint8_t data_buf
[1052]; // receiver buffer, should be 1024..
66 // download EML memory, where the "legic read" command puts the data.
67 GetEMLFromBigBuf(data_buf
, sizeof(data_buf
), 0);
68 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 2000)){
69 PrintAndLog("Command execute timeout");
73 // Output CDF System area (9 bytes) plus remaining header area (12 bytes)
75 uint32_t calc_crc
= CRC8Legic(data_buf
, 4);
77 PrintAndLog("\nCDF: System Area");
78 PrintAndLog("------------------------------------------------------");
79 PrintAndLog("MCD: %02x, MSN: %02x %02x %02x, MCC: %02x %s",
85 (calc_crc
== crc
) ? "OK":"Fail"
90 dcf
= ((int)data_buf
[6] << 8) | (int)data_buf
[5];
92 // New unwritten media?
95 PrintAndLog("DCF: %d (%02x %02x), Token Type=NM (New Media)",
101 } else if(dcf
> 60000) { // Master token?
105 if(data_buf
[6] == 0xec) {
106 strncpy(token_type
, "XAM", sizeof(token_type
));
108 stamp_len
= 0x0c - (data_buf
[5] >> 4);
110 switch (data_buf
[5] & 0x7f) {
112 strncpy(token_type
, "IAM",sizeof(token_type
));
113 fl
= (0x2f - (data_buf
[5] & 0x7f)) + 1;
116 strncpy(token_type
, "SAM",sizeof(token_type
));
117 fl
= (0x6f - (data_buf
[5] & 0x7f)) + 1;
120 strncpy(token_type
, "GAM",sizeof(token_type
));
121 fl
= (0x7f - (data_buf
[5] & 0x7f)) + 1;
125 stamp_len
= 0xfc - data_buf
[6];
128 PrintAndLog("DCF: %d (%02x %02x), Token Type=%s (OLE=%01u), OL=%02u, FL=%02u",
133 (data_buf
[5]&0x80)>>7,
138 } else { // Is IM(-S) type of card...
140 if(data_buf
[7] == 0x9F && data_buf
[8] == 0xFF) {
142 strncpy(token_type
, "IM-S", sizeof(token_type
));
144 strncpy(token_type
, "IM", sizeof(token_type
));
147 PrintAndLog("DCF: %d (%02x %02x), Token Type=%s (OLE=%01u)",
152 (data_buf
[5]&0x80)>>7
156 // Makes no sence to show this on blank media...
160 PrintAndLog("WRP=%02u, WRC=%01u, RD=%01u, SSC=%02x",
162 (data_buf
[7]&0x70)>>4,
163 (data_buf
[7]&0x80)>>7,
168 // Header area is only available on IM-S cards, on master tokens this data is the master token data itself
169 if(bIsSegmented
|| dcf
> 60000) {
171 PrintAndLog("Master token data");
172 PrintAndLog("%s", sprint_hex(data_buf
+8, 14));
174 PrintAndLog("Remaining Header Area");
175 PrintAndLog("%s", sprint_hex(data_buf
+9, 13));
181 uint8_t segCrcBytes
[8] = {0x00};
182 uint32_t segCalcCRC
= 0;
189 PrintAndLog("\nADF: User Area");
190 PrintAndLog("------------------------------------------------------");
194 // Data start point on segmented cards
198 for (segmentNum
=1; segmentNum
< 128; segmentNum
++ )
200 segment_len
= ((data_buf
[i
+1]^crc
)&0x0f) * 256 + (data_buf
[i
]^crc
);
201 segment_flag
= ((data_buf
[i
+1]^crc
)&0xf0)>>4;
202 wrp
= (data_buf
[i
+2]^crc
);
203 wrc
= ((data_buf
[i
+3]^crc
)&0x70)>>4;
205 bool hasWRC
= (wrc
> 0);
206 bool hasWRP
= (wrp
> wrc
);
207 int wrp_len
= (wrp
- wrc
);
208 int remain_seg_payload_len
= (segment_len
- wrp
- 5);
210 // validate segment-crc
211 segCrcBytes
[0]=data_buf
[0]; //uid0
212 segCrcBytes
[1]=data_buf
[1]; //uid1
213 segCrcBytes
[2]=data_buf
[2]; //uid2
214 segCrcBytes
[3]=data_buf
[3]; //uid3
215 segCrcBytes
[4]=(data_buf
[i
]^crc
); //hdr0
216 segCrcBytes
[5]=(data_buf
[i
+1]^crc
); //hdr1
217 segCrcBytes
[6]=(data_buf
[i
+2]^crc
); //hdr2
218 segCrcBytes
[7]=(data_buf
[i
+3]^crc
); //hdr3
220 segCalcCRC
= CRC8Legic(segCrcBytes
, 8);
221 segCRC
= data_buf
[i
+4]^crc
;
223 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)",
231 (segment_flag
& 0x4) >> 2,
232 (segment_flag
& 0x8) >> 3,
235 ((data_buf
[i
+3]^crc
) & 0x80) >> 7,
237 ( segCRC
== segCalcCRC
) ? "OK" : "fail"
243 PrintAndLog("WRC protected area: (I %d | K %d| WRC %d)", i
, k
, wrc
);
244 PrintAndLog("\nrow | data");
245 PrintAndLog("-----+------------------------------------------------");
247 for ( k
=i
; k
< (i
+wrc
); ++k
)
250 print_hex_break( data_buf
+i
, wrc
, 16);
256 PrintAndLog("Remaining write protected area: (I %d | K %d | WRC %d | WRP %d WRP_LEN %d)",i
, k
, wrc
, wrp
, wrp_len
);
257 PrintAndLog("\nrow | data");
258 PrintAndLog("-----+------------------------------------------------");
260 for (k
=i
; k
< (i
+wrp_len
); ++k
)
263 print_hex_break( data_buf
+i
, wrp_len
, 16);
267 // does this one work? (Answer: Only if KGH/BGH is used with BCD encoded card number! So maybe this will show just garbage...)
269 PrintAndLog("Card ID: %2X%02X%02X", data_buf
[i
-4]^crc
, data_buf
[i
-3]^crc
, data_buf
[i
-2]^crc
);
272 PrintAndLog("Remaining segment payload: (I %d | K %d | Remain LEN %d)", i
, k
, remain_seg_payload_len
);
273 PrintAndLog("\nrow | data");
274 PrintAndLog("-----+------------------------------------------------");
276 for ( k
=i
; k
< (i
+remain_seg_payload_len
); ++k
)
279 print_hex_break( data_buf
+i
, remain_seg_payload_len
, 16);
281 i
+= remain_seg_payload_len
;
283 PrintAndLog("-----+------------------------------------------------\n");
285 // end with last segment
286 if (segment_flag
& 0x8) return 0;
292 // Data start point on unsegmented cards
295 wrp
= data_buf
[7] & 0x0F;
296 wrc
= (data_buf
[7] & 0x07) >> 4;
298 bool hasWRC
= (wrc
> 0);
299 bool hasWRP
= (wrp
> wrc
);
300 int wrp_len
= (wrp
- wrc
);
301 int remain_seg_payload_len
= (1024 - 22 - wrp
); // Any chance to get physical card size here!?
303 PrintAndLog("Unsegmented card - WRP: %02u, WRC: %02u, RD: %01u",
306 (data_buf
[7] & 0x80) >> 7
310 PrintAndLog("WRC protected area: (I %d | WRC %d)", i
, wrc
);
311 PrintAndLog("\nrow | data");
312 PrintAndLog("-----+------------------------------------------------");
313 print_hex_break( data_buf
+i
, wrc
, 16);
318 PrintAndLog("Remaining write protected area: (I %d | WRC %d | WRP %d | WRP_LEN %d)", i
, wrc
, wrp
, wrp_len
);
319 PrintAndLog("\nrow | data");
320 PrintAndLog("-----+------------------------------------------------");
321 print_hex_break( data_buf
+i
, wrp_len
, 16);
324 // does this one work? (Answer: Only if KGH/BGH is used with BCD encoded card number! So maybe this will show just garbage...)
326 PrintAndLog("Card ID: %2X%02X%02X", data_buf
[i
-4], data_buf
[i
-3], data_buf
[i
-2]);
329 PrintAndLog("Remaining segment payload: (I %d | Remain LEN %d)", i
, remain_seg_payload_len
);
330 PrintAndLog("\nrow | data");
331 PrintAndLog("-----+------------------------------------------------");
332 print_hex_break( data_buf
+i
, remain_seg_payload_len
, 16);
333 i
+= remain_seg_payload_len
;
335 PrintAndLog("-----+------------------------------------------------\n");
342 int CmdLegicRFRead(const char *Cmd
) {
347 char cmdp
= param_getchar(Cmd
, 0);
348 if ( cmdp
== 'H' || cmdp
== 'h' ) return usage_legic_read();
350 int byte_count
=0, offset
=0;
351 sscanf(Cmd
, "%i %i", &offset
, &byte_count
);
352 if(byte_count
== 0) byte_count
= -1;
353 if(byte_count
+ offset
> 1024) byte_count
= 1024 - offset
;
355 UsbCommand c
= {CMD_READER_LEGIC_RF
, {offset
, byte_count
, 0}};
356 clearCommandBuffer();
361 int CmdLegicLoad(const char *Cmd
) {
363 char cmdp
= param_getchar(Cmd
, 0);
364 if ( cmdp
== 'H' || cmdp
== 'h' || cmdp
== 0x00) return usage_legic_load();
366 char filename
[FILE_PATH_SIZE
] = {0x00};
367 int len
= strlen(Cmd
);
369 if (len
> FILE_PATH_SIZE
) {
370 PrintAndLog("Filepath too long (was %s bytes), max allowed is %s ", len
, FILE_PATH_SIZE
);
373 memcpy(filename
, Cmd
, len
);
375 FILE *f
= fopen(filename
, "r");
377 PrintAndLog("couldn't open '%s'", Cmd
);
383 uint8_t data
[USB_CMD_DATA_SIZE
] = {0x00};
386 while ( fgets(line
, sizeof(line
), f
) ) {
387 int res
= sscanf(line
, "%x %x %x %x %x %x %x %x",
388 (unsigned int *)&data
[index
],
389 (unsigned int *)&data
[index
+ 1],
390 (unsigned int *)&data
[index
+ 2],
391 (unsigned int *)&data
[index
+ 3],
392 (unsigned int *)&data
[index
+ 4],
393 (unsigned int *)&data
[index
+ 5],
394 (unsigned int *)&data
[index
+ 6],
395 (unsigned int *)&data
[index
+ 7]);
398 PrintAndLog("Error: could not read samples");
404 if ( index
== USB_CMD_DATA_SIZE
){
405 // PrintAndLog("sent %d | %d | %d", index, offset, totalbytes);
406 UsbCommand c
= { CMD_DOWNLOADED_SIM_SAMPLES_125K
, {offset
, 0, 0}};
407 memcpy(c
.d
.asBytes
, data
, sizeof(data
));
408 clearCommandBuffer();
410 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 1500)){
411 PrintAndLog("Command execute timeout");
424 UsbCommand c
= { CMD_DOWNLOADED_SIM_SAMPLES_125K
, {offset
, 0, 0}};
425 memcpy(c
.d
.asBytes
, data
, 8);
426 clearCommandBuffer();
428 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 1500)){
429 PrintAndLog("Command execute timeout");
435 PrintAndLog("loaded %u samples", totalbytes
);
439 int CmdLegicSave(const char *Cmd
) {
440 int requested
= 1024;
443 char filename
[FILE_PATH_SIZE
];
444 uint8_t got
[1024] = {0x00};
446 sscanf(Cmd
, " %s %i %i", filename
, &requested
, &offset
);
448 /* If no length given save entire legic read buffer */
449 /* round up to nearest 8 bytes so the saved data can be used with legicload */
453 if (requested
% 8 != 0) {
454 int remainder
= requested
% 8;
455 requested
= requested
+ 8 - remainder
;
458 if (offset
+ requested
> sizeof(got
)) {
459 PrintAndLog("Tried to read past end of buffer, <bytes> + <offset> > 1024");
463 GetFromBigBuf(got
, requested
, offset
);
464 if ( !WaitForResponseTimeout(CMD_ACK
, NULL
, 2000)){
465 PrintAndLog("Command execute timeout");
469 FILE *f
= fopen(filename
, "w");
471 PrintAndLog("couldn't open '%s'", Cmd
+1);
475 for (int j
= 0; j
< requested
; j
+= 8) {
476 fprintf(f
, "%02x %02x %02x %02x %02x %02x %02x %02x\n",
477 got
[j
+0], got
[j
+1], got
[j
+2], got
[j
+3],
478 got
[j
+4], got
[j
+5], got
[j
+6], got
[j
+7]
481 if (delivered
>= requested
) break;
485 PrintAndLog("saved %u samples", delivered
);
489 //TODO: write a help text (iceman)
490 int CmdLegicRfSim(const char *Cmd
) {
491 UsbCommand c
= {CMD_SIMULATE_TAG_LEGIC_RF
, {6,3,0}};
492 sscanf(Cmd
, " %"lli
" %"lli
" %"lli
, &c
.arg
[0], &c
.arg
[1], &c
.arg
[2]);
493 clearCommandBuffer();
498 //TODO: write a help text (iceman)
499 int CmdLegicRfWrite(const char *Cmd
) {
500 UsbCommand c
= {CMD_WRITER_LEGIC_RF
};
501 int res
= sscanf(Cmd
, " 0x%"llx
" 0x%"llx
, &c
.arg
[0], &c
.arg
[1]);
503 PrintAndLog("Please specify the offset and length as two hex strings");
506 clearCommandBuffer();
511 //TODO: write a help text (iceman)
512 int CmdLegicRfRawWrite(const char *Cmd
) {
514 UsbCommand c
= { CMD_RAW_WRITER_LEGIC_RF
, {0,0,0} };
515 int res
= sscanf(Cmd
, " 0x%"llx
" 0x%"llx
, &c
.arg
[0], &c
.arg
[1]);
517 PrintAndLog("Please specify the offset and value as two hex strings");
521 if (c
.arg
[0] == 0x05 || c
.arg
[0] == 0x06) {
522 PrintAndLog("############# DANGER !! #############");
523 PrintAndLog("# changing the DCF is irreversible #");
524 PrintAndLog("#####################################");
525 PrintAndLog("do youe really want to continue? y(es) n(o)");
526 scanf(" %c", &answer
);
527 if (answer
== 'y' || answer
== 'Y') {
534 clearCommandBuffer();
539 //TODO: write a help text (iceman)
540 int CmdLegicRfFill(const char *Cmd
) {
541 UsbCommand cmd
= {CMD_WRITER_LEGIC_RF
, {0,0,0} };
542 int res
= sscanf(Cmd
, " 0x%"llx
" 0x%"llx
" 0x%"llx
, &cmd
.arg
[0], &cmd
.arg
[1], &cmd
.arg
[2]);
544 PrintAndLog("Please specify the offset, length and value as two hex strings");
549 UsbCommand c
= {CMD_DOWNLOADED_SIM_SAMPLES_125K
, {0, 0, 0}};
550 memcpy(c
.d
.asBytes
, cmd
.arg
[2], 48);
552 for(i
= 0; i
< 22; i
++) {
555 clearCommandBuffer();
557 WaitForResponse(CMD_ACK
, NULL
);
559 clearCommandBuffer();
564 int CmdLegicCalcCrc8(const char *Cmd
){
567 uint8_t cmdp
= 0, uidcrc
= 0, type
=0;
571 while(param_getchar(Cmd
, cmdp
) != 0x00) {
572 switch(param_getchar(Cmd
, cmdp
)) {
576 if ( data
== NULL
) {
577 PrintAndLog("Can't allocate memory. exiting");
581 param_gethex_ex(Cmd
, cmdp
+1, data
, &len
);
582 // if odd symbols, (hexbyte must be two symbols)
583 if ( len
& 1 ) errors
= true;
590 uidcrc
= param_get8ex(Cmd
, cmdp
+1, 0, 16);
595 type
= param_get8ex(Cmd
, cmdp
+1, 0, 10);
603 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd
, cmdp
));
611 if (data
!= NULL
) free(data
);
612 return usage_legic_calccrc8();
617 PrintAndLog("LEGIC CRC16: %X", CRC16Legic(data
, len
, uidcrc
));
620 PrintAndLog("LEGIC CRC8: %X", CRC8Legic(data
, len
) );
628 static command_t CommandTable
[] = {
629 {"help", CmdHelp
, 1, "This help"},
630 {"decode", CmdLegicDecode
, 0, "Display deobfuscated and decoded LEGIC RF tag data (use after hf legic reader)"},
631 {"read", CmdLegicRFRead
, 0, "[offset][length] -- read bytes from a LEGIC card"},
632 {"save", CmdLegicSave
, 0, "<filename> [<length>] -- Store samples"},
633 {"load", CmdLegicLoad
, 0, "<filename> -- Restore samples"},
634 {"sim", CmdLegicRfSim
, 0, "[phase drift [frame drift [req/resp drift]]] Start tag simulator (use after load or read)"},
635 {"write", CmdLegicRfWrite
,0, "<offset> <length> -- Write sample buffer (user after load or read)"},
636 {"writeRaw",CmdLegicRfRawWrite
, 0, "<address> <value> -- Write direct to address"},
637 {"fill", CmdLegicRfFill
, 0, "<offset> <length> <value> -- Fill/Write tag with constant value"},
638 {"crc8", CmdLegicCalcCrc8
, 1, "Calculate Legic CRC8 over given hexbytes"},
639 {NULL
, NULL
, 0, NULL
}
642 int CmdHFLegic(const char *Cmd
) {
643 clearCommandBuffer();
644 CmdsParse(CommandTable
, Cmd
);
648 int CmdHelp(const char *Cmd
) {
649 CmdsHelp(CommandTable
);