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