2 if it don't works with you tag-layout - be so kind and let me know ;-)
4 Tested on Tags with those Layouts:
6 (example) Legic-Prime Layout with 'Kaba Group Header'
7 +----+----+----+----+----+----+----+----+
8 0x00|MCD |MSN0|MSN1|MSN2|MCC | 60 | ea | 9f |
9 +----+----+----+----+----+----+----+----+
10 0x08| ff | 00 | 00 | 00 | 11 |Bck0|Bck1|Bck2|
11 +----+----+----+----+----+----+----+----+
12 0x10|Bck3|Bck4|Bck5|BCC | 00 | 00 |Seg0|Seg1|
13 +----+----+----+----+----+----+----+----+
14 0x18|Seg2|Seg3|SegC|Stp0|Stp1|Stp2|Stp3|UID0|
15 +----+----+----+----+----+----+----+----+
19 MSN = Manufacturer SerialNumber
20 60 ea = DCF Low + DCF high
21 9f = raw byte which holds the bits for OLE,WRP,WRC,RD
22 ff = unknown but important
24 11 = unknown but important
25 Bck = header-backup-area
26 00 00 = Year (00 = 2000) & Week (not important)
28 SegC = Crc8 over the Segment Header
29 Stp = Stamp (could be more as 4 - up to 7)
30 UID = dec User-ID for online-Mapping
31 kghC = crc8 over MCD + MSN0..MSN2 + UID
34 (example) Legic-Cash on MIM256/1024 tag' (37 bytes)
35 +----+----+----+----+----+----+----+----+
36 0x00|Seg0|Seg1|Seg2|Seg3|SegC|STP0|STP1|STP2|
37 +----+----+----+----+----+----+----+----+
38 0x08|STP3|STP4|STP5|STP6| 01 |CURh|CURl|LIMh|
39 +----+----+----+----+----+----+----+----+
40 0x10|LIMm|LIMl|CHKh|CHKl|BALh|BALm|BALl|LRBh|
41 +----+----+----+----+----+----+----+----+
42 0x18|LRBm|LRBl|CHKh|CHKl|SHDh|SHDm|SHDl|LRSh|
43 +----+----+----+----+----+----+----+----+
44 0x20|LRSm|LRSl| CV |CHKh|CHKl|
45 +----+----+----+----+----+
46 STP = Stamp (seems to be always 7 bytes)
47 01 = unknown but important
48 CUR = currency in HEX (ISO 4217)
50 CHK = crc16 over byte-addr 0x05..0x12
52 LRB = ID of the reader that changed the balance
53 CHK = crc16 over BAL + LRB
55 LRS = ID of the reader that changed the shadow balance (?? should be always the same as LRB)
56 CV = Counter value for transactions
57 CHK = crc16 over SHD + LRS + CV
59 (example) Legic-Prime Layout 'gantner unsegmented user-credential'
60 +----+----+----+----+----+----+----+----+
61 0x00|MCD |MSN0|MSN1|MSN2|MCC | 60 | ea | 08 |
62 +----+----+----+----+----+----+----+----+
63 0x08|Stp0|Stp1|Stp2|Stp3|Stp4|Dat0|Dat1|uCRC| <- addr 0x08..0x0f is WRP
64 +----+----+----+----+----+----+----+----+
65 0x10|emb0| <- this is only within wrp if addr 0x07==09
68 MSN = Manufacturer SerialNumber
69 60 ea = DCF Low + DCF high
70 08 = raw byte which holds the bits for OLE,WRP,WRC,RD
71 Stp = Stamp (could be more as 4 - up to 7)
72 Dat = Online-Mapping Data
73 uCRC = crc8 over addr 0x00..0x03+0x07..0x0E
76 (example) Legic-Prime Layout 'gantner unsegmented Master-Token (IAM) with a stamp_len of 4'
77 +----+----+----+----+----+----+----+----+
78 0x00|MCD |MSN0|MSN1|MSN2|MCC | 20 | f8 | 08 |
79 +----+----+----+----+----+----+----+----+
80 0x08|Stp0|Stp1|Stp2|Stp3| 00 | 00 | 00 |CRC1|
81 +----+----+----+----+----+----+----+----+
82 0x10| 00 | 00 | 00 | 00 | 00 |CRC2|
83 +----+----+----+----+----+----+
85 MSN = Manufacturer SerialNumber
86 60 ea = DCF Low + DCF high
87 08 = raw byte which holds the bits for OLE,WRP,WRC,RD
88 Stp = Stamp (could be more as 4 - up to 7)
89 Dat = Online-Mapping Data
90 CRC1 = crc8 over addr 0x00..0x03+0x07..0x0E (special 'gantner crc8')
91 CRC2 = MCD + MSB0..2+ addr 0x06 + addr 0x05 + addr 0x07 + Stamp (regular Master-Token-CRC)
95 Known issues; needs to be fixed:
96 * last byte in last segment is handled incorrectly when it is the last bytes on the card itself (MIM256: => byte 256)
102 local utils
= require('utils')
103 local getopt
= require('getopt')
104 local ansicolors
= require('ansicolors')
107 -- global variables / defines
108 local bxor
= bit32
.bxor
109 local bbit
= bit32
.extract
110 local input
= utils
.input
111 local confirm
= utils
.confirm
114 -- init ansicolor-values & ansicolors switch
115 local colored_output
= true
124 local acy
= ansicolors
.yellow
125 local acc
= ansicolors
.cyan
126 local acr
= ansicolors
.reset
130 -- default colors (change to whatever you want)
131 function load_colors(onoff
)
134 acgreen
= ansicolors
.green
135 accyan
= ansicolors
.cyan
136 acred
= ansicolors
.red
137 acyellow
= ansicolors
.yellow
138 acblue
= ansicolors
.blue
139 acmagenta
= ansicolors
.magenta
140 acoff
= ansicolors
.reset
142 acy
= ansicolors
.yellow
143 acc
= ansicolors
.cyan
144 acr
= ansicolors
.reset
162 example
= "script run hf_legic"
163 author
= "Mosci, uhei"
168 This script helps you to read, create and modify Legic Prime Tags ( MIM22, MIM256, MIM1024 )
169 The virtual tag (and therefore the file to be saved) is always a MIM1024 tag.
170 it's kinda interactive with following commands in three categories:
172 Data I/O Segment Manipulation Token-Data
173 ----------------- -------------------- -----------------
174 ]]..acy
..[[rt]]..acr
..[[ -> read Tag ]]..acy
..[[as]]..acr
..[[ -> add Segment ]]..acy
..[[mt]]..acr
..[[ -> make Token
175 ]]..acy
..[[wt]]..acr
..[[ -> write Tag ]]..acy
..[[es]]..acr
..[[ -> edit Segment Header ]]..acy
..[[et]]..acr
..[[ -> edit Token data
176 ]]..acy
..[[ed]]..acr
..[[ => edit Segment Data ]]..acy
..[[tk]]..acr
..[[ => toggle KGH-Flag
177 File I/O ]]..acy
..[[rs]]..acr
..[[ => remove Segment
178 ----------------- ]]..acy
..[[cc]]..acr
..[[ -> check Segment-CRC
179 ]]..acy
..[[lf]]..acr
..[[ -> load bin File ]]..acy
..[[ck]]..acr
..[[ -> check KGH
180 ]]..acy
..[[sf]]..acr
..[[ -> save eml/bin File ]]..acy
..[[ds]]..acr
..[[ -> dump Segments
181 ]]..acy
..[[xf]]..acr
..[[ -> xor to File
184 (partially) known Segments Virtual Tags Script Output
185 --------------------------- ------------------------------- ------------------------
186 ]]..acy
..[[dlc]]..acr
..[[ -> dump Legic-Cash ]]..acy
..[[ct]]..acr
..[[ -> copy mainTag to backupTag ]]..acy
..[[tac]]..acr
..[[ -> toggle ansicolors
187 ]]..acy
..[[elc]]..acr
..[[ -> edit Legic-Cash ]]..acy
..[[tc]]..acr
..[[ -> copy backupTag to mainTag
188 ]]..acy
..[[d3p]]..acr
..[[ -> dump 3rd-Party-Cash ]]..acy
..[[tt]]..acr
..[[ -> switch mainTag & backupTag
189 ]]..acy
..[[e3p]]..acr
..[[ -> edit 3rd-Party-Cash ]]..acy
..[[di]]..acr
..[[ -> dump mainTag
190 ]]..acy
..[[do]]..acr
..[[ => dump backupTag
192 rt: 'read tag' - reads a tag placed near to the PM3
193 wt: 'write tag' - writes the content of the 'virtual inTag' to a tag placed near to th PM3
194 without the need of changing anything - MCD,MSN,MCC will be read from the tag
195 before and applied to the output.
197 lf: 'load file' - load a (xored) binary file (*.bin) from the local Filesystem into the 'virtual inTag'
198 sf: 'save file' - saves the 'virtual inTag' to the local Filesystem as eml and bin (xored with Tag-MCC)
199 xf: 'xor file' - saves the 'virtual inTag' to the local Filesystem (xored with chosen MCC - use '00' for plain values)
201 ct: 'copy tag' - copy the 'virtual Tag' to a second 'virtual TAG' - not useful yet, but inernally needed
202 tc: 'copy tag' - copy the 'second virtual Tag' to 'virtual TAG' - not useful yet, but inernally needed
203 tt: 'toggle tag' - copy mainTag to BackupTag and backupTag to mainTag
205 di: 'dump mainTag' - shows the current content of the 'virtual Tag'
206 do: 'dump backupTag' - shows the current content of the 'virtual outTag'
207 ds: 'dump Segments' - will show the content of a selected Segment
208 as: 'add Segment' - will add a 'empty' Segment to the inTag
209 es: 'edit Segment' - edit the Segment-Header of a selected Segment (len, WRP, WRC, RD, valid)
210 all other Segment-Header-Values are either calculated or not needed to edit (yet)
211 ed: 'edit data' - edit the Data of a Segment (ADF-Aera / Stamp & Payload specific Data)
212 et: 'edit Token' - edit Data of a Token (CDF-Area / SAM, SAM64, SAM63, IAM, GAM specific Data)
213 mt: 'make Token' - create a Token 'from scratch' (guided)
214 rs: 'remove segment' - removes a Segment (except Segment 00, but this can be set to valid=0 for Master-Token)
215 cc: 'check Segment-CRC' - checks & calculates (if check failed) the Segment-CRC of all Segments
216 ck: 'check KGH-CRC' - checks the and calculates a 'Kaba Group Header' if one was detected
217 'Kaba Group Header CRC calculation'
218 tk: 'toggle KGH' - toggle the (script-internal) flag for kgh-calculation for a segment
219 xc: 'etra c' - show string that was used to calculate the kgh-crc of a segment
221 dlc: 'dump Legic-Cash' - show balance and checksums of a Legic-Cash Segment
222 elc: 'edit Legic-Cash' - edit values of a Legic-Cash Segment
224 d3p: 'dump 3rd Party' - show balance, history and checksums of a (yet) unknown 3rd-Party Cash Segment
225 e3p: 'edit 3rd Party' - edit Data in 3rd-Party Cash Segment
227 tac: 'toggle ansicolors' - switch on and off the colored text-output of this script
228 default can be changed by setting the variable 'colored_output' to false
233 -- curency-codes for Legic-Cash-Segments (ISO 4217)
242 -- This is only meant to be used when errors occur
244 print(acred
.."ERROR: "..acoff
,err
)
251 -- the proxmark3 client can't handle such long strings
252 -- by breaking up at specific points it still looks good.
253 print(string.sub(desc
, 0, 1961))
254 print(string.sub(desc
, 1962, 3925))
255 print(string.sub(desc
, 3926, #desc
))
256 print("Version: "..version
)
257 print("Example usage: "..example
)
261 -- table check helper
263 return type(t
) == 'table'
267 -- To have two char string for a byte
268 local function padString(str
)
276 -- creates a 'deep copy' of a table (a=b only references)
277 function deepCopy(object
)
278 local lookup_table
= {}
279 local function _copy(object
)
280 if type(object
) ~= "table" then
282 elseif lookup_table
[object
] then
283 return lookup_table
[object
]
286 lookup_table
[object
] = new_table
287 for index
, value
in pairs(object
) do
288 new_table
[_copy(index
)] = _copy(value
)
290 return setmetatable(new_table
, getmetatable(object
))
297 function xorme(hex
, xor
, index
)
298 if ( index
>= 23 ) then
299 return ('%02x'):format(bxor( tonumber(hex
,16) , tonumber(xor
,16) ))
306 -- (de)obfuscate bytes
307 function xorBytes(inBytes
, crc
)
309 for index
= 1, #inBytes
do
310 bytes
[index
] = xorme(inBytes
[index
], crc
, index
)
312 if (#inBytes
== #bytes
) then
314 bytes
[5] = string.sub(crc
,-2)
317 print("error: byte-count missmatch")
323 -- split csv-string into table
324 local function split(str
, sep
)
325 local sep
= sep
or ','
327 local matchfunc
= string.gmatch(str
, "([^"..sep
.."]+)")
328 if not matchfunc
then return {str
} end
329 for str
in matchfunc
do
330 table.insert(fields
, str
)
336 -- join table with a separator
337 local function join(list
, sep
)
338 local sep
= sep
or ','
340 if len
== 0 then return "" end
343 s
= s
.. sep
.. list
[i
]
349 -- check availability of file
350 function file_check(file_name
)
351 if not file_name
then return false, "" end
353 local arr
= split(file_name
, ".")
354 local ext
= table.remove(arr
)
355 local name
= join(arr
, '.')
356 local path
= core
.search_file(name
, "."..ext
)
357 if (path
== nil) then return false, "" end
359 local file_found
= io
.open(path
, "r")
360 if file_found
== nil then
369 -- put a string into a bytes-table
370 function str2bytes(s
)
371 if (string.len(s
)%2 ~= 0) then
372 return print("stamp should be a even hexstring e.g.: deadbeef or 0badc0de")
375 for i
=1, string.len(s
), 2 do
376 table.insert(res
, string.sub(s
,i
,(i
+1)))
382 -- put certain bytes into a new table
383 function bytesToTable(bytes
, bstart
, bend
)
385 for i
=0, (bend
-bstart
) do
386 t
[i
]=padString(bytes
[bstart
+i
])
392 -- read file into table
393 function getInputBytes(infile
)
397 local arr
= split(infile
, ".")
398 local ext
= table.remove(arr
)
399 local name
= join(arr
, '.')
400 local path
= core
.search_file(name
, "."..ext
)
401 if (path
== nil) then oops("failed to read from file ".. infile
); return false; end
403 local fhi
,err
= io
.open(path
,"rb")
404 if err
then oops("failed to read from file ".. path
); return false; end
406 file_data
= fhi
:read("*a");
407 for i
= 1, #file_data
do
408 bytes
[i
] = string.format("%x",file_data
:byte(i
))
411 if (bytes
[7]=='00') then return false end
412 print(#bytes
.. " bytes from "..path
.." loaded")
417 -- create tag-table helper
418 function createTagTable()
444 -- put bytes into tag-table
445 function bytesToTag(bytes
, tag)
446 if istable(tag) == false then return oops("tag is no table in: bytesToTag ("..type(tag)..")") end
448 tag.MCD
=padString(bytes
[1]);
449 tag.MSN0
=padString(bytes
[2]);
450 tag.MSN1
=padString(bytes
[3]);
451 tag.MSN2
=padString(bytes
[4]);
452 tag.MCC
=padString(bytes
[5]);
453 tag.DCFl
=padString(bytes
[6]);
454 tag.DCFh
=padString(bytes
[7]);
455 tag.raw
=padString(bytes
[8]);
456 tag.SSC
=padString(bytes
[9]);
457 tag.Type
=getTokenType(tag.DCFl
);
458 tag.OLE
=bbit("0x"..tag.DCFl
,7,1)
459 tag.WRP
=("%d"):format(bbit("0x"..bytes
[8],0,4))
460 tag.WRC
=("%d"):format(bbit("0x"..bytes
[8],4,3))
461 tag.RD
=("%d"):format(bbit("0x"..bytes
[8],7,1))
462 if (tag.Type
=="SAM" and tag.raw
=='9f') then
463 tag.Stamp_len
=(0xfc-bbit("0x"..tag.DCFh
,0,8))
464 elseif (tag.Type
=="SAM" and (tag.raw
=='08' or tag.raw
=='09')) then
465 tag.Stamp_len
= tonumber(tag.raw
,10)
467 tag.data
=bytesToTable(bytes
, 10, 13)
468 tag.Bck
=bytesToTable(bytes
, 14, 20)
469 tag.MTC
=bytesToTable(bytes
, 21, 22)
471 print(acgreen
.."Tag-Type: ".. tag.Type
..acoff
)
472 if (tag.Type
=="SAM" and #bytes
>23) then
473 tag=segmentsToTag(bytes
, tag)
474 print(acgreen
..(#tag.SEG
+1).." Segment(s) found"..acoff
)
475 -- unsegmented Master-Token
479 table.insert(tag.data
, tag.Bck
[i
])
481 tag.data
[#tag.data
]=tag.MTC
[0]
483 --tag.MTC[0]=tag.MTC[1]
486 print(accyan
..#bytes
.." bytes for Tag processed"..acoff
)
492 -- put segments from byte-table to tag-table
493 function segmentsToTag(bytes
, tag)
497 if (istable(tag)) then
500 tag.SEG
[i
]=getSegmentData(bytes
, start
, ("%02d"):format(i
))
501 if (tag.Type
=="SAM") then
502 if (checkKghCrc(tag, i
)) then tag.SEG
[i
].kgh
=true end
504 start
=start
+tag.SEG
[i
].len
505 until ((tag.SEG
[i
].valid
==0) or tag.SEG
[i
].last
==1 or i
==126)
507 else return oops("tag is no table in: segmentsToTag ("..type(tag)..")") end
508 else print("no Segments: must be a MIM22") end
512 -- read Tag-Table in bytes-table
513 function tagToBytes(tag)
514 if istable(tag) == false then return oops("tag is no table in tagToBytes ("..type(tag)..")") end
519 table.insert(bytes
, tag.MCD
)
520 table.insert(bytes
, tag.MSN0
)
521 table.insert(bytes
, tag.MSN1
)
522 table.insert(bytes
, tag.MSN2
)
523 table.insert(bytes
, tag.MCC
)
524 table.insert(bytes
, tag.DCFl
)
525 table.insert(bytes
, tag.DCFh
)
526 table.insert(bytes
, tag.raw
)
527 table.insert(bytes
, tag.SSC
)
529 for i
=0, #tag.data
do
530 table.insert(bytes
, tag.data
[i
])
533 if(istable(tag.Bck
)) then
535 table.insert(bytes
, tag.Bck
[i
])
538 -- token-create-time / master-token crc
540 table.insert(bytes
, tag.MTC
[i
])
543 if (type(tag.SEG
[0])=='table') then
545 for i2
=1, #tag.SEG
[i
].raw
+1 do
546 table.insert(bytes
, #bytes
+1, tag.SEG
[i
].raw
[i2
])
548 table.insert(bytes
, #bytes
+1, tag.SEG
[i
].crc
)
549 for i2
=0, #tag.SEG
[i
].data
-1 do
550 table.insert(bytes
, #bytes
+1, tag.SEG
[i
].data
[i2
])
555 for i
=#bytes
+1, 1024 do
556 table.insert(bytes
, i
, '00')
564 -- write virtual Tag to real Tag
565 function writeToTag(tag)
568 local writeDCF
= false
569 if(utils
.confirm(acred
.."\nPlace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff
) == false) then
572 if(utils
.confirm(acred
.."\nShould the decremental field (DCF) be written?: "..acoff
) == true) then
576 -- get used bytes / tag-len
577 if (istable(tag.SEG
)) then
578 if (istable(tag.Bck
)) then
580 taglen
= taglen
+ tag.SEG
[i
] . len
583 local uid_old
= tag.MCD
..tag.MSN0
..tag.MSN1
..tag.MSN2
585 -- read new tag into memory so we can xor the new data with the new MCC
586 outTAG
= readFromPM3()
587 outbytes
= tagToBytes(outTAG
)
588 -- copy 'inputbuffer' to 'outputbuffer'
589 tag.MCD
= outbytes
[1]
590 tag.MSN0
= outbytes
[2]
591 tag.MSN1
= outbytes
[3]
592 tag.MSN2
= outbytes
[4]
593 tag.MCC
= outbytes
[5]
594 -- recheck all segments-crc/kghcrc (only on a credential)
595 if (istable(tag.Bck
)) then
598 local uid_new
= tag.MCD
..tag.MSN0
..tag.MSN1
..tag.MSN2
600 if (check43rdPartyCash1(uid_old
, tag.SEG
[i
].data
)) then
601 io
.write(accyan
.."\nfixing known checksums"..acoff
.." ... ")
602 if (fix3rdPartyCash1(uid_new
, tag.SEG
[i
].data
)) then
603 io
.write(acgreen
.." done\n"..acoff
)
605 oops("\nsomething went wrong at the repair of the 3rd-party-cash-segment")
610 bytes
= tagToBytes(tag)
612 if (tag.Type
~= "SAM") then
613 bytes
[22] = calcMtCrc(bytes
)
616 bytes
= xorBytes(bytes
,tag.MCC
)
621 -- write data to file
623 WriteBytes
= input(acyellow
.."enter number of bytes to write?"..acoff
, taglen
)
624 -- write pm3-buffer to Tag
625 for i
=1, WriteBytes
do
627 cmd
= ("hf legic wrbl -o %d -d %s "):format(i
-1, padString(bytes
[i
]))
628 print(acgreen
..cmd
..acoff
)
630 core
.clearCommandBuffer()
633 -- write DCF in reverse order (requires 'mosci-patch')
634 cmd
= ('hf legic wrbl -o 5 -d %s%s'):format(padString(bytes
[i
-1]), padString(bytes
[i
]))
635 print(acgreen
..cmd
..acoff
)
637 core
.clearCommandBuffer()
639 print(acgreen
.."skip byte 0x05-0x06 - DCF"..acoff
)
642 print(acgreen
.."skip byte 0x05 - will be written next step"..acoff
)
644 print(acgreen
.."skip byte 0x00-0x04 - unwritable area"..acoff
)
653 -- read file into virtual-tag
654 local function readFile(filename
)
659 local res
, path
= file_check(filename
)
661 return oops("input file: "..acyellow
..filename
..acoff
.." not found")
664 bytes
= getInputBytes(path
)
665 if bytes
== false then return oops('couldnt get input bytes') end
668 bytes
= xorBytes(bytes
,bytes
[5])
669 print("create virtual tag from ".. #bytes
.. " bytes")
670 -- create Tag for plain bytes
671 tag = createTagTable()
672 -- load plain bytes to tag-table
674 tag = bytesToTag(bytes
, tag)
679 local function save_BIN(data
, filename
)
683 local fn
= filename
..ext
685 -- Make sure we don't overwrite a file
686 local res
, path
= file_check(fn
)
687 while res
== false do
688 fn
= filename
..ext
:gsub(ext
, "-"..tostring(counter
)..ext
)
689 counter
= counter
+ 1
690 res
, path
= file_check(fn
)
693 outfile
= io
.open(path
, 'wb')
697 local byte
= string.char(tonumber(data
[i
], 16))
705 -- write bytes to file
706 function writeFile(bytes
, filename
)
707 local emlext
= ".eml"
709 if (filename
~= 'MyLegicClone') then
710 res
, path
= file_check(filename
..emlext
)
712 local answer
= confirm("\nthe output-file "..path
.." already exists!\nthis will delete the previous content!\ncontinue?")
713 if not answer
then return print("user abort") end
718 local fho
, err
= io
.open(path
, "w")
720 return oops("OOps ... failed to open output-file ".. path
)
723 bytes
= xorBytes(bytes
, bytes
[5])
727 line
= padString(bytes
[i
])
728 elseif (bcnt
<= 7) then
729 line
= line
.." "..padString(bytes
[i
])
732 -- write line to new file
733 fho
:write(line
.."\n")
734 -- reset counter & line
742 print("\nwrote "..acyellow
..(#bytes
* 3)..acoff
.." bytes to " ..acyellow
..filename
..emlext
..acoff
)
745 local fn_bin
, fn_bin_num
= save_BIN(bytes
, filename
)
746 if fn_bin
and fn_bin_num
then
747 print("\nwrote "..acyellow
..fn_bin_num
..acoff
.." bytes to BINARY file "..acyellow
..fn_bin
..acoff
)
753 function getRandomTempName()
754 local upperCase
= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
755 local lowerCase
= "abcdefghijklmnopqrstuvwxyz"
757 local characterSet
= upperCase
.. lowerCase
762 for i
= 1, keyLength
do
763 local rand
= math
.random(#characterSet
)
764 output
= output
.. string.sub(characterSet
, rand
, rand
)
767 output
= "hf-legic-temp-" .. output
773 -- read from pm3 into virtual-tag
774 function readFromPM3()
775 local tag, bytes
, infile
776 infile
=getRandomTempName()
777 core
.console("hf legic dump -f "..infile
)
778 tag=readFile(infile
..".bin")
780 res
, path
= file_check(infile
..".bin")
781 if res
then os
.remove(path
) end
784 res
, path
= file_check(infile
..".json")
785 if res
then os
.remove(path
) end
792 local function makeTagMap()
794 if (#tagMap
== 0) then
795 tagMap
['name'] = input(accyan
.."enter Name for this Map: "..acoff
, "newTagMap")
796 tagMap
['mappings'] = {}
798 -- insert fixed Tag-CRC
799 table.insert(tagMap
.crc8
, {name
= 'TAG-CRC', pos
= 5, seq
= {1, 4}})
802 print(accyan
.."new tagMap created"..acoff
)
807 -- save mapping to file
808 local function saveTagMap(map
, filename
)
812 if #filename
> 0 then
813 res
, path
= file_check(filename
)
815 local answer
= confirm("\nthe output-file "..acyellow
..path
..acoff
.." alredy exists!\nthis will delete the previous content!\ncontinue?")
816 if not answer
then return print("user abort") end
821 local fho
,err
= io
.open(path
, "w")
822 if err
then oops("OOps ... failed to open output-file "..acyellow
..path
..acoff
) end
824 -- write line to new file
825 for k
, v
in pairs(map
) do
827 for k2
, v2
in pairs(v
) do
828 if (k
== 'mappings') then
829 fho
:write(k
..","..k2
..","..v2
['name']..","..v2
['start']..","..v2
['end']..","..((v2
['highlight']) and "1" or "0").."\n")
830 elseif (k
== "crc8") then
832 tmp
= k
..","..k2
..","..v2
['name']..","..v2
['pos']..","
833 tmp
=tmp
..tbl2seqstr(v2
['seq'])
838 fho
:write(k
..","..v
.."\n")
847 local function toggleHighlight(tbl
)
848 if (tbl
['highlight']) then
849 tbl
['highlight'] = false
851 tbl
['highlight'] = true
857 -- return table od seqence-string
858 local function seqstr2tbl(seqstr
)
859 local s
= split(seqstr
)
862 for sk
, sv
in pairs(s
) do
865 table.insert(res
, s2
[1])
866 table.insert(res
, s2
[2])
874 -- return sequence-string from table
875 local function tbl2seqstr(seqtbl
)
877 if (istable(seqtbl
)) then
878 for sk
, sv
in pairs(seqtbl
) do
879 res
= res
..sv
..((sk
%2==0) and "," or "-")
881 if (string.sub(res
, string.len(res
))== ",") then
882 res
= string.sub(res
, 1, string.len(res
)-1)
889 -- read map-file into map
890 function loadTagMap(filename
)
891 local map
={mappings
={}, crc8
={}, crc16
={}}
898 local res
, path
= file_check(filename
)
900 return oops("input file: "..acyellow
..filename
..acoff
.." not found")
903 local fhi
,err
= io
.open(path
)
911 if (#fields
== 2) then
912 if (fields
[1] == 'offset') then
913 offset
= tonumber(fields
[2],10)
916 map
[fields
[1]]
=fields
[2]
917 elseif (fields
[1]=='mappings') then
921 temp
['name']=fields
[3]
922 temp
['start']=tonumber(fields
[4], 10)
923 temp
['end']=tonumber(fields
[5], 10)
924 if(temp
['start']>22) then
925 temp
['start']=temp
['start']+offset
926 temp
['end']=temp
['end']+offset
928 if (tonumber(fields
[6], 10)==1) then temp
['highlight']= true
929 else temp
['highlight']= false end
930 table.insert(map
['mappings'], m
, temp
)
931 elseif (fields
[1]=='crc8') then
935 temp
['name']=fields
[3]
936 temp
['pos']=tonumber(fields
[4], 10)+offset
937 local s
=string.sub(line
, string.len(fields
[1]..","..fields
[2]..","..fields
[3]..",")+1, string.len(line
))
938 temp
['seq']=seqstr2tbl(s
)
939 for k
, v
in pairs(temp
['seq']) do
940 if(tonumber(v
, 10)>22) then v
=tonumber(v
, 10)+offset
end
941 temp
['seq'][k
]=tonumber(v
, 10)
943 table.insert(map
.crc8
, temp
)
952 -- dump tagMap (mappings only)
953 function dumpTagMap(tag, tagMap
)
954 if(#tagMap
.mappings
>0) then
955 bytes
=tagToBytes(tag)
958 -- start display mappings
959 for k
, v
in pairs(tagMap
.mappings
) do
960 if ((lastend
+1)<v
['start']) then
963 if (isPosCrc8(tagMap
, v
['start'])>0) then
964 if ( checkMapCrc8(tagMap
, bytes
, isPosCrc8(tagMap
, v
['start']) ) ) then
965 io
.write("("..("%04d"):format(v
['start']).."-"..("%04d"):format(v
['end'])..") "..acgreen
..v
['name']..acoff
)
967 io
.write("("..("%04d"):format(v
['start']).."-"..("%04d"):format(v
['end'])..") "..acred
..v
['name']..acoff
)
970 io
.write("("..("%04d"):format(v
['start']).."-"..("%04d"):format(v
['end'])..") "..((v
['highlight']) and acmagenta
or acyellow
)..v
['name']..acoff
)
974 while (#v
['name'] + temp
:len()) < 20 do temp
= temp
.." " end
976 for i
=v
['start'], v
['end'] do
977 temp
=temp
..bytes
[i
].." "
988 function isPosCrc8(tagMap
, pos
)
990 if (#tagMap
.crc8
>0) then
991 for k
, v
in pairs(tagMap
.crc8
) do
992 if(v
['pos']==pos
) then res
=k
end
1000 function checkMapCrc8(tagMap
, bytes
, n
)
1002 if (#tagMap
.crc8
>0) then
1003 if(istable(tagMap
.crc8
[n
])) then
1005 for k2
, v2
in pairs(tagMap
.crc8
[n
]) do
1006 if (istable(v2
)) then
1007 temp
=temp
..tbl2seqstr(v2
)
1011 local tempres
=getSequences(bytes
, temp
)
1012 tempres
=("%02x"):format(utils
.Crc8Legic(tempres
))
1013 if (bytes
[tagMap
.crc8
[n
]['pos']]
==tempres
) then
1022 -- edit existing Map
1023 function editTagMap(tag, tagMap
)
1025 ]]..acc
..[[Data]]..acr
..[[
1027 ]]..acy
..[[dm]]..acr
..[[ - show ]]..acy
..[[dr]]..acr
..[[ - dump raw
1029 ]]..acc
..[[Mappings]]..acr
..[[
1031 ]]..acy
..[[im]]..acr
..[[ - insert ]]..acy
..[[am]]..acr
..[[ - add
1032 ]]..acy
..[[rm]]..acr
..[[ - remove ]]..acy
..[[mas]]..acr
..[[ - map all segments
1034 ]]..acc
..[[CRC8]]..acr
..[[
1036 ]]..acy
..[[ac8]]..acr
..[[ - add ]]..acy
..[[sc8]]..acr
..[[ - show
1037 ]]..acy
..[[rc8]]..acr
..[[ - remove
1039 ]]..acy
..[[q]]..acr
..[[ - exit ]]..acy
..[[h]]..acr
..[[ - Help
1042 --if(#tagMap.mappings==0) then oops("no mappings in tagMap"); return tagMap end
1043 print("tagMap edit-mode submenu")
1045 x
=input('tagMap submenu:', 'h')
1046 if (x
=='h') then print(t
)
1047 elseif (x
=='dm') then tagMmap
=dumpTagMap(tag, tagMap
)
1048 elseif (x
=='dr') then tagMmap
=dumpMap(tag, tagMap
)
1049 elseif (x
=='rc8') then
1050 if (istable(tagMap
.crc8
)) then
1051 local x1
= selectTableEntry(tagMap
.crc8
, "select number of CRC8 to remove:")
1052 if (istable(tagMap
.crc8
[x1
])) then
1053 table.remove(tagMap
.crc8
, x1
)
1056 elseif (x
=='ac8') then
1057 local p
=tonumber(input("enter byte-addr of crc8", '0'),10)
1059 local i1
=input("enter comma-seperated byte-sequences (e.g.: '1-4,23-26')", '1-4,23-26')
1060 local s1
=split(i1
, ',')
1063 for k
, v
in pairs(s1
) do
1066 table.insert(temp
.seq
, v1
[1])
1067 table.insert(temp
.seq
, v1
[2])
1071 temp
['name']=input("enter a name for the CRC8", "CRC "..(#tagMap
.crc8
+1))
1072 table.insert(tagMap
.crc8
, temp
)
1075 elseif (string.sub(x
, 1, 3)=='sc8') then
1076 local bytes
=tagToBytes(tag)
1078 -- trigger manually by sc8 <'4digit' checkadd> <'seqeuence-string'>
1079 -- e.g.: sc8 0027 1-4,23-36
1080 if (string.len(x
)>=9) then
1081 pos
=tonumber(string.sub(x
, 5, 8), 10)
1082 x
=string.sub(x
, 9, string.len(x
))
1083 print("x: "..x
.." - pos:"..pos
)
1085 x
=selectTableEntry(tagMap
.crc8
, "select CRC:")
1086 if(istable(tagMap
.crc8
[x
])) then
1087 pos
=tagMap
.crc8
[x
]['pos']
1088 x
=tbl2seqstr(tagMap
.crc8
[x
]['seq'])
1091 if (type(x
)=='string') then
1092 res
=("%02x"):format(utils
.Crc8Legic(getSequences(bytes
, x
)))
1093 print(accyan
.."Sequence:\t"..acoff
..x
)
1094 print(accyan
.."Bytes:\t\t"..acoff
..getSequences(bytes
, x
))
1095 print(accyan
.."calculated: "..acoff
..res
..accyan
.." bytes["..pos
.."]: "..acoff
..bytes
[pos
].." ("..compareCrc(utils
.Crc8Legic(getSequences(bytes
, x
)), bytes
[pos
])..")")
1097 elseif (x
=="tm") then
1098 x
=selectTableEntry(tagMap
.mappings
, "select number of Mapping:")
1099 tagMap
.mappings
[x
]=toggleHighlight(tagMap
.mappings
[x
])
1100 elseif (x
=='am') then tagMap
=addMapping(tag, tagMap
)
1101 elseif (x
=='im') then tagMap
=addMapping(tag, tagMap
, selectTableEntry(tagMap
.mappings
, "select List-Position for insert:"))
1102 elseif (x
=='rm') then tagMap
=deleteMapping(tag, tagMap
)
1103 elseif (x
=='mas') then tagMap
=mapTag(tagMap
); tagMap
=mapAllSegments(tag, tagMap
)
1104 elseif (type(actions
[string.sub(x
, 3)])=='function') then actions
[string.sub(x
, 3)]()
1107 print("exit sub-Menu")
1112 -- dump raw mapped and unmapped
1113 function dumpMap(tag, tagMap
)
1116 local bytes
= tagToBytes(tag)
1117 local stats
= getSegmentStats(bytes
)
1118 dend
=stats
[#stats
]['end']
1119 print(accyan
.."Tag uses "..dend
.." bytes:"..acoff
)
1120 for i
=dstart
, dend
do
1121 if (check4MappedByte(i
, tagMap
) and not check4MapCrc8(i
, tagMap
) and not check4Highlight(i
, tagMap
)) then io
.write(""..acyellow
)
1122 elseif (check4MapCrc8(i
, tagMap
)) then
1123 if ( checkMapCrc8(tagMap
, bytes
, isPosCrc8(tagMap
, i
) ) ) then
1124 io
.write(""..acgreen
)
1131 -- highlighted mapping
1132 if (check4Highlight(i
, tagMap
)) then io
.write(""..acmagenta
) end
1135 if (i
%8==0) then io
.write("\n")
1136 else io
.write(" ") end
1139 io
.write("\n"..acoff
)
1143 -- show bytes used for crc-calculation
1144 function getSequences(bytes
, seqstr
)
1145 if (type(seqstr
) ~= "string") then seqstr
= input("enter comma-seperated sequences (e.g.: '1-4,23-26')", '1-4,23-26') end
1146 local seqs
= split(seqstr
, ',')
1149 for k
, v
in pairs(seqs
) do
1150 local seq
= split(v
,'-')
1152 for i
= seq
[1], seq
[2] do
1153 res
= res
..bytes
[i
].." "
1156 if(string.len(res
)>0) then res
= res
.." " end
1159 oops("no sequence found in '"..seqstr
.."'")
1165 -- check if byte-addr is a know crc
1166 function check4MapCrc8(addr
, tagMap
)
1168 for i
=1, #tagMap
.crc8
do
1169 if (addr
== tagMap
.crc8
[i
]['pos']) then
1177 -- check if byte-addr is a know crc
1178 function check4MapCrc16(addr
, tagMap
)
1180 for i
=1, #tagMap
.crc16
do
1181 if (addr
== tagMap
.crc16
[i
]['pos']) then
1189 -- check if byte is mapped or not
1190 function check4MappedByte(addr
, tagMap
)
1192 for _
, v
in pairs(tagMap
.mappings
) do
1193 if (addr
>= v
['start'] and addr
<= v
['end'] ) then
1201 -- check if byte is highlighted or not
1202 function check4Highlight(addr
, tagMap
)
1204 for _
, v
in pairs(tagMap
.mappings
) do
1205 if (addr
>= v
['start'] and addr
<= v
['end'] ) then
1206 res
= v
['highlight']
1213 -- add interactive mapping
1214 function addMapping(tag, tagMap
, x
)
1215 if (type(x
) ~= "number") then x
= #tagMap
.mappings
+ 1 end
1216 local bytes
= tagToBytes(tag)
1217 local myMapping
= {}
1218 myMapping
['name'] = input(accyan
.."enter Maping-Name:"..acoff
, string.format("mapping %d", #tagMap
.mappings
+1))
1219 myMapping
['start'] = tonumber(input(accyan
.."enter start-addr:"..acoff
, '1'), 10)
1220 myMapping
['end'] = tonumber(input(accyan
.."enter end-addr:"..acoff
, #bytes
), 10)
1221 myMapping
['highlight'] = confirm("set highlighted")
1222 table.insert(tagMap
.mappings
, x
, myMapping
)
1228 function deleteMapping(tag, tagMap
)
1229 if(#tagMap
.mappings
>0) then
1230 local d
= selectTableEntry(tagMap
.mappings
, "select number of Mapping to remove:")
1231 if (type(d
)=='number') then
1232 table.remove(tagMap
.mappings
, d
)
1233 else oops("deleteMapping: got type = "..type(d
).." - expected type = 'number'")
1240 -- select a mapping from a tagmap
1241 function selectTableEntry(table, action
)
1242 if (type(action
) ~= "string") then action
= "select number of item:" end
1243 for k
, v
in pairs(table) do
1244 print(accyan
..k
..acoff
.."\t-> "..accyan
..v
['name']..acoff
)
1246 local res
= tonumber(input(action
, 0), 10)
1247 if (istable(table[res
])) then
1256 function mapAllSegments(tag, tagMap
)
1257 local bytes
=tagToBytes(tag)
1259 segs
=getSegmentStats(bytes
)
1260 if (istable(segs
)) then
1261 for k
, v
in pairs(segs
) do
1262 -- wrp (write proteted) = byte 2
1263 WRP
= tonumber(bytes
[v
['start']+2],16)
1264 -- wrc (write control) - bit 4-6 of byte 3
1265 WRC
= tonumber(bbit("0x"..bytes
[v
['start']+3],4,3),16)
1266 --tagMap=mapTokenData(tagMap, 'Segment '..("%02d"):format(v['index']).." HDR", v['start'], v['start']+3)
1267 tagMap
=mapTokenData(tagMap
, 'Segment '..("%02d"):format(v
['index']).." CRC", v
['start']+4, v
['start']+4, true)
1268 table.insert(tagMap
.crc8
, {name
= 'Segment '..("%02d"):format(v
['index']).." CRC", pos
=v
['start']+4, seq
={1,4,v
['start'],v
['start']+3}} )
1271 tagMap
=mapTokenData(tagMap
, 'Segment '..("%02d"):format(v
['index']).." WRC", v
['start']+5, v
['start']+5+WRC
-1, true)
1272 elseif (WRP
>WRC
and WRC
>0) then
1274 tagMap
=mapTokenData(tagMap
, 'Segment '..("%02d"):format(v
['index']).." WRC", v
['start']+5, v
['start']+5+WRC
-1, true)
1275 tagMap
=mapTokenData(tagMap
, 'Segment '..("%02d"):format(v
['index']).." WRP", v
['start']+WRC
+5, v
['start']+5+WRP
-1, true)
1278 tagMap
=mapTokenData(tagMap
, 'Segment '..("%02d"):format(v
['index']).." WRP", v
['start']+5, v
['start']+5+WRP
-1, true)
1280 tagMap
=mapTokenData(tagMap
, 'Segment '..("%02d"):format(v
['index']).." data", v
['start']+5+WRPC
, v
['end'], false)
1283 print(#segs
.." Segments mapped")
1285 oops("autoMapSegments failed: no Segments found")
1291 -- map all token data
1292 function mapTokenData(tagMap
, mname
, mstart
, mend
, mhigh
)
1293 --if ( not mhigh ) then mhigh=false end
1294 local myMapping
= {}
1295 myMapping
['name'] = mname
1296 myMapping
['start'] = mstart
1297 myMapping
['end'] = mend
1298 myMapping
['highlight'] = mhigh
1299 table.insert(tagMap
.mappings
, myMapping
)
1305 function mapTag(tagMap
)
1307 tagMap
=mapTokenData(tagMap
, 'Tag-ID', 1, 4, true)
1308 tagMap
=mapTokenData(tagMap
, 'Tag-CRC', 5, 5, false)
1309 tagMap
=mapTokenData(tagMap
, 'DCF', 6, 7, true)
1310 tagMap
=mapTokenData(tagMap
, 'THDR-Raw/Stamp-Len', 8, 8, true)
1311 tagMap
=mapTokenData(tagMap
, 'SSC', 9, 9, true)
1312 tagMap
=mapTokenData(tagMap
, 'Header', 10, 13, false)
1313 tagMap
=mapTokenData(tagMap
, 'Backup', 14, 19, true)
1314 tagMap
=mapTokenData(tagMap
, 'Bck-CRC', 20, 20, false)
1315 tagMap
=mapTokenData(tagMap
, 'TokenTime', 21, 22, false)
1321 -- dump virtual Tag-Data
1322 function dumpTag(tag)
1328 res
=acyellow
.."\nCDF: System Area"..acoff
1329 res
= res
.."\n"..dumpCDF(tag)
1330 -- segments (user-token area)
1331 if(tag.Type
=="SAM" and tag.raw
=='9f') then
1332 res
= res
..acyellow
.."\n\nADF: User Area"..acoff
1333 for i
=0, #tag.SEG
do
1334 res
=res
.."\n"..dumpSegment(tag, i
).."\n"
1341 -- dump tag-system area
1342 function dumpCDF(tag)
1347 if (istable(tag)) then
1348 res
= res
..accyan
.."MCD: "..acoff
..tag.MCD
..accyan
.." MSN: "..acoff
..tag.MSN0
.." "..tag.MSN1
.." "..tag.MSN2
..accyan
.." MCC: "..acoff
..tag.MCC
.."\n"
1349 res
= res
.."DCF: "..tag.DCFl
.." "..tag.DCFh
..", Token_Type="..tag.Type
.." (OLE="..tag.OLE
.."), Stamp_len="..tag.Stamp_len
.."\n"
1350 res
= res
.."WRP="..tag.WRP
..", WRC="..tag.WRC
..", RD="..tag.RD
..", raw="..tag.raw
..((tag.raw
=='9f') and (", SSC="..tag.SSC
.."\n") or "\n")
1352 -- credential (end-user tag)
1353 if (tag.Type
=="SAM" and tag.raw
=='9f') then
1354 res
= res
.."Remaining Header Area\n"
1355 for i
=0, (#tag.data
) do
1356 res
= res
..tag.data
[i
].." "
1358 res
= res
.."\nBackup Area\n"
1359 for i
=0, (#tag.Bck
) do
1360 res
= res
..tag.Bck
[i
].." "
1362 res
= res
.."\nTime Area\n"
1363 for i
=0, (#tag.MTC
) do
1364 res
= res
..tag.MTC
[i
].." "
1368 -- Master Token specific
1369 elseif (tag.Type
~="SAM") then
1370 res
= res
.."Master-Token Area\nStamp: "
1371 res
= res
..tag.SSC
.." "
1372 for i
=0, tag.Stamp_len
-2 do
1373 res
= res
..tag.data
[i
].." "
1375 res
=res
.."\nunused payload\n"
1376 for i
=0, (#tag.data
-tag.Stamp_len
-1) do
1377 res
= res
..tag.data
[i
].." "
1379 bytes
=tagToBytes(tag)
1380 local mtcrc
=calcMtCrc(bytes
)
1381 res
=res
.."\nMaster-Token CRC: "
1382 res
= res
..tag.MTC
[1].." ("..((tag.MTC
[1]==mtcrc
) and "valid" or "error")..")"
1385 -- 'Gantner User-Credential' specific
1386 elseif (tag.Type
=="SAM" and (tag.raw
=='08' or tag.raw
=='09')) then
1387 print(acgreen
.."Gantner Detected"..acoff
)
1391 else print(acred
.."no valid Tag in dumpCDF"..acoff
) end
1395 -- dump single segment
1396 function dumpSegment(tag, index
)
1399 local dp
=0 --data-position in table
1400 local res
="" --result
1401 local raw
="" --raw-header
1403 if ( (istable(tag.SEG
[i
])) and tag.Type
=="SAM" and tag.raw
=="9f") then
1404 if (istable(tag.SEG
[i
].raw
)) then
1405 for k
,v
in pairs(tag.SEG
[i
].raw
) do
1411 res
= res
..accyan
.."Segment "..("%02d"):format(tag.SEG
[i
].index
)..acoff
..": "
1412 res
= res
.."raw header: "..string.sub(raw
,0,-2)..", flag="..tag.SEG
[i
].flag
..", (valid="..("%x"):format(tag.SEG
[i
].valid
)..", last="..("%x"):format(tag.SEG
[i
].last
).."), "
1413 res
= res
.."len="..("%04d"):format(tag.SEG
[i
].len
)..", WRP="..("%02x"):format(tag.SEG
[i
].WRP
)..", WRC="..("%02x"):format(tag.SEG
[i
].WRC
)..", "
1414 res
= res
.."RD="..("%02x"):format(tag.SEG
[i
].RD
)..", CRC="..tag.SEG
[i
].crc
.." "
1415 res
= res
.."("..(checkSegmentCrc(tag, i
) and acgreen
.."valid" or acred
.."error") ..acoff
..")"
1420 if ((tag.SEG
[i
].WRC
>0)) then
1421 res
= res
.."\nWRC protected area:\n"
1422 for i2
=dp
, dp
+tag.SEG
[i
].WRC
-1 do
1423 res
= res
..tag.SEG
[i
].data
[i2
].." "
1429 if (tag.SEG
[i
].WRP
>tag.SEG
[i
].WRC
) then
1430 res
= res
.."\nRemaining write protected area:\n"
1431 for i2
=dp
, dp
+(tag.SEG
[i
].WRP
-tag.SEG
[i
].WRC
)-1 do
1432 res
= res
..tag.SEG
[i
].data
[i2
].." "
1438 if (#tag.SEG
[i
].data
-dp
>0) then
1439 res
= res
.."\nRemaining segment payload:\n"
1440 for i2
=dp
, #tag.SEG
[i
].data
-2 do
1441 res
= res
..tag.SEG
[i
].data
[dp
].." "
1444 if (tag.SEG
[i
].kgh
) then
1445 res
= res
..tag.SEG
[i
].data
[dp
].." (KGH: "..(checkKghCrc(tag, i
) and acgreen
.."valid" or acred
.."error") ..acoff
..")"
1446 else res
= res
..tag.SEG
[i
].data
[dp
] end
1451 return print(acred
.."Segment not found"..acoff
)
1456 -- return bytes 'sstrat' to 'send' from a table
1457 function dumpTable(tab
, header
, tstart
, tend
)
1459 for i
=tstart
, tend
do
1460 res
=res
..tab
[i
].." "
1462 if (#header
== 0) then
1465 return (header
.." #"..(tend
-tstart
+1).."\n"..res
)
1470 -- dump 3rd Party Cash
1471 function dump3rdPartyCash1(tag , seg
)
1472 local uid
=tag.MCD
..tag.MSN0
..tag.MSN1
..tag.MSN2
1473 local stamp
=tag.SEG
[seg
].data
[0].." "..tag.SEG
[seg
].data
[1].." "..tag.SEG
[seg
].data
[2]
1474 local datastamp
=tag.SEG
[seg
].data
[20].." "..tag.SEG
[seg
].data
[21].." "..tag.SEG
[seg
].data
[22]
1475 local balance
=tonumber(tag.SEG
[seg
].data
[32]..tag.SEG
[seg
].data
[33] ,16)
1476 local balancecrc
=utils
.Crc8Legic(uid
..tag.SEG
[seg
].data
[32]..tag.SEG
[seg
].data
[33])
1477 local mirror
=tonumber(tag.SEG
[seg
].data
[35]..tag.SEG
[seg
].data
[36] ,16)
1478 local mirrorcrc
=utils
.Crc8Legic(uid
..tag.SEG
[seg
].data
[35]..tag.SEG
[seg
].data
[36])
1479 local lastbal0
=tonumber(tag.SEG
[seg
].data
[39]..tag.SEG
[seg
].data
[40] ,16)
1480 local lastbal1
=tonumber(tag.SEG
[seg
].data
[41]..tag.SEG
[seg
].data
[42] ,16)
1481 local lastbal2
=tonumber(tag.SEG
[seg
].data
[43]..tag.SEG
[seg
].data
[44] ,16)
1484 -- display decoded/known stuff
1485 print("\n------------------------------")
1486 print("Tag-ID:\t\t "..uid
)
1487 print("Stamp:\t\t "..stamp
)
1488 print("UID-Mapping: \t\t"..("%06d"):format(tonumber(tag.SEG
[seg
].data
[46]..tag.SEG
[seg
].data
[47]..tag.SEG
[seg
].data
[48], 16)))
1489 print("------------------------------")
1490 print("checksum 1:\t\t "..tag.SEG
[seg
].data
[31].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[seg
].data
, "", 19, 30)), tag.SEG
[seg
].data
[31])..")")
1491 print("checksum 2:\t\t "..tag.SEG
[seg
].data
[34].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[seg
].data
, "", 32, 33)), tag.SEG
[seg
].data
[34])..")")
1492 print("checksum 3:\t\t "..tag.SEG
[seg
].data
[37].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[seg
].data
, "", 35, 36)), tag.SEG
[seg
].data
[37])..")")
1494 print("checksum 4:\t\t "..tag.SEG
[seg
].data
[55].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[seg
].data
, "", 46, 54)), tag.SEG
[seg
].data
[55])..")")
1495 print("checksum 5:\t\t "..tag.SEG
[seg
].data
[62].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[seg
].data
, "", 56, 61)), tag.SEG
[seg
].data
[62])..")")
1496 print("checksum 6:\t\t "..tag.SEG
[seg
].data
[73].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[seg
].data
, "", 63, 72)), tag.SEG
[seg
].data
[73])..")")
1497 print("checksum 7:\t\t "..tag.SEG
[seg
].data
[89].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[seg
].data
, "", 74, 88)), tag.SEG
[seg
].data
[89])..")")
1498 print("------------------------------")
1499 print(string.format("Balance:\t\t %3.2f", balance
/100).." ".."("..compareCrc(balancecrc
, tag.SEG
[seg
].data
[34])..")")
1500 print(string.format("Shadow:\t\t\t %3.2f", mirror
/100).." ".."("..compareCrc(balancecrc
, tag.SEG
[seg
].data
[37])..")")
1501 print("------------------------------")
1502 print(string.format("History 1:\t\t %3.2f", lastbal0
/100))
1503 print(string.format("History 2:\t\t %3.2f", lastbal1
/100))
1504 print(string.format("History 3:\t\t %3.2f", lastbal2
/100))
1505 print("------------------------------\n")
1509 -- dump Legic-Cash data
1510 function dumpLegicCash(tag, x
)
1512 if istable(tag.SEG
[x
]) == false then return end
1514 io
.write("in Segment "..tag.SEG
[x
].index
.." :\n")
1515 print("--------------------------------\n\tLegic-Cash Values\n--------------------------------")
1516 local limit
, curr
, balance
, rid
, tcv
1517 -- currency of balance & limit
1518 curr
=string.upper(tag.SEG
[x
].data
[8]..tag.SEG
[x
].data
[9])
1519 if currency
[curr
] ~= nil then
1520 curr
= currency
[curr
]
1523 limit
=string.format("%4.2f", tonumber(tag.SEG
[x
].data
[10]..tag.SEG
[x
].data
[11]..tag.SEG
[x
].data
[12], 16)/100)
1525 balance
=string.format("%4.2f", tonumber(tag.SEG
[x
].data
[15]..tag.SEG
[x
].data
[16]..tag.SEG
[x
].data
[17], 16)/100)
1526 -- reader-id who wrote last transaction
1527 rid
=tonumber(tag.SEG
[x
].data
[18]..tag.SEG
[x
].data
[19]..tag.SEG
[x
].data
[20], 16)
1528 -- transaction counter value
1529 tcv
=tonumber(tag.SEG
[x
].data
[29], 16)
1530 print("Currency:\t\t "..curr
)
1531 print("Limit:\t\t\t "..limit
)
1532 print("Balance:\t\t "..balance
)
1533 print("Transaction Counter:\t "..tcv
)
1534 print("Reader-ID:\t\t "..rid
.."\n--------------------------------\n")
1539 function print3rdPartyCash1(tag, x
)
1541 if istable(tag.SEG
[x
]) == false then return end
1543 local uid
=tag.MCD
..tag.MSN0
..tag.MSN1
..tag.MSN2
1544 print("\n\t\tStamp : "..dumpTable(tag.SEG
[x
].data
, "", 0 , 2))
1545 print("\t\tBlock 0: "..dumpTable(tag.SEG
[x
].data
, "", 3 , 18))
1547 print("\t\tBlock 1: "..dumpTable(tag.SEG
[x
].data
, "", 19, 30))
1548 print("checksum 1: Tag-ID .. Block 1 => LegicCrc8 = "..tag.SEG
[x
].data
[31].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[x
].data
, "", 19, 30)), tag.SEG
[x
].data
[31])..")")
1550 print("\t\tBlock 2: "..dumpTable(tag.SEG
[x
].data
, "", 32, 33))
1551 print("checksum 2: Block 2 => LegicCrc8 = "..tag.SEG
[x
].data
[34].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[x
].data
, "", 32, 33)), tag.SEG
[x
].data
[34])..")")
1553 print("\t\tBlock 3: "..dumpTable(tag.SEG
[x
].data
, "", 35, 36))
1554 print("checksum 3: Block 3 => LegicCrc8 = "..tag.SEG
[x
].data
[37].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[x
].data
, "", 35, 36)), tag.SEG
[x
].data
[37])..")")
1556 print("\t\tyet unknown: "..tag.SEG
[x
].data
[38])
1558 print("\t\tHisatory 1: "..dumpTable(tag.SEG
[x
].data
, "", 39, 40))
1559 print("\t\tHisatory 2: "..dumpTable(tag.SEG
[x
].data
, "", 41, 42))
1560 print("\t\tHisatory 3: "..dumpTable(tag.SEG
[x
].data
, "", 43, 44))
1562 print("\t\tyet unknown: "..tag.SEG
[x
].data
[45])
1564 print("\t\tKGH-UID HEX: "..dumpTable(tag.SEG
[x
].data
, "", 46, 48))
1565 print("\t\tBlock 4: "..dumpTable(tag.SEG
[x
].data
, "", 49, 54))
1566 print("checksum 4: Tag-ID .. KGH-UID .. Block 4 => LegicCrc8 = "..tag.SEG
[x
].data
[55].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[x
].data
, "", 46, 54)), tag.SEG
[x
].data
[55])..")")
1568 print("\t\tBlock 5: "..dumpTable(tag.SEG
[x
].data
, "", 56, 61))
1569 print("checksum 5: Tag-ID .. Block 5 => LegicCrc8 = "..tag.SEG
[x
].data
[62].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[x
].data
, "", 56, 61)), tag.SEG
[x
].data
[62])..")")
1571 print("\t\tBlock 6: "..dumpTable(tag.SEG
[x
].data
, "", 63, 72))
1572 print("checksum 6: Tag-ID .. Block 6 => LegicCrc8 = "..tag.SEG
[x
].data
[73].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[x
].data
, "", 63, 72)), tag.SEG
[x
].data
[73])..")")
1574 print("\t\tBlock 7: "..dumpTable(tag.SEG
[x
].data
, "", 74, 88))
1575 print("checksum 7: Tag-ID .. Block 7 => LegicCrc8 = "..tag.SEG
[x
].data
[89].." ("..compareCrc(utils
.Crc8Legic(uid
..dumpTable(tag.SEG
[x
].data
, "", 74, 88)), tag.SEG
[x
].data
[89])..")")
1577 print("\t\tBlock 8: "..dumpTable(tag.SEG
[x
].data
, "", 90, 94))
1580 --- Token related --
1583 function makeToken()
1585 ['Type'] = {"SAM", "SAM63", "SAM64", "IAM", "GAM"},
1586 ['DCF'] = {"60ea", "31fa", "30fa", "80fa", "f0fa"},
1587 ['WRP'] = {"15", "2", "2", "2", "2"},
1588 ['WRC'] = {"01", "02", "02", "00", "00"},
1589 ['RD'] = {"01", "00", "00", "00", "00"},
1590 ['Stamp'] = {"00", "00", "00", "00", "00"},
1591 ['Segment'] = {"0d", "c0", "04", "00", "be", "01", "02", "03", "04", "01", "02", "03", "04"}
1594 for k
, v
in pairs(mt
.Type
) do
1595 ttype
= ttype
..k
..") "..v
.." "
1597 mtq
= tonumber(input("select number for Token-Type\n"..ttype
, '1'), 10)
1598 if (type(mtq
) ~= "number") then return print("selection invalid!")
1599 elseif (mtq
> #mt
.Type
) then return print("selection invalid!")
1600 else print("Token-Type '"..mt
.Type
[mtq
].."' selected") end
1601 local raw
= calcHeaderRaw(mt
.WRP
[mtq
], mt
.WRC
[mtq
], mt
.RD
[mtq
])
1604 bytes
= {"01", "02", "03", "04", "cb", string.sub(mt
.DCF
[mtq
], 0, 2), string.sub(mt
.DCF
[mtq
], 3), raw
,
1605 "00", "00", "00", "00", "00", "00", "00", "00",
1606 "00", "00", "00", "00", "00", "00"}
1608 for i
= 0, #mt
.Segment
do
1609 table.insert(bytes
, mt
.Segment
[i
])
1614 for i
= #bytes
, 1023 do table.insert(bytes
, "00") end
1616 -- if Master-Token -> calc Master-Token-CRC
1617 if (mtq
>1) then bytes
[22] = calcMtCrc(bytes
) end
1619 local tempTag
= createTagTable()
1620 -- remove segment if MasterToken
1621 if (mtq
>1) then tempTag
.SEG
[0] = nil end
1623 return bytesToTag(bytes
, tempTag
)
1628 function editTag(tag)
1629 -- for simulation it makes sense to edit everything
1630 local edit_sim
= "MCD MSN0 MSN1 MSN2 MCC DCFl DCFh WRP WRC RD"
1631 -- on real tags it makes only sense to edit DCF, WRP, WRC, RD
1632 local edit_real
= "DCFl DCFh WRP WRC RD"
1633 if (confirm(acyellow
.."do you want to edit non-writeable values (e.g. for simulation)?"..acoff
)) then
1635 else edit_tag
= edit_real
end
1637 if(istable(tag)) then
1638 for k
,v
in pairs(tag) do
1639 if(type(v
) ~= "table" and type(v
) ~= "boolean" and string.find(edit_tag
, k
)) then
1640 tag[k
] = input("value for: "..accyan
..k
..acoff
, v
)
1644 if (tag.Type
== "SAM") then ttype
= "Header"; else ttype
= "Stamp"; end
1645 if (confirm(acyellow
.."do you want to edit "..ttype
.." Data?"..acoff
)) then
1646 -- master-token specific
1647 if(istable(tag.Bck
) == false) then
1648 -- stamp-data length=(0xfc-DCFh)
1649 -- on MT: SSC holds the Starting Stamp Character (Stamp0)
1650 tag.SSC
=input(ttype
.."0: ", tag.SSC
)
1651 -- rest of stamp-bytes are in tag.data 0..n
1652 for i
=0, (tonumber(0xfc ,10)-("%d"):format('0x'..tag.DCFh
))-2 do
1653 tag.data
[i
] = input(ttype
.. i
+1 ..": ", tag.data
[i
])
1656 --- on credentials byte7 should always be 9f and byte8 ff
1657 -- on Master-Token not (even on SAM63/64 not)
1658 -- tag.SSC=input(ttype.."0: ", tag.SSC)
1659 for i
=0, #tag.data
do
1660 tag.data
[i
] = input(ttype
.. i
..": ", tag.data
[i
])
1665 bytes
= tagToBytes(tag)
1667 --- check data-consistency (calculate tag.raw)
1668 bytes
[8] = calcHeaderRaw(tag.WRP
, tag.WRC
, tag.RD
)
1670 --- Master-Token specific
1671 -- should be triggered if a SAM was converted to a non-SAM (user-Token to Master-Token)
1672 -- or a Master-Token has being edited (also SAM64 & SAM63 - which are in fact Master-Token)
1673 if(tag.Type
~= "SAM" or bytes
[6]..bytes
[7] ~= "60ea") then
1674 -- calc new Master-Token crc
1675 bytes
[22] = calcMtCrc(bytes
)
1677 -- ensure tag.SSC set to 'ff' on credential-token (SAM)
1679 -- if a Master-Token was converted to a Credential-Token
1680 -- lets unset the Time-Area to 00 00 (will contain Stamp-Data on MT)
1685 tag = bytesToTag(bytes
, tag)
1690 -- calculates header-byte (addr 0x07)
1691 function calcHeaderRaw(wrp
, wrc
, rd
)
1692 wrp
= ("%02x"):format(tonumber(wrp
, 10))
1693 rd
= tonumber(rd
, 16)
1694 local res
= ("%02x"):format(tonumber(wrp
, 16)+tonumber(wrc
.."0", 16)+((rd
>0) and tonumber("8"..(rd
-1), 16) or 0))
1699 -- determine TagType (bits 0..6 of DCFlow)
1700 function getTokenType(DCFl
)
1706 local tt
= bbit("0x"..DCFl
,0,7)
1707 if (tt
>= 0 and tt
<= 47) then tt
= "IAM"
1708 elseif (tt
== 49) then tt
= "SAM63"
1709 elseif (tt
== 48) then tt
= "SAM64"
1710 elseif (tt
>= 50 and tt
<= 111) then tt
= "SAM"
1711 elseif (tt
>= 112 and tt
<= 127) then tt
= "GAM"
1717 -- clear beackup-area of a virtual tag
1718 function clearBackupArea(tag)
1719 for i
=1, #tag.Bck
do
1725 --- Segment related --
1727 -- get segmemnt-data from byte-table
1728 function getSegmentData(bytes
, start
, index
)
1735 ['raw'] = {'00', '00', '00', '00'},
1743 if (bytes
[start
]) then
1746 segment
.index
= index
1747 -- flag = high nibble of byte 1
1748 segment
.flag
= string.sub(bytes
[start
+1],0,1)
1749 -- valid = bit 6 of byte 1
1750 segment
.valid
= bbit("0x"..bytes
[start
+1],6,1)
1751 -- last = bit 7 of byte 1
1752 segment
.last
= bbit("0x"..bytes
[start
+1],7,1)
1753 -- len = (byte 0)+(bit0-3 of byte 1)
1754 segment
.len
= tonumber(bbit("0x"..bytes
[start
+1],0,4)..bytes
[start
],16)
1755 -- raw segment header
1756 segment
.raw
= {bytes
[start
], bytes
[start
+1], bytes
[start
+2], bytes
[start
+3]}
1757 -- wrp (write proteted) = byte 2
1758 segment
.WRP
= tonumber(bytes
[start
+2],16)
1759 -- wrc (write control) - bit 4-6 of byte 3
1760 segment
.WRC
= bbit("0x"..bytes
[start
+3],4,3)
1761 -- rd (read disabled) - bit 7 of byte 3
1762 segment
.RD
= bbit("0x"..bytes
[start
+3],7,1)
1764 segment
.crc
= bytes
[start
+4]
1765 -- segment-data starts at segment.len - segment.header - segment.crc
1766 for i
=0, (segment
.len
-5) do
1767 segment
.data
[i
]=bytes
[start
+5+i
]
1775 -- get index, start-aadr, length and content
1776 function getSegmentStats(bytes
)
1778 local sValid
, sLast
, sLen
, sStart
, x
1783 -- valid = bit 6 of byte 1
1784 sValid
= bbit("0x"..bytes
[sStart
+1],6,1)
1785 -- last = bit 7 of byte 1
1786 sLast
= bbit("0x"..bytes
[sStart
+1],7,1)
1787 -- len = (byte 0)+(bit0-3 of byte 1)
1788 sLen
= tonumber(bbit("0x"..bytes
[sStart
+1],0,4)..bytes
[sStart
],16)
1789 --print("index: "..("%02d"):format(x).." Len: "..sLen.." start:"..sStart.." end: "..(sStart+sLen-1))
1792 s
['end']=sStart
+sLen
-1
1794 if ( (sStart
+sLen
-1)>sStart
) then
1795 table.insert(sStats
, s
)
1799 until (sLast
==1 or sValid
==0 or x
==126)
1800 if (#sStats
>0 ) then return sStats
1801 else return false; end
1805 -- regenerate segment-header (after edit)
1806 function regenSegmentHeader(segment
)
1808 local raw
= segment
.raw
1810 -- len bit0..7 | len=12bit=low nibble of byte1..byte0
1811 raw
[1]=("%02x"):format(bbit("0x"..("%03x"):format(seg
.len
),0,8))
1812 -- high nibble of len bit6=valid , bit7=last of byte 1 | ?what are bit 5+6 for? maybe kgh?
1813 raw
[2]=("%02x"):format(bbit("0x"..("%03x"):format(seg
.len
),8,4)+bbit("0x"..("%02x"):format((seg
.valid
*64)+(seg
.last
*128)),0,8))
1815 raw
[3]=("%02x"):format(bbit("0x"..("%02x"):format(seg
.WRP
),0,8))
1817 raw
[4]=("%02x"):format(tonumber((seg
.WRC
*16)+(seg
.RD
*128),10))
1819 seg
.flag
=string.sub(raw
[2],0,1)
1820 --print(raw[1].." "..raw[2].." "..raw[3].." "..raw[4])
1821 if(#seg
.data
>(seg
.len
-5)) then
1822 print("current payload: ".. #seg
.data
.." - desired payload: ".. seg
.len
-5)
1823 print(acyellow
.."Data-Length has being reduced:"..acgreen
.." auto-removing "..acyellow
.. #seg
.data
-(seg
.len
-5) ..acgreen
.." bytes from Payload!"..acoff
);
1824 for i
=(seg
.len
-5), #seg
.data
-1 do
1825 table.remove(seg
.data
)
1827 elseif (#seg
.data
<(seg
.len
-5)) then
1828 print("current payload: ".. #seg
.data
.." - desired payload: ".. seg
.len
-5)
1829 print(acyellow
.."Data-Length has being extended:"..acgreen
.." auto-adding "..acyellow
..(seg
.len
-5)-#seg
.data
..acgreen
.." bytes to Payload!"..acoff
);
1830 for i
=#seg
.data
, (seg
.len
-5-1) do
1831 table.insert(seg
.data
, '00')
1838 -- edit segment helper
1839 function editSegment(tag, index
)
1841 local edit_possible
="valid len RD WRP WRC Stamp Payload"
1842 if (istable(tag.SEG
[index
])) then
1843 for k
,v
in pairs(tag.SEG
[index
]) do
1844 if(string.find(edit_possible
,k
)) then
1845 tag.SEG
[index
][k
]=tonumber(input(accyan
..k
..acoff
..": ", v
),10)
1848 else print("Segment with Index: "..("%02d"):format(index
).." not found in Tag")
1851 regenSegmentHeader(tag.SEG
[index
])
1852 print("\n"..dumpSegment(tag, index
).."\n")
1857 -- edit Segment Data
1858 function editSegmentData(data
, uid
)
1860 if istable(data
) == false then print("no Segment-Data found") end
1862 local lc
= check4LegicCash(data
, uid
)
1865 data
[i
]=input(accyan
.."Data"..i
..acoff
..": ", data
[i
])
1868 data
= fixLegicCash(data
, uid
)
1874 -- list available segmets in virtual tag
1875 function segmentList(tag)
1878 if (istable(tag.SEG
[0])) then
1879 for i
=0, #tag.SEG
do
1880 res
= res
.. tag.SEG
[i
].index
.. " "
1883 else print("no Segments found in Tag")
1889 -- helper to selecting a segment
1890 function selectSegment(tag)
1892 if (istable(tag.SEG
[0])) then
1893 print("availabe Segments:\n"..segmentList(tag))
1894 sel
=input("select Segment: ", '00')
1895 sel
=tonumber(sel
,10)
1896 if (sel
) then return sel
1899 print("\nno Segments found")
1906 function addSegment(tag)
1914 ['raw'] = {'0d', '40', '04', '00'},
1922 if (istable(tag.SEG
[0])) then
1923 tag.SEG
[#tag.SEG
].last
=0
1924 table.insert(tag.SEG
, segment
)
1926 tag.SEG
[#tag.SEG
].data
[i
]=("%02x"):format(i
)
1928 tag.SEG
[#tag.SEG
].index
=("%02d"):format(#tag.SEG
)
1931 print("no Segment-Table found")
1936 -- get only the stamp-bytes of a segment
1937 function getSegmentStamp(seg
, bytes
)
1940 --- the 'real' stamp on MIM is not really easy to tell for me since the 'data-block' covers stamp0..stampn+data0..datan
1941 -- there a no stamps longer than 7 bytes & they are write-protected by default , and I have not seen user-credntials
1942 -- with stamps smaller 3 bytes (except: Master-Token)
1943 -- WRP -> Read/Write Protection
1944 -- WRC -> Read/Write Condition
1945 -- RD depends on WRC - if WRC > 0 and RD=1: only reader with matching #WRC of Stamp-bytes in their Database have Read-Access to the Tag
1946 if (seg
.WRP
<7) then stamp_len
=(seg
.WRP
) end
1947 for i
=1, (stamp_len
) do
1948 stamp
=stamp
..seg
.data
[i
-1]
1951 stamp
=str2bytes(stamp
)
1953 else return stamp
end
1957 -- edit stamp of a segment
1958 function editStamp(new_stamp
, uid
, data
)
1959 local stamp
=str2bytes(new_stamp
)
1960 for i
=0, #stamp
-1 do
1963 -- now fill in stamp
1964 for i
=0, (string.len(new_stamp
)/2)-1 do
1967 return fix3rdPartyCash1(uid
, data
)
1971 -- autoselect special/known segments
1972 function autoSelectSegment(tag, s
)
1973 local uid
=tag.MCD
..tag.MSN0
..tag.MSN1
..tag.MSN2
1976 io
.write("autoSelect ")
1977 --- search for desired segment-type
1978 -- 3rd Party Segment
1979 if (s
=="3rdparty") then
1983 res
=check43rdPartyCash1(uid
, tag.SEG
[x
].data
)
1984 until ( res
or x
==0 )
1986 -- Legic-Cash Segment
1987 if (s
=="legiccash") then
1991 res
=check4LegicCash(tag.SEG
[x
].data
, uid
)
1992 until ( res
or x
==0 )
1997 io
.write("\nautoselected Index: "..string.format("%02d", x
).."\n")
2002 io
.write(acyellow
.."no Segment found\n"..acoff
)
2007 -- delete segment (except segment 00)
2008 function delSegment(tag, index
)
2009 if (istable(tag.SEG
[0])) then
2011 if (type(index
)=="string") then index
=tonumber(index
,10) end
2013 table.remove(tag.SEG
, index
)
2014 for i
=0, #tag.SEG
do
2015 tag.SEG
[i
].index
=("%02d"):format(i
)
2018 if(istable(tag.SEG
[#tag.SEG
])) then tag.SEG
[#tag.SEG
].last
=1 end
2024 -- edit uid 3rd party cash
2025 function edit3rdUid(mapid
, uid
, data
)
2026 mapid
=("%06x"):format(tonumber(mapid
, 10))
2027 data
[46]=string.sub(mapid
, 1 ,2)
2028 data
[47]=string.sub(mapid
, 3 ,4)
2029 data
[48]=string.sub(mapid
, 5 ,6)
2030 return fix3rdPartyCash1(uid
, data
)
2034 -- edit balance 3rd party cash
2035 function edit3rdCash(new_cash
, uid
, data
)
2036 new_cash
=("%04x"):format(new_cash
)
2037 data
[32]=string.sub(new_cash
, 0,2)
2038 data
[33]=string.sub(new_cash
, 3,4)
2039 data
[34]=("%02x"):format(utils
.Crc8Legic(uid
..new_cash
))
2040 data
[35]=string.sub(new_cash
, 0,2)
2041 data
[36]=string.sub(new_cash
, 3,4)
2042 data
[37]=("%02x"):format(utils
.Crc8Legic(uid
..new_cash
))
2043 data
[39]=string.sub(new_cash
, 0,2)
2044 data
[40]=string.sub(new_cash
, 3,4)
2049 return fix3rdPartyCash1(uid
, data
)
2053 -- edit 3rd-party cash
2054 function edit3rdPartyCash1(tag, x
)
2055 local uid
=tag.MCD
..tag.MSN0
..tag.MSN1
..tag.MSN2
2056 if (confirm("\nedit Balance?")) then
2057 local new_cash
=input("enter new Balance≤\nwithout comma and without currency-sign! (0-65535)", "100")
2058 tag.SEG
[x
].data
=edit3rdCash(new_cash
, uid
, tag.SEG
[x
].data
)
2060 -- change User-ID (used for online-account-mapping)
2061 if (confirm("\nedit UserID-Mapping?")) then
2062 local new_mapid
=input("enter new UserID (6-digit value)", "012345")
2063 tag.SEG
[x
].data
=edit3rdUid(new_mapid
, uid
, tag.SEG
[x
].data
)
2065 if (confirm("\nedit Stamp?")) then
2066 local new_stamp
=input("enter new Stamp", getSegmentStamp(tag.SEG
[x
]))
2067 tag.SEG
[x
].data
=editStamp(new_stamp
, uid
, tag.SEG
[x
].data
)
2068 new_stamp
=getSegmentStamp(tag.SEG
[x
], 'true')
2069 print("stamp_bytes: "..#new_stamp
)
2070 -- replace stamp in 'block 1' also
2071 io
.write("editing stamp in Block 1 also ")
2072 for i
=20, (20+#new_stamp
-1) do
2073 tag.SEG
[x
].data
[i
]=new_stamp
[i
-19]
2077 -- fix known checksums
2078 tag.SEG
[x
].data
=fix3rdPartyCash1(uid
, tag.SEG
[x
].data
)
2085 function editLegicCash(data
, uid
)
2086 local limit
, curr
, balance
, rid
, tcv
2087 -- currency of balance & limit
2088 curr
=currency
[data
[8]..data
[9]]
2090 limit
=string.format("%4.2f", tonumber(data
[10]..data
[11]..data
[12], 16)/100)
2092 balance
=string.format("%4.2f", tonumber(data
[15]..data
[16]..data
[17], 16)/100)
2093 -- reader-id who wrote last transaction
2094 rid
=tonumber(data
[18]..data
[19]..data
[20], 16)
2095 -- transaction counter value
2096 tcv
=tonumber(data
[29], 16)
2099 if (confirm(accyan
.."change Currency?"..acoff
)) then
2100 for k
, v
in pairs(currency
) do io
.write(k
.. " = " .. v
.. "\n") end
2101 curr
=input(accyan
.."enter the 4-digit Hex for the new Currency:"..acoff
, data
[8]..data
[9])
2102 data
[8]=string.sub(curr
, 1, 2)
2103 data
[9]=string.sub(curr
, 3, 4)
2107 if (confirm(accyan
.."change Limit?"..acoff
)) then
2108 limit
=string.format("%06x", input(accyan
.."enter the Decimal for the new Limit:"..acoff
, limit
))
2109 data
[10]=string.sub(limit
, 1, 2)
2110 data
[11]=string.sub(limit
, 3, 4)
2111 data
[12]=string.sub(limit
, 5, 6)
2115 if (confirm(accyan
.."change Balance?"..acoff
)) then
2116 balance
=string.format("%06x", input(accyan
.."enter the Decimal for the new Balance:"..acoff
, balance
))
2117 print("Balance: "..balance
)
2118 data
[15]=string.sub(balance
, 1, 2)
2119 data
[16]=string.sub(balance
, 3, 4)
2120 data
[17]=string.sub(balance
, 5, 6)
2123 -- edit transaction-counter
2124 if (confirm(accyan
.."change Transaction-Counter?"..acoff
)) then
2125 tcv
=string.format("%02x", input(accyan
.."enter the 4-digit Hex for the new Currency:"..acoff
, data
[29]))
2130 if (confirm(accyan
.."change Last-Reader-ID?"..acoff
)) then
2131 rid
=string.format("%06x", input(accyan
.."enter the Decimal for the new Balance:"..acoff
, rid
))
2132 print("Balance: "..balance
)
2133 data
[18]=string.sub(rid
, 1, 2)
2134 data
[19]=string.sub(rid
, 3, 4)
2135 data
[20]=string.sub(rid
, 5, 6)
2138 return fixLegicCash(data
, uid
)
2142 -- chack for signature of a 'Legic-Cash-Segment'
2143 function check4LegicCash(data
, uid
)
2145 local stamp_len
=(#data
-25)
2147 for i
=0, stamp_len
-1 do
2148 stamp
=stamp
..data
[i
].." "
2150 if (data
[7]=="01") then
2151 if (("%04x"):format(utils
.Crc16Legic(dumpTable(data
, "", 0, 12), uid
)) == data
[13]..data
[14]) then
2152 if (("%04x"):format(utils
.Crc16Legic(dumpTable(data
, "", 15, 20), uid
)) == data
[21]..data
[22]) then
2153 if (("%04x"):format(utils
.Crc16Legic(dumpTable(data
, "", 23, 29), uid
)) == data
[30]..data
[31]) then
2154 io
.write(accyan
.."Legic-Cash Segment detected "..acoff
)
2165 -- chack for signature of a '3rd Party Cash-Segment' - not all bytes know until yet !!
2166 function check43rdPartyCash1(uid
, data
)
2168 -- too explicit checking will avoid fixing ;-)
2169 if (string.find(compareCrc(utils
.Crc8Legic(uid
..dumpTable(data
, "", 19, 30)), data
[31]),"valid")) then
2170 --if (compareCrc(utils.Crc8Legic(uid..data[32]..data[33]), data[34])=="valid") then
2171 --if (compareCrc(utils.Crc8Legic(uid..data[35]..data[36]), data[37])=="valid") then
2172 --if (compareCrc(utils.Crc8Legic(uid..dumpTable(data, "", 56, 61)), data[62])=="valid") then
2173 --if (compareCrc(utils.Crc8Legic(uid..dumpTable(data, "", 74, 88)), data[89])=="valid") then
2174 io
.write(accyan
.."3rd Party Cash-Segment detected "..acoff
)
2187 -- build segmentCrc credentials
2188 function segmentCrcCredentials(tag, segid
)
2189 if (istable(tag.SEG
[0])) then
2190 local cred
= tag.MCD
..tag.MSN0
..tag.MSN1
..tag.MSN2
2191 cred
= cred
..tag.SEG
[segid
].raw
[1]..tag.SEG
[segid
].raw
[2]..tag.SEG
[segid
].raw
[3]..tag.SEG
[segid
].raw
[4]
2193 else return print(acyellow
.."Master-Token / unsegmented Tag!"..acoff
) end
2197 -- build kghCrc credentials
2198 function kghCrcCredentials(tag, segid
)
2199 if (istable(tag) and istable(tag.SEG
[0])) then
2201 if (type(segid
)=="string") then segid
=tonumber(segid
,10) end
2202 if (segid
>0) then x
='93' end
2203 local cred
= tag.MCD
..tag.MSN0
..tag.MSN1
..tag.MSN2
..("%02x"):format(tag.SEG
[segid
].WRP
)
2204 cred
= cred
..("%02x"):format(tag.SEG
[segid
].WRC
)..("%02x"):format(tag.SEG
[segid
].RD
)..x
2205 for i
=0, #tag.SEG
[segid
].data
-2 do
2206 cred
= cred
..tag.SEG
[segid
].data
[i
]
2213 -- compare two bytes
2214 function compareCrc(calc
, guess
)
2215 calc
=("%02x"):format(calc
)
2216 if (calc
==guess
) then return acgreen
.."valid"..acoff
2217 else return acred
.."error "..acoff
..calc
.."!="..guess
end
2222 function compareCrc16(calc
, guess
)
2223 calc
=("%04x"):format(calc
)
2224 if (calc
==guess
) then return acgreen
.."valid"..acoff
2225 else return acred
.."error "..acoff
..calc
.."!="..guess
end
2229 -- repair / fix crc's of a 'Legic-Cash-Segment'
2230 function fixLegicCash(data
, uid
)
2231 if(#data
==32 and data
[7]=="01") then
2232 local crc1
, crc2
, crc3
2233 -- set shadow-balance equal to balance
2237 -- set shadow-last-reader to last-reader
2241 -- calculate all crc's
2242 crc1
=("%04x"):format(utils
.Crc16Legic(dumpTable(data
, "", 0, 12), uid
))
2243 crc2
=("%04x"):format(utils
.Crc16Legic(dumpTable(data
, "", 15, 20), uid
))
2244 crc3
=("%04x"):format(utils
.Crc16Legic(dumpTable(data
, "", 23, 29), uid
))
2246 data
[13]=string.sub(crc1
, 1, 2)
2247 data
[14]=string.sub(crc1
, 3, 4)
2248 data
[21]=string.sub(crc2
, 1, 2)
2249 data
[22]=string.sub(crc2
, 3, 4)
2250 data
[30]=string.sub(crc3
, 1, 2)
2251 data
[31]=string.sub(crc3
, 3, 4)
2257 -- repair / fix (yet known) crc's of a '3rd Party Cash-Segment' - not all bytes know until yet !!
2258 function fix3rdPartyCash1(uid
, data
)
2261 data
[31]=("%02x"):format(utils
.Crc8Legic(uid
..dumpTable(data
, "", 19, 30)))
2263 data
[34]=("%02x"):format(utils
.Crc8Legic(uid
..data
[32]..data
[33]))
2265 data
[37]=("%02x"):format(utils
.Crc8Legic(uid
..data
[35]..data
[36]))
2267 data
[55]=("%02x"):format(utils
.Crc8Legic(uid
..dumpTable(data
, "", 46, 54)))
2269 data
[62]=("%02x"):format(utils
.Crc8Legic(uid
..dumpTable(data
, "", 56, 61)))
2271 data
[73]=("%02x"):format(utils
.Crc8Legic(uid
..dumpTable(data
, "", 63, 72)))
2273 data
[89]=("%02x"):format(utils
.Crc8Legic(uid
..dumpTable(data
, "", 74, 88)))
2279 -- calculate Master-Token crc
2280 function calcMtCrc(bytes
)
2282 local cmd
=bytes
[1]..bytes
[2]..bytes
[3]..bytes
[4]..bytes
[7]..bytes
[6]..bytes
[8]
2283 local len
=(tonumber(0xfc ,10)-("%d"):format('0x'..bytes
[7]))
2287 local res
=("%02x"):format(utils
.Crc8Legic(cmd
))
2292 -- calculate segmentCRC for a given segment
2293 function calcSegmentCrc(tag, segid
)
2294 if (istable(tag.SEG
[0])) then
2295 -- check if a 'Kaber Group Header' exists
2296 local data
=segmentCrcCredentials(tag, segid
)
2297 return ("%02x"):format(utils
.Crc8Legic(data
))
2302 -- calcuate kghCRC for a given segment
2303 function calcKghCrc(tag, segid
)
2304 if (istable(tag.SEG
[0])) then
2305 -- check if a 'Kaber Group Header' exists
2307 local data
=kghCrcCredentials(tag, segid
)
2308 return ("%02x"):format(utils
.Crc8Legic(data
))
2313 -- check all segment-crc
2314 function checkAllSegCrc(tag)
2315 if (istable(tag.SEG
[0])) then
2316 for i
=0, #tag.SEG
do
2317 crc
=calcSegmentCrc(tag, i
)
2320 else return print(acyellow
.."Master-Token / unsegmented Tag"..acoff
) end
2324 -- check all segmnet-crc
2325 function checkAllKghCrc(tag)
2326 if (istable(tag.SEG
[0])) then
2327 for i
=0, #tag.SEG
do
2328 crc
=calcKghCrc(tag, i
)
2329 if (tag.SEG
[i
].kgh
) then
2330 tag.SEG
[i
].data
[#tag.SEG
[i
].data
-1]=crc
2337 -- validate segmentCRC for a given segment
2338 function checkSegmentCrc(tag, segid
)
2339 local data
=segmentCrcCredentials(tag, segid
)
2340 if (("%02x"):format(utils
.Crc8Legic(data
))==tag.SEG
[segid
].crc
) then
2347 -- validate kghCRC to segment in tag-table
2348 function checkKghCrc(tag, segid
)
2349 if (type(tag.SEG
[segid
])=='table') then
2350 if (tag.data
[3]=="11" and tag.raw
=="9f" and tag.SSC
=="ff") then
2351 local data
=kghCrcCredentials(tag, segid
)
2352 if (("%02x"):format(utils
.Crc8Legic(data
))==tag.SEG
[segid
].data
[tag.SEG
[segid
].len
-5-1]) then return true; end
2353 else return false; end
2354 else oops(acred
.."'Kaba Group header' detected but no Segment-Data found"..ansocolors
.reset
) end
2358 -- helptext for modify-mode
2359 function modifyHelp()
2362 Data I/O Segment Manipulation Token-Data
2363 ----------------- -------------------- ---------------------
2364 ]]..acy
..[[rt]]..acr
..[[ => read Tag ]]..acy
..[[as]]..acr
..[[ => add Segment ]]..acy
..[[mt]]..acr
..[[ => make Token
2365 ]]..acy
..[[wt]]..acr
..[[ => write Tag ]]..acy
..[[es]]..acr
..[[ => edit Segment Header ]]..acy
..[[et]]..acr
..[[ => edit Token data
2366 ]]..acy
..[[ed]]..acr
..[[ => edit Segment Data ]]..acy
..[[tk]]..acr
..[[ => toggle KGH-Flag
2367 File I/O ]]..acy
..[[rs]]..acr
..[[ => remove Segment
2368 ----------------- ]]..acy
..[[cc]]..acr
..[[ => check Segment-CRC
2369 ]]..acy
..[[lf]]..acr
..[[ => load bin File ]]..acy
..[[ck]]..acr
..[[ => check KGH
2370 ]]..acy
..[[sf]]..acr
..[[ => save eml/bin File ]]..acy
..[[ds]]..acr
..[[ => dump Segments
2371 ]]..acy
..[[xf]]..acr
..[[ => xor to File
2374 Virtual Tags tagMap (partial) known Segments
2375 -------------------------------- --------------------- ---------------------------
2376 ]]..acy
..[[ct]]..acr
..[[ => copy mainTag to backupTag ]]..acy
..[[mm]]..acr
..[[ => make (new) Map ]]..acy
..[[dlc]]..acr
..[[ => dump Legic-Cash
2377 ]]..acy
..[[tc]]..acr
..[[ => copy backupTag to mainTag ]]..acy
..[[em]]..acr
..[[ => edit Map submenu ]]..acy
..[[elc]]..acr
..[[ => edit Legic-Cash
2378 ]]..acy
..[[tt]]..acr
..[[ => switch mainTag & backupTag ]]..acy
..[[lm]]..acr
..[[ => load map from file ]]..acy
..[[d3p]]..acr
..[[ => dump 3rd-Party-Cash
2379 ]]..acy
..[[di]]..acr
..[[ => dump mainTag ]]..acy
..[[sm]]..acr
..[[ => save map to file ]]..acy
..[[e3p]]..acr
..[[ => edit 3rd-Party-Cash
2380 ]]..acy
..[[do]]..acr
..[[ => dump backupTag
2382 ]]..acy
..[[h]]..acr
..[[ => this help ]]..acy
..[[q]]..acr
..[[ => quit
2388 -- modify Tag (interactive)
2389 function modifyMode()
2390 local i
, backupTAG
, outTAG
, inTAG
, outfile
, infile
, sel
, segment
, bytes
, outbytes
, tagMap
2396 print(" Version: "..acgreen
..version
..acr
);
2398 print("\n".."tags im Memory: "..(istable(inTAG
) and ((currentTag
=='inTAG') and acgreen
.."*mainTAG"..acoff
or "mainTAG") or "").." "..(istable(backupTAG
) and ((currentTag
=='backupTAG') and acgreen
.."*backupTAG"..acoff
or "backupTAG") or ""))
2402 -- read real Tag with PM3 into virtual 'mainTAG'
2403 ["rt"] = function(x
)
2404 inTAG
=readFromPM3();
2408 -- write content of virtual 'mainTAG' to real Tag with PM3
2409 ["wt"] = function(x
)
2413 -- copy mainTAG to backupTAG
2414 ["ct"] = function(x
)
2415 print(accyan
.."copy mainTAG to backupTAG"..acoff
)
2416 backupTAG
=deepCopy(inTAG
)
2419 -- copy backupTAG to mainTAG
2420 ["tc"] = function(x
)
2421 print(accyan
.."copy backupTAG to mainTAG"..acoff
)
2422 inTAG
=deepCopy(backupTAG
)
2425 -- toggle between mainTAG and backupTAG
2426 ["tt"] = function(x
)
2427 -- copy main to temp
2428 outTAG
=deepCopy(inTAG
)
2429 -- copy backup to main
2430 inTAG
=deepCopy(backupTAG
)
2431 print(accyan
.."toggle to "..accyan
..((currentTag
=='inTAG') and "backupTAG" or "mainTAG")..acoff
)
2432 if(currentTag
=="inTAG") then currentTag
='backupTAG'
2433 else currentTag
='inTAG' end
2434 -- copy temp (main) to backup
2435 backupTAG
=deepCopy(outTAG
)
2438 -- load file into mainTAG
2439 ["lf"] = function(x
)
2440 if (x
and not x
=="" and type(x
)=='string' and file_check(x
)) then
2443 filename
= input("enter filename: ", "legic.temp")
2445 inTAG
=readFile(filename
)
2446 -- check for existing tagMap
2447 local res
, path
= file_check(filename
..".map")
2449 if(confirm(accyan
.."Mapping-File for "..acoff
..path
..accyan
.." found - load it also?"..acoff
)) then
2450 tagMap
=loadTagMap(filename
..".map")
2455 -- save values of mainTAG to a file (xored with MCC of mainTAG)
2456 ["sf"] = function(x
)
2457 if istable(inTAG
) then
2458 outfile
= input("enter filename:", "hf-legic-"..inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
)
2459 bytes
= tagToBytes(inTAG
)
2460 --bytes=xorBytes(bytes, inTAG.MCC)
2462 writeFile(bytes
, outfile
)
2467 -- save values of mainTAG to a file (xored with 'specific' MCC)
2468 ["xf"] = function(x
)
2469 if istable(inTAG
) then
2470 outfile
= input("enter filename:", "hf-legic-"..inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
)
2471 crc
= input("enter new crc: ('00' for a plain dump)", inTAG
.MCC
)
2472 print("obfuscate with: "..crc
)
2473 bytes
=tagToBytes(inTAG
)
2476 writeFile(bytes
, outfile
)
2481 -- dump mainTAG (and all Segments)
2482 ["di"] = function(x
)
2483 if (istable(inTAG
)) then
2484 local uid
=inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2485 if(istable(inTAG
.SEG
[0])) then
2486 for i
=0, #inTAG
.SEG
do
2487 if(check43rdPartyCash1(uid
, inTAG
.SEG
[i
].data
)) then
2488 io
.write(accyan
.."in Segment index: "..inTAG
.SEG
[i
].index
..acoff
.. "\n")
2489 elseif(check4LegicCash(inTAG
.SEG
[i
].data
, uid
)) then
2490 io
.write(accyan
.."in Segment index: "..inTAG
.SEG
[i
].index
..acoff
.."\n")
2492 lci
=inTAG
.SEG
[i
].index
;
2496 print("\n"..dumpTag(inTAG
).."\n")
2497 if (lc
) then actions
["dlc"](lci
) end
2502 -- dump backupTAG (and all Segments)
2503 ["do"] = function(x
) if (istable(backupTAG
)) then print("\n"..dumpTag(backupTAG
).."\n") end end,
2505 -- create a empty tagMap
2506 ["mm"] = function(x
)
2507 -- clear existing tagMap and init
2508 if (istable(inTAG
)) then
2514 ["em"] = function(x
)
2515 if (istable(inTAG
)==false) then
2516 if (confirm("no mainTAG in memory!\nread from PM3?")) then
2518 elseif (confirm("load from File?")) then
2523 if (istable(tagMap
)==false) then actions
['mm']() end
2525 tagMap
=editTagMap(inTAG
, tagMap
)
2529 ["sm"] = function(x
)
2530 if (istable(tagMap
)) then
2531 if (istable(tagMap
) and #tagMap
.mappings
>0) then
2532 print(accyan
.."Map contains "..acoff
..#tagMap
..accyan
.." mappings"..acoff
)
2533 saveTagMap(tagMap
, input(accyan
.."enter filename:"..acoff
, "Legic.map"))
2535 print(acyellow
.."no mappings in tagMap!"..acoff
)
2541 ["lm"] = function(x
)
2542 tagMap
= loadTagMap(input(accyan
.."enter filename:"..acoff
, "Legic.map"))
2545 -- dump single segment
2546 ["ds"] = function(x
)
2547 if (type(x
)=="string" and string.len(x
)>0) then
2548 sel
= tonumber(x
,10)
2550 sel
= selectSegment(inTAG
)
2552 if (sel
) then print("\n"..(dumpSegment(inTAG
, sel
) or acred
.."no Segments available") ..acoff
.."\n") end
2555 -- edit segment header
2556 ["es"] = function(x
)
2557 if (type(x
)=="string" and string.len(x
)>0) then sel
=tonumber(x
,10)
2558 else sel
=selectSegment(inTAG
) end
2560 if(istable(inTAG
.SEG
[0])) then
2561 inTAG
=editSegment(inTAG
, sel
)
2562 inTAG
.SEG
[sel
]=regenSegmentHeader(inTAG
.SEG
[sel
])
2564 print(acyellow
.."no Segments in Tag"..acoff
)
2570 ["as"] = function(x
)
2571 if (istable(inTAG
.SEG
[0])) then
2572 inTAG
=addSegment(inTAG
)
2573 inTAG
.SEG
[#inTAG
.SEG
-1]=regenSegmentHeader(inTAG
.SEG
[#inTAG
.SEG
-1])
2574 inTAG
.SEG
[#inTAG
.SEG
]=regenSegmentHeader(inTAG
.SEG
[#inTAG
.SEG
])
2575 else print(accyan
.."Master-Token / unsegmented Tag!"..acoff
)
2580 ["rs"] = function(x
)
2581 if (istable(inTAG
.SEG
[0])) then
2582 if (type(x
)=="string" and string.len(x
)>0) then sel
=tonumber(x
,10)
2583 else sel
=selectSegment(inTAG
) end
2584 inTAG
=delSegment(inTAG
, sel
)
2585 for i
=0, #inTAG
.SEG
do
2586 inTAG
.SEG
[i
]=regenSegmentHeader(inTAG
.SEG
[i
])
2591 -- edit data-portion of single segment
2592 ["ed"] = function(x
)
2593 if (type(x
) == "string" and string.len(x
)>0) then sel
=tonumber(x
,10)
2594 else sel
= selectSegment(inTAG
) end
2595 if (istable(inTAG
.SEG
[sel
])) then
2596 local uid
= inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2597 inTAG
.SEG
[sel
].data
= editSegmentData(inTAG
.SEG
[sel
].data
, uid
)
2601 -- edit Tag (MCD, MSN, MCC etc.)
2602 ["et"] = function(x
)
2603 if (istable(inTAG
)) then
2608 -- make (dummy) Token
2609 ["mt"] = function(x
) inTAG
=makeToken(); actions
.di() end,
2611 -- fix segment-crc on single segment
2612 ["ts"] = function(x
)
2613 if (type(x
)=="string" and string.len(x
)>0) then sel
=tonumber(x
,10)
2614 else sel
=selectSegment(inTAG
) end
2615 regenSegmentHeader(inTAG
.SEG
[sel
])
2618 -- toggle kgh-crc-flag on a single segment
2619 ["tk"] = function(x
)
2620 if (istable(inTAG
) and istable(inTAG
.SEG
[0])) then
2621 if (type(x
)=="string" and string.len(x
)>0) then
2622 sel
= tonumber(x
,10)
2624 sel
= selectSegment(inTAG
)
2626 if(inTAG
.SEG
[sel
].kgh
) then
2627 inTAG
.SEG
[sel
].kgh
= false
2629 inTAG
.SEG
[sel
].kgh
= true
2634 -- calculate LegicCrc8
2636 if (type(x
)=="string" and string.len(x
)>0) then
2637 print(("%02x"):format(utils
.Crc8Legic(x
)))
2642 ["xb"] = function(x
)
2645 -- print string for LegicCrc8-calculation about single segment
2646 ["xc"] = function(x
)
2647 if (istable(inTAG
) and istable(inTAG
.SEG
[0])) then
2648 if (type(x
)=="string" and string.len(x
)>0) then
2649 sel
= tonumber(x
,10)
2651 sel
= selectSegment(inTAG
)
2653 print("k "..kghCrcCredentials(inTAG
, sel
))
2657 -- fix legic-cash checksums
2658 ["flc"] = function(x
)
2659 if (type(x
)=="string" and string.len(x
)>0) then
2662 x
= selectSegment(inTAG
)
2664 local uid
=inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2665 inTAG
.SEG
[x
].data
=fixLegicCash(inTAG
.SEG
[x
].data
, uid
)
2668 -- edit legic-cash values fixLegicCash(data, uid)
2669 ["elc"] = function(x
)
2670 x
=autoSelectSegment(inTAG
, "legiccash")
2671 local uid
=inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2672 inTAG
.SEG
[x
].data
=editLegicCash(inTAG
.SEG
[x
].data
, uid
)
2675 -- dump legic-cash human-readable
2676 ["dlc"] = function(x
)
2677 -- if segment index was user defined
2678 if (type(x
)=="string" and string.len(x
)>0) then
2680 print(string.format("User-Selected Index %02d", x
))
2682 -- or try to find match
2683 x
= autoSelectSegment(inTAG
, "legiccash")
2686 dumpLegicCash(inTAG
, x
)
2689 -- dump 3rd-party-cash-segment
2690 ["d3p"] = function(x
)
2691 local uid
=inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2692 -- if segment index was user defined
2693 if (type(x
)=="string" and string.len(x
)>0) then
2695 print(string.format("User-Selected Index %02d", x
))
2697 -- or try to find match
2698 x
= autoSelectSegment(inTAG
, "3rdparty")
2700 if (istable(inTAG
) and istable(inTAG
.SEG
[x
]) and inTAG
.SEG
[x
].len
== 100) then
2701 uid
=inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2702 if (check43rdPartyCash1(uid
, inTAG
.SEG
[x
].data
)) then
2703 dump3rdPartyCash1(inTAG
, x
)
2708 -- dump 3rd-party-cash-segment (raw blocks and checksums over 'known areas')
2709 ["r3p"] = function(x
)
2710 local uid
=inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2711 -- if segment index was user defined
2712 if (type(x
)=="string" and string.len(x
)>0) then
2714 print(string.format("User-Selected Index %02d", x
))
2716 -- or try to find match
2717 x
= autoSelectSegment(inTAG
, "3rdparty")
2719 print3rdPartyCash1(inTAG
, x
)
2722 -- edit 3rd-party-cash-segment values (Balance, Mapping-UID, Stamp)
2723 ["e3p"] = function(x
)
2724 local uid
=inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2725 -- if segment index was user defined
2726 if (type(x
)=="string" and string.len(x
)>0) then
2728 print(string.format("User-Selected Index %02d", x
))
2731 -- or try to find match
2732 x
= autoSelectSegment(inTAG
, "3rdparty")
2734 if (istable(inTAG
) and istable(inTAG
.SEG
[x
]) and inTAG
.SEG
[x
].len
== 100) then
2735 inTAG
=edit3rdPartyCash1(inTAG
, x
)
2736 dump3rdPartyCash1(inTAG
, x
)
2740 -- force fixing 3rd-party-checksums
2741 ["f3p"] = function(x
)
2742 if(type(x
)=="string" and string.len(x
)>=2) then
2745 x
= selectSegment(inTAG
)
2747 if (istable(inTAG
.SEG
[x
])) then
2748 local uid
=inTAG
.MCD
..inTAG
.MSN0
..inTAG
.MSN1
..inTAG
.MSN2
2749 inTAG
.SEG
[x
].data
=fix3rdPartyCash1(uid
, inTAG
.SEG
[x
].data
)
2753 -- get stamp from single segment
2754 ["gs"] = function(x
)
2755 if(type(x
)=="string" and string.len(x
)>=2) then
2758 x
= selectSegment(inTAG
)
2760 local stamp
=getSegmentStamp(inTAG
.SEG
[x
])
2761 print("Stamp : "..stamp
)
2762 stamp
=str2bytes(stamp
)
2763 print("length: "..#stamp
)
2767 ["c6"] = function(x
) local crc16
=string.format("%4.04x", utils
.Crc16(x
))
2768 print(string.sub(crc16
, 0,2).." "..string.sub(crc16
, 3,4))
2771 -- check & fix segments-crc of all segments
2772 ["cc"] = function(x
) if (istable(inTAG
)) then checkAllSegCrc(inTAG
) end end,
2774 -- set backup-area-bytes to '00'
2775 ["cb"] = function(x
)
2776 if (istable(inTAG
)) then
2777 print(accyan
.."purge BackupArea"..acoff
)
2778 inTAG
=clearBackupArea(inTAG
)
2782 -- check and fix all segments inTAG.SEG[x].kgh toggled 'on'
2783 ["ck"] = function(x
) if (istable(inTAG
)) then checkAllKghCrc(inTAG
) end end,
2785 -- check and fix all segments inTAG.SEG[x].kgh toggled 'on'
2786 ["tac"] = function(x
)
2787 if (colored_output
) then
2788 colored_output
=false
2792 load_colors(colored_output
)
2796 -- default message / prompt
2797 ic
=input("Legic command? ('"..acy
.."h"..acr
.."' for help - '"..acy
.."q"..acr
.."' for quit)", acy
.."h"..acr
)
2798 -- command actions decisions (first match, longer commands before shorter)
2799 if (type(actions
[string.lower(string.sub(ic
,0,3))])=='function') then
2800 actions
[string.lower(string.sub(ic
,0,3))](string.sub(ic
,5))
2801 elseif (type(actions
[string.lower(string.sub(ic
,0,2))])=='function') then
2802 actions
[string.lower(string.sub(ic
,0,2))](string.sub(ic
,4))
2803 elseif (type(actions
[string.lower(string.sub(ic
,0,1))])=='function') then
2804 actions
[string.lower(string.sub(ic
,0,1))](string.sub(ic
,3))
2808 until (string.sub(ic
,0,1)=="q")
2814 -- set init colors/switch (can be toggled with 'tac' => 'toggle ansicolors')
2815 load_colors(colored_output
)
2816 if (#args
== 0 ) then modifyMode() end
2818 local inTAG
, backupTAG
, outTAG
, outfile
, interactive
, crc
2822 -- just a spacer for better readability
2825 for o
, a
in getopt
.getopt(args
, 'hrmi:do:c:') do
2827 if o
== "h" then return help(); end
2828 -- read tag from PM3
2829 if o
== "r" then inTAG
=readFromPM3() end
2831 if o
== "i" then inTAG
=readFile(a
) end
2833 if o
== "d" then dfs
=true end
2834 -- interacive modifying
2839 -- xor (e.g. for clone or plain file)
2851 -- file conversion (output to file)
2852 if ofs
== false then return end
2854 -- dump infile / tag-read
2856 print("-----------------------------------------")
2857 print(dumpTag(inTAG
))
2860 bytes
=tagToBytes(inTAG
)
2862 -- xor will be done in function writeFile
2863 -- with the value of byte[5]
2871 writeFile(bytes
, outfile
)
2873 --- read real tag into virtual tag
2874 -- inTAG=readFromPM3() end
2875 --- or simply use the bytes that where wriiten
2876 inTAG
=bytesToTag(bytes
, inTAG
)
2879 print("-----------------------------------------")
2880 print(dumpTag(inTAG
))