change scripts/ to luascripts/

This commit is contained in:
Philippe Teuwen 2019-08-21 23:17:01 +02:00
commit a8ee33baf4
47 changed files with 8 additions and 8 deletions

View file

@ -0,0 +1,199 @@
local cmds = require('commands')
local getopt = require('getopt')
local lib14a = require('read14a')
copyright = ''
author = "Martin Holst Swende"
version = 'v1.0.1'
desc = [[
This is a script to allow raw 1444a commands to be sent and received.
]]
example = [[
# 1. Connect and don't disconnect
script run 14araw -p
# 2. Send mf auth, read response (nonce)
script run 14araw -o -x 6000F57b -p
# 3. disconnect
script run 14araw -o
# All three steps in one go:
script run 14araw -x 6000F57b
]]
usage = [[
script run 14araw -x 6000F57b
Arguments:
-o do not connect - use this only if you previously used -p to stay connected
-r do not read response
-c calculate and append CRC
-p stay connected - dont inactivate the field
-x <payload> Data to send (NO SPACES!)
-d Debug flag
-t Topaz mode
-3 ISO14443-4 (use RATS)
]]
--[[
This script communicates with
/armsrc/iso14443a.c, specifically ReaderIso14443a() at around line 1779 and onwards.
Check there for details about data format and how commands are interpreted on the
device-side.
]]
-- Some globals
local DEBUG = false -- the debug flag
-------------------------------
-- Some utilities
-------------------------------
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
-- The main entry point
function main(args)
if args == nil or #args == 0 then return help() end
local ignore_response = false
local append_crc = false
local stayconnected = false
local payload = nil
local doconnect = true
local topaz_mode = false
local no_rats = false
-- Read the parameters
for o, a in getopt.getopt(args, 'orcpx:dt3') do
if o == 'o' then doconnect = false end
if o == 'r' then ignore_response = true end
if o == 'c' then append_crc = true end
if o == 'p' then stayconnected = true end
if o == 'x' then payload = a end
if o == 'd' then DEBUG = true end
if o == 't' then topaz_mode = true end
if o == '3' then no_rats = true end
end
-- First of all, connect
if doconnect then
dbg("doconnect")
info, err = lib14a.read(true, no_rats)
if err then
lib14a.disconnect()
return oops(err)
end
print(('Connected to card, uid = %s'):format(info.uid))
end
-- The actual raw payload, if any
if payload then
res, err = sendRaw(payload,{ignore_response = ignore_response, topaz_mode = topaz_mode, append_crc = append_crc})
if err then
lib14a.disconnect()
return oops(err)
end
if not ignoreresponse then
-- Display the returned data
showdata(res)
end
end
-- And, perhaps disconnect?
if not stayconnected then
lib14a.disconnect()
end
end
--- Picks out and displays the data read from a tag
-- Specifically, takes a usb packet, converts to a Command
-- (as in commands.lua), takes the data-array and
-- reads the number of bytes specified in arg1 (arg0 in c-struct)
-- and displays the data
-- @param usbpacket the data received from the device
function showdata(usbpacket)
local cmd_response = Command.parse(usbpacket)
local len = tonumber(cmd_response.arg1) *2
--print("data length:",len)
local data = string.sub(tostring(cmd_response.data), 0, len);
print("<< ",data)
end
function sendRaw(rawdata, options)
print('>> ', rawdata)
local flags = lib14a.ISO14A_COMMAND.ISO14A_NO_DISCONNECT + lib14a.ISO14A_COMMAND.ISO14A_RAW
if options.topaz_mode then
flags = flags + lib14a.ISO14A_COMMAND.ISO14A_TOPAZMODE
end
if options.append_crc then
flags = flags + lib14a.ISO14A_COMMAND.ISO14A_APPEND_CRC
end
local command = Command:newMIX{cmd = cmds.CMD_HF_ISO14443A_READER,
arg1 = flags, -- Send raw
-- arg2 contains the length, which is half the length
-- of the ASCII-string rawdata
arg2 = string.len(rawdata)/2,
data = rawdata}
return command:sendMIX(options.ignore_response)
end
-------------------------
-- Testing
-------------------------
function selftest()
DEBUG = true
dbg('Performing test')
main()
main('-p')
main(' -o -x 6000F57b -p')
main('-o')
main('-x 6000F57b')
dbg('Tests done')
end
-- Flip the switch here to perform a sanity check.
-- It read a nonce in two different ways, as specified in the usage-section
if '--test'==args then
selftest()
else
-- Call the main
main(args)
end

View file

@ -0,0 +1,554 @@
--[[
script to create a clone-dump with new crc
Author: mosci
my Fork: https://github.com/icsom/proxmark3.git
Upstream: https://github.com/Proxmark/proxmark3.git
1. read tag-dump, xor byte 22..end with byte 0x05 of the inputfile
2. write to outfile
3. set byte 0x05 to newcrc
4. until byte 0x21 plain like in inputfile
5. from 0x22..end xored with newcrc
6. calculate new crc on each segment (needs to know the new MCD & MSN0..2)
simplest usage:
read a valid legic tag with 'hf legic reader'
save the dump with 'hf legic save orig.hex'
place your 'empty' tag on the reader and run 'script run Legic_clone -i orig.hex -w'
you will see some output like:
read 1024 bytes from legic_dumps/j_0000.hex
place your empty tag onto the PM3 to read and display the MCD & MSN0..2
the values will be shown below
confirm whnen ready [y/n] ?y
#db# setting up legic card
#db# MIM 256 card found, reading card ...
#db# Card read, use 'hf legic decode' or
#db# 'data hexsamples 8' to view results
0b ad c0 de <- !! here you'll see the MCD & MSN of your empty tag, which has to be typed in manually as seen below !!
type in MCD as 2-digit value - e.g.: 00 (default: 79 )
> 0b
type in MSN0 as 2-digit value - e.g.: 01 (default: 28 )
> ad
type in MSN1 as 2-digit value - e.g.: 02 (default: d1 )
> c0
type in MSN2 as 2-digit value - e.g.: 03 (default: 43 )
> de
MCD:0b, MSN:ad c0 de, MCC:79 <- this crc is calculated from the MCD & MSN and must match the one on yout empty tag
wrote 1024 bytes to myLegicClone.hex
enter number of bytes to write? (default: 86 )
loaded 1024 samples
#db# setting up legic card
#db# MIM 256 card found, writing 0x00 - 0x01 ...
#db# write successful
...
#db# setting up legic card
#db# MIM 256 card found, writing 0x56 - 0x01 ...
#db# write successful
proxmark3>
the default value (number of bytes to write) is calculated over all valid segments and should be ok - just hit enter, wait until write has finished
and your clone should be ready (except there has to be a additional KGH-CRC to be calculated - which credentials are unknown until yet)
the '-w' switch will only work with my fork - it needs the binary legic_crc8 which is not part of the proxmark3-master-branch
also the ability to write DCF is not possible with the proxmark3-master-branch
but creating dumpfile-clone files will be possible (without valid segment-crc - this has to done manually with)
(example) Legic-Prime Layout with 'Kaba Group Header'
+----+----+----+----+----+----+----+----+
0x00|MCD |MSN0|MSN1|MSN2|MCC | 60 | ea | 9f |
+----+----+----+----+----+----+----+----+
0x08| ff | 00 | 00 | 00 | 11 |Bck0|Bck1|Bck2|
+----+----+----+----+----+----+----+----+
0x10|Bck3|Bck4|Bck5|BCC | 00 | 00 |Seg0|Seg1|
+----+----+----+----+----+----+----+----+
0x18|Seg2|Seg3|SegC|Stp0|Stp1|Stp2|Stp3|UID0|
+----+----+----+----+----+----+----+----+
0x20|UID1|UID2|kghC|
+----+----+----+
MCD= ManufacturerID (1 Byte)
MSN0..2= ManufactureSerialNumber (3 Byte)
MCC= CRC (1 Byte) calculated over MCD,MSN0..2
DCF= DecrementalField (2 Byte) 'credential' (enduser-Tag) seems to have always DCF-low=0x60 DCF-high=0xea
Bck0..5= Backup (6 Byte) Bck0 'dirty-flag', Bck1..5 SegmentHeader-Backup
BCC= BackupCRC (1 Byte) CRC calculated over Bck1..5
Seg0..3= SegmentHeader (on MIM 4 Byte )
SegC= SegmentCRC (1 Byte) calculated over MCD,MSN0..2,Seg0..3
Stp0..n= Stamp0... (variable length) length = Segment-Len - UserData - 1
UID0..n= UserDater (variable length - with KGH hex 0x00-0x63 / dec 0-99) length = Segment-Len - WRP - WRC - 1
kghC= KabaGroupHeader (1 Byte + addr 0x0c must be 0x11)
as seen on this example: addr 0x05..0x08 & 0x0c must have been set to this values - otherwise kghCRC will not be created by a official reader (not accepted)
--]]
copyright = ''
author = 'Mosci'
version = 'v1.0.1'
desc = [[
This is a script which create a clone-dump of a dump from a Legic Prime Tag (MIM256 or MIM1024)
(created with 'hf legic save my_dump.hex')
]]
example = [[
script run legic_clone -i my_dump.hex -o my_clone.hex -c f8
script run legic_clone -i my_dump.hex -d -s
]]
usage = [[
script run legic_clone -h -i <file> -o <file> -c <crc> -d -s -w
requiered arguments:
-i <input file> (file to read data from)
optional arguments :
-h - Help text
-o <output file> - requieres option -c to be given
-c <new-tag crc> - requieres option -o to be given
-d - Display content of found Segments
-s - Display summary at the end
-w - write directly to Tag - a file myLegicClone.hex wille be generated also
e.g.:
hint: using the CRC '00' will result in a plain dump ( -c 00 )
]]
local utils = require('utils')
local getopt = require('getopt')
local bxor = bit32.bxor
-- we need always 2 digits
local function prepend_zero(s)
if (string.len(s) == 1) then
return '0' .. s
else
if (string.len(s) == 0) then
return '00'
else
return s
end
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
-- Check availability of file
local function file_check(file_name)
local file_found = io.open(file_name, "r")
if not file_found then
file_found = false
else
file_found = true
end
return file_found
end
--- xor-wrapper
-- xor all from addr 0x22 (start counting from 1 => 23)
local function xorme(hex, xor, index)
if ( index >= 23 ) then
return ('%02x'):format(bxor( tonumber(hex,16) , tonumber(xor,16) ))
else
return hex
end
end
-- read input-file into array
local function getInputBytes(infile)
local line
local bytes = {}
local fhi,err = io.open(infile)
if err then print("OOps ... faild to read from file ".. infile); return false; end
while true do
line = fhi:read()
if line == nil then break end
for byte in line:gmatch("%w+") do
table.insert(bytes, byte)
end
end
fhi:close()
print("\nread ".. #bytes .." bytes from ".. infile)
return bytes
end
-- write to file
local function writeOutputBytes(bytes, outfile)
local line
local bcnt = 0
local fho,err = io.open(outfile,"w")
if err then print("OOps ... faild to open output-file ".. outfile); return false; end
for i = 1, #bytes do
if (bcnt == 0) then
line = bytes[i]
elseif (bcnt <= 7) then
line = line.." "..bytes[i]
end
if (bcnt == 7) then
-- write line to new file
fho:write(line.."\n")
-- reset counter & line
bcnt = -1
line = ""
end
bcnt = bcnt + 1
end
fho:close()
print("\nwrote ".. #bytes .." bytes to " .. outfile)
return true
end
-- xore certain bytes
local function xorBytes(inBytes, crc)
local bytes = {}
for index = 1, #inBytes do
bytes[index] = xorme(inBytes[index], crc, index)
end
if (#inBytes == #bytes) then
-- replace crc
bytes[5] = string.sub(crc,-2)
return bytes
else
print("error: byte-count missmatch")
return false
end
end
-- get raw segment-data
function getSegmentData(bytes, start, index)
local raw, len, valid, last, wrp, wrc, rd, crc
local segment = {}
segment[0] = bytes[start]..' '..bytes[start+1]..' '..bytes[start+2]..' '..bytes[start+3]
-- flag = high nibble of byte 1
segment[1] = string.sub(bytes[start+1],0,1)
-- valid = bit 6 of byte 1
segment[2] = tonumber(bit32.extract('0x'..bytes[start+1],6,1),16)
-- last = bit 7 of byte 1
segment[3] = tonumber(bit32.extract('0x'..bytes[start+1],7,1),16)
-- len = (byte 0)+(bit0-3 of byte 1)
segment[4] = tonumber(('%03x'):format(tonumber(bit32.extract('0x'..bytes[start+1],0,3),16)..tonumber(bytes[start],16)),16)
-- wrp (write proteted) = byte 2
segment[5] = tonumber(bytes[start+2])
-- wrc (write control) - bit 4-6 of byte 3
segment[6] = tonumber(bit32.extract('0x'..bytes[start+3],4,3),16)
-- rd (read disabled) - bit 7 of byte 3
segment[7] = tonumber(bit32.extract('0x'..bytes[start+3],7,1),16)
-- crc byte 4
segment[8] = bytes[start+4]
-- segment index
segment[9] = index
-- # crc-byte
segment[10] = start+4
return segment
end
--- Kaba Group Header
-- checks if a segment does have a kghCRC
-- returns boolean false if no kgh has being detected or the kghCRC if a kgh was detected
function CheckKgh(bytes, segStart, segEnd)
if (bytes[8]=='9f' and bytes[9]=='ff' and bytes[13]=='11') then
local i
local data = {}
segStart = tonumber(segStart, 10)
segEnd = tonumber(segEnd, 10)
local dataLen = segEnd-segStart-5
--- gather creadentials for verify
local WRP = bytes[(segStart+2)]
local WRC = ("%02x"):format(tonumber(bit32.extract("0x"..bytes[segStart+3],4,3),16))
local RD = ("%02x"):format(tonumber(bit32.extract("0x"..bytes[segStart+3],7,1),16))
local XX = "00"
cmd = bytes[1]..bytes[2]..bytes[3]..bytes[4]..WRP..WRC..RD..XX
for i = (segStart+5), (segStart+5+dataLen-2) do
cmd = cmd..bytes[i]
end
local KGH = ("%02x"):format(utils.Crc8Legic(cmd))
if (KGH == bytes[segEnd-1]) then
return KGH
else
return false
end
else
return false
end
end
-- get only the addresses of segemnt-crc's and the length of bytes
function getSegmentCrcBytes(bytes)
local start = 23
local index = 0
local crcbytes = {}
repeat
seg = getSegmentData(bytes,start,index)
crcbytes[index] = seg[10]
start = start + seg[4]
index = index + 1
until (seg[3] == 1 or tonumber(seg[9]) == 126 )
crcbytes[index] = start
return crcbytes
end
-- print segment-data (hf legic decode like)
function displaySegments(bytes)
--display segment header(s)
start = 23
index = '00'
--repeat until last-flag ist set to 1 or segment-index has reached 126
repeat
wrc = ''
wrp = ''
pld = ''
Seg = getSegmentData(bytes, start, index)
KGH = CheckKgh(bytes, start, (start+tonumber(Seg[4],10)))
printSegment(Seg)
-- wrc
if (Seg[6] > 0) then
print("WRC protected area:")
-- length of wrc = wrc
for i=1, Seg[6] do
-- starts at (segment-start + segment-header + segment-crc)-1
wrc = wrc..bytes[(start+4+1+i)-1]..' '
end
print(wrc)
elseif (Seg[5] > 0) then
print("Remaining write protected area:")
-- length of wrp = (wrp-wrc)
for i=1, (Seg[5]-Seg[6]) do
-- starts at (segment-start + segment-header + segment-crc + wrc)-1
wrp = wrp..bytes[(start+4+1+Seg[6]+i)-1]..' '
end
print(wrp)
end
-- payload
print("Remaining segment payload:")
--length of payload = segment-len - segment-header - segment-crc - wrp -wrc
for i=1, (Seg[4]-4-1-Seg[5]-Seg[6]) do
-- starts at (segment-start + segment-header + segment-crc + segment-wrp + segemnt-wrc)-1
pld = pld..bytes[(start+4+1+Seg[5]+Seg[6]+i)-1]..' '
end
print(pld)
if (KGH) then
print("'Kaba Group Header' detected")
end
start = start+Seg[4]
index = prepend_zero(tonumber(Seg[9])+1)
until (Seg[3] == 1 or tonumber(Seg[9]) == 126 )
end
-- print Segment values
function printSegment(SegmentData)
res = "\nSegment "..SegmentData[9]..": "
res = res.. "raw header="..SegmentData[0]..", "
res = res.. "flag="..SegmentData[1].." (valid="..SegmentData[2].." last="..SegmentData[3].."), "
res = res.. "len="..("%04d"):format(SegmentData[4])..", "
res = res.. "WRP="..prepend_zero(SegmentData[5])..", "
res = res.. "WRC="..prepend_zero(SegmentData[6])..", "
res = res.. "RD="..SegmentData[7]..", "
res = res.. "crc="..SegmentData[8]
print(res)
end
-- write clone-data to tag
function writeToTag(plainBytes)
local SegCrcs = {}
if(utils.confirm("\nplace your empty tag onto the PM3 to read and display the MCD & MSN0..2\nthe values will be shown below\n confirm when ready") == false) then
return
end
-- gather MCD & MSN from new Tag - this must be enterd manually
cmd = 'hf legic read 0x00 0x04'
core.console(cmd)
print("\nthese are the MCD MSN0 MSN1 MSN2 from the Tag that has being read:")
cmd = 'data hexsamples 4'
core.console(cmd)
print("^^ use this values as input for the following answers (one 2-digit-value per question/answer):")
-- enter MCD & MSN (in hex)
MCD = utils.input("type in MCD as 2-digit value - e.g.: 00", plainBytes[1])
MSN0 = utils.input("type in MSN0 as 2-digit value - e.g.: 01", plainBytes[2])
MSN1 = utils.input("type in MSN1 as 2-digit value - e.g.: 02", plainBytes[3])
MSN2 = utils.input("type in MSN2 as 2-digit value - e.g.: 03", plainBytes[4])
-- calculate crc8 over MCD & MSN
cmd = MCD..MSN0..MSN1..MSN2
MCC = ("%02x"):format(utils.Crc8Legic(cmd))
print("MCD:"..MCD..", MSN:"..MSN0.." "..MSN1.." "..MSN2..", MCC:"..MCC)
-- calculate new Segment-CRC for each valid segment
SegCrcs = getSegmentCrcBytes(plainBytes)
for i=0, (#SegCrcs-1) do
-- SegCrcs[i]-4 = address of first byte of segmentHeader (low byte segment-length)
segLen = tonumber(("%1x"):format(tonumber(bit32.extract("0x"..plainBytes[(SegCrcs[i]-3)],0,3),16))..("%02x"):format(tonumber(plainBytes[SegCrcs[i]-4],16)),16)
segStart = (SegCrcs[i]-4)
segEnd = (SegCrcs[i]-4+segLen)
KGH = CheckKgh(plainBytes,segStart,segEnd)
if (KGH) then
print("'Kaba Group Header' detected - re-calculate...")
end
cmd = MCD..MSN0..MSN1..MSN2..plainBytes[SegCrcs[i]-4]..plainBytes[SegCrcs[i]-3]..plainBytes[SegCrcs[i]-2]..plainBytes[SegCrcs[i]-1]
plainBytes[SegCrcs[i]] = ("%02x"):format(utils.Crc8Legic(cmd))
end
-- apply MCD & MSN to plain data
plainBytes[1] = MCD
plainBytes[2] = MSN0
plainBytes[3] = MSN1
plainBytes[4] = MSN2
plainBytes[5] = MCC
-- prepare plainBytes for writing (xor plain data with new MCC)
bytes = xorBytes(plainBytes, MCC)
-- write data to file
if (writeOutputBytes(bytes, "myLegicClone.hex")) then
WriteBytes = utils.input("enter number of bytes to write?", SegCrcs[#SegCrcs])
-- load file into pm3-buffer
cmd = 'hf legic eload myLegicClone.hex'
core.console(cmd)
-- write pm3-buffer to Tag
for i=0, WriteBytes do
if ( i<5 or i>6) then
cmd = ('hf legic write o %02x d 01'):format(i)
core.console(cmd)
elseif (i == 6) then
-- write DCF in reverse order (requires 'mosci-patch')
cmd = 'hf legic write o 05 d 02'
core.console(cmd)
else
print("skipping byte 0x05 - will be written next step")
end
utils.Sleep(0.2)
end
end
end
-- main function
function main(args)
-- some variables
local i = 0
local oldcrc, newcrc, infile, outfile
local bytes = {}
local segments = {}
-- parse arguments for the script
for o, a in getopt.getopt(args, 'hwsdc:i:o:') do
-- output file
if o == 'o' then
outfile = a
ofs = true
if (file_check(a)) then
local answer = utils.confirm('\nthe output-file '..a..' alredy exists!\nthis will delete the previous content!\ncontinue?')
if (answer==false) then return oops('quiting') end
end
end
-- input file
if o == 'i' then
infile = a
if (file_check(infile)==false) then
return oops('input file: '..infile..' not found')
else
bytes = getInputBytes(infile)
oldcrc = bytes[5]
ifs = true
if (bytes == false) then return oops('couldnt get input bytes') end
end
i = i+1
end
-- new crc
if o == 'c' then
newcrc = a
ncs = true
end
-- display segments switch
if o == 'd' then ds = true; end
-- display summary switch
if o == 's' then ss = true; end
-- write to tag switch
if o == 'w' then ws = true; end
-- help
if o == 'h' then return help() end
end
if (not ifs) then return oops('option -i <input file> is required but missing') end
-- bytes to plain
bytes = xorBytes(bytes, oldcrc)
-- show segments (works only on plain bytes)
if (ds) then
print("+------------------------------------------- Segments -------------------------------------------+")
displaySegments(bytes);
end
if (ofs and ncs) then
-- xor bytes with new crc
newBytes = xorBytes(bytes, newcrc)
-- write output
if (writeOutputBytes(newBytes, outfile)) then
-- show summary if requested
if (ss) then
-- information
res = "\n+-------------------------------------------- Summary -------------------------------------------+"
res = res .."\ncreated clone_dump from\n\t"..infile.." crc: "..oldcrc.."\ndump_file:"
res = res .."\n\t"..outfile.." crc: "..string.sub(newcrc,-2)
res = res .."\nyou may load the new file with: hf legic load "..outfile
res = res .."\n\nif you don't write to tag immediately ('-w' switch) you will need to recalculate each segmentCRC"
res = res .."\nafter writing this dump to a tag!"
res = res .."\n\na segmentCRC gets calculated over MCD,MSN0..3,Segment-Header0..3"
res = res .."\ne.g. (based on Segment00 of the data from "..infile.."):"
res = res .."\nhf legic crc8 "..bytes[1]..bytes[2]..bytes[3]..bytes[4]..bytes[23]..bytes[24]..bytes[25]..bytes[26]
-- this can not be calculated without knowing the new MCD, MSN0..2
print(res)
end
end
else
if (ss) then
-- show why the output-file was not written
print("\nnew file not written - some arguments are missing ..")
print("output file: ".. (ofs and outfile or "not given"))
print("new crc: ".. (ncs and newcrc or "not given"))
end
end
-- write to tag
if (ws and #bytes == 1024) then
writeToTag(bytes)
end
end
-- call main with arguments
main(args)

View file

@ -0,0 +1,235 @@
local utils = require('utils')
local cmds = require('commands')
local Amiibo = require('amiibolib')
local reader = require('read14a')
local bin = require('bin')
local emu = require('emulator')
local luamiibo_open, err = package.loadlib("./libluamiibo.so", "luaopen_luamiibo")
if err then
print(err)
return
end
local luamiibo = luamiibo_open()
local function nfc_read_amiibo ()
local command = Command:newMIX{
cmd = cmds.CMD_HF_MIFAREU_READCARD,
arg1 = 0,
arg2 = 135
}
local result, err = command:sendMIX()
if result then
-- Do Mifare Ultralight read
local count, cmd, arg0, data_len, offset = bin.unpack('LLLL', result)
if arg0 == 0 then
return nil, "Card select failed"
end
-- Do GetFromBigBuf
local data = core.GetFromBigBuf(offset, data_len)
return data, err
else
return nil, "Couldn't read Amiibo"
end
end
local function emulate_amiibo (amiibo_data)
-- Make UID args
-- Use known ID/sig for known ECDSA signature - REPLACE ME!
local uid_bytes = '\x00\x04\xFF\xFF\xFF\xFF\xFF\xFF'
local ecc_sig = ''
.. '\x00\x00\x00\x00\x00\x00\x00\x00'
.. '\x00\x00\x00\x00\x00\x00\x00\x00'
.. '\x00\x00\x00\x00\x00\x00\x00\x00'
.. '\x00\x00\x00\x00\x00\x00\x00\x00'
if amiibo_data:len() == 520 then
-- Add common ending bytes
print('Added missing ending bytes')
amiibo_data = amiibo_data
.. '\x01\x00\x0F\xBD\x00\x00\x00\x04'
.. '\x5F\x00\x00\x00\x00\x00\x00\x00'
.. '\x00\x00\x00\x00'
end
if amiibo_data:len() == 572 then
-- Get ECC signature and use original serial
uid_bytes = '\x00' .. amiibo_data:sub(1,3) .. amiibo_data:sub(5,8)
ecc_sig = amiibo_data:sub(541, 572)
print('Amiibo image contains ECC signature', hexlify(ecc_sig))
--amiibo_data = amiibo_data:sub(1,540)
elseif amiibo_data:len() == 540 then
if uid_bytes ~= '\x00\x04\xFF\xFF\xFF\xFF\xFF\xFF' then
print('Using known ECC sig pair')
else
print('No known ECC/sig pair; using null signature')
uid_bytes = '\x00' .. amiibo_data:sub(1,3) .. amiibo_data:sub(5,8)
end
amiibo_data = amiibo_data .. ecc_sig
else
print('Unusual Amiibo image size', amiibo_data:len())
end
-- Send amiibo data to emulator memory. If the Amiibo was just scanned, this
-- is already set!
if not emu:set_mem(amiibo_data, false) then
print('Failed to set emulator card memory')
return
end
-- Get UID parts
local count, uid_first, uid_second = bin.unpack('>I>I', uid_bytes)
print(string.format('Simulating with UID: 0x%04x 0x%04x', uid_first, uid_second))
-- Begin simulating NTAG215
local simCmd = Command:newMIX{
cmd = cmds.CMD_HF_ISO14443A_SIMULATE,
arg1 = 7,
arg2 = uid_first,
arg3 = uid_second
}
local _, err = simCmd:sendMIX()
if err then
print('Failed to start simulator', err)
return
else
print('Starting simulator')
end
end
local function test_packing()
-- Load Pikachu dump instead
local dumpfile = io.open("pika.bin", "rb")
local pikachu = dumpfile:read("*all")
local unpacked_pika = luamiibo.unpack(pikachu)
local packed_data = luamiibo.pack(unpacked_pika)
print('Original', utils.hexlify(pikachu))
print('Unpacked', utils.hexlify(unpacked_pika))
print('Packed', utils.hexlify(packed_data))
end
local function load_sim(argv)
local tag = assert(io.open(argv[2], "rb"))
local data = tag:read("*all")
tag:close()
emulate_amiibo(data)
return
end
local function dump_sim(argv)
local keypath = argv[2]
if keypath == nil then
keypath = 'amiitool_keys.bin'
end
luamiibo.load_keys(keypath)
-- Read all 135 pages
dump = emu:get_mem(540)
if dump == false then
print('Failed to read emulator memory')
else
local amiiboData = Amiibo:new{tag = dump}
print('Dumped ' .. dump:len() .. ' bytes')
print(hexlify(dump))
print('Nickname: ' .. utils.hexlify(amiiboData:display_nickname()))
-- Write dump to file
local filename = argv[2]
if filename ~= nil then
local outfile = assert(io.open(filename, "wb"))
outfile:write(dump)
outfile:close()
print('Wrote to ' .. filename)
else
print('No output file specified')
end
end
end
local function main(args)
argv = {}
for arg in string.gmatch(args, "%S+") do
table.insert(argv, arg)
end
-- Load and emulate Amiibo from image
if argv[1] == 'help' then
print('read - scan amiibo')
print('load <amiibo.bin> - load and simulate amiibo')
print('dump [output_file] - dump card memory')
print('help - print this help')
return
elseif argv[1] == 'load' then
load_sim(argv)
return
elseif argv[1] == 'dump' then
dump_sim(argv)
return
elseif argv[1] ~= 'read' and argv[1] ~= nil then
print('Unknown command')
end
local keypath = argv[2]
if keypath == nil then
keypath = 'amiitool_keys.bin'
end
if luamiibo.load_keys(keypath) then
print('Loaded retail keys from ' .. keypath)
else
print('Failed to load retail keys from ' .. keypath)
return
end
local tag, err = nfc_read_amiibo()
if err then
print(err)
return
elseif tag:len() ~= 540 then
print('Incorrect tag data size ' .. tag:len())
return
end
parsed_tag = reader.parse14443a(tag)
print('Tag type:', parsed_tag.name)
print('Tag UID:', parsed_tag.uid)
print('Tag len:', tag:len())
--print('Tag data:', utils.hexlify(tag))
local amiiboData = Amiibo:new{tag = tag}
--print('Unpacked:', utils.hexlify(amiiboData.plain))
--print('Repacked:', utils.hexlify(amiiboData:export_tag()))
print('Figure ID:', utils.hexlify(amiiboData.figure_id))
print('Settings init:', amiiboData.settings_initialized)
if amiiboData.settings_initialized then
print('Nickname:', amiiboData:display_nickname())
print('Appdata writes:', amiiboData.appdata_counter)
end
print('UID:', utils.hexlify(amiiboData.uid))
print('Write key:', utils.hexlify(amiiboData:get_pwd()))
--print('Attempting emulation...')
--emulate_amiibo(amiiboData:export_tag())
return
end
main(args)

View file

@ -0,0 +1,302 @@
local getopt = require('getopt')
copyright = ''
author = 'Kenzy Carey'
version = 'v1.0.1'
desc = [[
.-----------------------------------------------------------------.
/ .-. .-. \
| / \ BruteSim / \ |
| |\_. | (bruteforce simulation for multiple tags) | /| |
|\| | /| by |\ | |/|
| `---' | Kenzy Carey | `---' |
| | | |
| |-----------------------------------------------------| |
\ | | /
\ / \ /
`---' `---'
*SUPPORTED TAGS: pyramid, awid, fdx, jablotron, noralsy, presco, visa2000, 14a, hid
This script uses the Proxmark3 implementations of simulation to bruteforce given ranges of id.
It uses both LF and HF simulations.
-- Author note
-- I wrote this as i was doing a PACS audit. This is far from complete, but is easily expandable.
-- The idea was based on proxbrute, but i needed more options, and support for different readers.
-- I dont know LUA, so I used Brian Redbeards lf_bulk_program.lua script as a starting point, sorry if its kludgy.
]]
example = [[
-- (the above example would bruteforce pyramid tags, starting at 10:1000, ending at 10:991, and waiting 1 second between each card)
script run brutesim -r pyramid -f 10 -b 1000 -c 10 -t 1 -d down
]]
usage = [[
script run brutesim -r rfid_tag -f facility_code -b base_card_number -c count -t timeout -d direction
Arguments:
-h this help
-r *see below RFID Tag: the RFID tag to emulate
pyramid
awid
fdx
jablotron
noralsy
presco
visa2000
14a
hid
-f 0-999 facility code (dfx: country id, 14a: type)
-b 0-65535 base card number to start from
-c 1-65536 number of cards to try
-t .0-99999, pause timeout between cards (use the word 'pause' to wait for user input)
-d up, down direction to move through card numbers
]]
local DEBUG = true
local bor = bit32.bor
local bxor = bit32.bxor
local lshift = bit32.lshift
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function exitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
--
-- Check if a string is empty
local function isempty(s)
return s == nil or s == ''
end
-- The code below was blatantly stolen from Brian Redbeard's lf_bulk_program.lua script
local function toBits(num, bits)
bits = bits or math.max(1, select(2, math.frexp(num)))
local t = {}
for b = bits, 1, -1 do
t[b] = math.fmod(num, 2)
num = math.floor((num - t[b]) / 2)
end
return table.concat(t)
end
--
-- check for parity in bit-string.
local function evenparity(s)
local _, count = string.gsub(s, '1', '')
local p = count % 2
if (p == 0) then
return false
end
return true
end
--
-- calcs hex for HID
local function cardHex(i, f)
fac = lshift(f, 16)
id = bor(i, fac)
stream = toBits(id, 26)
high = evenparity(string.sub(stream, 0, 12)) and 1 or 0
low = not evenparity(string.sub(stream, 13)) and 1 or 0
bits = bor(lshift(id, 1), low)
bits = bor(bits, lshift(high, 25))
preamble = bor(0, lshift(1, 5))
bits = bor(bits, lshift(1, 26))
return ('%04x%08x'):format(preamble, bits)
end
--
--
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
if #args == 0 then return help() end
for o, a in getopt.getopt(args, 'r:f:b:c:t:d:h') do -- Populate command like arguments
if o == 'r' then rfidtag = a end
if o == 'f' then facility = a end
if o == 'b' then baseid = a end
if o == 'c' then count = a end
if o == 't' then timeout = a end
if o == 'd' then direction = a end
if o == 'h' then return print(usage) end
end
-- Check to see if -r argument was passed
if isempty(rfidtag) then
print('You must supply the flag -r (rfid tag)')
print(usage)
return
end
-- Check what RFID Tag we are using
if rfidtag == 'pyramid' then
consolecommand = 'lf pyramid sim' -- set the console command
rfidtagname = 'Farpointe/Pyramid' -- set the display name
facilityrequired = 1 -- set if FC is required
elseif rfidtag == 'awid' then
consolecommand = 'lf awid sim'
rfidtagname = 'AWID'
facilityrequired = 1
elseif rfidtag == 'fdx' then -- I'm not sure why you would need to bruteforce this ¯\_(ツ)_/¯
consolecommand = 'lf fdx sim'
rfidtagname = 'FDX-B'
facilityrequired = 1
elseif rfidtag == 'jablotron' then
consolecommand = 'lf jablotron sim'
rfidtagname = 'Jablotron'
facilityrequired = 0
elseif rfidtag == 'noralsy' then
consolecommand = 'lf noralsy sim'
rfidtagname = 'Noralsy'
facilityrequired = 0
elseif rfidtag == 'presco' then
consolecommand = 'lf presco sim d'
rfidtagname = 'Presco'
facilityrequired = 0
elseif rfidtag == 'visa2000' then
consolecommand = 'lf visa2000 sim'
rfidtagname = 'Visa2000'
facilityrequired = 0
elseif rfidtag == '14a' then
consolecommand = 'hf 14a sim'
if facility == '1' then rfidtagname = 'MIFARE Classic' -- Here we use the -f option to read the 14a type instead of the facility code
elseif facility == '2' then rfidtagname = 'MIFARE Ultralight'
elseif facility == '3' then rfidtagname = 'MIFARE Desfire'
elseif facility == '4' then rfidtagname = 'ISO/IEC 14443-4'
elseif facility == '5' then rfidtagname = 'MIFARE Tnp3xxx'
else
print('Invalid 14a type (-f) supplied. Must be 1-5')
print(usage)
return
end
facilityrequired = 0 -- Disable the FC required check, as we used it for type instead of FC
elseif rfidtag == 'hid' then
consolecommand = 'lf hid sim'
rfidtagname = 'HID'
facilityrequired = 1
else -- Display error and exit out if bad RFID tag was supplied
print('Invalid rfid tag (-r) supplied')
print(usage)
return
end
if isempty(baseid) then -- Display error and exit out if no starting id is set
print('You must supply the flag -b (base id)')
print(usage)
return
end
if isempty(count) then -- Display error and exit out of no count is set
print('You must supply the flag -c (count)')
print(usage)
return
end
if facilityrequired == 1 then -- If FC is required
facilitymessage = ' - Facility Code: ' -- Add FC to status message
if isempty(facility) then -- If FC was left blank, display warning and set FC to 0
print('Using 0 for the facility code as -f was not supplied')
facility = 0
end
else -- If FC is not required
facility = '' -- Clear FC
facilitymessage = '' -- Remove FC from status message
end
if isempty(timeout) then -- If timeout was not supplied, show warning and set timeout to 0
print('Using 0 for the timeout as -t was not supplied')
timeout = 0
end
if isempty(direction) then -- If direction was not supplied, show warning and set direction to down
print("Using down for direction as -d was not supplied")
direction = 'down'
end
if tonumber(count) < 1 then
print('Count -c must be set to 1 or higher')
return
else
count = count -1 -- Make our count accurate by removing 1, because math
end
if direction == 'down' then -- If counting down, set up our for loop to count down
endid = baseid - count
fordirection = -1
elseif direction == 'up' then -- If counting up, set our for loop to count up
endid = baseid + count
fordirection = 1
else -- If invalid direction was set, show warning and set up our for loop to count down
print('Invalid direction (-d) supplied, using down')
endid = baseid - count
fordirection = -1
end
-- display status message
print('')
print('BruteForcing '..rfidtagname..''..facilitymessage..''..facility..' - CardNumber Start: '..baseid..' - CardNumber End: '..endid..' - TimeOut: '..timeout)
print("")
-- loop through for each count (-c)
for cardnum = baseid, endid, fordirection do
-- If rfid tag is set to HID, convert card to HEX using the stolen code above
if rfidtag == 'hid' then cardnum = cardHex(cardnum, facility) end
-- send command to proxmark
core.console(consolecommand..' '..facility..' '..cardnum)
if timeout == 'pause' then
print('Press enter to continue ...')
io.read()
else
os.execute('sleep '..timeout..'')
end
end
-- ping the proxmark to stop emulation and see if its still responding
core.console('hw ping')
end
main(args)

View file

@ -0,0 +1,178 @@
local bin = require('bin')
local getopt = require('getopt')
local lib14a = require('read14a')
local utils = require('utils')
copyright = ''
author = "Iceman"
version = 'v1.0.0'
desc = [[
This script calculates mifare keys based on uid diversification for DI.
Algo not found by me.
]]
example = [[
-- if called without, it reads tag uid
script run calc_di
--
script run calc_di -u 11223344556677
]]
usage = [[
script run calc_di -h -u <uid>
Arguments:
-h : this help
-u <UID> : UID
]]
local DEBUG = true
local BAR = '286329204469736E65792032303133'
local MIS = '0A14FD0507FF4BCD026BA83F0A3B89A9'
local bxor = bit32.bxor
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR: ', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
-- Exit message
local function exitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
---
-- dumps all keys to file
local function dumptofile(keys)
dbg('dumping keys to file')
if utils.confirm('Do you wish to save the keys to dumpfile?') then
local destination = utils.input('Select a filename to store to', 'dumpkeys.bin')
local file = io.open(destination, 'wb')
if file == nil then
print('Could not write to file ', destination)
return
end
-- Mifare Mini has 5 sectors,
local key_a = ''
local key_b = ''
for sector = 0, #keys do
local keyA, keyB = unpack(keys[sector])
key_a = key_a .. bin.pack('H', keyA);
key_b = key_b .. bin.pack('H', keyB);
end
file:write(key_a)
file:write(key_b)
file:close()
end
end
---
-- create key
local function keygen(uid)
local data = MIS..uid..BAR
local hash = utils.ConvertAsciiToBytes(utils.Sha1Hex(data))
return string.format("%02X%02X%02X%02X%02X%02X",
hash[3+1],
hash[2+1],
hash[1+1],
hash[0+1],
hash[7+1],
hash[6+1]
)
end
---
-- print keys
local function printKeys(keys)
print('|---|----------------|---|----------------|---|')
print('|sec|key A |res|key B |res|')
print('|---|----------------|---|----------------|---|')
for sector = 0, #keys do
local keyA, keyB = unpack(keys[sector])
print(('|%03d| %s | %s | %s | %s |'):format(sector, keyA, 1, keyB, 1))
end
print('|---|----------------|---|----------------|---|')
end
---
-- createfull set of keys
local function createKeys(uid)
local key = keygen(uid)
local k = {}
for i = 0,4 do
k[i] = { key, key }
end
return k
end
---
-- main
local function main(args)
print( string.rep('==', 30) )
print()
local uid
local useUID = false
-- Arguments for the script
for o, a in getopt.getopt(args, 'hu:') do
if o == 'h' then return help() end
if o == 'u' then uid = a; useUID = true end
end
if useUID then
-- uid string checks if supplied
if uid == nil then return oops('empty uid string') end
if #uid == 0 then return oops('empty uid string') end
if #uid ~= 14 then return oops('uid wrong length. Should be 7 hex bytes') end
else
-- GET TAG UID
local tag, err = lib14a.read(false, true)
if not tag then return oops(err) end
core.clearCommandBuffer()
-- simple tag check
if 0x09 ~= tag.sak then
if 0x4400 ~= tag.atqa then
return oops(('[!] found tag %s :: looking for Mifare Mini 0.3k'):format(tag.name))
end
end
uid = tag.uid
end
print('|UID|', uid)
local keys, err = createKeys( uid )
printKeys( keys )
dumptofile( keys )
end
main(args)

View file

@ -0,0 +1,180 @@
local bin = require('bin')
local getopt = require('getopt')
local lib14a = require('read14a')
local utils = require('utils')
copyright = ''
author = "Iceman"
version = 'v1.0.0'
desc = [[
This script calculates mifare Ultralight-EV1 pwd based on uid diversification for an Italian ticketsystem
Algo not found by me.
]]
example =[[
-- if called without, it reads tag uid
script run calc_ev1_it
--
script run calc_ev1_it -u 11223344556677
]]
usage = [[
script run calc_ev1_it -h -u <uid> "
Arguments:
-h : this help
-u <UID> : UID
]]
local DEBUG = true
local bxor = bit32.bxor
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR: ', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print("Example usage")
print(example)
print(usage)
end
--
-- Exit message
local function exitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local _xortable = {
--[[ position, 4byte xor
--]]
{"00","4f2711c1"},
{"01","07D7BB83"},
{"02","9636EF07"},
{"03","B5F4460E"},
{"04","F271141C"},
{"05","7D7BB038"},
{"06","636EF871"},
{"07","5F4468E3"},
{"08","271149C7"},
{"09","D7BB0B8F"},
{"0A","36EF8F1E"},
{"0B","F446863D"},
{"0C","7114947A"},
{"0D","7BB0B0F5"},
{"0E","6EF8F9EB"},
{"0F","44686BD7"},
{"10","11494fAF"},
{"11","BB0B075F"},
{"12","EF8F96BE"},
{"13","4686B57C"},
{"14","1494F2F9"},
{"15","B0B07DF3"},
{"16","F8F963E6"},
{"17","686B5FCC"},
{"18","494F2799"},
{"19","0B07D733"},
{"1A","8F963667"},
{"1B","86B5F4CE"},
{"1C","94F2719C"},
{"1D","B07D7B38"},
{"1E","F9636E70"},
{"1F","6B5F44E0"},
}
local function findEntryByUid( uid )
-- xor UID4,UID5,UID6,UID7
-- mod 0x20 (dec 32)
local pos = (bxor(uid[4], uid[5], uid[6], uid[7])) % 32
-- convert to hexstring
pos = string.format('%02X', pos)
for k, v in pairs(_xortable) do
if ( v[1] == pos ) then
return utils.ConvertHexToBytes(v[2])
end
end
return nil
end
---
-- create pwd
local function pwdgen(uid)
-- PWD CALC
-- PWD0 = T0 xor B xor C xor D
-- PWD1 = T1 xor A xor C xor E
-- PWD2 = T2 xor A xor B xor F
-- PWD3 = T3 xor G
local uidbytes = utils.ConvertHexToBytes(uid)
local entry = findEntryByUid(uidbytes)
if entry == nil then return nil, "Can't find a xor entry" end
local pwd0 = bxor( entry[1], uidbytes[2], uidbytes[3], uidbytes[4])
local pwd1 = bxor( entry[2], uidbytes[1], uidbytes[3], uidbytes[5])
local pwd2 = bxor( entry[3], uidbytes[1], uidbytes[2], uidbytes[6])
local pwd3 = bxor( entry[4], uidbytes[7])
return string.format('%02X%02X%02X%02X', pwd0, pwd1, pwd2, pwd3)
end
--
-- main
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local uid = '04111211121110'
local useUID = false
-- Arguments for the script
for o, a in getopt.getopt(args, 'hu:') do
if o == 'h' then return help() end
if o == 'u' then uid = a; useUID = true end
end
if useUID then
-- uid string checks
if uid == nil then return oops('empty uid string') end
if #uid == 0 then return oops('empty uid string') end
if #uid ~= 14 then return oops('uid wrong length. Should be 7 hex bytes') end
else
-- GET TAG UID
local tag, err = lib14a.read(false, true)
if not tag then return oops(err) end
core.clearCommandBuffer()
uid = tag.uid
end
print('UID | '..uid)
local pwd, err = pwdgen(uid)
if not pwd then return ooops(err) end
print(string.format('PWD | %s', pwd))
end
main(args)

View file

@ -0,0 +1,200 @@
local bin = require('bin')
local getopt = require('getopt')
local lib14a = require('read14a')
local utils = require('utils')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This script calculates mifare keys based on uid diversification for mizip.
Algo not found by me.
]]
example = [[
-- if called without, it reads tag uid
script run calc_mizip
--
script run calc_mizip -u 11223344
]]
usage = [[
script run calc_mizip -h -u <uid>
Arguments:
-h : this help
-u <UID> : UID
]]
local DEBUG = true
local bxor = bit32.bxor
local _xortable = {
--[[ sector key A/B, 6byte xor
--]]
{1, '09125a2589e5', 'F12C8453D821'},
{2, 'AB75C937922F', '73E799FE3241'},
{3, 'E27241AF2C09', 'AA4D137656AE'},
{4, '317AB72F4490', 'B01327272DFD'},
}
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR: ', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print("Example usage")
print(example)
print(usage)
end
--
-- Exit message
local function exitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
--
-- dumps all keys to file
local function dumptofile(keys)
dbg('dumping keys to file')
if utils.confirm('Do you wish to save the keys to dumpfile?') then
local destination = utils.input('Select a filename to store to', 'dumpkeys.bin')
local file = io.open(destination, 'wb')
if file == nil then
print('Could not write to file ', destination)
return
end
-- Mifare Mini has 5 sectors,
local key_a = ''
local key_b = ''
for sector = 0, #keys do
local keyA, keyB = unpack(keys[sector])
key_a = key_a .. bin.pack('H', keyA);
key_b = key_b .. bin.pack('H', keyB);
end
file:write(key_a)
file:write(key_b)
file:close()
end
end
---
-- key bytes to string
local function keyStr(p1, p2, p3, p4, p5, p6)
return string.format('%02X%02X%02X%02X%02X%02X',p1, p2, p3, p4, p5, p6)
end
---
-- create key
local function calckey(uid, xorkey, keytype)
local p1,p2,p3,p4,p5,p6
if keytype == 'A' then
p1 = bxor( uid[1], xorkey[1])
p2 = bxor( uid[2], xorkey[2])
p3 = bxor( uid[3], xorkey[3])
p4 = bxor( uid[4], xorkey[4])
p5 = bxor( uid[1], xorkey[5])
p6 = bxor( uid[2], xorkey[6])
else
p1 = bxor( uid[3], xorkey[1])
p2 = bxor( uid[4], xorkey[2])
p3 = bxor( uid[1], xorkey[3])
p4 = bxor( uid[2], xorkey[4])
p5 = bxor( uid[3], xorkey[5])
p6 = bxor( uid[4], xorkey[6])
end
return keyStr(p1,p2,p3,p4,p5,p6)
end
---
-- print keys
local function printKeys(keys)
print('|---|----------------|---|----------------|---|')
print('|sec|key A |res|key B |res|')
print('|---|----------------|---|----------------|---|')
for sector = 0, #keys do
local keyA, keyB = unpack(keys[sector])
print(('|%03d| %s | %s | %s | %s |'):format(sector, keyA, 1, keyB, 1))
end
print('|---|----------------|---|----------------|---|')
end
---
-- create a full set of keys
local function createKeys(uid)
local uidbytes = utils.ConvertHexToBytes(uid)
local k = {}
k[0] = { keyStr(0xA0,0xA1,0xA2,0xA3,0xA4,0xA5), keyStr(0xB4,0xC1,0x32,0x43,0x9e,0xef) }
for _, v in pairs(_xortable) do
local keyA = calckey(uidbytes, utils.ConvertHexToBytes(v[2]), 'A')
local keyB = calckey(uidbytes, utils.ConvertHexToBytes(v[3]), 'B')
k[v[1]] = { keyA, keyB }
end
return k
end
---
-- main
local function main(args)
print( string.rep('==', 30) )
print()
local uid = '11223344'
local useUID = false
-- Arguments for the script
for o, a in getopt.getopt(args, 'hu:') do
if o == 'h' then return help() end
if o == 'u' then uid = a ; useUID = true end
end
if useUID then
-- uid string checks
if uid == nil then return oops('empty uid string') end
if #uid == 0 then return oops('empty uid string') end
if #uid ~= 8 then return oops('uid wrong length. Should be 4 hex bytes') end
else
-- GET TAG UID
local tag, err = lib14a.read(false, true)
if not tag then return oops(err) end
core.clearCommandBuffer()
-- simple tag check
if 0x09 ~= tag.sak then
if 0x4400 ~= tag.atqa then
return oops(('[!] found tag %s :: looking for Mifare Mini 0.3k'):format(tag.name))
end
end
uid = tag.uid
end
print('|UID|', uid)
local keys, err = createKeys( uid )
printKeys( keys )
dumptofile( keys )
end
main(args)

View file

@ -0,0 +1,266 @@
local cmds = require('commands')
local getopt = require('getopt')
local lib14b = require('read14b')
local utils = require('utils')
local iso7816 = require('7816_error')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This is a script to communicate with a CALYSPO / 14443b tag using the '14b raw' commands
]]
example = [[
script run calypso -b 11223344
]]
usage = [[
script run calypso -h -b
Arguments:
h this helptext
b raw bytes to send
]]
--[[
This script communicates with /armsrc/iso14443b.c,
Check there for details about data format and how commands are interpreted on the
device-side.
]]
local function calypso_parse(result)
local r = Command.parse(result)
local len = r.arg2 * 2
r.data = string.sub(r.data, 0, len);
print('GOT:', r.data)
if r.arg1 == 0 then
return r, nil
end
return nil,nil
end
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR: ', err)
lib14b.disconnect()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- helper function, give current count of items in lua-table.
local function tablelen(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
---
-- helper function, gives a sorted table from table t,
-- order can be a seperate sorting-order function.
local function spairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
---
-- Sends a usbpackage , "hf 14b raw"
-- if it reads the response, it converts it to a lua object "Command" first and the Data is cut to correct length.
local function calypso_send_cmd_raw(data, ignoreresponse )
local command, flags, result, err
flags = lib14b.ISO14B_COMMAND.ISO14B_RAW +
lib14b.ISO14B_COMMAND.ISO14B_APPEND_CRC
data = data or "00"
command = Command:newMIX{
cmd = cmds.CMD_HF_ISO14443B_COMMAND,
arg1 = flags,
arg2 = #data/2, -- LEN of data, half the length of the ASCII-string hex string
data = data} -- data bytes (commands etc)
result, err = command:sendMIX(ignoreresponse)
if result then
local r = calypso_parse(result)
return r, nil
end
return respone, err
end
---
-- calypso_card_num : Reads card number from ATR and
-- writes it in the tree in decimal format.
local function calypso_card_num(card)
if not card then return end
local card_num = tonumber( card.uid:sub(1,8),16 )
print('Card UID', card.uid)
print('Card Number', card_num)
end
---
-- analyse CALYPSO apdu status bytes.
local function calypso_apdu_status(apdu)
-- last two is CRC
-- next two is APDU status bytes.
local status = false
local mess = 'FAIL'
local sw = apdu:sub( #apdu-7, #apdu-4)
desc, err = iso7816.tostring(sw)
print ('SW', sw, desc, err )
status = ( sw == '9000' )
return status
end
local _calypso_cmds = {
-- Break down of command bytes:
-- A4 = select
-- Master File 3F00
-- 0x3F = master file
-- 0x00 = master file id, is constant to 0x00.
-- DF Dedicated File 38nn
-- can be seen as directories
-- 0x38
-- 0xNN id
-- ["01.Select ICC file"] = '0294 a4 080004 3f00 0002',
-- EF Elementary File
-- EF1 Pin file
-- EF2 Key file
-- Grey Lock file
-- Electronic deposit file
-- Electronic Purse file
-- Electronic Transaction log file
--['01.Select ICC file'] = '0294 a4 00 0002 3f00',
['01.Select ICC file'] = '0294 a4 080004 3f00 0002',
['02.ICC'] = '0394 b2 01 041d',
['03.Select EnvHol file'] = '0294 a4 080004 2000 2001',
['04.EnvHol1'] = '0394 b2 01 041d',
['05.Select EvLog file'] = '0294 a4 080004 2000 2010',
['06.EvLog1'] = '0394 b2 01 041d',
['07.EvLog2'] = '0294 b2 02 041d',
['08.EvLog3'] = '0394 b2 03 041d',
['09.Select ConList file']= '0294 a4 080004 2000 2050',
['10.ConList'] = '0394 b2 01 041d',
['11.Select Contra file'] = '0294 a4 080004 2000 2020',
['12.Contra1'] = '0394 b2 01 041d',
['13.Contra2'] = '0294 b2 02 041d',
['14.Contra3'] = '0394 b2 03 041d',
['15.Contra4'] = '0294 b2 04 041d',
['16.Select Counter file']= '0394 a4 080004 2000 2069',
['17.Counter'] = '0294 b2 01 041d',
['18.Select SpecEv file'] = '0394 a4 080004 2000 2040',
['19.SpecEv1'] = '0294 b2 01 041d',
}
---
-- The main entry point
function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local data, apdu, flags, uid, cid, result, err, card
-- Read the parameters
for o, a in getopt.getopt(args, 'h') do
if o == 'h' then return help() end
if o == 'b' then bytes = a end
end
lib14b.connect()
-- Select 14b tag.
card, err = lib14b.waitFor14443b()
if not card then return oops(err) end
calypso_card_num(card)
cid = card.cid
--[[
NAME VALUE APDU_POS
PCB 0x0A 0
CID 0x00 1
CLA 0x94 2
SELECT FILE 0xA4 3
READ FILE 0xB2 3
P1 4
P2 5
LEN_
0 1 2 3 4 5 6 7
apdu = '02 94 a4 08 00 04 3f 00 00 02' --select ICC file
DF_NAME = "1TIC.ICA"
--]]
--for i = 1,10 do
--result, err = calypso_send_cmd_raw('0294a40800043f000002',false) --select ICC file
for i, apdu in spairs(_calypso_cmds) do
print('>>', i )
apdu = apdu:gsub('%s+', '')
result, err = calypso_send_cmd_raw(apdu , false)
if result then
calypso_apdu_status(result.data)
print('<<', result.data )
else
print('<< no answer')
end
end
lib14b.disconnect()
end
---
-- a simple selftest function, tries to convert
function selftest()
DEBUG = true
dbg('Performing test')
dbg('Tests done')
end
-- Flip the switch here to perform a sanity check.
-- It read a nonce in two different ways, as specified in the usage-section
if '--test'==args then
selftest()
else
-- Call the main
main(args)
end

View file

@ -0,0 +1,16 @@
--[[
A sampe script file on how to implement at cmd line inteface.
--]]
print("This is how a cmd-line interface could be implemented\nPrint 'exit' to exit.\n")
local answer
repeat
io.write("$>")
io.flush()
answer = io.read()
if answer ~= 'exit' then
local func = assert(loadstring("return " .. answer))
io.write("\n"..tostring(func() or "").."\n");
end--]]
until answer == "exit"
print("Bye\n");

View file

@ -0,0 +1,628 @@
---
-- requirements
local cmds = require('commands')
local getopt = require('getopt')
local utils = require('utils')
local lib14a = require('read14a')
local json = require('dkjson')
local toys = require('default_toys_di')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This is a script to dump and decrypt the data of a specific type of Mifare Mini token.
The dump is decrypted. If a raw dump is wanted, use the -r parameter
]]
example = [[
script run didump
-- selftest
script run didump -t
-- Generate raw dump, into json.
script run didump -r
-- load file
script run didump -i dumpdata.json
]]
usage = [[
script run didump -h -t -r -d -e -v -i dumpdata.json
Arguments:
h this helptext
r raw
t selftest
d decrypt data
e encrypt data
v validate data
i dumpdata.json load json dump file
end
]]
-- Some shortcuts
local band = bit32.band
local bor = bit32.bor
local bnot = bit32.bnot
local bxor = bit32.bxor
local lsh = bit32.lshift
local rsh = bit32.rshift
-- Some globals
local PM3_SUCCESS = 0
local FOO = 'AF62D2EC0491968CC52A1A7165F865FE'
local BAR = '286329204469736E65792032303133'
local MIS = '0A14FD0507FF4BCD026BA83F0A3B89A9'
local outputTemplate = os.date("toydump_%Y-%m-%d_%H%M%S");
local TIMEOUT = 2000
local DEBUG = true
local numBlocks = 20
local numSectors = 5
local CHECKSUM_OFFSET = 12; -- +1???
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
print('###', args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR: ', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
--
local function print_info(tagdata)
--got table with data.
local h = tagdata[2]:sub(1,8)
local t = tostring( tonumber( h, 16 ) )
local item = toys.Find(t)
print( ("Modelid : %s , %s, v.%s.0"):format(t, item[3], item[2]))
end
---
-- Get checksum,
-- called: data is string (32 hex digits)
-- returns: number
local function getChecksum(data)
local chksum = data:sub(25,32)
return tonumber(chksum,16)
end
---
-- calculate checksum
-- called: data is bytes (24 hex digits)
-- returns: number
local function calculateChecksum(data)
-- Generate table
local _tbl = {}
_tbl[0] = { 0x0 }
_tbl[1] = { 0x77073096 }
_tbl[2] = { 0xEE0E612C }
_tbl[3] = { 0x990951BA }
_tbl[4] = { 0x76DC419 }
_tbl[5] = { 0x706AF48F }
_tbl[6] = { 0xE963A535 }
_tbl[7] = { 0x9E6495A3 }
_tbl[8] = { 0xEDB8832 }
_tbl[9] = { 0x79DCB8A4 }
_tbl[10] = { 0xE0D5E91E }
_tbl[11] = { 0x97D2D988 }
_tbl[12] = { 0x9B64C2B }
_tbl[13] = { 0x7EB17CBD }
_tbl[14] = { 0xE7B82D07 }
_tbl[15] = { 0x90BF1D91 }
_tbl[16] = { 0x1DB71064 }
_tbl[17] = { 0x6AB020F2 }
_tbl[18] = { 0xF3B97148 }
_tbl[19] = { 0x84BE41DE }
_tbl[20] = { 0x1ADAD47D }
_tbl[21] = { 0x6DDDE4EB }
_tbl[22] = { 0xF4D4B551 }
_tbl[23] = { 0x83D385C7 }
_tbl[24] = { 0x136C9856 }
_tbl[25] = { 0x646BA8C0 }
_tbl[26] = { 0xFD62F97A }
_tbl[27] = { 0x8A65C9EC }
_tbl[28] = { 0x14015C4F }
_tbl[29] = { 0x63066CD9 }
_tbl[30] = { 0xFA0F3D63 }
_tbl[31] = { 0x8D080DF5 }
_tbl[32] = { 0x3B6E20C8 }
_tbl[33] = { 0x4C69105E }
_tbl[34] = { 0xD56041E4 }
_tbl[35] = { 0xA2677172 }
_tbl[36] = { 0x3C03E4D1 }
_tbl[37] = { 0x4B04D447 }
_tbl[38] = { 0xD20D85FD }
_tbl[39] = { 0xA50AB56B }
_tbl[40] = { 0x35B5A8FA }
_tbl[41] = { 0x42B2986C }
_tbl[42] = { 0xDBBBC9D6 }
_tbl[43] = { 0xACBCF940 }
_tbl[44] = { 0x32D86CE3 }
_tbl[45] = { 0x45DF5C75 }
_tbl[46] = { 0xDCD60DCF }
_tbl[47] = { 0xABD13D59 }
_tbl[48] = { 0x26D930AC }
_tbl[49] = { 0x51DE003A }
_tbl[50] = { 0xC8D75180 }
_tbl[51] = { 0xBFD06116 }
_tbl[52] = { 0x21B4F4B5 }
_tbl[53] = { 0x56B3C423 }
_tbl[54] = { 0xCFBA9599 }
_tbl[55] = { 0xB8BDA50F }
_tbl[56] = { 0x2802B89E }
_tbl[57] = { 0x5F058808 }
_tbl[58] = { 0xC60CD9B2 }
_tbl[59] = { 0xB10BE924 }
_tbl[60] = { 0x2F6F7C87 }
_tbl[61] = { 0x58684C11 }
_tbl[62] = { 0xC1611DAB }
_tbl[63] = { 0xB6662D3D }
_tbl[64] = { 0x76DC4190 }
_tbl[65] = { 0x1DB7106 }
_tbl[66] = { 0x98D220BC }
_tbl[67] = { 0xEFD5102A }
_tbl[68] = { 0x71B18589 }
_tbl[69] = { 0x6B6B51F }
_tbl[70] = { 0x9FBFE4A5 }
_tbl[71] = { 0xE8B8D433 }
_tbl[72] = { 0x7807C9A2 }
_tbl[73] = { 0xF00F934 }
_tbl[74] = { 0x9609A88E }
_tbl[75] = { 0xE10E9818 }
_tbl[76] = { 0x7F6A0DBB }
_tbl[77] = { 0x86D3D2D }
_tbl[78] = { 0x91646C97 }
_tbl[79] = { 0xE6635C01 }
_tbl[80] = { 0x6B6B51F4 }
_tbl[81] = { 0x1C6C6162 }
_tbl[82] = { 0x856530D8 }
_tbl[83] = { 0xF262004E }
_tbl[84] = { 0x6C0695ED }
_tbl[85] = { 0x1B01A57B }
_tbl[86] = { 0x8208F4C1 }
_tbl[87] = { 0xF50FC457 }
_tbl[88] = { 0x65B0D9C6 }
_tbl[89] = { 0x12B7E950 }
_tbl[90] = { 0x8BBEB8EA }
_tbl[91] = { 0xFCB9887C }
_tbl[92] = { 0x62DD1DDF }
_tbl[93] = { 0x15DA2D49 }
_tbl[94] = { 0x8CD37CF3 }
_tbl[95] = { 0xFBD44C65 }
_tbl[96] = { 0x4DB26158 }
_tbl[97] = { 0x3AB551CE }
_tbl[98] = { 0xA3BC0074 }
_tbl[99] = { 0xD4BB30E2 }
_tbl[100] = { 0x4ADFA541 }
_tbl[101] = { 0x3DD895D7 }
_tbl[102] = { 0xA4D1C46D }
_tbl[103] = { 0xD3D6F4FB }
_tbl[104] = { 0x4369E96A }
_tbl[105] = { 0x346ED9FC }
_tbl[106] = { 0xAD678846 }
_tbl[107] = { 0xDA60B8D0 }
_tbl[108] = { 0x44042D73 }
_tbl[109] = { 0x33031DE5 }
_tbl[110] = { 0xAA0A4C5F }
_tbl[111] = { 0xDD0D7CC9 }
_tbl[112] = { 0x5005713C }
_tbl[113] = { 0x270241AA }
_tbl[114] = { 0xBE0B1010 }
_tbl[115] = { 0xC90C2086 }
_tbl[116] = { 0x5768B525 }
_tbl[117] = { 0x206F85B3 }
_tbl[118] = { 0xB966D409 }
_tbl[119] = { 0xCE61E49F }
_tbl[120] = { 0x5EDEF90E }
_tbl[121] = { 0x29D9C998 }
_tbl[122] = { 0xB0D09822 }
_tbl[123] = { 0xC7D7A8B4 }
_tbl[124] = { 0x59B33D17 }
_tbl[125] = { 0x2EB40D81 }
_tbl[126] = { 0xB7BD5C3B }
_tbl[127] = { 0xC0BA6CAD }
_tbl[128] = { 0xEDB88320 }
_tbl[129] = { 0x9ABFB3B6 }
_tbl[130] = { 0x3B6E20C }
_tbl[131] = { 0x74B1D29A }
_tbl[132] = { 0xEAD54739 }
_tbl[133] = { 0x9DD277AF }
_tbl[134] = { 0x4DB2615 }
_tbl[135] = { 0x73DC1683 }
_tbl[136] = { 0xE3630B12 }
_tbl[137] = { 0x94643B84 }
_tbl[138] = { 0xD6D6A3E }
_tbl[139] = { 0x7A6A5AA8 }
_tbl[140] = { 0xE40ECF0B }
_tbl[141] = { 0x9309FF9D }
_tbl[142] = { 0xA00AE27 }
_tbl[143] = { 0x7D079EB1 }
_tbl[144] = { 0xF00F9344 }
_tbl[145] = { 0x8708A3D2 }
_tbl[146] = { 0x1E01F268 }
_tbl[147] = { 0x6906C2FE }
_tbl[148] = { 0xF762575D }
_tbl[149] = { 0x806567CB }
_tbl[150] = { 0x196C3671 }
_tbl[151] = { 0x6E6B06E7 }
_tbl[152] = { 0xFED41B76 }
_tbl[153] = { 0x89D32BE0 }
_tbl[154] = { 0x10DA7A5A }
_tbl[155] = { 0x67DD4ACC }
_tbl[156] = { 0xF9B9DF6F }
_tbl[157] = { 0x8EBEEFF9 }
_tbl[158] = { 0x17B7BE43 }
_tbl[159] = { 0x60B08ED5 }
_tbl[160] = { 0xD6D6A3E8 }
_tbl[161] = { 0xA1D1937E }
_tbl[162] = { 0x38D8C2C4 }
_tbl[163] = { 0x4FDFF252 }
_tbl[164] = { 0xD1BB67F1 }
_tbl[165] = { 0xA6BC5767 }
_tbl[166] = { 0x3FB506DD }
_tbl[167] = { 0x48B2364B }
_tbl[168] = { 0xD80D2BDA }
_tbl[169] = { 0xAF0A1B4C }
_tbl[170] = { 0x36034AF6 }
_tbl[171] = { 0x41047A60 }
_tbl[172] = { 0xDF60EFC3 }
_tbl[173] = { 0xA867DF55 }
_tbl[174] = { 0x316E8EEF }
_tbl[175] = { 0x4669BE79 }
_tbl[176] = { 0xCB61B38C }
_tbl[177] = { 0xBC66831A }
_tbl[178] = { 0x256FD2A0 }
_tbl[179] = { 0x5268E236 }
_tbl[180] = { 0xCC0C7795 }
_tbl[181] = { 0xBB0B4703 }
_tbl[182] = { 0x220216B9 }
_tbl[183] = { 0x5505262F }
_tbl[184] = { 0xC5BA3BBE }
_tbl[185] = { 0xB2BD0B28 }
_tbl[186] = { 0x2BB45A92 }
_tbl[187] = { 0x5CB36A04 }
_tbl[188] = { 0xC2D7FFA7 }
_tbl[189] = { 0xB5D0CF31 }
_tbl[190] = { 0x2CD99E8B }
_tbl[191] = { 0x5BDEAE1D }
_tbl[192] = { 0x9B64C2B0 }
_tbl[193] = { 0xEC63F226 }
_tbl[194] = { 0x756AA39C }
_tbl[195] = { 0x26D930A }
_tbl[196] = { 0x9C0906A9 }
_tbl[197] = { 0xEB0E363F }
_tbl[198] = { 0x72076785 }
_tbl[199] = { 0x5005713 }
_tbl[200] = { 0x95BF4A82 }
_tbl[201] = { 0xE2B87A14 }
_tbl[202] = { 0x7BB12BAE }
_tbl[203] = { 0xCB61B38 }
_tbl[204] = { 0x92D28E9B }
_tbl[205] = { 0xE5D5BE0D }
_tbl[206] = { 0x7CDCEFB7 }
_tbl[207] = { 0xBDBDF21 }
_tbl[208] = { 0x86D3D2D4 }
_tbl[209] = { 0xF1D4E242 }
_tbl[210] = { 0x68DDB3F8 }
_tbl[211] = { 0x1FDA836E }
_tbl[212] = { 0x81BE16CD }
_tbl[213] = { 0xF6B9265B }
_tbl[214] = { 0x6FB077E1 }
_tbl[215] = { 0x18B74777 }
_tbl[216] = { 0x88085AE6 }
_tbl[217] = { 0xFF0F6A70 }
_tbl[218] = { 0x66063BCA }
_tbl[219] = { 0x11010B5C }
_tbl[220] = { 0x8F659EFF }
_tbl[221] = { 0xF862AE69 }
_tbl[222] = { 0x616BFFD3 }
_tbl[223] = { 0x166CCF45 }
_tbl[224] = { 0xA00AE278 }
_tbl[225] = { 0xD70DD2EE }
_tbl[226] = { 0x4E048354 }
_tbl[227] = { 0x3903B3C2 }
_tbl[228] = { 0xA7672661 }
_tbl[229] = { 0xD06016F7 }
_tbl[230] = { 0x4969474D }
_tbl[231] = { 0x3E6E77DB }
_tbl[232] = { 0xAED16A4A }
_tbl[233] = { 0xD9D65ADC }
_tbl[234] = { 0x40DF0B66 }
_tbl[235] = { 0x37D83BF0 }
_tbl[236] = { 0xA9BCAE53 }
_tbl[237] = { 0xDEBB9EC5 }
_tbl[238] = { 0x47B2CF7F }
_tbl[239] = { 0x30B5FFE9 }
_tbl[240] = { 0xBDBDF21C }
_tbl[241] = { 0xCABAC28A }
_tbl[242] = { 0x53B39330 }
_tbl[243] = { 0x24B4A3A6 }
_tbl[244] = { 0xBAD03605 }
_tbl[245] = { 0xCDD70693 }
_tbl[246] = { 0x54DE5729 }
_tbl[247] = { 0x23D967BF }
_tbl[248] = { 0xB3667A2E }
_tbl[249] = { 0xC4614AB8 }
_tbl[250] = { 0x5D681B02 }
_tbl[251] = { 0x2A6F2B94 }
_tbl[252] = { 0xB40BBE37 }
_tbl[253] = { 0xC30C8EA1 }
_tbl[254] = { 0x5A05DF1B }
_tbl[255] = { 0x2D02EF8D }
-- Calculate it
local ret = 0
for i,item in pairs(data) do
local tmp = band(ret, 0xFF)
local index = band( bxor(tmp, item), 0xFF)
ret = bxor(rsh(ret,8), _tbl[index][1])
end
return ret
end
---
-- update checksum
-- called: data is string, ( >= 24 hex digits )
-- returns: string, (data concat new checksum)
local function updateChecksum(data)
local part = data:sub(1,24)
local chksum = calculateChecksum( utils.ConvertHexToBytes(part))
return string.format("%s%X", part, chksum)
end
---
--
local function keygen(uid)
local data = MIS..uid..BAR
local hash = utils.ConvertAsciiToBytes(utils.Sha1Hex(data))
return string.format("%02X%02X%02X%02X%02X%02X",
hash[3+1],
hash[2+1],
hash[1+1],
hash[0+1],
hash[7+1],
hash[6+1]
)
end
--- encode 'table' into a json formatted string
--
local function convert_to_json( obj )
if type(obj) == "table" then
return json.encode (obj, { indent = true })
end
return oops('[fail] input object must be a lua-TABLE')
end
--
-- Save
local function save_json(filename, data)
jsondata = convert_to_json(data)
filename = filename or 'dumpdata.json'
local f = io.open(filename, "w")
if not f then return oops(string.format("Could not write to file %s", tostring(filename))) end
f:write(jsondata)
io.close(f)
return filename
end
--- loads a json formatted text file with
--
-- @param filename the file containing the json-dump (defaults to dumpdata.json)
local function load_json(filename)
filename = filename or 'dumpdata.json'
local f = io.open(filename, "rb")
if not f then return oops(string.format("Could not read file %s", tostring(filename))) end
-- Read file
local t = f:read("*all")
io.close(f)
local obj, pos, err = json.decode(t, 1, nil)
if err then return oops(string.format("importing json file failed. %s", err)) end
dbg(string.format('loaded file %s', input))
return obj
-- local len, hex = bin.unpack( ("H%d"):format(#t), t)
end
---
-- Generate encryption key
local function create_key(uid)
local key = ''
local sha = utils.Sha1Hex( FOO..BAR..uid )
sha = utils.ConvertBytesToHex( utils.ConvertAsciiToBytes(sha:sub(1,16)) )
key = utils.SwapEndiannessStr( sha:sub(1,8) , 32 )
key = key..utils.SwapEndiannessStr( sha:sub(9,16), 32 )
key = key..utils.SwapEndiannessStr( sha:sub(17,24), 32 )
key = key..utils.SwapEndiannessStr( sha:sub(25,32), 32 )
return key
end
---
-- decode response and get the blockdata from a normal mifare read command
local function getblockdata(response)
if not response then
return nil, 'No response from device'
end
if response.Status == PM3_SUCCESS then
return response.Data
else
return nil, "Couldn't read block.. ["..response.Status.."]"
end
end
local function readblock( blockno, key )
-- Read block N
local keytype = '00'
local data = ('%02x%s%s'):format(blockno, keytype, key)
local c = Command:newNG{cmd = cmds.CMD_HF_MIFARE_READBL, data = data}
local b, err = getblockdata(c:sendNG(false))
if not b then return oops(err) end
return b
end
--- reads all blocks from tag
--
local function readtag(mfkey, aeskey )
local tagdata = {}
for blockNo = 0, numBlocks-1 do
if core.kbd_enter_pressed() then
print("[fail] aborted by user")
return nil
end
-- read block from tag.
local blockdata = readblock(blockNo, mfkey)
if not blockdata then return oops('[!] failed reading block') end
-- rules:
-- the following blocks is NOT encrypted
-- block 0 (manufacturing) and 18
-- block with all zeros
-- sector trailor
if blockNo == 0 or blockNo == 18 then
elseif blockNo%4 ~= 3 then
if not string.find(blockdata, '^0+$') then
if aeskey then
local decrypted, err = core.aes128_decrypt_ecb(aeskey, blockdata)
if err then dbg(err) end
blockdata = utils.ConvertAsciiToHex(decrypted)
end
end
else
-- Sectorblocks, not encrypted, but we add our known key to it since it is normally zeros.
blockdata = mfkey..blockdata:sub(13,20)..mfkey
end
table.insert(tagdata, blockdata)
end
return tagdata
end
---
-- simple selftest of functionality
local function selftest()
local testdata = '000F42430D0A14000001D11F'..'5D738517'
local chksum = getChecksum(testdata)
local calc = calculateChecksum( utils.ConvertHexToBytes(testdata:sub(1,24)))
print ( testdata:sub(1,24) )
print ( ('%x - %x'):format(chksum, calc))
local isValid = false
local validStr = "FAIL"
if calc == chksum then
isValid = true
validStr = "OK"
end
local newtestdata = updateChecksum(testdata)
local revalidated = "FAIL"
if newtestdata == testdata then
revalidated = "OK"
end
print ('TESTDATA :: '..testdata)
print ('DATA :: '..testdata:sub(1,24))
print (('VALID CHKSUM :: %s'):format(validStr ))
print (('UPDATE CHKSUM :: %s'):format(revalidated))
local testkey = keygen('0456263a873a80')
print ('TEST KEY :: '..testkey)
print ('VALID KEY :: 29564af75805')
end
local function setdevicedebug( status )
local c = 'hw dbg '
if status then
c = c..'1'
else
c = c..'0'
end
core.console(c)
end
---
-- The main entry point
-- -d decrypt
-- -e encrypt
-- -v validate
function main(args)
local cmd, tag, err, blockNo, mfkey
local shall_validate = false
local shall_dec = false
local shall_enc = false
local blocks = {}
local aeskey = ''
local input = ''
-- Read the parameters
for o, a in getopt.getopt(args, 'htdevi:') do
if o == 'h' then help() return end
if o == 't' then return selftest() end
if o == 'd' then shall_dec = true end
if o == 'e' then shall_enc = true end
if o == 'v' then shall_validate = true end
if o == 'i' then input = load_json(a) end
end
-- Turn off Debug
setdevicedebug(false)
-- GET TAG UID
tag, err = lib14a.read(false, true)
if err then
lib14a.disconnect()
return oops(err)
end
core.clearCommandBuffer()
-- simple tag check
if 0x09 ~= tag.sak then
if 0x4400 ~= tag.atqa then
return oops(('[fail] found tag %s :: looking for Mifare Mini 0.3k'):format(tag.name))
end
end
dbg ('[ok] found '..tag.name)
-- tag key
mfkey = keygen(tag.uid)
dbg('[ok] using mf keyA : '.. mfkey)
-- AES key
aeskey = create_key(tag.uid)
dbg('[ok] using AES key : '.. aeskey)
-- read tag data, complete, enc/dec
tagdata = readtag(mfkey, aeskey)
dbg('[ok] read card data')
-- show information?
print_info(tagdata)
-- save
res = save_json(nil, tagdata)
if not res then return oops('[fail] saving json file') end
dbg('[ok] read card data')
end
main(args)

View file

@ -0,0 +1,140 @@
-- The getopt-functionality is loaded from pm3/getopt.lua
-- Have a look there for further details
getopt = require('getopt')
bin = require('bin')
copyright = ''
author = "Martin Holst Swende \n @Marshmellow \n @iceman"
version = 'v1.0.1'
desc =[[
This script takes a dumpfile from 'hf mfu dump' and converts it to a format that can be used
by the emulator
]]
example = [[
script run dumptoemul-mfu -i dumpdata-foobar.bin
]]
usage = [[
script run dumptoemul-mfu [-i <file>] [-o <file>]
Arguments:
-h This help
-i <file> Specifies the dump-file (input). If omitted, 'dumpdata.bin' is used
-o <filename> Specifies the output file. If omitted, <uid>.eml is used.
]]
local DEBUG = false
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
local function convert_to_ascii(hexdata)
if string.len(hexdata) % 8 ~= 0 then
return oops(("Bad data, length should be a multiple of 8 (was %d)"):format(string.len(hexdata)))
end
local js,i = "[";
for i = 1, string.len(hexdata),8 do
js = js .."'" ..string.sub(hexdata,i,i+7).."',\n"
end
js = js .. "]"
return js
end
local function readdump(infile)
t = infile:read('*all')
len = string.len(t)
local len,hex = bin.unpack(('H%d'):format(len),t)
return hex
end
local function convert_to_emulform(hexdata)
if string.len(hexdata) % 8 ~= 0 then
return oops(('Bad data, length should be a multiple of 8 (was %d)'):format(string.len(hexdata)))
end
local ascii,i = '';
for i = 1, string.len(hexdata), 8 do
ascii = ascii..string.sub(hexdata, i, i+7)..'\n'
end
return string.sub(ascii, 1, -2)
end
local function main(args)
local input = 'dumpdata.bin'
local output
for o, a in getopt.getopt(args, 'i:o:h') do
if o == 'h' then return help() end
if o == 'i' then input = a end
if o == 'o' then output = a end
end
-- Validate the parameters
local infile = io.open(input, 'rb')
if infile == nil then
return oops('Could not read file ', input)
end
local dumpdata = readdump(infile)
-- The hex-data is now in ascii-format,
-- But first, check the uid
-- lua uses start index and endindex, not count.
-- UID is 3three skip bcc0 then 4bytes.
-- 1 lua is one-index.
-- 1 + 112 (56*2) new dump format has version/signature/counter data here
-- 113,114,115,116,117,118 UID first three bytes
-- 119,120 bcc0
-- 121--- UID last four bytes
local uid = string.sub(dumpdata, 113, 113+5)..string.sub(dumpdata, 113+8, 113+8+7)
output = output or (uid .. '.eml')
-- Format some linebreaks
dumpdata = convert_to_emulform(dumpdata)
local outfile = io.open(output, 'w')
if outfile == nil then
return oops('Could not write to file ', output)
end
outfile:write(dumpdata:lower())
io.close(outfile)
print(('Wrote an emulator-dump to the file %s'):format(output))
end
--[[
In the future, we may implement so that scripts are invoked directly
into a 'main' function, instead of being executed blindly. For future
compatibility, I have done so, but I invoke my main from here.
--]]
main(args)

View file

@ -0,0 +1,142 @@
-- The getopt-functionality is loaded from pm3/getopt.lua
-- Have a look there for further details
getopt = require('getopt')
bin = require('bin')
copyright = ''
author = 'Martin Holst Swende'
version = 'v1.0.1'
desc = [[
This script takes a dumpfile from 'hf mf dump' and converts it to a format that can be used
by the emulator
]]
example = [[
script run dumptoemul -i dumpdata-foobar.bin
]]
usage = [[
_script run dumptoemul [-i <file>] [-o <file>]
Arguments:
-h This help
-i <file> Specifies the dump-file (input). If omitted, 'dumpdata.bin' is used
-o <filename> Specifies the output file. If omitted, <uid>.eml is used.
]]
local DEBUG = false
-------------------------------
-- Some utilities
-------------------------------
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
local function convert_to_ascii(hexdata)
if string.len(hexdata) % 32 ~= 0 then
return oops(('Bad data, length should be a multiple of 32 (was %d)'):format(string.len(hexdata)))
end
local js,i = '[';
for i = 1, string.len(hexdata),32 do
js = js .."'" ..string.sub(hexdata,i,i+31).."',\n"
end
js = js .. ']'
return js
end
local function readdump(infile)
t = infile:read('*all')
len = string.len(t)
local len,hex = bin.unpack(('H%d'):format(len),t)
return hex
end
local function convert_to_emulform(hexdata)
if string.len(hexdata) % 32 ~= 0 then
return oops(('Bad data, length should be a multiple of 32 (was %d)'):format(string.len(hexdata)))
end
local ascii,i = '';
for i = 1, string.len(hexdata),32 do
ascii = ascii..string.sub(hexdata,i,i+31)..'\n'
end
return string.sub(ascii, 1, -2)
end
local function main(args)
local input = 'dumpdata.bin'
local output
for o, a in getopt.getopt(args, 'i:o:h') do
if o == 'h' then return help() end
if o == 'i' then input = a end
if o == 'o' then output = a end
end
-- Validate the parameters
local infile = io.open(input, 'rb')
if infile == nil then
return oops('Could not read file ', input)
end
local dumpdata = readdump(infile)
-- The hex-data is now in ascii-format,
if dumpdata == NIL then return oops('Dumpfle not loaded') end
-- But first, check the uid
local uid = string.sub(dumpdata, 1, 8)
output = output or (uid .. '.eml')
-- Format some linebreaks
dumpdata = convert_to_emulform(dumpdata)
if dumpdata == NIL then return oops('Dumpfle not loaded') end
local outfile = io.open(output, 'w')
if outfile == nil then
return oops('Could not write to file ', output)
end
outfile:write(dumpdata:lower())
io.close(outfile)
print(('Wrote an emulator-dump to the file %s'):format(output))
end
--[[
In the future, we may implement so that scripts are invoked directly
into a 'main' function, instead of being executed blindly. For future
compatibility, I have done so, but I invoke my main from here.
--]]
main(args)

90
client/luascripts/e.lua Normal file
View file

@ -0,0 +1,90 @@
local getopt = require('getopt')
local utils = require('utils')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This script calculates many checksums (CRC) over the provided hex input.
]]
example = [[
script run e -b 010203040506070809
script run e -b 010203040506070809 -w 16
]]
usage = [[
Arguments:
-b data in hex
-w bitwidth of the CRC family of algorithm. <optional> defaults to all known CRC presets.
]]
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
-- The main entry point
function main(args)
local data
local width = 0
-- Read the parameters
for o, a in getopt.getopt(args, 'hb:w:') do
if o == 'h' then return help() end
if o == 'b' then data = a end
if o == 'w' then width = a end
end
data = data or '01020304'
width = width or 0
print( string.rep('-',60) )
print('Bit width of CRC | '..width)
print('Bytes | '..data)
print('')
print( ('%-20s| %-16s| %s'):format('Model','CRC', 'CRC reverse','bigEnd', 'bigEnd','little','little'))
print( string.rep('-',60) )
local lists, err = core.reveng_models(width)
if lists == nil then return oops(err) end
for _,i in pairs(lists) do
if string.len(i) > 1 then
local a1 = core.reveng_runmodel(i, data, false, '0')
local a2 = core.reveng_runmodel(i, data, true, '0')
local a3 = core.reveng_runmodel(i, data, false, 'b')
local a4 = core.reveng_runmodel(i, data, false, 'B')
local a5 = core.reveng_runmodel(i, data, false, 'l')
local a6 = core.reveng_runmodel(i, data, false, 'L')
print( ('%-20s| %-16s| %-16s| %-16s| %-16s| %-16s| %-16s'):format(i, a1:upper(), a2:upper(),a3:upper(),a4:upper(),a5:upper(),a6:upper() ) )
end
end
end
main(args)

View file

@ -0,0 +1,77 @@
local getopt = require('getopt')
local bin = require('bin')
local dumplib = require('html_dumplib')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc =[[
This script takes an dumpfile on EML (ASCII) format and converts it to the PM3 dumpbin file to be used with `hf mf restore`
]]
example =[[
1. script run emul2dump
2. script run emul2dump -i myfile.eml
3. script run emul2dump -i myfile.eml -o myfile.bin
]]
usage = [[
script run emul2dump [-i <file>] [-o <file>]
Arguments:
-h This help
-i <filename> Specifies the dump-file (input). If omitted, 'dumpdata.eml' is used
-o <filename> Specifies the output file. If omitted, <currdate>.bin is used.
]]
---
-- This is only meant to be used when errors occur
local function oops(err)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function main(args)
local input = 'dumpdata.eml'
local output = os.date('%Y-%m-%d_%H%M%S.bin');
-- Arguments for the script
for o, a in getopt.getopt(args, 'hi:o:') do
if o == 'h' then return help() end
if o == 'i' then input = a end
if o == 'o' then output = a end
end
local filename, err = dumplib.convert_eml_to_bin(input,output)
if err then return oops(err) end
ExitMsg(('Wrote a BIN dump to the file %s'):format(filename))
end
main(args)

View file

@ -0,0 +1,82 @@
-- The getopt-functionality is loaded from pm3/getopt.lua
-- Have a look there for further details
getopt = require('getopt')
bin = require('bin')
dumplib = require('html_dumplib')
copyright = ''
author = 'Martin Holst Swende'
version = 'v1.0.1'
desc = [[
This script takes a dumpfile on EML (ASCII) format and produces a html based dump, which is a
bit more easily analyzed.
]]
example = [[
script run emul2html -o dumpdata.eml
]]
usage = [[
script run htmldump [-i <file>] [-o <file>]
Arguments:
-h This help
-i <file> Specifies the dump-file (input). If omitted, 'dumpdata.eml' is used
-o <filename> Speciies the output file. If omitted, <curdate>.html is used.
]]
-- Some globals
local DEBUG = false -- the debug flag
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
local function main(args)
local input = 'dumpdata.eml'
local output = os.date('%Y-%m-%d_%H%M%S.html');
for o, a in getopt.getopt(args, 'i:o:h') do
if o == 'h' then return help() end
if o == 'i' then input = a end
if o == 'o' then output = a end
end
local filename, err = dumplib.convert_eml_to_html(input,output)
if err then return oops(err) end
print(('Wrote a HTML dump to the file %s'):format(filename))
end
--[[
In the future, we may implement so that scripts are invoked directly
into a 'main' function, instead of being executed blindly. For future
compatibility, I have done so, but I invoke my main from here.
--]]
main(args)

View file

@ -0,0 +1,216 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local lib14a = require('read14a')
local utils = require('utils')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This script will generate 'hf mf wrbl' commands for each block to format a Mifare card.
Alla datablocks gets 0x00
As default the script sets the keys A/B to 0xFFFFFFFFFFFF
and the access bytes will become 0x78,0x77,0x88
The GDB will become 0x00
The script will skip the manufactoring block 0.
]]
example = [[
-- generate commands
1. script run formatMifare
-- generate command, replacing key with new key.
2. script run formatMifare -k aabbccddeeff -n 112233445566 -a FF0780
-- generate commands and execute them against card.
3. script run formatMifare -x
]]
usage = [[
script run formatMifare -k <key> -n <key> -a <access> -x
Arguments:
-h - this help
-k <key> - the current six byte key with write access
-n <key> - the new key that will be written to the card
-a <access> - the new access bytes that will be written to the card
-x - execute the commands aswell.
]]
local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds
local DEBUG = true -- the debug flag
local CmdString = 'hf mf wrbl %d B %s %s'
local numBlocks = 64
local numSectors = 16
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
--
-- Read information from a card
function GetCardInfo()
result, err = lib14a.read(false, true)
if not result then
print(err)
return
end
print(('Found: %s'):format(result.name))
core.clearCommandBuffer()
if 0x18 == result.sak then -- NXP MIFARE Classic 4k | Plus 4k
-- IFARE Classic 4K offers 4096 bytes split into forty sectors,
-- of which 32 are same size as in the 1K with eight more that are quadruple size sectors.
numSectors = 40
elseif 0x08 == result.sak then -- NXP MIFARE CLASSIC 1k | Plus 2k
-- 1K offers 1024 bytes of data storage, split into 16 sector
numSectors = 16
elseif 0x09 == result.sak then -- NXP MIFARE Mini 0.3k
-- MIFARE Classic mini offers 320 bytes split into five sectors.
numSectors = 5
elseif 0x10 == result.sak then -- NXP MIFARE Plus 2k
numSectors = 32
elseif 0x01 == result.sak then -- NXP MIFARE TNP3xxx 1K
numSectors = 16
else
print("I don't know how many sectors there are on this type of card, defaulting to 16")
end
--[[
The mifare Classic 1k card has 16 sectors of 4 data blocks each.
The first 32 sectors of a mifare Classic 4k card consists of 4 data blocks and the remaining
8 sectors consist of 16 data blocks.
--]]
-- Defaults to 16 * 4 = 64 - 1 = 63
numBlocks = numSectors * 4 - 1
if numSectors > 32 then
numBlocks = 32*4+ (numSectors-32)*16 -1
end
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local OldKey, NewKey, Accessbytes
local x = false
-- Arguments for the script
for o, a in getopt.getopt(args, 'hk:n:a:x') do
if o == 'h' then return help() end
if o == 'k' then OldKey = a end
if o == 'n' then NewKey = a end
if o == 'a' then Accessbytes = a end
if o == 'x' then x = true end
end
-- validate input args.
OldKey = OldKey or 'FFFFFFFFFFFF'
if #(OldKey) ~= 12 then
return oops( string.format('Wrong length of write key (was %d) expected 12', #OldKey))
end
NewKey = NewKey or 'FFFFFFFFFFFF'
if #(NewKey) ~= 12 then
return oops( string.format('Wrong length of new key (was %d) expected 12', #NewKey))
end
--Accessbytes = Accessbytes or '787788'
Accessbytes = Accessbytes or 'FF0780'
if #(Accessbytes) ~= 6 then
return oops( string.format('Wrong length of accessbytes (was %d) expected 12', #Accessbytes))
end
GetCardInfo()
-- Show info
print( string.format('Estimating number of blocks: %d', numBlocks))
print( string.format('Old key: %s', OldKey))
print( string.format('New key: %s', NewKey))
print( string.format('New Access: %s', Accessbytes))
print( string.rep('--', 20) )
-- Set new block data
local EMPTY_BL = string.rep('00', 16)
local EMPTY_SECTORTRAIL = string.format('%s%s%s%s', NewKey, Accessbytes, '00', NewKey)
dbg( string.format('New sector-trailer : %s', EMPTY_SECTORTRAIL))
dbg( string.format('New emptyblock: %s', EMPTY_BL))
dbg('')
if x then
print('[Warning] you have used the EXECUTE parameter, which means this will run these commands against card.')
end
-- Ask
local dialogResult = utils.confirm('Do you want to erase this card')
if dialogResult == false then
return ExitMsg('Quiting it is then. Your wish is my command...')
end
print( string.rep('--', 20) )
-- main loop
for block = 0, numBlocks, 1 do
local reminder = (block+1) % 4
local cmd
if reminder == 0 then
cmd = CmdString:format(block, OldKey , EMPTY_SECTORTRAIL)
else
cmd = CmdString:format(block, OldKey , EMPTY_BL)
end
if block ~= 0 then
print(cmd)
if x then core.console(cmd) end
end
if core.kbd_enter_pressed() then
print('aborted by user')
break
end
end
end
main(args)

View file

@ -0,0 +1,18 @@
local reader = require('hf_reader')
local function main(args)
print("WORK IN PROGRESS - not expected to be functional yet")
info, err = reader.waitForTag()
if err then
print(err)
return
end
local k,v
print("Tag info")
for k,v in pairs(info) do
print(string.format(" %s : %s", tostring(k), tostring(v)))
end
return
end
main(args)

View file

@ -0,0 +1,83 @@
-- The getopt-functionality is loaded from pm3/getopt.lua
-- Have a look there for further details
getopt = require('getopt')
bin = require('bin')
dumplib = require('html_dumplib')
copyright = ''
author = 'Martin Holst Swende'
version = 'v1.0.1'
desc =[[
This script takes a dumpfile and produces a html based dump, which is a
bit more easily analyzed.
]]
example = [[
script run htmldump -o mifarecard_foo.html
]]
usage = [[
script run htmldump [-i <file>] [-o <file>]
Arguments:
-h This help
-i <file> Specifies the dump-file (input). If omitted, 'dumpdata.bin' is used
-o <filename> Speciies the output file. If omitted, <curtime>.html is used.
]]
-------------------------------
-- Some utilities
-------------------------------
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
local function main(args)
local input = 'dumpdata.bin'
local output = os.date('%Y-%m-%d_%H%M%S.html');
for o, a in getopt.getopt(args, 'i:o:h') do
if o == 'h' then return help() end
if o == 'i' then input = a end
if o == 'o' then output = a end
end
local filename, err = dumplib.convert_bin_to_html(input,output, 16)
if err then return oops(err) end
print(('Wrote a HTML dump to the file %s'):format(filename))
end
--[[
In the future, we may implement so that scripts are invoked directly
into a 'main' function, instead of being executed blindly. For future
compatibility, I have done so, but I invoke my main from here.
--]]
main(args)

View file

@ -0,0 +1,120 @@
local cmds = require('commands')
local lib15 = require('read15')
local getopt = require('getopt')
local utils = require('utils')
copyright = 'Copyright (c) 2018 IceSQL AB. All rights reserved.'
author = 'Christian Herrmann'
version = 'v1.0.5'
desc = [[
This script tries to set UID on a IS15693 SLIX magic card
Remember the UID ->MUST<- start with 0xE0
]]
example = [[
-- ISO15693 slix magic tag
script run iso15_magic -u E004013344556677
script run iso15_magic -u E004013344556677 -a
]]
usage = [[
script run iso15_magic -h -u <uid>
Arguments:
-h : this help
-u <UID> : UID (16 hexsymbols)
-a : use offical pm3 repo ISO15 commands instead of iceman fork.
]]
local DEBUG = true
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
--- Set UID on magic command enabled on a ICEMAN based REPO
local function magicUID_iceman(b0, b1)
print('Using backdoor Magic tag function')
core.console('hf 15 raw -2 -c 02213E00000000')
core.console('hf 15 raw -2 -c 02213F69960000')
core.console('hf 15 raw -2 -c 022138'..b1)
core.console('hf 15 raw -2 -c 022139'..b0)
end
--
--- Set UID on magic command enabled, OFFICAL REPO
local function magicUID_offical(b0, b1)
print('Using backdoor Magic tag function OFFICAL REPO')
core.console('hf 15 cmd raw -c 02213E00000000')
core.console('hf 15 cmd raw -c 02213F69960000')
core.console('hf 15 cmd raw -c 022138'..b1)
core.console('hf 15 cmd raw -c 022139'..b0)
end
---
-- The main entry point
function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local uid = 'E004013344556677'
local use_iceman = true
-- Read the parameters
for o, a in getopt.getopt(args, 'hu:a') do
if o == 'h' then return help() end
if o == 'u' then uid = a end
if o == 'a' then use_iceman = false end
end
-- uid string checks
if uid == nil then return oops('empty uid string') end
if #uid == 0 then return oops('empty uid string') end
if #uid ~= 16 then return oops('uid wrong length. Should be 8 hex bytes') end
local bytes = utils.ConvertHexToBytes(uid)
local block0 = string.format('%02X%02X%02X%02X', bytes[4], bytes[3], bytes[2], bytes[1])
local block1 = string.format('%02X%02X%02X%02X', bytes[8], bytes[7], bytes[6], bytes[5])
print('new UID | '..uid)
core.clearCommandBuffer()
if use_iceman then
magicUID_iceman(block0, block1)
else
magicUID_offical(block0, block1)
end
end
main(args)

2776
client/luascripts/legic.lua Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,63 @@
local utils = require('utils')
local getopt = require('getopt')
-- this script writes bytes 8 to 256 on the Legic MIM256
copyright = ''
author = 'Mosci'
version = 'v1.0.1'
desc =
[[
This is a script which writes value 0x01 to bytes from position 0x07 until 0xFF on a Legic Prime Tag (MIM256 or MIM1024) -- (created with 'hf legic save my_dump.hex') --
]]
example = [[
script run legic_buffer2card
]]
usage = [[
script run legic_buffer2card -h
Arguments
-h - Help text
]]
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- simple loop-write from 0x07 to 0xff
function main()
-- parse arguments for the script
for o, a in getopt.getopt(args, 'h') do
if o == 'h' then return help() end
end
local cmd = ''
local i
for i = 7, 255 do
cmd = ('hf legic write o %02x d 01'):format(i)
print(cmd)
core.clearCommandBuffer()
core.console(cmd)
-- got a 'cmd-buffer overflow' on my mac - so just wait a little
-- works without that pause on my linux-box
utils.Sleep(0.1)
end
end
main()

View file

@ -0,0 +1,195 @@
--
-- lf_bulk.lua - A tool to clone a large number of tags at once.
-- Updated 2017-04-18
-- Updated 2018-02-20 iceman
local getopt = require('getopt')
copyright = ''
author = "Brian Redbeard"
version = 'v1.0.1'
desc = [[
Perform bulk enrollment of 26 bit H10301 style RFID Tags
For more info, check the comments in the code
]]
example = [[
--
script run lf_bulk.lua -f 1 -b 1000 -c 10
]]
usage = [[
script run lf_bulk.lua -f facility -b base_id_num -c count
Arguments:
-h : this help
-f : facility id
-b : starting card id
-c : count, number of cards to make
]]
local DEBUG = true
--local bxor = bit32.bxor
local bor = bit32.bor
local lshift = bit32.lshift
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, errr
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
-- Exit message
local function exitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
--[[Implement a function to simply visualize the bitstream in a text format
--This is especially helpful for troubleshooting bitwise math issues]]--
local function toBits(num,bits)
-- returns a table of bits, most significant first.
bits = bits or math.max(1, select(2, math.frexp(num)))
local t = {} -- will contain the bits
for b = bits, 1, -1 do
t[b] = math.fmod(num, 2)
num = math.floor((num - t[b]) / 2)
end
return table.concat(t)
end
--[[
Likely, I'm an idiot, but I couldn't find any parity functions in Lua
This can also be done with a combination of bitwise operations (in fact,
is the canonically "correct" way to do it, but my brain doesn't just
default to this and so counting some ones is good enough for me
]]--
local function evenparity(s)
local _, count = string.gsub(s, '1', '')
local p = count % 2
if (p == 0) then
return false
else
return true
end
end
local function isempty(s)
return s == nil or s == ''
end
--[[
The Proxmark3 "clone" functions expect the data to be in hex format so
take the card id number and facility ID as arguments and construct the
hex. This should be easy enough to extend to non 26bit formats
]]--
local function cardHex(i, f)
fac = lshift(f, 16)
id = bor(i, fac)
stream = toBits(id, 24)
--As the function defaults to even parity and returns a boolean,
--perform a 'not' function to get odd parity
high = evenparity(string.sub(stream,1,12)) and 1 or 0
low = not evenparity(string.sub(stream,13)) and 1 or 0
bits = bor( lshift(id, 1), low)
bits = bor( bits, lshift(high, 25))
--Since the lua library bit32 is (obviously) 32 bits and we need to
--encode 36 bits to properly do a 26 bit tag with the preamble we need
--to create a higher order and lower order component which we will
--then assemble in the return. The math above defines the proper
--encoding as per HID/Weigand/etc. These bit flips are due to the
--format length check on bit 38 (cmdlfhid.c:64) and
--bit 31 (cmdlfhid.c:66).
preamble = bor(0, lshift(1, 5))
bits = bor(bits, lshift(1, 26))
return ('%04x%08x'):format(preamble, bits)
end
---
-- main
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
if #args == 0 then return help() end
--I really wish a better getopt function would be brought in supporting
--long arguments, but it seems this library was chosen for BSD style
--compatibility
for o, a in getopt.getopt(args, 'f:b:c:h') do
if o == 'h' then return help() end
if o == 'f' then
if isempty(a) then
print('You did not supply a facility code, using 0')
facility = 0
else
facility = a
end
end
if o == 'b' then
if isempty(a) then return oops('You must supply the flag -b (base id)') end
baseid = a
end
if o == 'c' then
if isempty(a) then return oops('You must supply the flag -c (count)') end
count = a
end
end
--Due to my earlier complaints about how this specific getopt library
--works, specifying ':' does not enforce supplying a value, thus we
--need to do these checks all over again.
if isempty(baseid) then return oops('You must supply the flag -b (base id)') end
if isempty(count) then return oops('You must supply the flag -c (count)') end
--If the facility ID is non specified, ensure we code it as zero
if isempty(facility) then
print('Using 0 for the facility code as -f was not supplied')
facility = 0
end
--The next baseid + count function presents a logic/UX conflict
--where users specifying -c 1 (count = 1) would try to program two
--tags. This makes it so that -c 0 & -c 1 both code one tag, and all
--other values encode the expected amount.
if tonumber(count) > 0 then count = count - 1 end
endid = baseid + count
for cardnum = baseid, endid do
local card = cardHex(cardnum, facility)
print('Press enter to program card '..cardnum..':'..facility..' (hex: '..card..')')
--This would be better with 'press Enter', but we'll take what we can get.
io.read()
core.console( ('lf hid clone %s'):format(card) )
end
end
main(args)

View file

@ -0,0 +1,288 @@
--[[
This is an example of Lua-scripting within Proxmark3. This is a lua-side
implementation of hf mf chk
This code is licensed to you under the terms of the GNU GPL, version 2 or,
at your option, any later version. See the LICENSE.txt file for the text of
the license.
Copyright (C) 2013 m h swende <martin at swende.se>
--]]
local cmds = require('commands')
local keylist = require('mf_default_keys')
local lib14a = require('read14a')
local getopt = require('getopt')
local utils = require('utils')
copyright = ''
author = "Holiman"
version = 'v1.0.1'
desc = ("This script implements Mifare check keys.\
It utilises a large list of default keys (currently %d keys).\
If you want to add more, just put them inside /lualibs/mf_default_keys.lua\n"):format(#keylist)
example = [[
1. script run mfkeys
]]
usage = [[
Arguments:
-h : this help
-p : print keys
]]
local PM3_SUCCESS = 0 -- needs to be refactored into own like pm3_cmd
local TIMEOUT = 10000 -- 10 seconds
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- waits for answer from pm3 device
local function checkCommand(response)
if not response then
print("Timeout while waiting for response. Increase TIMEOUT in mfkeys.lua to wait longer")
return nil, "Timeout while waiting for device to respond"
end
if response.Status == PM3_SUCCESS then
--decode data array
key = response.Data:sub(1, 12)
found = tonumber(response.Data:sub(13,14))
if found == 1 then
return key
end
end
return nil
end
local function checkBlock(blockno, testkeys, keytype)
-- The command data is only 512 bytes,
-- each key is 6 bytes,
-- NG args inside dataarray is 4 bytes. That give us (512-4)/6 or max 84 keys in one go.
-- If there's more, we need to split it up
local start, remaining = 1, #testkeys
local maxchunk = math.floor((512-4)/6)
local chunksize = remaining
if remaining > maxchunk then chunksize = maxchunk end
local n = chunksize
while remaining > 0 do
local d0 = ('%02X%02X00%02X'):format(keytype, blockno, chunksize)
local d1 = table.concat(testkeys, "", start, n)
core.clearCommandBuffer()
print(("Testing block %d, keytype %d, with %d keys"):format(blockno, keytype, chunksize))
local c = Command:newNG{cmd = cmds.CMD_HF_MIFARE_CHKKEYS, data = d0..d1}
key, err = checkCommand(c:sendNG(false))
if key then return key, blockno end
start = start + chunksize
remaining = remaining - chunksize
if remaining < maxchunk then chunksize = remaining end
n = n + chunksize
end
return nil
end
---
-- A function to display the results
local function display_results(keys)
local sector, keyA, keyB, succA, succB
print('')
print('|---|----------------|---|----------------|---|')
print('|sec|key A |res|key B |res|')
print('|---|----------------|---|----------------|---|')
for sector = 0, #keys do
succA, succB, keyA, keyB = unpack(keys[sector])
print(('|%03d| %s | %s | %s | %s |'):format(sector, keyA, succA, keyB, succB))
end
print('|---|----------------|---|----------------|---|')
end
---
-- A little helper to place an item first in the list
local function placeFirst(akey, list)
akey = akey:lower()
if list[1] == akey then
-- Already at pole position
return list
end
local result = {akey}
--print(("Putting '%s' first"):format(akey))
for i,v in ipairs(list) do
if v ~= akey then
result[#result+1] = v
end
end
return result
end
--[[
The mifare Classic 1k card has 16 sectors of 4 data blocks each.
The first 32 sectors of a mifare Classic 4k card consists of 4 data blocks and the remaining
8 sectors consist of 16 data blocks.
--]]
local function get_blockno(s)
local b, sector
if type(s) == 'string' then
sector = tonumber(s)
else
sector = s
end
if sector < 32 then
b = sector * 4
else
b = 32 * 4 + (sector - 32) * 16
end
return ('%02x'):format(b)
end
--
-- dumps all keys to file
local function dumptofile(keys)
if utils.confirm('Do you wish to save the keys to dumpfile?') then
local destination = utils.input('Select a filename to store to', 'dumpkeys.bin')
local file = io.open(destination, 'wb')
if file == nil then
print('Could not write to file ', destination)
return
end
local key_a = ''
local key_b = ''
--for sector,_ in pairs(keys) do
for sector = 0, #keys do
local succA, succB, keyA, keyB = unpack(keys[sector])
key_a = key_a .. bin.pack('H', keyA);
key_b = key_b .. bin.pack('H', keyB);
end
file:write(key_a)
file:write(key_b)
file:close()
end
end
---
--
local function printkeys()
for i=1, #keylist do
print(i, keylist[i])
end
print ('Number of keys: '..#keylist)
end
---
--
local function perform_check(numsectors)
local keyType = 0 -- A=0, B=1
-- empty list of found keys
local keys = {}
for i = 0, numsectors-1 do
keys[i] = {0,0,'',''}
end
core.fast_push_mode(true)
local start_time = os.time()
for sector = 0, #keys do
-- Check if user aborted
if core.kbd_enter_pressed() then
print('Aborted by user')
break
end
local targetblock = tonumber(get_blockno(sector), 16)
local succA, succB, keyA, keyB = unpack(keys[sector])
local keyA = checkBlock(targetblock, keylist, 0)
if keyA then succA = 1; keylist = placeFirst(keyA, keylist) end
keyA = keyA or '------------'
local keyB = checkBlock(targetblock, keylist, 1)
if keyB then succB = 1; keylist = placeFirst(keyB, keylist) end
keyB = keyB or '------------'
keys[sector] = {succA, succB, keyA, keyB}
end
local end_time = os.time()
print('')
print('[+] mfkeys - Checkkey execution time: '..os.difftime(end_time, start_time)..' sec')
core.fast_push_mode(false)
display_results(keys)
-- save to dumpkeys.bin
dumptofile(keys)
end
--
-- shows tag information
local function taginfo(tag)
local sectors = 16
-- Show tag info
print((' Found tag %s'):format(tag.name))
if 0x18 == tag.sak then --NXP MIFARE Classic 4k | Plus 4k
-- MIFARE Classic 4K offers 4096 bytes split into forty sectors,
-- of which 32 are same size as in the 1K with eight more that are quadruple size sectors.
sectors = 40
elseif 0x08 == tag.sak then -- NXP MIFARE CLASSIC 1k | Plus 2k
-- 1K offers 1024 bytes of data storage, split into 16 sector
sectors = 16
elseif 0x09 == tag.sak then -- NXP MIFARE Mini 0.3k
-- MIFARE Classic mini offers 320 bytes split into five sectors.
sectors = 5
elseif 0x10 == tag.sak then-- "NXP MIFARE Plus 2k"
sectors = 32
else
print("I don't know how many sectors there are on this type of card, defaulting to 16")
end
return sectors
end
---
-- The main entry point
local function main(args)
local numSectors = 16
-- Arguments for the script
for o, a in getopt.getopt(args, 'hp') do
if o == 'h' then return help() end
if o == 'p' then return printkeys() end
end
-- identify tag
tag, err = lib14a.read(false, true)
if not tag then return oops(err) end
-- detect sectors and print taginfo
numsectors = taginfo(tag)
perform_check(numsectors)
end
main( args)

View file

@ -0,0 +1,134 @@
local getopt = require('getopt')
copyright = ''
author = "Neuromancer"
version = 'v1.0.1'
desc = [[
This script tries to decode Mifare Classic Access bytes
]]
example = [[
1. script run mifare_access -a 7F0F0869
]]
usage = [[
script run mifare_access -h -a <access bytes>
Arguments:
-h : this help
-a <access bytes> : 4 bytes ACCESS CONDITIONS
]]
local DEBUG = true
local bxor = bit32.bxor
local band = bit32.band
local rshift = bit32.rshift
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
local access_condition_sector_trailer = {}
access_condition_sector_trailer[0x0] = {'never','key A','key A','never','key A','key A'}
access_condition_sector_trailer[0x2] = {'never','never','key A','never','key A','never'}
access_condition_sector_trailer[0x4] = {'never','key B','key A|B','never','never','key B'}
access_condition_sector_trailer[0x6] = {'never','never','key A|B','never','never','never'}
access_condition_sector_trailer[0x1] = {'never','key A','key A','key A','key A','key A'}
access_condition_sector_trailer[0x3] = {'never','key B','key A|B','key B','never','key B'}
access_condition_sector_trailer[0x5] = {'never','never','key A|B','key B','never','never'}
access_condition_sector_trailer[0x7] = {'never','never','key A|B','never','never','never'}
local access_condition_data_block = {}
access_condition_data_block[0x0] = {'key A|B','key A|B','key A|B','key A|B'}
access_condition_data_block[0x2] = {'key A|B','never','never','never'}
access_condition_data_block[0x4] = {'key A|B','key B','never','never'}
access_condition_data_block[0x6] = {'key A|B','key B','key B','key A|B'}
access_condition_data_block[0x1] = {'key A|B','never','never','key A|B'}
access_condition_data_block[0x3] = {'key B','key B','never','never'}
access_condition_data_block[0x5] = {'key B','never','never','never'}
access_condition_data_block[0x7] = {'never','never','never','never'}
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local access = ''
-- Read the parameters
for o, a in getopt.getopt(args, 'ha:') do
if o == 'h' then return help() end
if o == 'a' then access = a end
end
if access == nil then return oops('empty ACCESS CONDITIONS') end
if #access == 0 then return oops('empty ACCESS CONDITIONS') end
if #access ~= 8 then return oops('Wrong length. Should be 4 hex bytes ACCESS CONDITIONS (e.g. 7F0F0869)') end
local c2_b = tonumber(string.sub(access, 1, 1), 16)
local c1_b = tonumber(string.sub(access, 2, 2), 16)
local c1 = tonumber(string.sub(access, 3, 3), 16)
local c3_b = tonumber(string.sub(access, 4, 4), 16)
local c3 = tonumber(string.sub(access, 5, 5), 16)
local c2 = tonumber(string.sub(access, 6, 6), 16)
local gpb = string.sub(access, 7, 8)
if bxor(c1, c1_b) ~= 0xF then print('!!! bitflip in c1') end
if bxor(c2, c2_b) ~= 0xF then print('!!! bitflip in c2') end
if bxor(c3, c3_b) ~= 0xF then print('!!! bitflip in c3') end
local ab = c1 * 256 + c2 * 16 + c3
for block = 0,3 do
print('--> block '..block)
-- mask bits for block
local abi = band(rshift(ab, block), 0x111)
-- compress bits
abi = band(abi + rshift(abi, 3) + rshift(abi, 6),7)
-- print(abi)
if block == 3 then
print(' KEYSECXA read: '..access_condition_sector_trailer[abi][1])
print(' KEYSECXA write: '..access_condition_sector_trailer[abi][2])
print(' ACCESS COND. read: '..access_condition_sector_trailer[abi][3])
print('ACCESS COND. write: '..access_condition_sector_trailer[abi][4])
print(' KEYSECXB read: '..access_condition_sector_trailer[abi][5])
print(' KEYSECXB write: '..access_condition_sector_trailer[abi][6])
else
print(' read: '..access_condition_data_block[abi][1])
print(' write: '..access_condition_data_block[abi][2])
print(' inc: '..access_condition_data_block[abi][3])
print('decr, transfer, restore: '..access_condition_data_block[abi][4])
end
end
print('GPB: '..gpb)
end
main(args)

View file

@ -0,0 +1,218 @@
local getopt = require('getopt')
local lib14a = require('read14a')
local cmds = require('commands')
local utils = require('utils')
copyright = ''
author = "Martin Holst Swende"
version = 'v1.0.2'
desc = [[
This is a script which automates cracking and dumping mifare classic cards. It sets itself into
'listening'-mode, after which it cracks and dumps any mifare classic card that you
place by the device.
]]
example = [[
script run mifare_autopwn
]]
usage = [[
Arguments:
-h this help
-d debug logging on
-k known key for Sector 0 , keytype A
Output files from this operation:
<uid>.eml - emulator file
<uid>.html - html file containing card data
dumpkeys.bin - keys are dumped here. OBS! This file is volatile, as other commands overwrite it sometimes.
dumpdata.bin - card data in binary form. OBS! This file is volatile, as other commands (hf mf dump) overwrite it.
]]
-------------------------------
-- Some utilities
-------------------------------
local DEBUG = false
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
-- Waits for a mifare card to be placed within the vicinity of the reader.
-- @return if successfull: an table containing card info
-- @return if unsuccessfull : nil, error
local function wait_for_mifare()
while not core.kbd_enter_pressed() do
res, err = lib14a.read()
if res then return res end
-- err means that there was no response from card
end
return nil, 'Aborted by user'
end
local function nested(key,sak)
local typ = 1
if 0x18 == sak then --NXP MIFARE Classic 4k | Plus 4k | Ev1 4k
typ = 4
elseif 0x08 == sak then -- NXP MIFARE CLASSIC 1k | Plus 2k | Ev1 1K
typ = 1
elseif 0x09 == sak then -- NXP MIFARE Mini 0.3k
typ = 0
elseif 0x10 == sak then-- "NXP MIFARE Plus 2k"
typ = 2
elseif 0x01 == sak then-- "NXP MIFARE TNP3xxx 1K"
typ = 1
else
print("I don't know how many sectors there are on this type of card, defaulting to 16")
end
local cmd = string.format('hf mf nested %d 0 A %s d', typ, key)
core.console(cmd)
end
local function dump(uid, numsectors)
dbg('dumping tag memory')
local typ = 1
if 0x18 == sak then --NXP MIFARE Classic 4k | Plus 4k | Ev1 4k
typ = 4
elseif 0x08 == sak then -- NXP MIFARE CLASSIC 1k | Plus 2k | Ev1 1K
typ = 1
elseif 0x09 == sak then -- NXP MIFARE Mini 0.3k
typ = 0
elseif 0x10 == sak then-- "NXP MIFARE Plus 2k"
typ = 2
elseif 0x01 == sak then-- "NXP MIFARE TNP3xxx 1K"
typ = 1
end
if utils.confirm('Do you wish to create a memory dump of tag?') then
local dumpfile = 'hf-mf-'..uid..'-data'
local dmp = ('hf mf dump %s f %s'):format(typ, dumpfile)
core.console(dmp)
-- Save the global args, those are *our* arguments
local myargs = args
-- Set the arguments for htmldump script
args =('-i %s.bin -o %s.html'):format(dumpfile, dumpfile)
-- call it
require('htmldump')
-- Set back args. Not that it's used, just for the karma...
args = myargs
end
end
--
-- performs a test if tag nonce uses weak or hardend prng
local function perform_prng_test()
local isweak = core.detect_prng()
if isweak == 1 then
dbg('PRNG detection : WEAK nonce detected')
elseif isweak == 0 then
dbg('PRNG detection : HARDEND nonce detected')
else
dbg('PRNG detection : failed')
end
return isweak
end
---
-- The main entry point
local function main(args)
local verbose, _exit, res, uid, err, _, sak
local seen_uids = {}
local key = ''
local print_message = true
-- Read the parameters
for o, a in getopt.getopt(args, 'hdk:') do
if o == 'h' then help() return end
if o == 'd' then DEBUG = true end
if o == 'k' then key = a end
end
while not _exit do
if print_message then
print('Waiting for card or press Enter to stop')
print_message = false
end
res, err = wait_for_mifare()
if err then return oops(err) end
-- Seen already?
uid = res.uid
sak = res.sak
if not seen_uids[uid] then
-- Store it
seen_uids[uid] = uid
-- check if PRNG is WEAK
if perform_prng_test() == 1 then
print('Card found, commencing crack on UID', uid)
if #key == 12 then
print('Using key: '..key);
else
-- Crack it
local cnt
err, res = core.mfDarkside()
if err == -1 then return oops('Button pressed. Aborted.')
elseif err == -2 then return oops([[Card is not vulnerable to Darkside attack (doesn't send NACK on authentication requests).]])
elseif err == -3 then return oops([[Card is not vulnerable to Darkside attack (its random number generator is not predictable).]])
elseif err == -4 then return oops([[
Card is not vulnerable to Darkside attack (its random number generator seems to be based on the wellknown
generating polynomial with 16 effective bits only, but shows unexpected behaviour.]])
elseif err == -5 then return oops('Aborted via keyboard.')
end
-- The key is actually 8 bytes, so a
-- 6-byte key is sent as 00XXXXXX
-- This means we unpack it as first
-- two bytes, then six bytes actual key data
-- We can discard first and second return values
_,_,key = bin.unpack('H2H6',res)
print('Found valid key: '..key);
end
-- Use nested attack
nested(key, sak)
-- Dump info
dump(uid, sak)
if #key == 12 then _exit = true end
else
print('Card found, darkside attack useless PRNG hardend on UID', uid)
end
print_message = true
end
end
end
-- Call the main
main(args)

View file

@ -0,0 +1,355 @@
local cmds = require('commands')
local lib14a = require('read14a')
local getopt = require('getopt')
copyright = ''
author = 'Dominic Celiano'
version = 'v1.0.1'
desc =
[[
Purpose: Lua script to communicate with the Mifare Plus EV1, including personalization (setting the keys) and proximity check. Manually edit the file to add to the commands you can send the card.
Please read the NXP manual before running this script to prevent making irreversible changes. Also note:
- The Mifare Plus must start in SL0 for personalization. Card can then be moved to SL1 or SL3.
- The keys are hardcoded in the script to "00...". Unless you change this, only use this script for testing purposes.
- Make sure you choose your card size correctly (2kB or 4kB).
Small changes can be to made this script to communicate with the Mifare Plus S, X, or SE.
]]
example = [[
-- default
script run mifareplus
]]
usage = [[
script run mifareplus -h
Arguments:
-h : this help
]]
-- Default
SIXTEEN_BYTES_ZEROS = '00000000000000000000000000000000'
-- ISO7816 commands used
GETVERS_INIT = '0360' -- Begins the GetVersion command
GETVERS_CONT = '03AF' -- Continues the GetVersion command
POWEROFF = 'OFF'
WRITEPERSO = '03A8'
COMMITPERSO = '03AA'
AUTH_FIRST = '0370'
AUTH_CONT = '0372'
AUTH_NONFIRST = '0376'
PREPAREPC = '03F0'
PROXIMITYCHECK = '03F2'
VERIFYPC = '03FD'
READPLAINNOMACUNMACED = '0336'
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
-- Used to send raw data to the firmware to subsequently forward the data to the card.
local function sendRaw(rawdata, crc, power)
print(("<sent>: %s"):format(rawdata))
local flags = lib14a.ISO14A_COMMAND.ISO14A_RAW
if crc then
flags = flags + lib14a.ISO14A_COMMAND.ISO14A_APPEND_CRC
end
if power then
flags = flags + lib14a.ISO14A_COMMAND.ISO14A_NO_DISCONNECT
end
local command = Command:newMIX{cmd = cmds.CMD_HF_ISO14443A_READER,
arg1 = flags, -- Send raw
arg2 = string.len(rawdata) / 2, -- arg2 contains the length, which is half the length of the ASCII-string rawdata
data = rawdata
}
local ignore_response = false
local result, err = command:sendMIX(ignore_response)
if result then
--unpack the first 4 parts of the result as longs, and the last as an extremely long string to later be cut down based on arg1, the number of bytes returned
local count,cmd,arg1,arg2,arg3,data = bin.unpack('LLLLH512',result)
returned_bytes = string.sub(data, 1, arg1 * 2)
if #returned_bytes > 0 then
print(("<recvd>: %s"):format(returned_bytes)) -- need to multiply by 2 because the hex digits are actually two bytes when they are strings
return returned_bytes
else
return nil
end
else
oops("Error sending the card raw data.")
return nil
end
end
local function writePerso()
-- Used to write any data, including the keys (Key A and Key B), for all the sectors.
-- writePerso() command parameters:
-- 1 byte - 0xA8 - Command Code
-- 2 bytes - Address of the first block or key to be written to (40 blocks are numbered from 0x0000 to 0x00FF)
-- X bytes - The data bytes to be written, starting from the first block. Amount of data sent can be from 16 to 240 bytes in 16 byte increments. This allows
-- up to 15 blocks to be written at once.
-- response from PICC:
-- 0x90 - OK
-- 0x09 - targeted block is invalid for writes, i.e. block 0, which contains manufacturer data
-- 0x0B - command invalid
-- 0x0C - unexpected command length
cardsize = 4 --need to set to 4 for 4k or 2 for 2k
if(cardsize == 4) then
numsectors = 39
elseif(cardsize == 2) then
numsectors = 31
else
oops("Invalid card size")
end
-- Write to the AES sector keys
print("Setting AES Sector keys")
for i=0,numsectors do --for each sector number
local keyA_block = "40" .. string.format("%02x", i * 2)
local keyB_block = "40" .. string.format("%02x", (i * 2) + 1)
--Can also calculate the keys fancily to make them unique, if desired
keyA = SIXTEEN_BYTES_ZEROS
keyB = SIXTEEN_BYTES_ZEROS
writeBlock(keyA_block, keyA)
writeBlock(keyB_block, keyB)
end
print("Finished setting AES Sector keys")
print("Setting misc keys which haven't been set yet.")
--CardMasterKey
blocknum = "9000"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--CardConfigurationKey
blocknum = "9001"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--L3SwitchKey
blocknum = "9003"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--SL1CardAuthKey
blocknum = "9004"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--L3SectorSwitchKey
blocknum = "9006"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--L1L3MixSectorSwitchKey
blocknum = "9007"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--VC Keys
--VCProximityKey
blocknum = "A001"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--VCSelectENCKey
blocknum = "A080"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--VCSelectMACKey
blocknum = "A081"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--TransactionMACKey1
blocknum = "C000"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
--TransactionMACConfKey1
blocknum = "C001"
writeBlock(blocknum, SIXTEEN_BYTES_ZEROS)
print("Finished setting misc keys.")
print("WritePerso finished! Card is ready to move into new security level.")
end
local function writeBlock(blocknum, data)
-- Method writes 16 bytes of the string sent (data) to the specified block number
-- The block numbers sent to the card need to be in little endian format (i.e. block 0x0001 is sent as 0x1000)
blocknum_little_endian = string.sub(blocknum, 3, 4) .. string.sub(blocknum, 1, 2)
commandString = WRITEPERSO .. blocknum_little_endian .. data --Write 16 bytes (32 hex chars).
response = sendRaw(commandString, true, true) --0x90 is returned upon success
if string.sub(response, 3, 4) ~= "90" then
oops(("error occurred while trying to write to block %s"):format(blocknum))
end
end
local function authenticateAES()
-- Used to try to authenticate with the AES keys we programmed into the card, to ensure the authentication works correctly.
commandString = AUTH_FIRST
commandString = commandString .. ''
end
local function getVersion()
sendRaw(GETVERS_INIT, true, true)
sendRaw(GETVERS_CONT, true, true)
sendRaw(GETVERS_CONT, true, true)
end
local function commitPerso(SL)
--pass SL as "01" to move to SL1 or "03" to move to SL3.
commandString = COMMITPERSO .. SL
response = sendRaw(commandString, true, true) --0x90 is returned upon success
if string.sub(response, 3, 4) ~= "90" then
oops("error occurred while trying to switch security level")
end
end
local function calculateMAC(MAC_input)
-- Pad the input if it is not a multiple of 16 bytes (32 nibbles).
if(string.len(MAC_input) % 32 ~= 0) then
MAC_input = MAC_input .. "80"
end
while(string.len(MAC_input) % 32 ~= 0) do
MAC_input = MAC_input .. "0"
end
print("Padded MAC Input = " .. MAC_input .. ", length (bytes) = " .. string.len(MAC_input) / 2)
--The MAC would actually be calculated here, and the output stored in raw_output
raw_output = "00010203040506070001020304050607" -- Dummy filler for now of 16-byte output. To be filled with actual MAC for testing purposes.
-- The final 8-byte MAC output is a concatenation of every 2nd byte starting from the second MSB.
final_output = ""
j = 3
for i = 1,8 do
final_output = final_output .. string.sub(RndR, j, j + 1) .. string.sub(RndC, j, j + 1)
j = j + 4
end
return final_output
end
local function proximityCheck()
--PreparePC--
commandString = PREPAREPC
response = sendRaw(commandString, true, true)
if not response then return oops("This card is not support the proximity check command.") end
OPT = string.sub(response, 5, 6)
if tonumber(OPT) == 1 then
pps_present = true
else
pps_present = false
end
pubRespTime = string.sub(response, 7, 10)
if(pps_present == true) then
pps = string.sub(response, 11, 12)
else
pps = ''
end
print("OPT = " .. OPT .. " pubRespTime = " .. pubRespTime .. " pps = " .. pps)
--PC--
RndC = "0001020304050607" --Random Challenge
num_rounds = 8 --Needs to be 1, 2, 4, or 8
part_len = 8 / num_rounds
j = 1
RndR = ""
for i = 1,num_rounds do
pRndC = ""
for q = 1,(part_len*2) do
pRndC = pRndC .. string.sub(RndC,j,j)
j = j + 1
end
commandString = PROXIMITYCHECK .. "0" .. tostring(part_len) .. pRndC
pRndR = string.sub(sendRaw(commandString, true, true), 3, 3+part_len)
RndR = RndR .. pRndR
end
print("RndC = " .. RndC .. " RndR = " .. RndR)
--VerifyPC--
MAC_input = "FD" .. OPT .. pubRespTime
if pps_present then
MAC_input = MAC_input .. pps
end
rnum_concat = ""
rnum_concat = RndR .. RndC --temporary (only works for when a single random challenge (8 bytes) is sent)
-- j = 1
-- for i = 1,8 do
-- rnum_concat = rnum_concat .. string.sub(RndR, j, j + 1) .. string.sub(RndC, j, j + 1)
-- j = j + 2
-- end
MAC_input = MAC_input .. rnum_concat
print("Concatenation of random numbers = " .. rnum_concat)
print("Final PCD concatenation before input into MAC function = " .. MAC_input)
MAC_tag = calculateMAC(MAC_input)
print("8-byte PCD MAC_tag (placeholder - currently incorrect) = " .. MAC_tag)
commandString = VERIFYPC .. MAC_tag
response = sendRaw(commandString, true, true)
print(#response, response)
if #response < 20 then return oops("Wrong response length (expected 20, got "..#response..") exiting") end
PICC_MAC = string.sub(response, 5, 20)
print("8-byte MAC returned by PICC = " .. PICC_MAC)
MAC_input = "90" .. string.sub(MAC_input, 3)
print("Final PICC concatenation before input into MAC function = " .. MAC_input)
MAC_tag = calculateMAC(MAC_input)
print("8-byte PICC MAC_tag (placeholder - currently incorrect) = " .. MAC_tag)
end
---
-- The main entry point
function main(args)
local o, a
for o, a in getopt.getopt(args, 'h') do -- Populate command line arguments
if o == "h" then return help() end
end
-- Initialize the card using the already-present read14a library
-- Perform RATS and PPS (Protocol and Parameter Selection) check to finish the ISO 14443-4 protocol.
info,err = lib14a.read(true, false)
if not info then
lib14a.disconnect()
return oops(err)
end
--
response = sendRaw("D01100", true, true)
if not response then
lib14a.disconnect()
return oops("No response from PPS check")
end
print("Connected to")
print(" Type : "..info.name)
print(" UID : "..info.uid)
-- Now, the card is initialized and we can do more interesting things.
--writePerso()
--commitPerso("03") --move to SL3
--getVersion()
proximityCheck()
--commandString = VERIFYPC .. "186EFDE8DDC7D30B"
-- MAC = f5180d6e 40fdeae8 e9dd6ac7 bcd3350b
-- response = sendRaw(commandString, true, true)
-- attempt to read VCProximityKey at block A001
-- commandString = READPLAINNOMACUNMACED .. "01A0" .. "01"
-- response = sendRaw(commandString, true, true)
-- authenticate with CardConfigurationKey
-- commandString = AUTH_FIRST .. "0190" .. "00"
-- response = sendRaw(commandString, true, true)
-- Power off the Proxmark
sendRaw(POWEROFF, false, false)
lib14a.disconnect()
end
main(args)

View file

@ -0,0 +1,253 @@
local getopt = require('getopt')
local cmds = require('commands')
local lib14a = require('read14a')
local utils = require('utils')
--
-- Refactored iceman, 2019
copyright = ''
author = 'Martin Holst Swende & Asper'
version = 'v1.0.1'
desc = [[
This script will automatically recognize and dump full content of a NFC NDEF Initialized tag; non-initialized tags will be ignored.
It also write the dump to an eml-file <uid>.eml.
(The difference between an .eml-file and a .bin-file is that the eml file contains
ASCII representation of the hex-data, with linebreaks between 'rows'. A .bin-file contains the
raw data, but when saving into that for, we lose the infromation about how the memory is structured.
For example: 24 bytes could be 6 blocks of 4 bytes, or vice versa.
Therefore, the .eml is better to use file when saving dumps.)
]]
example = [[
1. script run ndef_dump
]]
usage = [[
script run ndef_dump
Arguments:
-h this help
-d debug logging on
-v verbose output (from ndef parsing)
]]
local DEBUG = true -- the debug flag
local band = bit32.band
local rshift = bit32.rshift
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Sends an instruction to do nothing, only disconnect
function disconnect()
local command = Command:newMIX{cmd = cmds.CMD_HF_ISO14443A_READER, arg1 = 0,}
-- We can ignore the response here, no ACK is returned for this command
-- Check /armsrc/iso14443a.c, ReaderIso14443a() for details
return command:sendMIX(true)
end
---
--
local function getblockdata(response)
if not response then
return nil, 'No response from device'
end
local count, cmd, arg0, arg1, arg2, data = bin.unpack('LLLLH40', response)
if arg0 == 1 then
return data:sub(1, 32)
end
return nil, "Couldn't read block"
end
---_ Gets data from a block
-- @return {block, block+1, block+2, block+3} if successfull
-- @return nil, errormessage if unsuccessfull
local function getBlock(blockno)
local block, err
local c = Command:newMIX{cmd = cmds.CMD_HF_MIFAREU_READBL, arg1 = blockno, data = 0}
block, err = getblockdata(c:sendMIX(false))
if not block then return oops(err) end
if #block < 32 then
return nil, ('Expected at least 16 bytes, got %d - this tag is not NDEF-compliant'):format(string.len(data))
end
-- Now, parse out the block data
-- 0534 00B9 049C AD7F 4A00 0000 E110 1000 2155
-- b0b0 b0b0 b1b1 b1b1 b2b2 b2b2 b3b3 b3b3 CRCC
b0 = string.sub(block, 1, 8)
b1 = string.sub(block, 9, 16)
b2 = string.sub(block, 17, 24)
b3 = string.sub(block, 25, 32)
return {b0, b1, b2, b3}
end
---
--
local function main( args)
print( string.rep('--',20) )
print( string.rep('--',20) )
local err, data, data2, k, v, i
local verbose = 0
-- Read the parameters
for o, a in getopt.getopt(args, 'hdv') do
if o == 'h' then return help() end
if o == 'd' then DEBUG = true end
if o == 'v' then verbose = 1 end
end
-- First of all, connect
info, err = lib14a.read(true, true)
if err then
disconnect();
return oops(err)
end
core.clearCommandBuffer()
if info.name:match("Ultralight") then
print('[=] Found a tag')
else
disconnect()
return oops('[!] Not a Ultralightbased card. This script reads NDEF formatted UL/NTAGS')
end
-- Info contained within the tag (block 0 example)
-- 0534 00B9 049C AD7F 4A00 0000 E110 1000 2155
-- b0b0 b0b0 b1b1 b1b1 b2b2 b2b2 b3b3 b3b3 CRCC
-- MM?? ???? ???? ???? ???? ???? NNVV SS?? ----
-- M = Manufacturer info
-- N = NDEF-Structure-Compliant (if value is E1)
-- V = NFC Forum Specification version (if 10 = v1.0)
-- First, get blockt 3 byte 2
local blocks, err = getBlock(0)
if err then
disconnect()
return oops(err)
end
-- Block 3 contains number of blocks
local b3 = utils.ConvertHexToBytes(blocks[4]);
local t5tarea = b3[3] * 8
local t5tarea_blocks = t5tarea / 4;
-- NDEF compliant?
if b3[1] ~= 0xE1 then
disconnect()
return oops('[!] This tag is not NDEF-Compliant')
end
-- Reuse existing info
local blockData = {blocks[1], blocks[2], blocks[3], blocks[4]}
--[[ Due to the infineon my-d move bug
(if I send 30 0F i receive block0f+block00+block01+block02 insted of block0f+block10+block11+block12)
the only way to avoid this is to send the read command as many times as block numbers
removing bytes from 5 to 18 from each answer.
--]]
print('[=] Dumping data...')
for i = 4, t5tarea_blocks - 1, 1 do
blocks, err = getBlock(i)
if err then
disconnect();
return oops(err)
end
table.insert(blockData, blocks[1])
end
-- Deactivate field
disconnect()
-- Print results
print('[=] --- Tag NDEF Message info')
print('[=] '.. string.rep('--', 50) )
print('[=] Type : ', info.name)
print('[=] UID : ', info.uid)
print('[=] Manufacturer : ', info.manufacturer)
print('[=] Capacity Container : '.. blockData[4])
print(('[=] %02X : NDEF Magic Number'):format(b3[1]) )
local vLow = band(b3[2], 0xF)
local vHi = band(rshift(b3[2], 4), 0xF)
print(('[=] %02X : version %d.%d supported by tag'):format(b3[2], vHi, vLow) )
print(('[=] %02X : Physical Memory Size: %d bytes'):format(b3[3], t5tarea) )
if b3[3] == 0x96 then
print((' %02X : NDEF Memory Size: %d bytes'):format(b3[3], 48))
elseif b3[3] == 0x12 then
print((' %02X : NDEF Memory Size: %d bytes'):format(b3[3], 144))
elseif b3[3] == 0x3E then
print((' %02X : NDEF Memory Size: %d bytes'):format(b3[3], 496))
elseif b3[3] == 0x6D then
print((' %02X : NDEF Memory Size: %d bytes'):format(b3[3], 872))
end
local rLow = band(b3[4], 0xF)
local rHi = band(rshift(b3[4], 4), 0xF)
local wstr, rstr
if rLow == 0 then
wstr = 'Write access granted without any security'
elseif rLow == 0x0F then
wstr = 'No write access granted at all'
else
wstr = '(RFU)'
end
if rHi ~= 0x00 then
rstr = '(RFU)'
else
rstr = 'Read access granted without any security'
end
print( ('[=] %02X : %s / %s'):format(b3[4], rstr, wstr))
print('[=] '.. string.rep('--', 50) )
local ndefdata = table.concat(blockData, '', 5)
core.ndefparse(t5tarea, verbose, ndefdata)
print('[=] '.. string.rep('--', 50) )
print('')
print('[=] Tag dump')
print('|---|-------------------|')
for k,v in ipairs(blockData) do
-- print(string.format('Block %02x: %02x %02x %02x %02x', k-1, string.byte(v, 1,4)))
print(string.format(' %02x | %s', k-1, v) )
end
print('|---|-------------------|')
local filename, err = utils.WriteDumpFile(info.uid, blockData)
if err then return oops(err) end
print(string.format('[+] Dumped data into %s', filename))
end
main(args)

View file

@ -0,0 +1,388 @@
local getopt = require('getopt')
local lib14a = require('read14a')
local utils = require('utils')
copyright = 'Copyright (c) 2017 IceSQL AB. All rights reserved.'
author = "Christian Herrmann"
version = 'v1.0.4'
desc = [[
This script writes a empty template for 3D printing system onto a empty NTAG213 or MAGIC NTAG21*
Thanks to @jack for his invaluable input on some of the configuration.
]]
example =[[
-- This will generate GOLD, PLA, TH, EU, 200m, tagbased uid.
script run ntag_3d -c 46 -m 50 -p 5448 -s 4555 -l 200
-- This will generate GOLD, PLA, TH, EU, 200m, userbased uid.
script run ntag_3d -u 11223344556677 -c 46 -m 50 -p 5448 -s 4555 -l 200
-- This will generate GOLD, PLA, TH, EU, 200m, userbased uid. and configure a MAGIC NTAG.
script run ntag_3d -u 11223344556677 -c 46 -m 50 -p 5448 -s 4555 -l 200 -1
]]
usage = [[
script run ntag_3d -h -t -u <uid> -c <color> -m <material> -p <region> -s <region> -l <length>
Arguments:
-h : this help
-t : selftest
-u <UID> : UID
-c <COLOR> : color of filament
-m <MATERIAL> : material of filament
-p <REGION> : Manufacturer region
-s <REGION> : Sales region
-l <LENGTH> : Spool length. Use only 100,200,300. 300 has problems on OSX
]]
local DEBUG = true
local TIMEOUT = 10000 -- 10 seconds
local bxor = bit32.bxor
local band = bit32.band
local rshift = bit32.rshift
local _regions = {
{'4742', 'GB'},
{'5457', 'TW'},
{'4555', 'EU'},
{'5553', 'US'},
{'454E', 'EN'},
{'4A50', 'JP'},
{'434E', 'CN'},
{'5448', 'TH'},
{'4153', 'AS'},
{'5246', 'RF'},
{'4746', 'GF'},
{'4341', 'CA'},
{'504D', 'PM'},
{'5044', 'PD'},
}
local _manufacturers = {
{'5457', 'TW'},
{'434E', 'CN'},
{'5448', 'TH'},
}
local _sales = {
{'4742', 'GB'},
{'4555', 'EU'},
{'5553', 'US'},
{'454E', 'EN'},
{'504D', 'PM'},
}
local _materials = {
{'20', 'Other material'},
{'41', 'ABS'},
{'46', 'Flexible TPE Tree'},
{'46', 'TPE'},
{'46', 'PVA'},
{'47', 'PETG'},
{'50', 'PLA'},
{'51', 'PLA'},
{'54', 'Tough PLA'},
{'55', 'UVCR'},
{'56', 'Water Soluble PVA'},
}
local _colors = {
{'30', 'Bronze'},
{'31', 'Silver'},
{'32', 'Clear Red'},
{'33', 'Clear'},
{'34', 'Bottle Green'},
{'35', 'Neon Magenta'},
{'36', 'SteelBlue'},
{'37', 'Sun Orange'},
{'38', 'Pearl White'},
{'39', 'Copper'},
{'41', 'Purple'},
{'42', 'Blue'},
{'43', 'Neon Tangerine'},
{'44', 'Viridity'},
{'45', 'Olivine'},
{'46', 'Gold'},
{'47', 'Green'},
{'48', 'Neon Green'},
{'49', 'Snow White'},
{'4A', 'Neon Yellow'},
{'4B', 'Black'},
{'4C', 'Violet'},
{'4D', 'Grape Purple'},
{'4E', 'Purpurine'},
{'4F', 'Clear Yellow'},
{'50', 'Clear Green'},
{'51', 'Clear Tangerine'},
{'52', 'Red'},
{'53', 'Cyber Yellow'},
{'54', 'Tangerine'},
{'55', 'Clear Blue'},
{'56', 'Clear Purple'},
{'57', 'White'},
{'58', 'Clear Magenta'},
{'59', 'Yellow'},
{'5A', 'Nature'},
}
---
--
local function find( arr, name )
if not name then return nil end
name = name:lower()
for k, v in pairs(arr) do
if ( v[2]:lower() == name or v[1]:lower() == name ) then
return v
end
end
return nil
end
---
--
local function list( arr, desc )
print ('Value\t'..desc)
print (string.rep('=', 20))
for k, v in pairs(arr) do
print(("%s\t%s"):format(v[1],v[2]))
end
end
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
---
--
local function write_tag(uid, t)
print('Writing to tag')
core.console('hw dbg 0')
utils.Sleep(0.5)
local cmd = ''
local pwd, pack = core.keygen_algo_d(uid)
for i= 8, 23 do
cmd = ('hf mfu wrbl b %02d d %s k %08X'):format(i, t[i], pwd)
core.console(cmd)
end
--cfg1
core.console(('hf mfu wrbl b 42 d %s k %08X'):format(t[42], pwd))
--cfg0
core.console(('hf mfu wrbl b 41 d %s k %08X'):format(t[41], pwd))
--dynamic
core.console(('hf mfu wrbl b 40 d %s k %08X'):format(t[40], pwd))
core.console('hw dbg 1')
utils.Sleep(0.5)
print('Done')
end
---
-- configures a magic NTAG for NTAG213, with UID and PWD,PACK.
local function configure_magic_ntag(uid)
print('Configuring MAGIC NTAG')
-- Save the global args, those are *our* arguments
local myargs = args
local pwd, pack = core.keygen_algo_d(uid)
-- Set the arguments for mfu_magic script v1.0.8
-- -t 12 == configure NTAG213F
-- -u == set UID
-- -p == set pwd
-- -a == set pack
args =('-t 12 -u %s -p %08X -a %04X'):format(uid, pwd, pack)
require('mfu_magic')
-- Set back args. Not that it's used, just for the karma...
args = myargs
print('Done')
end
---
-- generates random hex numbers between 31-39
local function random_num_hex(length)
local str = ''
local i
for i = 1, length, 1 do
str = str..math.random(31, 39)
end
return str
end
---
--
local function nwo( val )
local b1 = band(val, 0xFF)
local b2 = band( rshift(val, 8), 0xFF)
local b3 = band( rshift(val, 16), 0xFF)
local b4 = band( rshift(val, 24), 0xFF)
return ('%02X%02X%02X%02X'):format(b1, b2, b3, b4)
end
---
-- NTAG213 template
local function template_NTAG213(uid, material, color, length, manufacture, sales)
local pwd, pack = core.keygen_algo_d(uid)
local m = tonumber(length, 10) * 1000
local m_str = nwo(m)
local t = {}
-- default empty file
for i = 0,42 do
t[i] = '00000000'
end
-- t[4] = '0103A00C' --
-- t[5] = '340300FE' --
-- 6,7
t[8] = '5A'..material..color..'00' -- 5A, material, color, 00
t[9] = '00'..random_num_hex(3) -- 00, three bytes serial number
t[10] = m_str -- total capacity
t[11] = m_str -- total capacity
t[12] = 'D2002D00' -- fixed
t[13] = manufacture..sales -- regioner,
t[14] = random_num_hex(4) -- serial number
-- 15,16
t[17] = '34000000' -- fixed
-- 18,19
-- remaining capacity of spool
t[20] = m_str
t[21] = nwo( bxor( m, 0x54321248))
t[22] = nwo( bxor( (m - 3876923 ), 0x31275455))
t[23] = nwo( bxor( (m + 6923923 ), 0x76235481))
-- 24-39
t[40] = '000000BD' --dynamic
t[41] = '07000008' --cfg0
t[42] = '80050000' --cfg1
t[43] = ('%08X'):format(pwd)
t[44] = ('%04X0000'):format(pack)
return t
end
---
-- outputs the called arguments
local function print_conf(uid, material, color, length, producer, sales )
print('Create tag as following')
print( string.rep('--',16) )
print('UID ', uid)
print('Material ', material[2])
print('Color ', color[2])
print('Spool length ', length)
print('Region')
print(' manufacturer', producer[2])
print(' sales ', sales[2])
print( string.rep('--',16) )
end
---
-- self test
local function selftest()
list(_regions, 'Regions')
list(_materials, 'Materials')
list(_colors, 'Colors')
return nil
end
---
-- The main entry point
local function main(args)
math.randomseed(os.time());
math.random();
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local uid = '04C5DF4A6D5180'
local useUID = false
local useMAGIC = false
local material, color, length, producer, sales
if #args == 0 then return help() end
-- Read the parameters
for o, a in getopt.getopt(args, 'ht1u:l:m:c:p:s:') do
if o == 'h' then return help() end
if o == 't' then return selftest() end
if o == 'u' then uid = a; useUID = true end
if o == 'm' then material = a end
if o == 'c' then color = a end
if o == 'l' then length = tonumber(a) end
if o == 'p' then producer = a end
if o == 's' then sales = a end
if o == '1' then useMAGIC = true end
end
color = find(_colors, color)
if not color then list(_colors, 'Colors'); return oops('\n\nNot valid color') end
material = find(_materials, material)
if not material then list(_materials, 'Materials'); return oops('\n\nNot valid material') end
producer = find(_manufacturers, producer)
if not producer then list(_manufacturers, 'Regions Manufacturers'); return oops('\n\nNo valid manufacturer region') end
sales = find(_sales, sales)
if not sales then list(_sales, 'Regions Sales'); return oops('\n\nNo valid sales region') end
if length > 300 then
return oops('\n\nNot valid spool length. Must be lesser than 300')
end
if useUID then
-- uid string checks
if uid == nil then return oops('empty uid string') end
if #uid == 0 then return oops('empty uid string') end
if #uid ~= 14 then return oops('uid wrong length. Should be 7 hex bytes') end
else
-- GET TAG UID
local tag, err = lib14a.read(false, true)
if not tag then return oops(err) end
core.clearCommandBuffer()
uid = tag.uid
end
--print
print_conf(uid, material, color, length, producer, sales )
-- create template
local t = template_NTAG213(uid, material[1], color[1], length, producer[1], sales[1])
-- using MAGIC NTAG
if useMAGIC then
configure_magic_ntag(uid)
end
-- write template data to tag
write_tag(uid, t)
end
main(args)

View file

@ -0,0 +1,61 @@
-- The getopt-functionality is loaded from pm3/getopt.lua
-- Have a look there for further details
getopt = require('getopt')
copyright = ''
usage = 'script run parameters.lua -a 1 -blala -c -de'
author = 'Martin Holst Swende'
version = 'v1.0.1'
desc = [[
This is an example script to demonstrate handle parameters in scripts.
For more info, check the comments in the code
]]
example = [[
]]
usage = [[
]]
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
local function main(args)
print('These parameters were passed')
--[[
When passing parameters,
x: means that a value should follow x
y means that 'y' is a flag, either on or off
So, the string a:b:def means that we support up to
5 parameters; two with values and three flags. The following
should be valid:
script run parameters.lua -a 1 -blala -c -de
Notice two things:
1. 'blala' works just like 'b lala', both set 'b' to 'lala'
2. Flags can be put together, '-de' is the same as '-d -e'
3. The format -b=lala is *not* supported
4. The format b lala (without -) is *not* supported
--]]
for o, a in getopt.getopt(args, 'ha:b:ced') do
if o == 'h' then return help() end
print(o, a)
end
end
--[[
In the future, we may implement so that scripts are invoked directly
into a 'main' function, instead of being executed blindly. For future
compatibility, I have done so, but I invoke my main from here.
--]]
main(args)

View file

@ -0,0 +1,141 @@
local getopt = require('getopt')
local bin = require('bin')
copyright = 'Copyright (c) 2018 Bogito. All rights reserved.'
author = 'Bogito'
version = 'v1.0.2'
desc =
[[
This script will read the flash memory of RDV4 and print the stored passwords.
It was meant to be used as a help tool after using the BogRun standalone mode.
(Iceman) script adapted to read and print keys in the default dictionary flashmemory sections.
]]
example =
[[
-- This will scan the first 256 bytes of flash memory for stored passwords
script run read_pwd_mem
-- This will scan 256 bytes of flash memory at offset 64 for stored passwords
script run read_pwd_mem -o 64
-- This will scan 32 bytes of flash memory at offset 64 for stored passwords
script run read_pwd_mem -o 64 -l 32
-- This will print found
script run read_pwd_mem -o 241664 -k 6
]]
usage =
[[
Usage:
script run read_pwd_mem -h -o <offset> -l <length> -k <keylength>
Arguments:
-h : this help
-o <offset> : memory offset, default is 0
-l <length> : length in bytes, default is 256
-k <keylen> : key length in bytes <4|6|8> , default is 4
-m : print Mifare dictionary keys
-t : print t55xx dictionary passwords
-i : print iClass dictionary keys
]]
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
-- The main entry point
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local data, err, quadlet
local cnt = 0
local offset = 0
local length = 256
local keylength = 4
local usedkey = false
for o, a in getopt.getopt(args, 'ho:l:k:mti') do
-- help
if o == 'h' then return help() end
-- offset
if o == 'o' then offset = tonumber(a) end
-- num of bytes to read
if o == 'l' then
length = tonumber(a)
if length < 0 or length > 256 then
return oops('Error: Length is not valid. Must be less than 256')
end
end
-- keylength
if o == 'k' then keylength = tonumber(a); usedkey = true end
if o == 'm' then keylength = 6; usedkey = true; length = 8192; offset = 0x3F000-0x6000; end
if o == 't' then keylength = 4; usedkey = true; length = 4096; offset = 0x3F000-0x3000; end
if o == 'i' then keylength = 8; usedkey = true; length = 4096; offset = 0x3F000-0x4000; end
end
if (offset < 0) or (offset % 4 ~= 0) then
return oops('Error: Offset is not valid. Mod-4 values are only allowed.')
end
print('Memory offset', offset)
print('Length ', length)
print('Key length ', keylength)
print( string.rep('--', 20) )
data, err = core.GetFromFlashMem(offset, length)
if err then return oops(err) end
if usedkey then
_, keys, s = bin.unpack('SH'..length-2, data)
if keys == 0xFFFF then return "No keys found in section" end
local kl = keylength * 2
for i = 1, keys do
key = string.sub(s, (i - 1) * kl + 1, i * kl )
print(string.format('[%02d] %s',i, key))
end
print( string.rep('--',20) )
print( ('[+] found %d passwords'):format(keys))
else
_, s = bin.unpack('H'..length, data)
local cnt = 0, i
for i = 1, (length/keylength) do
key = string.sub(s, (i-1)*8+1, i*8)
if key == 'FFFFFFFF' then break end
print(string.format('[%02d] %s',i, key))
cnt = cnt + 1
end
print( string.rep('--',20) )
print( ('[+] found %d passwords'):format(cnt))
end
print( string.rep('--',20) )
end
main(args)

View file

@ -0,0 +1,121 @@
local getopt = require('getopt')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc =
[[
This is a script that tries to bring back a chinese magic card (1k generation1)
from the dead when it's block 0 has been written with bad values.
or mifare Ultralight magic card which answers to chinese backdoor commands
]]
example = [[
-- target a Ultralight based card
1. script run remagic -u
]]
usage = [[
script run remagic
Arguments:
-h this help
-u remagic a Ultralight tag w 7 bytes UID.
]]
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
local function cmdUltralight()
return {
[0] = 'hf 14a raw -p -a -b 7 40',
[1] = 'hf 14a raw -p -a 43',
[2] = 'hf 14a raw -c -a A2005380712A',
[3] = 'hf 14a raw -p -a -b 7 40',
[4] = 'hf 14a raw -p -a 43',
[5] = 'hf 14a raw -c -a A2010200D980',
[6] = 'hf 14a raw -p -a -b 7 40',
[7] = 'hf 14a raw -p -a 43',
[8] = 'hf 14a raw -c -a A2025B480000',
[9] = 'hf 14a raw -c -a 5000',
}
end
local function cmdClassic()
return {
[0] = 'hf 14a raw -p -a -b 7 40',
[1] = 'hf 14a raw -p -a 43',
[2] = 'hf 14a raw -c -p -a A000',
[3] = 'hf 14a raw -c -p -a 01020304049802000000000000001001',
[4] = 'hf 14a raw -c -a 5000',
}
end
local function cmdRestoreST()
local arr = {}
for i = 0, 15 do
local blk = 3 + (4*i)
arr[i] = 'hf mf csetbl '..blk..' FFFFFFFFFFFFFF078000FFFFFFFFFFFF'
end
return arr
end
local function sendCmds( cmds )
for i = 0, #cmds do
if cmds[i] then
print ( cmds[i] )
core.console( cmds[i] )
core.clearCommandBuffer()
end
end
end
---
-- The main entry point
function main(args)
local i
local cmds = {}
local isUltralight = false
-- Read the parameters
for o, a in getopt.getopt(args, 'hu') do
if o == 'h' then return help() end
if o == 'u' then isUltralight = true end
end
core.clearCommandBuffer()
if isUltralight then
sendCmds ( cmdUltralight() )
else
sendCmds( cmdClassic() )
sendCmds( cmdRestoreST() )
end
end
main(args)

View file

@ -0,0 +1,335 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local utils = require('utils')
local format = string.format
local floor = math.floor
copyright = ''
author = "Iceman"
version = 'v1.0.1'
desc =[[
This script will program a T55x7 TAG with a configuration and four blocks of data.
It will then try to detect and read back those block data and compare if read data matches the expected data.
lf t55xx wipe
lf t55xx detect
lf t55xx write b 1 d 00000000
lf t55xx write b 2 d ffffffff
lf t55xx write b 3 d 80000000
lf t55xx write b 4 d 00000001
Loop:
try write different configuration blocks, and read block1-4 and comparing the read values with the values used to write.
testsuit for T55XX commands demodulation
]]
example = [[
1. script run test_t55x7
]]
usage = [[
script run test_t55x7
Arguments:
-h this help
]]
local DEBUG = true -- the debug flag
local TIMEOUT = 1500
local total_tests = 0
local total_pass = 0
local data_blocks_cmds = {
[1] = '00000000',
[2] = 'ffffffff',
[3] = '80000000',
[4] = '00000001',
}
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print("Example usage")
print(example)
print(usage)
end
---
-- Exit message
local function exitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
---
-- ask/fsk/psk configuration blocks to test
local function GetConfigs( modulation )
local t = {}
t['PSK1'] = {
[1] = '00001040',
[2] = '00041040',
[3] = '00081040',
[4] = '000c1040',
[5] = '00101040',
[6] = '00141040',
[7] = '00181040',
[8] = '001c1040',
}
t['PSK2'] = {
[1] = '00002040',
[2] = '00042040',
[3] = '00082040',
[4] = '000c2040',
[5] = '00102040',
[6] = '00142040',
[7] = '00182040',
[8] = '001c2040',
}
t['PSK3'] = {
[1] = '00003040',
[2] = '00043040',
[3] = '00083040',
[4] = '000c3040',
[5] = '00103040',
[6] = '00143040',
[7] = '00183040',
[8] = '001c3040',
}
t['FSK1'] = {
[1] = '00004040',
[2] = '00004040',
[3] = '00044040',
[4] = '00084040',
[5] = '000c4040',
[6] = '00104040',
[7] = '00144040',
[8] = '00184040',
[9] = '001c4040',
}
t['FSK2'] = {
[1] = '00005040',
[2] = '00045040',
[3] = '00085040',
[4] = '000c5040',
[5] = '00105040',
[6] = '00145040',
[7] = '00185040',
[8] = '001c5040',
}
t['FSK1A'] = {
[1] = '00006040',
[2] = '00046040',
[3] = '00086040',
[4] = '000c6040',
[5] = '00106040',
[6] = '00146040',
[7] = '00186040',
[8] = '001c6040',
}
t['FSK2A'] = {
[1] = '00007040',
[2] = '00047040',
[3] = '00087040',
[4] = '000c7040',
[5] = '00107040',
[6] = '00147040',
[7] = '00187040',
[8] = '001c7040',
}
t['ASK'] = {
[1] = '00008040',
[2] = '00048040',
[3] = '00088040',
[4] = '000c8040',
[5] = '00108040',
[6] = '00148040',
[7] = '00188040',
[8] = '001c8040',
}
t['BI'] = {
[1] = '00010040',
[2] = '00050040',
[3] = '00090040',
[4] = '000d0040',
[5] = '00110040',
[6] = '00150040',
[7] = '00190040',
[8] = '001d0040',
}
return t[modulation:upper()]
end
---
-- lf t55xx wipe
local function WipeCard()
print('Wiping card')
core.console('lf t55xx wipe')
print('Detecting card')
local res, msg = core.t55xx_detect()
if not res then
oops("Can't detect modulation. Test failed.")
core.console('rem [ERR:DETECT:WIPED] Failed to detect after wipe')
return false
else
local wipe_data_cmd = 'lf t55xx write b %s d %s'
for _ = 1, #data_blocks_cmds do
local val = data_blocks_cmds[_]
local c = string.format(wipe_data_cmd, _, val)
core.console(c)
end
return true
end
end
---
-- lf t55xx read
local function CheckReadBlock(block)
local data, msg
-- blockno, page1, override, pwd
data, msg = core.t55xx_readblock(block, '0', '0', '')
if not data then
return ''
end
return ('%08X'):format(data)
end
local function test(modulation)
local process_block0_cmds = {}
local y
local password = '00000000'
local block = '00' -- configuration block 0
local flags = '00' -- page 0, no pwd, no testmode
local s = ('Start test of %s'):format(modulation)
print(s)
process_block0_cmds = GetConfigs(modulation)
if process_block0_cmds == nil then return oops('Cant find modulation '..modulation) end
for _ = 1, #process_block0_cmds do
local p_config_cmd = process_block0_cmds[_]
local errors = 0
core.clearCommandBuffer()
-- Write Config block
dbg(('lf t55xx write b 0 d %s'):format(p_config_cmd))
local data = ('%s%s%s%s'):format(utils.SwapEndiannessStr(p_config_cmd, 32), password, block, flags)
local wc = Command:newNG{cmd = cmds.CMD_LF_T55XX_WRITEBL, data = data}
local response, err = wc:sendNG(false, TIMEOUT)
if not response then return oops(err) end
-- Detect
local res, msg = core.t55xx_detect()
if not res then
print("can't detect modulation, skip to next config")
core.console(format('rem [ERR:DETECT:%s] Failed to detect modulation', p_config_cmd))
core.console(format('rem [SUMMARY:%s] FAIL detection', p_config_cmd))
total_tests = total_tests + #data_blocks_cmds
else
-- Loop block1-2
for _ = 1, #data_blocks_cmds do
total_tests = total_tests + 1
local val = data_blocks_cmds[_]
local blockdata, msg = CheckReadBlock(_)
if blockdata:lower() ~= val:lower() then
print( ('Test %s == %s Failed'):format(val, blockdata))
core.console( format('rem [ERR:READ:%s:%d] block %d: read %s instead of %s', p_config_cmd, _, _, blockdata, val))
errors = errors+1
else
print( ('Test %s == %s OK'):format(val, blockdata))
total_pass = total_pass + 1
end
end
if errors >0 then
core.console( format('rem [SUMMARY:%s] FAIL %d test%s', p_config_cmd, errors, errors > 1 and "s" or ""))
else
core.console( format('rem [SUMMARY:%s] PASS all tests', p_config_cmd))
end
end
end
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
-- Arguments for the script
for o, arg in getopt.getopt(args, 'h') do
if o == 'h' then return help() end
end
core.clearCommandBuffer()
local res
-- Adjust this table to set which configurations should be tested
-- local test_modes = { 'PSK1', 'PSK2', 'PSK3', 'FSK1', 'FSK2', 'FSK1A', 'FSK2A', 'ASK', 'BI' }
local test_modes = { 'ASK' }
for _ = 1, #test_modes do
res = WipeCard()
if res then
print (test_modes[_])
test(test_modes[_])
else
exitMsg('Abort!')
return
end
end
exitMsg('Tests finished')
core.console(
format('rem [SUMMARY] Success rate: %d/%d tests passed%s'
, total_pass
, total_tests
, total_pass < total_tests and ', help me improving that number!' or ' \\o/'
)
)
end
main(args)

View file

@ -0,0 +1,148 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local utils = require('utils')
local format=string.format
local floor=math.floor
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc =[[
This script will program a T55x7 TAG with the configuration: block 0x00 data 0x000100
The outlined procedure is as following:
--ASK
00 00 80 40
-- max 2
-- manchester
-- bit rate
"lf t55xx write b 0 d 00008040"
"lf t55xx detect"
"lf t55xx info"
Loop:
change the configuretion block 0 with:
-xx 00 xxxx = RF/8
-xx 04 xxxx = RF/16
-xx 08 xxxx = RF/32
-xx 0C xxxx = RF/40
-xx 10 xxxx = RF/50
-xx 14 xxxx = RF/64
-xx 18 xxxx = RF/100
-xx 1C xxxx = RF/128
testsuit for the ASK/MANCHESTER demod
]]
example =[[
1. script run test_t55x7_ask
]]
usage = [[
script run test_t55x7_ask
Arguments:
-h : this help
]]
local DEBUG = true -- the debug flag
local TIMEOUT = 1500
--BLOCK 0 = 00008040 ASK / MAN
local config1 = '00'
local config2 = '8040'
local procedurecmds = {
[1] = '%s%02X%s',
[2] = 'lf t55xx detect',
[3] = 'lf t55xx info',
}
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function test()
local y
local password = '00000000'
local block = '00'
local flags = '00'
for y = 0x0, 0x1d, 0x4 do
for _ = 1, #procedurecmds do
local pcmd = procedurecmds[_]
if #pcmd == 0 then
elseif _ == 1 then
local config = pcmd:format(config1, y, config2)
dbg(('lf t55xx write b 0 d %s'):format(config))
local data = ('%s%s%s%s'):format(utils.SwapEndiannessStr(config, 32), password, block, flags)
local wc = Command:newNG{cmd = cmds.CMD_LF_T55XX_WRITEBL, data = data}
local response, err = wc:sendNG(false, TIMEOUT)
if not response then return oops(err) end
else
dbg(pcmd)
core.console( pcmd )
end
end
core.clearCommandBuffer()
end
print( string.rep('--',20) )
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
-- Arguments for the script
for o, arg in getopt.getopt(args, 'h') do
if o == 'h' then return help() end
end
core.clearCommandBuffer()
test()
print( string.rep('--',20) )
end
main(args)

View file

@ -0,0 +1,144 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local utils = require('utils')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This script will program a T55x7 TAG with the configuration: block 0x00 data 0x00010040
The outlined procedure is as following:
--BIPHASE 00010040
--
"lf t55xx write b 0 d 00010040"
"lf t55xx detect"
"lf t55xx info"
Loop:
change the configuretion block 0 with:
-xx01xxxx = RF/8
-xx05xxxx = RF/16
-xx09xxxx = RF/32
-xx0Dxxxx = RF/40
-xx11xxxx = RF/50
-xx15xxxx = RF/64
-xx19xxxx = RF/100
-xx1Dxxxx = RF/128
testsuit for the BIPHASE demod
]]
example = [[
1. script run test_t55x7_bi
]]
usage = [[
script run test_t55x7_bi
Arguments:
-h : this help
]]
local DEBUG = true -- the debug flag
local TIMEOUT = 1500
--BLOCK 0 = 00010040 BIPHASE
local config1 = '00'
local config2 = '0040'
local procedurecmds = {
[1] = '%s%02X%s',
[2] = 'lf t55xx detect',
[3] = 'lf t55xx info',
}
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function test()
local y
local password = '00000000'
local block = '00'
local flags = '00'
for y = 1, 0x1D, 4 do
for _ = 1, #procedurecmds do
local pcmd = procedurecmds[_]
if #pcmd == 0 then
elseif _ == 1 then
local config = pcmd:format(config1, y, config2)
dbg(('lf t55xx write b 0 d %s'):format(config))
local data = ('%s%s%s%s'):format(utils.SwapEndiannessStr(config, 32), password, block, flags)
local wc = Command:newNG{cmd = cmds.CMD_LF_T55XX_WRITEBL, data = data}
local response, err = wc:sendNG(false, TIMEOUT)
if not response then return oops(err) end
else
dbg(pcmd)
core.console( pcmd )
end
end
core.clearCommandBuffer()
end
print( string.rep('--',20) )
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
-- Arguments for the script
for o, arg in getopt.getopt(args, 'h') do
if o == 'h' then return help() end
end
core.clearCommandBuffer()
test()
print( string.rep('--',20) )
end
main(args)

View file

@ -0,0 +1,146 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local utils = require('utils')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This script will program a T55x7 TAG with the configuration: block 0x00 data 0x000100
The outlined procedure is as following:
--ASK
00 00 80 40
-- max 2 blocks
-- FSK1
-- bit rate
"lf t55xx write b 0 d 00007040"
"lf t55xx detect"
"lf t55xx info"
Loop:
change the configuretion block 0 with:
-xx 00 xxxx = RF/8
-xx 04 xxxx = RF/16
-xx 08 xxxx = RF/32
-xx 0C xxxx = RF/40
-xx 10 xxxx = RF/50
-xx 14 xxxx = RF/64
-xx 18 xxxx = RF/100
-xx 1C xxxx = RF/128
testsuit for the ASK/MANCHESTER demod
]]
example = [[
1. script run test_t55x7_fsk
]]
usage = [[
script run test_t55x7_fsk
Arguments:
-h : this help
]]
local DEBUG = true -- the debug flag
local TIMEOUT = 1500
--BLOCK 0 = 00008040 FSK
local config1 = '00'
local config2 = '040'
local procedurecmds = {
[1] = '%s%02X%X%s',
[2] = 'lf t55xx detect',
[3] = 'lf t55xx info',
}
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function test(modulation)
local y
local password = '00000000'
local block = '00'
local flags = '00'
for y = 0x0, 0x1d, 0x4 do
for _ = 1, #procedurecmds do
local pcmd = procedurecmds[_]
if #pcmd == 0 then
elseif _ == 1 then
local config = pcmd:format(config1, y, modulation, config2)
dbg(('lf t55xx write b 0 d %s'):format(config))
local data = ('%s%s%s%s'):format(utils.SwapEndiannessStr(config, 32), password, block, flags)
local wc = Command:newNG{cmd = cmds.CMD_LF_T55XX_WRITEBL, data = data}
local response, err = wc:sendNG(false, TIMEOUT)
if not response then return oops(err) end
else
dbg(pcmd)
core.console( pcmd )
end
end
core.clearCommandBuffer()
end
print( string.rep('--',20) )
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
-- Arguments for the script
for o, arg in getopt.getopt(args, 'h') do
if o == 'h' then return help() end
end
core.clearCommandBuffer()
test(4)
test(5)
test(6)
test(7)
print( string.rep('--',20) )
end
main(args)

View file

@ -0,0 +1,164 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local utils = require('utils')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This script will program a T55x7 TAG with the configuration: block 0x00 data 0x00088040
The outlined procedure is as following:
"lf t55xx write b 0 d 00088040"
"lf t55xx detect"
"lf t55xx info"
Loop OUTER:
change the configuretion block 0 with:
-xxxx8xxx = PSK RF/2 with Manchester modulation
-xxxx1xxx = PSK RF/2 with PSK1 modulation (phase change when input changes)
-xxxx2xxx = PSK RF/2 with PSk2 modulation (phase change on bitclk if input high)
-xxxx3xxx = PSK RF/2 with PSk3 modulation (phase change on rising edge of input)
Loop INNER
for each outer configuration, also do
XXXXX0XX = PSK RF/2
XXXXX4XX = PSK RF/4
XXXXX8XX = PSK RF/8
In all 12 individual test for the PSK demod
]]
example = [[
1. script run test_t55x7_psk
2. script run test_t55x7_psk -o
]]
usage = [[
script run test_t55x7_psk
Arguments:
-h : this help
]]
local DEBUG = true -- the debug flag
local TIMEOUT = 1500
-- --BLOCK 0 = 00 08 80 40 PSK
-- -----------
-- 08------- bitrate
-- 8----- modulation PSK1
-- 0---- PSK ClockRate
-- 40 max 2 blocks
local procedurecmds = {
[1] = '00%02X%X%X40',
[2] = 'lf t55xx detect',
[3] = 'lf t55xx info',
}
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function test(modulation)
local bitrate
local clockrate
local password = '00000000'
local block = '00'
local flags = '00'
for bitrate = 0x0, 0x1d, 0x4 do
for clockrate = 0,8,4 do
for _ = 1, #procedurecmds do
local cmd = procedurecmds[_]
if #cmd == 0 then
elseif _ == 1 then
dbg('Writing to T55x7 TAG')
local config = cmd:format(bitrate, modulation, clockrate)
dbg(('lf t55xx write b 0 d %s'):format(config))
local data = ('%s%s%s%s'):format(utils.SwapEndiannessStr(config, 32), password, block, flags)
local wc = Command:newNG{cmd = cmds.CMD_LF_T55XX_WRITEBL, data = data}
local response, err = wc:sendNG(false, TIMEOUT)
if not response then return oops(err) end
else
dbg(cmd)
core.console( cmd )
end
end
core.clearCommandBuffer()
end
end
print( string.rep('--',20) )
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
-- Arguments for the script
for o, arg in getopt.getopt(args, 'h') do
if o == 'h' then return help() end
end
core.clearCommandBuffer()
test(1) -- PSK1
--test(2) -- PSK2
--test(3) -- PSK3
print( string.rep('--',20) )
end
main(args)
-- Where it iterates over
-- xxxx8xxx = PSK RF/2 with Manchester modulation
-- xxxx1xxx = PSK RF/2 with PSK1 modulation (phase change when input changes)
-- xxxx2xxx = PSK RF/2 with PSk2 modulation (phase change on bitclk if input high)
-- xxxx3xxx = PSK RF/2 with PSk3 modulation (phase change on rising edge of input)
-- XXXXX0XX = PSK RF/2
-- XXXXX4XX = PSK RF/4
-- XXXXX8XX = PSK RF/8

View file

@ -0,0 +1,188 @@
local cmds = require('commands')
local getopt = require('getopt')
local lib14a = require('read14a')
local utils = require('utils')
local pre = require('precalc')
local toys = require('default_toys')
local lsh = bit32.lshift
local rsh = bit32.rshift
local bor = bit32.bor
local band = bit32.band
copyright = ''
author = "Iceman"
version = 'v1.0.1'
desc =[[
This script will try making a barebone clone of a tnp3 tag on to a magic generation1 card.
]]
example =[[
script run tnp3clone
script run tnp3clone -h
script run tnp3clone -l
script run tnp3clone -t aa00 -s 0030
]]
usage = [[
script run tnp3clone -t <toytype> -s <subtype>
Arguments:
-h : this help
-l : list all known toy tokens
-t <data> : toytype id, 4hex symbols
-s <data> : subtype id, 4hex symbols
For fun, try the following subtype id:
0612 - Lightcore
0118 - Series 1
0138 - Series 2
0234 - Special
023c - Special
0020 - Swapforce
]]
local PM3_SUCCESS = 0
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
---
-- decode response and get the blockdata from a normal mifare read command
local function getblockdata(response)
if not response then
return nil, 'No response from device'
end
if response.Status == PM3_SUCCESS then
return response.Data
else
return nil, "Couldn't read block.. ["..response.Status.."]"
end
end
local function readblock( blocknum, keyA )
-- Read block N
local keytype = '00'
local data = ('%02x%s%s'):format(blocknum, keytype, keyA)
local c = Command:newNG{cmd = cmds.CMD_HF_MIFARE_READBL, data = data}
local b, err = getblockdata(c:sendNG(false))
if not b then return oops(err) end
return b
end
---
-- decode response and get the blockdata from backdoor magic command
local function readmagicblock( blocknum )
-- Read block N
local CSETBLOCK_SINGLE_OPERATION = 0x1F
local c = Command:newMIX{
cmd = cmds.CMD_HF_MIFARE_CGETBL
, arg1 = CSETBLOCK_SINGLE_OPERATION
, arg3 = blocknum
}
local b, err = getblockdata(c:sendMIX())
if not b then return oops(err) end
return b
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
local numBlocks = 64
local cset = 'hf mf csetbl '
local csetuid = 'hf mf csetuid '
local cget = 'hf mf cgetbl '
local empty = '00000000000000000000000000000000'
local AccAndKeyB = '7F0F0869000000000000'
local atqa = '0F01'
local sak = '81'
-- Defaults to Gusto
local toytype = 'C201'
local subtype = '0030'
local DEBUG = true
-- Arguments for the script
for o, a in getopt.getopt(args, 'ht:s:l') do
if o == 'h' then return help() end
if o == 't' then toytype = a end
if o == 's' then subtype = a end
if o == 'l' then return toys.List() end
end
if #toytype ~= 4 then return oops('[!] Wrong size - toytype. (4hex symbols)') end
if #subtype ~= 4 then return oops('[!] Wrong size - subtype. (4hex symbols)') end
-- look up type, find & validate types
local item = toys.Find( toytype, subtype)
if item then
print( ('[+] Looking up input: Found %s - %s (%s)'):format(item[6], item[5], item[4]) )
else
print('[-] Didn\'t find item type. If you are sure about it, post on forum')
end
--15,16
--13-14
-- find tag
local card, err = lib14a.read(false, true)
if not card then return oops(err) end
-- load keys
local akeys = pre.GetAll(card.uid)
local keyA = akeys:sub(1, 12 )
local b0 = readblock(0, keyA)
if not b0 then
print('[-] failed reading block with factorydefault key. Trying chinese magic read.')
b0, err = readmagicblock(0)
if not b0 then
oops('[!] '..err)
return oops('[!] failed reading block with chinese magic command. Quitting...')
end
end
core.clearCommandBuffer()
-- wipe card.
local cmd = (csetuid..'%s %s %s w'):format(card.uid, atqa, sak)
core.console(cmd)
core.clearCommandBuffer()
local b1 = toytype..string.rep('00',10)..subtype
local calc = utils.Crc16(b0..b1)
local calcEndian = bor(rsh(calc,8), lsh(band(calc, 0xff), 8))
local cmd = (cset..'1 %s%04x'):format( b1, calcEndian)
core.console(cmd)
core.clearCommandBuffer()
local pos, key
for blockNo = 2, numBlocks-1, 1 do
pos = (math.floor( blockNo / 4 ) * 12)+1
key = akeys:sub(pos, pos + 11 )
if blockNo%4 == 3 then
cmd = ('%s %d %s%s'):format(cset,blockNo,key,AccAndKeyB)
core.console(cmd)
end
end
core.clearCommandBuffer()
-- Set sector trailer S0, since it has different access rights
cmd = ('%s 3 %s0f0f0f69000000000000'):format(cset, keyA)
core.console(cmd)
core.clearCommandBuffer()
end
main(args)

View file

@ -0,0 +1,289 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local lib14a = require('read14a')
local utils = require('utils')
local md5 = require('md5')
local dumplib = require('html_dumplib')
local toys = require('default_toys')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc =[[
This script will try to dump the contents of a Mifare TNP3xxx card.
It will need a valid KeyA in order to find the other keys and decode the card.
]]
example = [[
script run tnp3dump
script run tnp3dump -n
script run tnp3dump -p
script run tnp3dump -k aabbccddeeff
script run tnp3dump -k aabbccddeeff -n
script run tnp3dump -o myfile
script run tnp3dump -n -o myfile
script run tnp3dump -p -o myfile
script run tnp3dump -k aabbccddeeff -n -o myfile
]]
usage = [[
script run tnp3dump -k <key> -n -p -o <filename>
Arguments:
-h : this help
-k <key> : Sector 0 Key A.
-n : Use the nested cmd to find all keys
-p : Use the precalc to find all keys
-o : filename for the saved dumps
]]
local PM3_SUCCESS = 0
local RANDOM = '20436F707972696768742028432920323031302041637469766973696F6E2E20416C6C205269676874732052657365727665642E20'
local DEBUG = false -- the debug flag
local numBlocks = 64
local numSectors = 16
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function readdumpkeys(infile)
t = infile:read("*all")
len = string.len(t)
local len,hex = bin.unpack(("H%d"):format(len),t)
return hex
end
local function getblockdata(response)
if not response then
return nil, 'No response from device'
end
if response.Status == PM3_SUCCESS then
return response.Data
else
return nil, "Couldn't read block.. ["..response.Status.."]"
end
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
local keyA, cmd, err
local useNested = false
local usePreCalc = false
local cmdReadBlockString = 'hf mf rdbl %d A %s'
local input = "dumpkeys.bin"
local outputTemplate = os.date("toydump_%Y-%m-%d_%H%M%S");
-- Arguments for the script
for o, a in getopt.getopt(args, 'hk:npo:') do
if o == "h" then return help() end
if o == "k" then keyA = a end
if o == "n" then useNested = true end
if o == "p" then usePreCalc = true end
if o == "o" then outputTemplate = a end
end
-- validate input args.
keyA = keyA or '4b0b20107ccb'
if #(keyA) ~= 12 then
return oops( string.format('Wrong length of write key (was %d) expected 12', #keyA))
end
-- Turn off Debug
local cmdSetDbgOff = "hw dbg 0"
core.console( cmdSetDbgOff)
utils.Sleep(0.5)
result, err = lib14a.read(false, true)
if not result then return oops(err) end
core.clearCommandBuffer()
-- Show tag info
print((' Found tag %s'):format(result.name))
dbg(('Using keyA : %s'):format(keyA))
--Trying to find the other keys
if useNested then
core.console( ('hf mf nested 1 0 A %s d'):format(keyA) )
end
core.clearCommandBuffer()
local akeys = ''
if usePreCalc then
local pre = require('precalc')
akeys = pre.GetAll(result.uid)
dbg(akeys)
else
print('Loading dumpkeys.bin')
local hex, err = utils.ReadDumpFile(input)
if not hex then
return oops(err)
end
akeys = hex:sub(0,12*16)
end
local block0, block1
-- Read block 0
dbg('Reading block 0')
local blockno = '00'
local keytype = '00'
local data = ('%s%s%s'):format(blockno, keytype, keyA)
cmd = Command:newNG{cmd = cmds.CMD_HF_MIFARE_READBL, data = data}
block0, err = getblockdata(cmd:sendNG(false))
if not block0 then return oops(err) end
core.clearCommandBuffer()
-- Read block 1
dbg('Reading block 1')
local blockno = '01'
data = ('%s%s%s'):format(blockno, keytype, keyA)
cmd = Command:newNG{cmd = cmds.CMD_HF_MIFARE_READBL, data = data}
block1, err = getblockdata(cmd:sendNG(false))
if not block1 then return oops(err) end
core.clearCommandBuffer()
local tmpHash = block0..block1..'%02x'..RANDOM
local key
local pos = 0
local blockNo
local blocks = {}
-- main loop
io.write('Reading blocks > ')
for blockNo = 0, numBlocks-1, 1 do
io.flush()
if core.kbd_enter_pressed() then
print("aborted by user")
break
end
core.clearCommandBuffer()
pos = (math.floor( blockNo / 4 ) * 12)+1
key = akeys:sub(pos, pos + 11 )
data = ('%02x%s%s'):format(blockNo, keytype, key)
cmd = Command:newNG{cmd = cmds.CMD_HF_MIFARE_READBL, data = data}
local blockdata, err = getblockdata(cmd:sendNG(false))
if not blockdata then return oops(err) end
if blockNo%4 ~= 3 then
if blockNo < 8 then
-- Block 0-7 not encrypted
blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata)
else
-- blocks with zero not encrypted.
if string.find(blockdata, '^0+$') then
blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata)
else
local baseStr = utils.ConvertHexToAscii(tmpHash:format(blockNo))
local key = md5.sumhexa(baseStr)
local aestest = core.aes128_decrypt(key, blockdata)
local hex = utils.ConvertAsciiToHex(aestest)
blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,hex)
io.write(blockNo..',')
end
end
else
-- Sectorblocks, not encrypted
blocks[blockNo+1] = ('%02d :: %s%s'):format(blockNo,key,blockdata:sub(13,32))
end
end
io.write('\n')
core.clearCommandBuffer()
-- Print results
local bindata = {}
local emldata = ''
for _,s in pairs(blocks) do
local slice = s:sub(8,#s)
local str = utils.ConvertHexToAscii(slice)
emldata = emldata..slice..'\n'
for c in (str):gmatch('.') do
bindata[#bindata+1] = c
end
end
print( string.rep('--',20) )
local uid = block0:sub(1,8)
local toytype = block1:sub(1,4)
local cardidLsw = block1:sub(9,16)
local cardidMsw = block1:sub(16,24)
local cardid = block1:sub(9,24)
local subtype = block1:sub(25,28)
-- Write dump to files
if not DEBUG then
local foo = dumplib.SaveAsBinary(bindata, outputTemplate..'-'..uid..'.bin')
print(("Wrote a BIN dump to: %s"):format(foo))
local bar = dumplib.SaveAsText(emldata, outputTemplate..'-'..uid..'.eml')
print(("Wrote a EML dump to: %s"):format(bar))
end
print( string.rep('--',20) )
-- Show info
local item = toys.Find(toytype, subtype)
if item then
print((' ITEM TYPE : %s - %s (%s)'):format(item[6],item[5], item[4]) )
else
print((' ITEM TYPE : 0x%s 0x%s'):format(toytype, subtype))
end
print( (' UID : 0x%s'):format(uid) )
print( (' CARDID : 0x%s'):format(cardid ) )
print( string.rep('--',20) )
core.clearCommandBuffer()
end
main(args)

View file

@ -0,0 +1,498 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local lib14a = require('read14a')
local utils = require('utils')
local md5 = require('md5')
local toys = require('default_toys')
local pre = require('precalc')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc =[[
This script will try to load a binary datadump of a Mifare TNP3xxx card.
It vill try to validate all checksums and view some information stored in the dump
For an experimental mode, it tries to manipulate some data.
At last it sends all data to the PM3 device memory where it can be used in the command "hf mf sim"
]]
example =[[
1. script run tnp3sim
2. script run tnp3sim -m
3. script run tnp3sim -m -i myfile
]]
usage = [[
script run tnp3sim -h -m -i <filename>
Arguments:
-h : this help
-m : Maxed out items (experimental)
-i : filename for the datadump to read (bin)
]]
local DEBUG = true -- the debug flag
local RANDOM = '20436F707972696768742028432920323031302041637469766973696F6E2E20416C6C205269676874732052657365727665642E20'
local band = bit32.band
local bor = bit32.bor
local lshift = bit32.lshift
local rshift = bit32.rshift
local byte = string.byte
local char = string.char
local sub = string.sub
local format = string.format
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function writedumpfile(infile)
t = infile:read('*all')
len = string.len(t)
local len,hex = bin.unpack(('H%d'):format(len),t)
return hex
end
-- blocks with data
-- there are two dataareas, in block 8 or block 36, ( 1==8 ,
-- checksum type = 0, 1, 2, 3
local function GetCheckSum(blocks, dataarea, chksumtype)
local crc
local area = 36
if dataarea == 1 then
area = 8
end
if chksumtype == 0 then
crc = blocks[1]:sub(29,32)
elseif chksumtype == 1 then
crc = blocks[area]:sub(29,32)
elseif chksumtype == 2 then
crc = blocks[area]:sub(25,28)
elseif chksumtype == 3 then
crc = blocks[area]:sub(21,24)
end
return utils.SwapEndianness(crc,16)
end
local function SetAllCheckSum(blocks)
print('Updating all checksums')
SetCheckSum(blocks, 3)
SetCheckSum(blocks, 2)
SetCheckSum(blocks, 1)
SetCheckSum(blocks, 0)
end
local function SetCheckSum(blocks, chksumtype)
if blocks == nil then return nil, 'Argument \"blocks\" nil' end
local newcrc
local area1 = 8
local area2 = 36
if chksumtype == 0 then
newcrc = ('%04X'):format(CalcCheckSum(blocks,1,0))
blocks[1] = blocks[1]:sub(1,28)..newcrc:sub(3,4)..newcrc:sub(1,2)
elseif chksumtype == 1 then
newcrc = ('%04X'):format(CalcCheckSum(blocks,1,1))
blocks[area1] = blocks[area1]:sub(1,28)..newcrc:sub(3,4)..newcrc:sub(1,2)
newcrc = ('%04X'):format(CalcCheckSum(blocks,2,1))
blocks[area2] = blocks[area2]:sub(1,28)..newcrc:sub(3,4)..newcrc:sub(1,2)
elseif chksumtype == 2 then
newcrc = ('%04X'):format(CalcCheckSum(blocks,1,2))
blocks[area1] = blocks[area1]:sub(1,24)..newcrc:sub(3,4)..newcrc:sub(1,2)..blocks[area1]:sub(29,32)
newcrc = ('%04X'):format(CalcCheckSum(blocks,2,2))
blocks[area2] = blocks[area2]:sub(1,24)..newcrc:sub(3,4)..newcrc:sub(1,2)..blocks[area2]:sub(29,32)
elseif chksumtype == 3 then
newcrc = ('%04X'):format(CalcCheckSum(blocks,1,3))
blocks[area1] = blocks[area1]:sub(1,20)..newcrc:sub(3,4)..newcrc:sub(1,2)..blocks[area1]:sub(25,32)
newcrc = ('%04X'):format(CalcCheckSum(blocks,2,3))
blocks[area2] = blocks[area2]:sub(1,20)..newcrc:sub(3,4)..newcrc:sub(1,2)..blocks[area2]:sub(25,32)
end
end
function CalcCheckSum(blocks, dataarea, chksumtype)
local area = 36
if dataarea == 1 then
area = 8
end
if chksumtype == 0 then
data = blocks[0]..blocks[1]:sub(1,28)
elseif chksumtype == 1 then
data = blocks[area]:sub(1,28)..'0500'
elseif chksumtype == 2 then
data = blocks[area+1]..blocks[area+2]..blocks[area+4]
elseif chksumtype == 3 then
data = blocks[area+5]..blocks[area+6]..blocks[area+8]..string.rep('00',0xe0)
end
return utils.Crc16(data)
end
local function ValidateCheckSums(blocks)
print(' Validating checksums')
local isOk, crc, calc
-- Checksum Type 0
crc = GetCheckSum(blocks,1,0)
calc = CalcCheckSum(blocks, 1, 0)
if crc == calc then isOk='Ok' else isOk = 'Error' end
io.write( ('TYPE 0 : %04x = %04x -- %s\n'):format(crc,calc,isOk))
-- Checksum Type 1 (DATAAREAHEADER 1)
crc = GetCheckSum(blocks,1,1)
calc = CalcCheckSum(blocks,1,1)
if crc == calc then isOk='Ok' else isOk = 'Error' end
io.write( ('TYPE 1 area 1: %04x = %04x -- %s\n'):format(crc,calc,isOk))
-- Checksum Type 1 (DATAAREAHEADER 2)
crc = GetCheckSum(blocks,2,1)
calc = CalcCheckSum(blocks,2,1)
if crc == calc then isOk='Ok' else isOk = 'Error' end
io.write( ('TYPE 1 area 2: %04x = %04x -- %s\n'):format(crc,calc,isOk))
-- Checksum Type 2 (DATAAREA 1)
crc = GetCheckSum(blocks,1,2)
calc = CalcCheckSum(blocks,1,2)
if crc == calc then isOk='Ok' else isOk = 'Error' end
io.write( ('TYPE 2 area 1: %04x = %04x -- %s\n'):format(crc,calc,isOk))
-- Checksum Type 2 (DATAAREA 2)
crc = GetCheckSum(blocks,2,2)
calc = CalcCheckSum(blocks,2,2)
if crc == calc then isOk='Ok' else isOk = 'Error' end
io.write( ('TYPE 2 area 2: %04x = %04x -- %s\n'):format(crc,calc,isOk))
-- Checksum Type 3 (DATAAREA 1)
crc = GetCheckSum(blocks,1,3)
calc = CalcCheckSum(blocks,1,3)
if crc == calc then isOk='Ok' else isOk = 'Error' end
io.write( ('TYPE 3 area 1: %04x = %04x -- %s\n'):format(crc,calc,isOk))
-- Checksum Type 3 (DATAAREA 2)
crc = GetCheckSum(blocks,2,3)
calc = CalcCheckSum(blocks,2,3)
if crc == calc then isOk='Ok' else isOk = 'Error' end
io.write( ('TYPE 3 area 2: %04x = %04x -- %s\n'):format(crc,calc,isOk))
end
local function AddKey(keys, blockNo, data)
local pos = (math.floor( blockNo / 4 ) * 12)+1
local key = keys:sub(pos, pos + 11 )
return key..data:sub(13)
end
local function LoadEmulator(uid, blocks)
print('Sending dumpdata to emulator memory')
local keys = pre.GetAll(uid)
local cmd, blockdata
for _,b in pairs(blocks) do
blockdata = b
if _%4 ~= 3 then
if (_ >= 8 and _<=21) or (_ >= 36 and _<=49) then
local base = ('%s%s%02x%s'):format(blocks[0], blocks[1], _ , RANDOM)
local baseStr = utils.ConvertHexToAscii(base)
local key = md5.sumhexa(baseStr)
local enc = core.aes128_encrypt(key, blockdata)
blockdata = utils.ConvertAsciiToHex(enc)
end
else
-- add keys if not existing..
if ( blockdata:sub(1,12) == '000000000000' ) then
blockdata = AddKey(keys, _, blockdata)
end
end
io.write( _..',')
io.flush()
core.clearCommandBuffer()
cmd = Command:newMIX{cmd = cmds.CMD_HF_MIFARE_EML_MEMSET, arg1 = _ ,arg2 = 1,arg3 = 16, data = blockdata}
local err, msg = cmd:sendMIX(true)
if err == nil then return err, msg end
end
io.write('\n')
end
local function Num2Card(m, l)
local k = {
0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,0x42, 0x43, 0x44, 0x46, 0x47, 0x48, 0x4A, 0x4B,
0x4C, 0x4D, 0x4E, 0x50, 0x51, 0x52, 0x53, 0x54,0x56, 0x57, 0x58, 0x59, 0x5A, 0x00
}
local msw = tonumber(utils.SwapEndiannessStr(m,32),16)
local lsw = tonumber(utils.SwapEndiannessStr(l,32),16)
if msw > 0x17ea1 then
return "too big"
end
if msw == 0x17ea1 and lsw > 0x8931fee8 then
return "out of range"
end
local s = ""
local index
for i = 1,10 do
index, msw, lsw = DivideByK( msw, lsw)
if ( index <= 1 ) then
s = char(k[index]) .. s
else
s = char(k[index-1]) .. s
end
print (index-1, msw, lsw)
end
return s
end
--33LRT-LM9Q9
--7, 122, 3474858630
--20, 4, 1008436634
--7, 0, 627182959
--17, 0, 21626998
--16, 0, 745758
--23, 0, 25715
--21, 0, 886
--16, 0, 30
--1, 0, 1
--1, 0, 0
function DivideByK(msw, lsw)
local lowLSW
local highLSW
local remainder = 0
local RADIX = 29
--local num = 0 | band( rshift(msw,16), 0xffff)
local num = band( rshift(msw, 16), 0xffff)
--highLSW = 0 | lshift( (num / RADIX) , 16)
highLSW = lshift( (num / RADIX) , 16)
remainder = num % RADIX
num = bor( lshift(remainder,16), band(msw, 0xffff))
--highLSW |= num / RADIX
highLSW = highLSW or (num / RADIX)
remainder = num % RADIX
num = bor( lshift(remainder,16), ( band(rshift(lsw,16), 0xffff)))
--lowLSW = 0 | (num / RADIX) << 16
lowLSW = 0 or (lshift( (num / RADIX), 16))
remainder = num % RADIX
num = bor( lshift(remainder,16) , band(lsw, 0xffff) )
lowLSW = bor(lowLSW, (num / RADIX))
remainder = num % RADIX
return remainder, highLSW, lowLSW
-- uint num = 0 | (msw >> 16) & 0xffff;
-- highLSW = 0 | (num / RADIX) << 16;
-- remainder = num % RADIX;
-- num = (remainder << 16) | (msw & 0xffff);
-- highLSW |= num / RADIX;
-- remainder = num % RADIX;
-- num = (remainder << 16) | ((lsw >> 16) & 0xffff);
-- lowLSW = 0 | (num / RADIX) << 16;
-- remainder = num % RADIX;
-- num = (remainder << 16) | (lsw & 0xffff);
-- lowLSW |= num / RADIX;
-- remainder = num % RADIX;
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
local result, err, hex
local maxed = false
local inputTemplate = 'dumpdata.bin'
local outputTemplate = os.date('toydump_%Y-%m-%d_%H%M');
-- Arguments for the script
for o, a in getopt.getopt(args, 'hmi:o:') do
if o == 'h' then return help() end
if o == 'm' then maxed = true end
if o == 'o' then outputTemplate = a end
if o == 'i' then inputTemplate = a end
end
-- Turn off Debug
local cmdSetDbgOff = 'hw dbg 0'
core.console( cmdSetDbgOff)
utils.Sleep(0.5)
-- Load dump.bin file
print( ('Load data from %s'):format(inputTemplate))
hex, err = utils.ReadDumpFile(inputTemplate)
if not hex then return oops(err) end
local blocks = {}
local blockindex = 0
for i = 1, #hex, 32 do
blocks[blockindex] = hex:sub(i, i+31)
blockindex = blockindex + 1
end
if DEBUG then ValidateCheckSums(blocks) end
--
print( string.rep('--',20) )
print(' Gathering info')
local uid = blocks[0]:sub(1,8)
local toytype = blocks[1]:sub(1,4)
local cardidLsw = blocks[1]:sub(9,16)
local cardidMsw = blocks[1]:sub(17,24)
local subtype = blocks[1]:sub(25,28)
-- Show info
print( string.rep('--',20) )
local item = toys.Find( toytype, subtype)
if item then
local itemStr = ('%s - %s (%s)'):format(item[6],item[5], item[4])
print(' ITEM TYPE : '..itemStr )
else
print( (' ITEM TYPE : 0x%s 0x%s'):format(toytype, subtype) )
end
print( (' UID : %s'):format(uid) )
print( (' CARDID : %s %s [%s]'):format(
cardidMsw,cardidLsw,
--Num2Card(cardidMsw, cardidLsw))
'')
)
print( string.rep('--',20) )
-- Experience should be:
local experience = blocks[8]:sub(1,6)
print(('Experience : %d'):format(utils.SwapEndianness(experience,16)))
local money = blocks[8]:sub(7,10)
print(('Money : %d'):format(utils.SwapEndianness(money,16)))
--
-- Sequence number
local seqnum = blocks[8]:sub(18,19)
print(('Sequence number : %d'):format( tonumber(seqnum,16)))
local fairy = blocks[9]:sub(1,8)
--FD0F = Left, FF0F = Right
local path = 'not choosen'
if fairy:sub(2,2) == 'D' then
path = 'Left'
elseif fairy:sub(2,2) == 'F' then
path = 'Right'
end
print(('Fairy : %d [Path: %s] '):format(utils.SwapEndianness(fairy,24),path))
local hat = blocks[9]:sub(8,11)
print(('Hat : %d'):format(utils.SwapEndianness(hat,16)))
local level = blocks[13]:sub(27,28)
print(('LEVEL : %d'):format( tonumber(level,16)))
--local health = blocks[]:sub();
--print(('Health : %d'):format( tonumber(health,16))
--0x0D 0x29 0x0A 0x02 16-bit hero points value. Maximum 100.
local heropoints = blocks[13]:sub(20,23)
print(('Hero points : %d'):format(utils.SwapEndianness(heropoints,16)))
--0x10 0x2C 0x0C 0x04 32 bit flag value indicating heroic challenges completed.
local challenges = blocks[16]:sub(25,32)
print(('Finished hero challenges : %d'):format(utils.SwapEndianness(challenges,32)))
-- Character Name
local name1 = blocks[10]:sub(1,32)
local name2 = blocks[12]:sub(1,32)
print('Custom name : '..utils.ConvertHexToAscii(name1..name2))
if maxed then
print('Lets try to max out some values')
-- max out money, experience
--print (blocks[8])
blocks[8] = 'FFFFFF'..'FFFF'..blocks[8]:sub(11,32)
blocks[36] = 'FFFFFF'..'FFFF'..blocks[36]:sub(11,32)
--print (blocks[8])
-- max out hero challenges
--print (blocks[16])
blocks[16] = blocks[16]:sub(1,24)..'FFFFFFFF'
blocks[44] = blocks[44]:sub(1,24)..'FFFFFFFF'
--print (blocks[16])
-- max out heropoints
--print (blocks[13])
blocks[13] = blocks[13]:sub(1,19)..'0064'..blocks[13]:sub(24,32)
blocks[41] = blocks[41]:sub(1,19)..'0064'..blocks[41]:sub(24,32)
--print (blocks[13])
-- Update Checksums
SetAllCheckSum(blocks)
-- Validate Checksums
ValidateCheckSums(blocks)
end
--Load dumpdata to emulator memory
if DEBUG then
err = LoadEmulator(uid, blocks)
if err then return oops(err) end
core.clearCommandBuffer()
print('The simulation is now prepared.\n --> run \"hf mf sim u '..uid..'\" <--')
end
end
main(args)

View file

@ -0,0 +1,131 @@
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local utils = require('utils')
local dumplib = require('html_dumplib')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc =[[
This script will load several traces files in ../traces/ folder and do
"data load"
"lf search 1 u"
The following tracefiles will be loaded:
em*.pm3
m*.pm3
]]
example =[[
script run tracetest
]]
usage = [[
script run tracetest -h
Arguments:
-h : this help
]]
local DEBUG = true -- the debug flag
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
-- Exit message
local function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
local cmdDataLoad = 'data load %s';
local tracesEM = "find '../traces/' -iname 'em*.pm3' -type f"
local tracesMOD = "find '../traces/' -iname 'm*.pm3' -type f"
local write2File = false
local outputTemplate = os.date('testtest_%Y-%m-%d_%H%M%S')
-- Arguments for the script
for o, arg in getopt.getopt(args, 'h') do
if o == 'h' then return help() end
end
core.clearCommandBuffer()
local files = {}
-- Find a set of traces staring with EM
local p = assert( io.popen(tracesEM))
for file in p:lines() do
table.insert(files, file)
end
p.close();
-- Find a set of traces staring with MOD
p = assert( io.popen(tracesMOD) )
for file in p:lines() do
table.insert(files, file)
end
p.close();
local cmdLFSEARCH = 'lf search 1 u'
-- main loop
io.write('Starting to test traces > ')
for _,file in pairs(files) do
local x = 'data load '..file
dbg(x)
core.console(x)
dbg(cmdLFSEARCH)
core.console(cmdLFSEARCH)
core.clearCommandBuffer()
if core.kbd_enter_pressed() then
print('aborted by user')
break
end
end
io.write('\n')
print( string.rep('--',20) )
end
main(args)

View file

@ -0,0 +1,177 @@
local cmds = require('commands')
local getopt = require('getopt')
local lib14a = require('read14a')
local utils = require('utils')
copyright = ''
author = 'Iceman'
version = 'v1.0.1'
desc = [[
This is a script that reads AZTEK iso14443a tags.
It starts from block 0, and ends at default block 20. Use 'b' to say different endblock.
xor: the first three block (0,1,2) is not XORED. The rest seems to be xored.
]]
example = [[
-- default
script run ufodump
-- stop at block 10
script run ufodump -b 10
]]
usage = [[
script run ufudump -h -b
Arguments:
h this helptext
b endblock in decimal (1-255, default 20)
]]
-- Some globals
local DEBUG = false -- the debug flag
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
--- Picks out and displays the data read from a tag
-- Specifically, takes a usb packet, converts to a Command
-- (as in commands.lua), takes the data-array and
-- reads the number of bytes specified in arg1 (arg0 in c-struct)
-- and displays the data
-- @blockno just to print which block the data belong to
-- @param usbpacket the data received from the device
function showdata(blockno, data)
local xorkey = '55AA55AA55AA55AA6262'
local s = data.." | "
local dex = ''
local rs
for i = 1, 20-4, 4 do
local item = string.sub(data, i, i+3)
local xor = string.sub(xorkey, i, i+3)
if blockno > 2 then
rs = bit32.bxor(tonumber(item,16) , tonumber(xor,16))
else
rs = tonumber(item, 16)
end
dex = (dex..'%04X'):format(rs)
end
s = s..dex.." | "
print( (" %02d | %s"):format(blockno,s))
end
--
-- Send a "raw" iso14443a package, ie "hf 14a raw" command
function sendRaw(rawdata, options)
local flags = lib14a.ISO14A_COMMAND.ISO14A_NO_DISCONNECT
+ lib14a.ISO14A_COMMAND.ISO14A_RAW
+ lib14a.ISO14A_COMMAND.ISO14A_APPEND_CRC
+ lib14a.ISO14A_COMMAND.ISO14A_NO_RATS
local command = Command:newMIX{cmd = cmds.CMD_HF_ISO14443A_READER,
arg1 = flags, -- Send raw
-- arg2 contains the length, which is half the length
-- of the ASCII-string rawdata
arg2 = string.len(rawdata)/2,
data = rawdata}
return command:sendMIX(options.ignore_response)
end
---
-- The main entry point
function main(args)
local ignore_response = false
local endblock = 20
-- Read the parameters
for o, a in getopt.getopt(args, 'hb:') do
if o == 'h' then return help() end
if o == 'b' then endblock = a end
end
endblock = endblock or 20
-- First of all, connect
info, err = lib14a.read(true, true)
if err then
lib14a.disconnect()
return oops(err)
end
core.clearCommandBuffer()
local blockData = {}
-- Show tag info
print(('\nFound Card UID [%s]\n'):format(info.uid))
print('blk | data | xored')
print('----+------------------+-------------------')
for block = 00, endblock do
local cmd = string.format('10%02x00', block)
res, err = sendRaw(cmd , {ignore_response = ignore_response})
if err then
lib14a.disconnect()
return oops(err)
end
local cmd_response = Command.parse(res)
local len = tonumber(cmd_response.arg1) * 2
local data = string.sub(tostring(cmd_response.data), 0, len-4)
showdata(block, data)
table.insert(blockData, data)
end
print("----+------------------+-------------------")
lib14a.disconnect()
local filename, err = utils.WriteDumpFile(info.uid, blockData)
if err then return oops(err) end
print(string.format('\nDumped data into %s', filename))
end
-------------------------
-- Testing
-------------------------
function selftest()
DEBUG = true
dbg('Performing test')
main()
dbg('Tests done')
end
-- Flip the switch here to perform a sanity check.
-- It read a nonce in two different ways, as specified in the usage-section
if '--test' == args then
selftest()
else
-- Call the main
main(args)
end

View file

@ -0,0 +1,146 @@
local getopt = require('getopt')
local utils = require('utils')
copyright = ''
author = "Iceman"
version = 'v1.0.1'
desc = [[
This script tries to set UID on a mifare Ultralight magic card which either
- answers to chinese backdoor commands
- brickable magic tag (must write in one session)
]]
example = [[
-- backdoor magic tag
script run ul_uid -u 11223344556677
-- brickable magic tag
script run ul_uid -b -u 11223344556677
]]
usage = [[
script run ul_uid -h -b -u <uid>
Arguments:
-h : this help
-u <UID> : UID (14 hexsymbols)
-b : write to brickable magic tag
]]
local DEBUG = true
local bxor = bit32.bxor
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print('Example usage')
print(example)
print(usage)
end
--
--- Set UID on magic command enabled
function magicUID(b0, b1, b2)
print('Using backdoor Magic tag function')
-- write block 0
core.console('hf 14a raw -p -a -b 7 40')
core.console('hf 14a raw -p -a 43')
core.console('hf 14a raw -c -a A200'..b0)
-- write block 1
core.console('hf 14a raw -p -a -b 7 40')
core.console('hf 14a raw -p -a 43')
core.console('hf 14a raw -c -a A201'..b1)
-- write block 2
core.console('hf 14a raw -p -a -b 7 40')
core.console('hf 14a raw -p -a 43')
core.console('hf 14a raw -c -a A202'..b2)
end
--
--- Set UID on magic but brickable
function brickableUID(b0, b1, b2)
print('Using BRICKABLE Magic tag function')
core.console('hf 14a raw -p -s -3')
-- write block 0
core.console('hf 14a raw -p -c A200'..b0)
-- write block 1
core.console('hf 14a raw -p -c A201'..b1)
-- write block 2
core.console('hf 14a raw -p -c A202'..b2)
end
---
-- The main entry point
function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local uid = '04112233445566'
local tagtype = 1
-- Read the parameters
for o, a in getopt.getopt(args, 'hu:b') do
if o == 'h' then return help() end
if o == 'u' then uid = a end
if o == 'b' then tagtype = 2 end
end
-- uid string checks
if uid == nil then return oops('empty uid string') end
if #uid == 0 then return oops('empty uid string') end
if #uid ~= 14 then return oops('uid wrong length. Should be 7 hex bytes') end
local uidbytes = utils.ConvertHexToBytes(uid)
local bcc1 = bxor(0x88, uidbytes[1], uidbytes[2], uidbytes[3])
local bcc2 = bxor(uidbytes[4], uidbytes[5], uidbytes[6], uidbytes[7])
local block0 = string.format('%02X%02X%02X%02X', uidbytes[1], uidbytes[2], uidbytes[3], bcc1)
local block1 = string.format('%02X%02X%02X%02X', uidbytes[4], uidbytes[5], uidbytes[6], uidbytes[7])
local block2 = string.format('%02X%02X%02X%02X', bcc2, 0x48, 0x00, 0x00)
print('new UID | '..uid)
core.clearCommandBuffer()
if tagtype == 2 then
brickableUID(block0, block1, block2)
else
magicUID(block0, block1, block2)
end
--halt
core.console('hf 14a raw -c -a 5000')
end
main(args)